#!/usr/bin/env python3
from pathlib import Path
import json, subprocess, time
from faster_whisper import WhisperModel

SRC=Path('/home/spazio/ksd30_transcription/downloads')
OUT=Path('/home/spazio/ksd30_transcription/transcripts')
OUT.mkdir(parents=True,exist_ok=True)
model=WhisperModel('small',device='cpu',compute_type='int8')
media=sorted([p for p in SRC.iterdir() if p.suffix.lower() in ('.mp3','.mp4')])
for n,p in enumerate(media,1):
    txt=OUT/(p.stem+'_transcript.txt')
    meta=OUT/(p.stem+'_meta.json')
    if txt.exists() and meta.exists():
        try:
            m=json.loads(meta.read_text('utf8'))
            if m.get('complete'):
                print(f'SKIP {n}/{len(media)} {p.name}',flush=True); continue
        except: pass
    print(f'START {n}/{len(media)} {p.name}',flush=True)
    started=time.time(); segs,info=model.transcribe(str(p),language='ru',vad_filter=True,beam_size=5,condition_on_previous_text=True)
    paras=[]; last_end=0.0
    checkpoint=OUT/(p.stem+'_checkpoint.txt')
    for i,s in enumerate(segs,1):
        t=s.text.strip()
        if t: paras.append(t); last_end=float(s.end)
        if i%50==0:
            checkpoint.write_text('\n\n'.join(paras),'utf8')
            print(f'PROGRESS {n}/{len(media)} segments={i} end={last_end:.1f}',flush=True)
    body='\n\n'.join(paras).strip()+'\n'
    txt.write_text(body,'utf8')
    probe=subprocess.run(['ffprobe','-v','error','-show_entries','format=duration','-of','json',str(p)],capture_output=True,text=True,check=True)
    duration=float(json.loads(probe.stdout)['format']['duration'])
    meta.write_text(json.dumps({'source':p.name,'language':getattr(info,'language','ru'),'duration':duration,'last_speech_end':last_end,'segments':len(paras),'complete':True,'elapsed':time.time()-started},ensure_ascii=False,indent=2),'utf8')
    checkpoint.unlink(missing_ok=True)
    print(f'DONE {n}/{len(media)} {p.name} duration={duration:.1f} last={last_end:.1f}',flush=True)
print(f'BATCH_DONE files={len(media)}',flush=True)
