import gradio as gr import time import requests import os def read_file(file_obj): """Reads text from a .txt file only (no PDF/docx).""" if file_obj is None: return "" file_ext = os.path.splitext(file_obj.name)[1].lower() if file_ext != ".txt": return f"Unsupported file type: {file_ext}" try: return file_obj.read().decode("utf-8") except Exception as e: return f"Error reading file: {str(e)}" def fetch_url(url: str): """Fetch text from URL.""" try: resp = requests.get(url, timeout=10) resp.raise_for_status() return resp.text[:1000] # just show first 1000 chars except Exception as e: return f"Error fetching URL: {str(e)}" def process_input(choice, text_val, url_val, file_val): """ Minimal process function that: 1. Shows a progress bar for 4 steps (with time.sleep to visualize). 2. Reads content from the chosen input type. 3. Returns that content to the output. """ with gr.Progress() as p: # STEP 1: "Reading input" placeholder p(0, total=4, desc="Reading input") time.sleep(1) # Actually read the content now if choice == "Text": content = text_val or "No text provided" elif choice == "URL": content = fetch_url(url_val or "") else: # "File" content = read_file(file_val) # STEP 2: Some dummy step p(1, total=4, desc="Doing something else") time.sleep(1) # STEP 3: Another dummy step p(2, total=4, desc="Almost done...") time.sleep(1) # STEP 4: Final step p(3, total=4, desc="Finalizing") time.sleep(1) # Return the content to show in the output return content def create_interface(): with gr.Blocks(title="Minimal Progress Bar Demo") as demo: gr.Markdown("# Minimal Progress Bar Demo") gr.Markdown( "Select an input type, provide some data, then click **Analyze**. " "A progress bar will appear with four steps." ) # 1) Dropdown to select input input_choice = gr.Dropdown( choices=["Text", "URL", "File"], value="Text", label="Select Input Type" ) # 2) Containers for each input with gr.Column(visible=True) as text_col: text_input = gr.Textbox( label="Enter Text", placeholder="Paste text here...", lines=3 ) with gr.Column(visible=False) as url_col: url_input = gr.Textbox( label="Enter URL", placeholder="https://example.com" ) with gr.Column(visible=False) as file_col: file_input = gr.File( label="Upload a .txt File Only", file_types=[".txt"] ) # Toggle visibility function def show_inputs(choice): return { text_col: choice == "Text", url_col: choice == "URL", file_col: choice == "File" } input_choice.change( fn=show_inputs, inputs=[input_choice], outputs=[text_col, url_col, file_col] ) analyze_btn = gr.Button("Analyze", variant="primary") # 3) Output output_box = gr.Textbox( label="Output", lines=6 ) # Link the button to the process function analyze_btn.click( fn=process_input, inputs=[input_choice, text_input, url_input, file_input], outputs=[output_box], show_progress=True ) return demo if __name__ == "__main__": demo = create_interface() demo.launch()