File size: 4,511 Bytes
a51a477
 
 
 
 
 
 
 
 
64ba922
a51a477
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
# /// script
# requires-python = ">=3.10"
# dependencies = [
#   "torch",
#   "transformers>=4.56",
#   "mistral-common[audio]>=1.8.1",
#   "datasets",
#   "accelerate",
#   "jiwer",
#   "librosa",
#   "soundfile",
#   "requests",
#   "numpy",
# ]
# ///
"""
Voxtral baseline WER eval — HuggingFace Job script (uv run --script).

Transcribes the user's held-out labeled recordings (same seed-42/10% split as
training and the local eval_voxtral.py) with an open-weights Voxtral model and
reports WER. No personalization — this is the cold-model baseline.

Env: MODEL_ID (default mistralai/Voxtral-Mini-3B-2507), N_CLIPS (default 30),
     USER_ID; secrets: HF_TOKEN, SUPABASE_SERVICE_ROLE_KEY.
"""
import os, tempfile, time

import requests
import torch
import jiwer
from datasets import Dataset

MODEL_ID     = os.environ.get("MODEL_ID", "mistralai/Voxtral-Mini-3B-2507")
N_CLIPS      = int(os.environ.get("N_CLIPS", "30"))
USER_ID      = os.environ["USER_ID"]
SUPABASE_URL = os.environ.get("SUPABASE_URL", "https://hehlulmegluxmtlupwgp.supabase.co")
SB_KEY       = os.environ["SUPABASE_SERVICE_ROLE_KEY"]

hdrs = {"apikey": SB_KEY, "Authorization": f"Bearer {SB_KEY}"}

recs = requests.get(f"{SUPABASE_URL}/rest/v1/training_recordings", headers=hdrs,
                    params={"select": "audio_url,phrase_id", "user_id": f"eq.{USER_ID}"}).json()
phrases = requests.get(f"{SUPABASE_URL}/rest/v1/training_phrases", headers=hdrs,
                       params={"select": "id,text"}).json()
phrase_map = {p["id"]: p["text"] for p in phrases}
dataset_all = [{"audio_url": r["audio_url"], "text": phrase_map[r["phrase_id"]]}
               for r in recs if r["phrase_id"] in phrase_map]
print(f"{len(dataset_all)} labeled recordings")

# Same held-out split as training / local eval (seed 42, 10% of the FULL list).
test_size = max(1, int(len(dataset_all) * 0.1))
full = Dataset.from_list([{"idx": i} for i in range(len(dataset_all))])
eval_indices = [r["idx"] for r in full.train_test_split(test_size=test_size, seed=42)["test"]]
dataset = [dataset_all[i] for i in eval_indices]

# WAV clips only (no ffmpeg on the job image; the modern pipeline records WAV).
wav_ds, skipped = [], 0
WAV_DIR = tempfile.mkdtemp()
for i, item in enumerate(dataset):
    url = item["audio_url"]
    if not url.split("?")[0].lower().endswith(".wav"):
        skipped += 1
        continue
    r = requests.get(url.replace("/object/public/", "/object/"), headers=hdrs)
    if not r.ok:
        skipped += 1
        continue
    path = os.path.join(WAV_DIR, f"{i}.wav")
    open(path, "wb").write(r.content)
    wav_ds.append({"path": path, "text": item["text"]})
    if len(wav_ds) >= N_CLIPS:
        break
print(f"eval clips: {len(wav_ds)} wav ({skipped} non-wav/failed skipped)")

from transformers import AutoProcessor, VoxtralForConditionalGeneration

print(f"loading {MODEL_ID}…", flush=True)
processor = AutoProcessor.from_pretrained(MODEL_ID)
model = VoxtralForConditionalGeneration.from_pretrained(
    MODEL_ID, torch_dtype=torch.bfloat16, device_map="cuda")
model.eval()

# Method name had a typo in early transformers releases — support both.
_req = getattr(processor, "apply_transcription_request",
               getattr(processor, "apply_transcrition_request", None))

norm = jiwer.Compose([jiwer.ToLowerCase(), jiwer.RemovePunctuation(),
                      jiwer.RemoveMultipleSpaces(), jiwer.Strip(),
                      jiwer.ReduceToListOfListOfWords()])

rows = []
t0 = time.time()
for i, item in enumerate(wav_ds):
    inputs = _req(language="en", audio=item["path"], model_id=MODEL_ID)
    inputs = inputs.to("cuda", dtype=torch.bfloat16)
    with torch.no_grad():
        out = model.generate(**inputs, max_new_tokens=200)
    hyp = processor.batch_decode(out[:, inputs.input_ids.shape[1]:],
                                 skip_special_tokens=True)[0].strip()
    wer = jiwer.wer(item["text"], hyp or "",
                    reference_transform=norm, hypothesis_transform=norm)
    rows.append((wer, item["text"], hyp))
    print(f"[{i}] wer={wer:.2f} ref={item['text']!r} hyp={hyp!r}", flush=True)

mean_wer = sum(w for w, _, _ in rows) / max(1, len(rows))
print("\n================ RESULTS ================")
print(f"model: {MODEL_ID}")
print(f"mean WER: {mean_wer:.3f} over {len(rows)} clips "
      f"({(time.time()-t0)/max(1,len(rows)):.1f}s/clip)")
print("worst 5:")
for w, ref, hyp in sorted(rows, reverse=True)[:5]:
    print(f"  {w:.2f}  ref: {ref!r}")
    print(f"        hyp: {hyp!r}")