File size: 1,995 Bytes
d6e49e1
 
e6218e4
191dc44
3264dd4
d6e49e1
e6218e4
 
191dc44
 
 
e6218e4
 
 
d6e49e1
191dc44
 
 
 
 
 
3264dd4
 
 
 
 
 
e6218e4
191dc44
e6218e4
 
 
191dc44
e6218e4
 
 
 
d6e49e1
 
e6218e4
 
 
5e5ef17
 
 
 
3264dd4
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
41
42
43
44
45
46
47
48
49
50
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 for Hugging Face Chat Tools",
    description="Enter the URL of an image, video, document, etc. to download it. "
                "This tool is designed for use with Hugging Face Chat Tools: "
                "[https://hf.co/chat/tools/66f1a8159d41ad4398ebb711](https://hf.co/chat/tools/66f1a8159d41ad4398ebb711)",
    concurrency_limit=None
)

iface.launch()