sultan-hassan commited on
Commit
cfd749b
Β·
verified Β·
1 Parent(s): f61c521

Upload 2 files

Browse files
Files changed (2) hide show
  1. README.md +1 -1
  2. app.py +361 -104
README.md CHANGED
@@ -15,7 +15,7 @@ short_description: One homework question at a time, for kids with ADHD
15
 
16
  Hold a worksheet up to the camera and Homework Hero turns it into a game with one question at a time. Built for kids with ADHD, who often freeze when they see a full page of problems.
17
 
18
- Gemma 4 reads the worksheet, checks answers, and gives hints that never reveal the answer. A gentle time bar, a progress path, "save for later," and a movement break every 3 questions keep kids moving. Hints and cheers can be in English, Spanish, Amharic, or French. No accounts, and no photos are saved.
19
 
20
  ## How it connects to Gemma 4
21
 
 
15
 
16
  Hold a worksheet up to the camera and Homework Hero turns it into a game with one question at a time. Built for kids with ADHD, who often freeze when they see a full page of problems.
17
 
18
+ Gemma 4 reads the worksheet, checks answers, and gives hints that never reveal the answer. Pip, a friendly space buddy, cheers kids on while a rocket flies toward the finish. Sounds, confetti, stars and streaks reward progress; a "read it to me" button speaks each question; "later" saves hard questions for the end; and a movement break every 3 questions keeps kids moving. Sound can be turned off, and animations stop automatically for anyone whose device is set to reduce motion. Hints and cheers can be in English, Spanish, Amharic, or French. No accounts, and no photos are saved.
19
 
20
  ## How it connects to Gemma 4
21
 
app.py CHANGED
@@ -354,49 +354,114 @@ def e(s: str) -> str:
354
  return html.escape(str(s))
355
 
356
 
357
- def progress_html(state: dict) -> str:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
358
  total = len(state["questions"])
359
  done = state["done"]
360
- stones = []
361
- for i in range(total):
362
- cls = "done" if i < done else ("now" if i == done else "")
363
- mark = "β˜…" if i < done else str(i + 1)
364
- stones.append(f'<span class="stone {cls}">{mark}</span>')
365
- return (
366
- '<div class="hh-progress">'
367
- f'<div class="hh-path">{"".join(stones)}</div>'
368
- f'<p class="hh-count">{done} of {total} done</p></div>'
369
- )
 
 
 
 
 
 
 
 
 
 
370
 
371
 
372
  def question_html(state: dict) -> str:
373
  q = state["queue"][0]
374
- # A fresh key restarts the CSS time-bar animation for every question.
375
- key = f"t{int(time.time() * 1000)}"
376
  return f"""
377
- <div class="hh-card">
378
- <p class="hh-label">Just this one</p>
379
  <p class="hh-question">{e(q)}</p>
380
- <div class="hh-timer" aria-label="Time for this question">
381
- <div class="hh-fill {key}" style="animation-duration:{QUESTION_SECONDS}s"></div>
382
  </div>
383
- <p class="hh-timer-note">The bar is just a guide. Take the time you need.</p>
384
  </div>"""
385
 
386
 
387
- def feedback_html(kind: str, text: str) -> str:
388
- if not text:
389
- return ""
390
- return f'<div class="hh-feedback {kind}">{e(text)}</div>'
391
 
392
 
393
  def break_html(n: int) -> str:
394
  title, body = BREAKS[n % len(BREAKS)]
 
395
  return f"""
396
- <div class="hh-card hh-break">
397
- <p class="hh-label">Brain break</p>
 
398
  <p class="hh-question">{e(title)}</p>
399
  <p class="hh-break-body">{e(body)}</p>
 
 
400
  </div>"""
401
 
402
 
@@ -404,11 +469,18 @@ def done_html(state: dict) -> str:
404
  total = len(state["questions"])
405
  mins = max(1, round((time.time() - state["started"]) / 60))
406
  return f"""
407
- <div class="hh-card hh-done">
408
- <p class="hh-trophy">πŸ†</p>
409
  <p class="hh-question">Mission complete!</p>
410
- <p class="hh-break-body">You finished all {total} questions in about {mins} minute{'s' if mins != 1 else ''}.
411
- You used {state['hints']} hint{'s' if state['hints'] != 1 else ''}. That's what heroes do.</p>
 
 
 
 
 
 
 
412
  </div>"""
413
 
414
 
@@ -423,37 +495,34 @@ def show(screen: int):
423
 
424
  def start(image, lang, state):
425
  live = available_backends()
 
426
  if image is None and live:
427
- return [state, gr.update(value=feedback_html("oops", "Add a photo of the worksheet first."))] + \
428
- [gr.update()] * 3 + show(0)
429
  try:
430
  img = image if image is not None else Image.open(SAMPLE)
431
  questions = extract_questions(img, live)
432
  except Exception as ex:
433
- return [state, gr.update(value=feedback_html("oops", f"Couldn't reach Gemma ({ex}). Check the API keys in the Space settings, then try again."))] + \
434
- [gr.update()] * 3 + show(0)
435
  if not questions:
436
- return [state, gr.update(value=feedback_html("oops", "I couldn't find any questions. Try a closer photo with good light."))] + \
437
- [gr.update()] * 3 + show(0)
438
 
439
  state = {
440
  "questions": questions, "queue": list(questions), "done": 0,
441
- "hint_level": 0, "hints": 0, "breaks": 0,
442
  "started": time.time(), "live": live, "lang": lang,
443
  }
444
- note = "" if live else "Demo mode: no Gemma connection, so this uses the sample worksheet."
445
- return [state, gr.update(value=feedback_html("info", note) if note else ""),
446
- progress_html(state), question_html(state), ""] + show(1)
 
 
447
 
448
 
449
  def submit(answer_text, state):
450
- """Check the answer, then stay, celebrate, take a break, or finish.
451
-
452
- Outputs: answer, state, progress, card, feedback, break_card, done_card, *screens
453
- """
454
  keep = gr.update()
455
  if not answer_text or not answer_text.strip():
