helliun commited on
Commit
ca48be3
·
verified ·
1 Parent(s): 3ee7b89

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +396 -26
app.py CHANGED
@@ -1,43 +1,413 @@
1
- from pathlib import Path
 
 
 
2
  from fastapi import FastAPI
 
3
  from fastapi.staticfiles import StaticFiles
4
  import uvicorn
5
- import gradio as gr
6
- from datetime import datetime
7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
 
9
- # create a FastAPI app
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
  app = FastAPI()
11
 
12
- # create a static directory to store the static files
13
- static_dir = Path('./static')
14
- static_dir.mkdir(parents=True, exist_ok=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
 
16
- # mount FastAPI StaticFiles server
17
- app.mount("/static", StaticFiles(directory=static_dir), name="static")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
 
19
- # Gradio code
20
- def predict(text_input):
21
- file_name = f"{datetime.utcnow().strftime('%s')}.html"
22
- file_path = static_dir / file_name
23
- print(file_path)
24
- with open(file_path, "w") as f:
25
- f.write(f"""<h2>Hello {text_input} </h2>
26
- <h3>{file_name}</h3>
27
- """)
 
 
 
 
 
 
 
 
 
 
 
 
 
28
 
29
- return f'<a href="/static/{file_name}" target="_blank">{file_name}</a>'
30
 
31
 
32
- with gr.Blocks() as block:
33
- text_input = gr.Textbox(label="Name")
34
- markdown = gr.Markdown(label="Output Box")
35
- new_btn = gr.Button("New")
36
- new_btn.click(fn=predict, inputs=[text_input], outputs=[markdown])
37
 
38
- # mount Gradio app to FastAPI app
39
- app = gr.mount_gradio_app(app, block, path="/")
 
 
40
 
 
 
 
 
41
  # serve the app
42
  if __name__ == "__main__":
43
  uvicorn.run(app, host="0.0.0.0", port=7860)
 
1
+ import pandas as pd
2
+ from openai import OpenAI
3
+ import json
4
+ import gradio as gr
5
  from fastapi import FastAPI
6
+ from fastapi.responses import HTMLResponse
7
  from fastapi.staticfiles import StaticFiles
8
  import uvicorn
 
 
9
 
10
+ client = OpenAI()
11
+
12
+ def generate_questions(category, num_categories, num_questions):
13
+ if category == "":
14
+ category = "general knowledge"
15
+ print(category)
16
+ response = client.chat.completions.create(
17
+ model="gpt-4o-mini",
18
+ messages=[
19
+ {
20
+ "role": "user",
21
+ "content": [
22
+ {
23
+ "type": "text",
24
+ "text": f"Break the category \"{category}\" into {num_categories} subcategories, and for each subcategory create {num_questions} True/False questions ranging from a question a Beginner would know to a question only an Expert would know. There should be as many True as False, and the structure of the questions should not make it obvious which is the answer. Only experts should get the hard questions right. Provide the correct answers and a field with a 1 sentence explanation. This will total out to {num_categories * num_questions} questions. Output just a JSON, nothing else. Below is an example JSON output for \"nutrition\" where 6 categories of 5 questions were requested, but remember, for you, there should be a total of {num_categories * num_questions} questions with {num_categories} categories and {num_questions} questions per category.\n\n```json\n{{\n \"Macronutrients\": [\n {{\n \"question\": \"Protein is one of the three primary macronutrients.\",\n \"answer\": True,\n \"explanation\": \"Protein is one of the three primary macronutrients, along with carbohydrates and fats.\"\n }},\n {{\n \"question\": \"Carbohydrates are the body's main source of energy.\",\n \"answer\": True,\n \"explanation\": \"Carbohydrates are typically the body's preferred energy source.\"\n }},\n {{\n \"question\": \"Fats have the same caloric content per gram as carbohydrates.\",\n \"answer\": False,\n \"explanation\": \"Fats have 9 calories per gram, while carbohydrates have 4 calories per gram.\"\n }},\n {{\n \"question\": \"All proteins are equally effective for muscle growth.\",\n \"answer\": False,\n \"explanation\": \"Different proteins have varying amino acid profiles and bioavailability, affecting their effectiveness.\"\n }},\n {{\n \"question\": \"Omega-3 fatty acids are a type of fat that can reduce inflammation.\",\n \"answer\": True,\n \"explanation\": \"Omega-3 fatty acids, found in foods like fish, are known to have anti-inflammatory properties.\"\n }}\n ],\n \"Micronutrients\": [\n {{ ...\"}}"
25
+ }
26
+ ]
27
+ }
28
+ ],
29
+ response_format={"type": "json_object"},
30
+ temperature=1,
31
+ max_tokens=4071,
32
+ top_p=1,
33
+ frequency_penalty=0,
34
+ presence_penalty=0
35
+ )
36
+ return json.loads(response.choices[0].message.content)
37
+
38
+ # Function to calculate Metaknowledge score
39
+ def calculate_meta_cog_score(df):
40
+ df['Correct'] = df['User Answer'] == df['Correct Answer']
41
+ df['C'] = df['Correct'].apply(lambda x: 1 if x else -1)
42
+ n = len(df)
43
+ sum_C_Conf = (df['C'] * df['Confidence']).sum()
44
+ meta_cog_ratio = 0.5 + (sum_C_Conf / (2 * n))
45
+ return meta_cog_ratio
46
+
47
+ def display_current_question(questions, index):
48
+ if index < len(questions):
49
+ question = questions[index]
50
+ return (
51
+ f"**Question {index + 1}:** {question['question']}",
52
+ None, None, True
53
+ )
54
+ else:
55
+ return ("", None, None, False)
56
+
57
+ def calculate_scores(df):
58
+ df['Correct'] = df['User Answer'] == df['Correct Answer']
59
+ df['C'] = df['Correct'].apply(lambda x: 1 if x else 0)
60
+
61
+ # Expected score based on confidence
62
+ df['Expected Score'] = df['Confidence']
63
+ df['Actual Score'] = df['C']
64
+
65
+ # Difference between expected and actual scores
66
+ df['Overconfidence'] = (df['Expected Score'] > df['Actual Score']).astype(float) * (df['Expected Score'] - df['Actual Score'])
67
+ df['Underconfidence'] = (df['Expected Score'] < df['Actual Score']).astype(float) * (df['Actual Score'] - df['Expected Score'])
68
+
69
+ n = len(df)
70
+ sum_C_Conf = (df['C'] * df['Confidence']).sum()
71
+ meta_cog_ratio = 0.5 + (sum_C_Conf / (2 * n))
72
+
73
+ accuracy = df['Correct'].mean()
74
+ overconfidence = df['Overconfidence'].sum() / n
75
+ underconfidence = df['Underconfidence'].sum() / n
76
+
77
+ return {
78
+ # 'Metaknowledge Score': f"{round(meta_cog_ratio * 100, 0)}%",
79
+ 'Accuracy': f"{round(accuracy * 100, 0)}%",
80
+ 'Overconfidence': f"{round(overconfidence * 100, 0)}%",
81
+ 'Underconfidence': f"{round(underconfidence * 100, 0)}%"
82
+ }
83
+
84
+ # Function to analyze results using GPT-4o-mini
85
+ def analyze_results(df, overall_scores, subcategory_scores):
86
+ # Prepare the data for analysis
87
+ questions = df['Question'].tolist()
88
+ correct_answers = df['Correct Answer'].tolist()
89
+ user_answers = df['User Answer'].tolist()
90
+ explanations = df['Explanation'].tolist()
91
+ confidence = df['Confidence'].tolist()
92
+ subcategories = df['Section'].tolist()
93
+
94
+ # Generate a summary of the results
95
+ response = client.chat.completions.create(
96
+ model="gpt-4o-mini",
97
+ messages=[
98
+ {
99
+ "role": "user",
100
+ "content": f"""
101
+ Analyze the following quiz results:
102
+ - Overall Accuracy: {overall_scores['Accuracy']}
103
+ - Overall Overconfidence: {overall_scores['Overconfidence']}
104
+ - Overall Underconfidence: {overall_scores['Underconfidence']}
105
+
106
+ Section scores:
107
+ {subcategory_scores}
108
+
109
+ The following is a list of my answers and confidence levels for each question, with the correct answers and subcategory:
110
+ {list(zip(questions, user_answers, correct_answers, explanations, confidence, subcategories))}
111
+
112
+ Provide an analysis of what I got wrong in terms of overall sections and specific questions, as well as what I was overconfident and underconfident in. Don't use numbers, as they're already displayed elsewhere.
113
+ The analysis should be only about 2 paragraphs. Write the subcategory names in bold when you use them.
114
+ """
115
+ }
116
+ ],
117
+ # response_format={ "type": "json_object" },
118
+ temperature=0.7,
119
+ max_tokens=1024,
120
+ top_p=1,
121
+ frequency_penalty=0,
122
+ presence_penalty=0
123
+ )
124
+
125
+ analysis = response.choices[0].message.content
126
+
127
+ # Start the table with larger column titles using <b> for bold and <span> for custom styling
128
+ question_details = (
129
+ "<table><thead><tr>"
130
+ "<th><b><span style='font-size:16px'>Question</span></b></th>"
131
+ "<th><b><span style='font-size:16px'>User Answer</span></b></th>"
132
+ "<th><b><span style='font-size:16px'>Correct Answer</span></b></th>"
133
+ "<th><b><span style='font-size:16px'>Explanation</span></b></th>"
134
+ "</tr></thead><tbody>"
135
+ )
136
+
137
+ for q, ua, ca, subcategory, e in zip(questions, user_answers, correct_answers, subcategories, explanations):
138
+ user_answer_str = 'True' if ua else 'False'
139
+ correct_answer_str = 'True' if ca else 'False'
140
+
141
+ # Check if the answer is incorrect
142
+ if ua != ca:
143
+ question_details += (
144
+ f"<tr><td><b>{q}</b></td><td><b>{user_answer_str}</b></td>"
145
+ f"<td><b>{correct_answer_str}</b></td><td><b>{e}</b></td></tr>"
146
+ )
147
+ else:
148
+ question_details += (
149
+ f"<tr><td>{q}</td><td>{user_answer_str}</td>"
150
+ f"<td>{correct_answer_str}</td><td>{e}</td></tr>"
151
+ )
152
+
153
+ question_details += "</tbody></table>"
154
+
155
+ return f"## Analysis of Results\n\n{analysis}\n\n## Detailed Questions and Answers\n\n{question_details}"
156
+
157
+ # Modify the submit_answer function to include analysis
158
+ def submit_answer(category, num_categories, num_questions, questions, index, user_answer, confidence, user_answers):
159
+ question_data = questions[index]
160
+ subcategory = question_data["subcategory"]
161
+
162
+ user_answers.append({
163
+ "Question": question_data["question"],
164
+ "Explanation": question_data["explanation"],
165
+ "User Answer": confidence > 0.5,
166
+ "Correct Answer": question_data["answer"],
167
+ "Confidence": 2*abs(confidence-0.5),
168
+ "Section": subcategory
169
+ })
170
+ index += 1
171
 
172
+ if index >= len(questions):
173
+ df = pd.DataFrame(user_answers)
174
+ overall_scores = calculate_scores(df)
175
+ subcategory_scores = df.groupby('Section').apply(calculate_scores).to_dict()
176
+ analysis = analyze_results(df, overall_scores, subcategory_scores)
177
+
178
+ overall_score_df = pd.DataFrame([["Overall", *overall_scores.values()]], columns=['Section', 'Accuracy', 'Overconfidence', 'Underconfidence'])
179
+ subcategory_scores_df = pd.DataFrame([(subcategory, *score.values()) for subcategory, score in subcategory_scores.items()], columns=['Section', 'Accuracy', 'Overconfidence', 'Underconfidence'])
180
+ results_df = pd.concat([overall_score_df, subcategory_scores_df], ignore_index=True)
181
+ results_df = gr.DataFrame(label="Results", value=results_df, visible=True)
182
+ return "", index, gr.update(visible=False), user_answers, results_df, gr.update(visible=False), gr.update(visible=False), gr.update(value=analysis, visible=True), gr.update(visible=False)
183
+ else:
184
+ question_text, _, _, visible = display_current_question(questions, index)
185
+ return question_text, index, gr.update(visible=True), user_answers, gr.update(visible=False), gr.update(visible=True, value=0.5), gr.update(visible=False, value=None), gr.update(visible=False), gr.update(visible=True)
186
+
187
+ # Gradio UI setup
188
+ with gr.Blocks(theme="soft", css="footer{display:none !important}") as demo:
189
+ # Top bar with menu
190
+ # gr.Markdown("""## &nbsp; Deep Quizzer <img src="file/Subject.png" img align="left" width="20" height="20" />""")
191
+ gr.Markdown("""Discover what you truly know and ***how aware you are of your knowledge***. Deep Quizzer identifies gaps in your understanding and helps boost your confidence in areas you excel. Take a quiz to sharpen your skills and knowledge today!""")
192
+ with gr.Row():
193
+ category_input = gr.Textbox(label="Topic", placeholder="general knowledge", scale=4)
194
+ num_categories_input = gr.Number(label="Number of Quiz Sections", value=5, scale=1, maximum=6)
195
+ num_questions_input = gr.Number(label="Questions per Section", value=5, scale=1, maximum=6)
196
+ total_questions_display = gr.Number(label="Total Questions in Quiz", value=25, scale=1)
197
+ submit_category = gr.Button("Generate Quiz")
198
+ question_area = gr.Markdown(visible=False)
199
+ answer_area = gr.Radio(["True", "False"], label="Your Answer", visible=False)
200
+ with gr.Column():
201
+ confidence_slider = gr.Slider(0, 1, value=0.5, visible=False, container=False)
202
+ with gr.Row(visible=False) as guides:
203
+ gr.Markdown('<p style="text-align: left;">False</p>')
204
+ gr.Markdown('<p style="text-align: left;">Maybe False</p>')
205
+ gr.Markdown('<p style="text-align: center;">Not Sure</p>')
206
+ gr.Markdown('<p style="text-align: right;">Maybe True</p>')
207
+ gr.Markdown('<p style="text-align: right;">True</p>')
208
+
209
+ submit_answer_btn = gr.Button("Submit Answer", visible=False)
210
+ result_area = gr.DataFrame(label="Results", visible=False)
211
+ loading_text = gr.Textbox(label="Generating Quiz...", visible=False)
212
+ analysis_area = gr.Markdown(visible=False)
213
+ questions_state = gr.State()
214
+ index_state = gr.State(0)
215
+ user_answers_state = gr.State([])
216
+
217
+ def on_generate_quiz(category, num_categories, num_questions):
218
+ questions_data = generate_questions(category, num_categories, num_questions)
219
+
220
+ questions = []
221
+ for subcategory, qs in questions_data.items():
222
+ for q in qs:
223
+ q["subcategory"] = subcategory
224
+ questions.append(q)
225
+
226
+ import random
227
+ random.shuffle(questions)
228
+ print(len(questions))
229
+
230
+ index = 0
231
+ question_text, _, _, visible = display_current_question(questions, index)
232
+ return (
233
+ gr.update(value=question_text, visible=visible),
234
+ questions,
235
+ index,
236
+ [],
237
+ gr.update(visible=visible),
238
+ gr.update(visible=False, value=None),
239
+ gr.update(visible=True, value=0.5),
240
+ gr.update(visible=True),
241
+ gr.update(visible=False),
242
+ gr.update(visible=False),
243
+ gr.update(visible=False),
244
+ gr.update(visible=True)
245
+ )
246
+
247
+ def remove_button():
248
+ return gr.update(visible=False)
249
+
250
+ def display_loading():
251
+ return gr.update(visible=True)
252
+
253
+ def update_total_questions(num_categories, num_questions):
254
+ total_questions = num_categories * num_questions
255
+ return gr.update(value=total_questions)
256
+
257
+ def display_results(index, questions):
258
+ if index >= len(questions):
259
+ return gr.update(visible=True)
260
+
261
+ num_categories_input.change(update_total_questions, inputs=[num_categories_input, num_questions_input], outputs=[total_questions_display])
262
+ num_questions_input.change(update_total_questions, inputs=[num_categories_input, num_questions_input], outputs=[total_questions_display])
263
+
264
+ submit_category.click(remove_button, inputs=[], outputs=[submit_category])
265
+ submit_category.click(display_loading, inputs=[], outputs=[loading_text])
266
+
267
+ def make_uninteractive():
268
+ return (
269
+ gr.update(interactive=False),
270
+ gr.update(interactive=False, visible=False),
271
+ gr.update(interactive=False, visible=False)
272
+ )
273
+
274
+ submit_category.click(
275
+ make_uninteractive,
276
+ inputs=[],
277
+ outputs=[category_input, num_categories_input, num_questions_input]
278
+ )
279
+
280
+ submit_category.click(
281
+ on_generate_quiz,
282
+ inputs=[category_input, num_categories_input, num_questions_input],
283
+ outputs=[
284
+ question_area,
285
+ questions_state,
286
+ index_state,
287
+ user_answers_state,
288
+ question_area,
289
+ answer_area,
290
+ confidence_slider,
291
+ submit_answer_btn,
292
+ result_area,
293
+ submit_category,
294
+ loading_text,
295
+ guides
296
+ ]
297
+ )
298
+
299
+
300
+ submit_answer_btn.click(
301
+ submit_answer,
302
+ inputs=[category_input, num_categories_input, num_questions_input, questions_state, index_state, answer_area, confidence_slider, user_answers_state],
303
+ outputs=[question_area, index_state, submit_answer_btn, user_answers_state, result_area, confidence_slider, answer_area, analysis_area, guides]
304
+ )
305
+
306
+ submit_answer_btn.click(display_results, inputs=[index_state, questions_state], outputs=[result_area])
307
+
308
+ # Launch the app
309
+ # app.launch(share=False, allowed_paths=["/"])
310
+ from starlette.middleware.cors import CORSMiddleware
311
+
312
+ # Define the FastAPI app
313
  app = FastAPI()
314
 
315
+ @app.middleware("http")
316
+ async def add_csp_header(request, call_next):
317
+ response = await call_next(request)
318
+ response.headers['Content-Security-Policy'] = "frame-ancestors 'self' https://*.azurewebsites.net"
319
+ return response
320
+
321
+ @app.middleware("https")
322
+ async def add_csp_header(request, call_next):
323
+ response = await call_next(request)
324
+ response.headers['Content-Security-Policy'] = "frame-ancestors 'self' https://*.azurewebsites.net"
325
+ return response
326
+
327
+ app.add_middleware(
328
+ CORSMiddleware,
329
+ allow_origins=["*"], # Adjust this in production
330
+ allow_credentials=True,
331
+ allow_methods=["*"],
332
+ allow_headers=["*"],
333
+ )
334
+
335
+ # Define paths for static files
336
+ app.mount("/static", StaticFiles(directory="."), name="static")
337
+
338
+ # Define the navigation HTML template with corrected styling
339
+ nav_html = '''
340
+ <div style="background-color: #40E0D0; padding: 10px 20px; display: flex; align-items: center; position: absolute; top: 0; left: 0; width: 100%; box-sizing: border-box;">
341
+ <a href="/" style="color: black; margin: 0 15px; text-decoration: none; font-size: 18px; font-weight: bold; display: flex; align-items: center;">
342
+ <img src="/static/Subject.png" alt="Deep Quizzer Logo" width="25" height="25" style="margin-right: 10px;" />
343
+ Deep Quizzer
344
+ </a>
345
+ <a href="/about" style="color: black; margin: 0 15px; text-decoration: none; font-size: 18px; font-weight: bold; display: flex; align-items: center;">About</a>
346
+ </div>
347
+ '''
348
 
349
+ # Define the main page HTML
350
+ index_html = f'''
351
+ <head>
352
+ <meta charset="UTF-8">
353
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
354
+ <title>Deep Quizzer</title>
355
+ <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@400;600&display=swap" rel="stylesheet">
356
+ <style>
357
+ body {{
358
+ font-family: 'Montserrat', sans-serif;
359
+ margin: 0; /* Remove default margin */
360
+ }}
361
+ iframe {{
362
+ margin-top: 50px; /* Prevent iframe content from being hidden under the navbar */
363
+ }}
364
+ </style>
365
+ </head>
366
+ <body>
367
+ {nav_html}
368
+ <div>
369
+ <iframe src="/gradioapp" style="border: 0; width: 100%; height: calc(100vh - 50px);"></iframe>
370
+ </div>
371
+ </body>
372
+ '''
373
 
374
+ # Define the about page HTML
375
+ about_html = f'''
376
+ <head>
377
+ <meta charset="UTF-8">
378
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
379
+ <title>About Deep Quizzer</title>
380
+ <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@400;600&display=swap" rel="stylesheet">
381
+ <style>
382
+ body {{
383
+ font-family: 'Montserrat', sans-serif;
384
+ margin: 0; /* Remove default margin */
385
+ }}
386
+ </style>
387
+ </head>
388
+ <body>
389
+ {nav_html}
390
+ <div style="padding: 70px 20px 20px;"> <!-- Adjust padding to account for the navbar height -->
391
+ <h1>About Deep Quizzer</h1>
392
+ <p>Deep Quizzer is an interactive quiz platform designed to test your knowledge and awareness. You can explore different categories, answer questions, and gain insights into your confidence and accuracy levels. The platform helps identify areas where you excel and where you may need improvement.</p>
393
+ </div>
394
+ </body>
395
+ '''
396
 
 
397
 
398
 
399
+ # Mount Gradio app
400
+ app = gr.mount_gradio_app(app, demo, path="/gradioapp", allowed_paths=["/"], root_path="deploy/")
 
 
 
401
 
402
+ # Define the route for the main page
403
+ @app.get("/", response_class=HTMLResponse)
404
+ async def index():
405
+ return index_html
406
 
407
+ # Define the route for the about page
408
+ @app.get("/about", response_class=HTMLResponse)
409
+ async def about():
410
+ return about_html
411
  # serve the app
412
  if __name__ == "__main__":
413
  uvicorn.run(app, host="0.0.0.0", port=7860)