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