3v324v23 commited on
Commit
f98e127
·
1 Parent(s): 6064a3e

Enhance scoring and training scripts with new features and benchmarks

Browse files

- Updated test_scoring.py to include subject handling in save_class and added assertions for progress tracking.
- Modified finetune.py to introduce new command-line arguments for layer training, optimizer selection, gradient checkpointing, and maximum training steps.
- Added minerva_benchmark.py for benchmarking phoneme models on Minerva lines, including false flag detection and planted mistake scoring.
- Created minerva_dataset.py to cut reviewed Minerva lines into a training set, ensuring a proper split by video and maintaining CSV compatibility for training.

.gitignore CHANGED
@@ -10,3 +10,6 @@ __pycache__/
10
  # local transcription of the copyrighted course book
11
  book/
12
  *.pdf
 
 
 
 
10
  # local transcription of the copyrighted course book
11
  book/
12
  *.pdf
13
+ # local Minerva clips cut by scripts/minerva_dataset.py (copyrighted videos; never committed)
14
+ data/minerva/
15
+ checkpoints/
README.md CHANGED
@@ -189,7 +189,7 @@ alter table public.attempts
189
  add column if not exists version text not null default '';
190
  ```
191
 
192
- The page's "ההתקדמות שלי" button reads these rows back through `GET /api/progress` (best score and tries per phrase, recordings, days practised) and shows them per topic; the best scores then follow the student between devices. The teacher's **דיווחים** tab aggregates `issues` without returning student identities. It shows a candidate when the same judgement occurred in at least five attempts, for at least three students and 30% of the students who attempted that phrase. These are investigation candidates, not proof of a scoring error; a teacher must explicitly turn one into a calibration draft and apply it.
193
 
194
  ### The teacher
195
 
@@ -208,6 +208,7 @@ create table public.user_access (
208
  email text not null,
209
  roles text[] not null default array['student']::text[],
210
  entitlements text[] not null default '{}'::text[],
 
211
  updated_at timestamptz not null default now(),
212
  updated_by uuid references auth.users(id),
213
  constraint valid_roles check (roles <@ array['student','teacher','flagger','admin','developer']::text[]),
@@ -229,6 +230,7 @@ alter table public.access_audit enable row level security;
229
  If `user_access` was created with the earlier three student features, run this once:
230
 
231
  ```sql
 
232
  alter table public.user_access drop constraint if exists valid_entitlements;
233
  update public.user_access
234
  set entitlements = array_append(entitlements, 'practice')
