amalsp commited on
Commit
7263c70
·
verified ·
1 Parent(s): 5e443ae

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +57 -0
app.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, Request
2
+ from fastapi.responses import HTMLResponse, JSONResponse
3
+ import openai
4
+ import os
5
+
6
+ app = FastAPI()
7
+
8
+ OPENAI_API_KEY = os.getenv("OPENAI_API_KEY", "")
9
+
10
+ @app.get("/", response_class=HTMLResponse)
11
+ async def root():
12
+ return """
13
+ <html>
14
+ <head>
15
+ <title>SuperDeepSite: AI Website Generator</title>
16
+ </head>
17
+ <body>
18
+ <h1>SuperDeepSite 🚀</h1>
19
+ <form id=\"genform\" action=\"/generate\" method=\"post\">
20
+ Describe your website or app:<br>
21
+ <textarea name=\"prompt\" rows=\"6\" cols=\"50\"></textarea><br>
22
+ <input type=\"submit\" value=\"Generate Code!\">
23
+ </form>
24
+ </body>
25
+ </html>
26
+ """
27
+
28
+ @app.post("/generate", response_class=HTMLResponse)
29
+ async def generate(request: Request):
30
+ form = await request.form()
31
+ user_prompt = form.get("prompt", "")
32
+
33
+ if not OPENAI_API_KEY:
34
+ return HTMLResponse(
35
+ "<b>Error:</b> Set <code>OPENAI_API_KEY</code> as a secret/environment variable in your Space settings."
36
+ )
37
+
38
+ openai.api_key = OPENAI_API_KEY
39
+ prompt = f"Generate Python Flask code for a web app that: {user_prompt}\nGive only the code."
40
+
41
+ try:
42
+ completion = openai.ChatCompletion.create(
43
+ model="gpt-3.5-turbo",
44
+ messages=[
45
+ {"role": "system", "content": "You are a code-writing assistant."},
46
+ {"role": "user", "content": prompt}
47
+ ],
48
+ max_tokens=700,
49
+ )
50
+ code_output = completion.choices[0].message.content
51
+ code_html = f"<pre style='background:#eee;padding:1em'>{code_output}</pre>"
52
+ except Exception as e:
53
+ code_html = f"<b>Error:</b> {str(e)}"
54
+
55
+ return HTMLResponse(
56
+ f"<h2>Result</h2>{code_html}<br><a href='/'>← Go Back</a>"
57
+ )