Yago Bolivar commited on
Commit
c511b4a
·
1 Parent(s): d7ea0bf

feat: implement file download utility with error handling and filename inference

Browse files
Files changed (1) hide show
  1. src/download_utils.py +98 -0
src/download_utils.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ import os
3
+ import shutil
4
+
5
+ def download_file(url: str, save_dir: str, filename: str = None) -> str | None:
6
+ """
7
+ Downloads a file from a URL and saves it to the specified directory.
8
+
9
+ Args:
10
+ url: The URL of the file to download.
11
+ save_dir: The directory where the file should be saved.
12
+ filename: Optional. The name to save the file as.
13
+ If None, tries to infer from URL or Content-Disposition.
14
+
15
+ Returns:
16
+ The full path to the downloaded file if successful, None otherwise.
17
+ """
18
+ if not url:
19
+ print("Error: Download URL cannot be empty.")
20
+ return None
21
+
22
+ os.makedirs(save_dir, exist_ok=True)
23
+
24
+ try:
25
+ with requests.get(url, stream=True, timeout=30) as r:
26
+ r.raise_for_status() # Raise an exception for bad status codes
27
+
28
+ if not filename:
29
+ # Try to get filename from Content-Disposition header
30
+ content_disposition = r.headers.get('content-disposition')
31
+ if content_disposition:
32
+ import re
33
+ fname_match = re.findall('filename="?([^"]+)"?', content_disposition)
34
+ if fname_match:
35
+ filename = fname_match[0]
36
+ if not filename: # Fallback to last part of URL
37
+ filename = url.split('/')[-1]
38
+ if not filename: # If URL ends with '/', generate a name
39
+ filename = "downloaded_file"
40
+
41
+ # Sanitize filename (basic example, might need more robust sanitization)
42
+ filename = "".join(c for c in filename if c.isalnum() or c in ['.', '_', '-']).strip()
43
+ if not filename: # If sanitization results in empty filename
44
+ filename = "downloaded_file_unnamed"
45
+
46
+ local_filepath = os.path.join(save_dir, filename)
47
+
48
+ with open(local_filepath, 'wb') as f:
49
+ shutil.copyfileobj(r.raw, f)
50
+
51
+ print(f"Successfully downloaded '{filename}' to '{local_filepath}'")
52
+ return local_filepath
53
+ except requests.exceptions.RequestException as e:
54
+ print(f"Error downloading file from {url}: {e}")
55
+ return None
56
+ except IOError as e:
57
+ print(f"Error saving file to {local_filepath}: {e}")
58
+ return None
59
+ except Exception as e:
60
+ print(f"An unexpected error occurred during download: {e}")
61
+ return None
62
+
63
+ if __name__ == '__main__':
64
+ # Example Usage:
65
+ test_url = "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf" # A sample PDF
66
+ download_dir = "test_downloads"
67
+
68
+ # Test 1: Basic download
69
+ print("\n--- Test 1: Basic Download ---")
70
+ downloaded_path = download_file(test_url, download_dir)
71
+ if downloaded_path and os.path.exists(downloaded_path):
72
+ print(f"Test 1 Success: File at {downloaded_path}")
73
+ else:
74
+ print("Test 1 Failed.")
75
+
76
+ # Test 2: Download with specified filename
77
+ print("\n--- Test 2: Download with specified filename ---")
78
+ custom_filename = "my_custom_dummy.pdf"
79
+ downloaded_path_custom = download_file(test_url, download_dir, filename=custom_filename)
80
+ if downloaded_path_custom and os.path.exists(downloaded_path_custom) and os.path.basename(downloaded_path_custom) == custom_filename:
81
+ print(f"Test 2 Success: File at {downloaded_path_custom}")
82
+ else:
83
+ print("Test 2 Failed.")
84
+
85
+ # Test 3: Invalid URL
86
+ print("\n--- Test 3: Invalid URL ---")
87
+ invalid_url = "http://invalid.url/nonexistentfile.txt"
88
+ downloaded_path_invalid = download_file(invalid_url, download_dir)
89
+ if downloaded_path_invalid is None:
90
+ print("Test 3 Success: Handled invalid URL correctly.")
91
+ else:
92
+ print("Test 3 Failed.")
93
+
94
+ # Cleanup (optional)
95
+ # if os.path.exists(download_dir):
96
+ # import shutil
97
+ # shutil.rmtree(download_dir)
98
+ # print(f"\nCleaned up '{download_dir}' directory.")