Spaces:
Sleeping
Sleeping
File size: 8,802 Bytes
6e19f63 fc0b4cb 6e19f63 44abb7c 6e19f63 8be8236 44abb7c 8be8236 44abb7c 8be8236 da5bcdc 8be8236 da5bcdc 8be8236 da5bcdc 8be8236 da5bcdc 8be8236 da5bcdc 8be8236 da5bcdc 8be8236 da5bcdc 8be8236 da5bcdc 8be8236 da5bcdc 8be8236 da5bcdc 8be8236 da5bcdc 8be8236 da5bcdc 8be8236 da5bcdc 8be8236 6e19f63 8be8236 6e19f63 8be8236 6e19f63 da5bcdc 44abb7c 8be8236 6e19f63 da5bcdc 8be8236 da5bcdc 6e19f63 44abb7c da5bcdc 8be8236 da5bcdc 6e19f63 da5bcdc 6e19f63 8be8236 6e19f63 9e8ab62 6e19f63 9e8ab62 8be8236 9e8ab62 7928d62 6e19f63 43d514c fc0b4cb 6e19f63 fc0b4cb 6e19f63 fc0b4cb 6e19f63 fc0b4cb 44abb7c 6e19f63 8be8236 da5bcdc 9e8ab62 8be8236 57a2c17 8be8236 9e8ab62 da5bcdc 8be8236 44abb7c 57a2c17 8be8236 6e19f63 8be8236 da5bcdc 8be8236 6e19f63 da5bcdc 57a2c17 8be8236 da5bcdc 8be8236 44abb7c da5bcdc 8be8236 9e8ab62 da5bcdc 8be8236 44abb7c 8be8236 9e8ab62 7928d62 8be8236 fc0b4cb 8be8236 fc0b4cb |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 |
import gradio as gr
import requests
import re
import tempfile
import importlib.util
import sys
import os
import traceback
# Print Gradio version for debugging
GRADIO_VERSION = gr.__version__
print(f"Using Gradio version: {GRADIO_VERSION}")
# Minimal hardcoded apps that should work with any Gradio version
HELLO_WORLD_APP = """
import gradio as gr
def hello_world():
return "Hello, World!"
demo = gr.Interface(
fn=hello_world,
inputs=None,
outputs="text"
)
"""
CALCULATOR_APP = """
import gradio as gr
def calculate(a, b, operation):
if operation == "add":
return a + b
elif operation == "subtract":
return a - b
elif operation == "multiply":
return a * b
elif operation == "divide":
return a / b if b != 0 else "Error: Division by zero"
else:
return "Invalid operation"
demo = gr.Interface(
fn=calculate,
inputs=[
gr.Number(label="First Number"),
gr.Number(label="Second Number"),
gr.Radio(["add", "subtract", "multiply", "divide"], label="Operation")
],
outputs="text"
)
"""
TEXT_ANALYZER_APP = """
import gradio as gr
def analyze_text(text):
if not text:
return "Please enter some text"
num_chars = len(text)
num_words = len(text.split())
return f"Characters: {num_chars}, Words: {num_words}"
demo = gr.Interface(
fn=analyze_text,
inputs="text",
outputs="text"
)
"""
def call_openai_api(api_key, prompt):
"""Direct API call to OpenAI with minimal output requirements"""
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {api_key}"
}
system_prompt = """You are an expert Gradio developer.
Create a standalone Gradio application based on the user's prompt.
Your response should ONLY include Python code without any explanation.
IMPORTANT: Use the MOST BASIC Gradio features ONLY.
- Use gr.Interface() instead of gr.Blocks()
- Use string literals "text" for text inputs/outputs
- Do not use any component methods like .click() or event handlers
- Do not use component properties or attributes
- Keep it extremely simple
Example of a valid app:
```python
import gradio as gr
def my_function(text_input):
return f"You entered: {text_input}"
demo = gr.Interface(
fn=my_function,
inputs="text",
outputs="text"
)
```
The code must:
1. Import only gradio and basic Python libraries
2. Define simple functions
3. Create a minimal gr.Interface named 'demo'
4. NOT include a launch command or if __name__ == "__main__" block
"""
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()
return result["choices"][0]["message"]["content"], None
except Exception as e:
return None, f"API Error: {str(e)}"
def extract_code_blocks(text):
"""Extract code blocks from markdown"""
pattern = r'```(?:python)?\s*([\s\S]*?)```'
matches = re.findall(pattern, text)
if not matches and text.strip():
if re.search(r'import\s+\w+|def\s+\w+\(|class\s+\w+:', text):
return [text.strip()]
return [match.strip() for match in matches]
def load_generated_app(code):
"""Load and run the generated Gradio app"""
# Save code to temp file
with tempfile.NamedTemporaryFile(suffix='.py', delete=False) as f:
f.write(code.encode('utf-8'))
temp_file = f.name
try:
# Import module
module_name = os.path.basename(temp_file).replace('.py', '')
spec = importlib.util.spec_from_file_location(module_name, temp_file)
module = importlib.util.module_from_spec(spec)
sys.modules[module_name] = module
spec.loader.exec_module(module)
# Get the Gradio interface
if hasattr(module, 'demo'):
return module.demo, None
else:
return None, "No 'demo' variable found in the generated code"
except Exception as e:
error_details = traceback.format_exc()
return None, f"{str(e)}\n{error_details}"
finally:
try:
os.unlink(temp_file)
except:
pass
def get_template_app(prompt_text):
"""Get appropriate template app based on prompt keywords"""
prompt_lower = prompt_text.lower()
if "hello" in prompt_lower or "world" in prompt_lower:
return HELLO_WORLD_APP
elif "calculator" in prompt_lower or "math" in prompt_lower or "calculate" in prompt_lower:
return CALCULATOR_APP
else:
return TEXT_ANALYZER_APP
# Create the main UI - using the most basic approach
with gr.Blocks() as demo:
gr.Markdown(f"# AI Gradio App Generator (v{GRADIO_VERSION})")
gr.Markdown("Describe the Gradio app you want, and I'll generate it for you.")
api_key = gr.Textbox(
label="OpenAI API Key",
placeholder="sk-...",
type="password"
)
prompt = gr.Textbox(
label="App Description",
placeholder="Describe the Gradio app you want to create...",
lines=3
)
submit_btn = gr.Button("Generate App")
template_btn = gr.Button("Use Template App")
code_output = gr.Code(language="python", label="Generated Code")
status_output = gr.Textbox(label="Status")
app_container = gr.HTML(label="Generated App")
def on_submit(api_key_input, prompt_text):
# Validate API key
if not api_key_input or len(api_key_input) < 20:
return None, "Please provide a valid OpenAI API key", "<p>Enter a valid API key</p>"
try:
# Try to generate code via API
response, error = call_openai_api(api_key_input, prompt_text)
if error:
# Fall back to template if API fails
template_code = get_template_app(prompt_text)
app, app_error = load_generated_app(template_code)
if app_error:
return template_code, f"Template fallback also failed: {app_error}", "<p>Failed to generate app</p>"
return template_code, "Using template app (API failed)", f"<iframe src='/template' width='100%' height='500px'></iframe>"
# Extract code from response
code_blocks = extract_code_blocks(response)
if not code_blocks:
template_code = get_template_app(prompt_text)
return template_code, "No code found in API response, using template", f"<iframe src='/template' width='100%' height='500px'></iframe>"
code = code_blocks[0]
# Try to load the generated app
app, app_error = load_generated_app(code)
if app_error:
# Fall back to template
template_code = get_template_app(prompt_text)
return template_code, f"Generated code error: {app_error}\nUsing template instead", f"<iframe src='/template' width='100%' height='500px'></iframe>"
return code, "App generated successfully!", f"<iframe src='/generated' width='100%' height='500px'></iframe>"
except Exception as e:
# Final fallback
template_code = get_template_app(prompt_text)
return template_code, f"Error: {str(e)}\nUsing template instead", f"<iframe src='/template' width='100%' height='500px'></iframe>"
def on_template(prompt_text):
template_code = get_template_app(prompt_text)
return template_code, "Using built-in template app", f"<iframe src='/template' width='100%' height='500px'></iframe>"
submit_btn.click(
on_submit,
inputs=[api_key, prompt],
outputs=[code_output, status_output, app_container]
)
template_btn.click(
on_template,
inputs=[prompt],
outputs=[code_output, status_output, app_container]
)
# Hello world demo that should work with any Gradio version
def hello_world():
return "Hello, World!"
basic_demo = gr.Interface(
fn=hello_world,
inputs=None,
outputs="text",
title="Hello World App"
)
if __name__ == "__main__":
# Use the simplest launch method
demo.launch(server_name="0.0.0.0", server_port=7860) |