Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,204 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import importlib.util
|
3 |
+
import sys
|
4 |
+
import tempfile
|
5 |
+
import traceback
|
6 |
+
from pathlib import Path
|
7 |
+
|
8 |
+
import gradio as gr
|
9 |
+
import openai
|
10 |
+
from flask import Flask, render_template, request, jsonify
|
11 |
+
from dotenv import load_dotenv
|
12 |
+
|
13 |
+
from utils import sanitize_code, extract_code_blocks, validate_gradio_code
|
14 |
+
|
15 |
+
# Load environment variables
|
16 |
+
load_dotenv()
|
17 |
+
|
18 |
+
# Configure OpenAI API
|
19 |
+
openai.api_key = os.getenv("OPENAI_API_KEY")
|
20 |
+
if not openai.api_key:
|
21 |
+
raise ValueError("OPENAI_API_KEY environment variable is not set")
|
22 |
+
|
23 |
+
app = Flask(__name__)
|
24 |
+
generated_app = None
|
25 |
+
current_code = ""
|
26 |
+
|
27 |
+
def generate_gradio_app(prompt):
|
28 |
+
"""Generate Gradio app code using OpenAI API"""
|
29 |
+
try:
|
30 |
+
response = openai.chat.completions.create(
|
31 |
+
model="gpt-4o", # Using gpt-4o for best code generation
|
32 |
+
messages=[
|
33 |
+
{"role": "system", "content": """You are an expert Gradio developer.
|
34 |
+
Create a standalone Gradio application based on the user's prompt.
|
35 |
+
Your response should ONLY include Python code without any explanation.
|
36 |
+
The code must:
|
37 |
+
1. Import all necessary libraries
|
38 |
+
2. Define a complete, functional Gradio interface
|
39 |
+
3. Launch the interface with share=False and show_api=False
|
40 |
+
4. Use gr.Blocks() for complex interfaces
|
41 |
+
5. Handle errors gracefully
|
42 |
+
6. Use relative paths for any file operations
|
43 |
+
7. NOT use external APIs or services unless specifically requested
|
44 |
+
8. Be completely self-contained in a single script
|
45 |
+
9. End with a simple if __name__ == "__main__": block that launches the app
|
46 |
+
"""
|
47 |
+
},
|
48 |
+
{"role": "user", "content": prompt}
|
49 |
+
],
|
50 |
+
temperature=0.2,
|
51 |
+
max_tokens=4000
|
52 |
+
)
|
53 |
+
|
54 |
+
generated_code = response.choices[0].message.content
|
55 |
+
code_blocks = extract_code_blocks(generated_code)
|
56 |
+
|
57 |
+
if code_blocks:
|
58 |
+
return code_blocks[0], None
|
59 |
+
else:
|
60 |
+
return generated_code, None
|
61 |
+
|
62 |
+
except Exception as e:
|
63 |
+
return None, str(e)
|
64 |
+
|
65 |
+
def load_and_run_gradio_app(code):
|
66 |
+
"""Load and run the generated Gradio app code"""
|
67 |
+
global generated_app, current_code
|
68 |
+
|
69 |
+
# Check if code is safe to execute
|
70 |
+
is_valid, error_msg = validate_gradio_code(code)
|
71 |
+
if not is_valid:
|
72 |
+
return None, error_msg
|
73 |
+
|
74 |
+
# Clean up previous app if it exists
|
75 |
+
if generated_app:
|
76 |
+
try:
|
77 |
+
generated_app.close()
|
78 |
+
except:
|
79 |
+
pass
|
80 |
+
|
81 |
+
# Save code to a temporary file
|
82 |
+
with tempfile.NamedTemporaryFile(suffix='.py', delete=False) as f:
|
83 |
+
f.write(code.encode('utf-8'))
|
84 |
+
temp_file = f.name
|
85 |
+
|
86 |
+
try:
|
87 |
+
# Import the module
|
88 |
+
module_name = os.path.basename(temp_file).replace('.py', '')
|
89 |
+
spec = importlib.util.spec_from_file_location(module_name, temp_file)
|
90 |
+
module = importlib.util.module_from_spec(spec)
|
91 |
+
sys.modules[module_name] = module
|
92 |
+
spec.loader.exec_module(module)
|
93 |
+
|
94 |
+
# Find the Gradio interface
|
95 |
+
for attr_name in dir(module):
|
96 |
+
attr = getattr(module, attr_name)
|
97 |
+
if isinstance(attr, gr.Blocks) or isinstance(attr, gr.Interface):
|
98 |
+
# Save a reference to the app
|
99 |
+
generated_app = attr
|
100 |
+
current_code = code
|
101 |
+
|
102 |
+
# Return the app
|
103 |
+
return attr, None
|
104 |
+
|
105 |
+
return None, "No Gradio interface found in the generated code"
|
106 |
+
|
107 |
+
except Exception as e:
|
108 |
+
error_details = traceback.format_exc()
|
109 |
+
return None, f"Error executing the generated code: {str(e)}\n{error_details}"
|
110 |
+
finally:
|
111 |
+
# Clean up the temporary file
|
112 |
+
try:
|
113 |
+
os.unlink(temp_file)
|
114 |
+
except:
|
115 |
+
pass
|
116 |
+
|
117 |
+
def create_ui():
|
118 |
+
"""Create the main Gradio interface"""
|
119 |
+
with gr.Blocks(title="Dynamic Gradio App Generator") as interface:
|
120 |
+
gr.Markdown("# 🤖 Dynamic Gradio App Generator")
|
121 |
+
gr.Markdown("Describe the Gradio app you want to create, and the AI will generate and run it for you.")
|
122 |
+
|
123 |
+
with gr.Row():
|
124 |
+
with gr.Column(scale=2):
|
125 |
+
prompt = gr.Textbox(
|
126 |
+
label="App Description",
|
127 |
+
placeholder="Describe the Gradio app you want to create...",
|
128 |
+
lines=5
|
129 |
+
)
|
130 |
+
|
131 |
+
with gr.Row():
|
132 |
+
submit_btn = gr.Button("Generate & Run App", variant="primary")
|
133 |
+
clear_btn = gr.Button("Clear", variant="secondary")
|
134 |
+
|
135 |
+
with gr.Accordion("Generated Code", open=False):
|
136 |
+
code_output = gr.Code(language="python", label="Generated Code")
|
137 |
+
|
138 |
+
with gr.Column(scale=3):
|
139 |
+
output = gr.Markdown("Your generated app will appear here.")
|
140 |
+
error_output = gr.Markdown(visible=False)
|
141 |
+
|
142 |
+
def on_submit(prompt_text):
|
143 |
+
# Generate the Gradio app code
|
144 |
+
code, error = generate_gradio_app(prompt_text)
|
145 |
+
if error:
|
146 |
+
return None, f"⚠️ **Error generating code**: {error}", gr.update(visible=True), None
|
147 |
+
|
148 |
+
# Load and run the generated app
|
149 |
+
app, run_error = load_and_run_gradio_app(code)
|
150 |
+
if run_error:
|
151 |
+
return code, f"⚠️ **Error running the generated app**: {run_error}", gr.update(visible=True), None
|
152 |
+
|
153 |
+
# Create an iframe to display the app
|
154 |
+
iframe_html = f'<iframe src="/generated_app" width="100%" height="800px" frameborder="0"></iframe>'
|
155 |
+
return code, "", gr.update(visible=False), iframe_html
|
156 |
+
|
157 |
+
def on_clear():
|
158 |
+
return "", "", gr.update(visible=False), "Your generated app will appear here."
|
159 |
+
|
160 |
+
submit_btn.click(
|
161 |
+
on_submit,
|
162 |
+
inputs=[prompt],
|
163 |
+
outputs=[code_output, error_output, error_output, output]
|
164 |
+
)
|
165 |
+
|
166 |
+
clear_btn.click(
|
167 |
+
on_clear,
|
168 |
+
inputs=[],
|
169 |
+
outputs=[prompt, code_output, error_output, output]
|
170 |
+
)
|
171 |
+
|
172 |
+
return interface
|
173 |
+
|
174 |
+
# Flask routes to handle the generated app
|
175 |
+
@app.route('/generated_app')
|
176 |
+
def serve_generated_app():
|
177 |
+
"""Serve the generated Gradio app"""
|
178 |
+
if not generated_app:
|
179 |
+
return "No app has been generated yet. Please create one first."
|
180 |
+
|
181 |
+
# Create a tempfile with the current code
|
182 |
+
with tempfile.NamedTemporaryFile(suffix='.py', delete=False) as f:
|
183 |
+
f.write(current_code.encode('utf-8'))
|
184 |
+
temp_file = f.name
|
185 |
+
|
186 |
+
# Execute the code in a subprocess
|
187 |
+
# This is a simplified version - in a real app, you'd need a more robust solution
|
188 |
+
import subprocess
|
189 |
+
result = subprocess.run([sys.executable, temp_file], capture_output=True, text=True)
|
190 |
+
|
191 |
+
# Clean up
|
192 |
+
os.unlink(temp_file)
|
193 |
+
|
194 |
+
if result.returncode != 0:
|
195 |
+
return f"Error running the app: {result.stderr}"
|
196 |
+
|
197 |
+
return result.stdout
|
198 |
+
|
199 |
+
if __name__ == "__main__":
|
200 |
+
# Create the Gradio interface
|
201 |
+
demo = create_ui()
|
202 |
+
|
203 |
+
# Launch the Gradio app
|
204 |
+
demo.launch(server_name="0.0.0.0", server_port=7860)
|