Refactor tutor game references from "בחכי ערבי" to "ערבוט" across application files; update access management features and permissions handling in the management panel; enhance user interface for access permissions; add access management functionality in the management system; improve test setup for authentication.
Browse files- .env.example +4 -0
- README.md +46 -1
- app/auth.py +52 -4
- app/main.py +191 -53
- app/tutor.py +4 -4
- static/index.html +103 -29
- tests/test_lab.py +1 -0
.env.example
CHANGED
|
@@ -35,6 +35,10 @@ SUPABASE_PUBLISHABLE_KEY=
|
|
| 35 |
# classes). Who may sign in is set by the classes the teacher opens there (see the README), not here.
|
| 36 |
TEACHER_EMAILS=
|
| 37 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
# Needed by the management panel and the classes: the project's secret key (Project Settings -> API Keys -> secret, or the
|
| 39 |
# legacy service_role key). It reads every student's rows, so it is NOT public: on Hugging Face set it as a *secret*.
|
| 40 |
# scripts/bench.py needs it (with the two values above) to read the lab's recordings.
|
|
|
|
| 35 |
# classes). Who may sign in is set by the classes the teacher opens there (see the README), not here.
|
| 36 |
TEACHER_EMAILS=
|
| 37 |
|
| 38 |
+
# Bootstrap accounts with full access, including the Lab. Admins do not get Lab access. Keep at least one address here
|
| 39 |
+
# so database permission mistakes cannot lock every developer out.
|
| 40 |
+
DEVELOPER_EMAILS=
|
| 41 |
+
|
| 42 |
# Needed by the management panel and the classes: the project's secret key (Project Settings -> API Keys -> secret, or the
|
| 43 |
# legacy service_role key). It reads every student's rows, so it is NOT public: on Hugging Face set it as a *secret*.
|
| 44 |
# scripts/bench.py needs it (with the two values above) to read the lab's recordings.
|
README.md
CHANGED
|
@@ -145,6 +145,51 @@ The page's "ההתקדמות שלי" button reads these rows back through `GET /
|
|
| 145 |
|
| 146 |
### The teacher
|
| 147 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 148 |
`TEACHER_EMAILS` names the teacher's Google account (several are separated by commas or spaces). After sign-in a teacher chooses between **תרגול**, the same practice a student gets, and **ניהול**, the management panel. The panel lists every student with their usage (recordings, those of the last 7 days, days practised, last practice), progress (sentences practised) and grade (the average of the best scores), and pressing a student opens their own screen in place of the class's: their figures, their homework, every lesson of the class with its topics, and their best and weakest sentences, all counted as the class counts. "חזרה לכיתה", or the browser's back button, returns to the class.
|
| 149 |
|
| 150 |
### Flags: a score that is wrong
|
|
@@ -369,7 +414,7 @@ alter table public.dailies enable row level security;
|
|
| 369 |
|
| 370 |
### Video library
|
| 371 |
|
| 372 |
-
Apart from those there is one library of videos for the whole course: they are not part of the path, need no date, and are the same for every level and class. In **תוכן** the card "ספריה דיגיטלית" comes first, above the levels; the teacher adds a video (a name and a link), renames one, moves one up or down the list with its arrows, and deletes one there.
|
| 373 |
|
| 374 |
```sql
|
| 375 |
create table public.library (
|
|
|
|
| 145 |
|
| 146 |
### The teacher
|
| 147 |
|
| 148 |
+
Access is managed from **ניהול → הרשאות**. Its matrix grants practice, management, Lab, games, the digital library,
|
| 149 |
+
problem reporting, ערבוט, and the learning path independently. ערבוט has its own permission because each
|
| 150 |
+
conversation uses the paid model API; unlike the other student features it is off until explicitly granted.
|
| 151 |
+
Developers have full access including the Lab; admins do not receive Lab access. `DEVELOPER_EMAILS` bootstraps one or more developer
|
| 152 |
+
accounts; keep at least one there to prevent a database mistake from locking every developer out. Existing
|
| 153 |
+
`TEACHER_EMAILS` accounts retain the old management abilities during migration, but no longer receive Lab access.
|
| 154 |
+
|
| 155 |
+
On first use, the permissions tab displays this migration to run in the Supabase SQL editor:
|
| 156 |
+
|
| 157 |
+
```sql
|
| 158 |
+
create table public.user_access (
|
| 159 |
+
user_id uuid primary key references auth.users(id) on delete cascade,
|
| 160 |
+
email text not null,
|
| 161 |
+
roles text[] not null default array['student']::text[],
|
| 162 |
+
entitlements text[] not null default '{}'::text[],
|
| 163 |
+
updated_at timestamptz not null default now(),
|
| 164 |
+
updated_by uuid references auth.users(id),
|
| 165 |
+
constraint valid_roles check (roles <@ array['student','teacher','flagger','admin','developer']::text[]),
|
| 166 |
+
constraint valid_entitlements check (entitlements <@ array['practice','games','tutor','path','library']::text[])
|
| 167 |
+
);
|
| 168 |
+
create unique index user_access_email_idx on public.user_access (lower(email));
|
| 169 |
+
alter table public.user_access enable row level security;
|
| 170 |
+
create table public.access_audit (
|
| 171 |
+
id bigint generated always as identity primary key,
|
| 172 |
+
target_user_id uuid not null,
|
| 173 |
+
changed_by uuid not null,
|
| 174 |
+
old_access jsonb not null,
|
| 175 |
+
new_access jsonb not null,
|
| 176 |
+
created_at timestamptz not null default now()
|
| 177 |
+
);
|
| 178 |
+
alter table public.access_audit enable row level security;
|
| 179 |
+
```
|
| 180 |
+
|
| 181 |
+
If `user_access` was created with the earlier three student features, run this once:
|
| 182 |
+
|
| 183 |
+
```sql
|
| 184 |
+
alter table public.user_access drop constraint if exists valid_entitlements;
|
| 185 |
+
update public.user_access
|
| 186 |
+
set entitlements = array_append(entitlements, 'practice')
|
| 187 |
+
where 'path' = any(entitlements) and not ('practice' = any(entitlements));
|
| 188 |
+
alter table public.user_access add constraint valid_entitlements check (
|
| 189 |
+
entitlements <@ array['practice','games','tutor','path','library']::text[]
|
| 190 |
+
);
|
| 191 |
+
```
|
| 192 |
+
|
| 193 |
`TEACHER_EMAILS` names the teacher's Google account (several are separated by commas or spaces). After sign-in a teacher chooses between **תרגול**, the same practice a student gets, and **ניהול**, the management panel. The panel lists every student with their usage (recordings, those of the last 7 days, days practised, last practice), progress (sentences practised) and grade (the average of the best scores), and pressing a student opens their own screen in place of the class's: their figures, their homework, every lesson of the class with its topics, and their best and weakest sentences, all counted as the class counts. "חזרה לכיתה", or the browser's back button, returns to the class.
|
| 194 |
|
| 195 |
### Flags: a score that is wrong
|
|
|
|
| 414 |
|
| 415 |
### Video library
|
| 416 |
|
| 417 |
+
Apart from those there is one library of videos for the whole course: they are not part of the path, need no date, and are the same for every level and class. In **תוכן** the card "ספריה דיגיטלית" comes first, above the levels; the teacher adds a video (a name and a link), renames one, moves one up or down the list with its arrows, and deletes one there. A permitted student enters it from the "ספרייה דיגיטלית" button on the opening screen: a list appears, and a video plays in the same box as the path's videos. The ones opened are marked (on that device). Create the table once (its `level` column stays empty):
|
| 418 |
|
| 419 |
```sql
|
| 420 |
create table public.library (
|
app/auth.py
CHANGED
|
@@ -45,13 +45,14 @@ Writing: a lesson's written homework (see workbook.py) is kept in the Supabase t
|
|
| 45 |
and topic, written with the student's own token like the attempts, so it follows them to any device. The panel
|
| 46 |
reads every student's with the secret key.
|
| 47 |
|
| 48 |
-
Tutor: each conversation of the game
|
| 49 |
Supabase table `tutor_chats`, written with the secret key, for the teacher to read.
|
| 50 |
|
| 51 |
Env: SUPABASE_URL (https://<project-ref>.supabase.co)
|
| 52 |
SUPABASE_PUBLISHABLE_KEY (the publishable/anon key; it is public and also goes to the page)
|
| 53 |
TEACHER_EMAILS (optional: the accounts with the management panel, separated by commas or spaces)
|
| 54 |
TUTORS_EMAIL (optional: more accounts that flag a wrong score, as the teachers do; separated by commas or spaces)
|
|
|
|
| 55 |
SUPABASE_SECRET_KEY (the secret/service-role key, needed by the panel, the classes and the flags; never public)
|
| 56 |
Without them the service is open, as before.
|
| 57 |
"""
|
|
@@ -89,16 +90,18 @@ class ClassConflict(ValueError):
|
|
| 89 |
|
| 90 |
class SupabaseAuth:
|
| 91 |
def __init__(self, url: str, key: str, teachers: frozenset[str] = frozenset(), secret: str = "",
|
| 92 |
-
tutors: frozenset[str] = frozenset()):
|
| 93 |
self.url, self.key = url.rstrip("/"), key
|
| 94 |
self.teachers = teachers # lower-case emails of the accounts with the management panel
|
| 95 |
self.tutors = tutors # lower-case emails of the accounts that flag a wrong score, besides the teachers
|
|
|
|
| 96 |
self.secret = secret # reads every student's rows and the classes; empty = the panel has no data
|
| 97 |
self._cache: dict[str, tuple[float, dict]] = {}
|
| 98 |
self._classes: tuple[float, list[dict]] | None = None
|
| 99 |
self._videos: tuple[float, list[dict]] | None = None
|
| 100 |
self._texts: tuple[float, list[dict]] | None = None
|
| 101 |
self._ranked: tuple[float, frozenset[str] | None] | None = None
|
|
|
|
| 102 |
self._level_videos: dict[str, tuple[float, list[dict]]] = {} # by table: the daily videos, the library
|
| 103 |
self._lock = threading.Lock()
|
| 104 |
|
|
@@ -599,6 +602,51 @@ class SupabaseAuth:
|
|
| 599 |
break
|
| 600 |
return users
|
| 601 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 602 |
def all_attempts(self) -> list[dict]:
|
| 603 |
"""Every student's attempts, as `attempts` gives one student's, each with its user_id. "Different sentence"
|
| 604 |
rows remain marked as unrelated for diagnostics, but count toward progress like every non-empty recording."""
|
|
@@ -665,7 +713,7 @@ def load_auth() -> SupabaseAuth | None:
|
|
| 665 |
" and ".join(missing), seen or "none")
|
| 666 |
return None
|
| 667 |
emails = lambda name: frozenset(re.split(r"[\s,;]+", os.environ.get(name, "").strip().lower())) - {""}
|
| 668 |
-
teachers, tutors = emails("TEACHER_EMAILS"), emails("TUTORS_EMAIL")
|
| 669 |
secret = os.environ.get("SUPABASE_SECRET_KEY", "").strip()
|
| 670 |
log.info("sign-in on: %s", "the students of the classes" if secret else "any account (no SUPABASE_SECRET_KEY)")
|
| 671 |
if os.environ.get("ALLOWED_EMAILS", "").strip():
|
|
@@ -674,4 +722,4 @@ def load_auth() -> SupabaseAuth | None:
|
|
| 674 |
log.warning("TEACHER_EMAILS is set without SUPABASE_SECRET_KEY: the management panel has no data to show")
|
| 675 |
if tutors and not secret:
|
| 676 |
log.warning("TUTORS_EMAIL is set without SUPABASE_SECRET_KEY: a flag cannot be saved")
|
| 677 |
-
return SupabaseAuth(url, key, teachers, secret, tutors)
|
|
|
|
| 45 |
and topic, written with the student's own token like the attempts, so it follows them to any device. The panel
|
| 46 |
reads every student's with the secret key.
|
| 47 |
|
| 48 |
+
Tutor: each conversation of the game ערבוט (see tutor.py), what the student said and how the tutor answered, in the
|
| 49 |
Supabase table `tutor_chats`, written with the secret key, for the teacher to read.
|
| 50 |
|
| 51 |
Env: SUPABASE_URL (https://<project-ref>.supabase.co)
|
| 52 |
SUPABASE_PUBLISHABLE_KEY (the publishable/anon key; it is public and also goes to the page)
|
| 53 |
TEACHER_EMAILS (optional: the accounts with the management panel, separated by commas or spaces)
|
| 54 |
TUTORS_EMAIL (optional: more accounts that flag a wrong score, as the teachers do; separated by commas or spaces)
|
| 55 |
+
DEVELOPER_EMAILS (optional bootstrap accounts with full access, including the Lab)
|
| 56 |
SUPABASE_SECRET_KEY (the secret/service-role key, needed by the panel, the classes and the flags; never public)
|
| 57 |
Without them the service is open, as before.
|
| 58 |
"""
|
|
|
|
| 90 |
|
| 91 |
class SupabaseAuth:
|
| 92 |
def __init__(self, url: str, key: str, teachers: frozenset[str] = frozenset(), secret: str = "",
|
| 93 |
+
tutors: frozenset[str] = frozenset(), developers: frozenset[str] = frozenset()):
|
| 94 |
self.url, self.key = url.rstrip("/"), key
|
| 95 |
self.teachers = teachers # lower-case emails of the accounts with the management panel
|
| 96 |
self.tutors = tutors # lower-case emails of the accounts that flag a wrong score, besides the teachers
|
| 97 |
+
self.developers = developers # bootstrap accounts; only developers may use the lab
|
| 98 |
self.secret = secret # reads every student's rows and the classes; empty = the panel has no data
|
| 99 |
self._cache: dict[str, tuple[float, dict]] = {}
|
| 100 |
self._classes: tuple[float, list[dict]] | None = None
|
| 101 |
self._videos: tuple[float, list[dict]] | None = None
|
| 102 |
self._texts: tuple[float, list[dict]] | None = None
|
| 103 |
self._ranked: tuple[float, frozenset[str] | None] | None = None
|
| 104 |
+
self._access: dict[str, tuple[float, dict | None]] = {}
|
| 105 |
self._level_videos: dict[str, tuple[float, list[dict]]] = {} # by table: the daily videos, the library
|
| 106 |
self._lock = threading.Lock()
|
| 107 |
|
|
|
|
| 602 |
break
|
| 603 |
return users
|
| 604 |
|
| 605 |
+
def access_for(self, user_id: str) -> dict | None:
|
| 606 |
+
"""The roles and student entitlements assigned to an account. None also means the migration table is absent."""
|
| 607 |
+
now = time.monotonic()
|
| 608 |
+
with self._lock:
|
| 609 |
+
hit = self._access.get(user_id)
|
| 610 |
+
if hit and hit[0] > now:
|
| 611 |
+
return hit[1]
|
| 612 |
+
try:
|
| 613 |
+
rows = self._admin("/rest/v1/user_access?" + urllib.parse.urlencode({
|
| 614 |
+
"user_id": f"eq.{user_id}", "select": "user_id,email,roles,entitlements,updated_at"}))
|
| 615 |
+
value = rows[0] if rows else None
|
| 616 |
+
except AuthUnavailable as e:
|
| 617 |
+
if "answered 404" not in str(e):
|
| 618 |
+
raise
|
| 619 |
+
value = None
|
| 620 |
+
with self._lock:
|
| 621 |
+
self._access[user_id] = (now + CLASSES_TTL, value)
|
| 622 |
+
return value
|
| 623 |
+
|
| 624 |
+
def access_rows(self) -> list[dict] | None:
|
| 625 |
+
"""All explicit access assignments, or None until the user_access table is installed."""
|
| 626 |
+
try:
|
| 627 |
+
return self._admin("/rest/v1/user_access?select=user_id,email,roles,entitlements,updated_at") or []
|
| 628 |
+
except AuthUnavailable as e:
|
| 629 |
+
if "answered 404" in str(e):
|
| 630 |
+
return None
|
| 631 |
+
raise
|
| 632 |
+
|
| 633 |
+
def set_access(self, target: dict, roles: list[str], entitlements: list[str], actor: dict) -> None:
|
| 634 |
+
"""Upsert an assignment and append a best-effort audit record."""
|
| 635 |
+
old = self.access_for(target["id"])
|
| 636 |
+
row = {"user_id": target["id"], "email": target["email"].lower(), "roles": roles,
|
| 637 |
+
"entitlements": entitlements, "updated_at": datetime.now(timezone.utc).isoformat(),
|
| 638 |
+
"updated_by": actor["id"]}
|
| 639 |
+
self._admin("/rest/v1/user_access?on_conflict=user_id", "POST", row,
|
| 640 |
+
prefer="resolution=merge-duplicates,return=minimal")
|
| 641 |
+
with self._lock:
|
| 642 |
+
self._access.pop(target["id"], None)
|
| 643 |
+
try:
|
| 644 |
+
self._admin("/rest/v1/access_audit", "POST",
|
| 645 |
+
{"target_user_id": target["id"], "changed_by": actor["id"],
|
| 646 |
+
"old_access": old or {}, "new_access": row}, prefer="return=minimal")
|
| 647 |
+
except AuthUnavailable as e:
|
| 648 |
+
log.warning("access changed but audit row was not stored: %s", e)
|
| 649 |
+
|
| 650 |
def all_attempts(self) -> list[dict]:
|
| 651 |
"""Every student's attempts, as `attempts` gives one student's, each with its user_id. "Different sentence"
|
| 652 |
rows remain marked as unrelated for diagnostics, but count toward progress like every non-empty recording."""
|
|
|
|
| 713 |
" and ".join(missing), seen or "none")
|
| 714 |
return None
|
| 715 |
emails = lambda name: frozenset(re.split(r"[\s,;]+", os.environ.get(name, "").strip().lower())) - {""}
|
| 716 |
+
teachers, tutors, developers = emails("TEACHER_EMAILS"), emails("TUTORS_EMAIL"), emails("DEVELOPER_EMAILS")
|
| 717 |
secret = os.environ.get("SUPABASE_SECRET_KEY", "").strip()
|
| 718 |
log.info("sign-in on: %s", "the students of the classes" if secret else "any account (no SUPABASE_SECRET_KEY)")
|
| 719 |
if os.environ.get("ALLOWED_EMAILS", "").strip():
|
|
|
|
| 722 |
log.warning("TEACHER_EMAILS is set without SUPABASE_SECRET_KEY: the management panel has no data to show")
|
| 723 |
if tutors and not secret:
|
| 724 |
log.warning("TUTORS_EMAIL is set without SUPABASE_SECRET_KEY: a flag cannot be saved")
|
| 725 |
+
return SupabaseAuth(url, key, teachers, secret, tutors, developers)
|
app/main.py
CHANGED
|
@@ -6,7 +6,7 @@ Env: MODEL_ID (default facebook/wav2vec2-xlsr-53-espeak-cv-ft, or a path to a
|
|
| 6 |
SUPABASE_URL, SUPABASE_PUBLISHABLE_KEY (Google sign-in, see app/auth.py)
|
| 7 |
TEACHER_EMAILS, SUPABASE_SECRET_KEY (the teacher's management panel, its classes and the lesson videos, see app/auth.py)
|
| 8 |
TUTORS_EMAIL (more accounts that, like the teachers, flag a recording scored wrong, see app/auth.py)
|
| 9 |
-
ANTHROPIC_API_KEY,
|
| 10 |
A local .env file is loaded if present; real environment variables win over it.
|
| 11 |
"""
|
| 12 |
from __future__ import annotations
|
|
@@ -41,7 +41,7 @@ from .speech_evaluation import SpeechEvaluationService
|
|
| 41 |
from .texts import read_line, text_phrases
|
| 42 |
from .tts import LINE_VOICES, RAEF_VOICE_ID, VOICES, SawtakTTS, TTSUnavailable, load_tts
|
| 43 |
from .tutor import (BY_ID, DAILY_LIMIT, MAX_TEXT, MAX_TURNS, SCENARIOS, Tutor, TutorLimit,
|
| 44 |
-
TutorUnavailable, load_tutor
|
| 45 |
from .verb_game import VerbExerciseGenerator
|
| 46 |
|
| 47 |
logging.basicConfig(level=logging.INFO)
|
|
@@ -156,6 +156,37 @@ CREATE_SCORING_RULES = ("create table public.scoring_rules (id text primary key,
|
|
| 156 |
# The students the teacher gave the tutor's rank (see auth.py): theirs in every class, so it is kept by email.
|
| 157 |
CREATE_TUTORS = ("create table public.tutors (email text primary key, granted_by text not null default '', "
|
| 158 |
"created_at timestamptz not null default now()); alter table public.tutors enable row level security;")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 159 |
MAX_NOTE = 500
|
| 160 |
MIGRATE_ATTEMPT_ISSUES = ("alter table public.attempts add column if not exists issues jsonb not null default '[]'::jsonb, "
|
| 161 |
"add column if not exists model text not null default '', "
|
|
@@ -386,21 +417,50 @@ def create_app(scorer: Scorer | None = None, tts: SawtakTTS | None = None,
|
|
| 386 |
except AuthUnavailable as e:
|
| 387 |
raise HTTPException(503, f"class list not available: {e}")
|
| 388 |
mine = [c for c in classes if email in c["emails"]] # a student may be in several classes
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 394 |
try:
|
| 395 |
-
|
|
|
|
| 396 |
except AuthUnavailable as e:
|
| 397 |
log.warning("tutors not read: %s", e)
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 404 |
|
| 405 |
members = [Depends(signed_in)]
|
| 406 |
|
|
@@ -463,16 +523,20 @@ def create_app(scorer: Scorer | None = None, tts: SawtakTTS | None = None,
|
|
| 463 |
several chooses one to practise in), for a teacher "dailies" (the daily videos of every class), and the lessons of all of them together (every lesson for a teacher, and for an account in no class). The page
|
| 464 |
asks this right after sign-in to learn whether the account is let in."""
|
| 465 |
mine = user["classes"] if user else []
|
| 466 |
-
|
|
|
|
| 467 |
[l for l in ALL_LESSONS if any(l in lessons_of(c) for c in mine)]
|
| 468 |
# a teacher is in no class, and sees the daily videos of every class, each once by its earliest day
|
| 469 |
every: dict[int, dict] = {}
|
| 470 |
-
|
|
|
|
| 471 |
if d["id"] not in every or d["date"] < every[d["id"]]["date"]:
|
| 472 |
every[d["id"]] = d
|
| 473 |
return {"email": user["email"] if user else "", "teacher": bool(user and user["teacher"]),
|
| 474 |
**({"tutor": True} if user and user["tutor"] else {}), # the page shows them the flag under a score
|
| 475 |
-
|
|
|
|
|
|
|
| 476 |
"classes": [{"name": c["name"], "lessons": lessons_of(c), **homework_of(c, topics()),
|
| 477 |
"dailies": dailies_of(c, daily_rows())} for c in mine],
|
| 478 |
"lessons": lessons}
|
|
@@ -483,7 +547,7 @@ def create_app(scorer: Scorer | None = None, tts: SawtakTTS | None = None,
|
|
| 483 |
s = summary(app.state.auth.attempts(user["token"]) if user else [], text_bank(text_rows()))
|
| 484 |
return {k: s[k] for k in ("best", "tries", "recordings", "days")}
|
| 485 |
|
| 486 |
-
@app.get("/api/writing")
|
| 487 |
def writing(user: dict | None = Depends(signed_in)):
|
| 488 |
"""The signed-in student's written homework, {topic id: its lines}. 503 when it cannot be read (or without
|
| 489 |
sign-in): the page then shows the copy it keeps on the device."""
|
|
@@ -495,7 +559,7 @@ def create_app(scorer: Scorer | None = None, tts: SawtakTTS | None = None,
|
|
| 495 |
raise HTTPException(503, f"written homework not available: {e}")
|
| 496 |
return {"writing": {t: lines[:WRITE_TOPICS[t]] for t, lines in mine.items() if t in WRITE_TOPICS}}
|
| 497 |
|
| 498 |
-
@app.put("/api/writing/{topic}")
|
| 499 |
def write(topic: str, body: dict = Body(...), user: dict | None = Depends(signed_in)):
|
| 500 |
"""Keeps what the student wrote in a writing topic: {"lines": a string per sentence, an empty one for a
|
| 501 |
sentence not written yet}, in place of what was kept before."""
|
|
@@ -590,6 +654,83 @@ def create_app(scorer: Scorer | None = None, tts: SawtakTTS | None = None,
|
|
| 590 |
raise HTTPException(503, f"Supabase לא זמין: {e}")
|
| 591 |
return {"ok": True}
|
| 592 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 593 |
@app.get("/api/flags")
|
| 594 |
def flags(status: str = Query("pending"), a: SupabaseAuth = Depends(teacher_only)):
|
| 595 |
"""The score reports awaiting a teacher's decision (or one reviewed state)."""
|
|
@@ -652,7 +793,7 @@ def create_app(scorer: Scorer | None = None, tts: SawtakTTS | None = None,
|
|
| 652 |
return HTTPException(503, f"Supabase לא זמין: {e}")
|
| 653 |
|
| 654 |
@app.get("/api/lab")
|
| 655 |
-
def lab_items(speaker: str = Query(""), a: SupabaseAuth = Depends(
|
| 656 |
user: dict | None = Depends(signed_in)):
|
| 657 |
"""The lab's diagnostic list, with how many recordings each item has (`counts`) and how many of them are
|
| 658 |
`speaker`'s, by default the signed-in teacher's (`mine`: the lab's test marks an item submitted by it; the
|
|
@@ -675,7 +816,7 @@ def create_app(scorer: Scorer | None = None, tts: SawtakTTS | None = None,
|
|
| 675 |
|
| 676 |
@app.post("/api/lab/score")
|
| 677 |
def lab_score(request: Request, item: str = Form(...), audio: UploadFile = File(...),
|
| 678 |
-
mistake: int = Form(-1), save: bool = Form(True), a: SupabaseAuth = Depends(
|
| 679 |
user: dict | None = Depends(signed_in)):
|
| 680 |
"""Scores a recording of a lab item as a practice recording is scored (with the native baseline), with the
|
| 681 |
teacher's stage-by-stage trace, and keeps it with its label unless `save` is off, as said by the signed-in
|
|
@@ -734,18 +875,18 @@ def create_app(scorer: Scorer | None = None, tts: SawtakTTS | None = None,
|
|
| 734 |
return found, data
|
| 735 |
|
| 736 |
@app.get("/api/lab/tts")
|
| 737 |
-
def lab_tts_voices(a: SupabaseAuth = Depends(
|
| 738 |
"""The voices the automatic test can use (none without TTS on this server)."""
|
| 739 |
return {"voices": list(LAB_TTS_VOICES) if app.state.tts else []}
|
| 740 |
|
| 741 |
@app.get("/api/lab/tts/{item}")
|
| 742 |
-
def lab_tts_listen(item: str, voice: str = Query(...), a: SupabaseAuth = Depends(
|
| 743 |
"""What the automatic test sent for an item: the voice's WAV (cached, so no new synthesis)."""
|
| 744 |
return Response(lab_tts_audio(item, voice)[1], media_type="audio/wav", headers={"Cache-Control": "private, no-store"})
|
| 745 |
|
| 746 |
@app.post("/api/lab/tts")
|
| 747 |
def lab_tts_score(item: str = Form(...), voice: str = Form(...), save: bool = Form(True),
|
| 748 |
-
a: SupabaseAuth = Depends(
|
| 749 |
"""The automatic test, one item: a TTS voice says it, and it is scored and kept as said right by the speaker
|
| 750 |
"TTS <voice>", like an approved take of the test. Scored without the native baseline, which is made of the same
|
| 751 |
voice and would measure every sound against itself. {"result", "saved", "audio", "speaker", "error"?}."""
|
|
@@ -770,7 +911,7 @@ def create_app(scorer: Scorer | None = None, tts: SawtakTTS | None = None,
|
|
| 770 |
return {"result": result, "saved": True, "audio": kept, "speaker": speaker}
|
| 771 |
|
| 772 |
@app.get("/api/lab/results")
|
| 773 |
-
def lab_results(speaker: str = Query(""), a: SupabaseAuth = Depends(
|
| 774 |
"""The benchmark of the lab's recordings as they were scored (see lab.benchmark), of one speaker or of all;
|
| 775 |
with the confirmed flags' false issues beside each sound. scripts/bench.py rescores them with the current scorer."""
|
| 776 |
try:
|
|
@@ -795,7 +936,7 @@ def create_app(scorer: Scorer | None = None, tts: SawtakTTS | None = None,
|
|
| 795 |
"recordings": recordings}
|
| 796 |
|
| 797 |
@app.get("/api/lab/minerva")
|
| 798 |
-
def lab_minerva(a: SupabaseAuth = Depends(
|
| 799 |
"""The imported Minerva audio joined with its reviewed JSON sentence metadata."""
|
| 800 |
try:
|
| 801 |
samples = a.lab_samples(full=True)
|
|
@@ -833,7 +974,7 @@ def create_app(scorer: Scorer | None = None, tts: SawtakTTS | None = None,
|
|
| 833 |
|
| 834 |
@app.delete("/api/lab/samples")
|
| 835 |
def lab_delete_samples(speaker: str | None = Query(None), everyone: bool = Query(False),
|
| 836 |
-
a: SupabaseAuth = Depends(
|
| 837 |
"""Deletes the lab's recordings, rows and files, to record the list afresh: one `speaker`'s ("" the unnamed),
|
| 838 |
or with `everyone` every speaker's. One of the two is required, so a missing parameter never deletes all.
|
| 839 |
{"deleted": how many recordings}."""
|
|
@@ -847,7 +988,7 @@ def create_app(scorer: Scorer | None = None, tts: SawtakTTS | None = None,
|
|
| 847 |
return {"deleted": n}
|
| 848 |
|
| 849 |
@app.get("/api/lab/samples/{sample_id}/audio")
|
| 850 |
-
def lab_sample_audio(sample_id: int, a: SupabaseAuth = Depends(
|
| 851 |
"""Streams a private saved lab recording to a teacher, including imported Minerva segments."""
|
| 852 |
try:
|
| 853 |
found = a.lab_audio(sample_id)
|
|
@@ -859,7 +1000,7 @@ def create_app(scorer: Scorer | None = None, tts: SawtakTTS | None = None,
|
|
| 859 |
return Response(data, media_type=media_type, headers={"Cache-Control": "private, no-store"})
|
| 860 |
|
| 861 |
@app.post("/api/lab/samples/{sample_id}/exclude-word")
|
| 862 |
-
def lab_exclude_word(sample_id: int, body: dict = Body(...), a: SupabaseAuth = Depends(
|
| 863 |
"""Includes or excludes one word from Minerva evaluation metrics, without changing the pipeline's score."""
|
| 864 |
word, excluded = body.get("word"), body.get("excluded")
|
| 865 |
if not isinstance(word, int) or word < 0 or not isinstance(excluded, bool):
|
|
@@ -889,7 +1030,7 @@ def create_app(scorer: Scorer | None = None, tts: SawtakTTS | None = None,
|
|
| 889 |
|
| 890 |
@app.post("/api/lab/samples/{sample_id}/rescore")
|
| 891 |
def lab_rescore_sample(sample_id: int, trace: bool = Query(False), setting: str = Query(""),
|
| 892 |
-
a: SupabaseAuth = Depends(
|
| 893 |
"""A lab recording scored again by the current scorer (as practice scores, with the native baseline), nothing
|
| 894 |
kept: {"id", "result": what the benchmark reads of it (lab.compact)}. The page rescores the recordings one by
|
| 895 |
one and sends the results to POST /api/lab/results.
|
|
@@ -966,7 +1107,7 @@ def create_app(scorer: Scorer | None = None, tts: SawtakTTS | None = None,
|
|
| 966 |
return out
|
| 967 |
|
| 968 |
@app.post("/api/lab/samples/{sample_id}/sweep")
|
| 969 |
-
def lab_sweep_sample(sample_id: int, a: SupabaseAuth = Depends(
|
| 970 |
"""A lab recording scored under each GOP setting of lab.SWEEP (GOP_RATIO_POOL x GOP_VOWEL_WINDOW), nothing kept.
|
| 971 |
The model runs once; each setting scores its posteriors against the native baseline rebuilt under it.
|
| 972 |
{"id", "results": {setting: what the benchmark reads (lab.compact)}}; the page sends them to POST /api/lab/sweep."""
|
|
@@ -995,7 +1136,7 @@ def create_app(scorer: Scorer | None = None, tts: SawtakTTS | None = None,
|
|
| 995 |
return {"id": sample_id, "results": results}
|
| 996 |
|
| 997 |
@app.post("/api/lab/sweep")
|
| 998 |
-
def lab_sweep_results(body: dict = Body(...), a: SupabaseAuth = Depends(
|
| 999 |
"""The benchmark of every setting from the sweeps of the recordings ({"results": {sample id: {setting: result}}}):
|
| 1000 |
{"settings": [{"key", "pool", "window", "quality", "partial", "totals", "vowels" (lab.vowel_stats),
|
| 1001 |
"changed": how many sound scores differ from max|wide's, "sounds"}] best first, "current": the server's own
|
|
@@ -1035,7 +1176,7 @@ def create_app(scorer: Scorer | None = None, tts: SawtakTTS | None = None,
|
|
| 1035 |
"model": MODEL_ID, "version": build_version()}
|
| 1036 |
|
| 1037 |
@app.post("/api/lab/results")
|
| 1038 |
-
def lab_rescored_results(body: dict = Body(...), a: SupabaseAuth = Depends(
|
| 1039 |
"""The benchmark of rescored recordings ({"results": {sample id: result}}, from the rescore above), beside the
|
| 1040 |
benchmark of the same recordings as they were stored: {"now", "stored", "model", "version"}."""
|
| 1041 |
given = body.get("results")
|
|
@@ -1061,7 +1202,7 @@ def create_app(scorer: Scorer | None = None, tts: SawtakTTS | None = None,
|
|
| 1061 |
"vowel_window": ("wide" if cfg.gop.vowel_window is None else f"±{cfg.gop.vowel_window}") if cfg else None}
|
| 1062 |
|
| 1063 |
@app.post("/api/lab/flags/{flag_id}/rescore")
|
| 1064 |
-
def lab_rescore_flag(flag_id: int, a: SupabaseAuth = Depends(
|
| 1065 |
"""A flagged recording scored again by the current scorer, against what was kept with the flag: {"old",
|
| 1066 |
"new": score and flagged sounds, "issues": the sounds a teacher marked as wrongly flagged, each with
|
| 1067 |
`still` (flagged again), "result": the new result with its trace}."""
|
|
@@ -1326,7 +1467,7 @@ def create_app(scorer: Scorer | None = None, tts: SawtakTTS | None = None,
|
|
| 1326 |
raise HTTPException(503, class_store_error(e))
|
| 1327 |
return {"ok": True}
|
| 1328 |
|
| 1329 |
-
@app.get("/api/videos")
|
| 1330 |
def videos(user: dict | None = Depends(signed_in)):
|
| 1331 |
"""The lesson videos, each lesson's in its order on the path: id, lesson, title, url (the Vimeo or YouTube link, for a teacher only), embed
|
| 1332 |
(its player, for the page's frame) and pos (how many of the lesson's own topics stand before it, see
|
|
@@ -1402,7 +1543,7 @@ def create_app(scorer: Scorer | None = None, tts: SawtakTTS | None = None,
|
|
| 1402 |
raise HTTPException(503, text_store_error(e) if "texts" in str(e) else video_store_error(e))
|
| 1403 |
return {"ok": True}
|
| 1404 |
|
| 1405 |
-
@app.get("/api/texts")
|
| 1406 |
def texts(user: dict | None = Depends(signed_in)):
|
| 1407 |
"""The teacher's texts as the page takes topics and phrases (see `/api/phrases`), for the lessons a video is
|
| 1408 |
given for (see `videos`). "categories": a topic per text, laid out as a story: id ("t<n>"), name, lesson, story,
|
|
@@ -1493,7 +1634,7 @@ def create_app(scorer: Scorer | None = None, tts: SawtakTTS | None = None,
|
|
| 1493 |
return {"dailies": [{"id": v["id"], "level": v["level"], "title": v["title"], "url": v["url"],
|
| 1494 |
"embed": video_embed(v["url"])} for v in rows if v["level"] in LEVEL_IDS]}
|
| 1495 |
|
| 1496 |
-
@app.get("/api/library")
|
| 1497 |
def library(user: dict | None = Depends(signed_in)):
|
| 1498 |
"""The video library, which stands outside the path and is one for every level and class: id, title, url
|
| 1499 |
(for a teacher only) and embed (its player) of each, in the teacher's order (see `order_library`)."""
|
|
@@ -1607,12 +1748,12 @@ def create_app(scorer: Scorer | None = None, tts: SawtakTTS | None = None,
|
|
| 1607 |
return [lesson for lesson in READY_LESSONS
|
| 1608 |
if any(lesson in lessons_of(course) for course in user["classes"])]
|
| 1609 |
|
| 1610 |
-
@app.get("/api/verb-game")
|
| 1611 |
def verb_game(user: dict | None = Depends(signed_in)):
|
| 1612 |
"""Configuration for "פועל יוצא" and the complete paradigms currently unlocked."""
|
| 1613 |
return app.state.verb_game.metadata(verb_lessons(user))
|
| 1614 |
|
| 1615 |
-
@app.post("/api/verb-game/question")
|
| 1616 |
def verb_question(body: dict = Body(...), user: dict | None = Depends(signed_in)):
|
| 1617 |
"""Create a Level 1--5 exercise; answers remain server-side."""
|
| 1618 |
try:
|
|
@@ -1625,7 +1766,7 @@ def create_app(scorer: Scorer | None = None, tts: SawtakTTS | None = None,
|
|
| 1625 |
except LookupError as e:
|
| 1626 |
raise HTTPException(404, str(e))
|
| 1627 |
|
| 1628 |
-
@app.post("/api/verb-game/answer")
|
| 1629 |
def verb_answer(body: dict = Body(...), _user: dict | None = Depends(signed_in)):
|
| 1630 |
"""Grade one opaque question once and return feedback plus measured client response time."""
|
| 1631 |
try:
|
|
@@ -1636,7 +1777,7 @@ def create_app(scorer: Scorer | None = None, tts: SawtakTTS | None = None,
|
|
| 1636 |
except LookupError as e:
|
| 1637 |
raise HTTPException(410, str(e))
|
| 1638 |
|
| 1639 |
-
@app.post("/api/verb-game/speech")
|
| 1640 |
def verb_speech(audio: UploadFile = File(...), question_id: str = Form(...),
|
| 1641 |
user: dict | None = Depends(signed_in)):
|
| 1642 |
"""Evaluate Levels 4–5 audio without turning uncertain recognition into an error."""
|
|
@@ -1682,12 +1823,9 @@ def create_app(scorer: Scorer | None = None, tts: SawtakTTS | None = None,
|
|
| 1682 |
return save_flag(phrase, result, data, audio.content_type, note, user)
|
| 1683 |
|
| 1684 |
def tutor_for(user: dict | None) -> Tutor:
|
| 1685 |
-
"""The tutor game,
|
| 1686 |
-
on a service with no sign-in. 404 for anyone else, 503 without a key."""
|
| 1687 |
if app.state.tutor is None:
|
| 1688 |
raise HTTPException(503, "המורה לא מוגדר בשרת (חסר ANTHROPIC_API_KEY)")
|
| 1689 |
-
if user and not user["teacher"] and not tutor_open():
|
| 1690 |
-
raise HTTPException(404, "not available")
|
| 1691 |
return app.state.tutor
|
| 1692 |
|
| 1693 |
def tutor_day(user: dict | None) -> tuple[str, str, int | None, object]:
|
|
@@ -1700,9 +1838,9 @@ def create_app(scorer: Scorer | None = None, tts: SawtakTTS | None = None,
|
|
| 1700 |
since = now.replace(hour=0, minute=0, second=0, microsecond=0).astimezone(timezone.utc).isoformat()
|
| 1701 |
return user["id"], day, DAILY_LIMIT, lambda: app.state.auth.tutor_chats_since(user["id"], since)
|
| 1702 |
|
| 1703 |
-
@app.get("/api/tutor")
|
| 1704 |
def tutor_info(user: dict | None = Depends(signed_in)):
|
| 1705 |
-
"""
|
| 1706 |
page shows those of the lessons the student has started), and how many conversations are left today (None: no
|
| 1707 |
limit)."""
|
| 1708 |
try:
|
|
@@ -1714,7 +1852,7 @@ def create_app(scorer: Scorer | None = None, tts: SawtakTTS | None = None,
|
|
| 1714 |
"left": None if limit is None else max(0, limit - t.started(student, day, seed)),
|
| 1715 |
"scenarios": [{k: s[k] for k in ("id", "lesson", "title", "desc", "who", "ar", "she")} for s in SCENARIOS]}
|
| 1716 |
|
| 1717 |
-
@app.post("/api/tutor/start")
|
| 1718 |
def tutor_start(tasks: BackgroundTasks, body: dict = Body(...), user: dict | None = Depends(signed_in)):
|
| 1719 |
"""A new conversation on a scenario card: {"scenario", "gender": "m" or "f"}. Gives its id, the tutor's opening
|
| 1720 |
message (see Tutor.message) and how many conversations are left today; 429 when none are, 502 when the model
|
|
@@ -1736,7 +1874,7 @@ def create_app(scorer: Scorer | None = None, tts: SawtakTTS | None = None,
|
|
| 1736 |
return {"id": chat.id, "message": opening, "turns": MAX_TURNS,
|
| 1737 |
"left": None if limit is None else max(0, limit - t.started(student, day))}
|
| 1738 |
|
| 1739 |
-
@app.post("/api/tutor/turn")
|
| 1740 |
def tutor_turn(tasks: BackgroundTasks, body: dict = Body(...), user: dict | None = Depends(signed_in)):
|
| 1741 |
"""The student's sentence, as the page heard it: {"id", "text"}. Gives the tutor's answer (see Tutor.turn)."""
|
| 1742 |
t = tutor_for(user)
|
|
@@ -1766,7 +1904,7 @@ def create_app(scorer: Scorer | None = None, tts: SawtakTTS | None = None,
|
|
| 1766 |
"rules": check_detectable(s.rules, lambda ph: s.vocab.sound_id(ph) is not None, s.vocab.model_id),
|
| 1767 |
"dialect_realisations_missing": {k: sorted(v) for k, v in s.vocab.class_missing.items()}}
|
| 1768 |
|
| 1769 |
-
@app.get("/api/tts/{phrase_id}", dependencies=
|
| 1770 |
def tts_phrase(phrase_id: int):
|
| 1771 |
"""The model answer spoken by Raef, or by a dialogue line's own voice. 503 tells the page to use the device voice."""
|
| 1772 |
names = {i: n for n, i in {**VOICES, **LINE_VOICES}.items()}
|
|
@@ -1797,7 +1935,7 @@ def create_app(scorer: Scorer | None = None, tts: SawtakTTS | None = None,
|
|
| 1797 |
app.state.refs.invalidate()
|
| 1798 |
return {"ok": True, "removed": removed}
|
| 1799 |
|
| 1800 |
-
@app.get("/api/prompt-audio/{phrase_id}", dependencies=
|
| 1801 |
def prompt_audio(phrase_id: int, engine: str = "gtts"):
|
| 1802 |
"""The Hebrew prompt read aloud (edge-tts or gTTS). 503 tells the page to stay silent."""
|
| 1803 |
phrase = phrase_of(phrase_id)
|
|
@@ -1810,7 +1948,7 @@ def create_app(scorer: Scorer | None = None, tts: SawtakTTS | None = None,
|
|
| 1810 |
return Response(data, media_type="audio/mpeg", headers={
|
| 1811 |
"Cache-Control": "private, max-age=86400", "X-TTS-Engine": used})
|
| 1812 |
|
| 1813 |
-
@app.get("/api/say", dependencies=
|
| 1814 |
def say(text: str = Query(..., min_length=1, max_length=400), engine: str = "gtts"):
|
| 1815 |
"""A short Hebrew text read aloud: driving mode's spoken messages."""
|
| 1816 |
if engine not in ENGINES:
|
|
@@ -1823,7 +1961,7 @@ def create_app(scorer: Scorer | None = None, tts: SawtakTTS | None = None,
|
|
| 1823 |
raise HTTPException(503, str(e))
|
| 1824 |
return Response(data, media_type="audio/mpeg", headers={"Cache-Control": "no-store", "X-TTS-Engine": used})
|
| 1825 |
|
| 1826 |
-
@app.post("/api/score")
|
| 1827 |
def score(tasks: BackgroundTasks, phrase_id: int = Form(...), audio: UploadFile = File(...),
|
| 1828 |
user: dict | None = Depends(signed_in)):
|
| 1829 |
phrase = phrase_of(phrase_id)
|
|
|
|
| 6 |
SUPABASE_URL, SUPABASE_PUBLISHABLE_KEY (Google sign-in, see app/auth.py)
|
| 7 |
TEACHER_EMAILS, SUPABASE_SECRET_KEY (the teacher's management panel, its classes and the lesson videos, see app/auth.py)
|
| 8 |
TUTORS_EMAIL (more accounts that, like the teachers, flag a recording scored wrong, see app/auth.py)
|
| 9 |
+
ANTHROPIC_API_KEY, TUTOR_MODEL (the permission-controlled AI tutor game ערבוט, see app/tutor.py)
|
| 10 |
A local .env file is loaded if present; real environment variables win over it.
|
| 11 |
"""
|
| 12 |
from __future__ import annotations
|
|
|
|
| 41 |
from .texts import read_line, text_phrases
|
| 42 |
from .tts import LINE_VOICES, RAEF_VOICE_ID, VOICES, SawtakTTS, TTSUnavailable, load_tts
|
| 43 |
from .tutor import (BY_ID, DAILY_LIMIT, MAX_TEXT, MAX_TURNS, SCENARIOS, Tutor, TutorLimit,
|
| 44 |
+
TutorUnavailable, load_tutor)
|
| 45 |
from .verb_game import VerbExerciseGenerator
|
| 46 |
|
| 47 |
logging.basicConfig(level=logging.INFO)
|
|
|
|
| 156 |
# The students the teacher gave the tutor's rank (see auth.py): theirs in every class, so it is kept by email.
|
| 157 |
CREATE_TUTORS = ("create table public.tutors (email text primary key, granted_by text not null default '', "
|
| 158 |
"created_at timestamptz not null default now()); alter table public.tutors enable row level security;")
|
| 159 |
+
CREATE_USER_ACCESS = ("create table public.user_access (user_id uuid primary key references auth.users(id) on delete cascade, "
|
| 160 |
+
"email text not null, roles text[] not null default array['student']::text[], "
|
| 161 |
+
"entitlements text[] not null default '{}'::text[], updated_at timestamptz not null default now(), "
|
| 162 |
+
"updated_by uuid references auth.users(id), "
|
| 163 |
+
"constraint valid_roles check (roles <@ array['student','teacher','flagger','admin','developer']::text[]), "
|
| 164 |
+
"constraint valid_entitlements check (entitlements <@ array['practice','games','tutor','path','library']::text[])); "
|
| 165 |
+
"create unique index user_access_email_idx on public.user_access (lower(email)); "
|
| 166 |
+
"alter table public.user_access enable row level security; "
|
| 167 |
+
"create table public.access_audit (id bigint generated always as identity primary key, "
|
| 168 |
+
"target_user_id uuid not null, changed_by uuid not null, old_access jsonb not null, "
|
| 169 |
+
"new_access jsonb not null, created_at timestamptz not null default now()); "
|
| 170 |
+
"alter table public.access_audit enable row level security;")
|
| 171 |
+
ROLES = frozenset({"student", "teacher", "flagger", "admin", "developer"})
|
| 172 |
+
MIGRATE_USER_ACCESS = ("alter table public.user_access drop constraint if exists valid_entitlements; "
|
| 173 |
+
"update public.user_access set entitlements = array_append(entitlements, 'practice') "
|
| 174 |
+
"where 'path' = any(entitlements) and not ('practice' = any(entitlements)); "
|
| 175 |
+
"alter table public.user_access add constraint valid_entitlements check "
|
| 176 |
+
"(entitlements <@ array['practice','games','tutor','path','library']::text[]);")
|
| 177 |
+
ENTITLEMENTS = frozenset({"practice", "games", "tutor", "path", "library"})
|
| 178 |
+
DEFAULT_ENTITLEMENTS = ENTITLEMENTS - {"tutor"} # the paid AI tutor is always an explicit grant
|
| 179 |
+
ROLE_PERMISSIONS = {
|
| 180 |
+
"student": frozenset(),
|
| 181 |
+
"teacher": frozenset({"exercises.use_all", "students.view", "games.use", "path.use", "exercises.use", "library.view"}),
|
| 182 |
+
"flagger": frozenset({"flags.create"}),
|
| 183 |
+
"admin": frozenset({"exercises.use_all", "students.view", "management.access", "users.manage",
|
| 184 |
+
"classes.manage", "content.manage", "flags.review", "games.use", "path.use",
|
| 185 |
+
"exercises.use", "library.view"}),
|
| 186 |
+
"developer": frozenset({"*"}),
|
| 187 |
+
}
|
| 188 |
+
ENTITLEMENT_PERMISSIONS = {"practice": {"practice.use", "exercises.use"}, "games": {"games.use"},
|
| 189 |
+
"tutor": {"tutor.use"}, "path": {"path.use"}, "library": {"library.view"}}
|
| 190 |
MAX_NOTE = 500
|
| 191 |
MIGRATE_ATTEMPT_ISSUES = ("alter table public.attempts add column if not exists issues jsonb not null default '[]'::jsonb, "
|
| 192 |
"add column if not exists model text not null default '', "
|
|
|
|
| 417 |
except AuthUnavailable as e:
|
| 418 |
raise HTTPException(503, f"class list not available: {e}")
|
| 419 |
mine = [c for c in classes if email in c["emails"]] # a student may be in several classes
|
| 420 |
+
roles, entitlements = {"student"}, set(DEFAULT_ENTITLEMENTS)
|
| 421 |
+
if hasattr(a, "access_for"):
|
| 422 |
+
try:
|
| 423 |
+
assigned = a.access_for(user["id"])
|
| 424 |
+
except AuthUnavailable as e:
|
| 425 |
+
raise HTTPException(503, f"permissions not available: {e}")
|
| 426 |
+
if assigned:
|
| 427 |
+
roles = set(assigned.get("roles") or ["student"]) & ROLES
|
| 428 |
+
entitlements = set(assigned.get("entitlements") or []) & ENTITLEMENTS
|
| 429 |
+
# Legacy environment assignments retain their old abilities while deployments move to user_access.
|
| 430 |
+
if email in getattr(a, "teachers", ()):
|
| 431 |
+
roles.update({"teacher", "admin", "flagger"})
|
| 432 |
+
if email in getattr(a, "tutors", ()):
|
| 433 |
+
roles.add("flagger")
|
| 434 |
+
if email in getattr(a, "developers", ()):
|
| 435 |
+
roles.add("developer")
|
| 436 |
+
if "flagger" not in roles:
|
| 437 |
try:
|
| 438 |
+
if email in (a.ranked() or ()):
|
| 439 |
+
roles.add("flagger")
|
| 440 |
except AuthUnavailable as e:
|
| 441 |
log.warning("tutors not read: %s", e)
|
| 442 |
+
privileged = roles - {"student"}
|
| 443 |
+
if classes and not mine and not privileged and not entitlements:
|
| 444 |
+
raise HTTPException(403, "this account is not on the list")
|
| 445 |
+
permissions = set().union(*(ROLE_PERMISSIONS[r] for r in roles))
|
| 446 |
+
permissions.update(*[ENTITLEMENT_PERMISSIONS[e] for e in entitlements])
|
| 447 |
+
return {**user, "token": token.strip(), "roles": sorted(roles), "entitlements": sorted(entitlements),
|
| 448 |
+
"permissions": sorted(permissions), "teacher": bool(roles & {"teacher", "admin", "developer"}),
|
| 449 |
+
"tutor": "flags.create" in permissions or "*" in permissions, "classes": mine}
|
| 450 |
+
|
| 451 |
+
def require(permission: str):
|
| 452 |
+
def allowed(user: dict | None = Depends(signed_in)) -> SupabaseAuth:
|
| 453 |
+
if app.state.auth is None: # authentication is optional in local/open deployments
|
| 454 |
+
return app.state.auth
|
| 455 |
+
permissions = set(user.get("permissions", ())) if user else set()
|
| 456 |
+
if "*" not in permissions and permission not in permissions:
|
| 457 |
+
raise HTTPException(403, f"missing permission: {permission}")
|
| 458 |
+
return app.state.auth
|
| 459 |
+
return allowed
|
| 460 |
+
|
| 461 |
+
admin_only = require("management.access")
|
| 462 |
+
lab_only = require("lab.access")
|
| 463 |
+
teacher_only = admin_only # compatibility name for the management endpoints below
|
| 464 |
|
| 465 |
members = [Depends(signed_in)]
|
| 466 |
|
|
|
|
| 523 |
several chooses one to practise in), for a teacher "dailies" (the daily videos of every class), and the lessons of all of them together (every lesson for a teacher, and for an account in no class). The page
|
| 524 |
asks this right after sign-in to learn whether the account is let in."""
|
| 525 |
mine = user["classes"] if user else []
|
| 526 |
+
can_all = bool(user and ({"*", "exercises.use_all"} & set(user.get("permissions", ()))))
|
| 527 |
+
lessons = ALL_LESSONS if not mine or can_all else \
|
| 528 |
[l for l in ALL_LESSONS if any(l in lessons_of(c) for c in mine)]
|
| 529 |
# a teacher is in no class, and sees the daily videos of every class, each once by its earliest day
|
| 530 |
every: dict[int, dict] = {}
|
| 531 |
+
can_manage = bool(user and ({"*", "management.access"} & set(user.get("permissions", ()))))
|
| 532 |
+
for d in [d for c in app.state.auth.classes() for d in dailies_of(c, daily_rows())] if can_manage else []:
|
| 533 |
if d["id"] not in every or d["date"] < every[d["id"]]["date"]:
|
| 534 |
every[d["id"]] = d
|
| 535 |
return {"email": user["email"] if user else "", "teacher": bool(user and user["teacher"]),
|
| 536 |
**({"tutor": True} if user and user["tutor"] else {}), # the page shows them the flag under a score
|
| 537 |
+
"roles": user.get("roles", []) if user else [], "entitlements": user.get("entitlements", []) if user else [],
|
| 538 |
+
"permissions": user.get("permissions", []) if user else ["*"],
|
| 539 |
+
**({"dailies": sorted(every.values(), key=lambda d: (d["date"], d["id"]))} if can_all else {}),
|
| 540 |
"classes": [{"name": c["name"], "lessons": lessons_of(c), **homework_of(c, topics()),
|
| 541 |
"dailies": dailies_of(c, daily_rows())} for c in mine],
|
| 542 |
"lessons": lessons}
|
|
|
|
| 547 |
s = summary(app.state.auth.attempts(user["token"]) if user else [], text_bank(text_rows()))
|
| 548 |
return {k: s[k] for k in ("best", "tries", "recordings", "days")}
|
| 549 |
|
| 550 |
+
@app.get("/api/writing", dependencies=[Depends(require("practice.use"))])
|
| 551 |
def writing(user: dict | None = Depends(signed_in)):
|
| 552 |
"""The signed-in student's written homework, {topic id: its lines}. 503 when it cannot be read (or without
|
| 553 |
sign-in): the page then shows the copy it keeps on the device."""
|
|
|
|
| 559 |
raise HTTPException(503, f"written homework not available: {e}")
|
| 560 |
return {"writing": {t: lines[:WRITE_TOPICS[t]] for t, lines in mine.items() if t in WRITE_TOPICS}}
|
| 561 |
|
| 562 |
+
@app.put("/api/writing/{topic}", dependencies=[Depends(require("practice.use"))])
|
| 563 |
def write(topic: str, body: dict = Body(...), user: dict | None = Depends(signed_in)):
|
| 564 |
"""Keeps what the student wrote in a writing topic: {"lines": a string per sentence, an empty one for a
|
| 565 |
sentence not written yet}, in place of what was kept before."""
|
|
|
|
| 654 |
raise HTTPException(503, f"Supabase לא זמין: {e}")
|
| 655 |
return {"ok": True}
|
| 656 |
|
| 657 |
+
@app.get("/api/access/users")
|
| 658 |
+
def access_users(a: SupabaseAuth = Depends(require("users.manage")),
|
| 659 |
+
actor: dict | None = Depends(signed_in)):
|
| 660 |
+
"""All accounts and their explicit roles/entitlements for the permission editor."""
|
| 661 |
+
if not hasattr(a, "access_rows"):
|
| 662 |
+
return {"users": [], "setup": CREATE_USER_ACCESS, "migration": MIGRATE_USER_ACCESS,
|
| 663 |
+
"me": actor["id"] if actor else ""}
|
| 664 |
+
try:
|
| 665 |
+
users, rows = a.users(), a.access_rows()
|
| 666 |
+
except AuthUnavailable as e:
|
| 667 |
+
raise HTTPException(503, f"Supabase לא זמין: {e}")
|
| 668 |
+
if rows is None:
|
| 669 |
+
return {"users": [], "setup": CREATE_USER_ACCESS, "migration": MIGRATE_USER_ACCESS,
|
| 670 |
+
"me": actor["id"] if actor else ""}
|
| 671 |
+
assigned = {r["user_id"]: r for r in rows}
|
| 672 |
+
result = []
|
| 673 |
+
for account in users:
|
| 674 |
+
row = assigned.get(account["id"], {})
|
| 675 |
+
email = account["email"].lower()
|
| 676 |
+
roles = set(row.get("roles") or ["student"])
|
| 677 |
+
fixed = []
|
| 678 |
+
if email in getattr(a, "teachers", ()):
|
| 679 |
+
roles.update({"teacher", "admin", "flagger"}); fixed += ["teacher", "admin", "flagger"]
|
| 680 |
+
if email in getattr(a, "tutors", ()):
|
| 681 |
+
roles.add("flagger"); fixed.append("flagger")
|
| 682 |
+
if email in getattr(a, "developers", ()):
|
| 683 |
+
roles.add("developer"); fixed.append("developer")
|
| 684 |
+
entitlements = (set(row.get("entitlements") or []) if row else set(DEFAULT_ENTITLEMENTS)) & ENTITLEMENTS
|
| 685 |
+
effective = set().union(*(ROLE_PERMISSIONS[r] for r in roles & ROLES))
|
| 686 |
+
effective.update(*[ENTITLEMENT_PERMISSIONS[e] for e in entitlements])
|
| 687 |
+
result.append({**account, "roles": sorted(roles & ROLES),
|
| 688 |
+
"entitlements": sorted(entitlements), "permissions": sorted(effective),
|
| 689 |
+
"fixed_roles": sorted(set(fixed))})
|
| 690 |
+
return {"users": result, "setup": "", "migration": MIGRATE_USER_ACCESS,
|
| 691 |
+
"me": actor["id"] if actor else ""}
|
| 692 |
+
|
| 693 |
+
@app.put("/api/access/users/{target_id}")
|
| 694 |
+
def update_access(target_id: str, body: dict = Body(...),
|
| 695 |
+
a: SupabaseAuth = Depends(require("users.manage")),
|
| 696 |
+
actor: dict | None = Depends(signed_in)):
|
| 697 |
+
roles, entitlements = body.get("roles"), body.get("entitlements")
|
| 698 |
+
if not isinstance(roles, list) or not roles or not all(isinstance(x, str) for x in roles):
|
| 699 |
+
raise HTTPException(400, "roles must be a non-empty list")
|
| 700 |
+
if not isinstance(entitlements, list) or not all(isinstance(x, str) for x in entitlements):
|
| 701 |
+
raise HTTPException(400, "entitlements must be a list")
|
| 702 |
+
roles, entitlements = set(roles), set(entitlements)
|
| 703 |
+
if not roles <= ROLES or not entitlements <= ENTITLEMENTS:
|
| 704 |
+
raise HTTPException(400, "unknown role or entitlement")
|
| 705 |
+
if not actor or target_id == actor["id"]:
|
| 706 |
+
raise HTTPException(403, "you cannot change your own access")
|
| 707 |
+
is_developer = "*" in actor.get("permissions", ())
|
| 708 |
+
try:
|
| 709 |
+
users = a.users()
|
| 710 |
+
target = next((u for u in users if u["id"] == target_id), None)
|
| 711 |
+
if not target:
|
| 712 |
+
raise HTTPException(404, "account not found")
|
| 713 |
+
old = a.access_for(target_id) if hasattr(a, "access_for") else None
|
| 714 |
+
old_roles = set((old or {}).get("roles") or ["student"])
|
| 715 |
+
if (("developer" in roles) != ("developer" in old_roles)) and not is_developer:
|
| 716 |
+
raise HTTPException(403, "only developers can change developer access")
|
| 717 |
+
if target["email"].lower() in getattr(a, "developers", ()) and "developer" not in roles:
|
| 718 |
+
raise HTTPException(403, "this developer is configured by the server")
|
| 719 |
+
if "developer" in old_roles and "developer" not in roles:
|
| 720 |
+
rows = a.access_rows() or []
|
| 721 |
+
remaining = sum("developer" in (r.get("roles") or []) and r.get("user_id") != target_id for r in rows)
|
| 722 |
+
remaining += sum(e != target["email"].lower() for e in getattr(a, "developers", ()))
|
| 723 |
+
if not remaining:
|
| 724 |
+
raise HTTPException(409, "the last developer cannot be removed")
|
| 725 |
+
a.set_access(target, sorted(roles), sorted(entitlements), actor)
|
| 726 |
+
except HTTPException:
|
| 727 |
+
raise
|
| 728 |
+
except AuthUnavailable as e:
|
| 729 |
+
if "answered 404" in str(e):
|
| 730 |
+
raise HTTPException(503, f"permissions table is missing; run: {CREATE_USER_ACCESS}")
|
| 731 |
+
raise HTTPException(503, f"Supabase לא זמין: {e}")
|
| 732 |
+
return {"ok": True}
|
| 733 |
+
|
| 734 |
@app.get("/api/flags")
|
| 735 |
def flags(status: str = Query("pending"), a: SupabaseAuth = Depends(teacher_only)):
|
| 736 |
"""The score reports awaiting a teacher's decision (or one reviewed state)."""
|
|
|
|
| 793 |
return HTTPException(503, f"Supabase לא זמין: {e}")
|
| 794 |
|
| 795 |
@app.get("/api/lab")
|
| 796 |
+
def lab_items(speaker: str = Query(""), a: SupabaseAuth = Depends(lab_only),
|
| 797 |
user: dict | None = Depends(signed_in)):
|
| 798 |
"""The lab's diagnostic list, with how many recordings each item has (`counts`) and how many of them are
|
| 799 |
`speaker`'s, by default the signed-in teacher's (`mine`: the lab's test marks an item submitted by it; the
|
|
|
|
| 816 |
|
| 817 |
@app.post("/api/lab/score")
|
| 818 |
def lab_score(request: Request, item: str = Form(...), audio: UploadFile = File(...),
|
| 819 |
+
mistake: int = Form(-1), save: bool = Form(True), a: SupabaseAuth = Depends(lab_only),
|
| 820 |
user: dict | None = Depends(signed_in)):
|
| 821 |
"""Scores a recording of a lab item as a practice recording is scored (with the native baseline), with the
|
| 822 |
teacher's stage-by-stage trace, and keeps it with its label unless `save` is off, as said by the signed-in
|
|
|
|
| 875 |
return found, data
|
| 876 |
|
| 877 |
@app.get("/api/lab/tts")
|
| 878 |
+
def lab_tts_voices(a: SupabaseAuth = Depends(lab_only)):
|
| 879 |
"""The voices the automatic test can use (none without TTS on this server)."""
|
| 880 |
return {"voices": list(LAB_TTS_VOICES) if app.state.tts else []}
|
| 881 |
|
| 882 |
@app.get("/api/lab/tts/{item}")
|
| 883 |
+
def lab_tts_listen(item: str, voice: str = Query(...), a: SupabaseAuth = Depends(lab_only)):
|
| 884 |
"""What the automatic test sent for an item: the voice's WAV (cached, so no new synthesis)."""
|
| 885 |
return Response(lab_tts_audio(item, voice)[1], media_type="audio/wav", headers={"Cache-Control": "private, no-store"})
|
| 886 |
|
| 887 |
@app.post("/api/lab/tts")
|
| 888 |
def lab_tts_score(item: str = Form(...), voice: str = Form(...), save: bool = Form(True),
|
| 889 |
+
a: SupabaseAuth = Depends(lab_only), user: dict | None = Depends(signed_in)):
|
| 890 |
"""The automatic test, one item: a TTS voice says it, and it is scored and kept as said right by the speaker
|
| 891 |
"TTS <voice>", like an approved take of the test. Scored without the native baseline, which is made of the same
|
| 892 |
voice and would measure every sound against itself. {"result", "saved", "audio", "speaker", "error"?}."""
|
|
|
|
| 911 |
return {"result": result, "saved": True, "audio": kept, "speaker": speaker}
|
| 912 |
|
| 913 |
@app.get("/api/lab/results")
|
| 914 |
+
def lab_results(speaker: str = Query(""), a: SupabaseAuth = Depends(lab_only)):
|
| 915 |
"""The benchmark of the lab's recordings as they were scored (see lab.benchmark), of one speaker or of all;
|
| 916 |
with the confirmed flags' false issues beside each sound. scripts/bench.py rescores them with the current scorer."""
|
| 917 |
try:
|
|
|
|
| 936 |
"recordings": recordings}
|
| 937 |
|
| 938 |
@app.get("/api/lab/minerva")
|
| 939 |
+
def lab_minerva(a: SupabaseAuth = Depends(lab_only)):
|
| 940 |
"""The imported Minerva audio joined with its reviewed JSON sentence metadata."""
|
| 941 |
try:
|
| 942 |
samples = a.lab_samples(full=True)
|
|
|
|
| 974 |
|
| 975 |
@app.delete("/api/lab/samples")
|
| 976 |
def lab_delete_samples(speaker: str | None = Query(None), everyone: bool = Query(False),
|
| 977 |
+
a: SupabaseAuth = Depends(lab_only)):
|
| 978 |
"""Deletes the lab's recordings, rows and files, to record the list afresh: one `speaker`'s ("" the unnamed),
|
| 979 |
or with `everyone` every speaker's. One of the two is required, so a missing parameter never deletes all.
|
| 980 |
{"deleted": how many recordings}."""
|
|
|
|
| 988 |
return {"deleted": n}
|
| 989 |
|
| 990 |
@app.get("/api/lab/samples/{sample_id}/audio")
|
| 991 |
+
def lab_sample_audio(sample_id: int, a: SupabaseAuth = Depends(lab_only)):
|
| 992 |
"""Streams a private saved lab recording to a teacher, including imported Minerva segments."""
|
| 993 |
try:
|
| 994 |
found = a.lab_audio(sample_id)
|
|
|
|
| 1000 |
return Response(data, media_type=media_type, headers={"Cache-Control": "private, no-store"})
|
| 1001 |
|
| 1002 |
@app.post("/api/lab/samples/{sample_id}/exclude-word")
|
| 1003 |
+
def lab_exclude_word(sample_id: int, body: dict = Body(...), a: SupabaseAuth = Depends(lab_only)):
|
| 1004 |
"""Includes or excludes one word from Minerva evaluation metrics, without changing the pipeline's score."""
|
| 1005 |
word, excluded = body.get("word"), body.get("excluded")
|
| 1006 |
if not isinstance(word, int) or word < 0 or not isinstance(excluded, bool):
|
|
|
|
| 1030 |
|
| 1031 |
@app.post("/api/lab/samples/{sample_id}/rescore")
|
| 1032 |
def lab_rescore_sample(sample_id: int, trace: bool = Query(False), setting: str = Query(""),
|
| 1033 |
+
a: SupabaseAuth = Depends(lab_only)):
|
| 1034 |
"""A lab recording scored again by the current scorer (as practice scores, with the native baseline), nothing
|
| 1035 |
kept: {"id", "result": what the benchmark reads of it (lab.compact)}. The page rescores the recordings one by
|
| 1036 |
one and sends the results to POST /api/lab/results.
|
|
|
|
| 1107 |
return out
|
| 1108 |
|
| 1109 |
@app.post("/api/lab/samples/{sample_id}/sweep")
|
| 1110 |
+
def lab_sweep_sample(sample_id: int, a: SupabaseAuth = Depends(lab_only)):
|
| 1111 |
"""A lab recording scored under each GOP setting of lab.SWEEP (GOP_RATIO_POOL x GOP_VOWEL_WINDOW), nothing kept.
|
| 1112 |
The model runs once; each setting scores its posteriors against the native baseline rebuilt under it.
|
| 1113 |
{"id", "results": {setting: what the benchmark reads (lab.compact)}}; the page sends them to POST /api/lab/sweep."""
|
|
|
|
| 1136 |
return {"id": sample_id, "results": results}
|
| 1137 |
|
| 1138 |
@app.post("/api/lab/sweep")
|
| 1139 |
+
def lab_sweep_results(body: dict = Body(...), a: SupabaseAuth = Depends(lab_only)):
|
| 1140 |
"""The benchmark of every setting from the sweeps of the recordings ({"results": {sample id: {setting: result}}}):
|
| 1141 |
{"settings": [{"key", "pool", "window", "quality", "partial", "totals", "vowels" (lab.vowel_stats),
|
| 1142 |
"changed": how many sound scores differ from max|wide's, "sounds"}] best first, "current": the server's own
|
|
|
|
| 1176 |
"model": MODEL_ID, "version": build_version()}
|
| 1177 |
|
| 1178 |
@app.post("/api/lab/results")
|
| 1179 |
+
def lab_rescored_results(body: dict = Body(...), a: SupabaseAuth = Depends(lab_only)):
|
| 1180 |
"""The benchmark of rescored recordings ({"results": {sample id: result}}, from the rescore above), beside the
|
| 1181 |
benchmark of the same recordings as they were stored: {"now", "stored", "model", "version"}."""
|
| 1182 |
given = body.get("results")
|
|
|
|
| 1202 |
"vowel_window": ("wide" if cfg.gop.vowel_window is None else f"±{cfg.gop.vowel_window}") if cfg else None}
|
| 1203 |
|
| 1204 |
@app.post("/api/lab/flags/{flag_id}/rescore")
|
| 1205 |
+
def lab_rescore_flag(flag_id: int, a: SupabaseAuth = Depends(lab_only)):
|
| 1206 |
"""A flagged recording scored again by the current scorer, against what was kept with the flag: {"old",
|
| 1207 |
"new": score and flagged sounds, "issues": the sounds a teacher marked as wrongly flagged, each with
|
| 1208 |
`still` (flagged again), "result": the new result with its trace}."""
|
|
|
|
| 1467 |
raise HTTPException(503, class_store_error(e))
|
| 1468 |
return {"ok": True}
|
| 1469 |
|
| 1470 |
+
@app.get("/api/videos", dependencies=[Depends(require("path.use"))])
|
| 1471 |
def videos(user: dict | None = Depends(signed_in)):
|
| 1472 |
"""The lesson videos, each lesson's in its order on the path: id, lesson, title, url (the Vimeo or YouTube link, for a teacher only), embed
|
| 1473 |
(its player, for the page's frame) and pos (how many of the lesson's own topics stand before it, see
|
|
|
|
| 1543 |
raise HTTPException(503, text_store_error(e) if "texts" in str(e) else video_store_error(e))
|
| 1544 |
return {"ok": True}
|
| 1545 |
|
| 1546 |
+
@app.get("/api/texts", dependencies=[Depends(require("path.use"))])
|
| 1547 |
def texts(user: dict | None = Depends(signed_in)):
|
| 1548 |
"""The teacher's texts as the page takes topics and phrases (see `/api/phrases`), for the lessons a video is
|
| 1549 |
given for (see `videos`). "categories": a topic per text, laid out as a story: id ("t<n>"), name, lesson, story,
|
|
|
|
| 1634 |
return {"dailies": [{"id": v["id"], "level": v["level"], "title": v["title"], "url": v["url"],
|
| 1635 |
"embed": video_embed(v["url"])} for v in rows if v["level"] in LEVEL_IDS]}
|
| 1636 |
|
| 1637 |
+
@app.get("/api/library", dependencies=[Depends(require("library.view"))])
|
| 1638 |
def library(user: dict | None = Depends(signed_in)):
|
| 1639 |
"""The video library, which stands outside the path and is one for every level and class: id, title, url
|
| 1640 |
(for a teacher only) and embed (its player) of each, in the teacher's order (see `order_library`)."""
|
|
|
|
| 1748 |
return [lesson for lesson in READY_LESSONS
|
| 1749 |
if any(lesson in lessons_of(course) for course in user["classes"])]
|
| 1750 |
|
| 1751 |
+
@app.get("/api/verb-game", dependencies=[Depends(require("games.use"))])
|
| 1752 |
def verb_game(user: dict | None = Depends(signed_in)):
|
| 1753 |
"""Configuration for "פועל יוצא" and the complete paradigms currently unlocked."""
|
| 1754 |
return app.state.verb_game.metadata(verb_lessons(user))
|
| 1755 |
|
| 1756 |
+
@app.post("/api/verb-game/question", dependencies=[Depends(require("games.use"))])
|
| 1757 |
def verb_question(body: dict = Body(...), user: dict | None = Depends(signed_in)):
|
| 1758 |
"""Create a Level 1--5 exercise; answers remain server-side."""
|
| 1759 |
try:
|
|
|
|
| 1766 |
except LookupError as e:
|
| 1767 |
raise HTTPException(404, str(e))
|
| 1768 |
|
| 1769 |
+
@app.post("/api/verb-game/answer", dependencies=[Depends(require("games.use"))])
|
| 1770 |
def verb_answer(body: dict = Body(...), _user: dict | None = Depends(signed_in)):
|
| 1771 |
"""Grade one opaque question once and return feedback plus measured client response time."""
|
| 1772 |
try:
|
|
|
|
| 1777 |
except LookupError as e:
|
| 1778 |
raise HTTPException(410, str(e))
|
| 1779 |
|
| 1780 |
+
@app.post("/api/verb-game/speech", dependencies=[Depends(require("games.use"))])
|
| 1781 |
def verb_speech(audio: UploadFile = File(...), question_id: str = Form(...),
|
| 1782 |
user: dict | None = Depends(signed_in)):
|
| 1783 |
"""Evaluate Levels 4–5 audio without turning uncertain recognition into an error."""
|
|
|
|
| 1823 |
return save_flag(phrase, result, data, audio.content_type, note, user)
|
| 1824 |
|
| 1825 |
def tutor_for(user: dict | None) -> Tutor:
|
| 1826 |
+
"""The paid tutor game, after the tutor.use dependency authorized the account (or on an open service)."""
|
|
|
|
| 1827 |
if app.state.tutor is None:
|
| 1828 |
raise HTTPException(503, "המורה לא מוגדר בשרת (חסר ANTHROPIC_API_KEY)")
|
|
|
|
|
|
|
| 1829 |
return app.state.tutor
|
| 1830 |
|
| 1831 |
def tutor_day(user: dict | None) -> tuple[str, str, int | None, object]:
|
|
|
|
| 1838 |
since = now.replace(hour=0, minute=0, second=0, microsecond=0).astimezone(timezone.utc).isoformat()
|
| 1839 |
return user["id"], day, DAILY_LIMIT, lambda: app.state.auth.tutor_chats_since(user["id"], since)
|
| 1840 |
|
| 1841 |
+
@app.get("/api/tutor", dependencies=[Depends(require("tutor.use"))])
|
| 1842 |
def tutor_info(user: dict | None = Depends(signed_in)):
|
| 1843 |
+
"""ערבוט: whether this account may play, its scenario cards (one for each lesson, in the course's order; the
|
| 1844 |
page shows those of the lessons the student has started), and how many conversations are left today (None: no
|
| 1845 |
limit)."""
|
| 1846 |
try:
|
|
|
|
| 1852 |
"left": None if limit is None else max(0, limit - t.started(student, day, seed)),
|
| 1853 |
"scenarios": [{k: s[k] for k in ("id", "lesson", "title", "desc", "who", "ar", "she")} for s in SCENARIOS]}
|
| 1854 |
|
| 1855 |
+
@app.post("/api/tutor/start", dependencies=[Depends(require("tutor.use"))])
|
| 1856 |
def tutor_start(tasks: BackgroundTasks, body: dict = Body(...), user: dict | None = Depends(signed_in)):
|
| 1857 |
"""A new conversation on a scenario card: {"scenario", "gender": "m" or "f"}. Gives its id, the tutor's opening
|
| 1858 |
message (see Tutor.message) and how many conversations are left today; 429 when none are, 502 when the model
|
|
|
|
| 1874 |
return {"id": chat.id, "message": opening, "turns": MAX_TURNS,
|
| 1875 |
"left": None if limit is None else max(0, limit - t.started(student, day))}
|
| 1876 |
|
| 1877 |
+
@app.post("/api/tutor/turn", dependencies=[Depends(require("tutor.use"))])
|
| 1878 |
def tutor_turn(tasks: BackgroundTasks, body: dict = Body(...), user: dict | None = Depends(signed_in)):
|
| 1879 |
"""The student's sentence, as the page heard it: {"id", "text"}. Gives the tutor's answer (see Tutor.turn)."""
|
| 1880 |
t = tutor_for(user)
|
|
|
|
| 1904 |
"rules": check_detectable(s.rules, lambda ph: s.vocab.sound_id(ph) is not None, s.vocab.model_id),
|
| 1905 |
"dialect_realisations_missing": {k: sorted(v) for k, v in s.vocab.class_missing.items()}}
|
| 1906 |
|
| 1907 |
+
@app.get("/api/tts/{phrase_id}", dependencies=[Depends(require("practice.use"))])
|
| 1908 |
def tts_phrase(phrase_id: int):
|
| 1909 |
"""The model answer spoken by Raef, or by a dialogue line's own voice. 503 tells the page to use the device voice."""
|
| 1910 |
names = {i: n for n, i in {**VOICES, **LINE_VOICES}.items()}
|
|
|
|
| 1935 |
app.state.refs.invalidate()
|
| 1936 |
return {"ok": True, "removed": removed}
|
| 1937 |
|
| 1938 |
+
@app.get("/api/prompt-audio/{phrase_id}", dependencies=[Depends(require("practice.use"))])
|
| 1939 |
def prompt_audio(phrase_id: int, engine: str = "gtts"):
|
| 1940 |
"""The Hebrew prompt read aloud (edge-tts or gTTS). 503 tells the page to stay silent."""
|
| 1941 |
phrase = phrase_of(phrase_id)
|
|
|
|
| 1948 |
return Response(data, media_type="audio/mpeg", headers={
|
| 1949 |
"Cache-Control": "private, max-age=86400", "X-TTS-Engine": used})
|
| 1950 |
|
| 1951 |
+
@app.get("/api/say", dependencies=[Depends(require("practice.use"))])
|
| 1952 |
def say(text: str = Query(..., min_length=1, max_length=400), engine: str = "gtts"):
|
| 1953 |
"""A short Hebrew text read aloud: driving mode's spoken messages."""
|
| 1954 |
if engine not in ENGINES:
|
|
|
|
| 1961 |
raise HTTPException(503, str(e))
|
| 1962 |
return Response(data, media_type="audio/mpeg", headers={"Cache-Control": "no-store", "X-TTS-Engine": used})
|
| 1963 |
|
| 1964 |
+
@app.post("/api/score", dependencies=[Depends(require("practice.use"))])
|
| 1965 |
def score(tasks: BackgroundTasks, phrase_id: int = Form(...), audio: UploadFile = File(...),
|
| 1966 |
user: dict | None = Depends(signed_in)):
|
| 1967 |
phrase = phrase_of(phrase_id)
|
app/tutor.py
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
"""
|
| 2 |
|
| 3 |
The tutor writes; the student talks. The page turns the student's speech into text (the browser's own recognition)
|
| 4 |
and sends the text; the tutor's answer comes back as text too, so the student sees what the tutor understood.
|
|
@@ -16,7 +16,7 @@ this process's memory while it runs (a restart ends it) and is kept, turn by tur
|
|
| 16 |
`tutor_chats` (CREATE_TUTOR_CHATS), so the teacher can read what was said and how the tutor answered.
|
| 17 |
|
| 18 |
Env: ANTHROPIC_API_KEY (or CLAUDE_API_KEY) required; without it the game is not offered
|
| 19 |
-
|
| 20 |
TUTOR_MODEL optional: the Claude model the tutor runs on (default DEFAULT_MODEL), e.g. claude-sonnet-5-5
|
| 21 |
"""
|
| 22 |
from __future__ import annotations
|
|
@@ -479,7 +479,7 @@ class Tutor:
|
|
| 479 |
def load_tutor() -> Tutor | None:
|
| 480 |
key = (os.environ.get("ANTHROPIC_API_KEY", "") or os.environ.get("CLAUDE_API_KEY", "")).strip()
|
| 481 |
if not key:
|
| 482 |
-
log.info("no ANTHROPIC_API_KEY: the tutor game (
|
| 483 |
return None
|
| 484 |
try:
|
| 485 |
import anthropic
|
|
@@ -487,7 +487,7 @@ def load_tutor() -> Tutor | None:
|
|
| 487 |
log.warning("ANTHROPIC_API_KEY is set but the anthropic package is not installed: the tutor game is off")
|
| 488 |
return None
|
| 489 |
model = os.environ.get("TUTOR_MODEL", "").strip() or DEFAULT_MODEL
|
| 490 |
-
log.info("the tutor game (
|
| 491 |
return Tutor(anthropic.Anthropic(api_key=key, timeout=30.0, max_retries=2), model)
|
| 492 |
|
| 493 |
|
|
|
|
| 1 |
+
"""ערבוט: short spoken conversations with an AI tutor, on scenario cards, one for each lesson of the course.
|
| 2 |
|
| 3 |
The tutor writes; the student talks. The page turns the student's speech into text (the browser's own recognition)
|
| 4 |
and sends the text; the tutor's answer comes back as text too, so the student sees what the tutor understood.
|
|
|
|
| 16 |
`tutor_chats` (CREATE_TUTOR_CHATS), so the teacher can read what was said and how the tutor answered.
|
| 17 |
|
| 18 |
Env: ANTHROPIC_API_KEY (or CLAUDE_API_KEY) required; without it the game is not offered
|
| 19 |
+
Access is granted per account in the management panel; an open service remains open.
|
| 20 |
TUTOR_MODEL optional: the Claude model the tutor runs on (default DEFAULT_MODEL), e.g. claude-sonnet-5-5
|
| 21 |
"""
|
| 22 |
from __future__ import annotations
|
|
|
|
| 479 |
def load_tutor() -> Tutor | None:
|
| 480 |
key = (os.environ.get("ANTHROPIC_API_KEY", "") or os.environ.get("CLAUDE_API_KEY", "")).strip()
|
| 481 |
if not key:
|
| 482 |
+
log.info("no ANTHROPIC_API_KEY: the tutor game (ערבוט) is off")
|
| 483 |
return None
|
| 484 |
try:
|
| 485 |
import anthropic
|
|
|
|
| 487 |
log.warning("ANTHROPIC_API_KEY is set but the anthropic package is not installed: the tutor game is off")
|
| 488 |
return None
|
| 489 |
model = os.environ.get("TUTOR_MODEL", "").strip() or DEFAULT_MODEL
|
| 490 |
+
log.info("the tutor game (ערבוט) runs on %s", model)
|
| 491 |
return Tutor(anthropic.Anthropic(api_key=key, timeout=30.0, max_retries=2), model)
|
| 492 |
|
| 493 |
|
static/index.html
CHANGED
|
@@ -173,7 +173,7 @@ body[data-view=verbs] #vids{max-width:none;gap:6px;margin-top:0}
|
|
| 173 |
/* "הפועל זכרון": the verbs of the verb table's lesson as a memory game on a misbaha that snakes over the whole screen.
|
| 174 |
A bead shows gold, turning on its cord; open, a verb: the Hebrew, or the Arabic (said aloud) in transliteration. A found
|
| 175 |
pair turns green and stays open. The cord, the imam and the tassel are those of "פועל זמני", grown to the screen. */
|
| 176 |
-
/*
|
| 177 |
:root{--tc-wall:#EFE7DD; --tc-in:#FFFFFF; --tc-out:#D9FDD3; --tc-head:#36501D; --tc-fix:#FFF6D6}
|
| 178 |
@media (prefers-color-scheme: dark){:root{--tc-wall:#0B141A; --tc-in:#202C33; --tc-out:#005C4B; --tc-head:#202C33; --tc-fix:#3A2F17}}
|
| 179 |
body.tutor-chat{overflow:hidden}
|
|
@@ -720,13 +720,16 @@ body.lab #wrap{max-width:none}
|
|
| 720 |
.rrow .pill,.rrow .none{justify-self:end}
|
| 721 |
.rrow .none{color:var(--muted);font-size:12px;text-align:end}
|
| 722 |
/* the panel's two parts: the classes (opened, edited, deleted) and the students (their progress, a class at a time) */
|
| 723 |
-
.modes{display:grid;grid-template-columns:repeat(
|
| 724 |
.modes button{display:flex;flex-direction:column;align-items:center;gap:2px;padding:8px 6px;border:0;border-radius:10px;background:transparent;color:var(--ink);font:700 16px/1.2 var(--f-body);cursor:pointer}
|
| 725 |
.modes button small{font:600 12px/1.2 var(--f-body);color:var(--muted)}
|
| 726 |
.modes button[aria-selected=true]{background:var(--surface);box-shadow:0 1px 2px rgba(0,0,0,.15)}
|
| 727 |
#manage.classes :is(#mTutors,#mTabs,#mHead,#mLessons,#mRoster,#mStudent),#manage:not(.classes) #mClasses{display:none}
|
| 728 |
#manage.content :is(#mTutors,#mTabs,#mHead,#mLessons,#mRoster,#mStudent),#manage:not(.content) #mContent{display:none}
|
| 729 |
#manage.flags :is(#mClasses,#mContent,#mTutors,#mTabs,#mHead,#mLessons,#mRoster,#mStudent),#manage:not(.flags) #mFlags{display:none}
|
|
|
|
|
|
|
|
|
|
| 730 |
.flag-review{gap:10px}.flag-review h2{margin:0}.flag-review .meta{color:var(--muted);font-size:13px}.flag-review fieldset{border:0;margin:0;padding:0;display:flex;flex-wrap:wrap;gap:7px}
|
| 731 |
.flag-review fieldset label{display:flex;align-items:center;gap:5px;padding:6px 8px;border:1px solid var(--line);border-radius:9px}.flag-review select,.flag-review textarea{font:inherit;border:1px solid var(--line);border-radius:9px;padding:7px;background:var(--surface);color:var(--ink)}
|
| 732 |
.flag-review textarea{width:100%;resize:vertical}
|
|
@@ -1182,7 +1185,7 @@ body.quiet :is(#mic,#playMine,#driveBtn,.phone-btn),body.driving :is(#quietBtn,#
|
|
| 1182 |
#mailForm button:disabled{opacity:.6;cursor:default}
|
| 1183 |
#mailMsg{margin:0;text-align:center;font:400 15px/1.5 var(--f-body);color:#1C241D;overflow-wrap:anywhere}
|
| 1184 |
#roles{display:flex;gap:14px;flex-wrap:wrap;justify-content:center}
|
| 1185 |
-
#roles :is(#manageBtn,#labBtn){background:#fff;color:#4B6A2C;box-shadow:inset 0 0 0 2px #4B6A2C}
|
| 1186 |
#bootErr{margin:0;max-width:90vw;font:12px/1.4 ui-monospace,monospace;color:#9B2C2C;white-space:pre-wrap;overflow-wrap:anywhere;text-align:left}
|
| 1187 |
@keyframes start-in{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:none}}
|
| 1188 |
@media (prefers-reduced-motion:reduce){#startBtn,#loginBtn,#roles button,#mailForm{animation:none;opacity:1}#logo-splash{transition:none}}
|
|
@@ -1201,7 +1204,7 @@ body.quiet :is(#mic,#playMine,#driveBtn,.phone-btn),body.driving :is(#quietBtn,#
|
|
| 1201 |
<symbol id="i-mic" viewBox="0 0 24 24"><rect x="9" y="2" width="6" height="12" rx="3"/><path d="M5 11a7 7 0 0 0 14 0M12 18v4M8 22h8"/></symbol>
|
| 1202 |
<symbol id="i-car" viewBox="0 0 24 24"><path d="M19 17h2c.6 0 1-.4 1-1v-3c0-.9-.7-1.7-1.5-1.9C18.7 10.6 16 10 16 10s-1.3-1.4-2.2-2.3c-.5-.4-1.1-.7-1.8-.7H5c-.6 0-1.1.4-1.4.9l-1.4 2.9A3.7 3.7 0 0 0 2 12v4c0 .6.4 1 1 1h2M9 17h6"/><circle cx="7" cy="17" r="2"/><circle cx="17" cy="17" r="2"/></symbol>
|
| 1203 |
</defs></svg>
|
| 1204 |
-
<div id="logo-splash"><img src="static/logo-intro.svg" alt="אהלא וסהלא, בית הספר ללימוד השפה הערבית" width="489" height="225"><button id="startBtn">יאללה נבלש</button><div id="roles" hidden><button id="practiceBtn">תרגול</button><button id="manageBtn">ניהול</button><button id="labBtn">מעבדה</button></div><button id="loginBtn" hidden>כניסה עם Google</button><form id="mailForm" hidden><span>או עם קישור שנשלח לדוא"ל</span><input id="mailIn" type="email" dir="ltr" required autocomplete="email" placeholder="name@example.com" aria-label="כתובת הדוא"ל"><button id="mailBtn">שלחו לי קישור כניסה</button><p id="mailMsg" role="status" hidden></p></form><div id="denied" hidden>הכתובת הזו אינה באף כיתה. בקשו מהמורה להוסיף אותו.<button id="switchBtn">כניסה עם חשבון אחר</button></div></div>
|
| 1205 |
<script>
|
| 1206 |
/* While the opening screen is up, an error that stops the page's start shows under the logo: a phone has no console to read it in. */
|
| 1207 |
(()=>{
|
|
@@ -1226,7 +1229,7 @@ body.quiet :is(#mic,#playMine,#driveBtn,.phone-btn),body.driving :is(#quietBtn,#
|
|
| 1226 |
|
| 1227 |
<div id="today" hidden></div>
|
| 1228 |
<section id="vids" aria-live="polite"></section>
|
| 1229 |
-
<nav id="nav" aria-label="ניווט"><button data-view="">מסלול</button><button data-view="verbs">פעלים</button><button data-view="games" hidden>משחקים</button><button data-view="
|
| 1230 |
<nav class="path" id="path" aria-label="מסלול הלימוד"></nav>
|
| 1231 |
<button id="toNow" hidden></button>
|
| 1232 |
|
|
@@ -1304,10 +1307,11 @@ body.quiet :is(#mic,#playMine,#driveBtn,.phone-btn),body.driving :is(#quietBtn,#
|
|
| 1304 |
<section class="wrap" id="manage" aria-labelledby="mTitle">
|
| 1305 |
<div class="roundbar"><h1 class="mtitle" id="mTitle">ניהול</h1><span class="sep"></span><button class="btn" id="mRefresh">רענון</button><button class="btn" id="mLab">מעבדה</button><button class="btn primary" id="mPractice">לתרגול</button></div>
|
| 1306 |
<div class="sub" id="mState" aria-live="polite"></div>
|
| 1307 |
-
<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><button role="tab" data-mode="flags">ניטור<small>פעילות ודיווחי ציונים</small></button></div>
|
| 1308 |
<div id="mClasses"></div>
|
| 1309 |
<div id="mContent"></div>
|
| 1310 |
<div id="mFlags"></div>
|
|
|
|
| 1311 |
<div class="card hard" id="mTutors" hidden></div>
|
| 1312 |
<div class="tabs" id="mTabs" role="tablist" aria-label="סינון תלמידים לפי כיתה" hidden></div>
|
| 1313 |
<div class="card" id="mHead" hidden></div>
|
|
@@ -1605,7 +1609,7 @@ body.quiet :is(#mic,#playMine,#driveBtn,.phone-btn),body.driving :is(#quietBtn,#
|
|
| 1605 |
<ul><li><b>שינוי שם:</b> לוחצים <b>שינוי שם</b> ליד הסרטון, מקלידים את השם החדש ומאשרים.</li>
|
| 1606 |
<li><b>שינוי סדר:</b> בחיצים <b>↑</b> ו-<b>↓</b> שבשורה של הסרטון מזיזים אותו מקום אחד למעלה או למטה. התלמידים רואים את הסרטונים באותו סדר.</li></ul>
|
| 1607 |
<h3>מה התלמידים רואים</h3>
|
| 1608 |
-
<ul><li>התלמידים מגיעים לסרטונים דרך ה
|
| 1609 |
<li>כל תלמיד רואה את כל הסרטונים, בלי קשר לשלב או לכיתה שלו.</li>
|
| 1610 |
<li>סרטון בספריה אינו תרגול, ולכן הוא לא נספר בהתקדמות או בציונים.</li></ul>
|
| 1611 |
<h3>אם משהו לא עובד</h3>
|
|
@@ -1676,6 +1680,8 @@ let daily=null, dailySaid=new Set(), dailyWas={}; // the daily session on the
|
|
| 1676 |
let ALL_LEVELS=[], ALL_LESSONS=[], ALL_CATS=[], GAMES=[], MY_LESSONS=null, LESSONS=[], CATS=[], PHRASES=[], cat=store.get("ihki.cat",""), best=store.get("ihki.best2",{}), order=[], pos=0, cur=null;
|
| 1677 |
let myAudioUrl=null;
|
| 1678 |
let TUTOR=false, lastRec=null; // a teacher, or an account of TUTORS_EMAIL, flags a score that is wrong; the latest recording sent to be scored, {id, blob}
|
|
|
|
|
|
|
| 1679 |
const phraseOf=id=>PHRASES.find(p=>p.id===id); // by id: the list skips the phrases that have no tab
|
| 1680 |
const categoryOf=id=>CATS.find(c=>c.id===id)||GAMES.find(g=>g.id===id);
|
| 1681 |
|
|
@@ -1786,21 +1792,21 @@ function drawNav(){ // the tabs, and the screen of videos when one is on show
|
|
| 1786 |
box.append(b);
|
| 1787 |
};
|
| 1788 |
if(view==="games"){
|
| 1789 |
-
if(tutorList&&TUTOR_INFO&&TUTOR_INFO.available){ drawTutorList(box); return; } //
|
| 1790 |
-
const games=GAMES.filter(game=>!game.hidden);
|
| 1791 |
box.append(mark("","משחקים","h2"));
|
| 1792 |
-
if(VERB_GAME_VISIBLE){
|
| 1793 |
const switcher=mark("now","","button");
|
| 1794 |
switcher.append(mark("","↻","i"),mark("","פועל יוצא","b"),mark("","מהבנה לשליפה מהירה של הטיית הפועל","small"));
|
| 1795 |
switcher.onclick=openVerbGame; box.append(switcher);
|
| 1796 |
}
|
| 1797 |
const memo=mark("now","","button"), upto=vtLessonNow(); // the memory game, on the verb table's lesson
|
| 1798 |
memo.append(mark("","📿","i"),mark("","הפועל זכרון","b"),mark("",`הפכו חרוזים ומצאו זוגות של פעלים · עד ${(ALL_LESSONS.find(l=>l.id===upto)||{}).name||""}`,"small"));
|
| 1799 |
-
memo.onclick=openMemoryGame; if(upto) box.append(memo);
|
| 1800 |
-
const talk=TUTOR_INFO&&TUTOR_INFO.available; //
|
| 1801 |
if(talk){
|
| 1802 |
const b=mark("now","","button"), n=tutorScenarios().length;
|
| 1803 |
-
b.append(mark("","💬","i"),mark("","
|
| 1804 |
b.onclick=()=>{ tutorList=true; drawNav(); window.scrollTo(0,0); }; box.append(b);
|
| 1805 |
}
|
| 1806 |
if(!games.length&&!upto&&!talk) box.append(mark("","המשחקים הראשונים יגיעו בקרוב.","p"));
|
|
@@ -2035,15 +2041,16 @@ function mgSamples(t){ // points along the cord every 3px, from the top row's
|
|
| 2035 |
}
|
| 2036 |
return pts;
|
| 2037 |
}
|
| 2038 |
-
/*
|
| 2039 |
device's speech recognition turns what they said into their own message, sent at once: the student sees what the
|
| 2040 |
tutor understood. A browser without recognition, or the keyboard button, lets them type instead.
|
| 2041 |
The students read Arabic only in Hebrew letters, so every Arabic line here is shown in them: the tutor's message,
|
| 2042 |
the correction, and the student's own sentence as the tutor read it (it replaces the recognition's Arabic script). */
|
| 2043 |
async function loadTutor(){
|
|
|
|
| 2044 |
try{ await ready; }catch{}
|
| 2045 |
try{ const r=await api("/api/tutor"); TUTOR_INFO=r.ok?await r.json():null; }catch{ TUTOR_INFO=null; }
|
| 2046 |
-
if(TUTOR_INFO&&TUTOR_INFO.available) $("nav").querySelector('[data-view="games"]').hidden=false;
|
| 2047 |
if(document.body.dataset.view==="games") drawNav();
|
| 2048 |
}
|
| 2049 |
function lessonStarted(id){ // a sentence of the lesson has been said (a teacher has every lesson open)
|
|
@@ -2055,10 +2062,10 @@ function tutorScenarios(){ // the scenarios of the student's lessons that they
|
|
| 2055 |
const mine=new Set(LESSONS.map(l=>l.id));
|
| 2056 |
return ((TUTOR_INFO&&TUTOR_INFO.scenarios)||[]).filter(s=>mine.has(s.lesson)&&lessonStarted(s.lesson));
|
| 2057 |
}
|
| 2058 |
-
function drawTutorList(box){ //
|
| 2059 |
const back=mark("back","","button");
|
| 2060 |
back.innerHTML='<svg class="ic" aria-hidden="true"><use href="#i-back"/></svg> חזרה למשחקים'; back.onclick=()=>{ tutorList=false; drawNav(); };
|
| 2061 |
-
box.append(back,mark("","
|
| 2062 |
const open=tutorScenarios(), all=((TUTOR_INFO&&TUTOR_INFO.scenarios)||[]).filter(s=>LESSONS.some(l=>l.id===s.lesson)), left=TUTOR_INFO.left;
|
| 2063 |
box.append(mark("tc-intro",`בחרו שיחה. ח'ליל וחבריו מדברים רק במילים שכבר למדתם${left==null?"":` · נשארו ${left} שיחות היום`}`,"p"));
|
| 2064 |
if(!open.length) box.append(mark("","התרחיש הראשון ייפתח כשתתחילו את השיעור הראשון 💛","p"));
|
|
@@ -2073,7 +2080,7 @@ function drawTutorList(box){ // בחכי ערבי: a card for each open scenar
|
|
| 2073 |
}
|
| 2074 |
function openTutorChat(s){
|
| 2075 |
closeTutorChat();
|
| 2076 |
-
const root=mark("tc","","section"); root.setAttribute("role","dialog"); root.setAttribute("aria-label",`
|
| 2077 |
root.innerHTML=`<header class="tc-head"><button class="tc-close" type="button" aria-label="יציאה מהשיחה">→</button>
|
| 2078 |
<span class="tc-avatar" lang="ar" aria-hidden="true"></span>
|
| 2079 |
<div class="tc-who"><b></b><small></small></div><span class="tc-count"></span></header>
|
|
@@ -4052,7 +4059,7 @@ function sentence(p,under){ // a sentence as the student sees it, and a small
|
|
| 4052 |
setTr(name,p.read?p.tr:p.he); text.append(name,mark("",under,"small")); return text;
|
| 4053 |
}
|
| 4054 |
/* The students part starts with one unique list; its class tabs are filters and keep class-specific calculations. */
|
| 4055 |
-
let CLASS=null, shownClass=store.get("ihki.mstudentClass","*"); // "*" is every student; otherwise the class on show
|
| 4056 |
let mMode=store.get("ihki.mmode",""); // the panel's part on show: "classes" or "students" (the classes, before the first one)
|
| 4057 |
let FLAG_REVIEWS={pending:[],confirmed:[]}, CALIBRATIONS=[], ATTEMPT_PATTERNS=[], flagsError="", flagsLoaded=false, flagAudioUrls=[];
|
| 4058 |
let SCORING_RULES=null, scoringRulesError=""; // the rules of pronunciation-rules.md and whether each is on (see drawScoringRules)
|
|
@@ -4086,6 +4093,7 @@ async function loadManage(){
|
|
| 4086 |
}
|
| 4087 |
CLASS=await res.json(); await loadContent();
|
| 4088 |
if(mMode==="flags") await loadFlags();
|
|
|
|
| 4089 |
TEACHER_DAILIES=CLASS.classes.flatMap(classDailies).map(d=>({...d.v,date:d.date})).sort((a,b)=>a.date.localeCompare(b.date)); // as just saved; the earliest day of each comes first
|
| 4090 |
}catch{ state.textContent="השרת לא זמין."; return; }
|
| 4091 |
state.textContent=""; state.classList.toggle("setup",!!(CLASS.setup||[]).length);
|
|
@@ -4105,6 +4113,59 @@ function drawBuild(info){
|
|
| 4105 |
box.replaceChildren(title,mark("","מידע טכני לזיהוי הגרסה שפועלת כעת.","p"),list);
|
| 4106 |
box.hidden=false;
|
| 4107 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4108 |
function drawManage(){
|
| 4109 |
const classes=CLASS.classes||[];
|
| 4110 |
if(shownClass!=="*"&&!classes.some(c=>c.name===shownClass)) shownClass="*";
|
|
@@ -4116,10 +4177,10 @@ function drawManage(){
|
|
| 4116 |
// clean); the totals beside their own fields (`tries` stays the per-sentence one)
|
| 4117 |
const students=CLASS.students.filter(s=>!klass||klass.name in s.classes).map(s=>{ if(klass&&s.since) s={...s,...s.since[klass.name]}; const t=stuTally(s,listed);
|
| 4118 |
return {...s,nick:klass?s.classes[klass.name]:s.name?"":Object.values(s.classes).find(Boolean)||"",classNames:Object.keys(s.classes),done:t.done,n:t.n,avg:t.avg}; });
|
| 4119 |
-
if(!["classes","students","content","flags"].includes(mMode)) mMode=classes.length?"students":"classes";
|
| 4120 |
-
$("mModes").hidden=false; for(const mode of ["classes","content","flags"]) $("manage").classList.toggle(mode,mMode===mode);
|
| 4121 |
for(const b of $("mModes").children) b.setAttribute("aria-selected",b.dataset.mode===mMode);
|
| 4122 |
-
drawClasses(classes); drawContent(); drawFlags(); drawTutors(); drawTabs(classes); drawHead(klass,students);
|
| 4123 |
if(klass||!classes.length) drawLessons(students,listed); else{ $("mLessons").innerHTML=""; $("mLessons").hidden=true; }
|
| 4124 |
drawRoster(klass,students,listed);
|
| 4125 |
const one=students.find(s=>s.email===shownStudent); // a student who left the class has no screen in it
|
|
@@ -4130,6 +4191,7 @@ function drawManage(){
|
|
| 4130 |
async function showMode(mode){
|
| 4131 |
mMode=mode; store.set("ihki.mmode",mode); drawManage();
|
| 4132 |
if(mode==="flags"&&!flagsLoaded){ await loadFlags(); drawManage(); }
|
|
|
|
| 4133 |
}
|
| 4134 |
for(const b of $("mModes").children) b.onclick=()=>showMode(b.dataset.mode);
|
| 4135 |
setInterval(()=>{
|
|
@@ -4433,7 +4495,7 @@ function drawContent(){
|
|
| 4433 |
sec.ontoggle=()=>{ wide[key]=sec.open?1:0; store.set("ihki.copen",wide); };
|
| 4434 |
return sec;
|
| 4435 |
};
|
| 4436 |
-
vcard(fold("library","ספריה דיגיטלית",`${LIBRARY.length?LIBRARY.length+" סרטונים":"עוד אין סרטונים"} · משותפת לכל הרמות`),null,"library",LIBRARY,"הסרטונים שבספריה","סרטון לספריה","משותפת לכל הרמות: פת
|
| 4437 |
for(const g of byLevel(ALL_LESSONS)){
|
| 4438 |
const sec=fold(g.level.id,g.level.name,`${lessonsWord(g.lessons)} · ${g.lessons.filter(l=>!l.soon).length} מוכנים`);
|
| 4439 |
vcard(sec,g.level.id,"dailies",DAILIES,"סרטונים יומיים","סרטון יומי","את התאריך של כל סרטון קובעים בעריכת הכיתה","הסרטון נוסף לסרטונים היומיים של הרמה. כדי שתלמידים יראו אותו, קובעים לו תאריך בעריכת הכיתה: מאותו יום הוא מופיע להם בכפתור „סרטון יומי” שמעל המסלול."," גם הכיתות שקבעו לו תאריך לא יראו אותו עוד.","למשל: יום 1 · ברכות");
|
|
@@ -5978,9 +6040,11 @@ function useLessons(ids){ // the path shows these lessons only (null: every on
|
|
| 5978 |
const said=c=>PHRASES.some(p=>p.cat===c.id&&p.listed!==false); // a topic with sentences to say: not new words, pairs or writing
|
| 5979 |
if(CATS.length&&!CATS.some(c=>c.id===cat&&said(c))) cat=(CATS.find(said)||CATS[0]).id; // e.g. the last topic was a game
|
| 5980 |
}
|
| 5981 |
-
const ready=fetch("/api/phrases").then(r=>r.json()).then(d=>{
|
| 5982 |
-
ALL_LEVELS=d.levels||[]; ALL_LESSONS=d.lessons; ALL_CATS=d.categories; GAMES=d.games||[]; PHRASES=d.phrases;
|
| 5983 |
-
$("nav").querySelector('[data-view="games"]').hidden=
|
|
|
|
|
|
|
| 5984 |
for(const c of ALL_CATS) c.name=c.name.replace(/ ← /g,"\u00a0←\u00a0"); // the arrow never ends a line
|
| 5985 |
useLessons(MY_LESSONS);
|
| 5986 |
startCat(); opened=true;
|
|
@@ -5992,15 +6056,20 @@ function enter(){
|
|
| 5992 |
const splash=$("logo-splash");
|
| 5993 |
$("wrap").inert=false; splash.classList.add("done"); setTimeout(()=>splash.remove(),400);
|
| 5994 |
if(MY_CLASSES.length>1&&!MY_CLASS) askClass(); // in several classes and none practised in before: which one?
|
|
|
|
| 5995 |
}
|
| 5996 |
$("startBtn").onclick=$("practiceBtn").onclick=enter;
|
|
|
|
| 5997 |
$("manageBtn").onclick=()=>{ enter(); showManage(); };
|
| 5998 |
$("labBtn").onclick=()=>{ enter(); showLab(); };
|
| 5999 |
$("startBtn").focus({preventScroll:true});
|
| 6000 |
/* With sign-in configured, the start button waits behind the Google button and, under it, the email one: Supabase
|
| 6001 |
sends the address a link that opens the page signed in (no password). A teacher gets two buttons in the start
|
| 6002 |
button's place: practice, as a student does, or the management panel. */
|
| 6003 |
-
if(!AUTH_URL)
|
|
|
|
|
|
|
|
|
|
| 6004 |
if(AUTH_URL){
|
| 6005 |
const start=$("startBtn"), login=$("loginBtn"), logout=$("logoutBtn"), roles=$("roles"), mail=$("mailForm");
|
| 6006 |
start.hidden=true; login.hidden=false;
|
|
@@ -6034,6 +6103,10 @@ if(AUTH_URL){
|
|
| 6034 |
const res=await Promise.race([api("/api/me").catch(()=>null),new Promise(r=>setTimeout(()=>r(null),10000))]); // a session or server that hangs leaves the logo alone on the screen
|
| 6035 |
const ok=!res||res.status!==403; // a server that cannot be reached is not a refusal
|
| 6036 |
const me=res&&res.ok?await res.json().catch(()=>({})):{}, teacher=!!me.teacher;
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6037 |
const mine=me.classes||[]; // a teacher practises every lesson and is not asked for a class
|
| 6038 |
MY_CLASSES=teacher?[]:mine; MY_CLASS=null; FREE=teacher; TUTOR=!!me.tutor; TEACHER_DAILIES=me.dailies||[];
|
| 6039 |
$("myClass").textContent=mine.length>1?(teacher?`כיתות: ${mine.map(c=>c.name).join(" · ")}`:"בחירת כיתה"):mine.length?`כיתת ${mine[0].name}`:"";
|
|
@@ -6041,8 +6114,9 @@ if(AUTH_URL){
|
|
| 6041 |
MY_LESSONS=me.lessons||null; if(ALL_LESSONS.length) useLessons(MY_LESSONS);
|
| 6042 |
if(MY_CLASSES.length===1) MY_CLASS=mine[0];
|
| 6043 |
else{ const last=MY_CLASSES.find(c=>c.name===store.get("ihki.class","")); if(last) useClass(last); } // the class practised in last
|
| 6044 |
-
|
| 6045 |
-
|
|
|
|
| 6046 |
}catch(e){ start.hidden=false; throw e; } },0); // a failure here still lets the student in, and shows under the logo
|
| 6047 |
});
|
| 6048 |
}
|
|
|
|
| 173 |
/* "הפועל זכרון": the verbs of the verb table's lesson as a memory game on a misbaha that snakes over the whole screen.
|
| 174 |
A bead shows gold, turning on its cord; open, a verb: the Hebrew, or the Arabic (said aloud) in transliteration. A found
|
| 175 |
pair turns green and stays open. The cord, the imam and the tassel are those of "פועל זמני", grown to the screen. */
|
| 176 |
+
/* ערבוט: the tutor chat, laid out like WhatsApp: the tutor's messages at the right, the student's (green) at the left */
|
| 177 |
:root{--tc-wall:#EFE7DD; --tc-in:#FFFFFF; --tc-out:#D9FDD3; --tc-head:#36501D; --tc-fix:#FFF6D6}
|
| 178 |
@media (prefers-color-scheme: dark){:root{--tc-wall:#0B141A; --tc-in:#202C33; --tc-out:#005C4B; --tc-head:#202C33; --tc-fix:#3A2F17}}
|
| 179 |
body.tutor-chat{overflow:hidden}
|
|
|
|
| 720 |
.rrow .pill,.rrow .none{justify-self:end}
|
| 721 |
.rrow .none{color:var(--muted);font-size:12px;text-align:end}
|
| 722 |
/* the panel's two parts: the classes (opened, edited, deleted) and the students (their progress, a class at a time) */
|
| 723 |
+
.modes{display:grid;grid-template-columns:repeat(5,1fr);gap:4px;padding:4px;border-radius:14px;background:var(--line)}
|
| 724 |
.modes button{display:flex;flex-direction:column;align-items:center;gap:2px;padding:8px 6px;border:0;border-radius:10px;background:transparent;color:var(--ink);font:700 16px/1.2 var(--f-body);cursor:pointer}
|
| 725 |
.modes button small{font:600 12px/1.2 var(--f-body);color:var(--muted)}
|
| 726 |
.modes button[aria-selected=true]{background:var(--surface);box-shadow:0 1px 2px rgba(0,0,0,.15)}
|
| 727 |
#manage.classes :is(#mTutors,#mTabs,#mHead,#mLessons,#mRoster,#mStudent),#manage:not(.classes) #mClasses{display:none}
|
| 728 |
#manage.content :is(#mTutors,#mTabs,#mHead,#mLessons,#mRoster,#mStudent),#manage:not(.content) #mContent{display:none}
|
| 729 |
#manage.flags :is(#mClasses,#mContent,#mTutors,#mTabs,#mHead,#mLessons,#mRoster,#mStudent),#manage:not(.flags) #mFlags{display:none}
|
| 730 |
+
#manage.access :is(#mClasses,#mContent,#mFlags,#mTutors,#mTabs,#mHead,#mLessons,#mRoster,#mStudent),#manage:not(.access) #mAccess{display:none}
|
| 731 |
+
.access-scroll{overflow:auto}.access-table{width:100%;border-collapse:collapse;min-width:980px}.access-table :is(th,td){padding:9px 7px;border-bottom:1px solid var(--line);text-align:center}.access-table th{position:sticky;top:0;background:var(--surface);font-size:13px;white-space:nowrap;z-index:1}.access-table :is(th,td):first-child{text-align:start;position:sticky;right:0;background:var(--surface);z-index:2;min-width:190px}.access-table td:first-child{font-weight:700}.access-table td:first-child small{display:block;color:var(--muted);font-weight:400;direction:ltr;overflow:hidden;text-overflow:ellipsis}.access-table input{width:18px;height:18px}.access-table .save-cell{min-width:80px}
|
| 732 |
+
@media(max-width:700px){.modes{grid-template-columns:repeat(2,1fr)}}
|
| 733 |
.flag-review{gap:10px}.flag-review h2{margin:0}.flag-review .meta{color:var(--muted);font-size:13px}.flag-review fieldset{border:0;margin:0;padding:0;display:flex;flex-wrap:wrap;gap:7px}
|
| 734 |
.flag-review fieldset label{display:flex;align-items:center;gap:5px;padding:6px 8px;border:1px solid var(--line);border-radius:9px}.flag-review select,.flag-review textarea{font:inherit;border:1px solid var(--line);border-radius:9px;padding:7px;background:var(--surface);color:var(--ink)}
|
| 735 |
.flag-review textarea{width:100%;resize:vertical}
|
|
|
|
| 1185 |
#mailForm button:disabled{opacity:.6;cursor:default}
|
| 1186 |
#mailMsg{margin:0;text-align:center;font:400 15px/1.5 var(--f-body);color:#1C241D;overflow-wrap:anywhere}
|
| 1187 |
#roles{display:flex;gap:14px;flex-wrap:wrap;justify-content:center}
|
| 1188 |
+
#roles :is(#libraryBtn,#manageBtn,#labBtn){background:#fff;color:#4B6A2C;box-shadow:inset 0 0 0 2px #4B6A2C}
|
| 1189 |
#bootErr{margin:0;max-width:90vw;font:12px/1.4 ui-monospace,monospace;color:#9B2C2C;white-space:pre-wrap;overflow-wrap:anywhere;text-align:left}
|
| 1190 |
@keyframes start-in{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:none}}
|
| 1191 |
@media (prefers-reduced-motion:reduce){#startBtn,#loginBtn,#roles button,#mailForm{animation:none;opacity:1}#logo-splash{transition:none}}
|
|
|
|
| 1204 |
<symbol id="i-mic" viewBox="0 0 24 24"><rect x="9" y="2" width="6" height="12" rx="3"/><path d="M5 11a7 7 0 0 0 14 0M12 18v4M8 22h8"/></symbol>
|
| 1205 |
<symbol id="i-car" viewBox="0 0 24 24"><path d="M19 17h2c.6 0 1-.4 1-1v-3c0-.9-.7-1.7-1.5-1.9C18.7 10.6 16 10 16 10s-1.3-1.4-2.2-2.3c-.5-.4-1.1-.7-1.8-.7H5c-.6 0-1.1.4-1.4.9l-1.4 2.9A3.7 3.7 0 0 0 2 12v4c0 .6.4 1 1 1h2M9 17h6"/><circle cx="7" cy="17" r="2"/><circle cx="17" cy="17" r="2"/></symbol>
|
| 1206 |
</defs></svg>
|
| 1207 |
+
<div id="logo-splash"><img src="static/logo-intro.svg" alt="אהלא וסהלא, בית הספר ללימוד השפה הערבית" width="489" height="225"><button id="startBtn">יאללה נבלש</button><div id="roles" hidden><button id="practiceBtn">תרגול</button><button id="libraryBtn">ספרייה דיגיטלית</button><button id="manageBtn">ניהול</button><button id="labBtn">מעבדה</button></div><button id="loginBtn" hidden>כניסה עם Google</button><form id="mailForm" hidden><span>או עם קישור שנשלח לדוא"ל</span><input id="mailIn" type="email" dir="ltr" required autocomplete="email" placeholder="name@example.com" aria-label="כתובת הדוא"ל"><button id="mailBtn">שלחו לי קישור כניסה</button><p id="mailMsg" role="status" hidden></p></form><div id="denied" hidden>הכתובת הזו אינה באף כיתה. בקשו מהמורה להוסיף אותו.<button id="switchBtn">כניסה עם חשבון אחר</button></div></div>
|
| 1208 |
<script>
|
| 1209 |
/* While the opening screen is up, an error that stops the page's start shows under the logo: a phone has no console to read it in. */
|
| 1210 |
(()=>{
|
|
|
|
| 1229 |
|
| 1230 |
<div id="today" hidden></div>
|
| 1231 |
<section id="vids" aria-live="polite"></section>
|
| 1232 |
+
<nav id="nav" aria-label="ניווט"><button data-view="">מסלול</button><button data-view="verbs">פעלים</button><button data-view="games" hidden>משחקים</button><button data-view="refer">חבר מביא חבר</button></nav>
|
| 1233 |
<nav class="path" id="path" aria-label="מסלול הלימוד"></nav>
|
| 1234 |
<button id="toNow" hidden></button>
|
| 1235 |
|
|
|
|
| 1307 |
<section class="wrap" id="manage" aria-labelledby="mTitle">
|
| 1308 |
<div class="roundbar"><h1 class="mtitle" id="mTitle">ניהול</h1><span class="sep"></span><button class="btn" id="mRefresh">רענון</button><button class="btn" id="mLab">מעבדה</button><button class="btn primary" id="mPractice">לתרגול</button></div>
|
| 1309 |
<div class="sub" id="mState" aria-live="polite"></div>
|
| 1310 |
+
<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><button role="tab" data-mode="flags">ניטור<small>פעילות ודיווחי ציונים</small></button><button role="tab" data-mode="access">הרשאות<small>תפקידים וגישה</small></button></div>
|
| 1311 |
<div id="mClasses"></div>
|
| 1312 |
<div id="mContent"></div>
|
| 1313 |
<div id="mFlags"></div>
|
| 1314 |
+
<div class="card" id="mAccess"></div>
|
| 1315 |
<div class="card hard" id="mTutors" hidden></div>
|
| 1316 |
<div class="tabs" id="mTabs" role="tablist" aria-label="סינון תלמידים לפי כיתה" hidden></div>
|
| 1317 |
<div class="card" id="mHead" hidden></div>
|
|
|
|
| 1609 |
<ul><li><b>שינוי שם:</b> לוחצים <b>שינוי שם</b> ליד הסרטון, מקלידים את השם החדש ומאשרים.</li>
|
| 1610 |
<li><b>שינוי סדר:</b> בחיצים <b>↑</b> ו-<b>↓</b> שבשורה של הסרטון מזיזים אותו מקום אחד למעלה או למטה. התלמידים רואים את הסרטונים באותו סדר.</li></ul>
|
| 1611 |
<h3>מה התלמידים רואים</h3>
|
| 1612 |
+
<ul><li>התלמידים מגיעים לסרטונים דרך הכפתור <b>ספרייה דיגיטלית</b> במסך הפתיחה.</li>
|
| 1613 |
<li>כל תלמיד רואה את כל הסרטונים, בלי קשר לשלב או לכיתה שלו.</li>
|
| 1614 |
<li>סרטון בספריה אינו תרגול, ולכן הוא לא נספר בהתקדמות או בציונים.</li></ul>
|
| 1615 |
<h3>אם משהו לא עובד</h3>
|
|
|
|
| 1680 |
let ALL_LEVELS=[], ALL_LESSONS=[], ALL_CATS=[], GAMES=[], MY_LESSONS=null, LESSONS=[], CATS=[], PHRASES=[], cat=store.get("ihki.cat",""), best=store.get("ihki.best2",{}), order=[], pos=0, cur=null;
|
| 1681 |
let myAudioUrl=null;
|
| 1682 |
let TUTOR=false, lastRec=null; // a teacher, or an account of TUTORS_EMAIL, flags a score that is wrong; the latest recording sent to be scored, {id, blob}
|
| 1683 |
+
let ME_PERMISSIONS=new Set(), ME_ROLES=[], ME_ENTITLEMENTS=[];
|
| 1684 |
+
const can=permission=>ME_PERMISSIONS.has("*")||ME_PERMISSIONS.has(permission);
|
| 1685 |
const phraseOf=id=>PHRASES.find(p=>p.id===id); // by id: the list skips the phrases that have no tab
|
| 1686 |
const categoryOf=id=>CATS.find(c=>c.id===id)||GAMES.find(g=>g.id===id);
|
| 1687 |
|
|
|
|
| 1792 |
box.append(b);
|
| 1793 |
};
|
| 1794 |
if(view==="games"){
|
| 1795 |
+
if(tutorList&&TUTOR_INFO&&TUTOR_INFO.available){ drawTutorList(box); return; } // ערבוט's scenarios, in the tab's place
|
| 1796 |
+
const games=can("games.use")?GAMES.filter(game=>!game.hidden):[];
|
| 1797 |
box.append(mark("","משחקים","h2"));
|
| 1798 |
+
if(can("games.use")&&VERB_GAME_VISIBLE){
|
| 1799 |
const switcher=mark("now","","button");
|
| 1800 |
switcher.append(mark("","↻","i"),mark("","פועל יוצא","b"),mark("","מהבנה לשליפה מהירה של הטיית הפועל","small"));
|
| 1801 |
switcher.onclick=openVerbGame; box.append(switcher);
|
| 1802 |
}
|
| 1803 |
const memo=mark("now","","button"), upto=vtLessonNow(); // the memory game, on the verb table's lesson
|
| 1804 |
memo.append(mark("","📿","i"),mark("","הפועל זכרון","b"),mark("",`הפכו חרוזים ומצאו זוגות של פעלים · עד ${(ALL_LESSONS.find(l=>l.id===upto)||{}).name||""}`,"small"));
|
| 1805 |
+
memo.onclick=openMemoryGame; if(can("games.use")&&upto) box.append(memo);
|
| 1806 |
+
const talk=can("tutor.use")&&TUTOR_INFO&&TUTOR_INFO.available; // ערבוט: it opens the list of its scenarios
|
| 1807 |
if(talk){
|
| 1808 |
const b=mark("now","","button"), n=tutorScenarios().length;
|
| 1809 |
+
b.append(mark("","💬","i"),mark("","ערבוט","b"),mark("",n?`שיחה עם דמויות מהשיעורים · ${n} תרחישים פתוחים`:"שיחה עם דמויות מהשיעורים · נפתח עם השיעור הראשון","small"));
|
| 1810 |
b.onclick=()=>{ tutorList=true; drawNav(); window.scrollTo(0,0); }; box.append(b);
|
| 1811 |
}
|
| 1812 |
if(!games.length&&!upto&&!talk) box.append(mark("","המשחקים הראשונים יגיעו בקרוב.","p"));
|
|
|
|
| 2041 |
}
|
| 2042 |
return pts;
|
| 2043 |
}
|
| 2044 |
+
/* ערבוט: a WhatsApp-like chat with an AI tutor (app/tutor.py). The tutor writes; the student talks, and the
|
| 2045 |
device's speech recognition turns what they said into their own message, sent at once: the student sees what the
|
| 2046 |
tutor understood. A browser without recognition, or the keyboard button, lets them type instead.
|
| 2047 |
The students read Arabic only in Hebrew letters, so every Arabic line here is shown in them: the tutor's message,
|
| 2048 |
the correction, and the student's own sentence as the tutor read it (it replaces the recognition's Arabic script). */
|
| 2049 |
async function loadTutor(){
|
| 2050 |
+
if(AUTH_URL&&!can("tutor.use")){ TUTOR_INFO=null; return; }
|
| 2051 |
try{ await ready; }catch{}
|
| 2052 |
try{ const r=await api("/api/tutor"); TUTOR_INFO=r.ok?await r.json():null; }catch{ TUTOR_INFO=null; }
|
| 2053 |
+
if((!AUTH_URL||can("tutor.use"))&&TUTOR_INFO&&TUTOR_INFO.available) $("nav").querySelector('[data-view="games"]').hidden=false;
|
| 2054 |
if(document.body.dataset.view==="games") drawNav();
|
| 2055 |
}
|
| 2056 |
function lessonStarted(id){ // a sentence of the lesson has been said (a teacher has every lesson open)
|
|
|
|
| 2062 |
const mine=new Set(LESSONS.map(l=>l.id));
|
| 2063 |
return ((TUTOR_INFO&&TUTOR_INFO.scenarios)||[]).filter(s=>mine.has(s.lesson)&&lessonStarted(s.lesson));
|
| 2064 |
}
|
| 2065 |
+
function drawTutorList(box){ // ערבוט: a card for each open scenario, the latest lesson's first
|
| 2066 |
const back=mark("back","","button");
|
| 2067 |
back.innerHTML='<svg class="ic" aria-hidden="true"><use href="#i-back"/></svg> חזרה למשחקים'; back.onclick=()=>{ tutorList=false; drawNav(); };
|
| 2068 |
+
box.append(back,mark("","ערבוט","h2"));
|
| 2069 |
const open=tutorScenarios(), all=((TUTOR_INFO&&TUTOR_INFO.scenarios)||[]).filter(s=>LESSONS.some(l=>l.id===s.lesson)), left=TUTOR_INFO.left;
|
| 2070 |
box.append(mark("tc-intro",`בחרו שיחה. ח'ליל וחבריו מדברים רק במילים שכבר למדתם${left==null?"":` · נשארו ${left} שיחות היום`}`,"p"));
|
| 2071 |
if(!open.length) box.append(mark("","התרחיש הראשון ייפתח כשתתחילו את השיעור הראשון 💛","p"));
|
|
|
|
| 2080 |
}
|
| 2081 |
function openTutorChat(s){
|
| 2082 |
closeTutorChat();
|
| 2083 |
+
const root=mark("tc","","section"); root.setAttribute("role","dialog"); root.setAttribute("aria-label",`ערבוט · ${s.title}`);
|
| 2084 |
root.innerHTML=`<header class="tc-head"><button class="tc-close" type="button" aria-label="יציאה מהשיחה">→</button>
|
| 2085 |
<span class="tc-avatar" lang="ar" aria-hidden="true"></span>
|
| 2086 |
<div class="tc-who"><b></b><small></small></div><span class="tc-count"></span></header>
|
|
|
|
| 4059 |
setTr(name,p.read?p.tr:p.he); text.append(name,mark("",under,"small")); return text;
|
| 4060 |
}
|
| 4061 |
/* The students part starts with one unique list; its class tabs are filters and keep class-specific calculations. */
|
| 4062 |
+
let CLASS=null, ACCESS=null, accessError="", shownClass=store.get("ihki.mstudentClass","*"); // "*" is every student; otherwise the class on show
|
| 4063 |
let mMode=store.get("ihki.mmode",""); // the panel's part on show: "classes" or "students" (the classes, before the first one)
|
| 4064 |
let FLAG_REVIEWS={pending:[],confirmed:[]}, CALIBRATIONS=[], ATTEMPT_PATTERNS=[], flagsError="", flagsLoaded=false, flagAudioUrls=[];
|
| 4065 |
let SCORING_RULES=null, scoringRulesError=""; // the rules of pronunciation-rules.md and whether each is on (see drawScoringRules)
|
|
|
|
| 4093 |
}
|
| 4094 |
CLASS=await res.json(); await loadContent();
|
| 4095 |
if(mMode==="flags") await loadFlags();
|
| 4096 |
+
if(mMode==="access") await loadAccess();
|
| 4097 |
TEACHER_DAILIES=CLASS.classes.flatMap(classDailies).map(d=>({...d.v,date:d.date})).sort((a,b)=>a.date.localeCompare(b.date)); // as just saved; the earliest day of each comes first
|
| 4098 |
}catch{ state.textContent="השרת לא זמין."; return; }
|
| 4099 |
state.textContent=""; state.classList.toggle("setup",!!(CLASS.setup||[]).length);
|
|
|
|
| 4113 |
box.replaceChildren(title,mark("","מידע טכני לזיהוי הגרסה שפועלת כעת.","p"),list);
|
| 4114 |
box.hidden=false;
|
| 4115 |
}
|
| 4116 |
+
const ACCESS_COLUMNS=[
|
| 4117 |
+
{label:"תרגול",kind:"entitlements",value:"practice",permission:"practice.use"},
|
| 4118 |
+
{label:"ניהול",kind:"roles",value:"admin",permission:"management.access"},
|
| 4119 |
+
{label:"מעבדה",kind:"roles",value:"developer",permission:"lab.access"},
|
| 4120 |
+
{label:"משחקים",kind:"entitlements",value:"games",permission:"games.use"},
|
| 4121 |
+
{label:"ספרייה דיגיטלית",kind:"entitlements",value:"library",permission:"library.view"},
|
| 4122 |
+
{label:"דיווח תקלות",kind:"roles",value:"flagger",permission:"flags.create"},
|
| 4123 |
+
{label:"ערבוט",kind:"entitlements",value:"tutor",permission:"tutor.use"},
|
| 4124 |
+
{label:"מסלול",kind:"entitlements",value:"path",permission:"path.use"},
|
| 4125 |
+
];
|
| 4126 |
+
async function loadAccess(){
|
| 4127 |
+
accessError="";
|
| 4128 |
+
try{
|
| 4129 |
+
const res=await api("/api/access/users"), data=await res.json().catch(()=>({}));
|
| 4130 |
+
if(!res.ok) throw new Error(data.detail||res.status);
|
| 4131 |
+
ACCESS=data;
|
| 4132 |
+
}catch(e){ ACCESS=null; accessError=e.message; }
|
| 4133 |
+
}
|
| 4134 |
+
function drawAccess(){
|
| 4135 |
+
const box=$("mAccess"); box.replaceChildren();
|
| 4136 |
+
const title=mark("","משתמשים והרשאות","h2"); box.append(title);
|
| 4137 |
+
if(accessError){ box.append(mark("setup",`ההרשאות לא זמינות: ${accessError}`,"p")); return; }
|
| 4138 |
+
if(!ACCESS){ box.append(mark("sub","טוען…","p")); return; }
|
| 4139 |
+
if(ACCESS.setup){ const code=mark("",ACCESS.setup,"code"); code.dir="ltr"; box.append(mark("setup","יש ליצור את טבלאות ההרשאות ב-Supabase:","p"),code); return; }
|
| 4140 |
+
const note=mark("sub","כל עמודה היא הרשאה נפרדת. ערבוט מופרד ממשחקים כי הוא משתמש בשירות API בתשלום. רק מפתחים יכולים לתת גישה למעבדה.","p"); box.append(note);
|
| 4141 |
+
if(ACCESS.migration){ const details=document.createElement("details"), summary=document.createElement("summary"), code=mark("",ACCESS.migration,"code"); summary.textContent="שדרוג טבלת הרשאות קיימת"; code.dir="ltr"; details.className="setup"; details.append(summary,code); box.append(details); }
|
| 4142 |
+
const scroll=mark("access-scroll",""), table=mark("access-table","","table"), head=document.createElement("thead"), hr=document.createElement("tr");
|
| 4143 |
+
hr.append(mark("","משתמש","th")); for(const col of ACCESS_COLUMNS) hr.append(mark("",col.label,"th")); hr.append(mark("","","th")); head.append(hr); table.append(head);
|
| 4144 |
+
const body=document.createElement("tbody");
|
| 4145 |
+
for(const user of ACCESS.users||[]){
|
| 4146 |
+
const row=document.createElement("tr"), who=document.createElement("td"), email=mark("",user.email,"small"); email.dir="ltr"; who.append(user.name||user.email,email); row.append(who);
|
| 4147 |
+
for(const col of ACCESS_COLUMNS){
|
| 4148 |
+
const td=document.createElement("td"), input=document.createElement("input"); input.type="checkbox"; input.dataset.kind=col.kind; input.value=col.value; input.checked=(user[col.kind]||[]).includes(col.value)||(user.permissions||[]).includes("*")||(user.permissions||[]).includes(col.permission);
|
| 4149 |
+
input.setAttribute("aria-label",`${col.label}: ${user.name||user.email}`);
|
| 4150 |
+
input.disabled=user.id===ACCESS.me||(col.value==="developer"&&!can("lab.access"))||(user.fixed_roles||[]).includes(col.value);
|
| 4151 |
+
if((user.fixed_roles||[]).includes(col.value)) input.title="נקבע בהגדרות השרת"; td.append(input); row.append(td);
|
| 4152 |
+
}
|
| 4153 |
+
const save=mark("btn primary","שמירה","button"), saveCell=mark("save-cell","","td"); saveCell.append(save); row.append(saveCell); save.disabled=user.id===ACCESS.me||((user.fixed_roles||[]).includes("developer")&&!can("lab.access"));
|
| 4154 |
+
save.onclick=async()=>{
|
| 4155 |
+
const selected=kind=>[...row.querySelectorAll(`input[data-kind="${kind}"]:checked`)].map(x=>x.value);
|
| 4156 |
+
const roles=[...(user.roles||[]).filter(x=>!["admin","developer","flagger"].includes(x)),...selected("roles")];
|
| 4157 |
+
if(!roles.length) roles.push("student");
|
| 4158 |
+
save.disabled=true;
|
| 4159 |
+
try{
|
| 4160 |
+
const res=await api(`/api/access/users/${user.id}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({roles,entitlements:selected("entitlements")})});
|
| 4161 |
+
const data=await res.json().catch(()=>({})); if(!res.ok) throw new Error(data.detail||res.status);
|
| 4162 |
+
note.textContent=`ההרשאות של ${user.name||user.email} נשמרו.`; await loadAccess(); drawAccess();
|
| 4163 |
+
}catch(e){ note.textContent="השמירה נכשלה: "+e.message; save.disabled=false; }
|
| 4164 |
+
};
|
| 4165 |
+
body.append(row);
|
| 4166 |
+
}
|
| 4167 |
+
table.append(body); scroll.append(table); box.append(scroll);
|
| 4168 |
+
}
|
| 4169 |
function drawManage(){
|
| 4170 |
const classes=CLASS.classes||[];
|
| 4171 |
if(shownClass!=="*"&&!classes.some(c=>c.name===shownClass)) shownClass="*";
|
|
|
|
| 4177 |
// clean); the totals beside their own fields (`tries` stays the per-sentence one)
|
| 4178 |
const students=CLASS.students.filter(s=>!klass||klass.name in s.classes).map(s=>{ if(klass&&s.since) s={...s,...s.since[klass.name]}; const t=stuTally(s,listed);
|
| 4179 |
return {...s,nick:klass?s.classes[klass.name]:s.name?"":Object.values(s.classes).find(Boolean)||"",classNames:Object.keys(s.classes),done:t.done,n:t.n,avg:t.avg}; });
|
| 4180 |
+
if(!["classes","students","content","flags","access"].includes(mMode)) mMode=classes.length?"students":"classes";
|
| 4181 |
+
$("mModes").hidden=false; for(const mode of ["classes","content","flags","access"]) $("manage").classList.toggle(mode,mMode===mode);
|
| 4182 |
for(const b of $("mModes").children) b.setAttribute("aria-selected",b.dataset.mode===mMode);
|
| 4183 |
+
drawClasses(classes); drawContent(); drawFlags(); drawAccess(); drawTutors(); drawTabs(classes); drawHead(klass,students);
|
| 4184 |
if(klass||!classes.length) drawLessons(students,listed); else{ $("mLessons").innerHTML=""; $("mLessons").hidden=true; }
|
| 4185 |
drawRoster(klass,students,listed);
|
| 4186 |
const one=students.find(s=>s.email===shownStudent); // a student who left the class has no screen in it
|
|
|
|
| 4191 |
async function showMode(mode){
|
| 4192 |
mMode=mode; store.set("ihki.mmode",mode); drawManage();
|
| 4193 |
if(mode==="flags"&&!flagsLoaded){ await loadFlags(); drawManage(); }
|
| 4194 |
+
if(mode==="access"){ await loadAccess(); drawManage(); }
|
| 4195 |
}
|
| 4196 |
for(const b of $("mModes").children) b.onclick=()=>showMode(b.dataset.mode);
|
| 4197 |
setInterval(()=>{
|
|
|
|
| 4495 |
sec.ontoggle=()=>{ wide[key]=sec.open?1:0; store.set("ihki.copen",wide); };
|
| 4496 |
return sec;
|
| 4497 |
};
|
| 4498 |
+
vcard(fold("library","ספריה דיגיטלית",`${LIBRARY.length?LIBRARY.length+" סרטונים":"עוד אין סרטונים"} · משותפת לכל הרמות`),null,"library",LIBRARY,"הסרטונים שבספריה","סרטון לספריה","משותפת לכל הרמות: נפתחת לתלמידים המורשים מהכפתור „ספרייה דיגיטלית” במסך הפתיחה","הסרטון נוסף לספריה הדיגיטלית. תלמידים שקיבלו הרשאה רואים אותו דרך הכפתור „ספרייה דיגיטלית” במסך הפתיחה.","","למשל: שיר לסיום");
|
| 4499 |
for(const g of byLevel(ALL_LESSONS)){
|
| 4500 |
const sec=fold(g.level.id,g.level.name,`${lessonsWord(g.lessons)} · ${g.lessons.filter(l=>!l.soon).length} מוכנים`);
|
| 4501 |
vcard(sec,g.level.id,"dailies",DAILIES,"סרטונים יומיים","סרטון יומי","את התאריך של כל סרטון קובעים בעריכת הכיתה","הסרטון נוסף לסרטונים היומיים של הרמה. כדי שתלמידים יראו אותו, קובעים לו תאריך בעריכת הכיתה: מאותו יום הוא מופיע להם בכפתור „סרטון יומי” שמעל המסלול."," גם הכיתות שקבעו לו תאריך לא יראו אותו עוד.","למשל: יום 1 · ברכות");
|
|
|
|
| 6040 |
const said=c=>PHRASES.some(p=>p.cat===c.id&&p.listed!==false); // a topic with sentences to say: not new words, pairs or writing
|
| 6041 |
if(CATS.length&&!CATS.some(c=>c.id===cat&&said(c))) cat=(CATS.find(said)||CATS[0]).id; // e.g. the last topic was a game
|
| 6042 |
}
|
| 6043 |
+
const ready=fetch("/api/phrases").then(r=>{ if(!r.ok) throw new Error(`phrases: ${r.status}`); return r.json(); }).then(d=>{
|
| 6044 |
+
ALL_LEVELS=d.levels||[]; ALL_LESSONS=d.lessons||[]; ALL_CATS=d.categories||[]; GAMES=d.games||[]; PHRASES=d.phrases||[];
|
| 6045 |
+
$("nav").querySelector('[data-view="games"]').hidden=AUTH_URL
|
| 6046 |
+
? !can("games.use")&&!can("tutor.use")
|
| 6047 |
+
: !GAMES.some(game=>!game.hidden)&&!(TUTOR_INFO&&TUTOR_INFO.available);
|
| 6048 |
for(const c of ALL_CATS) c.name=c.name.replace(/ ← /g,"\u00a0←\u00a0"); // the arrow never ends a line
|
| 6049 |
useLessons(MY_LESSONS);
|
| 6050 |
startCat(); opened=true;
|
|
|
|
| 6056 |
const splash=$("logo-splash");
|
| 6057 |
$("wrap").inert=false; splash.classList.add("done"); setTimeout(()=>splash.remove(),400);
|
| 6058 |
if(MY_CLASSES.length>1&&!MY_CLASS) askClass(); // in several classes and none practised in before: which one?
|
| 6059 |
+
if(AUTH_URL&&!can("path.use")){ if(can("games.use")||can("tutor.use")) showView("games"); else if(can("library.view")) showView("library"); }
|
| 6060 |
}
|
| 6061 |
$("startBtn").onclick=$("practiceBtn").onclick=enter;
|
| 6062 |
+
$("libraryBtn").onclick=()=>{ enter(); showView("library"); };
|
| 6063 |
$("manageBtn").onclick=()=>{ enter(); showManage(); };
|
| 6064 |
$("labBtn").onclick=()=>{ enter(); showLab(); };
|
| 6065 |
$("startBtn").focus({preventScroll:true});
|
| 6066 |
/* With sign-in configured, the start button waits behind the Google button and, under it, the email one: Supabase
|
| 6067 |
sends the address a link that opens the page signed in (no password). A teacher gets two buttons in the start
|
| 6068 |
button's place: practice, as a student does, or the management panel. */
|
| 6069 |
+
if(!AUTH_URL){
|
| 6070 |
+
$("startBtn").hidden=true; $("roles").hidden=false; $("manageBtn").hidden=$("labBtn").hidden=true;
|
| 6071 |
+
loadTutor(); // an open service: the tutor game, when the server has its key
|
| 6072 |
+
}
|
| 6073 |
if(AUTH_URL){
|
| 6074 |
const start=$("startBtn"), login=$("loginBtn"), logout=$("logoutBtn"), roles=$("roles"), mail=$("mailForm");
|
| 6075 |
start.hidden=true; login.hidden=false;
|
|
|
|
| 6103 |
const res=await Promise.race([api("/api/me").catch(()=>null),new Promise(r=>setTimeout(()=>r(null),10000))]); // a session or server that hangs leaves the logo alone on the screen
|
| 6104 |
const ok=!res||res.status!==403; // a server that cannot be reached is not a refusal
|
| 6105 |
const me=res&&res.ok?await res.json().catch(()=>({})):{}, teacher=!!me.teacher;
|
| 6106 |
+
ME_PERMISSIONS=new Set(me.permissions||[]); ME_ROLES=me.roles||[]; ME_ENTITLEMENTS=me.entitlements||[];
|
| 6107 |
+
$("nav").querySelector('[data-view=""]').hidden=!can("path.use");
|
| 6108 |
+
$("nav").querySelector('[data-view="verbs"]').hidden=!can("games.use");
|
| 6109 |
+
$("nav").querySelector('[data-view="games"]').hidden=!can("games.use")&&!can("tutor.use");
|
| 6110 |
const mine=me.classes||[]; // a teacher practises every lesson and is not asked for a class
|
| 6111 |
MY_CLASSES=teacher?[]:mine; MY_CLASS=null; FREE=teacher; TUTOR=!!me.tutor; TEACHER_DAILIES=me.dailies||[];
|
| 6112 |
$("myClass").textContent=mine.length>1?(teacher?`כיתות: ${mine.map(c=>c.name).join(" · ")}`:"בחירת כיתה"):mine.length?`כיתת ${mine[0].name}`:"";
|
|
|
|
| 6114 |
MY_LESSONS=me.lessons||null; if(ALL_LESSONS.length) useLessons(MY_LESSONS);
|
| 6115 |
if(MY_CLASSES.length===1) MY_CLASS=mine[0];
|
| 6116 |
else{ const last=MY_CLASSES.find(c=>c.name===store.get("ihki.class","")); if(last) useClass(last); } // the class practised in last
|
| 6117 |
+
const management=can("management.access"), laboratory=can("lab.access"), library=can("library.view"), practice=can("practice.use")||can("path.use")||can("games.use")||can("tutor.use");
|
| 6118 |
+
start.hidden=!ok||management||laboratory||library; roles.hidden=!management&&!laboratory&&!library; $("practiceBtn").hidden=!practice; $("libraryBtn").hidden=!library; $("manageBtn").hidden=$("toManage").hidden=!management; $("labBtn").hidden=!laboratory; $("mLab").hidden=!laboratory; denied.hidden=ok;
|
| 6119 |
+
if(ok){ [...roles.querySelectorAll("button:not([hidden])"),start].find(x=>!x.hidden)?.focus({preventScroll:true}); loadProgress().then(()=>{ if(PHRASES.length&&$("wrap").inert) startCat(); }); loadContent(); loadWriting(); loadTutor(); }
|
| 6120 |
}catch(e){ start.hidden=false; throw e; } },0); // a failure here still lets the student in, and shows under the logo
|
| 6121 |
});
|
| 6122 |
}
|
tests/test_lab.py
CHANGED
|
@@ -30,6 +30,7 @@ class NoTTS:
|
|
| 30 |
|
| 31 |
class FakeAuth:
|
| 32 |
url, key, teachers, tutors = "https://proj.supabase.co", "sb_publishable_x", frozenset({"t@b.c", "u@b.c"}), frozenset()
|
|
|
|
| 33 |
|
| 34 |
def __init__(self):
|
| 35 |
self.samples, self.missing = [], False
|
|
|
|
| 30 |
|
| 31 |
class FakeAuth:
|
| 32 |
url, key, teachers, tutors = "https://proj.supabase.co", "sb_publishable_x", frozenset({"t@b.c", "u@b.c"}), frozenset()
|
| 33 |
+
developers = frozenset({"t@b.c", "u@b.c"})
|
| 34 |
|
| 35 |
def __init__(self):
|
| 36 |
self.samples, self.missing = [], False
|