Add tests for models tab and POWSM ONNX export, and implement fine-tuning for POWSM-CTC
Browse files- Created `test_models_tab.py` to verify the functionality of the models tab, including model switching and settings management.
- Introduced `test_powsm_onnx.py` to test the POWSM ONNX export functionality, ensuring correct handling of model exports and environmental configurations.
- Developed `finetune_powsm.py` for fine-tuning the POWSM-CTC model on Palestinian Arabic recordings, including support for dynamic padding and training configurations.
- .dockerignore +4 -0
- .gitignore +4 -0
- Dockerfile +7 -2
- README.md +23 -0
- app/auth.py +13 -2
- app/lab.py +26 -0
- app/main.py +283 -3
- app/model_settings.py +159 -0
- app/models.py +107 -0
- app/powsm.py +237 -0
- app/prefetch.py +35 -0
- app/scorer.py +11 -2
- docs/zero-shot-phone-models.md +111 -0
- requirements-zero-shot.txt +77 -0
- requirements.txt +1 -0
- scripts/export_powsm_onnx.py +155 -0
- scripts/setup_zero_shot_deps.sh +22 -0
- scripts/zero_shot_phone_models.py +388 -0
- static/index.html +461 -14
- tests/test_lab.py +10 -1
- tests/test_models_tab.py +265 -0
- tests/test_powsm_onnx.py +108 -0
- train/finetune_powsm.py +291 -0
.dockerignore
CHANGED
|
@@ -10,3 +10,7 @@ checkpoints
|
|
| 10 |
.git
|
| 11 |
*.mp3
|
| 12 |
*.pcm
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
.git
|
| 11 |
*.mp3
|
| 12 |
*.pcm
|
| 13 |
+
exports
|
| 14 |
+
.zero-shot-deps
|
| 15 |
+
book
|
| 16 |
+
*.pdf
|
.gitignore
CHANGED
|
@@ -15,3 +15,7 @@ data/minerva/
|
|
| 15 |
checkpoints/
|
| 16 |
.env.*
|
| 17 |
!.env.example
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
checkpoints/
|
| 16 |
.env.*
|
| 17 |
!.env.example
|
| 18 |
+
# extra packages for scripts/zero_shot_phone_models.py (scripts/setup_zero_shot_deps.sh)
|
| 19 |
+
.zero-shot-deps/
|
| 20 |
+
# exported models (scripts/export_powsm_onnx.py): uploaded to the Hub, never committed
|
| 21 |
+
exports/
|
Dockerfile
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
|
|
| 1 |
# CPU image; runs on Hugging Face Spaces (Docker SDK), Render, Fly, or any VM.
|
| 2 |
FROM python:3.11-slim
|
| 3 |
|
|
@@ -15,8 +16,12 @@ RUN pip install --no-cache-dir -r requirements.txt
|
|
| 15 |
ARG MODEL_ID=facebook/wav2vec2-xlsr-53-espeak-cv-ft
|
| 16 |
ENV MODEL_ID=${MODEL_ID}
|
| 17 |
USER user
|
| 18 |
-
# bake the model into the image so cold starts don't download 1.2 GB
|
| 19 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
|
| 21 |
COPY --chown=user app ./app
|
| 22 |
COPY --chown=user static ./static
|
|
|
|
| 1 |
+
# syntax=docker/dockerfile:1
|
| 2 |
# CPU image; runs on Hugging Face Spaces (Docker SDK), Render, Fly, or any VM.
|
| 3 |
FROM python:3.11-slim
|
| 4 |
|
|
|
|
| 16 |
ARG MODEL_ID=facebook/wav2vec2-xlsr-53-espeak-cv-ft
|
| 17 |
ENV MODEL_ID=${MODEL_ID}
|
| 18 |
USER user
|
| 19 |
+
# bake the model into the image so cold starts don't download it (1.2-1.6 GB). MODEL_ID is a Space variable:
|
| 20 |
+
# a wav2vec2 repo, or powsm-onnx:<repo> for the exported POWSM (app/powsm.py). A private repo needs a Space secret
|
| 21 |
+
# HF_TOKEN; it is mounted for this step only and never stored in the image.
|
| 22 |
+
COPY --chown=user app/__init__.py app/powsm.py app/prefetch.py ./app/
|
| 23 |
+
RUN --mount=type=secret,id=HF_TOKEN,mode=0444,required=false \
|
| 24 |
+
if [ -s /run/secrets/HF_TOKEN ]; then export HF_TOKEN="$(cat /run/secrets/HF_TOKEN)"; fi; python -m app.prefetch
|
| 25 |
|
| 26 |
COPY --chown=user app ./app
|
| 27 |
COPY --chown=user static ./static
|
README.md
CHANGED
|
@@ -749,6 +749,29 @@ MODEL_ID=checkpoints/ihki-ft uvicorn app.main:app --host 0.0.0.0 --port 7860
|
|
| 749 |
|
| 750 |
The script reports phoneme error rate (PER) before and after training. A GPU is advisable. A free Colab T4 handles a few hundred clips in minutes.
|
| 751 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 752 |
## Calibration knobs
|
| 753 |
|
| 754 |
- `ScorerConfig.flag_below` (50): the phoneme score under which a consonant gets a tip.
|
|
|
|
| 749 |
|
| 750 |
The script reports phoneme error rate (PER) before and after training. A GPU is advisable. A free Colab T4 handles a few hundred clips in minutes.
|
| 751 |
|
| 752 |
+
### POWSM on the Space
|
| 753 |
+
|
| 754 |
+
The most accurate model so far is POWSM-CTC fine-tuned on the Minerva lines with short padding (`train/finetune_powsm.py --pad random`). On the test lines it reaches 16.5% PER, against 38% for the base model, at 0.57 s a recording on 2 CPU threads. See [docs/zero-shot-phone-models.md](docs/zero-shot-phone-models.md). The Space runs it as an ONNX export, with `onnxruntime` and torch only. ESPnet, which training needs, stays on the training machine.
|
| 755 |
+
|
| 756 |
+
1. **Export it.** Do this once per fine-tune, on the training machine, after running `scripts/setup_zero_shot_deps.sh`:
|
| 757 |
+
```bash
|
| 758 |
+
python scripts/export_powsm_onnx.py checkpoints/powsm-ft-shortpad/powsm_ft.pt exports/powsm-ft-shortpad \
|
| 759 |
+
--check data/minerva/dev.csv # each frame's best phone should match ESPnet's 100%
|
| 760 |
+
```
|
| 761 |
+
2. **Upload the folder to a Hub model repo.** Use `--private` if the model should not be public: it was trained on the copyrighted Minerva clips.
|
| 762 |
+
```bash
|
| 763 |
+
hf repo create wzender/ihki-powsm-ft --repo-type model --private
|
| 764 |
+
hf upload wzender/ihki-powsm-ft exports/powsm-ft-shortpad .
|
| 765 |
+
```
|
| 766 |
+
3. **Point the Space at it.** In the Space settings, set the variable `MODEL_ID=powsm-onnx:wzender/ihki-powsm-ft`, and `POWSM_ONNX_THREADS=2` to match the free hardware. For a private repo, also add a secret `HF_TOKEN` with read access. The Docker build passes that secret only to the step that downloads the model, which is then baked into the image. Saving the settings rebuilds the Space. `/api/health` and the panel's פרטי המערכת show the model.
|
| 767 |
+
|
| 768 |
+
Settings:
|
| 769 |
+
- `POWSM_ONNX_PRECISION=int8` loads the int8 copy: 0.38 s a recording, but ط and ص drop by 5–6 points.
|
| 770 |
+
- `POWSM_PAD_SECONDS` overrides the padding (default: what the export was trained for, none here).
|
| 771 |
+
- `POWSM_ONNX_REPO` names the repo the panel's "מודלים" tab offers.
|
| 772 |
+
|
| 773 |
+
To roll back, delete `MODEL_ID`. The Space rebuilds onto the base model.
|
| 774 |
+
|
| 775 |
## Calibration knobs
|
| 776 |
|
| 777 |
- `ScorerConfig.flag_below` (50): the phoneme score under which a consonant gets a tip.
|
app/auth.py
CHANGED
|
@@ -101,10 +101,11 @@ CREATE_LEARNER_CLASS_STATE = (
|
|
| 101 |
BACKUP_TABLES = (
|
| 102 |
"dailies", "library", "videos", "texts", "classes", "writings", "tutors", "flags",
|
| 103 |
"lab_samples", "calibrations", "scoring_rules", "user_access", "access_audit", "app_secrets",
|
| 104 |
-
"system_events", "tutor_chats",
|
| 105 |
)
|
| 106 |
BACKUP_NATURAL_KEYS = {"writings": "user_id,topic", "tutors": "email", "scoring_rules": "id",
|
| 107 |
-
"user_access": "user_id", "app_secrets": "name", "tutor_chats": "id"
|
|
|
|
| 108 |
|
| 109 |
|
| 110 |
class AuthUnavailable(RuntimeError):
|
|
@@ -923,6 +924,16 @@ class SupabaseAuth:
|
|
| 923 |
"updated_at": datetime.now(timezone.utc).isoformat()},
|
| 924 |
prefer="resolution=merge-duplicates,return=minimal")
|
| 925 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 926 |
def users(self) -> list[dict]:
|
| 927 |
"""Every account that has signed in: id, email, name (as Google gave it; empty for one who signed in by email)."""
|
| 928 |
users: list[dict] = []
|
|
|
|
| 101 |
BACKUP_TABLES = (
|
| 102 |
"dailies", "library", "videos", "texts", "classes", "writings", "tutors", "flags",
|
| 103 |
"lab_samples", "calibrations", "scoring_rules", "user_access", "access_audit", "app_secrets",
|
| 104 |
+
"system_events", "tutor_chats", "model_settings",
|
| 105 |
)
|
| 106 |
BACKUP_NATURAL_KEYS = {"writings": "user_id,topic", "tutors": "email", "scoring_rules": "id",
|
| 107 |
+
"user_access": "user_id", "app_secrets": "name", "tutor_chats": "id",
|
| 108 |
+
"model_settings": "model"}
|
| 109 |
|
| 110 |
|
| 111 |
class AuthUnavailable(RuntimeError):
|
|
|
|
| 924 |
"updated_at": datetime.now(timezone.utc).isoformat()},
|
| 925 |
prefer="resolution=merge-duplicates,return=minimal")
|
| 926 |
|
| 927 |
+
def model_settings(self) -> list[dict]:
|
| 928 |
+
"""The scorer settings tuned per model in the panel's "מודלים" tab: model, settings, updated_by, updated_at."""
|
| 929 |
+
return self._admin("/rest/v1/model_settings?select=*") or []
|
| 930 |
+
|
| 931 |
+
def set_model_settings(self, model: str, settings: dict, by: str) -> None:
|
| 932 |
+
"""Replaces one model's settings (an upsert on the model id)."""
|
| 933 |
+
self._admin("/rest/v1/model_settings", "POST", {"model": model, "settings": settings, "updated_by": by,
|
| 934 |
+
"updated_at": datetime.now(timezone.utc).isoformat()},
|
| 935 |
+
prefer="resolution=merge-duplicates,return=minimal")
|
| 936 |
+
|
| 937 |
def users(self) -> list[dict]:
|
| 938 |
"""Every account that has signed in: id, email, name (as Google gave it; empty for one who signed in by email)."""
|
| 939 |
users: list[dict] = []
|
app/lab.py
CHANGED
|
@@ -100,6 +100,25 @@ ITEMS = [
|
|
| 100 |
_item("vow-miin", "vowels", "iː", "מי", ("مين", "m iː n"), pair="i / iː"),
|
| 101 |
]
|
| 102 |
BY_ID = {item["id"]: item for item in ITEMS}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
MINERVA_METADATA = Path(__file__).resolve().parent.parent / "data" / "minerva_metadata.json"
|
| 104 |
|
| 105 |
|
|
@@ -183,6 +202,13 @@ def public_items() -> list[dict]:
|
|
| 183 |
return out
|
| 184 |
|
| 185 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 186 |
# ---------- the benchmark ----------
|
| 187 |
# A recording's sounds are judged against its label: a sound said right should not be flagged (one that is, is a false
|
| 188 |
# rejection), and the planted mistake should be (one that is not, is a miss). The numbers are per sound as written.
|
|
|
|
| 100 |
_item("vow-miin", "vowels", "iː", "מי", ("مين", "m iː n"), pair="i / iː"),
|
| 101 |
]
|
| 102 |
BY_ID = {item["id"]: item for item in ITEMS}
|
| 103 |
+
|
| 104 |
+
# A deliberately small, single-take screen for comparing acoustic models with Hebrew speakers. Unlike the full
|
| 105 |
+
# diagnostic list above, this is not saved as labelled benchmark data: the same take is scored by every comparison
|
| 106 |
+
# model and shown side by side. It mixes the two pharyngeals, Hebrew ח' /x/, emphatics and short/long vowels. زمن
|
| 107 |
+
# is intentional: Hebrew speakers commonly insert an alif-like long /a:/ and say zama:n although both vowels are
|
| 108 |
+
# short. كتاب is the positive control, where the alif really should be long.
|
| 109 |
+
QUICK_QUIZ = [
|
| 110 |
+
_item("quick-halib", "quick", "ħ", "חַלִיב — ח גרונית", ("حليب", "ħ a l iː b")),
|
| 111 |
+
_item("quick-baid", "quick", "ʕ", "בַּעִיד — ע גרונית", ("بعيد", "b a ʕ iː d")),
|
| 112 |
+
_item("quick-khali", "quick", "x", "חַ'אלִי — ח׳", ("خالي", "x aː l i")),
|
| 113 |
+
_item("quick-zaman", "quick", "a", "זַמַן — שתי תנועות קצרות (לא זַמַאן)", ("زمن", "z a m a n")),
|
| 114 |
+
_item("quick-kitab", "quick", "aː", "כִּתַאבּ — אליף ארוכה", ("كتاب", "k i t aː b")),
|
| 115 |
+
_item("quick-sabah", "quick", "ħ", "סַבַּאח — ח בסוף ואליף ארוכה", ("صباح", "sˤ a b aː ħ")),
|
| 116 |
+
_item("quick-sual", "quick", "ʔ", "סֻאַאל — המזה ואליף ארוכה", ("سؤال", "s u ʔ aː l")),
|
| 117 |
+
_item("quick-tawle", "quick", "tˤ", "טַאוְלֶה — ט נחצית", ("طاولة", "tˤ aː w l e")),
|
| 118 |
+
_item("quick-zghir", "quick", "ɣ", "זְעִ'יר — ע׳", ("صغير", "sˤ ɣ iː r")),
|
| 119 |
+
_item("quick-bint", "quick", "i", "בִּנְת — תנועה קצרה", ("بنت", "b i n t")),
|
| 120 |
+
]
|
| 121 |
+
QUICK_BY_ID = {item["id"]: item for item in QUICK_QUIZ}
|
| 122 |
MINERVA_METADATA = Path(__file__).resolve().parent.parent / "data" / "minerva_metadata.json"
|
| 123 |
|
| 124 |
|
|
|
|
| 202 |
return out
|
| 203 |
|
| 204 |
|
| 205 |
+
def public_quick_quiz() -> list[dict]:
|
| 206 |
+
"""The ten model-comparison prompts, without exposing any extra scorer internals."""
|
| 207 |
+
return [{"id": item["id"], "number": number, "focus": item["focus"], "he": item["he"],
|
| 208 |
+
"ar": item["variants"][0][0], "tr": " ".join(to_hebrew(item["variants"][0][1], item["variants"][0][0]))}
|
| 209 |
+
for number, item in enumerate(QUICK_QUIZ, 1)]
|
| 210 |
+
|
| 211 |
+
|
| 212 |
# ---------- the benchmark ----------
|
| 213 |
# A recording's sounds are judged against its label: a sound said right should not be flagged (one that is, is a false
|
| 214 |
# rejection), and the planted mistake should be (one that is not, is a miss). The numbers are per sound as written.
|
app/main.py
CHANGED
|
@@ -1,7 +1,8 @@
|
|
| 1 |
"""HTTP service: serves the practice page and scores recordings.
|
| 2 |
|
| 3 |
Run: uvicorn app.main:app --host 0.0.0.0 --port 7860
|
| 4 |
-
Env: MODEL_ID (default facebook/wav2vec2-xlsr-53-espeak-cv-ft, or a path to a fine-tuned checkpoint
|
|
|
|
| 5 |
SAWTAK_API_KEY (model-answer playback with the Raef voice, see app/tts.py)
|
| 6 |
SUPABASE_URL, SUPABASE_PUBLISHABLE_KEY (Google sign-in, see app/auth.py)
|
| 7 |
TEACHER_EMAILS, SUPABASE_SECRET_KEY (the teacher's management panel, its classes and the lesson videos, see app/auth.py)
|
|
@@ -52,9 +53,13 @@ from .math_skills import algebra9
|
|
| 52 |
from . import push as pushes
|
| 53 |
from .phrases import CATEGORIES, GAMES, LESSONS, LEVELS, PHRASES, public_phrases
|
| 54 |
from .prompt_tts import ENGINES, PromptTTSUnavailable, hebrew_mp3
|
|
|
|
|
|
|
|
|
|
| 55 |
from .reference import References
|
| 56 |
from .rules import TOGGLES, check_detectable
|
| 57 |
-
from .
|
|
|
|
| 58 |
from .speech_evaluation import SpeechEvaluationService
|
| 59 |
from .texts import read_line, text_phrases
|
| 60 |
from .tts import BASELINE_VOICES, LINE_VOICES, RAEF_VOICE_ID, VOICES, SawtakTTS, TTSUnavailable, load_tts, voice_name
|
|
@@ -90,6 +95,7 @@ def subject_code(label: object) -> str:
|
|
| 90 |
label = " ".join(str(label or "").split())
|
| 91 |
return next((code for code, name in SUBJECT_LABELS.items() if name == label), "")
|
| 92 |
MODEL_ID = os.environ.get("MODEL_ID", "facebook/wav2vec2-xlsr-53-espeak-cv-ft")
|
|
|
|
| 93 |
LOCAL_TZ = ZoneInfo("Asia/Jerusalem") # a day of practice is the students' calendar day
|
| 94 |
WARM_WORKERS = 3 # Sawtak requests the cache-warm sweep runs at once (tts.MAX_CONCURRENT and its pace apply)
|
| 95 |
MAX_UPLOAD = 2_000_000 # bytes; 15 s of opus is ~100 KB
|
|
@@ -539,6 +545,7 @@ def create_app(scorer: Scorer | None = None, tts: SawtakTTS | None = None,
|
|
| 539 |
app.state.scorer.set_calibrations([r for r in rows if not r.get("model") or r.get("model") == MODEL_ID])
|
| 540 |
except AuthUnavailable as e:
|
| 541 |
log.warning("calibrations not loaded: %s", e)
|
|
|
|
| 542 |
if app.state.auth and hasattr(app.state.auth, "scoring_rules"):
|
| 543 |
try:
|
| 544 |
reload_scoring_rules(app.state.auth)
|
|
@@ -1418,7 +1425,8 @@ def create_app(scorer: Scorer | None = None, tts: SawtakTTS | None = None,
|
|
| 1418 |
label = r["label"] if r["label"] in ("correct", "mistake") else "correct"
|
| 1419 |
for tally in (counts, mine) if who and (r.get("speaker") or "") == who else (counts,):
|
| 1420 |
tally.setdefault(r["item"], {"correct": 0, "mistake": 0})[label] += 1
|
| 1421 |
-
return {"items": lab.public_items(), "
|
|
|
|
| 1422 |
|
| 1423 |
@app.post("/api/lab/score")
|
| 1424 |
def lab_score(request: Request, item: str = Form(...), audio: UploadFile = File(...),
|
|
@@ -3205,6 +3213,278 @@ def create_app(scorer: Scorer | None = None, tts: SawtakTTS | None = None,
|
|
| 3205 |
app.state.auth.log_event("permission", user, f"מפתח API: {name}", {"key": name, "action": "clear"})
|
| 3206 |
return keys_status(response)
|
| 3207 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3208 |
@app.get("/api/prompt-audio/{phrase_id}", dependencies=[Depends(require("practice.use"))])
|
| 3209 |
def prompt_audio(phrase_id: int, engine: str = "gtts"):
|
| 3210 |
"""The Hebrew prompt read aloud (edge-tts or gTTS). 503 tells the page to stay silent."""
|
|
|
|
| 1 |
"""HTTP service: serves the practice page and scores recordings.
|
| 2 |
|
| 3 |
Run: uvicorn app.main:app --host 0.0.0.0 --port 7860
|
| 4 |
+
Env: MODEL_ID (default facebook/wav2vec2-xlsr-53-espeak-cv-ft, or a path to a fine-tuned checkpoint;
|
| 5 |
+
a POWSM fine-tune's .pt file or powsm:<ara> loads POWSM-CTC, see app/powsm.py)
|
| 6 |
SAWTAK_API_KEY (model-answer playback with the Raef voice, see app/tts.py)
|
| 7 |
SUPABASE_URL, SUPABASE_PUBLISHABLE_KEY (Google sign-in, see app/auth.py)
|
| 8 |
TEACHER_EMAILS, SUPABASE_SECRET_KEY (the teacher's management panel, its classes and the lesson videos, see app/auth.py)
|
|
|
|
| 53 |
from . import push as pushes
|
| 54 |
from .phrases import CATEGORIES, GAMES, LESSONS, LEVELS, PHRASES, public_phrases
|
| 55 |
from .prompt_tts import ENGINES, PromptTTSUnavailable, hebrew_mp3
|
| 56 |
+
from .model_settings import CREATE_MODEL_SETTINGS, build as build_model_config, clean as clean_model_settings, describe as describe_model_settings
|
| 57 |
+
from .models import (POWSM_ONNX_REPO, availability as model_availability, catalog as model_catalog,
|
| 58 |
+
known as model_known)
|
| 59 |
from .reference import References
|
| 60 |
from .rules import TOGGLES, check_detectable
|
| 61 |
+
from .archi import archify
|
| 62 |
+
from .scorer import SAMPLE_RATE, Scorer, decode_audio, decode_audio_with_timing, frame_energy, load_scorer, tokenize
|
| 63 |
from .speech_evaluation import SpeechEvaluationService
|
| 64 |
from .texts import read_line, text_phrases
|
| 65 |
from .tts import BASELINE_VOICES, LINE_VOICES, RAEF_VOICE_ID, VOICES, SawtakTTS, TTSUnavailable, load_tts, voice_name
|
|
|
|
| 95 |
label = " ".join(str(label or "").split())
|
| 96 |
return next((code for code, name in SUBJECT_LABELS.items() if name == label), "")
|
| 97 |
MODEL_ID = os.environ.get("MODEL_ID", "facebook/wav2vec2-xlsr-53-espeak-cv-ft")
|
| 98 |
+
ENV_MODEL_ID = MODEL_ID # the one the server starts with; the panel's "מודלים" tab can switch until a restart
|
| 99 |
LOCAL_TZ = ZoneInfo("Asia/Jerusalem") # a day of practice is the students' calendar day
|
| 100 |
WARM_WORKERS = 3 # Sawtak requests the cache-warm sweep runs at once (tts.MAX_CONCURRENT and its pace apply)
|
| 101 |
MAX_UPLOAD = 2_000_000 # bytes; 15 s of opus is ~100 KB
|
|
|
|
| 545 |
app.state.scorer.set_calibrations([r for r in rows if not r.get("model") or r.get("model") == MODEL_ID])
|
| 546 |
except AuthUnavailable as e:
|
| 547 |
log.warning("calibrations not loaded: %s", e)
|
| 548 |
+
apply_model_settings(app.state.scorer, MODEL_ID)
|
| 549 |
if app.state.auth and hasattr(app.state.auth, "scoring_rules"):
|
| 550 |
try:
|
| 551 |
reload_scoring_rules(app.state.auth)
|
|
|
|
| 1425 |
label = r["label"] if r["label"] in ("correct", "mistake") else "correct"
|
| 1426 |
for tally in (counts, mine) if who and (r.get("speaker") or "") == who else (counts,):
|
| 1427 |
tally.setdefault(r["item"], {"correct": 0, "mistake": 0})[label] += 1
|
| 1428 |
+
return {"items": lab.public_items(), "quick_quiz": lab.public_quick_quiz(), "groups": lab.GROUPS,
|
| 1429 |
+
"counts": counts, "mine": mine, "setup": setup}
|
| 1430 |
|
| 1431 |
@app.post("/api/lab/score")
|
| 1432 |
def lab_score(request: Request, item: str = Form(...), audio: UploadFile = File(...),
|
|
|
|
| 3213 |
app.state.auth.log_event("permission", user, f"מפתח API: {name}", {"key": name, "action": "clear"})
|
| 3214 |
return keys_status(response)
|
| 3215 |
|
| 3216 |
+
# ---- the phoneme model: which one scores, switched from the panel's "מודלים" tab ----
|
| 3217 |
+
app.state.model_switch = {"state": "idle", "target": "", "error": "", "started_at": 0.0, "by": ""}
|
| 3218 |
+
model_lock = threading.Lock()
|
| 3219 |
+
|
| 3220 |
+
def models_only(user: dict | None = Depends(signed_in)) -> SupabaseAuth:
|
| 3221 |
+
"""Only developers ("*") switch the model: every learner's score changes with it. Like keys_only, an open
|
| 3222 |
+
deployment (no sign-in) is refused too."""
|
| 3223 |
+
permissions = set((user or {}).get("permissions", ()))
|
| 3224 |
+
if app.state.auth is None or ("*" not in permissions and "models.manage" not in permissions):
|
| 3225 |
+
raise HTTPException(403, "missing permission: models.manage")
|
| 3226 |
+
return app.state.auth
|
| 3227 |
+
|
| 3228 |
+
def models_status(user: dict | None) -> dict:
|
| 3229 |
+
permissions = set((user or {}).get("permissions", ()))
|
| 3230 |
+
return {"active": MODEL_ID, "default": ENV_MODEL_ID, "switch": dict(app.state.model_switch),
|
| 3231 |
+
"can_switch": app.state.auth is not None and bool(permissions & {"*", "models.manage"}),
|
| 3232 |
+
"models": model_catalog(MODEL_ID)}
|
| 3233 |
+
|
| 3234 |
+
def prepare_scorer(model_id: str) -> Scorer:
|
| 3235 |
+
"""A scorer for `model_id` set up as the running one would be: its stored settings, the calibrations made for
|
| 3236 |
+
it and the rules switched off in ניטור."""
|
| 3237 |
+
scorer = load_scorer(model_id)
|
| 3238 |
+
apply_model_settings(scorer, model_id)
|
| 3239 |
+
if app.state.auth and hasattr(app.state.auth, "calibrations"):
|
| 3240 |
+
try:
|
| 3241 |
+
rows = app.state.auth.calibrations("applied")
|
| 3242 |
+
scorer.set_calibrations([r for r in rows if not r.get("model") or r.get("model") == model_id])
|
| 3243 |
+
except AuthUnavailable as e:
|
| 3244 |
+
log.warning("calibrations not loaded for %s: %s", model_id, e)
|
| 3245 |
+
if app.state.auth and hasattr(app.state.auth, "scoring_rules"):
|
| 3246 |
+
try:
|
| 3247 |
+
scorer.set_disabled(r["id"] for r in app.state.auth.scoring_rules() if not r.get("active", True))
|
| 3248 |
+
except AuthUnavailable as e:
|
| 3249 |
+
log.warning("scoring rules not loaded for %s: %s", model_id, e)
|
| 3250 |
+
return scorer
|
| 3251 |
+
|
| 3252 |
+
def use_model(model_id: str, user: dict | None) -> None:
|
| 3253 |
+
"""Loads `model_id` beside the running one, then swaps it in: requests in flight finish on the old one.
|
| 3254 |
+
The swap carries over what belongs to the scoring, not to the model: the switched-off rules, the native
|
| 3255 |
+
baseline (rebuilt from the cached voices, scored by the new model) and the calibrations made for it."""
|
| 3256 |
+
global MODEL_ID
|
| 3257 |
+
try:
|
| 3258 |
+
scorer = prepare_scorer(model_id)
|
| 3259 |
+
app.state.compare.pop(model_id, None) # the comparison's own copy, if it had one, is this one now
|
| 3260 |
+
old = app.state.scorer
|
| 3261 |
+
app.state.scorer, MODEL_ID = scorer, model_id
|
| 3262 |
+
if app.state.tts:
|
| 3263 |
+
app.state.refs = References(scorer, app.state.tts, list(BASELINE_VOICES.values()))
|
| 3264 |
+
del old
|
| 3265 |
+
try: # hand the old model's memory back (the GPU has room for one model at a time)
|
| 3266 |
+
import gc
|
| 3267 |
+
import torch
|
| 3268 |
+
gc.collect()
|
| 3269 |
+
if torch.cuda.is_available():
|
| 3270 |
+
torch.cuda.empty_cache()
|
| 3271 |
+
except ImportError:
|
| 3272 |
+
pass
|
| 3273 |
+
app.state.model_switch.update(state="idle", error="")
|
| 3274 |
+
log.info("phoneme model switched to %s by %s", model_id, (user or {}).get("email", "?"))
|
| 3275 |
+
if app.state.auth:
|
| 3276 |
+
app.state.auth.log_event("permission", user, f"מודל: {model_id}", {"model": model_id, "action": "switch"})
|
| 3277 |
+
except Exception as e: # the running model stays; the panel shows why
|
| 3278 |
+
log.exception("loading the model %s failed", model_id)
|
| 3279 |
+
app.state.model_switch.update(state="error", error=f"{type(e).__name__}: {e}"[:400])
|
| 3280 |
+
|
| 3281 |
+
@app.get("/api/admin/models")
|
| 3282 |
+
def models(response: Response, _a: SupabaseAuth = Depends(admin_only), user: dict | None = Depends(signed_in)):
|
| 3283 |
+
"""The models this server can score with, what each was measured to do, and which one is scoring now."""
|
| 3284 |
+
response.headers["Cache-Control"] = "no-store"
|
| 3285 |
+
return models_status(user)
|
| 3286 |
+
|
| 3287 |
+
@app.put("/api/admin/models/active")
|
| 3288 |
+
def switch_model(response: Response, body: dict = Body(...), _a: SupabaseAuth = Depends(models_only),
|
| 3289 |
+
user: dict | None = Depends(signed_in)):
|
| 3290 |
+
"""Starts loading another model in the background; GET /api/admin/models shows when it took over.
|
| 3291 |
+
The choice lasts until the server restarts (MODEL_ID decides the one it starts with)."""
|
| 3292 |
+
response.headers["Cache-Control"] = "no-store"
|
| 3293 |
+
model_id = body.get("model_id")
|
| 3294 |
+
if not isinstance(model_id, str) or not (model_known(model_id) or model_id == ENV_MODEL_ID):
|
| 3295 |
+
raise HTTPException(400, "unknown model")
|
| 3296 |
+
ok, why = model_availability(model_id)
|
| 3297 |
+
if not ok:
|
| 3298 |
+
raise HTTPException(409, why)
|
| 3299 |
+
with model_lock:
|
| 3300 |
+
if app.state.model_switch["state"] == "loading":
|
| 3301 |
+
raise HTTPException(409, "מודל אחר נטען כרגע")
|
| 3302 |
+
if model_id == MODEL_ID:
|
| 3303 |
+
return models_status(user)
|
| 3304 |
+
app.state.model_switch = {"state": "loading", "target": model_id, "error": "", "started_at": time.time(),
|
| 3305 |
+
"by": (user or {}).get("email", "")}
|
| 3306 |
+
threading.Thread(target=use_model, args=(model_id, user), daemon=True, name="model-switch").start()
|
| 3307 |
+
return models_status(user)
|
| 3308 |
+
|
| 3309 |
+
# ---- debugging: one recording scored by several models side by side (the practice page's 🔬 button) ----
|
| 3310 |
+
app.state.compare = {} # model id -> (scorer, References or None), loaded on first use and kept
|
| 3311 |
+
compare_lock = threading.Lock()
|
| 3312 |
+
|
| 3313 |
+
def compare_ids() -> list[str]:
|
| 3314 |
+
"""COMPARE_MODELS (comma-separated), else the base model, the wav2vec2 fine-tune and POWSM (the local
|
| 3315 |
+
export, or the Hub one). The model scoring now always comes first; models this server can't load are left out."""
|
| 3316 |
+
raw = os.environ.get("COMPARE_MODELS", "").strip()
|
| 3317 |
+
if raw:
|
| 3318 |
+
ids = [m.strip() for m in raw.split(",") if m.strip()]
|
| 3319 |
+
else:
|
| 3320 |
+
local = "exports/powsm-ft-shortpad"
|
| 3321 |
+
ids = ["facebook/wav2vec2-xlsr-53-espeak-cv-ft", "checkpoints/ihki-ft-minerva",
|
| 3322 |
+
local if Path(local, "powsm_onnx.json").is_file() else f"powsm-onnx:{POWSM_ONNX_REPO}"]
|
| 3323 |
+
ids = [MODEL_ID] + [m for m in ids if m != MODEL_ID]
|
| 3324 |
+
return [m for m in ids if m == MODEL_ID or model_availability(m)[0]]
|
| 3325 |
+
|
| 3326 |
+
def quick_compare_ids() -> list[str]:
|
| 3327 |
+
"""The stable three columns promised by the lab's quick Hebrew-speaker benchmark."""
|
| 3328 |
+
local = "exports/powsm-ft-shortpad"
|
| 3329 |
+
ids = ["facebook/wav2vec2-xlsr-53-espeak-cv-ft", "checkpoints/ihki-ft-minerva",
|
| 3330 |
+
local if Path(local, "powsm_onnx.json").is_file() else f"powsm-onnx:{POWSM_ONNX_REPO}"]
|
| 3331 |
+
return [model_id for model_id in ids if model_id == MODEL_ID or model_availability(model_id)[0]]
|
| 3332 |
+
|
| 3333 |
+
def compare_scorer(model_id: str):
|
| 3334 |
+
"""(scorer, native baselines) for a model: the running ones for the active model, else loaded once."""
|
| 3335 |
+
if model_id == MODEL_ID:
|
| 3336 |
+
return app.state.scorer, app.state.refs
|
| 3337 |
+
with compare_lock:
|
| 3338 |
+
if model_id not in app.state.compare:
|
| 3339 |
+
scorer = prepare_scorer(model_id)
|
| 3340 |
+
refs = References(scorer, app.state.tts, list(BASELINE_VOICES.values())) if app.state.tts else None
|
| 3341 |
+
app.state.compare[model_id] = (scorer, refs)
|
| 3342 |
+
return app.state.compare[model_id]
|
| 3343 |
+
|
| 3344 |
+
def compare_view(result: dict) -> dict:
|
| 3345 |
+
"""What the comparison panel draws from a result: the verdict, what was heard, each word's sounds."""
|
| 3346 |
+
words = [{"tr": w.get("tr", ""), "heard_tr": w.get("heard_tr", ""), "score": w.get("score"),
|
| 3347 |
+
"phonemes": [{"ipa": p.get("ipa", ""), "score": round(p.get("score", 0)), "flagged": bool(p.get("flagged")),
|
| 3348 |
+
"heard": p.get("heard") or ""} for p in w.get("phonemes", [])]}
|
| 3349 |
+
for w in result.get("words", [])]
|
| 3350 |
+
return {"score": result.get("score"), "unrelated": bool(result.get("unrelated")),
|
| 3351 |
+
"heard_tr": result.get("heard_tr", ""), "heard_ipa": result.get("heard_ipa", ""), "words": words,
|
| 3352 |
+
"tips": [t.get("title", "") for t in result.get("tips", [])], "references": refs if isinstance(refs := result.get("references"), int) else len(refs or [])}
|
| 3353 |
+
|
| 3354 |
+
@app.post("/api/admin/compare-models")
|
| 3355 |
+
def compare_models(phrase_id: int | None = Form(None), item: str = Form(""), audio: UploadFile = File(...),
|
| 3356 |
+
_a: SupabaseAuth = Depends(models_only), user: dict | None = Depends(signed_in)):
|
| 3357 |
+
"""One recording scored by each comparison model, as /api/score would score it with that model. Nothing is
|
| 3358 |
+
saved. The first call loads the models that aren't running (several seconds each)."""
|
| 3359 |
+
if item:
|
| 3360 |
+
found = lab.QUICK_BY_ID.get(item)
|
| 3361 |
+
if found is None:
|
| 3362 |
+
raise HTTPException(404, "no such quick benchmark item")
|
| 3363 |
+
phrase, reference_key = lab.phrase(found), f"quick:{item}"
|
| 3364 |
+
elif phrase_id is not None:
|
| 3365 |
+
phrase, reference_key = phrase_of(phrase_id), phrase_id
|
| 3366 |
+
else:
|
| 3367 |
+
raise HTTPException(400, "phrase_id or item is required")
|
| 3368 |
+
data = audio.file.read(MAX_UPLOAD + 1)
|
| 3369 |
+
if len(data) > MAX_UPLOAD:
|
| 3370 |
+
raise HTTPException(413, "recording too long")
|
| 3371 |
+
try:
|
| 3372 |
+
wav = decode_audio(data)
|
| 3373 |
+
except ValueError:
|
| 3374 |
+
raise HTTPException(400, "could not decode audio")
|
| 3375 |
+
names = {m["id"]: m["name"] for m in model_catalog(MODEL_ID)}
|
| 3376 |
+
out = []
|
| 3377 |
+
for model_id in (quick_compare_ids() if item else compare_ids()):
|
| 3378 |
+
row = {"model": model_id, "name": names.get(model_id, model_id), "active": model_id == MODEL_ID}
|
| 3379 |
+
try:
|
| 3380 |
+
t0 = time.perf_counter()
|
| 3381 |
+
scorer, refs = compare_scorer(model_id)
|
| 3382 |
+
row["load_ms"] = round(1000 * (time.perf_counter() - t0))
|
| 3383 |
+
t0 = time.perf_counter()
|
| 3384 |
+
baselines = refs.get(reference_key, phrase) if refs else []
|
| 3385 |
+
result = scorer.score(wav, phrase, baselines, diagnostics=False)
|
| 3386 |
+
row["ms"] = round(1000 * (time.perf_counter() - t0))
|
| 3387 |
+
row.update(compare_view(result))
|
| 3388 |
+
except Exception as e: # one model failing must not hide the others
|
| 3389 |
+
log.exception("comparison with %s failed", model_id)
|
| 3390 |
+
row["error"] = f"{type(e).__name__}: {e}"[:300]
|
| 3391 |
+
out.append(row)
|
| 3392 |
+
return {"phrase": phrase.get("key", phrase.get("he", "")), "models": out}
|
| 3393 |
+
|
| 3394 |
+
# ---- the scorer's settings per model (thresholds, floors, GOP), tuned in the "מודלים" tab ----
|
| 3395 |
+
def model_settings_row(model_id: str) -> tuple[bool, dict | None]:
|
| 3396 |
+
"""(is the table there, the model's stored row or None). Raises AuthUnavailable on other failures."""
|
| 3397 |
+
a = app.state.auth
|
| 3398 |
+
if not a or not hasattr(a, "model_settings"):
|
| 3399 |
+
return False, None
|
| 3400 |
+
try:
|
| 3401 |
+
rows = a.model_settings()
|
| 3402 |
+
except AuthUnavailable as e:
|
| 3403 |
+
if "answered 404" in str(e):
|
| 3404 |
+
return False, None
|
| 3405 |
+
raise
|
| 3406 |
+
return True, next((r for r in rows if r.get("model") == model_id), None)
|
| 3407 |
+
|
| 3408 |
+
def apply_model_settings(scorer: Scorer, model_id: str) -> None:
|
| 3409 |
+
"""Puts a model's stored settings on its scorer. No row leaves the scorer as it was built."""
|
| 3410 |
+
try:
|
| 3411 |
+
_, row = model_settings_row(model_id)
|
| 3412 |
+
if row:
|
| 3413 |
+
scorer.cfg = build_model_config(model_id, row.get("settings") or {})
|
| 3414 |
+
except (AuthUnavailable, ValueError, TypeError) as e:
|
| 3415 |
+
log.warning("model settings for %s not applied: %s", model_id, e)
|
| 3416 |
+
|
| 3417 |
+
def sound_counts() -> dict[str, int]:
|
| 3418 |
+
"""How often each sound occurs in the phrase bank: the tab shows which thresholds matter most."""
|
| 3419 |
+
if getattr(app.state, "sound_counts", None) is None:
|
| 3420 |
+
counts: dict[str, int] = {}
|
| 3421 |
+
vocab = app.state.scorer.vocab
|
| 3422 |
+
for p in PHRASES:
|
| 3423 |
+
for ar, ipa in p["variants"]:
|
| 3424 |
+
try:
|
| 3425 |
+
for t in tokenize(archify(ar, ipa), vocab):
|
| 3426 |
+
counts[t.sound] = counts.get(t.sound, 0) + 1
|
| 3427 |
+
except KeyError:
|
| 3428 |
+
pass
|
| 3429 |
+
app.state.sound_counts = counts
|
| 3430 |
+
return app.state.sound_counts
|
| 3431 |
+
|
| 3432 |
+
def model_settings_payload(model_id: str, user: dict | None) -> dict:
|
| 3433 |
+
try:
|
| 3434 |
+
stored, row = model_settings_row(model_id)
|
| 3435 |
+
except AuthUnavailable as e:
|
| 3436 |
+
raise HTTPException(503, f"Supabase לא זמין: {e}")
|
| 3437 |
+
permissions = set((user or {}).get("permissions", ()))
|
| 3438 |
+
row = row or {}
|
| 3439 |
+
try:
|
| 3440 |
+
described = describe_model_settings(model_id, row.get("settings") or {}, sound_counts())
|
| 3441 |
+
except ValueError as e: # a row written by hand that no longer validates: show the defaults and why
|
| 3442 |
+
described = {**describe_model_settings(model_id, {}, sound_counts()), "error": str(e)}
|
| 3443 |
+
return {"model": model_id, "active": model_id == MODEL_ID, "stored": stored,
|
| 3444 |
+
"create_sql": None if stored else CREATE_MODEL_SETTINGS,
|
| 3445 |
+
"can_edit": stored and app.state.auth is not None and bool(permissions & {"*", "models.manage"}),
|
| 3446 |
+
"updated_by": row.get("updated_by", ""), "updated_at": row.get("updated_at"), **described}
|
| 3447 |
+
|
| 3448 |
+
def settings_model(model_id) -> str:
|
| 3449 |
+
if not isinstance(model_id, str) or not (model_known(model_id) or model_id in (MODEL_ID, ENV_MODEL_ID)):
|
| 3450 |
+
raise HTTPException(400, "unknown model")
|
| 3451 |
+
return model_id
|
| 3452 |
+
|
| 3453 |
+
@app.get("/api/admin/model-settings")
|
| 3454 |
+
def model_settings(response: Response, model: str = Query(""), _a: SupabaseAuth = Depends(admin_only),
|
| 3455 |
+
user: dict | None = Depends(signed_in)):
|
| 3456 |
+
"""One model's scorer settings: each with its default, its value now and whether it was changed."""
|
| 3457 |
+
response.headers["Cache-Control"] = "no-store"
|
| 3458 |
+
return model_settings_payload(settings_model(model or MODEL_ID), user)
|
| 3459 |
+
|
| 3460 |
+
@app.put("/api/admin/model-settings")
|
| 3461 |
+
def save_model_settings(response: Response, body: dict = Body(...), _a: SupabaseAuth = Depends(models_only),
|
| 3462 |
+
user: dict | None = Depends(signed_in)):
|
| 3463 |
+
"""Replaces a model's settings (an empty object: back to the defaults). For the model scoring now they take
|
| 3464 |
+
effect at once, and the native baselines are scored again under them."""
|
| 3465 |
+
response.headers["Cache-Control"] = "no-store"
|
| 3466 |
+
model_id = settings_model(body.get("model"))
|
| 3467 |
+
try:
|
| 3468 |
+
settings = clean_model_settings(body.get("settings", {}))
|
| 3469 |
+
cfg = build_model_config(model_id, settings)
|
| 3470 |
+
except (ValueError, TypeError) as e:
|
| 3471 |
+
raise HTTPException(400, str(e))
|
| 3472 |
+
stored, _ = model_settings_row(model_id)
|
| 3473 |
+
if not stored:
|
| 3474 |
+
raise HTTPException(503, f"הטבלה model_settings לא קיימת. הריצו ב-SQL Editor: {CREATE_MODEL_SETTINGS}")
|
| 3475 |
+
try:
|
| 3476 |
+
app.state.auth.set_model_settings(model_id, settings, (user or {}).get("email", "").lower())
|
| 3477 |
+
except AuthUnavailable as e:
|
| 3478 |
+
raise HTTPException(503, f"Supabase לא זמין: {e}")
|
| 3479 |
+
if model_id == MODEL_ID:
|
| 3480 |
+
app.state.scorer.cfg = cfg
|
| 3481 |
+
if app.state.refs is not None:
|
| 3482 |
+
app.state.refs.invalidate()
|
| 3483 |
+
log.info("model settings for %s replaced by %s: %s", model_id, (user or {}).get("email", "?"), settings)
|
| 3484 |
+
app.state.auth.log_event("permission", user, f"הגדרות מודל: {model_id}",
|
| 3485 |
+
{"model": model_id, "action": "settings", "settings": settings})
|
| 3486 |
+
return model_settings_payload(model_id, user)
|
| 3487 |
+
|
| 3488 |
@app.get("/api/prompt-audio/{phrase_id}", dependencies=[Depends(require("practice.use"))])
|
| 3489 |
def prompt_audio(phrase_id: int, engine: str = "gtts"):
|
| 3490 |
"""The Hebrew prompt read aloud (edge-tts or gTTS). 503 tells the page to stay silent."""
|
app/model_settings.py
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The scorer's settings a developer tunes per model from the panel's "מודלים" tab (stored in model_settings).
|
| 2 |
+
|
| 3 |
+
A model starts from ScorerConfig's defaults and FLAG_BELOW_BY_MODEL (scorer.py). A stored row overrides some of them:
|
| 4 |
+
{"flag_below": 45, "gop.leniency": 0.4, "flag_below_sound": {"ħ": 30, "ʕ": null}}
|
| 5 |
+
`null` for a sound means "the general threshold", which also clears a built-in one (the base model's ħ at 20).
|
| 6 |
+
Settings belong to the model they were tuned on: a threshold means something else under another model's scores.
|
| 7 |
+
"""
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
from dataclasses import replace
|
| 11 |
+
|
| 12 |
+
from .align import POOLS
|
| 13 |
+
from .scorer import ScorerConfig, scorer_config
|
| 14 |
+
|
| 15 |
+
CREATE_MODEL_SETTINGS = ("create table public.model_settings (model text primary key, "
|
| 16 |
+
"settings jsonb not null default '{}'::jsonb, updated_by text not null default '', "
|
| 17 |
+
"updated_at timestamptz not null default now()); "
|
| 18 |
+
"alter table public.model_settings enable row level security;")
|
| 19 |
+
|
| 20 |
+
# key: a ScorerConfig field, or gop.<GopConfig field>. kind: number | int | choice | window (an int, or None: wide)
|
| 21 |
+
FIELDS: list[dict] = [
|
| 22 |
+
{"key": "flag_below", "group": "flag", "kind": "number", "min": 0, "max": 100, "step": 1,
|
| 23 |
+
"label": "סף סימון כללי",
|
| 24 |
+
"help": "הגה שקיבל ציון מתחת לסף מסומן כטעות ומקבל טיפ. הגים עם סף משלהם (למטה) משתמשים בו במקום זה."},
|
| 25 |
+
{"key": "issue_below", "group": "flag", "kind": "number", "min": 0, "max": 100, "step": 1,
|
| 26 |
+
"label": "סף \"לא מדויק\"",
|
| 27 |
+
"help": "הגה מתחת לסף נרשם ברשימת ההגים כלא מדויק, גם בלי טיפ. גם תנועה ארוכה שנאמרה קצרה נמדדת מולו."},
|
| 28 |
+
{"key": "max_issues", "group": "flag", "kind": "int", "min": 1, "max": 20, "step": 1,
|
| 29 |
+
"label": "הכי הרבה הגים ברשימה", "help": "כמה הגים לא מדויקים מוצגים לתלמיד לכל היותר בכל הקלטה."},
|
| 30 |
+
{"key": "unrelated_ratio", "group": "unrelated", "kind": "number", "min": 0.1, "max": 1, "step": 0.05,
|
| 31 |
+
"label": "סף \"משפט אחר\"",
|
| 32 |
+
"help": "כמה רחוק מה שנשמע מהמשפט הצפוי עד שהמערכת אומרת שנאמר משפט אחר. גבוה יותר: סלחני יותר."},
|
| 33 |
+
{"key": "unrelated_veto_share", "group": "unrelated", "kind": "number", "min": 0, "max": 1, "step": 0.05,
|
| 34 |
+
"label": "וטו: חלק העיצורים שנמצאו",
|
| 35 |
+
"help": "אם לפחות החלק הזה של העיצורים נמצא בבירור ביישור, המשפט לא ייחשב אחר גם כשהמרחק גדול."},
|
| 36 |
+
{"key": "unrelated_veto_mean", "group": "unrelated", "kind": "number", "min": 0, "max": 100, "step": 1,
|
| 37 |
+
"label": "וטו: ציון ממוצע מינימלי", "help": "וטו \"משפט אחר\" חל רק כשהציון הממוצע של ההגים לפחות כזה."},
|
| 38 |
+
{"key": "near_vowel_floor", "group": "floors", "kind": "number", "min": 0, "max": 100, "step": 1,
|
| 39 |
+
"label": "תנועה שנשמעה כשכנתה",
|
| 40 |
+
"help": "ציון מינימום לתנועה שנשמעה כתנועה קרובה (i/e, u/o, קצרה/ארוכה): הבדל שלא כדאי להעניש עליו."},
|
| 41 |
+
{"key": "ayin_deleted_floor", "group": "floors", "kind": "number", "min": 0, "max": 100, "step": 1,
|
| 42 |
+
"label": "ע שלא נשמעה",
|
| 43 |
+
"help": "ציון מינימום ל־ע שהמודל לא שמע בכלל: המודל המקורי מפיל לעתים ע שנאמרה נכון."},
|
| 44 |
+
{"key": "onset_transient_floor", "group": "floors", "kind": "number", "min": 0, "max": 100, "step": 1,
|
| 45 |
+
"label": "עיצור ראשון מול רעש פתיחה", "help": "ציון מינימום לעיצור ראשון שהפסיד לקפיצה של פריים אחד בתחילת ההקלטה."},
|
| 46 |
+
{"key": "ref_noise_floor", "group": "floors", "kind": "number", "min": 0, "max": 100, "step": 1,
|
| 47 |
+
"label": "הגה שהמודל לא מודד במשפט",
|
| 48 |
+
"help": "אם הקול הילידי (TTS) קיבל על הגה ציון מתחת לזה, ההגה לא נמדד במשפט הזה והתלמיד מקבל עליו ציון מלא."},
|
| 49 |
+
{"key": "ref_min_mean", "group": "floors", "kind": "number", "min": 0, "max": 100, "step": 1,
|
| 50 |
+
"label": "אמינות הקול הילידי",
|
| 51 |
+
"help": "קול ילידי שהממוצע שלו מתחת לזה לא משמש בסיס להשוואה."},
|
| 52 |
+
{"key": "word_min_weight", "group": "floors", "kind": "number", "min": 0, "max": 1, "step": 0.05,
|
| 53 |
+
"label": "משקל ההגה החלש במילה", "help": "כמה הגה אחד חלש מוריד את ציון המילה כולה (0: לא משפיע, 1: קובע לבד)."},
|
| 54 |
+
{"key": "gop.leniency", "group": "gop", "kind": "number", "min": 0, "max": 1, "step": 0.05,
|
| 55 |
+
"label": "רכות הציון",
|
| 56 |
+
"help": "כמה הציון סלחני כשהמוד�� מתלבט בין ההגה הנכון לאחר. 0: ליניארי וקשוח; גבוה יותר: מתחרה כפול עדיין מקבל ציון סביר."},
|
| 57 |
+
{"key": "gop.confident_peak", "group": "gop", "kind": "number", "min": 0.05, "max": 0.95, "step": 0.05,
|
| 58 |
+
"label": "ביטחון מספיק", "help": "מאיזו הסתברות של ההגה הנכון השיא כבר לא מוריד את הציון."},
|
| 59 |
+
{"key": "gop.ratio_pool", "group": "gop", "kind": "choice", "choices": list(POOLS),
|
| 60 |
+
"label": "איחוד הפריימים", "help": "איך מצרפים את הפריימים של הגה לציון אחד (docs/gop-pooling.md). gated: רק הפריימים הרועשים."},
|
| 61 |
+
{"key": "gop.energy_gate", "group": "gop", "kind": "number", "min": 0, "max": 1, "step": 0.05,
|
| 62 |
+
"label": "סף עוצמה (gated)", "help": "פריימים שקטים מהחלק הזה של הפריים החזק ביותר לא נספרים."},
|
| 63 |
+
{"key": "gop.vowel_window", "group": "gop", "kind": "window", "min": 0, "max": 10,
|
| 64 |
+
"label": "חלון התנועה", "help": "מכמה פריימים סביב תנועה קוראים את המתחרים שלה. רחב: כמו עיצורים."},
|
| 65 |
+
{"key": "gop.consonant_window", "group": "gop", "kind": "window", "min": 1, "max": 12,
|
| 66 |
+
"label": "חלון העיצור", "help": "כמה פריימים של שקט סביב עיצור נכללים בקריאה שלו. רחב: עד ההגה הבא."},
|
| 67 |
+
]
|
| 68 |
+
GROUPS = {"flag": "סימון טעויות", "unrelated": "זיהוי \"משפט אחר\"", "floors": "רצפות והקלות",
|
| 69 |
+
"gop": "ניקוד ההגה (מתקדם)"}
|
| 70 |
+
FIELD = {f["key"]: f for f in FIELDS}
|
| 71 |
+
|
| 72 |
+
# Per-sound thresholds: the sounds tokens stand for (TargetToken.sound), grouped as a Hebrew speaker meets them.
|
| 73 |
+
SOUND_GROUPS = [
|
| 74 |
+
("גרוניים", [("ħ", "ח (ح)"), ("ʕ", "ע (ع)"), ("h", "ה (ه)"), ("ʔ", "א (ء)"), ("x", "ח׳ (خ)"), ("ɣ", "ע׳ (غ)")]),
|
| 75 |
+
("מודגשים", [("tˤ", "ט (ط)"), ("sˤ", "צ (ص)"), ("dˤ", "ד׳ (ض)"), ("ZH", "ט׳ (ظ)")]),
|
| 76 |
+
("אותיות עם כמה הגיות", [("Q", "ק (ق)"), ("K", "כ (ك)"), ("J", "ג׳ (ج)"), ("TH", "ת׳ (ث)"), ("DH", "ד״ (ذ)")]),
|
| 77 |
+
("עיצורים נוספים", [("r", "ר (ر)"), ("l", "ל (ل)"), ("ʃ", "ש (ش)"), ("s", "ס (س)"), ("z", "ז (ز)"), ("t", "ת (ت)"),
|
| 78 |
+
("d", "ד (د)"), ("k", "כ (ك)"), ("b", "ב (ب)"), ("f", "פ (ف)"), ("m", "מ (م)"), ("n", "נ (ن)"),
|
| 79 |
+
("w", "ו (و)"), ("j", "י (ي)")]),
|
| 80 |
+
]
|
| 81 |
+
SOUNDS = {s for _, group in SOUND_GROUPS for s, _ in group}
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def _get(cfg: ScorerConfig, key: str):
|
| 85 |
+
return getattr(cfg.gop, key[4:]) if key.startswith("gop.") else getattr(cfg, key)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def defaults(model_id: str) -> dict:
|
| 89 |
+
"""What a model runs with before any stored setting: the fields, and the sounds with a built-in threshold."""
|
| 90 |
+
cfg = scorer_config(model_id)
|
| 91 |
+
return {"fields": {f["key"]: _get(cfg, f["key"]) for f in FIELDS}, "sounds": dict(cfg.flag_below_sound)}
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def clean(raw: dict) -> dict:
|
| 95 |
+
"""A stored or submitted settings object, checked field by field. Raises ValueError (in Hebrew) on a bad one."""
|
| 96 |
+
if not isinstance(raw, dict):
|
| 97 |
+
raise ValueError("ההגדרות צריכות להיות אובייקט")
|
| 98 |
+
out: dict = {}
|
| 99 |
+
for key, value in raw.items():
|
| 100 |
+
if key == "flag_below_sound":
|
| 101 |
+
if not isinstance(value, dict):
|
| 102 |
+
raise ValueError("ספי ההגים צריכים להיות אובייקט")
|
| 103 |
+
sounds = {}
|
| 104 |
+
for sound, t in value.items():
|
| 105 |
+
if sound not in SOUNDS:
|
| 106 |
+
raise ValueError(f"הגה לא מוכר: {sound}")
|
| 107 |
+
if t is not None and (isinstance(t, bool) or not isinstance(t, (int, float)) or not 0 <= t <= 100):
|
| 108 |
+
raise ValueError(f"סף ל־{sound} צריך להיות בין 0 ל־100")
|
| 109 |
+
sounds[sound] = None if t is None else float(t)
|
| 110 |
+
out[key] = sounds
|
| 111 |
+
continue
|
| 112 |
+
f = FIELD.get(key)
|
| 113 |
+
if f is None:
|
| 114 |
+
raise ValueError(f"הגדרה לא מוכרת: {key}")
|
| 115 |
+
kind = f["kind"]
|
| 116 |
+
if kind == "choice":
|
| 117 |
+
if value not in f["choices"]:
|
| 118 |
+
raise ValueError(f"{f['label']}: ערך לא מוכר")
|
| 119 |
+
elif kind == "window":
|
| 120 |
+
if value is not None and (isinstance(value, bool) or not isinstance(value, int)
|
| 121 |
+
or not f["min"] <= value <= f["max"]):
|
| 122 |
+
raise ValueError(f"{f['label']}: רחב, או מספר פריימים בין {f['min']} ל־{f['max']}")
|
| 123 |
+
else:
|
| 124 |
+
if isinstance(value, bool) or not isinstance(value, (int, float)) or not f["min"] <= value <= f["max"]:
|
| 125 |
+
raise ValueError(f"{f['label']}: ערך בין {f['min']} ל־{f['max']}")
|
| 126 |
+
if kind == "int" and int(value) != value:
|
| 127 |
+
raise ValueError(f"{f['label']}: מספר שלם")
|
| 128 |
+
value = int(value) if kind == "int" else float(value)
|
| 129 |
+
out[key] = value
|
| 130 |
+
return out
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def build(model_id: str, settings: dict | None) -> ScorerConfig:
|
| 134 |
+
"""The model's ScorerConfig with its stored settings applied."""
|
| 135 |
+
cfg = scorer_config(model_id)
|
| 136 |
+
settings = clean(settings or {})
|
| 137 |
+
gop = {k[4:]: v for k, v in settings.items() if k.startswith("gop.")}
|
| 138 |
+
top = {k: v for k, v in settings.items() if not k.startswith("gop.") and k != "flag_below_sound"}
|
| 139 |
+
sounds = dict(cfg.flag_below_sound)
|
| 140 |
+
for sound, t in settings.get("flag_below_sound", {}).items():
|
| 141 |
+
if t is None:
|
| 142 |
+
sounds.pop(sound, None)
|
| 143 |
+
else:
|
| 144 |
+
sounds[sound] = t
|
| 145 |
+
return replace(cfg, **top, flag_below_sound=sounds, gop=replace(cfg.gop, **gop))
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def describe(model_id: str, settings: dict | None, sound_counts: dict[str, int]) -> dict:
|
| 149 |
+
"""Everything the tab draws: each field with its default and value, each sound with its threshold."""
|
| 150 |
+
base, cfg = defaults(model_id), build(model_id, settings)
|
| 151 |
+
stored = clean(settings or {})
|
| 152 |
+
fields = [{**f, "group_label": GROUPS[f["group"]], "default": base["fields"][f["key"]], "value": _get(cfg, f["key"]),
|
| 153 |
+
"changed": f["key"] in stored} for f in FIELDS]
|
| 154 |
+
stored_sounds = stored.get("flag_below_sound", {})
|
| 155 |
+
sounds = [{"group": name, "sounds": [{"sound": s, "label": label, "count": sound_counts.get(s, 0),
|
| 156 |
+
"default": base["sounds"].get(s), "value": cfg.flag_below_sound.get(s),
|
| 157 |
+
"changed": s in stored_sounds} for s, label in group]}
|
| 158 |
+
for name, group in SOUND_GROUPS]
|
| 159 |
+
return {"fields": fields, "sounds": sounds, "general": cfg.flag_below}
|
app/models.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The phoneme models the management panel's "מודלים" tab offers, with what each was measured to do.
|
| 2 |
+
|
| 3 |
+
Numbers: Minerva test split (255 native lines), greedy CTC mapped onto the labels' phonemes, measured 2026-10-25
|
| 4 |
+
with scripts/zero_shot_phone_models.py (docs/zero-shot-phone-models.md). Speeds: one 2.7 s recording, on this
|
| 5 |
+
project's laptop GPU and on 2 CPU threads (about what the free Space has). POWSM runs padded to 8 s (app/powsm.py):
|
| 6 |
+
its PER, consonant PER and long vowels below are measured that way; its other sounds at the 20 s they were first
|
| 7 |
+
measured at (8 s changed PER by 0.4 points). The short-padding fine-tune runs unpadded, measured that way throughout.
|
| 8 |
+
"""
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
|
| 13 |
+
import os
|
| 14 |
+
|
| 15 |
+
from .powsm import DEPS, ONNX_PREFIX, parse_model_id
|
| 16 |
+
|
| 17 |
+
# the Hub repo the exported POWSM is uploaded to (scripts/export_powsm_onnx.py; README "POWSM on the Space")
|
| 18 |
+
POWSM_ONNX_REPO = os.environ.get("POWSM_ONNX_REPO", "wzender/ihki-powsm-ft").strip()
|
| 19 |
+
|
| 20 |
+
ROOT = Path(__file__).resolve().parent.parent
|
| 21 |
+
|
| 22 |
+
# Per model: recall of each sound (None: the model has no symbol for it), PER and consonant PER.
|
| 23 |
+
CATALOG: list[dict] = [
|
| 24 |
+
{"id": "facebook/wav2vec2-xlsr-53-espeak-cv-ft", "name": "Facebook (מקורי)", "family": "wav2vec2",
|
| 25 |
+
"summary": "המודל הרב־לשוני שהאתר נבנה עליו. לא אומן על ערבית פלסטינית: כמעט לא שומע ח ו־ע.",
|
| 26 |
+
"trained": False, "free_space": True,
|
| 27 |
+
"metrics": {"per": .38, "consonant_per": .29, "ħ": .09, "ʕ": .02, "tˤ": None, "sˤ": None, "dˤ": 0.0,
|
| 28 |
+
"long_vowels": .45},
|
| 29 |
+
"speed": {"gpu": .05, "cpu": .8}, "fps": 50},
|
| 30 |
+
{"id": "checkpoints/ihki-ft-minerva", "name": "wav2vec2 מאומן", "family": "wav2vec2",
|
| 31 |
+
"summary": "אותו מודל, מאומן על הקלטות Minerva. מחליף ישיר: אותו גודל ואותה מהירות, גם על השרת החינמי.",
|
| 32 |
+
"trained": True, "free_space": True,
|
| 33 |
+
"metrics": {"per": .23, "consonant_per": .15, "ħ": .94, "ʕ": .69, "tˤ": None, "sˤ": None, "dˤ": .04,
|
| 34 |
+
"long_vowels": .74},
|
| 35 |
+
"speed": {"gpu": .05, "cpu": .8}, "fps": 50},
|
| 36 |
+
{"id": "checkpoints/powsm-ft-minerva/powsm_ft.pt", "name": "POWSM מאומן", "family": "POWSM-CTC",
|
| 37 |
+
"summary": "מודל פונטי חדש (2026), מאומן על הקלטות Minerva. הכי מדויק, והיחיד ששומע את העיצורים המודגשים (ط ص ض).",
|
| 38 |
+
"trained": True, "free_space": False,
|
| 39 |
+
"metrics": {"per": .16, "consonant_per": .10, "ħ": .94, "ʕ": .89, "tˤ": .82, "sˤ": .77, "dˤ": .46,
|
| 40 |
+
"long_vowels": .68},
|
| 41 |
+
"speed": {"gpu": .29, "cpu": 1.8}, "fps": 25},
|
| 42 |
+
{"id": "checkpoints/powsm-ft-shortpad/powsm_ft.pt", "name": "POWSM מאומן ומהיר", "family": "POWSM-CTC",
|
| 43 |
+
"summary": "אותו POWSM מאומן, שאומן שוב גם על הקלטות קצרות בלי ריפוד: מדויק כמו המקורי ומהיר פי 5 במעבד.",
|
| 44 |
+
"trained": True, "free_space": True,
|
| 45 |
+
"metrics": {"per": .16, "consonant_per": .105, "ħ": .92, "ʕ": .90, "tˤ": .81, "sˤ": .68, "dˤ": .64,
|
| 46 |
+
"long_vowels": .69},
|
| 47 |
+
"speed": {"gpu": .06, "cpu": .8}, "fps": 25},
|
| 48 |
+
{"id": f"{ONNX_PREFIX}{POWSM_ONNX_REPO}", "name": "POWSM מאומן ומהיר (לשרת)", "family": "POWSM-CTC · ONNX",
|
| 49 |
+
"summary": "אותו מודל, מיוצא ל־ONNX: רץ בלי ESPnet, גם על השרת החינמי, ומהיר מהמודל הנוכחי. נטען מ־Hugging Face.",
|
| 50 |
+
"trained": True, "free_space": True,
|
| 51 |
+
"metrics": {"per": .165, "consonant_per": .105, "ħ": .92, "ʕ": .90, "tˤ": .81, "sˤ": .68, "dˤ": .64,
|
| 52 |
+
"long_vowels": .69},
|
| 53 |
+
"speed": {"gpu": None, "cpu": .57}, "fps": 25},
|
| 54 |
+
{"id": "exports/powsm-ft-shortpad", "name": "POWSM מאומן ומהיר (ONNX מקומי)", "family": "POWSM-CTC · ONNX",
|
| 55 |
+
"summary": "הייצוא ל־ONNX מהתיקייה המקומית, לפני ההעלאה ל־Hugging Face.",
|
| 56 |
+
"trained": True, "free_space": True,
|
| 57 |
+
"metrics": {"per": .165, "consonant_per": .105, "ħ": .92, "ʕ": .90, "tˤ": .81, "sˤ": .68, "dˤ": .64,
|
| 58 |
+
"long_vowels": .69},
|
| 59 |
+
"speed": {"gpu": None, "cpu": .57}, "fps": 25},
|
| 60 |
+
{"id": "powsm:<ara>", "name": "POWSM (מקורי)", "family": "POWSM-CTC",
|
| 61 |
+
"summary": "POWSM כפי שפורסם, עם הנחיית ערבית. שומע ח ו־ע היטב בלי אימון, אבל לא כותב תנועות ארוכות.",
|
| 62 |
+
"trained": False, "free_space": False,
|
| 63 |
+
"metrics": {"per": .37, "consonant_per": .22, "ħ": .87, "ʕ": .85, "tˤ": .66, "sˤ": .72, "dˤ": .54,
|
| 64 |
+
"long_vowels": 0.0},
|
| 65 |
+
"speed": {"gpu": .29, "cpu": 1.8}, "fps": 25},
|
| 66 |
+
]
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def availability(model_id: str) -> tuple[bool, str]:
|
| 70 |
+
"""(can this server load it, why not). A Hub id counts as loadable: it downloads on first use."""
|
| 71 |
+
if model_id.startswith(ONNX_PREFIX) or (Path(model_id) / "powsm_onnx.json").is_file():
|
| 72 |
+
try:
|
| 73 |
+
import onnxruntime # noqa: F401
|
| 74 |
+
except ImportError:
|
| 75 |
+
return False, "חסרה החבילה onnxruntime בשרת (requirements.txt)"
|
| 76 |
+
return True, ""
|
| 77 |
+
if model_id.startswith("exports/"):
|
| 78 |
+
return False, "הייצוא ל־ONNX לא נמצא בשרת (scripts/export_powsm_onnx.py)"
|
| 79 |
+
powsm = parse_model_id(model_id)
|
| 80 |
+
if powsm:
|
| 81 |
+
if not (DEPS / "pkgs").exists():
|
| 82 |
+
return False, "חסרות חבילות ההרצה של POWSM בשרת (scripts/setup_zero_shot_deps.sh)"
|
| 83 |
+
if powsm[1] and not Path(powsm[1]).is_file():
|
| 84 |
+
return False, "קובץ המודל לא נמצא בשרת"
|
| 85 |
+
return True, ""
|
| 86 |
+
local = Path(model_id)
|
| 87 |
+
if model_id.startswith(("checkpoints/", "./", "/")) or local.exists():
|
| 88 |
+
if not (local / "config.json").is_file():
|
| 89 |
+
return False, "תיקיית המודל לא נמצאה בשרת"
|
| 90 |
+
return True, ""
|
| 91 |
+
return True, ""
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def catalog(active: str) -> list[dict]:
|
| 95 |
+
"""Every catalog model, plus the active one when it isn't in the catalog (a MODEL_ID of its own)."""
|
| 96 |
+
rows = [dict(m) for m in CATALOG]
|
| 97 |
+
if not any(m["id"] == active for m in rows):
|
| 98 |
+
rows.insert(0, {"id": active, "name": "מודל מותאם", "family": "", "summary": "הוגדר ב־MODEL_ID; לא נמדד כאן.",
|
| 99 |
+
"trained": None, "free_space": None, "metrics": None, "speed": None, "fps": None})
|
| 100 |
+
for m in rows:
|
| 101 |
+
m["available"], m["why"] = availability(m["id"])
|
| 102 |
+
m["active"] = m["id"] == active
|
| 103 |
+
return rows
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def known(model_id: str) -> bool:
|
| 107 |
+
return any(m["id"] == model_id for m in CATALOG)
|
app/powsm.py
ADDED
|
@@ -0,0 +1,237 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""POWSM-CTC (espnet/powsm_ctc) as the app's phoneme model: an Emitter like HFEmitter.
|
| 2 |
+
|
| 3 |
+
Serve a fine-tune with MODEL_ID=checkpoints/powsm-ft-minerva/powsm_ft.pt (train/finetune_powsm.py), or the
|
| 4 |
+
published model with MODEL_ID=powsm:<ara>. It needs the extra packages from scripts/setup_zero_shot_deps.sh
|
| 5 |
+
(.zero-shot-deps/), which are not in requirements.txt: this is for trying the model locally, not yet for the Space.
|
| 6 |
+
|
| 7 |
+
What the adapter changes so the scorer can read POWSM's output unchanged:
|
| 8 |
+
- columns: only POWSM's phone tokens (6,405 of 40,002; the rest are text pieces and task tags) and the blank,
|
| 9 |
+
renormalised. Phone names lose their slashes and tie bars (/d͡ʒ/ -> dʒ), the spelling the scorer's rules use.
|
| 10 |
+
- frames: the language/task prompt's two positions and the padding after the speech are dropped, and every frame
|
| 11 |
+
is repeated once. POWSM runs at 25 frames/s; the scorer's frame counts (vowel length, alignment padding) were
|
| 12 |
+
tuned at wav2vec2's 50.
|
| 13 |
+
"""
|
| 14 |
+
from __future__ import annotations
|
| 15 |
+
|
| 16 |
+
import glob
|
| 17 |
+
import os
|
| 18 |
+
import sys
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
|
| 21 |
+
import numpy as np
|
| 22 |
+
|
| 23 |
+
ROOT = Path(__file__).resolve().parent.parent
|
| 24 |
+
DEPS = ROOT / ".zero-shot-deps"
|
| 25 |
+
SAMPLE_RATE = 16_000
|
| 26 |
+
# POWSM was trained on 20 s inputs (its model card says pad to 20 s) and loses accuracy without padding (test PER
|
| 27 |
+
# 16% -> 21%). 8 s keeps it (16.2%) at 1.8 s a recording on 2 CPU threads instead of 4.4 s. A fine-tune trained on
|
| 28 |
+
# random padding (train/finetune_powsm.py --pad random) needs none: unpadded it scores 16.2% at ~0.8 s.
|
| 29 |
+
# POWSM_PAD_SECONDS, when set, overrides both (0: no padding).
|
| 30 |
+
SECONDS = 8.0
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def pad_seconds(checkpoint: str | None) -> float:
|
| 34 |
+
"""The padding a model runs with: POWSM_PAD_SECONDS if set, none for a short-padding fine-tune, else SECONDS."""
|
| 35 |
+
env = os.environ.get("POWSM_PAD_SECONDS", "").strip()
|
| 36 |
+
if env:
|
| 37 |
+
return float(env)
|
| 38 |
+
if checkpoint:
|
| 39 |
+
import torch
|
| 40 |
+
args = torch.load(checkpoint, map_location="cpu").get("args") or {}
|
| 41 |
+
if args.get("pad") == "random":
|
| 42 |
+
return 0.0
|
| 43 |
+
return SECONDS
|
| 44 |
+
PROMPT = 2 # the language and task tokens the encoder prepends to its output
|
| 45 |
+
UPSAMPLE = 2 # 25 frames/s -> the 50 the scorer was tuned at
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def use_extra_deps() -> None:
|
| 49 |
+
"""Make .zero-shot-deps importable, after the app's own packages so its torch/numpy always win."""
|
| 50 |
+
if not (DEPS / "pkgs").exists():
|
| 51 |
+
raise RuntimeError("POWSM needs extra packages: run scripts/setup_zero_shot_deps.sh first")
|
| 52 |
+
for sub in ("pkgs", "stubs"):
|
| 53 |
+
if str(DEPS / sub) not in sys.path:
|
| 54 |
+
sys.path.append(str(DEPS / sub))
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def patch_espnet_for_powsm_ctc() -> None:
|
| 58 |
+
"""ESPnet 202511 (the newest release for Python 3.10) can't run POWSM-CTC as published: the encoder hands
|
| 59 |
+
Conv2dSubsampling the language/task prompt, which that release's layer doesn't accept. Same logic as ESPnet
|
| 60 |
+
master: linear -> prepend the prompt embeddings -> positional encoding."""
|
| 61 |
+
import torch
|
| 62 |
+
from espnet.nets.pytorch_backend.transformer import subsampling
|
| 63 |
+
|
| 64 |
+
def forward(self, x, x_mask, prefix_embeds=None):
|
| 65 |
+
x = self.conv(x.unsqueeze(1))
|
| 66 |
+
b, c, t, f = x.size()
|
| 67 |
+
linear, pos_enc = self.out[0], self.out[1]
|
| 68 |
+
x = linear(x.transpose(1, 2).contiguous().view(b, t, c * f))
|
| 69 |
+
if x_mask is not None:
|
| 70 |
+
x_mask = x_mask[:, :, :-2:2][:, :, :-2:2]
|
| 71 |
+
if prefix_embeds is not None:
|
| 72 |
+
x = torch.cat([prefix_embeds, x], dim=1)
|
| 73 |
+
if x_mask is not None:
|
| 74 |
+
ones = torch.ones(x_mask.shape[0], 1, prefix_embeds.size(1), dtype=x_mask.dtype, device=x_mask.device)
|
| 75 |
+
x_mask = torch.cat([ones, x_mask], dim=-1)
|
| 76 |
+
return pos_enc(x), x_mask
|
| 77 |
+
|
| 78 |
+
subsampling.Conv2dSubsampling.forward = forward
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def load_powsm(lang: str = "<ara>", checkpoint: str | None = None, device: str | None = None):
|
| 82 |
+
"""espnet/powsm_ctc as ESPnet's greedy-CTC Speech2Text, with an optional fine-tune's weights on top."""
|
| 83 |
+
use_extra_deps()
|
| 84 |
+
import torch
|
| 85 |
+
from huggingface_hub import snapshot_download
|
| 86 |
+
patch_espnet_for_powsm_ctc()
|
| 87 |
+
from espnet2.bin.s2t_inference_ctc import Speech2TextGreedySearch
|
| 88 |
+
device = device or ("cuda" if torch.cuda.is_available() else "cpu")
|
| 89 |
+
s2t = Speech2TextGreedySearch.from_pretrained("espnet/powsm_ctc", device=device, lang_sym=lang, task_sym="<pr>")
|
| 90 |
+
model = s2t.s2t_model
|
| 91 |
+
# The checkpoint stores the subsampling linear layer as `embed.out.*` (master's layout); the release expects
|
| 92 |
+
# `embed.out.0.*` and silently leaves it random. Copy it in.
|
| 93 |
+
ckpt = glob.glob(f"{snapshot_download('espnet/powsm_ctc')}/exp/s2t_train*/*.pth")[0]
|
| 94 |
+
state = torch.load(ckpt, map_location="cpu")
|
| 95 |
+
lin = model.encoder.embed.out[0]
|
| 96 |
+
with torch.no_grad():
|
| 97 |
+
lin.weight.copy_(state["encoder.embed.out.weight"])
|
| 98 |
+
lin.bias.copy_(state["encoder.embed.out.bias"])
|
| 99 |
+
if checkpoint: # train/finetune_powsm.py saves only the weights it trained
|
| 100 |
+
saved = torch.load(checkpoint, map_location="cpu")
|
| 101 |
+
missing = set(saved["state"]) - set(model.state_dict())
|
| 102 |
+
if missing:
|
| 103 |
+
raise KeyError(f"{checkpoint} has weights this model lacks: {sorted(missing)[:5]}")
|
| 104 |
+
model.load_state_dict(saved["state"], strict=False)
|
| 105 |
+
model.eval()
|
| 106 |
+
return s2t
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def parse_model_id(model_id: str) -> tuple[str, str | None] | None:
|
| 110 |
+
"""(language token, checkpoint) when MODEL_ID names a POWSM model, else None.
|
| 111 |
+
'powsm' or 'powsm:<ara>' is the published model; a path to a .pt file is a fine-tune (always <ara>)."""
|
| 112 |
+
if model_id == "powsm" or model_id.startswith("powsm:"):
|
| 113 |
+
return (model_id.split(":", 1)[1] if ":" in model_id else "<ara>"), None
|
| 114 |
+
if model_id.endswith(".pt"):
|
| 115 |
+
return "<ara>", model_id
|
| 116 |
+
return None
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
class PowsmEmitter:
|
| 120 |
+
"""POWSM-CTC -> (T, V) log-posteriors over its phone tokens, at 50 frames/s (see the module docstring)."""
|
| 121 |
+
|
| 122 |
+
def __init__(self, lang: str = "<ara>", checkpoint: str | None = None, device: str | None = None):
|
| 123 |
+
import torch
|
| 124 |
+
self.torch = torch
|
| 125 |
+
self.s2t = load_powsm(lang, checkpoint, device)
|
| 126 |
+
self.pad = pad_seconds(checkpoint)
|
| 127 |
+
model = self.s2t.s2t_model
|
| 128 |
+
tokens = model.token_list
|
| 129 |
+
cols, names = [model.blank_id], {"<blank>": 0}
|
| 130 |
+
for i, t in enumerate(tokens):
|
| 131 |
+
if len(t) > 2 and t[0] == "/" and t[-1] == "/":
|
| 132 |
+
name = t[1:-1].replace("͡", "")
|
| 133 |
+
if name not in names: # a tie-barred spelling that collides with a plain one keeps the plain one
|
| 134 |
+
names[name] = len(cols)
|
| 135 |
+
cols.append(i)
|
| 136 |
+
self.cols = torch.tensor(cols)
|
| 137 |
+
self.token_to_id: dict[str, int] = names
|
| 138 |
+
self.blank_token = "<blank>"
|
| 139 |
+
self.lang_id = self.s2t.converter.token2id[lang]
|
| 140 |
+
self.task_id = self.s2t.converter.token2id["<pr>"]
|
| 141 |
+
|
| 142 |
+
def __call__(self, wav: np.ndarray) -> np.ndarray:
|
| 143 |
+
torch = self.torch
|
| 144 |
+
model, device = self.s2t.s2t_model, self.s2t.device
|
| 145 |
+
n = int(self.pad * SAMPLE_RATE)
|
| 146 |
+
x = np.pad(wav, (0, max(0, n - len(wav)))).astype(np.float32) # longer recordings run as they are
|
| 147 |
+
speech = torch.from_numpy(x)[None].to(device)
|
| 148 |
+
prefix = torch.tensor([[self.lang_id, self.task_id]], device=device)
|
| 149 |
+
prev = torch.tensor([[model.na]], device=device)
|
| 150 |
+
with torch.inference_mode():
|
| 151 |
+
enc, _ = model.encode(speech, torch.tensor([speech.shape[1]], device=device), prev,
|
| 152 |
+
torch.tensor([1], device=device), prefix, torch.tensor([2], device=device))
|
| 153 |
+
if isinstance(enc, tuple):
|
| 154 |
+
enc = enc[0]
|
| 155 |
+
enc = enc[0, PROMPT:]
|
| 156 |
+
keep = max(1, round(enc.shape[0] * len(wav) / len(x))) # frames that cover the speech
|
| 157 |
+
logits = model.ctc.ctc_lo(enc[:keep].float())[:, self.cols.to(device)]
|
| 158 |
+
logp = torch.log_softmax(logits, -1).cpu().numpy()
|
| 159 |
+
return np.repeat(logp, UPSAMPLE, axis=0)
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
# ---- the exported model (scripts/export_powsm_onnx.py): what the Space runs, with onnxruntime and torch only ----
|
| 163 |
+
|
| 164 |
+
ONNX_PREFIX = "powsm-onnx:"
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def onnx_model_dir(model_id: str, download: bool = True) -> Path | None:
|
| 168 |
+
"""The folder of an exported POWSM when MODEL_ID names one, else None: powsm-onnx:<Hub repo> (downloaded once,
|
| 169 |
+
then from the Hugging Face cache) or a local folder with powsm_onnx.json."""
|
| 170 |
+
if model_id.startswith(ONNX_PREFIX):
|
| 171 |
+
repo = model_id[len(ONNX_PREFIX):]
|
| 172 |
+
if not download:
|
| 173 |
+
return Path(repo)
|
| 174 |
+
from huggingface_hub import snapshot_download
|
| 175 |
+
return Path(snapshot_download(repo, allow_patterns=["powsm_onnx.json", "frontend.npz", onnx_precision_file()]))
|
| 176 |
+
local = Path(model_id)
|
| 177 |
+
return local if (local / "powsm_onnx.json").is_file() else None
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def onnx_precision_file(meta: dict | None = None) -> str:
|
| 181 |
+
"""The weights file POWSM_ONNX_PRECISION picks: fp32 (the default) or int8. On the Minerva test lines, 2 CPU
|
| 182 |
+
threads: fp32 PER 16.5% at 0.57 s a recording; int8 16.6% at 0.38 s, but ط 81% -> 76% and ص 68% -> 62%."""
|
| 183 |
+
precision = os.environ.get("POWSM_ONNX_PRECISION", "fp32").strip().lower() or "fp32"
|
| 184 |
+
files = (meta or {}).get("files") or {"fp32": "model.onnx", "int8": "model.int8.onnx"}
|
| 185 |
+
return files.get(precision) or files["fp32"]
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
class PowsmOnnxEmitter:
|
| 189 |
+
"""An exported POWSM-CTC -> (T, V) log-posteriors over its phone tokens at 50 frames/s, like PowsmEmitter but
|
| 190 |
+
without ESPnet. The front end (STFT, mel, log, global mean/variance) runs in torch from frontend.npz; the encoder
|
| 191 |
+
and CTC head in onnxruntime. The prompt (<ara>, <pr>) is baked into the export."""
|
| 192 |
+
|
| 193 |
+
def __init__(self, folder: str, precision: str | None = None):
|
| 194 |
+
import json
|
| 195 |
+
|
| 196 |
+
import onnxruntime as ort
|
| 197 |
+
import torch
|
| 198 |
+
self.torch, self.folder = torch, Path(folder)
|
| 199 |
+
self.meta = json.loads((self.folder / "powsm_onnx.json").read_text(encoding="utf-8"))
|
| 200 |
+
weights = (self.meta["files"].get(precision) or self.meta["files"]["fp32"]) if precision \
|
| 201 |
+
else onnx_precision_file(self.meta)
|
| 202 |
+
opts = ort.SessionOptions()
|
| 203 |
+
opts.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
|
| 204 |
+
# a container can see more cores than it may use (the free Space has 2): POWSM_ONNX_THREADS caps them
|
| 205 |
+
threads = int(os.environ.get("POWSM_ONNX_THREADS", "0") or 0)
|
| 206 |
+
if threads > 0:
|
| 207 |
+
opts.intra_op_num_threads, opts.inter_op_num_threads = threads, 1
|
| 208 |
+
self.session = ort.InferenceSession(str(self.folder / weights), opts, providers=["CPUExecutionProvider"])
|
| 209 |
+
fe = np.load(self.folder / "frontend.npz")
|
| 210 |
+
self.window = torch.from_numpy(fe["window"].astype(np.float32))
|
| 211 |
+
self.melmat = torch.from_numpy(fe["melmat"].astype(np.float32))
|
| 212 |
+
self.mean = torch.from_numpy(fe["mean"].astype(np.float32))
|
| 213 |
+
self.std = torch.from_numpy(fe["std"].astype(np.float32))
|
| 214 |
+
self.n_fft, self.win, self.hop = int(fe["n_fft"]), int(fe["win_length"]), int(fe["hop_length"])
|
| 215 |
+
self.token_to_id: dict[str, int] = self.meta["vocab"]
|
| 216 |
+
self.blank_token = "<blank>"
|
| 217 |
+
env = os.environ.get("POWSM_PAD_SECONDS", "").strip()
|
| 218 |
+
self.pad = float(env) if env else float(self.meta.get("pad_seconds", SECONDS))
|
| 219 |
+
self.weights = weights
|
| 220 |
+
|
| 221 |
+
def features(self, x: np.ndarray):
|
| 222 |
+
"""ESPnet's DefaultFrontend + GlobalMVN: centred STFT, power, 80 mel bands, natural log, (x - mean) / std."""
|
| 223 |
+
torch = self.torch
|
| 224 |
+
spec = torch.stft(torch.from_numpy(x), self.n_fft, hop_length=self.hop, win_length=self.win,
|
| 225 |
+
window=self.window, center=True, pad_mode="reflect", normalized=False, onesided=True,
|
| 226 |
+
return_complex=True)
|
| 227 |
+
power = spec.real ** 2 + spec.imag ** 2 # (F, T)
|
| 228 |
+
mel = torch.clamp(power.transpose(0, 1) @ self.melmat, min=1e-10).log()
|
| 229 |
+
return ((mel - self.mean) / self.std)[None].numpy()
|
| 230 |
+
|
| 231 |
+
def __call__(self, wav: np.ndarray) -> np.ndarray:
|
| 232 |
+
n = int(self.pad * SAMPLE_RATE)
|
| 233 |
+
x = np.pad(wav, (0, max(0, n - len(wav)))).astype(np.float32) # a longer recording runs as it is
|
| 234 |
+
feats = self.features(x)
|
| 235 |
+
logp = self.session.run(None, {"feats": feats, "feats_lens": np.array([feats.shape[1]], dtype=np.int64)})[0][0]
|
| 236 |
+
keep = max(1, round(logp.shape[0] * len(wav) / len(x))) # frames that cover the speech
|
| 237 |
+
return np.repeat(logp[:keep], UPSAMPLE, axis=0)
|
app/prefetch.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Downloads MODEL_ID's files while the Docker image is built, so a cold start doesn't (see the Dockerfile).
|
| 2 |
+
|
| 3 |
+
MODEL_ID=powsm-onnx:<repo> python -m app.prefetch # an exported POWSM (scripts/export_powsm_onnx.py)
|
| 4 |
+
MODEL_ID=facebook/wav2vec2-xlsr-53-espeak-cv-ft python -m app.prefetch
|
| 5 |
+
|
| 6 |
+
A private repo needs HF_TOKEN (the Dockerfile passes the Space secret of that name to this step only).
|
| 7 |
+
"""
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import os
|
| 11 |
+
import sys
|
| 12 |
+
|
| 13 |
+
from .powsm import ONNX_PREFIX, onnx_model_dir, parse_model_id
|
| 14 |
+
|
| 15 |
+
DEFAULT = "facebook/wav2vec2-xlsr-53-espeak-cv-ft"
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def main() -> None:
|
| 19 |
+
model_id = os.environ.get("MODEL_ID", "").strip() or DEFAULT
|
| 20 |
+
if model_id.startswith(ONNX_PREFIX):
|
| 21 |
+
print("exported POWSM:", onnx_model_dir(model_id))
|
| 22 |
+
return
|
| 23 |
+
if parse_model_id(model_id):
|
| 24 |
+
sys.exit(f"MODEL_ID={model_id} needs ESPnet, which the image doesn't have: export it with "
|
| 25 |
+
f"scripts/export_powsm_onnx.py and use MODEL_ID={ONNX_PREFIX}<repo>")
|
| 26 |
+
from huggingface_hub import hf_hub_download
|
| 27 |
+
from transformers import AutoFeatureExtractor, Wav2Vec2ForCTC
|
| 28 |
+
AutoFeatureExtractor.from_pretrained(model_id)
|
| 29 |
+
Wav2Vec2ForCTC.from_pretrained(model_id)
|
| 30 |
+
hf_hub_download(model_id, "vocab.json")
|
| 31 |
+
print("wav2vec2:", model_id)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
if __name__ == "__main__":
|
| 35 |
+
main()
|
app/scorer.py
CHANGED
|
@@ -1126,8 +1126,17 @@ def scorer_config(model_id: str) -> ScorerConfig:
|
|
| 1126 |
|
| 1127 |
|
| 1128 |
def load_scorer(model_id: str) -> Scorer:
|
| 1129 |
-
|
| 1130 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1131 |
scorer = Scorer(emitter, vocab, scorer_config(model_id))
|
| 1132 |
# resolve every phoneme once at startup so missing symbols show up in the logs and /api/health
|
| 1133 |
from .phrases import PHRASES
|
|
|
|
| 1126 |
|
| 1127 |
|
| 1128 |
def load_scorer(model_id: str) -> Scorer:
|
| 1129 |
+
from .powsm import PowsmEmitter, PowsmOnnxEmitter, onnx_model_dir, parse_model_id
|
| 1130 |
+
powsm, exported = parse_model_id(model_id), onnx_model_dir(model_id)
|
| 1131 |
+
if exported: # an exported POWSM-CTC (scripts/export_powsm_onnx.py): onnxruntime only, what the Space runs
|
| 1132 |
+
emitter = PowsmOnnxEmitter(str(exported))
|
| 1133 |
+
vocab = Vocab(emitter.token_to_id, blank_token=emitter.blank_token)
|
| 1134 |
+
elif powsm: # POWSM-CTC through ESPnet (app/powsm.py): a local trial, needs .zero-shot-deps
|
| 1135 |
+
emitter = PowsmEmitter(*powsm)
|
| 1136 |
+
vocab = Vocab(emitter.token_to_id, blank_token=emitter.blank_token)
|
| 1137 |
+
else:
|
| 1138 |
+
emitter = HFEmitter(model_id)
|
| 1139 |
+
vocab = Vocab(emitter.token_to_id)
|
| 1140 |
scorer = Scorer(emitter, vocab, scorer_config(model_id))
|
| 1141 |
# resolve every phoneme once at startup so missing symbols show up in the logs and /api/health
|
| 1142 |
from .phrases import PHRASES
|
docs/zero-shot-phone-models.md
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Zero-shot phone models on Palestinian Arabic
|
| 2 |
+
|
| 3 |
+
Can a newer phone recognizer replace `facebook/wav2vec2-xlsr-53-espeak-cv-ft` as the base model? Every model was run
|
| 4 |
+
as-is (no training on our data) on the held-out Minerva lines and compared with the current base and the current
|
| 5 |
+
fine-tune (`checkpoints/ihki-ft-minerva`). Measured 2026-10-25 with
|
| 6 |
+
[scripts/zero_shot_phone_models.py](../scripts/zero_shot_phone_models.py). Raw results, including every line's
|
| 7 |
+
transcript, are saved locally in `data/minerva/bench/zero-shot-{dev,test}.json`.
|
| 8 |
+
|
| 9 |
+
## Verdict
|
| 10 |
+
|
| 11 |
+
- **Nothing replaces the fine-tune as-is.** It has the lowest phoneme error rate (23% on test) and the best long-vowel
|
| 12 |
+
recall, and it already fits the app.
|
| 13 |
+
- **ZIPA isn't worth pursuing.** It's no better than the current base overall, and it never hears ħ, ʕ or the
|
| 14 |
+
emphatics.
|
| 15 |
+
- **POWSM-CTC with the Arabic prompt is the strongest starting point for fine-tuning.** Untrained on our data, it hears
|
| 16 |
+
ħ (87%) and ʕ (85%) about as well as the fine-tune. It's also the only model that hears the emphatics: tˤ 66%,
|
| 17 |
+
sˤ 72%, dˤ 54%. The current vocab has no symbol for tˤ or sˤ, and the fine-tune gets dˤ only 4% of the time.
|
| 18 |
+
Its weak points:
|
| 19 |
+
- It never writes a long vowel: `aː` came out as `a` 235 times out of 268, though its vocab has `aː`.
|
| 20 |
+
- It runs at 25 frames/s, half our 50.
|
| 21 |
+
- It needs a new loader, because it runs on ESPnet rather than Hugging Face `transformers`.
|
| 22 |
+
|
| 23 |
+
**Next step:** fine-tune POWSM-CTC with the Arabic prompt on `data/minerva` instead of w2v-BERT 2.0. Training on
|
| 24 |
+
labels that mark length should teach it the long vowels it currently never writes. Check what 25 frames/s does to the
|
| 25 |
+
vowel-length check before moving it into the app.
|
| 26 |
+
|
| 27 |
+
## Results: test split (255 lines)
|
| 28 |
+
|
| 29 |
+
| Model | PER | Consonant PER | ħ | ʕ | tˤ | sˤ | dˤ | ʔ | Long vowels | Vowel length | Frames/s | s/clip | Fits app? |
|
| 30 |
+
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
| 31 |
+
| xlsr-53-espeak (current base) | 38% | 29% | 9% | 2% | no symbol | no symbol | 0% | 3% | 45% | 85% | 50 | 0.05 | yes |
|
| 32 |
+
| **ihki-ft-minerva (current fine-tune)** | **23%** | **15%** | **94%** | 69% | no symbol | no symbol | 4% | **72%** | **74%** | **91%** | 50 | 0.05 | yes |
|
| 33 |
+
| ZIPA large CR-CTC | 38% | 29% | 0% | 0% | 0% | 0% | 0% | 5% | 39% | 86% | 49 | 0.32 | new loader (ONNX) |
|
| 34 |
+
| POWSM-CTC, no language | 43% | 32% | 6% | 1% | 0% | 0% | 0% | 0% | 0% | 81% | 25 | 0.29 | new loader (ESPnet) |
|
| 35 |
+
| **POWSM-CTC, Arabic prompt** | 37% | 22% | 87% | **85%** | **66%** | **72%** | **54%** | 62% | 0% | 79% | 25 | 0.29 | new loader (ESPnet) |
|
| 36 |
+
|
| 37 |
+
The dev split (192 lines) gives the same ranking: fine-tune 26%, POWSM with the Arabic prompt 40%, ZIPA 39%,
|
| 38 |
+
base 41%, POWSM without a language 46%. The fine-tune picked its best epoch on dev, so its dev number is slightly
|
| 39 |
+
optimistic. That's why test is the headline.
|
| 40 |
+
|
| 41 |
+
What each column means:
|
| 42 |
+
|
| 43 |
+
- **PER**: phoneme error rate, i.e. edits needed to turn the model's output into the label, divided by the label's
|
| 44 |
+
length.
|
| 45 |
+
- **Consonant PER**: the same with every vowel removed from both. These are the sounds the scorer grades hardest.
|
| 46 |
+
- **ħ … ʔ, Long vowels**: how often a labelled sound was heard as itself. "No symbol" means the model's vocab can't
|
| 47 |
+
write it. Long vowels covers `aː iː uː eː oː` together.
|
| 48 |
+
- **Vowel length**: of the labelled vowels the model heard as some vowel, how often it got long vs short right.
|
| 49 |
+
- **Frames/s**: CTC output rate. The long-vowel check measures vowel length in frames, so fewer frames means coarser
|
| 50 |
+
timing.
|
| 51 |
+
- **s/clip**: wall time on the laptop (RTX 1000 Ada, 6 GB). ZIPA runs on CPU (see Setup).
|
| 52 |
+
|
| 53 |
+
What each sound was heard as instead (test):
|
| 54 |
+
|
| 55 |
+
| Model | ħ (127) | ʕ (209) | tˤ (62) | aː (268) |
|
| 56 |
+
|---|---|---|---|---|
|
| 57 |
+
| Current base | h 79, nothing 15, x 8 | nothing 133, aː 25 | t 46 | a 70, nothing 32 |
|
| 58 |
+
| Fine-tune | x 5, ʃ 2 | nothing 31, ʔ 6 | t 58 (no symbol) | a 49 |
|
| 59 |
+
| ZIPA | h 89, nothing 19 | nothing 128, aː 22 | t 47 | a 72, nothing 28 |
|
| 60 |
+
| POWSM, no language | h 88, nothing 10 | nothing 135, a 22 | t 47 | a 127, e 68 |
|
| 61 |
+
| POWSM, Arabic prompt | x 6, a 5 | nothing 14, a 8 | t 14 | a 235 |
|
| 62 |
+
|
| 63 |
+
With the Arabic prompt POWSM also leans toward Standard Arabic: it adds case endings and some MSA forms. For example,
|
| 64 |
+
it wrote *bsēder* as *sadari…* and *madrase* as *madrasi(ja)*. Fine-tuning on Palestinian labels should fix that,
|
| 65 |
+
but it's worth watching.
|
| 66 |
+
|
| 67 |
+
## Method
|
| 68 |
+
|
| 69 |
+
- **Models:**
|
| 70 |
+
- [anyspeech/zipa-large-crctc-500k](https://huggingface.co/anyspeech/zipa-large-crctc-500k): the official ONNX
|
| 71 |
+
export.
|
| 72 |
+
- [espnet/powsm_ctc](https://huggingface.co/espnet/powsm_ctc): run with the phone-recognition task token `<pr>`,
|
| 73 |
+
either with no language (`<unk>`) or with `<ara>`, and padded to 20 s as its model card says.
|
| 74 |
+
- **Decoding:** greedy CTC for every model, on audio trimmed with the app's own `decode_audio`.
|
| 75 |
+
- **Mapping onto our labels** (`canon()` in the script):
|
| 76 |
+
- Length marks join their vowel, and long consonants count as geminates.
|
| 77 |
+
- Details the labels never write are dropped (dental `t̪`, aspiration).
|
| 78 |
+
- Symbols with no contrast in Palestinian are merged: χ→x, ʁ→ɣ, ɾ→r, ɡ→g.
|
| 79 |
+
- Vowel qualities fold to `a e i o u` (ɛ→e, ɪ→i, ə→e, ʊ→u).
|
| 80 |
+
- Geminates collapse to one sound on both sides, as the scorer's `tokenize()` does.
|
| 81 |
+
- **Fairness caveat:** the current base and the fine-tune have no symbols for tˤ, sˤ or ðˤ. Training mapped them to
|
| 82 |
+
t, s and z. Their PER counts those as errors, which costs the fine-tune a few points. The per-sound columns show it
|
| 83 |
+
directly.
|
| 84 |
+
|
| 85 |
+
## Setup notes
|
| 86 |
+
|
| 87 |
+
ZIPA and POWSM need packages that conflict with the app's environment. They install into a git-ignored
|
| 88 |
+
`.zero-shot-deps/` folder (`scripts/setup_zero_shot_deps.sh`, pinned in `requirements-zero-shot.txt`), and only this
|
| 89 |
+
script uses it.
|
| 90 |
+
|
| 91 |
+
POWSM-CTC doesn't run on the newest ESPnet release for Python 3.10 (202511) as published. The script patches that
|
| 92 |
+
release in memory, with two fixes:
|
| 93 |
+
|
| 94 |
+
1. The encoder passes the language/task prompt to its subsampling layer, which doesn't accept it in that release. The
|
| 95 |
+
patch copies ESPnet master's logic.
|
| 96 |
+
2. The checkpoint names that layer's weights differently from what the release expects, so the release silently leaves
|
| 97 |
+
the layer randomly initialised. Before this fix the model output junk. The script copies those weights in by hand.
|
| 98 |
+
|
| 99 |
+
ESPnet also imports `torchaudio`, which has no build for torch 2.14. It's only used for multi-microphone beamforming
|
| 100 |
+
code that POWSM never runs, so the setup script installs a placeholder that fails loudly if anything calls it.
|
| 101 |
+
|
| 102 |
+
ZIPA runs on CPU, because onnxruntime's GPU build needs CUDA 12 and this machine has CUDA 13. At about 0.3 s per clip
|
| 103 |
+
that's fine for evaluation.
|
| 104 |
+
|
| 105 |
+
Rerun:
|
| 106 |
+
|
| 107 |
+
```bash
|
| 108 |
+
scripts/setup_zero_shot_deps.sh # once
|
| 109 |
+
python scripts/zero_shot_phone_models.py --split test # all models; or --models powsm-ara,ft
|
| 110 |
+
python scripts/zero_shot_phone_models.py --split test --report # just the table
|
| 111 |
+
```
|
requirements-zero-shot.txt
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Extra packages for scripts/zero_shot_phone_models.py (ZIPA and POWSM-CTC), on top of requirements.txt.
|
| 2 |
+
# Installed with --no-deps into .zero-shot-deps/ by scripts/setup_zero_shot_deps.sh, never into the app venv:
|
| 3 |
+
# ESPnet's own pins (old librosa, typeguard, ...) conflict with the app's torch/numpy, so this is the exact set
|
| 4 |
+
# that was checked to work with torch 2.14 / numpy 2.2 / Python 3.10.
|
| 5 |
+
|
| 6 |
+
# ZIPA (ONNX). The CPU build: onnxruntime-gpu 1.23 needs CUDA 12 and the app runs CUDA 13.
|
| 7 |
+
onnxruntime==1.23.2
|
| 8 |
+
lhotse==1.33.0
|
| 9 |
+
coloredlogs==15.0.1
|
| 10 |
+
humanfriendly==10.0
|
| 11 |
+
flatbuffers==25.12.19
|
| 12 |
+
protobuf==7.36.2
|
| 13 |
+
audioread==3.1.0
|
| 14 |
+
cytoolz==1.2.0
|
| 15 |
+
toolz==1.2.0
|
| 16 |
+
intervaltree==3.2.1
|
| 17 |
+
sortedcontainers==2.4.0
|
| 18 |
+
soundfile==0.14.0
|
| 19 |
+
|
| 20 |
+
# exporting POWSM to ONNX (scripts/export_powsm_onnx.py)
|
| 21 |
+
onnx==1.17.0
|
| 22 |
+
|
| 23 |
+
# POWSM-CTC (ESPnet). 202511 is the newest release for Python 3.10; the script patches its two POWSM-CTC bugs.
|
| 24 |
+
espnet==202511
|
| 25 |
+
espnet-model-zoo==0.1.7
|
| 26 |
+
espnet-tts-frontend==0.0.4
|
| 27 |
+
espnet-g2p-en==2.1.0.post1
|
| 28 |
+
antlr4-python3-runtime==4.9.3
|
| 29 |
+
ci_sdr==0.0.2
|
| 30 |
+
cloudpickle==3.1.2
|
| 31 |
+
ConfigArgParse==1.8.0
|
| 32 |
+
ctc_segmentation==1.7.5
|
| 33 |
+
Cython==3.3.0
|
| 34 |
+
decorator==5.3.1
|
| 35 |
+
defusedxml==0.7.1
|
| 36 |
+
Distance==0.1.3
|
| 37 |
+
editdistance==0.8.1
|
| 38 |
+
einops==0.8.2
|
| 39 |
+
fast_bss_eval==0.1.3
|
| 40 |
+
h5py==3.16.0
|
| 41 |
+
hydra-core==1.3.7
|
| 42 |
+
importlib-metadata==4.13.0
|
| 43 |
+
inflect==7.0.0
|
| 44 |
+
jaconv==0.5.0
|
| 45 |
+
jamo==0.4.1
|
| 46 |
+
joblib==1.6.0
|
| 47 |
+
kaldiio==2.18.1
|
| 48 |
+
lazy-loader==0.6
|
| 49 |
+
librosa==0.11.0
|
| 50 |
+
llvmlite==0.50.0
|
| 51 |
+
msgpack==1.2.3
|
| 52 |
+
nltk==3.10.4
|
| 53 |
+
numba==0.68.0
|
| 54 |
+
omegaconf==2.3.1
|
| 55 |
+
opt_einsum==3.4.0
|
| 56 |
+
pandas==2.3.3
|
| 57 |
+
platformdirs==4.12.4
|
| 58 |
+
pooch==1.9.0
|
| 59 |
+
pypinyin==0.44.0
|
| 60 |
+
python-dateutil==3.0.0
|
| 61 |
+
pytorch-wpe==0.0.1
|
| 62 |
+
pytz==2026.5
|
| 63 |
+
pyworld==0.3.5
|
| 64 |
+
resampy==0.4.3
|
| 65 |
+
scikit-learn==1.7.2
|
| 66 |
+
scipy==1.15.3
|
| 67 |
+
sentencepiece==0.1.97
|
| 68 |
+
six==1.17.0
|
| 69 |
+
soxr==1.1.0
|
| 70 |
+
standard-aifc==3.13.0
|
| 71 |
+
standard-sunau==3.13.0
|
| 72 |
+
threadpoolctl==3.7.0
|
| 73 |
+
torch-complex==0.4.4
|
| 74 |
+
typeguard==2.13.3
|
| 75 |
+
tzdata==2026.5
|
| 76 |
+
Unidecode==1.4.0
|
| 77 |
+
zipp==4.1.2
|
requirements.txt
CHANGED
|
@@ -13,3 +13,4 @@ pywebpush>=2.0 # the daily video's morning reminder (app/push.py)
|
|
| 13 |
edge-tts>=7.0
|
| 14 |
gTTS>=2.5
|
| 15 |
tzdata>=2024.1 # time zones for zoneinfo: the slim image may not carry the system ones
|
|
|
|
|
|
| 13 |
edge-tts>=7.0
|
| 14 |
gTTS>=2.5
|
| 15 |
tzdata>=2024.1 # time zones for zoneinfo: the slim image may not carry the system ones
|
| 16 |
+
onnxruntime>=1.20 # the exported POWSM phoneme model (app/powsm.py PowsmOnnxEmitter, MODEL_ID=powsm-onnx:<repo>)
|
scripts/export_powsm_onnx.py
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Export a POWSM-CTC fine-tune to ONNX, so the Space can run it with onnxruntime alone (no ESPnet).
|
| 3 |
+
|
| 4 |
+
Usage: python scripts/export_powsm_onnx.py checkpoints/powsm-ft-shortpad/powsm_ft.pt exports/powsm-ft-shortpad
|
| 5 |
+
python scripts/export_powsm_onnx.py <checkpoint> <out> --check data/minerva/dev.csv # compare with ESPnet
|
| 6 |
+
|
| 7 |
+
Needs the export-time packages (scripts/setup_zero_shot_deps.sh). Writes to <out>:
|
| 8 |
+
model.onnx encoder + CTC head for one recording: feats (1, T, 80) and their length -> log-posteriors
|
| 9 |
+
(1, T', V) over POWSM's phone tokens only. The prompt is baked in: <ara>, <pr>, no previous
|
| 10 |
+
text, so its two positions are already dropped from T'.
|
| 11 |
+
model.int8.onnx the same with int8 weights (dynamic quantisation): ~4x smaller, faster on a CPU
|
| 12 |
+
frontend.npz what turns 16 kHz audio into feats, copied from the model: STFT window, mel matrix,
|
| 13 |
+
global mean and std (app/powsm.py PowsmOnnxEmitter applies them with torch.stft)
|
| 14 |
+
powsm_onnx.json vocab (phone -> column), blank, padding, frame rate and where it came from
|
| 15 |
+
Upload <out> to a Hub model repo and serve it with MODEL_ID=powsm-onnx:<repo> (or MODEL_ID=<out> locally).
|
| 16 |
+
"""
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
|
| 19 |
+
import argparse
|
| 20 |
+
import csv
|
| 21 |
+
import json
|
| 22 |
+
import sys
|
| 23 |
+
import time
|
| 24 |
+
from pathlib import Path
|
| 25 |
+
|
| 26 |
+
import numpy as np
|
| 27 |
+
|
| 28 |
+
ROOT = Path(__file__).resolve().parent.parent
|
| 29 |
+
sys.path.insert(0, str(ROOT))
|
| 30 |
+
|
| 31 |
+
from app.powsm import PROMPT, load_powsm, pad_seconds, use_extra_deps # noqa: E402
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def main() -> None:
|
| 35 |
+
ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
|
| 36 |
+
ap.add_argument("checkpoint", help="a train/finetune_powsm.py checkpoint (powsm_ft.pt)")
|
| 37 |
+
ap.add_argument("out", type=Path)
|
| 38 |
+
ap.add_argument("--lang", default="<ara>")
|
| 39 |
+
ap.add_argument("--check", type=Path, help="a CSV whose first clips are scored both ways and compared")
|
| 40 |
+
ap.add_argument("--check-n", type=int, default=20)
|
| 41 |
+
ap.add_argument("--no-int8", action="store_true", help="skip the int8 copy")
|
| 42 |
+
args = ap.parse_args()
|
| 43 |
+
use_extra_deps()
|
| 44 |
+
import torch
|
| 45 |
+
|
| 46 |
+
s2t = load_powsm(args.lang, args.checkpoint, device="cpu")
|
| 47 |
+
model = s2t.s2t_model.eval()
|
| 48 |
+
conv = s2t.converter
|
| 49 |
+
lang_id, task_id = conv.token2id[args.lang], conv.token2id["<pr>"]
|
| 50 |
+
|
| 51 |
+
# the phone columns, named as the app's scorer spells them (no slashes, no tie bars)
|
| 52 |
+
cols, names = [model.blank_id], {"<blank>": 0}
|
| 53 |
+
for i, t in enumerate(model.token_list):
|
| 54 |
+
if len(t) > 2 and t[0] == "/" and t[-1] == "/":
|
| 55 |
+
name = t[1:-1].replace("͡", "")
|
| 56 |
+
if name not in names:
|
| 57 |
+
names[name] = len(cols)
|
| 58 |
+
cols.append(i)
|
| 59 |
+
|
| 60 |
+
class EncoderCTC(torch.nn.Module):
|
| 61 |
+
"""POWSM's encoder and CTC head with the prompt fixed: (feats, lengths) -> log-posteriors over phones."""
|
| 62 |
+
|
| 63 |
+
def __init__(self):
|
| 64 |
+
super().__init__()
|
| 65 |
+
self.encoder, self.ctc = model.encoder, model.ctc
|
| 66 |
+
with torch.no_grad():
|
| 67 |
+
prefix = torch.tensor([[lang_id, task_id]])
|
| 68 |
+
prev = torch.tensor([[model.na]])
|
| 69 |
+
memory, mem_lens, _ = model.prompt_encoder(model.pos_enc(model.embed(prev)), torch.tensor([1]))
|
| 70 |
+
self.register_buffer("prefix", model.embed_proj(model.embed(prefix)))
|
| 71 |
+
self.register_buffer("memory", model.prompt_proj(memory))
|
| 72 |
+
self.register_buffer("memory_mask", torch.ones(1, 1, memory.shape[1], dtype=torch.bool))
|
| 73 |
+
self.register_buffer("cols", torch.tensor(cols))
|
| 74 |
+
|
| 75 |
+
def forward(self, feats, feats_lens):
|
| 76 |
+
enc, _, _ = self.encoder(feats, feats_lens, ctc=self.ctc, prefix_embeds=self.prefix,
|
| 77 |
+
memory=self.memory, memory_mask=self.memory_mask)
|
| 78 |
+
if isinstance(enc, tuple):
|
| 79 |
+
enc = enc[0]
|
| 80 |
+
logits = self.ctc.ctc_lo(enc[:, PROMPT:])
|
| 81 |
+
return torch.log_softmax(logits.index_select(-1, self.cols), dim=-1)
|
| 82 |
+
|
| 83 |
+
def features(wav: np.ndarray):
|
| 84 |
+
x = torch.from_numpy(wav.astype(np.float32))[None]
|
| 85 |
+
feats, lens = model.frontend(x, torch.tensor([x.shape[1]]))
|
| 86 |
+
return model.normalize(feats, lens)
|
| 87 |
+
|
| 88 |
+
net = EncoderCTC().eval()
|
| 89 |
+
args.out.mkdir(parents=True, exist_ok=True)
|
| 90 |
+
sample = (np.random.default_rng(0).standard_normal(16000 * 3) * 0.05).astype(np.float32)
|
| 91 |
+
feats, lens = features(sample)
|
| 92 |
+
onnx_path = args.out / "model.onnx"
|
| 93 |
+
print("exporting", onnx_path, flush=True)
|
| 94 |
+
with torch.no_grad():
|
| 95 |
+
torch.onnx.export(net, (feats, lens), str(onnx_path), input_names=["feats", "feats_lens"],
|
| 96 |
+
output_names=["logp"], dynamic_axes={"feats": {1: "T"}, "logp": {1: "frames"}},
|
| 97 |
+
opset_version=17, dynamo=False)
|
| 98 |
+
if not args.no_int8:
|
| 99 |
+
from onnxruntime.quantization import QuantType, quantize_dynamic
|
| 100 |
+
print("quantising to int8", flush=True)
|
| 101 |
+
# only the matrix products: onnxruntime's CPU kernels have no int8 convolution (ConvInteger)
|
| 102 |
+
quantize_dynamic(str(onnx_path), str(args.out / "model.int8.onnx"), weight_type=QuantType.QInt8,
|
| 103 |
+
op_types_to_quantize=["MatMul", "Gemm"])
|
| 104 |
+
|
| 105 |
+
fe = model.frontend
|
| 106 |
+
stft = fe.stft
|
| 107 |
+
window = torch.hann_window(stft.win_length).numpy()
|
| 108 |
+
np.savez(args.out / "frontend.npz", window=window, melmat=fe.logmel.melmat.numpy(),
|
| 109 |
+
mean=model.normalize.mean.numpy(), std=model.normalize.std.numpy(),
|
| 110 |
+
n_fft=stft.n_fft, win_length=stft.win_length, hop_length=stft.hop_length)
|
| 111 |
+
assert stft.center and stft.window == "hann" and fe.logmel.log_base is None
|
| 112 |
+
meta = {"kind": "powsm-ctc-onnx", "lang": args.lang, "blank": 0, "vocab": names,
|
| 113 |
+
"pad_seconds": pad_seconds(args.checkpoint), "frames_per_second": 25, "prompt_positions": PROMPT,
|
| 114 |
+
"source": {"base": "espnet/powsm_ctc", "checkpoint": str(args.checkpoint)},
|
| 115 |
+
"files": {"fp32": "model.onnx", "int8": None if args.no_int8 else "model.int8.onnx"}}
|
| 116 |
+
(args.out / "powsm_onnx.json").write_text(json.dumps(meta, ensure_ascii=False, indent=1), encoding="utf-8")
|
| 117 |
+
print("wrote", sorted(p.name for p in args.out.iterdir()), flush=True)
|
| 118 |
+
|
| 119 |
+
if args.check:
|
| 120 |
+
check(args, net, features)
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def check(args, net, features) -> None:
|
| 124 |
+
"""ESPnet's own model vs the app's ONNX emitter (fp32 and int8) on real clips: same frames, same argmax?"""
|
| 125 |
+
import torch
|
| 126 |
+
|
| 127 |
+
from app.powsm import PowsmOnnxEmitter
|
| 128 |
+
from app.scorer import decode_audio
|
| 129 |
+
rows = list(csv.DictReader(open(args.check, encoding="utf-8")))[: args.check_n]
|
| 130 |
+
clips = [decode_audio((args.check.parent / r["audio"]).read_bytes()) for r in rows]
|
| 131 |
+
for kind in ("fp32", "int8"):
|
| 132 |
+
if kind == "int8" and args.no_int8:
|
| 133 |
+
continue
|
| 134 |
+
em = PowsmOnnxEmitter(str(args.out), precision=kind)
|
| 135 |
+
diffs, agree, total, t = [], 0, 0, 0.0
|
| 136 |
+
for wav in clips:
|
| 137 |
+
x = np.pad(wav, (0, max(0, int(em.pad * 16000) - len(wav)))).astype(np.float32)
|
| 138 |
+
with torch.no_grad():
|
| 139 |
+
f, ln = features(x)
|
| 140 |
+
ref = net(f, ln)[0].numpy()
|
| 141 |
+
keep = max(1, round(ref.shape[0] * len(wav) / len(x)))
|
| 142 |
+
ref = ref[:keep]
|
| 143 |
+
t0 = time.perf_counter()
|
| 144 |
+
got = em(wav)[::2] # the emitter repeats each frame for the scorer's 50 frames/s
|
| 145 |
+
t += time.perf_counter() - t0
|
| 146 |
+
n = min(len(ref), len(got))
|
| 147 |
+
diffs.append(float(np.abs(np.exp(ref[:n]) - np.exp(got[:n])).max()))
|
| 148 |
+
agree += int((ref[:n].argmax(-1) == got[:n].argmax(-1)).sum())
|
| 149 |
+
total += n
|
| 150 |
+
print(f"{kind}: frames whose best phone matches ESPnet {100 * agree / total:.2f}% · "
|
| 151 |
+
f"largest posterior difference {max(diffs):.4f} · {t / len(clips):.2f} s/clip", flush=True)
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
if __name__ == "__main__":
|
| 155 |
+
main()
|
scripts/setup_zero_shot_deps.sh
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
# Install the extra packages for scripts/zero_shot_phone_models.py into .zero-shot-deps/ (git-ignored),
|
| 3 |
+
# outside the app venv. The script adds that folder to its own import path; nothing else sees it.
|
| 4 |
+
set -euo pipefail
|
| 5 |
+
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
|
| 6 |
+
PY="${PYTHON:-$ROOT/.venv/bin/python}"
|
| 7 |
+
DEST="$ROOT/.zero-shot-deps"
|
| 8 |
+
|
| 9 |
+
rm -rf "$DEST"
|
| 10 |
+
"$PY" -m pip install --quiet --no-deps --target "$DEST/pkgs" -r "$ROOT/requirements-zero-shot.txt"
|
| 11 |
+
|
| 12 |
+
# ESPnet imports torchaudio for multi-microphone beamforming, which POWSM never runs, and there is no
|
| 13 |
+
# torchaudio build for torch 2.14. A placeholder lets the import succeed and fails loudly if anything uses it.
|
| 14 |
+
mkdir -p "$DEST/stubs/torchaudio"
|
| 15 |
+
cat > "$DEST/stubs/torchaudio/__init__.py" <<'EOF'
|
| 16 |
+
"""Placeholder: ESPnet imports torchaudio for beamforming code that POWSM never runs."""
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def __getattr__(name):
|
| 20 |
+
raise ImportError(f"torchaudio placeholder: '{name}' is not available (no torchaudio build for this torch)")
|
| 21 |
+
EOF
|
| 22 |
+
echo "installed into $DEST"
|
scripts/zero_shot_phone_models.py
ADDED
|
@@ -0,0 +1,388 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""How well do other phone recognizers hear Palestinian Arabic as-is? Zero-shot, on held-out Minerva lines.
|
| 3 |
+
|
| 4 |
+
Usage: python scripts/zero_shot_phone_models.py # every model, dev.csv
|
| 5 |
+
python scripts/zero_shot_phone_models.py --models zipa,ft --split test
|
| 6 |
+
python scripts/zero_shot_phone_models.py --report # print the table from the saved JSON
|
| 7 |
+
|
| 8 |
+
ZIPA and POWSM need extra packages: run scripts/setup_zero_shot_deps.sh once (it installs into .zero-shot-deps/,
|
| 9 |
+
outside the app venv). Results go to data/minerva/bench/zero-shot-<split>.json, merged with earlier runs, so models
|
| 10 |
+
can be run one at a time.
|
| 11 |
+
|
| 12 |
+
Each model's greedy CTC output is mapped onto the labels' phoneme set before scoring (canon()): length marks join
|
| 13 |
+
their vowel, details the labels never write (dental t̪, aspiration) are dropped, symbols with no contrast in
|
| 14 |
+
Palestinian are merged (χ→x, ʁ→ɣ, ɾ→r), and vowel qualities fold to a e i o u (ɛ→e, ɪ→i, ə→e). Geminates collapse
|
| 15 |
+
to one sound in both, as the scorer's tokenize() does. Measured:
|
| 16 |
+
PER phoneme error rate (edit distance / reference length)
|
| 17 |
+
consonant PER the same with every vowel removed from both sides: the sounds the scorer grades hardest
|
| 18 |
+
per sound how often each labelled sound was heard as itself, and what was heard instead
|
| 19 |
+
vowel length of the labelled vowels the model heard as some vowel, how often it got long/short right
|
| 20 |
+
frames/s CTC frame rate: the long-vowel check measures vowel length in frames
|
| 21 |
+
s/clip wall time per clip on this machine
|
| 22 |
+
The fine-tuned checkpoint picked its best epoch on dev.csv, so its dev numbers are slightly optimistic; use
|
| 23 |
+
--split test for reported numbers.
|
| 24 |
+
"""
|
| 25 |
+
from __future__ import annotations
|
| 26 |
+
|
| 27 |
+
import argparse
|
| 28 |
+
import collections
|
| 29 |
+
import csv
|
| 30 |
+
import json
|
| 31 |
+
import sys
|
| 32 |
+
import time
|
| 33 |
+
import unicodedata
|
| 34 |
+
from pathlib import Path
|
| 35 |
+
|
| 36 |
+
import numpy as np
|
| 37 |
+
|
| 38 |
+
ROOT = Path(__file__).resolve().parent.parent
|
| 39 |
+
sys.path.insert(0, str(ROOT))
|
| 40 |
+
|
| 41 |
+
from app.align import greedy_decode # noqa: E402
|
| 42 |
+
from app.scorer import SAMPLE_RATE, decode_audio # noqa: E402
|
| 43 |
+
|
| 44 |
+
DATA = ROOT / "data" / "minerva"
|
| 45 |
+
# the sounds the table shows (the JSON has every sound)
|
| 46 |
+
KEY_SOUNDS = ["ħ", "ʕ", "x", "ɣ", "h", "ʔ", "tˤ", "sˤ", "dˤ"]
|
| 47 |
+
VOWELS = set("aeiou")
|
| 48 |
+
|
| 49 |
+
# ---------- mapping a model's IPA onto the labels' phoneme set ----------
|
| 50 |
+
|
| 51 |
+
DROP = set("̪̺̻̥̬̃̚ʰʲʷ̩̯̆̈ʼ̟̠̝̞̹̜˞ˑ̤̰") # details the labels never write
|
| 52 |
+
SAME = { # no contrast in Palestinian (or a spelling of the same symbol)
|
| 53 |
+
"ɡ": "g", "ʤ": "dʒ", "ʧ": "tʃ", "χ": "x", "ʁ": "ɣ", "ɾ": "r", "ɹ": "r", "ʀ": "r", "ɫ": "l",
|
| 54 |
+
"ʜ": "ħ", "ʢ": "ʕ", "ɦ": "h",
|
| 55 |
+
}
|
| 56 |
+
FOLD = { # vowel quality -> the five the labels use
|
| 57 |
+
"ɑ": "a", "æ": "a", "ɐ": "a", "ʌ": "a", "ä": "a", "ɒ": "a",
|
| 58 |
+
"ɛ": "e", "ə": "e", "œ": "e", "ɘ": "e", "ɜ": "e",
|
| 59 |
+
"ɪ": "i", "ɨ": "i", "y": "i", "ʏ": "i",
|
| 60 |
+
"ɔ": "o", "ɵ": "o", "ø": "o",
|
| 61 |
+
"ʊ": "u", "ɯ": "u", "ʉ": "u",
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def is_modifier(ch: str) -> bool:
|
| 66 |
+
return unicodedata.category(ch) in ("Mn", "Lm", "Sk") and ch not in "ʔʕ"
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def canon(phone: str) -> str:
|
| 70 |
+
"""One phone (as a model writes it) -> the labels' notation, '' if nothing is left."""
|
| 71 |
+
p = "".join(ch for ch in phone.replace("͡", "").replace("‿", "") if ch not in DROP)
|
| 72 |
+
p = p.replace("ˠ", "ˤ").replace("̴", "ˤ") # velarized ~ pharyngealized: both are how emphatics get written
|
| 73 |
+
long = "ː" in p
|
| 74 |
+
p = p.replace("ː", "")
|
| 75 |
+
p = SAME.get(p, p)
|
| 76 |
+
p = "".join(FOLD.get(ch, ch) for ch in p) if p and all(FOLD.get(ch, ch) in VOWELS for ch in p) else p
|
| 77 |
+
if len(p) > 1 and all(ch in VOWELS for ch in p): # a diphthong or a doubled vowel
|
| 78 |
+
p = p[0]
|
| 79 |
+
if not p:
|
| 80 |
+
return ""
|
| 81 |
+
return p + "ː" if long and p in VOWELS else p # a long consonant is a geminate: collapsed below anyway
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
AFFRICATES = {("d", "ʒ"): "dʒ", ("t", "ʃ"): "tʃ"}
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def to_phones(tokens: list[str]) -> list[str]:
|
| 88 |
+
"""Model tokens (whole phones, or single characters as ZIPA writes them) -> canonical phones,
|
| 89 |
+
geminates collapsed."""
|
| 90 |
+
phones: list[str] = []
|
| 91 |
+
for tok in tokens:
|
| 92 |
+
tok = tok.strip()
|
| 93 |
+
if not tok or tok in ("|", "▁") or (tok.startswith("<") and tok.endswith(">")):
|
| 94 |
+
continue
|
| 95 |
+
if phones and all(is_modifier(ch) for ch in tok): # ː or ˤ written as its own token
|
| 96 |
+
phones[-1] += tok
|
| 97 |
+
elif phones and phones[-1].endswith("͡"): # tie bar: t͡ ʃ
|
| 98 |
+
phones[-1] += tok
|
| 99 |
+
else:
|
| 100 |
+
phones.append(tok)
|
| 101 |
+
out: list[str] = []
|
| 102 |
+
for p in phones:
|
| 103 |
+
c = canon(p)
|
| 104 |
+
if not c:
|
| 105 |
+
continue
|
| 106 |
+
if out and (out[-1], c) in AFFRICATES:
|
| 107 |
+
out[-1] = AFFRICATES[(out[-1], c)]
|
| 108 |
+
elif not out or out[-1] != c:
|
| 109 |
+
out.append(c)
|
| 110 |
+
return out
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def reference(ipa: str) -> list[str]:
|
| 114 |
+
return to_phones([t for t in ipa.split() if t != "|"])
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def align(ref: list[str], hyp: list[str]) -> tuple[int, list[tuple[str | None, str | None]]]:
|
| 118 |
+
"""Levenshtein distance and the aligned pairs (ref, hyp); None marks an insertion or a deletion."""
|
| 119 |
+
n, m = len(ref), len(hyp)
|
| 120 |
+
d = np.zeros((n + 1, m + 1), dtype=np.int32)
|
| 121 |
+
d[:, 0] = np.arange(n + 1)
|
| 122 |
+
d[0, :] = np.arange(m + 1)
|
| 123 |
+
for i in range(1, n + 1):
|
| 124 |
+
for j in range(1, m + 1):
|
| 125 |
+
d[i, j] = min(d[i - 1, j - 1] + (ref[i - 1] != hyp[j - 1]), d[i - 1, j] + 1, d[i, j - 1] + 1)
|
| 126 |
+
pairs: list[tuple[str | None, str | None]] = []
|
| 127 |
+
i, j = n, m
|
| 128 |
+
while i or j:
|
| 129 |
+
if i and j and d[i, j] == d[i - 1, j - 1] + (ref[i - 1] != hyp[j - 1]):
|
| 130 |
+
pairs.append((ref[i - 1], hyp[j - 1]))
|
| 131 |
+
i, j = i - 1, j - 1
|
| 132 |
+
elif i and d[i, j] == d[i - 1, j] + 1:
|
| 133 |
+
pairs.append((ref[i - 1], None))
|
| 134 |
+
i -= 1
|
| 135 |
+
else:
|
| 136 |
+
pairs.append((None, hyp[j - 1]))
|
| 137 |
+
j -= 1
|
| 138 |
+
return int(d[n, m]), pairs[::-1]
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def consonants(phones: list[str]) -> list[str]:
|
| 142 |
+
return [p for p in phones if p.rstrip("ː") not in VOWELS]
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
# ---------- models ----------
|
| 146 |
+
|
| 147 |
+
def use_extra_deps() -> None:
|
| 148 |
+
from app.powsm import use_extra_deps as use
|
| 149 |
+
try:
|
| 150 |
+
use()
|
| 151 |
+
except RuntimeError as e:
|
| 152 |
+
sys.exit(str(e))
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
class HFModel:
|
| 156 |
+
"""The app's own emitter (wav2vec2 phoneme CTC)."""
|
| 157 |
+
|
| 158 |
+
def __init__(self, model_id: str):
|
| 159 |
+
from app.scorer import HFEmitter
|
| 160 |
+
self.em = HFEmitter(model_id)
|
| 161 |
+
self.i2t = {i: t for t, i in self.em.token_to_id.items()}
|
| 162 |
+
self.blank = self.em.token_to_id["<pad>"]
|
| 163 |
+
self.inventory = {canon(t) for t in self.em.token_to_id if not t.startswith("<")}
|
| 164 |
+
|
| 165 |
+
def __call__(self, wav: np.ndarray) -> tuple[list[str], int]:
|
| 166 |
+
logp = self.em(wav)
|
| 167 |
+
return [self.i2t[i] for i in greedy_decode(logp, self.blank)], logp.shape[0]
|
| 168 |
+
|
| 169 |
+
def close(self) -> None:
|
| 170 |
+
del self.em
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
class Zipa:
|
| 174 |
+
"""ZIPA (Zipformer, CR-CTC) from its official ONNX export, on CPU: onnxruntime's GPU build needs CUDA 12."""
|
| 175 |
+
|
| 176 |
+
def __init__(self, repo: str = "anyspeech/zipa-large-crctc-500k"):
|
| 177 |
+
use_extra_deps()
|
| 178 |
+
import onnxruntime as ort
|
| 179 |
+
from huggingface_hub import hf_hub_download
|
| 180 |
+
from lhotse.features.kaldi.extractors import Fbank, FbankConfig
|
| 181 |
+
self.sess = ort.InferenceSession(hf_hub_download(repo, "model.onnx"), providers=["CPUExecutionProvider"])
|
| 182 |
+
self.fbank = Fbank(FbankConfig(num_filters=80, dither=0.0, snip_edges=False)) # as ZIPA's inference/utils.py
|
| 183 |
+
self.tokens: dict[int, str] = {}
|
| 184 |
+
for line in open(hf_hub_download(repo, "tokens.txt"), encoding="utf-8"):
|
| 185 |
+
tok, idx = line.rstrip("\n").rsplit(" ", 1)
|
| 186 |
+
self.tokens[int(idx)] = tok
|
| 187 |
+
self.inventory = None # it writes phones letter by letter, so any combination is possible
|
| 188 |
+
|
| 189 |
+
def __call__(self, wav: np.ndarray) -> tuple[list[str], int]:
|
| 190 |
+
import torch
|
| 191 |
+
feats = self.fbank.extract_batch([torch.from_numpy(wav.copy())], sampling_rate=SAMPLE_RATE)[0]
|
| 192 |
+
feats = feats.unsqueeze(0).numpy()
|
| 193 |
+
logp, lens = self.sess.run(None, {"x": feats, "x_lens": np.array([feats.shape[1]], dtype=np.int64)})
|
| 194 |
+
logp = logp[0][: int(lens[0])]
|
| 195 |
+
return [self.tokens[i] for i in greedy_decode(logp, 0)], logp.shape[0]
|
| 196 |
+
|
| 197 |
+
def close(self) -> None:
|
| 198 |
+
del self.sess
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
class Powsm:
|
| 202 |
+
"""POWSM-CTC (ESPnet), greedy CTC with the phone-recognition task token and a language token."""
|
| 203 |
+
|
| 204 |
+
SECONDS = 20 # trained on 20 s inputs: the model card says pad to 20 s (None or 0: no padding)
|
| 205 |
+
|
| 206 |
+
def __init__(self, lang: str = "<unk>", checkpoint: str | None = None, pad: float | None = None):
|
| 207 |
+
use_extra_deps()
|
| 208 |
+
self.pad = self.SECONDS if pad is None else pad
|
| 209 |
+
from app.powsm import load_powsm
|
| 210 |
+
self.s2t = load_powsm(lang, checkpoint)
|
| 211 |
+
self.enc_frames = 0
|
| 212 |
+
self.s2t.s2t_model.encoder.register_forward_hook(self._count)
|
| 213 |
+
toks = self.s2t.s2t_model.token_list
|
| 214 |
+
self.inventory = {canon(t[1:-1]) for t in toks if len(t) > 2 and t[0] == "/" and t[-1] == "/"}
|
| 215 |
+
|
| 216 |
+
def _count(self, module, inputs, output):
|
| 217 |
+
enc = output[0][0] if isinstance(output[0], tuple) else output[0]
|
| 218 |
+
self.enc_frames = enc.shape[1] - 2 # minus the language and task positions
|
| 219 |
+
|
| 220 |
+
def __call__(self, wav: np.ndarray) -> tuple[list[str], int]:
|
| 221 |
+
n = int((self.pad or 0) * SAMPLE_RATE)
|
| 222 |
+
x = np.pad(wav, (0, max(0, n - len(wav)))).astype(np.float32) # a longer recording runs as it is
|
| 223 |
+
tokens = self.s2t(x)[0][1]
|
| 224 |
+
phones = [t[1:-1] for t in tokens if len(t) > 2 and t[0] == "/" and t[-1] == "/"]
|
| 225 |
+
return phones, round(self.enc_frames * len(wav) / len(x)) # frames that cover the speech
|
| 226 |
+
|
| 227 |
+
def close(self) -> None:
|
| 228 |
+
del self.s2t
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
MODELS = { # name -> (label, how it would plug into the app, loader)
|
| 232 |
+
"base": ("xlsr-53-espeak (current base)", "yes", lambda: HFModel("facebook/wav2vec2-xlsr-53-espeak-cv-ft")),
|
| 233 |
+
"ft": ("ihki-ft-minerva (current fine-tune)", "yes",
|
| 234 |
+
lambda: HFModel(str(ROOT / "checkpoints" / "ihki-ft-minerva"))),
|
| 235 |
+
"zipa": ("ZIPA large CR-CTC", "new loader (ONNX)", lambda: Zipa()),
|
| 236 |
+
"powsm": ("POWSM-CTC, no language", "new loader (ESPnet)", lambda: Powsm("<unk>", None, POWSM_PAD)),
|
| 237 |
+
"powsm-ara": ("POWSM-CTC, Arabic prompt", "new loader (ESPnet)", lambda: Powsm("<ara>", None, POWSM_PAD)),
|
| 238 |
+
"powsm-ft": ("POWSM-CTC fine-tuned (Arabic prompt)", "new loader (ESPnet)",
|
| 239 |
+
lambda: Powsm("<ara>", str(ROOT / "checkpoints" / "powsm-ft-minerva" / "powsm_ft.pt"), POWSM_PAD)),
|
| 240 |
+
"powsm-ft-short": ("POWSM-CTC fine-tuned on short padding", "new loader (ESPnet)",
|
| 241 |
+
lambda: Powsm("<ara>", str(ROOT / "checkpoints" / "powsm-ft-shortpad" / "powsm_ft.pt"),
|
| 242 |
+
POWSM_PAD)),
|
| 243 |
+
}
|
| 244 |
+
POWSM_PAD: float | None = None # --powsm-pad: seconds the POWSM models pad to (None: their 20 s)
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
# ---------- running and reporting ----------
|
| 248 |
+
|
| 249 |
+
def evaluate(name: str, rows: list[dict], clips: list[np.ndarray]) -> dict:
|
| 250 |
+
label, fits, load = MODELS[name]
|
| 251 |
+
print(f"[{name}] loading {label}", file=sys.stderr)
|
| 252 |
+
model = load()
|
| 253 |
+
model(clips[0]) # warm-up, not timed
|
| 254 |
+
errs = c_errs = total = c_total = 0
|
| 255 |
+
frames = seconds = elapsed = 0.0
|
| 256 |
+
n = collections.Counter()
|
| 257 |
+
heard: dict[str, collections.Counter] = collections.defaultdict(collections.Counter)
|
| 258 |
+
length_ok = length_n = 0
|
| 259 |
+
lines = []
|
| 260 |
+
for k, (row, wav) in enumerate(zip(rows, clips)):
|
| 261 |
+
t = time.perf_counter()
|
| 262 |
+
tokens, n_frames = model(wav)
|
| 263 |
+
elapsed += time.perf_counter() - t
|
| 264 |
+
frames += n_frames
|
| 265 |
+
seconds += len(wav) / SAMPLE_RATE
|
| 266 |
+
ref, hyp = reference(row["ipa"]), to_phones(tokens)
|
| 267 |
+
e, pairs = align(ref, hyp)
|
| 268 |
+
errs, total = errs + e, total + len(ref)
|
| 269 |
+
ce, _ = align(consonants(ref), consonants(hyp))
|
| 270 |
+
c_errs, c_total = c_errs + ce, c_total + len(consonants(ref))
|
| 271 |
+
for r, h in pairs:
|
| 272 |
+
if r is None:
|
| 273 |
+
continue
|
| 274 |
+
n[r] += 1
|
| 275 |
+
heard[r][h if h is not None else "∅"] += 1
|
| 276 |
+
if h is not None and r.rstrip("ː") in VOWELS and h.rstrip("ː") in VOWELS:
|
| 277 |
+
length_n += 1
|
| 278 |
+
length_ok += r.endswith("ː") == h.endswith("ː")
|
| 279 |
+
lines.append({"item": row["item"], "ref": " ".join(ref), "hyp": " ".join(hyp), "errors": e})
|
| 280 |
+
if (k + 1) % 50 == 0:
|
| 281 |
+
print(f"[{name}] {k + 1}/{len(rows)} PER so far {errs / total:.3f}", file=sys.stderr)
|
| 282 |
+
inventory = getattr(model, "inventory", None)
|
| 283 |
+
model.close()
|
| 284 |
+
try:
|
| 285 |
+
import torch
|
| 286 |
+
torch.cuda.empty_cache()
|
| 287 |
+
except ImportError:
|
| 288 |
+
pass
|
| 289 |
+
sounds = {}
|
| 290 |
+
for s in sorted(n, key=lambda s: -n[s]):
|
| 291 |
+
sounds[s] = {"n": n[s], "recall": heard[s][s] / n[s],
|
| 292 |
+
"heard_as": dict(heard[s].most_common(6)),
|
| 293 |
+
"in_vocab": None if inventory is None else s in inventory}
|
| 294 |
+
return {"label": label, "fits_app": fits, "clips": len(rows), "per": errs / total,
|
| 295 |
+
"consonant_per": c_errs / c_total, "vowel_length_accuracy": length_ok / max(1, length_n),
|
| 296 |
+
"frames_per_second": frames / seconds, "seconds_per_clip": elapsed / len(rows),
|
| 297 |
+
"sounds": sounds, "lines": lines}
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
def ordered(results: dict) -> list[str]:
|
| 301 |
+
"""Saved runs in MODELS order, runs with another padding (powsm-ft@8s) after their model."""
|
| 302 |
+
out = []
|
| 303 |
+
for m in MODELS:
|
| 304 |
+
out += [k for k in results if k == m or k.startswith(m + "@")]
|
| 305 |
+
return out + [k for k in results if k not in out]
|
| 306 |
+
|
| 307 |
+
|
| 308 |
+
def pct(x: float | None) -> str:
|
| 309 |
+
return "—" if x is None else f"{100 * x:.0f}%"
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
def table(results: dict) -> str:
|
| 313 |
+
head = ["Model", "PER", "Consonant PER", *KEY_SOUNDS, "Long vowels", "Vowel length", "Frames/s", "s/clip",
|
| 314 |
+
"Fits app?"]
|
| 315 |
+
out = ["| " + " | ".join(head) + " |", "|" + "---|" * len(head)]
|
| 316 |
+
for name in ordered(results):
|
| 317 |
+
r = results[name]
|
| 318 |
+
cells = [r["label"], pct(r["per"]), pct(r["consonant_per"])]
|
| 319 |
+
for s in KEY_SOUNDS:
|
| 320 |
+
info = r["sounds"].get(s)
|
| 321 |
+
if info is None:
|
| 322 |
+
cells.append("—")
|
| 323 |
+
elif info["in_vocab"] is False:
|
| 324 |
+
cells.append("no symbol")
|
| 325 |
+
else:
|
| 326 |
+
cells.append(pct(info["recall"]))
|
| 327 |
+
longs = [v for s, v in r["sounds"].items() if s.endswith("ː")]
|
| 328 |
+
hit = sum(v["recall"] * v["n"] for v in longs)
|
| 329 |
+
cells += [pct(hit / max(1, sum(v["n"] for v in longs))), pct(r["vowel_length_accuracy"]),
|
| 330 |
+
f"{r['frames_per_second']:.0f}", f"{r['seconds_per_clip']:.2f}", r["fits_app"]]
|
| 331 |
+
out.append("| " + " | ".join(cells) + " |")
|
| 332 |
+
return "\n".join(out)
|
| 333 |
+
|
| 334 |
+
|
| 335 |
+
def confusions(results: dict, sounds: list[str]) -> str:
|
| 336 |
+
out = []
|
| 337 |
+
for name in ordered(results):
|
| 338 |
+
r = results[name]
|
| 339 |
+
parts = []
|
| 340 |
+
for s in sounds:
|
| 341 |
+
info = r["sounds"].get(s)
|
| 342 |
+
if not info:
|
| 343 |
+
continue
|
| 344 |
+
wrong = [f"{h} {c}" for h, c in info["heard_as"].items() if h != s][:3]
|
| 345 |
+
parts.append(f"{s} ({info['n']}): " + (", ".join(wrong) or "—"))
|
| 346 |
+
out.append(f"- **{r['label']}**: " + "; ".join(parts))
|
| 347 |
+
return "\n".join(out)
|
| 348 |
+
|
| 349 |
+
|
| 350 |
+
def main() -> None:
|
| 351 |
+
ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
|
| 352 |
+
local = {"powsm-ft": "powsm-ft-minerva", "powsm-ft-short": "powsm-ft-shortpad"}
|
| 353 |
+
default = [m for m in MODELS if m not in local or (ROOT / "checkpoints" / local[m] / "powsm_ft.pt").exists()]
|
| 354 |
+
ap.add_argument("--models", default=",".join(default), help=f"comma-separated, from: {', '.join(MODELS)}")
|
| 355 |
+
ap.add_argument("--split", default="dev", choices=["dev", "test"])
|
| 356 |
+
ap.add_argument("--limit", type=int, help="only the first N clips (a quick check)")
|
| 357 |
+
ap.add_argument("--report", action="store_true", help="print the table from the saved JSON, run nothing")
|
| 358 |
+
ap.add_argument("--powsm-pad", type=float, help="seconds the POWSM models pad to (default 20; 0: none). "
|
| 359 |
+
"A run with it is saved under the model's name plus @<seconds>")
|
| 360 |
+
args = ap.parse_args()
|
| 361 |
+
global POWSM_PAD
|
| 362 |
+
POWSM_PAD = args.powsm_pad
|
| 363 |
+
|
| 364 |
+
out_path = DATA / "bench" / f"zero-shot-{args.split}.json"
|
| 365 |
+
results = json.loads(out_path.read_text(encoding="utf-8")) if out_path.exists() else {}
|
| 366 |
+
if not args.report:
|
| 367 |
+
names = [m.strip() for m in args.models.split(",") if m.strip()]
|
| 368 |
+
unknown = [m for m in names if m not in MODELS]
|
| 369 |
+
if unknown:
|
| 370 |
+
sys.exit(f"unknown model(s): {', '.join(unknown)}")
|
| 371 |
+
with open(DATA / f"{args.split}.csv", encoding="utf-8") as f:
|
| 372 |
+
rows = list(csv.DictReader(f))[: args.limit]
|
| 373 |
+
clips = [decode_audio((DATA / r["audio"]).read_bytes()) for r in rows]
|
| 374 |
+
for name in names:
|
| 375 |
+
key = f"{name}@{args.powsm_pad:g}s" if args.powsm_pad is not None and name.startswith("powsm") else name
|
| 376 |
+
results[key] = evaluate(name, rows, clips)
|
| 377 |
+
results[key]["label"] += f" (pad {args.powsm_pad:g} s)" if key != name else ""
|
| 378 |
+
if not args.limit: # a partial run doesn't overwrite the saved numbers
|
| 379 |
+
out_path.parent.mkdir(parents=True, exist_ok=True)
|
| 380 |
+
out_path.write_text(json.dumps(results, ensure_ascii=False, indent=1), encoding="utf-8")
|
| 381 |
+
print(table(results))
|
| 382 |
+
print()
|
| 383 |
+
print("What each key sound was heard as instead (count):")
|
| 384 |
+
print(confusions(results, ["ħ", "ʕ", "tˤ", "sˤ", "aː", "iː"]))
|
| 385 |
+
|
| 386 |
+
|
| 387 |
+
if __name__ == "__main__":
|
| 388 |
+
main()
|
static/index.html
CHANGED
|
@@ -700,6 +700,7 @@ body.driving .mic::before{display:none} body.driving .mic-zone.two{display:flex}
|
|
| 700 |
/* The teacher's panel (its parts are styled further down: the class tabs, the figures, the lessons, the students). */
|
| 701 |
body:not(.manage) #manage,body.lab #manage,body:not(.lab) #lab,body.manage #wrap>header,body.manage #path,body.manage #today,body.manage #toNow,body.manage #practice,body:not(.home) #toManage{display:none}
|
| 702 |
body.lab #wrap,body.manage #wrap:has(#manage.access){max-width:none}
|
|
|
|
| 703 |
body.manage #manage{width:100%;max-width:none}
|
| 704 |
.mtitle{font:400 24px/1 var(--f-display);margin:0}
|
| 705 |
#mState.setup{padding:10px 12px;border:1px solid var(--sumac);border-radius:10px;color:var(--ink)}
|
|
@@ -789,8 +790,8 @@ body.manage #manage{width:100%;max-width:none}
|
|
| 789 |
.minerva-excluded{opacity:.65;text-decoration:line-through}
|
| 790 |
.lab-actions{display:flex;flex-wrap:wrap;align-items:center;gap:8px}
|
| 791 |
#labModes{grid-template-columns:repeat(5,1fr)}
|
| 792 |
-
#lab:not(.test) #labTest,#lab:not(.record) #labRecord,#lab:not(.flags) #labFlags,#lab:not(.minerva) #labMinerva,#lab:not(.results) #labResults{display:none}
|
| 793 |
-
#labTest,#labRecord,#labFlags,#labMinerva,#labResults{display:flex;flex-direction:column;gap:12px;min-width:0}
|
| 794 |
#labList,#labFlagList,#wzList{display:flex;flex-direction:column;gap:10px}
|
| 795 |
.wz-bar{flex-basis:100%;height:6px;border-radius:3px;background:var(--line);overflow:hidden}
|
| 796 |
.wz-bar i{display:block;height:100%;width:0;background:var(--ok);transition:width .3s}
|
|
@@ -926,8 +927,125 @@ body.manage #manage{width:100%;max-width:none}
|
|
| 926 |
#manage.content :is(#mTabs,#mHead,#mLessons,#mRoster,#mStudent),#manage:not(.content) #mContent{display:none}
|
| 927 |
#manage.flags :is(#mClasses,#mContent,#mTabs,#mHead,#mLessons,#mRoster,#mStudent),#manage:not(.flags) #mFlags{display:none}
|
| 928 |
#manage.access :is(#mClasses,#mContent,#mFlags,#mTabs,#mHead,#mLessons,#mRoster,#mStudent),#manage:not(.access) #mAccess{display:none}
|
|
|
|
| 929 |
.access-actions{display:flex;justify-content:flex-end;margin:8px 0}.access-scroll{overflow:auto}.access-table{width:100%;border-collapse:collapse;min-width:1180px}.access-table :is(th,td){padding:9px 10px;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 th>span{display:block;margin-bottom:4px}.access-table .access-all{display:inline-flex;align-items:center;gap:4px;color:var(--muted);font-weight:600;cursor:pointer}.access-table .access-all small{font-size:11px}.access-table :is(th,td):first-child{text-align:start;position:sticky;right:0;background:var(--surface);z-index:2;min-width:260px}.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:96px}
|
| 930 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 931 |
.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}
|
| 932 |
.flag-review.flag-urgent{border-inline-start:4px solid var(--sumac)}.flag-review.flag-lower{border-inline-start:4px solid var(--line)}
|
| 933 |
.flag-priority{display:inline-block;margin-inline-start:6px;padding:2px 7px;border-radius:999px;font-size:12px;font-weight:700}.flag-priority.urgent{background:var(--sumac-bg);color:var(--sumac)}.flag-priority.lower{background:var(--bg);color:var(--muted)}
|
|
@@ -1639,11 +1757,12 @@ html.a11y-reduce-motion *,html.a11y-reduce-motion *::before,html.a11y-reduce-mot
|
|
| 1639 |
<section class="wrap" id="manage" aria-labelledby="mTitle">
|
| 1640 |
<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>
|
| 1641 |
<div class="sub" id="mState" aria-live="polite"></div>
|
| 1642 |
-
<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>
|
| 1643 |
<div id="mClasses"></div>
|
| 1644 |
<div id="mContent"></div>
|
| 1645 |
<div id="mFlags"></div>
|
| 1646 |
<div class="card" id="mAccess"></div>
|
|
|
|
| 1647 |
<div class="tabs" id="mTabs" role="tablist" aria-label="סינון תלמידים לפי כיתה" hidden></div>
|
| 1648 |
<div class="card" id="mHead" hidden></div>
|
| 1649 |
<div class="card hard" id="mLessons" hidden></div>
|
|
@@ -1655,7 +1774,21 @@ html.a11y-reduce-motion *,html.a11y-reduce-motion *::before,html.a11y-reduce-mot
|
|
| 1655 |
<div class="roundbar"><h1 class="mtitle" id="labTitle">מעבדה</h1><span class="sep"></span><button class="btn" id="labManage">ניהול</button><button class="btn primary" id="labPractice">לתרגול</button></div>
|
| 1656 |
<p class="sub">רשימה קבועה של הברות ומילים קצרות, שכל אחת בודקת הגה אחד. כל דובר מקריא אותה פעם אחת. אומרים נכון, או בוחרים מראש את ההגה שבו תיעשה טעות מכוונת. כל הקלטה נשמרת עם התווית שלה, ומהן נמדד זיהוי הפונמות: כמה פעמים הגה שנאמר נכון סומן כטעות, וכמה טעויות מכוונות לא נתפסו.</p>
|
| 1657 |
<div class="sub" id="labState" aria-live="polite"></div>
|
| 1658 |
-
<div class="modes" id="labModes" role="tablist" aria-label="מעבדה"><button role="tab" data-mode="test">מבחן<small>הקלטת כל הרשימה</small></button><button role="tab" data-mode="record">הקלטה<small>פריט בודד, עם טעויות</small></button><button role="tab" data-mode="flags">דיווחים<small>הרצה מחדש של דיווחי ציון</small></button><button role="tab" data-mode="minerva">מינרווה<small>סרטונים ודיבור ילידי</small></button><button role="tab" data-mode="results">תוצאות<small>זיהוי לפי הגה</small></button></div>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1659 |
<div id="labTest">
|
| 1660 |
<div class="card wz-head">
|
| 1661 |
<p class="sub">כל שורה היא פריט לומר. השורה המסומנת היא הבאה בתור: לוחצים 🎤, אומרים את הפריט נכון ככל האפשר, וההקלטה מושמעת לבד. אחרי ההשמעה: ✓ שולח אותה ועובר לשורה הבאה, ✗ מוחק אותה ומקליטים שוב. מה שנשלח נשמר כ"נאמר נכון" של הדובר, והוא הבסיס לבדיקת זיהוי הפונמות.</p>
|
|
@@ -4924,6 +5057,38 @@ async function startRec(auto){ // auto: started by the page for the sentence o
|
|
| 4924 |
rec.start();
|
| 4925 |
}
|
| 4926 |
$("playMine").onclick=()=>{ if(myAudioUrl) new Audio(myAudioUrl).play(); };
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4927 |
|
| 4928 |
/* ---------- word-by-word answer, TTS ---------- */
|
| 4929 |
function revealWord(button){
|
|
@@ -5417,7 +5582,7 @@ async function loadManage(){
|
|
| 5417 |
state.textContent="טוען…"; state.classList.remove("setup");
|
| 5418 |
try{
|
| 5419 |
const [res,healthRes]=await Promise.all([api("/api/class"),fetch("/api/health").catch(()=>null)]); await ready;
|
| 5420 |
-
if(healthRes?.ok)
|
| 5421 |
if(!res.ok){
|
| 5422 |
const detail=(await res.json().catch(()=>({}))).detail||res.status;
|
| 5423 |
state.textContent=res.status===403?"הפאנל פתוח למורים בלבד.":`נתוני התלמידים לא זמינים כרגע (${detail}).`; return;
|
|
@@ -5425,6 +5590,7 @@ async function loadManage(){
|
|
| 5425 |
CLASS=await res.json(); await Promise.all([loadContent(),loadMathUnits()]);
|
| 5426 |
if(mMode==="flags") await loadFlags();
|
| 5427 |
if(mMode==="access") await loadAccess();
|
|
|
|
| 5428 |
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
|
| 5429 |
}catch{ state.textContent="השרת לא זמין."; return; }
|
| 5430 |
state.textContent=""; state.classList.toggle("setup",!!(CLASS.setup||[]).length);
|
|
@@ -5432,14 +5598,14 @@ async function loadManage(){
|
|
| 5432 |
const code=mark("",x.sql,"code"); code.dir="ltr"; state.append(mark("",x.what,"b"),mark(""," הריצו ב-SQL Editor של Supabase:"),code); }
|
| 5433 |
drawManage();
|
| 5434 |
}
|
| 5435 |
-
function drawBuild(info){
|
| 5436 |
const box=$("mBuild");
|
| 5437 |
if(!info) return;
|
| 5438 |
const updated=new Date(info.updated_at), date=Number.isNaN(updated.valueOf())?info.updated_at:
|
| 5439 |
new Intl.DateTimeFormat("he-IL",{dateStyle:"short",timeStyle:"short"}).format(updated);
|
| 5440 |
const list=document.createElement("dl");
|
| 5441 |
const item=(label,value,code=false)=>{ const row=document.createElement("div"), dt=document.createElement("dt"), dd=document.createElement("dd"), val=document.createElement(code?"code":"span"); dt.textContent=label; val.textContent=value||"לא זמין"; dd.append(val); row.append(dt,dd); return row; };
|
| 5442 |
-
list.append(item("מספר גרסה",info.version),item("עדכון אחרון",date),item("Commit ID",info.commit,true),item("הודעת commit",info.commit_message));
|
| 5443 |
const title=mark("","פרטי המערכת","h2"); title.id="mBuildTitle";
|
| 5444 |
box.replaceChildren(title,mark("","מידע טכני לזיהוי הגרסה שפועלת כעת.","p"),list);
|
| 5445 |
box.hidden=false;
|
|
@@ -5454,6 +5620,233 @@ const ACCESS_COLUMNS=[
|
|
| 5454 |
{label:"יאללה נדבר",kind:"entitlements",value:"tutor",permission:"tutor.use"},
|
| 5455 |
{label:"מסלול",kind:"entitlements",value:"path",permission:"path.use"},
|
| 5456 |
];
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5457 |
async function loadAccess(){
|
| 5458 |
accessError="";
|
| 5459 |
try{
|
|
@@ -5535,10 +5928,10 @@ function drawManage(){
|
|
| 5535 |
// progress; only the class's own lessons count); the totals beside their own fields (`tries` stays the per-sentence one)
|
| 5536 |
const students=CLASS.students.filter(s=>!klass||klass.name in s.classes).map(s=>{ const t=stuTally(s,listed);
|
| 5537 |
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}; });
|
| 5538 |
-
if(!["classes","students","content","flags","access"].includes(mMode)) mMode=classes.length?"students":"classes";
|
| 5539 |
-
$("mModes").hidden=false; for(const mode of ["classes","content","flags","access"]) $("manage").classList.toggle(mode,mMode===mode);
|
| 5540 |
for(const b of $("mModes").children) b.setAttribute("aria-selected",b.dataset.mode===mMode);
|
| 5541 |
-
drawClasses(classes); drawContent(); drawFlags(); drawAccess(); drawTabs(classes); drawHead(klass,students);
|
| 5542 |
if(klass||!classes.length) drawLessons(students,listed); else{ $("mLessons").innerHTML=""; $("mLessons").hidden=true; }
|
| 5543 |
drawRoster(klass,students,listed);
|
| 5544 |
const one=students.find(s=>s.email===shownStudent); // a student who left the class has no screen in it
|
|
@@ -5550,6 +5943,7 @@ async function showMode(mode){
|
|
| 5550 |
mMode=mode; store.set("ihki.mmode",mode); drawManage();
|
| 5551 |
if(mode==="flags"&&!flagsLoaded){ await loadFlags(); drawManage(); }
|
| 5552 |
if(mode==="access"){ await loadAccess(); drawManage(); }
|
|
|
|
| 5553 |
}
|
| 5554 |
for(const b of $("mModes").children) b.onclick=()=>showMode(b.dataset.mode);
|
| 5555 |
setInterval(()=>{
|
|
@@ -5735,7 +6129,8 @@ function drawFlags(){
|
|
| 5735 |
const group=document.createElement("details"), summary=document.createElement("summary");
|
| 5736 |
const key=`date-${day}`, label=dayLabel(day), people=new Set(flags.map(f=>f.email||"")).size;
|
| 5737 |
group.className="flag-group"; group.open=flagGroupOpen[key]===true; group.ontoggle=()=>{ flagGroupOpen[key]=group.open; };
|
| 5738 |
-
|
|
|
|
| 5739 |
const table=mark("flag-patterns flag-pending","","table"), headRow=document.createElement("tr");
|
| 5740 |
for(const x of ["ציון","מה התלמיד/ה אמר/ה","מה המודל שמע","אבחון ל־pipeline","","",""]) headRow.append(mark("",x,"th"));
|
| 5741 |
table.append(headRow); group.append(table);
|
|
@@ -5774,6 +6169,7 @@ function drawFlags(){
|
|
| 5774 |
toggle.onclick=()=>{ detail.hidden=!detail.hidden; flagGroupOpen[openKey]=!detail.hidden; toggle.textContent=detail.hidden?"פרטים ▾":"פרטים ▴"; };
|
| 5775 |
toggleCell.append(toggle);
|
| 5776 |
const reporter=mark("meta",`${f.email||"ללא משתמש"}`,"p"), age=flagAge(f.created_at); if(age) reporter.append(" · ",age);
|
|
|
|
| 5777 |
detailCell.append(reporter);
|
| 5778 |
if(f.note) detailCell.append(mark("",`הערת המדווח/ת: ${f.note}`,"p"));
|
| 5779 |
const field=document.createElement("fieldset"); field.append(mark("","אילו אבחנות של המערכת היו שגויות?","legend"));
|
|
@@ -7117,16 +7513,67 @@ async function showLab(){
|
|
| 7117 |
labMode(store.get("ihki.labMode","test"));
|
| 7118 |
}
|
| 7119 |
function labMode(mode){
|
| 7120 |
-
if(!["test","record","flags","minerva","results"].includes(mode)) mode="
|
| 7121 |
store.set("ihki.labMode",mode);
|
| 7122 |
for(const b of $("labModes").children) b.setAttribute("aria-selected",b.dataset.mode===mode?"true":"false");
|
| 7123 |
-
for(const m of ["test","record","flags","minerva","results"]) $("lab").classList.toggle(m,m===mode);
|
|
|
|
| 7124 |
if(mode==="test"){ drawWizard(); loadTtsVoices(); }
|
| 7125 |
if(mode==="flags"&&!labFlags) loadLabFlags();
|
| 7126 |
if(mode==="minerva") loadMinerva();
|
| 7127 |
if(mode==="results") loadLabResults();
|
| 7128 |
}
|
| 7129 |
for(const b of $("labModes").children) b.onclick=()=>labMode(b.dataset.mode);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7130 |
const labCount=id=>{ const c=LAB.counts[id]||{}; return (c.correct||0)+(c.mistake||0); };
|
| 7131 |
function drawLabList(){
|
| 7132 |
const box=$("labList"); box.replaceChildren();
|
|
|
|
| 700 |
/* The teacher's panel (its parts are styled further down: the class tabs, the figures, the lessons, the students). */
|
| 701 |
body:not(.manage) #manage,body.lab #manage,body:not(.lab) #lab,body.manage #wrap>header,body.manage #path,body.manage #today,body.manage #toNow,body.manage #practice,body:not(.home) #toManage{display:none}
|
| 702 |
body.lab #wrap,body.manage #wrap:has(#manage.access){max-width:none}
|
| 703 |
+
body.manage #wrap:has(#manage.models){max-width:1120px}
|
| 704 |
body.manage #manage{width:100%;max-width:none}
|
| 705 |
.mtitle{font:400 24px/1 var(--f-display);margin:0}
|
| 706 |
#mState.setup{padding:10px 12px;border:1px solid var(--sumac);border-radius:10px;color:var(--ink)}
|
|
|
|
| 790 |
.minerva-excluded{opacity:.65;text-decoration:line-through}
|
| 791 |
.lab-actions{display:flex;flex-wrap:wrap;align-items:center;gap:8px}
|
| 792 |
#labModes{grid-template-columns:repeat(5,1fr)}
|
| 793 |
+
#lab:not(.quick) #labQuick,#lab:not(.test) #labTest,#lab:not(.record) #labRecord,#lab:not(.flags) #labFlags,#lab:not(.minerva) #labMinerva,#lab:not(.results) #labResults{display:none}
|
| 794 |
+
#labQuick,#labTest,#labRecord,#labFlags,#labMinerva,#labResults{display:flex;flex-direction:column;gap:12px;min-width:0}
|
| 795 |
#labList,#labFlagList,#wzList{display:flex;flex-direction:column;gap:10px}
|
| 796 |
.wz-bar{flex-basis:100%;height:6px;border-radius:3px;background:var(--line);overflow:hidden}
|
| 797 |
.wz-bar i{display:block;height:100%;width:0;background:var(--ok);transition:width .3s}
|
|
|
|
| 927 |
#manage.content :is(#mTabs,#mHead,#mLessons,#mRoster,#mStudent),#manage:not(.content) #mContent{display:none}
|
| 928 |
#manage.flags :is(#mClasses,#mContent,#mTabs,#mHead,#mLessons,#mRoster,#mStudent),#manage:not(.flags) #mFlags{display:none}
|
| 929 |
#manage.access :is(#mClasses,#mContent,#mFlags,#mTabs,#mHead,#mLessons,#mRoster,#mStudent),#manage:not(.access) #mAccess{display:none}
|
| 930 |
+
#manage.models :is(#mClasses,#mContent,#mFlags,#mAccess,#mTabs,#mHead,#mLessons,#mRoster,#mStudent),#manage:not(.models) #mModels{display:none}
|
| 931 |
.access-actions{display:flex;justify-content:flex-end;margin:8px 0}.access-scroll{overflow:auto}.access-table{width:100%;border-collapse:collapse;min-width:1180px}.access-table :is(th,td){padding:9px 10px;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 th>span{display:block;margin-bottom:4px}.access-table .access-all{display:inline-flex;align-items:center;gap:4px;color:var(--muted);font-weight:600;cursor:pointer}.access-table .access-all small{font-size:11px}.access-table :is(th,td):first-child{text-align:start;position:sticky;right:0;background:var(--surface);z-index:2;min-width:260px}.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:96px}
|
| 932 |
+
#mModes{grid-template-columns:repeat(6,1fr)}
|
| 933 |
+
/* the developers' model comparison under a result: one column per model, the same recording */
|
| 934 |
+
.cmp-box{margin-top:6px;border-top:1px dashed var(--line);padding-top:8px;display:flex;flex-direction:column;gap:8px}
|
| 935 |
+
.cmp-bar{display:flex;align-items:center;gap:10px;flex-wrap:wrap}
|
| 936 |
+
.cmp-auto{display:flex;align-items:center;gap:4px;font-size:13px;color:var(--muted);cursor:pointer}
|
| 937 |
+
.cmp-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:8px}
|
| 938 |
+
.cmp-col{border:1px solid var(--line);border-radius:12px;padding:8px 10px;display:flex;flex-direction:column;gap:6px;background:var(--surface);min-width:0}
|
| 939 |
+
.cmp-col.active{border-color:var(--olive);box-shadow:0 0 0 1px var(--olive) inset}
|
| 940 |
+
.cmp-col h4{margin:0;font:700 14px/1.25 var(--f-body)}
|
| 941 |
+
.cmp-col .cmp-meta{font-size:11px;color:var(--muted);font-variant-numeric:tabular-nums}
|
| 942 |
+
.cmp-verdict{display:flex;align-items:center;gap:8px}
|
| 943 |
+
.cmp-verdict .num{font:700 26px/1 var(--f-body);font-variant-numeric:tabular-nums}
|
| 944 |
+
.cmp-heard{font-size:13px;color:var(--muted)}
|
| 945 |
+
.cmp-heard b{color:var(--ink);font-weight:600}
|
| 946 |
+
.cmp-word{display:flex;flex-wrap:wrap;gap:3px;align-items:center;padding-top:4px;border-top:1px solid var(--line)}
|
| 947 |
+
.cmp-word>.w{font:700 14px var(--f-tr);margin-inline-end:4px;width:100%}
|
| 948 |
+
.cmp-ph{font:600 12px/1.3 var(--f-ipa);padding:1px 5px;border-radius:6px;background:var(--bg);border:1px solid var(--line);direction:ltr;unicode-bidi:isolate;white-space:nowrap}
|
| 949 |
+
.cmp-ph.low{background:var(--amber-bg);color:var(--amber)}
|
| 950 |
+
.cmp-ph.flag{background:var(--sumac-bg);color:var(--sumac);border-color:var(--sumac)}
|
| 951 |
+
.cmp-ph.diff{outline:2px solid var(--ink);outline-offset:1px}
|
| 952 |
+
.cmp-tips{margin:0;padding-inline-start:16px;font-size:12px;color:var(--muted)}
|
| 953 |
+
.cmp-err{font-size:12px;color:var(--sumac);direction:ltr;unicode-bidi:isolate;word-break:break-word}
|
| 954 |
+
/* the "מודלים" tab: one card per phoneme model, its accuracy as a ring and its sounds as bars */
|
| 955 |
+
#mModels{display:flex;flex-direction:column;gap:12px}
|
| 956 |
+
.mdl-now{flex-direction:row;align-items:center;gap:14px;flex-wrap:wrap}
|
| 957 |
+
.mdl-now .mdl-icon{width:44px;height:44px;border-radius:12px;display:grid;place-items:center;background:var(--olive-soft);font-size:24px;flex:none}
|
| 958 |
+
.mdl-now h2{margin:0;font:400 22px/1.2 var(--f-display)}
|
| 959 |
+
.mdl-now code,.mdl-card code{font:13px var(--f-ipa);color:var(--muted);direction:ltr;unicode-bidi:isolate;word-break:break-all}
|
| 960 |
+
.mdl-now .mdl-text{flex:1;min-width:220px;display:flex;flex-direction:column;gap:2px}
|
| 961 |
+
.mdl-pill{display:inline-flex;align-items:center;gap:5px;border-radius:999px;padding:2px 10px;font:700 13px/1.6 var(--f-body);white-space:nowrap}
|
| 962 |
+
.mdl-pill.on{background:var(--ok-bg);color:var(--ok)}
|
| 963 |
+
.mdl-pill.wait{background:var(--amber-bg);color:var(--amber)}
|
| 964 |
+
.mdl-pill.bad{background:var(--sumac-bg);color:var(--sumac)}
|
| 965 |
+
.mdl-pill.off{background:var(--line);color:var(--muted)}
|
| 966 |
+
.mdl-pill.best{background:var(--olive-soft);color:var(--olive-deep)}
|
| 967 |
+
.mdl-cmp h2,.mdl-card h3{margin:0;font:400 19px/1.2 var(--f-display)}
|
| 968 |
+
.mdl-cmp .mdl-row{display:grid;grid-template-columns:minmax(110px,170px) 1fr 52px;align-items:center;gap:10px;padding:3px 0}
|
| 969 |
+
.mdl-cmp .mdl-row b{font-weight:700;font-size:15px}
|
| 970 |
+
.mdl-track{display:block;height:10px;border-radius:999px;background:var(--line);overflow:hidden;position:relative}
|
| 971 |
+
.mdl-fill{position:absolute;inset-block:0;inset-inline-start:0;border-radius:4px;background:var(--olive);min-width:2px;transition:width .5s ease}
|
| 972 |
+
.mdl-val{font:700 15px var(--f-body);font-variant-numeric:tabular-nums;text-align:end}
|
| 973 |
+
.mdl-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(300px,1fr));gap:12px}
|
| 974 |
+
.mdl-card{position:relative}
|
| 975 |
+
.mdl-card.active{border-color:var(--olive);box-shadow:0 0 0 2px var(--olive) inset}
|
| 976 |
+
.mdl-card.unavail{opacity:.75}
|
| 977 |
+
.mdl-card .mdl-head{display:flex;align-items:flex-start;gap:8px;flex-wrap:wrap}
|
| 978 |
+
.mdl-card .mdl-head h3{flex:1;min-width:140px}
|
| 979 |
+
.mdl-card .mdl-sum{margin:0;color:var(--muted);font-size:14px;line-height:1.45}
|
| 980 |
+
.mdl-hero{display:flex;align-items:center;gap:14px}
|
| 981 |
+
.mdl-ring{flex:none;width:96px;height:96px}
|
| 982 |
+
.mdl-ring circle{fill:none;stroke-width:9}
|
| 983 |
+
.mdl-ring .track{stroke:var(--line)}
|
| 984 |
+
.mdl-ring .val{stroke:var(--olive);stroke-linecap:round;transition:stroke-dasharray .6s ease}
|
| 985 |
+
.mdl-ring text{fill:var(--ink);font:700 22px var(--f-body);text-anchor:middle;dominant-baseline:central}
|
| 986 |
+
.mdl-hero .mdl-hero-text{display:flex;flex-direction:column;gap:2px;font-size:14px;color:var(--muted)}
|
| 987 |
+
.mdl-hero .mdl-hero-text b{color:var(--ink);font-size:16px}
|
| 988 |
+
.mdl-bars{display:flex;flex-direction:column;gap:6px}
|
| 989 |
+
.mdl-bars .mdl-row{display:grid;grid-template-columns:92px 1fr 44px;align-items:center;gap:8px;font-size:14px}
|
| 990 |
+
.mdl-bars .mdl-row .none{grid-column:2/4;color:var(--muted);font-size:13px}
|
| 991 |
+
.mdl-facts{display:flex;flex-wrap:wrap;gap:6px 14px;font-size:13px;color:var(--muted);border-top:1px solid var(--line);padding-top:8px}
|
| 992 |
+
.mdl-facts span{display:inline-flex;gap:5px;align-items:center}
|
| 993 |
+
.mdl-act{display:flex;align-items:center;gap:10px;flex-wrap:wrap}
|
| 994 |
+
.mdl-act .why{font-size:13px;color:var(--sumac)}
|
| 995 |
+
.mdl-note{margin:0;font-size:13px;color:var(--muted)}
|
| 996 |
+
.mdl-spin{display:inline-block;width:12px;height:12px;border:2px solid currentColor;border-inline-end-color:transparent;border-radius:50%;animation:mdlspin .8s linear infinite}
|
| 997 |
+
@keyframes mdlspin{to{transform:rotate(360deg)}}
|
| 998 |
+
/* the tab's tuning: per-sound thresholds as sliders (red: flagged, green: passes) and the scorer's other settings */
|
| 999 |
+
.ms-head{flex-direction:row;align-items:center;gap:10px;flex-wrap:wrap}
|
| 1000 |
+
.ms-head h2{margin:0;font:400 22px/1.2 var(--f-display);flex:1;min-width:200px}
|
| 1001 |
+
.ms-head select{font:600 15px var(--f-body);padding:6px 10px;border-radius:10px;border:1px solid var(--line);background:var(--surface);color:var(--ink)}
|
| 1002 |
+
.ms-legend{display:flex;gap:14px;flex-wrap:wrap;font-size:13px;color:var(--muted)}
|
| 1003 |
+
.ms-legend i{display:inline-block;width:14px;height:10px;border-radius:3px;vertical-align:middle;margin-inline-end:5px}
|
| 1004 |
+
.ms-legend .bad{background:var(--sumac)} .ms-legend .good{background:var(--ok)}
|
| 1005 |
+
.ms-sounds h3,.ms-group h3{margin:0;font:400 18px/1.2 var(--f-display)}
|
| 1006 |
+
/* the equalizer: vertical faders side by side, grouped; a dashed line across a bank marks the general threshold */
|
| 1007 |
+
.eq{display:flex;gap:14px;overflow-x:auto;padding:4px 2px 8px;scrollbar-width:thin;align-items:stretch}
|
| 1008 |
+
.eq-group{display:flex;flex-direction:column;gap:6px;flex:none}
|
| 1009 |
+
.eq-group>.eq-name{font:700 12px/1.2 var(--f-body);color:var(--muted);text-align:center;border-top:2px solid var(--line);padding-top:5px;letter-spacing:.02em}
|
| 1010 |
+
.eq-bands{display:flex;gap:4px;align-items:flex-end}
|
| 1011 |
+
.eq-band{width:58px;flex:none;display:flex;flex-direction:column;align-items:center;gap:4px;padding:6px 2px 6px;border-radius:12px;border:1px solid transparent;position:relative}
|
| 1012 |
+
.eq-band:hover,.eq-band:focus-within{background:var(--bg);border-color:var(--line)}
|
| 1013 |
+
.eq-band.dirty{box-shadow:0 0 0 2px var(--amber) inset}
|
| 1014 |
+
.eq-band.wide{width:96px}
|
| 1015 |
+
.eq-val{font:700 15px/1.1 var(--f-body);font-variant-numeric:tabular-nums;min-height:18px;text-align:center}
|
| 1016 |
+
.eq-val.inherit{color:var(--muted);font-weight:600;font-size:12px}
|
| 1017 |
+
.eq-fader{position:relative;height:170px;width:34px;display:flex;justify-content:center}
|
| 1018 |
+
.eq-fader input{writing-mode:vertical-lr;direction:rtl;width:34px;height:170px;margin:0;appearance:none;-webkit-appearance:none;background:transparent;cursor:pointer}
|
| 1019 |
+
.eq-fader input::-webkit-slider-runnable-track{width:10px;border-radius:999px;background:linear-gradient(to top,var(--sumac) 0 var(--t),var(--ok) var(--t) 100%)}
|
| 1020 |
+
.eq-fader input::-moz-range-track{width:10px;border-radius:999px;background:linear-gradient(to top,var(--sumac) 0 var(--t),var(--ok) var(--t) 100%)}
|
| 1021 |
+
.eq-fader.plain input::-webkit-slider-runnable-track{background:linear-gradient(to top,var(--olive) 0 var(--t),var(--line) var(--t) 100%)}
|
| 1022 |
+
.eq-fader.plain input::-moz-range-track{background:linear-gradient(to top,var(--olive) 0 var(--t),var(--line) var(--t) 100%)}
|
| 1023 |
+
.eq-fader input::-webkit-slider-thumb{-webkit-appearance:none;width:28px;height:14px;border-radius:4px;background:var(--surface);border:2px solid var(--ink);box-shadow:inset 0 -3px 0 var(--line)}
|
| 1024 |
+
.eq-fader input::-moz-range-thumb{width:24px;height:10px;border-radius:4px;background:var(--surface);border:2px solid var(--ink)}
|
| 1025 |
+
.eq-fader input:disabled{opacity:.4;cursor:default}
|
| 1026 |
+
.eq-fader input:focus-visible{outline:2px solid var(--olive);outline-offset:2px;border-radius:6px}
|
| 1027 |
+
.eq-general{position:absolute;inset-inline:-4px;height:0;border-top:2px dashed var(--ink);opacity:.35;pointer-events:none}
|
| 1028 |
+
.eq-scale{width:26px;flex:none;position:relative;height:170px;margin-top:28px;font:600 11px var(--f-body);color:var(--muted);font-variant-numeric:tabular-nums}
|
| 1029 |
+
.eq-scale span{position:absolute;inset-inline-end:0;transform:translateY(50%)}
|
| 1030 |
+
.eq-letter{font:700 16px/1.1 var(--f-body);text-align:center;white-space:nowrap}
|
| 1031 |
+
.eq-letter small{display:block;font:600 11px/1.2 var(--f-body);color:var(--muted)}
|
| 1032 |
+
.eq-label{font:600 12px/1.25 var(--f-body);text-align:center;min-height:30px;display:flex;align-items:center}
|
| 1033 |
+
.eq-led{display:flex;align-items:center;gap:4px;border:0;background:transparent;color:var(--muted);font:600 11px var(--f-body);cursor:pointer;padding:2px 4px;border-radius:6px}
|
| 1034 |
+
.eq-led::before{content:"";width:9px;height:9px;border-radius:50%;background:var(--line);box-shadow:inset 0 0 0 1px rgba(0,0,0,.15)}
|
| 1035 |
+
.eq-led[aria-pressed=true]{color:var(--ink)}
|
| 1036 |
+
.eq-led[aria-pressed=true]::before{background:var(--ok);box-shadow:0 0 6px var(--ok)}
|
| 1037 |
+
.eq-led:disabled{cursor:default}
|
| 1038 |
+
.eq-reset{position:absolute;top:2px;inset-inline-start:2px;border:0;background:transparent;color:var(--muted);cursor:pointer;font-size:12px;padding:0 3px;border-radius:5px}
|
| 1039 |
+
.eq-reset:hover{color:var(--ink);background:var(--line)}
|
| 1040 |
+
.eq-band select{font:600 13px var(--f-body);padding:4px;border-radius:8px;border:1px solid var(--line);background:var(--surface);color:var(--ink);width:100%;margin-top:auto}
|
| 1041 |
+
.eq-choice{height:170px;display:flex;flex-direction:column;justify-content:center;width:100%}
|
| 1042 |
+
.eq-info{min-height:40px;margin:0;padding:8px 12px;border-radius:10px;background:var(--bg);font-size:13px;color:var(--muted);line-height:1.45}
|
| 1043 |
+
.eq-info b{color:var(--ink)}
|
| 1044 |
+
.ms-bar{position:sticky;bottom:10px;z-index:5;flex-direction:row;align-items:center;gap:10px;flex-wrap:wrap;box-shadow:0 4px 18px rgba(0,0,0,.18)}
|
| 1045 |
+
.ms-bar .count{flex:1;min-width:160px;font-weight:700}
|
| 1046 |
+
.ms-bar .count.clean{color:var(--muted);font-weight:400}
|
| 1047 |
+
@media (prefers-reduced-motion:reduce){.mdl-spin{animation:none}.mdl-fill,.mdl-ring .val{transition:none}}
|
| 1048 |
+
@media(max-width:700px){.modes,#mModes{grid-template-columns:repeat(2,1fr)}}
|
| 1049 |
.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}
|
| 1050 |
.flag-review.flag-urgent{border-inline-start:4px solid var(--sumac)}.flag-review.flag-lower{border-inline-start:4px solid var(--line)}
|
| 1051 |
.flag-priority{display:inline-block;margin-inline-start:6px;padding:2px 7px;border-radius:999px;font-size:12px;font-weight:700}.flag-priority.urgent{background:var(--sumac-bg);color:var(--sumac)}.flag-priority.lower{background:var(--bg);color:var(--muted)}
|
|
|
|
| 1757 |
<section class="wrap" id="manage" aria-labelledby="mTitle">
|
| 1758 |
<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>
|
| 1759 |
<div class="sub" id="mState" aria-live="polite"></div>
|
| 1760 |
+
<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><button role="tab" data-mode="models">מודלים<small>בחירה והשוואה</small></button></div>
|
| 1761 |
<div id="mClasses"></div>
|
| 1762 |
<div id="mContent"></div>
|
| 1763 |
<div id="mFlags"></div>
|
| 1764 |
<div class="card" id="mAccess"></div>
|
| 1765 |
+
<div id="mModels"></div>
|
| 1766 |
<div class="tabs" id="mTabs" role="tablist" aria-label="סינון תלמידים לפי כיתה" hidden></div>
|
| 1767 |
<div class="card" id="mHead" hidden></div>
|
| 1768 |
<div class="card hard" id="mLessons" hidden></div>
|
|
|
|
| 1774 |
<div class="roundbar"><h1 class="mtitle" id="labTitle">מעבדה</h1><span class="sep"></span><button class="btn" id="labManage">ניהול</button><button class="btn primary" id="labPractice">לתרגול</button></div>
|
| 1775 |
<p class="sub">רשימה קבועה של הברות ומילים קצרות, שכל אחת בודקת הגה אחד. כל דובר מקריא אותה פעם אחת. אומרים נכון, או בוחרים מראש את ההגה שבו תיעשה טעות מכוונת. כל הקלטה נשמרת עם התווית שלה, ומהן נמדד זיהוי הפונמות: כמה פעמים הגה שנאמר נכון סומן כטעות, וכמה טעויות מכוונות לא נתפסו.</p>
|
| 1776 |
<div class="sub" id="labState" aria-live="polite"></div>
|
| 1777 |
+
<div class="modes" id="labModes" role="tablist" aria-label="מעבדה"><button role="tab" data-mode="quick">בדיקה<small>10 שאלות · 3 מודלים</small></button><button role="tab" data-mode="test">מבחן מלא<small>הקלטת כל הרשימה</small></button><button role="tab" data-mode="record">הקלטה<small>פריט בודד, עם טעויות</small></button><button role="tab" data-mode="flags">דיווחים<small>הרצה מחדש של דיווחי ציון</small></button><button role="tab" data-mode="minerva">מינרווה<small>סרטונים ודיבור ילידי</small></button><button role="tab" data-mode="results">תוצאות<small>זיהוי לפי הגה</small></button></div>
|
| 1778 |
+
<div id="labQuick">
|
| 1779 |
+
<div class="card wz-head">
|
| 1780 |
+
<h2>בדיקה מהירה לדוברי עברית</h2>
|
| 1781 |
+
<p class="sub">עשר מילים שבודקות ח ו־ע גרוניות, ח׳, ע׳, עיצורים נחציים והבדל בין תנועה קצרה לאליף ארוכה. הקליטו כל מילה פעם אחת; אותה הקלטה נבדקת ב־Facebook, ב־wav2vec2 המאומן וב־POWSM short-pad (ONNX). ההקלטות אינן נשמרות.</p>
|
| 1782 |
+
<div class="lab-actions"><b id="quickProgress"></b><span class="sub" id="quickState" aria-live="polite">בחרו שאלה והקליטו</span><button class="btn" id="quickReset">התחלה מחדש</button></div>
|
| 1783 |
+
</div>
|
| 1784 |
+
<div class="card lab-item">
|
| 1785 |
+
<div class="lab-head"><span class="ar" id="quickAr"></span><span class="lab-tr" id="quickTr"></span><span class="sub" id="quickHe"></span></div>
|
| 1786 |
+
<div class="lab-rec"><button class="mic" id="quickMic" aria-label="הקלטת תשובה"><svg class="ic" aria-hidden="true"><use href="#i-mic"/></svg></button><span class="sub">לחצו, אמרו את המילה, ולחצו שוב לסיום</span></div>
|
| 1787 |
+
<div class="cmp-grid" id="quickOut"></div>
|
| 1788 |
+
<div class="lab-actions"><button class="btn" id="quickPrev">הקודם</button><button class="btn primary" id="quickNext">הבא ←</button></div>
|
| 1789 |
+
</div>
|
| 1790 |
+
<div class="card"><div class="stage-table-wrap"><table class="lab-table" id="quickSummary"></table></div></div>
|
| 1791 |
+
</div>
|
| 1792 |
<div id="labTest">
|
| 1793 |
<div class="card wz-head">
|
| 1794 |
<p class="sub">כל שורה היא פריט לומר. השורה המסומנת היא הבאה בתור: לוחצים 🎤, אומרים את הפריט נכון ככל האפשר, וההקלטה מושמעת לבד. אחרי ההשמעה: ✓ שולח אותה ועובר לשורה הבאה, ✗ מוחק אותה ומקליטים שוב. מה שנשלח נשמר כ"נאמר נכון" של הדובר, והוא הבסיס לבדיקת זיהוי הפונמות.</p>
|
|
|
|
| 5057 |
rec.start();
|
| 5058 |
}
|
| 5059 |
$("playMine").onclick=()=>{ if(myAudioUrl) new Audio(myAudioUrl).play(); };
|
| 5060 |
+
/* The lab's model comparison: one recording scored by each comparison model (POST /api/admin/compare-models).
|
| 5061 |
+
A sound flagged by one model and not another is outlined when the models' sound lists line up. */
|
| 5062 |
+
function drawComparison(models,target="quickOut"){
|
| 5063 |
+
const out=$(target); out.replaceChildren();
|
| 5064 |
+
const ok=models.filter(m=>!m.error);
|
| 5065 |
+
const sameShape=ok.length>1&&ok.every(m=>m.words.length===ok[0].words.length&&m.words.every((w,i)=>w.phonemes.length===ok[0].words[i].phonemes.length));
|
| 5066 |
+
const disagree=(wi,pi)=>sameShape&&new Set(ok.map(m=>m.words[wi].phonemes[pi].flagged)).size>1;
|
| 5067 |
+
for(const m of models){
|
| 5068 |
+
const col=mark(`cmp-col${m.active?" active":""}`,""), title=mark("",m.name,"h4");
|
| 5069 |
+
if(m.active) title.append(mark("meta"," · פעיל"));
|
| 5070 |
+
col.append(title,mark("cmp-meta",m.model));
|
| 5071 |
+
if(m.error){ col.append(mark("cmp-err",m.error)); out.append(col); continue; }
|
| 5072 |
+
col.append(mark("cmp-meta",`${m.ms} ms${m.load_ms>500?` · נטען ב־${(m.load_ms/1000).toFixed(1)} ש׳`:""} · ${m.references} קולות ייחוס`));
|
| 5073 |
+
const v=mark("cmp-verdict",""), s=m.score;
|
| 5074 |
+
v.append(mark("num",s==null?"–":String(Math.round(s))),
|
| 5075 |
+
mark(`pill ${m.unrelated?"bad":s>=EXCELLENT?"good":s>=60?"mid":"bad"}`,m.unrelated?"משפט אחר?":s>=EXCELLENT?"מצוין":s>=60?"כמעט":"נסו שוב"));
|
| 5076 |
+
col.append(v);
|
| 5077 |
+
const heard=mark("cmp-heard","נשמע: "), ht=mark("",m.heard_tr||"–","b"); setTr(ht,m.heard_tr||"–"); heard.append(ht); col.append(heard);
|
| 5078 |
+
m.words.forEach((w,wi)=>{
|
| 5079 |
+
const row=mark("cmp-word",""), wt=mark("w",""); setTr(wt,w.tr||""); row.append(wt);
|
| 5080 |
+
w.phonemes.forEach((p,pi)=>{
|
| 5081 |
+
const chip=mark(`cmp-ph${p.flagged?" flag":p.score<75?" low":""}${disagree(wi,pi)?" diff":""}`,`${p.ipa} ${p.score}${p.flagged&&p.heard?` →${p.heard==="_"?"∅":p.heard}`:""}`);
|
| 5082 |
+
chip.title=`${p.ipa}: ${p.score}${p.flagged?" · מסומן כטעות":""}${p.heard?` · נשמע ${p.heard==="_"?"כלום":p.heard}`:""}${disagree(wi,pi)?" · המודלים לא מסכימים":""}`;
|
| 5083 |
+
row.append(chip);
|
| 5084 |
+
});
|
| 5085 |
+
col.append(row);
|
| 5086 |
+
});
|
| 5087 |
+
if(m.tips.length){ const ul=mark("cmp-tips","","ul"); for(const t of m.tips) ul.append(mark("",t,"li")); col.append(ul); }
|
| 5088 |
+
out.append(col);
|
| 5089 |
+
}
|
| 5090 |
+
}
|
| 5091 |
+
|
| 5092 |
|
| 5093 |
/* ---------- word-by-word answer, TTS ---------- */
|
| 5094 |
function revealWord(button){
|
|
|
|
| 5582 |
state.textContent="טוען…"; state.classList.remove("setup");
|
| 5583 |
try{
|
| 5584 |
const [res,healthRes]=await Promise.all([api("/api/class"),fetch("/api/health").catch(()=>null)]); await ready;
|
| 5585 |
+
if(healthRes?.ok){ const health=await healthRes.json(); drawBuild(health.build,health.model); }
|
| 5586 |
if(!res.ok){
|
| 5587 |
const detail=(await res.json().catch(()=>({}))).detail||res.status;
|
| 5588 |
state.textContent=res.status===403?"הפאנל פתוח למורים בלבד.":`נתוני התלמידים לא זמינים כרגע (${detail}).`; return;
|
|
|
|
| 5590 |
CLASS=await res.json(); await Promise.all([loadContent(),loadMathUnits()]);
|
| 5591 |
if(mMode==="flags") await loadFlags();
|
| 5592 |
if(mMode==="access") await loadAccess();
|
| 5593 |
+
if(mMode==="models"){ await loadModels(); if(MODELS) await loadModelSettings(MS_MODEL||MODELS.active); }
|
| 5594 |
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
|
| 5595 |
}catch{ state.textContent="השרת לא זמין."; return; }
|
| 5596 |
state.textContent=""; state.classList.toggle("setup",!!(CLASS.setup||[]).length);
|
|
|
|
| 5598 |
const code=mark("",x.sql,"code"); code.dir="ltr"; state.append(mark("",x.what,"b"),mark(""," הריצו ב-SQL Editor של Supabase:"),code); }
|
| 5599 |
drawManage();
|
| 5600 |
}
|
| 5601 |
+
function drawBuild(info,model){
|
| 5602 |
const box=$("mBuild");
|
| 5603 |
if(!info) return;
|
| 5604 |
const updated=new Date(info.updated_at), date=Number.isNaN(updated.valueOf())?info.updated_at:
|
| 5605 |
new Intl.DateTimeFormat("he-IL",{dateStyle:"short",timeStyle:"short"}).format(updated);
|
| 5606 |
const list=document.createElement("dl");
|
| 5607 |
const item=(label,value,code=false)=>{ const row=document.createElement("div"), dt=document.createElement("dt"), dd=document.createElement("dd"), val=document.createElement(code?"code":"span"); dt.textContent=label; val.textContent=value||"לא זמין"; dd.append(val); row.append(dt,dd); return row; };
|
| 5608 |
+
list.append(item("מספר גרסה",info.version),item("עדכון אחרון",date),item("Commit ID",info.commit,true),item("הודעת commit",info.commit_message),item("מודל",model,true));
|
| 5609 |
const title=mark("","פרטי המערכת","h2"); title.id="mBuildTitle";
|
| 5610 |
box.replaceChildren(title,mark("","מידע טכני לזיהוי הגרסה שפועלת כעת.","p"),list);
|
| 5611 |
box.hidden=false;
|
|
|
|
| 5620 |
{label:"יאללה נדבר",kind:"entitlements",value:"tutor",permission:"tutor.use"},
|
| 5621 |
{label:"מסלול",kind:"entitlements",value:"path",permission:"path.use"},
|
| 5622 |
];
|
| 5623 |
+
/* The "מודלים" tab: the phoneme models this server can score with (app/models.py), what each was measured to do
|
| 5624 |
+
on the Minerva test lines, and a switch (developers only) that loads another one beside the running one. */
|
| 5625 |
+
let MODELS=null, modelsError="", modelsPoll=0;
|
| 5626 |
+
const MODEL_SOUNDS=[["ħ","ח (ح)"],["ʕ","ע (ع)"],["tˤ","ט (ط)"],["sˤ","צ (ص)"],["dˤ","ד׳ (ض)"],["long_vowels","תנועות ארוכות"]];
|
| 5627 |
+
async function loadModels(){
|
| 5628 |
+
modelsError="";
|
| 5629 |
+
try{ const res=await api("/api/admin/models"), data=await res.json().catch(()=>({})); if(!res.ok) throw new Error(data.detail||res.status); MODELS=data; }
|
| 5630 |
+
catch(err){ MODELS=null; modelsError=err.message; }
|
| 5631 |
+
clearTimeout(modelsPoll);
|
| 5632 |
+
if(MODELS?.switch?.state==="loading") modelsPoll=setTimeout(async()=>{ await loadModels(); if(mMode==="models"&&document.body.classList.contains("manage")) drawManage(); },2000);
|
| 5633 |
+
}
|
| 5634 |
+
function modelRing(acc){
|
| 5635 |
+
const r=40, c=2*Math.PI*r, svg=document.createElementNS("http://www.w3.org/2000/svg","svg");
|
| 5636 |
+
svg.setAttribute("viewBox","0 0 100 100"); svg.setAttribute("class","mdl-ring"); svg.setAttribute("role","img");
|
| 5637 |
+
svg.setAttribute("aria-label",`דיוק פונמות ${Math.round(acc*100)}%`);
|
| 5638 |
+
const circle=(cls,dash)=>{ const el=document.createElementNS("http://www.w3.org/2000/svg","circle"); el.setAttribute("cx",50); el.setAttribute("cy",50); el.setAttribute("r",r); el.setAttribute("class",cls); if(dash!=null){ el.setAttribute("stroke-dasharray",`${dash} ${c}`); el.setAttribute("transform","rotate(-90 50 50)"); } return el; };
|
| 5639 |
+
const text=document.createElementNS("http://www.w3.org/2000/svg","text"); text.setAttribute("x",50); text.setAttribute("y",50); text.textContent=`${Math.round(acc*100)}%`;
|
| 5640 |
+
svg.append(circle("track"),circle("val",Math.max(0,acc)*c),text);
|
| 5641 |
+
const title=document.createElementNS("http://www.w3.org/2000/svg","title"); title.textContent=`נכון ב־${Math.round(acc*100)}% מהפונמות (שגיאה ${Math.round((1-acc)*100)}%)`; svg.prepend(title);
|
| 5642 |
+
return svg;
|
| 5643 |
+
}
|
| 5644 |
+
function modelBar(label,value,tip){
|
| 5645 |
+
const row=mark("mdl-row",""); row.append(mark("",label,"span"));
|
| 5646 |
+
if(value==null){ row.append(mark("none","אין למודל סמל להגה הזה")); return row; }
|
| 5647 |
+
const track=mark("mdl-track",""), fill=mark("mdl-fill",""); fill.style.width=`${Math.round(value*100)}%`; track.append(fill);
|
| 5648 |
+
row.title=tip||`${label}: ${Math.round(value*100)}%`; row.append(track,mark("mdl-val",`${Math.round(value*100)}%`)); return row;
|
| 5649 |
+
}
|
| 5650 |
+
async function switchModel(id,button,msg){
|
| 5651 |
+
button.disabled=true; msg.textContent="מתחיל לטעון…";
|
| 5652 |
+
try{ const res=await api("/api/admin/models/active",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({model_id:id})}), data=await res.json().catch(()=>({})); if(!res.ok) throw new Error(data.detail||res.status); MODELS=data; }
|
| 5653 |
+
catch(err){ msg.textContent="ההחלפה לא התחילה: "+err.message; button.disabled=false; return; }
|
| 5654 |
+
await loadModels(); drawManage();
|
| 5655 |
+
}
|
| 5656 |
+
/* The tuning section of the "מודלים" tab: one model's scorer settings (app/model_settings.py), changed locally
|
| 5657 |
+
(MS_DRAFT) and saved together. For the model scoring now they apply at once; for another, when it is switched on. */
|
| 5658 |
+
let MS=null, MS_MODEL="", msError="", MS_DRAFT={fields:{},sounds:{}}, msMsg="";
|
| 5659 |
+
async function loadModelSettings(model){
|
| 5660 |
+
msError=""; MS_MODEL=model||MS_MODEL;
|
| 5661 |
+
try{ const res=await api(`/api/admin/model-settings?model=${encodeURIComponent(MS_MODEL)}`), data=await res.json().catch(()=>({})); if(!res.ok) throw new Error(data.detail||res.status); MS=data; MS_MODEL=data.model; }
|
| 5662 |
+
catch(err){ MS=null; msError=err.message; }
|
| 5663 |
+
MS_DRAFT={fields:{},sounds:{}};
|
| 5664 |
+
}
|
| 5665 |
+
const msFieldValue=f=>f.key in MS_DRAFT.fields?MS_DRAFT.fields[f.key]:f.value;
|
| 5666 |
+
const msSoundValue=s=>s.sound in MS_DRAFT.sounds?MS_DRAFT.sounds[s.sound]:s.value; // null: the general threshold
|
| 5667 |
+
const msGeneral=()=>{ const f=MS.fields.find(x=>x.key==="flag_below"); return msFieldValue(f); };
|
| 5668 |
+
const msDirtyCount=()=>Object.keys(MS_DRAFT.fields).length+Object.keys(MS_DRAFT.sounds).length;
|
| 5669 |
+
function msOverrides(){ // every setting that differs from the model's default, as the server stores it
|
| 5670 |
+
const out={}, sounds={};
|
| 5671 |
+
for(const f of MS.fields){ const v=msFieldValue(f); if(v!==f.default) out[f.key]=v; }
|
| 5672 |
+
for(const g of MS.sounds) for(const s of g.sounds){ const v=msSoundValue(s); if(v!==s.default) sounds[s.sound]=v; }
|
| 5673 |
+
if(Object.keys(sounds).length) out.flag_below_sound=sounds;
|
| 5674 |
+
return out;
|
| 5675 |
+
}
|
| 5676 |
+
async function saveModelSettings(settings,msg){
|
| 5677 |
+
msg.textContent="שומר…";
|
| 5678 |
+
try{ const res=await api("/api/admin/model-settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:MS_MODEL,settings})}), data=await res.json().catch(()=>({})); if(!res.ok) throw new Error(data.detail||res.status); MS=data; MS_DRAFT={fields:{},sounds:{}}; msMsg=data.active?"נשמר. ההקלטות מעכשיו נבדקות בהגדרות החדשות.":"נשמר. ההגדרות יחולו כשהמודל יופעל."; drawManage(); }
|
| 5679 |
+
catch(err){ msg.textContent="השמירה נכשלה: "+err.message; }
|
| 5680 |
+
}
|
| 5681 |
+
const fmtSetting=(f,v)=>v==null?"רחב":f.kind==="choice"?v:f.kind==="int"||f.kind==="window"?String(v):(f.step<1?Number(v).toFixed(2):String(Math.round(v)));
|
| 5682 |
+
function eqScale(){ // 0..100 marks beside a bank of threshold faders
|
| 5683 |
+
const scale=mark("eq-scale",""); for(const v of [0,25,50,75,100]){ const t=mark("",String(v)); t.style.bottom=`${v}%`; scale.append(t); } return scale;
|
| 5684 |
+
}
|
| 5685 |
+
function eqFader(min,max,step,label){
|
| 5686 |
+
const wrap=mark("eq-fader",""), input=document.createElement("input");
|
| 5687 |
+
input.type="range"; input.min=min; input.max=max; input.step=step; input.setAttribute("aria-label",label);
|
| 5688 |
+
input.setAttribute("aria-orientation","vertical"); wrap.append(input); return [wrap,input];
|
| 5689 |
+
}
|
| 5690 |
+
function drawModelSettings(box){
|
| 5691 |
+
const head=mark("card ms-head",""); head.append(mark("","🎚️ כוונון המודל","h2"));
|
| 5692 |
+
const pick=document.createElement("select"); pick.setAttribute("aria-label","המודל שמכווננים");
|
| 5693 |
+
for(const m of (MODELS?.models||[])){ const o=document.createElement("option"); o.value=m.id; o.textContent=m.name+(m.active?" · פעיל":""); pick.append(o); }
|
| 5694 |
+
pick.value=MS_MODEL; pick.onchange=async()=>{ if(msDirtyCount()&&!confirm("יש שינויים שלא נשמרו. לעבור מודל בלי לשמור?")){ pick.value=MS_MODEL; return; } MS=null; msMsg=""; drawManage(); await loadModelSettings(pick.value); drawManage(); };
|
| 5695 |
+
head.append(pick); box.append(head);
|
| 5696 |
+
if(msError){ box.append(mark("card setup",`ההגדרות לא זמינות: ${msError}`)); return; }
|
| 5697 |
+
if(!MS){ box.append(mark("card","טוען הגדרות…")); return; }
|
| 5698 |
+
const ro=!MS.can_edit;
|
| 5699 |
+
const intro=mark("card","");
|
| 5700 |
+
intro.append(mark("",MS.active?"המודל הזה בודק עכשיו: שמירה חלה מיד, והקולות הילידיים נמדדים מחדש.":"המודל לא פעיל כרגע: ההגדרות יחולו כשיופעל.","p"));
|
| 5701 |
+
if(!MS.stored){ intro.append(mark("setup","כדי לשמור הגדרות, צרו ב־Supabase את הטבלה model_settings (SQL Editor):","p")); const code=mark("",MS.create_sql,"code"); code.dir="ltr"; intro.append(code); }
|
| 5702 |
+
else if(ro) intro.append(mark("meta","רק מפתח/ת יכול/ה לשנות את ההגדרות; כאן הן מוצגות לקריאה.","p"));
|
| 5703 |
+
if(MS.error) intro.append(mark("setup",`ההגדרות השמורות לא תקינות ולכן לא חלות: ${MS.error}`,"p"));
|
| 5704 |
+
if(MS.updated_by) intro.append(mark("meta",`עודכן לאחרונה על ידי ${MS.updated_by}${MS.updated_at?" · "+new Date(MS.updated_at).toLocaleString("he-IL"):""}`,"p"));
|
| 5705 |
+
box.append(intro);
|
| 5706 |
+
const bar=mark("card ms-bar",""), count=mark("count",""), save=mark("btn primary","שמירה","button"), undo=mark("btn","ביטול השינויים","button"), reset=mark("btn danger","איפוס לברירת המחדל","button"), msg=mark("msg",msMsg);
|
| 5707 |
+
const refreshBar=()=>{ const n=msDirtyCount(); count.textContent=n?`${n} ${n===1?"שינוי שלא נשמר":"שינויים שלא נשמרו"}`:"אין שינויים שלא נשמרו"; count.className="count"+(n?"":" clean"); save.disabled=undo.disabled=ro||!n; reset.disabled=ro||(!Object.keys(msOverrides()).length&&!n); };
|
| 5708 |
+
const touched=()=>{ refreshBar(); msMsg=""; msg.textContent=""; };
|
| 5709 |
+
|
| 5710 |
+
/* 1. the sound equalizer: one band per sound, its threshold as a fader */
|
| 5711 |
+
const card=mark("card ms-sounds",""); card.append(mark("","ספי סימון לכל הגה","h3"));
|
| 5712 |
+
const legend=mark("ms-legend",""), l1=mark("",""), l2=mark("",""), l3=mark("",""), l4=mark("","");
|
| 5713 |
+
l1.append(mark("bad","","i"),"מתחת לסף: מסומן כטעות ומקבל טיפ"); l2.append(mark("good","","i"),"מעל הסף: עובר");
|
| 5714 |
+
l3.textContent="- - - הסף הכללי"; l4.textContent="● נורית דולקת: להגה יש סף משלו";
|
| 5715 |
+
legend.append(l1,l2,l3,l4); card.append(legend);
|
| 5716 |
+
const eq=mark("eq",""), info=mark("eq-info","מעבר עם העכבר או המקלדת על פס מציג כאן את הפרטים שלו."), painters=[], generalLines=[];
|
| 5717 |
+
eq.append(eqScale());
|
| 5718 |
+
for(const g of MS.sounds){
|
| 5719 |
+
const group=mark("eq-group",""), bands=mark("eq-bands","");
|
| 5720 |
+
for(const s of g.sounds){
|
| 5721 |
+
const band=mark("eq-band",""), val=mark("eq-val",""), [fader,input]=eqFader(0,100,1,`סף הסימון של ${s.label}`), line=mark("eq-general","");
|
| 5722 |
+
fader.append(line); generalLines.push(line);
|
| 5723 |
+
const [he,ar]=s.label.split(" "), letter=mark("eq-letter",he); letter.append(mark("",ar||"","small"));
|
| 5724 |
+
const led=mark("eq-led","משלו","button"), resetBtn=mark("eq-reset","↺","button"); resetBtn.title=`ברירת המחדל: ${s.default==null?"הסף הכללי":s.default}`;
|
| 5725 |
+
const describe=()=>{ const v=msSoundValue(s); info.replaceChildren(mark("",s.label,"b"),` · ${s.count?`${s.count.toLocaleString("he-IL")} מופעים במשפטים`:"לא מופיע במשפטים"} · ${v==null?`משתמש בסף הכללי (${Math.round(msGeneral())})`:`סף משלו: ${Math.round(v)}`} · ברירת מחדל: ${s.default==null?"הסף הכללי":s.default}`); };
|
| 5726 |
+
const paint=()=>{ const v=msSoundValue(s), eff=v==null?msGeneral():v;
|
| 5727 |
+
input.value=eff; input.style.setProperty("--t",`${eff}%`); input.disabled=ro||v==null; led.disabled=ro;
|
| 5728 |
+
led.setAttribute("aria-pressed",v!=null); led.title=v!=null?"לחיצה: חזרה לסף הכללי":"לחיצה: סף משלו להגה הזה";
|
| 5729 |
+
val.textContent=v==null?"כללי":String(Math.round(v)); val.className="eq-val"+(v==null?" inherit":"");
|
| 5730 |
+
band.classList.toggle("dirty",s.sound in MS_DRAFT.sounds); resetBtn.hidden=ro||v===s.default; };
|
| 5731 |
+
const set=v=>{ if(v===s.value) delete MS_DRAFT.sounds[s.sound]; else MS_DRAFT.sounds[s.sound]=v; paint(); describe(); touched(); };
|
| 5732 |
+
input.oninput=()=>set(+input.value);
|
| 5733 |
+
led.onclick=()=>set(msSoundValue(s)==null?Math.round(msGeneral()):null);
|
| 5734 |
+
resetBtn.onclick=()=>set(s.default);
|
| 5735 |
+
band.onmouseenter=describe; band.addEventListener("focusin",describe);
|
| 5736 |
+
band.title=`${s.label} · ${s.count?s.count.toLocaleString("he-IL")+" מופעים":"לא מופיע במשפטים"}`;
|
| 5737 |
+
band.append(resetBtn,val,fader,letter,led); bands.append(band); painters.push(paint); paint();
|
| 5738 |
+
}
|
| 5739 |
+
group.append(bands,mark("eq-name",g.group)); eq.append(group);
|
| 5740 |
+
}
|
| 5741 |
+
const placeGeneral=()=>{ const gv=msGeneral(); for(const l of generalLines) l.style.bottom=`calc(${gv}% - 1px)`; };
|
| 5742 |
+
placeGeneral();
|
| 5743 |
+
card.append(eq,info); box.append(card);
|
| 5744 |
+
|
| 5745 |
+
/* 2. the other settings: a fader bank per group; choices as short menus in the same row */
|
| 5746 |
+
const groups=[...new Set(MS.fields.map(f=>f.group))];
|
| 5747 |
+
for(const gid of groups){
|
| 5748 |
+
const fields=MS.fields.filter(f=>f.group===gid), gcard=mark("card ms-group","");
|
| 5749 |
+
gcard.append(mark("",fields[0].group_label,"h3"));
|
| 5750 |
+
const geq=mark("eq",""), bands=mark("eq-bands",""), ginfo=mark("eq-info","מעבר על פס מציג כאן מה הוא עושה.");
|
| 5751 |
+
for(const f of fields){
|
| 5752 |
+
const band=mark("eq-band wide",""), val=mark("eq-val",""), label=mark("eq-label",f.label), resetBtn=mark("eq-reset","↺","button");
|
| 5753 |
+
resetBtn.title=`חזרה לברירת המחדל (${fmtSetting(f,f.default)})`;
|
| 5754 |
+
const describe=()=>ginfo.replaceChildren(mark("",f.label,"b"),` · ${f.help} · ברירת מחדל: ${fmtSetting(f,f.default)}`);
|
| 5755 |
+
let paint;
|
| 5756 |
+
const set=v=>{ if(v===f.value) delete MS_DRAFT.fields[f.key]; else MS_DRAFT.fields[f.key]=v; paint(); describe(); touched();
|
| 5757 |
+
if(f.key==="flag_below"){ placeGeneral(); painters.forEach(p=>p()); } };
|
| 5758 |
+
if(f.kind==="choice"||f.kind==="window"){
|
| 5759 |
+
const holder=mark("eq-choice",""), sel=document.createElement("select"); sel.disabled=ro; sel.setAttribute("aria-label",f.label);
|
| 5760 |
+
const opts=f.kind==="choice"?f.choices.map(c=>[c,c]):[["wide","רחב"],...Array.from({length:f.max-f.min+1},(_,i)=>[String(f.min+i),`${f.min+i} פריימים`])];
|
| 5761 |
+
for(const [v,t] of opts){ const o=document.createElement("option"); o.value=v; o.textContent=t; sel.append(o); }
|
| 5762 |
+
sel.onchange=()=>set(f.kind==="choice"?sel.value:sel.value==="wide"?null:+sel.value);
|
| 5763 |
+
paint=()=>{ const v=msFieldValue(f); sel.value=f.kind==="choice"?v:v==null?"wide":String(v); val.textContent=fmtSetting(f,v); band.classList.toggle("dirty",f.key in MS_DRAFT.fields); resetBtn.hidden=ro||v===f.default; };
|
| 5764 |
+
holder.append(sel); band.append(resetBtn,holder,label); // the menu shows the value itself
|
| 5765 |
+
}else{
|
| 5766 |
+
const [fader,input]=eqFader(f.min,f.max,f.step,f.label); fader.classList.add("plain"); input.disabled=ro;
|
| 5767 |
+
const read=()=>{ const v=Number(input.value); return Math.min(f.max,Math.max(f.min,f.kind==="int"?Math.round(v):Math.round(v/f.step)*f.step)); };
|
| 5768 |
+
input.oninput=()=>set(+read().toFixed(4));
|
| 5769 |
+
paint=()=>{ const v=msFieldValue(f); input.value=v; input.style.setProperty("--t",`${100*(v-f.min)/(f.max-f.min)}%`); val.textContent=fmtSetting(f,v); band.classList.toggle("dirty",f.key in MS_DRAFT.fields); resetBtn.hidden=ro||v===f.default; };
|
| 5770 |
+
band.append(resetBtn,val,fader,label);
|
| 5771 |
+
}
|
| 5772 |
+
resetBtn.onclick=()=>set(f.default);
|
| 5773 |
+
band.onmouseenter=describe; band.addEventListener("focusin",describe); band.title=f.help;
|
| 5774 |
+
bands.append(band); paint();
|
| 5775 |
+
}
|
| 5776 |
+
geq.append(bands); gcard.append(geq,ginfo); box.append(gcard);
|
| 5777 |
+
}
|
| 5778 |
+
|
| 5779 |
+
/* 3. save bar */
|
| 5780 |
+
save.onclick=()=>saveModelSettings(msOverrides(),msg);
|
| 5781 |
+
undo.onclick=()=>{ MS_DRAFT={fields:{},sounds:{}}; msMsg=""; drawManage(); };
|
| 5782 |
+
reset.onclick=()=>{ if(confirm("להחזיר את כל ההגדרות של המודל הזה לברירת המחדל?")) saveModelSettings({},msg); };
|
| 5783 |
+
bar.append(count,save,undo,reset,msg); box.append(bar); refreshBar();
|
| 5784 |
+
}
|
| 5785 |
+
function drawModels(){
|
| 5786 |
+
const box=$("mModels"); box.replaceChildren();
|
| 5787 |
+
if(mMode!=="models") return;
|
| 5788 |
+
if(modelsError){ const card=mark("card",""); card.append(mark("","מודלים","h2"),mark("setup",`רשימת המודלים לא זמינה: ${modelsError}`,"p")); box.append(card); return; }
|
| 5789 |
+
if(!MODELS){ box.append(mark("card","טוען את רשימת המודלים…")); return; }
|
| 5790 |
+
const {models,active,switch:sw,can_switch,default:start}=MODELS, current=models.find(m=>m.active)||{name:active,id:active};
|
| 5791 |
+
const measured=models.filter(m=>m.metrics), best=measured.reduce((a,m)=>!a||m.metrics.per<a.metrics.per?m:a,null);
|
| 5792 |
+
/* 1. what is scoring now */
|
| 5793 |
+
const now=mark("card mdl-now",""), icon=mark("mdl-icon","🎙️"), text=mark("mdl-text","");
|
| 5794 |
+
text.append(mark("meta","המודל שבודק עכשיו את ההקלטות","span"),mark("",current.name,"h2"),mark("",current.id,"code"));
|
| 5795 |
+
const state=sw.state==="loading"?(()=>{ const p=mark("mdl-pill wait",""); p.append(mark("mdl-spin",""),`טוען את ${(models.find(m=>m.id===sw.target)||{name:sw.target}).name}…`); return p; })()
|
| 5796 |
+
:sw.state==="error"?mark("mdl-pill bad","⚠ הטעינה האחרונה נכשלה"):mark("mdl-pill on","✓ פעיל");
|
| 5797 |
+
now.append(icon,text,state); box.append(now);
|
| 5798 |
+
if(sw.state==="error"){ const err=mark("card",""); err.append(mark("","הטעינה נכשלה; המודל הקודם ממשיך לבדוק.","b"),mark("",sw.error,"code")); box.append(err); }
|
| 5799 |
+
/* 2. the comparison: phoneme accuracy, one bar per measured model, best first */
|
| 5800 |
+
if(measured.length>1){
|
| 5801 |
+
const cmp=mark("card mdl-cmp","");
|
| 5802 |
+
cmp.append(mark("","השוואה: דיוק פונמות","h2"),mark("mdl-note","כמה מהפונמות שדוברים ילידים אמרו המודל שמע נכון, ב־255 משפטי Minerva שהמודלים לא ראו באימון. גבוה יותר טוב יותר.","p"));
|
| 5803 |
+
for(const m of [...measured].sort((a,b)=>a.metrics.per-b.metrics.per)){
|
| 5804 |
+
const acc=1-m.metrics.per, row=mark("mdl-row",""), name=mark("",m.name,"b");
|
| 5805 |
+
if(m.active) name.append(mark("meta"," · פעיל","span"));
|
| 5806 |
+
const track=mark("mdl-track",""), fill=mark("mdl-fill",""); fill.style.width=`${Math.round(acc*100)}%`; track.append(fill);
|
| 5807 |
+
row.title=`${m.name}: ${Math.round(acc*100)}% נכון · שגיאת פונמות ${Math.round(m.metrics.per*100)}% · שגיאת עיצורים ${Math.round(m.metrics.consonant_per*100)}%`;
|
| 5808 |
+
row.append(name,track,mark("mdl-val",`${Math.round(acc*100)}%`)); cmp.append(row);
|
| 5809 |
+
}
|
| 5810 |
+
box.append(cmp);
|
| 5811 |
+
}
|
| 5812 |
+
/* 3. one card per model */
|
| 5813 |
+
const grid=mark("mdl-grid","");
|
| 5814 |
+
for(const m of models){
|
| 5815 |
+
const card=mark(`card mdl-card${m.active?" active":""}${m.available?"":" unavail"}`,""), head=mark("mdl-head","");
|
| 5816 |
+
head.append(mark("",m.name,"h3"));
|
| 5817 |
+
if(m.active) head.append(mark("mdl-pill on","✓ פעיל"));
|
| 5818 |
+
else if(sw.state==="loading"&&sw.target===m.id){ const p=mark("mdl-pill wait",""); p.append(mark("mdl-spin",""),"נטען…"); head.append(p); }
|
| 5819 |
+
if(best&&m.id===best.id) head.append(mark("mdl-pill best","★ הכי מדויק"));
|
| 5820 |
+
if(!m.available) head.append(mark("mdl-pill off","לא זמין בשרת הזה"));
|
| 5821 |
+
card.append(head,mark("",m.id,"code"),mark("mdl-sum",m.summary,"p"));
|
| 5822 |
+
if(m.metrics){
|
| 5823 |
+
const hero=mark("mdl-hero",""), ht=mark("mdl-hero-text","");
|
| 5824 |
+
ht.append(mark("","דיוק פונמות","b"),mark("",`שגיאת פונמות ${Math.round(m.metrics.per*100)}%`,"span"),mark("",`שגיאת עיצורים ${Math.round(m.metrics.consonant_per*100)}%`,"span"));
|
| 5825 |
+
hero.append(modelRing(1-m.metrics.per),ht); card.append(hero);
|
| 5826 |
+
const bars=mark("mdl-bars",""); bars.append(mark("meta","כמה פעמים שמע נכון את ההגים הקשים","span"));
|
| 5827 |
+
for(const [key,label] of MODEL_SOUNDS) bars.append(modelBar(label,m.metrics[key]));
|
| 5828 |
+
card.append(bars);
|
| 5829 |
+
}
|
| 5830 |
+
const facts=mark("mdl-facts","");
|
| 5831 |
+
if(m.family) facts.append(mark("",`🧠 ${m.family}`,"span"));
|
| 5832 |
+
if(m.trained!=null) facts.append(mark("",m.trained?"🎯 מאומן על ערבית פלסטינית":"📦 כפי שפורסם","span"));
|
| 5833 |
+
if(m.speed) facts.append(mark("",`⚡ ${[m.speed.gpu!=null?`${m.speed.gpu} ש׳ להקלטה ב־GPU`:"",m.speed.cpu!=null?`${m.speed.cpu} ש׳ במעבד (2 ליבות)`:""].filter(Boolean).join(" · ")}`,"span"));
|
| 5834 |
+
if(m.free_space!=null) facts.append(mark("",m.free_space?"✓ רץ על השרת החינמי":"✗ איטי מדי לשרת החינמי","span"));
|
| 5835 |
+
if(m.id===start) facts.append(mark("","⏻ נטען בהפעלת השרת","span"));
|
| 5836 |
+
if(facts.childElementCount) card.append(facts);
|
| 5837 |
+
const act=mark("mdl-act",""), msg=mark("why","");
|
| 5838 |
+
if(m.active) act.append(mark("meta","המודל הזה בודק עכשיו","span"));
|
| 5839 |
+
else if(!m.available) act.append(mark("why",m.why,"span"));
|
| 5840 |
+
else if(!can_switch) act.append(mark("meta","רק מפתח/ת יכול/ה להחליף מודל","span"));
|
| 5841 |
+
else{ const b=mark("btn primary","הפעלת המודל","button"); b.disabled=sw.state==="loading"; b.onclick=()=>{ if(confirm(`להחליף את המודל ל־${m.name}? כל ההקלטות מעכשיו ייבדקו בו.`)) switchModel(m.id,b,msg); }; act.append(b,msg); }
|
| 5842 |
+
const tune=mark("btn","🎚️ כוונון","button"); tune.onclick=async()=>{ if(msDirtyCount()&&!confirm("יש שינויים שלא נשמרו. לעבור מודל בלי לשמור?")) return; MS=null; msMsg=""; MS_MODEL=m.id; drawManage(); await loadModelSettings(m.id); drawManage(); document.querySelector(".ms-head")?.scrollIntoView({behavior:"smooth",block:"start"}); };
|
| 5843 |
+
act.append(tune);
|
| 5844 |
+
card.append(act); grid.append(card);
|
| 5845 |
+
}
|
| 5846 |
+
box.append(grid);
|
| 5847 |
+
drawModelSettings(box);
|
| 5848 |
+
box.append(mark("mdl-note",`ההחלפה נשמרת עד הפעלה מחדש של השרת, ואז נטען שוב ${start}. כדי לקבע מודל: MODEL_ID בקובץ .env או במשתני ה־Space. ספי הסימון המובנים כוילו רק למודל Facebook; מודל אחר מתחיל מהסף הכללי 50, ואפשר לכוונן אותו ב־🎚️ כוונון המודל. ההגדרות נשמרות לכל מודל בנפרד ונשארות גם אחרי הפעלה מחדש.`,"p"));
|
| 5849 |
+
}
|
| 5850 |
async function loadAccess(){
|
| 5851 |
accessError="";
|
| 5852 |
try{
|
|
|
|
| 5928 |
// progress; only the class's own lessons count); the totals beside their own fields (`tries` stays the per-sentence one)
|
| 5929 |
const students=CLASS.students.filter(s=>!klass||klass.name in s.classes).map(s=>{ const t=stuTally(s,listed);
|
| 5930 |
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}; });
|
| 5931 |
+
if(!["classes","students","content","flags","access","models"].includes(mMode)) mMode=classes.length?"students":"classes";
|
| 5932 |
+
$("mModes").hidden=false; for(const mode of ["classes","content","flags","access","models"]) $("manage").classList.toggle(mode,mMode===mode);
|
| 5933 |
for(const b of $("mModes").children) b.setAttribute("aria-selected",b.dataset.mode===mMode);
|
| 5934 |
+
drawClasses(classes); drawContent(); drawFlags(); drawAccess(); drawModels(); drawTabs(classes); drawHead(klass,students);
|
| 5935 |
if(klass||!classes.length) drawLessons(students,listed); else{ $("mLessons").innerHTML=""; $("mLessons").hidden=true; }
|
| 5936 |
drawRoster(klass,students,listed);
|
| 5937 |
const one=students.find(s=>s.email===shownStudent); // a student who left the class has no screen in it
|
|
|
|
| 5943 |
mMode=mode; store.set("ihki.mmode",mode); drawManage();
|
| 5944 |
if(mode==="flags"&&!flagsLoaded){ await loadFlags(); drawManage(); }
|
| 5945 |
if(mode==="access"){ await loadAccess(); drawManage(); }
|
| 5946 |
+
if(mode==="models"){ await loadModels(); if(!MS&&MODELS) await loadModelSettings(MODELS.active); drawManage(); }
|
| 5947 |
}
|
| 5948 |
for(const b of $("mModes").children) b.onclick=()=>showMode(b.dataset.mode);
|
| 5949 |
setInterval(()=>{
|
|
|
|
| 6129 |
const group=document.createElement("details"), summary=document.createElement("summary");
|
| 6130 |
const key=`date-${day}`, label=dayLabel(day), people=new Set(flags.map(f=>f.email||"")).size;
|
| 6131 |
group.className="flag-group"; group.open=flagGroupOpen[key]===true; group.ontoggle=()=>{ flagGroupOpen[key]=group.open; };
|
| 6132 |
+
const models=[...new Set(flags.map(f=>f.model||"לא ידוע"))].join(", ");
|
| 6133 |
+
summary.append(mark("",label,"b"),mark("meta",` · ${flags.length} ${flags.length===1?"דיווח":"דיווחים"} · ${people} ${people===1?"מדווח/ת":"מדווחים"} · מודל: ${models}`)); group.append(summary); box.append(group);
|
| 6134 |
const table=mark("flag-patterns flag-pending","","table"), headRow=document.createElement("tr");
|
| 6135 |
for(const x of ["ציון","מה התלמיד/ה אמר/ה","מה המודל שמע","אבחון ל־pipeline","","",""]) headRow.append(mark("",x,"th"));
|
| 6136 |
table.append(headRow); group.append(table);
|
|
|
|
| 6169 |
toggle.onclick=()=>{ detail.hidden=!detail.hidden; flagGroupOpen[openKey]=!detail.hidden; toggle.textContent=detail.hidden?"פרטים ▾":"פרטים ▴"; };
|
| 6170 |
toggleCell.append(toggle);
|
| 6171 |
const reporter=mark("meta",`${f.email||"ללא משתמש"}`,"p"), age=flagAge(f.created_at); if(age) reporter.append(" · ",age);
|
| 6172 |
+
reporter.append(" · ",`מודל: ${f.model||"לא ידוע"}`);
|
| 6173 |
detailCell.append(reporter);
|
| 6174 |
if(f.note) detailCell.append(mark("",`הערת המדווח/ת: ${f.note}`,"p"));
|
| 6175 |
const field=document.createElement("fieldset"); field.append(mark("","אילו אבחנות של המערכת היו שגויות?","legend"));
|
|
|
|
| 7513 |
labMode(store.get("ihki.labMode","test"));
|
| 7514 |
}
|
| 7515 |
function labMode(mode){
|
| 7516 |
+
if(!["quick","test","record","flags","minerva","results"].includes(mode)) mode="quick";
|
| 7517 |
store.set("ihki.labMode",mode);
|
| 7518 |
for(const b of $("labModes").children) b.setAttribute("aria-selected",b.dataset.mode===mode?"true":"false");
|
| 7519 |
+
for(const m of ["quick","test","record","flags","minerva","results"]) $("lab").classList.toggle(m,m===mode);
|
| 7520 |
+
if(mode==="quick") drawQuickQuiz();
|
| 7521 |
if(mode==="test"){ drawWizard(); loadTtsVoices(); }
|
| 7522 |
if(mode==="flags"&&!labFlags) loadLabFlags();
|
| 7523 |
if(mode==="minerva") loadMinerva();
|
| 7524 |
if(mode==="results") loadLabResults();
|
| 7525 |
}
|
| 7526 |
for(const b of $("labModes").children) b.onclick=()=>labMode(b.dataset.mode);
|
| 7527 |
+
|
| 7528 |
+
/* Ten single-take prompts for a quick Hebrew-speaker comparison. Nothing is persisted: each blob goes directly to
|
| 7529 |
+
the existing developer-only model comparison endpoint and the compact summary stays in this page. */
|
| 7530 |
+
let quickAt=0, quickRec=null, quickRows={};
|
| 7531 |
+
function drawQuickQuiz(){
|
| 7532 |
+
const items=LAB?.quick_quiz||[], it=items[quickAt]; if(!it) return;
|
| 7533 |
+
$("quickProgress").textContent=`שאלה ${quickAt+1} מתוך ${items.length}`;
|
| 7534 |
+
$("quickAr").textContent=it.ar; setTr($("quickTr"),it.tr); $("quickHe").textContent=it.he;
|
| 7535 |
+
$("quickPrev").disabled=quickAt===0; $("quickNext").disabled=quickAt===items.length-1;
|
| 7536 |
+
$("quickOut").replaceChildren(); $("quickState").textContent=quickRows[it.id]?"השאלה הושלמה — אפשר להקליט שוב":"מוכנים להקלטה";
|
| 7537 |
+
drawQuickSummary();
|
| 7538 |
+
}
|
| 7539 |
+
function drawQuickSummary(){
|
| 7540 |
+
const table=$("quickSummary"); table.replaceChildren();
|
| 7541 |
+
const head=document.createElement("tr"); for(const h of ["#","מילה","Facebook","wav2vec2 מאומן","POWSM ONNX"]) head.append(mark("",h,"th")); table.append(head);
|
| 7542 |
+
for(const it of (LAB?.quick_quiz||[])){
|
| 7543 |
+
const tr=document.createElement("tr"), rows=quickRows[it.id]||[], cells=[
|
| 7544 |
+
rows.find(r=>r.model==="facebook/wav2vec2-xlsr-53-espeak-cv-ft"),
|
| 7545 |
+
rows.find(r=>r.model==="checkpoints/ihki-ft-minerva"), rows.find(r=>r.model?.includes("powsm-ft-shortpad"))];
|
| 7546 |
+
tr.onclick=()=>{quickAt=it.number-1;drawQuickQuiz()};
|
| 7547 |
+
for(const value of [it.number,it.ar,...cells.map(row=>row?.error?"שגיאה":row?.score==null?"—":Math.round(row.score))]) tr.append(mark("",value,"td"));
|
| 7548 |
+
table.append(tr);
|
| 7549 |
+
}
|
| 7550 |
+
}
|
| 7551 |
+
$("quickPrev").onclick=()=>{ if(quickAt>0){quickAt--;drawQuickQuiz()} };
|
| 7552 |
+
$("quickNext").onclick=()=>{ if(quickAt<(LAB?.quick_quiz?.length||1)-1){quickAt++;drawQuickQuiz()} };
|
| 7553 |
+
$("quickReset").onclick=()=>{ quickRows={}; quickAt=0; drawQuickQuiz(); };
|
| 7554 |
+
$("quickMic").onclick=async()=>{
|
| 7555 |
+
if(quickRec){ quickRec.stop(); return; }
|
| 7556 |
+
if(!navigator.mediaDevices||!window.MediaRecorder){ $("quickState").textContent="הדפדפן הזה אינו תומך בהקלטה."; return; }
|
| 7557 |
+
const item=LAB.quick_quiz[quickAt], button=$("quickMic");
|
| 7558 |
+
try{
|
| 7559 |
+
const stream=await navigator.mediaDevices.getUserMedia({audio:true}), chunks=[], type=pickType();
|
| 7560 |
+
const rec=quickRec=new MediaRecorder(stream,type?{mimeType:type}:{});
|
| 7561 |
+
rec.ondataavailable=e=>{if(e.data.size) chunks.push(e.data)};
|
| 7562 |
+
rec.onstop=async()=>{
|
| 7563 |
+
stream.getTracks().forEach(t=>t.stop()); quickRec=null; button.classList.remove("live"); button.disabled=true;
|
| 7564 |
+
$("quickState").textContent="בודק בשלושת המודלים… הטעינה הראשונה עשויה ל��חת עד חצי דקה";
|
| 7565 |
+
try{
|
| 7566 |
+
const blob=new Blob(chunks,{type:rec.mimeType||type||"audio/webm"}), fd=new FormData(); fd.append("item",item.id); fd.append("audio",blob,"rec");
|
| 7567 |
+
const res=await api("/api/admin/compare-models",{method:"POST",body:fd}), data=await res.json().catch(()=>({}));
|
| 7568 |
+
if(!res.ok) throw new Error(data.detail||res.status);
|
| 7569 |
+
quickRows[item.id]=data.models; drawComparison(data.models,"quickOut"); drawQuickSummary();
|
| 7570 |
+
$("quickState").textContent="הושלם";
|
| 7571 |
+
}catch(err){ $("quickState").textContent="הבדיקה נכשלה: "+err.message; }
|
| 7572 |
+
finally{button.disabled=false}
|
| 7573 |
+
};
|
| 7574 |
+
await listenCue(); rec.start(); button.classList.add("live"); $("quickState").textContent="מקליט… לחצו שוב לסיום";
|
| 7575 |
+
}catch(err){ quickRec=null; $("quickState").textContent="לא ניתן לפתוח את המיקרופון: "+err.message; }
|
| 7576 |
+
};
|
| 7577 |
const labCount=id=>{ const c=LAB.counts[id]||{}; return (c.correct||0)+(c.mistake||0); };
|
| 7578 |
function drawLabList(){
|
| 7579 |
const box=$("labList"); box.replaceChildren();
|
tests/test_lab.py
CHANGED
|
@@ -5,7 +5,7 @@ import numpy as np
|
|
| 5 |
from test_scoring import emissions, scorer_for
|
| 6 |
|
| 7 |
from app.auth import AuthUnavailable
|
| 8 |
-
from app.lab import ITEMS, benchmark, public_items, still_flagged
|
| 9 |
from app.translit import to_hebrew
|
| 10 |
|
| 11 |
|
|
@@ -18,6 +18,15 @@ def tone_wav():
|
|
| 18 |
return buf.getvalue()
|
| 19 |
|
| 20 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
class NoTTS:
|
| 22 |
"""No native baseline: the stub model would score the voice as it scores the learner, and forgive everything."""
|
| 23 |
|
|
|
|
| 5 |
from test_scoring import emissions, scorer_for
|
| 6 |
|
| 7 |
from app.auth import AuthUnavailable
|
| 8 |
+
from app.lab import ITEMS, QUICK_QUIZ, benchmark, public_items, public_quick_quiz, still_flagged
|
| 9 |
from app.translit import to_hebrew
|
| 10 |
|
| 11 |
|
|
|
|
| 18 |
return buf.getvalue()
|
| 19 |
|
| 20 |
|
| 21 |
+
def test_quick_quiz_is_a_ten_word_hebrew_speaker_benchmark():
|
| 22 |
+
public = public_quick_quiz()
|
| 23 |
+
assert len(QUICK_QUIZ) == len(public) == 10
|
| 24 |
+
assert [item["number"] for item in public] == list(range(1, 11))
|
| 25 |
+
assert {"ħ", "ʕ", "x", "a", "aː"}.issubset({item["focus"] for item in public})
|
| 26 |
+
zaman = next(item for item in QUICK_QUIZ if item["id"] == "quick-zaman")
|
| 27 |
+
assert zaman["variants"][0] == ("زمن", "z a m a n")
|
| 28 |
+
|
| 29 |
+
|
| 30 |
class NoTTS:
|
| 31 |
"""No native baseline: the stub model would score the voice as it scores the learner, and forgive everything."""
|
| 32 |
|
tests/test_models_tab.py
ADDED
|
@@ -0,0 +1,265 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The panel's "מודלים" tab (app/models.py, /api/admin/models): what each model measured, and the developer's switch."""
|
| 2 |
+
import time
|
| 3 |
+
|
| 4 |
+
from fastapi.testclient import TestClient
|
| 5 |
+
from test_keystore import AdminAuth, KeyAuth, bearer
|
| 6 |
+
from test_scoring import emissions, scorer_for
|
| 7 |
+
|
| 8 |
+
import app.main
|
| 9 |
+
from app.main import create_app
|
| 10 |
+
from app.models import CATALOG
|
| 11 |
+
|
| 12 |
+
BASE = "facebook/wav2vec2-xlsr-53-espeak-cv-ft"
|
| 13 |
+
FT = "checkpoints/ihki-ft-minerva"
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def client(auth):
|
| 17 |
+
return TestClient(create_app(scorer_for(emissions(["ħ", "aː", "l"])), auth=auth))
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def wait_switch(c, headers, seconds=5.0):
|
| 21 |
+
for _ in range(int(seconds / 0.05)):
|
| 22 |
+
data = c.get("/api/admin/models", headers=headers).json()
|
| 23 |
+
if data["switch"]["state"] != "loading":
|
| 24 |
+
return data
|
| 25 |
+
time.sleep(0.05)
|
| 26 |
+
raise AssertionError("the switch never finished")
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def test_the_catalog_shows_every_model_with_its_numbers_and_the_active_one(monkeypatch):
|
| 30 |
+
monkeypatch.setattr(app.main, "MODEL_ID", BASE)
|
| 31 |
+
with client(KeyAuth()) as c:
|
| 32 |
+
data = c.get("/api/admin/models", headers=bearer("teacher")).json()
|
| 33 |
+
assert data["active"] == BASE and data["can_switch"] is True
|
| 34 |
+
ids = [m["id"] for m in data["models"]]
|
| 35 |
+
assert ids == [m["id"] for m in CATALOG]
|
| 36 |
+
active = [m for m in data["models"] if m["active"]]
|
| 37 |
+
assert [m["id"] for m in active] == [BASE]
|
| 38 |
+
assert all(0 <= m["metrics"]["per"] <= 1 for m in data["models"])
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def test_a_model_set_in_model_id_but_not_in_the_catalog_is_listed_first(monkeypatch):
|
| 42 |
+
monkeypatch.setattr(app.main, "MODEL_ID", "someone/else")
|
| 43 |
+
with client(KeyAuth()) as c:
|
| 44 |
+
data = c.get("/api/admin/models", headers=bearer("teacher")).json()
|
| 45 |
+
assert data["models"][0]["id"] == "someone/else" and data["models"][0]["active"]
|
| 46 |
+
assert data["models"][0]["metrics"] is None
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def test_an_admin_sees_the_models_but_cannot_switch(monkeypatch):
|
| 50 |
+
monkeypatch.setattr(app.main, "MODEL_ID", BASE)
|
| 51 |
+
with client(AdminAuth()) as c:
|
| 52 |
+
data = c.get("/api/admin/models", headers=bearer("teacher")).json()
|
| 53 |
+
assert data["can_switch"] is False
|
| 54 |
+
res = c.put("/api/admin/models/active", json={"model_id": FT}, headers=bearer("teacher"))
|
| 55 |
+
assert res.status_code == 403
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def test_switching_loads_the_new_model_and_swaps_it_in(monkeypatch, tmp_path):
|
| 59 |
+
monkeypatch.setattr(app.main, "MODEL_ID", BASE)
|
| 60 |
+
monkeypatch.setattr(app.main, "model_availability", lambda model_id: (True, ""))
|
| 61 |
+
loaded = []
|
| 62 |
+
new = scorer_for(emissions(["ħ", "aː", "l"]))
|
| 63 |
+
monkeypatch.setattr(app.main, "load_scorer", lambda model_id: loaded.append(model_id) or new)
|
| 64 |
+
auth = KeyAuth()
|
| 65 |
+
with client(auth) as c:
|
| 66 |
+
res = c.put("/api/admin/models/active", json={"model_id": FT}, headers=bearer("teacher"))
|
| 67 |
+
assert res.status_code == 200
|
| 68 |
+
data = wait_switch(c, bearer("teacher"))
|
| 69 |
+
assert loaded == [FT]
|
| 70 |
+
assert data["active"] == FT and data["switch"]["state"] == "idle"
|
| 71 |
+
assert c.app.state.scorer is new
|
| 72 |
+
assert c.get("/api/health").json()["model"] == FT
|
| 73 |
+
assert any(details == {"model": FT, "action": "switch"} for _, _, details in auth.events)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def test_a_failed_load_keeps_the_running_model_and_says_why(monkeypatch):
|
| 77 |
+
monkeypatch.setattr(app.main, "MODEL_ID", BASE)
|
| 78 |
+
monkeypatch.setattr(app.main, "model_availability", lambda model_id: (True, ""))
|
| 79 |
+
|
| 80 |
+
def broken(model_id):
|
| 81 |
+
raise OSError("no such model")
|
| 82 |
+
monkeypatch.setattr(app.main, "load_scorer", broken)
|
| 83 |
+
with client(KeyAuth()) as c:
|
| 84 |
+
before = c.app.state.scorer
|
| 85 |
+
c.put("/api/admin/models/active", json={"model_id": FT}, headers=bearer("teacher"))
|
| 86 |
+
data = wait_switch(c, bearer("teacher"))
|
| 87 |
+
assert data["active"] == BASE and data["switch"]["state"] == "error"
|
| 88 |
+
assert "no such model" in data["switch"]["error"]
|
| 89 |
+
assert c.app.state.scorer is before
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def test_unknown_or_unavailable_models_are_refused(monkeypatch):
|
| 93 |
+
monkeypatch.setattr(app.main, "MODEL_ID", BASE)
|
| 94 |
+
monkeypatch.setattr(app.main, "model_availability", lambda model_id: (False, "קובץ המודל לא נמצא בשרת"))
|
| 95 |
+
with client(KeyAuth()) as c:
|
| 96 |
+
assert c.put("/api/admin/models/active", json={"model_id": "evil/model"},
|
| 97 |
+
headers=bearer("teacher")).status_code == 400
|
| 98 |
+
res = c.put("/api/admin/models/active", json={"model_id": FT}, headers=bearer("teacher"))
|
| 99 |
+
assert res.status_code == 409 and "לא נמצא" in res.json()["detail"]
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
# ---- the scorer's settings per model ----
|
| 103 |
+
|
| 104 |
+
class SettingsAuth(KeyAuth):
|
| 105 |
+
def __init__(self, table=True):
|
| 106 |
+
super().__init__()
|
| 107 |
+
self.settings_rows, self.settings_table = {}, table
|
| 108 |
+
|
| 109 |
+
def model_settings(self):
|
| 110 |
+
if not self.settings_table:
|
| 111 |
+
raise app.main.AuthUnavailable("Supabase answered 404: relation model_settings does not exist")
|
| 112 |
+
return list(self.settings_rows.values())
|
| 113 |
+
|
| 114 |
+
def set_model_settings(self, model, settings, by):
|
| 115 |
+
self.settings_rows[model] = {"model": model, "settings": settings, "updated_by": by,
|
| 116 |
+
"updated_at": "2026-10-25T12:00:00+00:00"}
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def test_settings_show_each_default_and_the_base_models_built_in_ħ_threshold(monkeypatch):
|
| 120 |
+
monkeypatch.setattr(app.main, "MODEL_ID", BASE)
|
| 121 |
+
with client(SettingsAuth()) as c:
|
| 122 |
+
data = c.get(f"/api/admin/model-settings?model={BASE}", headers=bearer("teacher")).json()
|
| 123 |
+
assert data["stored"] and data["can_edit"] and data["active"]
|
| 124 |
+
flag = next(f for f in data["fields"] if f["key"] == "flag_below")
|
| 125 |
+
assert flag["default"] == 50.0 and flag["value"] == 50.0 and not flag["changed"]
|
| 126 |
+
sounds = {s["sound"]: s for g in data["sounds"] for s in g["sounds"]}
|
| 127 |
+
assert sounds["ħ"]["default"] == 20.0 and sounds["ʕ"]["default"] is None
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def test_saving_settings_for_the_active_model_applies_them_at_once(monkeypatch):
|
| 131 |
+
monkeypatch.setattr(app.main, "MODEL_ID", BASE)
|
| 132 |
+
auth = SettingsAuth()
|
| 133 |
+
with client(auth) as c:
|
| 134 |
+
res = c.put("/api/admin/model-settings", headers=bearer("teacher"), json={
|
| 135 |
+
"model": BASE, "settings": {"flag_below": 42, "gop.leniency": 0.5, "flag_below_sound": {"ħ": None, "ʕ": 35}}})
|
| 136 |
+
assert res.status_code == 200, res.text
|
| 137 |
+
cfg = c.app.state.scorer.cfg
|
| 138 |
+
assert cfg.flag_below == 42 and cfg.gop.leniency == 0.5
|
| 139 |
+
assert "ħ" not in cfg.flag_below_sound and cfg.flag_below_sound["ʕ"] == 35
|
| 140 |
+
data = res.json()
|
| 141 |
+
assert next(f for f in data["fields"] if f["key"] == "flag_below")["changed"]
|
| 142 |
+
assert auth.settings_rows[BASE]["settings"]["flag_below"] == 42
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def test_settings_for_another_model_wait_until_it_is_switched_on(monkeypatch):
|
| 146 |
+
monkeypatch.setattr(app.main, "MODEL_ID", BASE)
|
| 147 |
+
monkeypatch.setattr(app.main, "model_availability", lambda model_id: (True, ""))
|
| 148 |
+
monkeypatch.setattr(app.main, "load_scorer", lambda model_id: scorer_for(emissions(["ħ", "aː", "l"])))
|
| 149 |
+
with client(SettingsAuth()) as c:
|
| 150 |
+
before = c.app.state.scorer.cfg.flag_below
|
| 151 |
+
c.put("/api/admin/model-settings", headers=bearer("teacher"), json={"model": FT, "settings": {"flag_below": 33}})
|
| 152 |
+
assert c.app.state.scorer.cfg.flag_below == before
|
| 153 |
+
c.put("/api/admin/models/active", json={"model_id": FT}, headers=bearer("teacher"))
|
| 154 |
+
wait_switch(c, bearer("teacher"))
|
| 155 |
+
assert c.app.state.scorer.cfg.flag_below == 33
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def test_bad_settings_are_refused_with_the_reason(monkeypatch):
|
| 159 |
+
monkeypatch.setattr(app.main, "MODEL_ID", BASE)
|
| 160 |
+
with client(SettingsAuth()) as c:
|
| 161 |
+
for bad in ({"flag_below": 140}, {"gop.ratio_pool": "median"}, {"nonsense": 1},
|
| 162 |
+
{"flag_below_sound": {"ħ": -3}}, {"flag_below_sound": {"🙂": 30}}, {"max_issues": 2.5}):
|
| 163 |
+
res = c.put("/api/admin/model-settings", headers=bearer("teacher"), json={"model": BASE, "settings": bad})
|
| 164 |
+
assert res.status_code == 400, bad
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def test_without_the_table_settings_are_read_only_and_say_how_to_create_it(monkeypatch):
|
| 168 |
+
monkeypatch.setattr(app.main, "MODEL_ID", BASE)
|
| 169 |
+
with client(SettingsAuth(table=False)) as c:
|
| 170 |
+
data = c.get("/api/admin/model-settings", headers=bearer("teacher")).json()
|
| 171 |
+
assert not data["stored"] and not data["can_edit"] and "create table public.model_settings" in data["create_sql"]
|
| 172 |
+
res = c.put("/api/admin/model-settings", headers=bearer("teacher"), json={"model": BASE, "settings": {}})
|
| 173 |
+
assert res.status_code == 503
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def test_an_admin_reads_settings_but_cannot_save_them(monkeypatch):
|
| 177 |
+
monkeypatch.setattr(app.main, "MODEL_ID", BASE)
|
| 178 |
+
|
| 179 |
+
class Admin(SettingsAuth):
|
| 180 |
+
developers = frozenset()
|
| 181 |
+
with client(Admin()) as c:
|
| 182 |
+
assert c.get("/api/admin/model-settings", headers=bearer("teacher")).json()["can_edit"] is False
|
| 183 |
+
assert c.put("/api/admin/model-settings", headers=bearer("teacher"),
|
| 184 |
+
json={"model": BASE, "settings": {}}).status_code == 403
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
def test_stored_settings_are_applied_when_the_server_starts(monkeypatch):
|
| 188 |
+
monkeypatch.setattr(app.main, "MODEL_ID", BASE)
|
| 189 |
+
auth = SettingsAuth()
|
| 190 |
+
auth.set_model_settings(BASE, {"issue_below": 80}, "dev@x")
|
| 191 |
+
with client(auth) as c:
|
| 192 |
+
assert c.app.state.scorer.cfg.issue_below == 80
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
# ---- the practice page's model comparison (developers) ----
|
| 196 |
+
|
| 197 |
+
def a_second_of_audio() -> bytes:
|
| 198 |
+
import io
|
| 199 |
+
import wave
|
| 200 |
+
import numpy as np
|
| 201 |
+
t = np.arange(16000) / 16000
|
| 202 |
+
pcm = (0.3 * np.sin(2 * np.pi * 220 * t) * 32767).astype("<i2").tobytes()
|
| 203 |
+
buf = io.BytesIO()
|
| 204 |
+
with wave.open(buf, "wb") as w:
|
| 205 |
+
w.setnchannels(1); w.setsampwidth(2); w.setframerate(16000); w.writeframes(pcm)
|
| 206 |
+
return buf.getvalue()
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
def toilet_id():
|
| 210 |
+
from test_scoring import TOILET
|
| 211 |
+
from app.phrases import PHRASES
|
| 212 |
+
return PHRASES.index(TOILET)
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
def test_a_recording_is_scored_by_every_comparison_model_the_running_one_first(monkeypatch):
|
| 216 |
+
from test_scoring import TOILET # noqa: F401 w eː n | i l ħ a m m aː m
|
| 217 |
+
monkeypatch.setattr(app.main, "MODEL_ID", BASE)
|
| 218 |
+
monkeypatch.setenv("COMPARE_MODELS", f"{FT},broken/model")
|
| 219 |
+
monkeypatch.setattr(app.main, "model_availability", lambda model_id: (True, ""))
|
| 220 |
+
loads = []
|
| 221 |
+
|
| 222 |
+
def load(model_id):
|
| 223 |
+
loads.append(model_id)
|
| 224 |
+
if model_id == "broken/model":
|
| 225 |
+
raise OSError("no such model")
|
| 226 |
+
return scorer_for(emissions(["w", "eː", "n", "i", "l", "χ", "a", "m", "aː", "m"])) # ħ said as χ
|
| 227 |
+
monkeypatch.setattr(app.main, "load_scorer", load)
|
| 228 |
+
with client(KeyAuth()) as c:
|
| 229 |
+
files = {"audio": ("a.wav", a_second_of_audio(), "audio/wav")}
|
| 230 |
+
res = c.post("/api/admin/compare-models", data={"phrase_id": toilet_id()}, files=files, headers=bearer("teacher"))
|
| 231 |
+
assert res.status_code == 200, res.text
|
| 232 |
+
rows = res.json()["models"]
|
| 233 |
+
assert [r["model"] for r in rows] == [BASE, FT, "broken/model"]
|
| 234 |
+
assert rows[0]["active"] and not rows[1]["active"]
|
| 235 |
+
assert "no such model" in rows[2]["error"] and "score" not in rows[2]
|
| 236 |
+
ft = rows[1]
|
| 237 |
+
assert ft["score"] is not None and any(p["flagged"] and p["ipa"] == "ħ" for w in ft["words"] for p in w["phonemes"])
|
| 238 |
+
# loaded once, kept for the next recording; the broken one is tried again
|
| 239 |
+
c.post("/api/admin/compare-models", data={"phrase_id": toilet_id()}, files=files, headers=bearer("teacher"))
|
| 240 |
+
assert loads.count(FT) == 1 and loads.count("broken/model") == 2
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
def test_only_developers_compare_models(monkeypatch):
|
| 244 |
+
monkeypatch.setattr(app.main, "MODEL_ID", BASE)
|
| 245 |
+
with client(AdminAuth()) as c:
|
| 246 |
+
res = c.post("/api/admin/compare-models", data={"phrase_id": toilet_id()},
|
| 247 |
+
files={"audio": ("a.wav", a_second_of_audio(), "audio/wav")}, headers=bearer("teacher"))
|
| 248 |
+
assert res.status_code == 403
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
def test_quick_lab_item_is_compared_without_a_phrase_id(monkeypatch):
|
| 252 |
+
monkeypatch.setattr(app.main, "MODEL_ID", BASE)
|
| 253 |
+
monkeypatch.setattr(app.main, "model_availability", lambda model_id: True and (True, ""))
|
| 254 |
+
monkeypatch.setattr(app.main, "load_scorer", lambda model_id: scorer_for(emissions(["z", "a", "m", "a", "n"])))
|
| 255 |
+
with client(KeyAuth()) as c:
|
| 256 |
+
files = {"audio": ("a.wav", a_second_of_audio(), "audio/wav")}
|
| 257 |
+
res = c.post("/api/admin/compare-models", data={"item": "quick-zaman"}, files=files,
|
| 258 |
+
headers=bearer("teacher"))
|
| 259 |
+
assert res.status_code == 200, res.text
|
| 260 |
+
data = res.json()
|
| 261 |
+
assert data["phrase"] == "lab:quick-zaman"
|
| 262 |
+
assert len(data["models"]) == 3
|
| 263 |
+
assert all(row.get("score") is not None for row in data["models"])
|
| 264 |
+
assert c.post("/api/admin/compare-models", data={"item": "quick-nope"}, files=files,
|
| 265 |
+
headers=bearer("teacher")).status_code == 404
|
tests/test_powsm_onnx.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The exported POWSM (app/powsm.py PowsmOnnxEmitter): what the Space runs with onnxruntime alone.
|
| 2 |
+
The real model is 1.6 GB, so onnxruntime's session is replaced by one that answers with known log-posteriors;
|
| 3 |
+
scripts/export_powsm_onnx.py --check compares the real export with ESPnet frame by frame."""
|
| 4 |
+
import json
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
import pytest
|
| 8 |
+
|
| 9 |
+
import app.powsm as powsm
|
| 10 |
+
from app.models import availability
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def export(tmp_path, pad=0.0):
|
| 14 |
+
folder = tmp_path / "export"
|
| 15 |
+
folder.mkdir()
|
| 16 |
+
meta = {"kind": "powsm-ctc-onnx", "lang": "<ara>", "blank": 0, "vocab": {"<blank>": 0, "a": 1, "ħ": 2},
|
| 17 |
+
"pad_seconds": pad, "frames_per_second": 25, "prompt_positions": 2,
|
| 18 |
+
"files": {"fp32": "model.onnx", "int8": "model.int8.onnx"}}
|
| 19 |
+
(folder / "powsm_onnx.json").write_text(json.dumps(meta), encoding="utf-8")
|
| 20 |
+
rng = np.random.default_rng(0)
|
| 21 |
+
np.savez(folder / "frontend.npz", window=np.hanning(400).astype(np.float32),
|
| 22 |
+
melmat=rng.random((257, 80)).astype(np.float32), mean=np.zeros(80, np.float32),
|
| 23 |
+
std=np.ones(80, np.float32), n_fft=512, win_length=400, hop_length=160)
|
| 24 |
+
for name in ("model.onnx", "model.int8.onnx"):
|
| 25 |
+
(folder / name).write_bytes(b"")
|
| 26 |
+
return folder
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class FakeSession:
|
| 30 |
+
"""Like the export: 4x fewer frames than feats, log-posteriors over the 3 vocab columns."""
|
| 31 |
+
seen: list = []
|
| 32 |
+
|
| 33 |
+
def __init__(self, path, opts=None, providers=None):
|
| 34 |
+
self.path = path
|
| 35 |
+
FakeSession.seen.append(path)
|
| 36 |
+
|
| 37 |
+
def run(self, outputs, inputs):
|
| 38 |
+
feats = inputs["feats"]
|
| 39 |
+
assert feats.shape[0] == 1 and feats.shape[2] == 80 and inputs["feats_lens"][0] == feats.shape[1]
|
| 40 |
+
frames = feats.shape[1] // 4
|
| 41 |
+
logp = np.log(np.full((1, frames, 3), 1 / 3, dtype=np.float32))
|
| 42 |
+
return [logp]
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
@pytest.fixture
|
| 46 |
+
def fake_ort(monkeypatch):
|
| 47 |
+
import onnxruntime
|
| 48 |
+
monkeypatch.setattr(onnxruntime, "InferenceSession", FakeSession)
|
| 49 |
+
monkeypatch.delenv("POWSM_PAD_SECONDS", raising=False)
|
| 50 |
+
monkeypatch.delenv("POWSM_ONNX_PRECISION", raising=False)
|
| 51 |
+
FakeSession.seen = []
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def test_an_unpadded_export_gives_the_scorer_50_frames_a_second(tmp_path, fake_ort):
|
| 55 |
+
em = powsm.PowsmOnnxEmitter(str(export(tmp_path, pad=0.0)))
|
| 56 |
+
assert em.pad == 0.0 and em.token_to_id["ħ"] == 2 and em.blank_token == "<blank>"
|
| 57 |
+
logp = em(np.zeros(16000 * 2, dtype=np.float32))
|
| 58 |
+
stft_frames = 1 + 2 * 16000 // 160 # a centred STFT: one frame every 10 ms, plus one
|
| 59 |
+
assert logp.shape == ((stft_frames // 4) * 2, 3) # POWSM's 25 frames/s, each repeated once
|
| 60 |
+
assert np.allclose(np.exp(logp).sum(-1), 1)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def test_padding_keeps_only_the_frames_that_cover_the_speech(tmp_path, fake_ort):
|
| 64 |
+
em = powsm.PowsmOnnxEmitter(str(export(tmp_path, pad=8.0)))
|
| 65 |
+
one_second = em(np.zeros(16000, dtype=np.float32))
|
| 66 |
+
padded_frames = (1 + 8 * 16000 // 160) // 4
|
| 67 |
+
assert one_second.shape[0] == round(padded_frames / 8) * 2
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def test_pad_seconds_from_the_environment_wins(tmp_path, fake_ort, monkeypatch):
|
| 71 |
+
monkeypatch.setenv("POWSM_PAD_SECONDS", "4")
|
| 72 |
+
assert powsm.PowsmOnnxEmitter(str(export(tmp_path, pad=0.0))).pad == 4.0
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def test_fp32_is_the_default_and_int8_is_one_setting_away(tmp_path, fake_ort, monkeypatch):
|
| 76 |
+
folder = export(tmp_path)
|
| 77 |
+
assert powsm.PowsmOnnxEmitter(str(folder)).weights == "model.onnx"
|
| 78 |
+
monkeypatch.setenv("POWSM_ONNX_PRECISION", "int8")
|
| 79 |
+
assert powsm.PowsmOnnxEmitter(str(folder)).weights == "model.int8.onnx"
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def test_model_ids_that_name_an_export(tmp_path, monkeypatch):
|
| 83 |
+
folder = export(tmp_path)
|
| 84 |
+
assert powsm.onnx_model_dir(str(folder)) == folder
|
| 85 |
+
assert powsm.onnx_model_dir("facebook/wav2vec2-xlsr-53-espeak-cv-ft") is None
|
| 86 |
+
assert powsm.onnx_model_dir("checkpoints/powsm-ft-shortpad/powsm_ft.pt") is None
|
| 87 |
+
fetched = []
|
| 88 |
+
import huggingface_hub
|
| 89 |
+
monkeypatch.setattr(huggingface_hub, "snapshot_download",
|
| 90 |
+
lambda repo, allow_patterns=None: fetched.append((repo, allow_patterns)) or str(folder))
|
| 91 |
+
assert powsm.onnx_model_dir("powsm-onnx:someone/powsm") == folder
|
| 92 |
+
repo, patterns = fetched[0]
|
| 93 |
+
assert repo == "someone/powsm" and "model.onnx" in patterns and "model.int8.onnx" not in patterns
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def test_the_image_build_refuses_a_model_that_needs_espnet(monkeypatch):
|
| 97 |
+
from app import prefetch
|
| 98 |
+
monkeypatch.setenv("MODEL_ID", "checkpoints/powsm-ft-shortpad/powsm_ft.pt")
|
| 99 |
+
with pytest.raises(SystemExit) as e:
|
| 100 |
+
prefetch.main()
|
| 101 |
+
assert "export_powsm_onnx" in str(e.value)
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def test_the_models_tab_offers_an_export_when_onnxruntime_is_there(tmp_path):
|
| 105 |
+
assert availability(f"{powsm.ONNX_PREFIX}someone/powsm") == (True, "")
|
| 106 |
+
assert availability(str(export(tmp_path))) == (True, "")
|
| 107 |
+
ok, why = availability("exports/not-there")
|
| 108 |
+
assert not ok and "ONNX" in why
|
train/finetune_powsm.py
ADDED
|
@@ -0,0 +1,291 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Fine-tune POWSM-CTC (espnet/powsm_ctc) on Palestinian Arabic recordings: phone recognition with the <ara> prompt.
|
| 2 |
+
|
| 3 |
+
Data: the same CSVs as train/finetune.py (`audio,ipa`, plus the other Minerva columns). Labels are written in the
|
| 4 |
+
phrases.py convention and mapped onto POWSM's phone tokens (all but dʒ -> d͡ʒ and g -> ɡ are the same symbol).
|
| 5 |
+
|
| 6 |
+
Training uses POWSM's own loss, with targets built the way its recipe builds them (egs2/powsm/s2t1,
|
| 7 |
+
local/process_ipapack.py):
|
| 8 |
+
text "<ara><pr><notimestamps> /t//a//m//aː//m/" the final layer and layer 14 learn this
|
| 9 |
+
text_ctc the same phones without length marks layers 4, 8, 10 learn this (the recipe's "nosup" target)
|
| 10 |
+
text_prev <na>
|
| 11 |
+
Audio is padded to POWSM's 20 s, with random leading silence in training as its preprocessor does. --pad random
|
| 12 |
+
pads each clip to a random length instead (none, 2, 4, 8, 12 or 20 s), so the model stops depending on 20 s of padding:
|
| 13 |
+
unpadded, the 20 s fine-tune lost 5 points of PER (16% -> 21%) and is 5x faster on a CPU.
|
| 14 |
+
|
| 15 |
+
Memory (6 GB): only the top --train-layers encoder layers train. The CTC head stays frozen unless --train-head:
|
| 16 |
+
it also feeds its predictions back into layers 4, 8 and 10, so training it means backpropagating through nearly the
|
| 17 |
+
whole encoder.
|
| 18 |
+
|
| 19 |
+
Needs the extra packages from scripts/setup_zero_shot_deps.sh. Example:
|
| 20 |
+
python -m train.finetune_powsm --train data/minerva/train.csv --eval data/minerva/dev.csv \
|
| 21 |
+
--out checkpoints/powsm-ft-minerva
|
| 22 |
+
Then compare on test: python scripts/zero_shot_phone_models.py --models powsm-ft,ft --split test
|
| 23 |
+
|
| 24 |
+
Short padding, from the 20 s fine-tune:
|
| 25 |
+
python -m train.finetune_powsm --train data/minerva/train.csv --eval data/minerva/dev.csv \
|
| 26 |
+
--init checkpoints/powsm-ft-minerva/powsm_ft.pt --pad random --eval-pad 0 --epochs 6 --lr 3e-5 \
|
| 27 |
+
--out checkpoints/powsm-ft-shortpad
|
| 28 |
+
"""
|
| 29 |
+
from __future__ import annotations
|
| 30 |
+
|
| 31 |
+
import argparse
|
| 32 |
+
import csv
|
| 33 |
+
import json
|
| 34 |
+
import math
|
| 35 |
+
import random
|
| 36 |
+
import sys
|
| 37 |
+
import time
|
| 38 |
+
from pathlib import Path
|
| 39 |
+
|
| 40 |
+
import numpy as np
|
| 41 |
+
import torch
|
| 42 |
+
|
| 43 |
+
ROOT = Path(__file__).resolve().parent.parent
|
| 44 |
+
sys.path.insert(0, str(ROOT))
|
| 45 |
+
sys.path.insert(0, str(ROOT / "scripts"))
|
| 46 |
+
|
| 47 |
+
import zero_shot_phone_models as zs # noqa: E402
|
| 48 |
+
from app.scorer import SAMPLE_RATE, decode_audio # noqa: E402
|
| 49 |
+
|
| 50 |
+
LANG, TASK = "<ara>", "<pr>"
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
class Targets:
|
| 54 |
+
"""Our phonemes -> POWSM token ids, for the `text` and `text_ctc` targets."""
|
| 55 |
+
|
| 56 |
+
def __init__(self, s2t):
|
| 57 |
+
self.tokenizer, self.converter = s2t.tokenizer, s2t.converter
|
| 58 |
+
phones = [t[1:-1] for t in s2t.s2t_model.token_list if len(t) > 2 and t[0] == "/" and t[-1] == "/"]
|
| 59 |
+
self.phones = set(phones)
|
| 60 |
+
self.map: dict[str, str] = {}
|
| 61 |
+
self._phones_by_canon: dict[str, list[str]] = {}
|
| 62 |
+
for p in phones:
|
| 63 |
+
self._phones_by_canon.setdefault(zs.canon(p), []).append(p)
|
| 64 |
+
|
| 65 |
+
def phone(self, ours: str) -> str:
|
| 66 |
+
if ours not in self.map:
|
| 67 |
+
if ours in self.phones:
|
| 68 |
+
self.map[ours] = ours
|
| 69 |
+
else: # the plainest POWSM spelling of the same sound (dʒ -> d͡ʒ, g -> ɡ)
|
| 70 |
+
cands = sorted(self._phones_by_canon.get(ours, []), key=len)
|
| 71 |
+
if not cands:
|
| 72 |
+
raise KeyError(f"POWSM has no phone token for {ours!r}")
|
| 73 |
+
self.map[ours] = cands[0]
|
| 74 |
+
return self.map[ours]
|
| 75 |
+
|
| 76 |
+
def ids(self, text: str) -> list[int]:
|
| 77 |
+
return self.converter.tokens2ids(self.tokenizer.text2tokens(text))
|
| 78 |
+
|
| 79 |
+
def __call__(self, ipa: str) -> tuple[list[int], list[int]]:
|
| 80 |
+
ours = [t for t in ipa.split() if t != "|"]
|
| 81 |
+
collapsed = [p for i, p in enumerate(ours) if i == 0 or p != ours[i - 1]] # geminates -> one sound
|
| 82 |
+
powsm = [self.phone(p) for p in collapsed]
|
| 83 |
+
text = self.ids(f"{LANG}{TASK}<notimestamps> " + "".join(f"/{p}/" for p in powsm))[1:] # drop leading ▁
|
| 84 |
+
nosup = [p.replace("ː", "") for p in powsm]
|
| 85 |
+
nosup = [p for i, p in enumerate(nosup) if i == 0 or p != nosup[i - 1]]
|
| 86 |
+
text_ctc = text[:2] + self.ids("".join(f"/{p}/" for p in nosup))
|
| 87 |
+
return text, text_ctc
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def load_rows(path: str, targets: Targets) -> list[dict]:
|
| 91 |
+
root = Path(path).parent
|
| 92 |
+
rows = []
|
| 93 |
+
with open(path, encoding="utf-8") as f:
|
| 94 |
+
for row in csv.DictReader(f):
|
| 95 |
+
wav = decode_audio((root / row["audio"]).read_bytes())
|
| 96 |
+
text, text_ctc = targets(row["ipa"])
|
| 97 |
+
rows.append({"wav": wav, "text": text, "text_ctc": text_ctc, "ipa": row["ipa"], "item": row.get("item")})
|
| 98 |
+
print(f"{path}: {len(rows)} utterances", flush=True)
|
| 99 |
+
return rows
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def pad_ids(seqs: list[list[int]], device) -> tuple[torch.Tensor, torch.Tensor]:
|
| 103 |
+
n = max(len(s) for s in seqs)
|
| 104 |
+
out = torch.full((len(seqs), n), -1, dtype=torch.long)
|
| 105 |
+
for i, s in enumerate(seqs):
|
| 106 |
+
out[i, : len(s)] = torch.tensor(s)
|
| 107 |
+
return out.to(device), torch.tensor([len(s) for s in seqs], device=device)
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
SHORT_PADS = (0, 2, 4, 8, 12, 20) # --pad random: the lengths a training clip is padded to (0: not at all)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def make_batch(items: list[dict], model, train: bool, device, pad: str = "20") -> dict:
|
| 114 |
+
"""POWSM's input: every clip padded to the same length, with some silence before it in training.
|
| 115 |
+
pad "20": 20 s, as POWSM was trained. "random": a length from SHORT_PADS for the batch (at least its longest clip),
|
| 116 |
+
and a random split of the padding before and after the speech."""
|
| 117 |
+
longest = max(len(it["wav"]) for it in items)
|
| 118 |
+
seconds = random.choice(SHORT_PADS) if pad == "random" else zs.Powsm.SECONDS
|
| 119 |
+
n = max(longest, int(seconds * SAMPLE_RATE))
|
| 120 |
+
speech = np.zeros((len(items), n), dtype=np.float32)
|
| 121 |
+
for i, it in enumerate(items):
|
| 122 |
+
wav = it["wav"][:n]
|
| 123 |
+
start = random.randint(0, n - len(wav)) if train else 0 # the preprocessor's random leading silence
|
| 124 |
+
speech[i, start: start + len(wav)] = wav
|
| 125 |
+
text, text_len = pad_ids([it["text"] for it in items], device)
|
| 126 |
+
text_ctc, text_ctc_len = pad_ids([it["text_ctc"] for it in items], device)
|
| 127 |
+
prev, prev_len = pad_ids([[model.na]] * len(items), device)
|
| 128 |
+
prefix, prefix_len = pad_ids([it["text"][:2] for it in items], device)
|
| 129 |
+
return {"speech": torch.from_numpy(speech).to(device),
|
| 130 |
+
"speech_lengths": torch.full((len(items),), n, dtype=torch.long, device=device),
|
| 131 |
+
"text": text, "text_lengths": text_len, "text_ctc": text_ctc, "text_ctc_lengths": text_ctc_len,
|
| 132 |
+
"text_prev": prev, "text_prev_lengths": prev_len, "prefix": prefix, "prefix_lengths": prefix_len}
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def set_trainable(model, train_layers: int, train_head: bool) -> list[str]:
|
| 136 |
+
for p in model.parameters():
|
| 137 |
+
p.requires_grad = False
|
| 138 |
+
layers = model.encoder.encoders
|
| 139 |
+
parts = [*layers[len(layers) - train_layers:], model.encoder.after_norm]
|
| 140 |
+
if train_head:
|
| 141 |
+
parts += [model.ctc, model.encoder.conditioning_layer]
|
| 142 |
+
for part in parts:
|
| 143 |
+
for p in part.parameters():
|
| 144 |
+
p.requires_grad = True
|
| 145 |
+
return [k for k, p in model.named_parameters() if p.requires_grad]
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def use_checkpointing(model, train_layers: int) -> None:
|
| 149 |
+
"""Recompute the trained layers' activations in the backward pass instead of keeping them."""
|
| 150 |
+
from torch.utils.checkpoint import checkpoint
|
| 151 |
+
layers = model.encoder.encoders
|
| 152 |
+
for layer in layers[len(layers) - train_layers:]:
|
| 153 |
+
fwd = layer.forward
|
| 154 |
+
|
| 155 |
+
def wrapped(*args, _fwd=fwd, **kwargs):
|
| 156 |
+
if not torch.is_grad_enabled():
|
| 157 |
+
return _fwd(*args, **kwargs)
|
| 158 |
+
return checkpoint(_fwd, *args, use_reentrant=False, **kwargs)
|
| 159 |
+
layer.forward = wrapped
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
@torch.no_grad()
|
| 163 |
+
def evaluate(powsm, rows: list[dict], limit: int | None = None, pad: float | None = None) -> dict:
|
| 164 |
+
"""Greedy-decode every line (as the bake-off does) and score it with the bake-off's phoneme error rate,
|
| 165 |
+
with the clips padded to `pad` seconds (None: POWSM's 20; 0: not padded)."""
|
| 166 |
+
powsm.s2t.s2t_model.eval()
|
| 167 |
+
powsm.pad = zs.Powsm.SECONDS if pad is None else pad
|
| 168 |
+
errs = c_errs = total = c_total = 0
|
| 169 |
+
long_n = long_ok = 0
|
| 170 |
+
for it in rows[:limit]:
|
| 171 |
+
tokens, _ = powsm(it["wav"])
|
| 172 |
+
ref, hyp = zs.reference(it["ipa"]), zs.to_phones(tokens)
|
| 173 |
+
e, pairs = zs.align(ref, hyp)
|
| 174 |
+
errs, total = errs + e, total + len(ref)
|
| 175 |
+
ce, _ = zs.align(zs.consonants(ref), zs.consonants(hyp))
|
| 176 |
+
c_errs, c_total = c_errs + ce, c_total + len(zs.consonants(ref))
|
| 177 |
+
for r, h in pairs:
|
| 178 |
+
if r is not None and r.endswith("ː"):
|
| 179 |
+
long_n += 1
|
| 180 |
+
long_ok += r == h
|
| 181 |
+
if torch.cuda.is_available():
|
| 182 |
+
torch.cuda.empty_cache() # hand decoding's buffers back before training resumes (6 GB is tight)
|
| 183 |
+
return {"per": errs / total, "consonant_per": c_errs / c_total, "long_vowels": long_ok / max(1, long_n)}
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def main():
|
| 187 |
+
ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
|
| 188 |
+
ap.add_argument("--train", required=True)
|
| 189 |
+
ap.add_argument("--eval", required=True)
|
| 190 |
+
ap.add_argument("--out", default="checkpoints/powsm-ft")
|
| 191 |
+
ap.add_argument("--epochs", type=float, default=10)
|
| 192 |
+
ap.add_argument("--lr", type=float, default=5e-5)
|
| 193 |
+
ap.add_argument("--batch", type=int, default=4)
|
| 194 |
+
ap.add_argument("--accum", type=int, default=8, help="batches per optimizer step (effective batch = batch x accum)")
|
| 195 |
+
ap.add_argument("--train-layers", type=int, default=8, help="train the top N of the 18 encoder layers")
|
| 196 |
+
ap.add_argument("--train-head", action="store_true", help="also train the CTC head (needs much more memory)")
|
| 197 |
+
ap.add_argument("--checkpointing", action="store_true", help="gradient checkpointing: less memory, slower")
|
| 198 |
+
ap.add_argument("--max-steps", type=int, default=0, help="stop after this many optimizer steps (a memory check)")
|
| 199 |
+
ap.add_argument("--eval-limit", type=int, help="score only the first N eval lines (a quick check)")
|
| 200 |
+
ap.add_argument("--pad", choices=["20", "random"], default="20",
|
| 201 |
+
help="training clips padded to POWSM's 20 s, or to a random length (see SHORT_PADS)")
|
| 202 |
+
ap.add_argument("--eval-pad", type=float, help="seconds the eval clips are padded to when picking the best epoch "
|
| 203 |
+
"(default 20; 0: none). 8 s is also reported when it differs")
|
| 204 |
+
ap.add_argument("--init", help="start from a fine-tune's weights (powsm_ft.pt) instead of the published model")
|
| 205 |
+
ap.add_argument("--seed", type=int, default=0)
|
| 206 |
+
args = ap.parse_args()
|
| 207 |
+
random.seed(args.seed)
|
| 208 |
+
torch.manual_seed(args.seed)
|
| 209 |
+
|
| 210 |
+
powsm = zs.Powsm(LANG, args.init)
|
| 211 |
+
model, device = powsm.s2t.s2t_model, powsm.s2t.device
|
| 212 |
+
targets = Targets(powsm.s2t)
|
| 213 |
+
train_rows = load_rows(args.train, targets)
|
| 214 |
+
eval_rows = load_rows(args.eval, targets)
|
| 215 |
+
print("phone tokens:", {k: v for k, v in targets.map.items() if k != v} or "all the same symbol", flush=True)
|
| 216 |
+
|
| 217 |
+
init_keys = set(torch.load(args.init, map_location="cpu")["state"]) if args.init else set()
|
| 218 |
+
names = set_trainable(model, args.train_layers, args.train_head)
|
| 219 |
+
trainable = [p for p in model.parameters() if p.requires_grad]
|
| 220 |
+
print(f"training {sum(p.numel() for p in trainable) / 1e6:.0f}M of "
|
| 221 |
+
f"{sum(p.numel() for p in model.parameters()) / 1e6:.0f}M parameters", flush=True)
|
| 222 |
+
if args.checkpointing:
|
| 223 |
+
use_checkpointing(model, args.train_layers)
|
| 224 |
+
|
| 225 |
+
import bitsandbytes as bnb
|
| 226 |
+
opt = bnb.optim.AdamW8bit(trainable, lr=args.lr, weight_decay=0.01)
|
| 227 |
+
steps_per_epoch = math.ceil(len(train_rows) / (args.batch * args.accum))
|
| 228 |
+
total_steps = args.max_steps or math.ceil(steps_per_epoch * args.epochs)
|
| 229 |
+
warmup = max(1, int(0.1 * total_steps))
|
| 230 |
+
sched = torch.optim.lr_scheduler.LambdaLR(
|
| 231 |
+
opt, lambda s: min((s + 1) / warmup, max(0.0, (total_steps - s) / max(1, total_steps - warmup))))
|
| 232 |
+
|
| 233 |
+
out = Path(args.out)
|
| 234 |
+
out.mkdir(parents=True, exist_ok=True)
|
| 235 |
+
def scores() -> dict:
|
| 236 |
+
m = evaluate(powsm, eval_rows, args.eval_limit, args.eval_pad)
|
| 237 |
+
if args.eval_pad is not None and args.eval_pad != 8:
|
| 238 |
+
m["at_8s"] = evaluate(powsm, eval_rows, args.eval_limit, 8)
|
| 239 |
+
return m
|
| 240 |
+
|
| 241 |
+
best = scores()
|
| 242 |
+
print(f"baseline: {json.dumps(best)}", flush=True)
|
| 243 |
+
best_per, history, step = best["per"], [{"epoch": 0, **best}], 0
|
| 244 |
+
|
| 245 |
+
def save(metrics: dict) -> None:
|
| 246 |
+
keep = set(names) | init_keys # with --init, also the weights the earlier fine-tune changed
|
| 247 |
+
state = {k: v.detach().cpu() for k, v in model.state_dict().items() if k in keep}
|
| 248 |
+
torch.save({"state": state, "lang": LANG, "phone_map": targets.map, "args": vars(args),
|
| 249 |
+
"metrics": metrics}, out / "powsm_ft.pt")
|
| 250 |
+
|
| 251 |
+
epoch, t0 = 0, time.time()
|
| 252 |
+
while step < total_steps:
|
| 253 |
+
epoch += 1
|
| 254 |
+
model.train()
|
| 255 |
+
order = random.sample(range(len(train_rows)), len(train_rows))
|
| 256 |
+
batches = [order[i: i + args.batch] for i in range(0, len(order), args.batch)]
|
| 257 |
+
running, n_loss = 0.0, 0
|
| 258 |
+
for b, idx in enumerate(batches):
|
| 259 |
+
batch = make_batch([train_rows[i] for i in idx], model, True, device, args.pad)
|
| 260 |
+
with torch.autocast("cuda", dtype=torch.bfloat16, enabled=device != "cpu"):
|
| 261 |
+
loss, stats, _ = model(**batch)
|
| 262 |
+
(loss / args.accum).backward()
|
| 263 |
+
running, n_loss = running + float(loss), n_loss + 1
|
| 264 |
+
if (b + 1) % args.accum == 0 or b + 1 == len(batches):
|
| 265 |
+
torch.nn.utils.clip_grad_norm_(trainable, 1.0)
|
| 266 |
+
opt.step()
|
| 267 |
+
sched.step()
|
| 268 |
+
opt.zero_grad(set_to_none=True)
|
| 269 |
+
step += 1
|
| 270 |
+
if step % 10 == 0:
|
| 271 |
+
mem = torch.cuda.max_memory_allocated() / 1e9 if device != "cpu" else 0
|
| 272 |
+
print(f"epoch {epoch} step {step}/{total_steps} loss {running / n_loss:.3f} "
|
| 273 |
+
f"lr {sched.get_last_lr()[0]:.2e} mem {mem:.1f}GB {time.time() - t0:.0f}s", flush=True)
|
| 274 |
+
running, n_loss = 0.0, 0
|
| 275 |
+
if step >= total_steps:
|
| 276 |
+
break
|
| 277 |
+
metrics = scores()
|
| 278 |
+
history.append({"epoch": epoch, "step": step, **metrics})
|
| 279 |
+
print(f"epoch {epoch}: {json.dumps(metrics)}", flush=True)
|
| 280 |
+
if metrics["per"] < best_per:
|
| 281 |
+
best_per = metrics["per"]
|
| 282 |
+
save({"epoch": epoch, **metrics})
|
| 283 |
+
print(f" saved (best PER so far) to {out / 'powsm_ft.pt'}", flush=True)
|
| 284 |
+
(out / "history.json").write_text(json.dumps(history, indent=1), encoding="utf-8")
|
| 285 |
+
if not (out / "powsm_ft.pt").exists():
|
| 286 |
+
print("no epoch beat the baseline; nothing saved", flush=True)
|
| 287 |
+
print(f"best dev PER {best_per:.3f}; history in {out / 'history.json'}", flush=True)
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
if __name__ == "__main__":
|
| 291 |
+
main()
|