ClarzW commited on
Commit
b7a8716
·
verified ·
1 Parent(s): 7134160

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +751 -0
app.py ADDED
@@ -0,0 +1,751 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Import all libraries that are needed
2
+ import gradio as gr
3
+ import re
4
+ import os
5
+ import psycopg2
6
+ import time
7
+ import uuid
8
+ from collections import defaultdict
9
+
10
+ sql_host = os.getenv('SQL_HOST')
11
+ db = os.getenv('DB')
12
+ user = os.getenv('USER')
13
+ password = os.getenv('PASSWORD')
14
+ quiz1 = os.getenv('QUIZ1')
15
+ quiz2 = os.getenv('QUIZ2')
16
+ quiz3 = os.getenv('QUIZ3')
17
+ quiz4 = os.getenv('QUIZ4')
18
+ quiz5 = os.getenv('QUIZ5')
19
+ quiz6 = os.getenv('QUIZ6')
20
+ ro_user = os.getenv('RO_USER')
21
+ ro_password = os.getenv('RO_PASSWORD')
22
+ email_secret = os.getenv('EMAIL')
23
+
24
+ # Session management
25
+ sessions = defaultdict(lambda: {"timer": 60 * 45, "stop_quiz": True})
26
+
27
+ # Function to generate a unique user id for that session
28
+ def generate_session_id():
29
+ return str(uuid.uuid4())
30
+
31
+ # Function to format time in MM:SS format
32
+ def format_time(seconds):
33
+ minutes, seconds = divmod(seconds, 60)
34
+ return f"{minutes:02}:{seconds:02}"
35
+
36
+ # Function to start the countdown
37
+ def start_countdown(session_id):
38
+ while sessions[session_id]["timer"] >= 0:
39
+ if sessions[session_id]["stop_quiz"]:
40
+ return None
41
+ yield gr.update(value=format_time(sessions[session_id]["timer"])), gr.update(), gr.update()
42
+ time.sleep(1)
43
+ sessions[session_id]["timer"] -= 1
44
+ yield gr.update(value=format_time(sessions[session_id]["timer"])), gr.update(visible=False), gr.update(visible=True)
45
+
46
+ # Function to stop the countdown
47
+ def stop_countdown(session_id):
48
+ sessions[session_id]["stop_quiz"] = True
49
+
50
+ # Validation function
51
+ def validate_inputs(session_id, first_name, last_name, email):
52
+
53
+ # Check if first and last name are present
54
+ if not first_name or not last_name:
55
+ return gr.update(visible=True, value="First name and Last Name are required."), gr.update(visible=True), gr.update(visible=False), gr.update(visible=False)
56
+
57
+ # Check if email address is valid
58
+ if not re.match(rf"^[^@]+@({email_secret})$", email, re.IGNORECASE):
59
+ return gr.update(visible=True, value="Please enter a valid email address."), gr.update(visible=True), gr.update(visible=False), gr.update(visible=False)
60
+
61
+ # If inputs are valid, allow quiz to start and take user to next page
62
+ sessions[session_id]["stop_quiz"] = False
63
+ return gr.update(visible=False), gr.update(visible=False), gr.update(visible=True)
64
+
65
+ # Function to reveal the final page, either when timer runs out or "End Quiz" is clicked
66
+ def final_page_reveal():
67
+ return gr.update(visible=False), gr.update(visible=False), gr.update(visible=True)
68
+
69
+ # Function to initialize the database
70
+ def initialize_database():
71
+
72
+ # Details for connecting to Rockborne database
73
+ conn = psycopg2.connect(
74
+ host=sql_host,
75
+ database=db,
76
+ user=user,
77
+ password=password
78
+ )
79
+ cursor = conn.cursor()
80
+
81
+ # Create the Quiz table
82
+ cursor.execute('''
83
+ CREATE TABLE IF NOT EXISTS Quiz (
84
+ quiz_id SERIAL PRIMARY KEY,
85
+ first_name TEXT,
86
+ last_name TEXT,
87
+ email TEXT
88
+ );
89
+ ''')
90
+
91
+ # Create the QuizAnswers table
92
+ cursor.execute('''
93
+ CREATE TABLE IF NOT EXISTS QuizAnswers (
94
+ quiz_id INTEGER,
95
+ question_number INTEGER,
96
+ answer TEXT,
97
+ FOREIGN KEY (quiz_id) REFERENCES Quiz (quiz_id),
98
+ PRIMARY KEY (quiz_id, question_number)
99
+ );
100
+ ''')
101
+ # Create the employee table
102
+ cursor.execute('''
103
+ CREATE TABLE IF NOT EXISTS employee (
104
+ id INT PRIMARY KEY,
105
+ name VARCHAR(75),
106
+ department VARCHAR(2),
107
+ manager_id INT
108
+ );
109
+ ''')
110
+
111
+ # Insert data into the employee table
112
+ cursor.executemany('''
113
+ INSERT INTO employee (id, name, department, manager_id)
114
+ VALUES (%s, %s, %s, %s)
115
+ ON CONFLICT (id) DO NOTHING;
116
+ ''', [
117
+ (101, 'John', 'A', None),
118
+ (102, 'Dan', 'A', 101),
119
+ (103, 'James', 'A', 101),
120
+ (104, 'Amy', 'A', 101),
121
+ (105, 'Anne', 'A', 101),
122
+ (106, 'Ron', 'B', 101)
123
+ ])
124
+
125
+ # Create the courses table
126
+ cursor.execute('''
127
+ CREATE TABLE IF NOT EXISTS courses (
128
+ student VARCHAR(1) PRIMARY KEY,
129
+ class VARCHAR(50)
130
+ );
131
+ ''')
132
+
133
+ # Insert data into the courses table
134
+ cursor.executemany('''
135
+ INSERT INTO courses (student, class)
136
+ VALUES (%s, %s)
137
+ ON CONFLICT (student) DO NOTHING;
138
+ ''', [
139
+ ('A', 'Maths'),
140
+ ('B', 'English'),
141
+ ('C', 'Maths'),
142
+ ('D', 'Biology'),
143
+ ('E', 'Maths'),
144
+ ('F', 'Computer'),
145
+ ('G', 'Maths'),
146
+ ('H', 'Maths'),
147
+ ('I', 'Maths')
148
+ ])
149
+
150
+ # Create the salesperson table
151
+ cursor.execute('''
152
+ CREATE TABLE IF NOT EXISTS salesperson (
153
+ sales_id INT PRIMARY KEY,
154
+ name VARCHAR(50),
155
+ salary DECIMAL(10, 2),
156
+ commission_rate DECIMAL(5, 2),
157
+ hire_date DATE
158
+ );
159
+ ''')
160
+
161
+ # Insert data into the salesperson table
162
+ cursor.executemany('''
163
+ INSERT INTO salesperson (sales_id, name, salary, commission_rate, hire_date)
164
+ VALUES (%s, %s, %s, %s, %s)
165
+ ON CONFLICT (sales_id) DO NOTHING;
166
+ ''', [
167
+ (1, 'John', 100000, 6, '2006-04-01'),
168
+ (2, 'Amy', 120000, 5, '2010-05-01'),
169
+ (3, 'Mark', 65000, 12, '2008-12-25'),
170
+ (4, 'Pam', 25000, 25, '2005-01-01'),
171
+ (5, 'Alex', 50000, 10, '2007-02-03')
172
+ ])
173
+
174
+ # Create the company table
175
+ cursor.execute('''
176
+ CREATE TABLE IF NOT EXISTS company (
177
+ com_id INT PRIMARY KEY,
178
+ name VARCHAR(50),
179
+ city VARCHAR(50)
180
+ );
181
+ ''')
182
+
183
+ # Insert data into the company table
184
+ cursor.executemany('''
185
+ INSERT INTO company (com_id, name, city)
186
+ VALUES (%s, %s, %s)
187
+ ON CONFLICT (com_id) DO NOTHING;
188
+ ''', [
189
+ (1, 'RED', 'Boston'),
190
+ (2, 'ORANGE', 'New York'),
191
+ (3, 'YELLOW', 'Boston'),
192
+ (4, 'GREEN', 'Austin')
193
+ ])
194
+
195
+ # Create the orders table
196
+ cursor.execute('''
197
+ CREATE TABLE IF NOT EXISTS orders (
198
+ order_id INT PRIMARY KEY,
199
+ order_date DATE,
200
+ com_id INT,
201
+ sales_id INT,
202
+ amount DECIMAL(10, 2),
203
+ FOREIGN KEY (sales_id) REFERENCES salesperson(sales_id),
204
+ FOREIGN KEY (com_id) REFERENCES company(com_id)
205
+ );
206
+ ''')
207
+
208
+ # Insert data into the orders table
209
+ cursor.executemany('''
210
+ INSERT INTO orders (order_id, order_date, com_id, sales_id, amount)
211
+ VALUES (%s, %s, %s, %s, %s)
212
+ ON CONFLICT (order_id) DO NOTHING;
213
+ ''', [
214
+ (1, '2014-01-01', 3, 4, 100000),
215
+ (2, '2014-02-01', 4, 5, 5000),
216
+ (3, '2014-03-01', 1, 1, 50000),
217
+ (4, '2014-04-01', 1, 4, 25000)
218
+ ])
219
+
220
+ # Create the tree table
221
+ cursor.execute('''
222
+ CREATE TABLE IF NOT EXISTS tree (
223
+ id INT PRIMARY KEY,
224
+ p_id INT
225
+ );
226
+ ''')
227
+
228
+ # Insert data into the tree table
229
+ cursor.executemany('''
230
+ INSERT INTO tree (id, p_id)
231
+ VALUES (%s, %s)
232
+ ON CONFLICT (id) DO NOTHING;
233
+ ''', [
234
+ (1, None),
235
+ (2, 1),
236
+ (3, 1),
237
+ (4, 2),
238
+ (5, 2)
239
+ ])
240
+
241
+ # Create the movies table
242
+ cursor.execute('''
243
+ CREATE TABLE IF NOT EXISTS movies (
244
+ id INT PRIMARY KEY,
245
+ movie VARCHAR(50),
246
+ description VARCHAR(50),
247
+ rating DECIMAL(3, 1)
248
+ );
249
+ ''')
250
+
251
+ # Insert data into the movies table
252
+ cursor.executemany('''
253
+ INSERT INTO movies (id, movie, description, rating)
254
+ VALUES (%s, %s, %s, %s)
255
+ ON CONFLICT (id) DO NOTHING;
256
+ ''', [
257
+ (1, 'War', 'Great 3D', 8.9),
258
+ (2, 'Science', 'Fiction', 8.5),
259
+ (3, 'Irish', 'Boring', 6.2),
260
+ (4, 'Ice song', 'Fantasy', 8.6),
261
+ (5, 'House card', 'Interesting', 9.1)
262
+ ])
263
+
264
+ # Create the product table
265
+ cursor.execute('''
266
+ CREATE TABLE IF NOT EXISTS product (
267
+ product_key INT PRIMARY KEY
268
+ );
269
+ ''')
270
+
271
+ # Insert data into the product table
272
+ cursor.executemany('''
273
+ INSERT INTO product (product_key)
274
+ VALUES (%s)
275
+ ON CONFLICT (product_key) DO NOTHING;
276
+ ''', [
277
+ (5,),
278
+ (6,)
279
+ ])
280
+
281
+ # Create the customer table
282
+ cursor.execute('''
283
+ CREATE TABLE IF NOT EXISTS customer (
284
+ customer_id INT ,
285
+ product_key INT,
286
+ PRIMARY KEY (customer_id, product_key),
287
+ FOREIGN KEY (product_key) REFERENCES product(product_key)
288
+ );
289
+ ''')
290
+
291
+ # Insert data into the customer table
292
+ cursor.executemany('''
293
+ INSERT INTO customer (customer_id, product_key)
294
+ VALUES (%s, %s)
295
+ ON CONFLICT (customer_id, product_key) DO NOTHING;
296
+ ''', [
297
+ (1, 5),
298
+ (2, 6),
299
+ (3, 5),
300
+ (3, 6),
301
+ (1, 6)
302
+ ])
303
+
304
+ # Create the locations table
305
+ cursor.execute('''
306
+ CREATE TABLE IF NOT EXISTS locations (
307
+ postal_code VARCHAR(50) PRIMARY KEY,
308
+ city_name VARCHAR(50),
309
+ location VARCHAR(50)
310
+ );
311
+ ''')
312
+
313
+ # Insert data into the locations table
314
+ cursor.executemany('''
315
+ INSERT INTO locations (postal_code, city_name, location)
316
+ VALUES (%s, %s, %s)
317
+ ON CONFLICT (postal_code) DO NOTHING;
318
+ ''', [
319
+ ('900', 'Los Angeles', 'California'),
320
+ ('921', 'San Diego', 'CA'),
321
+ ('691', 'Bakersfield', 'California')
322
+ ])
323
+
324
+ # Create the departments table
325
+ cursor.execute('''
326
+ CREATE TABLE IF NOT EXISTS departments (
327
+ department_id INT PRIMARY KEY,
328
+ department_name VARCHAR(50),
329
+ location VARCHAR(50)
330
+ );
331
+ ''')
332
+
333
+ # Insert data into the departments table
334
+ cursor.executemany('''
335
+ INSERT INTO departments (department_id, department_name, location)
336
+ VALUES (%s, %s, %s)
337
+ ON CONFLICT (department_id) DO NOTHING;
338
+ ''', [
339
+ (101, 'HR', 'California'),
340
+ (102, 'IT', 'NY'),
341
+ (103, 'Finance', 'CA')
342
+ ])
343
+
344
+ # Create the employees table
345
+ cursor.execute('''
346
+ CREATE TABLE IF NOT EXISTS employees (
347
+ employee_id INT PRIMARY KEY,
348
+ employee_name VARCHAR(50),
349
+ department_id INT,
350
+ postal_code INT,
351
+ FOREIGN KEY(department_id) REFERENCES departments(department_id)
352
+ );
353
+ ''')
354
+
355
+ # Insert data into the employees table
356
+ cursor.executemany('''
357
+ INSERT INTO employees (employee_id, employee_name, department_id, postal_code)
358
+ VALUES (%s, %s, %s, %s)
359
+ ON CONFLICT (employee_id) DO NOTHING;
360
+ ''', [
361
+ (1, 'Kent', '101', 900),
362
+ (2, 'Taylor', '102', 691),
363
+ (3, 'Rachel', '103', 690),
364
+ (4, 'Sam', '101', 921)
365
+ ])
366
+
367
+
368
+ conn.commit()
369
+ cursor.close()
370
+ conn.close()
371
+
372
+ # Call the function to initialise the database
373
+ initialize_database()
374
+
375
+ # Function to create a new quiz entry and return the quiz_id
376
+ def start_quiz(session_id, first_name, last_name, email):
377
+
378
+ # Connect to the database
379
+ conn = psycopg2.connect(
380
+ host=sql_host,
381
+ database=db,
382
+ user=user,
383
+ password=password
384
+ )
385
+ cursor = conn.cursor()
386
+
387
+ # If quiz is allowed to start (i.e. details are valid), submit the user details into the database with incrementally increased "quiz_id"
388
+ if not sessions[session_id]["stop_quiz"]:
389
+ cursor.execute('''
390
+ INSERT INTO Quiz (first_name, last_name, email)
391
+ VALUES (%s, %s, %s)
392
+ RETURNING quiz_id
393
+ ''', (first_name, last_name, email))
394
+ quiz_id = cursor.fetchone()[0]
395
+
396
+ # If quiz is not allowed to start (i.e. details not valid) don't update anything
397
+ else:
398
+ quiz_id = None
399
+ conn.commit()
400
+ cursor.close()
401
+ conn.close()
402
+ return quiz_id
403
+
404
+ # Function to save a user's answerto a given question to the database
405
+ def save_answer(quiz_id, question_number, answer):
406
+
407
+ # Connect to the database
408
+ conn = psycopg2.connect(
409
+ host=sql_host,
410
+ database=db,
411
+ user=user,
412
+ password=password
413
+ )
414
+ cursor = conn.cursor()
415
+
416
+ # Insert their answer into the database, updating if one already existed for that question
417
+ cursor.execute('''
418
+ INSERT INTO QuizAnswers (quiz_id, question_number, answer)
419
+ VALUES (%s, %s, %s)
420
+ ON CONFLICT (quiz_id, question_number)
421
+ DO UPDATE SET answer = EXCLUDED.answer
422
+ ''', (quiz_id, question_number, answer))
423
+ conn.commit()
424
+ cursor.close()
425
+ conn.close()
426
+
427
+ # Return success message
428
+ return "Answer saved successfully!"
429
+
430
+ # Function to return question details
431
+ def get_questions(question):
432
+ questions = {
433
+ "Question 1": quiz1,
434
+ "Question 2": quiz2,
435
+ "Question 3": quiz3,
436
+ "Question 4": quiz4,
437
+ "Question 5": quiz5,
438
+ "Question 6": quiz6
439
+ }
440
+ return questions.get(question, "No details available")
441
+
442
+ # Define the function to execute SQL queries
443
+ def execute_sql(query):
444
+ try:
445
+ # Connect to the database
446
+ conn = psycopg2.connect(
447
+ host=sql_host,
448
+ database=db,
449
+ user=ro_user,
450
+ password=ro_password
451
+ )
452
+ cursor = conn.cursor()
453
+
454
+ # Ensure the query only accesses the appropriate table
455
+ if "quiz" in query.lower():
456
+ return f"### SQL Output\n\nYou are not allowed to access the table 'quiz'."
457
+ if "quizanswers" in query.lower():
458
+ return f"### SQL Output\n\nYou are not allowed to access the table 'quizanswers'."
459
+ if "insert" in query.lower():
460
+ return f"### SQL Output\n\nYou are not allowed use 'insert'."
461
+ if "delete" in query.lower():
462
+ return f"### SQL Output\n\nYou are not allowed use 'delete'."
463
+ if "update" in query.lower():
464
+ return f"### SQL Output\n\nYou are not allowed use 'update'."
465
+ if "merge" in query.lower():
466
+ return f"### SQL Output\n\nYou are not allowed use 'merge'."
467
+ if "truncate" in query.lower():
468
+ return f"### SQL Output\n\nYou are not allowed use 'truncate'."
469
+ if "create" in query.lower():
470
+ return f"### SQL Output\n\nYou are not allowed use 'create'."
471
+ if "alter" in query.lower():
472
+ return f"### SQL Output\n\nYou are not allowed use 'alter'."
473
+ if "drop" in query.lower():
474
+ return f"### SQL Output\n\nYou are not allowed use 'drop'."
475
+ if "rename" in query.lower():
476
+ return f"### SQL Output\n\nYou are not allowed use 'rename'."
477
+
478
+ cursor.execute(query)
479
+ conn.commit()
480
+
481
+ # If the query involves a select statement, display their answer in a formatted table
482
+ if "select" in query.strip().lower():
483
+ results = cursor.fetchall()
484
+ column_names = [description[0] for description in cursor.description]
485
+
486
+ # Create the header row with column names
487
+ header = "| " + " | ".join(column_names) + " |"
488
+
489
+ # Create the separator row with dashes
490
+ separator = "| " + " | ".join(['---' for _ in column_names]) + " |"
491
+
492
+ # Create the data rows
493
+ rows = "\n".join(["| " + " | ".join(map(str, row)) + " |" for row in results])
494
+
495
+ # Combine header, separator, and rows into the final table string
496
+ results_str = f"{header}\n{separator}\n{rows}"
497
+
498
+ # Return the formatted table to be rendered in gr.Markdown
499
+ return f"### SQL Output\n\n{results_str}"
500
+
501
+ # If not a select statement, show that query was executed successfully
502
+ else:
503
+ return "Query executed successfully"
504
+
505
+ # If there is an error, return error message
506
+ except Exception as e:
507
+ return str(e)
508
+
509
+ # Close connection to the database
510
+ finally:
511
+ if conn:
512
+ cursor.close()
513
+ conn.close()
514
+
515
+ #NEWW
516
+ def show_confirmation():
517
+ return (gr.update(visible=True), # Make confirmation message visible
518
+ gr.update(visible=True), # Make the "Yes, End Quiz" button visible
519
+ gr.update(visible=True), # Make the "No, I want to continue" button visible
520
+ gr.update(visible=False)) # Hide the original "End Quiz" button
521
+
522
+ def hide_confirmation():
523
+ return (gr.update(visible=False), # Hide confirmation message
524
+ gr.update(visible=False), # Hide the "Yes, End Quiz" button
525
+ gr.update(visible=False), # Hide the "No, I want to continue" button
526
+ gr.update(visible=True)) # Show the original "End Quiz" button again
527
+
528
+
529
+ # Define the Gradio app layout
530
+ with gr.Blocks() as app:
531
+
532
+ # This defines the landing page, with instructions and inputs for user details
533
+ with gr.Column(visible=True) as intro:
534
+
535
+ # Generate a unique session_id for the user
536
+ session_id = gr.State(generate_session_id)
537
+
538
+ # HTML code for welcome page and instructions
539
+ gr.Markdown("<h1 style='text-align: center;'>WELCOME</h1>")
540
+ gr.Markdown("<h2>Instructions</h2>", elem_id="instructions-title")
541
+ gr.Markdown("""
542
+ <p>This test is designed to evaluate your SQL proficiency by measuring your ability to write efficient and accurate SQL select queries. It will help you identify your strengths and areas for improvement.</p>
543
+ <p>This test consists of 6 SQL questions with varied levels of difficulty.</p>
544
+ <p>You will have 45 minutes to complete the assessment.</p>
545
+ <p>To start this test please input your first name, last name and your email address, then click on ‘Begin Test’.</p>
546
+ <p>After starting the test, click ‘Test query’ to test your SQL queries and view its output.</p>
547
+ <p>For each question, you <b>must</b> press 'Save Answer' for the answer to be submitted. These can be resubmitted, but only the most recent version will be marked.</p>
548
+ <p>When the timer reaches 0, the test will immediately end and no further answers can be submitted.</p>
549
+ <p>Clicking "End Quiz" before the time finishes will automatically end the quiz, it does <b>not</b> submit any unsaved answers.</p>
550
+ <p><b style="font-size:20px;">Do NOT refresh the page, this start a new user entry.</b></p>
551
+ """)
552
+
553
+ # Textboxes for users to input details
554
+ first_name = gr.Textbox(label="First Name")
555
+ last_name = gr.Textbox(label="Last Name")
556
+ email = gr.Textbox(label="Email")
557
+ error_message = gr.Markdown("", visible=False)
558
+ submit_button = gr.Button("Start Test")
559
+
560
+ # This defines the exit page, telling the user to quit the application
561
+ with gr.Column(visible=False) as exit_page:
562
+ gr.HTML(
563
+ """
564
+ <div style="display: flex; justify-content: center; align-items: flex-start; height: 100vh; margin: 0;">
565
+ <div style="text-align: center; border: 2px solid black; padding: 20px; padding-bottom: 40px; margin-top: 40px;">
566
+ <h1 style="margin-bottom: 30px;">Exit Page</h1>
567
+ <p style="margin-bottom: 20px;">Thank you for completing the quiz.</p>
568
+ <p style="margin-bottom: 20px;">Please do not try to reattempt this assessment, only your first submission will be marked.</p>
569
+ <p>You may now close this page within your browser.</p>
570
+ </div>
571
+ </div>
572
+ """
573
+ )
574
+
575
+ # This defines the page with quiz questions
576
+ with gr.Column(visible=False) as quiz_page:
577
+
578
+ # Important instructions repeated in a markdown
579
+ gr.Markdown(
580
+ """
581
+ <div style="display: flex; flex-direction: column; align-items: center;">
582
+ <h1>Quiz Questions</h1>
583
+ <div style="border: 2px solid black; padding: 20px; text-align: left; width: 100%; max-width: 1000px;">
584
+ <b>Remember the following:</b>
585
+ <div style="margin-top: 10px;">
586
+ <ul style="list-style-position: inside; padding-left: 20px;">
587
+ <li>For each question, you <b>must</b> press 'Save Answer' for the answer to be submitted. These can be resubmitted, but only the most recent version will be marked.</li>
588
+ <li>When the timer reaches 0, the test will immediately end and no further answers can be submitted.</li>
589
+ <li>Clicking "End Quiz" before the time finishes will automatically end the quiz; it does <b>not</b> submit any unsaved answers.</li>
590
+ <li><b style="font-size:20px;">Do NOT refresh the page, this start a new user entry.</b></p></li>
591
+ </div>
592
+ </div>
593
+ </div>
594
+ """
595
+ )
596
+
597
+ quiz_id = gr.State(value=None) # State to store the quiz_id
598
+
599
+ # First row on this page
600
+ with gr.Row():
601
+ # Fixed left pane with questions and timer box
602
+ with gr.Column(scale=1, min_width=200):
603
+ # Create buttons for each question
604
+ question_buttons = [
605
+ gr.Button(value=f"Question {i}", elem_id=f"question_{i}") for i in range(1, 7)
606
+ ]
607
+
608
+ # Timer box
609
+ text = gr.Textbox(label="Remaining time", value="45:00", lines=1, interactive=False)
610
+
611
+ # Right pane with details and SQL editor
612
+ with gr.Column(scale=3):
613
+
614
+ # Shows active question number at the top of the page
615
+ details_output = gr.Markdown(value="")
616
+
617
+ # Editor for user to put their code in
618
+ sql_editors = [gr.Code(label=f"Write your answer for Question {i} here:", language="sql", lines=8, visible=False) for i in range(1, 7)]
619
+
620
+ # Output to show the result of user's query when they test it
621
+ sql_output = gr.Markdown("""<h3>SQL Output</h3><br><br>""")
622
+
623
+ question_number = gr.State(value=None)
624
+
625
+ # Function to allow users to click between questions
626
+ def on_question_click(question_number):
627
+ question_number = int(question_number)
628
+ question = f"Question {question_number}"
629
+ editor_updates = [gr.update(visible=(i == question_number)) for i in range(1, 7)]
630
+ # Clear the SQL output
631
+ sql_output_update = gr.update(value="")
632
+ return [get_questions(question), question_number] + editor_updates + [sql_output_update]
633
+
634
+ # Bund the function 'on_question_click' to the question buttons
635
+ for i in range(1, 7):
636
+ question_buttons[i-1].click(
637
+ on_question_click,
638
+ inputs=[gr.Number(value=i, visible=False)],
639
+ outputs=[details_output, question_number] + sql_editors + [sql_output],
640
+ concurrency_limit=20
641
+ )
642
+ # Row with buttons to test query, save answer and end quiz
643
+ with gr.Row():
644
+ with gr.Column(scale=1):
645
+ test_query_button = gr.Button("Test Query")
646
+ with gr.Column(scale=1):
647
+ save_answer_button = gr.Button("Save Answer")
648
+ with gr.Column(scale=1):
649
+ end_quiz_button = gr.Button("End Quiz")
650
+
651
+ # Function to test a user's query
652
+ def test_query(active_question, *sql_codes):
653
+ if active_question is not None:
654
+ # Convert active_question to an integer
655
+ question_index = int(active_question) - 1
656
+ sql_code = sql_codes[question_index]
657
+ return execute_sql(sql_code)
658
+ return "Please select a question first."
659
+
660
+ # Function to save a user's query
661
+ def save_answer_multi(quiz_id, active_question, *sql_codes):
662
+ if active_question is not None:
663
+ # Convert active_question to an integer
664
+ question_index = int(active_question) - 1
665
+ sql_code = sql_codes[question_index]
666
+ return save_answer(quiz_id, int(active_question), sql_code)
667
+ return "Please select a question first."
668
+
669
+ # Bind the test_query_button to the function that tests the query
670
+ test_query_button.click(
671
+ test_query,
672
+ inputs=[question_number] + sql_editors,
673
+ outputs=sql_output,
674
+ concurrency_limit=20
675
+ )
676
+
677
+ # Bind the save_answer_button to the function that saves the answer
678
+ save_answer_button.click(
679
+ save_answer_multi,
680
+ inputs=[quiz_id, question_number] + sql_editors,
681
+ outputs=sql_output,
682
+ concurrency_limit=20
683
+ )
684
+
685
+ # Confirmation components
686
+ confirmation_message = gr.Markdown("<b>Are you sure you want to end the quiz?</b>", visible=False)
687
+ with gr.Row():
688
+ with gr.Column():
689
+ confirm_button = gr.Button("Yes, End Quiz", visible=False)
690
+ with gr.Column():
691
+ cancel_button = gr.Button("No, I want to continue", visible=False)
692
+
693
+ # Bind the end_quiz_button to show the confirmation popup
694
+ end_quiz_button.click(fn=show_confirmation,
695
+ inputs=[],
696
+ outputs=[confirmation_message, confirm_button, cancel_button, end_quiz_button]
697
+ )
698
+
699
+ # Bind the confirm_button to the functions that end the quiz
700
+ confirm_button.click(fn=final_page_reveal,
701
+ inputs=[],
702
+ outputs=[error_message, quiz_page, exit_page],
703
+ concurrency_limit=20
704
+ )
705
+
706
+ # Bind the confirm_button to the function that stops the countdown
707
+ confirm_button.click(fn=stop_countdown,
708
+ inputs=[session_id],
709
+ outputs=[],
710
+ concurrency_limit=20
711
+ )
712
+
713
+ # Bind the cancel_button to hide the confirmation popup and show the end quiz button again
714
+ cancel_button.click(fn=hide_confirmation,
715
+ inputs=[],
716
+ outputs=[confirmation_message, confirm_button, cancel_button, end_quiz_button])
717
+
718
+
719
+
720
+ # Bind the submit_button to functions that validate the inputs and starts the quiz
721
+ submit_button.click(
722
+ fn=lambda sid, fn, ln, em: (
723
+ validate_inputs(sid, fn, ln, em)[0],
724
+ validate_inputs(sid, fn, ln, em)[1],
725
+ validate_inputs(sid, fn, ln, em)[2],
726
+ start_quiz(sid, fn, ln, em)
727
+ ),
728
+ inputs=[session_id, first_name, last_name, email],
729
+ outputs=[error_message, intro, quiz_page, quiz_id],
730
+ concurrency_limit=20
731
+ )
732
+
733
+ # Also bind the submit_button to the function that starts the countdown
734
+ submit_button.click(
735
+ fn=start_countdown,
736
+ inputs=[session_id],
737
+ outputs=[text, quiz_page, exit_page],
738
+ concurrency_limit=20
739
+ )
740
+
741
+ # Also bind the submit_button to the function to reveal question 1 on the new page
742
+ submit_button.click(
743
+ fn=on_question_click,
744
+ inputs=[gr.Number(value=1, visible=False)],
745
+ outputs=[details_output, question_number] + sql_editors + [sql_output],
746
+ concurrency_limit=20
747
+ )
748
+
749
+ # Launch the app with support for concurrent users
750
+ if __name__ == "__main__":
751
+ app.launch(share=False, max_threads=40) # Adjust max_threads as needed