-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquiz_interface.py
More file actions
149 lines (121 loc) · 6.15 KB
/
quiz_interface.py
File metadata and controls
149 lines (121 loc) · 6.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
import os
from typing import List, Dict
from rich.console import Console
from rich.panel import Panel
from rich.prompt import Prompt, Confirm
from rich.table import Table
from rich.text import Text
from rich import box
class QuizInterface:
def __init__(self):
self.console = Console()
def show_welcome(self):
"""Show welcome message"""
welcome_text = Text()
welcome_text.append("Micro Learning - PDF Quiz Generator", style="bold white")
welcome_text.append("\n\n", style="white")
welcome_text.append("Upload your PDF and test your knowledge with True/False questions!", style="white")
panel = Panel(welcome_text, box=box.ROUNDED, border_style="blue")
self.console.print(panel)
def select_pdf(self) -> str:
"""Allow user to select a PDF file"""
self.console.print("\n[bold cyan]PDF Selection[/bold cyan]")
# Check if pdfs folder exists
if not os.path.exists("pdfs"):
os.makedirs("pdfs")
self.console.print("[yellow]Created 'pdfs' folder. Please add your PDF files there.[/yellow]")
return None
# List PDF files in the folder
pdf_files = [f for f in os.listdir("pdfs") if f.lower().endswith('.pdf')]
if not pdf_files:
self.console.print("[red]No PDF files found in the 'pdfs' folder.[/red]")
self.console.print("[yellow]Please add your PDF files to the 'pdfs' folder and try again.[/yellow]")
return None
# Show list of available PDFs
table = Table(title="Available PDF Files", box=box.ROUNDED)
table.add_column("Number", style="cyan", no_wrap=True)
table.add_column("Filename", style="white")
table.add_column("Size", style="green")
for i, pdf_file in enumerate(pdf_files, 1):
file_path = os.path.join("pdfs", pdf_file)
size = os.path.getsize(file_path)
size_str = f"{size / 1024:.1f} KB" if size < 1024*1024 else f"{size / (1024*1024):.1f} MB"
table.add_row(str(i), pdf_file, size_str)
self.console.print(table)
# Allow user to select
while True:
try:
choice = Prompt.ask(
f"\n[bold]Select a PDF file (1-{len(pdf_files)})[/bold]",
default="1"
)
choice_idx = int(choice) - 1
if 0 <= choice_idx < len(pdf_files):
selected_file = os.path.join("pdfs", pdf_files[choice_idx])
self.console.print(f"[green]Selected: {pdf_files[choice_idx]}[/green]")
return selected_file
else:
self.console.print("[red]Invalid selection. Please try again.[/red]")
except ValueError:
self.console.print("[red]Please enter a valid number.[/red]")
def show_quiz_start(self, num_questions: int):
"""Show quiz start"""
quiz_text = Text()
quiz_text.append("Quiz Starting!", style="bold white")
quiz_text.append(f"\n\nYou will be asked {num_questions} True/False questions.", style="white")
quiz_text.append("\nAnswer with 'T' for True or 'F' for False.", style="white")
quiz_text.append("\nYou'll get explanations for wrong answers.", style="white")
panel = Panel(quiz_text, box=box.ROUNDED, border_style="green")
self.console.print(panel)
if not Confirm.ask("\n[bold]Ready to start?[/bold]"):
return False
return True
def ask_question(self, question_data: Dict, question_num: int, total_questions: int) -> bool:
"""Ask a single question and return user's answer"""
question = question_data['question']
# Create question panel
question_text = Text()
question_text.append(f"Question {question_num}/{total_questions}\n\n", style="bold cyan")
question_text.append(question, style="white")
question_text.append("\n\n", style="white")
question_text.append("T = True | F = False", style="yellow")
panel = Panel(question_text, box=box.ROUNDED, border_style="cyan")
self.console.print(panel)
# Handle answer
while True:
answer = Prompt.ask("\n[bold]Your answer[/bold]", choices=["T", "F", "t", "f"])
user_answer = answer.upper() == "T"
correct_answer = question_data['answer']
# Show result
if user_answer == correct_answer:
self.console.print("[green]Correct![/green]")
self.console.print(f"[yellow]Explanation:[/yellow] {question_data['explanation']}")
else:
self.console.print("[red]Wrong![/red]")
self.console.print(f"[yellow]Explanation:[/yellow] {question_data['explanation']}")
return user_answer == correct_answer
def show_results(self, correct_answers: int, total_questions: int):
"""Show final quiz results"""
percentage = (correct_answers / total_questions) * 100
# Determine message based on score
if percentage >= 90:
message = "Excellent! You really know this material!"
color = "green"
elif percentage >= 70:
message = "Good job! You have a solid understanding."
color = "yellow"
elif percentage >= 50:
message = "Not bad! Keep studying to improve."
color = "orange"
else:
message = "Keep practicing! Review the material again."
color = "red"
results_text = Text()
results_text.append("Quiz Complete!", style="bold white")
results_text.append(f"\n\nScore: {correct_answers}/{total_questions} ({percentage:.1f}%)", style="white")
results_text.append(f"\n\n{message}", style=color)
panel = Panel(results_text, box=box.ROUNDED, border_style=color)
self.console.print(panel)
def ask_continue(self) -> bool:
"""Ask if continue with another quiz"""
return Confirm.ask("\n[bold]Would you like to try another PDF?[/bold]")