From 56ed2477c54cbc24173620b0fc79072cec75fa5d Mon Sep 17 00:00:00 2001 From: Morgan Williams Date: Wed, 24 Dec 2025 16:32:02 +0100 Subject: [PATCH] works! --- .gitignore | 1 + benchmark.py | 41 ++-- benchmarks/results.json | 10 +- compare.py | 263 ++++++++++++++++++++++++++ depth_estimators/apple_depth_pro.py | 23 ++- depth_estimators/depth_anything_v2.py | 25 ++- estimate.py | 13 +- 7 files changed, 342 insertions(+), 34 deletions(-) create mode 100644 compare.py diff --git a/.gitignore b/.gitignore index 585dc8e..07c2f2a 100644 --- a/.gitignore +++ b/.gitignore @@ -35,3 +35,4 @@ temp*.png /outputs checkpoints/depth_pro.pt benchmark_test.log +/output diff --git a/benchmark.py b/benchmark.py index 9595478..ecd1106 100644 --- a/benchmark.py +++ b/benchmark.py @@ -2,9 +2,11 @@ import json import csv import sys +import os from pathlib import Path import tempfile -from depth_estimators import AppleDepthPro, VideoDepthAnythingEstimator +# from depth_estimators import AppleDepthPro +from depth_estimators.depth_anything_v2 import DepthAnythingV2Estimator sys.path.insert(0, str(Path(__file__).parent / "scripts")) from downscale_video import downscale_to_1080p24 @@ -19,14 +21,15 @@ def save_results(results: dict, output_dir: str = "benchmarks"): tsv_path = Path(output_dir) / "results.tsv" with open(tsv_path, "w", newline='') as f: writer = csv.writer(f, delimiter="\t") - writer.writerow(["model", "frames", "total_time", "avg_time", "fps"]) + writer.writerow(["model", "frames", "total_time", "avg_time", "fps", "video_path"]) for model_name, stats in results.items(): writer.writerow([ model_name, stats["frames_processed"], stats["total_time"], stats["avg_time_per_frame"], - round(1 / stats["avg_time_per_frame"], 2) + round(1 / stats["avg_time_per_frame"], 2), + stats.get("video_path", "") ]) print(f"\nResults saved to {output_dir}/") @@ -53,26 +56,36 @@ def main(): prepared_video = Path(downscale_to_1080p24(video_path)) results = {} + num_threads = max(1, os.cpu_count() - 4) - print("\nBenchmarking Apple Depth Pro...") - depth_dir = output_base / "apple_depth_pro" - estimator = AppleDepthPro() - results["apple_depth_pro"] = estimator.process_video(str(prepared_video), str(depth_dir)) + # print("\nBenchmarking Apple Depth Pro...") + # depth_dir = output_base / "apple_depth_pro" + # estimator = AppleDepthPro() + # results["apple_depth_pro"] = estimator.process_video(str(prepared_video), str(depth_dir)) - print("\nBenchmarking Video Depth Anything...") - depth_dir = output_base / "video_depth_anything" - estimator = VideoDepthAnythingEstimator() - results["video_depth_anything"] = estimator.process_video(str(prepared_video), str(depth_dir)) + print("\nBenchmarking Depth Anything V2 Small...") + depth_dir = output_base / "depth_anything_v2_small" + estimator = DepthAnythingV2Estimator(encoder='vits', num_threads=num_threads) + results["depth_anything_v2_small"] = estimator.process_video(str(prepared_video), str(depth_dir)) + + print("\nBenchmarking Depth Anything V2 Base...") + depth_dir = output_base / "depth_anything_v2_base" + estimator = DepthAnythingV2Estimator(encoder='vitb', num_threads=num_threads) + results["depth_anything_v2_base"] = estimator.process_video(str(prepared_video), str(depth_dir)) + + print("\nBenchmarking Depth Anything V2 Large...") + depth_dir = output_base / "depth_anything_v2_large" + estimator = DepthAnythingV2Estimator(encoder='vitl', num_threads=num_threads) + results["depth_anything_v2_large"] = estimator.process_video(str(prepared_video), str(depth_dir)) print("\n" + "="*60) for model_name, stats in results.items(): - fps = 1 / stats['avg_time_per_frame'] if stats['avg_time_per_frame'] > 0 else 0 print(f"{model_name}:") print(f" Frames: {stats['frames_processed']}") print(f" Total: {stats['total_time']:.3f}s") print(f" Avg/frame: {stats['avg_time_per_frame']:.3f}s") - print(f" FPS: {fps:.2f}") - stats['fps'] = round(fps, 2) + print(f" FPS: {stats['fps']}") + print(f" Video: {stats.get('video_path', 'N/A')}") print("="*60) save_results(results) diff --git a/benchmarks/results.json b/benchmarks/results.json index b909930..c582533 100644 --- a/benchmarks/results.json +++ b/benchmarks/results.json @@ -1,8 +1,14 @@ { "apple_depth_pro": { "frames_processed": 3, - "total_time": 12.463420629501343, - "avg_time_per_frame": 4.154473543167114, + "total_time": 12.089050054550171, + "avg_time_per_frame": 4.029683351516724, + "device": "mps" + }, + "video_depth_anything": { + "frames_processed": 3, + "total_time": 13.964018106460571, + "avg_time_per_frame": 4.6546727021535235, "device": "mps" } } \ No newline at end of file diff --git a/compare.py b/compare.py new file mode 100644 index 0000000..0e97e74 --- /dev/null +++ b/compare.py @@ -0,0 +1,263 @@ +#!/usr/bin/env python3 +import sys +import subprocess +import tempfile +from pathlib import Path +from tqdm import tqdm + + +def create_ass_subtitle(title: str, duration: float, position: str = "bottom_center") -> str: + """Create an ASS subtitle entry with positioning.""" + # ASS format: Dialogue: layer, start, end, style, name, marginL, marginR, marginV, effect, text + # Position codes: \pos(x,y) for absolute positioning, or use alignment + # Alignment: 1=bottom-left, 2=bottom-center, 3=bottom-right, etc. + + start_time = "00:00:00.00" + end_time = format_timestamp(duration) + + # Use alignment 2 for bottom-center + dialogue = f"Dialogue: 0,{start_time},{end_time},TitleStyle,,0,0,0,,{title}" + return dialogue + + +def format_timestamp(seconds: float) -> str: + """Convert seconds to ASS timestamp format (HH:MM:SS.CC).""" + hours = int(seconds // 3600) + minutes = int((seconds % 3600) // 60) + secs = int(seconds % 60) + centisecs = int((seconds % 1) * 100) + return f"{hours:02d}:{minutes:02d}:{secs:02d}.{centisecs:02d}" + + +def create_ass_file(title: str, duration: float) -> str: + """Create a complete ASS subtitle file with proper formatting.""" + ass_content = """[Script Info] +Title: Comparison Video +ScriptType: v4.00+ +Collisions: Normal +PlayResX: 1920 +PlayResY: 1080 + +[V4+ Styles] +Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding +Style: TitleStyle,Arial,48,&H00FFFFFF,&H000000FF,&H00000000,&H00000000,0,0,0,0,100,100,0,0,1,3,2,2,10,10,50,1 + +[Events] +Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text +""" + + start_time = "00:00:00.00" + end_time = format_timestamp(duration) + + dialogue = f"Dialogue: 0,{start_time},{end_time},TitleStyle,,0,0,0,,{title}" + ass_content += dialogue + + return ass_content + + +def get_video_title(video_path: str) -> str: + """Extract a clean title from video path.""" + path = Path(video_path) + return path.stem + + +def get_short_title(full_title: str) -> str: + """Convert full title to short compact name for subtitles.""" + # Map long names to short names + short_names = { + 'depth_anything_v2_small': 'dav2_small', + 'depth_anything_v2_base': 'dav2_base', + 'depth_anything_v2_large': 'dav2_large', + 'apple_depth_pro': 'adp', + } + + # Check for exact matches first + if full_title in short_names: + return short_names[full_title] + + # Check for partial matches (in case of old bench names) + for long_name, short_name in short_names.items(): + if long_name in full_title: + return short_name + + # Return original if no mapping found + return full_title + + +def get_video_duration(video_path: str) -> float: + """Get video duration using ffprobe.""" + try: + result = subprocess.run( + [ + "ffprobe", + "-v", "error", + "-show_entries", "format=duration", + "-of", "default=noprint_wrappers=1:nokey=1:noprint_wrappers=1", + video_path + ], + capture_output=True, + text=True, + check=True + ) + return float(result.stdout.strip()) + except Exception as e: + raise ValueError(f"Failed to get duration of {video_path}: {e}") + + +def compare_videos(video_paths: list, output_path: str = "comparison.mp4"): + """Create a side-by-side comparison video with subtitles.""" + + if not video_paths: + raise ValueError("No video paths provided") + + # Resolve video paths + resolved_paths = [] + for video_path in video_paths: + # Handle both with and without extension + if not video_path.endswith(('.mp4', '.MOV', '.mov', '.avi', '.mkv')): + test_path = video_path + '.mp4' + if Path(test_path).exists(): + video_path = test_path + elif not Path(video_path).exists(): + print(f"Warning: Video not found: {video_path}") + continue + + if not Path(video_path).exists(): + print(f"Warning: Video not found: {video_path}") + continue + + resolved_paths.append(video_path) + + if not resolved_paths: + raise ValueError("No valid videos found") + + print(f"Creating comparison video from {len(resolved_paths)} videos...") + + # Get video information + videos_info = [] + max_duration = 0 + + for video_path in resolved_paths: + try: + duration = get_video_duration(video_path) + title = get_video_title(video_path) + videos_info.append({ + 'path': video_path, + 'title': title, + 'duration': duration + }) + max_duration = max(max_duration, duration) + except Exception as e: + print(f"Error processing {video_path}: {e}") + continue + + if not videos_info: + raise ValueError("No valid videos could be processed") + + # Create subtitle files for each video + subtitle_files = [] + with tempfile.TemporaryDirectory() as tmpdir: + tmpdir = Path(tmpdir) + + for i, video_info in enumerate(videos_info): + short_title = get_short_title(video_info['title']) + ass_content = create_ass_file(short_title, max_duration) + sub_file = tmpdir / f"subtitle_{i}.ass" + sub_file.write_text(ass_content) + subtitle_files.append(str(sub_file)) + + # Build ffmpeg complex filter for side-by-side layout with subtitles + inputs = [] + filter_parts = [] + + # Add video inputs + for i, video_info in enumerate(videos_info): + inputs.extend(["-i", video_info['path']]) + + # Build the filter graph + # Scale videos and add subtitles + scaled_filters = [] + subtitle_filters = [] + + for i in range(len(videos_info)): + # Scale to 720p height, round width to even number for codec compatibility + scaled_filters.append(f"[{i}]scale=-1:720,pad=ceil(iw/2)*2:ceil(ih/2)*2[v{i}]") + # Add subtitle overlay using absolute path + sub_path = subtitle_files[i].replace("\\", "/").replace("'", "\\'") # Escape for ffmpeg filter + subtitle_filters.append(f"[v{i}]subtitles='{sub_path}'[v{i}_sub]") + + # Concatenate all videos horizontally + concat_inputs = "".join([f"[v{i}_sub]" for i in range(len(videos_info))]) + concat_filter = f"{concat_inputs}hstack=inputs={len(videos_info)}" + + filter_graph = ";".join(scaled_filters + subtitle_filters) + f";{concat_filter}" + + # Build ffmpeg command + cmd = [ + "ffmpeg", + "-y", + *inputs, + "-filter_complex", filter_graph, + "-c:v", "libx264", + "-preset", "fast", + "-crf", "23", + "-c:a", "aac", + output_path + ] + + print(f"Output: {output_path}") + print("Encoding comparison video...") + + try: + subprocess.run(cmd, check=True) + print(f"Comparison video saved to: {output_path}") + except subprocess.CalledProcessError as e: + raise ValueError(f"FFmpeg encoding failed: {e}") + + +def generate_default_output_name(video_paths: list) -> str: + """Generate a readable default output filename from input video names.""" + titles = [get_video_title(path) for path in video_paths] + # Join titles with underscores, limit length + combined = "_vs_".join(titles) + if len(combined) > 60: + # If too long, abbreviate + combined = "_vs_".join([t[:10] for t in titles]) + return f"{combined}_comparison.mp4" + + +def main(): + if len(sys.argv) < 2: + print("Usage: uv run compare [video3] ... [--output output.mp4]") + print("Example: uv run compare dav2_base.mp4 dav2_large dav2_small") + sys.exit(1) + + # Parse arguments + video_paths = [] + output_path = None + + args = sys.argv[1:] + i = 0 + while i < len(args): + if args[i] == "--output" and i + 1 < len(args): + output_path = args[i + 1] + i += 2 + elif not args[i].startswith("--"): + video_paths.append(args[i]) + i += 1 + else: + i += 1 + + # Generate default output name if not specified + if output_path is None: + output_path = generate_default_output_name(video_paths) + + try: + compare_videos(video_paths, output_path) + except Exception as e: + print(f"Error: {e}", file=sys.stderr) + sys.exit(1) + + +if __name__ == "__main__": + main() diff --git a/depth_estimators/apple_depth_pro.py b/depth_estimators/apple_depth_pro.py index 2dffb8c..0dc33cb 100644 --- a/depth_estimators/apple_depth_pro.py +++ b/depth_estimators/apple_depth_pro.py @@ -9,6 +9,8 @@ import torch import depth_pro import numpy as np from PIL import Image +from tqdm import tqdm +from scripts.stitch_video import stitch_frames_to_hevc class AppleDepthPro: @@ -34,7 +36,7 @@ class AppleDepthPro: else: self.device = torch.device("cpu") - def process_video(self, video_path: str, output_dir: str = "output", max_frames: int = 8): + def process_video(self, video_path: str, output_dir: str = "output", max_frames: int = None): process = psutil.Process() mem_before = process.memory_info().rss / 1024 / 1024 @@ -53,12 +55,14 @@ class AppleDepthPro: frames_dir = Path(tmpdir) / "frames" frames_dir.mkdir() - cmd = ["ffmpeg", "-i", video_path, "-frames:v", str(max_frames), f"{frames_dir}/frame_%04d.png"] + cmd = ["ffmpeg", "-i", video_path] + if max_frames is not None: + cmd.extend(["-frames:v", str(max_frames)]) + cmd.append(f"{frames_dir}/frame_%04d.png") subprocess.run(cmd, capture_output=True, check=True) frames = sorted(frames_dir.glob("frame_*.png")) - print(f" Warming up model with first frame...") first_frame = frames[0] image, _, f_px = depth_pro.load_rgb(str(first_frame)) image = self.transform(image).to(self.device) @@ -70,8 +74,7 @@ class AppleDepthPro: frame_times = [] - for i, frame in enumerate(frames, 1): - print(f" Processing frame {i}/{len(frames)}...") + for i, frame in enumerate(tqdm(frames, desc=" Processing frames", unit="frame"), 1): output = output_dir / f"depth_{frame.name}" image, _, f_px = depth_pro.load_rgb(str(frame)) @@ -82,7 +85,6 @@ class AppleDepthPro: prediction = self.model.infer(image, f_px=f_px) elapsed = time.time() - start frame_times.append(elapsed) - print(f" Inference: {elapsed:.3f}s") depth = prediction["depth"].cpu().numpy() depth_normalized = ((depth - depth.min()) / (depth.max() - depth.min()) * 255).astype(np.uint8) @@ -94,6 +96,12 @@ class AppleDepthPro: mem_peak = process.memory_info().rss / 1024 / 1024 + print(f" Stitching frames to HEVC video...") + # Create video path adjacent to output_dir with same name + output_dir_name = output_dir.name + video_path = output_dir.parent / f"{output_dir_name}.mp4" + stitch_frames_to_hevc(str(output_dir), str(video_path), fps=24) + return { "frames_processed": len(frame_times), "total_time": total_time, @@ -102,5 +110,6 @@ class AppleDepthPro: "warmup_time": warmup_time, "warmup_inference": warmup_inference, "memory_mb": round(mem_peak, 1), - "device": str(self.device) + "device": str(self.device), + "video_path": str(video_path) } diff --git a/depth_estimators/depth_anything_v2.py b/depth_estimators/depth_anything_v2.py index 81d70a7..16c7d7b 100644 --- a/depth_estimators/depth_anything_v2.py +++ b/depth_estimators/depth_anything_v2.py @@ -9,9 +9,11 @@ import torch import numpy as np from PIL import Image import cv2 +from tqdm import tqdm sys.path.insert(0, str(Path(__file__).parent.parent / "Depth-Anything-V2")) from depth_anything_v2.dpt import DepthAnythingV2 +from scripts.stitch_video import stitch_frames_to_hevc _threads_configured = False @@ -53,7 +55,7 @@ class DepthAnythingV2Estimator: self.model = self.model.to(self.device).eval() - def process_video(self, video_path: str, output_dir: str = "output", max_frames: int = 8): + def process_video(self, video_path: str, output_dir: str = "output", max_frames: int = None): process = psutil.Process() mem_before = process.memory_info().rss / 1024 / 1024 @@ -70,14 +72,17 @@ class DepthAnythingV2Estimator: cap = cv2.VideoCapture(video_path) frames = [] - for i in range(max_frames): + i = 0 + while True: ret, frame = cap.read() if not ret: break + if max_frames is not None and i >= max_frames: + break frames.append(frame) + i += 1 cap.release() - print(f" Warming up model with first frame...") warmup_start = time.time() with torch.no_grad(): _ = self.model.infer_image(frames[0], 518) @@ -86,15 +91,12 @@ class DepthAnythingV2Estimator: frame_times = [] - for i, frame in enumerate(frames): - print(f" Processing frame {i+1}/{len(frames)}...") - + for i, frame in enumerate(tqdm(frames, desc=" Processing frames", unit="frame")): start = time.time() with torch.no_grad(): depth = self.model.infer_image(frame, 518) elapsed = time.time() - start frame_times.append(elapsed) - print(f" Inference: {elapsed:.3f}s") depth_normalized = ((depth - depth.min()) / (depth.max() - depth.min()) * 255).astype(np.uint8) Image.fromarray(depth_normalized).save(output_dir / f"depth_frame_{i+1:04d}.png") @@ -105,6 +107,12 @@ class DepthAnythingV2Estimator: mem_peak = process.memory_info().rss / 1024 / 1024 + print(f" Stitching frames to HEVC video...") + # Create video path adjacent to output_dir with same name + output_dir_name = output_dir.name + video_path = output_dir.parent / f"{output_dir_name}.mp4" + stitch_frames_to_hevc(str(output_dir), str(video_path), fps=24) + return { "frames_processed": len(frame_times), "total_time": total_time, @@ -113,5 +121,6 @@ class DepthAnythingV2Estimator: "warmup_time": warmup_time, "warmup_inference": warmup_inference, "memory_mb": round(mem_peak, 1), - "device": str(self.device) + "device": str(self.device), + "video_path": str(video_path) } diff --git a/estimate.py b/estimate.py index 476fd6a..98b652e 100644 --- a/estimate.py +++ b/estimate.py @@ -3,23 +3,30 @@ from depth_estimators import AppleDepthPro, DepthAnythingV2Estimator num_threads = max(1, os.cpu_count() - 4) +# print('\n' + '='*60) +# print('Benchmarking Apple Depth Pro') +# print('='*60) +# estimator = AppleDepthPro() +# result = estimator.process_video('samples/1080p24fps/barcelona-lights_1080p.MOV', 'output/apple_depth_pro') +# print('RESULT:', result) + print('\n' + '='*60) print('Benchmarking Depth Anything V2 Small') print('='*60) estimator = DepthAnythingV2Estimator(encoder='vits', num_threads=num_threads) -result = estimator.process_video('samples/1080p24fps/barcelona-lights_1080p.MOV', 'output/depth_anything_v2_small_bench') +result = estimator.process_video('samples/1080p24fps/barcelona-lights_1080p.MOV', 'output/dav2_small') print('RESULT:', result) print('\n' + '='*60) print('Benchmarking Depth Anything V2 Base') print('='*60) estimator = DepthAnythingV2Estimator(encoder='vitb', num_threads=num_threads) -result = estimator.process_video('samples/1080p24fps/barcelona-lights_1080p.MOV', 'output/depth_anything_v2_base_bench') +result = estimator.process_video('samples/1080p24fps/barcelona-lights_1080p.MOV', 'output/dav2_base') print('RESULT:', result) print('\n' + '='*60) print('Benchmarking Depth Anything V2 Large') print('='*60) estimator = DepthAnythingV2Estimator(encoder='vitl', num_threads=num_threads) -result = estimator.process_video('samples/1080p24fps/barcelona-lights_1080p.MOV', 'output/depth_anything_v2_large_bench') +result = estimator.process_video('samples/1080p24fps/barcelona-lights_1080p.MOV', 'output/dav2_large') print('RESULT:', result) -- knotmirror 0.0.1