"""Redact only the synthetic workspace path displayed in content-search errors.
Videos are sampled at 5 fps, retaining their original duration. No time is cut.
"""
import sys, subprocess
from pathlib import Path
from PIL import Image, ImageDraw, ImageFont
FONT=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf',12)
def redact(im):
    region=im.crop((360,129,920,164))
    if any(r>200 and g<120 and b<150 for r,g,b in region.getdata()):
        draw=ImageDraw.Draw(im)
        draw.rectangle((360,129,920,162),fill=(253,253,253))
        draw.text((365,133),'Failed to search workspace contents in [path redacted].',font=FONT,fill=(255,45,65))
    return im
source=Path(sys.argv[1]); dest=Path(sys.argv[2])
if source.suffix=='.png':
    redact(Image.open(source).convert('RGB')).save(dest)
else:
    w,h=1280,800
    read=subprocess.Popen(['ffmpeg','-v','error','-i',str(source),'-vf','fps=5,scale=1280:800','-f','rawvideo','-pix_fmt','rgb24','pipe:1'],stdout=subprocess.PIPE)
    write=subprocess.Popen(['ffmpeg','-v','error','-y','-f','rawvideo','-pix_fmt','rgb24','-s','1280x800','-r','5','-i','pipe:0','-c:v','libx264','-preset','veryfast','-crf','20','-pix_fmt','yuv420p','-movflags','+faststart',str(dest)],stdin=subprocess.PIPE)
    while True:
        buf=read.stdout.read(w*h*3)
        if not buf:break
        im=Image.frombytes('RGB',(w,h),buf)
        write.stdin.write(redact(im).tobytes())
    write.stdin.close()
    assert read.wait()==0
    assert write.wait()==0
