KingNish commited on
Commit
191dc44
·
verified ·
1 Parent(s): e6218e4

Error handling and little update

Browse files
Files changed (1) hide show
  1. app.py +12 -4
app.py CHANGED
@@ -1,21 +1,29 @@
1
  import gradio as gr
2
  import requests
3
  import os
 
4
 
5
  def download_file(url):
6
  """Downloads a file from a URL and returns the local file path."""
 
 
 
7
  try:
8
  response = requests.get(url, stream=True)
9
  response.raise_for_status() # Raise an exception for bad status codes
10
 
11
- # Generate a unique temporary filename
12
- temp_filename = os.path.basename(url)
 
 
 
 
13
  with open(temp_filename, 'wb') as f:
14
- for chunk in response.iter_content(chunk_size=8192):
15
  f.write(chunk)
16
  return temp_filename
17
  except requests.exceptions.MissingSchema:
18
- return "Error: Invalid URL format. Please include the protocol (e.g., http:// or https://)."
19
  except requests.exceptions.ConnectionError:
20
  return "Error: Could not connect to the server. Please check your internet connection."
21
  except requests.exceptions.RequestException as e:
 
1
  import gradio as gr
2
  import requests
3
  import os
4
+ import re
5
 
6
  def download_file(url):
7
  """Downloads a file from a URL and returns the local file path."""
8
+ if not url.startswith("http://") and not url.startswith("https://"):
9
+ url = "http://" + url # Prepend "http://" if not present
10
+
11
  try:
12
  response = requests.get(url, stream=True)
13
  response.raise_for_status() # Raise an exception for bad status codes
14
 
15
+ # Generate a safe and unique temporary filename
16
+ original_filename = os.path.basename(url)
17
+ # Remove invalid characters from filename
18
+ safe_filename = re.sub(r'[^\w\-_\. ]', '_', original_filename)
19
+ temp_filename = f"{safe_filename}"
20
+
21
  with open(temp_filename, 'wb') as f:
22
+ for chunk in response.iter_content(chunk_size=8192000):
23
  f.write(chunk)
24
  return temp_filename
25
  except requests.exceptions.MissingSchema:
26
+ return "Error: Invalid URL format. Even after adding 'http://', the URL is still invalid."
27
  except requests.exceptions.ConnectionError:
28
  return "Error: Could not connect to the server. Please check your internet connection."
29
  except requests.exceptions.RequestException as e: