main
John Lauer Keep short trailing subtitle fragments with their spoken phrase d18b09e
"""Remove measured padded silence; retain each scene's complete visual span at faster playback."""
from pathlib import Path
import json,re,subprocess,math,hashlib,difflib,textwrap,os
R=Path(__file__).resolve().parents[1];old=R/'videos/full-edit-r10';out=R/os.environ.get('LOAD_EDIT_OUT','videos/full-edit-r10-tight');out.mkdir(exist_ok=True);(out/'segments').mkdir(exist_ok=True)
report=json.loads((old/'edit-report.json').read_text());words=[w for s in json.loads((old/'transcription-words.json').read_text())['segments'] for w in s['words']]
def norm(w):
 w=re.sub(r'[^a-z0-9]','',w.lower());return {'20':'twenty','7000':'seventhousand','keycad':'kicad','snacks':'snags'}.get(w,w)
def probe(p):return float(subprocess.check_output(['ffprobe','-v','error','-show_entries','format=duration','-of','csv=p=0',str(p)],text=True))
def stamp(t):
 x=round(t*1000);return f'{x//3600000:02}:{x//60000%60:02}:{x//1000%60:02}.{x%1000:03}'
def sha(p):return hashlib.sha256(p.read_bytes()).hexdigest()
source_t=0;dest_t=0;rows=[];cues=[];chapters=[];unmatched=[]
for i,s in enumerate(report['scenes']):
 src=R/s['output'];duration=s['duration'];log=subprocess.run(['ffmpeg','-hide_banner','-i',str(src),'-vn','-af',f'apad=whole_dur={duration},silencedetect=noise=-38dB:d=0.12','-t',str(duration),'-f','null','-'],capture_output=True,text=True,check=True).stderr
 gaps=[(float(a),float(b)) for a,b in re.findall(r'silence_start: ([\d.]+).*?silence_end: ([\d.]+)',log,re.S)]
 removes=[]
 for a,b in gaps:
  boundary=a<.15 or b>duration-.15
  if not boundary and b-a<.7:continue
  pad=.06 if boundary else .175
  lo=math.ceil((a+pad)*48000)/48000;hi=math.floor((b-pad)*48000)/48000
  if hi>lo:removes.append((lo,hi))
 keeps=[];p=0
 for a,b in removes:
  if a>p:keeps.append((p,a))
  p=b
 if p<duration:keeps.append((p,duration))
 length=sum(b-a for a,b in keeps);frames=math.ceil(length*30);length=frames/30
 def map_time(t):return min(length,max(0,sum(max(0,min(t,b)-a) for a,b in keeps)))
 target=out/'segments'/f'{i:03}.mp4'
 if not target.exists():
  audio=';'.join(f'[0:a]atrim=start={a}:end={b},asetpts=PTS-STARTPTS[a{k}]' for k,(a,b) in enumerate(keeps));audio+=';'+''.join(f'[a{k}]' for k in range(len(keeps)))+f'concat=n={len(keeps)}:v=0:a=1,apad[a]'
  vf=f'[0:v]setpts=(PTS-STARTPTS)*{length/duration},fps=30,scale={os.environ.get('LOAD_EDIT_WIDTH','1280')}:{os.environ.get('LOAD_EDIT_HEIGHT','720')},setsar=1[v]'
  subprocess.run(['ffmpeg','-v','error','-y','-i',str(src),'-filter_complex',audio+';'+vf,'-map','[v]','-map','[a]','-t',str(length),'-c:v','libx264','-preset','veryfast','-threads','2','-crf','22','-g','30','-keyint_min','30','-pix_fmt','yuv420p','-c:a','aac','-b:a','128k','-ar','48000','-ac','2','-movflags','+faststart',str(target)],check=True)
 ref=s['narration'].split();ws=[w for w in words if source_t-.15 <= w['start'] < source_t+duration-.08];matcher=difflib.SequenceMatcher(None,[norm(w) for w in ref],[norm(w['word']) for w in ws],autojunk=False);timings=[None]*len(ref)
 for tag,a,b,c,d in matcher.get_opcodes():
  if tag=='equal':
   for k,j in zip(range(a,b),range(c,d)):timings[k]=(max(0,ws[j]['start']-source_t),min(duration,ws[j]['end']-source_t))
  elif a<b:
   low=max(0,ws[c]['start']-source_t) if c<len(ws) else duration-.2;high=min(duration,ws[d-1]['end']-source_t) if d>c else low+.15
   if high<=low:high=low+.15
   for k in range(a,b):timings[k]=(low+(high-low)*(k-a)/(b-a),low+(high-low)*(k+1-a)/(b-a))
   unmatched.append({'scene':s['id'],'reference':' '.join(ref[a:b]),'recognized':' '.join(w['word'] for w in ws[c:d]),'timing':'ASR span interpolation'})
 group=[];start=0
 for k,w in enumerate(ref):
  if not group:start=k
  group.append(w);text=' '.join(group)
  if len(text)>=58 or len(group)>=10 or re.search(r'[.!?]$',w) or k==len(ref)-1:
   a=dest_t+map_time(timings[start][0]);b=dest_t+map_time(timings[k][1])+.10;b=min(dest_t+length,b)
   if b>a:cues.append({'start':round(a,3),'end':round(b,3),'text':'\n'.join(textwrap.wrap(text,42)),'scene':s['id']})
   group=[]
 chapters.append({'t':round(dest_t,3),'title':s['id'].replace('-',' ')})
 rows.append({'id':s['id'],'source':s['output'],'sourceSha256':sha(src),'sourceStart':source_t,'outputStart':dest_t,'sourceDuration':duration,'duration':length,'videoSpeed':duration/length,'removedAudioIntervals':removes,'output':str(target.relative_to(R)),'narration':s['narration']})
 source_t+=duration;dest_t+=length;print(i,s['id'],round(duration-length,3),'seconds removed',flush=True)
