Datasets:
Download pipeline/workers.py from faraway00/StyleEdit: direct link, hf CLI and curl.
- Browser
- Download file 7.2 kB
-
https://huggingface.co/datasets/faraway00/StyleEdit/resolve/main/pipeline/workers.py
- Command line
-
hf download hf://datasets/faraway00/StyleEdit/pipeline/workers.py
-
curl -L -o workers.py https://huggingface.co/datasets/faraway00/StyleEdit/resolve/main/pipeline/workers.py
7.2 kB
| """Long-lived RPC model workers; independent environments, exclusive GPU forwards.""" | |
| import os | |
| os.environ.setdefault('HF_HUB_OFFLINE','1') | |
| import fcntl,json,sys,time,traceback,contextlib,subprocess | |
| from pathlib import Path | |
| from common import * | |
| from video_io import backend,decode_flags,decode_output_flags,encoder_flags | |
| from gpu_depth import infer_depth,percentiles,encode_device | |
| MODE=sys.argv[1] | |
| OVERLAP=os.environ.get('STYLEEDIT_OVERLAP','1')=='1' | |
| # Model libraries print progress to stdout. Keep the RPC stream private. | |
| RPC=sys.stdout;sys.stdout=sys.stderr | |
| import numpy as np,torch | |
| from PIL import Image | |
| import torch.nn.functional as F | |
| torch.set_num_threads(4) | |
| lock=open(os.environ.get('STYLEEDIT_GPU_LOCK','/opt/styleedit-gpu.lock'),'a') | |
| t=time.monotonic() | |
| if MODE=='filter': | |
| sys.path.insert(0,str(CORE));sys.path.insert(0,str(CORE/'code')) | |
| from run_pipeline import pair_run | |
| from pipelined_filter import pair_run as overlapped_pair_run,gpu_section | |
| from curation.eden_encoder import create_checkpoint_dinov3_encoder | |
| from curation.filter import weights_ready | |
| w=CORE/'weights/vision-encoder';weights_ready(w) | |
| model=create_checkpoint_dinov3_encoder(str(w/'backbone'),str(w/'projection.safetensors'),projection_dim=1024,patchify_factor=1).cuda().eval() | |
| cfg=json.loads((CORE/'pipeline.json').read_text()) | |
| else: | |
| from depth_anything_3.api import DepthAnything3 | |
| model=DepthAnything3.from_pretrained('/opt/da3-large-weights').cuda().eval() | |
| da3_provenance={'config_sha256':sha('/opt/da3-large-weights/config.json'),'weights_sha256':sha('/opt/da3-large-weights/model.safetensors'),'code_commit':subprocess.check_output(['git','-C','/opt/depth-anything-3-code','rev-parse','HEAD'],text=True).strip()} | |
| torch.cuda.synchronize() | |
| RPC.write(json.dumps({'ready':MODE,'load_seconds':time.monotonic()-t,'gpu':torch.cuda.get_device_name(0),'torch':torch.__version__})+'\n');RPC.flush() | |
| def depth(job): | |
| start=time.monotonic();d=Path(job['dir']);meta=ffprobe(d/'source.mp4');w,h=meta['width'],meta['height'];n=meta['frames'] | |
| if not 1<=n<=160:raise ValueError('Joint DA3 frame budget exceeded (160); never silently truncate/chunk') | |
| pts=np.array(meta['pts']);fps=float(__import__('fractions').Fraction(meta['avg_frame_rate'])) | |
| if max(abs(pts-pts[0]-np.arange(n)/fps))>0.001:raise ValueError('VFR source requires explicit timestamp-preserving encoder') | |
| if n*w*h*3>2*1024**3:raise ValueError('Decoded RGB exceeds 2GiB per-video memory cap') | |
| t=time.monotonic();raw=subprocess.check_output(['ffmpeg','-v','error','-threads','2',*decode_flags(),'-i',str(d/'source.mp4'),*decode_output_flags(),'-f','rawvideo','-pix_fmt','rgb24','pipe:1']);rgb=np.frombuffer(raw,np.uint8).reshape(-1,h,w,3) | |
| assert len(rgb)==n;decode_seconds=time.monotonic()-t | |
| torch.cuda.reset_peak_memory_stats();torch.cuda.synchronize();t=time.monotonic() | |
| with contextlib.ExitStack() as gpu_stack: | |
| if OVERLAP: | |
| fcntl.flock(lock,fcntl.LOCK_EX);gpu_stack.callback(fcntl.flock,lock,fcntl.LOCK_UN) | |
| with torch.inference_mode():dep_gpu=infer_depth(model,[Image.fromarray(x) for x in rgb]) | |
| torch.cuda.synchronize() | |
| inference_seconds=time.monotonic()-t | |
| if len(dep_gpu)!=n or not bool(torch.isfinite(dep_gpu).all()) or bool((dep_gpu<=0).any()):raise ValueError('Invalid DA3 depth') | |
| dep=dep_gpu if backend()=='cuda' else dep_gpu.cpu().numpy();raw_shape=list(dep.shape) | |
| t=time.monotonic() | |
| # One fixed inverse-depth mapping per clip; only video is persisted. | |
| with contextlib.ExitStack() as mapping_stack: | |
| if OVERLAP and backend()=='cuda': | |
| fcntl.flock(lock,fcntl.LOCK_EX);mapping_stack.callback(fcntl.flock,lock,fcntl.LOCK_UN) | |
| lo,hi=percentiles(dep) if backend()=='cuda' else np.percentile(1/dep,[0.5,99.5]) | |
| assert hi>lo | |
| mapping_seconds=time.monotonic()-t;conversion_seconds=pipe_write_seconds=0.0 | |
| device_stats={} | |
| if backend()=='cuda': | |
| with contextlib.ExitStack() as conversion_stack: | |
| if OVERLAP: | |
| fcntl.flock(lock,fcntl.LOCK_EX);conversion_stack.callback(fcntl.flock,lock,fcntl.LOCK_UN) | |
| device_stats=encode_device(dep,float(lo),float(hi),w,h,meta['avg_frame_rate'],d/'depth.mp4') | |
| conversion_seconds=device_stats['conversion_seconds'];encoder_finish_seconds=device_stats['encode_mux_seconds']-conversion_seconds | |
| else: | |
| 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',*encoder_flags(),'-pix_fmt','yuv420p','-movflags','+faststart',str(d/'depth.mp4')],stdin=subprocess.PIPE) | |
| try: | |
| for z in dep: | |
| stage_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) | |
| conversion_seconds+=time.monotonic()-stage_t | |
| stage_t=time.monotonic();proc.stdin.write(gray.tobytes());pipe_write_seconds+=time.monotonic()-stage_t | |
| finally:proc.stdin.close() | |
| stage_t=time.monotonic() | |
| if proc.wait()!=0:raise RuntimeError('Depth encoder failed') | |
| encoder_finish_seconds=time.monotonic()-stage_t | |
| stage_t=time.monotonic() | |
| check=ffprobe(d/'depth.mp4') | |
| if check['frames']!=n or max(abs(np.array(check['pts'])-check['pts'][0]-(pts-pts[0])))>.001:raise ValueError('Depth video timestamp mismatch') | |
| out={'model':'depth-anything/DA3-LARGE','model_provenance':da3_provenance,'process_res':504,'joint_frames':n,'source_width':w,'source_height':h,'raw_depth_shape':raw_shape,'stored_depth':'depth.mp4 only','units':'relative_depth_not_meters','video_mapping':'inverse depth, per-video fixed percentile 0.5/99.5; near bright','inverse_depth_clip':[float(lo),float(hi)],'decode_seconds':decode_seconds,'inference_seconds':inference_seconds,'video_backend':backend(),'depth_conversion':'GPU resident depth -> CUDA FP32 mapping -> NVENC device input, chunk8' if backend()=='cuda' else 'CPU FP32 resize/inverse-depth/quantize','encoding':{**({'codec':'h264_nvenc','api':'PyNvVideoCodec 2.2.3 device input','preset':'p4','rate_control':'constqp','qp':16,'device_stats':device_stats} if backend()=='cuda' else {'codec':'libx264','preset':'veryfast','threads':8,'crf':16}),'mapping_seconds':mapping_seconds,'conversion_seconds':conversion_seconds,'pipe_write_seconds':pipe_write_seconds,'encoder_finish_seconds':encoder_finish_seconds,'validation_seconds':time.monotonic()-stage_t},'encode_save_validate_seconds':time.monotonic()-t,'total_seconds':time.monotonic()-start,'peak_gpu_gib':torch.cuda.max_memory_allocated()/1024**3,'timestamp_validation':'all frames <=1ms','torch':torch.__version__} | |
| atomic(d/'depth.json',out);return out | |
| for line in sys.stdin: | |
| try: | |
| job=json.loads(line) | |
| with contextlib.ExitStack() as stack: | |
| if not OVERLAP: | |
| fcntl.flock(lock,fcntl.LOCK_EX);stack.callback(fcntl.flock,lock,fcntl.LOCK_UN) | |
| if MODE=='filter': | |
| args=(job['row'],[job['dir']+'/'+s+'.mp4' for s in ['source','edited']],model,cfg) | |
| out=overlapped_pair_run(*args,lock) if OVERLAP else pair_run(*args) | |
| else:out=depth(job) | |
| reply={'ok':True,'result':out} | |
| except Exception as e: | |
| torch.cuda.empty_cache();reply={'ok':False,'error':type(e).__name__+': '+str(e),'traceback':traceback.format_exc()} | |
| RPC.write(json.dumps(reply)+'\n');RPC.flush() | |