"""Remove private PR metadata; preserve only Attachments and the synthetic demo image.
Usage: python3 publish-captures.py RAW_RUN OUTPUT_DIR SIDE
"""
from PIL import Image, ImageDraw, ImageFont
import pathlib,sys,subprocess,json
src,out,side=pathlib.Path(sys.argv[1]),pathlib.Path(sys.argv[2]),sys.argv[3]
out.mkdir(exist_ok=True,parents=True)
font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf',20)
im=Image.open(src/'tiles-2.png').convert('RGB')
# Only generic app chrome and the synthetic PASTE TEST demo remain in this crop.
im.crop((0,1520,1080,1940)).save(out/f'{side}-attachments.png')
Image.open(src/'viewer-1.png').save(out/f'{side}-viewer.png')
info=json.loads(subprocess.check_output(['ffprobe','-v','quiet','-show_streams','-of','json',str(src/'flow.mp4')]))
video=next(x for x in info['streams'] if x['codec_type']=='video')
w,h=int(video['width']),int(video['height'])
dec=subprocess.Popen(['ffmpeg','-v','error','-i',str(src/'flow.mp4'),'-vf','fps=10,scale=540:1212','-f','rawvideo','-pix_fmt','rgb24','-'],stdout=subprocess.PIPE)
enc=subprocess.Popen(['ffmpeg','-v','error','-y','-f','rawvideo','-pix_fmt','rgb24','-s','540x1212','-r','10','-i','-','-an','-c:v','libx264','-preset','fast','-crf','21','-pix_fmt','yuv420p','-movflags','+faststart',str(out/f'{side}-flow.mp4')],stdin=subprocess.PIPE)
i=0
while True:
 data=dec.stdout.read(540*1212*3)
 if not data: break
 if len(data)!=540*1212*3: raise RuntimeError('short frame')
 frame=Image.frombytes('RGB',(540,1212),data)
 viewer=all(max(frame.getpixel(p))<12 for p in [(20,150),(100,300),(500,200)])
 if not viewer:
  clean=Image.new('RGB',frame.size,'#151515')
  clean.paste(frame.crop((0,760,540,970)),(0,760))
  frame=clean
 draw=ImageDraw.Draw(frame)
 draw.rectangle((0,0,540,90),fill='#151515')
 draw.text((18,14),f'{side.title()} · Android 16 · Pixel 9',font=font,fill='white')
 draw.text((18,45),f'{i/10:.1f}s · private PR metadata hidden',font=font,fill='white')
 enc.stdin.write(frame.tobytes()); i+=1
enc.stdin.close()
assert dec.wait()==0 and enc.wait()==0
print('Published frames',i)
