3v324v23 commited on
Commit
3b6eb00
ยท
1 Parent(s): e5f0c48

Add text handling functionality and update scoring tests

Browse files

- Introduced a new module `texts.py` to manage text entries added by teachers, including story and dialogue formats.
- Implemented functions for processing Arabic text transliterations, phonetics, and reading rules.
- Enhanced the scoring tests in `test_scoring.py` to accommodate the new text functionalities, including adding, deleting, and ordering texts alongside videos.
- Updated API endpoints to handle content that includes both videos and texts, ensuring proper validation and response handling.

Files changed (6) hide show
  1. README.md +28 -1
  2. app/auth.py +44 -5
  3. app/main.py +159 -42
  4. app/texts.py +189 -0
  5. static/index.html +116 -64
  6. tests/test_scoring.py +61 -9
README.md CHANGED
@@ -116,7 +116,7 @@ The panel has three parts, chosen at its top (the third, **ืชื•ื›ืŸ**, is descri
116
 
117
  ### Content and videos
118
 
119
- The panel's third part, **ืชื•ื›ืŸ**, shows the course as the students get it: every level, its lessons (those not written yet as "ื‘ืงืจื•ื‘"), and under each ready lesson its topics in the path's order. There the teacher adds a video to a lesson: a name and a Vimeo link, as Vimeo's share button gives it (`https://vimeo.com/1233611297/d46ac373c8?share=copy&fl=sv&fe=ci`; the hash after the number is what opens an unlisted video, and the sharing parameters are dropped). The video becomes a topic of the lesson, with โ–ถ on its circle, and pressing it plays it in a box over the page, in Vimeo's player. A lesson may have several videos. A new one is added at the lesson's end, and the โ†‘ โ†“ arrows on its row move it a step at a time to its place: before the first topic, between two topics, beside another video, or after them all. The path shows the lesson in that order. A video is not practised, so it counts in no figure; the path marks the ones a student opened ("โœ“ ื ืฆืคื”"), on their device only. In the panel each video also has "ืฆืคื™ื™ื”" and "ืžื—ื™ืงื”". Students get the videos of their classes' lessons (`GET /api/videos`); adding, moving and deleting (`POST /api/videos`, `PUT /api/videos/order`, `DELETE /api/videos/{id}`) answer teachers only.
120
 
121
  The videos are kept in Supabase like the classes, read and written with `SUPABASE_SECRET_KEY` only. Create the table once (until it exists the lessons have no videos, and adding one is refused with this command in the message):
122
 
@@ -143,6 +143,33 @@ For the video to play inside the page, its Vimeo privacy setting has to allow em
143
 
144
  Keeping the link from being passed on is done in Vimeo, not here: the page has to give the browser the player's address, so a student who looks for it finds it (the server only keeps the link itself, `url`, for teachers). In the video's privacy settings on Vimeo, hide it from vimeo.com and allow embedding on specific domains only, naming the app's own domain (on Hugging Face, `<owner>-<space>.hf.space`). The video then plays inside the app and nowhere else: its link, opened or embedded anywhere else, shows nothing. Domain-level privacy needs a paid Vimeo plan.
145
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
146
  ### Homework
147
 
148
  In the class's dialog the teacher sets its homework: one topic of the class's lessons (for example the conversation "ืฉื™ื—ืช ื”ื™ื›ืจื•ืช"), and optionally the day it is due. The students see it on the path itself: the bubble over the homework topic's circle says "ืฉื™ืขื•ืจื™ ื‘ื™ืช" and counts the days left ("ื ืฉืืจื• 3 ื™ืžื™ื", "ืžื’ื™ืฉื™ื ืžื—ืจ!", "ืžื’ื™ืฉื™ื ื”ื™ื•ื!", and "ื‘ืื™ื—ื•ืจ ืฉืœ ื™ื•ืžื™ื™ื" once the day passed). On the last two days the bubble and the circle's ring turn amber, and red after them. The path's focus does not move: the page still opens on the next topic in the course's order, which keeps its own "ื”ืชื—ื™ืœื•" bubble, so the homework's bubble may be further up or down the path. The homework is done when every sentence of the topic was practised, whenever that was; the circle then gets its โœ“ and "ืฉื™ืขื•ืจื™ ื”ื‘ื™ืช ื”ื•ืฉืœืžื•". In the panel the class's card shows how many students finished and names those who did not, the furthest from it first. The students get the homework with `GET /api/me`, so a change reaches them the next time they open the page.
 
116
 
117
  ### Content and videos
118
 
119
+ The panel's third part, **ืชื•ื›ืŸ**, shows the course as the students get it: every level, its lessons (those not written yet as "ื‘ืงืจื•ื‘"), and under each ready lesson its topics in the path's order. There the teacher adds a video to a lesson: a name and a Vimeo link, as Vimeo's share button gives it (`https://vimeo.com/1233611297/d46ac373c8?share=copy&fl=sv&fe=ci`; the hash after the number is what opens an unlisted video, and the sharing parameters are dropped). The video becomes a topic of the lesson, with โ–ถ on its circle, and pressing it plays it in a box over the page, in Vimeo's player. A lesson may have several videos. A new one is added at the lesson's end, and the โ†‘ โ†“ arrows on its row move it a step at a time to its place: before the first topic, between two topics, beside another video, or after them all. The path shows the lesson in that order. A video is not practised, so it counts in no figure; the path marks the ones a student opened ("โœ“ ื ืฆืคื”"), on their device only. In the panel each video also has "ืฆืคื™ื™ื”" and "ืžื—ื™ืงื”". Students get the videos of their classes' lessons (`GET /api/videos`); adding, moving and deleting (`POST /api/videos`, `PUT /api/content/order`, `DELETE /api/videos/{id}`) answer teachers only.
120
 
121
  The videos are kept in Supabase like the classes, read and written with `SUPABASE_SECRET_KEY` only. Create the table once (until it exists the lessons have no videos, and adding one is refused with this command in the message):
122
 
 
143
 
144
  Keeping the link from being passed on is done in Vimeo, not here: the page has to give the browser the player's address, so a student who looks for it finds it (the server only keeps the link itself, `url`, for teachers). In the video's privacy settings on Vimeo, hide it from vimeo.com and allow embedding on specific domains only, naming the app's own domain (on Hugging Face, `<owner>-<space>.hf.space`). The video then plays inside the app and nowhere else: its link, opened or embedded anywhere else, shows nothing. Domain-level privacy needs a paid Vimeo plan.
145
 
146
+ ### Texts
147
+
148
+ In **ืชื•ื›ืŸ** the teacher also adds texts to a lesson, as many as they like: a story or a dialogue, practised like the course's own conversation "ืฉื™ื—ืช ื”ื™ื›ืจื•ืช". "+ ื”ื•ืกืคืช ื˜ืงืกื˜" under the lesson asks for a name and the text twice, a line per sentence: in Hebrew, and the same lines, in the same order, in Arabic written in Hebrew letters as the course writes it (`ื›ึดึผื™ืฃ ื—ึทืืœึทื›ึผ?`). Each is pasted into its box, or read into it from a plain-text file (`.txt`, UTF-8), and can be corrected there before it is added. Empty lines are not counted, and the two must have the same number of lines; otherwise the text is refused, with both numbers in the message. The kind is chosen there too:
149
+
150
+ - **ืกื™ืคื•ืจ**: every line is played in the voice the student chose in the settings.
151
+ - **ืฉื™ื—ื”**: the teacher picks a voice for the odd lines and one for the even lines, from the app's voices.
152
+
153
+ The text becomes a topic of the lesson, laid out as a story: all its lines on the card, said one after the other, with "ื”ืฉืžืขืช ื”ืฉื™ื—ื”" and "ื‘ื•ื—ืŸ". It counts like any topic (the lesson's progress, the class's figures, and it can be the homework). Like a video it is added at the lesson's end and moved with the โ†‘ โ†“ arrows on its row, past topics, videos and other texts (`PUT /api/content/order` places both kinds); "ืชืจื’ื•ืœ" on the row opens it as the students get it, and "ืžื—ื™ืงื”" removes it (the recordings made in it stay in `attempts`, uncounted).
154
+
155
+ The scorer needs each line's phonemes and the answer's voice needs it in Arabic letters, so the server reads the transliteration word by word (`app/texts.py`). A word of the course is found by its transliteration and gets the course's own Arabic spelling and accepted pronunciations (dagesh, shva and final letters are not compared; an unpointed word is found by its letters alone). Any other word is read by rule from its letters and points, which is close but not always right: vowel length and some spellings (ู‰, ุก, ุฉ) cannot be told from the transliteration, and an unpointed word outside the course has no vowels to read. The panel lists those words on the text's row ("ืžื™ืœื™ื ืฉืื™ื ืŸ ื‘ืžื™ืœื•ืŸ ื”ืงื•ืจืก ื ืงืจืื• ืœืคื™ ื”ื›ืชื™ื‘"), so the teacher knows which lines are worth a listen. A word the course should know is added to `LEX` in `app/workbook.py`.
156
+
157
+ A line's phrase id is past the bank's (1,000,000 + the text's id ร— 1000 + the line's number) and its topic is `t<text id>`; an attempt is recorded under that topic and the line's Hebrew (numbered from its second appearance in the text: `ื›ืŸ (2)`). The texts are kept in Supabase like the videos (`GET /api/texts` gives a student those of their classes' lessons; `POST /api/texts` and `DELETE /api/texts/{id}` answer teachers only). Create the table once:
158
+
159
+ ```sql
160
+ create table public.texts (
161
+ id bigint generated always as identity primary key,
162
+ lesson text not null, -- the lesson id, e.g. 2 or 2.1
163
+ title text not null, -- the topic's name on the path
164
+ voices text[] not null default '{}', -- a dialogue's two voices by name (odd lines, even lines); empty = a story
165
+ lines jsonb not null, -- [[Hebrew, Arabic in Hebrew letters], ...]
166
+ pos int, -- as in videos
167
+ ord int not null default 0,
168
+ created_at timestamptz not null default now()
169
+ );
170
+ alter table public.texts enable row level security;
171
+ ```
172
+
173
  ### Homework
174
 
175
  In the class's dialog the teacher sets its homework: one topic of the class's lessons (for example the conversation "ืฉื™ื—ืช ื”ื™ื›ืจื•ืช"), and optionally the day it is due. The students see it on the path itself: the bubble over the homework topic's circle says "ืฉื™ืขื•ืจื™ ื‘ื™ืช" and counts the days left ("ื ืฉืืจื• 3 ื™ืžื™ื", "ืžื’ื™ืฉื™ื ืžื—ืจ!", "ืžื’ื™ืฉื™ื ื”ื™ื•ื!", and "ื‘ืื™ื—ื•ืจ ืฉืœ ื™ื•ืžื™ื™ื" once the day passed). On the last two days the bubble and the circle's ring turn amber, and red after them. The path's focus does not move: the page still opens on the next topic in the course's order, which keeps its own "ื”ืชื—ื™ืœื•" bubble, so the homework's bubble may be further up or down the path. The homework is done when every sentence of the topic was practised, whenever that was; the circle then gets its โœ“ and "ืฉื™ืขื•ืจื™ ื”ื‘ื™ืช ื”ื•ืฉืœืžื•". In the panel the class's card shows how many students finished and names those who did not, the furthest from it first. The students get the homework with `GET /api/me`, so a change reaches them the next time they open the page.
app/auth.py CHANGED
@@ -19,6 +19,10 @@ Videos: the teacher adds lesson videos in the panel's content part (a lesson, a
19
  each to its place among the lesson's topics, kept in the Supabase table `videos`. A student's path shows them as
20
  topics of their lessons.
21
 
 
 
 
 
