Datasets:
Download pipeline/benchmark_encoding.py from faraway00/StyleEdit: direct link, hf CLI and curl.
- Browser
- Download file 3.95 kB
-
https://huggingface.co/datasets/faraway00/StyleEdit/resolve/main/pipeline/benchmark_encoding.py
- Command line
-
hf download hf://datasets/faraway00/StyleEdit/pipeline/benchmark_encoding.py
-
curl -L -o benchmark_encoding.py https://huggingface.co/datasets/faraway00/StyleEdit/resolve/main/pipeline/benchmark_encoding.py
3.95 kB
| """Measure current video-only DA3 postprocessing on a real pilot source.""" | |
| import sys,json,time,subprocess,tempfile,shutil,os | |
| from pathlib import Path | |
| sys.argv=['benchmark','depth'] | |
| exec((Path(__file__).parent/'workers.py').read_text().split('def depth(job):')[0]) | |
| import requests | |
| scratch=Path(tempfile.mkdtemp(prefix='styleedit-encoding-',dir='/opt')) | |
| try: | |
| row=json.loads(Path('/workspace/styleedit-streaming-20261024/metadata.jsonl').read_text().splitlines()[0]) | |
| r=requests.get(row['source_video'],timeout=120);r.raise_for_status();src=scratch/'source.mp4';src.write_bytes(r.content) | |
| meta=ffprobe(src);w,h=meta['width'],meta['height'];n=meta['frames'] | |
| rgb=np.frombuffer(subprocess.check_output(['ffmpeg','-v','error','-threads','2','-i',str(src),'-f','rawvideo','-pix_fmt','rgb24','pipe:1']),np.uint8).reshape(-1,h,w,3) | |
| ts=time.monotonic() | |
| with torch.inference_mode():p=model.inference(image=[Image.fromarray(x) for x in rgb],process_res=504,process_res_method='upper_bound_resize',export_dir=None) | |
| torch.cuda.synchronize();inference=time.monotonic()-ts;dep=p.depth.astype(np.float32) | |
| ts=time.monotonic();lo,hi=np.percentile(1/dep,[.5,99.5]);percentile=time.monotonic()-ts | |
| configs=[('current_fast_2',['-c:v','libx264','-threads','2','-preset','fast','-crf','16']),('veryfast_8',['-c:v','libx264','-threads','8','-preset','veryfast','-crf','16']),('nvenc',['-c:v','h264_nvenc','-preset','p4','-rc','constqp','-qp','16'])] | |
| results=[] | |
| for repeat in range(2): | |
| for label,opts in configs: | |
| path=scratch/(label+'.mp4');total=time.monotonic();convert=write=0;refs=[] | |
| proc=subprocess.Popen(['ffmpeg','-y','-v','error','-threads','2','-f','rawvideo','-pix_fmt','gray','-s',f'{w}x{h}','-r',meta['avg_frame_rate'],'-i','pipe:0','-an',*opts,'-pix_fmt','yuv420p','-movflags','+faststart',str(path)],stdin=subprocess.PIPE,stderr=subprocess.PIPE) | |
| try: | |
| for z in dep: | |
| t=time.monotonic();z=F.interpolate(torch.from_numpy(z)[None,None],size=(h,w),mode='bilinear',align_corners=False)[0,0].numpy();gray=np.rint(np.clip((1/np.maximum(z,1e-6)-lo)/(hi-lo),0,1)*255).astype(np.uint8);convert+=time.monotonic()-t | |
| if repeat==0:refs.append(gray) | |
| t=time.monotonic();proc.stdin.write(gray.tobytes());write+=time.monotonic()-t | |
| proc.stdin.close();t=time.monotonic();err=proc.stderr.read().decode();rc=proc.wait();wait=time.monotonic()-t | |
| if rc:raise RuntimeError(err) | |
| t=time.monotonic();check=ffprobe(path);validate=time.monotonic()-t | |
| assert check['frames']==n and np.max(np.abs(np.array(check['pts'])-np.array(meta['pts'])))<=.001 | |
| result={'name':label,'repeat':repeat,'conversion_seconds':convert,'pipe_write_seconds':write,'encoder_finish_seconds':wait,'timestamp_validation_seconds':validate,'postprocess_seconds':time.monotonic()-total+percentile,'bytes':path.stat().st_size} | |
| if repeat==0: | |
| dec=subprocess.Popen(['ffmpeg','-v','error','-threads','2','-i',str(path),'-f','rawvideo','-pix_fmt','gray','pipe:1'],stdout=subprocess.PIPE);mae=[];mse=[] | |
| for ref in refs: | |
| raw=dec.stdout.read(w*h);assert len(raw)==w*h;diff=np.frombuffer(raw,np.uint8).reshape(h,w).astype(np.float32)-ref;mae.append(float(np.abs(diff).mean()));mse.append(float((diff**2).mean())) | |
| assert dec.wait()==0;result.update(decoded_mae_8bit=float(np.mean(mae)),decoded_rmse_8bit=float(np.sqrt(np.mean(mse)))) | |
| results.append(result);print('ENCODING_RESULT',json.dumps(result),file=sys.stderr,flush=True) | |
| except Exception as e: | |
| try:proc.stdin.close() | |
| except:pass | |
| proc.wait();results.append({'name':label,'repeat':repeat,'error':str(e)});print('ENCODING_ERROR',label,str(e),file=sys.stderr,flush=True) | |
| report={'source_id':row['id'],'frames':n,'width':w,'height':h,'inference_seconds':inference,'percentile_seconds':percentile,'npz_saved':False,'results':results} | |
| atomic(Path(__file__).parent/'encoding-benchmark.json',report) | |
| print(json.dumps(report,indent=2),file=sys.stderr) | |
| finally:shutil.rmtree(scratch) | |