#!/usr/bin/env python3
import importlib.util, json, re, time
from pathlib import Path
PROJECT=Path('/data/video-pipeline/Youtube-Video-Maker/Project/28052026-002-Tran-Quang-Dieu-Bui-Thi-Xuan')
STEP7=PROJECT/'scripts_run_step_07_tts_v2.py'
SCENES=PROJECT/'script/scenes.json'
OUT=PROJECT/'audio/pronunciation_review_candidates_tran_phonetic_scene070_cand1_only'

def log(m): print(time.strftime('%Y-%m-%d %H:%M:%S ')+m, flush=True)

def main():
    OUT.mkdir(parents=True, exist_ok=True)
    spec=importlib.util.spec_from_file_location('step7', STEP7)
    mod=importlib.util.module_from_spec(spec); spec.loader.exec_module(mod)
    scenes={s['scene_id']:s for s in json.loads(SCENES.read_text(encoding='utf-8'))['scenes']}
    s=scenes['scene_070']
    base,changes=mod.normalize(s['narration'])
    tts=re.sub(r'\btrần\s+quang\s+diệu\b','Chần Quang Diệu',base,flags=re.I)
    old_audio_dir=mod.AUDIO_DIR; mod.AUDIO_DIR=OUT
    try:
        cand_id=f'scene_070_cand1_retry_{time.strftime("%H%M%S")}'
        item={'scene_id':cand_id,'narration':s['narration'],'tts_text':tts,'normalization':changes+['scene070_cand1_retry_phonetic_chan'],'output':str(OUT/f'{cand_id}.wav')}
        log(f'GEN {cand_id}')
        r=mod.generate(item)
        log(f"{r.get('status')} {cand_id} output={OUT/f'{cand_id}.wav'} dur={r.get('duration')}")
    finally:
        mod.AUDIO_DIR=old_audio_dir
if __name__=='__main__': main()
