Spaces:
Sleeping
Sleeping
| from fastapi import FastAPI, Request | |
| from fastapi.responses import HTMLResponse, JSONResponse | |
| import openai | |
| import os | |
| app = FastAPI() | |
| OPENAI_API_KEY = os.getenv("OPENAI_API_KEY", "") | |
| async def root(): | |
| return """ | |
| <html> | |
| <head> | |
| <title>SuperDeepSite: AI Website Generator</title> | |
| </head> | |
| <body> | |
| <h1>SuperDeepSite π</h1> | |
| <form id=\"genform\" action=\"/generate\" method=\"post\"> | |
| Describe your website or app:<br> | |
| <textarea name=\"prompt\" rows=\"6\" cols=\"50\"></textarea><br> | |
| <input type=\"submit\" value=\"Generate Code!\"> | |
| </form> | |
| </body> | |
| </html> | |
| """ | |
| async def generate(request: Request): | |
| form = await request.form() | |
| user_prompt = form.get("prompt", "") | |
| if not OPENAI_API_KEY: | |
| return HTMLResponse( | |
| "<b>Error:</b> Set <code>OPENAI_API_KEY</code> as a secret/environment variable in your Space settings." | |
| ) | |
| openai.api_key = OPENAI_API_KEY | |
| prompt = f"Generate Python Flask code for a web app that: {user_prompt}\nGive only the code." | |
| try: | |
| completion = openai.ChatCompletion.create( | |
| model="gpt-3.5-turbo", | |
| messages=[ | |
| {"role": "system", "content": "You are a code-writing assistant."}, | |
| {"role": "user", "content": prompt} | |
| ], | |
| max_tokens=700, | |
| ) | |
| code_output = completion.choices[0].message.content | |
| code_html = f"<pre style='background:#eee;padding:1em'>{code_output}</pre>" | |
| except Exception as e: | |
| code_html = f"<b>Error:</b> {str(e)}" | |
| return HTMLResponse( | |
| f"<h2>Result</h2>{code_html}<br><a href='/'>β Go Back</a>" | |
| ) |