-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
74 lines (66 loc) · 2.73 KB
/
app.py
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
from flask import Flask, render_template, redirect, request, g
import sqlite3
from openai import OpenAI
import os
app = Flask(__name__)
# This function returns the database. If the database has not been created yet, it creates it and
# stores it in Flask's special global variable `g`.
def get_db():
db = getattr(g, '_database', None)
if db is None:
db = g._database = sqlite3.connect("feedback.db")
return db
# Similar to get_db, this function get's the OpenAI client, which is used to interact with the
# OpenAI API.
def get_openai_client():
api_key = os.environ.get("OPENAI_API_KEY")
if not api_key:
raise ValueError("OPENAI_API_KEY environment variable is not set")
client = OpenAI(api_key=api_key)
return client
# This function is decorated to return the index page when the user visits the root URL.
@app.route('/', methods=['GET'])
def index():
return render_template('index.html')
# This function is decorated to handle the feedback form submission's POST-request, storing the
# feedback in the database, and renders thanks page when complete.
@app.route('/feedback', methods=['POST'])
def feedback():
feedback = request.form.get('feedback')
db = get_db()
cur = db.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS feedback (feedback TEXT)") # Only happens once
cur.execute("INSERT INTO feedback (feedback) VALUES (?)", (feedback,))
db.commit()
return render_template('thanks.html')
@app.route('/summarize_feedback', methods=['GET'])
def summarize_feedback():
db = get_db()
cur = db.cursor()
cur.execute("SELECT feedback FROM feedback")
feedbacks = cur.fetchall()
feedbacks = [feedback[0] for feedback in feedbacks]
feedbacks = "\n".join(feedbacks)
openai_client = get_openai_client()
completion = openai_client.chat.completions.create(
messages=[
{
"role": "system",
"content": "Summarize the submitted feedbacks (new-line separated). Identify key topics about the assignment for the class to discuss. Format as an unordered list (ul) in html without code fences. Include the opening and closeing <ul> tags at the start and end of the response, and wrap each bullet point in an li, but don't render any other html.",
},
{
"role": "user",
"content": feedbacks,
}
],
model="gpt-3.5-turbo",
)
summary = completion.choices[0].message.content
return render_template('summary.html', summary=summary)
# This function is called when the app is done running.
# It closes the database connection.
# The OpenAI client does not need to be closed.
@app.teardown_appcontext
def close_connection(exception):
db = get_db()
db.close()