Files
logic-puzzle/scripts/review_elias_consistent.py
2026-11-14 08:55:48 +01:00

42 lines
2.2 KiB
Python

#!/usr/bin/env python3
"""Offline ASR flags for reference-anchored Elias takes; not a listening test."""
import difflib
import hashlib
import json
import time
from pathlib import Path
import numpy as np
import soundfile as sf
import torch
from scipy.signal import resample_poly
from huggingface_hub import snapshot_download
from transformers import pipeline
from review_qwen_narration import words
ROOT = Path(__file__).resolve().parents[1]
work = ROOT / 'artifacts/elias-consistent'
torch.set_num_threads(2)
model = snapshot_download('openai/whisper-base.en', revision='911407f4214e0e1d82085af863093ec0b66f9cd6', local_files_only=True)
recognizer = pipeline('automatic-speech-recognition', model=model, device='cpu')
results = {}
while True:
for metadata in sorted((work / 'takes').glob('*.json')):
if metadata.name in results: continue
take = json.loads(metadata.read_text())
path = metadata.with_suffix('.wav')
if not path.exists(): continue
sha = hashlib.sha256(path.read_bytes()).hexdigest()
if take['sha256'] != sha: raise ValueError(f'Stale take: {path}')
audio, rate = sf.read(path, dtype='float32')
if rate != 24000: raise ValueError(path)
recognized = recognizer({'raw':np.asarray(resample_poly(audio,2,3)), 'sampling_rate':16000}, chunk_length_s=25, ignore_warning=True)['text']
expected, actual = words(take['request']['text']), words(recognized)
differences = [{'expected':' '.join(expected[i:j]),'recognized':' '.join(actual[k:l])}
for tag,i,j,k,l in difflib.SequenceMatcher(None,expected,actual).get_opcodes() if tag != 'equal']
results[metadata.name] = {'expected':take['request']['text'],'recognized':recognized,'differences':differences,'sha256':sha}
(work / 'transcription-review.json').write_text(json.dumps(results,indent=2,ensure_ascii=False)+'\n')
print(f'Reviewed {len(results)}: {len(differences)} flags',flush=True)
if (work / 'manifest.json').exists() and len(results) == len(list((work / 'takes').glob('*.json'))): break
time.sleep(10)
print(f'{len(results)} takes reviewed; transcription flags require listening.',flush=True)