456
- return [keep, state, keep, keep, feedback_html("info", "Type your answer, then press Check."),
457
  keep, keep] + show(1)
458
  q = state["queue"][0]
459
  try:
@@ -462,18 +531,26 @@ def submit(answer_text, state):
462
  result = {"status": "cant_tell", "message": "Nice work! Let's keep going."}
463
 
464
  if result["status"] == "try_again":
465
- return [keep, state, keep, keep, feedback_html("again", result["message"]), keep, keep] + show(1)
 
 
466
 
467
  state["queue"].pop(0)
468
  state["done"] += 1
469
  state["hint_level"] = 0
470
- prog = progress_html(state)
 
 
 
471
  if not state["queue"]:
472
- return ["", state, prog, keep, "", keep, done_html(state)] + show(3)
473
  if state["done"] % BREAK_EVERY == 0:
474
  state["breaks"] += 1
475
- return ["", state, prog, keep, "", break_html(state["breaks"] - 1), keep] + show(2)
476
- return ["", state, prog, question_html(state), feedback_html("yay", result["message"] + " ⭐"),
 
 
 
477
  keep, keep] + show(1)
478
 
479
 
@@ -485,71 +562,241 @@ def hint(state):
485
  h = DEMO_HINTS[0]
486
  state["hint_level"] += 1
487
  state["hints"] += 1
488
- return state, feedback_html("hint", "πŸ’‘ " + h)
489
 
490
 
491
  def skip(state):
492
  q = state["queue"].pop(0)
493
  state["queue"].append(q)
494
  state["hint_level"] = 0
495
- msg = "No problem, we'll come back to that one later."
496
- return state, question_html(state), feedback_html("info", msg)
497
 
498
 
499
  def back_from_break(state):
500
- return [question_html(state), ""] + show(1)
501
 
502
 
503
  def restart(state):
504
  return [{}, ""] + show(0)
505
 
506
 
507
- # ---------------------------------------------------------------- UI
508
 
509
  CSS = """
510
- :root, .light { --hh-ink:#1F2A44; --hh-paper:#FFFFFF; --hh-sky:#E6F0FF; --hh-sun:#FFC83D;
511
- --hh-leaf:#2E8B57; --hh-plum:#6A4FB6; --hh-muted:#5B6478; --hh-line:#D5DEEE; }
512
- .dark { --hh-ink:#EEF2FA; --hh-paper:#1E2638; --hh-sky:#26324A; --hh-sun:#F2B82A;
513
- --hh-leaf:#5CC28A; --hh-plum:#A994F0; --hh-muted:#A8B1C4; --hh-line:#34405A; }
514
- .gradio-container { max-width: 760px !important; margin: 0 auto !important;
 
 
 
 
 
 
 
 
 
515
  font-family: 'Atkinson Hyperlegible', system-ui, sans-serif !important; }
516
- .hh-title h1 { font-family:'Fredoka', 'Atkinson Hyperlegible', sans-serif; font-size:2.4rem;
517
- font-weight:600; color:var(--hh-ink); margin:0.2em 0 0; }
518
- .hh-title p { color:var(--hh-muted); font-size:1.05rem; margin:0.2em 0 0.8em; }
519
- .hh-card { background:var(--hh-paper); border:2px solid var(--hh-line); border-radius:24px;
520
- padding:28px 28px 20px; color:var(--hh-ink); }
521
- .hh-label { color:var(--hh-muted); font-size:1rem; margin:0 0 6px; }
522
- .hh-question { font-family:'Fredoka', 'Atkinson Hyperlegible', sans-serif; font-weight:500;
523
- font-size:clamp(1.8rem, 5vw, 2.8rem); line-height:1.25; margin:0 0 22px; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
524
  .hh-timer { height:14px; border-radius:7px; background:var(--hh-sky); overflow:hidden; }
525
- .hh-fill { height:100%; width:100%; background:var(--hh-sun); transform-origin:left;
526
- animation-name: hh-shrink; animation-timing-function: linear; animation-fill-mode: forwards; }
527
- @keyframes hh-shrink { from { transform:scaleX(1);} to { transform:scaleX(0);} }
528
- @media (prefers-reduced-motion: reduce) { .hh-fill { animation:none; } }
529
- .hh-timer-note { color:var(--hh-muted); font-size:0.9rem; margin:8px 0 0; }
530
- .hh-progress { margin:4px 0 10px; }
531
- .hh-path { display:flex; flex-wrap:wrap; gap:8px; }
532
- .stone { width:38px; height:38px; border-radius:50%; display:inline-flex; align-items:center;
533
- justify-content:center; font-weight:700; border:2px solid var(--hh-line);
534
- color:var(--hh-muted); background:var(--hh-paper); }
535
- .stone.done { background:var(--hh-sun); border-color:var(--hh-sun); color:#1F2A44; }
536
- .stone.now { border-color:var(--hh-ink); color:var(--hh-ink); }
537
- .hh-count { color:var(--hh-muted); margin:8px 0 0; }
538
- .hh-feedback { border-radius:16px; padding:14px 18px; font-size:1.2rem; margin-top:4px; color:var(--hh-ink); }
539
- .hh-feedback.yay { background:color-mix(in srgb, var(--hh-leaf) 18%, transparent); }
540
- .hh-feedback.again { background:color-mix(in srgb, var(--hh-sun) 28%, transparent); }
541
- .hh-feedback.hint { background:color-mix(in srgb, var(--hh-plum) 16%, transparent); }
542
- .hh-feedback.info { background:var(--hh-sky); }
543
- .hh-feedback.oops { background:color-mix(in srgb, #D64545 18%, transparent); }
544
- .hh-break-body { font-size:1.3rem; line-height:1.5; margin:0 0 10px; }
545
- .hh-trophy { font-size:4rem; margin:0; }
546
- .hh-answer textarea, .hh-answer input { font-size:1.6rem !important; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
547
  """
548
 
