Spaces:
Runtime error
Runtime error
import gradio as gr | |
import os | |
DOWNLOADS_PATH = '/tmp/downloads' # Adjust if necessary | |
# Ensure the downloads path exists | |
os.makedirs(DOWNLOADS_PATH, exist_ok=True) | |
def list_directories(): | |
return [d for d in os.listdir(DOWNLOADS_PATH) if os.path.isdir(os.path.join(DOWNLOADS_PATH, d))] | |
def upload_file(file, directory): | |
if not file: | |
return 'No file selected' | |
directories = list_directories() | |
if directory not in directories: | |
return 'Invalid directory selected' | |
filepath = os.path.join(DOWNLOADS_PATH, directory, file.name) | |
os.makedirs(os.path.dirname(filepath), exist_ok=True) # Ensure the directory exists | |
with open(filepath, 'wb') as f: | |
f.write(file.read()) | |
return 'File uploaded successfully' | |
def get_directory_choices(): | |
return list_directories() | |
# Create Gradio interface | |
with gr.Blocks() as demo: | |
gr.Markdown("# File Upload with Directory Browser") | |
with gr.Row(): | |
with gr.Column(): | |
gr.Markdown("## Select Directory") | |
directory_dropdown = gr.Dropdown(choices=get_directory_choices(), label="Directory") | |
with gr.Column(): | |
gr.Markdown("## Upload File") | |
file_upload = gr.File(label="Choose File") | |
upload_btn = gr.Button("Upload") | |
upload_status = gr.Textbox(label="Status") | |
# Set up the button click action | |
upload_btn.click( | |
fn=upload_file, | |
inputs=[file_upload, directory_dropdown], | |
outputs=[upload_status] | |
) | |
# Update directory choices when the dropdown is interacted with | |
def update_directory_dropdown(): | |
return gr.Dropdown.update(choices=get_directory_choices()) | |
directory_dropdown.change(fn=update_directory_dropdown, inputs=[], outputs=[directory_dropdown]) | |
# Launch Gradio app | |
demo.launch(share=True, server_name="0.0.0.0",server_port=7860, debug=True) |