SQL_Quiz_Legend / app.py
ClarzW's picture
Update app.py
ac51d16 verified
Raw History Blame Contribute Delete
27.8 kB
# Import all libraries that are needed
import gradio as gr
import re
import os
import psycopg2
import time
import uuid
from collections import defaultdict
sql_host = os.getenv('SQL_HOST')
db = os.getenv('DB')
user = os.getenv('USER')
password = os.getenv('PASSWORD')
quiz1 = os.getenv('QUIZ1')
quiz2 = os.getenv('QUIZ2')
quiz3 = os.getenv('QUIZ3')
quiz4 = os.getenv('QUIZ4')
quiz5 = os.getenv('QUIZ5')
quiz6 = os.getenv('QUIZ6')
ro_user = os.getenv('RO_USER')
ro_password = os.getenv('RO_PASSWORD')
email_secret = os.getenv('EMAIL')
# Session management
sessions = defaultdict(lambda: {"timer": 60 * 45, "stop_quiz": True})
# Function to generate a unique user id for that session
def generate_session_id():
return str(uuid.uuid4())
# Function to format time in MM:SS format
def format_time(seconds):
minutes, seconds = divmod(seconds, 60)
return f"{minutes:02}:{seconds:02}"
# Function to start the countdown
def start_countdown(session_id):
while sessions[session_id]["timer"] >= 0:
if sessions[session_id]["stop_quiz"]:
return None
yield gr.update(value=format_time(sessions[session_id]["timer"])), gr.update(), gr.update()
time.sleep(1)
sessions[session_id]["timer"] -= 1
yield gr.update(value=format_time(sessions[session_id]["timer"])), gr.update(visible=False), gr.update(visible=True)
# Function to stop the countdown
def stop_countdown(session_id):
sessions[session_id]["stop_quiz"] = True
# Validation function
def validate_inputs(session_id, first_name, last_name, email):
# Check if first and last name are present
if not first_name or not last_name:
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)
# Check if email address is valid
if not re.match(rf"^[^@]+@({email_secret})$", email, re.IGNORECASE):
return gr.update(visible=True, value="Please enter a valid email address."), gr.update(visible=True), gr.update(visible=False), gr.update(visible=False)
# If inputs are valid, allow quiz to start and take user to next page
sessions[session_id]["stop_quiz"] = False
return gr.update(visible=False), gr.update(visible=False), gr.update(visible=True)
# Function to reveal the final page, either when timer runs out or "End Quiz" is clicked
def final_page_reveal():
return gr.update(visible=False), gr.update(visible=False), gr.update(visible=True)
# Function to initialize the database
def initialize_database():
# Details for connecting to Rockborne database
conn = psycopg2.connect(
host=sql_host,
database=db,
user=user,
password=password
)
cursor = conn.cursor()
# Create the Quiz table
cursor.execute('''
CREATE TABLE IF NOT EXISTS Quiz (
quiz_id SERIAL PRIMARY KEY,
first_name TEXT,
last_name TEXT,
email TEXT
);
''')
# Create the QuizAnswers table
cursor.execute('''
CREATE TABLE IF NOT EXISTS QuizAnswers (
quiz_id INTEGER,
question_number INTEGER,
answer TEXT,
FOREIGN KEY (quiz_id) REFERENCES Quiz (quiz_id),
PRIMARY KEY (quiz_id, question_number)
);
''')
# Create the employee table
cursor.execute('''
CREATE TABLE IF NOT EXISTS employee (
id INT PRIMARY KEY,
name VARCHAR(75),
department VARCHAR(2),
manager_id INT
);
''')
# Insert data into the employee table
cursor.executemany('''
INSERT INTO employee (id, name, department, manager_id)
VALUES (%s, %s, %s, %s)
ON CONFLICT (id) DO NOTHING;
''', [
(101, 'John', 'A', None),
(102, 'Dan', 'A', 101),
(103, 'James', 'A', 101),
(104, 'Amy', 'A', 101),
(105, 'Anne', 'A', 101),
(106, 'Ron', 'B', 101)
])
# Create the courses table
cursor.execute('''
CREATE TABLE IF NOT EXISTS courses (
student VARCHAR(1) PRIMARY KEY,
class VARCHAR(50)
);
''')
# Insert data into the courses table
cursor.executemany('''
INSERT INTO courses (student, class)
VALUES (%s, %s)
ON CONFLICT (student) DO NOTHING;
''', [
('A', 'Maths'),
('B', 'English'),
('C', 'Maths'),
('D', 'Biology'),
('E', 'Maths'),
('F', 'Computer'),
('G', 'Maths'),
('H', 'Maths'),
('I', 'Maths')
])
# Create the salesperson table
cursor.execute('''
CREATE TABLE IF NOT EXISTS salesperson (
sales_id INT PRIMARY KEY,
name VARCHAR(50),
salary DECIMAL(10, 2),
commission_rate DECIMAL(5, 2),
hire_date DATE
);
''')
# Insert data into the salesperson table
cursor.executemany('''
INSERT INTO salesperson (sales_id, name, salary, commission_rate, hire_date)
VALUES (%s, %s, %s, %s, %s)
ON CONFLICT (sales_id) DO NOTHING;
''', [
(1, 'John', 100000, 6, '2006-04-01'),
(2, 'Amy', 120000, 5, '2010-05-01'),
(3, 'Mark', 65000, 12, '2008-12-25'),
(4, 'Pam', 25000, 25, '2005-01-01'),
(5, 'Alex', 50000, 10, '2007-02-03')
])
# Create the company table
cursor.execute('''
CREATE TABLE IF NOT EXISTS company (
com_id INT PRIMARY KEY,
name VARCHAR(50),
city VARCHAR(50)
);
''')
# Insert data into the company table
cursor.executemany('''
INSERT INTO company (com_id, name, city)
VALUES (%s, %s, %s)
ON CONFLICT (com_id) DO NOTHING;
''', [
(1, 'RED', 'Boston'),
(2, 'ORANGE', 'New York'),
(3, 'YELLOW', 'Boston'),
(4, 'GREEN', 'Austin')
])
# Create the orders table
cursor.execute('''
CREATE TABLE IF NOT EXISTS orders (
order_id INT PRIMARY KEY,
order_date DATE,
com_id INT,
sales_id INT,
amount DECIMAL(10, 2),
FOREIGN KEY (sales_id) REFERENCES salesperson(sales_id),
FOREIGN KEY (com_id) REFERENCES company(com_id)
);
''')
# Insert data into the orders table
cursor.executemany('''
INSERT INTO orders (order_id, order_date, com_id, sales_id, amount)
VALUES (%s, %s, %s, %s, %s)
ON CONFLICT (order_id) DO NOTHING;
''', [
(1, '2014-01-01', 3, 4, 100000),
(2, '2014-02-01', 4, 5, 5000),
(3, '2014-03-01', 1, 1, 50000),
(4, '2014-04-01', 1, 4, 25000)
])
# Create the tree table
cursor.execute('''
CREATE TABLE IF NOT EXISTS tree (
id INT PRIMARY KEY,
p_id INT
);
''')
# Insert data into the tree table
cursor.executemany('''
INSERT INTO tree (id, p_id)
VALUES (%s, %s)
ON CONFLICT (id) DO NOTHING;
''', [
(1, None),
(2, 1),
(3, 1),
(4, 2),
(5, 2)
])
# Create the movies table
cursor.execute('''
CREATE TABLE IF NOT EXISTS movies (
id INT PRIMARY KEY,
movie VARCHAR(50),
description VARCHAR(50),
rating DECIMAL(3, 1)
);
''')
# Insert data into the movies table
cursor.executemany('''
INSERT INTO movies (id, movie, description, rating)
VALUES (%s, %s, %s, %s)
ON CONFLICT (id) DO NOTHING;
''', [
(1, 'War', 'Great 3D', 8.9),
(2, 'Science', 'Fiction', 8.5),
(3, 'Irish', 'Boring', 6.2),
(4, 'Ice song', 'Fantasy', 8.6),
(5, 'House card', 'Interesting', 9.1)
])
# Create the product table
cursor.execute('''
CREATE TABLE IF NOT EXISTS product (
product_key INT PRIMARY KEY
);
''')
# Insert data into the product table
cursor.executemany('''
INSERT INTO product (product_key)
VALUES (%s)
ON CONFLICT (product_key) DO NOTHING;
''', [
(5,),
(6,)
])
# Create the customer table
cursor.execute('''
CREATE TABLE IF NOT EXISTS customer (
customer_id INT ,
product_key INT,
PRIMARY KEY (customer_id, product_key),
FOREIGN KEY (product_key) REFERENCES product(product_key)
);
''')
# Insert data into the customer table
cursor.executemany('''
INSERT INTO customer (customer_id, product_key)
VALUES (%s, %s)
ON CONFLICT (customer_id, product_key) DO NOTHING;
''', [
(1, 5),
(2, 6),
(3, 5),
(3, 6),
(1, 6)
])
# Create the locations table
cursor.execute('''
CREATE TABLE IF NOT EXISTS locations (
postal_code VARCHAR(50) PRIMARY KEY,
city_name VARCHAR(50),
location VARCHAR(50)
);
''')
# Insert data into the locations table
cursor.executemany('''
INSERT INTO locations (postal_code, city_name, location)
VALUES (%s, %s, %s)
ON CONFLICT (postal_code) DO NOTHING;
''', [
('900', 'Los Angeles', 'California'),
('921', 'San Diego', 'CA'),
('691', 'Bakersfield', 'California')
])
# Create the departments table
cursor.execute('''
CREATE TABLE IF NOT EXISTS departments (
department_id INT PRIMARY KEY,
department_name VARCHAR(50),
location VARCHAR(50)
);
''')
# Insert data into the departments table
cursor.executemany('''
INSERT INTO departments (department_id, department_name, location)
VALUES (%s, %s, %s)
ON CONFLICT (department_id) DO NOTHING;
''', [
(101, 'HR', 'California'),
(102, 'IT', 'NY'),
(103, 'Finance', 'CA')
])
# Create the employees table
cursor.execute('''
CREATE TABLE IF NOT EXISTS employees (
employee_id INT PRIMARY KEY,
employee_name VARCHAR(50),
department_id INT,
postal_code INT,
FOREIGN KEY(department_id) REFERENCES departments(department_id)
);
''')
# Insert data into the employees table
cursor.executemany('''
INSERT INTO employees (employee_id, employee_name, department_id, postal_code)
VALUES (%s, %s, %s, %s)
ON CONFLICT (employee_id) DO NOTHING;
''', [
(1, 'Kent', '101', 900),
(2, 'Taylor', '102', 691),
(3, 'Rachel', '103', 690),
(4, 'Sam', '101', 921)
])
conn.commit()
cursor.close()
conn.close()
# Call the function to initialise the database
initialize_database()
# Function to create a new quiz entry and return the quiz_id
def start_quiz(session_id, first_name, last_name, email):
# Connect to the database
conn = psycopg2.connect(
host=sql_host,
database=db,
user=user,
password=password
)
cursor = conn.cursor()
# If quiz is allowed to start (i.e. details are valid), submit the user details into the database with incrementally increased "quiz_id"
if not sessions[session_id]["stop_quiz"]:
cursor.execute('''
INSERT INTO Quiz (first_name, last_name, email)
VALUES (%s, %s, %s)
RETURNING quiz_id
''', (first_name, last_name, email))
quiz_id = cursor.fetchone()[0]
# If quiz is not allowed to start (i.e. details not valid) don't update anything
else:
quiz_id = None
conn.commit()
cursor.close()
conn.close()
return quiz_id
# Function to save a user's answerto a given question to the database
def save_answer(quiz_id, question_number, answer):
# Connect to the database
conn = psycopg2.connect(
host=sql_host,
database=db,
user=user,
password=password
)
cursor = conn.cursor()
# Insert their answer into the database, updating if one already existed for that question
cursor.execute('''
INSERT INTO QuizAnswers (quiz_id, question_number, answer)
VALUES (%s, %s, %s)
ON CONFLICT (quiz_id, question_number)
DO UPDATE SET answer = EXCLUDED.answer
''', (quiz_id, question_number, answer))
conn.commit()
cursor.close()
conn.close()
# Return success message
return "Answer saved successfully!"
# Function to return question details
def get_questions(question):
questions = {
"Question 1": quiz1,
"Question 2": quiz2,
"Question 3": quiz3,
"Question 4": quiz4,
"Question 5": quiz5,
"Question 6": quiz6
}
return questions.get(question, "No details available")
# Define the function to execute SQL queries
def execute_sql(query):
try:
# Connect to the database
conn = psycopg2.connect(
host=sql_host,
database=db,
user=ro_user,
password=ro_password
)
cursor = conn.cursor()
# Ensure the query only accesses the appropriate table
if "quiz" in query.lower():
return f"### SQL Output\n\nYou are not allowed to access the table 'quiz'."
if "quizanswers" in query.lower():
return f"### SQL Output\n\nYou are not allowed to access the table 'quizanswers'."
if "insert" in query.lower():
return f"### SQL Output\n\nYou are not allowed use 'insert'."
if "delete" in query.lower():
return f"### SQL Output\n\nYou are not allowed use 'delete'."
if "update" in query.lower():
return f"### SQL Output\n\nYou are not allowed use 'update'."
if "merge" in query.lower():
return f"### SQL Output\n\nYou are not allowed use 'merge'."
if "truncate" in query.lower():
return f"### SQL Output\n\nYou are not allowed use 'truncate'."
if "create" in query.lower():
return f"### SQL Output\n\nYou are not allowed use 'create'."
if "alter" in query.lower():
return f"### SQL Output\n\nYou are not allowed use 'alter'."
if "drop" in query.lower():
return f"### SQL Output\n\nYou are not allowed use 'drop'."
if "rename" in query.lower():
return f"### SQL Output\n\nYou are not allowed use 'rename'."
cursor.execute(query)
conn.commit()
# If the query involves a select statement, display their answer in a formatted table
if "select" in query.strip().lower():
results = cursor.fetchall()
column_names = [description[0] for description in cursor.description]
# Create the header row with column names
header = "| " + " | ".join(column_names) + " |"
# Create the separator row with dashes
separator = "| " + " | ".join(['---' for _ in column_names]) + " |"
# Create the data rows
rows = "\n".join(["| " + " | ".join(map(str, row)) + " |" for row in results])
# Combine header, separator, and rows into the final table string
results_str = f"{header}\n{separator}\n{rows}"
# Return the formatted table to be rendered in gr.Markdown
return f"### SQL Output\n\n{results_str}"
# If not a select statement, show that query was executed successfully
else:
return "Query executed successfully"
# If there is an error, return error message
except Exception as e:
return str(e)
# Close connection to the database
finally:
if conn:
cursor.close()
conn.close()
#NEWW
def show_confirmation():
return (gr.update(visible=True), # Make confirmation message visible
gr.update(visible=True), # Make the "Yes, End Quiz" button visible
gr.update(visible=True), # Make the "No, I want to continue" button visible
gr.update(visible=False)) # Hide the original "End Quiz" button
def hide_confirmation():
return (gr.update(visible=False), # Hide confirmation message
gr.update(visible=False), # Hide the "Yes, End Quiz" button
gr.update(visible=False), # Hide the "No, I want to continue" button
gr.update(visible=True)) # Show the original "End Quiz" button again
# Define the Gradio app layout
with gr.Blocks() as app:
# This defines the landing page, with instructions and inputs for user details
with gr.Column(visible=True) as intro:
# Generate a unique session_id for the user
session_id = gr.State(generate_session_id)
# HTML code for welcome page and instructions
gr.Markdown("<h1 style='text-align: center;'>WELCOME</h1>")
gr.Markdown("<h2>Instructions</h2>", elem_id="instructions-title")
gr.Markdown("""
<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>
<p>This test consists of 6 SQL questions with varied levels of difficulty.</p>
<p>You will have 45 minutes to complete the assessment.</p>
<p>To start this test please input your first name, last name and your email address, then click on ‘Begin Test’.</p>
<p>After starting the test, click ‘Test query’ to test your SQL queries and view its output.</p>
<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>
<p>When the timer reaches 0, the test will immediately end and no further answers can be submitted.</p>
<p>Clicking "End Quiz" before the time finishes will automatically end the quiz, it does <b>not</b> submit any unsaved answers.</p>
<p><b style="font-size:20px;">Do NOT refresh the page, this will start a new user entry.</b></p>
""")
# Textboxes for users to input details
first_name = gr.Textbox(label="First Name")
last_name = gr.Textbox(label="Last Name")
email = gr.Textbox(label="Email")
error_message = gr.Markdown("", visible=False)
submit_button = gr.Button("Start Test")
# This defines the exit page, telling the user to quit the application
with gr.Column(visible=False) as exit_page:
gr.HTML(
"""
<div style="display: flex; justify-content: center; align-items: flex-start; height: 100vh; margin: 0;">
<div style="text-align: center; border: 2px solid black; padding: 20px; padding-bottom: 40px; margin-top: 40px;">
<h1 style="margin-bottom: 30px;">Exit Page</h1>
<p style="margin-bottom: 20px;">Thank you for completing the quiz.</p>
<p style="margin-bottom: 20px;">Please do not try to reattempt this assessment, only your first submission will be marked.</p>
<p>You may now close this page within your browser.</p>
</div>
</div>
"""
)
# This defines the page with quiz questions
with gr.Column(visible=False) as quiz_page:
# Important instructions repeated in a markdown
gr.Markdown(
"""
<div style="display: flex; flex-direction: column; align-items: center;">
<h1>Quiz Questions</h1>
<div style="border: 2px solid black; padding: 20px; text-align: left; width: 100%; max-width: 1000px;">
<b>Remember the following:</b>
<div style="margin-top: 10px;">
<ul style="list-style-position: inside; padding-left: 20px;">
<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>
<li>When the timer reaches 0, the test will immediately end and no further answers can be submitted.</li>
<li>Clicking "End Quiz" before the time finishes will automatically end the quiz; it does <b>not</b> submit any unsaved answers.</li>
<li><b style="font-size:20px;">Do NOT refresh the page, this will start a new user entry.</b></p></li>
</div>
</div>
</div>
"""
)
quiz_id = gr.State(value=None) # State to store the quiz_id
# First row on this page
with gr.Row():
# Fixed left pane with questions and timer box
with gr.Column(scale=1, min_width=200):
# Create buttons for each question
question_buttons = [
gr.Button(value=f"Question {i}", elem_id=f"question_{i}") for i in range(1, 7)
]
# Timer box
text = gr.Textbox(label="Remaining time", value="45:00", lines=1, interactive=False)
# Right pane with details and SQL editor
with gr.Column(scale=3):
# Shows active question number at the top of the page
details_output = gr.Markdown(value="")
# Editor for user to put their code in
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)]
# Output to show the result of user's query when they test it
sql_output = gr.Markdown("""<h3>SQL Output</h3><br><br>""")
question_number = gr.State(value=None)
# Function to allow users to click between questions
def on_question_click(question_number):
question_number = int(question_number)
question = f"Question {question_number}"
editor_updates = [gr.update(visible=(i == question_number)) for i in range(1, 7)]
# Clear the SQL output
sql_output_update = gr.update(value="")
return [get_questions(question), question_number] + editor_updates + [sql_output_update]
# Bund the function 'on_question_click' to the question buttons
for i in range(1, 7):
question_buttons[i-1].click(
on_question_click,
inputs=[gr.Number(value=i, visible=False)],
outputs=[details_output, question_number] + sql_editors + [sql_output],
concurrency_limit=20
)
# Row with buttons to test query, save answer and end quiz
with gr.Row():
with gr.Column(scale=1):
test_query_button = gr.Button("Test Query")
with gr.Column(scale=1):
save_answer_button = gr.Button("Save Answer")
with gr.Column(scale=1):
end_quiz_button = gr.Button("End Quiz")
# Function to test a user's query
def test_query(active_question, *sql_codes):
if active_question is not None:
# Convert active_question to an integer
question_index = int(active_question) - 1
sql_code = sql_codes[question_index]
return execute_sql(sql_code)
return "Please select a question first."
# Function to save a user's query
def save_answer_multi(quiz_id, active_question, *sql_codes):
if active_question is not None:
# Convert active_question to an integer
question_index = int(active_question) - 1
sql_code = sql_codes[question_index]
return save_answer(quiz_id, int(active_question), sql_code)
return "Please select a question first."
# Bind the test_query_button to the function that tests the query
test_query_button.click(
test_query,
inputs=[question_number] + sql_editors,
outputs=sql_output,
concurrency_limit=20
)
# Bind the save_answer_button to the function that saves the answer
save_answer_button.click(
save_answer_multi,
inputs=[quiz_id, question_number] + sql_editors,
outputs=sql_output,
concurrency_limit=20
)
# Confirmation components
confirmation_message = gr.Markdown("<b>Are you sure you want to end the quiz?</b>", visible=False)
with gr.Row():
with gr.Column():
confirm_button = gr.Button("Yes, end quiz", visible=False)
with gr.Column():
cancel_button = gr.Button("No, I want to continue", visible=False)
# Bind the end_quiz_button to show the confirmation popup
end_quiz_button.click(fn=show_confirmation,
inputs=[],
outputs=[confirmation_message, confirm_button, cancel_button, end_quiz_button]
)
# Bind the confirm_button to the functions that end the quiz
confirm_button.click(fn=final_page_reveal,
inputs=[],
outputs=[error_message, quiz_page, exit_page],
concurrency_limit=20
)
# Bind the confirm_button to the function that stops the countdown
confirm_button.click(fn=stop_countdown,
inputs=[session_id],
outputs=[],
concurrency_limit=20
)
# Bind the cancel_button to hide the confirmation popup and show the end quiz button again
cancel_button.click(fn=hide_confirmation,
inputs=[],
outputs=[confirmation_message, confirm_button, cancel_button, end_quiz_button])
# Bind the submit_button to functions that validate the inputs and starts the quiz
submit_button.click(
fn=lambda sid, fn, ln, em: (
validate_inputs(sid, fn, ln, em)[0],
validate_inputs(sid, fn, ln, em)[1],
validate_inputs(sid, fn, ln, em)[2],
start_quiz(sid, fn, ln, em)
),
inputs=[session_id, first_name, last_name, email],
outputs=[error_message, intro, quiz_page, quiz_id],
concurrency_limit=20
)
# Also bind the submit_button to the function that starts the countdown
submit_button.click(
fn=start_countdown,
inputs=[session_id],
outputs=[text, quiz_page, exit_page],
concurrency_limit=20
)
# Also bind the submit_button to the function to reveal question 1 on the new page
submit_button.click(
fn=on_question_click,
inputs=[gr.Number(value=1, visible=False)],
outputs=[details_output, question_number] + sql_editors + [sql_output],
concurrency_limit=20
)
# Launch the app with support for concurrent users
if __name__ == "__main__":
app.launch(share=False, max_threads=40) # Adjust max_threads as needed