549
  HEAD = (
550
  '<link rel="preconnect" href="https://fonts.googleapis.com">'
551
  '<link href="https://fonts.googleapis.com/css2?family=Atkinson+Hyperlegible:wght@400;700'
552
  '&family=Fredoka:wght@500;600&display=swap" rel="stylesheet">'
 
553
  )
554
 
555
  THEME = gr.themes.Soft(primary_hue="indigo", radius_size="lg")
@@ -573,51 +820,61 @@ STYLE = dict(theme=THEME, css=CSS, head=HEAD)
573
  with gr.Blocks(title="Homework Hero", **({} if NEW_GRADIO else STYLE)) as demo:
574
  state = gr.State({})
575
 
576
- gr.HTML('<div class="hh-title"><h1>Homework Hero</h1>'
577
- '<p>One question at a time. You\'ve got this.</p></div>')
 
 
 
 
578
 
579
  # Screen 0: setup
580
  with gr.Column(visible=True) as setup_screen:
 
 
581
  photo = gr.Image(label="Show me your worksheet", sources=["webcam", "upload"],
582
- type="pil", height=360)
583
  lang = gr.Dropdown(LANGUAGES, value="English", label="Language for hints and cheers")
584
- with gr.Row():
585
- start_btn = gr.Button("Start my mission", variant="primary", size="lg")
586
- sample_btn = gr.Button("Use the sample worksheet", size="lg")
587
  setup_msg = gr.HTML()
588
 
589
  # Screen 1: one question
590
  with gr.Column(visible=False) as play_screen:
591
- progress = gr.HTML()
592
  card = gr.HTML()
593
- answer = gr.Textbox(label="Your answer", placeholder="Type it here, then press Enter",
594
  elem_classes="hh-answer", autofocus=True)
595
- with gr.Row():
596
- check_btn = gr.Button("Check my answer", variant="primary", size="lg")
597
- hint_btn = gr.Button("Give me a hint", size="lg")
598
- skip_btn = gr.Button("Save for later", size="lg")
 
599
  feedback = gr.HTML()
600
 
601
  # Screen 2: movement break
602
  with gr.Column(visible=False) as break_screen:
603
  break_card = gr.HTML()
604
- back_btn = gr.Button("I'm back!", variant="primary", size="lg")
 
605
 
606
  # Screen 3: finished
607
  with gr.Column(visible=False) as done_screen:
608
  done_card = gr.HTML()
609
- again_btn = gr.Button("Start a new worksheet", variant="primary", size="lg")
 
610
 
611
  screens = [setup_screen, play_screen, break_screen, done_screen]
612
 
613
- start_outputs = [state, setup_msg, progress, card, feedback] + screens
614
  start_btn.click(start, [photo, lang, state], start_outputs)
615
  sample_btn.click(lambda l, s: start(Image.open(SAMPLE), l, s), [lang, state], start_outputs)
616
 
617
- route_outputs = [answer, state, progress, card, feedback, break_card, done_card] + screens
618
  check_btn.click(submit, [answer, state], route_outputs)
619
  answer.submit(submit, [answer, state], route_outputs)
620
  hint_btn.click(hint, [state], [state, feedback])
 
621
  skip_btn.click(skip, [state], [state, card, feedback])
622
  back_btn.click(back_from_break, [state], [card, feedback] + screens)
623
  again_btn.click(restart, [state], [state, setup_msg] + screens)
 
354
  return html.escape(str(s))
355
 
356
 
357
+ def uid() -> str:
358
+ return str(time.time_ns())
359
+
360
+
361
+ SPEECH_LANG = {"English": "en-US", "Spanish": "es-ES", "French": "fr-FR", "Amharic": "am-ET"}
362
+
363
+ CHEERS = ["Boom! You got it!", "Rocket power!", "Nailed it!", "Super star!", "You're on fire!"]
364
+
365
+
366
+ def buddy_svg(mood: str = "happy") -> str:
367
+ """Pip, the space buddy. Moods: happy, cheer, think, calm, oops."""
368
+ mouths = {
369
+ "happy": '<path d="M39 63 Q50 72 61 63" stroke="#1F2A44" stroke-width="4" fill="none" stroke-linecap="round"/>',
370
+ "cheer": '<path d="M37 60 Q50 80 63 60 Z" fill="#1F2A44"/><path d="M43 68 Q50 74 57 68" fill="#FF8FA3"/>',
371
+ "think": '<circle cx="56" cy="65" r="4" fill="#1F2A44"/>',
372
+ "calm": '<path d="M42 64 Q50 69 58 64" stroke="#1F2A44" stroke-width="4" fill="none" stroke-linecap="round"/>',
373
+ "oops": '<path d="M40 66 Q45 61 50 66 T60 66" stroke="#1F2A44" stroke-width="4" fill="none" stroke-linecap="round"/>',
374
+ }
375
+ eye_y = 44 if mood == "think" else 48
376
+ return f"""
377
+ <svg class="pip pip-{mood}" viewBox="0 0 100 100" aria-hidden="true">
378
+ <line x1="50" y1="20" x2="50" y2="8" stroke="#1F2A44" stroke-width="3" stroke-linecap="round"/>
379
+ <path d="M50 1 l2.6 5.4 5.9.8-4.3 4.1 1 5.9-5.2-2.8-5.2 2.8 1-5.9-4.3-4.1 5.9-.8z" fill="#FF7A6B"/>
380
+ <ellipse cx="50" cy="56" rx="38" ry="35" fill="#FFC83D" stroke="#1F2A44" stroke-width="3"/>
381
+ <ellipse cx="50" cy="66" rx="24" ry="16" fill="#FFE08A" opacity=".55"/>
382
+ <ellipse cx="37" cy="{eye_y}" rx="5" ry="6.5" fill="#1F2A44"/>
383
+ <ellipse cx="63" cy="{eye_y}" rx="5" ry="6.5" fill="#1F2A44"/>
384
+ <circle cx="39" cy="{eye_y - 2}" r="1.8" fill="#fff"/><circle cx="65" cy="{eye_y - 2}" r="1.8" fill="#fff"/>
385
+ <ellipse cx="26" cy="61" rx="6" ry="4" fill="#FF8FA3" opacity=".7"/>
386
+ <ellipse cx="74" cy="61" rx="6" ry="4" fill="#FF8FA3" opacity=".7"/>
387
+ {mouths.get(mood, mouths["happy"])}
388
+ </svg>"""
389
+
390
+
391
+ def buddy_html(mood: str, text: str, sfx: str = "", tone: str = "") -> str:
392
+ """Pip with a speech bubble. data-sfx tells the browser which sound/effect to play."""
393
+ if not text:
394
+ return ""
395
+ sfx_attr = f' data-sfx="{sfx}" data-id="{uid()}"' if sfx else ""
396
+ return f"""
397
+ <div class="hh-buddy {tone}"{sfx_attr}>
398
+ {buddy_svg(mood)}
399
+ <div class="hh-bubble">{e(text)}</div>
400
+ </div>"""
401
+
402
+
403
+ # Old name kept so the setup screen code stays simple.
404
+ def feedback_html(kind: str, text: str) -> str:
405
+ moods = {"yay": ("cheer", "correct"), "again": ("oops", "again"), "hint": ("think", "hint"),
406
+ "info": ("calm", ""), "oops": ("oops", "")}
407
+ mood, sfx = moods.get(kind, ("happy", ""))
408
+ return buddy_html(mood, text, sfx, tone=kind)
409
+
410
+
411
+ def hud_html(state: dict) -> str:
412
  total = len(state["questions"])
