nakas commited on
Commit
43d514c
·
verified ·
1 Parent(s): fc0b4cb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +37 -51
app.py CHANGED
@@ -7,32 +7,34 @@ 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.
@@ -127,6 +129,13 @@ def create_ui():
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...",
@@ -141,30 +150,34 @@ def create_ui():
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
 
@@ -176,34 +189,7 @@ def create_ui():
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)
 
7
 
8
  import gradio as gr
9
  import openai
 
10
  from dotenv import load_dotenv
11
 
12
  from utils import sanitize_code, extract_code_blocks, validate_gradio_code
13
 
14
+ # Load environment variables (for local development)
15
  load_dotenv()
16
 
17
+ # Global variables
 
 
 
 
 
 
 
 
 
 
18
  generated_app = None
19
  current_code = ""
20
+ user_api_key = ""
21
 
22
+ def generate_gradio_app(api_key, prompt):
23
  """Generate Gradio app code using OpenAI API"""
24
+ global user_api_key
25
+
26
+ # Validate API key
27
+ if not api_key or len(api_key) < 20:
28
+ return None, "Please provide a valid OpenAI API key"
29
+
30
+ # Store API key for this session
31
+ user_api_key = api_key
32
+
33
  try:
34
+ # Configure client with user's API key
35
+ client = openai.OpenAI(api_key=api_key)
36
+
37
+ response = client.chat.completions.create(
38
  model="gpt-4o", # Using gpt-4o for best code generation
39
  messages=[
40
  {"role": "system", "content": """You are an expert Gradio developer.
 
129
 
130
  with gr.Row():
131
  with gr.Column(scale=2):
132
+ api_key = gr.Textbox(
133
+ label="OpenAI API Key",
134
+ placeholder="sk-...",
135
+ type="password",
136
+ info="Your key is used for this session only and not stored"
137
+ )
138
+
139
  prompt = gr.Textbox(
140
  label="App Description",
141
  placeholder="Describe the Gradio app you want to create...",
 
150
  code_output = gr.Code(language="python", label="Generated Code")
151
 
152
  with gr.Column(scale=3):
153
+ output = gr.HTML("<div style='text-align: center; padding: 50px;'><h3>Your generated app will appear here</h3></div>")
154
  error_output = gr.Markdown(visible=False)
155
 
156
+ def on_submit(api_key_input, prompt_text):
157
  # Generate the Gradio app code
158
+ code, error = generate_gradio_app(api_key_input, prompt_text)
159
  if error:
160
+ return None, f"⚠️ **Error generating code**: {error}", gr.update(visible=True), gr.update(value="<div style='text-align: center; padding: 50px;'><h3>Error generating app</h3></div>")
161
 
162
  # Load and run the generated app
163
  app, run_error = load_and_run_gradio_app(code)
164
  if run_error:
165
+ return code, f"⚠️ **Error running the generated app**: {run_error}", gr.update(visible=True), gr.update(value="<div style='text-align: center; padding: 50px;'><h3>Error running app</h3></div>")
166
 
167
  # Create an iframe to display the app
168
+ iframe_html = f'''
169
+ <div style="border: 1px solid #ddd; border-radius: 8px; padding: 0; overflow: hidden;">
170
+ <iframe id="appFrame" src="/generated_app" width="100%" height="800px" frameborder="0"></iframe>
171
+ </div>
172
+ '''
173
  return code, "", gr.update(visible=False), iframe_html
174
 
175
  def on_clear():
176
+ return gr.update(value=""), "", gr.update(visible=False), "<div style='text-align: center; padding: 50px;'><h3>Your generated app will appear here</h3></div>"
177
 
178
  submit_btn.click(
179
  on_submit,
180
+ inputs=[api_key, prompt],
181
  outputs=[code_output, error_output, error_output, output]
182
  )
183
 
 
189
 
190
  return interface
191
 
192
+ # Create and launch the Gradio interface
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
193
  if __name__ == "__main__":
 
194
  demo = create_ui()
 
 
195
  demo.launch(server_name="0.0.0.0", server_port=7860)