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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <think>
2
+ We are building a comprehensive Gradio app. Due to the complexity, we'll structure the code in a modular way within a single script (app.py) and use SQLite for the database.
3
+
4
+ Steps:
5
+ 1. Set up the database (SQLite) for users, progress, questions, etc.
6
+ 2. Implement user authentication (signup, login) with password hashing.
7
+ 3. Design the main dashboard with gamification elements (streaks, XP, badges, leaderboard).
8
+ 4. Create the course/lesson structure with interactive quizzes (using Gradio components).
9
+ 5. Implement adaptive difficulty and gamification logic (hearts, XP, streaks).
10
+ 6. Add additional features: practice mode, resources, community chat, enrollment form.
11
+ 7. Create an admin/teacher panel for uploading questions and viewing progress.
12
+ 8. Ensure the UI is responsive and visually appealing with themes and emojis.
13
+
14
+ Note: We'll hardcode some questions and generate others using sympy for math.
15
+
16
+ Due to the extensive requirements, we'll focus on core functionality and then build upon it.
17
+
18
+ Important: We must use Gradio Blocks for complex layouts.
19
+
20
+ We'll structure the app with multiple tabs and conditional rendering based on user role and login state.
21
+
22
+ Let's break down:
23
+
24
+ 1. Database Setup:
25
+ - Create tables: users, progress, questions, badges, streaks, etc.
26
+
27
+ 2. User Authentication:
28
+ - Signup: username, password, role, grade, board/stream (if student)
29
+ - Login: username and password, then set session.
30
+
31
+ 3. Main Dashboard:
32
+ - After login, show: streak, XP, badges, daily goals, recommended lessons, leaderboard.
33
+
34
+ 4. Lessons:
35
+ - Each lesson: short explanation and 5-10 questions (multiple choice, fill-in, drag-and-drop).
36
+ - Adaptive: if wrong, next question easier; if correct, harder.
37
+
38
+ 5. Gamification:
39
+ - XP: earn for correct answers, lose hearts for mistakes (3 hearts per lesson).
40
+ - Badges: awarded on milestones.
41
+ - Streaks: maintained by daily login and completing at least one lesson.
42
+
43
+ 6. Additional Features:
44
+ - Practice Mode: random quizzes from past lessons.
45
+ - Resources: static notes and past papers (PDFs).
46
+ - Community: a simple chat interface (using Gradio ChatInterface) but note: we need persistence? We can use a global list for now, but for production a database is better. However, due to HF Spaces limitations, we'll use a list and it will reset on restart.
47
+ - Enrollment: a form for joining classes.
48
+
49
+ 7. Admin/Teacher Panel:
50
+ - Upload questions (via form) and view student progress (table).
51
+
52
+ 8. UI/UX:
53
+ - Use Gradio themes and custom CSS for mobile responsiveness.
54
+ - Add emojis and animations (CSS/JS) for correct answers (confetti).
55
+
56
+ 9. Security:
57
+ - Hash passwords with hashlib (sha256).
58
+ - Use parameterized queries to prevent SQL injection.
59
+
60
+ 10. Performance:
61
+ - Cache heavy operations (like generating math problems) and limit database queries.
62
+
63
+ Given the complexity, we'll start with the database and authentication, then build the dashboard and lessons.
64
+
65
+ We'll use the following structure:
66
+
67
+ - Define database functions (create_tables, add_user, authenticate_user, etc.)
68
+ - Define classes for User, Lesson, Question (for in-memory representation)
69
+ - Gradio app:
70
+ - State: to keep track of current user, progress, etc. (using gr.State)
71
+ - Tabs: for Dashboard, Lessons, Practice, Resources, Community, Admin, Enrollment.
72
+
73
+ However, note that Gradio doesn't have built-in tab navigation for multi-page, so we'll use gr.Tabs.
74
+
75
+ Due to the extensive nature, we'll focus on the core and then add features incrementally.
76
+
77
+ Important: We cannot implement everything in one go, so we'll create a minimal viable product and then extend.
78
+
79
+ Let's outline the code:
80
+
81
+ 1. Imports
82
+ 2. Database setup and helper functions
83
+ 3. Define hardcoded questions and generate some (for math)
84
+ 4. Gradio app layout and logic
85
+
86
+ We'll start with the authentication and dashboard.
87
+
88
+ Note: We are constrained by Hugging Face Spaces, so we must avoid long-running processes and heavy memory usage.
89
+
90
+ We'll use SQLite and store the database in the current directory (it will be ephemeral on HF Spaces unless we use the persistent storage, but note that free tier has 5GB and it's persistent across restarts? Actually, the space storage is persistent. So we can use a file.)
91
+
92
+ Steps for the app:
93
+
94
+ - On startup: create the database and tables if they don't exist.
95
+
96
+ We'll create:
97
+
98
+ users: id (integer primary key), username (text unique), password (text), role (text), grade (text, optional), board (text, optional), created_at (timestamp default current_timestamp)
99
+ progress: id, user_id (foreign key), lesson_id, score (integer), xp_earned (integer), completed_at (timestamp)
100
+ questions: id, subject, grade, board, type (mcq, fill, drag), difficulty (1-5), question_text, options (json for mcq), correct_answer, explanation
101
+ badges: id, user_id, badge_name, earned_at
102
+ streaks: user_id, current_streak, last_activity_date
103
+
104
+ We'll also have a table for lessons: id, subject, grade, board, title, description, estimated_time, difficulty
105
+
106
+ But for simplicity, we might hardcode lessons and questions in the code (or load from a JSON) for now.
107
+
108
+ We'll create a function to populate initial questions.
109
+
110
+ Due to the complexity, we'll focus on a few subjects and grades.
111
+
112
+ Implementation:
113
+
114
+ We'll create a Gradio Blocks app.
115
+
116
+ The app will have:
117
+
118
+ - A login/signup screen at the start.
119
+ - After login, the main app with tabs.
120
+
121
+ We'll use gr.State to store the current user and their state (like current lesson, hearts, etc.)
122
+
123
+ We'll break the UI into components:
124
+
125
+ - auth_ui: for login and signup
126
+ - dashboard_ui: for the main dashboard
127
+ - lessons_ui: for selecting and taking lessons
128
+ - practice_ui: for practice mode
129
+ - resources_ui: for resources
130
+ - community_ui: for community chat
131
+ - admin_ui: for admin panel
132
+ - enrollment_ui: for enrollment form
133
+
134
+ We'll use conditional visibility: if not logged in, show auth_ui; else show the main app.
135
+
136
+ We'll use tabs for the main app.
137
+
138
+ Let's code step by step.
139
+
140
+ Note: This will be a long script. We'll try to keep it organized.
141
+
142
+ We'll also add comments for clarity.
143
+
144
+ IMPORTANT: We are required to output only the code in a code block.
145
+
146
+ Let's begin.
147
+ </think>
148
+ ```python
149
+ import gradio as gr
150
+ import sqlite3
151
+ import hashlib
152
+ import random
153
+ import datetime
154
+ import json
155
+ import sympy
156
+ from sympy.abc import x
157
+ import time
158
+ import os
159
+ from typing import List, Dict, Tuple
160
+
161
+ # Database setup
162
+ def init_db():
163
+ conn = sqlite3.connect('classes_education.db')
164
+ c = conn.cursor()
165
+
166
+ # Create tables
167
+ c.execute('''CREATE TABLE IF NOT EXISTS users (
168
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
169
+ username TEXT UNIQUE NOT NULL,
170
+ password TEXT NOT NULL,
171
+ role TEXT NOT NULL CHECK(role IN ('student', 'parent', 'teacher')),
172
+ grade TEXT,
173
+ board TEXT,
174
+ stream TEXT,
175
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
176
+ )''')
177
+
178
+ c.execute('''CREATE TABLE IF NOT EXISTS progress (
179
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
180
+ user_id INTEGER NOT NULL,
181
+ subject TEXT NOT NULL,
182
+ level INTEGER DEFAULT 1,
183
+ xp INTEGER DEFAULT 0,
184
+ streak INTEGER DEFAULT 0,
185
+ last_active DATE,
186
+ badges TEXT DEFAULT '[]',
187
+ FOREIGN KEY(user_id) REFERENCES users(id)
188
+ )''')
189
+
190
+ c.execute('''CREATE TABLE IF NOT EXISTS questions (
191
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
192
+ subject TEXT NOT NULL,
193
+ grade TEXT NOT NULL,
194
+ board TEXT NOT NULL,
195
+ type TEXT NOT NULL,
196
+ difficulty INTEGER DEFAULT 1,
197
+ question TEXT NOT NULL,
198
+ options TEXT, # JSON for MCQ
199
+ correct_answer TEXT NOT NULL,
200
+ explanation TEXT
201
+ )''')
202
+
203
+ # Insert sample questions if empty
204
+ c.execute("SELECT COUNT(*) FROM questions")
205
+ if c.fetchone()[0] == 0:
206
+ # Sample questions for Mathematics
207
+ questions = [
208
+ ("Mathematics", "9", "Sindh Board", "mcq", 1,
209
+ "What is the value of Ο€ (pi)?",
210
+ '["3.14", "2.71", "1.618", "4.669"]',
211
+ "3.14", "Ο€ is approximately 3.14"),
212
+ ("Mathematics", "9", "Sindh Board", "fill", 2,
213
+ "Solve for x: 2x + 5 = 15",
214
+ None,
215
+ "5", "Subtract 5 from both sides: 2x = 10, then divide by 2"),
216
+ ("Physics", "10", "Aga Khan", "mcq", 1,
217
+ "What is the unit of force?",
218
+ '["Newton", "Joule", "Watt", "Pascal"]',
219
+ "Newton", "Force is measured in Newtons"),
220
+ ("Chemistry", "11", "Pre-Engineering", "mcq", 2,
221
+ "What is the atomic number of Oxygen?",
222
+ '["8", "16", "32", "64"]',
223
+ "8", "Oxygen has 8 protons")
224
+ ]
225
+ c.executemany('''INSERT INTO questions
226
+ (subject, grade, board, type, difficulty, question, options, correct_answer, explanation)
227
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)''', questions)
228
+
229
+ conn.commit()
230
+ conn.close()
231
+
232
+ # Initialize database
233
+ init_db()
234
+
235
+ # Password hashing
236
+ def hash_password(password: str) -> str:
237
+ return hashlib.sha256(password.encode()).hexdigest()
238
+
239
+ # User authentication
240
+ def authenticate_user(username: str, password: str) -> Tuple[bool, str, str]:
241
+ conn = sqlite3.connect('classes_education.db')
242
+ c = conn.cursor()
243
+ c.execute("SELECT id, password, role FROM users WHERE username=?", (username,))
244
+ user = c.fetchone()
245
+ conn.close()
246
+
247
+ if user and user[1] == hash_password(password):
248
+ return True, user[0], user[2] # user_id, role
249
+ return False, "", ""
250
+
251
+ # User registration
252
+ def register_user(username: str, password: str, role: str, grade: str = None, board: str = None, stream: str = None) -> bool:
253
+ try:
254
+ conn = sqlite3.connect('classes_education.db')
255
+ c = conn.cursor()
256
+ c.execute("INSERT INTO users (username, password, role, grade, board, stream) VALUES (?, ?, ?, ?, ?, ?)",
257
+ (username, hash_password(password), role, grade, board, stream))
258
+ conn.commit()
259
+
260
+ # Initialize progress
261
+ if role == "student":
262
+ subjects = ["Mathematics", "Physics", "Chemistry", "Biology", "General Science"]
263
+ for subject in subjects:
264
+ c.execute("INSERT INTO progress (user_id, subject) VALUES (?, ?)", (c.lastrowid, subject))
265
+ conn.commit()
266
+ conn.close()
267
+ return True
268
+ except sqlite3.IntegrityError:
269
+ return False
270
+
271
+ # Gamification functions
272
+ def update_streak(user_id: int) -> int:
273
+ conn = sqlite3.connect('classes_education.db')
274
+ c = conn.cursor()
275
+ today = datetime.date.today().isoformat()
276
+
277
+ c.execute("SELECT streak, last_active FROM progress WHERE user_id=?", (user_id,))
278
+ progress = c.fetchone()
279
+
280
+ if progress:
281
+ streak = progress[0]
282
+ last_active = progress[1]
283
+
284
+ if last_active:
285
+ last_date = datetime.date.fromisoformat(last_active)
286
+ current_date = datetime.date.today()
287
+ if (current_date - last_date).days == 1:
288
+ streak += 1
289
+ elif (current_date - last_active).days > 1:
290
+ streak = 1
291
+ else:
292
+ streak = 1
293
+
294
+ c.execute("UPDATE progress SET streak=?, last_active=? WHERE user_id=?", (streak, today, user_id))
295
+ conn.commit()
296
+ conn.close()
297
+ return streak
298
+ return 0
299
+
300
+ def add_xp(user_id: int, subject: str, amount: int) -> int:
301
+ conn = sqlite3.connect('classes_education.db')
302
+ c = conn.cursor()
303
+ c.execute("UPDATE progress SET xp = xp + ? WHERE user_id=? AND subject=?", (amount, user_id, subject))
304
+ c.execute("SELECT xp FROM progress WHERE user_id=? AND subject=?", (user_id, subject))
305
+ new_xp = c.fetchone()[0]
306
+ conn.commit()
307
+ conn.close()
308
+ return new_xp
309
+
310
+ def get_leaderboard() -> List[Tuple[str, int]]:
311
+ conn = sqlite3.connect('classes_education.db')
312
+ c = conn.cursor()
313
+ c.execute("SELECT u.username, SUM(p.xp) as total_xp FROM progress p JOIN users u ON p.user_id = u.id GROUP BY u.id ORDER BY total_xp DESC LIMIT 10")
314
+ leaderboard = c.fetchall()
315
+ conn.close()
316
+ return leaderboard
317
+
318
+ # Question handling
319
+ def get_questions(subject: str, grade: str, board: str, difficulty: int = 1, count: int = 5) -> List[Dict]:
320
+ conn = sqlite3.connect('classes_education.db')
321
+ c = conn.cursor()
322
+ c.execute("SELECT * FROM questions WHERE subject=? AND grade=? AND board=? AND difficulty=? ORDER BY RANDOM() LIMIT ?",
323
+ (subject, grade, board, difficulty, count))
324
+ questions = []
325
+ for row in c.fetchall():
326
+ questions.append({
327
+ "id": row[0],
328
+ "subject": row[1],
329
+ "grade": row[2],
330
+ "board": row[3],
331
+ "type": row[4],
332
+ "difficulty": row[5],
333
+ "question": row[6],
334
+ "options": json.loads(row[7]) if row[7] else None,
335
+ "correct_answer": row[8],
336
+ "explanation": row[9]
337
+ })
338
+ conn.close()
339
+ return questions
340
+
341
+ def generate_math_question(grade: str, difficulty: int) -> Dict:
342
+ if grade in ["9", "10"]:
343
+ if difficulty == 1:
344
+ a, b = random.randint(1, 10), random.randint(1, 10)
345
+ question = f"What is {a} + {b}?"
346
+ answer = str(a + b)
347
+ elif difficulty == 2:
348
+ a, b = random.randint(5, 15), random.randint(1, 5)
349
+ question = f"Solve: {a}x - {b} = {a*2 - b}. Find x."
350
+ answer = "2"
351
+ else:
352
+ expr = sympy.expand((x + random.randint(1, 5))**2)
353
+ question = f"Expand: (x + {expr.args[1].args[0]})Β²"
354
+ answer = str(expr)
355
+ else:
356
+ question = "What is the derivative of xΒ²?"
357
+ answer = "2x"
358
+
359
+ return {
360
+ "type": "fill",
361
+ "question": question,
362
+ "correct_answer": answer,
363
+ "explanation": "Generated math problem"
364
+ }
365
+
366
+ # Gradio UI Components
367
+ def login_ui():
368
+ with gr.Row():
369
+ with gr.Column(scale=1):
370
+ username = gr.Textbox(label="Username", placeholder="Enter your username")
371
+ password = gr.Textbox(label="Password", placeholder="Enter your password", type="password")
372
+ login_btn = gr.Button("Login")
373
+ with gr.Column(scale=1):
374
+ role = gr.Radio(["student", "parent", "teacher"], label="Role")
375
+ grade = gr.Dropdown(["1-5", "6-8", "9", "10", "11", "12"], label="Grade (for students)")
376
+ board = gr.Dropdown(["Sindh Board", "Aga Khan Board", "O Levels"], label="Board (for students)")
377
+ stream = gr.Dropdown(["Pre-Medical", "Pre-Engineering", "Computer Science"], label="Stream (for Intermediate)", visible=False)
378
+ register_btn = gr.Button("Register")
379
+
380
+ return username, password, role, grade, board, stream, login_btn, register_btn
381
+
382
+ def dashboard_ui(user_id: int, role: str):
383
+ conn = sqlite3.connect('classes_education.db')
384
+ c = conn.cursor()
385
+ c.execute("SELECT streak, xp, subject FROM progress WHERE user_id=?", (user_id,))
386
+ progress_data = c.fetchall()
387
+ conn.close()
388
+
389
+ streak = max([p[0] for p in progress_data]) if progress_data else 0
390
+ total_xp = sum([p[1] for p in progress_data])
391
+
392
+ with gr.Row():
393
+ gr.Markdown(f"### πŸ”₯ Streak: {streak} days | ⭐ Total XP: {total_xp}")
394
+
395
+ with gr.Row():
396
+ with gr.Column(scale=3):
397
+ # Daily goals
398
+ gr.Markdown("### 🎯 Daily Goals")
399
+ gr.Markdown("- Complete 3 lessons\n- Maintain streak\n- Earn 100 XP")
400
+
401
+ # Recommended lessons
402
+ gr.Markdown("### πŸ“š Recommended Lessons")
403
+ gr.Markdown("1. Mathematics: Algebra Basics\n2. Physics: Newton's Laws\n3. Chemistry: Atomic Structure")
404
+
405
+ with gr.Column(scale=2):
406
+ # Leaderboard
407
+ gr.Markdown("### πŸ† Leaderboard")
408
+ leaderboard = get_leaderboard()
409
+ leaderboard_text = "\n".join([f"{i+1}. {user[0]} - {user[1]} XP" for i, user in enumerate(leaderboard)])
410
+ gr.Textbox(leaderboard_text, interactive=False, label="Top 10 Students")
411
+
412
+ # Badges
413
+ gr.Markdown("### πŸ… Badges Earned")
414
+ gr.Markdown("- Matric Master\n- Science Whiz")
415
+
416
+ if role == "teacher":
417
+ with gr.Row():
418
+ gr.Markdown("### πŸ‘¨β€πŸ« Teacher Panel")
419
+ with gr.Column():
420
+ subject = gr.Dropdown(["Mathematics", "Physics", "Chemistry", "Biology", "General Science"], label="Subject")
421
+ grade = gr.Dropdown(["1-5", "6-8", "9", "10", "11", "12"], label="Grade")
422
+ board = gr.Dropdown(["Sindh Board", "Aga Khan Board", "O Levels"], label="Board")
423
+ question = gr.Textbox(label="Question")
424
+ options = gr.Textbox(label="Options (comma separated for MCQ)")
425
+ correct_answer = gr.Textbox(label="Correct Answer")
426
+ explanation = gr.Textbox(label="Explanation")
427
+ add_question_btn = gr.Button("Add Question")
428
+
429
+ return locals()
430
+
431
+ def lesson_ui(user_id: int, subject: str, grade: str, board: str):
432
+ hearts = 3
433
+ xp_earned = 0
434
+ current_question = 0
435
+ questions = get_questions(subject, grade, board, difficulty=1, count=5)
436
+
437
+ if not questions:
438
+ questions = [generate_math_question(grade, 1) for _ in range(5)]
439
+
440
+ def display_question(index):
441
+ q = questions[index]
442
+ if q["type"] == "mcq":
443
+ return gr.Radio(choices=q["options"], label=q["question"]), q["correct_answer"]
444
+ else: # fill-in
445
+ return gr.Textbox(label=q["question"]), q["correct_answer"]
446
+
447
+ question_display, correct_answer = display_question(current_question)
448
+
449
+ with gr.Row():
450
+ gr.Markdown(f"### πŸ“– {subject} Lesson | Grade {grade} | {board}")
451
+
452
+ with gr.Row():
453
+ hearts_display = gr.Markdown(f"❀️❀️❀️ (Lives: {hearts})")
454
+ xp_display = gr.Markdown(f"⭐ XP: {xp_earned}")
455
+
456
+ with gr.Row():
457
+ question_ui = question_display
458
+
459
+ with gr.Row():
460
+ submit_btn = gr.Button("Submit Answer")
461
+ next_btn = gr.Button("Next Question", visible=False)
462
+
463
+ feedback = gr.Markdown("")
464
+
465
+ def check_answer(answer):
466
+ nonlocal hearts, xp_earned, current_question
467
+ if answer == correct_answer:
468
+ feedback = "βœ… Correct! " + questions[current_question]["explanation"]
469
+ xp_earned += 10
470
+ add_xp(user_id, subject, 10)
471
+ else:
472
+ hearts -= 1
473
+ feedback = f"❌ Incorrect. Correct answer: {correct_answer}. Explanation: {questions[current_question]['explanation']}"
474
+
475
+ if hearts <= 0 or current_question >= len(questions) - 1:
476
+ submit_btn.visible = False
477
+ next_btn.visible = False
478
+ feedback += "\n\nπŸŽ‰ Lesson Completed!"
479
+ else:
480
+ next_btn.visible = True
481
+
482
+ return (
483
+ feedback,
484
+ hearts_display.update(value=f"❀️ {'❀️' * (hearts-1)}" + "β™‘" * (3-hearts) + f" (Lives: {hearts})"),
485
+ xp_display.update(value=f"⭐ XP: {xp_earned}"),
486
+ submit_btn.update(visible=hearts>0 and current_question<len(questions)-1),