413
  done = state["done"]
414
+ pct = 0 if total == 0 else done / total * 100
415
+ streak = state.get("streak", 0)
416
+ fire = f'<span class="chip fire">πŸ”₯ {streak} in a row</span>' if streak >= 2 else ""
417
+ dots = "".join(
418
+ f'<span class="dot {"lit" if i < done else ""}" style="left:{(i + 1) / total * 100:.2f}%"></span>'
419
+ for i in range(total - 1))
420
+ return f"""
421
+ <div class="hh-hud">
422
+ <div class="hh-track" role="progressbar" aria-valuemin="0" aria-valuemax="{total}" aria-valuenow="{done}">
423
+ <span class="earth">🌍</span>
424
+ <div class="rail"><div class="trail" style="width:{pct:.2f}%"></div>{dots}
425
+ <span class="rocket" style="left:{pct:.2f}%">πŸš€</span></div>
426
+ <span class="planet">πŸͺ</span>
427
+ </div>
428
+ <div class="hh-chips">
429
+ <span class="chip">⭐ {state.get('stars', 0)}</span>
430
+ <span class="chip">{done} / {total} done</span>
431
+ {fire}
432
+ </div>
433
+ </div>"""
434
 
435
 
436
  def question_html(state: dict) -> str:
437
  q = state["queue"][0]
438
+ n = state["done"] + 1
439
+ total = len(state["questions"])
440
  return f"""
441
+ <div class="hh-card hh-q" data-lang="{SPEECH_LANG.get(state.get('lang'), 'en-US')}" data-id="{uid()}">
442
+ <p class="hh-label">Mission {n} of {total} Β· just this one</p>
443
  <p class="hh-question">{e(q)}</p>
444
+ <div class="hh-timer" aria-hidden="true">
445
+ <div class="hh-fill" style="animation-duration:{QUESTION_SECONDS}s"></div>
446
  </div>
447
+ <p class="hh-timer-note">The fuel bar is just a guide. Take the time you need.</p>
448
  </div>"""
449
 
450
 
451
+ BREAK_ICONS = ["🀸", "🐱", "πŸ™Œ", "🎈"]
 
 
 
452
 
453
 
454
  def break_html(n: int) -> str:
455
  title, body = BREAKS[n % len(BREAKS)]
456
+ icon = BREAK_ICONS[n % len(BREAK_ICONS)]
457
  return f"""
458
+ <div class="hh-card hh-break" data-sfx="break" data-id="{uid()}">
459
+ <p class="hh-label">Brain break!</p>
460
+ <div class="hh-break-icon">{icon}</div>
461
  <p class="hh-question">{e(title)}</p>
462
  <p class="hh-break-body">{e(body)}</p>
463
+ <div class="hh-ring"><svg viewBox="0 0 120 120"><circle cx="60" cy="60" r="52" class="ring-bg"/>
464
+ <circle cx="60" cy="60" r="52" class="ring-fg"/></svg><span>20s</span></div>
465
  </div>"""
466
 
467
 
 
469
  total = len(state["questions"])
470
  mins = max(1, round((time.time() - state["started"]) / 60))
471
  return f"""
472
+ <div class="hh-card hh-done" data-sfx="win" data-id="{uid()}">
473
+ <div class="hh-trophy">πŸ†</div>
474
  <p class="hh-question">Mission complete!</p>
475
+ <div class="hh-stats">
476
+ <div><b>{total}</b><span>questions</span></div>
477
+ <div><b>⭐ {state.get('stars', 0)}</b><span>stars</span></div>
478
+ <div><b>πŸ”₯ {state.get('best_streak', 0)}</b><span>best streak</span></div>
479
+ <div><b>{mins}</b><span>minute{'s' if mins != 1 else ''}</span></div>
480
+ </div>
481
+ {buddy_svg("cheer")}
482
+ <p class="hh-break-body">You used {state['hints']} hint{'s' if state['hints'] != 1 else ''}.
483
+ Asking for help is what heroes do!</p>
484
  </div>"""
485
 
486
 
 
495
 
496
  def start(image, lang, state):
497
  live = available_backends()
498
+ keep = [gr.update()] * 3
499
  if image is None and live:
500
+ return [state, feedback_html("oops", "Show me a photo of your worksheet first!")] + keep + show(0)
 
501
  try:
502
  img = image if image is not None else Image.open(SAMPLE)
503
  questions = extract_questions(img, live)
504
  except Exception as ex:
505
+ return [state, feedback_html("oops", f"I couldn't reach Gemma ({ex}). Check the API keys in the Space settings, then try again.")] + keep + show(0)
 
506
  if not questions:
