#!/usr/bin/python3
import tkinter as tk
from tkinter import ttk,filedialog,messagebox,colorchooser
import pathlib,subprocess,threading,tempfile,json,sys,os,queue,traceback
root=tk.Tk(); root.title('FreeCaptionEditor 0.3'); root.geometry('680x470')
files=[]; out=tk.StringVar(); lang=tk.StringVar(value='es'); model=tk.StringVar(value='base'); size=tk.IntVar(value=64); pos=tk.StringVar(value='Bottom'); color=tk.StringVar(value='#FFFF00'); status=tk.StringVar(value='Select clips and output folder'); q=queue.Queue()
base=pathlib.Path.home()/'.local/share/freecaptioneditor'; env=base/'venv'; py=env/'bin/python'
def choose():
 files[:]=filedialog.askopenfilenames(filetypes=[('Videos','*.mp4 *.mkv *.mov *.webm *.avi'),('All','*')]); label.config(text=f'{len(files)} clip(s) selected')
def folder():
 p=filedialog.askdirectory();
 if p: out.set(p)
def pick():
 c=colorchooser.askcolor(color.get())[1]
 if c: color.set(c)
def run(cmd,**kw):
 result=subprocess.run([str(x) for x in cmd],capture_output=True,text=True,encoding='utf-8',errors='replace',**kw)
 with (base/'diagnostic.log').open('a',encoding='utf8') as log:
  log.write('\nCOMMAND: '+repr([str(x) for x in cmd])+'\n'+result.stderr+'\n')
 if result.returncode:
  raise RuntimeError(f'Exit {result.returncode}: '+(result.stderr.strip() or result.stdout.strip() or 'No diagnostic output'))
 return result.stdout
def ts(t):
 n=max(0,round(t*100)); return f'{n//360000}:{n//6000%60:02}:{n//100%60:02}.{n%100:02}'
def asscolor(c): return '&H00'+c[5:7]+c[3:5]+c[1:3]
def clean(s): return s.replace('\\','').replace('{','').replace('}','').replace('\n',' ')
def worker(paths,dest,language,mod,sz,position,highlight):
 try:
  base.mkdir(parents=True,exist_ok=True)
  (base/'diagnostic.log').write_text('FreeCaptionEditor 0.3\n',encoding='utf8')
  if not py.exists():
   q.put(('status','Creating private Python environment...')); run([sys.executable,'-m','venv',env])
  if subprocess.run([py,'-c','import faster_whisper'],capture_output=True).returncode:
   q.put(('status','Installing Whisper (internet required)...')); run([py,'-m','pip','install','faster-whisper'])
  helper='''import sys,json,wave\nimport numpy as np\nfrom faster_whisper import WhisperModel\nm=WhisperModel(sys.argv[1],device="cpu",compute_type="int8")\nwith wave.open(sys.argv[2], "rb") as f:\n audio=np.frombuffer(f.readframes(f.getnframes()),dtype="<i2").astype(np.float32)/32768.0\ns,_=m.transcribe(audio,language=None if sys.argv[3]=="auto" else sys.argv[3],word_timestamps=True)\nprint(json.dumps([[w.start,w.end,w.word] for seg in s for w in (seg.words or [])],ensure_ascii=False))'''
  for i,p in enumerate(paths):
   with tempfile.TemporaryDirectory() as audio_tmp:
    wav=pathlib.Path(audio_tmp)/'audio.wav'
    q.put(('status',f'Extracting audio {i+1}/{len(paths)}...'))
    run(['ffmpeg','-nostdin','-v','error','-i',p,'-map','0:a:0','-vn','-ac','1','-ar','16000','-c:a','pcm_s16le',wav])
    q.put(('status',f'Transcribing {i+1}/{len(paths)} (first run downloads model)...'))
    words=json.loads(run([py,'-c',helper,mod,wav,language]))
    if not words: raise RuntimeError('No speech recognized in '+str(p))
   info=json.loads(subprocess.check_output(['ffprobe','-v','error','-select_streams','v:0','-show_entries','stream=width,height:stream_side_data=rotation','-of','json',p],text=True))['streams'][0]; w,h=info['width'],info['height']; rot=next((x.get('rotation',0) for x in info.get('side_data_list',[])),0)
   if abs(rot)%180==90: w,h=h,w
   fs=max(12,round(sz*h/1920)); margin=round(h*.15); align={'Bottom':2,'Center':5,'Top':8}[position]
   header=f'''[Script Info]\nScriptType: v4.00+\nPlayResX: {w}\nPlayResY: {h}\nWrapStyle: 0\n[V4+ Styles]\nFormat: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding\nStyle: Default,DejaVu Sans,{fs},&H00FFFFFF,&H00FFFFFF,&H00000000,&H80000000,-1,0,0,0,100,100,0,0,1,3,1,{align},{int(w*.06)},{int(w*.06)},{margin},1\n[Events]\nFormat: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\n'''
   lines=[]
   for j in range(0,len(words),4):
    group=words[j:j+4]
    for k,(a,b,t) in enumerate(group):
     end=group[k+1][0] if k+1<len(group) else b
     if end<=a: continue
     phrase=' '.join(('{\\c'+asscolor(highlight)+'&}'+clean(x[2]).strip()+'{\\c&H00FFFFFF&}') if l==k else clean(x[2]).strip() for l,x in enumerate(group))
     lines.append(f'Dialogue: 0,{ts(a)},{ts(end)},Default,,0,0,0,,{phrase}')
   target=pathlib.Path(dest)/(pathlib.Path(p).stem+'_captioned.mp4'); n=2
   while target.exists(): target=pathlib.Path(dest)/(pathlib.Path(p).stem+f'_captioned_{n}.mp4'); n+=1
   q.put(('status',f'Exporting {i+1}/{len(paths)}...'))
   with tempfile.TemporaryDirectory() as tmp:
    pathlib.Path(tmp,'captions.ass').write_text(header+'\n'.join(lines),encoding='utf8')
    run(['ffmpeg','-nostdin','-v','error','-i',p,'-vf','ass=captions.ass','-c:v','libx264','-preset','fast','-crf','20','-c:a','aac','-movflags','+faststart','-n',target],cwd=tmp)
   q.put(('progress',100*(i+1)/len(paths)))
  q.put(('done','Finished successfully'))
 except Exception as e:
  try:
   with (base/'diagnostic.log').open('a',encoding='utf8') as log: log.write(traceback.format_exc())
  except OSError: pass
  q.put(('error',str(e)[-1800:]+'\n\nFull log: '+str(base/'diagnostic.log')))
