import subprocess,sys,json
from PIL import Image,ImageDraw,ImageFont
source,destination=sys.argv[1:3]
hide_label=len(sys.argv)>3
info=json.loads(subprocess.check_output(['ffprobe','-v','error','-select_streams','v:0','-show_entries','stream=width,height,r_frame_rate','-of','json',source]))['streams'][0]
w,h=info['width'],info['height'];fps=info['r_frame_rate']
a=subprocess.Popen(['ffmpeg','-loglevel','error','-i',source,'-f','rawvideo','-pix_fmt','rgb24','pipe:1'],stdout=subprocess.PIPE)
b=subprocess.Popen(['ffmpeg','-y','-loglevel','error','-f','rawvideo','-pixel_format','rgb24','-video_size',f'{w}x{h}','-framerate',fps,'-i','pipe:0','-c:v','libx264','-pix_fmt','yuv420p','-movflags','+faststart',destination],stdin=subprocess.PIPE)
font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf',12)
redacted=0;frames=0
while True:
 data=a.stdout.read(w*h*3)
 if not data:break
 if len(data)!=w*h*3:raise RuntimeError('short frame')
 im=Image.frombytes('RGB',(w,h),data)
 red=any(r>170 and r>g*1.5 and r>bl*1.3 for r,g,bl in im.crop((700,70,1100,107)).getdata())
 if red:
  draw=ImageDraw.Draw(im);draw.rectangle((700,107,1099,200),fill='white');draw.text((724,120),'Notification detail hidden for fixture privacy.',font=font,fill='#555555');draw.text((724,140),'Full authentication error is visible in the terminal.',font=font,fill='#555555');redacted+=1
 if hide_label:
  draw=ImageDraw.Draw(im);draw.rectangle((820,58,1050,98),fill='white');draw.text((825,68),'Environment label hidden',font=font,fill='#555555')
 yellow_rows=[y for y in range(200,min(h,480)) if all(all(abs(c-ref)<=4 for c,ref in zip(im.getpixel((x,y)),(252,244,231))) for x in (650,800,900))]
 if hide_label and yellow_rows:
  y=min(yellow_rows);draw=ImageDraw.Draw(im);draw.rectangle((360,y+2,750,y+29),fill=(253,244,231));draw.text((364,y+9),'SSH environment is reconnecting',font=font,fill='#333333')
 b.stdin.write(im.tobytes());frames+=1
b.stdin.close();a.wait();b.wait();print(f'{frames} frames; {redacted} notification bodies redacted')
