Files
logic-puzzle/scripts/review_qwen_narration.py
2026-11-13 10:18:42 +01:00

116 lines
5.5 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""Flag potential misreads in staged Qwen takes using offline Whisper.
This is an automated review aid, not a verified transcript or listening test.
"""
import argparse
import difflib
import hashlib
import json
from pathlib import Path
import re
import time
MODEL = 'openai/whisper-base.en'
REVISION = '911407f4214e0e1d82085af863093ec0b66f9cd6'
def words(text):
text = text.lower().replace('’', "'")
text = re.sub(r'\b13th\b', 'thirteenth', text)
text = re.sub(r'\b12th\b', 'twelfth', text)
numbers = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven',
'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen',
'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen']
for tens in ('twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'):
numbers.extend([tens] + [tens + ' ' + unit for unit in numbers[1:10]])
for number, word in enumerate(numbers):
text = re.sub(rf'\b{number}\b', word, text)
return re.findall(r"[a-z]+(?:'[a-z]+)?", text.replace('-', ' '))
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--work', type=Path, default=Path('artifacts/midnight-qwen'))
parser.add_argument('--watch', action='store_true',
help='Review new takes until the staged manifest is ready')
args = parser.parse_args()
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
torch.set_num_threads(2)
recognizer = None
results = []
manifest = args.work / 'manifest.json'
initial_manifest = (hashlib.sha256(manifest.read_bytes()).hexdigest()
if args.watch and manifest.exists() else None)
seen = set()
while True:
ready = manifest.exists() and (
not args.watch or hashlib.sha256(manifest.read_bytes()).hexdigest() != initial_manifest)
if ready:
source = json.loads(manifest.read_text())
keys = {cue['requestSha256'] for track in source['tracks'].values()
for cue in track['cues']}
paths = [args.work / 'takes' / f'{key}.json' for key in sorted(keys)]
else:
paths = sorted(p for p in (args.work / 'takes').glob('*.json')
if not p.name.endswith('.review.json'))
for metadata in paths:
if metadata.name in seen:
continue
if metadata.name.endswith('.review.json'):
continue
take = json.loads(metadata.read_text())
path = metadata.with_suffix('.wav')
sha = hashlib.sha256(path.read_bytes()).hexdigest()
assert take['sha256'] == sha
review_path = metadata.with_suffix('.review.json')
review = json.loads(review_path.read_text()) if review_path.exists() else {}
if review.get('sha256') != sha or review.get('revision') != REVISION:
if recognizer is None:
snapshot = snapshot_download(MODEL, revision=REVISION, local_files_only=True)
recognizer = pipeline('automatic-speech-recognition', model=snapshot,
device='cpu', dtype=torch.float32)
audio, rate = sf.read(path, dtype='float32')
audio = resample_poly(audio, 2, 3) if rate == 24000 else audio
assert rate in (24000, 16000)
recognised = recognizer({'raw': np.asarray(audio), 'sampling_rate': 16000},
chunk_length_s=25, ignore_warning=True)['text']
review = {'sha256': sha, 'model': MODEL, 'revision': REVISION,
'recognised': recognised}
review_path.write_text(json.dumps(review, indent=2) + '\n')
expected = take['spec']['text']
a, b = words(expected), words(review['recognised'])
changes = [{'expected': ' '.join(a[i:j]), 'recognised': ' '.join(b[k:l])}
for tag, i, j, k, l in difflib.SequenceMatcher(None, a, b).get_opcodes()
if tag != 'equal']
result = {'take': path.name, 'expected': expected,
'recognised': review['recognised'], 'differences': changes}
results.append(result)
seen.add(metadata.name)
print(f'Reviewed take {len(results)}: {len(changes)} potential differences', flush=True)
if not args.watch:
break
if ready:
final = json.loads(manifest.read_text())
expected = {cue['requestSha256'] + '.json'
for track in final['tracks'].values() for cue in track['cues']}
if expected <= seen:
results = [r for r in results if Path(r['take']).with_suffix('.json').name in expected]
break
time.sleep(5)
report = {'note': 'Automatic transcription is fallible. Differences are review flags, '
'not confirmed speech defects; a match is not a listening review.',
'model': MODEL, 'revision': REVISION, 'takes': results}
(args.work / 'word-review.json').write_text(json.dumps(report, indent=2, ensure_ascii=False)+'\n')
flagged = sum(bool(r['differences']) for r in results)
print(f'{len(results)} takes reviewed; {flagged} flagged. See {args.work}/word-review.json')
if __name__ == '__main__':
main()