22
  Env: SUPABASE_URL (https://<project-ref>.supabase.co)
23
  SUPABASE_PUBLISHABLE_KEY (the publishable/anon key; it is public and also goes to the page)
24
  TEACHER_EMAILS (optional: the accounts with the management panel, separated by commas or spaces)
@@ -63,6 +67,7 @@ class SupabaseAuth:
63
  self._cache: dict[str, tuple[float, dict]] = {}
64
  self._classes: tuple[float, list[dict]] | None = None
65
  self._videos: tuple[float, list[dict]] | None = None
 
66
  self._lock = threading.Lock()
67
 
68
  def user(self, token: str) -> dict | None:
@@ -220,13 +225,47 @@ class SupabaseAuth:
220
  self._admin("/rest/v1/videos", "POST", {"lesson": lesson, "title": title, "url": url, "pos": pos, "ord": ord})
221
  self._videos = None
222
 
223
- def place_videos(self, places: list[tuple[int, int, int]]) -> None:
224
- """Moves videos: (id, pos, ord) of each."""
225
  try:
226
- for id, pos, ord in places:
227
- self._admin(f"/rest/v1/videos?id=eq.{int(id)}", "PATCH", {"pos": pos, "ord": ord})
 
228
  finally:
229
- self._videos = None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
230
 
231
  def delete_video(self, id: int) -> None:
232
  self._admin(f"/rest/v1/videos?id=eq.{int(id)}", "DELETE")
 
19
  each to its place among the lesson's topics, kept in the Supabase table `videos`. A student's path shows them as
20
  topics of their lessons.
21
 
22
+ Texts: the teacher also adds texts there (a story or a dialogue: a lesson, a title, its lines in Hebrew and in
23
+ Arabic written in Hebrew letters, and a dialogue's two voices), kept in the Supabase table `texts` and placed among
24
+ the lesson's topics like the videos. Each is a topic practised line by line (see app/texts.py).
25
+
26
  Env: SUPABASE_URL (https://<project-ref>.supabase.co)
27
  SUPABASE_PUBLISHABLE_KEY (the publishable/anon key; it is public and also goes to the page)
28
  TEACHER_EMAILS (optional: the accounts with the management panel, separated by commas or spaces)
 
67
  self._cache: dict[str, tuple[float, dict]] = {}
68
  self._classes: tuple[float, list[dict]] | None = None
69
  self._videos: tuple[float, list[dict]] | None = None
70
+ self._texts: tuple[float, list[dict]] | None = None
71
  self._lock = threading.Lock()
72
 
73
  def user(self, token: str) -> dict | None:
 
225
  self._admin("/rest/v1/videos", "POST", {"lesson": lesson, "title": title, "url": url, "pos": pos, "ord": ord})
226
  self._videos = None
227
 
228
+ def place(self, places: list[tuple[str, int, int, int]]) -> None:
229
+ """Moves videos and texts: (table, id, pos, ord) of each; the table is "videos" or "texts"."""
230
  try:
231
+ for table, id, pos, ord in places:
232
+ assert table in ("videos", "texts")
233
+ self._admin(f"/rest/v1/{table}?id=eq.{int(id)}", "PATCH", {"pos": pos, "ord": ord})
234
  finally:
235
+ self._videos = self._texts = None
236
+
237
+ def texts(self, fresh: bool = False) -> list[dict]:
238
+ """Every text the teacher added: id, lesson (a lesson id), title, voices (a dialogue's two voices by name,
239
+ the odd lines' and the even lines'; empty for a story), lines ([Hebrew, Arabic in Hebrew letters] each), and
240
+ pos and ord as a video has them (see `videos`).
241
+ Kept for CLASSES_TTL, as each score asks. Without the secret key, or before the table is created, there are none."""
242
+ now = time.monotonic()
243
+ with self._lock:
244
+ hit = self._texts
245
+ if hit and hit[0] > now and not fresh:
246
+ return hit[1]
247
+ rows: list[dict] = []
248
+ if self.secret:
249
+ try:
250
+ rows = self._admin("/rest/v1/texts?select=*&order=id.asc")
251
+ for r in rows:
252
+ r["voices"], r["ord"] = r.get("voices") or [], r.get("ord") or 0
253
+ except AuthUnavailable as e:
254
+ if "answered 404" not in str(e):
255
+ raise
256
+ log.warning("the table `texts` is missing (see the README): the lessons have no texts")
257
+ with self._lock:
258
+ self._texts = (now + CLASSES_TTL, rows)
259
+ return rows
260
+
261
+ def add_text(self, lesson: str, title: str, voices: list[str], lines: list[list[str]], pos: int, ord: int) -> None:
262
+ self._admin("/rest/v1/texts", "POST", {"lesson": lesson, "title": title, "voices": voices, "lines": lines,
263
+ "pos": pos, "ord": ord})
264
+ self._texts = None
265
+
266
+ def delete_text(self, id: int) -> None:
267
+ self._admin(f"/rest/v1/texts?id=eq.{int(id)}", "DELETE")
268
+ self._texts = None
269
 
270
  def delete_video(self, id: int) -> None:
271
  self._admin(f"/rest/v1/videos?id=eq.{int(id)}", "DELETE")
app/main.py CHANGED
@@ -30,6 +30,7 @@ from .phrases import CATEGORIES, 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 .tts import VOICES, SawtakTTS, TTSUnavailable, load_tts
34
 
35
  logging.basicConfig(level=logging.INFO)
@@ -55,12 +56,39 @@ MIGRATE_VIDEOS = "alter table public.videos add column if not exists pos int, ad
55
  LESSON_TOPICS = {l: sum(c["lesson"] == l for c in CATEGORIES) for l in READY_LESSONS} # a video's place is 0..this many
56
 
57
 
58
- def lesson_videos(rows: list[dict], lesson: str) -> list[dict]:
59
- """A lesson's videos in their order on the path, each with its place: `pos` of the lesson's own topics stand
60
- before it (one without a place, or past the topics the lesson has now, stands after them all)."""
 
61
  n = LESSON_TOPICS[lesson]
62
- mine = [{**v, "pos": n if v.get("pos") is None else max(0, min(n, v["pos"]))} for v in rows if v["lesson"] == lesson]
63
- return sorted(mine, key=lambda v: (v["pos"], v.get("ord") or 0, v["id"]))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64
  TOPIC_LESSON = {c["id"]: c["lesson"] for c in CATEGORIES} # a topic's lesson: homework is a topic of the class's lessons
65
  MIGRATE_CLASSES = ("alter table public.classes add column if not exists nicknames jsonb not null default '{}', "
66
  "add column if not exists lessons text[] not null default '{}', "
@@ -72,12 +100,12 @@ def lessons_of(c: dict) -> list[str]:
72
  return [l for l in ALL_LESSONS if l in c["lessons"]] or ALL_LESSONS
73
 
74
 
75
- def homework_of(c: dict) -> dict:
76
  """A class's homework: the topic it practises now (a category id, e.g. the conversation "l2-talk"; "" when none
77
  is set) and the day it is due (ISO date, or None). A topic of a lesson the class no longer studies, or one the
78
- course no longer has, is no homework."""
79
  topic = c.get("homework") or ""
80
- return {"homework": topic, "due": c.get("due") or None} if TOPIC_LESSON.get(topic) in lessons_of(c) \
81
  else {"homework": "", "due": None}
82
 
83
 
@@ -129,13 +157,14 @@ def utc(stamp: str) -> datetime:
129
  return datetime.strptime(stamp[:19], "%Y-%m-%dT%H:%M:%S").replace(tzinfo=timezone.utc)
130
 
131
 
132
- def summary(rows: list[dict]) -> dict:
133
  """One student's attempts summed up: best score and tries per phrase id, recordings (all, and of the last
134
  7 days), days practised, time of the last one. A recording that did not match the sentence on the screen
135
  (unrelated) is a recording, on its day, but no try and no score: such ones are counted per phrase id in "missed",
136
  and all together in "unmatched"."""
137
  shown = {c["id"] for c in CATEGORIES}
138
  ids = {(p["cat"], p["he"]): i for i, p in enumerate(PHRASES) if p["cat"] in shown}
 
139
  best: dict[int, int] = {}
140
  tries: dict[int, int] = {}
141
  missed: dict[int, int] = {}
@@ -203,6 +232,30 @@ def create_app(scorer: Scorer | None = None, tts: SawtakTTS | None = None,
203
 
204
  members = [Depends(signed_in)]
205
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
206
  @app.get("/")
207
  def index():
208
  html = (STATIC / "index.html").read_text(encoding="utf-8")
@@ -221,13 +274,13 @@ def create_app(scorer: Scorer | None = None, tts: SawtakTTS | None = None,
221
  lessons = ALL_LESSONS if not mine or user["teacher"] else \
222
  [l for l in ALL_LESSONS if any(l in lessons_of(c) for c in mine)]
223
  return {"email": user["email"] if user else "", "teacher": bool(user and user["teacher"]),
224
- "classes": [{"name": c["name"], "lessons": lessons_of(c), **homework_of(c)} for c in mine],
225
  "lessons": lessons}
226
 
227
  @app.get("/api/progress")
228
  def progress(user: dict | None = Depends(signed_in)):
229
  """The signed-in student's progress: best score and tries per phrase id, recordings, days practised."""
230
- s = summary(app.state.auth.attempts(user["token"]) if user else [])
231
  return {k: s[k] for k in ("best", "tries", "recordings", "days")}
232
 
233
  @app.get("/api/class")
@@ -248,17 +301,18 @@ def create_app(scorer: Scorer | None = None, tts: SawtakTTS | None = None,
248
  for e in c["emails"]:
249
  member.setdefault(e, {})[c["name"]] = c["nicknames"].get(e, "")
250
  opened = {c["name"]: utc(c["created_at"]) for c in classes if c.get("created_at")}
 
251
 
252
  def student(email: str, name: str, joined: bool, mine: list[dict]) -> dict:
253
  into = member.get(email.lower(), {})
254
- since = {n: summary([r for r in mine if n not in opened or utc(r["created_at"]) >= opened[n]]) for n in into}
255
- return {"email": email, "name": name, "joined": joined, "classes": into, "since": since, **summary(mine)}
256
 
257
  students = [student(u["email"], u["name"], True, by.get(u["id"], []))
258
  for u in users if not classes or u["email"].lower() in member]
259
  missing = member.keys() - {s["email"].lower() for s in students}
260
  students += [student(e, "", False, []) for e in sorted(missing)]
261
- return {"classes": [{**c, "lessons": lessons_of(c), **homework_of(c)} for c in classes], "students": students}
262
 
263
  def class_store_error(e: AuthUnavailable) -> str:
264
  """The teacher's message when a class cannot be written; a 404 means Supabase has no `classes` table."""
@@ -284,7 +338,7 @@ def create_app(scorer: Scorer | None = None, tts: SawtakTTS | None = None,
284
  raise HTTPException(400, "ื‘ื—ืจื• ืœืคื—ื•ืช ืฉื™ืขื•ืจ ืื—ื“ ืœื›ื™ืชื”")
285
  lessons = [l for l in ALL_LESSONS if l in map(str, lessons)]
286
  homework, due = str(body.get("homework") or ""), str(body.get("due") or "") or None
287
- if homework and TOPIC_LESSON.get(homework) not in lessons:
288
  raise HTTPException(400, "ืฉื™ืขื•ืจื™ ื”ื‘ื™ืช ื”ื ื ื•ืฉื ืžืื—ื“ ืžืฉื™ืขื•ืจื™ ื”ื›ื™ืชื”")
289
  try:
290
  due = date.fromisoformat(due).isoformat() if homework and due else None # no date without homework
@@ -324,7 +378,7 @@ def create_app(scorer: Scorer | None = None, tts: SawtakTTS | None = None,
324
  def videos(user: dict | None = Depends(signed_in)):
325
  """The lesson videos, each lesson's in its order on the path: id, lesson, title, url (the Vimeo link, for a teacher only), embed
326
  (its player, for the page's frame) and pos (how many of the lesson's own topics stand before it, see
327
- `lesson_videos`). A student gets those of their classes' lessons; a teacher, and an account in no
328
  class, every one. One whose lesson the course no longer has is left out."""
329
  if not user:
330
  return {"videos": []}
@@ -338,8 +392,8 @@ def create_app(scorer: Scorer | None = None, tts: SawtakTTS | None = None,
338
  # the link itself goes to teachers only: a student's page gets the player's address, which it cannot do without
339
  return {"videos": [{"id": v["id"], "lesson": v["lesson"], "title": v["title"],
340
  **({"url": v["url"]} if user["teacher"] else {}),
341
- "embed": vimeo_embed(v["url"]), "pos": v["pos"]}
342
- for l in lessons for v in lesson_videos(rows, l)]}
343
 
344
  def video_store_error(e: AuthUnavailable) -> str:
345
  """The teacher's message when a video cannot be written; a 404 means Supabase has no `videos` table."""
@@ -363,32 +417,100 @@ def create_app(scorer: Scorer | None = None, tts: SawtakTTS | None = None,
363
  if not url:
364
  raise HTTPException(400, "ื–ื” ืœื ืงื™ืฉื•ืจ ืœืกืจื˜ื•ืŸ ื‘-Vimeo. ื”ื“ื‘ื™ืงื• ืงื™ืฉื•ืจ ื›ืžื• https://vimeo.com/1233611297/d46ac373c8")
365
  try:
366
- last = max((v.get("ord") or 0 for v in a.videos(fresh=True) if v["lesson"] == lesson), default=0)
367
- a.add_video(lesson, title, url, LESSON_TOPICS[lesson], last + 1)
368
  except AuthUnavailable as e:
369
  raise HTTPException(503, video_store_error(e))
370
  return {"ok": True}
371
 
372
- @app.put("/api/videos/order")
373
- def order_videos(body: dict = Body(...), a: SupabaseAuth = Depends(teacher_only)):
374
- """Places a lesson's videos among its topics: {"lesson", "order": [{"id", "pos"}]}, every video of the lesson
375
- once, in their order on the path; `pos` is how many of the lesson's own topics stand before the video."""
 
 
 
 
 
376
  lesson, order = str(body.get("lesson", "")), body.get("order")
377
  if lesson not in READY_LESSONS or not isinstance(order, list):
378
  raise HTTPException(400, "unknown lesson")
379
  try:
380
- places = [(int(o["id"]), int(o["pos"])) for o in order]
381
  except (KeyError, TypeError, ValueError):
382
- raise HTTPException(400, "each video needs an id and a place")
383
  try:
384
- mine = {v["id"] for v in a.videos(fresh=True) if v["lesson"] == lesson}
385
- if len(places) != len(mine) or {i for i, _ in places} != mine: # added or deleted meanwhile, in another tab
386
- raise HTTPException(409, "ืจืฉื™ืžืช ื”ืกืจื˜ื•ื ื™ื ื”ืฉืชื ืชื”. ืจืขื ื ื• ื•ื ืกื• ืฉื•ื‘")
387
- if any(not 0 <= pos <= LESSON_TOPICS[lesson] for _, pos in places):
 
388
  raise HTTPException(400, "no such place in the lesson")
389
- a.place_videos([(i, pos, k) for k, (i, pos) in enumerate(places)])
390
  except AuthUnavailable as e:
391
- raise HTTPException(503, video_store_error(e))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
392
  return {"ok": True}
393
 
394
  @app.delete("/api/videos/{video_id}")
@@ -439,12 +561,11 @@ def create_app(scorer: Scorer | None = None, tts: SawtakTTS | None = None,
439
  names = {i: n for n, i in VOICES.items()}
440
  if voice and voice not in names:
441
  raise HTTPException(400, "unknown voice")
442
- if not 0 <= phrase_id < len(PHRASES):
443
- raise HTTPException(404, "unknown phrase")
444
  if app.state.tts is None:
445
  raise HTTPException(503, "tts not configured")
446
  try:
447
- data, used = app.state.tts.wav(PHRASES[phrase_id]["variants"][0][0], voice)
448
  except TTSUnavailable as e:
449
  raise HTTPException(503, str(e))
450
  tts = app.state.tts # debug: lets the page show which voice spoke
@@ -456,12 +577,10 @@ def create_app(scorer: Scorer | None = None, tts: SawtakTTS | None = None,
456
  @app.get("/api/prompt-audio/{phrase_id}", dependencies=members)
457
  def prompt_audio(phrase_id: int, engine: str = "gtts"):
458
  """The Hebrew prompt read aloud (edge-tts or gTTS). 503 tells the page to stay silent."""
459
- if not 0 <= phrase_id < len(PHRASES):
460
- raise HTTPException(404, "unknown phrase")
461
  if engine not in ENGINES:
462
  raise HTTPException(400, "unknown engine")
463
  try:
464
- phrase = PHRASES[phrase_id]
465
  data, used = hebrew_mp3(phrase.get("he_say") or phrase["he"], engine) # pointed where the plain text is misread
466
  except PromptTTSUnavailable as e:
467
  raise HTTPException(503, str(e))
@@ -484,8 +603,7 @@ def create_app(scorer: Scorer | None = None, tts: SawtakTTS | None = None,
484
  @app.post("/api/score")
485
  def score(tasks: BackgroundTasks, phrase_id: int = Form(...), audio: UploadFile = File(...),
486
  user: dict | None = Depends(signed_in)):
487
- if not 0 <= phrase_id < len(PHRASES):
488
- raise HTTPException(404, "unknown phrase")
489
  data = audio.file.read(MAX_UPLOAD + 1)
490
  if len(data) > MAX_UPLOAD:
491
  raise HTTPException(413, "recording too long")
@@ -495,12 +613,11 @@ def create_app(scorer: Scorer | None = None, tts: SawtakTTS | None = None,
495
  raise HTTPException(400, "could not decode audio")
496
  if wav.size < 16_000 * 0.3:
497
  return {"error": "too_short", "message": "ืœื ื ืฉืžืข ื“ื™ื‘ื•ืจ. ื ืกื• ืฉื•ื‘, ืงืจื•ื‘ ื™ื•ืชืจ ืœืžื™ืงืจื•ืคื•ืŸ."}
498
- phrase = PHRASES[phrase_id]
499
  refs = app.state.refs.get(phrase_id, phrase) if app.state.refs else []
500
  result = app.state.scorer.score(wav, phrase, refs)
501
  if user and result.get("score") is not None: # the student's progress; sent after the answer
502
  tasks.add_task(app.state.auth.record, user["token"], {
503
- "cat": phrase["cat"], "phrase": phrase["he"], "score": round(result["score"]),
504
  "unrelated": bool(result.get("unrelated"))})
505
  return result
506
 
 
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)
 
56
  LESSON_TOPICS = {l: sum(c["lesson"] == l for c in CATEGORIES) for l in READY_LESSONS} # a video's place is 0..this many
57
 
58
 
59
+ def placed(rows: list[dict], lesson: str) -> list[dict]:
60
+ """A lesson's videos, or its texts, in their order on the path, each with its place: `pos` of the lesson's own
61
+ topics stand before it (one without a place, or past the topics the lesson has now, stands after them all), and
62
+ `ord` is its turn among the videos and texts of that place."""
63
  n = LESSON_TOPICS[lesson]
64
+ mine = [{**v, "pos": n if v.get("pos") is None else max(0, min(n, v["pos"])), "ord": v.get("ord") or 0}
65
+ for v in rows if v["lesson"] == lesson]
66
+ return sorted(mine, key=lambda v: (v["pos"], v["ord"], v["id"]))
67
+
68
+
69
+ # A text the teacher added (see texts.py) is a topic, "t<its id>", and each of its lines a phrase whose id is past the
70
+ # bank's: TEXT_BASE + the text's id * TEXT_SPAN + the line's number, so it holds as texts come and go.
71
+ TEXT_BASE, TEXT_SPAN = 1_000_000, 1000
72
+ MAX_LINES, MAX_LINE = 200, 300
73
+ VOICE_NAMES = [re.sub(r"[\u0591-\u05c7]", "", name) for name in VOICES] # as a topic names its voices: without the points
74
+ CREATE_TEXTS = ("create table public.texts (id bigint generated always as identity primary key, lesson text not null, "
75
+ "title text not null, voices text[] not null default '{}', lines jsonb not null, pos int, "
76
+ "ord int not null default 0, created_at timestamptz not null default now()); "
77
+ "alter table public.texts enable row level security;")
78
+ _BUILT: dict[tuple[int, int], tuple[list[dict], list[str]]] = {}
79
+
80
+
81
+ def built(row: dict) -> tuple[list[dict], list[str]]:
82
+ """A text's lines as phrases, and its words that were read by rule (see `texts.text_phrases`); built once."""
83
+ key = (row["id"], hash(str(row["lines"])))
84
+ if key not in _BUILT:
85
+ _BUILT[key] = text_phrases(f"t{row['id']}", row["lines"])
86
+ return _BUILT[key]
87
+
88
+
89
+ def text_bank(rows: list[dict]) -> dict[int, dict]:
90
+ """{phrase id: phrase} of the texts' lines."""
91
+ return {TEXT_BASE + r["id"] * TEXT_SPAN + k: p for r in rows for k, p in enumerate(built(r)[0])}
92
  TOPIC_LESSON = {c["id"]: c["lesson"] for c in CATEGORIES} # a topic's lesson: homework is a topic of the class's lessons
93
  MIGRATE_CLASSES = ("alter table public.classes add column if not exists nicknames jsonb not null default '{}', "
94
  "add column if not exists lessons text[] not null default '{}', "
 
100
  return [l for l in ALL_LESSONS if l in c["lessons"]] or ALL_LESSONS
101
 
102
 
103
+ def homework_of(c: dict, topics: dict[str, str] = TOPIC_LESSON) -> dict:
104
  """A class's homework: the topic it practises now (a category id, e.g. the conversation "l2-talk"; "" when none
105
  is set) and the day it is due (ISO date, or None). A topic of a lesson the class no longer studies, or one the
106
+ course no longer has, is no homework. `topics` is every topic's lesson: the course's, and the teacher's texts'."""
107
  topic = c.get("homework") or ""
108
+ return {"homework": topic, "due": c.get("due") or None} if topics.get(topic) in lessons_of(c) \
109
  else {"homework": "", "due": None}
110
 
111
 
 
157
  return datetime.strptime(stamp[:19], "%Y-%m-%dT%H:%M:%S").replace(tzinfo=timezone.utc)
158
 
159
 
160
+ def summary(rows: list[dict], texts: dict[int, dict] | None = None) -> dict:
161
  """One student's attempts summed up: best score and tries per phrase id, recordings (all, and of the last
162
  7 days), days practised, time of the last one. A recording that did not match the sentence on the screen
163
  (unrelated) is a recording, on its day, but no try and no score: such ones are counted per phrase id in "missed",
164
  and all together in "unmatched"."""
165
  shown = {c["id"] for c in CATEGORIES}
166
  ids = {(p["cat"], p["he"]): i for i, p in enumerate(PHRASES) if p["cat"] in shown}
167
+ ids.update({(p["cat"], p["key"]): i for i, p in (texts or {}).items()}) # the lines of the teacher's texts (see `text_bank`)
168
  best: dict[int, int] = {}
169
  tries: dict[int, int] = {}
170
  missed: dict[int, int] = {}
 
232
 
233
  members = [Depends(signed_in)]
234
 
235
+ def text_rows() -> list[dict]:
236
+ """The teacher's texts in the lessons the path shows. None without sign-in, or when they cannot be read."""
237
+ a: SupabaseAuth | None = app.state.auth
238
+ if a is None:
239
+ return []
240
+ try:
241
+ return [r for r in a.texts() if r["lesson"] in READY_LESSONS]
242
+ except AuthUnavailable as e:
243
+ log.warning("texts not read: %s", e)
244
+ return []
245
+
246
+ def topics() -> dict[str, str]:
247
+ """Every topic's lesson: the course's topics, and the teacher's texts."""
248
+ return {**TOPIC_LESSON, **{f"t{r['id']}": r["lesson"] for r in text_rows()}}
249
+
250
+ def phrase_of(phrase_id: int) -> dict:
251
+ """A phrase of the bank, or a line of a teacher's text; 404 for any other id."""
252
+ if 0 <= phrase_id < len(PHRASES):
253
+ return PHRASES[phrase_id]
254
+ phrase = text_bank(text_rows()).get(phrase_id) if phrase_id >= TEXT_BASE else None
255
+ if phrase is None:
256
+ raise HTTPException(404, "unknown phrase")
257
+ return phrase
258
+
259
  @app.get("/")
260
  def index():
261
  html = (STATIC / "index.html").read_text(encoding="utf-8")
 
274
  lessons = ALL_LESSONS if not mine or user["teacher"] else \
275
  [l for l in ALL_LESSONS if any(l in lessons_of(c) for c in mine)]
276
  return {"email": user["email"] if user else "", "teacher": bool(user and user["teacher"]),
277
+ "classes": [{"name": c["name"], "lessons": lessons_of(c), **homework_of(c, topics())} for c in mine],
278
  "lessons": lessons}
279
 
280
  @app.get("/api/progress")
281
  def progress(user: dict | None = Depends(signed_in)):
282
  """The signed-in student's progress: best score and tries per phrase id, recordings, days practised."""
283
+ s = summary(app.state.auth.attempts(user["token"]) if user else [], text_bank(text_rows()))
284
  return {k: s[k] for k in ("best", "tries", "recordings", "days")}
285
 
286
  @app.get("/api/class")
 
301
  for e in c["emails"]:
302
  member.setdefault(e, {})[c["name"]] = c["nicknames"].get(e, "")
303
  opened = {c["name"]: utc(c["created_at"]) for c in classes if c.get("created_at")}
304
+ bank, lesson_of = text_bank(text_rows()), topics()
305
 
306
  def student(email: str, name: str, joined: bool, mine: list[dict]) -> dict:
307
  into = member.get(email.lower(), {})
308
+ 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}
309
+ return {"email": email, "name": name, "joined": joined, "classes": into, "since": since, **summary(mine, bank)}
310
 
311
  students = [student(u["email"], u["name"], True, by.get(u["id"], []))
312
  for u in users if not classes or u["email"].lower() in member]
313
  missing = member.keys() - {s["email"].lower() for s in students}
314
  students += [student(e, "", False, []) for e in sorted(missing)]
315
+ return {"classes": [{**c, "lessons": lessons_of(c), **homework_of(c, lesson_of)} for c in classes], "students": students}
316
 
317
  def class_store_error(e: AuthUnavailable) -> str:
318
  """The teacher's message when a class cannot be written; a 404 means Supabase has no `classes` table."""
 
338
  raise HTTPException(400, "ื‘ื—ืจื• ืœืคื—ื•ืช ืฉื™ืขื•ืจ ืื—ื“ ืœื›ื™ืชื”")
339
  lessons = [l for l in ALL_LESSONS if l in map(str, lessons)]
340
  homework, due = str(body.get("homework") or ""), str(body.get("due") or "") or None
341
+ if homework and topics().get(homework) not in lessons:
342
  raise HTTPException(400, "ืฉื™ืขื•ืจื™ ื”ื‘ื™ืช ื”ื ื ื•ืฉื ืžืื—ื“ ืžืฉื™ืขื•ืจื™ ื”ื›ื™ืชื”")
343
  try:
344
  due = date.fromisoformat(due).isoformat() if homework and due else None # no date without homework
 
378
  def videos(user: dict | None = Depends(signed_in)):
379
  """The lesson videos, each lesson's in its order on the path: id, lesson, title, url (the Vimeo link, for a teacher only), embed
380
  (its player, for the page's frame) and pos (how many of the lesson's own topics stand before it, see
381
+ `placed`) and ord. A student gets those of their classes' lessons; a teacher, and an account in no
382
  class, every one. One whose lesson the course no longer has is left out."""
383
  if not user:
384
  return {"videos": []}
 
392
  # the link itself goes to teachers only: a student's page gets the player's address, which it cannot do without
393
  return {"videos": [{"id": v["id"], "lesson": v["lesson"], "title": v["title"],
394
  **({"url": v["url"]} if user["teacher"] else {}),
395
+ "embed": vimeo_embed(v["url"]), "pos": v["pos"], "ord": v["ord"]}
396
+ for l in lessons for v in placed(rows, l)]}
397
 
398
  def video_store_error(e: AuthUnavailable) -> str:
399
  """The teacher's message when a video cannot be written; a 404 means Supabase has no `videos` table."""
 
417
  if not url:
418
  raise HTTPException(400, "ื–ื” ืœื ืงื™ืฉื•ืจ ืœืกืจื˜ื•ืŸ ื‘-Vimeo. ื”ื“ื‘ื™ืงื• ืงื™ืฉื•ืจ ื›ืžื• https://vimeo.com/1233611297/d46ac373c8")
419
  try:
420
+ a.add_video(lesson, title, url, LESSON_TOPICS[lesson], next_ord(a, lesson))
 
421
  except AuthUnavailable as e:
422
  raise HTTPException(503, video_store_error(e))
423
  return {"ok": True}
424
 
425
+ def next_ord(a: SupabaseAuth, lesson: str) -> int:
426
+ """The turn of a new video or text: after the lesson's topics and whatever was added to it before."""
427
+ return max((r.get("ord") or 0 for r in a.videos(fresh=True) + a.texts(fresh=True) if r["lesson"] == lesson), default=0) + 1
428
+
429
+ @app.put("/api/content/order")
430
+ def order_content(body: dict = Body(...), a: SupabaseAuth = Depends(teacher_only)):
431
+ """Places what the teacher added to a lesson among its topics: {"lesson", "order": [{"kind": "video" or
432
+ "text", "id", "pos"}]}, every video and text of the lesson once, in their order on the path; `pos` is how
433
+ many of the lesson's own topics stand before it."""
434
  lesson, order = str(body.get("lesson", "")), body.get("order")
435
  if lesson not in READY_LESSONS or not isinstance(order, list):
436
  raise HTTPException(400, "unknown lesson")
437
  try:
438
+ places = [(str(o["kind"]), int(o["id"]), int(o["pos"])) for o in order]
439
  except (KeyError, TypeError, ValueError):
440
+ raise HTTPException(400, "each one needs a kind, an id and a place")
441
  try:
442
+ mine = {("video", v["id"]) for v in a.videos(fresh=True) if v["lesson"] == lesson} | \
443
+ {("text", t["id"]) for t in a.texts(fresh=True) if t["lesson"] == lesson}
444
+ if len(places) != len(mine) or {(kind, i) for kind, i, _ in places} != mine: # added or deleted meanwhile, in another tab
445
+ raise HTTPException(409, "ืชื•ื›ืŸ ื”ืฉื™ืขื•ืจ ื”ืฉืชื ื”. ืจืขื ื ื• ื•ื ืกื• ืฉื•ื‘")
446
+ if any(not 0 <= pos <= LESSON_TOPICS[lesson] for _, _, pos in places):
447
  raise HTTPException(400, "no such place in the lesson")
448
+ a.place([(kind + "s", i, pos, k) for k, (kind, i, pos) in enumerate(places)])
449
  except AuthUnavailable as e:
450
+ raise HTTPException(503, text_store_error(e) if "texts" in str(e) else video_store_error(e))
451
+ return {"ok": True}
452
+
453
+ @app.get("/api/texts")
454
+ def texts(user: dict | None = Depends(signed_in)):
455
+ """The teacher's texts as the page takes topics and phrases (see `/api/phrases`), for the lessons a video is
456
+ given for (see `videos`). "categories": a topic per text, laid out as a story: id ("t<n>"), name, lesson, story,
457
+ text (the text's own id), voices (a dialogue's two, by name), and pos and ord as a video has them; a teacher
458
+ also gets "guessed", the words that were read by rule. "phrases": the lines, in each text's order."""
459
+ if not user:
460
+ return {"categories": [], "phrases": []}
461
+ mine = user["classes"]
462
+ lessons = READY_LESSONS if not mine or user["teacher"] else \
463
+ [l for l in READY_LESSONS if any(l in lessons_of(c) for c in mine)]
464
+ rows = [r for l in lessons for r in placed(text_rows(), l)]
465
+ return {"categories": [{"id": f"t{r['id']}", "name": r["title"], "lesson": r["lesson"], "story": True, "text": r["id"],
466
+ **({"voices": r["voices"]} if r["voices"] else {}), "pos": r["pos"], "ord": r["ord"],
467
+ **({"guessed": built(r)[1]} if user["teacher"] else {})} for r in rows],
468
+ "phrases": [{"id": i, "cat": p["cat"], "he": p["he"], "tr": p["tr"], "ar": p["variants"][0][0], "seq": p["seq"]}
469
+ for i, p in text_bank(rows).items()]}
470
+
471
+ def text_store_error(e: AuthUnavailable) -> str:
472
+ """The teacher's message when a text cannot be written; a 404 means Supabase has no `texts` table."""
473
+ if "answered 404" in str(e):
474
+ return ("ื”ื˜ื‘ืœื” texts ืœื ืงื™ื™ืžืช ื‘-Supabase. ื”ืจื™ืฆื• ื‘-SQL Editor: "
475
+ f"{CREATE_TEXTS} ืื ื›ื‘ืจ ื ื•ืฆืจื”, ื”ืจื™ืฆื• ืฉื: notify pgrst, 'reload schema';")
476
+ return f"Supabase ืœื ื–ืžื™ืŸ: {e}"
477
+
478
+ @app.post("/api/texts")
479
+ def add_text(body: dict = Body(...), a: SupabaseAuth = Depends(teacher_only)):
480
+ """Adds a text to a lesson, after its topics and what was added before: {"lesson": the id of a ready lesson,
481
+ "title", "he": its lines in Hebrew, "tr": the same lines in Arabic written in Hebrew letters, "voices": a
482
+ dialogue's two voices by name (the odd lines', the even lines'); none for a story, which the student's own
483
+ voice reads}. Answers with "guessed": the words the course does not have, which were read by rule."""
484
+ lesson, title = str(body.get("lesson", "")), " ".join(str(body.get("title", "")).split())
485
+ if lesson not in READY_LESSONS:
486
+ raise HTTPException(400, "ื˜ืงืกื˜ ืžื•ืกื™ืคื™ื ืœืฉื™ืขื•ืจ ืžื•ื›ืŸ")
487
+ if not title or len(title) > MAX_TITLE:
488
+ raise HTTPException(400, f"ืœื˜ืงืกื˜ ืฆืจื™ืš ืฉื (ืขื“ {MAX_TITLE} ืชื•ื•ื™ื)")
489
+ voices = body.get("voices") or []
490
+ if not isinstance(voices, list) or voices and (len(voices) != 2 or not set(map(str, voices)) <= set(VOICE_NAMES)):
491
+ raise HTTPException(400, "ืœืฉื™ื—ื” ื‘ื•ื—ืจื™ื ืฉื ื™ ืงื•ืœื•ืช ืžื”ืจืฉื™ืžื”")
492
+ he, tr = ([" ".join(str(x).split()) for x in body.get(k) or []] if isinstance(body.get(k), list) else [] for k in ("he", "tr"))
493
+ if not he or not tr:
494
+ raise HTTPException(400, "ืฆืจื™ืš ืืช ื”ืฉื•ืจื•ืช ืคืขืžื™ื™ื: ื‘ืขื‘ืจื™ืช, ื•ื‘ืขืจื‘ื™ืช ื‘ืชืขืชื™ืง ืขื‘ืจื™")
495
+ if len(he) != len(tr):
496
+ raise HTTPException(400, f"ืžืกืคืจ ื”ืฉื•ืจื•ืช ืœื ื–ื”ื”: {len(he)} ื‘ืขื‘ืจื™ืช ื•-{len(tr)} ื‘ืขืจื‘ื™ืช")
497
+ if len(he) > MAX_LINES or any(len(x) > MAX_LINE for x in he + tr):
498
+ raise HTTPException(400, f"ื˜ืงืกื˜ ื”ื•ื ืขื“ {MAX_LINES} ืฉื•ืจื•ืช, ื•ืฉื•ืจื” ืขื“ {MAX_LINE} ืชื•ื•ื™ื")
499
+ for n, (h, t) in enumerate(zip(he, tr), 1):
500
+ if not h or not read_line(t)[0]:
501
+ raise HTTPException(400, f"ื‘ืฉื•ืจื” {n} ื—ืกืจ ื˜ืงืกื˜, ืื• ืฉื‘ืขืจื‘ื™ืช ืฉืœื” ืื™ืŸ ืื•ืชื™ื•ืช ืขื‘ืจื™ื•ืช")
502
+ try:
503
+ a.add_text(lesson, title, list(map(str, voices)), [[h, t] for h, t in zip(he, tr)], LESSON_TOPICS[lesson], next_ord(a, lesson))
504
+ except AuthUnavailable as e:
505
+ raise HTTPException(503, text_store_error(e))
506
+ return {"ok": True, "guessed": text_phrases("", [[h, t] for h, t in zip(he, tr)])[1]}
507
+
508
+ @app.delete("/api/texts/{text_id}")
509
+ def delete_text(text_id: int, a: SupabaseAuth = Depends(teacher_only)):
510
+ try:
511
+ a.delete_text(text_id)
512
+ except AuthUnavailable as e:
513
+ raise HTTPException(503, text_store_error(e))
514
  return {"ok": True}
515
 
516
  @app.delete("/api/videos/{video_id}")
 
561
  names = {i: n for n, i in VOICES.items()}
562
  if voice and voice not in names:
563
  raise HTTPException(400, "unknown voice")
564
+ text = phrase_of(phrase_id)["variants"][0][0]
 
565
  if app.state.tts is None:
566
  raise HTTPException(503, "tts not configured")
567
  try:
568
+ data, used = app.state.tts.wav(text, voice)
569
  except TTSUnavailable as e:
570
  raise HTTPException(503, str(e))
571
  tts = app.state.tts # debug: lets the page show which voice spoke
 
577
  @app.get("/api/prompt-audio/{phrase_id}", dependencies=members)
578
  def prompt_audio(phrase_id: int, engine: str = "gtts"):
579
  """The Hebrew prompt read aloud (edge-tts or gTTS). 503 tells the page to stay silent."""
580
+ phrase = phrase_of(phrase_id)
 
581
  if engine not in ENGINES:
582
  raise HTTPException(400, "unknown engine")
583
  try:
 
584
  data, used = hebrew_mp3(phrase.get("he_say") or phrase["he"], engine) # pointed where the plain text is misread
585
  except PromptTTSUnavailable as e:
586
  raise HTTPException(503, str(e))
 
603
  @app.post("/api/score")
604
  def score(tasks: BackgroundTasks, phrase_id: int = Form(...), audio: UploadFile = File(...),
605
  user: dict | None = Depends(signed_in)):
606
+ phrase = phrase_of(phrase_id)
 
607
  data = audio.file.read(MAX_UPLOAD + 1)
608
  if len(data) > MAX_UPLOAD:
609
  raise HTTPException(413, "recording too long")
 
613
  raise HTTPException(400, "could not decode audio")
614
  if wav.size < 16_000 * 0.3:
615
  return {"error": "too_short", "message": "ืœื ื ืฉืžืข ื“ื™ื‘ื•ืจ. ื ืกื• ืฉื•ื‘, ืงืจื•ื‘ ื™ื•ืชืจ ืœืžื™ืงืจื•ืคื•ืŸ."}
 
616
  refs = app.state.refs.get(phrase_id, phrase) if app.state.refs else []
617
  result = app.state.scorer.score(wav, phrase, refs)
618
  if user and result.get("score") is not None: # the student's progress; sent after the answer
619
  tasks.add_task(app.state.auth.record, user["token"], {
620
+ "cat": phrase["cat"], "phrase": phrase.get("key", phrase["he"]), "score": round(result["score"]),
621
  "unrelated": bool(result.get("unrelated"))})
622
  return result
623
 
app/texts.py ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Texts the teacher adds in the panel: a story or a dialogue, practised line by line like the course's conversation.
2
+
3
+ The teacher gives each line twice: in Hebrew, and in Arabic written in Hebrew letters, as the course writes it
4
+ (pointed, geresh for the sounds Hebrew lacks, ู‘ for doubling: ื›ึดึผื™ืฃ ื—ึทืืœึทื›ึผ). The scorer needs the line's phonemes
5
+ and the answer's voice needs it in Arabic letters, so each word is read here:
6
+ a word of the course (LEX in workbook.py), found by its transliteration, gets the course's own Arabic spelling and
7
+ accepted pronunciations. Dagesh, shva and the final letters' forms are not compared, and a word written without
8
+ points is found by its letters alone;
9
+ any other word is read by rule, letter by letter (`_guess`). Short vowels come from the points, so an unpointed
10
+ word that the course does not have is read badly. Such words are reported back to the teacher (`guessed`).
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import re
15
+
16
+ from .workbook import LEX, _variants
17
+
18
+ SHVA, DAGESH, SHADDA = "\u05b0", "\u05bc", "\u0651"
19
+ MARKS = re.compile("[\u05b0-\u05bc\u05c1\u05c2\u05c7\u0651]")
20
+ GERESH = "'\u05f3\u2019\u2018`\u00b4"
21
+ FINALS = {"ืš": "ื›", "ื": "ืž", "ืŸ": "ื ", "ืฃ": "ืค", "ืฅ": "ืฆ"}
22
+ VOWEL_OF = {"\u05b7": "a", "\u05b8": "a", "\u05b2": "a", "\u05b4": "i", "\u05bb": "u", "\u05b6": "e", "\u05b1": "e",
23
+ "\u05b5": "E", "\u05b9": "o", "\u05ba": "o", "\u05b3": "o", "\u05c7": "o"} # E: tsere, i alone and eห before ื™
24
+ # letter -> (phoneme, Arabic letter); ืง is the urban ส”, with q as a second reading
25
+ CONS = {"ื": ("ส”", "ุง"), "ื‘": ("b", "ุจ"), "ื’": ("g", "ุฌ"), "ื“": ("d", "ุฏ"), "ื”": ("h", "ู‡"), "ื•": ("w", "ูˆ"),
26
+ "ื–": ("z", "ุฒ"), "ื—": ("ฤง", "ุญ"), "ื˜": ("tหค", "ุท"), "ื™": ("j", "ูŠ"), "ื›": ("k", "ูƒ"), "ืœ": ("l", "ู„"),
27
+ "ืž": ("m", "ู…"), "ื ": ("n", "ู†"), "ืก": ("s", "ุณ"), "ืข": ("ส•", "ุน"), "ืค": ("f", "ู"), "ืฆ": ("sหค", "ุต"),
28
+ "ืง": ("ส”", "ู‚"), "ืจ": ("r", "ุฑ"), "ืฉ": ("สƒ", "ุด"), "ืช": ("t", "ุช")}
29
+ GERESHED = {"ื’": ("dส’", "ุฌ"), "ื—": ("x", "ุฎ"), "ืข": ("ษฃ", "ุบ"), "ื“": ("dหค", "ุถ"), "ื˜": ("รฐหค", "ุธ"), "ืช": ("t", "ุซ"),
30
+ "ื–": ("dส’", "ุฌ"), "ืฆ": ("sหค", "ุต")}
31
+ PUNCT_AR = {"?": "ุŸ", ",": "ุŒ", ";": "ุ›"}
32
+ Cluster = tuple[str, bool, str] # a letter, whether it has a geresh, its points
33
+
34
+
35
+ def _clusters(word: str) -> list[Cluster]:
36
+ """The word's letters, each with its geresh and points. A letter in brackets, the article's silent (ืœ), is left out."""
37
+ out: list[list] = []
38
+ for ch in re.sub(r"\([^)]*\)", "", word):
39
+ if "ื" <= ch <= "ืช":
40
+ out.append([FINALS.get(ch, ch), False, ""])
41
+ elif out and ch in GERESH:
42
+ out[-1][1] = True
43
+ elif out and MARKS.fullmatch(ch):
44
+ out[-1][2] += ch
45
+ return [(l, g, m) for l, g, m in out]
46
+
47
+
48
+ def _key(cl: list[Cluster], points: bool = True) -> str:
49
+ """What two spellings of one word share: the letters and their vowels, without dagesh (but the vav's) and shva.
50
+ The article's vowel is one, hiriq or tsere."""
51
+ def marks(k: int, letter: str, m: str) -> str:
52
+ keep = {"\u05b7" if c == "\u05b8" else c for c in m if c != SHVA and (c != DAGESH or letter == "ื•")}
53
+ if k == 0 and letter == "ื" and "\u05b4" in keep:
54
+ keep = keep - {"\u05b4"} | {"\u05b5"}
55
+ return "".join(sorted(keep))
56
+ return "".join(l + "'" * g + (marks(k, l, m) if points else "") for k, (l, g, m) in enumerate(cl))
57
+
58
+
59
+ def _lexicon() -> tuple[dict, dict]:
60
+ pointed, plain = {}, {}
61
+ for ar, (tr, ipas) in LEX.items():
62
+ cl = _clusters(tr)
63
+ entry = (ar.partition("#")[0], ipas)
64
+ pointed.setdefault(_key(cl), entry)
65
+ plain.setdefault(_key(cl, False), entry)
66
+ return pointed, plain
67
+
68
+
69
+ POINTED, PLAIN = _lexicon()
70
+
71
+
72
+ def _guess(cl: list[Cluster], silent_l: bool = False) -> tuple[str, list[str]]:
73
+ """(Arabic spelling, readings) of a word the course does not have, from its letters and points. `silent_l`: the
74
+ word was written with the article's (ืœ), so its first vowel is the article."""
75
+ phs: list[str] = []
76
+ ar = ""
77
+ n, i = len(cl), 0
78
+ bare = lambda c: not c[1] and not any(m in VOWEL_OF or m == SHADDA for m in c[2]) # no vowel of its own
79
+ pointed = any(m in VOWEL_OF for _, _, marks in cl for m in marks)
80
+ if n > 1 and cl[0][0] == "ื•" and bare(cl[0]) and (DAGESH in cl[0][2] or SHVA in cl[0][2]): # "and" on the word
81
+ phs, ar, i = ["u"], "ูˆ", 1
82
+ start, prev = i, None # prev: the vowel the letter before ended in
83
+ while i < n:
84
+ letter, geresh, marks = cl[i]
85
+ last, vowel = i == n - 1, next((VOWEL_OF[m] for m in marks if m in VOWEL_OF), None)
86
+ double = SHADDA in marks
87
+ i += 1
88
+ if bare((letter, geresh, marks)) and i - 1 > start: # a letter that only lengthens the vowel before it
89
+ long = None
90
+ if letter == "ื":
91
+ long, ar = ("a" if last else "aห"), ar + "ุง"
92
+ if prev:
93
+ phs.pop()
94
+ elif letter == "ื™" and (prev in ("i", "E") or not prev and last or not pointed and not last):
95
+ long, ar = ("eห" if prev == "E" else "i" if last else "iห"), ar + "ูŠ"
96
+ if prev:
97
+ phs.pop()
98
+ elif letter == "ื•" and not prev and (DAGESH in marks or not pointed and not last):
99
+ long, ar = ("u" if last else "uห"), ar + "ูˆ"
100
+ elif letter == "ื”" and last and (prev in ("a", "e", "E") or not pointed): # the feminine ending
101
+ ar += "ุฉ"
102
+ if not prev:
103
+ phs.append("a")
104
+ elif prev == "E":
105
+ phs[-1] = "e"
106
+ break
107
+ if long:
108
+ phs.append(long)
109
+ prev = None
110
+ continue
111
+ if letter == "ื•" and DAGESH in marks and double and not vowel and not prev: # ื•ึผู‘
112
+ phs += ["u", "w", "w"]
113
+ ar, prev = ar + "ูˆู‘", None
114
+ continue
115
+ if letter == "ื•" and vowel == "o" and not double and not prev and i - 1 > start: # ื•ึน
116
+ phs.append("o" if last else "oห")
117
+ ar, prev = ar + "ูˆ", None
118
+ continue
119
+ ph, ar_letter = (GERESHED if geresh and letter in GERESHED else CONS)[letter]
120
+ if letter == "ื" and i - 1 == start and vowel in ("i", "a", "E") and i < n and (
121
+ cl[i][0] == "ืœ" and bare(cl[i]) and i + 1 < n or silent_l): # the article: ืึดืœึฐ, or ืึด(ืœ) before a doubled letter
122
+ phs.append("i")
123
+ ar += "ุงู„"
124
+ if cl[i][0] == "ืœ" and bare(cl[i]):
125
+ phs.append("l")
126
+ i += 1
127
+ prev = None
128
+ continue
129
+ phs += [ph, ph] if double else [ph]
130
+ ar += ("ุง" if i - 1 == start else "ุฃ") if letter == "ื" else ar_letter + (SHADDA if double else "")
131
+ prev = vowel
132
+ if vowel:
133
+ phs.append(("e" if last else "i") if vowel == "E" else vowel) # a tsere is i inside the word, e at its end
134
+ main = " ".join(phs)
135
+ return ar, [main] + ([main.replace("ส”", "q") if not cl[start][0] == "ื" else "ส”" + main[1:].replace("ส”", "q")]
136
+ if any(l == "ืง" for l, _, _ in cl) else [])
137
+
138
+
139
+ def _word(token: str) -> tuple[str, list[str], bool] | None:
140
+ """(Arabic, readings, whether the course has the word) of one written word; None when it has no letters."""
141
+ cl = _clusters(token)
142
+ if not cl:
143
+ return None
144
+ tail = "".join(PUNCT_AR.get(c, c) for c in re.search(r"[?!.,;:]*$", token)[0])
145
+ pointed = any(m in VOWEL_OF for _, _, marks in cl for m in marks)
146
+ for cut, pre_ar, pre_ipa in ((0, "", ""), (1, "ูˆ", "u ")): # the word itself, then "and" written on it
147
+ if cut and not (len(cl) > 1 and cl[0][0] == "ื•" and not cl[0][1] and not any(m in VOWEL_OF for m in cl[0][2])):
148
+ break
149
+ hit = POINTED.get(_key(cl[cut:])) if pointed else PLAIN.get(_key(cl[cut:], False))
150
+ if hit:
151
+ return pre_ar + hit[0] + tail, [pre_ipa + ipa for ipa in hit[1]], True
152
+ rest = cl[2:] if len(cl) > 2 and cl[0][0] == "ื" and cl[1][0] == "ืœ" and not any(m in VOWEL_OF for m in cl[1][2]) else \
153
+ cl[1:] if len(cl) > 1 and cl[0][0] == "ื" and "(ืœ)" in token else None
154
+ hit = rest and (POINTED.get(_key(rest)) if pointed else PLAIN.get(_key(rest, False)))
155
+ if hit and not hit[0].startswith("ุงู„"): # the article on a word of the course: ืึดืœึฐื‘ึตึผื™ืช, ืึด(ืœ)ืกึทู‘ื™ึทึผืืจึทื”
156
+ said = "i l " if rest is cl[2:] or len(rest) == len(cl) - 2 else "i "
157
+ double = lambda ipa: ipa if said == "i l " else f"{ipa.split()[0]} {ipa}"
158
+ return "ุงู„" + hit[0] + tail, [said + double(ipa) for ipa in hit[1]], True
159
+ ar, ipas = _guess(cl, "(ืœ)" in token)
160
+ return (ar + tail, ipas, False) if ipas[0] else None
161
+
162
+
163
+ def read_line(tr: str) -> tuple[list[tuple[str, str, list[str]]], list[str]]:
164
+ """A line of Arabic in Hebrew letters as the words of a phrase, (Arabic, transliteration, readings) each, and
165
+ the words that were read by rule, as written."""
166
+ words, guessed = [], []
167
+ for token in tr.split():
168
+ word = _word(token)
169
+ if word is None: # a dash, a number
170
+ continue
171
+ ar, ipas, known = word
172
+ words.append((ar, token, ipas))
173
+ if not known:
174
+ guessed.append(token.strip("?!.,;:\"()"))
175
+ return words, guessed
176
+
177
+
178
+ def text_phrases(cat: str, lines: list[list[str]]) -> tuple[list[dict], list[str]]:
179
+ """A text's lines ([Hebrew, transliteration] each) as phrases in the format of phrases.py, in the text's order,
180
+ and its words that were read by rule. `key` is what a recording of the line is kept under: the Hebrew, numbered
181
+ from its second appearance in the text ("ื›ืŸ (2)"), so that two lines with the same Hebrew stay apart."""
182
+ out, guessed, seen = [], [], {}
183
+ for seq, (he, tr) in enumerate(lines, 1):
184
+ words, new = read_line(tr)
185
+ guessed += [w for w in new if w not in guessed]
186
+ seen[he] = seen.get(he, 0) + 1
187
+ out.append(dict(cat=cat, he=he, tr=tr, variants=_variants(words), seq=seq,
188
+ key=he if seen[he] == 1 else f"{he} ({seen[he]})"))
189
+ return out, guessed
static/index.html CHANGED
@@ -273,7 +273,15 @@ body:not(.manage) #manage,body.manage #wrap>header,body.manage #path,body.manage
273
  .clist{list-style:none;margin:10px 0;padding:0}
274
  .crow{display:grid;grid-template-columns:2em 1fr auto;gap:4px 10px;align-items:center;padding:8px 0;border-top:1px solid var(--line)}
275
  .crow>i{font:700 14px/1 var(--f-body);color:var(--muted);text-align:center;font-style:normal}
276
- .crow.video>i{color:var(--olive)}
 
 
 
 
 
 
 
 
277
  .crow .two{display:flex;flex-direction:column;gap:2px;min-width:0;overflow-wrap:anywhere}
278
  .crow small{color:var(--muted);font-size:13px}
279
  .crow>small{justify-self:end}
@@ -534,7 +542,7 @@ body.quiet :is(#mic,#playMine,#driveBtn),body.driving :is(#quietBtn,#heBtn,.micl
534
  <section class="wrap" id="manage" aria-labelledby="mTitle">
535
  <div class="roundbar"><h1 class="mtitle" id="mTitle">ื ื™ื”ื•ืœ</h1><span class="sep"></span><button class="btn" id="mRefresh">ืจืขื ื•ืŸ</button><button class="btn primary" id="mPractice">ืœืชืจื’ื•ืœ</button></div>
536
  <div class="sub" id="mState" aria-live="polite"></div>
537
- <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>
538
  <div id="mClasses"></div>
539
  <div id="mContent"></div>
540
  <div class="tabs" id="mTabs" role="tablist" aria-label="ื›ื™ืชื•ืช" hidden></div>
@@ -758,14 +766,26 @@ const STEP=108, SWAY=[0,.7,1,.7,0,-.7,-1,-.7]; // the road: the way down from
758
  let drawnW=0, nowWatch=null;
759
  /* A lesson's videos (the teacher adds them in the panel's content part) stand on the path among its topics, where the
760
  teacher put them. A video opens in a box over the page; the ones already opened are marked, on this device only. */
761
- let VIDEOS=[], watched=store.get("ihki.watched",{}); // {id, lesson, title, url, embed, pos} of the student's lessons, in the path's order; {video id: 1}
762
- // a lesson's topics and videos in the path's order: {c, i} is its i-th topic, {v} a video, which has `pos` topics before it
763
- const lessonItems=(cats,vids)=>[...cats.flatMap((c,i)=>[...vids.filter(v=>v.pos===i).map(v=>({v})),{c,i}]),...vids.filter(v=>v.pos>=cats.length).map(v=>({v}))];
764
- async function loadVideos(){
 
 
 
 
 
 
765
  if(!sb) return;
766
  try{
767
- const res=await api("/api/videos"); if(!res.ok) return;
768
- VIDEOS=(await res.json()).videos||[];
 
 
 
 
 
 
769
  if(PHRASES.length&&home&&!document.body.classList.contains("manage")) drawPath(true);
770
  }catch{}
771
  }
@@ -798,7 +818,7 @@ function drawPath(stay){
798
  const b=mark("chapter soon",""); b.style.top=y+"px"; b.append(mark("",lessonsWord(run)),mark("","ื‘ืงืจื•ื‘","small")); box.append(b);
799
  y+=52+28; continue;
800
  }
801
- const cats=CATS.filter(c=>c.lesson===l.id), parts=cats.map(c=>tally(listed.filter(p=>p.cat===c.id)));
802
  const whole=tally(listed.filter(p=>cats.some(c=>c.id===p.cat))), now=!whole.over&&next;
803
  const todo=Math.max(0,parts.findIndex(t=>!t.over)); // the topic the banner opens
804
  if(now) next=false;
@@ -813,8 +833,7 @@ function drawPath(stay){
813
  label.className="label"; label.style.setProperty("--w",Math.min(150,w/2-46+(right?-x:x))+"px");
814
  return [x,label];
815
  };
816
- const vids=VIDEOS.filter(v=>v.lesson===l.id), items=lessonItems(cats,vids);
817
- items.forEach(({c,i,v},at)=>{
818
  if(v){
819
  const seen=!!watched[v.id], [b,dot]=ball({over:seen},false), [x,label]=seat(b,at);
820
  b.classList.add("video"); dot.textContent="โ–ถ\uFE0E"; if(seen) dot.before(mark("badge","โœ“"));
@@ -823,9 +842,9 @@ function drawPath(stay){
823
  b.onclick=()=>playVideo(v); box.append(b);
824
  stops.push({x,y,went:seen}); y+=STEP; return;
825
  }
826
- const t=parts[i], cur=now&&i===todo, [b,dot]=ball(t,cur), [x,label]=seat(b,at);
827
  const mine=!!hw&&c===hw.c; // the homework topic: its bubble counts the days left
828
- dot.textContent=c.story?"๐Ÿ’ฌ":i+1; // the number stays; a finished topic gets a badge, the one to do now and the homework a bubble
829
  if(t.over) dot.before(mark("badge",t.gold?"โ˜…":"โœ“"));
830
  else if(cur||mine){
831
  const tag=mark("tag",mine?"":t.done?"ื”ืžืฉืš":"ื”ืชื—ื™ืœื•");
@@ -1721,7 +1740,7 @@ async function loadManage(){
1721
  const detail=(await res.json().catch(()=>({}))).detail||res.status;
1722
  state.textContent=res.status===403?"ื”ืคืื ืœ ืคืชื•ื— ืœืžื•ืจื™ื ื‘ืœื‘ื“.":`ื ืชื•ื ื™ ื”ืชืœืžื™ื“ื™ื ืœื ื–ืžื™ื ื™ื ื›ืจื’ืข (${detail}).`; return;
1723
  }
1724
- CLASS=await res.json(); await loadVideos();
1725
  }catch{ state.textContent="ื”ืฉืจืช ืœื ื–ืžื™ืŸ."; return; }
1726
  state.textContent=""; drawManage();
1727
  }
@@ -1771,10 +1790,14 @@ function drawClasses(classes){
1771
  }
1772
  }
1773
  /* The content part: every level, its lessons, and each lesson's topics as the path shows them: the course's own, and among
1774
- them the videos the teacher added (a name and a Vimeo link each). A video is added under its lesson, at its end; the
1775
- arrows on its row move it up and down the lesson, past a topic or another video, and it is deleted there too. */
 
 
 
1776
  function drawContent(){
1777
  const box=$("mContent"), listed=listedPhrases(); box.innerHTML="";
 
1778
  for(const g of byLevel(ALL_LESSONS)){
1779
  box.append(mark("clevel",g.level.name,"h2"));
1780
  for(let k=0;k<g.lessons.length;k++){
@@ -1783,69 +1806,98 @@ function drawContent(){
1783
  const run=[l]; while(g.lessons[k+1]&&g.lessons[k+1].soon) run.push(g.lessons[++k]);
1784
  box.append(mark("csoon",`${lessonsWord(run)} ยท ื‘ืงืจื•ื‘`,"p")); continue;
1785
  }
1786
- const cats=ALL_CATS.filter(c=>c.lesson===l.id), vids=VIDEOS.filter(v=>v.lesson===l.id);
1787
  const card=mark("card",""), top=mark("chead",""), name=mark("",l.name,"h2"), list=mark("clist","","ol");
1788
- name.append(mark("",[`${cats.length} ื ื•ืฉืื™ื`,vids.length&&`${vids.length} ืกืจื˜ื•ื ื™ื`].filter(Boolean).join(" ยท "),"small")); top.append(name);
1789
- const items=lessonItems(cats,vids);
1790
- items.forEach(({c,i,v},at)=>{
1791
- if(c){
1792
- const row=mark("crow","","li"), n=listed.filter(p=>p.cat===c.id).length;
1793
- row.append(mark("",c.story?"๐Ÿ’ฌ":i+1,"i"),mark("",c.name,"b"),mark("",`${c.story?"ืฉื™ื—ื”":"ืชืจื’ื•ืœ"} ยท ${n} ${c.unit==="ืžื™ืœื”"?"ืžื™ืœื™ื":c.unit==="ืคื•ืขืœ"?"ืคืขืœื™ื":"ืžืฉืคื˜ื™ื"}`,"small")); list.append(row); return;
 
 
 
 
 
 
 
 
 
 
 
1794
  }
1795
- const row=mark("crow video","","li"), text=mark("two",""), title=mark("","","b"), t=document.createElement("bdi"), link=document.createElement("small"), acts=mark("acts","");
1796
- row.dataset.id=v.id;
1797
- const up=mark("btn move","โ†‘","button"), down=mark("btn move","โ†“","button"), see=mark("btn","ืฆืคื™ื™ื”","button"), del=mark("btn danger","ืžื—ื™ืงื”","button");
1798
- t.textContent=v.title; title.append(t); link.dir="ltr"; link.textContent=v.url.replace("https://",""); text.append(title,link);
1799
  up.title="ื”ื–ื–ื” ืœืžืขืœื”: ืžื•ืงื“ื ื™ื•ืชืจ ื‘ืฉื™ืขื•ืจ"; down.title="ื”ื–ื–ื” ืœืžื˜ื”: ืžืื•ื—ืจ ื™ื•ืชืจ ื‘ืฉื™ืขื•ืจ";
1800
- up.setAttribute("aria-label",`${up.title}, ${v.title}`); down.setAttribute("aria-label",`${down.title}, ${v.title}`);
1801
  up.disabled=!at; down.disabled=at===items.length-1;
1802
- up.onclick=()=>moveVideo(l,items,at,-1,list); down.onclick=()=>moveVideo(l,items,at,1,list);
1803
- see.onclick=()=>playVideo(v,true); del.onclick=()=>deleteVideo(v);
1804
- acts.append(up,down,see,del); row.append(mark("","โ–ถ\uFE0E","i"),text,acts); list.append(row);
 
1805
  });
1806
- const add=document.createElement("details"), form=document.createElement("form"), field=(label,name,attrs)=>{
1807
- const lab=mark("",label,"label"), inp=Object.assign(document.createElement("input"),{name,required:true,autocomplete:"off",...attrs}); lab.append(inp); return lab; };
1808
- const row=mark("row",""), msg=mark("msg","");
1809
- add.className="vadd"; add.append(mark("btn","+ ื”ื•ืกืคืช ืกืจื˜ื•ืŸ","summary"),form); form.className="cform"; msg.setAttribute("role","alert");
1810
- row.append(mark("btn primary","ื”ื•ืกืคื”","button"),msg);
1811
- form.append(field("ืฉื ื”ืกืจื˜ื•ืŸ","title",{maxLength:80,placeholder:"ืœืžืฉืœ: ื”ืกื‘ืจ ืขืœ ื”ื˜ื™ื™ืช ื”ืคื•ืขืœ"}),
1812
- field("ืงื™ืฉื•ืจ ืœ-Vimeo","url",{inputMode:"url",placeholder:"https://vimeo.com/1233611297/d46ac373c8"}),
1813
- mark("sub","ื”ืกืจื˜ื•ืŸ ื™ื•ืคื™ืข ืœืชืœืžื™ื“ื™ื ื‘ืžืกืœื•ืœ ื›ื ื•ืฉื ืฉืœ ื”ืฉื™ืขื•ืจ. ื”ื•ื ื ื•ืกืฃ ื‘ืกื•ืฃ ื”ืฉื™ืขื•ืจ, ื•ื‘ื—ื™ืฆื™ื ืฉื‘ืฉื•ืจื” ืฉืœื• ืžื–ื™ื–ื™ื ืื•ืชื• ืœืžืงื•ืžื•.","small"),row);
1814
- form.onsubmit=e=>{ e.preventDefault(); addVideo(l,form,msg); };
1815
- card.append(top,list,add); box.append(card);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1816
  }
1817
  }
1818
  }
1819
- async function addVideo(l,form,msg){
1820
- const buttons=form.querySelectorAll("button"); msg.textContent=""; buttons.forEach(b=>b.disabled=true);
1821
- try{
1822
- const res=await api("/api/videos",{method:"POST",headers:{"Content-Type":"application/json"},
1823
- body:JSON.stringify({lesson:l.id,title:form.elements.title.value,url:form.elements.url.value})});
1824
- if(res.ok){ await loadVideos(); drawContent(); return; }
1825
- msg.textContent=(await res.json().catch(()=>({}))).detail||`ื”ื”ื•ืกืคื” ื ื›ืฉืœื” (${res.status})`;
1826
- }catch{ msg.textContent="ื”ืฉืจืช ืœื ื–ืžื™ืŸ."; }
1827
- buttons.forEach(b=>b.disabled=false);
1828
- }
1829
- async function moveVideo(l,items,at,step,list){ // the video changes places with its neighbour, a topic or another video
1830
- const to=[...items]; [to[at],to[at+step]]=[to[at+step],to[at]];
1831
  let topics=0; const order=[];
1832
- for(const it of to){ if(it.c) topics++; else order.push({id:it.v.id,pos:topics}); }
1833
  list.querySelectorAll("button").forEach(b=>b.disabled=true);
1834
  try{
1835
- const res=await api("/api/videos/order",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({lesson:l.id,order})});
1836
- if(!res.ok) alert((await res.json().catch(()=>({}))).detail||`ื”ื”ื–ื–ื” ื ื›ืฉืœื” (${res.status})`);
1837
  }catch{ alert("ื”ืฉืจืช ืœื ื–ืžื™ืŸ."); }
1838
- await loadVideos(); drawContent();
1839
- const moved=[...$("mContent").querySelectorAll(".crow.video")].find(r=>r.dataset.id==items[at].v.id); // the keyboard stays on the video that moved
1840
  const again=moved&&[...moved.querySelectorAll(".move")].find((b,k)=>k===(step<0?0:1)&&!b.disabled)||moved&&moved.querySelector(".move:not(:disabled)"); if(again) again.focus({preventScroll:true});
1841
  }
1842
- async function deleteVideo(v){
1843
- if(!confirm(`ืœืžื—ื•ืง ืืช ื”ืกืจื˜ื•ืŸ ${v.title}? ื”ื•ื ื™ื™ืจื“ ืžื”ืžืกืœื•ืœ ืฉืœ ื”ืชืœืžื™ื“ื™ื.`)) return;
1844
  try{
1845
- const res=await api(`/api/videos/${v.id}`,{method:"DELETE"});
1846
- if(!res.ok) alert((await res.json().catch(()=>({}))).detail||`ื”ืžื—ื™ืงื” ื ื›ืฉืœื” (${res.status})`);
1847
  }catch{ alert("ื”ืฉืจืช ืœื ื–ืžื™ืŸ."); }
1848
- await loadVideos(); drawContent();
1849
  }
1850
  async function deleteClass(c){
1851
  if(!confirm(`ืœืžื—ื•ืง ืืช ื”ื›ื™ืชื” ${c.name}? ื”ืชืœืžื™ื“ื™ื ืฉืœื” ืœื ื™ื•ื›ืœื• ืœื”ื™ื›ื ืก ืขื•ื“. ื”ื”ืงืœื˜ื•ืช ื•ื”ื”ืชืงื“ืžื•ืช ืฉืœื”ื ื ืฉืžืจื•ืช.`)) return;
@@ -2240,7 +2292,7 @@ if(AUTH_URL){
2240
  if(MY_CLASSES.length===1) MY_CLASS=mine[0];
2241
  else{ const last=MY_CLASSES.find(c=>c.name===store.get("ihki.class","")); if(last) useClass(last); } // the class practised in last
2242
  start.hidden=!ok||teacher; roles.hidden=$("toManage").hidden=!teacher; denied.hidden=ok;
2243
- if(ok){ (teacher?$("practiceBtn"):start).focus({preventScroll:true}); loadProgress().then(()=>{ if(PHRASES.length&&$("wrap").inert) startCat(); }); loadVideos(); }
2244
  },0);
2245
  });
2246
  }
 
273
  .clist{list-style:none;margin:10px 0;padding:0}
274
  .crow{display:grid;grid-template-columns:2em 1fr auto;gap:4px 10px;align-items:center;padding:8px 0;border-top:1px solid var(--line)}
275
  .crow>i{font:700 14px/1 var(--f-body);color:var(--muted);text-align:center;font-style:normal}
276
+ .crow.added>i{color:var(--olive)}
277
+ .crow small.guess{color:var(--amber)}
278
+ .cadds{display:flex;flex-direction:column;gap:8px}
279
+ .vrow{display:grid;grid-template-columns:1fr 1fr;gap:10px}
280
+ .vrow[hidden]{display:none}
281
+ .cform input[type=file]{padding:6px}
282
+ .cform textarea.lines{min-height:7em;direction:rtl;text-align:right}
283
+ .paste{display:flex;flex-direction:column;gap:4px}
284
+ .cform .paste label+label{flex-direction:row;align-items:center;gap:6px;flex-wrap:wrap;font-weight:500;color:var(--muted)}
285
  .crow .two{display:flex;flex-direction:column;gap:2px;min-width:0;overflow-wrap:anywhere}
286
  .crow small{color:var(--muted);font-size:13px}
287
  .crow>small{justify-self:end}
 
542
  <section class="wrap" id="manage" aria-labelledby="mTitle">
543
  <div class="roundbar"><h1 class="mtitle" id="mTitle">ื ื™ื”ื•ืœ</h1><span class="sep"></span><button class="btn" id="mRefresh">ืจืขื ื•ืŸ</button><button class="btn primary" id="mPractice">ืœืชืจื’ื•ืœ</button></div>
544
  <div class="sub" id="mState" aria-live="polite"></div>
545
+ <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>
546
  <div id="mClasses"></div>
547
  <div id="mContent"></div>
548
  <div class="tabs" id="mTabs" role="tablist" aria-label="ื›ื™ืชื•ืช" hidden></div>
 
766
  let drawnW=0, nowWatch=null;
767
  /* A lesson's videos (the teacher adds them in the panel's content part) stand on the path among its topics, where the
768
  teacher put them. A video opens in a box over the page; the ones already opened are marked, on this device only. */
769
+ let VIDEOS=[], watched=store.get("ihki.watched",{}); // {id, lesson, title, url, embed, pos, ord} of the student's lessons; {video id: 1}
770
+ /* A lesson's topics in the path's order: the course's own, {c, n} with the topic's number, and among them what the teacher
771
+ added, a video {v} or a text {c} (a topic like any other, laid out as a story: its category has `text`). Each of
772
+ those has `pos` of the course's topics before it, and `ord` is its turn among the ones of the same place. */
773
+ function lessonItems(id){
774
+ const course=ALL_CATS.filter(c=>c.lesson===id&&!c.text);
775
+ const added=[...VIDEOS.filter(v=>v.lesson===id).map(v=>({v,pos:v.pos,ord:v.ord})),...ALL_CATS.filter(c=>c.lesson===id&&c.text).map(c=>({c,pos:c.pos,ord:c.ord}))].sort((a,b)=>a.pos-b.pos||a.ord-b.ord);
776
+ return [...course.flatMap((c,i)=>[...added.filter(e=>e.pos===i),{c,n:i+1}]),...added.filter(e=>e.pos>=course.length)];
777
+ }
778
+ async function loadContent(){ // the videos, and the texts: their topics and lines join the course's
779
  if(!sb) return;
780
  try{
781
+ await ready;
782
+ const [v,t]=await Promise.all([api("/api/videos"),api("/api/texts")]);
783
+ if(v.ok) VIDEOS=(await v.json()).videos||[];
784
+ if(t.ok){
785
+ const d=await t.json(), old=new Set(ALL_CATS.filter(c=>c.text).map(c=>c.id));
786
+ ALL_CATS=[...ALL_CATS.filter(c=>!c.text),...d.categories||[]]; PHRASES=[...PHRASES.filter(p=>!old.has(p.cat)),...d.phrases||[]];
787
+ useLessons(MY_LESSONS);
788
+ }
789
  if(PHRASES.length&&home&&!document.body.classList.contains("manage")) drawPath(true);
790
  }catch{}
791
  }
 
818
  const b=mark("chapter soon",""); b.style.top=y+"px"; b.append(mark("",lessonsWord(run)),mark("","ื‘ืงืจื•ื‘","small")); box.append(b);
819
  y+=52+28; continue;
820
  }
821
+ const items=lessonItems(l.id), cats=items.filter(it=>it.c).map(it=>it.c), parts=cats.map(c=>tally(listed.filter(p=>p.cat===c.id)));
822
  const whole=tally(listed.filter(p=>cats.some(c=>c.id===p.cat))), now=!whole.over&&next;
823
  const todo=Math.max(0,parts.findIndex(t=>!t.over)); // the topic the banner opens
824
  if(now) next=false;
 
833
  label.className="label"; label.style.setProperty("--w",Math.min(150,w/2-46+(right?-x:x))+"px");
834
  return [x,label];
835
  };
836
+ items.forEach(({c,n,v},at)=>{
 
837
  if(v){
838
  const seen=!!watched[v.id], [b,dot]=ball({over:seen},false), [x,label]=seat(b,at);
839
  b.classList.add("video"); dot.textContent="โ–ถ\uFE0E"; if(seen) dot.before(mark("badge","โœ“"));
 
842
  b.onclick=()=>playVideo(v); box.append(b);
843
  stops.push({x,y,went:seen}); y+=STEP; return;
844
  }
845
+ const i=cats.indexOf(c), t=parts[i], cur=now&&i===todo, [b,dot]=ball(t,cur), [x,label]=seat(b,at);
846
  const mine=!!hw&&c===hw.c; // the homework topic: its bubble counts the days left
847
+ dot.textContent=c.story?"๐Ÿ’ฌ":n; // the number stays; a finished topic gets a badge, the one to do now and the homework a bubble
848
  if(t.over) dot.before(mark("badge",t.gold?"โ˜…":"โœ“"));
849
  else if(cur||mine){
850
  const tag=mark("tag",mine?"":t.done?"ื”ืžืฉืš":"ื”ืชื—ื™ืœื•");
 
1740
  const detail=(await res.json().catch(()=>({}))).detail||res.status;
1741
  state.textContent=res.status===403?"ื”ืคืื ืœ ืคืชื•ื— ืœืžื•ืจื™ื ื‘ืœื‘ื“.":`ื ืชื•ื ื™ ื”ืชืœืžื™ื“ื™ื ืœื ื–ืžื™ื ื™ื ื›ืจื’ืข (${detail}).`; return;
1742
  }
1743
+ CLASS=await res.json(); await loadContent();
1744
  }catch{ state.textContent="ื”ืฉืจืช ืœื ื–ืžื™ืŸ."; return; }
1745
  state.textContent=""; drawManage();
1746
  }
 
1790
  }
1791
  }
1792
  /* The content part: every level, its lessons, and each lesson's topics as the path shows them: the course's own, and among
1793
+ them what the teacher added: videos (a name and a Vimeo link each) and texts (a story or a dialogue, from two files).
1794
+ Both are added under their lesson, at its end; the arrows on a row move it up and down the lesson, past a topic, a
1795
+ video or a text, and it is deleted there too. */
1796
+ const send=(url,method,body)=>api(url,{method,headers:{"Content-Type":"application/json"},body:JSON.stringify(body)});
1797
+ const refused=async(res,what)=>(await res.json().catch(()=>({}))).detail||`${what} ื ื›ืฉืœื” (${res.status})`;
1798
  function drawContent(){
1799
  const box=$("mContent"), listed=listedPhrases(); box.innerHTML="";
1800
+ const voices=[...$("voiceId").options].filter(o=>o.value).map(o=>o.text.replace(/[ึ‘-ื‡]/g,""));
1801
  for(const g of byLevel(ALL_LESSONS)){
1802
  box.append(mark("clevel",g.level.name,"h2"));
1803
  for(let k=0;k<g.lessons.length;k++){
 
1806
  const run=[l]; while(g.lessons[k+1]&&g.lessons[k+1].soon) run.push(g.lessons[++k]);
1807
  box.append(mark("csoon",`${lessonsWord(run)} ยท ื‘ืงืจื•ื‘`,"p")); continue;
1808
  }
1809
+ const items=lessonItems(l.id), kinds=[items.filter(it=>it.n).length+" ื ื•ืฉืื™ื",[items.filter(it=>it.c&&!it.n).length,"ื˜ืงืกื˜ื™ื"],[items.filter(it=>it.v).length,"ืกืจื˜ื•ื ื™ื"]];
1810
  const card=mark("card",""), top=mark("chead",""), name=mark("",l.name,"h2"), list=mark("clist","","ol");
1811
+ name.append(mark("",kinds.map(x=>x.pop?x[0]&&x.join(" "):x).filter(Boolean).join(" ยท "),"small")); top.append(name);
1812
+ items.forEach(({c,n,v},at)=>{
1813
+ const lines=c?listed.filter(p=>p.cat===c.id).length:0;
1814
+ if(n){
1815
+ const row=mark("crow","","li");
1816
+ row.append(mark("",c.story?"๐Ÿ’ฌ":n,"i"),mark("",c.name,"b"),mark("",`${c.story?"ืฉื™ื—ื”":"ืชืจื’ื•ืœ"} ยท ${lines} ${c.unit==="ืžื™ืœื”"?"ืžื™ืœื™ื":c.unit==="ืคื•ืขืœ"?"ืคืขืœื™ื":"ืžืฉืคื˜ื™ื"}`,"small")); list.append(row); return;
1817
+ }
1818
+ const it=v||c, row=mark("crow added","","li"), text=mark("two",""), title=mark("","","b"), t=document.createElement("bdi"), acts=mark("acts","");
1819
+ const up=mark("btn move","โ†‘","button"), down=mark("btn move","โ†“","button"), see=mark("btn",v?"ืฆืคื™ื™ื”":"ืชืจื’ื•ืœ","button"), del=mark("btn danger","ืžื—ื™ืงื”","button");
1820
+ row.dataset.id=(v?"video":"text")+(v?v.id:c.text); t.textContent=v?v.title:c.name; title.append(t); text.append(title);
1821
+ if(v){ const link=document.createElement("small"); link.dir="ltr"; link.textContent=v.url.replace("https://",""); text.append(link); }
1822
+ else{
1823
+ text.append(mark("",[c.voices?`ืฉื™ื—ื” ยท ${c.voices.join(" ื•")}`:"ืกื™ืคื•ืจ",`${lines} ืฉื•ืจื•ืช`].join(" ยท "),"small"));
1824
+ if(c.guessed&&c.guessed.length){ // words the course does not have: read by their spelling, so worth a listen
1825
+ const g=mark("guess",`${c.guessed.length} ืžื™ืœื™ื ืฉืื™ื ืŸ ื‘ืžื™ืœื•ืŸ ื”ืงื•ืจืก ื ืงืจืื• ืœืคื™ ื”ื›ืชื™ื‘: `,"small"), w=document.createElement("bdi");
1826
+ w.textContent=c.guessed.slice(0,8).join(" ยท ")+(c.guessed.length>8?" โ€ฆ":""); g.append(w); text.append(g);
1827
+ }
1828
  }
 
 
 
 
1829
  up.title="ื”ื–ื–ื” ืœืžืขืœื”: ืžื•ืงื“ื ื™ื•ืชืจ ื‘ืฉื™ืขื•ืจ"; down.title="ื”ื–ื–ื” ืœืžื˜ื”: ืžืื•ื—ืจ ื™ื•ืชืจ ื‘ืฉื™ืขื•ืจ";
1830
+ up.setAttribute("aria-label",`${up.title}, ${t.textContent}`); down.setAttribute("aria-label",`${down.title}, ${t.textContent}`);
1831
  up.disabled=!at; down.disabled=at===items.length-1;
1832
+ up.onclick=()=>moveItem(l,items,at,-1,list); down.onclick=()=>moveItem(l,items,at,1,list);
1833
+ see.onclick=v?()=>playVideo(v,true):()=>{ $("mPractice").click(); pickCat(c.id); }; // a text is tried as its students get it
1834
+ del.onclick=()=>deleteItem(v?"videos":"texts",v?v.id:c.text,v?`ืืช ื”ืกืจื˜ื•ืŸ ${v.title}`:`ืืช ื”ื˜ืงืกื˜ ${c.name}`,v?"":" ื”ื”ืงืœื˜ื•ืช ืฉืœ ื”ืชืœืžื™ื“ื™ื ื‘ื• ื ืฉืžืจื•ืช, ืื‘ืœ ืœื ื™ื™ืกืคืจื• ืขื•ื“.");
1835
+ acts.append(up,down,see,del); row.append(mark("",v?"โ–ถ๏ธŽ":"๐Ÿ’ฌ","i"),text,acts); list.append(row);
1836
  });
1837
+ const adds=mark("cadds",""), adder=(label,fields,note,submit)=>{ // a closed form under the lesson
1838
+ const add=document.createElement("details"), form=document.createElement("form"), row=mark("row",""), msg=mark("msg","");
1839
+ add.className="vadd"; add.append(mark("btn",label,"summary"),form); form.className="cform"; msg.setAttribute("role","alert");
1840
+ row.append(mark("btn primary","ื”ื•ืกืคื”","button"),msg); form.append(...fields,mark("sub",note,"small"),row);
1841
+ form.onsubmit=async e=>{
1842
+ e.preventDefault(); const buttons=form.querySelectorAll("button"); msg.textContent=""; buttons.forEach(b=>b.disabled=true);
1843
+ try{ const bad=await submit(form); if(!bad){ await loadContent(); drawContent(); return; } msg.textContent=bad; }catch{ msg.textContent="ื”ืฉืจืช ืœื ื–ืžื™ืŸ."; }
1844
+ buttons.forEach(b=>b.disabled=false);
1845
+ };
1846
+ adds.append(add); return form;
1847
+ };
1848
+ const field=(label,name,attrs,tag="input")=>{ const lab=mark("",label,"label"), inp=Object.assign(document.createElement(tag),{name,required:true,autocomplete:"off",...attrs}); lab.append(inp); return lab; };
1849
+ const pick=(label,name,options)=>{ const lab=field(label,name,{},"select"); for(const [value,text] of options) lab.lastChild.add(new Option(text,value)); return lab; };
1850
+ adder("+ ื”ื•ืกืคืช ืกืจื˜ื•ืŸ",[field("ืฉื ื”ืกืจื˜ื•ืŸ","title",{maxLength:80,placeholder:"ืœืžืฉืœ: ื”ืกื‘ืจ ืขืœ ื”ื˜ื™ื™ืช ื”ืคื•ืขืœ"}),
1851
+ field("ืงื™ืฉื•ืจ ืœ-Vimeo","url",{inputMode:"url",placeholder:"https://vimeo.com/1233611297/d46ac373c8"})],
1852
+ "ื”ืกืจื˜ื•ืŸ ื™ื•ืคื™ืข ืœืชืœืžื™ื“ื™ื ื‘ืžืกืœื•ืœ ื›ื ื•ืฉื ืฉืœ ื”ืฉื™ืขื•ืจ. ื”ื•ื ื ื•ืกืฃ ื‘ืกื•ืฃ ื”ืฉื™ืขื•ืจ, ื•ื‘ื—ื™ืฆื™ื ืฉื‘ืฉื•ืจื” ืฉืœื• ืžื–ื™ื–ื™ื ืื•ืชื• ืœืžืงื•ืžื•.",
1853
+ async f=>{ const res=await send("/api/videos","POST",{lesson:l.id,title:f.elements.title.value,url:f.elements.url.value}); return res.ok?"":refused(res,"ื”ื”ื•ืกืคื”"); });
1854
+ const who=mark("vrow",""), paste=(label,name,hint)=>{ // the lines are pasted into the box, or read into it from a file; either way they can be fixed there
1855
+ const box=mark("paste",""), area=field(label,name,{rows:5,placeholder:hint,className:"lines"},"textarea"), from=mark("","ืื• ืžืงื•ื‘ืฅ txt: ","label"), file=Object.assign(document.createElement("input"),{type:"file",accept:".txt,text/plain"});
1856
+ file.onchange=async()=>{
1857
+ if(!file.files[0]) return;
1858
+ const text=(await file.files[0].text()).replace(/^๏ปฟ/,"");
1859
+ if(text.includes("๏ฟฝ")){ file.value=""; alert("ื”ืงื•ื‘ืฅ ืœื ืฉืžื•ืจ ื‘ืงื™ื“ื•ื“ UTF-8. ืฉืžืจื• ืื•ืชื• ืžื—ื“ืฉ ื›-UTF-8 (ื‘-Notepad: ืฉืžื™ืจื” ื‘ืฉื โ† ืงื™ื“ื•ื“), ืื• ื”ื“ื‘ื™ืงื• ืืช ื”ื˜ืงืกื˜ ื‘ืชื™ื‘ื”."); return; }
1860
+ area.lastChild.value=text;
1861
+ };
1862
+ from.append(file); box.append(area,from); return box;
1863
+ };
1864
+ who.append(pick("ื”ืงื•ืœ ืฉืœ ื”ืฉื•ืจื•ืช ื”ืื™-ื–ื•ื’ื™ื•ืช","v1",voices.map(n=>[n,n])),pick("ื”ืงื•ืœ ืฉืœ ื”ืฉื•ืจื•ืช ื”ื–ื•ื’ื™ื•ืช","v2",voices.map(n=>[n,n]))); who.hidden=true;
1865
+ if(voices.length>1) who.querySelector("[name=v2]").selectedIndex=1;
1866
+ const kind=pick("ืกื•ื’ ื”ื˜ืงืกื˜","kind",[["story","ืกื™ืคื•ืจ: ืงื•ืœ ืื—ื“, ื–ื” ืฉื”ืชืœืžื™ื“ ื‘ื—ืจ ื‘ื”ื’ื“ืจื•ืช"],["dialog","ืฉื™ื—ื”: ืฉื ื™ ื“ื•ื‘ืจื™ื, ืฉื•ืจื” ืœื›ืœ ืื—ื“ ื‘ืชื•ืจื•"]]);
1867
+ kind.lastChild.onchange=e=>{ who.hidden=e.target.value!=="dialog"; };
1868
+ adder("+ ื”ื•ืกืคืช ื˜ืงืกื˜",[field("ืฉื ื”ื˜ืงืกื˜","title",{maxLength:80,placeholder:"ืœืžืฉืœ: ื‘ืฉื•ืง"}),
1869
+ paste("ื”ื˜ืงืกื˜ ื‘ืขื‘ืจื™ืช","he","ืฉื•ืจื” ืœื›ืœ ืžืฉืคื˜"),paste("ื”ื˜ืงืกื˜ ื‘ืขืจื‘ื™ืช, ื‘ืชืขืชื™ืง ืขื‘ืจื™","tr","ืื•ืชืŸ ืฉื•ืจื•ืช, ื‘ืื•ืชื• ืกื“ืจ"),kind,who],
1870
+ "ื”ื˜ืงืกื˜ ื™ื•ืคื™ืข ืœืชืœืžื™ื“ื™ื ื‘ืžืกืœื•ืœ ื›ื ื•ืฉื ืฉืœ ื”ืฉื™ืขื•ืจ, ื‘ืžืฆื‘ ืฉื™ื—ื”: ื›ืœ ื”ืฉื•ืจื•ืช ืขืœ ื”ืžืกืš, ื•ืื•ืžืจื™ื ืื•ืชืŸ ืื—ืช ืื—ืจื™ ื”ืฉื ื™ื™ื”. ืืช ื”ืฉื•ืจื•ืช ืžื“ื‘ื™ืงื™ื ื‘ืชื™ื‘ื•ืช ืื• ื˜ื•ืขื ื™ื ืžืงื•ื‘ืฅ. ื‘ืฉืชื™ ื”ืชื™ื‘ื•ืช ืฆืจื™ืš ืœื”ื™ื•ืช ืื•ืชื• ืžืกืคืจ ืฉื•ืจื•ืช (ืฉื•ืจื•ืช ืจื™ืงื•ืช ืœื ื ืกืคืจื•ืช). ื”ื•ื ื ื•ืกืฃ ื‘ืกื•ืฃ ื”ืฉื™ืขื•ืจ, ื•ื‘ื—ื™ืฆื™ื ืฉื‘ืฉื•ืจื” ืฉืœื• ืžื–ื™ื–ื™ื ืื•ืชื• ืœืžืงื•ืžื•.",
1871
+ async f=>{
1872
+ const lines=text=>text.split(/\r?\n/).map(x=>x.trim()).filter(Boolean), he=lines(f.elements.he.value), tr=lines(f.elements.tr.value);
1873
+ if(he.length!==tr.length) return `ืžืกืคืจ ื”ืฉื•ืจื•ืช ืœื ื–ื”ื”: ${he.length} ื‘ืขื‘ืจื™ืช ื•-${tr.length} ื‘ืขืจื‘ื™ืช.`;
1874
+ const res=await send("/api/texts","POST",{lesson:l.id,title:f.elements.title.value,he,tr,voices:f.elements.kind.value==="dialog"?[f.elements.v1.value,f.elements.v2.value]:[]});
1875
+ return res.ok?"":refused(res,"ื”ื”ื•ืกืคื”");
1876
+ });
1877
+ card.append(top,list,adds); box.append(card);
1878
  }
1879
  }
1880
  }
1881
+ async function moveItem(l,items,at,step,list){ // a video or a text changes places with its neighbour, whatever that is
1882
+ const to=[...items], id=it=>it.v?{kind:"video",id:it.v.id}:{kind:"text",id:it.c.text}; [to[at],to[at+step]]=[to[at+step],to[at]];
 
 
 
 
 
 
 
 
 
 
1883
  let topics=0; const order=[];
1884
+ for(const it of to){ if(it.n) topics++; else order.push({...id(it),pos:topics}); }
1885
  list.querySelectorAll("button").forEach(b=>b.disabled=true);
1886
  try{
1887
+ const res=await send("/api/content/order","PUT",{lesson:l.id,order});
1888
+ if(!res.ok) alert(await refused(res,"ื”ื”ื–ื–ื”"));
1889
  }catch{ alert("ื”ืฉืจืช ืœื ื–ืžื™ืŸ."); }
1890
+ await loadContent(); drawContent();
1891
+ const me=id(items[at]), moved=[...$("mContent").querySelectorAll(".crow.added")].find(r=>r.dataset.id===me.kind+me.id); // the keyboard stays on what moved
1892
  const again=moved&&[...moved.querySelectorAll(".move")].find((b,k)=>k===(step<0?0:1)&&!b.disabled)||moved&&moved.querySelector(".move:not(:disabled)"); if(again) again.focus({preventScroll:true});
1893
  }
1894
+ async function deleteItem(table,id,what,more){
1895
+ if(!confirm(`ืœืžื—ื•ืง ${what}? ื–ื” ื™ื™ืจื“ ืžื”ืžืกืœื•ืœ ืฉืœ ื”ืชืœืžื™ื“ื™ื.${more}`)) return;
1896
  try{
1897
+ const res=await api(`/api/${table}/${id}`,{method:"DELETE"});
1898
+ if(!res.ok) alert(await refused(res,"ื”ืžื—ื™ืงื”"));
1899
  }catch{ alert("ื”ืฉืจืช ืœื ื–ืžื™ืŸ."); }
1900
+ await loadContent(); drawContent();
1901
  }
1902
  async function deleteClass(c){
1903
  if(!confirm(`ืœืžื—ื•ืง ืืช ื”ื›ื™ืชื” ${c.name}? ื”ืชืœืžื™ื“ื™ื ืฉืœื” ืœื ื™ื•ื›ืœื• ืœื”ื™ื›ื ืก ืขื•ื“. ื”ื”ืงืœื˜ื•ืช ื•ื”ื”ืชืงื“ืžื•ืช ืฉืœื”ื ื ืฉืžืจื•ืช.`)) return;
 
2292
  if(MY_CLASSES.length===1) MY_CLASS=mine[0];
2293
  else{ const last=MY_CLASSES.find(c=>c.name===store.get("ihki.class","")); if(last) useClass(last); } // the class practised in last
2294
  start.hidden=!ok||teacher; roles.hidden=$("toManage").hidden=!teacher; denied.hidden=ok;
2295
+ if(ok){ (teacher?$("practiceBtn"):start).focus({preventScroll:true}); loadProgress().then(()=>{ if(PHRASES.length&&$("wrap").inert) startCat(); }); loadContent(); }
2296
  },0);
2297
  });
2298
  }
tests/test_scoring.py CHANGED
@@ -433,7 +433,7 @@ def test_sign_in_guards_the_practice_endpoints():
433
  url, key, teachers = "https://proj.supabase.co", "sb_publishable_x", frozenset()
434
 
435
  def __init__(self):
436
- self.rows, self.cls, self.vids = [], [], []
437
 
438
  def classes(self, fresh=False):
439
  return self.cls
@@ -456,9 +456,18 @@ def test_sign_in_guards_the_practice_endpoints():
456
  def add_video(self, lesson, title, url, pos, ord):
457
  self.vids.append({"id": len(self.vids) + 1, "lesson": lesson, "title": title, "url": url, "pos": pos, "ord": ord})
458
 
459
- def place_videos(self, places):
460
- for id, pos, ord in places:
461
- next(v for v in self.vids if v["id"] == id).update(pos=pos, ord=ord)
 
 
 
 
 
 
 
 
 
462
 
463
  def delete_video(self, id):
464
  self.vids = [v for v in self.vids if v["id"] != id]
@@ -538,7 +547,7 @@ def test_sign_in_guards_the_practice_endpoints():
538
  first, second = c.get("/api/videos", headers=good).json()["videos"]
539
  N1 = sum(k["lesson"] == READY[0] for k in CATEGORIES) # a new video stands after its lesson's topics
540
  assert first == {"id": 1, "lesson": READY[0], "title": "ืคืชื™ื—ื” ืœืฉื™ืขื•ืจ", "url": "https://vimeo.com/1233611297/d46ac373c8",
541
- "embed": "https://player.vimeo.com/video/1233611297?h=d46ac373c8&dnt=1", "pos": N1}
542
  assert (second["url"], second["embed"]) == ("https://vimeo.com/76979871", "https://player.vimeo.com/video/76979871?dnt=1")
543
  from app.main import vimeo_link
544
  assert vimeo_link("https://player.vimeo.com/video/1233611297?h=d46ac373c8") == first["url"]
@@ -546,23 +555,66 @@ def test_sign_in_guards_the_practice_endpoints():
546
  assert c.post("/api/videos", json={"lesson": READY[0], "title": "b", "url": link}, headers=good).status_code == 200
547
  seen = lambda: [(v["id"], v["pos"]) for v in c.get("/api/videos", headers=good).json()["videos"] if v["lesson"] == READY[0]]
548
  assert seen() == [(1, N1), (3, N1)]
549
- order = lambda *o: c.put("/api/videos/order", json={"lesson": READY[0], "order": [{"id": i, "pos": p} for i, p in o]}, headers=good).status_code
550
  assert order((3, 0), (1, 0)) == 200 and seen() == [(3, 0), (1, 0)] # both before the first topic, the new one first
551
  assert order((3, 0), (1, 2)) == 200 and seen() == [(3, 0), (1, 2)]
552
  assert order((3, 0)) == 409 and order((3, 0), (2, 0)) == 409 # every video of the lesson, and no other's
553
  assert order((3, 0), (1, N1 + 1)) == 400 and order((3, -1), (1, 0)) == 400 and seen() == [(3, 0), (1, 2)]
554
- assert c.put("/api/videos/order", json={"lesson": SOON, "order": []}, headers=good).status_code == 400
555
  c.app.state.auth.vids[0].update(pos=None) # kept before videos had places: after the topics
556
  assert seen() == [(3, 0), (1, N1)]
557
  assert c.delete("/api/videos/3", headers=good).status_code == 200
558
- first["pos"] = N1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
559
  # a student gets the videos of their classes' lessons only, and adds or deletes none
560
  kept, c.app.state.auth.teachers = c.app.state.auth.cls, frozenset()
561
  c.app.state.auth.cls = [{"id": 7, "name": "V", "emails": ["a@b.c"], "nicknames": {}, "lessons": READY[1:2]}]
562
  assert c.get("/api/videos", headers=good).json()["videos"] == [{k: v for k, v in second.items() if k != "url"}] # without the link
563
  assert c.post("/api/videos", json={"lesson": READY[0], "title": "x", "url": link}, headers=good).status_code == 403
564
  assert c.delete("/api/videos/1", headers=good).status_code == 403
565
- assert c.put("/api/videos/order", json={"lesson": READY[0], "order": []}, headers=good).status_code == 403
 
566
  c.app.state.auth.cls, c.app.state.auth.teachers = kept, frozenset({"a@b.c"})
567
  assert c.delete("/api/videos/1", headers=good).status_code == 200
568
  assert c.get("/api/videos", headers=good).json()["videos"] == [second]
 
433
  url, key, teachers = "https://proj.supabase.co", "sb_publishable_x", frozenset()
434
 
435
  def __init__(self):
436
+ self.rows, self.cls, self.vids, self.txts = [], [], [], []
437
 
438
  def classes(self, fresh=False):
439
  return self.cls
 
456
  def add_video(self, lesson, title, url, pos, ord):
457
  self.vids.append({"id": len(self.vids) + 1, "lesson": lesson, "title": title, "url": url, "pos": pos, "ord": ord})
458
 
459
+ def place(self, places):
460
+ for table, id, pos, ord in places:
461
+ next(v for v in {"videos": self.vids, "texts": self.txts}[table] if v["id"] == id).update(pos=pos, ord=ord)
462
+
463
+ def texts(self, fresh=False):
464
+ return self.txts
465
+
466
+ def add_text(self, lesson, title, voices, lines, pos, ord):
467
+ self.txts.append({"id": len(self.txts) + 1, "lesson": lesson, "title": title, "voices": voices, "lines": lines, "pos": pos, "ord": ord})
468
+
469
+ def delete_text(self, id):
470
+ self.txts = [t for t in self.txts if t["id"] != id]
471
 
472
  def delete_video(self, id):
473
  self.vids = [v for v in self.vids if v["id"] != id]
 
547
  first, second = c.get("/api/videos", headers=good).json()["videos"]
548
  N1 = sum(k["lesson"] == READY[0] for k in CATEGORIES) # a new video stands after its lesson's topics
549
  assert first == {"id": 1, "lesson": READY[0], "title": "ืคืชื™ื—ื” ืœืฉื™ืขื•ืจ", "url": "https://vimeo.com/1233611297/d46ac373c8",
550
+ "embed": "https://player.vimeo.com/video/1233611297?h=d46ac373c8&dnt=1", "pos": N1, "ord": 1}
551
  assert (second["url"], second["embed"]) == ("https://vimeo.com/76979871", "https://player.vimeo.com/video/76979871?dnt=1")
552
  from app.main import vimeo_link
553
  assert vimeo_link("https://player.vimeo.com/video/1233611297?h=d46ac373c8") == first["url"]
 
555
  assert c.post("/api/videos", json={"lesson": READY[0], "title": "b", "url": link}, headers=good).status_code == 200
556
  seen = lambda: [(v["id"], v["pos"]) for v in c.get("/api/videos", headers=good).json()["videos"] if v["lesson"] == READY[0]]
557
  assert seen() == [(1, N1), (3, N1)]
558
+ order = lambda *o: c.put("/api/content/order", json={"lesson": READY[0], "order": [{"kind": "video", "id": i, "pos": p} for i, p in o]}, headers=good).status_code
559
  assert order((3, 0), (1, 0)) == 200 and seen() == [(3, 0), (1, 0)] # both before the first topic, the new one first
560
  assert order((3, 0), (1, 2)) == 200 and seen() == [(3, 0), (1, 2)]
561
  assert order((3, 0)) == 409 and order((3, 0), (2, 0)) == 409 # every video of the lesson, and no other's
562
  assert order((3, 0), (1, N1 + 1)) == 400 and order((3, -1), (1, 0)) == 400 and seen() == [(3, 0), (1, 2)]
563
+ assert c.put("/api/content/order", json={"lesson": SOON, "order": []}, headers=good).status_code == 400
564
  c.app.state.auth.vids[0].update(pos=None) # kept before videos had places: after the topics
565
  assert seen() == [(3, 0), (1, N1)]
566
  assert c.delete("/api/videos/3", headers=good).status_code == 200
567
+ first.update(pos=N1, ord=1)
568
+ second = c.get("/api/videos", headers=good).json()["videos"][1]
569
+ # a text: its lines in Hebrew and in Arabic written in Hebrew letters, the same number of each; a dialogue names two voices
570
+ he, tr = ["ืฉืœื•ื", "ืžื” ืฉืœื•ืžืš?", "ืฉืœื•ื"], ["ืžึทืจึฐื—ึทื‘ึทึผื", "ื›ึดึผื™ืฃ ื—ึทืืœึทื›ึผ?", "ืžึทืจึฐื—ึทื‘ึทึผื ื™ึทื ื–ึทืœึทืžึถื”"]
571
+ talk = {"lesson": READY[0], "title": " ื‘ืฉื•ืง ", "he": he, "tr": tr, "voices": ["ืืžื™ืจ", "ืจืืืฃ"]}
572
+ assert c.get("/api/texts").status_code == 401 and c.get("/api/texts", headers=good).json() == {"categories": [], "phrases": []}
573
+ for body, code in ((talk, 200), ({**talk, "title": "story", "voices": []}, 200),
574
+ ({**talk, "tr": tr[:2]}, 400), ({**talk, "he": [], "tr": []}, 400), ({**talk, "tr": ["x", "1", "-"]}, 400), # not Arabic in Hebrew letters
575
+ ({**talk, "voices": ["ืืžื™ืจ"]}, 400), ({**talk, "voices": ["ืืžื™ืจ", "nobody"]}, 400),
576
+ ({**talk, "lesson": SOON}, 400), ({**talk, "title": ""}, 400), ({**talk, "he": he * 80, "tr": tr * 80}, 400)):
577
+ r = c.post("/api/texts", json=body, headers=good)
578
+ assert r.status_code == code, (body, r.text)
579
+ d = c.get("/api/texts", headers=good).json()
580
+ assert d["categories"][0] == {"id": "t1", "name": "ื‘ืฉื•ืง", "lesson": READY[0], "story": True, "text": 1, "voices": ["ืืžื™ืจ", "ืจืืืฃ"],
581
+ "pos": N1, "ord": 2, "guessed": ["ื–ึทืœึทืžึถื”"]} # the course has the other words
582
+ assert "voices" not in d["categories"][1] and d["categories"][1]["ord"] == 3
583
+ line1, line2, line3 = d["phrases"][:3]
584
+ assert line1 == {"id": 1_001_000, "cat": "t1", "he": "ืฉืœื•ื", "tr": "ืžึทืจึฐื—ึทื‘ึทึผื", "ar": "ู…ุฑุญุจุง", "seq": 1}
585
+ assert (line2["id"], line2["ar"], line3["ar"]) == (1_001_001, "ูƒูŠู ุญุงู„ูƒุŸ", "ู…ุฑุญุจุง ูŠุง ุฒู„ู…ุฉ") and len(d["phrases"]) == 6
586
+ # a line is a phrase like the bank's: it has a prompt and an answer to play, and its recordings count (two lines
587
+ # with the same Hebrew stay apart)
588
+ assert c.get("/api/prompt-audio/1001999", headers=good).status_code == 404 and c.get("/api/tts/1001001", headers=good).status_code == 503
589
+ from app.main import built, summary as sums, text_bank
590
+ bank = text_bank(c.app.state.auth.txts)
591
+ assert bank[1_001_002]["key"] == "ืฉืœื•ื (2)" and bank[1_001_001]["variants"][0] == ("ูƒูŠู ุญุงู„ูƒุŸ", "k iห f | ฤง aห l a k")
592
+ got = sums([{"cat": "t1", "phrase": "ืฉืœื•ื (2)", "score": 80, "created_at": "2026-10-09T10:00:00+00:00"},
593
+ {"cat": "t1", "phrase": "ืฉืœื•ื", "score": 60, "created_at": "2026-10-09T10:00:00+00:00"},
594
+ {"cat": "t9", "phrase": "ืฉืœื•ื", "score": 99, "created_at": "2026-10-09T10:00:00+00:00"}], bank) # a deleted text's
595
+ assert got["best"] == {1_001_002: 80, 1_001_000: 60} and got["recordings"] == 3
596
+ for ar, ipa in (v for p in bank.values() for v in p["variants"]):
597
+ assert len(ar.split()) == len(ipa.split("|"))
598
+ # a text is placed among the topics like a video, and may be a class's homework
599
+ mixed = lambda *o: c.put("/api/content/order", json={"lesson": READY[0], "order": [{"kind": k, "id": i, "pos": p} for k, i, p in o]}, headers=good).status_code
600
+ assert mixed(("text", 2, 0), ("video", 1, 1), ("text", 1, 1)) == 200 and mixed(("text", 2, 0), ("text", 1, 1)) == 409
601
+ assert [(k["id"], k["pos"], k["ord"]) for k in c.get("/api/texts", headers=good).json()["categories"]] == [("t2", 0, 0), ("t1", 1, 2)]
602
+ assert c.get("/api/videos", headers=good).json()["videos"][0]["ord"] == 1
603
+ first.update(pos=1, ord=1)
604
+ assert c.post("/api/classes", json={"name": "T", "emails": "a@b.c", "lessons": READY[:1], "homework": "t1"}, headers=good).status_code == 200
605
+ assert c.get("/api/me", headers=good).json()["classes"][-1]["homework"] == "t1"
606
+ assert c.delete("/api/texts/1", headers=good).status_code == 200 # with its text gone, the homework is none
607
+ assert c.get("/api/me", headers=good).json()["classes"][-1]["homework"] == ""
608
+ assert c.delete("/api/texts/2", headers=good).status_code == 200
609
+ c.app.state.auth.cls = [k for k in c.app.state.auth.cls if k["name"] != "T"]
610
  # a student gets the videos of their classes' lessons only, and adds or deletes none
611
  kept, c.app.state.auth.teachers = c.app.state.auth.cls, frozenset()
612
  c.app.state.auth.cls = [{"id": 7, "name": "V", "emails": ["a@b.c"], "nicknames": {}, "lessons": READY[1:2]}]
613
  assert c.get("/api/videos", headers=good).json()["videos"] == [{k: v for k, v in second.items() if k != "url"}] # without the link
614
  assert c.post("/api/videos", json={"lesson": READY[0], "title": "x", "url": link}, headers=good).status_code == 403
615
  assert c.delete("/api/videos/1", headers=good).status_code == 403
616
+ assert c.put("/api/content/order", json={"lesson": READY[0], "order": []}, headers=good).status_code == 403
617
+ assert c.post("/api/texts", json={}, headers=good).status_code == 403 and c.delete("/api/texts/1", headers=good).status_code == 403
618
  c.app.state.auth.cls, c.app.state.auth.teachers = kept, frozenset({"a@b.c"})
619
  assert c.delete("/api/videos/1", headers=good).status_code == 200
620
  assert c.get("/api/videos", headers=good).json()["videos"] == [second]