isayahc commited on
Commit
60c8e5a
1 Parent(s): d3dd769

added functionality to download files

Browse files
Files changed (1) hide show
  1. utils.py +40 -20
utils.py CHANGED
@@ -1,33 +1,53 @@
1
  import requests
 
2
  from typing import Optional
3
- from urllib.parse import unquote
4
 
5
- def get_filename_from_cd(cd: Optional[str]) -> Optional[str]:
6
  """
7
- Get filename from content-disposition header.
8
  """
9
- if not cd:
10
- return None
11
- fname = [x.strip() for x in cd.split(';') if x.strip().startswith('filename=')]
12
- return unquote(fname[0].split('=')[1]) if fname else None
13
 
14
- def download_file(url: str) -> None:
 
 
 
 
15
  """
16
- Download a file from a URL and save it with the server-provided name.
 
17
  """
18
- response = requests.get(url)
19
- response.raise_for_status() # Raises an HTTPError if the HTTP request returned an unsuccessful status code
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
 
21
- filename = get_filename_from_cd(response.headers.get('content-disposition'))
22
 
23
- if filename:
24
- with open(filename, 'wb') as file:
25
- file.write(response.content)
26
- print(f"File downloaded and saved as: {filename}")
27
- else:
28
- print("Filename could not be determined from the server.")
29
 
30
  if __name__ == "__main__":
31
  # Example Usage
32
- url = "YOUR_FILE_URL_HERE"
33
- download_file(url)
 
1
  import requests
2
+ import os
3
  from typing import Optional
4
+ from urllib.parse import urlparse, unquote
5
 
6
+ def get_filename_from_url(url: str, cd: Optional[str]) -> str:
7
  """
8
+ Extracts and returns the filename from the URL or content-disposition header.
9
  """
10
+ if cd:
11
+ fname = [x.strip() for x in cd.split(';') if x.strip().startswith('filename=')]
12
+ if fname:
13
+ return unquote(fname[0].split('=')[1].strip('"'))
14
 
15
+ # Fallback to extracting filename from URL
16
+ parsed_url = urlparse(url)
17
+ return os.path.basename(parsed_url.path)
18
+
19
+ def download_file(url: str, save_dir: Optional[str] = None, save_name: Optional[str] = None) -> None:
20
  """
21
+ Downloads a file from the given URL and saves it in the specified directory.
22
+ If the directory does not exist, it will be created.
23
  """
24
+ try:
25
+ response = requests.get(url, stream=True)
26
+ response.raise_for_status()
27
+
28
+ filename = save_name if save_name else get_filename_from_url(url, response.headers.get('content-disposition'))
29
+
30
+ if save_dir:
31
+ os.makedirs(save_dir, exist_ok=True)
32
+ file_path = os.path.join(save_dir, filename)
33
+ else:
34
+ file_path = filename
35
+
36
+ with open(file_path, 'wb') as file:
37
+ for chunk in response.iter_content(chunk_size=8192):
38
+ if chunk:
39
+ file.write(chunk)
40
+
41
+ print(f"File downloaded and saved as: {file_path}")
42
+
43
+ except requests.exceptions.HTTPError as err:
44
+ print(f"HTTP Error: {err}")
45
+ except Exception as e:
46
+ print(f"Error: {e}")
47
 
 
48
 
 
 
 
 
 
 
49
 
50
  if __name__ == "__main__":
51
  # Example Usage
52
+ url = "https://llamahack.slack.com/files/U069A8NRB9T/F068ZTLK9KR/anthem_hsa_medical_insurance_benefit_booklet.pdf"
53
+ download_file(url,"data")