def start():
 if not files or not out.get(): messagebox.showerror('Missing input','Select videos and output folder'); return
 try: sz=size.get(); assert 20<=sz<=160
 except Exception: messagebox.showerror('Size','Choose 20–160'); return
 btn.config(state='disabled'); bar['value']=0; threading.Thread(target=worker,args=(files[:],out.get(),lang.get(),model.get(),sz,pos.get(),color.get()),daemon=True).start()
def poll():
 while not q.empty():
  kind,val=q.get()
  if kind=='progress': bar['value']=val
  else: status.set(val)
  if kind in ('done','error'):
   btn.config(state='normal')
   if kind=='error': messagebox.showerror('Error',val)
 root.after(150,poll)
f=ttk.Frame(root,padding=18); f.pack(fill='both',expand=True)
ttk.Label(f,text='FreeCaptionEditor',font=('Sans',20,'bold')).pack(anchor='w'); ttk.Button(f,text='Select video clips',command=choose).pack(anchor='w',pady=6); label=ttk.Label(f,text='No clips selected'); label.pack(anchor='w')
r=ttk.Frame(f); r.pack(fill='x',pady=8); ttk.Entry(r,textvariable=out).pack(side='left',fill='x',expand=True); ttk.Button(r,text='Output folder',command=folder).pack(side='left')
for title,var,values in [('Language',lang,['auto','es','en','fr','pt','it','de']),('Whisper model',model,['tiny','base','small','medium']),('Position',pos,['Bottom','Center','Top'])]:
 r=ttk.Frame(f); r.pack(fill='x',pady=3); ttk.Label(r,text=title,width=20).pack(side='left'); ttk.Combobox(r,textvariable=var,values=values,state='readonly').pack(side='left')
r=ttk.Frame(f); r.pack(fill='x',pady=4); ttk.Label(r,text='Font size (1080x1920)',width=20).pack(side='left'); ttk.Spinbox(r,from_=20,to=160,textvariable=size,width=8).pack(side='left'); ttk.Button(r,text='Highlight color',command=pick).pack(side='left',padx=12)
btn=ttk.Button(f,text='Generate captions',command=start); btn.pack(anchor='w',pady=10); bar=ttk.Progressbar(f); bar.pack(fill='x'); ttk.Label(f,textvariable=status,wraplength=630).pack(anchor='w',pady=8); root.after(150,poll); root.mainloop()