@@ -564,6 +566,7 @@ create table public.classes (
564
  emails text[] not null default '{}', -- the students' Google emails, lower-case
565
  nicknames jsonb not null default '{}', -- {email: nickname}, for the students who have one
566
  lessons text[] not null default '{}', -- the lesson ids the class studies; empty = every lesson
 
567
  homework text not null default '', -- the topic id the class practises now, e.g. l2-talk; '' = none
568
  due date, -- the day the homework is due, if it has one
569
  homeworks jsonb not null default '[]', -- every homework of the class: [{"topic": ..., "due": ...}]
@@ -581,7 +584,9 @@ alter table public.classes add column if not exists nicknames jsonb not null def
581
  add column if not exists homework text not null default '',
582
  add column if not exists due date,
583
  add column if not exists homeworks jsonb not null default '[]',
584
- add column if not exists dailies jsonb not null default '[]';
 
 
585
  ```
586
 
587
  The server keeps the list for a minute, so a change in the SQL editor (rather than the panel) applies within that time.
 
189
  add column if not exists version text not null default '';
190
  ```
191
 
192
+ The page reads these rows back through `GET /api/progress` (best score and tries per phrase, recordings, days practised, distinct practice days in the current week, and current/longest consecutive-day streaks); the best scores then follow the student between devices. Above the path, **הערבית שכבר שלכם** turns every practised phrase into a bead and scores of 85 or more into gold beads. It also shows a four-day weekly practice ring and a 🔥 consecutive-day streak; yesterday keeps a streak alive until the student has had today to continue it. New beads, gold mastery, meaningful personal bests, streaks and completed topics are celebrated on the practice card. The teacher's **דיווחים** tab aggregates `issues` without returning student identities. It shows a candidate when the same judgement occurred in at least five attempts, for at least three students and 30% of the students who attempted that phrase. These are investigation candidates, not proof of a scoring error; a teacher must explicitly turn one into a calibration draft and apply it.
193
 
194
  ### The teacher
195
 
 
208
  email text not null,
209
  roles text[] not null default array['student']::text[],
210
  entitlements text[] not null default '{}'::text[],
211
+ subject text not null default '', -- developer-set subject for admin-created classes
212
  updated_at timestamptz not null default now(),
213
  updated_by uuid references auth.users(id),
214
  constraint valid_roles check (roles <@ array['student','teacher','flagger','admin','developer']::text[]),
 
230
  If `user_access` was created with the earlier three student features, run this once:
231
 
232
  ```sql
233
+ alter table public.user_access add column if not exists subject text not null default '';
234
  alter table public.user_access drop constraint if exists valid_entitlements;
235
  update public.user_access
236
  set entitlements = array_append(entitlements, 'practice')
 
566
  emails text[] not null default '{}', -- the students' Google emails, lower-case
567
  nicknames jsonb not null default '{}', -- {email: nickname}, for the students who have one
568
  lessons text[] not null default '{}', -- the lesson ids the class studies; empty = every lesson
569
+ subject text not null default 'ערבית', -- existing classes; new ones copy the creating admin
570
  homework text not null default '', -- the topic id the class practises now, e.g. l2-talk; '' = none
571
  due date, -- the day the homework is due, if it has one
572
  homeworks jsonb not null default '[]', -- every homework of the class: [{"topic": ..., "due": ...}]
 
584
  add column if not exists homework text not null default '',
585
  add column if not exists due date,
586
  add column if not exists homeworks jsonb not null default '[]',
587
+ add column if not exists dailies jsonb not null default '[]',
588
+ add column if not exists subject text not null default 'ערבית';
589
+ update public.classes set subject = 'ערבית' where subject = '';
590
  ```
591
 
592
  The server keeps the list for a minute, so a change in the SQL editor (rather than the panel) applies within that time.
app/auth.py CHANGED
@@ -268,7 +268,8 @@ class SupabaseAuth:
268
  return rows
269
 
270
  def save_class(self, id: int | None, name: str, emails: list[str], nicknames: dict[str, str],
271
- lessons: list[str], homeworks: list[dict] = (), dailies: list[dict] | None = None) -> None:
 
272
  """Adds a class (id None) or replaces one's name, emails, nicknames, lessons and homeworks ([{"topic", "due"}]),
273
  and its daily videos' days ([{"video", "date"}]; None leaves them as they are, so a table made before them
274
  still takes a class that has none). A name already taken raises ClassConflict."""
@@ -278,6 +279,7 @@ class SupabaseAuth:
278
  if dailies is not None:
279
  body["dailies"] = list(dailies)
280
  if id is None:
 
281
  self._admin("/rest/v1/classes", "POST", body)
282
  elif not self._admin(f"/rest/v1/classes?id=eq.{int(id)}", "PATCH", body):
283
  raise KeyError(id)
@@ -624,12 +626,17 @@ class SupabaseAuth:
624
  return hit[1]
625
  try:
626
  rows = self._admin("/rest/v1/user_access?" + urllib.parse.urlencode({
627
- "user_id": f"eq.{user_id}", "select": "user_id,email,roles,entitlements,updated_at"}))
628
  value = rows[0] if rows else None
629
  except AuthUnavailable as e:
630
- if "answered 404" not in str(e):
 
 
 
 
631
  raise
632
- value = None
 
633
  with self._lock:
634
  self._access[user_id] = (now + CLASSES_TTL, value)
635
  return value
@@ -637,8 +644,11 @@ class SupabaseAuth:
637
  def access_rows(self) -> list[dict] | None:
638
  """All explicit access assignments, or None until the user_access table is installed."""
639
  try:
640
- return self._admin("/rest/v1/user_access?select=user_id,email,roles,entitlements,updated_at") or []
641
  except AuthUnavailable as e:
 
 
 
642
  if "answered 404" in str(e):
643
  return None
644
  raise
@@ -661,6 +671,19 @@ class SupabaseAuth:
661
  log.warning("access changed but audit row was not stored: %s", e)
662
  self.log_event("permission", actor, target["email"], {"roles": roles, "entitlements": entitlements})
663
 
 
 
 
 
 
 
 
 
 
 
 
 
 
664
  def secret_rows(self) -> list[dict] | None:
665
  """The API keys set in the panel, encrypted (see keystore.py), or None until the table `app_secrets` exists."""
666
  try:
 
268
  return rows
269
 
270
  def save_class(self, id: int | None, name: str, emails: list[str], nicknames: dict[str, str],
271
+ lessons: list[str], homeworks: list[dict] = (), dailies: list[dict] | None = None,
272
+ subject: str = "") -> None:
273
  """Adds a class (id None) or replaces one's name, emails, nicknames, lessons and homeworks ([{"topic", "due"}]),
274
  and its daily videos' days ([{"video", "date"}]; None leaves them as they are, so a table made before them
275
  still takes a class that has none). A name already taken raises ClassConflict."""
 
279
  if dailies is not None:
280
  body["dailies"] = list(dailies)
281
  if id is None:
282
+ body["subject"] = subject
283
  self._admin("/rest/v1/classes", "POST", body)
284
  elif not self._admin(f"/rest/v1/classes?id=eq.{int(id)}", "PATCH", body):
285
  raise KeyError(id)
 
626
  return hit[1]
627
  try:
628
  rows = self._admin("/rest/v1/user_access?" + urllib.parse.urlencode({
629
+ "user_id": f"eq.{user_id}", "select": "user_id,email,roles,entitlements,subject,updated_at"}))
630
  value = rows[0] if rows else None
631
  except AuthUnavailable as e:
632
+ if "subject" in str(e).lower():
633
+ rows = self._admin("/rest/v1/user_access?" + urllib.parse.urlencode({
634
+ "user_id": f"eq.{user_id}", "select": "user_id,email,roles,entitlements,updated_at"}))
635
+ value = ({**rows[0], "subject": ""} if rows else None)
636
+ elif "answered 404" not in str(e):
637
  raise
638
+ else:
639
+ value = None
640
  with self._lock:
641
  self._access[user_id] = (now + CLASSES_TTL, value)
642
  return value
 
644
  def access_rows(self) -> list[dict] | None:
645
  """All explicit access assignments, or None until the user_access table is installed."""
646
  try:
647
+ return self._admin("/rest/v1/user_access?select=user_id,email,roles,entitlements,subject,updated_at") or []
648
  except AuthUnavailable as e:
649
+ if "subject" in str(e).lower():
650
+ return [{**r, "subject": ""} for r in
651
+ (self._admin("/rest/v1/user_access?select=user_id,email,roles,entitlements,updated_at") or [])]
652
  if "answered 404" in str(e):
653
  return None
654
  raise
 
671
  log.warning("access changed but audit row was not stored: %s", e)
672
  self.log_event("permission", actor, target["email"], {"roles": roles, "entitlements": entitlements})
673
 
674
+ def set_admin_subject(self, target: dict, subject: str, actor: dict) -> None:
675
+ """Set an admin's subject without changing their access assignment."""
676
+ old = self.access_for(target["id"]) or {}
677
+ row = {"user_id": target["id"], "email": target["email"].lower(),
678
+ "roles": old.get("roles") or ["student"], "entitlements": old.get("entitlements") or [],
679
+ "subject": subject, "updated_at": datetime.now(timezone.utc).isoformat(),
680
+ "updated_by": actor["id"]}
681
+ self._admin("/rest/v1/user_access?on_conflict=user_id", "POST", row,
682
+ prefer="resolution=merge-duplicates,return=minimal")
683
+ with self._lock:
684
+ self._access.pop(target["id"], None)
685
+ self.log_event("permission", actor, target["email"], {"admin_subject": subject})
686
+
687
  def secret_rows(self) -> list[dict] | None:
688
  """The API keys set in the panel, encrypted (see keystore.py), or None until the table `app_secrets` exists."""
689
  try:
app/main.py CHANGED
@@ -161,7 +161,8 @@ CREATE_TUTORS = ("create table public.tutors (email text primary key, granted_by
161
  "created_at timestamptz not null default now()); alter table public.tutors enable row level security;")
162
  CREATE_USER_ACCESS = ("create table public.user_access (user_id uuid primary key references auth.users(id) on delete cascade, "
163
  "email text not null, roles text[] not null default array['student']::text[], "
164
- "entitlements text[] not null default '{}'::text[], updated_at timestamptz not null default now(), "
 
165
  "updated_by uuid references auth.users(id), "
166
  "constraint valid_roles check (roles <@ array['student','teacher','flagger','admin','developer']::text[]), "
167
  "constraint valid_entitlements check (entitlements <@ array['practice','games','tutor','path','library']::text[])); "
@@ -179,7 +180,8 @@ CREATE_SYSTEM_EVENTS = ("create table public.system_events (id bigint generated
179
  "created_at timestamptz not null default now()); "
180
  "create index system_events_created_at_idx on public.system_events (created_at desc); "
181
  "alter table public.system_events enable row level security;")
182
- MIGRATE_USER_ACCESS = ("alter table public.user_access drop constraint if exists valid_entitlements; "
 
183
  "update public.user_access set entitlements = array_append(entitlements, 'practice') "
184
  "where 'path' = any(entitlements) and not ('practice' = any(entitlements)); "
185
  "alter table public.user_access add constraint valid_entitlements check "
@@ -220,7 +222,9 @@ MIGRATE_CLASSES = ("alter table public.classes add column if not exists nickname
220
  "add column if not exists lessons text[] not null default '{}', "
221
  "add column if not exists homework text not null default '', add column if not exists due date, "
222
  "add column if not exists homeworks jsonb not null default '[]', "
223
- "add column if not exists dailies jsonb not null default '[]';")
 
 
224
  MAX_HOMEWORKS = 30
225
 
226
 
@@ -382,6 +386,38 @@ def summary(rows: list[dict], texts: dict[int, dict] | None = None) -> dict:
382
  "last": last.isoformat() if last else None}
383
 
384
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
385
  def create_app(scorer: Scorer | None = None, tts: SawtakTTS | None = None,
386
  auth: SupabaseAuth | None = None, tutor: Tutor | None = None) -> FastAPI:
387
  @asynccontextmanager
@@ -428,7 +464,7 @@ def create_app(scorer: Scorer | None = None, tts: SawtakTTS | None = None,
428
  except AuthUnavailable as e:
429
  raise HTTPException(503, f"class list not available: {e}")
430
  mine = [c for c in classes if email in c["emails"]] # a student may be in several classes
431
- roles, entitlements = {"student"}, set(DEFAULT_ENTITLEMENTS)
432
  if hasattr(a, "access_for"):
433
  try:
434
  assigned = a.access_for(user["id"])
@@ -456,6 +492,7 @@ def create_app(scorer: Scorer | None = None, tts: SawtakTTS | None = None,
456
  permissions = set().union(*(ROLE_PERMISSIONS[r] for r in roles))
457
  permissions.update(*[ENTITLEMENT_PERMISSIONS[e] for e in entitlements])
458
  return {**user, "token": token.strip(), "roles": sorted(roles), "entitlements": sorted(entitlements),
 
459
  "permissions": sorted(permissions), "teacher": bool(roles & {"teacher", "admin", "developer"}),
460
  "tutor": "flags.create" in permissions or "*" in permissions, "classes": mine}
461
 
@@ -554,9 +591,11 @@ def create_app(scorer: Scorer | None = None, tts: SawtakTTS | None = None,
554
 
555
  @app.get("/api/progress")
556
  def progress(user: dict | None = Depends(signed_in)):
557
- """The signed-in student's progress: best score and tries per phrase id, recordings, days practised."""
558
- s = summary(app.state.auth.attempts(user["token"]) if user else [], text_bank(text_rows()))
559
- return {k: s[k] for k in ("best", "tries", "recordings", "days")}
 
 
560
 
561
  @app.get("/api/writing", dependencies=[Depends(require("practice.use"))])
562
  def writing(user: dict | None = Depends(signed_in)):
@@ -761,6 +800,56 @@ def create_app(scorer: Scorer | None = None, tts: SawtakTTS | None = None,
761
  raise HTTPException(503, f"Supabase לא זמין: {e}")
762
  return {"ok": True}
763
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
764
  @app.get("/api/flags")
765
  def flags(status: str = Query("pending"), a: SupabaseAuth = Depends(teacher_only)):
766
  """The score reports awaiting a teacher's decision (or one reviewed state)."""
@@ -1410,11 +1499,11 @@ def create_app(scorer: Scorer | None = None, tts: SawtakTTS | None = None,
1410
  if "answered 404" in str(e):
1411
  return ("הטבלה classes לא קיימת ב-Supabase. צרו אותה ב-SQL Editor (הפקודה ב-README); "
1412
  "אם כבר נוצרה, הריצו שם: notify pgrst, 'reload schema';")
1413
- if any(col in str(e) for col in ("nicknames", "lessons", "homework", "'due'", "dailies")): # a table made before them
1414
  return f"לטבלה classes חסרות עמודות. הריצו ב-SQL Editor של Supabase: {MIGRATE_CLASSES}"
1415
  return f"Supabase לא זמין: {e}"
1416
 
1417
- def save_class(a: SupabaseAuth, id: int | None, body: dict) -> dict:
1418
  """Checks a class from the panel ({"name", "emails": the student list, see `class_members`, "lessons": lesson
1419
  ids, "homeworks": [{"topic": a topic of one of them, "due": its ISO date, or ""}], each topic once; or, as
1420
  before a class could have several, "homework" and "due" for a single one; "dailies": [{"video": the id of
@@ -1472,7 +1561,11 @@ def create_app(scorer: Scorer | None = None, tts: SawtakTTS | None = None,
1472
  raise HTTPException(409, f"כבר יש כיתה בשם {taken}")
1473
  # a class that has no daily videos, and had none, is saved without them: a table made before them takes it
1474
  had = any(c["id"] == id and c.get("dailies") for c in a.classes())
1475
- a.save_class(id, name, emails, nicks, lessons, homeworks, dailies if dailies or had else None)
 
 
 
 
1476
  except ClassConflict:
1477
  raise HTTPException(409, f"כבר יש כיתה בשם {name}")
1478
  except KeyError:
@@ -1482,12 +1575,12 @@ def create_app(scorer: Scorer | None = None, tts: SawtakTTS | None = None,
1482
  return {"ok": True}
1483
 
1484
  @app.post("/api/classes")
1485
- def add_class(body: dict = Body(...), a: SupabaseAuth = Depends(teacher_only)):
1486
- return save_class(a, None, body)
1487
 
1488
  @app.put("/api/classes/{class_id}")
1489
- def edit_class(class_id: int, body: dict = Body(...), a: SupabaseAuth = Depends(teacher_only)):
1490
- return save_class(a, class_id, body)
1491
 
1492
  @app.delete("/api/classes/{class_id}")
1493
  def delete_class(class_id: int, a: SupabaseAuth = Depends(teacher_only)):
 
161
  "created_at timestamptz not null default now()); alter table public.tutors enable row level security;")
162
  CREATE_USER_ACCESS = ("create table public.user_access (user_id uuid primary key references auth.users(id) on delete cascade, "
163
  "email text not null, roles text[] not null default array['student']::text[], "
164
+ "entitlements text[] not null default '{}'::text[], subject text not null default '', "
165
+ "updated_at timestamptz not null default now(), "
166
  "updated_by uuid references auth.users(id), "
167
  "constraint valid_roles check (roles <@ array['student','teacher','flagger','admin','developer']::text[]), "
168
  "constraint valid_entitlements check (entitlements <@ array['practice','games','tutor','path','library']::text[])); "
 
180
  "created_at timestamptz not null default now()); "
181
  "create index system_events_created_at_idx on public.system_events (created_at desc); "
182
  "alter table public.system_events enable row level security;")
183
+ MIGRATE_USER_ACCESS = ("alter table public.user_access add column if not exists subject text not null default ''; "
184
+ "alter table public.user_access drop constraint if exists valid_entitlements; "
185
  "update public.user_access set entitlements = array_append(entitlements, 'practice') "
186
  "where 'path' = any(entitlements) and not ('practice' = any(entitlements)); "
187
  "alter table public.user_access add constraint valid_entitlements check "
 
222
  "add column if not exists lessons text[] not null default '{}', "
223
  "add column if not exists homework text not null default '', add column if not exists due date, "
224
  "add column if not exists homeworks jsonb not null default '[]', "
225
+ "add column if not exists dailies jsonb not null default '[]', "
226
+ "add column if not exists subject text not null default 'ערבית'; "
227
+ "update public.classes set subject = 'ערבית' where subject = '';")
228
  MAX_HOMEWORKS = 30
229
 
230
 
 
386
  "last": last.isoformat() if last else None}
387
 
388
 
389
+ def weekly_practice_days(rows: list[dict]) -> int:
390
+ """Distinct Jerusalem calendar days practised since Monday of the current week."""
391
+ today = datetime.now(LOCAL_TZ).date()
392
+ monday = today - timedelta(days=today.weekday())
393
+ return len({utc(r["created_at"]).astimezone(LOCAL_TZ).date() for r in rows
394
+ if monday <= utc(r["created_at"]).astimezone(LOCAL_TZ).date() <= today})
395
+
396
+
397
+ def practice_streak(rows: list[dict]) -> dict:
398
+ """Current and longest runs of consecutive Jerusalem calendar days.
399
+
400
+ Yesterday may anchor the current run: a student does not lose the visible streak
401
+ before they have had a chance to practise today.
402
+ """
403
+ days = sorted({utc(r["created_at"]).astimezone(LOCAL_TZ).date() for r in rows})
404
+ if not days:
405
+ return {"current": 0, "best": 0, "last": None}
406
+ longest = run = 1
407
+ for previous, day in zip(days, days[1:]):
408
+ run = run + 1 if day == previous + timedelta(days=1) else 1
409
+ longest = max(longest, run)
410
+ today = datetime.now(LOCAL_TZ).date()
411
+ current = 0
412
+ if days[-1] >= today - timedelta(days=1):
413
+ current = 1
414
+ for i in range(len(days) - 1, 0, -1):
415
+ if days[i - 1] != days[i] - timedelta(days=1):
416
+ break
417
+ current += 1
418
+ return {"current": current, "best": longest, "last": days[-1].isoformat()}
419
+
420
+
421
  def create_app(scorer: Scorer | None = None, tts: SawtakTTS | None = None,
422
  auth: SupabaseAuth | None = None, tutor: Tutor | None = None) -> FastAPI:
423
  @asynccontextmanager
 
464
  except AuthUnavailable as e:
465
  raise HTTPException(503, f"class list not available: {e}")
466
  mine = [c for c in classes if email in c["emails"]] # a student may be in several classes
467
+ roles, entitlements, assigned = {"student"}, set(DEFAULT_ENTITLEMENTS), None
468
  if hasattr(a, "access_for"):
469
  try:
470
  assigned = a.access_for(user["id"])
 
492
  permissions = set().union(*(ROLE_PERMISSIONS[r] for r in roles))
493
  permissions.update(*[ENTITLEMENT_PERMISSIONS[e] for e in entitlements])
494
  return {**user, "token": token.strip(), "roles": sorted(roles), "entitlements": sorted(entitlements),
495
+ "subject": str((assigned or {}).get("subject") or ""),
496
  "permissions": sorted(permissions), "teacher": bool(roles & {"teacher", "admin", "developer"}),
497
  "tutor": "flags.create" in permissions or "*" in permissions, "classes": mine}
498
 
 
591
 
592
  @app.get("/api/progress")
593
  def progress(user: dict | None = Depends(signed_in)):
594
+ """The student's best scores and compact practice totals, including this week's active days."""
595
+ rows = app.state.auth.attempts(user["token"]) if user else []
596
+ s = summary(rows, text_bank(text_rows()))
597
+ return {**{k: s[k] for k in ("best", "tries", "recordings", "days")},
598
+ "week_days": weekly_practice_days(rows), "streak": practice_streak(rows)}
599
 
600
  @app.get("/api/writing", dependencies=[Depends(require("practice.use"))])
601
  def writing(user: dict | None = Depends(signed_in)):
 
800
  raise HTTPException(503, f"Supabase לא זמין: {e}")
801
  return {"ok": True}
802
 
803
+ @app.get("/api/admin-subjects")
804
+ def admin_subjects(a: SupabaseAuth = Depends(require("*")), actor: dict | None = Depends(signed_in)):
805
+ """Developer-only data for the dedicated subject editor in Monitoring."""
806
+ if not actor or "*" not in actor.get("permissions", ()):
807
+ raise HTTPException(403, "developers only")
808
+ try:
809
+ users, rows = a.users(), a.access_rows()
810
+ except AuthUnavailable as e:
811
+ raise HTTPException(503, f"Supabase לא זמין: {e}")
812
+ if rows is None:
813
+ return {"admins": [], "setup": CREATE_USER_ACCESS, "migration": MIGRATE_USER_ACCESS}
814
+ assigned = {r["user_id"]: r for r in rows}
815
+ out = []
816
+ for account in users:
817
+ row, email = assigned.get(account["id"], {}), account["email"].lower()
818
+ roles = set(row.get("roles") or [])
819
+ if email in getattr(a, "teachers", ()):
820
+ roles.add("admin")
821
+ if "admin" in roles:
822
+ out.append({"id": account["id"], "email": account["email"], "name": account.get("name", ""),
823
+ "subject": str(row.get("subject") or "")})
824
+ return {"admins": out, "setup": "", "migration": ""}
825
+
826
+ @app.put("/api/admin-subjects/{target_id}")
827
+ def update_admin_subject(target_id: str, body: dict = Body(...),
828
+ a: SupabaseAuth = Depends(require("*")), actor: dict | None = Depends(signed_in)):
829
+ if not actor or "*" not in actor.get("permissions", ()):
830
+ raise HTTPException(403, "developers only")
831
+ subject = " ".join(str(body.get("subject", "")).split())
832
+ if not subject or len(subject) > 80:
833
+ raise HTTPException(400, "subject must contain 1–80 characters")
834
+ try:
835
+ target = next((u for u in a.users() if u["id"] == target_id), None)
836
+ if not target:
837
+ raise HTTPException(404, "account not found")
838
+ old = a.access_for(target_id) or {}
839
+ roles = set(old.get("roles") or [])
840
+ if target["email"].lower() in getattr(a, "teachers", ()):
841
+ roles.add("admin")
842
+ if "admin" not in roles:
843
+ raise HTTPException(400, "the account is not an admin")
844
+ a.set_admin_subject(target, subject, actor)
845
+ except HTTPException:
846
+ raise
847
+ except AuthUnavailable as e:
848
+ if "subject" in str(e).lower():
849
+ raise HTTPException(503, f"permissions table needs upgrading; run: {MIGRATE_USER_ACCESS}")
850
+ raise HTTPException(503, f"Supabase לא זמין: {e}")
851
+ return {"ok": True, "subject": subject}
852
+
853
  @app.get("/api/flags")
854
  def flags(status: str = Query("pending"), a: SupabaseAuth = Depends(teacher_only)):
855
  """The score reports awaiting a teacher's decision (or one reviewed state)."""
 
1499
  if "answered 404" in str(e):
1500
  return ("הטבלה classes לא קיימת ב-Supabase. צרו אותה ב-SQL Editor (הפקודה ב-README); "
1501
  "אם כבר נוצרה, הריצו שם: notify pgrst, 'reload schema';")
1502
+ if any(col in str(e) for col in ("nicknames", "lessons", "homework", "'due'", "dailies", "subject")): # a table made before them
1503
  return f"לטבלה classes חסרות עמודות. הריצו ב-SQL Editor של Supabase: {MIGRATE_CLASSES}"
1504
  return f"Supabase לא זמין: {e}"
1505
 
1506
+ def save_class(a: SupabaseAuth, id: int | None, body: dict, actor: dict | None = None) -> dict:
1507
  """Checks a class from the panel ({"name", "emails": the student list, see `class_members`, "lessons": lesson
1508
  ids, "homeworks": [{"topic": a topic of one of them, "due": its ISO date, or ""}], each topic once; or, as
1509
  before a class could have several, "homework" and "due" for a single one; "dailies": [{"video": the id of
 
1561
  raise HTTPException(409, f"כבר יש כיתה בשם {taken}")
1562
  # a class that has no daily videos, and had none, is saved without them: a table made before them takes it
1563
  had = any(c["id"] == id and c.get("dailies") for c in a.classes())
1564
+ subject = str((actor or {}).get("subject") or "").strip()
1565
+ if (id is None and hasattr(a, "access_for") and actor and "admin" in actor.get("roles", ())
1566
+ and "developer" not in actor.get("roles", ()) and not subject):
1567
+ raise HTTPException(409, "לא הוגדר מקצוע למנהל/ת. מפתח/ת צריך להגדיר אותו בניטור.")
1568
+ a.save_class(id, name, emails, nicks, lessons, homeworks, dailies if dailies or had else None, subject)
1569
  except ClassConflict:
1570
  raise HTTPException(409, f"כבר יש כיתה בשם {name}")
1571
  except KeyError:
 
1575
  return {"ok": True}
1576
 
1577
  @app.post("/api/classes")
1578
+ def add_class(body: dict = Body(...), a: SupabaseAuth = Depends(teacher_only), actor: dict | None = Depends(signed_in)):
1579
+ return save_class(a, None, body, actor)
1580
 
1581
  @app.put("/api/classes/{class_id}")
1582
+ def edit_class(class_id: int, body: dict = Body(...), a: SupabaseAuth = Depends(teacher_only), actor: dict | None = Depends(signed_in)):
1583
+ return save_class(a, class_id, body, actor)
1584
 
1585
  @app.delete("/api/classes/{class_id}")
1586
  def delete_class(class_id: int, a: SupabaseAuth = Depends(teacher_only)):
app/scorer.py CHANGED
@@ -197,6 +197,8 @@ class Reference:
197
  @dataclass
198
  class ScorerConfig:
199
  flag_below: float = 50.0 # phoneme score under which a consonant gets a tip
 
 
200
  unrelated_ratio: float = 0.65 # normalised edit distance above which we say "different sentence"
201
  issue_below: float = 90.0 # phoneme score under which it is listed as imprecise
202
  max_issues: int = 8
@@ -619,7 +621,7 @@ class Scorer:
619
  heard_ph = "_" if sc.deleted else (i2t.get(sc.competitor) if sc.competitor is not None else None)
620
  check = self._check(tok, heard_ph)
621
  beyond.append(self._beyond_margin(tok, sc, heard_ph))
622
- flagged = (bool(sc.score < self.cfg.flag_below) and beyond[-1]
623
  and (tok.phoneme not in VOWELS or self._flag_vowel(toks, idx)))
624
  if idx in fit.inserted: # a vowel before this consonant (3.10): the reason its letter gives
625
  spec = self.rules.insertion
@@ -785,7 +787,7 @@ class Scorer:
785
  "consonant_window": g.consonant_window,
786
  "deleted_peak": round(float(np.exp(g.deleted_peak)), 3),
787
  "deleted_comp": round(float(np.exp(g.deleted_comp)), 3),
788
- "flag_below": cfg.flag_below, "issue_below": cfg.issue_below, "near_vowel_floor": cfg.near_vowel_floor,
789
  "word_min_weight": cfg.word_min_weight, "vowel_weight": 0.5, "unrelated_ratio": cfg.unrelated_ratio,
790
  "unrelated_cap": 30.0, "letter_good": LETTER_GOOD, "max_tips": max_tips, "max_issues": cfg.max_issues,
791
  "ref_min_mean": cfg.ref_min_mean, "margin_default": float(self.rules.scoring.get("margin_default", 0.0)),
@@ -874,10 +876,24 @@ def decode_audio(data: bytes) -> np.ndarray:
874
  return decode_audio_with_timing(data)[0]
875
 
876
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
877
  def load_scorer(model_id: str) -> Scorer:
878
  emitter = HFEmitter(model_id)
879
  vocab = Vocab(emitter.token_to_id)
880
- scorer = Scorer(emitter, vocab)
881
  # resolve every phoneme once at startup so missing symbols show up in the logs and /api/health
882
  from .phrases import PHRASES
883
  for p in PHRASES:
 
197
  @dataclass
198
  class ScorerConfig:
199
  flag_below: float = 50.0 # phoneme score under which a consonant gets a tip
200
+ flag_below_sound: dict[str, float] = field(default_factory=dict) # per sound, in place of flag_below (see
201
+ # FLAG_BELOW_BY_MODEL: it depends on the model)
202
  unrelated_ratio: float = 0.65 # normalised edit distance above which we say "different sentence"
203
  issue_below: float = 90.0 # phoneme score under which it is listed as imprecise
204
  max_issues: int = 8
 
621
  heard_ph = "_" if sc.deleted else (i2t.get(sc.competitor) if sc.competitor is not None else None)
622
  check = self._check(tok, heard_ph)
623
  beyond.append(self._beyond_margin(tok, sc, heard_ph))
624
+ flagged = (bool(sc.score < self.cfg.flag_below_sound.get(tok.sound, self.cfg.flag_below)) and beyond[-1]
625
  and (tok.phoneme not in VOWELS or self._flag_vowel(toks, idx)))
626
  if idx in fit.inserted: # a vowel before this consonant (3.10): the reason its letter gives
627
  spec = self.rules.insertion
 
787
  "consonant_window": g.consonant_window,
788
  "deleted_peak": round(float(np.exp(g.deleted_peak)), 3),
789
  "deleted_comp": round(float(np.exp(g.deleted_comp)), 3),
790
+ "flag_below": cfg.flag_below, "flag_below_sound": dict(cfg.flag_below_sound), "issue_below": cfg.issue_below, "near_vowel_floor": cfg.near_vowel_floor,
791
  "word_min_weight": cfg.word_min_weight, "vowel_weight": 0.5, "unrelated_ratio": cfg.unrelated_ratio,
792
  "unrelated_cap": 30.0, "letter_good": LETTER_GOOD, "max_tips": max_tips, "max_issues": cfg.max_issues,
793
  "ref_min_mean": cfg.ref_min_mean, "margin_default": float(self.rules.scoring.get("margin_default", 0.0)),
 
876
  return decode_audio_with_timing(data)[0]
877
 
878
 
879
+ # Per-sound flag thresholds, chosen per model on the Minerva dev split and checked on its test split
880
+ # (scripts/minerva_benchmark.py --sweep / --compare, with the TTS baselines). A threshold belongs to the model it was
881
+ # measured on: another model (a fine-tuned checkpoint) starts from the global flag_below until it is measured too.
882
+ FLAG_BELOW_BY_MODEL: dict[str, dict[str, float]] = {
883
+ # The base model hears a correct ح as ه/خ with scores in the 20s-40s: at 50 it flagged 12.7% of natives' ح;
884
+ # at 20, 5.6%, still catching 69% of خ and 71% of ه said for ح (was 76% / 75%).
885
+ "facebook/wav2vec2-xlsr-53-espeak-cv-ft": {"ħ": 20.0},
886
+ }
887
+
888
+
889
+ def scorer_config(model_id: str) -> ScorerConfig:
890
+ return ScorerConfig(flag_below_sound=dict(FLAG_BELOW_BY_MODEL.get(model_id, {})))
891
+
892
+
893
  def load_scorer(model_id: str) -> Scorer:
894
  emitter = HFEmitter(model_id)
895
  vocab = Vocab(emitter.token_to_id)
896
+ scorer = Scorer(emitter, vocab, scorer_config(model_id))
897
  # resolve every phoneme once at startup so missing symbols show up in the logs and /api/health
898
  from .phrases import PHRASES
899
  for p in PHRASES:
docs/grading-pipeline.md CHANGED
@@ -296,7 +296,7 @@ The base multilingual model also has one conservative built-in calibration: when
296
 
297
  Final per-token scores now exist. The decision to **flag** a token (show "heard as X" and a tip) needs all three of:
298
 
299
- 1. `score < flag_below` (50).
300
  2. The competitor beats the target by at least the pair's **margin** (rules §6.2):
301
  - substitution: `−gop ≥ margin(target, heard)`
302
  - deletion: `p_target ≤ deleted_peak − margin(target, "_")` in log space
@@ -479,6 +479,7 @@ The values live in code, not in the rules document. The `scoring:` block of `pro
479
  | `GopConfig.deleted_peak` / `deleted_comp` | 0.05 / 0.20 | deletion thresholds |
480
  | `GopConfig.consonant_window` | 4 frames | maximum context on each side of a consonant span; never crosses neighbours |
481
  | `ScorerConfig.flag_below` | 50 | max score for a flag and tip |
 
482
  | `ScorerConfig.issue_below` | 90 | max score to be listed as an issue |
483
  | `ScorerConfig.near_vowel_floor` | 90 | floor for neighbouring vowel qualities |
484
  | `ScorerConfig.word_min_weight` | 0.5 | weight of the weakest phoneme in a word |
 
296
 
297
  Final per-token scores now exist. The decision to **flag** a token (show "heard as X" and a tip) needs all three of:
298
 
299
+ 1. `score < flag_below` (50), or the sound's own threshold in `flag_below_sound`. That is set per model (`FLAG_BELOW_BY_MODEL`): for the base model ح uses 20, because it scores a correct ح in the 20s–40s (measured with `scripts/minerva_benchmark.py`).
300
  2. The competitor beats the target by at least the pair's **margin** (rules §6.2):
301
  - substitution: `−gop ≥ margin(target, heard)`
302
  - deletion: `p_target ≤ deleted_peak − margin(target, "_")` in log space
 
479
  | `GopConfig.deleted_peak` / `deleted_comp` | 0.05 / 0.20 | deletion thresholds |
480
  | `GopConfig.consonant_window` | 4 frames | maximum context on each side of a consonant span; never crosses neighbours |
481
  | `ScorerConfig.flag_below` | 50 | max score for a flag and tip |
482
+ | `ScorerConfig.flag_below_sound` | `{ħ: 20}` for the base model | per-sound replacement of `flag_below`, from `FLAG_BELOW_BY_MODEL[MODEL_ID]` |
483
  | `ScorerConfig.issue_below` | 90 | max score to be listed as an issue |
484
  | `ScorerConfig.near_vowel_floor` | 90 | floor for neighbouring vowel qualities |
485
  | `ScorerConfig.word_min_weight` | 0.5 | weight of the weakest phoneme in a word |
docs/trace-schema.ts CHANGED
@@ -90,6 +90,7 @@ export interface TraceConfig {
90
  deleted_peak: number; // deleted: p_target < deleted_peak and p_competitor < deleted_comp
91
  deleted_comp: number;
92
  flag_below: number; // a sound under this (and beyond its margin) is flagged
 
93
  issue_below: number; // a sound under this is listed as imprecise
94
  near_vowel_floor: number;
95
  word_min_weight: number;
 
90
  deleted_peak: number; // deleted: p_target < deleted_peak and p_competitor < deleted_comp
91
  deleted_comp: number;
92
  flag_below: number; // a sound under this (and beyond its margin) is flagged
93
+ flag_below_sound: Record<string, number>; // per sound, in place of flag_below (set per model)
94
  issue_below: number; // a sound under this is listed as imprecise
95
  near_vowel_floor: number;
96
  word_min_weight: number;
scripts/minerva_benchmark.py ADDED
@@ -0,0 +1,256 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Benchmark a phoneme model on held-out Minerva lines: false flags on native speech, and planted-mistake detection.
3
+
4
+ Usage: python scripts/minerva_benchmark.py --json base.json # MODEL_ID (or the default) on test.csv
5
+ python scripts/minerva_benchmark.py --model checkpoints/ihki-ft --json ft.json
6
+ python scripts/minerva_benchmark.py --refs --json base-refs.json # with the cached TTS baselines
7
+ python scripts/minerva_benchmark.py --compare base.json ft.json # side by side, no scoring
8
+ python scripts/minerva_benchmark.py --compare ft.json --threshold ħ=65 --threshold ʕ=40
9
+ python scripts/minerva_benchmark.py --sweep dev-ft.json # false flags vs detection per threshold
10
+
11
+ Every line is a native speaker saying it right, so
12
+ false flags = sounds the scorer marks down although they were said right (per sound, and what it heard instead);
13
+ detection = a learner's typical substitution, planted by scoring the line as if another sound was asked:
14
+ a clip with خ (x) scored as if ح (ħ) was written is a learner saying a Hebrew ח for ح.
15
+ The pairs are SWAPS below: (sound said, sound asked, its letter said, its letter asked). Run on dev.csv while choosing
16
+ thresholds or checkpoints and on test.csv for the numbers you report.
17
+
18
+ Every sound is scored once with the flag threshold open (flag_below=100) and its score saved, so --compare/--sweep can
19
+ apply any per-sound threshold afterwards: flagged at t = flagged at 100 and score < t (flag_below is used nowhere else).
20
+
21
+ Without --refs the numbers describe the acoustic model itself. --refs adds the TTS baseline the server uses, but only
22
+ from the local cache (no provider call): lines whose model answer was never generated are scored without it. A planted
23
+ sound never matches the baseline (the voice said the written sound), so with --refs detection is somewhat optimistic.
24
+ """
25
+ from __future__ import annotations
26
+
27
+ import argparse
28
+ import collections
29
+ import csv
30
+ import json
31
+ import os
32
+ import sys
33
+ from dataclasses import replace
34
+ from pathlib import Path
35
+
36
+ sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
37
+
38
+ from app.scorer import SAMPLE_RATE, decode_audio, frame_energy, load_scorer # noqa: E402
39
+
40
+ ROOT = Path(__file__).resolve().parent.parent
41
+ DEFAULT_THRESHOLD = 50.0 # ScorerConfig.flag_below
42
+ SWAPS = [ # (said, asked, letter said, letter asked): what a Hebrew speaker says instead of the Arabic sound
43
+ ("x", "ħ", "خ", "ح"), # Hebrew ח for ح
44
+ ("h", "ħ", "ه", "ح"), # ה for ح
45
+ ("ʔ", "ʕ", "ء", "ع"), # א for ع
46
+ ("ħ", "ʕ", "ح", "ع"), # ח for ع (voicing)
47
+ ("t", "tˤ", "ت", "ط"), # plain for emphatic
48
+ ("s", "sˤ", "س", "ص"),
49
+ ("d", "dˤ", "د", "ض"),
50
+ ("k", "q", "ك", "ق"), # Palestinian has no q in the bank; kept for completeness
51
+ ]
52
+
53
+
54
+ def swapped(phrase: dict, said: str, asked: str, l_said: str, l_asked: str) -> dict | None:
55
+ """The phrase with every `said` sound written as `asked` (None if it has none)."""
56
+ variants = []
57
+ for ar, ipa in phrase["variants"]:
58
+ toks = ipa.split(" ")
59
+ if said not in toks:
60
+ return None
61
+ variants.append((ar.replace(l_said, l_asked), " ".join(asked if t == said else t for t in toks)))
62
+ return {**phrase, "key": f"{phrase['key']}:{said}>{asked}", "variants": variants}
63
+
64
+
65
+ def phones(result: dict) -> list[dict]:
66
+ return [p for w in result.get("words", []) for p in w.get("phonemes", [])]
67
+
68
+
69
+ def cached_refs(scorer, tts):
70
+ """phrase -> [Reference] from the TTS cache only; never calls the provider."""
71
+ from app.arabic_diacritics import point_arabic
72
+ from app.tts import RAEF_VOICE_ID
73
+ memo = {}
74
+
75
+ def get(phrase: dict) -> list:
76
+ text = point_arabic(*phrase["variants"][0])
77
+ if text not in memo:
78
+ memo[text] = []
79
+ if tts is not None and tts.cached(text, RAEF_VOICE_ID):
80
+ ref = scorer.reference(decode_audio(tts.wav(text, RAEF_VOICE_ID)[0]), phrase)
81
+ memo[text] = [ref] if ref is not None else []
82
+ return memo[text]
83
+ return get
84
+
85
+
86
+ def run(model: str, csv_path: Path, limit: int, use_refs: bool) -> dict:
87
+ scorer = load_scorer(model)
88
+ production = {"*": scorer.cfg.flag_below, **scorer.cfg.flag_below_sound} # what the server would apply
89
+ scorer.cfg = replace(scorer.cfg, flag_below=100.0, flag_below_sound={}) # open: thresholds are applied afterwards
90
+ refs_for = lambda phrase: []
91
+ if use_refs:
92
+ from dotenv import load_dotenv
93
+ from app.tts import load_tts
94
+ load_dotenv(ROOT / ".env")
95
+ refs_for = cached_refs(scorer, load_tts())
96
+ rows = list(csv.DictReader(open(csv_path, encoding="utf-8")))[: limit or None]
97
+ tokens, scores, unrelated, with_refs = [], [], 0, 0
98
+ for n, row in enumerate(rows, 1):
99
+ wav = decode_audio((csv_path.parent / row["audio"]).read_bytes())
100
+ logp = scorer.emit(wav)
101
+ energy, duration = frame_energy(wav, len(logp)), len(wav) / SAMPLE_RATE
102
+ phrase = {"cat": "lab", "key": row["item"], "he": row["item"], "variants": [(row["ar"], row["ipa"])]}
103
+ refs = refs_for(phrase)
104
+ with_refs += bool(refs)
105
+ res = scorer.score_logp(logp, phrase, refs, False, duration, energy)
106
+ if res.get("error") or res.get("unrelated"):
107
+ unrelated += 1
108
+ continue
109
+ scores.append(res["score"])
110
+ for p in phones(res):
111
+ tokens.append({"kind": "native", "sound": p.get("sound") or p["ipa"], "score": round(p["score"], 1),
112
+ "flag": bool(p.get("flagged")), "heard": p.get("heard") or "_"})
113
+ for said, asked, l_said, l_asked in SWAPS:
114
+ planted = swapped(phrase, said, asked, l_said, l_asked)
115
+ if planted is None:
116
+ continue
117
+ r = scorer.score_logp(logp, planted, refs, False, duration, energy)
118
+ if r.get("error") or r.get("unrelated"):
119
+ continue
120
+ for p in phones(r):
121
+ if asked in (p["ipa"], p.get("sound")):
122
+ tokens.append({"kind": f"{said}>{asked}", "sound": asked, "score": round(p["score"], 1),
123
+ "flag": bool(p.get("flagged")), "heard": p.get("heard") or "_"})
124
+ if n % 50 == 0:
125
+ print(f"{n}/{len(rows)}", file=sys.stderr)
126
+ return {"model": model, "csv": str(csv_path), "refs": use_refs, "thresholds": production, "lines": len(rows), "with_refs": with_refs,
127
+ "unrelated": unrelated, "mean_score": round(sum(scores) / len(scores), 2) if scores else None,
128
+ "tokens": tokens}
129
+
130
+
131
+ def flagged(tok: dict, thresholds: dict[str, float]) -> bool:
132
+ return tok["flag"] and tok["score"] < thresholds.get(tok["sound"], thresholds.get("*", DEFAULT_THRESHOLD))
133
+
134
+
135
+ def thresholds_of(run_: dict, override: dict[str, float]) -> dict[str, float]:
136
+ """The run's production thresholds (the model's FLAG_BELOW_BY_MODEL), with --threshold on top."""
137
+ return {**run_.get("thresholds", {}), **override}
138
+
139
+
140
+ def summary(run_: dict, thresholds: dict[str, float]) -> dict:
141
+ """False flags per sound and detection per pair, at these thresholds."""
142
+ sounds = collections.defaultdict(lambda: {"right": 0, "false_flags": 0, "heard": collections.Counter()})
143
+ pairs = {f"{s}>{a}": {"planted": 0, "caught": 0, "caught_as_said": 0} for s, a, *_ in SWAPS}
144
+ for t in run_["tokens"]:
145
+ hit = flagged(t, thresholds)
146
+ if t["kind"] == "native":
147
+ s = sounds[t["sound"]]
148
+ s["right"] += 1
149
+ if hit:
150
+ s["false_flags"] += 1
151
+ s["heard"][t["heard"]] += 1
152
+ else:
153
+ p = pairs[t["kind"]]
154
+ p["planted"] += 1
155
+ p["caught"] += hit
156
+ p["caught_as_said"] += hit and t["heard"] == t["kind"].split(">")[0]
157
+ rate = lambda a, b: round(a / b, 4) if b else None
158
+ right = sum(s["right"] for s in sounds.values())
159
+ false = sum(s["false_flags"] for s in sounds.values())
160
+ return {
161
+ "frr": rate(false, right),
162
+ "sounds": {k: {"right": v["right"], "false_flags": v["false_flags"], "frr": rate(v["false_flags"], v["right"]),
163
+ "heard": dict(v["heard"].most_common(5))}
164
+ for k, v in sorted(sounds.items(), key=lambda kv: -(kv[1]["false_flags"] / max(1, kv[1]["right"])))},
165
+ "pairs": {k: {**v, "detection": rate(v["caught"], v["planted"]), "as_said": rate(v["caught_as_said"], v["planted"])}
166
+ for k, v in pairs.items()},
167
+ }
168
+
169
+
170
+ def pct(x) -> str:
171
+ return " - " if x is None else f"{100 * x:5.1f}%"
172
+
173
+
174
+ def label(r: dict) -> str:
175
+ return (Path(r["model"]).name + (" +refs" if r.get("refs") else ""))[-22:]
176
+
177
+
178
+ def report(runs: list[dict], thresholds: dict[str, float], min_right: int = 30) -> None:
179
+ sums = [summary(r, thresholds_of(r, thresholds)) for r in runs]
180
+ print(f"\n{'':<14}" + " ".join(f"{label(r):>22}" for r in runs))
181
+ print(f"{'lines':<14}" + " ".join(f"{r['lines'] - r['unrelated']:>22}" for r in runs))
182
+ print(f"{'with refs':<14}" + " ".join(f"{r.get('with_refs', 0):>22}" for r in runs))
183
+ print(f"{'mean score':<14}" + " ".join(f"{r['mean_score']:>22}" for r in runs))
184
+ print(f"{'false flags':<14}" + " ".join(f"{pct(s['frr']):>22}" for s in sums))
185
+ print(f"{'thresholds':<14}" + " ".join(
186
+ f"{', '.join(f'{k}={v:g}' for k, v in thresholds_of(r, thresholds).items()) or '*=50':>22}" for r in runs))
187
+ print("\nfalse flags per sound (native speech said right; lower is better)")
188
+ for k in [k for k, v in sums[0]["sounds"].items() if v["right"] >= min_right]:
189
+ cells = []
190
+ for s in sums:
191
+ v = s["sounds"].get(k)
192
+ cells.append(f"{pct(v['frr'])} {json.dumps(v['heard'], ensure_ascii=False)[:14]:<14}" if v else " " * 21)
193
+ print(f" {k:<5} n={sums[0]['sounds'][k]['right']:<5}" + " ".join(f"{c:>22}" for c in cells))
194
+ print("\ndetection of planted mistakes (said>asked; higher is better; in brackets: heard as the sound said)")
195
+ for k in sums[0]["pairs"]:
196
+ cells = [f"{pct(s['pairs'][k]['detection'])} ({pct(s['pairs'][k]['as_said']).strip()})" for s in sums]
197
+ print(f" {k:<6} n={sums[0]['pairs'][k]['planted']:<5}" + " ".join(f"{c:>22}" for c in cells))
198
+
199
+
200
+ def sweep(run_: dict, steps=range(20, 100, 5)) -> None:
201
+ """Per asked sound: false flags on native speech vs detection of each planted pair, for thresholds 20..95."""
202
+ print(f"\n{label(run_)} ({run_['csv']})")
203
+ for asked in dict.fromkeys(a for _, a, *_ in SWAPS):
204
+ pairs = [f"{s}>{a}" for s, a, *_ in SWAPS if a == asked]
205
+ native = [t for t in run_["tokens"] if t["kind"] == "native" and t["sound"] == asked]
206
+ planted = {p: [t for t in run_["tokens"] if t["kind"] == p] for p in pairs}
207
+ if not native or not any(planted.values()):
208
+ continue
209
+ print(f"\n {asked}: n={len(native)} native; " + ", ".join(f"{p} n={len(v)}" for p, v in planted.items()))
210
+ print(f" {'thr':>4} {'false':>7} " + " ".join(f"{p:>7}" for p in pairs))
211
+ for th in steps:
212
+ th_ = {asked: th}
213
+ ff = sum(flagged(t, th_) for t in native) / len(native)
214
+ det = [sum(flagged(t, th_) for t in v) / len(v) if v else None for v in planted.values()]
215
+ now = run_.get("thresholds", {})
216
+ mark = " <- now" if th == now.get(asked, now.get("*", DEFAULT_THRESHOLD)) else ""
217
+ print(f" {th:>4} {pct(ff)} " + " ".join(f"{pct(d)}" for d in det) + mark)
218
+
219
+
220
+ def parse_thresholds(items: list[str]) -> dict[str, float]:
221
+ out = {}
222
+ for item in items:
223
+ sound, _, value = item.partition("=")
224
+ out[sound] = float(value)
225
+ return out
226
+
227
+
228
+ def main() -> int:
229
+ ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
230
+ ap.add_argument("--model", default=os.environ.get("MODEL_ID", "facebook/wav2vec2-xlsr-53-espeak-cv-ft"))
231
+ ap.add_argument("--csv", type=Path, default=ROOT / "data" / "minerva" / "test.csv")
232
+ ap.add_argument("--limit", type=int, default=0, help="at most this many lines (0: all)")
233
+ ap.add_argument("--refs", action="store_true", help="use the cached TTS baselines, as the server does")
234
+ ap.add_argument("--json", type=Path, help="write the run (every sound's score) here")
235
+ ap.add_argument("--compare", type=Path, nargs="+", help="print saved runs side by side instead of scoring")
236
+ ap.add_argument("--sweep", type=Path, nargs="+", help="print threshold sweeps of saved runs")
237
+ ap.add_argument("--threshold", action="append", default=[], metavar="SOUND=T", help="per-sound flag threshold")
238
+ args = ap.parse_args()
239
+ thresholds = parse_thresholds(args.threshold)
240
+ load = lambda p: json.loads(p.read_text(encoding="utf-8"))
241
+ if args.sweep:
242
+ for p in args.sweep:
243
+ sweep(load(p))
244
+ return 0
245
+ if args.compare:
246
+ report([load(p) for p in args.compare], thresholds)
247
+ return 0
248
+ result = run(args.model, args.csv, args.limit, args.refs)
249
+ if args.json:
250
+ args.json.write_text(json.dumps(result, ensure_ascii=False), encoding="utf-8")
251
+ report([result], thresholds)
252
+ return 0
253
+
254
+
255
+ if __name__ == "__main__":
256
+ sys.exit(main())
scripts/minerva_dataset.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Cut every reviewed Minerva line from the local videos into a training set, split by video.
3
+
4
+ Usage: python scripts/minerva_dataset.py # -> data/minerva/{clips/,train.csv,dev.csv,test.csv}
5
+ python scripts/minerva_dataset.py --test 5 --dev 4 --seed 1
6
+
7
+ Nothing is uploaded: the clips stay on this machine (data/minerva/ is git-ignored). The split is by video, never by
8
+ line, so a speaker or a scene heard in training is never in dev/test. The CSVs have the columns train/finetune.py
9
+ reads (`audio,ipa`) plus `item,video,ar` for the benchmark (scripts/minerva_benchmark.py). Clips already cut are
10
+ kept, so a rerun only cuts what is missing.
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import argparse
15
+ import csv
16
+ import random
17
+ import sys
18
+ from pathlib import Path
19
+
20
+ sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
21
+
22
+ from app import lab # noqa: E402
23
+ from scripts.import_minerva import source_file, wav_segment # noqa: E402
24
+
25
+ ROOT = Path(__file__).resolve().parent.parent
26
+
27
+
28
+ def split(videos: list[dict], n_test: int, n_dev: int, seed: int) -> dict[str, str]:
29
+ """{video id: "train" | "dev" | "test"}, reproducible for a seed."""
30
+ ids = sorted(v["id"] for v in videos)
31
+ random.Random(seed).shuffle(ids)
32
+ return {vid: "test" if k < n_test else "dev" if k < n_test + n_dev else "train" for k, vid in enumerate(ids)}
33
+
34
+
35
+ def main() -> int:
36
+ ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
37
+ ap.add_argument("--videos-dir", type=Path, default=Path("/home/eyalshw/Videos/minerva"))
38
+ ap.add_argument("--out", type=Path, default=ROOT / "data" / "minerva")
39
+ ap.add_argument("--test", type=int, default=5, help="videos held out for the benchmark")
40
+ ap.add_argument("--dev", type=int, default=4, help="videos held out for choosing checkpoints and thresholds")
41
+ ap.add_argument("--seed", type=int, default=0)
42
+ args = ap.parse_args()
43
+
44
+ videos = list(lab.minerva_metadata())
45
+ parts = split(videos, args.test, args.dev, args.seed)
46
+ clips = args.out / "clips"
47
+ clips.mkdir(parents=True, exist_ok=True)
48
+ rows: dict[str, list[dict]] = {"train": [], "dev": [], "test": []}
49
+ cut = 0
50
+ for video in videos:
51
+ source = source_file(args.videos_dir, video["id"])
52
+ for segment in video["segments"]:
53
+ path = clips / f"{video['id']}-{segment['line']:02d}.wav"
54
+ if not path.exists():
55
+ path.write_bytes(wav_segment(source, segment["start"], segment["end"]))
56
+ cut += 1
57
+ rows[parts[video["id"]]].append({"audio": str(path.relative_to(args.out)), "ipa": segment["ipa"],
58
+ "item": segment["item"], "video": video["id"], "ar": segment["ar"]})
59
+ print(f"{parts[video['id']]:<5} {video['id']} {len(video['segments']):>3} lines {video['title']}")
60
+ for part, items in rows.items():
61
+ with open(args.out / f"{part}.csv", "w", encoding="utf-8", newline="") as f:
62
+ w = csv.DictWriter(f, fieldnames=["audio", "ipa", "item", "video", "ar"])
63
+ w.writeheader()
64
+ w.writerows(items)
65
+ seconds = sum(s["end"] - s["start"] for v in videos for s in v["segments"])
66
+ print(f"cut {cut} new clips; " + ", ".join(f"{p} {len(r)}" for p, r in rows.items())
67
+ + f" lines; {seconds / 60:.0f} min in all -> {args.out}")
68
+ return 0
69
+
70
+
71
+ if __name__ == "__main__":
72
+ sys.exit(main())
static/guide.html CHANGED
@@ -13,7 +13,7 @@
13
  :root{
14
  --bg:#EEF0E8; --surface:#FAFBF6; --ink:#1C241D; --muted:#5E685C; --line:#D5DACB;
15
  --olive:#4B6A2C; --olive-deep:#36501D; --on-olive:#FFFFFF; --olive-soft:#E3EAD6;
16
- --sumac:#A3303F; --sumac-bg:#F6E3E3; --ok:#2F7A4A; --ok-bg:#E1F0E4; --amber:#8A5E0E; --amber-bg:#F5ECD8; --gold:#B8860B; --gold-bg:#F7EBC6;
17
  --f-display:"Secular One","Assistant",system-ui,sans-serif;
18
  --f-body:"Assistant",system-ui,"Segoe UI",Arial,sans-serif;
19
  --f-tr:"Noto Sans Hebrew","Arial Hebrew",sans-serif;
@@ -21,12 +21,12 @@
21
  @media (prefers-color-scheme: dark){:root:not([data-theme="light"]){
22
  --bg:#141915; --surface:#1D241F; --ink:#E7EBE2; --muted:#9AA595; --line:#2F3830;
23
  --olive:#93B85F; --olive-deep:#6E8F42; --on-olive:#10150F; --olive-soft:#26301F;
24
- --sumac:#E77B87; --sumac-bg:#3A1E23; --ok:#6CC08A; --ok-bg:#1C3324; --amber:#E0B45A; --amber-bg:#3A2F17; --gold:#E8C35A; --gold-bg:#3A3217;
25
  color-scheme:dark}}
26
  :root[data-theme="dark"]{
27
  --bg:#141915; --surface:#1D241F; --ink:#E7EBE2; --muted:#9AA595; --line:#2F3830;
28
  --olive:#93B85F; --olive-deep:#6E8F42; --on-olive:#10150F; --olive-soft:#26301F;
29
- --sumac:#E77B87; --sumac-bg:#3A1E23; --ok:#6CC08A; --ok-bg:#1C3324; --amber:#E0B45A; --amber-bg:#3A2F17; --gold:#E8C35A; --gold-bg:#3A3217;
30
  color-scheme:dark}
31
  *{box-sizing:border-box}
32
  body{background:var(--bg);color:var(--ink);font:400 17px/1.6 var(--f-body);margin:0;padding-inline:max(16px,env(safe-area-inset-left),env(safe-area-inset-right));padding-block:max(18px,env(safe-area-inset-top)) max(48px,env(safe-area-inset-bottom));-webkit-text-size-adjust:100%}
@@ -69,6 +69,9 @@ section{display:flex;flex-direction:column;gap:16px}
69
  .m-today div{border:1px solid var(--line);border-radius:12px;padding:6px 4px;text-align:center;font:700 13px/1.25 var(--f-body);background:var(--bg)}
70
  .m-today div small{display:block;font-weight:400;color:var(--muted);font-size:11px}
71
  .m-today .hot{border-color:var(--olive);background:var(--olive-soft)}
 
 
 
72
  .m-nav{display:flex;gap:4px;flex-wrap:wrap}
73
  .m-nav span:not(.n){font:600 12px/1 var(--f-body);padding:6px 8px;border-radius:8px;color:var(--muted)}
74
  .m-nav span.on:not(.n){background:var(--olive);color:var(--on-olive)}
@@ -180,6 +183,8 @@ section{display:flex;flex-direction:column;gap:16px}
180
  .tips{display:grid;grid-template-columns:repeat(auto-fill,minmax(230px,1fr));gap:12px}
181
  .tip{border-inline-start:3px solid var(--olive);padding:4px 12px;display:flex;flex-direction:column;gap:4px}
182
  .tip p{font-size:15.5px;color:var(--muted)}
 
 
183
  .jump{position:sticky;top:env(safe-area-inset-top,0px);z-index:5;display:flex;gap:6px;overflow-x:auto;scrollbar-width:none;margin-inline:-16px;padding:8px 16px;background:var(--bg);border-bottom:1px solid var(--line)}
184
  .jump::-webkit-scrollbar{display:none}
185
  .jump a{flex:none;padding:6px 12px;border-radius:999px;border:1px solid var(--line);background:var(--surface);color:var(--ink);text-decoration:none;font:700 14px/1.2 var(--f-body)}
@@ -218,10 +223,10 @@ a,button{-webkit-tap-highlight-color:transparent}
218
  <header class="top">
219
  <span class="eyebrow">אהלא וסהלא · מדריך קצר</span>
220
  <h1>איך מתרגלים במסלול</h1>
221
- <p class="lead">המסלול הוא הדרך שלכם בין השיעורים. כל עיגול בדרך הוא נושא: בוחרים אותו, שומעים, אומרים בקול ומקבלים ציון על ההגייה. כל שיעור נפתח במילים החדשות שלו ובמשחק עליהן, כדי שתכירו אותן לפני שאומרים משפטים. כאן תמצאו מה עושה כל כפתור, ומה ההבדל בין סוגי הנושאים.</p>
222
  </header>
223
 
224
- <nav class="jump" aria-label="תוכן המדריך"><a href="#path">המסלול</a><a href="#states">העיגולים</a><a href="#kinds">סוגי נושאים</a><a href="#practice">התרגול</a><a href="#settings">הגדרות</a><a href="#tips">טיפים</a></nav>
225
 
226
  <!-- 1. the path screen -->
227
  <section id="path">
@@ -231,13 +236,14 @@ a,button{-webkit-tap-highlight-color:transparent}
231
  </div>
232
  <div class="pair">
233
  <div class="phone" aria-label="דוגמה של מסך המסלול">
234
- <div class="m-head at"><span class="n">1</span><span class="m-brand">אהלא וסהלא</span><span class="m-pill">כיתה ב׳ ▾</span><span class="m-drive">🚗 מצב נסיעה</span></div>
235
  <div class="m-today at l"><span class="n">2</span>
236
  <div class="hot">סרטון יומי<small>יום 3 · ברכות</small></div>
237
  <div>תרגול יומי<small>10 משפטים</small></div>
238
  <div>שיעורי בית<small>עוד יומיים</small></div>
239
  </div>
240
- <div class="m-nav at"><span class="n">3</span><span class="on">מסלול</span><span>ספריה דיגיטלית</span><span>חבר מביא חבר</span></div>
 
241
  <div class="m-level">שלב א׳<small>8 מתוך 10 שיעורים מוכנים</small></div>
242
  <div class="m-chapter at l"><span class="n">4</span><div>שיעור 3<i></i></div><small>תורגלו 22 מתוך 40</small></div>
243
  <div class="road">
@@ -256,9 +262,9 @@ a,button{-webkit-tap-highlight-color:transparent}
256
  </div>
257
  </div>
258
  <ol class="key">
259
- <li><span class="n">1</span><div><b>הכיתה ומצב נסיעה</b><span class="d">לחיצה על שם הכיתה מראה את חברי הכיתה, או מחליפה כיתה אם אתם ביותר מאחת. <b style="display:inline">מצב נסיעה</b> מקריא את המשפט, מקשיב לתשובה ואומר את ההערכה בקול, בלי להסתכל על המסך.</span></div></li>
260
  <li><span class="n">2</span><div><b>שלושה קיצורים להיום</b><span class="d"><b style="display:inline">סרטון יומי</b> שהמורה קבע להיום (מודגש עד שצופים). <b style="display:inline">תרגול יומי</b>: סבב של 10 משפטים, חצי לשיפור וחצי חדשים מהשיעור הנוכחי. <b style="display:inline">שיעורי בית</b>: פותח ישר את הנושא הקרוב להגשה.</span></div></li>
261
- <li><span class="n">3</span><div><b>לשוניות</b><span class="d">המסלול, הספרייה הדיגיטלית (סרטונים וטקסטים) וחבר מביא חבר.</span></div></li>
262
  <li><span class="n">4</span><div><b>כותרת השיעור</b><span class="d">הפס מראה כמה מהשיעור תורגל. לחיצה עליה פותחת את הנושא הבא שעוד לא נגמר. בסוף כל שיעור יש גביע 🏆 שמזהיב כשהשיעור הושלם.</span></div></li>
263
  <li><span class="n">5</span><div><b>הנושא של עכשיו</b><span class="d">מסומן בהילה ובבועה „התחילו” או „המשך”. אם גללתם רחוק, הכפתור „חזרה לנושא הנוכחי” מחזיר אליו.</span></div></li>
264
  <li><span class="n">6</span><div><b>כל הנושאים פתוחים</b><span class="d">אפשר לפתוח כל נושא בכל שיעור, גם בלי לסיים את מה שלפניו.</span></div></li>
@@ -278,10 +284,36 @@ a,button{-webkit-tap-highlight-color:transparent}
278
  <div class="state"><div class="ball done"><span class="badge">✓</span>2</div><b>הושלם</b><span>כל המשפטים נאמרו לפחות פעם אחת</span></div>
279
  <div class="state"><div class="ball gold"><span class="badge">★</span>1</div><b>זהב</b><span>כל המשפטים קיבלו „מצוין” (85 ומעלה)</span></div>
280
  <div class="state"><div class="ball" style="border-color:var(--amber);margin-top:22px"><div class="tag hw" style="font-size:10px">עוד 3 ימים</div>5</div><b>שיעורי בית</b><span>הבועה סופרת את הימים עד ההגשה</span></div>
 
281
  </div>
282
  </section>
283
 
284
- <!-- 3. topic kinds -->
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
285
  <section id="kinds">
286
  <div class="sechead">
287
  <h2>סוגי הנושאים</h2>
@@ -332,7 +364,7 @@ a,button{-webkit-tap-highlight-color:transparent}
332
  </div>
333
  </section>
334
 
335
- <!-- 4. the practice screen -->
336
  <section id="practice">
337
  <div class="sechead">
338
  <h2>מסך התרגול</h2>
@@ -340,7 +372,7 @@ a,button{-webkit-tap-highlight-color:transparent}
340
  </div>
341
  <div class="pair">
342
  <div class="phone" aria-label="דוגמה של מסך התרגול">
343
- <div class="m-bar at"><span class="n">1</span><span class="m-btn p">→ חזרה למסלול</span><span class="m-sp"></span><span class="m-btn">☰ רשימה</span><span class="m-btn gear">⚙</span></div>
344
  <div class="m-card">
345
  <div class="m-meta"><span>3 / 10</span><span>משפטים א׳</span></div>
346
  <div class="at l" style="display:flex;flex-direction:column;gap:6px;padding-inline:14px"><span class="n">2</span>
@@ -360,7 +392,7 @@ a,button{-webkit-tap-highlight-color:transparent}
360
  </div>
361
  </div>
362
  <ol class="key">
363
- <li><span class="n">1</span><div><b>שורת הכלים</b><span class="d"><b style="display:inline">חזרה למסלול</b> מימין. משמאל <b style="display:inline">רשימת המשפטים</b>, עם הציון הכי טוב בכל משפט, ו־⚙ <b style="display:inline">הגדרות ההשמעה</b> בפינה השמאלית העליונה (פירוט בהמשך).</span></div></li>
364
  <li><span class="n">2</span><div><b>המשפט</b><span class="d">מה שצריך לומר, ומעליו המיקום בנושא.</span></div></li>
365
  <li><span class="n">3</span><div><b>המיקרופון</b><span class="d">לוחצים פעם אחת ומדברים, וההקלטה נעצרת לבד. בלי מיקרופון אפשר לבחור <b style="display:inline">תרגול שקט</b> ולהרכיב את המשפט ממילים.</span></div></li>
366
  <li><span class="n">4</span><div><b>הציון</b><span class="d">כל מילה נצבעת לפי מה שנשמע: ירוק נאמר נכון, צהוב כמעט. מתחת מופיעים טיפים לשיפור.</span></div></li>
@@ -374,32 +406,46 @@ a,button{-webkit-tap-highlight-color:transparent}
374
  </div>
375
  </section>
376
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
377
 
378
- <!-- 5. playback settings -->
379
  <section id="settings">
380
  <div class="sechead">
381
  <h2>הגדרות השמעה ⚙</h2>
382
- <p>במסך התרגול, בפינה השמאלית העליונה, יש כפתור ⚙. הוא פותח חלון עם שלוש הגדרות. הבחירה נשמרת במכשיר לפעם הבאה.</p>
383
  </div>
384
  <div class="pair">
385
  <div class="phone" aria-label="דוגמה של חלון הגדרות ההשמעה">
386
  <div class="m-bar"><span class="m-btn p">→ חזרה למסלול</span><span class="m-sp"></span><span class="m-btn">☰ רשימה</span><span class="m-btn gear hl">⚙</span></div>
387
  <div class="dlg">
388
  <div class="dlg-h"><b>הגדרות השמעה</b><span class="m-btn">סגירה</span></div>
389
- <div class="row at l"><span class="n">1</span><span>קול ההשמעה</span><span class="sel">רַאאִף</span></div>
390
- <div class="row at l"><span class="n">2</span><span>מהירות</span><span class="seg"><i>x0.8</i><i class="on">x1</i><i>x1.5</i></span></div>
391
- <div class="row at l"><span class="n">3</span><span>הקראת המשפט בעברית</span><span class="tg on" aria-hidden="true"></span></div>
392
  </div>
393
  </div>
394
  <ol class="key">
395
- <li><span class="n">1</span><div><b>קול ההשמעה</b><span class="d"><b style="display:inline">רַאאִף</b> מקריא את כל התשובות, הסיפורים והשיחות.</span></div></li>
396
- <li><span class="n">2</span><div><b>מהירות</b><span class="d"><b style="display:inline">x0.8</b> לאט יותר, כדי לשמוע כל הברה. <b style="display:inline">x1</b> רגיל. <b style="display:inline">x1.5</b> מהיר, לאימון הבנת שמיעה.</span></div></li>
397
- <li><span class="n">3</span><div><b>הקראת המשפט בעברית</b><span class="d">כשמסומן, כל משפט חדש מוקרא בקול בעברית לפני שעונים, כך שאפשר לתרגל בלי לקרוא מהמסך. בנושאי ערבית ← עברית אין הקראה, כי העברית היא התשובה.</span></div></li>
398
  </ol>
399
  </div>
400
  </section>
401
 
402
- <!-- 6. tips -->
403
  <section id="tips">
404
  <div class="sechead"><h2>כמה טיפים</h2></div>
405
  <div class="tips">
 
13
  :root{
14
  --bg:#EEF0E8; --surface:#FAFBF6; --ink:#1C241D; --muted:#5E685C; --line:#D5DACB;
15
  --olive:#4B6A2C; --olive-deep:#36501D; --on-olive:#FFFFFF; --olive-soft:#E3EAD6;
16
+ --sumac:#A3303F; --sumac-bg:#F6E3E3; --ok:#2F7A4A; --ok-bg:#E1F0E4; --amber:#8A5E0E; --amber-bg:#F5ECD8; --orange:#C45F00; --gold:#B8860B; --gold-bg:#F7EBC6;
17
  --f-display:"Secular One","Assistant",system-ui,sans-serif;
18
  --f-body:"Assistant",system-ui,"Segoe UI",Arial,sans-serif;
19
  --f-tr:"Noto Sans Hebrew","Arial Hebrew",sans-serif;
 
21
  @media (prefers-color-scheme: dark){:root:not([data-theme="light"]){
22
  --bg:#141915; --surface:#1D241F; --ink:#E7EBE2; --muted:#9AA595; --line:#2F3830;
23
  --olive:#93B85F; --olive-deep:#6E8F42; --on-olive:#10150F; --olive-soft:#26301F;
24
+ --sumac:#E77B87; --sumac-bg:#3A1E23; --ok:#6CC08A; --ok-bg:#1C3324; --amber:#E0B45A; --amber-bg:#3A2F17; --orange:#F2A04A; --gold:#E8C35A; --gold-bg:#3A3217;
25
  color-scheme:dark}}
26
  :root[data-theme="dark"]{
27
  --bg:#141915; --surface:#1D241F; --ink:#E7EBE2; --muted:#9AA595; --line:#2F3830;
28
  --olive:#93B85F; --olive-deep:#6E8F42; --on-olive:#10150F; --olive-soft:#26301F;
29
+ --sumac:#E77B87; --sumac-bg:#3A1E23; --ok:#6CC08A; --ok-bg:#1C3324; --amber:#E0B45A; --amber-bg:#3A2F17; --orange:#F2A04A; --gold:#E8C35A; --gold-bg:#3A3217;
30
  color-scheme:dark}
31
  *{box-sizing:border-box}
32
  body{background:var(--bg);color:var(--ink);font:400 17px/1.6 var(--f-body);margin:0;padding-inline:max(16px,env(safe-area-inset-left),env(safe-area-inset-right));padding-block:max(18px,env(safe-area-inset-top)) max(48px,env(safe-area-inset-bottom));-webkit-text-size-adjust:100%}
 
69
  .m-today div{border:1px solid var(--line);border-radius:12px;padding:6px 4px;text-align:center;font:700 13px/1.25 var(--f-body);background:var(--bg)}
70
  .m-today div small{display:block;font-weight:400;color:var(--muted);font-size:11px}
71
  .m-today .hot{border-color:var(--olive);background:var(--olive-soft)}
72
+ .m-rewards{display:grid;grid-template-columns:46px 1fr auto;align-items:center;gap:8px;padding:8px 10px;border:1px solid var(--olive);border-radius:12px;background:var(--surface)}
73
+ .m-week{width:42px;height:42px;border-radius:50%;display:grid;place-items:center;background:var(--amber-bg);border:2px solid var(--orange);color:var(--orange);font:700 13px var(--f-body)}
74
+ .m-rewards b{display:block;font-size:13px}.m-rewards small{display:block;color:var(--orange);font-size:10.5px;font-weight:700}.m-fire{color:var(--olive);font-weight:700;font-size:11px;text-align:left}
75
  .m-nav{display:flex;gap:4px;flex-wrap:wrap}
76
  .m-nav span:not(.n){font:600 12px/1 var(--f-body);padding:6px 8px;border-radius:8px;color:var(--muted)}
77
  .m-nav span.on:not(.n){background:var(--olive);color:var(--on-olive)}
 
183
  .tips{display:grid;grid-template-columns:repeat(auto-fill,minmax(230px,1fr));gap:12px}
184
  .tip{border-inline-start:3px solid var(--olive);padding:4px 12px;display:flex;flex-direction:column;gap:4px}
185
  .tip p{font-size:15.5px;color:var(--muted)}
186
+ .reward-demo{background:var(--surface);border:1px solid var(--line);border-radius:18px;padding:16px;display:flex;flex-direction:column;gap:12px}.reward-stats{display:grid;grid-template-columns:repeat(4,1fr);gap:7px}.reward-stats div{padding:9px 4px;border-radius:10px;background:var(--olive-soft);text-align:center}.reward-stats div:first-child{background:var(--amber-bg);box-shadow:inset 0 0 0 1px var(--orange)}.reward-stats div:first-child b{color:var(--orange)}.reward-stats b{display:block;color:var(--olive);font:400 23px/1.1 var(--f-display)}.reward-stats small{font-size:11px;color:var(--muted)}
187
+ .reward-lesson{font:400 19px/1.2 var(--f-display);color:var(--olive);border-bottom:1px solid var(--line);padding-bottom:5px}.reward-subject{font-weight:700;font-size:14px}.beads{display:flex;gap:7px;flex-wrap:wrap}.bead{width:28px;height:28px;border-radius:50%;border:3px solid #52624b;background:radial-gradient(circle at 32% 27%,#dce7d4 0 9%,#769064 23%,#405136 72%);box-shadow:inset -2px -3px 3px rgb(0 0 0/.25)}.bead.gold{border-color:#9b690b;background:radial-gradient(circle at 32% 27%,#fff3a7 0 9%,#e4b83e 27%,#9d6509 75%)}
188
  .jump{position:sticky;top:env(safe-area-inset-top,0px);z-index:5;display:flex;gap:6px;overflow-x:auto;scrollbar-width:none;margin-inline:-16px;padding:8px 16px;background:var(--bg);border-bottom:1px solid var(--line)}
189
  .jump::-webkit-scrollbar{display:none}
190
  .jump a{flex:none;padding:6px 12px;border-radius:999px;border:1px solid var(--line);background:var(--surface);color:var(--ink);text-decoration:none;font:700 14px/1.2 var(--f-body)}
 
223
  <header class="top">
224
  <span class="eyebrow">אהלא וסהלא · מדריך קצר</span>
225
  <h1>איך מתרגלים במסלול</h1>
226
+ <p class="lead">המסלול הוא הדרך שלכם בין השיעורים. לומדים מילים, מתרגלים משפטים בקול, מקבלים משוב על ההגייה ואוספים את המשפטים שכבר הפכו לשלכם. כאן תמצאו את המסלול, הפרסים והמשוב, כל סוגי התרגול והכלים הנוספים באפליקציה.</p>
227
  </header>
228
 
229
+ <nav class="jump" aria-label="תוכן המדריך"><a href="#path">המסלול</a><a href="#states">העיגולים</a><a href="#rewards">ההתקדמות שלי</a><a href="#kinds">סוגי נושאים</a><a href="#practice">התרגול</a><a href="#more">עוד דרכי תרגול</a><a href="#settings">הגדרות</a><a href="#tips">טיפים</a></nav>
230
 
231
  <!-- 1. the path screen -->
232
  <section id="path">
 
236
  </div>
237
  <div class="pair">
238
  <div class="phone" aria-label="דוגמה של מסך המסלול">
239
+ <div class="m-head at"><span class="n">1</span><span class="m-brand">אהלא וסהלא</span><span class="m-pill">כיתה ב׳ ▾</span><span class="m-drive">? מדריך</span></div>
240
  <div class="m-today at l"><span class="n">2</span>
241
  <div class="hot">סרטון יומי<small>יום 3 · ברכות</small></div>
242
  <div>תרגול יומי<small>10 משפטים</small></div>
243
  <div>שיעורי בית<small>עוד יומיים</small></div>
244
  </div>
245
+ <div class="m-rewards at"><span class="n">3</span><span class="m-week">🔥 6</span><span><b>הערבית שכבר שלכם</b><small>רצף של 6 ימים · שיא 11</small></span><span class="m-fire">3/4 השבוע<br>18 ★</span></div>
246
+ <div class="m-nav"><span class="on">מסלול</span><span>פעלים</span><span>משחקים</span><span>חבר מביא חבר</span></div>
247
  <div class="m-level">שלב א׳<small>8 מתוך 10 שיעורים מוכנים</small></div>
248
  <div class="m-chapter at l"><span class="n">4</span><div>שיעור 3<i></i></div><small>תורגלו 22 מתוך 40</small></div>
249
  <div class="road">
 
262
  </div>
263
  </div>
264
  <ol class="key">
265
+ <li><span class="n">1</span><div><b>הכיתה והמדריך</b><span class="d">לחיצה על שם הכיתה מראה את חברי הכיתה, או מחליפה כיתה אם אתם ביותר מאחת. הכפתור <b style="display:inline">?</b> מחזיר למדריך הזה בכל רגע מהמסלול.</span></div></li>
266
  <li><span class="n">2</span><div><b>שלושה קיצורים להיום</b><span class="d"><b style="display:inline">סרטון יומי</b> שהמורה קבע להיום (מודגש עד שצופים). <b style="display:inline">תרגול יומי</b>: סבב של 10 משפטים, חצי לשיפור וחצי חדשים מהשיעור הנוכחי. <b style="display:inline">שיעורי בית</b>: פותח ישר את הנושא הקרוב להגשה.</span></div></li>
267
+ <li><span class="n">3</span><div><b>ההתקדמות והרצף שלכם</b><span class="d">🔥 הוא מספר ימי התרגול הרצופים ומופיע במרכז הכרטיס. לידו מופיעים יעד ארבעת הימים השבועי ומספר משפטי הזהב ★. לחיצה פותחת את כל אוסף החרוזים, לפי שיעור ונושא.</span></div></li>
268
  <li><span class="n">4</span><div><b>כותרת השיעור</b><span class="d">הפס מראה כמה מהשיעור תורגל. לחיצה עליה פותחת את הנושא הבא שעוד לא נגמר. בסוף כל שיעור יש גביע 🏆 שמזהיב כשהשיעור הושלם.</span></div></li>
269
  <li><span class="n">5</span><div><b>הנושא של עכשיו</b><span class="d">מסומן בהילה ובבועה „התחילו” או „המשך”. אם גללתם רחוק, הכפתור „חזרה לנושא הנוכחי” מחזיר אליו.</span></div></li>
270
  <li><span class="n">6</span><div><b>כל הנושאים פתוחים</b><span class="d">אפשר לפתוח כל נושא בכל שיעור, גם בלי לסיים את מה שלפניו.</span></div></li>
 
284
  <div class="state"><div class="ball done"><span class="badge">✓</span>2</div><b>הושלם</b><span>כל המשפטים נאמרו לפחות פעם אחת</span></div>
285
  <div class="state"><div class="ball gold"><span class="badge">★</span>1</div><b>זהב</b><span>כל המשפטים קיבלו „מצוין” (85 ומעלה)</span></div>
286
  <div class="state"><div class="ball" style="border-color:var(--amber);margin-top:22px"><div class="tag hw" style="font-size:10px">עוד 3 ימים</div>5</div><b>שיעורי בית</b><span>הבועה סופרת את הימים עד ההגשה</span></div>
287
+ <div class="state"><div class="ball video">▶&#xFE0E;</div><b>סרטון</b><span>✓ מופיע אחרי שפתחתם וצפיתם</span></div>
288
  </div>
289
  </section>
290
 
291
+ <!-- 3. progress rewards -->
292
+ <section id="rewards">
293
+ <div class="sechead">
294
+ <h2>הערבית שכבר שלכם</h2>
295
+ <p>זה המקום לראות לא רק מה סיימתם, אלא כמה ערבית כבר צברתם לאורך הדרך. פותחים אותו בלחיצה על הכרטיס שמעל המסלול.</p>
296
+ </div>
297
+ <div class="pair">
298
+ <div class="reward-demo" aria-label="דוגמה של אוסף ההתקדמות">
299
+ <div class="reward-stats"><div><b>🔥 6</b><small>רצף · שיא 11</small></div><div><b>42</b><small>משפטים שלכם</small></div><div><b>18</b><small>חרוזי זהב</small></div><div><b>3</b><small>ימים השבוע</small></div></div>
300
+ <div class="reward-lesson">שלב א׳ · שיעור 3</div>
301
+ <div class="reward-subject">משפטים: עברית ← ערבית א׳</div>
302
+ <div class="beads" aria-hidden="true"><i class="bead gold"></i><i class="bead gold"></i><i class="bead"></i><i class="bead gold"></i><i class="bead"></i><i class="bead"></i></div>
303
+ <div class="reward-subject">פעלים בעבר</div>
304
+ <div class="beads" aria-hidden="true"><i class="bead gold"></i><i class="bead"></i><i class="bead gold"></i><i class="bead"></i></div>
305
+ </div>
306
+ <div class="tips">
307
+ <div class="tip"><h3>חרוז לכל משפט</h3><p>הקלטה ראשונה עם דיבור אוספת את המשפט. לחיצה על חרוז באוסף מחזירה ישר למשפט שלו.</p></div>
308
+ <div class="tip"><h3>זהב ב־85</h3><p>כשהציון הטוב ביותר במשפט מגיע ל־85, החרוז הופך לזהב. האפליקציה שומרת את הציון הגבוה ביותר, לא את האחרון.</p></div>
309
+ <div class="tip"><h3>יעד שבועי 4/4</h3><p>הטבעת סופרת ימים שונים שבהם תרגלתם השבוע, מיום שני עד יום ראשון. די בהקלטה אחת עם דיבור כדי שהיום ייספר.</p></div>
310
+ <div class="tip"><h3>רצף 🔥</h3><p>הרצף סופר ימי תרגול רצופים. הרצף של אתמול נשאר מוצג במשך היום כדי שתספיקו להמשיך אותו; אם היום עובר בלי תרגול, הוא מתאפס. השיא האישי נשמר.</p></div>
311
+ <div class="tip"><h3>רגעים שחוגגים</h3><p>חרוז חדש, מעבר לזהב, שיא חדש, המשך רצף והשלמת נושא מקבלים הודעת חגיגה קצרה אחרי הציון.</p></div>
312
+ </div>
313
+ </div>
314
+ </section>
315
+
316
+ <!-- 4. topic kinds -->
317
  <section id="kinds">
318
  <div class="sechead">
319
  <h2>סוגי הנושאים</h2>
 
364
  </div>
365
  </section>
366
 
367
+ <!-- 5. the practice screen -->
368
  <section id="practice">
369
  <div class="sechead">
370
  <h2>מסך התרגול</h2>
 
372
  </div>
373
  <div class="pair">
374
  <div class="phone" aria-label="דוגמה של מסך התרגול">
375
+ <div class="m-bar at"><span class="n">1</span><span class="m-btn p">→ חזרה למסלול</span><span class="m-btn">🚗 מצב נסיעה</span><span class="m-sp"></span><span class="m-btn">☰ רשימה</span><span class="m-btn gear">⚙</span></div>
376
  <div class="m-card">
377
  <div class="m-meta"><span>3 / 10</span><span>משפטים א׳</span></div>
378
  <div class="at l" style="display:flex;flex-direction:column;gap:6px;padding-inline:14px"><span class="n">2</span>
 
392
  </div>
393
  </div>
394
  <ol class="key">
395
+ <li><span class="n">1</span><div><b>שורת הכלים</b><span class="d"><b style="display:inline">חזרה למסלול</b>, <b style="display:inline">מצב נסיעה</b> שמקריא ומקשיב בלי לגעת במסך, <b style="display:inline">רשימת המשפטים</b> עם הציון הכי טוב בכל משפט, ו־⚙ להגדרות ההשמעה. בשיחה מופיעים כאן גם השמעת השיחה ובוחן.</span></div></li>
396
  <li><span class="n">2</span><div><b>המשפט</b><span class="d">מה שצריך לומר, ומעליו המיקום בנושא.</span></div></li>
397
  <li><span class="n">3</span><div><b>המיקרופון</b><span class="d">לוחצים פעם אחת ומדברים, וההקלטה נעצרת לבד. בלי מיקרופון אפשר לבחור <b style="display:inline">תרגול שקט</b> ולהרכיב את המשפט ממילים.</span></div></li>
398
  <li><span class="n">4</span><div><b>הציון</b><span class="d">כל מילה נצבעת לפי מה שנשמע: ירוק נאמר נכון, צהוב כמעט. מתחת מופיעים טיפים לשיפור.</span></div></li>
 
406
  </div>
407
  </section>
408
 
409
+ <!-- 6. other practice routes -->
410
+ <section id="more">
411
+ <div class="sechead">
412
+ <h2>עוד דרכים לתרגל</h2>
413
+ <p>לא חייבים לבחור נושא ולתרגל אותו מההתחלה עד הסוף. אלה המסלולים הקצרים והמשחקיים שמופיעים לפי ההרשאות והשיעורים של הכיתה.</p>
414
+ </div>
415
+ <div class="topics">
416
+ <article class="topic"><div class="th"><div class="ball now">10</div><div><h3>תרגול יומי</h3><small>הכפתור מעל המסלול</small></div></div><p>סבב קצר של עד עשרה משפטים. הוא משלב משפטים חלשים שכדאי לשפר עם משפטים חדשים משיעורי הבית או מהשיעור הראשון שעוד לא הושלם. בסוף רואים כמה נאמרו וכמה ציונים השתפרו.</p><p class="ex"><b>הסבב מסומן כהושלם להיום:</b> אחרי שאמרתם לפחות חצי ממנו.</p></article>
417
+ <article class="topic"><div class="th"><div class="ball now">🚗</div><div><h3>מצב נסיעה</h3><small>במסך התרגול</small></div></div><p>האפליקציה מקריאה את ההנחיה, מקשיבה לתשובה, אומרת את ההערכה בקול וממשיכה. מתאים להליכה או נסיעה שבהן לא רוצים לגעת במסך. מסיימים בכפתור „סיום נסיעה”.</p></article>
418
+ <article class="topic"><div class="th"><div class="ball now">פעל</div><div><h3>לשונית פעלים</h3><small>טבלת הפעלים של הקורס</small></div></div><p>מחפשים פועל, עוברים בין השיעורים ורואים את הצורות שכבר נלמדו לפי בניין וגזרה. לחיצה על צורה בערבית משמיעה אותה. הסברים קצרים עוזרים לזהות את התבנית.</p></article>
419
+ <article class="topic"><div class="th"><div class="ball now">📿</div><div><h3>משחקי חזרה</h3><small>בלשונית משחקים, כשזמינים</small></div></div><p>משחק הזיכרון הופך חרוזים ומחבר בין פעלים בעברית ובערבית. משחקים נוספים יכולים להיפתח לפי החומר וההרשאה של הכיתה.</p></article>
420
+ <article class="topic"><div class="th"><div class="ball now">💬</div><div><h3>יאללה נדבר</h3><small>שיחה עם דמויות מהשיעורים, כשזמינה</small></div></div><p>בוחרים תרחיש ומנהלים שיחה קצרה בערבית עם דמות מהקורס. השיחה משתמשת במילים ובדקדוק שכבר נלמדו, ומתקנת ניסוח או דקדוק בעברית כשצריך.</p></article>
421
+ <article class="topic"><div class="th"><div class="ball video">▶&#xFE0E;</div><div><h3>סרטונים וספרייה</h3><small>לפי התוכן שהמורה פרסם</small></div></div><p>סרטון יומי מופיע מעל המסלול ביום שנקבע. סרטוני שיעור נמצאים בתוך הדרך, והספרייה הדיגיטלית נפתחת ממסך הכניסה למי שקיבל גישה.</p></article>
422
+ </div>
423
+ </section>
424
+
425
 
426
+ <!-- 7. playback settings -->
427
  <section id="settings">
428
  <div class="sechead">
429
  <h2>הגדרות השמעה ⚙</h2>
430
+ <p>במסך התרגול יש כפתור ⚙. הוא פותח שתי הגדרות שנשמרות במכשיר לפעם הבאה.</p>
431
  </div>
432
  <div class="pair">
433
  <div class="phone" aria-label="דוגמה של חלון הגדרות ההשמעה">
434
  <div class="m-bar"><span class="m-btn p">→ חזרה למסלול</span><span class="m-sp"></span><span class="m-btn">☰ רשימה</span><span class="m-btn gear hl">⚙</span></div>
435
  <div class="dlg">
436
  <div class="dlg-h"><b>הגדרות השמעה</b><span class="m-btn">סגירה</span></div>
437
+ <div class="row at l"><span class="n">1</span><span>מהירות</span><span class="sel">x1</span></div>
438
+ <div class="row at l"><span class="n">2</span><span>הקראת המשפט בעברית</span><span class="tg on" aria-hidden="true"></span></div>
 
439
  </div>
440
  </div>
441
  <ol class="key">
442
+ <li><span class="n">1</span><div><b>מהירות</b><span class="d"><b style="display:inline">x0.8</b> לאט יותר, כדי לשמוע כל הברה. <b style="display:inline">x1</b> רגיל. <b style="display:inline">x1.5</b> מהיר, לאימון הבנת שמיעה.</span></div></li>
443
+ <li><span class="n">2</span><div><b>הקראת המשפט בעברית</b><span class="d">כשמסומן, כל משפט חדש מוקרא בקול בעברית לפני שעונים, כך שאפשר לתרגל בלי לקרוא מהמסך. בנושאי ערבית ← עברית אין הקראה, כי העברית היא התשובה.</span></div></li>
 
444
  </ol>
445
  </div>
446
  </section>
447
 
448
+ <!-- 8. tips -->
449
  <section id="tips">
450
  <div class="sechead"><h2>כמה טיפים</h2></div>
451
  <div class="tips">
static/index.html CHANGED
@@ -319,6 +319,17 @@ body.memory-game{overflow:hidden}
319
  /* the way back to the path, at the head of the daily videos' screen (no tab of the foot's bar is lit there) */
320
  #vids button.back{display:inline-flex;align-self:flex-start;gap:6px;padding:6px 12px;border-radius:10px;background:var(--olive);border-color:var(--olive);color:var(--on-olive);font:700 15px var(--f-body)}
321
  #dailyDlg{width:min(92vw,380px)}
 
 
 
 
 
 
 
 
 
 
 
322
  .path{--track:color-mix(in srgb,var(--muted) 75%,var(--bg));position:relative;width:100%;max-width:460px;margin:4px auto 72px;background:#101510 url("/static/assets/arabic-calligraphy-path.webp?v=7") top center/100% auto repeat-y}
323
  .road{position:absolute;left:50%;top:0;width:1px;height:100%;overflow:visible;pointer-events:none}
324
  .road path{fill:none;stroke-linecap:round}
@@ -1256,6 +1267,11 @@ body.quiet :is(#mic,#playMine,#driveBtn,.phone-btn),body.driving :is(#quietBtn,#
1256
  </header>
1257
 
1258
  <div id="today" hidden></div>
 
 
 
 
 
1259
  <section id="vids" aria-live="polite"></section>
1260
  <nav id="nav" aria-label="ניווט"><button data-view="">מסלול</button><button data-view="verbs">פעלים</button><button data-view="games" hidden>משחקים</button><button data-view="refer">חבר מביא חבר</button></nav>
1261
  <nav class="path" id="path" aria-label="מסלול הלימוד"></nav>
@@ -1541,6 +1557,13 @@ body.quiet :is(#mic,#playMine,#driveBtn,.phone-btn),body.driving :is(#quietBtn,#
1541
  <p class="dlg-text" id="dailyText"></p>
1542
  <div class="row"><button class="btn primary" id="dailyClose">חזרה למסלול</button><button class="btn" id="dailyMore">סבב נוסף</button></div>
1543
  </dialog>
 
 
 
 
 
 
 
1544
  <dialog id="driveDlg" aria-labelledby="driveTitle">
1545
  <div class="dlg-head"><h2 id="driveTitle">מצב נסיעה</h2></div>
1546
  <p class="dlg-text">תרגול בלי לגעת במסך: האפליקציה מקריאה כל משפט, מקשיבה לתשובה שלכם ואומרת את ההערכה בקול. לסיום לוחצים על "סיום נסיעה".</p>
@@ -1707,6 +1730,7 @@ let ME_EMAIL=""; // the signed-in account: in the lab, who records
1707
  let MY_CLASSES=[], MY_CLASS=null; // a student's classes ({name, lessons, homeworks, dailies}), and the one they practise in now
1708
  let daily=null, dailySaid=new Set(), dailyWas={}; // the daily session on the card: its sentence ids, those said in it, and their best scores before it
1709
  let ALL_LEVELS=[], ALL_LESSONS=[], ALL_CATS=[], GAMES=[], MY_LESSONS=null, LESSONS=[], CATS=[], PHRASES=[], cat=store.get("ihki.cat",""), best=store.get("ihki.best2",{}), order=[], pos=0, cur=null;
 
1710
  let myAudioUrl=null;
1711
  let TUTOR=false, lastRec=null; // a teacher, or an account of TUTORS_EMAIL, flags a score that is wrong; the latest recording sent to be scored, {id, blob}
1712
  let ME_PERMISSIONS=new Set(), ME_ROLES=[], ME_ENTITLEMENTS=[];
@@ -2430,7 +2454,81 @@ function drawToday(){ // above the path: the daily session, and the homework t
2430
  work.append(mark("","שיעורי בית"),mark("",hw?(hw.left==null?hw.c.name:hw.msg):all.length?"✓ הושלמו":"אין כרגע","small"));
2431
  if(hw){ work.title=[hw.c.name,hw.l&&hw.l.name,hw.left==null?"":hw.msg].filter(Boolean).join(" · "); work.onclick=()=>openCat(hw.c); } else work.disabled=true;
2432
  box.append(vid,go,work); box.hidden=false;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2433
  }
 
 
 
 
 
 
 
2434
  function ball(t,now){ // a topic's button and the disc inside its ring
2435
  const b=document.createElement("button"), ring=document.createElement("span"), dot=document.createElement("span");
2436
  b.className="sat"+(t.gold?" gold":t.over?" done":now?" now":t.done?" started":"");
@@ -2870,6 +2968,8 @@ async function loadProgress(){
2870
  try{
2871
  const res=await api("/api/progress"); if(!res.ok) return;
2872
  const d=await res.json();
 
 
2873
  best={...d.best};
2874
  for(const k in sessionBest) if(best[k]==null||sessionBest[k]>best[k]) best[k]=sessionBest[k];
2875
  store.set("ihki.best2",best); marks();
@@ -3459,9 +3559,19 @@ $("heBtn").onclick=async()=>{
3459
  $("status").textContent="מקשיב… אמרו את התרגום בעברית (או לחצו לסיום)";
3460
  };
3461
  function keepScore(id,s){ // a sentence's best score, on the device and for this visit
3462
- if(best[id]==null||s>best[id]){best[id]=s; store.set("ihki.best2",best);}
 
 
3463
  if(!(sessionBest[id]>=s)) sessionBest[id]=s;
 
3464
  marks();
 
 
 
 
 
 
 
3465
  }
3466
 
3467
  /* A teacher can inspect the two phoneme sequences already produced by scoring. The expected row uses the
@@ -4172,6 +4282,7 @@ let FLAG_REVIEWS={pending:[],confirmed:[]}, CALIBRATIONS=[], ATTEMPT_PATTERNS=[]
4172
  let SCORING_RULES=null, scoringRulesError=""; // the rules of pronunciation-rules.md and whether each is on (see drawScoringRules)
4173
  let ACTIVITY=null, activityError="";
4174
  let SYSTEM_ACTIVITY=null, systemActivityError="";
 
4175
  let activityHours=+store.get("ihki.activityHours","24"); if(![24,168].includes(activityHours)) activityHours=24;
4176
  let shownStudent="", classScroll=0; // the student whose screen is on show (an email; "" for the class's), and where the class's was left
4177
  let CLASS_LESSONS=[], CLASS_SOON=[]; // the ready lessons of the class on show, and those still to come (every lesson before the first class)
@@ -4422,6 +4533,7 @@ function drawScoringRules(box){
4422
  function drawFlags(){
4423
  const box=$("mFlags"); box.innerHTML=""; for(const url of flagAudioUrls) URL.revokeObjectURL(url); flagAudioUrls=[];
4424
  drawActivity(box);
 
4425
  drawApiKeys(box);
4426
  drawSystemActivity(box);
4427
  drawTtsCacheControls(box);
@@ -4536,6 +4648,26 @@ function drawFlags(){
4536
  }
4537
  }
4538
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4539
  const flagGroupOpen={}; // reporter -> whether their group of reports is open; closed until the teacher opens it
4540
  let systemActivityOpen=false; // the recent activity starts closed; a redraw keeps it as the teacher left it
4541
  function drawSystemActivity(box){
@@ -4744,6 +4876,7 @@ function drawClasses(classes){
4744
  const card=mark("card",""), top=mark("chead",""), name=mark("","","h2"), n=document.createElement("bdi"), edit=mark("btn","עריכה","button"), del=mark("btn danger","מחיקה","button");
4745
  n.textContent=c.name; name.append(n); edit.onclick=()=>editClass(c); del.onclick=()=>deleteClass(c); top.append(name,edit,del);
4746
  const facts=mark("facts","","dl"), fact=(what,...value)=>{ const dd=document.createElement("dd"); dd.append(...value); facts.append(mark("",what,"dt"),dd); };
 
4747
  fact("שיעורים",lessonsLine(ALL_LESSONS.filter(l=>c.lessons.includes(l.id))));
4748
  const mine=CLASS.students.filter(s=>c.name in s.classes);
4749
  fact("תלמידים",...(mine.length?[`${mine.length}: `,...mine.flatMap((s,k)=>{ const b=document.createElement("bdi"); b.textContent=s.classes[c.name]||s.name||s.email; return k?[", ",b]:[b]; })]:["עוד אין"]));
 
319
  /* the way back to the path, at the head of the daily videos' screen (no tab of the foot's bar is lit there) */
320
  #vids button.back{display:inline-flex;align-self:flex-start;gap:6px;padding:6px 12px;border-radius:10px;background:var(--olive);border-color:var(--olive);color:var(--on-olive);font:700 15px var(--f-body)}
321
  #dailyDlg{width:min(92vw,380px)}
322
+ .reward-shelf{width:100%;max-width:460px;margin:0 auto;padding:11px 14px;border:1px solid var(--olive);border-radius:14px;background:var(--surface);color:var(--ink);display:grid;grid-template-columns:54px 1fr auto;align-items:center;gap:10px;text-align:start;cursor:pointer;box-shadow:0 2px 0 var(--line);font-family:var(--f-body)}
323
+ .reward-shelf:hover{background:var(--olive-soft)}
324
+ .streak-ring{width:50px;height:50px;border-radius:50%;display:grid;place-items:center;background:var(--amber-bg);border:2px solid var(--orange);color:var(--orange);font:700 16px/1 var(--f-body);box-shadow:0 2px 0 color-mix(in srgb,var(--orange) 55%,var(--line))}
325
+ .reward-copy{display:flex;min-width:0;flex-direction:column;line-height:1.25}.reward-copy b{font-size:16px}.reward-copy small{color:var(--orange);font-weight:700}.reward-totals{display:flex;flex-direction:column;align-items:flex-end;gap:3px;white-space:nowrap;font:700 13px/1.15 var(--f-body)}.reward-total{color:var(--amber)}.reward-week{color:var(--olive)}
326
+ body:not(.home) .reward-shelf,body.manage .reward-shelf,body[data-view] .reward-shelf{display:none}
327
+ #rewardsDlg{width:min(94vw,520px);max-height:88vh}.reward-summary{display:grid;grid-template-columns:repeat(4,1fr);gap:8px;margin:4px 0 12px}.reward-summary div{padding:10px 6px;border-radius:12px;background:var(--olive-soft);text-align:center}.reward-summary div:first-child{background:var(--amber-bg);box-shadow:inset 0 0 0 1px var(--orange)}.reward-summary div:first-child b{color:var(--orange)}.reward-summary b{display:block;color:var(--olive);font:400 25px/1.1 var(--f-display)}.reward-summary small{font-size:12px;color:var(--muted)}
328
+ .reward-lesson{margin:18px 0 0;padding:8px 0 5px;border-bottom:1px solid var(--line);color:var(--olive);font:400 20px/1.2 var(--f-display)}.reward-lesson:first-child{margin-top:8px}.reward-topic{margin:10px 0 5px;font:700 15px/1.2 var(--f-body)}.reward-topic small{margin-inline-start:6px;color:var(--muted)}.reward-beads{display:flex;flex-wrap:wrap;gap:7px;direction:rtl}.phrase-bead{width:31px;height:31px;border-radius:50%;border:3px solid #52624b;background:radial-gradient(circle at 32% 27%,#dce7d4 0 9%,#769064 23%,#405136 72%);box-shadow:inset -2px -3px 3px rgb(0 0 0/.3),0 2px 2px rgb(0 0 0/.2);cursor:pointer}.phrase-bead.gold{border-color:#9b690b;background:radial-gradient(circle at 32% 27%,#fff3a7 0 9%,#e4b83e 27%,#9d6509 75%)}
329
+ .reward-empty{padding:20px;border:1px dashed var(--line);border-radius:12px;color:var(--muted);text-align:center}
330
+ .reward-pop{position:fixed;z-index:60;left:50%;top:18%;width:min(88vw,360px);transform:translate(-50%,-12px) scale(.96);padding:14px 18px;border:1px solid var(--olive);border-radius:16px;background:var(--surface);color:var(--ink);box-shadow:0 12px 38px rgb(0 0 0/.28);text-align:center;opacity:0;pointer-events:none;transition:opacity .18s,transform .18s}.reward-pop.show{opacity:1;transform:translate(-50%,0) scale(1)}.reward-pop b{display:block;color:var(--olive);font:400 22px/1.25 var(--f-display)}.reward-pop.gold b{color:var(--amber)}.reward-pop small{color:var(--muted);font-weight:600}
331
+ @media (prefers-reduced-motion:reduce){.reward-pop{transition:none}}
332
+ @media (max-width:430px){.reward-summary{grid-template-columns:repeat(2,1fr)}}
333
  .path{--track:color-mix(in srgb,var(--muted) 75%,var(--bg));position:relative;width:100%;max-width:460px;margin:4px auto 72px;background:#101510 url("/static/assets/arabic-calligraphy-path.webp?v=7") top center/100% auto repeat-y}
334
  .road{position:absolute;left:50%;top:0;width:1px;height:100%;overflow:visible;pointer-events:none}
335
  .road path{fill:none;stroke-linecap:round}
 
1267
  </header>
1268
 
1269
  <div id="today" hidden></div>
1270
+ <button class="reward-shelf" id="rewardShelf" type="button" hidden>
1271
+ <span class="streak-ring" id="rewardStreak">🔥 0</span>
1272
+ <span class="reward-copy"><b>הערבית שכבר שלכם</b><small id="rewardCopy">עוד לא נאספו משפטים</small></span>
1273
+ <span class="reward-totals"><span class="reward-week" id="rewardWeek">0/4 השבוע</span><span class="reward-total" id="rewardTotal">0 ★</span></span>
1274
+ </button>
1275
  <section id="vids" aria-live="polite"></section>
1276
  <nav id="nav" aria-label="ניווט"><button data-view="">מסלול</button><button data-view="verbs">פעלים</button><button data-view="games" hidden>משחקים</button><button data-view="refer">חבר מביא חבר</button></nav>
1277
  <nav class="path" id="path" aria-label="מסלול הלימוד"></nav>
 
1557
  <p class="dlg-text" id="dailyText"></p>
1558
  <div class="row"><button class="btn primary" id="dailyClose">חזרה למסלול</button><button class="btn" id="dailyMore">סבב נוסף</button></div>
1559
  </dialog>
1560
+ <dialog id="rewardsDlg" aria-labelledby="rewardsTitle">
1561
+ <div class="dlg-head"><h2 id="rewardsTitle">הערבית שכבר שלכם</h2><button class="btn" id="rewardsClose">סגירה</button></div>
1562
+ <p class="dlg-text">כל משפט שאמרתם הוא חרוז במסבחה. ציון 85 ומעלה הופך אותו לזהב.</p>
1563
+ <div class="reward-summary" id="rewardSummary"></div>
1564
+ <div id="rewardCollection"></div>
1565
+ </dialog>
1566
+ <div class="reward-pop" id="rewardPop" role="status" aria-live="polite"><b></b><small></small></div>
1567
  <dialog id="driveDlg" aria-labelledby="driveTitle">
1568
  <div class="dlg-head"><h2 id="driveTitle">מצב נסיעה</h2></div>
1569
  <p class="dlg-text">תרגול בלי לגעת במסך: האפליקציה מקריאה כל משפט, מקשיבה לתשובה שלכם ואומרת את ההערכה בקול. לסיום לוחצים על "סיום נסיעה".</p>
 
1730
  let MY_CLASSES=[], MY_CLASS=null; // a student's classes ({name, lessons, homeworks, dailies}), and the one they practise in now
1731
  let daily=null, dailySaid=new Set(), dailyWas={}; // the daily session on the card: its sentence ids, those said in it, and their best scores before it
1732
  let ALL_LEVELS=[], ALL_LESSONS=[], ALL_CATS=[], GAMES=[], MY_LESSONS=null, LESSONS=[], CATS=[], PHRASES=[], cat=store.get("ihki.cat",""), best=store.get("ihki.best2",{}), order=[], pos=0, cur=null;
1733
+ let serverWeekDays=0, serverStreak={current:0,best:0,last:null}, rewardTimer=null;
1734
  let myAudioUrl=null;
1735
  let TUTOR=false, lastRec=null; // a teacher, or an account of TUTORS_EMAIL, flags a score that is wrong; the latest recording sent to be scored, {id, blob}
1736
  let ME_PERMISSIONS=new Set(), ME_ROLES=[], ME_ENTITLEMENTS=[];
 
2454
  work.append(mark("","שיעורי בית"),mark("",hw?(hw.left==null?hw.c.name:hw.msg):all.length?"✓ הושלמו":"אין כרגע","small"));
2455
  if(hw){ work.title=[hw.c.name,hw.l&&hw.l.name,hw.left==null?"":hw.msg].filter(Boolean).join(" · "); work.onclick=()=>openCat(hw.c); } else work.disabled=true;
2456
  box.append(vid,go,work); box.hidden=false;
2457
+ drawRewardShelf();
2458
+ }
2459
+ const localPracticeDays=()=>store.get("ihki.practiceDays",[]).filter(d=>typeof d==="string");
2460
+ function currentWeekDays(){
2461
+ const now=new Date(), start=new Date(now.getFullYear(),now.getMonth(),now.getDate()-((now.getDay()+6)%7));
2462
+ const local=localPracticeDays().filter(d=>new Date(d+"T12:00:00")>=start&&new Date(d+"T12:00:00")<=now).length;
2463
+ return Math.max(serverWeekDays,local);
2464
+ }
2465
+ function streakOf(values){
2466
+ const days=[...new Set(values)].sort(); if(!days.length) return {current:0,best:0,last:null};
2467
+ let run=1, bestRun=1; for(let i=1;i<days.length;i++){
2468
+ const previous=new Date(days[i-1]+"T12:00:00"), expected=new Date(previous); expected.setDate(previous.getDate()+1);
2469
+ run=todayOf(expected)===days[i]?run+1:1; bestRun=Math.max(bestRun,run);
2470
+ }
2471
+ const now=today(), yesterday=new Date(); yesterday.setDate(yesterday.getDate()-1);
2472
+ let current=days.at(-1)===now||days.at(-1)===todayOf(yesterday)?1:0;
2473
+ for(let i=days.length-1;current&&i>0;i--){ const d=new Date(days[i]+"T12:00:00"); d.setDate(d.getDate()-1); if(todayOf(d)!==days[i-1]) break; current++; }
2474
+ return {current,best:bestRun,last:days.at(-1)};
2475
+ }
2476
+ const todayOf=d=>d.toLocaleDateString("sv");
2477
+ function combinedStreak(){
2478
+ const local=streakOf(localPracticeDays()), yesterday=new Date(); yesterday.setDate(yesterday.getDate()-1);
2479
+ let current=Math.max(serverStreak.current||0,local.current);
2480
+ if(local.last===today()&&serverStreak.last===todayOf(yesterday)) current=Math.max(current,(serverStreak.current||0)+1);
2481
+ return {current,best:Math.max(serverStreak.best||0,local.best,current)};
2482
+ }
2483
+ function notePracticeDay(){
2484
+ const before=combinedStreak(), day=today(), existing=localPracticeDays(), fresh=!existing.includes(day);
2485
+ const days=[...new Set([...existing,day])].sort().slice(-60); store.set("ihki.practiceDays",days);
2486
+ const after=combinedStreak(); return fresh&&after.current>before.current?{...after,newBest:after.best>before.best}:null;
2487
+ }
2488
+ function rewardPhrases(){
2489
+ const cats=new Set(CATS.map(c=>c.id));
2490
+ return PHRASES.filter(p=>p.listed!==false&&cats.has(p.cat)&&best[p.id]!=null);
2491
+ }
2492
+ function drawRewardShelf(){
2493
+ const shelf=$("rewardShelf"); if(!PHRASES.length){ shelf.hidden=true; return; }
2494
+ const got=rewardPhrases(), gold=got.filter(p=>best[p.id]>=EXCELLENT).length, wd=currentWeekDays(), streak=combinedStreak(), goal=4;
2495
+ $("rewardStreak").textContent=`🔥 ${streak.current}`; $("rewardStreak").title=`רצף נוכחי: ${streak.current} ימים · שיא אישי: ${streak.best}`;
2496
+ $("rewardCopy").textContent=streak.current?`רצף של ${streak.current} ימים · שיא ${streak.best} · ${got.length} משפטים`:got.length?`מתחילים רצף היום · ${got.length} משפטים נאספו`:`אמרו משפט ראשון והתחילו רצף`;
2497
+ $("rewardWeek").textContent=`${Math.min(wd,goal)}/${goal} השבוע`;
2498
+ $("rewardTotal").textContent=`${gold} ★`; shelf.hidden=false;
2499
+ }
2500
+ function drawRewards(){
2501
+ const got=rewardPhrases(), gold=got.filter(p=>best[p.id]>=EXCELLENT).length, week=currentWeekDays(), streak=combinedStreak(), summary=$("rewardSummary"), box=$("rewardCollection");
2502
+ summary.replaceChildren();
2503
+ for(const [n,label] of [[`🔥 ${streak.current}`,`רצף נוכחי · שיא ${streak.best}`],[got.length,"משפטים שלכם"],[gold,"חרוזי זהב"],[week,"ימי תרגול השבוע"]]){
2504
+ const tile=document.createElement("div"); tile.append(mark("",String(n),"b"),mark("",label,"small")); summary.append(tile);
2505
+ }
2506
+ box.replaceChildren();
2507
+ if(!got.length){ box.append(mark("reward-empty","החרוז הראשון יחכה כאן אחרי שתאמרו משפט.","div")); return; }
2508
+ for(const lesson of LESSONS){
2509
+ const cats=CATS.filter(c=>c.lesson===lesson.id&&got.some(p=>p.cat===c.id)); if(!cats.length) continue;
2510
+ box.append(mark("reward-lesson",lessonName(lesson),"h3"));
2511
+ for(const c of cats){
2512
+ const phrases=got.filter(p=>p.cat===c.id), title=mark("reward-topic",c.name,"h4"), mastered=phrases.filter(p=>best[p.id]>=EXCELLENT).length;
2513
+ title.append(mark("",`${mastered}/${phrases.length} בזהב`,"small")); box.append(title);
2514
+ const row=mark("reward-beads","","div");
2515
+ for(const p of phrases){
2516
+ const bead=mark("phrase-bead"+(best[p.id]>=EXCELLENT?" gold":""),"","button");
2517
+ bead.type="button"; bead.title=`${lessonName(lesson)} · ${c.name} · ${p.he} · הציון הטוב ביותר ${Math.round(best[p.id])}`;
2518
+ bead.setAttribute("aria-label",bead.title); bead.onclick=()=>{ $("rewardsDlg").close(); pickCat(p.cat); openSentence(p.id); };
2519
+ row.append(bead);
2520
+ }
2521
+ box.append(row);
2522
+ }
2523
+ }
2524
  }
2525
+ function rewardPop(title,detail,gold=false){
2526
+ const pop=$("rewardPop"); clearTimeout(rewardTimer); pop.className="reward-pop"+(gold?" gold":"");
2527
+ pop.querySelector("b").textContent=title; pop.querySelector("small").textContent=detail;
2528
+ requestAnimationFrame(()=>pop.classList.add("show")); rewardTimer=setTimeout(()=>pop.classList.remove("show"),2600);
2529
+ }
2530
+ $("rewardShelf").onclick=()=>{ drawRewards(); $("rewardsDlg").showModal(); };
2531
+ $("rewardsClose").onclick=()=>$("rewardsDlg").close();
2532
  function ball(t,now){ // a topic's button and the disc inside its ring
2533
  const b=document.createElement("button"), ring=document.createElement("span"), dot=document.createElement("span");
2534
  b.className="sat"+(t.gold?" gold":t.over?" done":now?" now":t.done?" started":"");
 
2968
  try{
2969
  const res=await api("/api/progress"); if(!res.ok) return;
2970
  const d=await res.json();
2971
+ serverWeekDays=Number(d.week_days)||0;
2972
+ serverStreak=d.streak||serverStreak;
2973
  best={...d.best};
2974
  for(const k in sessionBest) if(best[k]==null||sessionBest[k]>best[k]) best[k]=sessionBest[k];
2975
  store.set("ihki.best2",best); marks();
 
3559
  $("status").textContent="מקשיב… אמרו את התרגום בעברית (או לחצו לסיום)";
3560
  };
3561
  function keepScore(id,s){ // a sentence's best score, on the device and for this visit
3562
+ const old=best[id], phrase=phraseOf(id), c=phrase&&CATS.find(x=>x.id===phrase.cat), before=c&&topicT(c);
3563
+ const improved=old==null||s>old;
3564
+ if(improved){best[id]=s; store.set("ihki.best2",best);}
3565
  if(!(sessionBest[id]>=s)) sessionBest[id]=s;
3566
+ const streakReward=notePracticeDay();
3567
  marks();
3568
+ if(!phrase) return;
3569
+ const after=c&&topicT(c), becameGold=s>=EXCELLENT&&(old==null||old<EXCELLENT);
3570
+ if(improved&&before&&!before.over&&after.over) rewardPop(after.gold?"הנושא כולו בזהב!":"הנושא הושלם!",c.name,after.gold);
3571
+ else if(becameGold) rewardPop("המשפט הפך לזהב ★",phrase.he,true);
3572
+ else if(streakReward&&streakReward.current>=2) rewardPop(`🔥 רצף של ${streakReward.current} ימים`,streakReward.newBest?"שיא אישי חדש":"ממשיכים מחר");
3573
+ else if(old==null) rewardPop("חרוז חדש נאסף",phrase.he);
3574
+ else if(improved&&s-old>=8) rewardPop(`שיא חדש: ${Math.round(old)} ← ${Math.round(s)}`,phrase.he);
3575
  }
3576
 
3577
  /* A teacher can inspect the two phoneme sequences already produced by scoring. The expected row uses the
 
4282
  let SCORING_RULES=null, scoringRulesError=""; // the rules of pronunciation-rules.md and whether each is on (see drawScoringRules)
4283
  let ACTIVITY=null, activityError="";
4284
  let SYSTEM_ACTIVITY=null, systemActivityError="";
4285
+ let ADMIN_SUBJECTS=null;
4286
  let activityHours=+store.get("ihki.activityHours","24"); if(![24,168].includes(activityHours)) activityHours=24;
4287
  let shownStudent="", classScroll=0; // the student whose screen is on show (an email; "" for the class's), and where the class's was left
4288
  let CLASS_LESSONS=[], CLASS_SOON=[]; // the ready lessons of the class on show, and those still to come (every lesson before the first class)
 
4533
  function drawFlags(){
4534
  const box=$("mFlags"); box.innerHTML=""; for(const url of flagAudioUrls) URL.revokeObjectURL(url); flagAudioUrls=[];
4535
  drawActivity(box);
4536
+ drawAdminSubjects(box);
4537
  drawApiKeys(box);
4538
  drawSystemActivity(box);
4539
  drawTtsCacheControls(box);
 
4648
  }
4649
  }
4650
  }
4651
+
4652
+ /* Developer-only: the subject stamped onto every class an admin creates. The API enforces the same boundary. */
4653
+ function drawAdminSubjects(box){
4654
+ if(!can("*")) return;
4655
+ const card=mark("card",""), list=document.createElement("div");
4656
+ card.append(mark("","מקצועות מנהלים","h2"),mark("sub","רק מפתחים רואים ועורכים את הכרטיס הזה. כיתה חדשה מקבלת אוטומטית את המקצוע של המנהל/ת שפתח/ה אותה.","p"),list); box.append(card);
4657
+ const show=data=>{
4658
+ ADMIN_SUBJECTS=data; list.replaceChildren();
4659
+ if(data.setup){ const code=mark("",data.setup,"code"); code.dir="ltr"; list.append(mark("setup","יש ליצור את טבלת ההרשאות:","p"),code); return; }
4660
+ if(!(data.admins||[]).length){ list.append(mark("sub","אין כרגע מנהלים.","p")); return; }
4661
+ for(const admin of data.admins){
4662
+ const row=mark("key-row",""), who=document.createElement("div"), form=document.createElement("form"), input=document.createElement("input"), save=mark("btn primary","שמירה","button"), msg=mark("msg","");
4663
+ who.append(mark("",admin.name||admin.email,"b"),mark("",admin.email,"small")); input.value=admin.subject||""; input.maxLength=80; input.required=true; input.placeholder="למשל: מתמטיקה או ערבית"; input.setAttribute("aria-label",`המקצוע של ${admin.name||admin.email}`); save.type="submit";
4664
+ form.onsubmit=async e=>{ e.preventDefault(); save.disabled=true; msg.textContent="שומר…"; try{ const res=await api(`/api/admin-subjects/${admin.id}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({subject:input.value})}), data=await res.json().catch(()=>({})); if(!res.ok) throw new Error(data.detail||res.status); admin.subject=data.subject; input.value=data.subject; msg.textContent="נשמר"; }catch(err){ msg.textContent="השמירה נכשלה: "+err.message; } save.disabled=false; };
4665
+ form.append(input,save,msg); row.append(who,form); list.append(row);
4666
+ }
4667
+ };
4668
+ if(ADMIN_SUBJECTS){ show(ADMIN_SUBJECTS); return; }
4669
+ list.append(mark("sub","טוען…","p")); api("/api/admin-subjects").then(async res=>{ const data=await res.json().catch(()=>({})); if(!res.ok) throw new Error(data.detail||res.status); show(data); }).catch(err=>list.replaceChildren(mark("note","לא ניתן לטעון את מקצועות המנהלים: "+err.message,"p")));
4670
+ }
4671
  const flagGroupOpen={}; // reporter -> whether their group of reports is open; closed until the teacher opens it
4672
  let systemActivityOpen=false; // the recent activity starts closed; a redraw keeps it as the teacher left it
4673
  function drawSystemActivity(box){
 
4876
  const card=mark("card",""), top=mark("chead",""), name=mark("","","h2"), n=document.createElement("bdi"), edit=mark("btn","עריכה","button"), del=mark("btn danger","מחיקה","button");
4877
  n.textContent=c.name; name.append(n); edit.onclick=()=>editClass(c); del.onclick=()=>deleteClass(c); top.append(name,edit,del);
4878
  const facts=mark("facts","","dl"), fact=(what,...value)=>{ const dd=document.createElement("dd"); dd.append(...value); facts.append(mark("",what,"dt"),dd); };
4879
+ fact("מקצוע",c.subject||"לא הוגדר");
4880
  fact("שיעורים",lessonsLine(ALL_LESSONS.filter(l=>c.lessons.includes(l.id))));
4881
  const mine=CLASS.students.filter(s=>c.name in s.classes);
4882
  fact("תלמידים",...(mine.length?[`${mine.length}: `,...mine.flatMap((s,k)=>{ const b=document.createElement("bdi"); b.textContent=s.classes[c.name]||s.name||s.email; return k?[", ",b]:[b]; })]:["עוד אין"]));
tests/test_scoring.py CHANGED
@@ -2,6 +2,7 @@
2
  import io
3
  import re
4
  import wave
 
5
 
6
  import numpy as np
7
  import pytest
@@ -1323,9 +1324,9 @@ def test_sign_in_guards_the_practice_endpoints():
1323
  self.rank = self.rank | {email} if on else self.rank - {email}
1324
  self.by = by
1325
 
1326
- def save_class(self, id, name, emails, nicknames, lessons, homeworks=(), dailies=None):
1327
  row = {"name": name, "emails": emails, "nicknames": nicknames, "lessons": lessons, "homeworks": list(homeworks),
1328
- **({} if dailies is None else {"dailies": list(dailies)})}
1329
  if id is None:
1330
  self.cls.insert(0, {"id": len(self.cls) + 1, **row})
1331
  elif c := next((c for c in self.cls if c["id"] == id), None):
@@ -1682,10 +1683,14 @@ def test_sign_in_guards_the_practice_endpoints():
1682
  assert token == "good" and row["phrase"] == TOILET["he"] and row["cat"] == TOILET["cat"]
1683
  assert row["score"] == round(r.json()["score"]) and row["unrelated"] is False
1684
  assert c.get("/api/progress").status_code == 401
1685
- assert c.get("/api/progress", headers={"Authorization": "Bearer good"}).json() == {
 
1686
  "best": {str(PHRASES.index(VERB)): 88}, "tries": {str(PHRASES.index(VERB)): 2}, "recordings": 3, "days": 2}
 
 
1687
  with TestClient(create_app(scorer_for(emissions(["w"])))) as c: # no sign-in: nothing to show
1688
- assert c.get("/api/progress").json() == {"best": {}, "tries": {}, "recordings": 0, "days": 0}
 
1689
  with TestClient(create_app(scorer_for(emissions(["w"])))) as c: # not configured: open, as before
1690
  assert 'AUTH_URL=""' in c.get("/").text and c.get("/api/tts/0").status_code == 503
1691
 
@@ -2012,3 +2017,23 @@ def test_trace_carries_frames_curves_and_paths():
2012
  assert all(v["tokens"] for v in t["variants"]) and sum(v["chosen"] for v in t["variants"]) == 1
2013
  e = frame_energy(np.r_[np.zeros(320), np.ones(320)], 2)
2014
  assert np.allclose(e, [0, 1])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
  import io
3
  import re
4
  import wave
5
+ from dataclasses import replace
6
 
7
  import numpy as np
8
  import pytest
 
1324
  self.rank = self.rank | {email} if on else self.rank - {email}
1325
  self.by = by
1326
 
1327
+ def save_class(self, id, name, emails, nicknames, lessons, homeworks=(), dailies=None, subject=""):
1328
  row = {"name": name, "emails": emails, "nicknames": nicknames, "lessons": lessons, "homeworks": list(homeworks),
1329
+ **({} if dailies is None else {"dailies": list(dailies)}), **({"subject": subject} if id is None and subject else {})}
1330
  if id is None:
1331
  self.cls.insert(0, {"id": len(self.cls) + 1, **row})
1332
  elif c := next((c for c in self.cls if c["id"] == id), None):
 
1683
  assert token == "good" and row["phrase"] == TOILET["he"] and row["cat"] == TOILET["cat"]
1684
  assert row["score"] == round(r.json()["score"]) and row["unrelated"] is False
1685
  assert c.get("/api/progress").status_code == 401
1686
+ progress = c.get("/api/progress", headers={"Authorization": "Bearer good"}).json()
1687
+ assert {k: progress[k] for k in ("best", "tries", "recordings", "days")} == {
1688
  "best": {str(PHRASES.index(VERB)): 88}, "tries": {str(PHRASES.index(VERB)): 2}, "recordings": 3, "days": 2}
1689
+ assert 0 <= progress["week_days"] <= 7
1690
+ assert set(progress["streak"]) == {"current", "best", "last"}
1691
  with TestClient(create_app(scorer_for(emissions(["w"])))) as c: # no sign-in: nothing to show
1692
+ assert c.get("/api/progress").json() == {"best": {}, "tries": {}, "recordings": 0, "days": 0,
1693
+ "week_days": 0, "streak": {"current": 0, "best": 0, "last": None}}
1694
  with TestClient(create_app(scorer_for(emissions(["w"])))) as c: # not configured: open, as before
1695
  assert 'AUTH_URL=""' in c.get("/").text and c.get("/api/tts/0").status_code == 503
1696
 
 
2017
  assert all(v["tokens"] for v in t["variants"]) and sum(v["chosen"] for v in t["variants"]) == 1
2018
  e = frame_energy(np.r_[np.zeros(320), np.ones(320)], 2)
2019
  assert np.allclose(e, [0, 1])
2020
+
2021
+
2022
+ def test_flag_threshold_per_sound():
2023
+ # ħ said as χ: flagged at the global 50, not once its own threshold is under the score; other sounds unchanged
2024
+ logp = emissions(["w", "eː", "n", "i", "l", "χ", "a", "m", "aː", "m"])
2025
+ scorer = scorer_for(logp)
2026
+ h = lambda r: next(p for w in r["words"] for p in w["phonemes"] if p["ipa"] == "ħ")
2027
+ before = h(scorer.score(None, TOILET))
2028
+ assert before["flagged"] and before["heard"] == "χ"
2029
+ scorer.cfg = replace(scorer.cfg, flag_below_sound={"ħ": before["score"]})
2030
+ r = scorer.score_logp(logp, TOILET, diagnostics=True)
2031
+ assert not h(r)["flagged"] and h(r)["score"] == before["score"]
2032
+ assert r["trace"]["config"]["flag_below_sound"] == {"ħ": before["score"]}
2033
+
2034
+
2035
+ def test_flag_thresholds_belong_to_their_model():
2036
+ from app.scorer import scorer_config
2037
+ assert scorer_config("facebook/wav2vec2-xlsr-53-espeak-cv-ft").flag_below_sound == {"ħ": 20.0}
2038
+ assert scorer_config("checkpoints/ihki-ft").flag_below_sound == {}
2039
+ assert scorer_config("checkpoints/ihki-ft").flag_below == 50
train/finetune.py CHANGED
@@ -11,6 +11,9 @@ which is exactly what the scorer depends on.
11
  Example:
12
  python -m train.finetune --train data/train.csv --eval data/eval.csv --out checkpoints/ihki-ft
13
  Then serve it with MODEL_ID=checkpoints/ihki-ft.
 
 
 
14
  """
15
  from __future__ import annotations
16
 
@@ -85,6 +88,11 @@ def main():
85
  ap.add_argument("--epochs", type=float, default=20)
86
  ap.add_argument("--lr", type=float, default=3e-5)
87
  ap.add_argument("--batch", type=int, default=8)
 
 
 
 
 
88
  args = ap.parse_args()
89
 
90
  vocab_path = hf_hub_download(args.base, "vocab.json") if not Path(args.base).is_dir() else str(Path(args.base) / "vocab.json")
@@ -93,6 +101,15 @@ def main():
93
  model = Wav2Vec2ForCTC.from_pretrained(args.base, ctc_loss_reduction="mean", ctc_zero_infinity=True,
94
  pad_token_id=vocab.blank)
95
  model.freeze_feature_encoder() # small data: train only the transformer + CTC head
 
 
 
 
 
 
 
 
 
96
 
97
  train_ds = PhonemeDataset(args.train, vocab, fe)
98
  eval_ds = PhonemeDataset(args.eval, vocab, fe)
@@ -101,10 +118,12 @@ def main():
101
 
102
  targs = TrainingArguments(
103
  output_dir=args.out, per_device_train_batch_size=args.batch, per_device_eval_batch_size=args.batch,
104
- gradient_accumulation_steps=max(1, 32 // args.batch), learning_rate=args.lr, warmup_ratio=0.1,
105
  num_train_epochs=args.epochs, eval_strategy="epoch", save_strategy="epoch", save_total_limit=2,
106
  load_best_model_at_end=True, metric_for_best_model="per", greater_is_better=False,
107
  fp16=torch.cuda.is_available(), logging_steps=10, report_to="none", remove_unused_columns=False,
 
 
108
  )
109
  trainer = Trainer(model=model, args=targs, train_dataset=train_ds, eval_dataset=eval_ds,
110
  data_collator=Collator(fe), compute_metrics=per_metric(vocab.blank),
 
11
  Example:
12
  python -m train.finetune --train data/train.csv --eval data/eval.csv --out checkpoints/ihki-ft
13
  Then serve it with MODEL_ID=checkpoints/ihki-ft.
14
+
15
+ On a small GPU (6GB): --train-layers 8 --optim adamw_bnb_8bit --checkpointing --batch 2
16
+ (the batch is accumulated to 32 either way, so only memory and speed change).
17
  """
18
  from __future__ import annotations
19
 
 
88
  ap.add_argument("--epochs", type=float, default=20)
89
  ap.add_argument("--lr", type=float, default=3e-5)
90
  ap.add_argument("--batch", type=int, default=8)
91
+ ap.add_argument("--train-layers", type=int, default=0,
92
+ help="train only the top N transformer layers and the CTC head (0: all layers)")
93
+ ap.add_argument("--optim", default="adamw_torch", help="e.g. adamw_bnb_8bit to cut optimizer memory by ~4x")
94
+ ap.add_argument("--checkpointing", action="store_true", help="gradient checkpointing: less memory, ~30%% slower")
95
+ ap.add_argument("--max-steps", type=int, default=-1, help="stop after this many steps (a quick memory check)")
96
  args = ap.parse_args()
97
 
98
  vocab_path = hf_hub_download(args.base, "vocab.json") if not Path(args.base).is_dir() else str(Path(args.base) / "vocab.json")
 
101
  model = Wav2Vec2ForCTC.from_pretrained(args.base, ctc_loss_reduction="mean", ctc_zero_infinity=True,
102
  pad_token_id=vocab.blank)
103
  model.freeze_feature_encoder() # small data: train only the transformer + CTC head
104
+ if args.train_layers:
105
+ layers = model.wav2vec2.encoder.layers
106
+ for p in model.wav2vec2.parameters():
107
+ p.requires_grad = False
108
+ for part in [*layers[len(layers) - args.train_layers:], model.wav2vec2.encoder.layer_norm]:
109
+ for p in part.parameters():
110
+ p.requires_grad = True
111
+ trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)
112
+ print(f"training {trainable / 1e6:.0f}M of {sum(p.numel() for p in model.parameters()) / 1e6:.0f}M parameters")
113
 
114
  train_ds = PhonemeDataset(args.train, vocab, fe)
115
  eval_ds = PhonemeDataset(args.eval, vocab, fe)
 
118
 
119
  targs = TrainingArguments(
120
  output_dir=args.out, per_device_train_batch_size=args.batch, per_device_eval_batch_size=args.batch,
121
+ gradient_accumulation_steps=max(1, 32 // args.batch), learning_rate=args.lr, warmup_steps=0.1,
122
  num_train_epochs=args.epochs, eval_strategy="epoch", save_strategy="epoch", save_total_limit=2,
123
  load_best_model_at_end=True, metric_for_best_model="per", greater_is_better=False,
124
  fp16=torch.cuda.is_available(), logging_steps=10, report_to="none", remove_unused_columns=False,
125
+ optim=args.optim, gradient_checkpointing=args.checkpointing,
126
+ gradient_checkpointing_kwargs={"use_reentrant": False}, max_steps=args.max_steps,
127
  )
128
  trainer = Trainer(model=model, args=targs, train_dataset=train_ds, eval_dataset=eval_ds,
129
  data_collator=Collator(fe), compute_metrics=per_metric(vocab.blank),