#!/usr/bin/env python3
"""
CCC Plus Quiz App - Completely Rewritten for Better UX
A modern, intuitive quiz application with improved interface and functionality
"""
import argparse
import logging
import os
import tempfile
import json
from datetime import datetime
from pathlib import Path
from typing import Optional, Tuple, List, Dict, Any
import gradio as gr
import pandas as pd
from reportlab.lib import colors
from reportlab.lib.pagesizes import A4
from reportlab.lib.units import mm
from reportlab.pdfgen import canvas
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.enums import TA_CENTER, TA_LEFT
# Configure logging
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s"
)
logger = logging.getLogger(__name__)
# Configuration
DEFAULT_CSV_PATH = "quiz.csv"
REQUIRED_COLUMNS = {"question", "option1", "option2", "option3", "option4", "answer"}
class QuizApp:
"""Main Quiz Application Class"""
def __init__(self):
self.reset_state()
def reset_state(self):
"""Reset all quiz state variables"""
self.quiz_data = []
self.current_index = 0
self.score = 0
self.user_answers = []
self.quiz_started = False
self.quiz_completed = False
self.start_time = None
self.end_time = None
self.user_name = ""
def load_csv(self, file_path: str) -> Tuple[bool, str]:
"""Load and validate CSV file"""
try:
if not file_path or not os.path.exists(file_path):
return False, "❌ File not found. Please check the file path."
# Try different encodings
df = None
for encoding in ['utf-8', 'latin1', 'cp1252', 'iso-8859-1']:
try:
df = pd.read_csv(file_path, encoding=encoding)
break
except UnicodeDecodeError:
continue
if df is None:
return False, "❌ Could not read the CSV file. Please check the file encoding."
# Normalize column names
df.columns = df.columns.str.strip().str.lower()
# Check required columns
missing_cols = REQUIRED_COLUMNS - set(df.columns)
if missing_cols:
return False, f"❌ Missing required columns: {', '.join(missing_cols)}"
# Process questions
self.quiz_data = []
for idx, row in df.iterrows():
try:
question = str(row['question']).strip()
if not question or question.lower() in ['nan', 'none', '']:
continue
options = [
str(row['option1']).strip(),
str(row['option2']).strip(),
str(row['option3']).strip(),
str(row['option4']).strip()
]
answer = str(row['answer']).strip()
# Validate answer exists in options
if answer not in options:
logger.warning(f"Question {idx+1}: Answer '{answer}' not found in options")
continue
self.quiz_data.append({
'question': question,
'options': options,
'answer': answer
})
except Exception as e:
logger.warning(f"Error processing row {idx+1}: {e}")
continue
if not self.quiz_data:
return False, "❌ No valid questions found in the CSV file."
return True, f"✅ Successfully loaded {len(self.quiz_data)} questions!"
except Exception as e:
logger.exception("Error loading CSV")
return False, f"❌ Error loading CSV: {str(e)}"
def start_quiz(self, name: str) -> Tuple[bool, str]:
"""Start the quiz"""
if not self.quiz_data:
return False, "❌ No quiz loaded. Please load a CSV file first."
self.user_name = name.strip() if name else "CCC PLUS QUIZ REPORT"
self.current_index = 0
self.score = 0
self.user_answers = []
self.quiz_started = True
self.quiz_completed = False
self.start_time = datetime.now()
return True, "🚀 Quiz started! Answer each question and click Next to proceed."
def get_current_question(self) -> Dict[str, Any]:
"""Get current question data"""
if not self.quiz_started or not self.quiz_data or self.current_index >= len(self.quiz_data):
return {}
question_data = self.quiz_data[self.current_index]
return {
'question_num': self.current_index + 1,
'total_questions': len(self.quiz_data),
'question': question_data['question'],
'options': question_data['options'],
'progress': ((self.current_index) / len(self.quiz_data)) * 100
}
def submit_answer(self, selected_answer: str) -> Tuple[bool, str, bool]:
"""Submit answer and move to next question"""
if not self.quiz_started or not self.quiz_data:
return False, "❌ Quiz not started.", False
if self.current_index >= len(self.quiz_data):
return False, "❌ Quiz already completed.", True
current_q = self.quiz_data[self.current_index]
is_correct = selected_answer == current_q['answer']
# Store the answer
self.user_answers.append({
'question': current_q['question'],
'selected': selected_answer,
'correct_answer': current_q['answer'],
'is_correct': is_correct
})
if is_correct:
self.score += 1
# Move to next question
self.current_index += 1
# Check if quiz is completed
if self.current_index >= len(self.quiz_data):
self.quiz_completed = True
self.end_time = datetime.now()
duration = self.end_time - self.start_time
duration_str = f"{duration.seconds // 60}m {duration.seconds % 60}s"
percentage = (self.score / len(self.quiz_data)) * 100
return True, f"""🎉 **Quiz Completed!**
**Final Score:** {self.score} out of {len(self.quiz_data)} ({percentage:.1f}%)
**Time Taken:** {duration_str}
**Performance:** {self.get_performance_level(percentage)}
Click "Generate Report" to download your detailed results!""", True
# Quiz continues
feedback = f"✅ Correct!" if is_correct else f"❌ Incorrect. The correct answer was: **{current_q['answer']}**"
return True, feedback, False
def get_performance_level(self, percentage: float) -> str:
"""Get performance level based on percentage"""
if percentage >= 90:
return "🏆 Excellent"
elif percentage >= 80:
return "👍 Good"
elif percentage >= 60:
return "👌 Average"
else:
return "📚 Needs Improvement"
def generate_pdf_report(self, photo_path: Optional[str] = None) -> Optional[str]:
"""Generate PDF report with candidate photo"""
if not self.user_answers:
return None
try:
# Create temporary file
temp_file = tempfile.NamedTemporaryFile(
prefix="CCC_Quiz_Report_",
suffix=".pdf",
delete=False
)
temp_file.close()
# Create PDF
doc = SimpleDocTemplate(
temp_file.name,
pagesize=A4,
leftMargin=25*mm,
rightMargin=25*mm,
topMargin=25*mm,
bottomMargin=25*mm
)
styles = getSampleStyleSheet()
story = []
# Custom styles
title_style = ParagraphStyle(
'CustomTitle',
parent=styles['Heading1'],
fontSize=18,
alignment=TA_CENTER,
textColor=colors.HexColor('#003366'),
spaceAfter=12
)
subtitle_style = ParagraphStyle(
'CustomSubtitle',
parent=styles['Normal'],
fontSize=12,
alignment=TA_CENTER,
textColor=colors.HexColor('#666666'),
spaceAfter=20
)
# Header with candidate photo
try:
from reportlab.platypus import Image
header_data = []
if photo_path and os.path.exists(photo_path):
try:
# Create header table with photo
photo_img = Image(photo_path, width=60, height=60)
header_info = [
"CCC Plus - Computer Concepts Plus",
"Quiz Assessment Report",
f"Candidate: {self.user_name}",
datetime.now().strftime('%d %B %Y at %H:%M:%S')
]
header_table = Table([
[photo_img, Paragraph("
".join(header_info), styles['Normal'])]
], colWidths=[80, 400])
header_table.setStyle(TableStyle([
('ALIGN', (0, 0), (0, 0), 'CENTER'),
('VALIGN', (0, 0), (-1, -1), 'TOP'),
('FONTSIZE', (1, 0), (1, 0), 12),
('BOTTOMPADDING', (0, 0), (-1, -1), 12),
]))
story.append(header_table)
except Exception as e:
logger.warning(f"Could not add photo to PDF: {e}")
# Fallback to text header
story.append(Paragraph("CCC Plus - Computer Concepts Plus", title_style))
story.append(Paragraph("Quiz Assessment Report", subtitle_style))
else:
# Text-only header
story.append(Paragraph("CCC Plus - Computer Concepts Plus", title_style))
story.append(Paragraph("Quiz Assessment Report", subtitle_style))
except ImportError:
# If reportlab Image is not available, use text header
story.append(Paragraph("CCC Plus - Computer Concepts Plus", title_style))
story.append(Paragraph("Quiz Assessment Report", subtitle_style))
story.append(Spacer(1, 20))
# Candidate info
info_data = [
['Candidate:', self.user_name],
['Date:', datetime.now().strftime('%d %B %Y at %H:%M:%S')],
['Questions Attempted:', str(len(self.user_answers))],
['Correct Answers:', str(self.score)],
['Score Percentage:', f"{(self.score/len(self.user_answers)*100):.1f}%"],
['Performance Level:', self.get_performance_level((self.score/len(self.user_answers)*100))]
]
info_table = Table(info_data, colWidths=[120, 200])
info_table.setStyle(TableStyle([
('ALIGN', (0, 0), (-1, -1), 'LEFT'),
('FONTNAME', (0, 0), (0, -1), 'Helvetica-Bold'),
('FONTSIZE', (0, 0), (-1, -1), 10),
('BOTTOMPADDING', (0, 0), (-1, -1), 6),
]))
story.append(info_table)
story.append(Spacer(1, 20))
# Results table with proper text wrapping
story.append(Paragraph("Detailed Results", styles['Heading2']))
story.append(Spacer(1, 12))
table_data = [['#', 'Question', 'Your Answer', 'Correct Answer', 'Result']]
# Custom paragraph style for table cells
cell_style = ParagraphStyle(
'CellStyle',
parent=styles['Normal'],
fontSize=8,
leading=10,
wordWrap='LTR',
leftIndent=2,
rightIndent=2
)
for i, answer in enumerate(self.user_answers, 1):
result_icon = '✓' if answer['is_correct'] else '✗'
# Wrap text in Paragraph objects for proper text wrapping
question_para = Paragraph(answer['question'], cell_style)
selected_para = Paragraph(answer['selected'], cell_style)
correct_para = Paragraph(answer['correct_answer'], cell_style)
table_data.append([
str(i),
question_para,
selected_para,
correct_para,
result_icon
])
# Adjust column widths for better fit
results_table = Table(table_data, colWidths=[15*mm, 90*mm, 35*mm, 35*mm, 15*mm])
results_table.setStyle(TableStyle([
('BACKGROUND', (0, 0), (-1, 0), colors.HexColor('#003366')),
('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke),
('ALIGN', (0, 0), (-1, -1), 'LEFT'),
('ALIGN', (0, 0), (0, -1), 'CENTER'), # Center align the # column
('ALIGN', (-1, 0), (-1, -1), 'CENTER'), # Center align the Result column
('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
('FONTSIZE', (0, 0), (-1, 0), 9),
('ROWBACKGROUNDS', (0, 1), (-1, -1), [colors.white, colors.HexColor('#f8f9fa')]),
('GRID', (0, 0), (-1, -1), 0.5, colors.HexColor('#dee2e6')),
('VALIGN', (0, 0), (-1, -1), 'TOP'),
('BOTTOMPADDING', (0, 0), (-1, -1), 6),
('TOPPADDING', (0, 0), (-1, -1), 6),
('LEFTPADDING', (0, 0), (-1, -1), 4),
('RIGHTPADDING', (0, 0), (-1, -1), 4),
]))
story.append(results_table)
story.append(Spacer(1, 30))
# Footer
footer_style = ParagraphStyle(
'Footer',
parent=styles['Normal'],
fontSize=8,
alignment=TA_CENTER,
textColor=colors.HexColor('#666666')
)
story.append(Paragraph(
f"NIELIT Chandigarh — © {datetime.now().year} — Generated automatically",
footer_style
))
doc.build(story)
logger.info(f"Generated PDF report: {temp_file.name}")
return temp_file.name
except Exception as e:
logger.exception("Error generating PDF report")
return None
# Global quiz app instance
quiz_app = QuizApp()
def handle_load_quiz(csv_path: str, uploaded_file) -> Tuple[str, Any, Any, Any]:
"""Handle quiz loading"""
# Extract file path
file_path = None
if uploaded_file is not None:
file_path = uploaded_file.name if hasattr(uploaded_file, 'name') else str(uploaded_file)
elif csv_path and csv_path.strip():
file_path = csv_path.strip()
if not file_path:
return "❌ Please provide a CSV file path or upload a file.", gr.update(), gr.update(), gr.update(visible=False)
# Reset quiz state
quiz_app.reset_state()
# Load quiz
success, message = quiz_app.load_csv(file_path)
if success:
return message, gr.update(visible=True), gr.update(visible=True), gr.update(visible=False)
else:
return message, gr.update(visible=False), gr.update(visible=False), gr.update(visible=False)
def handle_start_quiz(name: str) -> Tuple[str, Any, Any, Any, Any, str, Any]:
"""Handle quiz start"""
success, message = quiz_app.start_quiz(name)
if not success:
return message, gr.update(), gr.update(), gr.update(), gr.update(), "", gr.update()
# Get first question
q_data = quiz_app.get_current_question()
if not q_data:
return "❌ No questions available.", gr.update(), gr.update(), gr.update(), gr.update(), "", gr.update()
question_html = f"""
Computer Concepts Plus - Interactive Quiz Platform
NIELIT Chandigarh • National Institute of Electronics & Information Technology
NIELIT Chandigarh • © {datetime.now().year} • Enhanced Quiz Application
Built with ❤️ using Gradio • Version 2.0