# Merge short trailing fragments into a readable two-line cue.
merged=[]
for c in cues:
 if merged and len(c['text'].split())<=3 and c['scene']==merged[-1]['scene'] and len(merged[-1]['text'].replace('\n',' ')+' '+c['text'].replace('\n',' '))<=84:
  merged[-1]['text']='\n'.join(textwrap.wrap(merged[-1]['text'].replace('\n',' ')+' '+c['text'].replace('\n',' '),42));merged[-1]['end']=c['end']
 else:merged.append(c)
cues=merged
# Resolve ASR cue boundary overlap without repeating or dropping script words.
for a,b in zip(cues,cues[1:]):a['end']=min(a['end'],b['start'])
assert all(c['end']>c['start'] for c in cues)
p=out/'concat.txt';p.write_text(''.join(f"file '{R/r['output']}'\n" for r in rows));video=out/'electronic-load-r10-tight-web.mp4'
subprocess.run(['ffmpeg','-v','error','-y','-f','concat','-safe','0','-i',str(p),'-c','copy','-movflags','+faststart',str(video)],check=True)
(out/'captions.vtt').write_text('WEBVTT\n\n'+'\n\n'.join(f"{stamp(c['start'])} --> {stamp(c['end'])}\n{c['text']}" for c in cues)+'\n')
(out/'captions.srt').write_text('\n\n'.join(f"{i+1}\n{stamp(c['start']).replace('.',',')} --> {stamp(c['end']).replace('.',',')}\n{c['text']}" for i,c in enumerate(cues))+'\n')
(out/'chapters.json').write_text(json.dumps(chapters,indent=2)+'\n');(out/'caption-alignment.json').write_text(json.dumps({'method':'Final-mix ASR word timestamps aligned to exact authored narration; mismatched spans interpolated, then remapped through audio edit. Not manually word-aligned.','corrections':unmatched,'cues':cues},indent=2)+'\n')
(out/'edit-report.json').write_text(json.dumps({'status':'review-cut','sourceVideo':report['file'],'duration':probe(video),'sha256':sha(video),'sourceDuration':report['durationSeconds'],'silenceThresholdDb':-38,'minimumGapSeconds':.7,'retainedPauseSeconds':.35,'scenes':rows,'captionCues':len(cues),'physicalQualification':False},indent=2)+'\n');print('FINAL',probe(video),'CUES',len(cues),flush=True)