#!/usr/bin/env python3 """Offline transcription flags for generated postcards; not a listening review.""" import difflib import argparse import hashlib import json from pathlib import Path import time 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/postcard-voices' cards = json.loads((root / 'assets/postcards/recordings-source.json').read_text()) parser = argparse.ArgumentParser() parser.add_argument('--id', help='Review one postcard again') args = parser.parse_args() if args.id: cards = [card for card in cards if card['id'] == args.id] if not cards: parser.error('Unknown postcard') 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') report_path = work / 'transcription-review.json' results = json.loads(report_path.read_text()) if args.id and report_path.exists() else {} if args.id: results.pop(args.id, None) while not all(card['id'] in results for card in cards): for card in cards: if card['id'] in results: continue path = work / (card['id'] + '.wav') if not path.exists() or not path.with_suffix('.json').exists(): continue 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(card['text']), words(recognized) changes = [{'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[card['id']] = {'expected': card['text'], 'recognized': recognized, 'differences': changes, 'sha256': hashlib.sha256(path.read_bytes()).hexdigest()} report_path.write_text(json.dumps(results, indent=2, ensure_ascii=False) + '\n') print(f'{len(results)}/14 {card["id"]}: {len(changes)} potential differences', flush=True) if not all(card['id'] in results for card in cards): time.sleep(10)