quiz / app.py
guptadeepak18's picture
Update app.py
8c23cb2 verified
Raw History Blame Contribute Delete
3.98 kB
import streamlit as st
import pandas as pd
import random
import gspread
from oauth2client.service_account import ServiceAccountCredentials
# Google Sheets setup
scope = ["https://spreadsheets.google.com/feeds", "https://www.googleapis.com/auth/drive"]
credentials = ServiceAccountCredentials.from_json_keyfile_name('gspread-credentials.json', scope)
client = gspread.authorize(credentials)
responses_sheet = client.open("QuizResponses").sheet1
# Load questions from a Google Sheet
questions_url = 'https://docs.google.com/spreadsheets/d/1w5zZRg5drriTFrCAaT47e7H7ujYALIG5D7VTQsTpPxY/export?format=csv'
questions_df = pd.read_csv(questions_url)
# Fetch existing PRNs from the sheet
submitted_prns = set(responses_sheet.col_values(1))
# Function to shuffle questions and options
def get_random_questions(df, num_questions=5):
questions = df.sample(n=num_questions).to_dict('records')
for q in questions:
options = [q['Option1'], q['Option2'], q['Option3'], q['Option4']]
random.shuffle(options)
q['options'] = options
return questions
# Initialize session state
if 'student_info' not in st.session_state:
st.session_state['student_info'] = None
if 'questions' not in st.session_state:
st.session_state['questions'] = []
if 'current_question' not in st.session_state:
st.session_state['current_question'] = 0
if 'responses' not in st.session_state:
st.session_state['responses'] = []
if 'completed' not in st.session_state:
st.session_state['completed'] = False
# Page 1: Student Information
if st.session_state['student_info'] is None:
st.title("Student Quiz App")
st.subheader("Enter your details")
prn = st.text_input("PRN")
name = st.text_input("Name")
division = st.selectbox("Division", ['A', 'B', 'C', 'D'])
submit_info = st.button("Start Quiz")
if submit_info and prn and name and division:
if prn in submitted_prns:
st.error("You have already submitted the quiz.")
else:
st.session_state['student_info'] = {'prn': prn, 'name': name, 'division': division}
st.session_state['questions'] = get_random_questions(questions_df)
st.experimental_rerun()
# Page 2: Quiz
elif not st.session_state['completed']:
st.title("Quiz Time!")
question = st.session_state['questions'][st.session_state['current_question']]
st.write(f"Question {st.session_state['current_question'] + 1}:")
st.write(question['Question'])
choice = st.radio("Select your answer:", question['options'], index=None)
# Disable copy-paste with custom CSS
st.markdown(
"""
<style>
input, textarea { -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; }
</style>
""",
unsafe_allow_html=True
)
next_question = st.button("Next")
if next_question and choice is not None:
st.session_state['responses'].append({'question': question['Question'], 'answer': choice})
st.session_state['current_question'] += 1
if st.session_state['current_question'] >= len(st.session_state['questions']):
st.session_state['completed'] = True
st.experimental_rerun()
# Submission Page
if st.session_state['completed']:
st.title("Quiz Submitted!")
st.write("Thank you for participating.")
st.write("Your responses have been recorded.")
# Record the PRN to prevent re-submission
submitted_prns.add(st.session_state['student_info']['prn'])
responses_sheet.append_row([st.session_state['student_info']['prn'],
st.session_state['student_info']['name'],
st.session_state['student_info']['division'],
str(st.session_state['responses'])])
# Display responses (optional - for testing)
st.write(st.session_state['student_info'])
st.write(st.session_state['responses'])