507
+ return [state, feedback_html("oops", "I couldn't find any questions. Try a closer photo with good light.")] + keep + show(0)
 
508
 
509
  state = {
510
  "questions": questions, "queue": list(questions), "done": 0,
511
+ "hint_level": 0, "hints": 0, "breaks": 0, "stars": 0, "streak": 0, "best_streak": 0,
512
  "started": time.time(), "live": live, "lang": lang,
513
  }
514
+ hello = f"I found {len(questions)} missions! Let's do them one at a time."
515
+ if not live:
516
+ hello = "Demo mode: no Gemma connection, so I'm using the sample worksheet. " + hello
517
+ return [state, "", hud_html(state), question_html(state),
518
+ buddy_html("cheer", hello, "start")] + show(1)
519
 
520
 
521
  def submit(answer_text, state):
522
+ """Outputs: answer, state, hud, card, feedback, break_card, done_card, *screens"""
 
 
 
523
  keep = gr.update()
524
  if not answer_text or not answer_text.strip():
525
+ return [keep, state, keep, keep, feedback_html("info", "Type your answer, then press Check!"),
526
  keep, keep] + show(1)
527
  q = state["queue"][0]
528
  try:
 
531
  result = {"status": "cant_tell", "message": "Nice work! Let's keep going."}
532
 
533
  if result["status"] == "try_again":
534
+ state["streak"] = 0
535
+ return [keep, state, hud_html(state), keep, feedback_html("again", result["message"]),
536
+ keep, keep] + show(1)
537
 
538
  state["queue"].pop(0)
539
  state["done"] += 1
540
  state["hint_level"] = 0
541
+ state["stars"] += 1
542
+ state["streak"] += 1
543
+ state["best_streak"] = max(state["best_streak"], state["streak"])
544
+ hud = hud_html(state)
545
  if not state["queue"]:
546
+ return ["", state, hud, keep, "", keep, done_html(state)] + show(3)
547
  if state["done"] % BREAK_EVERY == 0:
548
  state["breaks"] += 1
549
+ return ["", state, hud, keep, "", break_html(state["breaks"] - 1), keep] + show(2)
550
+ msg = result["message"]
551
+ if state["streak"] >= 3:
552
+ msg += f" That's {state['streak']} in a row!"
553
+ return ["", state, hud, question_html(state), feedback_html("yay", msg + " ⭐"),
554
  keep, keep] + show(1)
555
 
556
 
 
562
  h = DEMO_HINTS[0]
563
  state["hint_level"] += 1
564
  state["hints"] += 1
565
+ return state, feedback_html("hint", h)
566
 
567
 
568
  def skip(state):
569
  q = state["queue"].pop(0)
570
  state["queue"].append(q)
571
  state["hint_level"] = 0
572
+ return state, question_html(state), feedback_html("info", "No problem! We'll come back to that one later.")
 
573
 
574
 
575
  def back_from_break(state):
576
+ return [question_html(state), buddy_html("cheer", "Welcome back! Ready for the next mission?", "start")] + show(1)
577
 
578
 
579
  def restart(state):
580
  return [{}, ""] + show(0)
581
 
582
 
583
+ # ---------------------------------------------------------------- styles, sounds, effects
584
 
