Spaces:
Sleeping
Sleeping
File size: 1,817 Bytes
7263c70 |
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 |
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", "")
@app.get("/", response_class=HTMLResponse)
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>
"""
@app.post("/generate", response_class=HTMLResponse)
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>"
) |