Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files11 unmodified lines1213141516171810 unmodified lines293031323334353637383940418 unmodified lines5051525354555657585960616263646566676869701 unmodified line7273747576777879808182838485868788899091921 unmodified line9495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211 unmodified lines# See the License for the specific language governing permissions and# limitations under the License.import gcimport osimport uuid10 unmodified linesimport xformers.opsfrom huggingface_hub import hf_hub_downloadfrom video_depth_anything.video_depth import VideoDepthAnythingfrom utils.dc_utils import read_video_frames, save_video# ============================================================# XFORMERS -> PYTORCH SDPA COMPATIBILITY SHIM# ============================================================_xf_original = xformers.ops.memory_efficient_attention8 unmodified linesop=None,**kwargs,):"""Route xformers memory-efficient attention throughPyTorch scaled_dot_product_attention.xformers uses:[B, M, H, K]torch SDPA uses:[B, H, M, K]"""if attn_bias is not None and not isinstance(attn_bias,torch.Tensor):return _xf_original(query,key,1 unmodified lineattn_bias,p,scale,op)squeeze = query.dim() == 3if squeeze:q, k, v = (t.unsqueeze(1)for t in (query, key, value))else:q, k, v = (t.transpose(1, 2)for t in (query, key, value))out = F.scaled_dot_product_attention(q,1 unmodified linev,attn_mask=attn_bias,dropout_p=p,scale=scale)return (out.squeeze(1)if squeezeelse out.transpose(1, 2))xformers.ops.memory_efficient_attention = _sdpa_shim# ============================================================# EXAMPLES# ============================================================examples = [["assets/example_videos/davis_rollercoaster.mp4",-1,-1,1280],["assets/example_videos/Tokyo-Walk_rgb.mp4",-1,-1,1280],["assets/example_videos/4158877-uhd_3840_2160_30fps_rgb.mp4",-1,-1,1280],["assets/example_videos/4511004-uhd_3840_2160_24fps_rgb.mp4",-1,-1,1280],["assets/example_videos/1753029-hd_1920_1080_30fps.mp4",-1,-1,1280],["assets/example_videos/davis_burnout.mp4",-1,-1,1280],["assets/example_videos/example_5473765-l.mp4",-1,-1,1280],["assets/example_videos/Istanbul-26920.mp4",-1,-1,1280],["assets/example_videos/obj_1.mp4",-1,-1,1280],["assets/example_videos/sheep_cut1.mp4",-1,-1,1280],]# ============================================================# DEVICE# ============================================================DEVICE = ("cuda"if torch.cuda.is_available()else "cpu")# ============================================================# MODEL CONFIGURATION# ============================================================model_configs = {"vits": {"encoder": "vits","features": 64,"out_channels": [48,96,192,384],},"vitl": {"encoder": "vitl","features": 256,"out_channels": [256,512,1024,1024],},}encoder2name = {"vits": "Small","vitl": "Large",}# Use LARGE modelencoder = "vitl"model_name = encoder2name[encoder]video_depth_anything = VideoDepthAnything(**model_configs[encoder])filepath = hf_hub_download(repo_id=(f"depth-anything/"f"Video-Depth-Anything-{model_name}"),filename=(f"video_depth_anything_{encoder}.pth"),repo_type="model",)video_depth_anything.load_state_dict(torch.load(filepath,map_location="cpu"))video_depth_anything = (video_depth_anything.to(DEVICE).eval())# ============================================================# UI TEXT# ============================================================title = "# Video Depth Anything"description = """Official demo for **Video Depth Anything**, modified to alsoexport the **raw depth prediction as a 32-bit floating-pointOpenEXR image sequence**.The MP4 depth video is only a visualization.For Blender displacement, use the **EXR ZIP**.The EXR files contain the raw floating-point depth values beforeconversion to an 8-bit video."""# ============================================================# SAVE RAW DEPTH AS OPENEXR# ============================================================def save_depths_as_rgb_exr(depths: np.ndarray,output_dir: str):"""Save raw depth frames as 32-bit floating-point EXRs.The same depth value is written into:RGBThis makes the EXRs easy to use with Blender'sImage Texture node.IMPORTANT:No 0-1 normalization.No conversion to uint8.No MP4 compression."""os.makedirs(output_dir,exist_ok=True)float_channel = Imath.PixelType(Imath.PixelType.FLOAT)for i, depth in enumerate(depths):# Explicitly keep data as 32-bit floatdepth = np.ascontiguousarray(depth,dtype=np.float32)if depth.ndim != 2:raise ValueError("Expected depth frame to be H x W. "f"Received: {depth.shape}")height, width = depth.shapeoutput_exr = os.path.join(output_dir,f"frame_{i:05d}.exr")header = OpenEXR.Header(width,height)header["channels"] = {"R": Imath.Channel(float_channel),"G": Imath.Channel(float_channel),"B": Imath.Channel(float_channel),}depth_bytes = depth.tobytes()exr_file = OpenEXR.OutputFile(output_exr,header)try:exr_file.writePixels({"R": depth_bytes,"G": depth_bytes,"B": depth_bytes,})finally:exr_file.close()# ============================================================# ZIP EXR SEQUENCE# ============================================================def zip_directory(source_dir: str,zip_path: str):with zipfile.ZipFile(zip_path,mode="w",compression=zipfile.ZIP_DEFLATED) as zip_file:for filename in sorted(os.listdir(source_dir)):file_path = os.path.join(source_dir,filename)if os.path.isfile(file_path):zip_file.write(file_path,arcname=filename)return zip_path# ============================================================# DEPTH INFERENCE# ============================================================@spaces.GPU(duration=240)def infer_video_depth(input_video: str,max_len: int = -1,target_fps: int = -1,max_res: int = 1280,input_size: int = 518,grayscale: bool = True,output_dir: str = "./outputs",):if not input_video:raise gr.Error("Please upload a video first.")# --------------------------------------------------------# FORCE INPUT SIZE TO MULTIPLE OF 14# --------------------------------------------------------input_size = int(round(float(input_size) / 14.0) * 14)input_size = max(input_size,14)print(f"Using model inference size: "f"{input_size}")# --------------------------------------------------------# READ VIDEO# --------------------------------------------------------frames, target_fps = read_video_frames(input_video,int(max_len),int(target_fps),int(max_res),)print(f"Loaded {len(frames)} frames")# --------------------------------------------------------# VIDEO DEPTH ANYTHING# --------------------------------------------------------depths, fps = (video_depth_anything.infer_video_depth(frames,target_fps,input_size=input_size,device=DEVICE,))# --------------------------------------------------------# PRESERVE RAW DEPTH# --------------------------------------------------------depths = np.asarray(depths,dtype=np.float32)print("Raw depth shape:",depths.shape)print("Raw depth range:",float(depths.min()),"to",float(depths.max()))# --------------------------------------------------------# OUTPUT DIRECTORY# --------------------------------------------------------video_name = os.path.basename(input_video)base_name = os.path.splitext(video_name)[0]# Unique folder for every generation.## This prevents EXRs from an older generation accidentally# getting included if you process another video with the# same filename but fewer frames.run_id = uuid.uuid4().hex[:8]run_dir = os.path.join(output_dir,f"{base_name}_{run_id}")os.makedirs(run_dir,exist_ok=True)# --------------------------------------------------------# FILE PATHS# --------------------------------------------------------processed_video_path = os.path.join(run_dir,f"{base_name}_src.mp4")depth_vis_path = os.path.join(run_dir,f"{base_name}_vis.mp4")depth_exr_dir = os.path.join(run_dir,f"{base_name}_depth_EXR")zip_path = os.path.join(run_dir,f"{base_name}_depth_EXR.zip")# --------------------------------------------------------# SAVE PREPROCESSED INPUT VIDEO# --------------------------------------------------------save_video(frames,processed_video_path,fps=fps)# --------------------------------------------------------# SAVE MP4 DEPTH PREVIEW## This IS quantized for viewing.## DO NOT use this file as the displacement source.# --------------------------------------------------------save_video(depths,depth_vis_path,fps=fps,is_depths=True,grayscale=bool(grayscale))# --------------------------------------------------------# SAVE RAW 32-BIT FLOAT DEPTH# --------------------------------------------------------print("Saving raw 32-bit EXR sequence...")save_depths_as_rgb_exr(depths,depth_exr_dir)# --------------------------------------------------------# ZIP EXR FRAMES# --------------------------------------------------------print("Creating EXR ZIP...")zip_directory(depth_exr_dir,zip_path)print("EXR ZIP:",zip_path)# --------------------------------------------------------# CLEAN GPU / RAM# --------------------------------------------------------del depthsdel framesgc.collect()if torch.cuda.is_available():torch.cuda.empty_cache()# --------------------------------------------------------# RETURN TO GRADIO# --------------------------------------------------------return [processed_video_path,depth_vis_path,zip_path]# ============================================================# GRADIO UI# ============================================================def construct_demo():with gr.Blocks(analytics_enabled=False) as demo:gr.Markdown(title)gr.Markdown(description)# ----------------------------------------------------# INPUT / OUTPUT# ----------------------------------------------------with gr.Row(equal_height=True):with gr.Column(scale=1):input_video = gr.Video(label="Input Video")with gr.Column(scale=2):with gr.Row(equal_height=True):processed_video = gr.Video(label=("Preprocessed Video"),interactive=False,autoplay=True,loop=True,show_share_button=True,scale=5,)depth_vis_video = gr.Video(label=("Generated Depth Preview"),interactive=False,autoplay=True,loop=True,show_share_button=True,scale=5,)depth_exr_file = gr.File(label=("Raw 32-bit EXR ""Depth Sequence (.zip)"),interactive=False)# ----------------------------------------------------# SETTINGS# ----------------------------------------------------with gr.Row(equal_height=True):with gr.Column(scale=1):with gr.Accordion("Advanced Settings",open=True):max_len = gr.Slider(label=("Max Process Length ""(frames; -1 = all)"),minimum=-1,maximum=1000,value=500,step=1,)target_fps = gr.Slider(label=("Target FPS ""(-1 = original)"),minimum=-1,maximum=30,value=15,step=1,)max_res = gr.Slider(label=("Max Output Side Resolution"),minimum=480,maximum=2560,value=1280,step=1,info=("Controls the maximum ""resolution of the video ""frames and final EXRs. ""This is different from ""the model inference size."),)# ----------------------------------------# NEW:# ACTUAL MODEL INFERENCE RESOLUTION# ----------------------------------------input_size = gr.Slider(label=("Model Inference Size"),minimum=392,maximum=896,value=518,step=14,info=("518 is the normal setting. ""Increasing this gives the ""model more spatial resolution, ""but VRAM usage rises quickly."),)grayscale = gr.Checkbox(label=("Grayscale MP4 Preview"),value=True,info=("Only affects the preview MP4. ""The EXR always contains raw ""floating-point depth."),)generate_btn = gr.Button("Generate Depth + EXR",variant="primary")# ------------------------------------------------# BLENDER INFO# ------------------------------------------------with gr.Column(scale=2):gr.Markdown("""### Blender EXR setupUnzip the EXR file first.Then load:`frame_00000.exr`as an **Image Sequence** in Blender.For the depth Image Texture:**Color Space**`Non-Color`**Interpolation**`Cubic`Then:`Image Texture`→ `Separate Color`→ `Red`→ `Map Range`→ displacementThe EXRs may look almost black in a normal image viewer.That does **not** mean the depth data is missing.They contain raw floating-point depth rather than a normalized8-bit image.""")# ----------------------------------------------------# EXAMPLES# ----------------------------------------------------gr.Examples(examples=examples,inputs=[input_video,max_len,target_fps,max_res],outputs=[processed_video,depth_vis_video,depth_exr_file],fn=infer_video_depth,cache_examples="lazy")# ----------------------------------------------------# GENERATE BUTTON# ----------------------------------------------------generate_btn.click(fn=infer_video_depth,inputs=[input_video,max_len,target_fps,max_res,input_size,grayscale],outputs=[processed_video,depth_vis_video,depth_exr_file],)return demo# ============================================================# START# ============================================================if __name__ == "__main__":demo = construct_demo()demo.queue()demo.launch(share=True)11 unmodified lines12131415161710 unmodified lines28293031323334353637383940414243448 unmodified lines53545556575859606162636465666768691 unmodified line7172737475767778798081828384851 unmodified line8788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559611 unmodified lines# See the License for the specific language governing permissions and# limitations under the License.import gcimport osimport uuid10 unmodified linesimport xformers.opsfrom huggingface_hub import hf_hub_download# =============================================================================# BLACKWELL / XFORMERS COMPATIBILITY SHIM## IMPORTANT:# This patch MUST run before VideoDepthAnything is imported.# The bundled DINOv2 attention module imports memory_efficient_attention by# name, so patching xformers.ops first ensures it receives this PyTorch SDPA# replacement instead of the incompatible xFormers CUDA kernel.# =============================================================================_xf_original = xformers.ops.memory_efficient_attention8 unmodified linesop=None,**kwargs,):"""Route xFormers memory-efficient attention through PyTorch SDPA.xFormers uses tensors shaped [B, M, H, K].PyTorch SDPA expects [B, H, M, K].Video Depth Anything inference normally uses attn_bias=None. If anon-Tensor xFormers-specific bias object is encountered, fall back toxFormers' original implementation."""if attn_bias is not None and not isinstance(attn_bias, torch.Tensor):return _xf_original(query,key,1 unmodified lineattn_bias,p,scale,op,)squeeze = query.dim() == 3if squeeze:q, k, v = (t.unsqueeze(1) for t in (query, key, value))else:q, k, v = (t.transpose(1, 2) for t in (query, key, value))out = F.scaled_dot_product_attention(q,1 unmodified linev,attn_mask=attn_bias,dropout_p=p,scale=scale,)return out.squeeze(1) if squeeze else out.transpose(1, 2)# Patch xFormers BEFORE importing VideoDepthAnything / bundled DINOv2.xformers.ops.memory_efficient_attention = _sdpa_shimprint("Blackwell attention patch installed:",xformers.ops.memory_efficient_attention is _sdpa_shim,)# =============================================================================# THESE IMPORTS MUST REMAIN AFTER THE XFORMERS PATCH ABOVE# =============================================================================from video_depth_anything.video_depth import VideoDepthAnythingfrom utils.dc_utils import read_video_frames, save_video# =============================================================================# EXAMPLES# =============================================================================examples = [["assets/example_videos/davis_rollercoaster.mp4", -1, -1, 1280],["assets/example_videos/Tokyo-Walk_rgb.mp4", -1, -1, 1280],["assets/example_videos/4158877-uhd_3840_2160_30fps_rgb.mp4", -1, -1, 1280],["assets/example_videos/4511004-uhd_3840_2160_24fps_rgb.mp4", -1, -1, 1280],["assets/example_videos/1753029-hd_1920_1080_30fps.mp4", -1, -1, 1280],["assets/example_videos/davis_burnout.mp4", -1, -1, 1280],["assets/example_videos/example_5473765-l.mp4", -1, -1, 1280],["assets/example_videos/Istanbul-26920.mp4", -1, -1, 1280],["assets/example_videos/obj_1.mp4", -1, -1, 1280],["assets/example_videos/sheep_cut1.mp4", -1, -1, 1280],]# =============================================================================# MODEL# =============================================================================DEVICE = "cuda" if torch.cuda.is_available() else "cpu"model_configs = {"vits": {"encoder": "vits","features": 64,"out_channels": [48, 96, 192, 384],},"vitl": {"encoder": "vitl","features": 256,"out_channels": [256, 512, 1024, 1024],},}encoder2name = {"vits": "Small","vitl": "Large",}# Large modelencoder = "vitl"model_name = encoder2name[encoder]video_depth_anything = VideoDepthAnything(**model_configs[encoder])filepath = hf_hub_download(repo_id=f"depth-anything/Video-Depth-Anything-{model_name}",filename=f"video_depth_anything_{encoder}.pth",repo_type="model",)video_depth_anything.load_state_dict(torch.load(filepath, map_location="cpu"))video_depth_anything = video_depth_anything.to(DEVICE).eval()# =============================================================================# UI TEXT# =============================================================================title = "# Video Depth Anything"description = """Official demo for **Video Depth Anything**, modified to export the model's**raw depth prediction as a 32-bit floating-point OpenEXR image sequence**.- **MP4 depth preview:** normalized/compressed visualization for viewing.- **EXR ZIP:** raw floating-point depth values for Blender displacement.For Blender, use the EXR sequence rather than the MP4 depth preview."""# =============================================================================# EXR EXPORT# =============================================================================def save_depths_as_rgb_exr(depths: np.ndarray, output_dir: str) -> None:"""Save raw depth values as 32-bit float RGB OpenEXR frames.The same raw depth value is written to R, G, and B so Blender can readthe sequence directly through a regular Image Texture node.No 0-1 normalization, uint8 conversion, colormap, or video compressionis applied to these files."""os.makedirs(output_dir, exist_ok=True)float_channel = Imath.PixelType(Imath.PixelType.FLOAT)for i, depth in enumerate(depths):depth = np.ascontiguousarray(depth, dtype=np.float32)if depth.ndim != 2:raise ValueError(f"Expected each depth frame to have shape HxW, got {depth.shape}")height, width = depth.shapeexr_path = os.path.join(output_dir, f"frame_{i:05d}.exr")header = OpenEXR.Header(width, height)header["channels"] = {"R": Imath.Channel(float_channel),"G": Imath.Channel(float_channel),"B": Imath.Channel(float_channel),}depth_bytes = depth.tobytes()exr_file = OpenEXR.OutputFile(exr_path, header)try:exr_file.writePixels({"R": depth_bytes,"G": depth_bytes,"B": depth_bytes,})finally:exr_file.close()def zip_directory(source_dir: str, zip_path: str) -> str:"""Zip an EXR sequence so Gradio can return it as one download."""with zipfile.ZipFile(zip_path,mode="w",compression=zipfile.ZIP_DEFLATED,) as zip_file:for filename in sorted(os.listdir(source_dir)):file_path = os.path.join(source_dir, filename)if os.path.isfile(file_path):zip_file.write(file_path,arcname=filename,)return zip_path# =============================================================================# INFERENCE# =============================================================================@spaces.GPU(duration=240)def infer_video_depth(input_video: str,max_len: int = -1,target_fps: int = -1,max_res: int = 1280,input_size: int = 518,grayscale: bool = True,output_dir: str = "./outputs",):if not input_video:raise gr.Error("Please upload a video first.")max_len = int(max_len)target_fps = int(target_fps)max_res = int(max_res)# VDA/DINOv2 patch size is 14, so keep inference size on a multiple of 14.input_size = int(round(float(input_size) / 14.0) * 14)input_size = max(input_size, 14)print(f"Using model inference size: {input_size}")# -------------------------------------------------------------------------# Read / preprocess source video# -------------------------------------------------------------------------frames, actual_fps = read_video_frames(input_video,max_len,target_fps,max_res,)print(f"Loaded {len(frames)} frames")# -------------------------------------------------------------------------# Raw Video Depth Anything inference# -------------------------------------------------------------------------depth_list, fps = video_depth_anything.infer_video_depth(frames,actual_fps,input_size=input_size,device=DEVICE,)# Preserve the model output as float32 BEFORE making any visualization.depths = np.asarray(depth_list, dtype=np.float32)print("Raw depth shape:", depths.shape)print("Raw depth range:",float(depths.min()),"to",float(depths.max()),)# -------------------------------------------------------------------------# Unique output folder for each run# -------------------------------------------------------------------------video_name = os.path.basename(input_video)base_name = os.path.splitext(video_name)[0]run_id = uuid.uuid4().hex[:8]run_dir = os.path.join(output_dir,f"{base_name}_{run_id}",)os.makedirs(run_dir, exist_ok=True)processed_video_path = os.path.join(run_dir,f"{base_name}_src.mp4",)depth_vis_path = os.path.join(run_dir,f"{base_name}_vis.mp4",)depth_exr_dir = os.path.join(run_dir,f"{base_name}_depth_EXR",)zip_path = os.path.join(run_dir,f"{base_name}_depth_EXR.zip",)# -------------------------------------------------------------------------# Save preprocessed source video# -------------------------------------------------------------------------save_video(frames,processed_video_path,fps=fps,)# -------------------------------------------------------------------------# Save normalized MP4 preview# -------------------------------------------------------------------------save_video(depths,depth_vis_path,fps=fps,is_depths=True,grayscale=bool(grayscale),)# -------------------------------------------------------------------------# Save RAW floating-point EXR sequence# -------------------------------------------------------------------------print("Saving raw 32-bit EXR sequence...")save_depths_as_rgb_exr(depths,depth_exr_dir,)print("Creating EXR ZIP...")zip_directory(depth_exr_dir,zip_path,)print("EXR ZIP:", zip_path)# -------------------------------------------------------------------------# Cleanup# -------------------------------------------------------------------------del depthsdel depth_listdel framesgc.collect()if torch.cuda.is_available():torch.cuda.empty_cache()return [processed_video_path,depth_vis_path,zip_path,]# =============================================================================# GRADIO UI# =============================================================================def construct_demo():with gr.Blocks(analytics_enabled=False) as demo:gr.Markdown(title)gr.Markdown(description)with gr.Row(equal_height=True):with gr.Column(scale=1):input_video = gr.Video(label="Input Video")with gr.Column(scale=2):with gr.Row(equal_height=True):processed_video = gr.Video(label="Preprocessed Video",interactive=False,autoplay=True,loop=True,show_share_button=True,scale=5,)depth_vis_video = gr.Video(label="Generated Depth Preview",interactive=False,autoplay=True,loop=True,show_share_button=True,scale=5,)depth_exr_file = gr.File(label="Raw 32-bit EXR Depth Sequence (.zip)",interactive=False,)with gr.Row(equal_height=True):with gr.Column(scale=1):with gr.Accordion("Advanced Settings",open=True,):max_len = gr.Slider(label="Max Process Length (frames; -1 = all)",minimum=-1,maximum=1000,value=500,step=1,)target_fps = gr.Slider(label="Target FPS (-1 = original)",minimum=-1,maximum=30,value=15,step=1,)max_res = gr.Slider(label="Max Side Resolution",minimum=480,maximum=2560,value=1280,step=1,info=("Controls the maximum size of the source/depth frames. ""This is separate from the model inference size."),)input_size = gr.Slider(label="Model Inference Size",minimum=392,maximum=896,value=518,step=14,info=("518 is the normal VDA setting. Higher values can ""preserve more spatial detail but use much more VRAM."),)grayscale = gr.Checkbox(label="Grayscale MP4 Preview",value=True,info=("Only affects the preview MP4. The EXRs always contain ""the raw floating-point depth."),)generate_btn = gr.Button("Generate Depth + EXR",variant="primary",)with gr.Column(scale=2):gr.Markdown("""### Blender EXR setup1. Unzip the downloaded EXR file.2. Load `frame_00000.exr` as an **Image Sequence**.3. Set the Image Texture to **Non-Color**.4. Use **Cubic** interpolation.5. Read the **R** channel.6. Feed it through **Map Range** before displacement.The EXRs may look very dark in a normal image viewer. That is normal: theycontain raw floating-point model values instead of a normalized 8-bit preview.""")# Examples retain the original four settings. The inference-size and# grayscale parameters use their function defaults for example runs.gr.Examples(examples=examples,inputs=[input_video,max_len,target_fps,max_res,],outputs=[processed_video,depth_vis_video,depth_exr_file,],fn=infer_video_depth,cache_examples="lazy",)generate_btn.click(fn=infer_video_depth,inputs=[input_video,max_len,target_fps,max_res,input_size,grayscale,],outputs=[processed_video,depth_vis_video,depth_exr_file,],)return demoif __name__ == "__main__":demo = construct_demo()demo.queue()# On Hugging Face Spaces, a public share URL is unnecessary.demo.launch()
app.py+207-753