585
  CSS = """
586
+ :root, .light {
587
+ --hh-ink:#1F2A44; --hh-paper:#FFFFFF; --hh-bg1:#EEF2FF; --hh-bg2:#FFF7E6; --hh-sky:#E3E9FF;
588
+ --hh-sun:#FFC83D; --hh-mint:#2FBF85; --hh-coral:#FF7A6B; --hh-plum:#7B61D9; --hh-muted:#5B6478;
589
+ --hh-line:#D9DFF0; --hh-shadow:0 10px 30px rgba(40,50,110,.12);
590
+ }
591
+ .dark {
592
+ --hh-ink:#EEF2FA; --hh-paper:#1D2438; --hh-bg1:#121729; --hh-bg2:#1A1730; --hh-sky:#2A3352;
593
+ --hh-sun:#F5BE2E; --hh-mint:#4FD39E; --hh-coral:#FF8E80; --hh-plum:#A994F0; --hh-muted:#A8B1C4;
594
+ --hh-line:#323C5C; --hh-shadow:0 10px 30px rgba(0,0,0,.35);
595
+ }
596
+ body, .gradio-container { background:
597
+ radial-gradient(circle at 12% 8%, var(--hh-bg2) 0, transparent 40%),
598
+ radial-gradient(circle at 90% 20%, var(--hh-bg1) 0, transparent 45%), var(--hh-bg1) !important; }
599
+ .gradio-container { max-width: 780px !important; margin: 0 auto !important;
600
  font-family: 'Atkinson Hyperlegible', system-ui, sans-serif !important; }
601
+ footer { opacity:.5; }
602
+
603
+ /* header */
604
+ .hh-head { display:flex; align-items:center; gap:14px; margin:6px 0 2px; }
605
+ .hh-head .pip { width:64px; height:64px; }
606
+ .hh-head h1 { font-family:'Fredoka','Atkinson Hyperlegible',sans-serif; font-size:2.3rem; font-weight:600;
607
+ color:var(--hh-ink); margin:0; line-height:1; }
608
+ .hh-head p { color:var(--hh-muted); margin:4px 0 0; font-size:1.05rem; }
609
+ .hh-sound { margin-left:auto; border:2px solid var(--hh-line); background:var(--hh-paper); color:var(--hh-ink);
610
+ border-radius:999px; padding:8px 14px; font-size:1rem; cursor:pointer; box-shadow:var(--hh-shadow); }
611
+ .hh-steps { display:flex; gap:10px; flex-wrap:wrap; margin:10px 0 4px; }
612
+ .hh-steps span { background:var(--hh-paper); border:2px solid var(--hh-line); border-radius:999px;
613
+ padding:8px 14px; color:var(--hh-ink); font-weight:700; }
614
+
615
+ /* buddy + bubble */
616
+ .hh-buddy { display:flex; align-items:center; gap:14px; margin:6px 0; animation:pop .35s ease-out; }
617
+ .pip { width:84px; height:84px; flex:none; animation:bob 2.6s ease-in-out infinite; }
618
+ .pip-cheer { animation:jump .6s ease-out 2, bob 2.6s ease-in-out 1.2s infinite; }
619
+ .pip-oops { animation:tilt .5s ease-in-out 2; }
620
+ .hh-bubble { position:relative; background:var(--hh-paper); color:var(--hh-ink); border:2px solid var(--hh-line);
621
+ border-radius:20px; padding:14px 18px; font-size:1.25rem; line-height:1.4; box-shadow:var(--hh-shadow); }
622
+ .hh-bubble::before { content:""; position:absolute; left:-11px; top:50%; width:18px; height:18px;
623
+ background:inherit; border-left:2px solid var(--hh-line); border-bottom:2px solid var(--hh-line);
624
+ transform:translateY(-50%) rotate(45deg); }
625
+ .hh-buddy.yay .hh-bubble { border-color:var(--hh-mint); }
626
+ .hh-buddy.again .hh-bubble { border-color:var(--hh-sun); }
627
+ .hh-buddy.hint .hh-bubble { border-color:var(--hh-plum); }
628
+ .hh-buddy.oops .hh-bubble { border-color:var(--hh-coral); }
629
+
630
+ /* HUD: rocket progress */
631
+ .hh-hud { margin:4px 0 12px; }
632
+ .hh-track { display:flex; align-items:center; gap:10px; font-size:1.8rem; }
633
+ .rail { position:relative; flex:1; height:16px; background:var(--hh-sky); border-radius:999px; }
634
+ .trail { height:100%; border-radius:999px; background:linear-gradient(90deg,var(--hh-plum),var(--hh-sun));
635
+ transition:width .8s cubic-bezier(.3,1.4,.5,1); }
636
+ .rail .dot { position:absolute; top:50%; width:8px; height:8px; margin:-4px 0 0 -4px; border-radius:50%;
637
+ background:var(--hh-line); }
638
+ .rail .dot.lit { background:#fff; }
639
+ .rocket { position:absolute; top:50%; transform:translate(-50%,-55%) rotate(45deg); font-size:2rem;
640
+ transition:left .8s cubic-bezier(.3,1.4,.5,1); filter:drop-shadow(0 4px 6px rgba(0,0,0,.2)); }
641
+ .hh-chips { display:flex; gap:8px; flex-wrap:wrap; margin-top:12px; }
642
+ .chip { background:var(--hh-paper); border:2px solid var(--hh-line); color:var(--hh-ink); border-radius:999px;
643
+ padding:6px 14px; font-weight:700; font-size:1.05rem; }
644
+ .chip.fire { border-color:var(--hh-coral); animation:pop .4s ease-out; }
645
+
646
+ /* question card */
647
+ .hh-card { background:var(--hh-paper); border:3px solid var(--hh-line); border-radius:28px;
648
+ padding:28px 30px 22px; color:var(--hh-ink); box-shadow:var(--hh-shadow); animation:pop .4s ease-out; }
649
+ .hh-card.wiggle { animation:wiggle .5s ease-in-out; border-color:var(--hh-sun); }
650
+ .hh-label { color:var(--hh-muted); font-size:1rem; font-weight:700; letter-spacing:.02em; margin:0 0 8px; }
651
+ .hh-question { font-family:'Fredoka','Atkinson Hyperlegible',sans-serif; font-weight:500;
652
+ font-size:clamp(2rem, 6vw, 3.2rem); line-height:1.2; margin:0 0 22px; }
653
  .hh-timer { height:14px; border-radius:7px; background:var(--hh-sky); overflow:hidden; }
654
+ .hh-fill { height:100%; width:100%; background:linear-gradient(90deg,var(--hh-mint),var(--hh-sun));
655
+ transform-origin:left; animation-name:shrink; animation-timing-function:linear; animation-fill-mode:forwards; }
656
+ .hh-timer-note { color:var(--hh-muted); font-size:.95rem; margin:8px 0 0; }
657
+
658
+ /* inputs and buttons */
659
+ .hh-answer textarea, .hh-answer input { font-size:1.8rem !important; padding:14px 16px !important;
660
+ border-radius:18px !important; }
661
+ .hh-btns button { font-size:1.15rem !important; border-radius:18px !important; min-height:58px; font-weight:700 !important;
662
+ transition:transform .12s ease; }
663
+ .hh-btns button:hover { transform:translateY(-2px); }
664
+ .hh-btns button:active { transform:scale(.97); }
665
+ .hh-go button, button.hh-go { background:var(--hh-mint) !important; color:#06281b !important; border:none !important; }
666
+ .hh-help button, button.hh-help { background:#EFEAFF !important; color:#3B2A8C !important; border:none !important; }
667
+ .hh-later button, button.hh-later { background:var(--hh-paper) !important; color:var(--hh-ink) !important;
668
+ border:2px solid var(--hh-line) !important; }
669
+ .hh-read button, button.hh-read { background:#FFF3D1 !important; color:#5A4300 !important; border:none !important; }
670
+
671
+ /* break */
672
+ .hh-break { text-align:center; }
673
+ .hh-break-icon { font-size:5rem; animation:jump .9s ease-in-out infinite; }
674
+ .hh-break-body { font-size:1.35rem; line-height:1.5; margin:0 0 14px; }
675
+ .hh-ring { position:relative; width:110px; height:110px; margin:6px auto 0; }
676
+ .hh-ring svg { width:100%; height:100%; transform:rotate(-90deg); }
677
+ .hh-ring circle { fill:none; stroke-width:10; }
678
+ .ring-bg { stroke:var(--hh-sky); }
679
+ .ring-fg { stroke:var(--hh-mint); stroke-linecap:round; stroke-dasharray:327; stroke-dashoffset:0;
680
+ animation:ring 20s linear forwards; }
681
+ .hh-ring span { position:absolute; inset:0; display:grid; place-items:center; font-weight:700; font-size:1.3rem;
682
+ color:var(--hh-ink); }
683
+
684
+ /* done */
685
+ .hh-done { text-align:center; }
686
+ .hh-done .pip { width:110px; height:110px; margin:6px auto 0; display:block; }
687
+ .hh-trophy { font-size:5.5rem; animation:jump .8s ease-out 3; }
688
+ .hh-stats { display:grid; grid-template-columns:repeat(4,1fr); gap:10px; margin:6px 0 4px; }
689
+ .hh-stats div { background:var(--hh-sky); border-radius:18px; padding:12px 6px; }
690
+ .hh-stats b { display:block; font-size:1.6rem; }
691
+ .hh-stats span { color:var(--hh-muted); font-size:.95rem; }
692
+ @media (max-width:560px) { .hh-stats { grid-template-columns:repeat(2,1fr); } .pip { width:64px; height:64px; } }
693
+
694
+ /* confetti */
695
+ #hh-fx { position:fixed; inset:0; pointer-events:none; overflow:hidden; z-index:9999; }
696
+ .cf { position:absolute; top:-20px; width:10px; height:16px; border-radius:3px; animation:fall linear forwards; }
697
+
698
+ @keyframes pop { from { transform:scale(.92); opacity:0 } to { transform:scale(1); opacity:1 } }
699
+ @keyframes bob { 0%,100% { transform:translateY(0) } 50% { transform:translateY(-6px) } }
700
+ @keyframes jump { 0%,100% { transform:translateY(0) } 40% { transform:translateY(-16px) scale(1.06) } }
701
+ @keyframes tilt { 0%,100% { transform:rotate(0) } 30% { transform:rotate(-8deg) } 70% { transform:rotate(8deg) } }
702
+ @keyframes wiggle { 0%,100% { transform:translateX(0) } 20% { transform:translateX(-8px) }
703
+ 40% { transform:translateX(8px) } 60% { transform:translateX(-5px) } 80% { transform:translateX(5px) } }
704
+ @keyframes shrink { from { transform:scaleX(1) } to { transform:scaleX(0) } }
705
+ @keyframes ring { to { stroke-dashoffset:327 } }
706
+ @keyframes fall { to { transform:translateY(110vh) rotate(720deg) } }
707
+ @media (prefers-reduced-motion: reduce) {
708
+ *, *::before, *::after { animation:none !important; transition:none !important; } }
709
+ """
710
+
711
+ FX_JS = r"""
712
+ <script>
713
+ (() => {
714
+ if (window.hhReady) return; window.hhReady = true;
715
+ let muted = false;
716
+ try { muted = localStorage.getItem('hh-muted') === '1'; } catch (e) {}
717
+ let ctx = null;
718
+ const ac = () => (ctx = ctx || new (window.AudioContext || window.webkitAudioContext)());
719
+
720
+ function tone(f, t, d, type = 'triangle', g = 0.18, slideTo = null) {
721
+ const a = ac(), o = a.createOscillator(), v = a.createGain(), s = a.currentTime + t;
722
+ o.type = type; o.frequency.setValueAtTime(f, s);
723
+ if (slideTo) o.frequency.exponentialRampToValueAtTime(slideTo, s + d);
724
+ v.gain.setValueAtTime(0.0001, s); v.gain.exponentialRampToValueAtTime(g, s + 0.02);
725
+ v.gain.exponentialRampToValueAtTime(0.0001, s + d);
726
+ o.connect(v).connect(a.destination); o.start(s); o.stop(s + d + 0.05);
727
+ }
728
+ const SFX = {
729
+ correct: () => [523, 659, 784, 1047].forEach((f, i) => tone(f, i * 0.08, 0.25)),
730
+ again: () => { tone(392, 0, 0.18, 'sine', 0.12); tone(330, 0.16, 0.28, 'sine', 0.12); },
731
+ hint: () => [1319, 1568, 1976].forEach((f, i) => tone(f, i * 0.06, 0.18, 'sine', 0.08)),
732
+ start: () => tone(300, 0, 0.45, 'sine', 0.12, 900),
733
+ break: () => { tone(220, 0, 0.25, 'square', 0.06, 440); tone(440, 0.25, 0.25, 'square', 0.06, 220); },
734
+ win: () => [523, 659, 784, 659, 784, 1047].forEach((f, i) => tone(f, i * 0.13, i === 5 ? 0.6 : 0.2, 'triangle', 0.2)),
735
+ };
736
+ function play(name) { if (!muted && SFX[name]) { try { SFX[name](); } catch (e) {} } }
737
+
738
+ function confetti(n) {
739
+ if (matchMedia('(prefers-reduced-motion: reduce)').matches) return;
740
+ let box = document.getElementById('hh-fx');
741
+ if (!box) { box = document.createElement('div'); box.id = 'hh-fx'; document.body.appendChild(box); }
742
+ const colors = ['#FFC83D', '#2FBF85', '#FF7A6B', '#7B61D9', '#4AA8FF'];
743
+ for (let i = 0; i < n; i++) {
744
+ const c = document.createElement('i'); c.className = 'cf';
745
+ c.style.left = Math.random() * 100 + 'vw';
746
+ c.style.background = colors[i % colors.length];
747
+ c.style.animationDuration = 1.6 + Math.random() * 1.6 + 's';
748
+ c.style.animationDelay = Math.random() * 0.3 + 's';
749
+ box.appendChild(c); setTimeout(() => c.remove(), 3800);
750
+ }
751
+ }
752
+ function wiggle() {
753
+ document.querySelectorAll('.hh-q').forEach(c => {
754
+ c.classList.remove('wiggle'); void c.offsetWidth; c.classList.add('wiggle'); });
755
+ }
756
+
757
+ const seen = new Set();
758
+ function scan() {
759
+ document.querySelectorAll('[data-sfx][data-id]').forEach(el => {
760
+ const id = el.dataset.id;
761
+ if (seen.has(id) || !el.offsetParent) return;
762
+ seen.add(id);
763
+ const s = el.dataset.sfx;
764
+ play(s);
765
+ if (s === 'correct') confetti(40);
766
+ if (s === 'win') { confetti(140); setTimeout(() => confetti(80), 700); }
767
+ if (s === 'again') wiggle();
768
+ });
769
+ }
770
+ new MutationObserver(() => requestAnimationFrame(scan))
771
+ .observe(document.documentElement, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });
772
+
773
+ function label() { document.querySelectorAll('.hh-sound').forEach(b => b.textContent = muted ? 'πŸ”‡ Sound off' : 'πŸ”Š Sound on'); }
774
+ document.addEventListener('click', ev => {
775
+ if (ctx && ctx.state === 'suspended') ctx.resume();
776
+ if (ev.target.closest('.hh-sound')) {
777
+ muted = !muted; try { localStorage.setItem('hh-muted', muted ? '1' : '0'); } catch (e) {}
778
+ label(); if (!muted) play('hint');
779
+ }
780
+ });
781
+ setInterval(label, 1500);
782
+
783
+ window.hhSpeak = () => {
784
+ const card = [...document.querySelectorAll('.hh-q')].find(c => c.offsetParent);
785
+ if (!card || !window.speechSynthesis) return;
786
+ const u = new SpeechSynthesisUtterance(card.querySelector('.hh-question').textContent
787
+ .replace(/Γ—/g, ' times ').replace(/Γ·/g, ' divided by '));
788
+ u.lang = card.dataset.lang || 'en-US'; u.rate = 0.9; u.pitch = 1.1;
789
+ speechSynthesis.cancel(); speechSynthesis.speak(u);
790
+ };
791
+ })();
792
+ </script>
793
  """
