Spaces:
Sleeping
Sleeping
import gradio as gr | |
import requests | |
import os | |
import re | |
import mimetypes | |
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}" | |
# Infer file extension from content type | |
content_type = response.headers['content-type'] | |
ext = mimetypes.guess_extension(content_type) | |
if ext and not temp_filename.endswith(ext): # Append extension if not already present | |
temp_filename += ext | |
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.", | |
concurrency_limit=None | |
) | |
iface.launch() |