feat: Implement speech evaluation service and verb game mechanics
Browse files- Add SpeechEvaluationService for handling speech scoring with uncertainty management.
- Introduce verb game mechanics for generating exercises and server-side checking for "פועל יוצא" levels 1-5.
- Create tests for speech evaluation and verb game functionalities to ensure correctness and reliability.
- Enhance existing test suite with new scenarios for tutor and student interactions in the scoring system.
- .env.example +5 -0
- README.md +65 -1
- app/auth.py +69 -4
- app/main.py +147 -2
- app/phrases.py +1 -1
- app/speech_evaluation.py +28 -0
- app/verb_game.py +298 -0
- app/workbook.py +56 -4
- static/index.html +426 -31
- tests/test_scoring.py +110 -2
- tests/test_speech_evaluation.py +23 -0
- tests/test_verb_game.py +91 -0
.env.example
CHANGED
|
@@ -22,3 +22,8 @@ TEACHER_EMAILS=
|
|
| 22 |
# Needed by the management panel and the classes: the project's secret key (Project Settings -> API Keys -> secret, or the
|
| 23 |
# legacy service_role key). It reads every student's rows, so it is NOT public: on Hugging Face set it as a *secret*.
|
| 24 |
SUPABASE_SECRET_KEY=
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
# Needed by the management panel and the classes: the project's secret key (Project Settings -> API Keys -> secret, or the
|
| 23 |
# legacy service_role key). It reads every student's rows, so it is NOT public: on Hugging Face set it as a *secret*.
|
| 24 |
SUPABASE_SECRET_KEY=
|
| 25 |
+
|
| 26 |
+
# Optional: accounts (separated by commas or spaces) that, like the teachers, get a flag under each score, for a recording they said
|
| 27 |
+
# right and the system scored wrong. A flag is kept in the Supabase table `flags` with its recording (see the README),
|
| 28 |
+
# so it needs SUPABASE_SECRET_KEY. These accounts may sign in without being in a class.
|
| 29 |
+
TUTORS_EMAIL=
|
README.md
CHANGED
|
@@ -35,7 +35,8 @@ app/
|
|
| 35 |
phrases.py phrase bank: accepted variants (Arabic + IPA) per phrase
|
| 36 |
grammar.py day-2 sentences as grammar: every pronoun × positive/negative, for the negation and conjugation buttons
|
| 37 |
workbook.py the course workbook lesson by lesson: each lesson's topics (pronouns, verbs, conjugations, the Hebrew → Arabic and Arabic → Hebrew sentences), and the levels
|
| 38 |
-
|
|
|
|
| 39 |
static/index.html frontend (MediaRecorder → /api/score)
|
| 40 |
train/finetune.py CTC fine-tuning on your own recordings
|
| 41 |
tests/ synthetic-emission tests, including an API test through ffmpeg
|
|
@@ -60,6 +61,21 @@ Tests (no model needed):
|
|
| 60 |
pip install -r requirements-dev.txt && pytest -q
|
| 61 |
```
|
| 62 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
## Deploy for the teacher: Hugging Face Spaces (free, https)
|
| 64 |
|
| 65 |
1. Create a Space at huggingface.co → New Space → SDK **Docker** → hardware **CPU basic** (free).
|
|
@@ -104,6 +120,54 @@ The page's "ההתקדמות שלי" button reads these rows back through `GET /
|
|
| 104 |
|
| 105 |
`TEACHER_EMAILS` names the teacher's Google account (several are separated by commas or spaces). After sign-in a teacher chooses between **תרגול**, the same practice a student gets, and **ניהול**, the management panel. The panel lists every student with their usage (recordings, those of the last 7 days, days practised, last practice), progress (sentences practised) and grade (the average of the best scores), and pressing a student opens their own screen in place of the class's: their figures, their homework, every lesson of the class with its topics, and their best and weakest sentences, all counted as the class counts. "חזרה לכיתה", or the browser's back button, returns to the class.
|
| 106 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 107 |
### Levels
|
| 108 |
|
| 109 |
The course has levels, each with a planned number of lessons (`LEVELS` in `app/workbook.py`: שלב א and שלב ב, 10 lessons each). Every lesson in `LESSONS` is keyed by its level and number, `(level, lesson)`; one outside the plan stops the app at startup. The path shows each level under its name, and the lessons not written yet as "בקרוב". Level 1's lessons keep their first ids ("1", topics "l1-…") so recorded attempts and saved classes still match; later levels' are "2.1", topics "l2.1-…".
|
|
|
|
| 35 |
phrases.py phrase bank: accepted variants (Arabic + IPA) per phrase
|
| 36 |
grammar.py day-2 sentences as grammar: every pronoun × positive/negative, for the negation and conjugation buttons
|
| 37 |
workbook.py the course workbook lesson by lesson: each lesson's topics (pronouns, verbs, conjugations, the Hebrew → Arabic and Arabic → Hebrew sentences), and the levels
|
| 38 |
+
verb_game.py "פועל יוצא" levels 1–5: exercise generation, adaptive choice, server-side grading
|
| 39 |
+
main.py FastAPI: page, phrases/scoring, and "פועל יוצא" endpoints
|
| 40 |
static/index.html frontend (MediaRecorder → /api/score)
|
| 41 |
train/finetune.py CTC fine-tuning on your own recordings
|
| 42 |
tests/ synthetic-emission tests, including an API test through ffmpeg
|
|
|
|
| 61 |
pip install -r requirements-dev.txt && pytest -q
|
| 62 |
```
|
| 63 |
|
| 64 |
+
## פועל יוצא (Switch & Speak)
|
| 65 |
+
|
| 66 |
+
The Games tab contains an RTL, touch-first conjugation drill with two paths: learning new verbs and a daily retrieval workout. Levels 1–3 implement recognition, pronoun matching, and timed switching. Level 4 records a spoken conjugation; Level 5 starts with a controlled Palestinian-Arabic prompt and evaluates the target conjugation in the response.
|
| 67 |
+
|
| 68 |
+
Conjugations come only from complete tables in `app/grammar.py` and the fully populated tables verified from the parsed Level 1/2 booklets. Every added booklet form must resolve to an Arabic entry in `workbook.LEX`; incomplete fill-in tables are excluded. Each verb carries the lesson where it is introduced, and signed-in learners receive only forms from their class's lessons.
|
| 69 |
+
|
| 70 |
+
API endpoints:
|
| 71 |
+
|
| 72 |
+
- `GET /api/verb-game` returns the available levels, tenses, and lesson-unlocked verbs.
|
| 73 |
+
- `POST /api/verb-game/question` accepts `{"level": 1..3, "mastery": {...}, "recent": [...]}` and returns an opaque question. Correct answers are not sent to the browser.
|
| 74 |
+
- `POST /api/verb-game/answer` accepts `{"question_id": "...", "answer": ..., "response_ms": 1234}`. A question can be graded only once. For Level 2, `answer` is a map from pronoun-card IDs to form-card IDs.
|
| 75 |
+
- `POST /api/verb-game/speech` accepts multipart `question_id` and `audio` for Levels 4–5. `SpeechEvaluationService` wraps the existing phoneme scorer so another dialect ASR can replace it later. An unrelated or low-confidence recognition returns `outcome: "uncertain"` and `counts_as_attempt: false`; it never becomes a grammatical error automatically.
|
| 76 |
+
|
| 77 |
+
Mastery is currently stored in browser local storage under `ihki.verbMastery` and `ihki.verbSummary`. `VERB_THRESH` in `static/index.html` configures the 85%/90% recognition gates, the Level 3 median response-time gate, and the 85% spoken-response gate; minimum attempt counts are defined next to it. `LEVELS` in `app/verb_game.py` configures choice counts and response windows. Persistent server mastery and spaced repetition remain separate work.
|
| 78 |
+
|
| 79 |
## Deploy for the teacher: Hugging Face Spaces (free, https)
|
| 80 |
|
| 81 |
1. Create a Space at huggingface.co → New Space → SDK **Docker** → hardware **CPU basic** (free).
|
|
|
|
| 120 |
|
| 121 |
`TEACHER_EMAILS` names the teacher's Google account (several are separated by commas or spaces). After sign-in a teacher chooses between **תרגול**, the same practice a student gets, and **ניהול**, the management panel. The panel lists every student with their usage (recordings, those of the last 7 days, days practised, last practice), progress (sentences practised) and grade (the average of the best scores), and pressing a student opens their own screen in place of the class's: their figures, their homework, every lesson of the class with its topics, and their best and weakest sentences, all counted as the class counts. "חזרה לכיתה", or the browser's back button, returns to the class.
|
| 122 |
|
| 123 |
+
### Flags: a score that is wrong
|
| 124 |
+
|
| 125 |
+
Sometimes a sentence is said right and the system scores it wrong. The teachers (`TEACHER_EMAILS`) report such cases, and `TUTORS_EMAIL` names more accounts that do (several are separated by commas or spaces; they may sign in without being in a class, and get no management panel). The teacher also gives a student this tutor's rank in the panel: at the top of **תלמידים**, the part "🚩 מדווחים על ציונים שגויים" opens a list of every student of every class, each with a box to tick. The rank is the student's, whatever classes they are in, and by itself lets nobody sign in; the panel marks such a student with 🚩 in every class (`PUT /api/tutors`, teachers only: `{"email", "tutor": true|false}`). It is kept by email in the table `tutors`; create it once (until then the panel shows this command):
|
| 126 |
+
|
| 127 |
+
```sql
|
| 128 |
+
create table public.tutors (
|
| 129 |
+
email text primary key,
|
| 130 |
+
granted_by text not null default '', -- the teacher who gave the rank
|
| 131 |
+
created_at timestamptz not null default now()
|
| 132 |
+
);
|
| 133 |
+
alter table public.tutors enable row level security; -- no policy: only the secret key reads and writes it
|
| 134 |
+
```
|
| 135 |
+
|
| 136 |
+
Under each score a teacher or a tutor gets an optional note and the button "🚩 אמרתי נכון, המערכת טעתה". Pressing it sends the recording to `POST /api/flags` (teachers and tutors only), which scores it again and keeps what describes the case in the table `flags`, written with `SUPABASE_SECRET_KEY`. A box then shows what was kept in words: the sentence, what the model heard, each word's score, the sounds that were marked down and what took their place, and whether the recording was stored. The row holds:
|
| 137 |
+
|
| 138 |
+
- who and what: `email`, `cat`, `phrase`, `he`, `note`;
|
| 139 |
+
- the answer the scorer matched (`ar`, `ipa`), its free decode (`heard_ipa`), `score` and `unrelated`;
|
| 140 |
+
- `result`: the whole score response (every word and phoneme with its score and what took its place, the tips, the issues);
|
| 141 |
+
- `model` and `version`, so a flag can be checked against the model and build that produced it;
|
| 142 |
+
- `audio`: the recording's name in the private storage bucket `flags` (null when it could not be stored).
|
| 143 |
+
|
| 144 |
+
Create the table and the bucket once (until then a flag is refused with this command in the message):
|
| 145 |
+
|
| 146 |
+
```sql
|
| 147 |
+
create table public.flags (
|
| 148 |
+
id bigint generated always as identity primary key,
|
| 149 |
+
email text not null, -- the tutor
|
| 150 |
+
cat text not null, -- the topic id
|
| 151 |
+
phrase text not null,
|
| 152 |
+
he text not null, -- the Hebrew prompt
|
| 153 |
+
ar text not null, -- the accepted answer the scorer matched
|
| 154 |
+
ipa text not null, -- its phonemes: what the tutor says was said
|
| 155 |
+
heard_ipa text not null, -- the model's free decode
|
| 156 |
+
score int not null,
|
| 157 |
+
unrelated boolean not null default false,
|
| 158 |
+
note text not null default '',
|
| 159 |
+
result jsonb not null, -- the whole score response
|
| 160 |
+
model text not null,
|
| 161 |
+
version text not null default '',
|
| 162 |
+
audio text, -- the recording's name in the storage bucket flags
|
| 163 |
+
created_at timestamptz not null default now()
|
| 164 |
+
);
|
| 165 |
+
alter table public.flags enable row level security; -- no policy: only the secret key reads and writes it
|
| 166 |
+
insert into storage.buckets (id, name) values ('flags', 'flags') on conflict (id) do nothing;
|
| 167 |
+
```
|
| 168 |
+
|
| 169 |
+
The rows are for the teacher to read later in Supabase (Table Editor → `flags`; the recordings under Storage → `flags`), to change the scoring or its calibration. As a flag says the sentence was said as written, `audio,ipa` of these rows is training data in the format `train/finetune.py` reads (see "Fine-tuning").
|
| 170 |
+
|
| 171 |
### Levels
|
| 172 |
|
| 173 |
The course has levels, each with a planned number of lessons (`LEVELS` in `app/workbook.py`: שלב א and שלב ב, 10 lessons each). Every lesson in `LESSONS` is keyed by its level and number, `(level, lesson)`; one outside the plan stops the app at startup. The path shows each level under its name, and the lessons not written yet as "בקרוב". Level 1's lessons keep their first ids ("1", topics "l1-…") so recorded attempts and saved classes still match; later levels' are "2.1", topics "l2.1-…".
|
app/auth.py
CHANGED
|
@@ -30,6 +30,13 @@ students get a reminder above the path to watch it.
|
|
| 30 |
Library: other videos (a title and a link each), in the Supabase table `library`, one for every level. Every student
|
| 31 |
browses them from the tab at the screen's foot, whatever their level and class.
|
| 32 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
Writing: a lesson's written homework (see workbook.py) is kept in the Supabase table `writings`, a row per student
|
| 34 |
and topic, written with the student's own token like the attempts, so it follows them to any device. The panel
|
| 35 |
reads every student's with the secret key.
|
|
@@ -37,7 +44,8 @@ reads every student's with the secret key.
|
|
| 37 |
Env: SUPABASE_URL (https://<project-ref>.supabase.co)
|
| 38 |
SUPABASE_PUBLISHABLE_KEY (the publishable/anon key; it is public and also goes to the page)
|
| 39 |
TEACHER_EMAILS (optional: the accounts with the management panel, separated by commas or spaces)
|
| 40 |
-
|
|
|
|
| 41 |
Without them the service is open, as before.
|
| 42 |
"""
|
| 43 |
from __future__ import annotations
|
|
@@ -71,14 +79,17 @@ class ClassConflict(ValueError):
|
|
| 71 |
|
| 72 |
|
| 73 |
class SupabaseAuth:
|
| 74 |
-
def __init__(self, url: str, key: str, teachers: frozenset[str] = frozenset(), secret: str = ""
|
|
|
|
| 75 |
self.url, self.key = url.rstrip("/"), key
|
| 76 |
self.teachers = teachers # lower-case emails of the accounts with the management panel
|
|
|
|
| 77 |
self.secret = secret # reads every student's rows and the classes; empty = the panel has no data
|
| 78 |
self._cache: dict[str, tuple[float, dict]] = {}
|
| 79 |
self._classes: tuple[float, list[dict]] | None = None
|
| 80 |
self._videos: tuple[float, list[dict]] | None = None
|
| 81 |
self._texts: tuple[float, list[dict]] | None = None
|
|
|
|
| 82 |
self._level_videos: dict[str, tuple[float, list[dict]]] = {} # by table: the daily videos, the library
|
| 83 |
self._lock = threading.Lock()
|
| 84 |
|
|
@@ -361,6 +372,58 @@ class SupabaseAuth:
|
|
| 361 |
self._admin(f"/rest/v1/{table}?id=eq.{int(id)}", "DELETE")
|
| 362 |
self._level_videos.pop(table, None)
|
| 363 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 364 |
def users(self) -> list[dict]:
|
| 365 |
"""Every account that has signed in: id, email, name (as Google gave it; empty for one who signed in by email)."""
|
| 366 |
users: list[dict] = []
|
|
@@ -396,11 +459,13 @@ def load_auth() -> SupabaseAuth | None:
|
|
| 396 |
" and ".join(missing), seen or "none")
|
| 397 |
return None
|
| 398 |
emails = lambda name: frozenset(re.split(r"[\s,;]+", os.environ.get(name, "").strip().lower())) - {""}
|
| 399 |
-
teachers = emails("TEACHER_EMAILS")
|
| 400 |
secret = os.environ.get("SUPABASE_SECRET_KEY", "").strip()
|
| 401 |
log.info("sign-in on: %s", "the students of the classes" if secret else "any account (no SUPABASE_SECRET_KEY)")
|
| 402 |
if os.environ.get("ALLOWED_EMAILS", "").strip():
|
| 403 |
log.warning("ALLOWED_EMAILS is no longer read: the teacher lists the students in the panel's classes")
|
| 404 |
if teachers and not secret:
|
| 405 |
log.warning("TEACHER_EMAILS is set without SUPABASE_SECRET_KEY: the management panel has no data to show")
|
| 406 |
-
|
|
|
|
|
|
|
|
|
| 30 |
Library: other videos (a title and a link each), in the Supabase table `library`, one for every level. Every student
|
| 31 |
browses them from the tab at the screen's foot, whatever their level and class.
|
| 32 |
|
| 33 |
+
Tutors: the teacher gives a student the tutor's rank in the panel, in the list of all the students above the classes' tabs. It is the student's,
|
| 34 |
+
whatever classes they are in, so it is kept by email in the Supabase table `tutors`.
|
| 35 |
+
|
| 36 |
+
Flags: a teacher, a tutor, and an account in TUTORS_EMAIL, gets a flag under each score, for a recording that was said right and scored
|
| 37 |
+
wrong. A flag keeps what describes the case in the Supabase table `flags`, and the recording itself in the storage
|
| 38 |
+
bucket `flags`, both written with the secret key: the material for changing the scoring, and later for fine-tuning.
|
| 39 |
+
|
| 40 |
Writing: a lesson's written homework (see workbook.py) is kept in the Supabase table `writings`, a row per student
|
| 41 |
and topic, written with the student's own token like the attempts, so it follows them to any device. The panel
|
| 42 |
reads every student's with the secret key.
|
|
|
|
| 44 |
Env: SUPABASE_URL (https://<project-ref>.supabase.co)
|
| 45 |
SUPABASE_PUBLISHABLE_KEY (the publishable/anon key; it is public and also goes to the page)
|
| 46 |
TEACHER_EMAILS (optional: the accounts with the management panel, separated by commas or spaces)
|
| 47 |
+
TUTORS_EMAIL (optional: more accounts that flag a wrong score, as the teachers do; separated by commas or spaces)
|
| 48 |
+
SUPABASE_SECRET_KEY (the secret/service-role key, needed by the panel, the classes and the flags; never public)
|
| 49 |
Without them the service is open, as before.
|
| 50 |
"""
|
| 51 |
from __future__ import annotations
|
|
|
|
| 79 |
|
| 80 |
|
| 81 |
class SupabaseAuth:
|
| 82 |
+
def __init__(self, url: str, key: str, teachers: frozenset[str] = frozenset(), secret: str = "",
|
| 83 |
+
tutors: frozenset[str] = frozenset()):
|
| 84 |
self.url, self.key = url.rstrip("/"), key
|
| 85 |
self.teachers = teachers # lower-case emails of the accounts with the management panel
|
| 86 |
+
self.tutors = tutors # lower-case emails of the accounts that flag a wrong score, besides the teachers
|
| 87 |
self.secret = secret # reads every student's rows and the classes; empty = the panel has no data
|
| 88 |
self._cache: dict[str, tuple[float, dict]] = {}
|
| 89 |
self._classes: tuple[float, list[dict]] | None = None
|
| 90 |
self._videos: tuple[float, list[dict]] | None = None
|
| 91 |
self._texts: tuple[float, list[dict]] | None = None
|
| 92 |
+
self._ranked: tuple[float, frozenset[str] | None] | None = None
|
| 93 |
self._level_videos: dict[str, tuple[float, list[dict]]] = {} # by table: the daily videos, the library
|
| 94 |
self._lock = threading.Lock()
|
| 95 |
|
|
|
|
| 372 |
self._admin(f"/rest/v1/{table}?id=eq.{int(id)}", "DELETE")
|
| 373 |
self._level_videos.pop(table, None)
|
| 374 |
|
| 375 |
+
def ranked(self, fresh: bool = False) -> frozenset[str] | None:
|
| 376 |
+
"""The lower-case emails the teacher gave the tutor's rank (the table `tutors`). Kept for CLASSES_TTL, as each
|
| 377 |
+
sign-in check asks. None before the table is created; without the secret key there are none."""
|
| 378 |
+
now = time.monotonic()
|
| 379 |
+
with self._lock:
|
| 380 |
+
hit = self._ranked
|
| 381 |
+
if hit and hit[0] > now and not fresh:
|
| 382 |
+
return hit[1]
|
| 383 |
+
emails: frozenset[str] | None = frozenset()
|
| 384 |
+
if self.secret:
|
| 385 |
+
try:
|
| 386 |
+
emails = frozenset(r["email"].lower() for r in self._admin("/rest/v1/tutors?select=email"))
|
| 387 |
+
except AuthUnavailable as e:
|
| 388 |
+
if "answered 404" not in str(e):
|
| 389 |
+
raise
|
| 390 |
+
log.warning("the table `tutors` is missing (see the README): no student has the tutor's rank")
|
| 391 |
+
emails = None
|
| 392 |
+
with self._lock:
|
| 393 |
+
self._ranked = (now + CLASSES_TTL, emails)
|
| 394 |
+
return emails
|
| 395 |
+
|
| 396 |
+
def set_tutor(self, email: str, on: bool, by: str) -> None:
|
| 397 |
+
"""Gives the account of this email the tutor's rank, or takes it back. `by` is the teacher who gave it."""
|
| 398 |
+
email = email.lower()
|
| 399 |
+
try:
|
| 400 |
+
if on:
|
| 401 |
+
self._admin("/rest/v1/tutors", "POST", {"email": email, "granted_by": by})
|
| 402 |
+
else:
|
| 403 |
+
self._admin(f"/rest/v1/tutors?email=eq.{urllib.parse.quote(email)}", "DELETE")
|
| 404 |
+
except ClassConflict: # has it already
|
| 405 |
+
pass
|
| 406 |
+
finally:
|
| 407 |
+
self._ranked = None
|
| 408 |
+
|
| 409 |
+
def add_flag(self, row: dict, audio: bytes, mime: str, name: str) -> bool:
|
| 410 |
+
"""Keeps a flagged score: the recording in the storage bucket `flags` under `name`, and the row in the table
|
| 411 |
+
`flags` with that name as its `audio`. A recording that cannot be stored is logged and the row is kept
|
| 412 |
+
without it (`audio` null); False tells that. A row that cannot be kept is raised."""
|
| 413 |
+
kept = False
|
| 414 |
+
if self.secret:
|
| 415 |
+
req = urllib.request.Request(
|
| 416 |
+
f"{self.url}/storage/v1/object/flags/{urllib.parse.quote(name)}", data=audio, method="POST",
|
| 417 |
+
headers={"Authorization": f"Bearer {self.secret}", "apikey": self.secret, "Content-Type": mime,
|
| 418 |
+
"User-Agent": "ihki/1.0"})
|
| 419 |
+
try:
|
| 420 |
+
urllib.request.urlopen(req, timeout=TIMEOUT).close()
|
| 421 |
+
kept = True
|
| 422 |
+
except (urllib.error.URLError, TimeoutError) as e: # HTTPError is a URLError
|
| 423 |
+
log.warning("a flag's recording not stored (is there a storage bucket `flags`? see the README): %s", e)
|
| 424 |
+
self._admin("/rest/v1/flags", "POST", {**row, "audio": name if kept else None})
|
| 425 |
+
return kept
|
| 426 |
+
|
| 427 |
def users(self) -> list[dict]:
|
| 428 |
"""Every account that has signed in: id, email, name (as Google gave it; empty for one who signed in by email)."""
|
| 429 |
users: list[dict] = []
|
|
|
|
| 459 |
" and ".join(missing), seen or "none")
|
| 460 |
return None
|
| 461 |
emails = lambda name: frozenset(re.split(r"[\s,;]+", os.environ.get(name, "").strip().lower())) - {""}
|
| 462 |
+
teachers, tutors = emails("TEACHER_EMAILS"), emails("TUTORS_EMAIL")
|
| 463 |
secret = os.environ.get("SUPABASE_SECRET_KEY", "").strip()
|
| 464 |
log.info("sign-in on: %s", "the students of the classes" if secret else "any account (no SUPABASE_SECRET_KEY)")
|
| 465 |
if os.environ.get("ALLOWED_EMAILS", "").strip():
|
| 466 |
log.warning("ALLOWED_EMAILS is no longer read: the teacher lists the students in the panel's classes")
|
| 467 |
if teachers and not secret:
|
| 468 |
log.warning("TEACHER_EMAILS is set without SUPABASE_SECRET_KEY: the management panel has no data to show")
|
| 469 |
+
if tutors and not secret:
|
| 470 |
+
log.warning("TUTORS_EMAIL is set without SUPABASE_SECRET_KEY: a flag cannot be saved")
|
| 471 |
+
return SupabaseAuth(url, key, teachers, secret, tutors)
|
app/main.py
CHANGED
|
@@ -5,6 +5,7 @@ Env: MODEL_ID (default facebook/wav2vec2-xlsr-53-espeak-cv-ft, or a path to a
|
|
| 5 |
SAWTAK_API_KEY, SAWTAK_VOICE_ID (model-answer playback, see app/tts.py)
|
| 6 |
SUPABASE_URL, SUPABASE_PUBLISHABLE_KEY (Google sign-in, see app/auth.py)
|
| 7 |
TEACHER_EMAILS, SUPABASE_SECRET_KEY (the teacher's management panel, its classes and the lesson videos, see app/auth.py)
|
|
|
|
| 8 |
A local .env file is loaded if present; real environment variables win over it.
|
| 9 |
"""
|
| 10 |
from __future__ import annotations
|
|
@@ -15,6 +16,7 @@ import os
|
|
| 15 |
import re
|
| 16 |
import time
|
| 17 |
import urllib.parse
|
|
|
|
| 18 |
from contextlib import asynccontextmanager
|
| 19 |
from datetime import date, datetime, timedelta, timezone
|
| 20 |
from pathlib import Path
|
|
@@ -30,8 +32,10 @@ from .phrases import CATEGORIES, GAMES, LESSONS, LEVELS, PHRASES, public_phrases
|
|
| 30 |
from .prompt_tts import ENGINES, PromptTTSUnavailable, hebrew_mp3
|
| 31 |
from .reference import References
|
| 32 |
from .scorer import Scorer, decode_audio, load_scorer
|
|
|
|
| 33 |
from .texts import read_line, text_phrases
|
| 34 |
from .tts import VOICES, SawtakTTS, TTSUnavailable, load_tts
|
|
|
|
| 35 |
|
| 36 |
logging.basicConfig(level=logging.INFO)
|
| 37 |
log = logging.getLogger("ihki")
|
|
@@ -112,6 +116,19 @@ CREATE_WRITINGS = ("create table public.writings (user_id uuid not null default
|
|
| 112 |
'create policy "students add their own writings" on public.writings for insert to authenticated with check (user_id = auth.uid()); '
|
| 113 |
'create policy "students change their own writings" on public.writings for update to authenticated '
|
| 114 |
"using (user_id = auth.uid()) with check (user_id = auth.uid());")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 115 |
TOPIC_LESSON = {c["id"]: c["lesson"] for c in CATEGORIES} # a topic's lesson: homework is a topic of the class's lessons
|
| 116 |
MIGRATE_CLASSES = ("alter table public.classes add column if not exists nicknames jsonb not null default '{}', "
|
| 117 |
"add column if not exists lessons text[] not null default '{}', "
|
|
@@ -259,6 +276,7 @@ def create_app(scorer: Scorer | None = None, tts: SawtakTTS | None = None,
|
|
| 259 |
yield
|
| 260 |
|
| 261 |
app = FastAPI(title="ihki", lifespan=lifespan)
|
|
|
|
| 262 |
app.mount("/static", StaticFiles(directory=STATIC), name="static")
|
| 263 |
|
| 264 |
def signed_in(request: Request) -> dict | None:
|
|
@@ -280,9 +298,15 @@ def create_app(scorer: Scorer | None = None, tts: SawtakTTS | None = None,
|
|
| 280 |
raise HTTPException(503, f"class list not available: {e}")
|
| 281 |
mine = [c for c in classes if email in c["emails"]] # a student may be in several classes
|
| 282 |
teacher = email in a.teachers
|
| 283 |
-
|
|
|
|
| 284 |
raise HTTPException(403, "this account is not on the list")
|
| 285 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 286 |
|
| 287 |
def teacher_only(user: dict | None = Depends(signed_in)) -> SupabaseAuth:
|
| 288 |
if not user or not user["teacher"]:
|
|
@@ -350,6 +374,7 @@ def create_app(scorer: Scorer | None = None, tts: SawtakTTS | None = None,
|
|
| 350 |
if d["id"] not in every or d["date"] < every[d["id"]]["date"]:
|
| 351 |
every[d["id"]] = d
|
| 352 |
return {"email": user["email"] if user else "", "teacher": bool(user and user["teacher"]),
|
|
|
|
| 353 |
**({"dailies": sorted(every.values(), key=lambda d: (d["date"], d["id"]))} if user and user["teacher"] else {}),
|
| 354 |
"classes": [{"name": c["name"], "lessons": lessons_of(c), **homework_of(c, topics()),
|
| 355 |
"dailies": dailies_of(c, daily_rows())} for c in mine],
|
|
@@ -396,11 +421,13 @@ def create_app(scorer: Scorer | None = None, tts: SawtakTTS | None = None,
|
|
| 396 |
def class_progress(a: SupabaseAuth = Depends(teacher_only)):
|
| 397 |
"""The teacher's panel: the classes (with their lessons and homework), and every student's summary (see `summary`) with
|
| 398 |
"written", their written homework ({topic id: its lines}), with
|
|
|
|
| 399 |
their classes ({name: nickname}) and, as "since", the same summary for each class ({name: summary}) of the attempts
|
| 400 |
made since the class was opened: a new class starts clean, whatever its students practised before. The students are the classes' accounts, or every account that signed in
|
| 401 |
when there is no class yet; one that never signed in has joined = false."""
|
| 402 |
try:
|
| 403 |
classes, users, rows, wrote = a.classes(fresh=True), a.users(), a.all_attempts(), a.all_writings()
|
|
|
|
| 404 |
except AuthUnavailable as e:
|
| 405 |
raise HTTPException(503, str(e))
|
| 406 |
by: dict[str, list[dict]] = {}
|
|
@@ -420,7 +447,9 @@ def create_app(scorer: Scorer | None = None, tts: SawtakTTS | None = None,
|
|
| 420 |
def student(email: str, name: str, joined: bool, mine: list[dict], wrote: dict | None = None) -> dict:
|
| 421 |
into = member.get(email.lower(), {})
|
| 422 |
since = {n: summary([r for r in mine if n not in opened or utc(r["created_at"]) >= opened[n]], bank) for n in into}
|
|
|
|
| 423 |
return {"email": email, "name": name, "joined": joined, "classes": into, "since": since, "written": wrote or {},
|
|
|
|
| 424 |
**summary(mine, bank)}
|
| 425 |
|
| 426 |
students = [student(u["email"], u["name"], True, by.get(u["id"], []), written.get(u["id"]))
|
|
@@ -432,9 +461,28 @@ def create_app(scorer: Scorer | None = None, tts: SawtakTTS | None = None,
|
|
| 432 |
setup = [{"what": "הטבלה writings לא קיימת ב-Supabase, ולכן שיעורי הבית בכתיבה לא נשמרים: מה שהתלמידים כתבו נשאר במכשיר שלהם "
|
| 433 |
"והפאנל מראה שלא כתבו. אחרי יצירת הטבלה, המשפטים נשלחים בכניסה הבאה של כל תלמיד.",
|
| 434 |
"sql": CREATE_WRITINGS}] if wrote is None else []
|
|
|
|
|
|
|
|
|
|
| 435 |
return {"classes": [{**c, "lessons": lessons_of(c), **homework_of(c, lesson_of)} for c in classes], "students": students,
|
| 436 |
"setup": setup}
|
| 437 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 438 |
def class_store_error(e: AuthUnavailable) -> str:
|
| 439 |
"""The teacher's message when a class cannot be written; a 404 means Supabase has no `classes` table."""
|
| 440 |
if "answered 404" in str(e):
|
|
@@ -770,6 +818,67 @@ def create_app(scorer: Scorer | None = None, tts: SawtakTTS | None = None,
|
|
| 770 |
return {"levels": LEVELS, "lessons": LESSONS, "categories": CATEGORIES, "games": GAMES, "phrases": public_phrases(),
|
| 771 |
"voices": [{"id": i, "name": n} for n, i in VOICES.items()]}
|
| 772 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 773 |
@app.get("/api/health")
|
| 774 |
def health():
|
| 775 |
s: Scorer = app.state.scorer
|
|
@@ -846,6 +955,42 @@ def create_app(scorer: Scorer | None = None, tts: SawtakTTS | None = None,
|
|
| 846 |
"unrelated": bool(result.get("unrelated"))})
|
| 847 |
return result
|
| 848 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 849 |
return app
|
| 850 |
|
| 851 |
|
|
|
|
| 5 |
SAWTAK_API_KEY, SAWTAK_VOICE_ID (model-answer playback, see app/tts.py)
|
| 6 |
SUPABASE_URL, SUPABASE_PUBLISHABLE_KEY (Google sign-in, see app/auth.py)
|
| 7 |
TEACHER_EMAILS, SUPABASE_SECRET_KEY (the teacher's management panel, its classes and the lesson videos, see app/auth.py)
|
| 8 |
+
TUTORS_EMAIL (more accounts that, like the teachers, flag a recording scored wrong, see app/auth.py)
|
| 9 |
A local .env file is loaded if present; real environment variables win over it.
|
| 10 |
"""
|
| 11 |
from __future__ import annotations
|
|
|
|
| 16 |
import re
|
| 17 |
import time
|
| 18 |
import urllib.parse
|
| 19 |
+
import uuid
|
| 20 |
from contextlib import asynccontextmanager
|
| 21 |
from datetime import date, datetime, timedelta, timezone
|
| 22 |
from pathlib import Path
|
|
|
|
| 32 |
from .prompt_tts import ENGINES, PromptTTSUnavailable, hebrew_mp3
|
| 33 |
from .reference import References
|
| 34 |
from .scorer import Scorer, decode_audio, load_scorer
|
| 35 |
+
from .speech_evaluation import SpeechEvaluationService
|
| 36 |
from .texts import read_line, text_phrases
|
| 37 |
from .tts import VOICES, SawtakTTS, TTSUnavailable, load_tts
|
| 38 |
+
from .verb_game import VerbExerciseGenerator
|
| 39 |
|
| 40 |
logging.basicConfig(level=logging.INFO)
|
| 41 |
log = logging.getLogger("ihki")
|
|
|
|
| 116 |
'create policy "students add their own writings" on public.writings for insert to authenticated with check (user_id = auth.uid()); '
|
| 117 |
'create policy "students change their own writings" on public.writings for update to authenticated '
|
| 118 |
"using (user_id = auth.uid()) with check (user_id = auth.uid());")
|
| 119 |
+
# A tutor's flags (see auth.py): a recording that was said right and scored wrong, with what the scorer made of it.
|
| 120 |
+
# `ipa` is what was said, so `audio,ipa` of these rows is training data as train/finetune.py reads it.
|
| 121 |
+
CREATE_FLAGS = ("create table public.flags (id bigint generated always as identity primary key, email text not null, "
|
| 122 |
+
"cat text not null, phrase text not null, he text not null, ar text not null, ipa text not null, heard_ipa text not null, "
|
| 123 |
+
"score int not null, unrelated boolean not null default false, note text not null default '', result jsonb not null, "
|
| 124 |
+
"model text not null, version text not null default '', audio text, created_at timestamptz not null default now()); "
|
| 125 |
+
"alter table public.flags enable row level security; "
|
| 126 |
+
"insert into storage.buckets (id, name) values ('flags', 'flags') on conflict (id) do nothing;")
|
| 127 |
+
# The students the teacher gave the tutor's rank (see auth.py): theirs in every class, so it is kept by email.
|
| 128 |
+
CREATE_TUTORS = ("create table public.tutors (email text primary key, granted_by text not null default '', "
|
| 129 |
+
"created_at timestamptz not null default now()); alter table public.tutors enable row level security;")
|
| 130 |
+
MAX_NOTE = 500
|
| 131 |
+
AUDIO_EXT = {"webm": "webm", "ogg": "ogg", "mp4": "m4a", "mpeg": "mp3", "wav": "wav", "x-wav": "wav"} # by the upload's type
|
| 132 |
TOPIC_LESSON = {c["id"]: c["lesson"] for c in CATEGORIES} # a topic's lesson: homework is a topic of the class's lessons
|
| 133 |
MIGRATE_CLASSES = ("alter table public.classes add column if not exists nicknames jsonb not null default '{}', "
|
| 134 |
"add column if not exists lessons text[] not null default '{}', "
|
|
|
|
| 276 |
yield
|
| 277 |
|
| 278 |
app = FastAPI(title="ihki", lifespan=lifespan)
|
| 279 |
+
app.state.verb_game = VerbExerciseGenerator()
|
| 280 |
app.mount("/static", StaticFiles(directory=STATIC), name="static")
|
| 281 |
|
| 282 |
def signed_in(request: Request) -> dict | None:
|
|
|
|
| 298 |
raise HTTPException(503, f"class list not available: {e}")
|
| 299 |
mine = [c for c in classes if email in c["emails"]] # a student may be in several classes
|
| 300 |
teacher = email in a.teachers
|
| 301 |
+
tutor = teacher or email in a.tutors # a teacher flags a wrong score too
|
| 302 |
+
if classes and not mine and not tutor: # before the first class, any account is let in
|
| 303 |
raise HTTPException(403, "this account is not on the list")
|
| 304 |
+
if not tutor: # the rank the teacher gave in the panel; it lets nobody in by itself
|
| 305 |
+
try:
|
| 306 |
+
tutor = email in (a.ranked() or ())
|
| 307 |
+
except AuthUnavailable as e:
|
| 308 |
+
log.warning("tutors not read: %s", e)
|
| 309 |
+
return {**user, "token": token.strip(), "teacher": teacher, "tutor": tutor, "classes": mine}
|
| 310 |
|
| 311 |
def teacher_only(user: dict | None = Depends(signed_in)) -> SupabaseAuth:
|
| 312 |
if not user or not user["teacher"]:
|
|
|
|
| 374 |
if d["id"] not in every or d["date"] < every[d["id"]]["date"]:
|
| 375 |
every[d["id"]] = d
|
| 376 |
return {"email": user["email"] if user else "", "teacher": bool(user and user["teacher"]),
|
| 377 |
+
**({"tutor": True} if user and user["tutor"] else {}), # the page shows them the flag under a score
|
| 378 |
**({"dailies": sorted(every.values(), key=lambda d: (d["date"], d["id"]))} if user and user["teacher"] else {}),
|
| 379 |
"classes": [{"name": c["name"], "lessons": lessons_of(c), **homework_of(c, topics()),
|
| 380 |
"dailies": dailies_of(c, daily_rows())} for c in mine],
|
|
|
|
| 421 |
def class_progress(a: SupabaseAuth = Depends(teacher_only)):
|
| 422 |
"""The teacher's panel: the classes (with their lessons and homework), and every student's summary (see `summary`) with
|
| 423 |
"written", their written homework ({topic id: its lines}), with
|
| 424 |
+
"tutor" (the teacher gave them the tutor's rank, see `set_tutor`; "tutor_fixed" when TEACHER_EMAILS or TUTORS_EMAIL gives it, which the panel cannot change),
|
| 425 |
their classes ({name: nickname}) and, as "since", the same summary for each class ({name: summary}) of the attempts
|
| 426 |
made since the class was opened: a new class starts clean, whatever its students practised before. The students are the classes' accounts, or every account that signed in
|
| 427 |
when there is no class yet; one that never signed in has joined = false."""
|
| 428 |
try:
|
| 429 |
classes, users, rows, wrote = a.classes(fresh=True), a.users(), a.all_attempts(), a.all_writings()
|
| 430 |
+
ranked = a.ranked(fresh=True)
|
| 431 |
except AuthUnavailable as e:
|
| 432 |
raise HTTPException(503, str(e))
|
| 433 |
by: dict[str, list[dict]] = {}
|
|
|
|
| 447 |
def student(email: str, name: str, joined: bool, mine: list[dict], wrote: dict | None = None) -> dict:
|
| 448 |
into = member.get(email.lower(), {})
|
| 449 |
since = {n: summary([r for r in mine if n not in opened or utc(r["created_at"]) >= opened[n]], bank) for n in into}
|
| 450 |
+
fixed = email.lower() in a.teachers | a.tutors
|
| 451 |
return {"email": email, "name": name, "joined": joined, "classes": into, "since": since, "written": wrote or {},
|
| 452 |
+
"tutor": fixed or email.lower() in (ranked or ()), **({"tutor_fixed": True} if fixed else {}),
|
| 453 |
**summary(mine, bank)}
|
| 454 |
|
| 455 |
students = [student(u["email"], u["name"], True, by.get(u["id"], []), written.get(u["id"]))
|
|
|
|
| 461 |
setup = [{"what": "הטבלה writings לא קיימת ב-Supabase, ולכן שיעורי הבית בכתיבה לא נשמרים: מה שהתלמידים כתבו נשאר במכשיר שלהם "
|
| 462 |
"והפאנל מראה שלא כתבו. אחרי יצירת הטבלה, המשפטים נשלחים בכניסה הבאה של כל תלמיד.",
|
| 463 |
"sql": CREATE_WRITINGS}] if wrote is None else []
|
| 464 |
+
if ranked is None:
|
| 465 |
+
setup.append({"what": "הטבלה tutors לא קיימת ב-Supabase, ולכן אי אפשר לתת לתלמיד דרגת מדווח/ת (דגל 🚩 מתחת לציון).",
|
| 466 |
+
"sql": CREATE_TUTORS})
|
| 467 |
return {"classes": [{**c, "lessons": lessons_of(c), **homework_of(c, lesson_of)} for c in classes], "students": students,
|
| 468 |
"setup": setup}
|
| 469 |
|
| 470 |
+
@app.put("/api/tutors")
|
| 471 |
+
def set_tutor(body: dict = Body(...), a: SupabaseAuth = Depends(teacher_only), user: dict | None = Depends(signed_in)):
|
| 472 |
+
"""Gives a student the tutor's rank, or takes it back: {"email", "tutor": true or false}. The rank is the
|
| 473 |
+
student's in every class: they get the flag under each score (see `flag`)."""
|
| 474 |
+
email = str(body.get("email", "")).strip().lower()
|
| 475 |
+
if not re.fullmatch(r"[^@\s]+@[^@\s]+\.[^@\s]+", email) or not isinstance(body.get("tutor"), bool):
|
| 476 |
+
raise HTTPException(400, "צריך כתובת אימייל של תלמיד/ה ו-tutor: true או false")
|
| 477 |
+
try:
|
| 478 |
+
a.set_tutor(email, body["tutor"], user["email"].lower())
|
| 479 |
+
except AuthUnavailable as e:
|
| 480 |
+
if "answered 404" in str(e):
|
| 481 |
+
raise HTTPException(503, "הטבלה tutors לא קיימת ב-Supabase. הריצו ב-SQL Editor: "
|
| 482 |
+
f"{CREATE_TUTORS} אם כבר נוצרה, הריצו שם: notify pgrst, 'reload schema';")
|
| 483 |
+
raise HTTPException(503, f"Supabase לא זמין: {e}")
|
| 484 |
+
return {"ok": True}
|
| 485 |
+
|
| 486 |
def class_store_error(e: AuthUnavailable) -> str:
|
| 487 |
"""The teacher's message when a class cannot be written; a 404 means Supabase has no `classes` table."""
|
| 488 |
if "answered 404" in str(e):
|
|
|
|
| 818 |
return {"levels": LEVELS, "lessons": LESSONS, "categories": CATEGORIES, "games": GAMES, "phrases": public_phrases(),
|
| 819 |
"voices": [{"id": i, "name": n} for n, i in VOICES.items()]}
|
| 820 |
|
| 821 |
+
def verb_lessons(user: dict | None) -> list[str]:
|
| 822 |
+
"""Lessons available to this learner, using the existing class rules."""
|
| 823 |
+
if not user or user["teacher"] or not user["classes"]:
|
| 824 |
+
return READY_LESSONS
|
| 825 |
+
return [lesson for lesson in READY_LESSONS
|
| 826 |
+
if any(lesson in lessons_of(course) for course in user["classes"])]
|
| 827 |
+
|
| 828 |
+
@app.get("/api/verb-game")
|
| 829 |
+
def verb_game(user: dict | None = Depends(signed_in)):
|
| 830 |
+
"""Configuration for "פועל יוצא" and the complete paradigms currently unlocked."""
|
| 831 |
+
return app.state.verb_game.metadata(verb_lessons(user))
|
| 832 |
+
|
| 833 |
+
@app.post("/api/verb-game/question")
|
| 834 |
+
def verb_question(body: dict = Body(...), user: dict | None = Depends(signed_in)):
|
| 835 |
+
"""Create a Level 1--5 exercise; answers remain server-side."""
|
| 836 |
+
try:
|
| 837 |
+
level = int(body.get("level", 1))
|
| 838 |
+
mastery = body.get("mastery") if isinstance(body.get("mastery"), dict) else {}
|
| 839 |
+
recent = body.get("recent") if isinstance(body.get("recent"), list) else []
|
| 840 |
+
return app.state.verb_game.question(level, verb_lessons(user), mastery, list(map(str, recent[-10:])))
|
| 841 |
+
except (TypeError, ValueError) as e:
|
| 842 |
+
raise HTTPException(400, str(e))
|
| 843 |
+
except LookupError as e:
|
| 844 |
+
raise HTTPException(404, str(e))
|
| 845 |
+
|
| 846 |
+
@app.post("/api/verb-game/answer")
|
| 847 |
+
def verb_answer(body: dict = Body(...), _user: dict | None = Depends(signed_in)):
|
| 848 |
+
"""Grade one opaque question once and return feedback plus measured client response time."""
|
| 849 |
+
try:
|
| 850 |
+
return app.state.verb_game.answer(str(body.get("question_id", "")), body.get("answer"),
|
| 851 |
+
int(body.get("response_ms", 0)))
|
| 852 |
+
except (TypeError, ValueError) as e:
|
| 853 |
+
raise HTTPException(400, str(e))
|
| 854 |
+
except LookupError as e:
|
| 855 |
+
raise HTTPException(410, str(e))
|
| 856 |
+
|
| 857 |
+
@app.post("/api/verb-game/speech")
|
| 858 |
+
def verb_speech(audio: UploadFile = File(...), question_id: str = Form(...),
|
| 859 |
+
user: dict | None = Depends(signed_in)):
|
| 860 |
+
"""Evaluate Levels 4–5 audio without turning uncertain recognition into an error."""
|
| 861 |
+
try:
|
| 862 |
+
question, phrase = app.state.verb_game.speech_phrase(question_id)
|
| 863 |
+
except LookupError as e:
|
| 864 |
+
raise HTTPException(410, str(e))
|
| 865 |
+
data = audio.file.read(MAX_UPLOAD + 1)
|
| 866 |
+
if len(data) > MAX_UPLOAD:
|
| 867 |
+
raise HTTPException(413, "recording too long")
|
| 868 |
+
try:
|
| 869 |
+
wav = decode_audio(data)
|
| 870 |
+
except ValueError:
|
| 871 |
+
raise HTTPException(400, "could not decode audio")
|
| 872 |
+
if wav.size < 16_000 * .3:
|
| 873 |
+
return {"outcome": "uncertain", "counts_as_attempt": False,
|
| 874 |
+
"message": "לא נשמע מספיק דיבור. האזינו להקלטה ונסו שוב."}
|
| 875 |
+
result = SpeechEvaluationService(app.state.scorer).evaluate(
|
| 876 |
+
wav, phrase, diagnostics=bool(user and user["teacher"]))
|
| 877 |
+
if result.get("outcome") == "correct":
|
| 878 |
+
app.state.verb_game.sessions.finish(question_id)
|
| 879 |
+
result["level"] = question.mode
|
| 880 |
+
return result
|
| 881 |
+
|
| 882 |
@app.get("/api/health")
|
| 883 |
def health():
|
| 884 |
s: Scorer = app.state.scorer
|
|
|
|
| 955 |
"unrelated": bool(result.get("unrelated"))})
|
| 956 |
return result
|
| 957 |
|
| 958 |
+
@app.post("/api/flags")
|
| 959 |
+
def flag(phrase_id: int = Form(...), audio: UploadFile = File(...), note: str = Form(""),
|
| 960 |
+
user: dict | None = Depends(signed_in)):
|
| 961 |
+
"""A tutor's flag: this recording of the phrase was said right and the score was wrong. The recording is scored
|
| 962 |
+
again here, so what is kept is the scorer's own answer and not the page's copy of it: the row of `flags`
|
| 963 |
+
(see CREATE_FLAGS) and the recording beside it. {"ok", "audio": whether the recording was kept too, "flag": the
|
| 964 |
+
row that was kept, which the page shows the tutor}."""
|
| 965 |
+
if not user or not user["tutor"]:
|
| 966 |
+
raise HTTPException(403, "tutors only")
|
| 967 |
+
phrase = phrase_of(phrase_id)
|
| 968 |
+
data = audio.file.read(MAX_UPLOAD + 1)
|
| 969 |
+
if len(data) > MAX_UPLOAD:
|
| 970 |
+
raise HTTPException(413, "recording too long")
|
| 971 |
+
try:
|
| 972 |
+
wav = decode_audio(data)
|
| 973 |
+
except ValueError:
|
| 974 |
+
raise HTTPException(400, "could not decode audio")
|
| 975 |
+
refs = app.state.refs.get(phrase_id, phrase) if app.state.refs else []
|
| 976 |
+
result = app.state.scorer.score(wav, phrase, refs)
|
| 977 |
+
if result.get("error"):
|
| 978 |
+
raise HTTPException(400, result["message"])
|
| 979 |
+
mime = (audio.content_type or "application/octet-stream").lower()
|
| 980 |
+
ext = AUDIO_EXT.get(mime.partition(";")[0].strip().rpartition("/")[2], "bin")
|
| 981 |
+
row = {"email": user["email"].lower(), "cat": phrase["cat"], "phrase": phrase.get("key", phrase["he"]),
|
| 982 |
+
"he": phrase["he"], "ar": result["variant"]["ar"], "ipa": result["variant"]["ipa"],
|
| 983 |
+
"heard_ipa": result["heard_ipa"], "score": result["score"], "unrelated": bool(result["unrelated"]),
|
| 984 |
+
"note": " ".join(note.split())[:MAX_NOTE], "result": result, "model": MODEL_ID, "version": build_version()}
|
| 985 |
+
try:
|
| 986 |
+
kept = app.state.auth.add_flag(row, data, mime, f"{date.today():%Y-%m}/{uuid.uuid4().hex}.{ext}")
|
| 987 |
+
except AuthUnavailable as e:
|
| 988 |
+
if "answered 404" in str(e):
|
| 989 |
+
raise HTTPException(503, "הטבלה flags לא קיימת ב-Supabase. הריצו ב-SQL Editor: "
|
| 990 |
+
f"{CREATE_FLAGS} אם כבר נוצרה, הריצו שם: notify pgrst, 'reload schema';")
|
| 991 |
+
raise HTTPException(503, f"Supabase לא זמין: {e}")
|
| 992 |
+
return {"ok": True, "audio": kept, "flag": row}
|
| 993 |
+
|
| 994 |
return app
|
| 995 |
|
| 996 |
|
app/phrases.py
CHANGED
|
@@ -147,6 +147,6 @@ def public_phrases():
|
|
| 147 |
shown = {c["id"] for c in CATEGORIES + GAMES}
|
| 148 |
return [
|
| 149 |
{"id": i, "cat": p["cat"], "he": p["he"], "tr": p["tr"], "ar": p["variants"][0][0],
|
| 150 |
-
**{k: p[k] for k in ("grp", "pron", "neg", "listed", "seq", "read") if k in p}}
|
| 151 |
for i, p in enumerate(PHRASES) if p["cat"] in shown
|
| 152 |
]
|
|
|
|
| 147 |
shown = {c["id"] for c in CATEGORIES + GAMES}
|
| 148 |
return [
|
| 149 |
{"id": i, "cat": p["cat"], "he": p["he"], "tr": p["tr"], "ar": p["variants"][0][0],
|
| 150 |
+
**{k: p[k] for k in ("grp", "pron", "neg", "listed", "seq", "read", "unlock", "binyan", "gizra") if k in p}}
|
| 151 |
for i, p in enumerate(PHRASES) if p["cat"] in shown
|
| 152 |
]
|
app/speech_evaluation.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Replaceable speech policy for spoken conjugation exercises.
|
| 2 |
+
|
| 3 |
+
The acoustic scorer is Palestinian-Arabic aware at the phoneme level, but it is not
|
| 4 |
+
treated as a general dialect ASR. In particular, an unrelated/low-confidence result
|
| 5 |
+
asks for a retry instead of becoming a grammatical error.
|
| 6 |
+
"""
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
from typing import Any
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class SpeechEvaluationService:
|
| 13 |
+
def __init__(self, scorer: Any, pass_score: int = 75):
|
| 14 |
+
self.scorer = scorer
|
| 15 |
+
self.pass_score = pass_score
|
| 16 |
+
|
| 17 |
+
def evaluate(self, wav, phrase: dict, diagnostics: bool = False) -> dict:
|
| 18 |
+
result = self.scorer.score(wav, phrase, diagnostics=diagnostics)
|
| 19 |
+
if result.get("error"):
|
| 20 |
+
return {**result, "outcome": "uncertain", "counts_as_attempt": False}
|
| 21 |
+
if result.get("unrelated"):
|
| 22 |
+
return {**result, "outcome": "uncertain", "counts_as_attempt": False,
|
| 23 |
+
"message": "לא הצלחתי לזהות בביטחון את ההטיה. האזינו להקלטה ונסו שוב."}
|
| 24 |
+
correct = int(result.get("score", 0)) >= self.pass_score
|
| 25 |
+
return {**result, "outcome": "correct" if correct else "needs_work",
|
| 26 |
+
"error_kind": None if correct else "undetermined",
|
| 27 |
+
"correct": correct, "counts_as_attempt": True,
|
| 28 |
+
"message": "נכון" if correct else "לא הצלחתי לאשר את התשובה. הקשיבו להקלטה ולתשובה ונסו שוב."}
|
app/verb_game.py
ADDED
|
@@ -0,0 +1,298 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Exercise generation and server-side checking for "פועל יוצא" levels 1--5.
|
| 2 |
+
|
| 3 |
+
The grammar tables are deliberately the only linguistic source used here. A verb
|
| 4 |
+
without a complete table is not eligible for the game: guessing a missing form is
|
| 5 |
+
worse than offering a smaller, accurate exercise pool.
|
| 6 |
+
"""
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import random
|
| 10 |
+
import secrets
|
| 11 |
+
import time
|
| 12 |
+
from dataclasses import dataclass, field
|
| 13 |
+
from typing import Any
|
| 14 |
+
|
| 15 |
+
from .grammar import PRONOUNS, VERBS
|
| 16 |
+
from .workbook import LEX
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
VERB_META = {
|
| 20 |
+
"akal": {"name": "אכל", "unlock": "1"},
|
| 21 |
+
"qaad": {"name": "ישב", "unlock": "1"},
|
| 22 |
+
"fatah": {"name": "פתח", "unlock": "1"},
|
| 23 |
+
"saal": {"name": "שאל", "unlock": "1"},
|
| 24 |
+
"tabakh": {"name": "בישל", "unlock": "3"},
|
| 25 |
+
"aja": {"name": "בא", "unlock": "4"},
|
| 26 |
+
"raah": {"name": "הלך", "unlock": "5"},
|
| 27 |
+
"faat": {"name": "נכנס / עבר", "unlock": "6"},
|
| 28 |
+
"fihem": {"name": "הבין", "unlock": "8"},
|
| 29 |
+
"laeb": {"name": "שיחק", "unlock": "10"},
|
| 30 |
+
"libes": {"name": "לבש", "unlock": "2.3"},
|
| 31 |
+
"labbas": {"name": "הלביש", "unlock": "2.3"},
|
| 32 |
+
"jaab": {"name": "הביא", "unlock": "2.5"},
|
| 33 |
+
"saaad": {"name": "עזר", "unlock": "2.6"},
|
| 34 |
+
"rakad": {"name": "רץ", "unlock": "2.7"},
|
| 35 |
+
"dall": {"name": "נשאר / המשיך", "unlock": "2.8"},
|
| 36 |
+
}
|
| 37 |
+
LEVELS = {
|
| 38 |
+
1: {"name": "בחירת ההטיה", "choices": 4, "window_ms": 12000},
|
| 39 |
+
2: {"name": "התאמת הגופים", "pairs": 6},
|
| 40 |
+
3: {"name": "החלפה מהירה", "choices": 3, "window_ms": 6000},
|
| 41 |
+
4: {"name": "אומרים בקול"},
|
| 42 |
+
5: {"name": "תגובה בשיחה"},
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
# Complete, filled past-tense tables in the parsed book. Order is PRONOUNS order.
|
| 46 |
+
# Arabic is not copied or inferred from transliteration: each form must resolve back
|
| 47 |
+
# to the application's existing LEX source of truth, otherwise the paradigm is dropped.
|
| 48 |
+
BOOK_PAST_TRANSLITERATIONS = {
|
| 49 |
+
"tabakh": ["טַבַּחֵ'ת", "טַבַּחֵ'ת", "טַבַּחְ'תִי", "טַבַּח'", "טַבְּחַ'ת", "טַבַּחְ'נַא", "טַבַּחְ'תוּ", "טַבַּח'וּ"],
|
| 50 |
+
"aja": ["אַגֵ'ית", "אַגֵ'ית", "אַגֵ'יתִי", "אַגַ'א", "אַגַ'ת", "אַגֵ'ינַא", "אַגֵ'יתוּ", "אַג'וּ"],
|
| 51 |
+
"raah": ["רֻחֵת", "רֻחֵת", "רֻחְתִי", "רַאח", "רַאחַת", "רֻחְנַא", "רֻחְתוּ", "רַאחוּ"],
|
| 52 |
+
"faat": ["פֻתֵת", "פֻתֵת", "פֻתִّי", "פַאת", "פַאתַת", "פֻתְנַא", "פֻתّוּ", "פַאתוּ"],
|
| 53 |
+
"fihem": ["פְהִמֵת", "פְהִמֵת", "פְהִמְתִי", "פִהֵם", "פִהְמַת", "פְהִמְנַא", "פְהִמְתוּ", "פִהְמוּ"],
|
| 54 |
+
"laeb": ["לְעִבֵּת", "לְעִבֵּת", "לְעִבְּתִי", "לִעֵבּ", "לִעְבַּת", "לְעִבְּנַא", "לְעִבְּתוּ", "לִעְבּוּ"],
|
| 55 |
+
"libes": ["לְבִּסֵת", "לְבִּסֵת", "לְבִּסְתִי", "לִבֵּס", "לִבְּסַת", "לְבִּסְנַא", "לְבִּסְתוּ", "לִבְּסוּ"],
|
| 56 |
+
"labbas": ["לַבַּّסֵת", "לַבַּّסֵת", "לַבַּّסְתִי", "לַבַּّס", "לַבַּّסַת", "לַבַּّסְנַא", "לַבַּّסְתוּ", "לַבַּّסוּ"],
|
| 57 |
+
"jaab": ["גִ'בֵּת", "גִ'בֵּת", "גִ'בְּתִי", "גַ'אבּ", "גַ'אבַּת", "גִ'בְּנַא", "גִ'בְּתוּ", "גַ'אבּוּ"],
|
| 58 |
+
"saaad": ["סַאעַדֵת", "סַאעַדֵת", "סַאעַדְתִי", "סַאעַד", "סַאעַדַת", "סַאעַדְנַא", "סַאעַדְתוּ", "סַאעַדוּ"],
|
| 59 |
+
"rakad": ["רַכַּדֵֿת", "רַכַּדֵֿת", "רַכַּדְֿתִי", "רַכַּדֿ", "רַכְּדַֿת", "רַכַּדְֿנַא", "רַכַּדְֿתוּ", "רַכַּדֿוּ"],
|
| 60 |
+
"dall": ["דַֿלֵّית", "דַֿלֵّית", "דַֿלֵّיתִי", "דַֿלّ", "דַֿלַّת", "דַֿלֵّינַא", "דַֿלֵّיתוּ", "דַֿלّוּ"],
|
| 61 |
+
}
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def _book_paradigms() -> dict[str, list[tuple[str, str]]]:
|
| 65 |
+
by_tr: dict[str, tuple[str, str]] = {}
|
| 66 |
+
for key, (tr, _ipas) in LEX.items():
|
| 67 |
+
by_tr.setdefault(tr, (key.partition("#")[0], tr, list(_ipas)))
|
| 68 |
+
return {verb: [by_tr[tr] for tr in forms] for verb, forms in BOOK_PAST_TRANSLITERATIONS.items()
|
| 69 |
+
if all(tr in by_tr for tr in forms)}
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
BOOK_VERBS = _book_paradigms()
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def _form(verb: str, pronoun: int) -> dict[str, Any]:
|
| 76 |
+
if verb in VERBS:
|
| 77 |
+
he, tr, arabic, ipas = VERBS[verb][pronoun]
|
| 78 |
+
return {"hebrew": he, "transliteration": tr, "arabic": arabic, "ipas": list(ipas)}
|
| 79 |
+
arabic, tr, ipas = BOOK_VERBS[verb][pronoun]
|
| 80 |
+
return {"hebrew": "", "transliteration": tr, "arabic": arabic, "ipas": ipas}
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def _paradigm(verb: str) -> list:
|
| 84 |
+
return VERBS[verb] if verb in VERBS else BOOK_VERBS[verb]
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def _distance(a: str, b: str) -> int:
|
| 88 |
+
"""Small edit distance, used only to rank real database forms as distractors."""
|
| 89 |
+
row = list(range(len(b) + 1))
|
| 90 |
+
for i, x in enumerate(a, 1):
|
| 91 |
+
old = row[0]
|
| 92 |
+
row[0] = i
|
| 93 |
+
for j, y in enumerate(b, 1):
|
| 94 |
+
above = row[j]
|
| 95 |
+
row[j] = min(row[j] + 1, row[j - 1] + 1, old + (x != y))
|
| 96 |
+
old = above
|
| 97 |
+
return row[-1]
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
@dataclass
|
| 101 |
+
class StoredQuestion:
|
| 102 |
+
mode: int
|
| 103 |
+
verb: str
|
| 104 |
+
correct: dict[str, str]
|
| 105 |
+
made_at: float
|
| 106 |
+
forms: dict[str, tuple[str, str]] = field(default_factory=dict)
|
| 107 |
+
phrase: dict[str, Any] | None = None
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
class PracticeSessionManager:
|
| 111 |
+
"""Short-lived opaque questions prevent clients from grading themselves."""
|
| 112 |
+
|
| 113 |
+
def __init__(self, ttl_seconds: int = 1800, rng: random.Random | None = None):
|
| 114 |
+
self.ttl_seconds = ttl_seconds
|
| 115 |
+
self.rng = rng or random.Random()
|
| 116 |
+
self.questions: dict[str, StoredQuestion] = {}
|
| 117 |
+
|
| 118 |
+
def put(self, question: StoredQuestion) -> str:
|
| 119 |
+
now = time.monotonic()
|
| 120 |
+
self.questions = {k: v for k, v in self.questions.items() if now - v.made_at < self.ttl_seconds}
|
| 121 |
+
key = secrets.token_urlsafe(18)
|
| 122 |
+
self.questions[key] = question
|
| 123 |
+
return key
|
| 124 |
+
|
| 125 |
+
def take(self, key: str) -> StoredQuestion | None:
|
| 126 |
+
question = self.questions.pop(key, None)
|
| 127 |
+
if question and time.monotonic() - question.made_at < self.ttl_seconds:
|
| 128 |
+
return question
|
| 129 |
+
return None
|
| 130 |
+
|
| 131 |
+
def get(self, key: str) -> StoredQuestion | None:
|
| 132 |
+
question = self.questions.get(key)
|
| 133 |
+
if question and time.monotonic() - question.made_at < self.ttl_seconds:
|
| 134 |
+
return question
|
| 135 |
+
self.questions.pop(key, None)
|
| 136 |
+
return None
|
| 137 |
+
|
| 138 |
+
def finish(self, key: str) -> None:
|
| 139 |
+
self.questions.pop(key, None)
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
class VerbExerciseGenerator:
|
| 143 |
+
def __init__(self, sessions: PracticeSessionManager | None = None):
|
| 144 |
+
self.sessions = sessions or PracticeSessionManager()
|
| 145 |
+
self.rng = self.sessions.rng
|
| 146 |
+
|
| 147 |
+
@staticmethod
|
| 148 |
+
def available(lessons: list[str]) -> list[str]:
|
| 149 |
+
allowed = set(lessons)
|
| 150 |
+
return [v for v in VERB_META
|
| 151 |
+
if (v in VERBS or v in BOOK_VERBS)
|
| 152 |
+
and len(_paradigm(v)) == len(PRONOUNS)
|
| 153 |
+
and VERB_META[v]["unlock"] in allowed]
|
| 154 |
+
|
| 155 |
+
def metadata(self, lessons: list[str]) -> dict[str, Any]:
|
| 156 |
+
return {
|
| 157 |
+
"levels": [{"id": n, **cfg} for n, cfg in LEVELS.items()],
|
| 158 |
+
"verbs": [{"id": v, "name": VERB_META[v]["name"], "unlock": VERB_META[v]["unlock"]}
|
| 159 |
+
for v in self.available(lessons)],
|
| 160 |
+
"tenses": [{"id": "past", "name": "עבר"}],
|
| 161 |
+
}
|
| 162 |
+
|
| 163 |
+
def _target(self, verbs: list[str], mastery: dict, recent: list[str]) -> tuple[str, int]:
|
| 164 |
+
candidates = [(v, p) for v in verbs for p in range(len(PRONOUNS))]
|
| 165 |
+
def priority(item: tuple[str, int]) -> float:
|
| 166 |
+
v, p = item
|
| 167 |
+
key = f"{v}:past:{PRONOUNS[p][0]}"
|
| 168 |
+
m = mastery.get(key, {}) if isinstance(mastery, dict) else {}
|
| 169 |
+
attempts = max(0, int(m.get("attempts", 0) or 0))
|
| 170 |
+
accuracy = float(m.get("correct", 0) or 0) / attempts if attempts else 0.0
|
| 171 |
+
slow = min(float(m.get("median_ms", 0) or 0) / 4000, 1.5)
|
| 172 |
+
recency_penalty = 5 if key in recent[-3:] else 0
|
| 173 |
+
# Incorrect, slow, and unseen forms rise; a little noise avoids a fixed drill order.
|
| 174 |
+
return (3 if attempts and accuracy < .7 else 0) + slow + (2 if not attempts else 0) - recency_penalty + self.rng.random()
|
| 175 |
+
return max(candidates, key=priority)
|
| 176 |
+
|
| 177 |
+
def question(self, level: int, lessons: list[str], mastery: dict | None = None,
|
| 178 |
+
recent: list[str] | None = None) -> dict[str, Any]:
|
| 179 |
+
if level not in LEVELS:
|
| 180 |
+
raise ValueError("unsupported level")
|
| 181 |
+
verbs = self.available(lessons)
|
| 182 |
+
if not verbs:
|
| 183 |
+
raise LookupError("no complete verb paradigms are unlocked")
|
| 184 |
+
if level == 2:
|
| 185 |
+
return self._matching(verbs, mastery or {}, recent or [])
|
| 186 |
+
if level in (4, 5):
|
| 187 |
+
return self._spoken(level, verbs, mastery or {}, recent or [])
|
| 188 |
+
verb, pron = self._target(verbs, mastery or {}, recent or [])
|
| 189 |
+
right = _form(verb, pron)
|
| 190 |
+
count = LEVELS[level]["choices"]
|
| 191 |
+
pool = []
|
| 192 |
+
for other_pron in range(len(PRONOUNS)):
|
| 193 |
+
if other_pron != pron:
|
| 194 |
+
pool.append((verb, other_pron, _form(verb, other_pron)))
|
| 195 |
+
if level == 3 and len(verbs) > 1:
|
| 196 |
+
for other in verbs:
|
| 197 |
+
if other != verb:
|
| 198 |
+
pool.append((other, pron, _form(other, pron)))
|
| 199 |
+
pool.sort(key=lambda x: (_distance(right["transliteration"], x[2]["transliteration"]), self.rng.random()))
|
| 200 |
+
unique, seen = [], {(right["transliteration"], right["arabic"])}
|
| 201 |
+
for _, _, form in pool:
|
| 202 |
+
signature = (form["transliteration"], form["arabic"])
|
| 203 |
+
if signature not in seen:
|
| 204 |
+
seen.add(signature)
|
| 205 |
+
unique.append(form)
|
| 206 |
+
if len(unique) == count - 1:
|
| 207 |
+
break
|
| 208 |
+
choices = [{"id": secrets.token_urlsafe(7), "transliteration": f["transliteration"], "arabic": f["arabic"]}
|
| 209 |
+
for f in [right, *unique]]
|
| 210 |
+
self.rng.shuffle(choices)
|
| 211 |
+
correct_id = next(c["id"] for c in choices if (c["transliteration"], c["arabic"]) ==
|
| 212 |
+
(right["transliteration"], right["arabic"]))
|
| 213 |
+
qid = self.sessions.put(StoredQuestion(level, verb, {"choice": correct_id}, time.monotonic()))
|
| 214 |
+
pronoun = PRONOUNS[pron]
|
| 215 |
+
return {
|
| 216 |
+
"question_id": qid, "level": level, "tense": {"id": "past", "name": "עבר"},
|
| 217 |
+
"verb": {"id": verb, "name": VERB_META[verb]["name"], "arabic": _form(verb, 3)["arabic"]},
|
| 218 |
+
"pronoun": {"id": pronoun[0], "hebrew": pronoun[1], "transliteration": pronoun[2]},
|
| 219 |
+
"choices": choices, "time_limit_ms": LEVELS[level]["window_ms"],
|
| 220 |
+
"mastery_key": f"{verb}:past:{pronoun[0]}",
|
| 221 |
+
}
|
| 222 |
+
|
| 223 |
+
def _matching(self, verbs: list[str], mastery: dict, recent: list[str]) -> dict[str, Any]:
|
| 224 |
+
verb, _ = self._target(verbs, mastery, recent)
|
| 225 |
+
count = min(LEVELS[2]["pairs"], len(PRONOUNS))
|
| 226 |
+
indices = self.rng.sample(range(len(PRONOUNS)), count)
|
| 227 |
+
left, right, correct, forms = [], [], {}, {}
|
| 228 |
+
for p in indices:
|
| 229 |
+
pron = PRONOUNS[p]
|
| 230 |
+
form = _form(verb, p)
|
| 231 |
+
pid, fid = secrets.token_urlsafe(6), secrets.token_urlsafe(6)
|
| 232 |
+
left.append({"id": pid, "hebrew": pron[1], "transliteration": pron[2]})
|
| 233 |
+
right.append({"id": fid, "transliteration": form["transliteration"], "arabic": form["arabic"]})
|
| 234 |
+
correct[pid] = fid
|
| 235 |
+
forms[fid] = (form["transliteration"], form["arabic"])
|
| 236 |
+
self.rng.shuffle(left)
|
| 237 |
+
self.rng.shuffle(right)
|
| 238 |
+
qid = self.sessions.put(StoredQuestion(2, verb, correct, time.monotonic(), forms))
|
| 239 |
+
return {"question_id": qid, "level": 2, "tense": {"id": "past", "name": "עבר"},
|
| 240 |
+
"verb": {"id": verb, "name": VERB_META[verb]["name"], "arabic": _form(verb, 3)["arabic"]},
|
| 241 |
+
"pronouns": left, "forms": right, "pair_count": count,
|
| 242 |
+
"mastery_key": f"{verb}:past:matching"}
|
| 243 |
+
|
| 244 |
+
def _spoken(self, level: int, verbs: list[str], mastery: dict, recent: list[str]) -> dict[str, Any]:
|
| 245 |
+
if level == 5:
|
| 246 |
+
# A controlled first conversation: the learner answers about themself. Keeping
|
| 247 |
+
# the target to ana makes the prompt natural and the grammar target unambiguous.
|
| 248 |
+
scored = [(v, 0) for v in verbs]
|
| 249 |
+
verb, pron = max(scored, key=lambda x: self.rng.random() +
|
| 250 |
+
(2 if not mastery.get(f"{x[0]}:past:ana") else 0))
|
| 251 |
+
else:
|
| 252 |
+
verb, pron = self._target(verbs, mastery, recent)
|
| 253 |
+
form = _form(verb, pron)
|
| 254 |
+
variants = [(form["arabic"], ipa) for ipa in form["ipas"]]
|
| 255 |
+
if level == 5:
|
| 256 |
+
pron_ar, pron_ipa = PRONOUNS[0][3][0]
|
| 257 |
+
variants += [(f"{pron_ar} {form['arabic']}", f"{pron_ipa} | {ipa}") for ipa in form["ipas"]]
|
| 258 |
+
phrase = {"variants": variants}
|
| 259 |
+
qid = self.sessions.put(StoredQuestion(level, verb, {}, time.monotonic(), phrase=phrase))
|
| 260 |
+
p = PRONOUNS[pron]
|
| 261 |
+
result = {
|
| 262 |
+
"question_id": qid, "level": level, "tense": {"id": "past", "name": "עבר"},
|
| 263 |
+
"verb": {"id": verb, "name": VERB_META[verb]["name"], "arabic": _form(verb, 3)["arabic"]},
|
| 264 |
+
"pronoun": {"id": p[0], "hebrew": p[1], "transliteration": p[2]},
|
| 265 |
+
"mastery_key": f"{verb}:past:{p[0]}:spoken",
|
| 266 |
+
}
|
| 267 |
+
if level == 5:
|
| 268 |
+
result["conversation"] = {"arabic": "شو عملت مبارح؟", "transliteration": "שוּ עְמֵלְת אִמְבַּארֵח?",
|
| 269 |
+
"hebrew": "מה עשית אתמול?"}
|
| 270 |
+
return result
|
| 271 |
+
|
| 272 |
+
def speech_phrase(self, question_id: str) -> tuple[StoredQuestion, dict[str, Any]]:
|
| 273 |
+
question = self.sessions.get(question_id)
|
| 274 |
+
if not question or question.mode not in (4, 5) or not question.phrase:
|
| 275 |
+
raise LookupError("spoken question expired")
|
| 276 |
+
return question, question.phrase
|
| 277 |
+
|
| 278 |
+
def answer(self, question_id: str, answer: Any, response_ms: int) -> dict[str, Any]:
|
| 279 |
+
q = self.sessions.take(question_id)
|
| 280 |
+
if not q:
|
| 281 |
+
raise LookupError("question expired or already answered")
|
| 282 |
+
response_ms = max(0, min(int(response_ms), 300_000))
|
| 283 |
+
if q.mode == 2:
|
| 284 |
+
supplied = answer if isinstance(answer, dict) else {}
|
| 285 |
+
# A duplicated written/spoken form is interchangeable with its identical twin.
|
| 286 |
+
pair_results = {pid: supplied.get(pid) in q.forms and q.forms[supplied[pid]] == q.forms[expected]
|
| 287 |
+
for pid, expected in q.correct.items()}
|
| 288 |
+
correct = sum(pair_results.values())
|
| 289 |
+
total = len(q.correct)
|
| 290 |
+
return {"correct": correct == total, "correct_pairs": correct, "total_pairs": total,
|
| 291 |
+
"pair_results": pair_results, "response_ms": response_ms}
|
| 292 |
+
chosen = str(answer)
|
| 293 |
+
ok = chosen == q.correct["choice"]
|
| 294 |
+
result = {"correct": ok, "response_ms": response_ms}
|
| 295 |
+
if not ok:
|
| 296 |
+
result["explanation"] = "הסיומת משתנה לפי הגוף. התאימו את ההטיה לכינוי שמופיע בשאלה."
|
| 297 |
+
result["correct_choice_id"] = q.correct["choice"]
|
| 298 |
+
return result
|
app/workbook.py
CHANGED
|
@@ -3856,9 +3856,59 @@ CATEGORIES = [{"id": f"l{lesson_id(*key)}-{tid}", "name": name, "lesson": lesson
|
|
| 3856 |
|
| 3857 |
# Games live outside the lesson path. Their phrases use the same scoring bank, but they are not topics,
|
| 3858 |
# do not affect lesson completion, and cannot be assigned as homework.
|
| 3859 |
-
GAMES = [{"id": "game-yalla-verb", "name": "
|
| 3860 |
"unit": "פועל", "task": "אמרו את הפועל בערבית מדוברת: בעבר ואז בעתיד, לפני שהבועה נעלמת"}]
|
| 3861 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3862 |
|
| 3863 |
|
| 3864 |
def _present_of(key: str) -> tuple[str, list[str]] | None:
|
|
@@ -3935,9 +3985,11 @@ def workbook_phrases() -> list[dict]:
|
|
| 3935 |
phrase["seq"] = seq
|
| 3936 |
out.append(phrase)
|
| 3937 |
for game in GAMES:
|
| 3938 |
-
for he, sentence, *he_say in GAME_ITEMS[game["id"]]:
|
| 3939 |
words = [_word(t) for t in sentence.split()]
|
| 3940 |
-
|
|
|
|
|
|
|
| 3941 |
say = _voiced(he_say[0] if he_say else he)
|
| 3942 |
if say != he:
|
| 3943 |
phrase["he_say"] = say
|
|
|
|
| 3856 |
|
| 3857 |
# Games live outside the lesson path. Their phrases use the same scoring bank, but they are not topics,
|
| 3858 |
# do not affect lesson completion, and cannot be assigned as homework.
|
| 3859 |
+
GAMES = [{"id": "game-yalla-verb", "name": "פועל נגד הזמן", "lesson": "1", "bubble": True, "hidden": False,
|
| 3860 |
"unit": "פועל", "task": "אמרו את הפועל בערבית מדוברת: בעבר ואז בעתיד, לפני שהבועה נעלמת"}]
|
| 3861 |
+
|
| 3862 |
+
|
| 3863 |
+
def _verb_hint(unlock: str, sentence: str) -> tuple[str, str]:
|
| 3864 |
+
"""The workbook's building and weak/stem class for a game's past + future pair."""
|
| 3865 |
+
defaults = {
|
| 3866 |
+
"1": ("בניין ראשון", "גזרת פַעַל"), "3": ("בניין ראשון", "גזרת פַעַל"),
|
| 3867 |
+
"5": ("בניין ראשון", "גזרת ע״ו"), "6": ("בניין ראשון", "גזרת ע״ו"),
|
| 3868 |
+
"8": ("בניין ראשון", "גזרת פִעֵל"), "10": ("בניין ראשון", "גזרת פִעֵל"),
|
| 3869 |
+
"2.1": ("בניין ראשון", "גזרת פַעַל"), "2.3": ("בניין שני", "גזרת השלמים"),
|
| 3870 |
+
"2.4": ("בניין שני", "גזרת השלמים"), "2.6": ("בניין שלישי", "גזרת השלמים"),
|
| 3871 |
+
"2.7": ("בניין ראשון", "גזרת פִעֵל"), "2.8": ("בניין ראשון", "גזרת הכפולים"),
|
| 3872 |
+
"2.9": ("בניין ראשון", "גזרת פִעֵל"),
|
| 3873 |
+
}
|
| 3874 |
+
past = sentence.split("،", 1)[0]
|
| 3875 |
+
special = {
|
| 3876 |
+
"اجا": ("בניין ראשון", "גזרת ל״א"), "حكى": ("בניין ראשון", "גזרת ל״א"),
|
| 3877 |
+
"اعطى": ("בניין רביעי", "גזרת ל״א"), "اشترى": ("בניין שמיני", "גזרת ל״א"),
|
| 3878 |
+
"اخد": ("בניין ראשון", "גזרת פַעַל"), "شكر": ("בניין ראשון", "גזרת פַעַל"),
|
| 3879 |
+
"تغدّى": ("בניין חמישי", "גזרת ל״א"), "غنّى": ("בניין שני", "גזרת ל״א"),
|
| 3880 |
+
"زاد": ("בניין ראשון", "גזרת ע״י"), "جاب": ("בניין ראשון", "גזרת ע״י"),
|
| 3881 |
+
"باع": ("בניין ראשון", "גזרת ע״י"), "صار": ("בניין ראשון", "גזרת ע״י"),
|
| 3882 |
+
"وقّف": ("בניין שני", "גזרת השלמים"), "استنّى": ("בניין עשירי", "גזרת ל״א"),
|
| 3883 |
+
"لاقى": ("בניין שלישי", "גזרת ל״א"), "ساوى": ("בניין שלישי", "גזרת ל״א"),
|
| 3884 |
+
"نسي": ("בניין ראשון", "גזרת ל״א"), "بكى": ("בניין ראשון", "גזרת ל״א"),
|
| 3885 |
+
"زعّل": ("בניין שני", "גזרת השלמים"), "مشي": ("בניין ראשון", "גזרת ל״א"),
|
| 3886 |
+
"نام": ("בניין ראשון", "גזרת ע״ו"), "عاش": ("בניין ראשון", "גזרת ע״י"),
|
| 3887 |
+
}
|
| 3888 |
+
return special[past] if past in special else defaults[unlock]
|
| 3889 |
+
|
| 3890 |
+
|
| 3891 |
+
def _game_verbs() -> list[tuple[str, tuple, str, str]]:
|
| 3892 |
+
"""Every verb when first taught: unlock lesson, exercise, building, and class.
|
| 3893 |
+
|
| 3894 |
+
Later review topics repeat earlier verbs; keeping the first occurrence makes the game cumulative without
|
| 3895 |
+
putting the same verb into its pool twice.
|
| 3896 |
+
"""
|
| 3897 |
+
out, seen = [], set()
|
| 3898 |
+
for key, topics in LESSONS.items():
|
| 3899 |
+
for tid, _, _, _, items in topics:
|
| 3900 |
+
if tid != "verbs":
|
| 3901 |
+
continue
|
| 3902 |
+
for item in items:
|
| 3903 |
+
signature = item[1] # the Arabic past + future pair is the stable identity
|
| 3904 |
+
if signature not in seen:
|
| 3905 |
+
seen.add(signature)
|
| 3906 |
+
unlock = lesson_id(*key)
|
| 3907 |
+
out.append((unlock, item, *_verb_hint(unlock, signature)))
|
| 3908 |
+
return out
|
| 3909 |
+
|
| 3910 |
+
|
| 3911 |
+
GAME_ITEMS = {"game-yalla-verb": _game_verbs()}
|
| 3912 |
|
| 3913 |
|
| 3914 |
def _present_of(key: str) -> tuple[str, list[str]] | None:
|
|
|
|
| 3985 |
phrase["seq"] = seq
|
| 3986 |
out.append(phrase)
|
| 3987 |
for game in GAMES:
|
| 3988 |
+
for unlock, (he, sentence, *he_say), binyan, gizra in GAME_ITEMS[game["id"]]:
|
| 3989 |
words = [_word(t) for t in sentence.split()]
|
| 3990 |
+
he = re.sub(r"\s*\(עבר, עתיד\)$", "", he)
|
| 3991 |
+
phrase = dict(cat=game["id"], he=he, tr=" ".join(t for _, t, _ in words),
|
| 3992 |
+
variants=_variants(words), unlock=unlock, binyan=binyan, gizra=gizra)
|
| 3993 |
say = _voiced(he_say[0] if he_say else he)
|
| 3994 |
if say != he:
|
| 3995 |
phrase["he_say"] = say
|
static/index.html
CHANGED
|
@@ -5,7 +5,7 @@
|
|
| 5 |
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
|
| 6 |
<title>אהלא וסהלא</title>
|
| 7 |
<link rel="preconnect" href="https://fonts.googleapis.com">
|
| 8 |
-
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Assistant:wght@400;600;700&family=Secular+One&family=Noto+Naskh+Arabic:wght@500;700&family=Noto+Sans+Mono&display=swap">
|
| 9 |
<style>
|
| 10 |
/* Layout: one compact practice card that fits the first screen: prompt, mic, hint, per-word feedback, actions. RTL. */
|
| 11 |
:root{
|
|
@@ -14,6 +14,9 @@
|
|
| 14 |
--sumac:#A3303F; --sumac-bg:#F6E3E3; --ok:#2F7A4A; --ok-bg:#E1F0E4; --amber:#8A5E0E; --amber-bg:#F5ECD8; --orange:#C45F00;
|
| 15 |
--f-display:"Secular One","Assistant",system-ui,sans-serif;
|
| 16 |
--f-body:"Assistant",system-ui,"Segoe UI",Arial,sans-serif;
|
|
|
|
|
|
|
|
|
|
| 17 |
--f-ar:"Noto Naskh Arabic","Geeza Pro","Arabic Typesetting","Traditional Arabic",serif;
|
| 18 |
--f-ipa:"Noto Sans Mono","DejaVu Sans Mono",ui-monospace,monospace;
|
| 19 |
}
|
|
@@ -89,6 +92,23 @@ body.home:not(.manage) #toNow{bottom:76px} body.home:not(.manage) #logoutBtn{bot
|
|
| 89 |
#vids button .seen{grid-row:1;grid-column:3}
|
| 90 |
#vids button.now{padding-block:16px;background:var(--olive);border-color:var(--olive);color:var(--on-olive);box-shadow:0 3px 0 var(--olive-deep);font-size:17px}
|
| 91 |
#vids button.now i,#vids button.now small{color:inherit}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
/* the way back to the path, at the head of the daily videos' screen (no tab of the foot's bar is lit there) */
|
| 93 |
#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)}
|
| 94 |
#dailyDlg{width:min(92vw,380px)}
|
|
@@ -148,6 +168,20 @@ body.home:not(.manage) #toNow{bottom:76px} body.home:not(.manage) #logoutBtn{bot
|
|
| 148 |
.cup.won{background:var(--amber-bg);border-color:var(--amber);box-shadow:0 0 0 6px color-mix(in srgb,var(--amber) 22%,transparent)}
|
| 149 |
#toNow{position:fixed;bottom:16px;left:50%;transform:translateX(-50%);z-index:8;padding:9px 16px;border:0;border-radius:999px;background:var(--olive);color:var(--on-olive);box-shadow:0 3px 0 var(--olive-deep),0 6px 16px rgb(0 0 0/.25);font:700 14px/1 var(--f-body);cursor:pointer}
|
| 150 |
@media (prefers-reduced-motion:reduce){.dot,.chapter{transition:none}.tag,.road .live{animation:none}.sat.now .ring::after{animation:none;opacity:.6}}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 151 |
.card{background:var(--surface);border:1px solid var(--line);border-radius:16px;padding:14px 16px;display:flex;flex-direction:column;gap:10px}
|
| 152 |
.meta{display:flex;justify-content:space-between;color:var(--muted);font-size:13px;letter-spacing:.04em;font-variant-numeric:tabular-nums}
|
| 153 |
.meta .idx{background:var(--olive-soft);color:var(--olive);font-weight:700;padding:1px 10px;border-radius:999px}
|
|
@@ -157,7 +191,7 @@ body.home:not(.manage) #toNow{bottom:76px} body.home:not(.manage) #logoutBtn{bot
|
|
| 157 |
.prompt .note{display:block;margin-top:4px;font:600 14px/1.3 var(--f-body);color:var(--muted)}
|
| 158 |
.task{color:var(--muted);font-size:14px;margin:-6px 0 0}
|
| 159 |
.hint{display:flex;flex-wrap:wrap;align-items:baseline;gap:2px 16px;padding:6px 12px;border-radius:10px;background:var(--olive-soft)}
|
| 160 |
-
.hint .tr{font
|
| 161 |
/* doubling mark: drawn here, because an Arabic shadda on a Hebrew letter has no glyph on Android */
|
| 162 |
.sh{position:relative}
|
| 163 |
.sh::before{content:"";position:absolute;top:-.16em;left:50%;transform:translateX(-50%);width:.44em;height:.26em;background:currentColor;-webkit-mask:var(--shadda) center/contain no-repeat;mask:var(--shadda) center/contain no-repeat}
|
|
@@ -217,6 +251,15 @@ body.driving .mic::before{display:none} body.driving .mic-zone.two{display:flex}
|
|
| 217 |
.word .n{font-size:12px;line-height:1.5;color:var(--muted);font-variant-numeric:tabular-nums}
|
| 218 |
.word .n [lang=ar]{font-family:var(--f-ar);font-size:14px}
|
| 219 |
.word .w.bad{background:none;color:var(--sumac)} .word .w.mid{background:none;color:var(--amber)} .word .w.good{background:none;color:var(--ink)}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 220 |
.tips{list-style:none;margin:0;padding:0;display:flex;flex-direction:column;gap:6px}
|
| 221 |
.tips li{padding:6px 10px;border-radius:10px;border:1px solid var(--line);font-size:15px;line-height:1.4}
|
| 222 |
.tips .what::after{content:" · "}
|
|
@@ -294,8 +337,8 @@ body:not(.manage) #manage,body.manage #wrap>header,body.manage #path,body.manage
|
|
| 294 |
.modes button{display:flex;flex-direction:column;align-items:center;gap:2px;padding:8px 6px;border:0;border-radius:10px;background:transparent;color:var(--ink);font:700 16px/1.2 var(--f-body);cursor:pointer}
|
| 295 |
.modes button small{font:600 12px/1.2 var(--f-body);color:var(--muted)}
|
| 296 |
.modes button[aria-selected=true]{background:var(--surface);box-shadow:0 1px 2px rgba(0,0,0,.15)}
|
| 297 |
-
#manage.classes :is(#mTabs,#mHead,#mLessons,#mRoster,#mStudent),#manage:not(.classes) #mClasses{display:none}
|
| 298 |
-
#manage.content :is(#mTabs,#mHead,#mLessons,#mRoster,#mStudent),#manage:not(.content) #mContent{display:none}
|
| 299 |
/* the content part: a level's name, then a card per lesson with its topics and videos, a row each, and the form that adds a video */
|
| 300 |
#mContent{display:flex;flex-direction:column;gap:12px}
|
| 301 |
.csec[open]>:not(:last-child){margin-bottom:12px}
|
|
@@ -338,9 +381,14 @@ body:not(.manage) #manage,body.manage #wrap>header,body.manage #path,body.manage
|
|
| 338 |
#mClasses>.btn{align-self:flex-start}
|
| 339 |
#mClasses .card>.btn{align-self:flex-start}
|
| 340 |
/* a student's own screen takes the class's place in the panel: the way back, their figures, their lessons, their sentences */
|
| 341 |
-
#manage.student :is(#mTabs,#mHead,#mLessons,#mRoster),#manage:not(.student) #mStudent{display:none}
|
| 342 |
#mStudent{display:flex;flex-direction:column;gap:inherit}
|
| 343 |
#mStudent .back{align-self:flex-start}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 344 |
.cform{display:flex;flex-direction:column;gap:10px}
|
| 345 |
.cform label{display:flex;flex-direction:column;gap:4px;font:700 14px/1.3 var(--f-body)}
|
| 346 |
.cform label small{font-weight:500;color:var(--muted)}
|
|
@@ -495,25 +543,56 @@ body.driving .card.storymode .prompt{display:block}
|
|
| 495 |
/* a story's quiz, once it ended: the grade is back on the card, over the mistakes made most often */
|
| 496 |
.card.storymode.quizdone .verdict{display:flex}
|
| 497 |
.tips li .sub{display:block}
|
| 498 |
-
/* "
|
| 499 |
-
.card.bubblemode{min-height:min(610px,72vh);overflow:hidden;position:relative;background:linear-gradient(180deg,#
|
| 500 |
-
.card.bubblemode .prompt{position:relative;z-index:1;display:grid;place-items:center;width:clamp(150px,42vw,220px);height:clamp(
|
| 501 |
-
.card.bubblemode .prompt::before{content:"";position:absolute;inset:-10px;border-radius:50%;border:
|
| 502 |
-
.card.bubblemode .prompt::after{content:"";position:absolute;left:
|
| 503 |
-
.card.bubblemode .bubble-grade{position:absolute;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 504 |
.card.bubblemode .task{font-weight:700;color:var(--olive)}
|
| 505 |
.card.bubblemode .donehint,.card.bubblemode .progress{position:relative;z-index:2}
|
| 506 |
-
.card.bubblemode>:not(.prompt){display:none!important}
|
| 507 |
body.bubble-game #wrap>header,body.bubble-game #practice>.roundbar{display:none}
|
| 508 |
#gameBack{display:none}
|
| 509 |
body.bubble-game #gameBack{display:flex;position:fixed;top:max(12px,env(safe-area-inset-top));right:12px;z-index:12;align-items:center;gap:6px;border:2px solid #111;border-radius:999px;background:#63bd4d;color:#111;padding:9px 14px;font:800 15px/1 var(--f-body);cursor:pointer;box-shadow:0 3px 0 #111}
|
| 510 |
body.bubble-game #gameBack:active{transform:translateY(2px);box-shadow:0 1px 0 #111}
|
| 511 |
-
.card.bubblemode .prompt.burst{animation:verb-burst .
|
| 512 |
.card.bubblemode .prompt.burst::before{animation:none;opacity:0}
|
| 513 |
-
|
|
|
|
| 514 |
@keyframes verb-time{from{clip-path:inset(0)}to{clip-path:inset(100% 0 0 0)}}
|
| 515 |
-
@keyframes verb-burst{0%{transform:scale(1);opacity:1}
|
| 516 |
-
@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 517 |
/* Without a microphone ("תרגול שקט ללא ציון"): a Hebrew sentence is answered by hand instead of said, built from its
|
| 518 |
Arabic words, tapped in order out of a bank that holds a few words too many. */
|
| 519 |
body.quiet :is(#mic,#playMine,#driveBtn,.phone-btn),body.driving :is(#quietBtn,#heBtn,.miclab,.phone-btn){display:none}
|
|
@@ -578,7 +657,7 @@ body.quiet :is(#mic,#playMine,#driveBtn,.phone-btn),body.driving :is(#quietBtn,#
|
|
| 578 |
|
| 579 |
<div id="today" hidden></div>
|
| 580 |
<section id="vids" aria-live="polite"></section>
|
| 581 |
-
<nav id="nav" aria-label="ניווט"><button data-view="">מסלול</button><button data-view="games" hidden>משחקים</button><button data-view="library">ספריה דיגיטלית</button></nav>
|
| 582 |
<nav class="path" id="path" aria-label="מסלול הלימוד"></nav>
|
| 583 |
<button id="toNow" hidden></button>
|
| 584 |
|
|
@@ -597,6 +676,9 @@ body.quiet :is(#mic,#playMine,#driveBtn,.phone-btn),body.driving :is(#quietBtn,#
|
|
| 597 |
<div id="envWarn" class="warn" hidden></div>
|
| 598 |
|
| 599 |
<main class="card" id="card" aria-live="polite">
|
|
|
|
|
|
|
|
|
|
| 600 |
<div class="meta"><span id="counter"></span></div>
|
| 601 |
<div class="progress" id="progress" hidden><i id="progressBar"></i></div>
|
| 602 |
<div class="donehint" id="doneHint" hidden></div>
|
|
@@ -629,6 +711,11 @@ body.quiet :is(#mic,#playMine,#driveBtn,.phone-btn),body.driving :is(#quietBtn,#
|
|
| 629 |
<div class="verdict"><span class="score" id="score"></span><span class="pill" id="pill"></span><div class="words" id="words"></div></div>
|
| 630 |
<p class="sub" id="whyHint" hidden></p>
|
| 631 |
<ul class="tips" id="tips"></ul>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 632 |
</section>
|
| 633 |
|
| 634 |
<div class="row" id="varRow" hidden>
|
|
@@ -652,6 +739,7 @@ body.quiet :is(#mic,#playMine,#driveBtn,.phone-btn),body.driving :is(#quietBtn,#
|
|
| 652 |
<div class="modes" id="mModes" role="tablist" aria-label="ניהול" hidden><button role="tab" data-mode="classes">כיתות<small>פתיחה, עריכה ומחיקה</small></button><button role="tab" data-mode="students">תלמידים<small>ההתקדמות בכל כיתה</small></button><button role="tab" data-mode="content">תוכן<small>נושאים, סרטונים וטקסטים</small></button></div>
|
| 653 |
<div id="mClasses"></div>
|
| 654 |
<div id="mContent"></div>
|
|
|
|
| 655 |
<div class="tabs" id="mTabs" role="tablist" aria-label="כיתות" hidden></div>
|
| 656 |
<div class="card" id="mHead" hidden></div>
|
| 657 |
<div class="card hard" id="mLessons" hidden></div>
|
|
@@ -744,6 +832,20 @@ body.quiet :is(#mic,#playMine,#driveBtn,.phone-btn),body.driving :is(#quietBtn,#
|
|
| 744 |
<label>הקראת המשפט בעברית<input type="checkbox" id="readHe"></label>
|
| 745 |
</div>
|
| 746 |
</dialog>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 747 |
<dialog id="phoneDlg" aria-labelledby="phoneTitle">
|
| 748 |
<div class="dlg-head"><h2 id="phoneTitle">ניתוח פונמות<small>הרצף הצפוי מול הפענוח החופשי של המודל</small></h2><button class="btn" id="phoneClose">סגירה</button></div>
|
| 749 |
<p class="phone-note">זהו פירוש המודל להקלטה, ולא תעתיק פונטי מוסמך. תנועות קרובות ואורך תנועה מסומנים כהתאמה מקורבת.</p>
|
|
@@ -752,6 +854,10 @@ body.quiet :is(#mic,#playMine,#driveBtn,.phone-btn),body.driving :is(#quietBtn,#
|
|
| 752 |
<section id="trackBox"><h3 class="heatmap-title">מיקום הפונמות בזמן</h3><div class="phone-track-wrap"><canvas id="phoneTrack" role="img" aria-label="רצף הפונמות הצפוי והמזוהה לאורך זמן"></canvas></div></section>
|
| 753 |
<section id="heatmapBox"><h3 class="heatmap-title">הסתברות פונמות לאורך ההקלטה</h3><div class="heatmap-wrap"><canvas id="phoneHeatmap" role="img" aria-label="מפת חום של הסתברויות הפונמות לאורך ההקלטה"></canvas></div><div class="heatmap-scale"><span>0%</span><i></i><span>100%</span><span>· ★ פונמה צפויה</span></div></section>
|
| 754 |
</dialog>
|
|
|
|
|
|
|
|
|
|
|
|
|
| 755 |
<div id="whyTip" role="tooltip" hidden></div>
|
| 756 |
<button id="logoutBtn" hidden>יציאה</button>
|
| 757 |
|
|
@@ -776,6 +882,7 @@ let MY_CLASSES=[], MY_CLASS=null; // a student's classes ({name, lessons, home
|
|
| 776 |
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
|
| 777 |
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;
|
| 778 |
let myAudioUrl=null;
|
|
|
|
| 779 |
const phraseOf=id=>PHRASES.find(p=>p.id===id); // by id: the list skips the phrases that have no tab
|
| 780 |
const categoryOf=id=>CATS.find(c=>c.id===id)||GAMES.find(g=>g.id===id);
|
| 781 |
|
|
@@ -870,6 +977,7 @@ function endDaily(){ // past the session's last sentence: back to the path, an
|
|
| 870 |
The library: videos that are not on the path, the same ones for every level and class. */
|
| 871 |
const dailyVideos=()=>{ const d=today(), seen=new Set(); return (FREE?TEACHER_DAILIES:(MY_CLASS?[MY_CLASS]:MY_CLASSES).flatMap(k=>k.dailies||[])).filter(v=>v.date<=d&&!seen.has(v.id)&&seen.add(v.id)).sort((a,b)=>b.date.localeCompare(a.date)); };
|
| 872 |
const libVideos=()=>LIBRARY;
|
|
|
|
| 873 |
function drawNav(){ // the tabs, and the screen of videos when one is on show
|
| 874 |
const view=document.body.dataset.view||"", box=$("vids"), d=today();
|
| 875 |
for(const b of $("nav").children){
|
|
@@ -885,6 +993,11 @@ function drawNav(){ // the tabs, and the screen of videos when one is on show
|
|
| 885 |
if(view==="games"){
|
| 886 |
const games=GAMES.filter(game=>!game.hidden);
|
| 887 |
box.append(mark("","משחקים","h2"));
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 888 |
if(!games.length) box.append(mark("","המשחקים הראשונים יגיעו בקרוב.","p"));
|
| 889 |
for(const game of games){
|
| 890 |
const b=mark("now","","button"), done=PHRASES.filter(p=>p.cat===game.id&&best[p.id]!=null).length;
|
|
@@ -899,6 +1012,50 @@ function drawNav(){ // the tabs, and the screen of videos when one is on show
|
|
| 899 |
else box.append(mark("",was.length?"להיום אין סרטון חדש. אפשר לחזור לסרטונים הקודמים.":"עוד אין סרטונים יומיים. כשנקבע לסרטון תאריך (בעריכת הכיתה), הוא מופיע כאן מאותו יום.","p"));
|
| 900 |
if(was.length) box.append(mark("","הסרטונים הקודמים","h3"));
|
| 901 |
for(const v of was) row(v,dailyWatched,"ihki.dailyWatched",dayWord(v.date));
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 902 |
}else{
|
| 903 |
box.append(mark("","ספריה דיגיטלית","h2"));
|
| 904 |
if(!libVideos().length) box.append(mark("","עוד אין סרטונים בספריה.","p"));
|
|
@@ -1188,16 +1345,58 @@ const EXCELLENT=85; // the score the verdict calls "מצוין"
|
|
| 1188 |
// left, it is the whole topic, and a practised sentence shows its best score (see show).
|
| 1189 |
// `here` is the topic's sentence on the card: not always the round's, because going back passes through the practised ones.
|
| 1190 |
let ordered=false, topic=[], here=null, showDone=store.get("ihki.showDone",false);
|
| 1191 |
-
const BUBBLE_MS=
|
| 1192 |
-
let bubbleTimer=null, bubbleDeadline=0, bubbleFor=null, bubbleResolving=false;
|
|
|
|
| 1193 |
const bubbleCat=()=>!daily&&(categoryOf(cat)||{}).bubble;
|
| 1194 |
-
function
|
| 1195 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1196 |
function armBubble(){
|
| 1197 |
pauseBubble();
|
| 1198 |
if(!bubbleCat()||home) return;
|
| 1199 |
-
if(bubbleFor!==cur.id){
|
|
|
|
|
|
|
|
|
|
| 1200 |
const left=Math.max(0,bubbleDeadline-Date.now());
|
|
|
|
|
|
|
| 1201 |
bubbleTimer=setTimeout(()=>{
|
| 1202 |
bubbleTimer=null;
|
| 1203 |
if(home||!bubbleCat()||bubbleResolving) return;
|
|
@@ -1208,7 +1407,14 @@ function armBubble(){
|
|
| 1208 |
function setRound(){
|
| 1209 |
quizOff();
|
| 1210 |
if(daily){ ordered=true; topic=order=[...daily]; pos=0; marks(); return; } // the session's sentences, in its own order
|
| 1211 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1212 |
ordered=list.length>0&&list.every(p=>p.seq!=null);
|
| 1213 |
topic=(ordered?list.sort((a,b)=>a.seq-b.seq):shuffle(list)).map(p=>p.id);
|
| 1214 |
const todo=topic.filter(id=>best[id]==null&&!(quiet&&silent[id])), all=showDone||!todo.length, box=$("showDone");
|
|
@@ -1564,7 +1770,8 @@ function show(p,wait){ // wait: do not record until the microphone button is p
|
|
| 1564 |
const c=categoryOf(daily?cur.cat:cat), mine=topic.includes(cur.id); // a topic or game may name its items and its own task
|
| 1565 |
$("card").classList.toggle("bubblemode",!!c.bubble);
|
| 1566 |
document.body.classList.toggle("bubble-game",!!c.bubble);
|
| 1567 |
-
$("
|
|
|
|
| 1568 |
if(c.bubble){ $("prompt").style.animation="none"; void $("prompt").offsetWidth; $("prompt").style.animation=""; }
|
| 1569 |
heStop(); $("heCheck").hidden=true; micZone.classList.toggle("two",heOk&&!!cur.read&&!story); // a phrase to read can be answered in Hebrew too
|
| 1570 |
$("task").textContent=cur.read?heOk?HE_TASK:"קראו בקול ותרגמו לעברית":mine&&c.task||"איך אומרים את זה בערבית מדוברת?";
|
|
@@ -1786,6 +1993,48 @@ function drawPhoneTrack(data){
|
|
| 1786 |
const seconds=(data.duration_ms||0)/1000;
|
| 1787 |
for(const part of [0,.25,.5,.75,1]) c.fillText(seconds?`${(seconds*part).toFixed(1)}s`:Math.round(part*100)+"%",label+part*plot,height-axis/2);
|
| 1788 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1789 |
$("phoneBtn").onclick=()=>{ if(lastPhone){ drawPhones(lastPhone); $("phoneDlg").showModal(); } };
|
| 1790 |
$("phoneClose").onclick=()=>$("phoneDlg").close();
|
| 1791 |
|
|
@@ -1795,6 +2044,8 @@ function render(r){
|
|
| 1795 |
if(FREE&&!$("card").classList.contains("storymode")){
|
| 1796 |
lastPhone=r; $("phoneBtn").hidden=false; $("phoneBtn").disabled=false;
|
| 1797 |
}
|
|
|
|
|
|
|
| 1798 |
$("status").textContent=r.score<30?"רוצים לנסות שוב? לחצו על המיקרופון":"לחצו כדי לנסות שוב";
|
| 1799 |
$("nextBtn").classList.add("primary");
|
| 1800 |
$("score").textContent=r.score;
|
|
@@ -1862,12 +2113,14 @@ async function bubbleOutcome(r,expired=false){
|
|
| 1862 |
bubbleResolving=true;
|
| 1863 |
if(!expired){
|
| 1864 |
const old=$("prompt").querySelector(".bubble-grade"); if(old) old.remove();
|
| 1865 |
-
|
|
|
|
| 1866 |
}
|
| 1867 |
if(correct){
|
|
|
|
| 1868 |
stopBubble();
|
| 1869 |
$("prompt").classList.add("burst");
|
| 1870 |
-
await pause(
|
| 1871 |
}else{
|
| 1872 |
if(!expired&&Date.now()<bubbleDeadline){
|
| 1873 |
bubbleResolving=false;
|
|
@@ -1875,10 +2128,13 @@ async function bubbleOutcome(r,expired=false){
|
|
| 1875 |
autoRec=true; autoRecord();
|
| 1876 |
return;
|
| 1877 |
}
|
|
|
|
|
|
|
|
|
|
| 1878 |
const a=await answerAudio(id);
|
| 1879 |
if(cur.id!==id||home) return;
|
| 1880 |
if(a) await playUrl(a.url,true); else await speakLocal(cur.ar,"ar");
|
| 1881 |
-
await pause(
|
| 1882 |
}
|
| 1883 |
bubbleResolving=false;
|
| 1884 |
if(cur.id===id&&!home&&bubbleCat()) nextPhrase();
|
|
@@ -1960,6 +2216,7 @@ async function startRec(auto){ // auto: started by the page for the sentence o
|
|
| 1960 |
const blob=new Blob(chunks,{type:rec.mimeType||"audio/webm"});
|
| 1961 |
if(myAudioUrl) URL.revokeObjectURL(myAudioUrl);
|
| 1962 |
myAudioUrl=URL.createObjectURL(blob); $("playMine").disabled=false;
|
|
|
|
| 1963 |
mic.disabled=true; $("status").textContent="מנתח…";
|
| 1964 |
try{
|
| 1965 |
const fd=new FormData(); fd.append("phrase_id",id); fd.append("audio",blob,"rec");
|
|
@@ -1993,7 +2250,7 @@ const nextPhrase=()=>{
|
|
| 1993 |
if(k<0) roundEnd(); else{ pos=k; show(); }
|
| 1994 |
return;
|
| 1995 |
}
|
| 1996 |
-
if(pos+1>=order.length&&(order!==topic||isStory())){ roundEnd(); return; } // a round of unpractised sentences
|
| 1997 |
pos=(pos+1)%order.length; if(pos===0&&!ordered) shuffle(order); show();
|
| 1998 |
};
|
| 1999 |
$("nextBtn").onclick=nextPhrase;
|
|
@@ -2193,7 +2450,7 @@ function drawManage(){
|
|
| 2193 |
if(!["classes","students","content"].includes(mMode)) mMode=classes.length?"students":"classes";
|
| 2194 |
$("mModes").hidden=false; $("manage").classList.toggle("classes",mMode==="classes"); $("manage").classList.toggle("content",mMode==="content");
|
| 2195 |
for(const b of $("mModes").children) b.setAttribute("aria-selected",b.dataset.mode===mMode);
|
| 2196 |
-
drawClasses(classes); drawContent(); drawTabs(classes); drawHead(klass,students); drawLessons(students,listed); drawRoster(klass,students,listed);
|
| 2197 |
const one=students.find(s=>s.email===shownStudent); // a student who left the class has no screen in it
|
| 2198 |
if(!one) shownStudent="";
|
| 2199 |
$("manage").classList.toggle("student",!!one); $("mStudent").innerHTML="";
|
|
@@ -2380,6 +2637,33 @@ addEventListener("popstate",e=>{
|
|
| 2380 |
const to=e.state&&e.state.student||""; if(to===shownStudent||!CLASS) return;
|
| 2381 |
shownStudent=to; drawManage(); scrollTo(0,to?0:classScroll);
|
| 2382 |
});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2383 |
function drawTabs(classes){
|
| 2384 |
const tabs=$("mTabs"); tabs.innerHTML=""; tabs.hidden=!classes.length;
|
| 2385 |
for(const c of classes){
|
|
@@ -2474,7 +2758,7 @@ function drawRoster(klass,students,listed){
|
|
| 2474 |
students.sort((a,b)=>(b.last||"").localeCompare(a.last||"")||b.joined-a.joined||a.email.localeCompare(b.email));
|
| 2475 |
for(const s of students){
|
| 2476 |
const row=mark("rrow","","button"), who=mark("who","");
|
| 2477 |
-
const shown=mark("",s.nick||s.name||s.email,"b"); shown.dir="auto"; // an address is cut at its end
|
| 2478 |
who.append(shown,mark("",lastSeen(s)+(s.unmatched?` · ${s.unmatched} לא זוהו`:""),"small"));
|
| 2479 |
who.title=s.email; row.append(who);
|
| 2480 |
for(const col of cols){ const t=col.of(s), c=mark("cell",""); c.append(ratio(t),bar(t.n?t.done/t.n:0)); c.title=`${col.title}: ${col.did} ${t.done} מתוך ${t.n}`+(t.avg!=null?`, ציון ${t.avg}`:""); row.append(c); }
|
|
@@ -2735,6 +3019,117 @@ $("newForm").onsubmit=async e=>{ // "next" checks the step on show; on the las
|
|
| 2735 |
buttons.forEach(b=>b.disabled=false);
|
| 2736 |
};
|
| 2737 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2738 |
function useLessons(ids){ // the path shows these lessons only (null: every one)
|
| 2739 |
LESSONS=ALL_LESSONS.filter(l=>!ids||ids.includes(l.id)); if(!LESSONS.length) LESSONS=ALL_LESSONS;
|
| 2740 |
CATS=ALL_CATS.filter(c=>LESSONS.some(l=>l.id===c.lesson)); // none when every lesson of the student's is still to come
|
|
@@ -2797,7 +3192,7 @@ if(AUTH_URL){
|
|
| 2797 |
const ok=!res||res.status!==403; // a server that cannot be reached is not a refusal
|
| 2798 |
const me=res&&res.ok?await res.json().catch(()=>({})):{}, teacher=!!me.teacher;
|
| 2799 |
const mine=me.classes||[]; // a teacher practises every lesson and is not asked for a class
|
| 2800 |
-
MY_CLASSES=teacher?[]:mine; MY_CLASS=null; FREE=teacher; TEACHER_DAILIES=me.dailies||[];
|
| 2801 |
$("myClass").textContent=mine.length>1?(teacher?`כיתות: ${mine.map(c=>c.name).join(" · ")}`:"בחירת כיתה"):mine.length?`כיתת ${mine[0].name}`:"";
|
| 2802 |
$("myClass").classList.toggle("many",MY_CLASSES.length>1); $("myClass").title=MY_CLASSES.length>1?"מעבר לכיתה אחרת":"התלמידים בכיתה שלי";
|
| 2803 |
MY_LESSONS=me.lessons||null; if(ALL_LESSONS.length) useLessons(MY_LESSONS);
|
|
|
|
| 5 |
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
|
| 6 |
<title>אהלא וסהלא</title>
|
| 7 |
<link rel="preconnect" href="https://fonts.googleapis.com">
|
| 8 |
+
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Assistant:wght@400;600;700&family=Secular+One&family=Noto+Naskh+Arabic:wght@500;700&family=Noto+Sans+Hebrew:wght@500;700&family=Noto+Sans+Mono&display=swap">
|
| 9 |
<style>
|
| 10 |
/* Layout: one compact practice card that fits the first screen: prompt, mic, hint, per-word feedback, actions. RTL. */
|
| 11 |
:root{
|
|
|
|
| 14 |
--sumac:#A3303F; --sumac-bg:#F6E3E3; --ok:#2F7A4A; --ok-bg:#E1F0E4; --amber:#8A5E0E; --amber-bg:#F5ECD8; --orange:#C45F00;
|
| 15 |
--f-display:"Secular One","Assistant",system-ui,sans-serif;
|
| 16 |
--f-body:"Assistant",system-ui,"Segoe UI",Arial,sans-serif;
|
| 17 |
+
/* Noto Sans Hebrew draws the vowel points larger and more distinctly than Assistant,
|
| 18 |
+
especially the line of patah versus the two dots of tsere on small screens. */
|
| 19 |
+
--f-tr:"Noto Sans Hebrew","Arial Hebrew","Rubik",sans-serif;
|
| 20 |
--f-ar:"Noto Naskh Arabic","Geeza Pro","Arabic Typesetting","Traditional Arabic",serif;
|
| 21 |
--f-ipa:"Noto Sans Mono","DejaVu Sans Mono",ui-monospace,monospace;
|
| 22 |
}
|
|
|
|
| 92 |
#vids button .seen{grid-row:1;grid-column:3}
|
| 93 |
#vids button.now{padding-block:16px;background:var(--olive);border-color:var(--olive);color:var(--on-olive);box-shadow:0 3px 0 var(--olive-deep);font-size:17px}
|
| 94 |
#vids button.now i,#vids button.now small{color:inherit}
|
| 95 |
+
/* Refer a friend: a compact campaign page inside the home navigation, with the two rewards kept visually distinct. */
|
| 96 |
+
.refer{display:flex;flex-direction:column;gap:14px}
|
| 97 |
+
.refer>header{display:block;text-align:center;padding:8px 6px 2px}
|
| 98 |
+
.refer>header h2{margin:0;font:400 28px/1.25 var(--f-display);color:var(--olive)}
|
| 99 |
+
.refer>header p{margin:5px 0 0;color:var(--muted)}
|
| 100 |
+
.refer-rewards{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:10px}
|
| 101 |
+
.refer-reward{padding:14px;border:1px solid var(--line);border-radius:14px;background:var(--surface)}
|
| 102 |
+
.refer-reward b{display:block;margin-bottom:5px;color:var(--olive);font-size:18px}
|
| 103 |
+
.refer-reward strong{color:var(--sumac)}
|
| 104 |
+
.refer-copy{margin:0;padding:14px;border-radius:14px;background:var(--olive-soft);text-align:center;font-weight:600}
|
| 105 |
+
.refer h3{margin:2px 0 0;font:400 21px/1.2 var(--f-display)}
|
| 106 |
+
.refer .refer-actions{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:9px}
|
| 107 |
+
.refer .refer-actions :is(a,button){display:flex;justify-content:center;align-items:center;min-height:50px;padding:10px 12px;border-radius:12px;border:1px solid var(--olive);background:var(--surface);color:var(--olive);font:700 16px/1.25 var(--f-body);text-align:center;text-decoration:none;cursor:pointer}
|
| 108 |
+
.refer .refer-actions a:first-child{background:var(--olive);color:var(--on-olive);box-shadow:0 3px 0 var(--olive-deep)}
|
| 109 |
+
.refer-message{margin:0;padding:14px;border:1px dashed var(--line);border-radius:12px;background:var(--surface);white-space:pre-line}
|
| 110 |
+
.refer-terms{margin:0;color:var(--muted);font-size:13px;line-height:1.45}
|
| 111 |
+
@media (max-width:430px){.refer-rewards,.refer .refer-actions{grid-template-columns:1fr}}
|
| 112 |
/* the way back to the path, at the head of the daily videos' screen (no tab of the foot's bar is lit there) */
|
| 113 |
#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)}
|
| 114 |
#dailyDlg{width:min(92vw,380px)}
|
|
|
|
| 168 |
.cup.won{background:var(--amber-bg);border-color:var(--amber);box-shadow:0 0 0 6px color-mix(in srgb,var(--amber) 22%,transparent)}
|
| 169 |
#toNow{position:fixed;bottom:16px;left:50%;transform:translateX(-50%);z-index:8;padding:9px 16px;border:0;border-radius:999px;background:var(--olive);color:var(--on-olive);box-shadow:0 3px 0 var(--olive-deep),0 6px 16px rgb(0 0 0/.25);font:700 14px/1 var(--f-body);cursor:pointer}
|
| 170 |
@media (prefers-reduced-motion:reduce){.dot,.chapter{transition:none}.tag,.road .live{animation:none}.sat.now .ring::after{animation:none;opacity:.6}}
|
| 171 |
+
.verb-dlg{width:min(94vw,560px);max-height:92vh;padding:0;border:0;border-radius:20px;background:var(--bg);color:var(--ink);box-shadow:0 18px 70px rgb(0 0 0/.35)}
|
| 172 |
+
.verb-dlg::backdrop{background:rgb(20 28 22/.58)}
|
| 173 |
+
.verb-shell{display:flex;flex-direction:column;gap:14px;padding:16px;min-height:min(76vh,650px)}
|
| 174 |
+
.verb-head{display:flex;align-items:center;gap:10px}.verb-head h2{flex:1;margin:0;font:400 26px var(--f-display)}
|
| 175 |
+
.verb-stats{display:flex;justify-content:space-between;gap:8px;color:var(--muted);font-weight:700;font-variant-numeric:tabular-nums}
|
| 176 |
+
.verb-track{height:7px;border-radius:8px;background:var(--line);overflow:hidden}.verb-track i{display:block;height:100%;width:0;background:var(--olive);transition:width .2s}
|
| 177 |
+
.verb-menu{display:grid;gap:10px}.verb-path{padding:16px;border:1px solid var(--line);border-radius:16px;background:var(--surface);color:var(--ink);text-align:start;font:700 17px var(--f-body);cursor:pointer}.verb-path small{display:block;margin-top:4px;color:var(--muted);font-weight:600}
|
| 178 |
+
.verb-levels{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:7px}.verb-levels button{display:flex;flex-direction:column;align-items:center;justify-content:center;gap:3px;min-height:58px;padding:7px 4px;border:1px solid var(--line);border-radius:10px;background:var(--surface);color:var(--ink);font-weight:700}.verb-levels button small{font:600 11px/1.25 var(--f-body);color:var(--muted)}.verb-levels button.on{background:var(--olive);color:var(--on-olive)}.verb-levels button.on small{color:inherit}.verb-levels button:disabled{opacity:1;border-style:dashed;color:var(--muted);background:color-mix(in srgb,var(--surface) 75%,var(--line))}.verb-levels button:disabled::before{content:"🔒";font-size:14px;line-height:1}
|
| 179 |
+
.verb-board{display:flex;flex:1;flex-direction:column;gap:12px}.verb-cue{text-align:center}.verb-cue h3{margin:8px 0 2px;font:400 clamp(28px,8vw,42px) var(--f-display)}.verb-cue .ar{font:26px var(--f-ar);color:var(--muted)}
|
| 180 |
+
.verb-pronoun{margin:8px 0 0;font:700 22px/1.65 var(--f-tr);letter-spacing:.025em}.verb-choices{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:10px}.verb-choice{min-height:84px;padding:8px 10px 4px;border:2px solid var(--line);border-radius:14px;background:var(--surface);color:var(--ink);font:700 25px/1.75 var(--f-tr);letter-spacing:.035em;cursor:pointer}.verb-choice .ar{display:block;margin-top:-5px;font:18px/1.25 var(--f-ar);letter-spacing:0;color:var(--muted)}.verb-choice.good{border-color:var(--ok);background:var(--ok-bg)}.verb-choice.bad{border-color:var(--sumac);background:var(--sumac-bg)}
|
| 181 |
+
.verb-match{display:grid;grid-template-columns:1fr 1fr;gap:8px}.verb-match button{min-height:68px;padding:6px 8px 3px;border:2px solid var(--line);border-radius:12px;background:var(--surface);color:var(--ink);font:700 22px/1.7 var(--f-tr);letter-spacing:.03em}.verb-match button small{display:block;margin-top:-5px;font:500 17px/1.5 var(--f-tr);letter-spacing:.02em;color:var(--muted)}.verb-match button.selected{border-color:var(--amber);background:var(--amber-bg)}.verb-match button.done{border-color:var(--ok);opacity:.58}.verb-match .ar{display:block;margin-top:-4px;font:16px/1.25 var(--f-ar);letter-spacing:0}
|
| 182 |
+
.verb-feedback{min-height:44px;padding:10px;border-radius:12px;text-align:center;font-weight:700}.verb-feedback:empty{padding:0}.verb-feedback.good{background:var(--ok-bg);color:var(--ok)}.verb-feedback.bad{background:var(--sumac-bg);color:var(--sumac)}
|
| 183 |
+
.verb-speak{display:flex;flex:1;flex-direction:column;align-items:center;justify-content:center;gap:12px;text-align:center}.verb-mic{display:grid;place-items:center;width:86px;height:86px;border:0;border-radius:50%;background:var(--olive);color:var(--on-olive);font-size:34px;box-shadow:0 5px 0 var(--olive-deep);cursor:pointer}.verb-mic.live{background:var(--sumac);box-shadow:0 5px 0 color-mix(in srgb,var(--sumac) 70%,#000)}.verb-mic:disabled{opacity:.5}.verb-record-actions{display:flex;gap:8px}.verb-conversation{padding:14px;border-radius:16px;background:var(--olive-soft)}.verb-conversation .ar{font:700 27px/1.6 var(--f-ar)}.verb-answer{font:700 25px/1.7 var(--f-tr);letter-spacing:.035em}
|
| 184 |
+
@media (max-width:410px){.verb-choices{grid-template-columns:1fr}.verb-shell{padding:12px}.verb-choice{min-height:62px}}
|
| 185 |
.card{background:var(--surface);border:1px solid var(--line);border-radius:16px;padding:14px 16px;display:flex;flex-direction:column;gap:10px}
|
| 186 |
.meta{display:flex;justify-content:space-between;color:var(--muted);font-size:13px;letter-spacing:.04em;font-variant-numeric:tabular-nums}
|
| 187 |
.meta .idx{background:var(--olive-soft);color:var(--olive);font-weight:700;padding:1px 10px;border-radius:999px}
|
|
|
|
| 191 |
.prompt .note{display:block;margin-top:4px;font:600 14px/1.3 var(--f-body);color:var(--muted)}
|
| 192 |
.task{color:var(--muted);font-size:14px;margin:-6px 0 0}
|
| 193 |
.hint{display:flex;flex-wrap:wrap;align-items:baseline;gap:2px 16px;padding:6px 12px;border-radius:10px;background:var(--olive-soft)}
|
| 194 |
+
.hint .tr{font:700 25px/1.75 var(--f-tr);letter-spacing:.035em}
|
| 195 |
/* doubling mark: drawn here, because an Arabic shadda on a Hebrew letter has no glyph on Android */
|
| 196 |
.sh{position:relative}
|
| 197 |
.sh::before{content:"";position:absolute;top:-.16em;left:50%;transform:translateX(-50%);width:.44em;height:.26em;background:currentColor;-webkit-mask:var(--shadda) center/contain no-repeat;mask:var(--shadda) center/contain no-repeat}
|
|
|
|
| 251 |
.word .n{font-size:12px;line-height:1.5;color:var(--muted);font-variant-numeric:tabular-nums}
|
| 252 |
.word .n [lang=ar]{font-family:var(--f-ar);font-size:14px}
|
| 253 |
.word .w.bad{background:none;color:var(--sumac)} .word .w.mid{background:none;color:var(--amber)} .word .w.good{background:none;color:var(--ink)}
|
| 254 |
+
.flag-box{display:flex;flex-wrap:wrap;align-items:center;gap:8px;border-top:1px dashed var(--line);padding-top:10px}
|
| 255 |
+
.flag-box input{flex:1 1 180px;min-width:0;padding:8px 10px;border:1px solid var(--line);border-radius:10px;font:inherit;background:var(--surface);color:inherit}
|
| 256 |
+
.flag-box .sub{flex-basis:100%;margin:0}
|
| 257 |
+
.flag-facts{display:grid;grid-template-columns:auto 1fr;gap:6px 12px;margin:8px 0 0}
|
| 258 |
+
.flag-facts dt{color:var(--muted);font-size:13px;white-space:nowrap}
|
| 259 |
+
.flag-facts dd{margin:0;min-width:0;overflow-wrap:anywhere}
|
| 260 |
+
.flag-facts .ipa{direction:ltr;text-align:right;font:13px/1.5 ui-monospace,monospace;unicode-bidi:isolate}
|
| 261 |
+
.flag-facts ul{margin:0;padding:0;list-style:none;display:flex;flex-direction:column;gap:3px}
|
| 262 |
+
.flag-facts b.good{color:var(--olive)} .flag-facts b.mid{color:#a86a00} .flag-facts b.bad{color:#9f2f27}
|
| 263 |
.tips{list-style:none;margin:0;padding:0;display:flex;flex-direction:column;gap:6px}
|
| 264 |
.tips li{padding:6px 10px;border-radius:10px;border:1px solid var(--line);font-size:15px;line-height:1.4}
|
| 265 |
.tips .what::after{content:" · "}
|
|
|
|
| 337 |
.modes button{display:flex;flex-direction:column;align-items:center;gap:2px;padding:8px 6px;border:0;border-radius:10px;background:transparent;color:var(--ink);font:700 16px/1.2 var(--f-body);cursor:pointer}
|
| 338 |
.modes button small{font:600 12px/1.2 var(--f-body);color:var(--muted)}
|
| 339 |
.modes button[aria-selected=true]{background:var(--surface);box-shadow:0 1px 2px rgba(0,0,0,.15)}
|
| 340 |
+
#manage.classes :is(#mTutors,#mTabs,#mHead,#mLessons,#mRoster,#mStudent),#manage:not(.classes) #mClasses{display:none}
|
| 341 |
+
#manage.content :is(#mTutors,#mTabs,#mHead,#mLessons,#mRoster,#mStudent),#manage:not(.content) #mContent{display:none}
|
| 342 |
/* the content part: a level's name, then a card per lesson with its topics and videos, a row each, and the form that adds a video */
|
| 343 |
#mContent{display:flex;flex-direction:column;gap:12px}
|
| 344 |
.csec[open]>:not(:last-child){margin-bottom:12px}
|
|
|
|
| 381 |
#mClasses>.btn{align-self:flex-start}
|
| 382 |
#mClasses .card>.btn{align-self:flex-start}
|
| 383 |
/* a student's own screen takes the class's place in the panel: the way back, their figures, their lessons, their sentences */
|
| 384 |
+
#manage.student :is(#mTutors,#mTabs,#mHead,#mLessons,#mRoster),#manage:not(.student) #mStudent{display:none}
|
| 385 |
#mStudent{display:flex;flex-direction:column;gap:inherit}
|
| 386 |
#mStudent .back{align-self:flex-start}
|
| 387 |
+
#mTutors .note{margin:0;padding:8px 16px}
|
| 388 |
+
#mTutors label{display:flex;align-items:center;gap:10px;padding:7px 16px;border-top:1px solid var(--line);cursor:pointer}
|
| 389 |
+
#mTutors label span{display:flex;flex-direction:column;min-width:0}
|
| 390 |
+
#mTutors label b{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
| 391 |
+
#mTutors label small{color:var(--muted);font-size:12px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
| 392 |
.cform{display:flex;flex-direction:column;gap:10px}
|
| 393 |
.cform label{display:flex;flex-direction:column;gap:4px;font:700 14px/1.3 var(--f-body)}
|
| 394 |
.cform label small{font-weight:500;color:var(--muted)}
|
|
|
|
| 543 |
/* a story's quiz, once it ended: the grade is back on the card, over the mistakes made most often */
|
| 544 |
.card.storymode.quizdone .verdict{display:flex}
|
| 545 |
.tips li .sub{display:block}
|
| 546 |
+
/* "פועל נגד הזמן": a Hebrew verb rises in a timed balloon while the microphone listens. */
|
| 547 |
+
.card.bubblemode{min-height:min(610px,72vh);overflow:hidden;position:relative;background:linear-gradient(180deg,#dff4ff 0%,#f5fbff 68%,var(--surface) 100%)}
|
| 548 |
+
.card.bubblemode .prompt{position:relative;z-index:1;display:grid;place-items:center;width:clamp(150px,42vw,220px);height:clamp(175px,48vw,250px);margin:clamp(30px,10vh,80px) auto 18px;padding:28px;box-sizing:border-box;border:2px solid #2e782a;border-radius:50% 50% 48% 52%/46% 46% 54% 54%;background:radial-gradient(ellipse at 29% 22%,rgb(255 255 255/.88) 0 5%,rgb(255 255 255/.35) 6% 13%,transparent 14%),radial-gradient(ellipse at 36% 29%,#9ce98a 0%,#69c956 30%,#45a83d 66%,#287823 100%);color:#10230e;text-shadow:0 1px 0 rgb(255 255 255/.45);box-shadow:inset 14px 18px 28px rgb(255 255 255/.2),inset -20px -24px 38px rgb(15 76 17/.3),0 22px 30px rgb(37 90 42/.22);animation:verb-rise 12s linear both}
|
| 549 |
+
.card.bubblemode .prompt::before{content:"";position:absolute;inset:-10px;border-radius:50% 50% 48% 52%/46% 46% 54% 54%;border:5px solid #205f20;clip-path:inset(0);animation:verb-time 12s linear both}
|
| 550 |
+
.card.bubblemode .prompt::after{content:"";position:absolute;left:50%;top:calc(100% - 2px);width:25px;height:22px;background:linear-gradient(135deg,#52b747,#277923);clip-path:polygon(50% 0,100% 100%,0 100%);transform:translateX(-50%);filter:drop-shadow(0 3px 2px rgb(0 0 0/.18))}
|
| 551 |
+
.card.bubblemode .bubble-grade{position:absolute;left:50%;bottom:28px;min-width:64px;padding:6px 11px;border:2px solid #fff;border-radius:999px;background:linear-gradient(180deg,#ffd95e,#f2a91d);color:#4c3100;box-shadow:0 3px 0 #a96800,0 6px 12px rgb(66 50 0/.22);font:800 20px/1 var(--f-display);font-variant-numeric:tabular-nums;white-space:nowrap;transform:translateX(-50%);animation:grade-pop .38s cubic-bezier(.2,1.8,.4,1)}
|
| 552 |
+
.card.bubblemode .bubble-grade::before{content:"★";margin-inline-end:4px;color:#fff;text-shadow:0 1px 1px rgb(92 58 0/.35)}
|
| 553 |
+
.card.bubblemode .bubble-grade.good{background:linear-gradient(180deg,#ffe66f,#ffc52f);color:#513600}
|
| 554 |
+
.card.bubblemode .bubble-grade.mid{background:linear-gradient(180deg,#fff0a7,#efbd3f);color:#513600}
|
| 555 |
+
.card.bubblemode .bubble-grade.bad{background:linear-gradient(180deg,#ffc1a9,#ef7558);color:#642114;box-shadow:0 3px 0 #a43d29,0 6px 12px rgb(66 20 0/.2)}
|
| 556 |
+
.bubble-score{display:flex;position:absolute;top:16px;left:16px;z-index:3;align-items:center;gap:9px;padding:8px 13px;border:2px solid #205f20;border-radius:14px;background:rgb(255 255 255/.9);color:#174f18;box-shadow:0 4px 0 #205f20,0 8px 18px rgb(30 91 36/.18);font:800 15px/1 var(--f-body);font-variant-numeric:tabular-nums;backdrop-filter:blur(5px)}
|
| 557 |
+
.bubble-score[hidden]{display:none}
|
| 558 |
+
.bubble-score b{min-width:1.5ch;font:800 30px/1 var(--f-display);text-align:center}
|
| 559 |
+
.bubble-score.tick b{animation:score-pop .38s cubic-bezier(.2,1.8,.4,1)}
|
| 560 |
+
.bubble-score small{display:block;margin-top:3px;color:#527254;font:700 12px/1 var(--f-body)}
|
| 561 |
+
.bubble-misses{display:flex;position:absolute;top:18px;left:145px;right:12px;z-index:3;align-items:flex-start;gap:3px;direction:ltr;pointer-events:none}
|
| 562 |
+
.bubble-misses[hidden]{display:none}
|
| 563 |
+
.mini-balloon{position:relative;flex:0 0 18px;width:18px;height:22px;border:1px solid #2e782a;border-radius:50% 50% 48% 52%/46% 46% 54% 54%;background:radial-gradient(ellipse at 29% 22%,rgb(255 255 255/.85) 0 8%,transparent 16%),radial-gradient(ellipse at 36% 29%,#9ce98a 0%,#69c956 38%,#287823 100%);box-shadow:inset -3px -4px 5px rgb(15 76 17/.25),0 2px 3px rgb(37 90 42/.22)}
|
| 564 |
+
.mini-balloon::after{content:"";position:absolute;left:50%;top:calc(100% - 1px);width:6px;height:5px;background:#348e30;clip-path:polygon(50% 0,100% 100%,0 100%);transform:translateX(-50%)}
|
| 565 |
+
.mini-balloon.landed{animation:mini-land .3s cubic-bezier(.2,1.7,.4,1)}
|
| 566 |
+
.miss-flight{position:fixed;z-index:30;margin:0;border:2px solid #2e782a;border-radius:50% 50% 48% 52%/46% 46% 54% 54%;background:radial-gradient(ellipse at 29% 22%,rgb(255 255 255/.88) 0 5%,rgb(255 255 255/.35) 6% 13%,transparent 14%),radial-gradient(ellipse at 36% 29%,#9ce98a 0%,#69c956 30%,#45a83d 66%,#287823 100%);box-shadow:inset -14px -18px 30px rgb(15 76 17/.3),0 14px 24px rgb(37 90 42/.2);pointer-events:none}
|
| 567 |
+
.card.bubblemode .prompt.missed{visibility:hidden}
|
| 568 |
+
.bubble-hint{position:absolute;top:84px;left:16px;z-index:3;min-width:150px;max-width:190px;padding:10px 13px;border-radius:12px;background:rgb(255 255 255/.94);color:#174f18;box-shadow:0 4px 14px rgb(30 91 36/.18);font:700 14px/1.35 var(--f-body);animation:hint-in .25s ease-out both}
|
| 569 |
+
.bubble-hint[hidden]{display:none}
|
| 570 |
+
.bubble-hint small{display:block;color:#527254;font-size:11px}
|
| 571 |
+
.bubble-hint .binyan{display:block;margin-top:2px}
|
| 572 |
+
.bubble-hint .gizra{display:block;margin-top:3px;color:#103f13;font:800 23px/1.35 var(--f-display);text-shadow:0 1px 0 #fff}
|
| 573 |
+
.bubble-hint .past{display:block;margin-top:9px;padding-top:7px;border-top:1px solid #c9ddc5}
|
| 574 |
+
.bubble-hint .past[hidden]{display:none}
|
| 575 |
+
.bubble-hint .past b{display:block;margin-top:2px;color:#103f13;font:800 25px/1.2 var(--f-display);direction:rtl}
|
| 576 |
+
.bubble-hint .past em{display:block;margin-top:2px;color:#527254;font:700 17px/1.2 sans-serif;font-style:normal;direction:rtl}
|
| 577 |
.card.bubblemode .task{font-weight:700;color:var(--olive)}
|
| 578 |
.card.bubblemode .donehint,.card.bubblemode .progress{position:relative;z-index:2}
|
| 579 |
+
.card.bubblemode>:not(.prompt):not(.bubble-score):not(.bubble-misses):not(.bubble-hint){display:none!important}
|
| 580 |
body.bubble-game #wrap>header,body.bubble-game #practice>.roundbar{display:none}
|
| 581 |
#gameBack{display:none}
|
| 582 |
body.bubble-game #gameBack{display:flex;position:fixed;top:max(12px,env(safe-area-inset-top));right:12px;z-index:12;align-items:center;gap:6px;border:2px solid #111;border-radius:999px;background:#63bd4d;color:#111;padding:9px 14px;font:800 15px/1 var(--f-body);cursor:pointer;box-shadow:0 3px 0 #111}
|
| 583 |
body.bubble-game #gameBack:active{transform:translateY(2px);box-shadow:0 1px 0 #111}
|
| 584 |
+
.card.bubblemode .prompt.burst{animation:verb-burst .28s ease-out forwards}
|
| 585 |
.card.bubblemode .prompt.burst::before{animation:none;opacity:0}
|
| 586 |
+
.card.bubblemode .prompt.burst::after{left:50%;top:50%;width:11px;height:11px;border-radius:50% 10% 55% 20%;background:#45a83d;clip-path:none;filter:none;box-shadow:0 -76px 0 #9ce98a,54px -54px 0 #348e30,76px 0 0 #72d261,54px 54px 0 #287823,0 76px 0 #8cdd79,-54px 54px 0 #3b9d35,-76px 0 0 #65c654,-54px -54px 0 #2e842a;animation:verb-splash .32s ease-out forwards}
|
| 587 |
+
@keyframes verb-rise{0%{transform:translateY(78px) rotate(-2deg) scale(.88)}45%{transform:translateY(5px) rotate(2deg) scale(.96)}100%{transform:translateY(-82px) rotate(-1deg) scale(1.04)}}
|
| 588 |
@keyframes verb-time{from{clip-path:inset(0)}to{clip-path:inset(100% 0 0 0)}}
|
| 589 |
+
@keyframes verb-burst{0%{transform:scale(1);opacity:1}35%{transform:scale(1.12,.9);opacity:1}58%{transform:scale(.82,1.18);opacity:.95}100%{transform:scale(1.7);opacity:0}}
|
| 590 |
+
@keyframes verb-splash{0%{transform:translate(-50%,-50%) scale(.15);opacity:0}35%{opacity:1}100%{transform:translate(-50%,-50%) scale(1.65);opacity:0}}
|
| 591 |
+
@keyframes score-pop{0%{transform:scale(1)}45%{transform:scale(1.55);color:#2d9b31}100%{transform:scale(1)}}
|
| 592 |
+
@keyframes grade-pop{0%{transform:translateX(-50%) scale(.25) rotate(-8deg);opacity:0}65%{transform:translateX(-50%) scale(1.18) rotate(3deg);opacity:1}100%{transform:translateX(-50%) scale(1) rotate(0)}}
|
| 593 |
+
@keyframes hint-in{from{transform:translateY(-6px);opacity:0}to{transform:none;opacity:1}}
|
| 594 |
+
@keyframes mini-land{0%{transform:scale(.4)}65%{transform:scale(1.35)}100%{transform:scale(1)}}
|
| 595 |
+
@media (prefers-reduced-motion:reduce){.card.bubblemode .prompt{animation:none}.card.bubblemode .prompt.burst{opacity:0}.card.bubblemode .prompt.burst::after{animation:none;opacity:0}}
|
| 596 |
/* Without a microphone ("תרגול שקט ללא ציון"): a Hebrew sentence is answered by hand instead of said, built from its
|
| 597 |
Arabic words, tapped in order out of a bank that holds a few words too many. */
|
| 598 |
body.quiet :is(#mic,#playMine,#driveBtn,.phone-btn),body.driving :is(#quietBtn,#heBtn,.miclab,.phone-btn){display:none}
|
|
|
|
| 657 |
|
| 658 |
<div id="today" hidden></div>
|
| 659 |
<section id="vids" aria-live="polite"></section>
|
| 660 |
+
<nav id="nav" aria-label="ניווט"><button data-view="">מסלול</button><button data-view="games" hidden>משחקים</button><button data-view="library">ספריה דיגיטלית</button><button data-view="refer">חבר מביא חבר</button></nav>
|
| 661 |
<nav class="path" id="path" aria-label="מסלול הלימוד"></nav>
|
| 662 |
<button id="toNow" hidden></button>
|
| 663 |
|
|
|
|
| 676 |
<div id="envWarn" class="warn" hidden></div>
|
| 677 |
|
| 678 |
<main class="card" id="card" aria-live="polite">
|
| 679 |
+
<div class="bubble-score" id="bubbleScore" hidden><span>ניקוד<small id="bubbleCount"></small></span><b id="bubblePoints">0</b></div>
|
| 680 |
+
<div class="bubble-misses" id="bubbleMisses" hidden aria-label="בלונים שלא התפוצצו"></div>
|
| 681 |
+
<div class="bubble-hint" id="bubbleHint" hidden><small>רמז</small><span class="binyan" id="bubbleBinyan"></span><strong class="gizra" id="bubbleGizra"></strong><span class="past" id="bubblePast" hidden><small>עבר · הוא</small><b id="bubblePastText"></b><em id="bubblePastAr" lang="ar"></em></span></div>
|
| 682 |
<div class="meta"><span id="counter"></span></div>
|
| 683 |
<div class="progress" id="progress" hidden><i id="progressBar"></i></div>
|
| 684 |
<div class="donehint" id="doneHint" hidden></div>
|
|
|
|
| 711 |
<div class="verdict"><span class="score" id="score"></span><span class="pill" id="pill"></span><div class="words" id="words"></div></div>
|
| 712 |
<p class="sub" id="whyHint" hidden></p>
|
| 713 |
<ul class="tips" id="tips"></ul>
|
| 714 |
+
<div class="flag-box" id="flagBox" hidden>
|
| 715 |
+
<input id="flagNote" maxlength="500" placeholder="מה קרה? (לא חובה)" aria-label="הערה לדיווח">
|
| 716 |
+
<button class="btn" id="flagBtn" title="ההקלטה, הציון ומה שהמודל שמע נשמרים למורה">🚩 אמרתי נכון, המערכת טעתה</button>
|
| 717 |
+
<p class="sub" id="flagMsg" role="status"></p>
|
| 718 |
+
</div>
|
| 719 |
</section>
|
| 720 |
|
| 721 |
<div class="row" id="varRow" hidden>
|
|
|
|
| 739 |
<div class="modes" id="mModes" role="tablist" aria-label="ניהול" hidden><button role="tab" data-mode="classes">כיתות<small>פתיחה, עריכה ומחיקה</small></button><button role="tab" data-mode="students">תלמידים<small>ההתקדמות בכל כיתה</small></button><button role="tab" data-mode="content">תוכן<small>נושאים, סרטונים וטקסטים</small></button></div>
|
| 740 |
<div id="mClasses"></div>
|
| 741 |
<div id="mContent"></div>
|
| 742 |
+
<div class="card hard" id="mTutors" hidden></div>
|
| 743 |
<div class="tabs" id="mTabs" role="tablist" aria-label="כיתות" hidden></div>
|
| 744 |
<div class="card" id="mHead" hidden></div>
|
| 745 |
<div class="card hard" id="mLessons" hidden></div>
|
|
|
|
| 832 |
<label>הקראת המשפט בעברית<input type="checkbox" id="readHe"></label>
|
| 833 |
</div>
|
| 834 |
</dialog>
|
| 835 |
+
<dialog id="verbDlg" class="verb-dlg" aria-labelledby="verbTitle">
|
| 836 |
+
<div class="verb-shell">
|
| 837 |
+
<div class="verb-head"><h2 id="verbTitle">פועל יוצא</h2><button class="btn" id="verbClose">סגירה</button></div>
|
| 838 |
+
<div class="verb-stats"><span id="verbProgress">מוכנים?</span><span id="verbStreak">רצף 0 🔥</span></div>
|
| 839 |
+
<div class="verb-track"><i id="verbBar"></i></div>
|
| 840 |
+
<div class="verb-menu" id="verbMenu">
|
| 841 |
+
<button class="verb-path" data-path="learn">ללמוד פעלים חדשים<small>זיהוי והתאמת גופים, בקצב נוח</small></button>
|
| 842 |
+
<button class="verb-path" data-path="daily">אימון הפעלים היומי<small>שליפה מהירה וחזרה על מה שכבר נלמד</small></button>
|
| 843 |
+
<div class="verb-levels" id="verbLevels"></div>
|
| 844 |
+
</div>
|
| 845 |
+
<div class="verb-board" id="verbBoard" hidden></div>
|
| 846 |
+
<div class="verb-feedback" id="verbFeedback" role="status"></div>
|
| 847 |
+
</div>
|
| 848 |
+
</dialog>
|
| 849 |
<dialog id="phoneDlg" aria-labelledby="phoneTitle">
|
| 850 |
<div class="dlg-head"><h2 id="phoneTitle">ניתוח פונמות<small>הרצף הצפוי מול הפענוח החופשי של המודל</small></h2><button class="btn" id="phoneClose">סגירה</button></div>
|
| 851 |
<p class="phone-note">זהו פירוש המודל להקלטה, ולא תעתיק פונטי מוסמך. תנועות קרובות ואורך תנועה מסומנים כהתאמה מקורבת.</p>
|
|
|
|
| 854 |
<section id="trackBox"><h3 class="heatmap-title">מיקום הפונמות בזמן</h3><div class="phone-track-wrap"><canvas id="phoneTrack" role="img" aria-label="רצף הפונמות הצפוי והמזוהה לאורך זמן"></canvas></div></section>
|
| 855 |
<section id="heatmapBox"><h3 class="heatmap-title">הסתברות פונמות לאורך ההקלטה</h3><div class="heatmap-wrap"><canvas id="phoneHeatmap" role="img" aria-label="מפת חום של הסתברויות הפונמות לאורך ההקלטה"></canvas></div><div class="heatmap-scale"><span>0%</span><i></i><span>100%</span><span>· ★ פונמה צפויה</span></div></section>
|
| 856 |
</dialog>
|
| 857 |
+
<dialog id="flagDlg" aria-labelledby="flagTitle">
|
| 858 |
+
<div class="dlg-head"><h2 id="flagTitle">🚩 הדיווח נשמר<small>זה מה שהמורה יראה על ההקלטה הזו</small></h2><button class="btn" id="flagClose">סגירה</button></div>
|
| 859 |
+
<dl class="flag-facts" id="flagFacts"></dl>
|
| 860 |
+
</dialog>
|
| 861 |
<div id="whyTip" role="tooltip" hidden></div>
|
| 862 |
<button id="logoutBtn" hidden>יציאה</button>
|
| 863 |
|
|
|
|
| 882 |
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
|
| 883 |
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;
|
| 884 |
let myAudioUrl=null;
|
| 885 |
+
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}
|
| 886 |
const phraseOf=id=>PHRASES.find(p=>p.id===id); // by id: the list skips the phrases that have no tab
|
| 887 |
const categoryOf=id=>CATS.find(c=>c.id===id)||GAMES.find(g=>g.id===id);
|
| 888 |
|
|
|
|
| 977 |
The library: videos that are not on the path, the same ones for every level and class. */
|
| 978 |
const dailyVideos=()=>{ const d=today(), seen=new Set(); return (FREE?TEACHER_DAILIES:(MY_CLASS?[MY_CLASS]:MY_CLASSES).flatMap(k=>k.dailies||[])).filter(v=>v.date<=d&&!seen.has(v.id)&&seen.add(v.id)).sort((a,b)=>b.date.localeCompare(a.date)); };
|
| 979 |
const libVideos=()=>LIBRARY;
|
| 980 |
+
const VERB_GAME_VISIBLE=false; // "פועל יוצא" is still under development; flip to true to publish it again.
|
| 981 |
function drawNav(){ // the tabs, and the screen of videos when one is on show
|
| 982 |
const view=document.body.dataset.view||"", box=$("vids"), d=today();
|
| 983 |
for(const b of $("nav").children){
|
|
|
|
| 993 |
if(view==="games"){
|
| 994 |
const games=GAMES.filter(game=>!game.hidden);
|
| 995 |
box.append(mark("","משחקים","h2"));
|
| 996 |
+
if(VERB_GAME_VISIBLE){
|
| 997 |
+
const switcher=mark("now","","button");
|
| 998 |
+
switcher.append(mark("","↻","i"),mark("","פועל יוצא","b"),mark("","מהבנה לשליפה מהירה של הטיית הפועל","small"));
|
| 999 |
+
switcher.onclick=openVerbGame; box.append(switcher);
|
| 1000 |
+
}
|
| 1001 |
if(!games.length) box.append(mark("","המשחקים הראשונים יגיעו בקרוב.","p"));
|
| 1002 |
for(const game of games){
|
| 1003 |
const b=mark("now","","button"), done=PHRASES.filter(p=>p.cat===game.id&&best[p.id]!=null).length;
|
|
|
|
| 1012 |
else box.append(mark("",was.length?"להיום אין סרטון חדש. אפשר לחזור לסרטונים הקודמים.":"עוד אין סרטונים יומיים. כשנקבע לסרטון תאריך (בעריכת הכיתה), הוא מופיע כאן מאותו יום.","p"));
|
| 1013 |
if(was.length) box.append(mark("","הסרטונים הקודמים","h3"));
|
| 1014 |
for(const v of was) row(v,dailyWatched,"ihki.dailyWatched",dayWord(v.date));
|
| 1015 |
+
}else if(view==="refer"){
|
| 1016 |
+
const page=mark("refer","","section");
|
| 1017 |
+
page.innerHTML=`
|
| 1018 |
+
<header><h2>חבר מביא חבר 🧡</h2><p>כולם מרוויחים, ויש לכם שותף או שותפה לדבר איתם בערבית 💬</p></header>
|
| 1019 |
+
<div class="refer-rewards">
|
| 1020 |
+
<div class="refer-reward"><b>מה אתם מקבלים?</b><strong>200 ₪ הנחה</strong> על הקורס הבא<br>או גיפט קארד בשווי <strong>150 ₪</strong> — לבחירתכם</div>
|
| 1021 |
+
<div class="refer-reward"><b>מה החבר/ה מקבלים?</b><strong>100 ₪ הנחה</strong> על ההצטרפות</div>
|
| 1022 |
+
</div>
|
| 1023 |
+
<p class="refer-copy">שלחו למרב ב־WhatsApp את שם החבר או החברה שאתם מביאים, והיא תדאג לכל השאר.</p>
|
| 1024 |
+
<div class="refer-actions">
|
| 1025 |
+
<a href="https://wa.me/972549898292" target="_blank" rel="noopener">שליחת הודעה למרב</a>
|
| 1026 |
+
<a id="referShare" href="#">שליחת ההודעה לחבר/ה</a>
|
| 1027 |
+
<button id="referCopy" type="button">העתקת ההודעה</button>
|
| 1028 |
+
</div>
|
| 1029 |
+
<h3>הודעה שאפשר להעביר ⬇️</h3>
|
| 1030 |
+
<p class="refer-message">היי 👋
|
| 1031 |
+
|
| 1032 |
+
אני בקורס ערבית מדוברת של אַהְלַא וּסַהְלַא, וזה פשוט עובד. הערבית כבר יוצאת לי מהפה 😊
|
| 1033 |
+
שיעור אחד בשבוע של שעה וחצי (בזום) ועוד תרגול (בזום, מהבית או מכל מקום
|
| 1034 |
+
|
| 1035 |
+
🎁 בגלל שהגעתם דרכי, מגיעה לכם 100 ₪ הנחה על ההצטרפות!
|
| 1036 |
+
|
| 1037 |
+
מה עושים?
|
| 1038 |
+
שלחו וואטסאפ למרב וכתבו לה שאני שלחתי אותך ההודעה 👇
|
| 1039 |
+
📲 054-989-8292
|
| 1040 |
+
|
| 1041 |
+
⏳ ההטבה לזמן מוגבל
|
| 1042 |
+
יַאללה, בואו נדבר ערבית ביחד 🧡</p>
|
| 1043 |
+
<p class="refer-terms">* המבצע בתוקף מעכשיו ועד 1.1.27, ואינו חל על אנשים שכבר הגיעו דרככם — ועליהם אנו מודים לכם!<br>* כדי ליהנות מההטבה, יש לעדכן אותנו בשם התלמיד/ה שהגיע/ה דרככם עד שבוע לאחר ההרשמה.</p>`;
|
| 1044 |
+
box.append(page);
|
| 1045 |
+
const shareText=`היי 👋\n\nאני בקורס ערבית מדוברת של אַהְלַא וּסַהְלַא, וזה פשוט עובד. הערבית כבר יוצאת לי מהפה 😊\nשיעור אחד בשבוע של שעה וחצי (בזום) ועוד תרגול (בזום, מהבית או מכל מקום\n\n🎁 בגלל שהגעתם דרכי, מגיעה לכם 100 ₪ הנחה על ההצטרפות!\n\nמה עושים?\nשלחו וואטסאפ למרב וכתבו לה שאני שלחתי אותך ההודעה 👇\n📲 054-989-8292\n\n⏳ ההטבה לזמן מוגבל\nיַאללה, בואו נדבר ערבית ביחד 🧡`;
|
| 1046 |
+
$("referShare").href=`https://wa.me/?text=${encodeURIComponent(shareText)}`;
|
| 1047 |
+
$("referCopy").onclick=async e=>{
|
| 1048 |
+
const button=e.currentTarget, copyFallback=()=>{
|
| 1049 |
+
const area=document.createElement("textarea"); area.value=shareText; area.style.position="fixed"; area.style.opacity="0";
|
| 1050 |
+
document.body.append(area); area.select(); const copied=document.execCommand("copy"); area.remove();
|
| 1051 |
+
if(!copied) throw new Error("copy failed");
|
| 1052 |
+
};
|
| 1053 |
+
try{
|
| 1054 |
+
if(navigator.clipboard) await navigator.clipboard.writeText(shareText); else copyFallback();
|
| 1055 |
+
button.textContent="ההודעה הועתקה ✓";
|
| 1056 |
+
}catch{ button.textContent="לא הצלחנו להעתיק"; }
|
| 1057 |
+
setTimeout(()=>button.textContent="העתקת ההודעה",2200);
|
| 1058 |
+
};
|
| 1059 |
}else{
|
| 1060 |
box.append(mark("","ספריה דיגיטלית","h2"));
|
| 1061 |
if(!libVideos().length) box.append(mark("","עוד אין סרטונים בספריה.","p"));
|
|
|
|
| 1345 |
// left, it is the whole topic, and a practised sentence shows its best score (see show).
|
| 1346 |
// `here` is the topic's sentence on the card: not always the round's, because going back passes through the practised ones.
|
| 1347 |
let ordered=false, topic=[], here=null, showDone=store.get("ihki.showDone",false);
|
| 1348 |
+
const BUBBLE_MS=12000, BUBBLE_HINT_MS=3000, BUBBLE_PAST_MS=6000, BUBBLE_ROUND=10;
|
| 1349 |
+
let bubbleTimer=null, bubbleHintTimer=null, bubblePastTimer=null, bubbleDeadline=0, bubbleFor=null, bubbleResolving=false, bubbleHintShown=false, bubblePastShown=false;
|
| 1350 |
+
let bubbleGame={answered:0,correct:0,total:0};
|
| 1351 |
const bubbleCat=()=>!daily&&(categoryOf(cat)||{}).bubble;
|
| 1352 |
+
function drawBubbleScore(tick=false){
|
| 1353 |
+
const box=$("bubbleScore");
|
| 1354 |
+
$("bubblePoints").textContent=bubbleGame.correct;
|
| 1355 |
+
$("bubbleCount").textContent=`${bubbleGame.answered} מתוך ${bubbleGame.total}`;
|
| 1356 |
+
if(tick){ box.classList.remove("tick"); void box.offsetWidth; box.classList.add("tick"); }
|
| 1357 |
+
}
|
| 1358 |
+
function countBubble(correct){
|
| 1359 |
+
bubbleGame.answered++; if(correct) bubbleGame.correct++;
|
| 1360 |
+
drawBubbleScore(correct);
|
| 1361 |
+
}
|
| 1362 |
+
async function keepMissedBalloon(){
|
| 1363 |
+
const source=$("prompt"), shelf=$("bubbleMisses"), from=source.getBoundingClientRect(), mini=mark("mini-balloon","");
|
| 1364 |
+
shelf.append(mini); const to=mini.getBoundingClientRect(); mini.style.visibility="hidden"; source.classList.add("missed");
|
| 1365 |
+
const ghost=mark("miss-flight",""); Object.assign(ghost.style,{left:from.left+"px",top:from.top+"px",width:from.width+"px",height:from.height+"px"}); document.body.append(ghost);
|
| 1366 |
+
if(!matchMedia("(prefers-reduced-motion:reduce)").matches){
|
| 1367 |
+
const dx=to.left+to.width/2-(from.left+from.width/2), dy=to.top+to.height/2-(from.top+from.height/2), scale=to.width/from.width;
|
| 1368 |
+
try{ await ghost.animate([{transform:"translate(0,0) scale(1)"},{transform:`translate(${dx}px,${dy}px) scale(${scale})`}],{duration:360,easing:"cubic-bezier(.4,0,.2,1)",fill:"forwards"}).finished; }catch{}
|
| 1369 |
+
}
|
| 1370 |
+
ghost.remove(); mini.style.visibility=""; mini.classList.add("landed");
|
| 1371 |
+
}
|
| 1372 |
+
function showBubbleHint(){
|
| 1373 |
+
if(!bubbleCat()||home||bubbleHintShown) return;
|
| 1374 |
+
const p=phraseOf(cur.id); if(!p.binyan&&!p.gizra) return;
|
| 1375 |
+
bubbleHintShown=true; $("bubbleBinyan").textContent=p.binyan||""; $("bubbleGizra").textContent=p.gizra||"";
|
| 1376 |
+
$("bubbleHint").hidden=false;
|
| 1377 |
+
}
|
| 1378 |
+
function showBubblePast(){
|
| 1379 |
+
if(!bubbleCat()||home||bubblePastShown) return;
|
| 1380 |
+
showBubbleHint(); bubblePastShown=true; const p=phraseOf(cur.id);
|
| 1381 |
+
$("bubblePastText").textContent=(p.tr||"").split(",",1)[0].trim();
|
| 1382 |
+
$("bubblePastAr").textContent=(p.ar||"").split("،",1)[0].trim(); $("bubblePast").hidden=false;
|
| 1383 |
+
}
|
| 1384 |
+
function pauseBubble(){
|
| 1385 |
+
if(bubbleTimer){ clearTimeout(bubbleTimer); bubbleTimer=null; }
|
| 1386 |
+
if(bubbleHintTimer){ clearTimeout(bubbleHintTimer); bubbleHintTimer=null; }
|
| 1387 |
+
if(bubblePastTimer){ clearTimeout(bubblePastTimer); bubblePastTimer=null; }
|
| 1388 |
+
}
|
| 1389 |
+
function stopBubble(){ pauseBubble(); bubbleDeadline=0; bubbleFor=null; bubbleResolving=false; bubbleHintShown=false; bubblePastShown=false; }
|
| 1390 |
function armBubble(){
|
| 1391 |
pauseBubble();
|
| 1392 |
if(!bubbleCat()||home) return;
|
| 1393 |
+
if(bubbleFor!==cur.id){
|
| 1394 |
+
bubbleFor=cur.id; bubbleDeadline=Date.now()+BUBBLE_MS; bubbleResolving=false; bubbleHintShown=false; bubblePastShown=false;
|
| 1395 |
+
$("bubbleHint").hidden=true; $("bubblePast").hidden=true;
|
| 1396 |
+
}
|
| 1397 |
const left=Math.max(0,bubbleDeadline-Date.now());
|
| 1398 |
+
if(!bubbleHintShown) bubbleHintTimer=setTimeout(()=>{ bubbleHintTimer=null; showBubbleHint(); },Math.max(0,left-(BUBBLE_MS-BUBBLE_HINT_MS)));
|
| 1399 |
+
if(!bubblePastShown) bubblePastTimer=setTimeout(()=>{ bubblePastTimer=null; showBubblePast(); },Math.max(0,left-(BUBBLE_MS-BUBBLE_PAST_MS)));
|
| 1400 |
bubbleTimer=setTimeout(()=>{
|
| 1401 |
bubbleTimer=null;
|
| 1402 |
if(home||!bubbleCat()||bubbleResolving) return;
|
|
|
|
| 1407 |
function setRound(){
|
| 1408 |
quizOff();
|
| 1409 |
if(daily){ ordered=true; topic=order=[...daily]; pos=0; marks(); return; } // the session's sentences, in its own order
|
| 1410 |
+
let list=PHRASES.filter(p=>p.cat===cat&&p.listed!==false);
|
| 1411 |
+
if(bubbleCat()){
|
| 1412 |
+
const ready=LESSONS.filter(l=>!l.soon), reached=FREE?ALL_LESSONS.filter(l=>!l.soon).at(-1):ready.find(l=>!tally(lessonList(l)).over)||ready.at(-1);
|
| 1413 |
+
const rank=reached?ALL_LESSONS.findIndex(l=>l.id===reached.id):-1;
|
| 1414 |
+
list=list.filter(p=>!p.unlock||ALL_LESSONS.findIndex(l=>l.id===p.unlock)<=rank);
|
| 1415 |
+
ordered=false; topic=order=shuffle(list).slice(0,BUBBLE_ROUND).map(p=>p.id); pos=0;
|
| 1416 |
+
bubbleGame={answered:0,correct:0,total:order.length}; $("bubbleMisses").replaceChildren(); drawBubbleScore(); marks(); return;
|
| 1417 |
+
}
|
| 1418 |
ordered=list.length>0&&list.every(p=>p.seq!=null);
|
| 1419 |
topic=(ordered?list.sort((a,b)=>a.seq-b.seq):shuffle(list)).map(p=>p.id);
|
| 1420 |
const todo=topic.filter(id=>best[id]==null&&!(quiet&&silent[id])), all=showDone||!todo.length, box=$("showDone");
|
|
|
|
| 1770 |
const c=categoryOf(daily?cur.cat:cat), mine=topic.includes(cur.id); // a topic or game may name its items and its own task
|
| 1771 |
$("card").classList.toggle("bubblemode",!!c.bubble);
|
| 1772 |
document.body.classList.toggle("bubble-game",!!c.bubble);
|
| 1773 |
+
$("bubbleScore").hidden=!c.bubble; $("bubbleMisses").hidden=!c.bubble; $("bubbleHint").hidden=true; if(c.bubble) drawBubbleScore();
|
| 1774 |
+
$("prompt").classList.remove("burst","missed");
|
| 1775 |
if(c.bubble){ $("prompt").style.animation="none"; void $("prompt").offsetWidth; $("prompt").style.animation=""; }
|
| 1776 |
heStop(); $("heCheck").hidden=true; micZone.classList.toggle("two",heOk&&!!cur.read&&!story); // a phrase to read can be answered in Hebrew too
|
| 1777 |
$("task").textContent=cur.read?heOk?HE_TASK:"קראו בקול ותרגמו לעברית":mine&&c.task||"איך אומרים את זה בערבית מדוברת?";
|
|
|
|
| 1993 |
const seconds=(data.duration_ms||0)/1000;
|
| 1994 |
for(const part of [0,.25,.5,.75,1]) c.fillText(seconds?`${(seconds*part).toFixed(1)}s`:Math.round(part*100)+"%",label+part*plot,height-axis/2);
|
| 1995 |
}
|
| 1996 |
+
/* A tutor's flag under the score: the sentence was said right and the system got it wrong. The recording goes back to
|
| 1997 |
+
the server, which scores it again and keeps it with what it made of it (the table `flags`), for the teacher. */
|
| 1998 |
+
$("flagBtn").onclick=async()=>{
|
| 1999 |
+
const rec=lastRec, btn=$("flagBtn"), msg=$("flagMsg");
|
| 2000 |
+
if(!rec) return;
|
| 2001 |
+
btn.disabled=true; msg.textContent="שומר…";
|
| 2002 |
+
try{
|
| 2003 |
+
const fd=new FormData(); fd.append("phrase_id",rec.id); fd.append("audio",rec.blob,"rec"); fd.append("note",$("flagNote").value);
|
| 2004 |
+
const res=await api("/api/flags",{method:"POST",body:fd});
|
| 2005 |
+
if(!res.ok){ const e=await res.json().catch(()=>({})); throw new Error(e.detail||res.status); }
|
| 2006 |
+
const out=await res.json();
|
| 2007 |
+
msg.textContent=out.audio?"נשמר למורה, עם ההקלטה. תודה!":"נשמר למורה, אבל בלי ההקלטה (אין מקום אחסון flags ב-Supabase).";
|
| 2008 |
+
$("flagNote").disabled=true; // one flag for a recording
|
| 2009 |
+
if(out.flag){ drawFlag(out.flag,out.audio); $("flagDlg").showModal(); }
|
| 2010 |
+
}catch(err){ msg.textContent="הדיווח לא נשמר: "+err.message; btn.disabled=false; }
|
| 2011 |
+
};
|
| 2012 |
+
/* What a flag kept, in words: the sentence, what the model heard in its place, each word's score and the sounds it
|
| 2013 |
+
marked down. `f` is the row of `flags` as the server answered it. */
|
| 2014 |
+
function drawFlag(f,audio){
|
| 2015 |
+
const facts=$("flagFacts"), r=f.result; facts.innerHTML="";
|
| 2016 |
+
const fact=(name,...body)=>{ const dd=document.createElement("dd"); dd.append(...body); facts.append(mark("",name,"dt"),dd); return dd; };
|
| 2017 |
+
const tr=text=>{ const s=document.createElement("span"); setTr(s,text||"–"); return s; };
|
| 2018 |
+
const ar=text=>{ const s=mark("ar",text); s.lang="ar"; return s; };
|
| 2019 |
+
const list=items=>{ const ul=document.createElement("ul"); for(const parts of items){ const li=document.createElement("li"); li.append(...parts); ul.append(li); } return ul; };
|
| 2020 |
+
const grade=s=>mark(band(s),Math.round(s),"b");
|
| 2021 |
+
fact("המשפט",f.he);
|
| 2022 |
+
fact("התשובה הנכונה",tr(r.variant.tr)," · ",ar(f.ar));
|
| 2023 |
+
fact("המודל שמע",tr(r.heard_tr));
|
| 2024 |
+
fact("הציון",grade(f.score),f.unrelated?" · המודל חשב שנאמר משפט אחר":" מתוך 100");
|
| 2025 |
+
fact("מילה אחר מילה",list(r.words.map(w=>[tr(w.tr),w.heard_tr&&w.heard_tr!==w.tr?" ← נשמע ":"",w.heard_tr&&w.heard_tr!==w.tr?tr(w.heard_tr):""," · ",grade(w.score)])));
|
| 2026 |
+
// every sound the scorer marked down, weakest first, by its name and what took its place
|
| 2027 |
+
const low=r.words.flatMap(w=>(w.phonemes||[]).filter(p=>p.score<75).map(p=>({...p,word:w.tr}))).sort((a,b)=>a.score-b.score);
|
| 2028 |
+
fact("הגאים שהורדו",low.length?list(low.map(p=>[mark("ipa",p.ipa)," במילה ",tr(p.word),
|
| 2029 |
+
p.heard==="_"?" – לא נשמע":p.heard?" – נשמע כמו ":"",p.heard&&p.heard!=="_"?mark("ipa",p.heard):""," · ",grade(p.score)])):"אף הגה לא ירד מתחת ל-75");
|
| 2030 |
+
if(r.tips.length) fact("מה נאמר לתלמיד",list(r.tips.map(t=>[t.title+": "+t.text])));
|
| 2031 |
+
fact("פונמות צפויות",mark("ipa",f.ipa)).className="ipa";
|
| 2032 |
+
fact("פונמות שנשמעו",mark("ipa",f.heard_ipa||"–")).className="ipa";
|
| 2033 |
+
if(f.note) fact("ההערה שלך",f.note);
|
| 2034 |
+
fact("ההקלטה",audio?"נשמרה עם הדיווח":"לא נשמרה (אין מקום אחסון flags ב-Supabase)");
|
| 2035 |
+
fact("המודל",mark("ipa",f.model+(f.version?" · "+f.version:""))).className="ipa";
|
| 2036 |
+
}
|
| 2037 |
+
$("flagClose").onclick=()=>$("flagDlg").close();
|
| 2038 |
$("phoneBtn").onclick=()=>{ if(lastPhone){ drawPhones(lastPhone); $("phoneDlg").showModal(); } };
|
| 2039 |
$("phoneClose").onclick=()=>$("phoneDlg").close();
|
| 2040 |
|
|
|
|
| 2044 |
if(FREE&&!$("card").classList.contains("storymode")){
|
| 2045 |
lastPhone=r; $("phoneBtn").hidden=false; $("phoneBtn").disabled=false;
|
| 2046 |
}
|
| 2047 |
+
$("flagBox").hidden=!(TUTOR&&lastRec&&lastRec.id===cur.id);
|
| 2048 |
+
$("flagBtn").disabled=$("flagNote").disabled=false; $("flagNote").value=$("flagMsg").textContent="";
|
| 2049 |
$("status").textContent=r.score<30?"רוצים לנסות שוב? לחצו על המיקרופון":"לחצו כדי לנסות שוב";
|
| 2050 |
$("nextBtn").classList.add("primary");
|
| 2051 |
$("score").textContent=r.score;
|
|
|
|
| 2113 |
bubbleResolving=true;
|
| 2114 |
if(!expired){
|
| 2115 |
const old=$("prompt").querySelector(".bubble-grade"); if(old) old.remove();
|
| 2116 |
+
const score=Math.round(r.score), band=score>=85?"good":score>=60?"mid":"bad";
|
| 2117 |
+
$("prompt").append(mark(`bubble-grade ${band}`,`${score} נק׳`));
|
| 2118 |
}
|
| 2119 |
if(correct){
|
| 2120 |
+
countBubble(true);
|
| 2121 |
stopBubble();
|
| 2122 |
$("prompt").classList.add("burst");
|
| 2123 |
+
await pause(290);
|
| 2124 |
}else{
|
| 2125 |
if(!expired&&Date.now()<bubbleDeadline){
|
| 2126 |
bubbleResolving=false;
|
|
|
|
| 2128 |
autoRec=true; autoRecord();
|
| 2129 |
return;
|
| 2130 |
}
|
| 2131 |
+
countBubble(false);
|
| 2132 |
+
await keepMissedBalloon();
|
| 2133 |
+
if(cur.id!==id||home) return;
|
| 2134 |
const a=await answerAudio(id);
|
| 2135 |
if(cur.id!==id||home) return;
|
| 2136 |
if(a) await playUrl(a.url,true); else await speakLocal(cur.ar,"ar");
|
| 2137 |
+
await pause(80);
|
| 2138 |
}
|
| 2139 |
bubbleResolving=false;
|
| 2140 |
if(cur.id===id&&!home&&bubbleCat()) nextPhrase();
|
|
|
|
| 2216 |
const blob=new Blob(chunks,{type:rec.mimeType||"audio/webm"});
|
| 2217 |
if(myAudioUrl) URL.revokeObjectURL(myAudioUrl);
|
| 2218 |
myAudioUrl=URL.createObjectURL(blob); $("playMine").disabled=false;
|
| 2219 |
+
lastRec={id,blob};
|
| 2220 |
mic.disabled=true; $("status").textContent="מנתח…";
|
| 2221 |
try{
|
| 2222 |
const fd=new FormData(); fd.append("phrase_id",id); fd.append("audio",blob,"rec");
|
|
|
|
| 2250 |
if(k<0) roundEnd(); else{ pos=k; show(); }
|
| 2251 |
return;
|
| 2252 |
}
|
| 2253 |
+
if(pos+1>=order.length&&(order!==topic||isStory()||bubbleCat())){ roundEnd(); return; } // a round of unpractised sentences, a game, or a story ended
|
| 2254 |
pos=(pos+1)%order.length; if(pos===0&&!ordered) shuffle(order); show();
|
| 2255 |
};
|
| 2256 |
$("nextBtn").onclick=nextPhrase;
|
|
|
|
| 2450 |
if(!["classes","students","content"].includes(mMode)) mMode=classes.length?"students":"classes";
|
| 2451 |
$("mModes").hidden=false; $("manage").classList.toggle("classes",mMode==="classes"); $("manage").classList.toggle("content",mMode==="content");
|
| 2452 |
for(const b of $("mModes").children) b.setAttribute("aria-selected",b.dataset.mode===mMode);
|
| 2453 |
+
drawClasses(classes); drawContent(); drawTutors(); drawTabs(classes); drawHead(klass,students); drawLessons(students,listed); drawRoster(klass,students,listed);
|
| 2454 |
const one=students.find(s=>s.email===shownStudent); // a student who left the class has no screen in it
|
| 2455 |
if(!one) shownStudent="";
|
| 2456 |
$("manage").classList.toggle("student",!!one); $("mStudent").innerHTML="";
|
|
|
|
| 2637 |
const to=e.state&&e.state.student||""; if(to===shownStudent||!CLASS) return;
|
| 2638 |
shownStudent=to; drawManage(); scrollTo(0,to?0:classScroll);
|
| 2639 |
});
|
| 2640 |
+
/* Above the classes' tabs: every student of every class, each with the tutor's rank to tick. The rank is the student's
|
| 2641 |
+
whatever class they are in: one who has it gets the flag under each score, and 🚩 beside their name in the lists. */
|
| 2642 |
+
let tutorsOpen=false;
|
| 2643 |
+
function drawTutors(){
|
| 2644 |
+
const box=$("mTutors"), all=[...CLASS.students].sort((a,b)=>(a.name||a.email).localeCompare(b.name||b.email,"he"));
|
| 2645 |
+
box.innerHTML=""; box.hidden=!all.length; if(!all.length) return;
|
| 2646 |
+
const sec=part(box), said=mark("note","מי שמסומן רואה דגל 🚩 מתחת לכל ציון, ומדווח כשאמר נכון והמערכת טעתה. הדרגה חלה בכל הכיתות של התלמיד/ה.","p");
|
| 2647 |
+
sec.open=tutorsOpen; sec.ontoggle=()=>{ tutorsOpen=sec.open; };
|
| 2648 |
+
sec.firstChild.append(mark("","🚩 מדווחים על ציונים שגויים"),mark("",`${all.filter(s=>s.tutor).length} מתוך ${all.length} תלמידים`,"small"));
|
| 2649 |
+
sec.append(said);
|
| 2650 |
+
for(const s of all){
|
| 2651 |
+
const row=document.createElement("label"), tick=document.createElement("input"), who=mark("",""), name=mark("",Object.values(s.classes).find(Boolean)||s.name||s.email,"b"), mail=document.createElement("bdi");
|
| 2652 |
+
name.dir="auto"; mail.dir="ltr"; mail.textContent=s.email;
|
| 2653 |
+
const more=mark("","","small"); more.append(mail,[...Object.keys(s.classes).map(c=>" · "+c),s.tutor_fixed?" · נקבע בהגדרות השרת":""].join(""));
|
| 2654 |
+
who.append(name,more);
|
| 2655 |
+
tick.type="checkbox"; tick.checked=!!s.tutor; tick.disabled=!!s.tutor_fixed;
|
| 2656 |
+
tick.onchange=async()=>{
|
| 2657 |
+
const on=tick.checked; tick.disabled=true;
|
| 2658 |
+
try{
|
| 2659 |
+
const res=await api("/api/tutors",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:s.email,tutor:on})});
|
| 2660 |
+
if(!res.ok) throw new Error((await res.json().catch(()=>({}))).detail||res.status);
|
| 2661 |
+
s.tutor=on; drawManage();
|
| 2662 |
+
}catch(err){ tick.checked=!on; tick.disabled=false; said.textContent="הדרגה לא נשמרה: "+err.message; }
|
| 2663 |
+
};
|
| 2664 |
+
row.append(tick,who); sec.append(row);
|
| 2665 |
+
}
|
| 2666 |
+
}
|
| 2667 |
function drawTabs(classes){
|
| 2668 |
const tabs=$("mTabs"); tabs.innerHTML=""; tabs.hidden=!classes.length;
|
| 2669 |
for(const c of classes){
|
|
|
|
| 2758 |
students.sort((a,b)=>(b.last||"").localeCompare(a.last||"")||b.joined-a.joined||a.email.localeCompare(b.email));
|
| 2759 |
for(const s of students){
|
| 2760 |
const row=mark("rrow","","button"), who=mark("who","");
|
| 2761 |
+
const shown=mark("",(s.nick||s.name||s.email)+(s.tutor?" 🚩":""),"b"); shown.dir="auto"; if(s.tutor) shown.title="מדווח/ת על ציונים שגויים"; // an address is cut at its end
|
| 2762 |
who.append(shown,mark("",lastSeen(s)+(s.unmatched?` · ${s.unmatched} לא זוהו`:""),"small"));
|
| 2763 |
who.title=s.email; row.append(who);
|
| 2764 |
for(const col of cols){ const t=col.of(s), c=mark("cell",""); c.append(ratio(t),bar(t.n?t.done/t.n:0)); c.title=`${col.title}: ${col.did} ${t.done} מתוך ${t.n}`+(t.avg!=null?`, ציון ${t.avg}`:""); row.append(c); }
|
|
|
|
| 3019 |
buttons.forEach(b=>b.disabled=false);
|
| 3020 |
};
|
| 3021 |
|
| 3022 |
+
/* "פועל יוצא" (Switch & Speak), Levels 1--5. Linguistic content and grading come from the server;
|
| 3023 |
+
lightweight mastery is kept on this device. */
|
| 3024 |
+
const VERB_ROUND=10, VERB_THRESH={2:.85,3:.90,4:.90,5:.85};
|
| 3025 |
+
let verbMeta=null, verbQuestion=null, verbStarted=0, verbLevel=1, verbPath="learn", verbN=0, verbStreak=0, verbRecent=[];
|
| 3026 |
+
let verbMastery=store.get("ihki.verbMastery",{}), verbSummary=store.get("ihki.verbSummary",{}), verbPairs={}, verbPicked=null;
|
| 3027 |
+
const verbRatio=n=>{const s=verbSummary[n]||{}; return s.attempts?s.correct/s.attempts:0};
|
| 3028 |
+
// FREE is set only from /api/me's server-verified teacher flag. Teachers can inspect every level.
|
| 3029 |
+
const verbUnlocked=n=>FREE||n===1
|
| 3030 |
+
||(n===2&&(verbSummary[1]?.attempts||0)>=10&&verbRatio(1)>=VERB_THRESH[2])
|
| 3031 |
+
||(n===3&&(verbSummary[2]?.attempts||0)>=6&&verbRatio(2)>=VERB_THRESH[3])
|
| 3032 |
+
||(n===4&&(verbSummary[3]?.attempts||0)>=10&&verbRatio(3)>=VERB_THRESH[4]&&(verbSummary[3]?.median_ms||Infinity)<=2000)
|
| 3033 |
+
||(n===5&&(verbSummary[4]?.attempts||0)>=6&&verbRatio(4)>=VERB_THRESH[5]);
|
| 3034 |
+
function drawVerbLevels(){
|
| 3035 |
+
const box=$("verbLevels"); box.replaceChildren();
|
| 3036 |
+
const reason=n=>{
|
| 3037 |
+
const s=verbSummary[n-1]||{}, accuracy=Math.round(verbRatio(n-1)*100), attempts=s.attempts||0;
|
| 3038 |
+
if(n===4) return `${attempts}/10 ניסיונות · ${accuracy}%/90% · ${s.median_ms?`${(s.median_ms/1000).toFixed(1)}/2.0 שנ׳`:"אין עדיין זמן"}`;
|
| 3039 |
+
if(n===5) return `${attempts}/6 תשובות בקול · ${accuracy}%/85%`;
|
| 3040 |
+
return "השלימו תחילה את הרמה הקודמת";
|
| 3041 |
+
};
|
| 3042 |
+
for(const l of verbMeta?.levels||[]){
|
| 3043 |
+
const locked=!verbUnlocked(l.id), b=mark(l.id===verbLevel?"on":"",`${l.id} · ${l.name}`,"button");
|
| 3044 |
+
b.disabled=locked; if(locked){const why=reason(l.id);b.append(mark("",why,"small"));b.title=why;b.setAttribute("aria-label",`${l.name}, נעול: ${why}`)}
|
| 3045 |
+
b.onclick=()=>{verbLevel=l.id; drawVerbLevels(); startVerbRound();}; box.append(b);
|
| 3046 |
+
}
|
| 3047 |
+
}
|
| 3048 |
+
async function openVerbGame(){
|
| 3049 |
+
const dlg=$("verbDlg"); $("verbBoard").hidden=true; $("verbMenu").hidden=false; $("verbFeedback").textContent="";
|
| 3050 |
+
dlg.showModal();
|
| 3051 |
+
if(!verbMeta){ const r=await api("/api/verb-game").catch(()=>null); if(!r||!r.ok){$("verbFeedback").textContent="המשחק לא זמין כרגע.";return} verbMeta=await r.json(); }
|
| 3052 |
+
drawVerbLevels();
|
| 3053 |
+
}
|
| 3054 |
+
$("verbClose").onclick=()=>$("verbDlg").close();
|
| 3055 |
+
$("verbDlg").addEventListener("close",()=>{verbQuestion=null});
|
| 3056 |
+
for(const b of document.querySelectorAll("[data-path]")) b.onclick=()=>{verbPath=b.dataset.path; verbLevel=verbPath==="daily"?[5,4,3,2,1].find(verbUnlocked):(verbUnlocked(2)?2:1); drawVerbLevels(); startVerbRound();};
|
| 3057 |
+
function startVerbRound(){ verbN=0; verbStreak=0; verbRecent=[]; $("verbMenu").hidden=true; $("verbBoard").hidden=false; nextVerb(); }
|
| 3058 |
+
async function nextVerb(){
|
| 3059 |
+
if(verbN>=VERB_ROUND){
|
| 3060 |
+
$("verbBoard").innerHTML=`<div class="verb-cue"><h3>כל הכבוד!</h3><p>סיימתם ${VERB_ROUND} שאלות. הרצף הטוב נשמר להמשך.</p><button class="btn primary" id="verbAgain">סבב נוסף</button></div>`;
|
| 3061 |
+
$("verbAgain").onclick=startVerbRound; $("verbFeedback").textContent=""; return;
|
| 3062 |
+
}
|
| 3063 |
+
$("verbFeedback").className="verb-feedback"; $("verbFeedback").textContent=""; $("verbBoard").innerHTML="טוען…";
|
| 3064 |
+
const payload={level:verbLevel,mastery:verbMastery,recent:verbRecent};
|
| 3065 |
+
const r=await api("/api/verb-game/question",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(payload)}).catch(()=>null);
|
| 3066 |
+
if(!r||!r.ok){$("verbBoard").textContent="לא הצלחנו לטעון שאלה.";return}
|
| 3067 |
+
verbQuestion=await r.json(); verbStarted=performance.now(); verbPairs={}; verbPicked=null;
|
| 3068 |
+
verbRecent.push(verbQuestion.mastery_key); if(verbRecent.length>6) verbRecent.shift();
|
| 3069 |
+
$("verbProgress").textContent=`שאלה ${verbN+1} מתוך ${VERB_ROUND} · רמה ${verbLevel}`; $("verbStreak").textContent=`רצף ${verbStreak} 🔥`; $("verbBar").style.width=`${verbN/VERB_ROUND*100}%`;
|
| 3070 |
+
drawVerbQuestion();
|
| 3071 |
+
}
|
| 3072 |
+
function cue(q){
|
| 3073 |
+
const top=mark("verb-cue","","div"); top.append(mark("",`${q.verb.name} · ${q.tense.name}`,"h3"),mark("ar",q.verb.arabic,"div")); return top;
|
| 3074 |
+
}
|
| 3075 |
+
function drawVerbQuestion(){
|
| 3076 |
+
const q=verbQuestion, board=$("verbBoard"); board.replaceChildren(cue(q));
|
| 3077 |
+
if(q.level>=4){
|
| 3078 |
+
if(q.conversation){const c=mark("verb-conversation","","div"); c.append(mark("ar",q.conversation.arabic,"div"),mark("",q.conversation.transliteration,"div"),mark("",q.conversation.hebrew,"small")); const hear=mark("btn","🔊 השמעת השאלה","button"); hear.onclick=()=>{const u=new SpeechSynthesisUtterance(q.conversation.arabic);u.lang="ar-PS";speechSynthesis.cancel();speechSynthesis.speak(u)}; c.append(hear); board.append(c)}
|
| 3079 |
+
else board.append(mark("verb-pronoun",`הגוף: ${q.pronoun.hebrew} · ${q.pronoun.transliteration}`,"p"));
|
| 3080 |
+
const speak=mark("verb-speak","","div"), mic=mark("verb-mic","🎙","button"), status=mark("","לחצו, אמרו את ההטיה ולחצו שוב לסיום","p"), actions=mark("verb-record-actions","","div"); mic.onclick=()=>verbRecord(mic,status,actions); speak.append(mic,status,actions); board.append(speak); return;
|
| 3081 |
+
}
|
| 3082 |
+
if(q.level===2){
|
| 3083 |
+
const grid=mark("verb-match","","div"), left=mark("","","div"), right=mark("","","div");
|
| 3084 |
+
for(const p of q.pronouns){ const b=mark("",p.hebrew,"button"); b.dataset.id=p.id; b.append(mark("",p.transliteration,"small")); b.onclick=()=>pickVerbPair("pronoun",b); left.append(b); }
|
| 3085 |
+
for(const f of q.forms){ const b=mark("",f.transliteration,"button"); b.dataset.id=f.id; b.append(mark("ar",f.arabic)); b.onclick=()=>pickVerbPair("form",b); right.append(b); }
|
| 3086 |
+
grid.append(left,right); board.append(grid); return;
|
| 3087 |
+
}
|
| 3088 |
+
const pron=mark("verb-pronoun",`הגוף: ${q.pronoun.hebrew} · ${q.pronoun.transliteration}`,"p"), choices=mark("verb-choices","","div"); board.append(pron,choices);
|
| 3089 |
+
for(const c of q.choices){ const b=mark("verb-choice",c.transliteration,"button"); b.append(mark("ar",c.arabic)); b.onclick=()=>submitVerb(c.id,b); choices.append(b); }
|
| 3090 |
+
}
|
| 3091 |
+
function pickVerbPair(kind,b){
|
| 3092 |
+
if(b.classList.contains("done")) return;
|
| 3093 |
+
document.querySelectorAll(`.verb-match button.selected`).forEach(x=>{if((kind==="pronoun")===(x.parentElement===$("verbBoard").querySelector(".verb-match>div:first-child")))x.classList.remove("selected")});
|
| 3094 |
+
b.classList.add("selected"); verbPicked=verbPicked||{}; verbPicked[kind]=b;
|
| 3095 |
+
if(!verbPicked.pronoun||!verbPicked.form) return;
|
| 3096 |
+
verbPairs[verbPicked.pronoun.dataset.id]=verbPicked.form.dataset.id; verbPicked.pronoun.classList.replace("selected","done"); verbPicked.form.classList.replace("selected","done"); verbPicked=null;
|
| 3097 |
+
if(Object.keys(verbPairs).length===verbQuestion.pair_count) submitVerb(verbPairs);
|
| 3098 |
+
}
|
| 3099 |
+
async function submitVerb(answer,button){
|
| 3100 |
+
const q=verbQuestion; if(!q) return; verbQuestion=null;
|
| 3101 |
+
const elapsed=Math.round(performance.now()-verbStarted), r=await api("/api/verb-game/answer",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({question_id:q.question_id,answer,response_ms:elapsed})}).catch(()=>null);
|
| 3102 |
+
if(!r||!r.ok){$("verbFeedback").textContent="התשובה לא נבדקה. נסו שאלה חדשה."; setTimeout(nextVerb,900);return}
|
| 3103 |
+
const result=await r.json(), ok=result.correct, feedback=$("verbFeedback");
|
| 3104 |
+
if(button){button.classList.add(ok?"good":"bad"); if(!ok){const right=$("verbBoard").querySelectorAll(".verb-choice"); q.choices.forEach((c,i)=>{if(c.id===result.correct_choice_id)right[i].classList.add("good")})}}
|
| 3105 |
+
if(q.level===2) for(const [pid,good] of Object.entries(result.pair_results||{})){const p=$("verbBoard").querySelector(`[data-id="${pid}"]`), f=$("verbBoard").querySelector(`[data-id="${verbPairs[pid]}"]`); for(const el of [p,f])if(el)el.classList.add(good?"good":"bad")}
|
| 3106 |
+
feedback.className="verb-feedback "+(ok?"good":"bad"); feedback.textContent=ok?`נכון! ${elapsed<2000?"שליפה מהירה ⚡":""}`:`עוד לא. ${result.explanation||"נסו שוב."}`;
|
| 3107 |
+
verbStreak=ok?verbStreak+1:0; verbN++; $("verbStreak").textContent=`רצף ${verbStreak} 🔥`; $("verbBar").style.width=`${verbN/VERB_ROUND*100}%`;
|
| 3108 |
+
const key=q.mastery_key, m=verbMastery[key]||{attempts:0,correct:0,times:[],streak:0}; m.attempts++; if(ok)m.correct++; m.streak=ok?(m.streak||0)+1:0; m.times=[...(m.times||[]),elapsed].slice(-20); m.median_ms=[...m.times].sort((a,b)=>a-b)[m.times.length>>1]; m.last=new Date().toISOString(); verbMastery[key]=m;
|
| 3109 |
+
const s=verbSummary[q.level]||{attempts:0,correct:0,times:[]}; s.attempts++; if(ok)s.correct++; s.times=[...(s.times||[]),elapsed].slice(-30); s.median_ms=[...s.times].sort((a,b)=>a-b)[s.times.length>>1]; verbSummary[q.level]=s; store.set("ihki.verbMastery",verbMastery); store.set("ihki.verbSummary",verbSummary); drawVerbLevels();
|
| 3110 |
+
setTimeout(nextVerb,ok?650:1500);
|
| 3111 |
+
}
|
| 3112 |
+
let verbRecorder=null, verbChunks=[], verbRecordingUrl=null;
|
| 3113 |
+
async function verbRecord(btn,status,actions){
|
| 3114 |
+
if(verbRecorder?.state==="recording"){verbRecorder.stop();return}
|
| 3115 |
+
if(!navigator.mediaDevices||!window.MediaRecorder){status.textContent="הדפדפן הזה אינו תומך בהקלטה.";return}
|
| 3116 |
+
try{
|
| 3117 |
+
const stream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:true,noiseSuppression:true}}), type=pickType(); verbChunks=[];
|
| 3118 |
+
const rec=verbRecorder=new MediaRecorder(stream,type?{mimeType:type}:{}); rec.ondataavailable=e=>{if(e.data.size)verbChunks.push(e.data)};
|
| 3119 |
+
rec.onstop=async()=>{stream.getTracks().forEach(t=>t.stop());btn.classList.remove("live");btn.disabled=true;status.textContent="בודק…";const blob=new Blob(verbChunks,{type:rec.mimeType||"audio/webm"}); if(verbRecordingUrl)URL.revokeObjectURL(verbRecordingUrl);verbRecordingUrl=URL.createObjectURL(blob);await scoreVerbSpeech(blob,btn,status,actions)};
|
| 3120 |
+
rec.start();btn.classList.add("live");status.textContent="מקשיב… לחצו שוב כשסיימתם";
|
| 3121 |
+
}catch{status.textContent="אין גישה למיקרופון. אשרו גישה בהגדרות הדפדפן."}
|
| 3122 |
+
}
|
| 3123 |
+
async function scoreVerbSpeech(blob,btn,status,actions){
|
| 3124 |
+
const q=verbQuestion, fd=new FormData();fd.append("question_id",q.question_id);fd.append("audio",blob,"answer.webm");const r=await api("/api/verb-game/speech",{method:"POST",body:fd}).catch(()=>null);btn.disabled=false;actions.replaceChildren();
|
| 3125 |
+
const replay=mark("btn","▶ ההקלטה שלי","button");replay.onclick=()=>new Audio(verbRecordingUrl).play();const retry=mark("btn","ניסיון נוסף","button");retry.onclick=()=>{actions.replaceChildren();status.textContent="לחצו והקליטו שוב"};actions.append(replay,retry);
|
| 3126 |
+
if(!r||!r.ok){status.textContent="הבדיקה אינה זמינה כרגע. ההקלטה לא נחשבה כטעות.";return}const result=await r.json(), feedback=$("verbFeedback");feedback.className="verb-feedback "+(result.outcome==="correct"?"good":result.outcome==="uncertain"?"":"bad");feedback.textContent=result.message||"נסו שוב";
|
| 3127 |
+
const answer=mark("verb-answer",result.variant?.tr||"","div");if(result.variant?.ar){answer.append(mark("ar",result.variant.ar));const hear=mark("btn","🔊 תשובה","button");hear.onclick=()=>{const u=new SpeechSynthesisUtterance(result.variant.ar);u.lang="ar-PS";speechSynthesis.cancel();speechSynthesis.speak(u)};actions.append(hear)}actions.before(answer);
|
| 3128 |
+
if(!result.counts_as_attempt)return;
|
| 3129 |
+
const ok=result.outcome==="correct", elapsed=Math.round(performance.now()-verbStarted), key=q.mastery_key,m=verbMastery[key]||{attempts:0,correct:0,times:[],streak:0};m.attempts++;if(ok)m.correct++;m.streak=ok?(m.streak||0)+1:0;m.times=[...(m.times||[]),elapsed].slice(-20);m.median_ms=[...m.times].sort((a,b)=>a-b)[m.times.length>>1];m.last=new Date().toISOString();verbMastery[key]=m;const s=verbSummary[q.level]||{attempts:0,correct:0};s.attempts++;if(ok)s.correct++;verbSummary[q.level]=s;store.set("ihki.verbMastery",verbMastery);store.set("ihki.verbSummary",verbSummary);drawVerbLevels();
|
| 3130 |
+
if(ok){verbQuestion=null;verbStreak++;verbN++;status.textContent="נכון ✓";setTimeout(nextVerb,1100)}
|
| 3131 |
+
}
|
| 3132 |
+
|
| 3133 |
function useLessons(ids){ // the path shows these lessons only (null: every one)
|
| 3134 |
LESSONS=ALL_LESSONS.filter(l=>!ids||ids.includes(l.id)); if(!LESSONS.length) LESSONS=ALL_LESSONS;
|
| 3135 |
CATS=ALL_CATS.filter(c=>LESSONS.some(l=>l.id===c.lesson)); // none when every lesson of the student's is still to come
|
|
|
|
| 3192 |
const ok=!res||res.status!==403; // a server that cannot be reached is not a refusal
|
| 3193 |
const me=res&&res.ok?await res.json().catch(()=>({})):{}, teacher=!!me.teacher;
|
| 3194 |
const mine=me.classes||[]; // a teacher practises every lesson and is not asked for a class
|
| 3195 |
+
MY_CLASSES=teacher?[]:mine; MY_CLASS=null; FREE=teacher; TUTOR=!!me.tutor; TEACHER_DAILIES=me.dailies||[];
|
| 3196 |
$("myClass").textContent=mine.length>1?(teacher?`כיתות: ${mine.map(c=>c.name).join(" · ")}`:"בחירת כיתה"):mine.length?`כיתת ${mine[0].name}`:"";
|
| 3197 |
$("myClass").classList.toggle("many",MY_CLASSES.length>1); $("myClass").title=MY_CLASSES.length>1?"מעבר לכיתה אחרת":"התלמידים בכיתה שלי";
|
| 3198 |
MY_LESSONS=me.lessons||null; if(ALL_LESSONS.length) useLessons(MY_LESSONS);
|
tests/test_scoring.py
CHANGED
|
@@ -1,5 +1,6 @@
|
|
| 1 |
"""Tests with synthetic CTC emissions: no model download needed."""
|
| 2 |
import io
|
|
|
|
| 3 |
import wave
|
| 4 |
|
| 5 |
import numpy as np
|
|
@@ -955,10 +956,11 @@ def test_sign_in_guards_the_practice_endpoints():
|
|
| 955 |
VERB = next(p for p in PHRASES if p["cat"] == "l1-verbs")
|
| 956 |
|
| 957 |
class FakeAuth:
|
| 958 |
-
url, key, teachers = "https://proj.supabase.co", "sb_publishable_x", frozenset()
|
| 959 |
|
| 960 |
def __init__(self):
|
| 961 |
self.rows, self.cls, self.vids, self.txts, self.days, self.wrote = [], [], [], [], {"dailies": [], "library": []}, {}
|
|
|
|
| 962 |
|
| 963 |
def writings(self, token):
|
| 964 |
return {t: lines for (u, t), lines in self.wrote.items() if u == "u1"}
|
|
@@ -972,6 +974,15 @@ def test_sign_in_guards_the_practice_endpoints():
|
|
| 972 |
def classes(self, fresh=False):
|
| 973 |
return self.cls
|
| 974 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 975 |
def save_class(self, id, name, emails, nicknames, lessons, homeworks=(), dailies=None):
|
| 976 |
row = {"name": name, "emails": emails, "nicknames": nicknames, "lessons": lessons, "homeworks": list(homeworks),
|
| 977 |
**({} if dailies is None else {"dailies": list(dailies)})}
|
|
@@ -1081,7 +1092,7 @@ def test_sign_in_guards_the_practice_endpoints():
|
|
| 1081 |
c.app.state.auth.cls, c.app.state.auth.teachers = [], frozenset({"a@b.c"})
|
| 1082 |
assert c.post("/api/classes", json={"name": "September 2026", "emails": "x@b.c", "lessons": ALL[:1]},
|
| 1083 |
headers=good).status_code == 200
|
| 1084 |
-
assert c.get("/api/me", headers=good).json() == {"email": "A@b.c", "teacher": True, "classes": [], "lessons": ALL, "dailies": []}
|
| 1085 |
# the content part: a teacher adds a video to a ready lesson by its Vimeo link, kept without the sharing parameters
|
| 1086 |
READY = [l["id"] for l in LESSONS if not l.get("soon")]
|
| 1087 |
SOON = next(l["id"] for l in LESSONS if l.get("soon"))
|
|
@@ -1336,3 +1347,100 @@ def test_result_scores_each_letter():
|
|
| 1336 |
# the coloured letter says why, with the advice for that mistake; a letter that was fine says nothing
|
| 1337 |
het, mem = (next(l for l in r["words"][1]["letters"] if l["t"][0] == c) for c in "חמ")
|
| 1338 |
assert het["why"] == "ח (ح) נשמעה כמו ח' (خ)" and het["tip"] == r["tips"][0]["text"] and "why" not in mem
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
"""Tests with synthetic CTC emissions: no model download needed."""
|
| 2 |
import io
|
| 3 |
+
import re
|
| 4 |
import wave
|
| 5 |
|
| 6 |
import numpy as np
|
|
|
|
| 956 |
VERB = next(p for p in PHRASES if p["cat"] == "l1-verbs")
|
| 957 |
|
| 958 |
class FakeAuth:
|
| 959 |
+
url, key, teachers, tutors = "https://proj.supabase.co", "sb_publishable_x", frozenset(), frozenset()
|
| 960 |
|
| 961 |
def __init__(self):
|
| 962 |
self.rows, self.cls, self.vids, self.txts, self.days, self.wrote = [], [], [], [], {"dailies": [], "library": []}, {}
|
| 963 |
+
self.rank = frozenset()
|
| 964 |
|
| 965 |
def writings(self, token):
|
| 966 |
return {t: lines for (u, t), lines in self.wrote.items() if u == "u1"}
|
|
|
|
| 974 |
def classes(self, fresh=False):
|
| 975 |
return self.cls
|
| 976 |
|
| 977 |
+
def ranked(self, fresh=False):
|
| 978 |
+
return self.rank
|
| 979 |
+
|
| 980 |
+
def set_tutor(self, email, on, by):
|
| 981 |
+
if self.rank is None:
|
| 982 |
+
raise AuthUnavailable("supabase answered 404: no table")
|
| 983 |
+
self.rank = self.rank | {email} if on else self.rank - {email}
|
| 984 |
+
self.by = by
|
| 985 |
+
|
| 986 |
def save_class(self, id, name, emails, nicknames, lessons, homeworks=(), dailies=None):
|
| 987 |
row = {"name": name, "emails": emails, "nicknames": nicknames, "lessons": lessons, "homeworks": list(homeworks),
|
| 988 |
**({} if dailies is None else {"dailies": list(dailies)})}
|
|
|
|
| 1092 |
c.app.state.auth.cls, c.app.state.auth.teachers = [], frozenset({"a@b.c"})
|
| 1093 |
assert c.post("/api/classes", json={"name": "September 2026", "emails": "x@b.c", "lessons": ALL[:1]},
|
| 1094 |
headers=good).status_code == 200
|
| 1095 |
+
assert c.get("/api/me", headers=good).json() == {"email": "A@b.c", "teacher": True, "tutor": True, "classes": [], "lessons": ALL, "dailies": []}
|
| 1096 |
# the content part: a teacher adds a video to a ready lesson by its Vimeo link, kept without the sharing parameters
|
| 1097 |
READY = [l["id"] for l in LESSONS if not l.get("soon")]
|
| 1098 |
SOON = next(l["id"] for l in LESSONS if l.get("soon"))
|
|
|
|
| 1347 |
# the coloured letter says why, with the advice for that mistake; a letter that was fine says nothing
|
| 1348 |
het, mem = (next(l for l in r["words"][1]["letters"] if l["t"][0] == c) for c in "חמ")
|
| 1349 |
assert het["why"] == "ח (ح) נשמעה כמו ח' (خ)" and het["tip"] == r["tips"][0]["text"] and "why" not in mem
|
| 1350 |
+
|
| 1351 |
+
|
| 1352 |
+
def test_a_tutor_flags_a_recording_scored_wrong(monkeypatch):
|
| 1353 |
+
from fastapi.testclient import TestClient
|
| 1354 |
+
|
| 1355 |
+
monkeypatch.setenv("SAWTAK_API_KEY", "") # no native baseline from a local .env: the score is the stub's own
|
| 1356 |
+
|
| 1357 |
+
from app.auth import AuthUnavailable
|
| 1358 |
+
from app.main import create_app
|
| 1359 |
+
|
| 1360 |
+
class FakeAuth:
|
| 1361 |
+
url, key, teachers, tutors = "https://proj.supabase.co", "sb_publishable_x", frozenset(), frozenset({"t@b.c"})
|
| 1362 |
+
|
| 1363 |
+
def __init__(self):
|
| 1364 |
+
self.cls, self.flags, self.table, self.rank = [], [], True, frozenset()
|
| 1365 |
+
|
| 1366 |
+
def user(self, token):
|
| 1367 |
+
return {"t": {"id": "u1", "email": "T@b.c"}, "s": {"id": "u2", "email": "s@b.c"}}.get(token)
|
| 1368 |
+
|
| 1369 |
+
def classes(self, fresh=False):
|
| 1370 |
+
return self.cls
|
| 1371 |
+
|
| 1372 |
+
def ranked(self, fresh=False):
|
| 1373 |
+
return self.rank
|
| 1374 |
+
|
| 1375 |
+
def set_tutor(self, email, on, by):
|
| 1376 |
+
if self.rank is None:
|
| 1377 |
+
raise AuthUnavailable("supabase answered 404: no table")
|
| 1378 |
+
self.rank = self.rank | {email} if on else self.rank - {email}
|
| 1379 |
+
self.by = by
|
| 1380 |
+
|
| 1381 |
+
def level_videos(self, table, fresh=False):
|
| 1382 |
+
return []
|
| 1383 |
+
|
| 1384 |
+
def texts(self, fresh=False):
|
| 1385 |
+
return []
|
| 1386 |
+
|
| 1387 |
+
def add_flag(self, row, audio, mime, name):
|
| 1388 |
+
if not self.table:
|
| 1389 |
+
raise AuthUnavailable("supabase answered 404: no table")
|
| 1390 |
+
self.flags.append((row, audio, mime, name))
|
| 1391 |
+
return True
|
| 1392 |
+
|
| 1393 |
+
t = np.arange(16000) / 16000
|
| 1394 |
+
buf = io.BytesIO()
|
| 1395 |
+
with wave.open(buf, "wb") as w:
|
| 1396 |
+
w.setnchannels(1); w.setsampwidth(2); w.setframerate(16000)
|
| 1397 |
+
w.writeframes((0.3 * np.sin(2 * np.pi * 220 * t) * 32767).astype("<i2").tobytes())
|
| 1398 |
+
pid = PHRASES.index(TOILET)
|
| 1399 |
+
send = lambda c, token, **data: c.post("/api/flags", data={"phrase_id": pid, **data}, headers={"Authorization": f"Bearer {token}"},
|
| 1400 |
+
files={"audio": ("rec", buf.getvalue(), "audio/wav")})
|
| 1401 |
+
# said with a Hebrew chet, as the model hears it: the tutor says it was right
|
| 1402 |
+
with TestClient(create_app(scorer_for(emissions(["w", "eː", "n", "i", "l", "χ", "a", "m", "aː", "m"])), auth=FakeAuth())) as c:
|
| 1403 |
+
a = c.app.state.auth
|
| 1404 |
+
assert c.get("/api/me", headers={"Authorization": "Bearer t"}).json()["tutor"] is True
|
| 1405 |
+
assert "tutor" not in c.get("/api/me", headers={"Authorization": "Bearer s"}).json()
|
| 1406 |
+
assert c.post("/api/flags", data={"phrase_id": pid}, files={"audio": ("rec", b"x", "audio/wav")}).status_code == 401
|
| 1407 |
+
assert send(c, "s").status_code == 403 and not a.flags # tutors only
|
| 1408 |
+
r = send(c, "t", note=" אמרתי ח נכונה ")
|
| 1409 |
+
(row, audio, mime, name), = a.flags
|
| 1410 |
+
assert r.status_code == 200 and r.json() == {"ok": True, "audio": True, "flag": row}, r.text # the page shows what was kept
|
| 1411 |
+
assert row["email"] == "t@b.c" and row["cat"] == TOILET["cat"] and row["he"] == TOILET["he"] and row["note"] == "אמרתי ח נכונה"
|
| 1412 |
+
assert row["ipa"] == "w eː n | i l ħ a m m aː m" and "χ" in row["heard_ipa"] and row["score"] == row["result"]["score"] < 100
|
| 1413 |
+
assert row["result"]["tips"][0]["key"] == "ħ>x" and "phoneme_heatmap" not in row["result"]
|
| 1414 |
+
assert audio == buf.getvalue() and mime == "audio/wav" and re.fullmatch(r"\d{4}-\d\d/[0-9a-f]{32}\.wav", name)
|
| 1415 |
+
assert send(c, "t", phrase_id=10**6).status_code == 404
|
| 1416 |
+
a.teachers = frozenset({"s@b.c"}) # a teacher flags too
|
| 1417 |
+
assert c.get("/api/me", headers={"Authorization": "Bearer s"}).json()["tutor"] is True and send(c, "s").status_code == 200
|
| 1418 |
+
a.teachers = frozenset()
|
| 1419 |
+
a.table = False # before the table is created: the command to create it
|
| 1420 |
+
r = send(c, "t")
|
| 1421 |
+
assert r.status_code == 503 and "create table public.flags" in r.json()["detail"]
|
| 1422 |
+
# a tutor is let in without a class, a student is not
|
| 1423 |
+
a.cls = [{"id": 1, "name": "B", "emails": ["other@b.c"], "nicknames": {}, "lessons": []}]
|
| 1424 |
+
assert c.get("/api/me", headers={"Authorization": "Bearer t"}).status_code == 200
|
| 1425 |
+
assert c.get("/api/me", headers={"Authorization": "Bearer s"}).status_code == 403
|
| 1426 |
+
# the rank the teacher gives a student in the panel: theirs in every class, and it lets nobody in by itself
|
| 1427 |
+
tok = lambda t: {"Authorization": f"Bearer {t}"}
|
| 1428 |
+
rank = lambda t, **body: c.put("/api/tutors", json=body, headers=tok(t))
|
| 1429 |
+
a.users, a.all_attempts, a.all_writings = lambda: [{"id": "u2", "email": "s@b.c", "name": ""}], lambda: [], lambda: []
|
| 1430 |
+
assert rank("s", email="s@b.c", tutor=True).status_code == 403 # teachers only (s is not in a class either)
|
| 1431 |
+
a.cls[0]["emails"].append("s@b.c"); a.teachers = frozenset({"t@b.c"})
|
| 1432 |
+
assert rank("s", email="s@b.c", tutor=True).status_code == 403 and "tutor" not in c.get("/api/me", headers=tok("s")).json()
|
| 1433 |
+
assert rank("t", email="nobody", tutor=True).status_code == 400 and rank("t", email="s@b.c", tutor="yes").status_code == 400
|
| 1434 |
+
assert rank("t", email=" S@b.c ", tutor=True).status_code == 200 and a.rank == {"s@b.c"} and a.by == "t@b.c"
|
| 1435 |
+
assert c.get("/api/me", headers=tok("s")).json()["tutor"] is True and send(c, "s").status_code == 503 # may flag (the table is still missing)
|
| 1436 |
+
panel = c.get("/api/class", headers=tok("t")).json()
|
| 1437 |
+
assert [(s["email"], s["tutor"], s.get("tutor_fixed")) for s in panel["students"]] == [("s@b.c", True, None), ("other@b.c", False, None)]
|
| 1438 |
+
assert rank("t", email="s@b.c", tutor=False).status_code == 200 and "tutor" not in c.get("/api/me", headers=tok("s")).json()
|
| 1439 |
+
a.rank = frozenset({"out@b.c"}) # ranked, but in no class: not let in
|
| 1440 |
+
known = a.user
|
| 1441 |
+
a.user = lambda token: {"id": "u3", "email": "out@b.c"} if token == "x" else known(token)
|
| 1442 |
+
assert c.get("/api/me", headers=tok("x")).status_code == 403
|
| 1443 |
+
a.rank = None # before the table is created: the panel says what to run, and so does giving the rank
|
| 1444 |
+
assert "create table public.tutors" in c.get("/api/class", headers=tok("t")).json()["setup"][-1]["sql"]
|
| 1445 |
+
r = rank("t", email="s@b.c", tutor=True)
|
| 1446 |
+
assert r.status_code == 503 and "create table public.tutors" in r.json()["detail"]
|
tests/test_speech_evaluation.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from app.speech_evaluation import SpeechEvaluationService
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class FakeScorer:
|
| 5 |
+
def __init__(self, result):
|
| 6 |
+
self.result = result
|
| 7 |
+
|
| 8 |
+
def score(self, *_args, **_kwargs):
|
| 9 |
+
return dict(self.result)
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def test_uncertain_recognition_is_not_counted_as_a_mistake():
|
| 13 |
+
service = SpeechEvaluationService(FakeScorer({"score": 20, "unrelated": True}))
|
| 14 |
+
result = service.evaluate([], {"variants": []})
|
| 15 |
+
assert result["outcome"] == "uncertain"
|
| 16 |
+
assert result["counts_as_attempt"] is False
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def test_low_score_is_not_mislabelled_as_grammar_or_pronunciation():
|
| 20 |
+
weak = SpeechEvaluationService(FakeScorer({"score": 60, "unrelated": False})).evaluate([], {})
|
| 21 |
+
good = SpeechEvaluationService(FakeScorer({"score": 90, "unrelated": False})).evaluate([], {})
|
| 22 |
+
assert weak["outcome"] == "needs_work" and weak["error_kind"] == "undetermined"
|
| 23 |
+
assert good["outcome"] == "correct" and good["correct"]
|
tests/test_verb_game.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import random
|
| 2 |
+
|
| 3 |
+
import pytest
|
| 4 |
+
|
| 5 |
+
from app.grammar import PRONOUNS, VERBS
|
| 6 |
+
from app.verb_game import BOOK_PAST_TRANSLITERATIONS, BOOK_VERBS, PracticeSessionManager, VerbExerciseGenerator
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
@pytest.fixture
|
| 10 |
+
def game():
|
| 11 |
+
return VerbExerciseGenerator(PracticeSessionManager(rng=random.Random(7)))
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def test_only_complete_unlocked_paradigms_are_available(game):
|
| 15 |
+
assert game.available([]) == []
|
| 16 |
+
assert game.available(["1"]) == ["akal", "qaad", "fatah", "saal"]
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def test_all_filled_book_paradigms_resolve_to_existing_lexicon(game):
|
| 20 |
+
assert set(BOOK_VERBS) == set(BOOK_PAST_TRANSLITERATIONS)
|
| 21 |
+
assert all(len(forms) == len(PRONOUNS) for forms in BOOK_VERBS.values())
|
| 22 |
+
assert "tabakh" in game.available(["3"])
|
| 23 |
+
assert "tabakh" not in game.available(["1"])
|
| 24 |
+
assert "jaab" in game.available(["2.5"])
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
@pytest.mark.parametrize("level,count", [(1, 4), (3, 3)])
|
| 28 |
+
def test_choice_question_uses_real_unique_conjugations(game, level, count):
|
| 29 |
+
q = game.question(level, ["1"])
|
| 30 |
+
real = {(row[1], row[2]) for table in VERBS.values() for row in table}
|
| 31 |
+
assert len(q["choices"]) == count
|
| 32 |
+
assert len({(c["transliteration"], c["arabic"]) for c in q["choices"]}) == count
|
| 33 |
+
assert all((c["transliteration"], c["arabic"]) in real for c in q["choices"])
|
| 34 |
+
assert q["tense"]["id"] == "past"
|
| 35 |
+
assert q["pronoun"]["id"] in {p[0] for p in PRONOUNS}
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def test_server_grades_choice_once_and_reports_timing(game):
|
| 39 |
+
q = game.question(1, ["1"])
|
| 40 |
+
result = game.answer(q["question_id"], q["choices"][0]["id"], 1234)
|
| 41 |
+
assert result["response_ms"] == 1234
|
| 42 |
+
with pytest.raises(LookupError):
|
| 43 |
+
game.answer(q["question_id"], q["choices"][0]["id"], 5)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def test_matching_accepts_an_identical_form_token(game):
|
| 47 |
+
q = game.question(2, ["1"])
|
| 48 |
+
stored = game.sessions.questions[q["question_id"]]
|
| 49 |
+
answer = dict(stored.correct)
|
| 50 |
+
# Simulate two form cards with the same visible/spoken value and swap the token.
|
| 51 |
+
first_pid, first_fid = next(iter(stored.correct.items()))
|
| 52 |
+
duplicate_fid = "same-visible-form"
|
| 53 |
+
stored.forms[duplicate_fid] = stored.forms[first_fid]
|
| 54 |
+
answer[first_pid] = duplicate_fid
|
| 55 |
+
result = game.answer(q["question_id"], answer, 2500)
|
| 56 |
+
assert result["correct"]
|
| 57 |
+
assert result["pair_results"][first_pid]
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def test_adaptive_selection_prioritizes_recent_error_over_mastered_form(game):
|
| 61 |
+
mastery = {}
|
| 62 |
+
for verb in VERBS:
|
| 63 |
+
for pronoun in PRONOUNS:
|
| 64 |
+
mastery[f"{verb}:past:{pronoun[0]}"] = {"attempts": 10, "correct": 10, "median_ms": 700}
|
| 65 |
+
mastery["fatah:past:inti"] = {"attempts": 4, "correct": 0, "median_ms": 3500}
|
| 66 |
+
q = game.question(1, ["1"], mastery)
|
| 67 |
+
assert q["mastery_key"] == "fatah:past:inti"
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def test_recent_questions_are_deprioritized(game):
|
| 71 |
+
key = "fatah:past:inti"
|
| 72 |
+
mastery = {key: {"attempts": 4, "correct": 0, "median_ms": 3500}}
|
| 73 |
+
q = game.question(1, ["1"], mastery, [key, key, key])
|
| 74 |
+
assert q["mastery_key"] != key
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def test_no_unlocked_paradigm_fails_cleanly(game):
|
| 78 |
+
with pytest.raises(LookupError):
|
| 79 |
+
game.question(1, ["2"])
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
@pytest.mark.parametrize("level", [4, 5])
|
| 83 |
+
def test_spoken_questions_keep_expected_forms_server_side(game, level):
|
| 84 |
+
q = game.question(level, ["1"])
|
| 85 |
+
assert "choices" not in q
|
| 86 |
+
stored, phrase = game.speech_phrase(q["question_id"])
|
| 87 |
+
assert stored.mode == level
|
| 88 |
+
assert phrase["variants"]
|
| 89 |
+
assert all(ar and ipa for ar, ipa in phrase["variants"])
|
| 90 |
+
if level == 5:
|
| 91 |
+
assert q["conversation"]["arabic"]
|