mikaelJ46 commited on
Commit
862ec4a
Β·
verified Β·
1 Parent(s): 37998af

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +511 -132
app.py CHANGED
@@ -170,57 +170,76 @@ def analyze_math_work(image, grade_level, topic):
170
  if not topic:
171
  return "⚠️ Please select a topic first!"
172
 
173
- system_prompt = f"""You are a patient and encouraging mathematics teacher for {grade_level} students.
174
- Your role is to:
175
- 1. Carefully examine the student's written work in the image
176
- 2. Identify what mathematical problem they are solving
177
- 3. Check their working step-by-step
178
- 4. Point out any errors with clear, kind explanations
179
- 5. Provide the correct solution with detailed steps
180
- 6. Encourage the student and give tips for improvement
181
 
182
- Current topic focus: {topic}
183
- Student level: {grade_level}
184
 
185
- Provide your feedback in this format:
 
186
 
187
- **πŸ“ Problem Identified:**
188
- [State what problem the student is trying to solve]
189
 
190
- **πŸ‘€ Student's Approach:**
191
- [Describe what the student did - their steps]
192
 
193
- **βœ… Evaluation:**
194
- [Is it correct? If not, where exactly did they go wrong?]
 
 
 
195
 
196
- **πŸ’‘ Detailed Feedback:**
197
- [Step-by-step explanation of mistakes and corrections]
 
 
 
198
 
199
- **πŸ“š Correct Solution:**
200
- [Show the complete correct solution with all steps clearly explained]
 
 
 
201
 
202
- **🌟 Encouragement & Tips:**
203
- [Positive feedback and 2-3 helpful tips for improvement]
 
 
204
 
205
- Be specific, kind, and educational. Focus on helping them understand their mistakes."""
206
 
207
  try:
208
- # Use Gemini with image
209
  response, source = ask_ai(system_prompt, temperature=0.5, image=image)
210
 
211
  if source == "error":
212
  return response
213
 
214
- # Add source indicator if not primary
215
- if source == "cohere":
216
- response = f"πŸ”΅ *[Analyzed by Cohere - text fallback]*\n\n{response}"
217
- elif source == "hf":
218
- response = f"🟒 *[Analyzed by HF - text fallback]*\n\n{response}"
 
 
 
 
 
 
 
219
 
220
- return response
221
 
222
  except Exception as e:
223
- return f"❌ Error analyzing work: {str(e)}\n\nPlease ensure:\n1. Your image is clear and readable\n2. The mathematical work is visible\n3. Try again or check your internet connection"
 
 
 
 
 
 
 
 
224
 
225
  # ---------- 5. Generate Practice Problems ----------
226
  def generate_practice_problem(grade_level, topic):
@@ -229,34 +248,51 @@ def generate_practice_problem(grade_level, topic):
229
  if not topic:
230
  return "⚠️ Please select a topic first!"
231
 
232
- prompt = f"""Generate ONE practice problem for {grade_level} students on the topic: "{topic}"
233
 
234
  Requirements:
235
- - Appropriate difficulty for {grade_level}
236
- - Clear problem statement
237
- - Include any necessary diagrams/context in text
238
- - Should take 5-10 minutes to solve
239
- - Show the correct solution process
240
 
241
- Format your response as:
242
 
243
- **πŸ“ Practice Problem:**
244
- [Clear problem statement]
245
 
246
- **πŸ’­ Hints:**
247
- [2-3 helpful hints to get started]
 
 
 
 
 
 
 
 
 
248
 
249
- **βœ… Solution (Hidden - for teacher reference):**
250
- [Step-by-step solution]
251
 
252
- Make it engaging and educational!"""
253
 
254
  response, source = ask_ai(prompt, temperature=0.6)
255
 
256
- if source in ["cohere", "hf"]:
257
- response = f"*[Generated by {source.upper()}]*\n\n{response}"
 
 
 
 
 
 
 
 
 
258
 
259
- return response
260
 
261
  # ---------- 6. AI Tutor Chat ----------
262
  def ai_tutor_chat(message, history, grade_level, topic):
@@ -267,37 +303,46 @@ def ai_tutor_chat(message, history, grade_level, topic):
267
  history.append((message, "⚠️ Please select a topic first to get focused help!"))
268
  return history
269
 
270
- system = f"""You are an expert mathematics tutor for {grade_level} students.
271
- Current topic: {topic}
272
 
273
- Your role:
274
- - Provide clear, step-by-step explanations
 
 
 
 
 
 
 
 
 
 
 
275
  - Use age-appropriate language for {grade_level}
276
- - Give practical examples
277
- - Be encouraging and patient
278
- - Break down complex concepts
279
- - Check for understanding
280
 
281
- Answer the student's question about {topic} in a way that helps them truly understand."""
282
 
283
  # Build conversation context
284
  conversation = ""
285
- for user_msg, bot_msg in history[-3:]:
286
  if user_msg:
287
  conversation += f"Student: {user_msg}\n"
288
  if bot_msg:
289
- clean_msg = bot_msg.replace("πŸ”΅ ", "").replace("🟒 ", "")
290
  conversation += f"Tutor: {clean_msg}\n"
291
 
