File size: 1,862 Bytes
1298ab7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
51
52
53
54
# Install necessary libraries
# !pip install gradio huggingface_hub requests

import gradio as gr
import requests
import os
from huggingface_hub import HfApi, HfFolder

def download_and_upload(download_url, hf_write_token, model_name):
    # Get the file name
    file_name = download_url.split("/")[-1]
    save_path = file_name

    # Download the file
    try:
        response = requests.get(download_url, stream=True)
        response.raise_for_status()
        with open(save_path, 'wb') as f:
            for chunk in response.iter_content(chunk_size=8192):
                f.write(chunk)
    except requests.exceptions.RequestException as e:
        return f"An error occurred while downloading the file: {e}"
    
    # Upload the file to Hugging Face
    try:
        api = HfApi()
        HfFolder.save_token(hf_write_token)
        api.upload_file(
            path_or_fileobj=save_path,
            path_in_repo=file_name,  # Use the downloaded file name as is
            repo_id=model_name,
            repo_type="model"
        )
        return f"File successfully uploaded to {model_name}."
    except Exception as e:
        return f"An error occurred while uploading the file: {e}"

# Gradio Interface
with gr.Blocks() as demo:
    gr.Markdown("# File Uploader")

    download_url = gr.Textbox(label="Download URL", placeholder="Enter the file download link")
    hf_write_token = gr.Textbox(label="Hugging Face Write Token", placeholder="Enter your Hugging Face write token", type="password")
    model_name = gr.Textbox(label="Model Name", placeholder="Enter the model name (e.g., username/model_name)")

    output = gr.Textbox(label="Output")

    upload_button = gr.Button("Download and Upload")

    upload_button.click(download_and_upload, inputs=[download_url, hf_write_token, model_name], outputs=output)

# Run the app
demo.launch()