794
 
795
  HEAD = (
796
  '<link rel="preconnect" href="https://fonts.googleapis.com">'
797
  '<link href="https://fonts.googleapis.com/css2?family=Atkinson+Hyperlegible:wght@400;700'
798
  '&family=Fredoka:wght@500;600&display=swap" rel="stylesheet">'
799
+ + FX_JS
800
  )
801
 
802
  THEME = gr.themes.Soft(primary_hue="indigo", radius_size="lg")
 
820
  with gr.Blocks(title="Homework Hero", **({} if NEW_GRADIO else STYLE)) as demo:
821
  state = gr.State({})
822
 
823
+ gr.HTML(f"""
824
+ <div class="hh-head">
825
+ {buddy_svg("happy")}
826
+ <div><h1>Homework Hero</h1><p>One question at a time. You've got this!</p></div>
827
+ <button class="hh-sound" type="button">πŸ”Š Sound on</button>
828
+ </div>""")
829
 
830
  # Screen 0: setup
831
  with gr.Column(visible=True) as setup_screen:
832
+ gr.HTML('<div class="hh-steps"><span>πŸ“Έ 1. Snap your worksheet</span>'
833
+ '<span>🌍 2. Pick a language</span><span>πŸš€ 3. Blast off!</span></div>')
834
  photo = gr.Image(label="Show me your worksheet", sources=["webcam", "upload"],
835
+ type="pil", height=340)
836
  lang = gr.Dropdown(LANGUAGES, value="English", label="Language for hints and cheers")
