Spaces:
Sleeping
Sleeping
File size: 1,454 Bytes
d6e49e1 e6218e4 191dc44 d6e49e1 e6218e4 191dc44 e6218e4 d6e49e1 191dc44 e6218e4 191dc44 e6218e4 191dc44 e6218e4 d6e49e1 e6218e4 d6e49e1 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
import gradio as gr
import requests
import os
import re
def download_file(url):
"""Downloads a file from a URL and returns the local file path."""
if not url.startswith("http://") and not url.startswith("https://"):
url = "http://" + url # Prepend "http://" if not present
try:
response = requests.get(url, stream=True)
response.raise_for_status() # Raise an exception for bad status codes
# Generate a safe and unique temporary filename
original_filename = os.path.basename(url)
# Remove invalid characters from filename
safe_filename = re.sub(r'[^\w\-_\. ]', '_', original_filename)
temp_filename = f"{safe_filename}"
with open(temp_filename, 'wb') as f:
for chunk in response.iter_content(chunk_size=8192000):
f.write(chunk)
return temp_filename
except requests.exceptions.MissingSchema:
return "Error: Invalid URL format. Even after adding 'http://', the URL is still invalid."
except requests.exceptions.ConnectionError:
return "Error: Could not connect to the server. Please check your internet connection."
except requests.exceptions.RequestException as e:
return f"Error downloading file: {e}"
iface = gr.Interface(
fn=download_file,
inputs=gr.Textbox(lines=1, placeholder="Enter URL of the file"),
outputs=gr.File(),
title="File Downloader",
description="Enter the URL of an image, video, document, etc. to download it.",
)
iface.launch() |