"""Transcribe the Parlez MP3s (French) on the CPU so each recording can be matched to its word or dialogue.
Output: Book/L4/audio_<slug>.json  [{file, seconds, text}] — resumable.   python tools/transcribe_audio.py"""
import os, sys, json, unicodedata
from faster_whisper import WhisperModel
SRC = r"D:/OneDrive - DolfTech/SABIS-EBooks/EBooks/French"
OUT = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "Book", "L4")
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
model = WhisperModel("medium", device="cpu", compute_type="int8", cpu_threads=8)
for folder in sorted(os.listdir(SRC)):
    if "parlez" not in unicodedata.normalize("NFC", folder):
        continue
    slug = "parlez" + folder.strip()[-1]
    res_dir = os.path.join(SRC, folder, "resources")
    dst = os.path.join(OUT, f"audio_{slug}.json")
    done = {r["file"]: r for r in json.load(open(dst, encoding="utf-8"))} if os.path.exists(dst) else {}
    files = sorted(f for f in os.listdir(res_dir) if f.endswith(".mp3"))
    for k, f in enumerate(files):
        if f in done:
            continue
        segs, info = model.transcribe(os.path.join(res_dir, f), language="fr", beam_size=5, vad_filter=False)
        text = " ".join(s.text.strip() for s in segs).strip()
        done[f] = dict(file=f, seconds=round(info.duration, 1), text=text)
        if k % 10 == 0 or k == len(files) - 1:
            os.makedirs(OUT, exist_ok=True)
            json.dump(sorted(done.values(), key=lambda r: r["file"]), open(dst, "w", encoding="utf-8"), ensure_ascii=False, indent=1)
            print(f"{slug}: {len(done)}/{len(files)}", flush=True)
print("TRANSCRIPTION DONE", flush=True)
