nakas commited on
Commit
fc0b4cb
·
verified ·
1 Parent(s): 46aaf2f

Update app.py

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