import gradio as gr import requests import re import os import subprocess import tempfile import sys import json import time import signal import atexit # Print Python version info for debugging print(f"Python version: {sys.version}") # Track running processes for cleanup running_processes = [] # Clean up any running processes on exit def cleanup_processes(): for process in running_processes: try: if process.poll() is None: # If process is still running process.terminate() process.wait(timeout=5) print(f"Terminated process {process.pid}") except Exception as e: print(f"Error terminating process: {e}") atexit.register(cleanup_processes) def call_openai_api(api_key, prompt): """Call OpenAI API to generate Gradio app code and requirements""" headers = { "Content-Type": "application/json", "Authorization": f"Bearer {api_key}" } system_prompt = """You are an expert at creating Python applications with Gradio. Your task is to create a complete, standalone Gradio application based on the user's prompt. Provide your response in the following JSON format: { "app_code": "# Your Python code here...", "requirements": ["gradio==3.32.0", "numpy", "pandas", ...], "app_name": "descriptive-name-of-app", "description": "Brief description of what the app does" } Important guidelines: 1. The app_code should be a complete Gradio application. 2. Include demo.launch(server_name="0.0.0.0", server_port=7861) at the end of the code 3. Don't use any resource that requires internet access (no API calls). 4. Only use libraries that can be installed via pip. 5. First requirement should be gradio==3.32.0 (important: use exactly this version). 6. Use only gr.Interface instead of gr.Blocks to avoid version compatibility issues. 7. Don't use any buttons' .click() methods or event handlers - use gr.Interface() only. 8. Make the app functionality self-contained and robust. 9. Don't create directories or write to any file paths. 10. Don't use flagging callbacks or features. Here's a simple template to follow: ```python import gradio as gr import numpy as np # Define your functions here def process_data(input_data): result = input_data * 2 # Simple example return f"Processed: {result}" # Create the Gradio interface demo = gr.Interface( fn=process_data, inputs=gr.Number(label="Input Data"), outputs=gr.Textbox(label="Result"), title="Data Processor" ) # Launch the app demo.launch(server_name="0.0.0.0", server_port=7861) ``` """ data = { "model": "gpt-4o", "messages": [ {"role": "system", "content": system_prompt}, {"role": "user", "content": prompt} ], "temperature": 0.2, "max_tokens": 4000 } try: response = requests.post( "https://api.openai.com/v1/chat/completions", headers=headers, json=data ) if response.status_code != 200: return None, f"API Error: {response.status_code} - {response.text}" result = response.json() content = result["choices"][0]["message"]["content"] # Try to parse the JSON response try: # Extract JSON from response json_pattern = r'```json\s*([\s\S]*?)```|({[\s\S]*})' json_matches = re.findall(json_pattern, content) json_str = "" for match in json_matches: if match[0]: # From code block json_str = match[0] break elif match[1]: # Direct JSON json_str = match[1] break if not json_str: json_str = content # Try the whole content app_info = json.loads(json_str) # Extract Python code if it's wrapped in code blocks if "```python" in app_info["app_code"]: code_pattern = r'```python\s*([\s\S]*?)```' code_match = re.search(code_pattern, app_info["app_code"]) if code_match: app_info["app_code"] = code_match.group(1) return app_info, None except json.JSONDecodeError: # Fallback pattern matching if JSON parsing fails app_code_pattern = r'```python\s*([\s\S]*?)```' app_code_matches = re.findall(app_code_pattern, content) app_code = app_code_matches[0] if app_code_matches else "" if not app_code: return None, "Could not extract app code from response" # Try to extract requirements req_pattern = r'import\s+([a-zA-Z0-9_]+)' req_matches = re.findall(req_pattern, app_code) requirements = ["gradio==3.32.0"] if req_matches: for module in req_matches: if module != "gradio" and module not in requirements and module != "os" and module != "sys": requirements.append(module) # Construct a partial app_info app_info = { "app_code": app_code, "requirements": requirements, "app_name": "gradio-app", "description": "Generated Gradio application" } return app_info, None except Exception as e: return None, f"Error: {str(e)}" def install_and_run_app(app_code, requirements): """Install requirements and run the app in a subprocess""" try: # Create a temporary directory for the app temp_dir = tempfile.mkdtemp() # Create app file app_file = os.path.join(temp_dir, "app.py") with open(app_file, 'w') as f: f.write(app_code) # Make sure port 7861 is specified if "server_port" not in app_code: with open(app_file, 'a') as f: f.write("\n\n# Ensure the app is running on port 7861\n") f.write("if 'demo' in locals():\n") f.write(" demo.launch(server_name='0.0.0.0', server_port=7861)\n") # Install requirements pip_output = "" for req in requirements: try: cmd = [sys.executable, "-m", "pip", "install", req] result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) pip_output += f"Installing {req}: {'SUCCESS' if result.returncode == 0 else 'FAILED'}\n" if result.returncode != 0: pip_output += f"Error: {result.stderr}\n" except Exception as e: pip_output += f"Error installing {req}: {str(e)}\n" # Run the app cmd = [sys.executable, app_file] app_process = subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True ) running_processes.append(app_process) # Wait a bit for the app to start time.sleep(3) # Check if the process is still running if app_process.poll() is not None: stdout, stderr = app_process.communicate() return None, f"App failed to start:\n{stderr}\n\nInstallation log:\n{pip_output}" return { "process": app_process, "app_file": app_file, "temp_dir": temp_dir, "url": "http://localhost:7861", "pip_output": pip_output }, None except Exception as e: return None, f"Error setting up and running app: {str(e)}" def stop_running_app(app_details): """Stop a running app and clean up""" try: if app_details and "process" in app_details: process = app_details["process"] if process.poll() is None: # If process is still running process.terminate() try: process.wait(timeout=5) except subprocess.TimeoutExpired: process.kill() if process in running_processes: running_processes.remove(process) # Clean up temp directory if app_details and "temp_dir" in app_details: import shutil try: shutil.rmtree(app_details["temp_dir"]) except: pass return True except Exception as e: print(f"Error stopping app: {str(e)}") return False # Create the Gradio interface with gr.Blocks(title="Gradio App Generator") as demo: gr.Markdown("# 🤖 Gradio App Generator") gr.Markdown(""" This app generates a Gradio application based on your description, installs required packages, and runs it directly within this container. The generated app will be displayed below. """) # State variable to track running app details app_details_state = gr.State(None) with gr.Row(): with gr.Column(scale=1): api_key = gr.Textbox( label="OpenAI API Key", placeholder="sk-...", type="password", info="Your key is used only for this session" ) prompt = gr.Textbox( label="App Description", placeholder="Describe the Gradio app you want to create...", lines=5 ) with gr.Row(): generate_btn = gr.Button("Generate & Run App", variant="primary") stop_btn = gr.Button("Stop Running App", variant="stop", visible=False) with gr.Accordion("Generated Code", open=False): code_output = gr.Code(language="python", label="App Code") with gr.Accordion("Package Installation Log", open=False): install_output = gr.Textbox(label="Installation Log", lines=5) status_output = gr.Markdown("") with gr.Column(scale=2): # Frame to display the running app app_frame = gr.HTML("