292
- full_prompt = f"{system}\n\n{conversation}Student: {message}\nTutor:"
293
 
294
  bot_response, source = ask_ai(full_prompt, temperature=0.7)
295
 
296
- # Add indicators for non-primary models
297
  if source == "cohere":
298
  bot_response = f"πŸ”΅ {bot_response}"
299
  elif source == "hf":
300
  bot_response = f"🟒 {bot_response}"
 
 
301
 
302
  history.append((message, bot_response))
303
  return history
@@ -310,55 +355,209 @@ def update_topics(grade_level):
310
  topics = syllabus_topics["math"].get(grade_level, [])
311
  return gr.Dropdown(choices=topics, value=None)
312
 
313
- # ---------- 8. Gradio UI ----------
314
- with gr.Blocks(theme=gr.themes.Soft(), title="Math Learning Assistant", css="""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
315
  .gradio-container {
316
- font-family: 'Inter', sans-serif;
317
  max-width: 1400px;
318
  margin: auto;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
319
  }
320
- .tab-nav button {font-weight: 600;}
321
  .feedback-box {
322
- background: #f8f9fa;
323
- border-left: 4px solid #4CAF50;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
324
  padding: 15px;
 
 
 
 
 
 
 
 
 
 
 
325
  border-radius: 8px;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
326
  }
327
  """) as app:
328
 
329
  gr.Markdown("""
330
- # ✍️ Math Learning Assistant
331
- ### AI-Powered Handwriting Recognition & Tutoring System
332
- **Write your math solutions naturally - Get instant AI feedback!**
333
 
334
- _πŸ€– Powered by Gemini AI (Vision) with intelligent fallback system (Cohere β†’ Hugging Face)_
335
  """)
336
 