837
+ with gr.Row(elem_classes="hh-btns"):
838
+ start_btn = gr.Button("πŸš€ Start my mission", elem_classes="hh-go", size="lg", min_width=90)
839
+ sample_btn = gr.Button("πŸ“„ Try the sample worksheet", elem_classes="hh-later", size="lg", min_width=90)
840
  setup_msg = gr.HTML()
841
 
842
  # Screen 1: one question
843
  with gr.Column(visible=False) as play_screen:
844
+ hud = gr.HTML()
845
  card = gr.HTML()
846
+ answer = gr.Textbox(label="Your answer", placeholder="Type it here, then press Enter ↡",
847
  elem_classes="hh-answer", autofocus=True)
848
+ with gr.Row(elem_classes="hh-btns"):
849
+ check_btn = gr.Button("βœ… Check", elem_classes="hh-go", size="lg", min_width=90)
850
+ hint_btn = gr.Button("πŸ’‘ Hint", elem_classes="hh-help", size="lg", min_width=90)
851
+ read_btn = gr.Button("πŸ”Š Read it", elem_classes="hh-read", size="lg", min_width=90)
852
+ skip_btn = gr.Button("⏭️ Later", elem_classes="hh-later", size="lg", min_width=90)
853
  feedback = gr.HTML()
854
 
855
  # Screen 2: movement break
856
  with gr.Column(visible=False) as break_screen:
857
  break_card = gr.HTML()
858
+ with gr.Row(elem_classes="hh-btns"):
859
+ back_btn = gr.Button("πŸ™Œ I'm back!", elem_classes="hh-go", size="lg", min_width=90)
860
 
861
  # Screen 3: finished
862
  with gr.Column(visible=False) as done_screen:
863
  done_card = gr.HTML()
864
+ with gr.Row(elem_classes="hh-btns"):
865
+ again_btn = gr.Button("πŸ“„ Start a new worksheet", elem_classes="hh-go", size="lg", min_width=90)
866
 
867
  screens = [setup_screen, play_screen, break_screen, done_screen]
868
 
869
+ start_outputs = [state, setup_msg, hud, card, feedback] + screens
870
  start_btn.click(start, [photo, lang, state], start_outputs)
871
  sample_btn.click(lambda l, s: start(Image.open(SAMPLE), l, s), [lang, state], start_outputs)
872
 
873
+ route_outputs = [answer, state, hud, card, feedback, break_card, done_card] + screens
874
  check_btn.click(submit, [answer, state], route_outputs)
875
  answer.submit(submit, [answer, state], route_outputs)
876
  hint_btn.click(hint, [state], [state, feedback])
877
+ read_btn.click(None, None, None, js="() => { window.hhSpeak && window.hhSpeak(); }")
878
  skip_btn.click(skip, [state], [state, card, feedback])
879
  back_btn.click(back_from_break, [state], [card, feedback] + screens)
880
  again_btn.click(restart, [state], [state, setup_msg] + screens)