Your generated app will appear here

") def on_generate(api_key_val, prompt_val, current_app_details): # Stop any previously running app if current_app_details: stop_running_app(current_app_details) # Validate API key if not api_key_val or len(api_key_val) < 20 or not api_key_val.startswith("sk-"): return ( None, None, "⚠️ Please provide a valid OpenAI API key", "

Invalid API key

", gr.update(visible=False), None ) try: # Call the OpenAI API to generate app code and requirements status_message = "⏳ Generating app code..." yield ( None, None, status_message, "

Generating code...

", gr.update(visible=False), None ) app_info, api_error = call_openai_api(api_key_val, prompt_val) if api_error or not app_info: return ( None, None, f"⚠️ {api_error or 'Failed to generate app'}", "

Error generating app

", gr.update(visible=False), None ) # At this point we have app code and requirements code = app_info["app_code"] requirements = app_info["requirements"] status_message = "⏳ Installing packages and starting app..." yield ( code, None, status_message, "

Installing packages...

", gr.update(visible=False), None ) # Install packages and run the app app_details, run_error = install_and_run_app(code, requirements) if run_error or not app_details: return ( code, None, f"⚠️ {run_error or 'Failed to run app'}", "

Error running app

", gr.update(visible=False), None ) # Create iframe to display the app iframe_html = f"""
""" return ( code, app_details["pip_output"], f"✅ App is running! View it below.", iframe_html, gr.update(visible=True), app_details ) except Exception as e: import traceback error_details = traceback.format_exc() return ( None, None, f"⚠️ Error: {str(e)}\n\n{error_details}", "

An error occurred

", gr.update(visible=False), None ) def on_stop(current_app_details): if current_app_details: stopped = stop_running_app(current_app_details) if stopped: return ( "✅ App stopped successfully", "

App stopped

", gr.update(visible=False), None ) return ( "⚠️ No app was running", "

No app was running

", gr.update(visible=False), None ) generate_btn.click( on_generate, inputs=[api_key, prompt, app_details_state], outputs=[ code_output, install_output, status_output, app_frame, stop_btn, app_details_state ] ) stop_btn.click( on_stop, inputs=[app_details_state], outputs=[status_output, app_frame, stop_btn, app_details_state] ) if __name__ == "__main__": demo.queue().launch(server_name="0.0.0.0", server_port=7860)