337
- # Grade Level and Topic Selection (Global)
338
- with gr.Row():
339
- grade_level = gr.Dropdown(
340
- choices=list(syllabus_topics["math"].keys()),
341
- label="πŸ“š Select Your Grade Level",
342
- value="Primary 3-4",
343
- info="Choose your current grade level"
344
- )
345
-
346
- topic_select = gr.Dropdown(
347
- choices=syllabus_topics["math"]["Primary 3-4"],
348
- label="πŸ“– Select Topic",
349
- info="Choose the topic you want to practice"
350
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
351
 
352
  # Update topics when grade changes
353
  grade_level.change(update_topics, grade_level, topic_select)
354
 
 
 
 
 
 
 
355
  with gr.Tabs():
356
  # ===== TAB 1: HANDWRITING ANALYSIS =====
357
  with gr.Tab("✍️ Write & Check Work"):
358
  gr.Markdown("""
359
- ### Write Your Math Solution
360
- Draw your solution using the canvas below OR upload a photo of your written work on paper.
361
- The AI will analyze your steps, identify errors, and help you improve!
 
 
 
 
 
362
  """)
363
 
364
  with gr.Row():
@@ -366,7 +565,7 @@ with gr.Blocks(theme=gr.themes.Soft(), title="Math Learning Assistant", css="""
366
  with gr.Tabs():
367
  with gr.Tab("πŸ–ŠοΈ Draw Here"):
368
  sketchpad = gr.Sketchpad(
369
- label="Write your solution (use finger/mouse/stylus)",
370
  type="pil",
371
  brush=gr.Brush(
372
  colors=["#000000", "#0000FF", "#FF0000", "#00AA00"],
@@ -377,34 +576,74 @@ with gr.Blocks(theme=gr.themes.Soft(), title="Math Learning Assistant", css="""
377
 
378
  with gr.Tab("πŸ“Έ Upload Photo"):
379
  image_upload = gr.Image(
380
- label="Upload photo of your written work",
381
  type="pil",
382
  height=500
383
  )
 
 
 
 
 
 
 
384
 
385
  with gr.Row():
386
  check_btn = gr.Button("πŸ” Check My Work", variant="primary", size="lg", scale=2)
387
  clear_canvas_btn = gr.Button("πŸ—‘οΈ Clear", size="lg", scale=1)
388
 
389
  with gr.Column(scale=1):
390
- gr.Markdown("### πŸ“Š AI Teacher's Feedback")
391
  feedback_output = gr.Textbox(
392
- label="Detailed Analysis & Feedback",
393
  lines=25,
394
- placeholder="Your personalized feedback will appear here...\n\nβœ“ Problem identification\nβœ“ Step-by-step analysis\nβœ“ Error detection\nβœ“ Correct solution\nβœ“ Learning tips",
395
  elem_classes="feedback-box"
396
  )
397
 
398
  # Event handlers for handwriting check
399
- def check_work_handler(sketch, upload, grade, topic):
 
 
 
400
  image_to_analyze = sketch if sketch is not None else upload
401
- if image_to_analyze is None:
402
- return "⚠️ Please draw your solution or upload an image first!"
403
- return analyze_math_work(image_to_analyze, grade, topic)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
404
 
405
  check_btn.click(
406
  fn=check_work_handler,
407
- inputs=[sketchpad, image_upload, grade_level, topic_select],
408
  outputs=feedback_output
409
  )
410
 
@@ -413,50 +652,97 @@ with gr.Blocks(theme=gr.themes.Soft(), title="Math Learning Assistant", css="""
413
  # ===== TAB 2: PRACTICE PROBLEMS =====
414
  with gr.Tab("πŸ“ Practice Questions"):
415
  gr.Markdown("""
416
- ### Generate Practice Problems
417
- Get custom practice problems for your level and topic. Solve them on paper or digitally!
 
 
 
 
418
  """)
419
 
420
  with gr.Row():
421
- generate_btn = gr.Button("🎲 Generate New Problem", variant="primary", size="lg")
 
 
 
 
 
 
422
 
423
  practice_output = gr.Textbox(
424
- label="Practice Problem",
425
- lines=15,
426
- placeholder="Click 'Generate New Problem' to get started!",
427
- interactive=False
428
  )
429
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
430
  generate_btn.click(
431
- fn=generate_practice_problem,
432
- inputs=[grade_level, topic_select],
433
  outputs=practice_output
434
  )
435
 
436
  # ===== TAB 3: AI TUTOR CHAT =====
437
  with gr.Tab("πŸ’¬ Ask AI Tutor"):
438
  gr.Markdown("""
439
- ### Chat with Your AI Math Tutor
440
- Ask questions about any math concept. Get clear, step-by-step explanations!
 
 
 
 
 
441
  """)
442
 
443
  chatbot = gr.Chatbot(
444
  height=500,
445
  show_label=False,
446
- placeholder="πŸ‘‹ Hi! I'm your AI math tutor. Ask me anything about the topic you selected!"
 
447
  )
448
 
449
  with gr.Row():
450
  msg_input = gr.Textbox(
451
- placeholder="Ask your question here... (e.g., 'How do I solve 3x + 5 = 20?')",
452
  label="Your Question",
453
  lines=2,
454
  scale=4
455
  )
456
- send_btn = gr.Button("πŸ“€ Send", variant="primary", scale=1)
457
 
458
  with gr.Row():
459
- clear_chat_btn = gr.Button("πŸ—‘οΈ Clear Chat")
 
 
 
 
 
 
460
 
461
  send_btn.click(
462
  ai_tutor_chat,
@@ -470,30 +756,123 @@ with gr.Blocks(theme=gr.themes.Soft(), title="Math Learning Assistant", css="""
470
  )
471
  clear_chat_btn.click(clear_chat, outputs=chatbot)
472
 
473
- # Footer with tips
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
474
  gr.Markdown("""
475
  ---
476
- ### πŸ’‘ Tips for Best Results:
477
 
478
- **For Handwriting Analysis:**
479
- - βœ“ Write clearly and show all your working steps
480
- - βœ“ Use proper mathematical notation
481
- - βœ“ If uploading a photo, ensure good lighting and focus
482
- - βœ“ Include the problem statement at the top
 
 
 
483
 
484
- **For Learning:**
485
- - βœ“ Don't worry about making mistakes - they help you learn!
486
- - βœ“ Try to solve problems on your own first
487
- - βœ“ Review the AI feedback carefully
488
- - βœ“ Practice regularly for best results
489
 
490
- **AI System Status:**
491
- - 🟒 **Gemini** (Primary): Vision-enabled analysis
492
- - πŸ”΅ **Cohere** (Secondary): Text-based fallback
493
- - 🟒 **Hugging Face** (Tertiary): Final fallback
494
 
495
- ---
496
- _Made with ❀️ for students learning mathematics_
 
497
  """)
498
 
499
  # Launch the app
 
170
  if not topic:
171
  return "⚠️ Please select a topic first!"
172
 
173
+ system_prompt = f"""You are an exceptional mathematics teacher specializing in {grade_level} level students.
174
+ Your student has submitted their work on: {topic}
 
 
 
 
 
 
175
 
176
+ Analyze their solution with EXTREME CLARITY and KINDNESS:
 
177
 
178
+ **πŸ“ PROBLEM IDENTIFIED:**
179
+ State exactly what mathematical problem they're solving
180
 
181
+ **πŸ‘€ STUDENT'S APPROACH:**
182
+ Describe their working, steps, and methods clearly
183
 
184
+ **βœ… CORRECTNESS EVALUATION:**
185
+ Is it completely correct? Partially correct? Incorrect? Be clear and specific.
186
 
187
+ **πŸ” DETAILED STEP-BY-STEP ANALYSIS:**
188
+ For each step:
189
+ - Is this step correct?
190
+ - If incorrect, explain the error gently
191
+ - Show the correct approach
192
 
193
+ **πŸ“š COMPLETE CORRECT SOLUTION:**
194
+ Show the entire correct solution with:
195
+ - All intermediate steps
196
+ - Mathematical notation
197
+ - Clear logic flow
198
 
199
+ **πŸ’‘ LEARNING INSIGHTS:**
200
+ - What concept was this testing?
201
+ - Key insight the student should remember
202
+ - Common mistakes students make
203
+ - Real-world connection (if applicable)
204
 
205
+ **🌟 ENCOURAGEMENT & IMPROVEMENT TIPS:**
206
+ - Positive feedback on what they did well
207
+ - 3 specific tips to improve
208
+ - Next level of difficulty to attempt
209
 
210
+ TONE: Be warm, encouraging, and supportive. Make them feel like learning is exciting! Use emojis to make feedback engaging."""
211
 
212
  try:
 
213
  response, source = ask_ai(system_prompt, temperature=0.5, image=image)
214
 
215
  if source == "error":
216
  return response
217
 
218
+ # Format the response nicely
219
+ formatted_response = f"""
220
+ ╔════════════════════════════════════════════════════════════════╗
221
+ β•‘ ✨ YOUR PERSONALIZED AI FEEDBACK ✨ β•‘
222
+ β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•
223
+
224
+ {response}
225
+
226
+ ╔════════════════════════════════════════════════════════════════╗
227
+ β•‘ 🎯 NEXT STEPS: Try the next problem or ask your AI tutor! β•‘
228
+ β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•
229
+ """
230
 
231
+ return formatted_response
232
 
233
  except Exception as e:
234
+ return f"""❌ Error analyzing work: {str(e)}
235
+
236
+ ⚑ **Quick Fix:**
237
+ 1. Make sure your image is clear and readable
238
+ 2. The math work should be visible and in focus
239
+ 3. Check your internet connection
240
+ 4. Try uploading a cleaner photo
241
+
242
+ πŸ’‘ **Pro Tip:** Good lighting and a straight-on photo work best!"""
243
 
244
  # ---------- 5. Generate Practice Problems ----------
245
  def generate_practice_problem(grade_level, topic):
 
248
  if not topic:
249
  return "⚠️ Please select a topic first!"
250
 
251
+ prompt = f"""Generate ONE engaging practice problem for {grade_level} students on: "{topic}"
252
 
253
  Requirements:
254
+ - Perfect difficulty for {grade_level}
255
+ - Clear, interesting problem statement
256
+ - 5-15 minutes to solve
257
+ - Include any necessary context or diagrams (text description)
 
258
 
259
+ Format:
260
 
261
+ **πŸ“ PROBLEM:**
262
+ [Clear problem statement - make it interesting!]
263
 
264
+ **πŸ’­ HELPFUL HINTS:**
265
+ Hint 1: [First step guidance]
266
+ Hint 2: [Process guidance]
267
+ Hint 3: [Concept check]
268
+
269
+ **🎯 DIFFICULTY:** [Easy/Medium/Hard]
270
+
271
+ **⏱️ EXPECTED TIME:** [5-10 minutes]
272
+
273
+ **βœ… COMPLETE SOLUTION (For After You Try):**
274
+ [Step-by-step solution with explanations]
275
 
276
+ **πŸ“š CONCEPT CHECK:**
277
+ [What this problem teaches you]
278
 
279
+ Make it FUN and ENCOURAGING!"""
280
 
281
  response, source = ask_ai(prompt, temperature=0.6)
282
 
283
+ formatted = f"""
284
+ ╔════════════════════════════════════════════════════════════════╗
285
+ β•‘ πŸ“ YOUR PERSONALIZED PRACTICE PROBLEM β•‘
286
+ β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•
287
+
288
+ {response}
289
+
290
+ ╔════════════════════════════════════════════════════════════════╗
291
+ β•‘ πŸ“Œ NEXT STEP: Solve this on paper, then upload to get help! β•‘
292
+ β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•
293
+ """
294
 
295
+ return formatted
296
 
297
  # ---------- 6. AI Tutor Chat ----------
298
  def ai_tutor_chat(message, history, grade_level, topic):
 
303
  history.append((message, "⚠️ Please select a topic first to get focused help!"))
304
  return history
305
 
306
+ system = f"""You are a world-class mathematics tutor specialized in teaching {grade_level} students.
307
+ Current topic focus: {topic}
308
 
309
+ Your approach:
310
+ 1. LISTEN to their question and understand exactly what they're confused about
311
+ 2. EXPLAIN using analogies, visuals descriptions, and real examples
312
+ 3. BREAK DOWN complex concepts into simple steps
313
+ 4. ASK CLARIFYING questions to check understanding
314
+ 5. PROVIDE examples and practice opportunities
315
+ 6. ENCOURAGE and motivate them
316
+
317
+ PERSONALITY:
318
+ - Warm, friendly, and patient
319
+ - Use emojis occasionally to stay engaging
320
+ - Celebrate their progress
321
+ - Make math FUN and RELEVANT
322
  - Use age-appropriate language for {grade_level}
 
 
 
 
323
 
324
+ Remember: You're not just answering - you're building understanding and confidence!"""
325
 
326
  # Build conversation context
327
  conversation = ""
328
+ for user_msg, bot_msg in history[-4:]:
329
  if user_msg:
330
  conversation += f"Student: {user_msg}\n"
331
  if bot_msg:
332
+ clean_msg = bot_msg.replace("πŸ”΅ ", "").replace("🟒 ", "").replace("πŸ“Œ ", "")
333
  conversation += f"Tutor: {clean_msg}\n"
334
 
335
+ full_prompt = f"{system}\n\n{conversation}\nStudent: {message}\n\nRespond as a caring, expert tutor:"
336
 
337
  bot_response, source = ask_ai(full_prompt, temperature=0.7)
338
 
339
+ # Add source indicator
340
  if source == "cohere":
341
  bot_response = f"πŸ”΅ {bot_response}"
342
  elif source == "hf":
343
  bot_response = f"🟒 {bot_response}"
344
+ else:
345
+ bot_response = f"πŸ“Œ {bot_response}"
346
 
347
  history.append((message, bot_response))
348
  return history
 
355
  topics = syllabus_topics["math"].get(grade_level, [])
356
  return gr.Dropdown(choices=topics, value=None)
357
 
358
+ # ---------- 8. Session & Progress Tracking ----------
359
+ import json
360
+ from pathlib import Path
361
+
362
+ class StudentSession:
363
+ def __init__(self, student_name="Student"):
364
+ self.student_name = student_name
365
+ self.start_time = datetime.now()
366
+ self.problems_attempted = 0
367
+ self.correct_solutions = 0
368
+ self.total_points = 0
369
+ self.session_history = []
370
+ self.achievements = []
371
+
372
+ def log_attempt(self, grade, topic, result):
373
+ """Log a learning attempt"""
374
+ self.problems_attempted += 1
375
+ self.session_history.append({
376
+ 'timestamp': datetime.now().isoformat(),
377
+ 'grade': grade,
378
+ 'topic': topic,
379
+ 'result': result
380
+ })
381
+
382
+ def get_stats(self):
383
+ """Get session statistics"""
384
+ accuracy = (self.correct_solutions / max(self.problems_attempted, 1)) * 100
385
+ return {
386
+ 'problems': self.problems_attempted,
387
+ 'correct': self.correct_solutions,
388
+ 'accuracy': accuracy,
389
+ 'points': self.total_points,
390
+ 'achievements': len(self.achievements)
391
+ }
392
+
393
+ session = StudentSession()
394
+
395
+ # ---------- 9. Gradio UI with Enhanced Design ----------
396
+ with gr.Blocks(theme=gr.themes.Soft(), title="✨ Smart Math Learning Assistant", css="""
397
+ :root {
398
+ --primary-color: #6366f1;
399
+ --success-color: #10b981;
400
+ --warning-color: #f59e0b;
401
+ --danger-color: #ef4444;
402
+ }
403
+
404
  .gradio-container {
405
+ font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
406
  max-width: 1400px;
407
  margin: auto;
408
+ background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
409
+ padding: 20px;
410
+ }
411
+
412
+ .header-section {
413
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
414
+ padding: 30px;
415
+ border-radius: 15px;
416
+ color: white;
417
+ margin-bottom: 30px;
418
+ box-shadow: 0 10px 30px rgba(0,0,0,0.2);
419
+ }
420
+
421
+ .header-section h1 {
422
+ margin: 0;
423
+ font-size: 2.5em;
424
+ font-weight: 700;
425
+ }
426
+
427
+ .stats-card {
428
+ background: white;
429
+ padding: 20px;
430
+ border-radius: 12px;
431
+ border-left: 5px solid var(--primary-color);
432
+ box-shadow: 0 4px 15px rgba(0,0,0,0.08);
433
  }
434
+
435
  .feedback-box {
436
+ background: linear-gradient(135deg, #f0fdf4 0%, #dcfce7 100%);
437
+ border-left: 5px solid var(--success-color);
438
+ padding: 20px;
439
+ border-radius: 12px;
440
+ font-size: 14px;
441
+ line-height: 1.8;
442
+ }
443
+
444
+ .error-box {
445
+ background: linear-gradient(135deg, #fef2f2 0%, #fee2e2 100%);
446
+ border-left: 5px solid var(--danger-color);
447
+ padding: 20px;
448
+ border-radius: 12px;
449
+ }
450
+
451
+ .problem-box {
452
+ background: linear-gradient(135deg, #fef9e7 0%, #fef3c7 100%);
453
+ border-left: 5px solid var(--warning-color);
454
+ padding: 20px;
455
+ border-radius: 12px;
456
+ }
457
+
458
+ .tab-button {
459
+ font-weight: 600;
460
+ font-size: 16px;
461
+ padding: 12px 24px !important;
462
+ }
463
+
464
+ .achievement-box {
465
+ background: linear-gradient(135deg, #fef3c7 0%, #fcd34d 100%);
466
  padding: 15px;
467
+ border-radius: 10px;
468
+ text-align: center;
469
+ margin: 10px;
470
+ }
471
+
472
+ button.primary-btn {
473
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
474
+ color: white;
475
+ font-weight: 600;
476
+ border: none;
477
+ padding: 12px 30px;
478
  border-radius: 8px;
479
+ cursor: pointer;
480
+ transition: all 0.3s ease;
481
+ }
482
+
483
+ button.primary-btn:hover {
484
+ transform: translateY(-2px);
485
+ box-shadow: 0 8px 20px rgba(102, 126, 234, 0.4);
486
+ }
487
+
488
+ .dropdown-label {
489
+ font-weight: 600;
490
+ font-size: 15px;
491
+ color: #1f2937;
492
+ }
493
+
494
+ .textbox-container textarea {
495
+ border-radius: 10px;
496
+ border: 2px solid #e5e7eb;
497
+ font-size: 14px;
498
  }
499
  """) as app:
500
 
501
  gr.Markdown("""
502
+ # ✨ Smart Math Learning Assistant
503
+ ### AI-Powered Adaptive Learning Platform
504
+ **Learn math the smart way - Write naturally, get instant AI feedback!**
505
 
506
+ _πŸš€ Personalized learning for every student | πŸ€– Advanced AI-powered analysis | πŸ“Š Real-time progress tracking_
507
  """)
508
 
509
+ # Grade Level and Topic Selection (Global) with Student Name
510
+ with gr.Group():
511
+ gr.Markdown("### πŸ‘€ Your Learning Profile")
512
+ with gr.Row():
513
+ student_name_input = gr.Textbox(
514
+ label="πŸ“ Your Name (Optional)",
515
+ placeholder="Enter your name for personalized learning",
516
+ value="Student"
517
+ )
518
+ grade_level = gr.Dropdown(
519
+ choices=list(syllabus_topics["math"].keys()),
520
+ label="πŸ“š Grade Level",
521
+ value="Primary 3-4",
522
+ info="Select your current grade"
523
+ )
524
+
525
+ topic_select = gr.Dropdown(
526
+ choices=syllabus_topics["math"]["Primary 3-4"],
527
+ label="πŸ“– Topic",
528
+ info="Choose what to practice"
529
+ )
530
+
531
+ # Progress Stats Bar
532
+ with gr.Group():
533
+ gr.Markdown("### πŸ“Š Your Progress Today")
534
+ with gr.Row():
535
+ problems_stat = gr.Textbox(value="Problems: 0", interactive=False, scale=1, container=False)
536
+ correct_stat = gr.Textbox(value="Correct: 0", interactive=False, scale=1, container=False)
537
+ accuracy_stat = gr.Textbox(value="Accuracy: 0%", interactive=False, scale=1, container=False)
538
+ points_stat = gr.Textbox(value="Points: 0", interactive=False, scale=1, container=False)
539
 
540
  # Update topics when grade changes
541
  grade_level.change(update_topics, grade_level, topic_select)
542
 
543
+ def update_student_name(name):
544
+ session.student_name = name if name else "Student"
545
+ return f"Welcome, {session.student_name}! πŸ‘‹"
546
+
547
+ student_name_input.change(update_student_name, student_name_input, None)
548
+
549
  with gr.Tabs():
550
  # ===== TAB 1: HANDWRITING ANALYSIS =====
551
  with gr.Tab("✍️ Write & Check Work"):
552
  gr.Markdown("""
553
+ ### πŸ“ Smart Solution Analyzer
554
+
555
+ **Three ways to submit your work:**
556
+ 1. ✏️ **Draw** your solution using the canvas
557
+ 2. πŸ“Έ **Upload** a photo of your written work on paper
558
+ 3. πŸ–₯️ **Type** if you prefer digital input
559
+
560
+ The AI Teacher will analyze every step and provide personalized feedback!
561
  """)
562
 
563
  with gr.Row():
 
565
  with gr.Tabs():
566
  with gr.Tab("πŸ–ŠοΈ Draw Here"):
567
  sketchpad = gr.Sketchpad(
568
+ label="✏️ Draw or write your solution",
569
  type="pil",
570
  brush=gr.Brush(
571
  colors=["#000000", "#0000FF", "#FF0000", "#00AA00"],
 
576
 
577
  with gr.Tab("πŸ“Έ Upload Photo"):
578
  image_upload = gr.Image(
579
+ label="πŸ“· Upload a clear photo of your work",
580
  type="pil",
581
  height=500
582
  )
583
+
584
+ with gr.Tab("πŸ“ Type Solution"):
585
+ text_input = gr.Textbox(
586
+ label="Or describe/type your solution here",
587
+ lines=10,
588
+ placeholder="Type your mathematical working, steps, or solution...",
589
+ )
590
 
591
  with gr.Row():
592
  check_btn = gr.Button("πŸ” Check My Work", variant="primary", size="lg", scale=2)
593
  clear_canvas_btn = gr.Button("πŸ—‘οΈ Clear", size="lg", scale=1)
594
 
595
  with gr.Column(scale=1):
596
+ gr.Markdown("### 🎯 AI Teacher's Detailed Feedback")
597
  feedback_output = gr.Textbox(
598
+ label="Your Personalized Analysis",
599
  lines=25,
600
+ placeholder="πŸ“‹ Your detailed feedback will appear here:\n\nβœ“ Problem you solved\nβœ“ Your approach analysis\nβœ“ Correct/incorrect assessment\nβœ“ Step-by-step explanation\nβœ“ Correct solution\nβœ“ Learning tips",
601
  elem_classes="feedback-box"
602
  )
603
 
604
  # Event handlers for handwriting check
605
+ def check_work_handler(sketch, upload, text, grade, topic):
606
+ if sketch is None and upload is None and (not text or not text.strip()):
607
+ return "⚠️ Please draw, upload an image, or type your solution!"
608
+
609
  image_to_analyze = sketch if sketch is not None else upload
610
+
611
+ if image_to_analyze:
612
+ feedback = analyze_math_work(image_to_analyze, grade, topic)
613
+ else:
614
+ # Use text-based analysis
615
+ system_prompt = f"""You are an encouraging math teacher for {grade} students learning {topic}.
616
+ The student has submitted: {text}
617
+
618
+ Analyze their solution like this:
619
+
620
+ **πŸ“ Problem Identified:**
621
+ [What they're solving]
622
+
623
+ **πŸ‘€ Analysis of Their Work:**
624
+ [What they did - is it correct?]
625
+
626
+ **βœ… Evaluation:**
627
+ [Correct? If not, where exactly is the error?]
628
+
629
+ **πŸ’‘ Detailed Explanation:**
630
+ [Step-by-step correct approach]
631
+
632
+ **🌟 Encouragement & Tips:**
633
+ [Positive feedback and 2-3 improvement tips]
634
+
635
+ Be kind, specific, and educational!"""
636
+ feedback, _ = ask_ai(system_prompt, temperature=0.5)
637
+
638
+ # Update stats
639
+ session.problems_attempted += 1
640
+ session.log_attempt(grade, topic, "checked")
641
+
642
+ return feedback
643
 
644
  check_btn.click(
645
  fn=check_work_handler,
646
+ inputs=[sketchpad, image_upload, text_input, grade_level, topic_select],
647
  outputs=feedback_output
648
  )
649
 
 
652
  # ===== TAB 2: PRACTICE PROBLEMS =====
653
  with gr.Tab("πŸ“ Practice Questions"):
654
  gr.Markdown("""
655
+ ### 🎲 Get Custom Practice Problems
656
+
657
+ Generated problems are **perfectly suited** to your level and topic!
658
+ - Solve them step-by-step on paper or digitally
659
+ - Upload your solution above to get feedback
660
+ - Challenge yourself with different problems
661
  """)
662
 
663
  with gr.Row():
664
+ generate_btn = gr.Button("🎲 Generate New Problem", variant="primary", size="lg", scale=1)
665
+ difficulty_level = gr.Radio(
666
+ choices=["Easy 😊", "Medium 😐", "Hard 😀"],
667
+ value="Medium 😐",
668
+ label="Difficulty Level",
669
+ scale=1
670
+ )
671
 
672
  practice_output = gr.Textbox(
673
+ label="πŸ“– Your Practice Problem",
674
+ lines=18,
675
+ placeholder="Click 'Generate New Problem' to get started!\n\nYou'll get:\nβœ“ Clear problem statement\nβœ“ Helpful hints\nβœ“ Full solution for reference",
676
+ elem_classes="problem-box"
677
  )
678
 
679
+ attempt_info = gr.Textbox(
680
+ label="How to use",
681
+ value="1️⃣ Read the problem carefully\n2️⃣ Solve it on paper or in the canvas\n3️⃣ Go to 'Write & Check Work' tab\n4️⃣ Get instant AI feedback!",
682
+ interactive=False,
683
+ lines=4
684
+ )
685
+
686
+ def generate_with_difficulty(grade, topic, diff):
687
+ diff_text = diff.split()[0].lower()
688
+ prompt = f"""Generate ONE practice problem for {grade} students on "{topic}"
689
+ Difficulty: {diff_text}
690
+
691
+ Format:
692
+ **πŸ“ Problem:**
693
+ [Clear statement]
694
+
695
+ **πŸ’­ Hints:**
696
+ [2-3 hints]
697
+
698
+ **βœ… Solution:**
699
+ [Step-by-step]"""
700
+ response, _ = ask_ai(prompt, temperature=0.6)
701
+ session.problems_attempted += 1
702
+ return response
703
+
704
  generate_btn.click(
705
+ fn=generate_with_difficulty,
706
+ inputs=[grade_level, topic_select, difficulty_level],
707
  outputs=practice_output
708
  )
709
 
710
  # ===== TAB 3: AI TUTOR CHAT =====
711
  with gr.Tab("πŸ’¬ Ask AI Tutor"):
712
  gr.Markdown("""
713
+ ### πŸ€– 24/7 Interactive AI Tutor
714
+
715
+ Ask anything about your topic! Your AI tutor will:
716
+ - πŸ“š Explain complex concepts clearly
717
+ - πŸ“ Show step-by-step solutions
718
+ - ❓ Answer your questions patiently
719
+ - πŸ’‘ Provide real-world examples
720
  """)
721
 
722
  chatbot = gr.Chatbot(
723
  height=500,
724
  show_label=False,
725
+ placeholder="πŸ‘‹ Hi! I'm your personal math tutor. Ask me anything about the topic you selected! Examples: 'How do I solve quadratic equations?', 'Can you explain fractions?'",
726
+ bubble_full_width=False
727
  )
728
 
729
  with gr.Row():
730
  msg_input = gr.Textbox(
731
+ placeholder="Ask your question... (e.g., 'What is the formula for area?')",
732
  label="Your Question",
733
  lines=2,
734
  scale=4
735
  )
736
+ send_btn = gr.Button("πŸ“€ Send", variant="primary", scale=1, size="lg")
737
 
738
  with gr.Row():
739
+ clear_chat_btn = gr.Button("πŸ—‘οΈ Clear Chat", scale=1)
740
+ hint_text = gr.Textbox(
741
+ value="πŸ’‘ Tip: Be specific! Ask about one concept at a time.",
742
+ interactive=False,
743
+ scale=3,
744
+ container=False
745
+ )
746
 
747
  send_btn.click(
748
  ai_tutor_chat,
 
756
  )
757
  clear_chat_btn.click(clear_chat, outputs=chatbot)
758
 
759
+ # ===== TAB 4: PROGRESS & ACHIEVEMENTS =====
760
+ with gr.Tab("πŸ† Progress & Achievements"):
761
+ gr.Markdown("""
762
+ ### πŸ“ˆ Your Learning Journey
763
+
764
+ Track your improvement, earn badges, and celebrate your wins!
765
+ """)
766
+
767
+ with gr.Row():
768
+ with gr.Column(scale=1):
769
+ gr.Markdown("### πŸ“Š Session Statistics")
770
+ total_problems = gr.Textbox(
771
+ label="Total Problems Attempted",
772
+ value="0",
773
+ interactive=False
774
+ )
775
+ session_time = gr.Textbox(
776
+ label="Time Spent Learning",
777
+ value="0 min",
778
+ interactive=False
779
+ )
780
+ topics_practiced = gr.Textbox(
781
+ label="Topics Practiced",
782
+ value="0",
783
+ interactive=False
784
+ )
785
+
786
+ with gr.Column(scale=1):
787
+ gr.Markdown("### 🎯 Your Achievements")
788
+ achievement_display = gr.Textbox(
789
+ label="Unlocked Badges",
790
+ value="🎯 Welcome Badge (Just joined!)\nπŸ”₯ Keep learning to unlock more!",
791
+ lines=8,
792
+ interactive=False
793
+ )
794
+
795
+ def get_session_stats():
796
+ stats = session.get_stats()
797
+ time_spent = (datetime.now() - session.start_time).seconds // 60
798
+ return {
799
+ 'total': str(stats['problems']),
800
+ 'time': f"{time_spent} min",
801
+ 'topics': str(len(set([h['topic'] for h in session.session_history]))),
802
+ }
803
+
804
+ with gr.Row():
805
+ refresh_btn = gr.Button("πŸ”„ Refresh Stats", variant="primary")
806
+
807
+ def refresh_handler():
808
+ s = get_session_stats()
809
+ return s['total'], s['time'], s['topics']
810
+
811
+ refresh_btn.click(
812
+ fn=refresh_handler,
813
+ inputs=[],
814
+ outputs=[total_problems, session_time, topics_practiced]
815
+ )
816
+
817
+ # ===== TAB 5: TIPS & GUIDE =====
818
+ with gr.Tab("πŸ“š Learning Guide"):
819
+ gr.Markdown("""
820
+ ### πŸŽ“ How to Get the Most from This App
821
+
822
+ #### πŸ–ŠοΈ **Write & Check Work**
823
+ - Write your solution clearly, showing every step
824
+ - Include the problem statement
825
+ - Use proper mathematical notation
826
+ - Upload a clear photo if handwriting
827
+
828
+ #### πŸ“ **Practice Questions**
829
+ - Start with the difficulty that challenges you
830
+ - Try solving BEFORE looking at hints
831
+ - Review the solution to understand concepts
832
+ - Repeat different problems on the same topic
833
+
834
+ #### πŸ’¬ **Ask AI Tutor**
835
+ - Ask one specific question at a time
836
+ - Use mathematical terminology when possible
837
+ - Ask "why" questions to understand concepts deeper
838
+ - Request step-by-step explanations
839
+
840
+ #### βœ… **Tips for Success**
841
+ 1. **Practice Regularly** - Consistency beats cramming
842
+ 2. **Understand, Don't Memorize** - Ask "why" for every step
843
+ 3. **Review Mistakes** - Your errors are your best teachers
844
+ 4. **Work Progressively** - Easy β†’ Medium β†’ Hard
845
+ 5. **Take Breaks** - Learning in focused 25-minute sessions works best
846
+
847
+ #### πŸš€ **Pro Tips**
848
+ - Use the eraser before submitting to fix small errors
849
+ - Request hints before checking the full solution
850
+ - Create a notebook to track your improvements
851
+ - Try to explain solutions to someone else
852
+ - Come back to difficult problems the next day
853
+ """)
854
+
855
+ # Footer
856
  gr.Markdown("""
857
  ---
858
+ ### 🌟 **Why Choose This Learning Platform?**
859
 
860
+ | Feature | Benefit |
861
+ |---------|---------|
862
+ | πŸ€– **AI-Powered Analysis** | Get intelligent, personalized feedback on every solution |
863
+ | 🎨 **Multiple Input Methods** | Draw, upload photos, or type - choose what works for you |
864
+ | πŸ“Š **Progress Tracking** | See your improvement over time |
865
+ | πŸ’¬ **24/7 AI Tutor** | Get help anytime, anywhere |
866
+ | 🎲 **Infinite Practice** | Never run out of problems to solve |
867
+ | ✨ **Adaptive Learning** | Personalized to your level and pace |
868
 
869
+ ---
 
 
 
 
870
 
871
+ **Made with ❀️ for students who want to truly understand mathematics**
 
 
 
872
 
873
+ _Current AI System: Gemini (Primary) β†’ Cohere (Secondary) β†’ Hugging Face (Backup)_
874
+
875
+ **Version 2.0 - Enhanced for Better Learning** ✨
876
  """)
877
 
878
  # Launch the app