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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
integrated_pipeline.py - Two-stage pipeline with fallback compatibility
|
| 4 |
+
- Stage 1: SAM2 -> lossless mask stream + metadata, then unload SAM2
|
| 5 |
+
- Stage 2: Read masks -> MatAnyone -> composite -> final output
|
| 6 |
+
- Maintains compatibility with existing UI calls
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
import os
|
| 10 |
+
import sys
|
| 11 |
+
import gc
|
| 12 |
+
import json
|
| 13 |
+
import subprocess
|
| 14 |
+
import tempfile
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
from typing import Dict, Any, Optional, Tuple
|
| 17 |
+
import numpy as np
|
| 18 |
+
import cv2
|
| 19 |
+
|
| 20 |
+
# Add the parent directory to Python path for imports
|
| 21 |
+
current_dir = Path(__file__).parent
|
| 22 |
+
parent_dir = current_dir.parent
|
| 23 |
+
sys.path.append(str(parent_dir))
|
| 24 |
+
|
| 25 |
+
class TwoStageProcessor:
|
| 26 |
+
def __init__(self, temp_dir: Optional[str] = None):
|
| 27 |
+
self.temp_dir = Path(temp_dir) if temp_dir else Path(tempfile.mkdtemp())
|
| 28 |
+
self.temp_dir.mkdir(exist_ok=True)
|
| 29 |
+
|
| 30 |
+
# Stage outputs
|
| 31 |
+
self.masks_path = self.temp_dir / "masks.mkv"
|
| 32 |
+
self.metadata_path = self.temp_dir / "meta.json"
|
| 33 |
+
|
| 34 |
+
def process_video(self, input_video: str, background_video: str,
|
| 35 |
+
click_points: list, output_path: str,
|
| 36 |
+
use_matanyone: bool = True, progress_callback=None) -> bool:
|
| 37 |
+
"""
|
| 38 |
+
Main entry point - maintains compatibility with existing UI
|
| 39 |
+
"""
|
| 40 |
+
try:
|
| 41 |
+
# Stage 1: Generate masks
|
| 42 |
+
if progress_callback:
|
| 43 |
+
progress_callback("Stage 1: Generating masks with SAM2...")
|
| 44 |
+
|
| 45 |
+
if not self._stage1_generate_masks(input_video, click_points, progress_callback):
|
| 46 |
+
return False
|
| 47 |
+
|
| 48 |
+
# Stage 2: Process and composite
|
| 49 |
+
if progress_callback:
|
| 50 |
+
progress_callback("Stage 2: Processing and compositing...")
|
| 51 |
+
|
| 52 |
+
return self._stage2_composite(input_video, background_video,
|
| 53 |
+
output_path, use_matanyone, progress_callback)
|
| 54 |
+
|
| 55 |
+
except Exception as e:
|
| 56 |
+
print(f"Two-stage processing failed: {e}")
|
| 57 |
+
return False
|
| 58 |
+
|
| 59 |
+
def _stage1_generate_masks(self, input_video: str, click_points: list,
|
| 60 |
+
progress_callback=None) -> bool:
|
| 61 |
+
"""Stage 1: SAM2 mask generation with complete memory cleanup"""
|
| 62 |
+
try:
|
| 63 |
+
# Import SAM2 only when needed
|
| 64 |
+
print("Loading SAM2...")
|
| 65 |
+
import torch
|
| 66 |
+
from sam2.build_sam import build_sam2_video_predictor
|
| 67 |
+
|
| 68 |
+
# Initialize SAM2
|
| 69 |
+
checkpoint = "checkpoints/sam2.1_hiera_large.pt"
|
| 70 |
+
model_cfg = "configs/sam2.1/sam2.1_hiera_l.yaml"
|
| 71 |
+
|
| 72 |
+
if not os.path.exists(checkpoint):
|
| 73 |
+
print(f"SAM2 checkpoint not found: {checkpoint}")
|
| 74 |
+
return False
|
| 75 |
+
|
| 76 |
+
predictor = build_sam2_video_predictor(model_cfg, checkpoint)
|
| 77 |
+
|
| 78 |
+
# Get video info
|
| 79 |
+
cap = cv2.VideoCapture(input_video)
|
| 80 |
+
fps = cap.get(cv2.CAP_PROP_FPS)
|
| 81 |
+
frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
|
| 82 |
+
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
|
| 83 |
+
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
|
| 84 |
+
cap.release()
|
| 85 |
+
|
| 86 |
+
# Save metadata
|
| 87 |
+
metadata = {
|
| 88 |
+
"fps": fps,
|
| 89 |
+
"frame_count": frame_count,
|
| 90 |
+
"width": width,
|
| 91 |
+
"height": height,
|
| 92 |
+
"click_points": click_points
|
| 93 |
+
}
|
| 94 |
+
|
| 95 |
+
with open(self.metadata_path, 'w') as f:
|
| 96 |
+
json.dump(metadata, f, indent=2)
|
| 97 |
+
|
| 98 |
+
# Initialize inference state
|
| 99 |
+
inference_state = predictor.init_state(video_path=input_video)
|
| 100 |
+
|
| 101 |
+
# Add prompts
|
| 102 |
+
for i, point in enumerate(click_points):
|
| 103 |
+
x, y = point
|
| 104 |
+
predictor.add_new_points_or_box(
|
| 105 |
+
inference_state=inference_state,
|
| 106 |
+
frame_idx=0,
|
| 107 |
+
obj_id=i,
|
| 108 |
+
points=np.array([[x, y]], dtype=np.float32),
|
| 109 |
+
labels=np.array([1], np.int32),
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
# Setup FFmpeg for lossless mask encoding
|
| 113 |
+
ffmpeg_cmd = [
|
| 114 |
+
'ffmpeg', '-y', '-f', 'rawvideo',
|
| 115 |
+
'-pix_fmt', 'gray', '-s', f'{width}x{height}',
|
| 116 |
+
'-r', str(fps), '-i', '-',
|
| 117 |
+
'-c:v', 'ffv1', '-level', '3', '-pix_fmt', 'gray',
|
| 118 |
+
str(self.masks_path)
|
| 119 |
+
]
|
| 120 |
+
|
| 121 |
+
ffmpeg_process = subprocess.Popen(
|
| 122 |
+
ffmpeg_cmd, stdin=subprocess.PIPE,
|
| 123 |
+
stderr=subprocess.PIPE, stdout=subprocess.PIPE
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
# Generate and stream masks
|
| 127 |
+
print(f"Processing {frame_count} frames...")
|
| 128 |
+
|
| 129 |
+
for out_frame_idx, out_obj_ids, out_mask_logits in predictor.propagate_in_video(inference_state):
|
| 130 |
+
if progress_callback:
|
| 131 |
+
progress = (out_frame_idx + 1) / frame_count * 50 # 50% of total progress for stage 1
|
| 132 |
+
progress_callback(f"Generating masks... Frame {out_frame_idx + 1}/{frame_count}", progress)
|
| 133 |
+
|
| 134 |
+
# Combine masks from all objects
|
| 135 |
+
combined_mask = np.zeros((height, width), dtype=np.uint8)
|
| 136 |
+
for obj_id in out_obj_ids:
|
| 137 |
+
mask = (out_mask_logits[obj_id] > 0.0).squeeze()
|
| 138 |
+
combined_mask = np.logical_or(combined_mask, mask).astype(np.uint8) * 255
|
| 139 |
+
|
| 140 |
+
# Write to FFmpeg
|
| 141 |
+
ffmpeg_process.stdin.write(combined_mask.tobytes())
|
| 142 |
+
|
| 143 |
+
# Finalize FFmpeg
|
| 144 |
+
ffmpeg_process.stdin.close()
|
| 145 |
+
ffmpeg_process.wait()
|
| 146 |
+
|
| 147 |
+
if ffmpeg_process.returncode != 0:
|
| 148 |
+
error = ffmpeg_process.stderr.read().decode()
|
| 149 |
+
print(f"FFmpeg error: {error}")
|
| 150 |
+
return False
|
| 151 |
+
|
| 152 |
+
print("Stage 1 complete: Masks saved")
|
| 153 |
+
|
| 154 |
+
# CRITICAL: Complete memory cleanup
|
| 155 |
+
del predictor
|
| 156 |
+
del inference_state
|
| 157 |
+
if 'torch' in locals():
|
| 158 |
+
if torch.cuda.is_available():
|
| 159 |
+
torch.cuda.empty_cache()
|
| 160 |
+
torch.cuda.synchronize()
|
| 161 |
+
|
| 162 |
+
# Force garbage collection
|
| 163 |
+
gc.collect()
|
| 164 |
+
|
| 165 |
+
# Clear SAM2 from sys.modules to prevent memory leaks
|
| 166 |
+
modules_to_clear = [mod for mod in sys.modules.keys() if 'sam2' in mod.lower()]
|
| 167 |
+
for mod in modules_to_clear:
|
| 168 |
+
del sys.modules[mod]
|
| 169 |
+
|
| 170 |
+
print("SAM2 completely unloaded from memory")
|
| 171 |
+
return True
|
| 172 |
+
|
| 173 |
+
except Exception as e:
|
| 174 |
+
print(f"Stage 1 failed: {e}")
|
| 175 |
+
return False
|
| 176 |
+
|
| 177 |
+
def _stage2_composite(self, input_video: str, background_video: str,
|
| 178 |
+
output_path: str, use_matanyone: bool, progress_callback=None) -> bool:
|
| 179 |
+
"""Stage 2: Read masks, refine with MatAnyone, and composite"""
|
| 180 |
+
try:
|
| 181 |
+
# Load metadata
|
| 182 |
+
with open(self.metadata_path, 'r') as f:
|
| 183 |
+
metadata = json.load(f)
|
| 184 |
+
|
| 185 |
+
frame_count = metadata["frame_count"]
|
| 186 |
+
|
| 187 |
+
# Read masks back from lossless stream
|
| 188 |
+
masks = self._read_mask_stream()
|
| 189 |
+
if masks is None:
|
| 190 |
+
return False
|
| 191 |
+
|
| 192 |
+
# Optional MatAnyone refinement
|
| 193 |
+
if use_matanyone:
|
| 194 |
+
if progress_callback:
|
| 195 |
+
progress_callback("Refining masks with MatAnyone...")
|
| 196 |
+
masks = self._refine_with_matanyone(input_video, masks, progress_callback)
|
| 197 |
+
if masks is None:
|
| 198 |
+
return False
|
| 199 |
+
|
| 200 |
+
# Final composition
|
| 201 |
+
if progress_callback:
|
| 202 |
+
progress_callback("Compositing final video...")
|
| 203 |
+
|
| 204 |
+
return self._composite_final_video(input_video, background_video,
|
| 205 |
+
masks, output_path, metadata, progress_callback)
|
| 206 |
+
|
| 207 |
+
except Exception as e:
|
| 208 |
+
print(f"Stage 2 failed: {e}")
|
| 209 |
+
return False
|
| 210 |
+
|
| 211 |
+
def _read_mask_stream(self) -> Optional[list]:
|
| 212 |
+
"""Read masks from the lossless FFV1 stream"""
|
| 213 |
+
try:
|
| 214 |
+
# Load metadata for dimensions
|
| 215 |
+
with open(self.metadata_path, 'r') as f:
|
| 216 |
+
metadata = json.load(f)
|
| 217 |
+
|
| 218 |
+
width = metadata["width"]
|
| 219 |
+
height = metadata["height"]
|
| 220 |
+
frame_count = metadata["frame_count"]
|
| 221 |
+
|
| 222 |
+
# Use FFmpeg to decode masks
|
| 223 |
+
ffmpeg_cmd = [
|
| 224 |
+
'ffmpeg', '-i', str(self.masks_path),
|
| 225 |
+
'-f', 'rawvideo', '-pix_fmt', 'gray', '-'
|
| 226 |
+
]
|
| 227 |
+
|
| 228 |
+
process = subprocess.Popen(
|
| 229 |
+
ffmpeg_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE
|
| 230 |
+
)
|
| 231 |
+
|
| 232 |
+
masks = []
|
| 233 |
+
frame_size = width * height
|
| 234 |
+
|
| 235 |
+
for frame_idx in range(frame_count):
|
| 236 |
+
frame_data = process.stdout.read(frame_size)
|
| 237 |
+
if len(frame_data) != frame_size:
|
| 238 |
+
print(f"Unexpected frame size at frame {frame_idx}")
|
| 239 |
+
break
|
| 240 |
+
|
| 241 |
+
mask = np.frombuffer(frame_data, dtype=np.uint8).reshape((height, width))
|
| 242 |
+
masks.append(mask)
|
| 243 |
+
|
| 244 |
+
process.stdout.close()
|
| 245 |
+
process.wait()
|
| 246 |
+
|
| 247 |
+
if process.returncode != 0:
|
| 248 |
+
error = process.stderr.read().decode()
|
| 249 |
+
print(f"FFmpeg decode error: {error}")
|
| 250 |
+
return None
|
| 251 |
+
|
| 252 |
+
print(f"Successfully read {len(masks)} masks from stream")
|
| 253 |
+
return masks
|
| 254 |
+
|
| 255 |
+
except Exception as e:
|
| 256 |
+
print(f"Failed to read mask stream: {e}")
|
| 257 |
+
return None
|
| 258 |
+
|
| 259 |
+
def _refine_with_matanyone(self, input_video: str, masks: list, progress_callback=None) -> Optional[list]:
|
| 260 |
+
"""Apply MatAnyone refinement to masks"""
|
| 261 |
+
try:
|
| 262 |
+
# Import MatAnyone only when needed
|
| 263 |
+
from matanyone.mat_anywhere import matting_inference_video
|
| 264 |
+
|
| 265 |
+
# Create temp directory for MatAnyone
|
| 266 |
+
matanyone_temp = self.temp_dir / "matanyone"
|
| 267 |
+
matanyone_temp.mkdir(exist_ok=True)
|
| 268 |
+
|
| 269 |
+
# Save masks as individual frames for MatAnyone
|
| 270 |
+
mask_dir = matanyone_temp / "masks"
|
| 271 |
+
mask_dir.mkdir(exist_ok=True)
|
| 272 |
+
|
| 273 |
+
for i, mask in enumerate(masks):
|
| 274 |
+
cv2.imwrite(str(mask_dir / f"mask_{i:06d}.png"), mask)
|
| 275 |
+
|
| 276 |
+
# Run MatAnyone
|
| 277 |
+
refined_masks_dir = matanyone_temp / "refined"
|
| 278 |
+
refined_masks_dir.mkdir(exist_ok=True)
|
| 279 |
+
|
| 280 |
+
success = matting_inference_video(
|
| 281 |
+
video_path=input_video,
|
| 282 |
+
mask_dir=str(mask_dir),
|
| 283 |
+
output_dir=str(refined_masks_dir),
|
| 284 |
+
progress_callback=progress_callback
|
| 285 |
+
)
|
| 286 |
+
|
| 287 |
+
if not success:
|
| 288 |
+
print("MatAnyone refinement failed, using original masks")
|
| 289 |
+
return masks
|
| 290 |
+
|
| 291 |
+
# Load refined masks
|
| 292 |
+
refined_masks = []
|
| 293 |
+
for i in range(len(masks)):
|
| 294 |
+
refined_path = refined_masks_dir / f"refined_{i:06d}.png"
|
| 295 |
+
if refined_path.exists():
|
| 296 |
+
refined_mask = cv2.imread(str(refined_path), cv2.IMREAD_GRAYSCALE)
|
| 297 |
+
refined_masks.append(refined_mask)
|
| 298 |
+
else:
|
| 299 |
+
refined_masks.append(masks[i]) # Fallback to original
|
| 300 |
+
|
| 301 |
+
return refined_masks
|
| 302 |
+
|
| 303 |
+
except Exception as e:
|
| 304 |
+
print(f"MatAnyone refinement failed: {e}, using original masks")
|
| 305 |
+
return masks
|
| 306 |
+
|
| 307 |
+
def _composite_final_video(self, input_video: str, background_video: str,
|
| 308 |
+
masks: list, output_path: str, metadata: Dict[str, Any],
|
| 309 |
+
progress_callback=None) -> bool:
|
| 310 |
+
"""Create final composite video"""
|
| 311 |
+
try:
|
| 312 |
+
# Setup video capture
|
| 313 |
+
fg_cap = cv2.VideoCapture(input_video)
|
| 314 |
+
bg_cap = cv2.VideoCapture(background_video)
|
| 315 |
+
|
| 316 |
+
fps = metadata["fps"]
|
| 317 |
+
width = metadata["width"]
|
| 318 |
+
height = metadata["height"]
|
| 319 |
+
|
| 320 |
+
# Setup output writer
|
| 321 |
+
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
|
| 322 |
+
out = cv2.VideoWriter(output_path, fourcc, fps, (width, height))
|
| 323 |
+
|
| 324 |
+
frame_idx = 0
|
| 325 |
+
total_frames = len(masks)
|
| 326 |
+
|
| 327 |
+
while frame_idx < total_frames:
|
| 328 |
+
# Read frames
|
| 329 |
+
ret_fg, fg_frame = fg_cap.read()
|
| 330 |
+
ret_bg, bg_frame = bg_cap.read()
|
| 331 |
+
|
| 332 |
+
if not ret_fg:
|
| 333 |
+
break
|
| 334 |
+
|
| 335 |
+
if not ret_bg:
|
| 336 |
+
# Loop background if shorter
|
| 337 |
+
bg_cap.set(cv2.CAP_PROP_POS_FRAMES, 0)
|
| 338 |
+
ret_bg, bg_frame = bg_cap.read()
|
| 339 |
+
|
| 340 |
+
if not ret_bg:
|
| 341 |
+
print("No background frame available")
|
| 342 |
+
break
|
| 343 |
+
|
| 344 |
+
# Resize background to match foreground
|
| 345 |
+
bg_frame = cv2.resize(bg_frame, (width, height))
|
| 346 |
+
|
| 347 |
+
# Get mask
|
| 348 |
+
mask = masks[frame_idx]
|
| 349 |
+
mask_norm = mask.astype(np.float32) / 255.0
|
| 350 |
+
mask_3ch = np.stack([mask_norm, mask_norm, mask_norm], axis=-1)
|
| 351 |
+
|
| 352 |
+
# Composite
|
| 353 |
+
composite = (fg_frame * mask_3ch + bg_frame * (1 - mask_3ch)).astype(np.uint8)
|
| 354 |
+
out.write(composite)
|
| 355 |
+
|
| 356 |
+
frame_idx += 1
|
| 357 |
+
|
| 358 |
+
if progress_callback and frame_idx % 10 == 0:
|
| 359 |
+
progress = 50 + (frame_idx / total_frames) * 50 # 50-100% for stage 2
|
| 360 |
+
progress_callback(f"Compositing... Frame {frame_idx}/{total_frames}", progress)
|
| 361 |
+
|
| 362 |
+
# Cleanup
|
| 363 |
+
fg_cap.release()
|
| 364 |
+
bg_cap.release()
|
| 365 |
+
out.release()
|
| 366 |
+
|
| 367 |
+
print(f"Final video saved to: {output_path}")
|
| 368 |
+
return True
|
| 369 |
+
|
| 370 |
+
except Exception as e:
|
| 371 |
+
print(f"Final composition failed: {e}")
|
| 372 |
+
return False
|
| 373 |
+
|
| 374 |
+
def cleanup(self):
|
| 375 |
+
"""Clean up temporary files"""
|
| 376 |
+
try:
|
| 377 |
+
if self.temp_dir.exists():
|
| 378 |
+
import shutil
|
| 379 |
+
shutil.rmtree(self.temp_dir)
|
| 380 |
+
except Exception as e:
|
| 381 |
+
print(f"Cleanup failed: {e}")
|
| 382 |
+
|
| 383 |
+
# Compatibility wrapper for existing UI
|
| 384 |
+
def process_video_two_stage(input_video: str, background_video: str,
|
| 385 |
+
click_points: list, output_path: str,
|
| 386 |
+
use_matanyone: bool = True, progress_callback=None) -> bool:
|
| 387 |
+
"""
|
| 388 |
+
Drop-in replacement for existing process_video function
|
| 389 |
+
"""
|
| 390 |
+
processor = TwoStageProcessor()
|
| 391 |
+
try:
|
| 392 |
+
result = processor.process_video(
|
| 393 |
+
input_video, background_video, click_points,
|
| 394 |
+
output_path, use_matanyone, progress_callback
|
| 395 |
+
)
|
| 396 |
+
return result
|
| 397 |
+
finally:
|
| 398 |
+
processor.cleanup()
|
| 399 |
+
|
| 400 |
+
if __name__ == "__main__":
|
| 401 |
+
# Test the pipeline
|
| 402 |
+
import argparse
|
| 403 |
+
parser = argparse.ArgumentParser()
|
| 404 |
+
parser.add_argument("--input", required=True)
|
| 405 |
+
parser.add_argument("--background", required=True)
|
| 406 |
+
parser.add_argument("--output", required=True)
|
| 407 |
+
parser.add_argument("--clicks", required=True, help="JSON string of click points")
|
| 408 |
+
parser.add_argument("--no-matanyone", action="store_true")
|
| 409 |
+
|
| 410 |
+
args = parser.parse_args()
|
| 411 |
+
|
| 412 |
+
click_points = json.loads(args.clicks)
|
| 413 |
+
use_matanyone = not args.no_matanyone
|
| 414 |
+
|
| 415 |
+
success = process_video_two_stage(
|
| 416 |
+
args.input, args.background, click_points,
|
| 417 |
+
args.output, use_matanyone,
|
| 418 |
+
lambda msg, prog=None: print(f"Progress: {msg} ({prog}%)" if prog else msg)
|
| 419 |
+
)
|
| 420 |
+
|
| 421 |
+
print("Processing completed!" if success else "Processing failed!")
|
two_stage_pipeline.py
ADDED
|
@@ -0,0 +1,388 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
|
| 4 |
+
- Stage 1: SAM2 -> lossless mask stream (FFV1 .mkv) + meta.json, then unload SAM2
|
| 5 |
+
- Stage 2: read mask stream -> (optional) MatAnyone refine -> composite -> mux audio
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import os, sys, gc, json, cv2, time, uuid, torch, shutil, logging, subprocess, threading
|
| 9 |
+
import numpy as np
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
from typing import Optional, Callable, Tuple, Dict, Any
|
| 12 |
+
from PIL import Image
|
| 13 |
+
|
| 14 |
+
logger = logging.getLogger("backgroundfx_pro.two_stage")
|
| 15 |
+
if not logger.handlers:
|
| 16 |
+
h = logging.StreamHandler()
|
| 17 |
+
h.setFormatter(logging.Formatter("[%(asctime)s] %(levelname)s:%(name)s: %(message)s"))
|
| 18 |
+
logger.addHandler(h)
|
| 19 |
+
logger.setLevel(logging.INFO)
|
| 20 |
+
|
| 21 |
+
# ---------------------------
|
| 22 |
+
# Env & CUDA helpers
|
| 23 |
+
# ---------------------------
|
| 24 |
+
def setup_env():
|
| 25 |
+
os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF","expandable_segments:True,max_split_size_mb:256,garbage_collection_threshold:0.7")
|
| 26 |
+
os.environ.setdefault("OMP_NUM_THREADS","1")
|
| 27 |
+
os.environ.setdefault("OPENBLAS_NUM_THREADS","1")
|
| 28 |
+
os.environ.setdefault("MKL_NUM_THREADS","1")
|
| 29 |
+
torch.set_grad_enabled(False)
|
| 30 |
+
try:
|
| 31 |
+
torch.backends.cudnn.benchmark = True
|
| 32 |
+
torch.backends.cuda.matmul.allow_tf32 = True
|
| 33 |
+
torch.backends.cudnn.allow_tf32 = True
|
| 34 |
+
torch.set_float32_matmul_precision("high")
|
| 35 |
+
except Exception:
|
| 36 |
+
pass
|
| 37 |
+
if torch.cuda.is_available():
|
| 38 |
+
try:
|
| 39 |
+
torch.cuda.set_per_process_memory_fraction(float(os.getenv("CUDA_MEMORY_FRACTION","0.88")))
|
| 40 |
+
except Exception:
|
| 41 |
+
pass
|
| 42 |
+
|
| 43 |
+
def free_cuda():
|
| 44 |
+
if torch.cuda.is_available():
|
| 45 |
+
torch.cuda.ipc_collect()
|
| 46 |
+
torch.cuda.empty_cache()
|
| 47 |
+
|
| 48 |
+
def unload_sam2_modules():
|
| 49 |
+
"""Aggressively unload SAM2 python modules to reduce RSS."""
|
| 50 |
+
try:
|
| 51 |
+
import importlib
|
| 52 |
+
mods = [m for m in list(sys.modules) if m.startswith("sam2")]
|
| 53 |
+
for m in mods:
|
| 54 |
+
sys.modules.pop(m, None)
|
| 55 |
+
importlib.invalidate_caches()
|
| 56 |
+
gc.collect()
|
| 57 |
+
free_cuda()
|
| 58 |
+
logger.info("SAM2 modules unloaded.")
|
| 59 |
+
except Exception as e:
|
| 60 |
+
logger.warning(f"Unloading SAM2 modules: {e}")
|
| 61 |
+
|
| 62 |
+
# ---------------------------
|
| 63 |
+
# Video probing
|
| 64 |
+
# ---------------------------
|
| 65 |
+
def probe_video(path:str) -> Tuple[int,int,float,int]:
|
| 66 |
+
cap = cv2.VideoCapture(path)
|
| 67 |
+
if not cap.isOpened():
|
| 68 |
+
raise RuntimeError(f"Cannot open video: {path}")
|
| 69 |
+
fps = cap.get(cv2.CAP_PROP_FPS) or 25.0
|
| 70 |
+
w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
|
| 71 |
+
h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
|
| 72 |
+
n = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
|
| 73 |
+
cap.release()
|
| 74 |
+
return w,h,float(fps),n
|
| 75 |
+
|
| 76 |
+
# ---------------------------
|
| 77 |
+
# FFmpeg mask writers/readers
|
| 78 |
+
# ---------------------------
|
| 79 |
+
class MaskFFV1Writer:
|
| 80 |
+
"""Write uint8 binary/gray masks to FFV1 lossless .mkv via pipe."""
|
| 81 |
+
def __init__(self, path:str, w:int, h:int, fps:float):
|
| 82 |
+
self.path = path
|
| 83 |
+
self.w, self.h, self.fps = w,h,fps
|
| 84 |
+
self.proc = None
|
| 85 |
+
|
| 86 |
+
def __enter__(self):
|
| 87 |
+
cmd = [
|
| 88 |
+
"ffmpeg","-y","-hide_banner","-loglevel","error",
|
| 89 |
+
"-f","rawvideo","-pix_fmt","gray","-s",f"{self.w}x{self.h}","-r",f"{self.fps}",
|
| 90 |
+
"-i","-",
|
| 91 |
+
"-c:v","ffv1","-level","3","-g","1", self.path
|
| 92 |
+
]
|
| 93 |
+
self.proc = subprocess.Popen(cmd, stdin=subprocess.PIPE)
|
| 94 |
+
return self
|
| 95 |
+
|
| 96 |
+
def write(self, mask_u8: np.ndarray):
|
| 97 |
+
# Expect HxW uint8 (0/255). Ensure contiguous.
|
| 98 |
+
if mask_u8.dtype != np.uint8:
|
| 99 |
+
mask_u8 = mask_u8.astype(np.uint8)
|
| 100 |
+
self.proc.stdin.write(mask_u8.tobytes())
|
| 101 |
+
|
| 102 |
+
def __exit__(self, exc_type, exc, tb):
|
| 103 |
+
if self.proc:
|
| 104 |
+
try:
|
| 105 |
+
self.proc.stdin.flush()
|
| 106 |
+
self.proc.stdin.close()
|
| 107 |
+
self.proc.wait(timeout=120)
|
| 108 |
+
except Exception:
|
| 109 |
+
self.proc.kill()
|
| 110 |
+
|
| 111 |
+
class MaskFFV1Reader:
|
| 112 |
+
"""Read uint8 masks from FFV1 .mkv via pipe."""
|
| 113 |
+
def __init__(self, path:str, w:int, h:int):
|
| 114 |
+
self.path = path
|
| 115 |
+
self.w,self.h = w,h
|
| 116 |
+
self.proc = None
|
| 117 |
+
self.frame_bytes = w*h
|
| 118 |
+
|
| 119 |
+
def __enter__(self):
|
| 120 |
+
cmd = [
|
| 121 |
+
"ffmpeg","-hide_banner","-loglevel","error","-i", self.path,
|
| 122 |
+
"-f","rawvideo","-pix_fmt","gray","-"
|
| 123 |
+
]
|
| 124 |
+
self.proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
|
| 125 |
+
return self
|
| 126 |
+
|
| 127 |
+
def read(self) -> Optional[np.ndarray]:
|
| 128 |
+
buf = self.proc.stdout.read(self.frame_bytes)
|
| 129 |
+
if not buf or len(buf) < self.frame_bytes:
|
| 130 |
+
return None
|
| 131 |
+
return np.frombuffer(buf, dtype=np.uint8).reshape(self.h, self.w)
|
| 132 |
+
|
| 133 |
+
def __exit__(self, exc_type, exc, tb):
|
| 134 |
+
if self.proc:
|
| 135 |
+
try:
|
| 136 |
+
self.proc.stdout.close()
|
| 137 |
+
self.proc.wait(timeout=30)
|
| 138 |
+
except Exception:
|
| 139 |
+
self.proc.kill()
|
| 140 |
+
|
| 141 |
+
# Fallback: PNG sequence (disk heavy but simple & robust)
|
| 142 |
+
class MaskPNGWriter:
|
| 143 |
+
def __init__(self, dirpath: Path):
|
| 144 |
+
self.dir = dirpath; self.dir.mkdir(parents=True, exist_ok=True); self.idx=0
|
| 145 |
+
def write(self, mask_u8: np.ndarray):
|
| 146 |
+
cv2.imwrite(str(self.dir / f"{self.idx:06d}.png"), mask_u8)
|
| 147 |
+
self.idx+=1
|
| 148 |
+
|
| 149 |
+
class MaskPNGReader:
|
| 150 |
+
def __init__(self, dirpath: Path):
|
| 151 |
+
self.dir=dirpath; self.idx=0
|
| 152 |
+
def read(self) -> Optional[np.ndarray]:
|
| 153 |
+
p = self.dir / f"{self.idx:06d}.png"
|
| 154 |
+
if not p.exists(): return None
|
| 155 |
+
img = cv2.imread(str(p), cv2.IMREAD_GRAYSCALE)
|
| 156 |
+
self.idx+=1
|
| 157 |
+
return img
|
| 158 |
+
|
| 159 |
+
# ---------------------------
|
| 160 |
+
# Stage 1 — SAM2 → mask dump
|
| 161 |
+
# ---------------------------
|
| 162 |
+
def stage1_dump_masks(video_path:str, out_dir:Path, obj_point:Tuple[int,int]=None) -> Dict[str,Any]:
|
| 163 |
+
"""
|
| 164 |
+
Run only SAM2, save masks as FFV1 (preferred) or PNG sequence + meta.json.
|
| 165 |
+
Returns meta dict.
|
| 166 |
+
"""
|
| 167 |
+
setup_env()
|
| 168 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 169 |
+
w,h,fps,n = probe_video(video_path)
|
| 170 |
+
out_dir.mkdir(parents=True, exist_ok=True)
|
| 171 |
+
meta = {"video":video_path, "width":w,"height":h,"fps":fps,"frames":n, "storage":None}
|
| 172 |
+
logger.info(f"[Stage1] {w}x{h}@{fps:.2f} | frames={n}")
|
| 173 |
+
|
| 174 |
+
# Load SAM2 (your wrapper)
|
| 175 |
+
from models.sam2_loader import SAM2Predictor
|
| 176 |
+
predictor = SAM2Predictor(device=device)
|
| 177 |
+
state = predictor.init_state(video_path=video_path)
|
| 178 |
+
|
| 179 |
+
# Prompt: center positive if not provided
|
| 180 |
+
if obj_point is None:
|
| 181 |
+
obj_point = (w//2, h//2)
|
| 182 |
+
pts = np.array([[obj_point[0], obj_point[1]]], dtype=np.float32)
|
| 183 |
+
labels = np.array([1], dtype=np.int32)
|
| 184 |
+
ann_obj_id = 1
|
| 185 |
+
with torch.inference_mode():
|
| 186 |
+
predictor.add_new_points(state, 0, ann_obj_id, pts, labels)
|
| 187 |
+
|
| 188 |
+
# Preferred: FFV1 mask stream
|
| 189 |
+
mask_mkv = out_dir / "mask.mkv"
|
| 190 |
+
use_png = False
|
| 191 |
+
try:
|
| 192 |
+
with MaskFFV1Writer(str(mask_mkv), w, h, fps) as writer, \
|
| 193 |
+
torch.inference_mode(), torch.autocast("cuda", dtype=torch.float16 if device.type=="cuda" else None):
|
| 194 |
+
for _, out_ids, out_logits in predictor.propagate_in_video(state):
|
| 195 |
+
# pick ann_obj_id
|
| 196 |
+
i = None
|
| 197 |
+
if isinstance(out_ids, torch.Tensor):
|
| 198 |
+
nz = (out_ids == ann_obj_id).nonzero(as_tuple=False)
|
| 199 |
+
if nz.numel() > 0: i = nz[0].item()
|
| 200 |
+
else:
|
| 201 |
+
ids = list(out_ids); i = ids.index(ann_obj_id) if ann_obj_id in ids else None
|
| 202 |
+
if i is None:
|
| 203 |
+
# write empty
|
| 204 |
+
writer.write(np.zeros((h,w), np.uint8))
|
| 205 |
+
continue
|
| 206 |
+
mask = (out_logits[i] > 0).detach()
|
| 207 |
+
mask_u8 = (mask.float().mul_(255).to("cpu", non_blocking=True).numpy()).astype(np.uint8)
|
| 208 |
+
writer.write(mask_u8)
|
| 209 |
+
meta["storage"] = "ffv1"
|
| 210 |
+
meta["mask_path"] = str(mask_mkv)
|
| 211 |
+
logger.info("[Stage1] Masks saved as FFV1 .mkv")
|
| 212 |
+
except Exception as e:
|
| 213 |
+
logger.warning(f"FFV1 writer failed ({e}), falling back to PNG sequence.")
|
| 214 |
+
png_dir = out_dir / "masks_png"
|
| 215 |
+
wr = MaskPNGWriter(png_dir)
|
| 216 |
+
with torch.inference_mode(), torch.autocast("cuda", dtype=torch.float16 if device.type=="cuda" else None):
|
| 217 |
+
for _, out_ids, out_logits in predictor.propagate_in_video(state):
|
| 218 |
+
i = None
|
| 219 |
+
if isinstance(out_ids, torch.Tensor):
|
| 220 |
+
nz = (out_ids == ann_obj_id).nonzero(as_tuple=False)
|
| 221 |
+
if nz.numel() > 0: i = nz[0].item()
|
| 222 |
+
else:
|
| 223 |
+
ids = list(out_ids); i = ids.index(ann_obj_id) if ann_obj_id in ids else None
|
| 224 |
+
if i is None:
|
| 225 |
+
wr.write(np.zeros((h,w), np.uint8)); continue
|
| 226 |
+
mask = (out_logits[i] > 0).detach()
|
| 227 |
+
wr.write((mask.float().mul_(255).to("cpu").numpy()).astype(np.uint8))
|
| 228 |
+
meta["storage"] = "png"
|
| 229 |
+
meta["mask_path"] = str(png_dir)
|
| 230 |
+
|
| 231 |
+
# Persist meta
|
| 232 |
+
with open(out_dir / "meta.json","w") as f:
|
| 233 |
+
json.dump(meta, f)
|
| 234 |
+
# Unload SAM2 completely
|
| 235 |
+
del predictor, state
|
| 236 |
+
free_cuda(); unload_sam2_modules()
|
| 237 |
+
return meta
|
| 238 |
+
|
| 239 |
+
# ---------------------------
|
| 240 |
+
# Stage 2 — refine + compose
|
| 241 |
+
# ---------------------------
|
| 242 |
+
def stage2_refine_and_compose(video_path:str, mask_dir:Path, background_image:Image.Image,
|
| 243 |
+
out_path:str, use_matany:bool=True) -> str:
|
| 244 |
+
w,h,fps,n = probe_video(video_path)
|
| 245 |
+
bg = background_image.resize((w,h), Image.LANCZOS)
|
| 246 |
+
bg_np = np.array(bg).astype(np.float32)
|
| 247 |
+
|
| 248 |
+
# Read meta
|
| 249 |
+
with open(mask_dir / "meta.json","r") as f:
|
| 250 |
+
meta = json.load(f)
|
| 251 |
+
storage = meta["storage"]; mask_path = meta["mask_path"]
|
| 252 |
+
|
| 253 |
+
# Optional MatAnyone
|
| 254 |
+
session = None
|
| 255 |
+
if use_matany:
|
| 256 |
+
try:
|
| 257 |
+
from models.matanyone_loader import MatAnyoneSession as _M
|
| 258 |
+
except Exception:
|
| 259 |
+
try:
|
| 260 |
+
from models.matanyone_loader import MatAnyoneLoader as _M
|
| 261 |
+
except Exception:
|
| 262 |
+
_M = None
|
| 263 |
+
if _M:
|
| 264 |
+
session = _M(device=torch.device("cuda" if torch.cuda.is_available() else "cpu"))
|
| 265 |
+
if hasattr(session,"model") and session.model is not None:
|
| 266 |
+
session.model.eval()
|
| 267 |
+
|
| 268 |
+
# Open video + writer
|
| 269 |
+
cap = cv2.VideoCapture(video_path)
|
| 270 |
+
fourcc = cv2.VideoWriter_fourcc(*"mp4v")
|
| 271 |
+
tmp_out = str(Path(out_path).with_suffix(".noaudio.mp4"))
|
| 272 |
+
writer = cv2.VideoWriter(tmp_out, fourcc, fps, (w,h))
|
| 273 |
+
|
| 274 |
+
# Open mask reader
|
| 275 |
+
if storage == "ffv1":
|
| 276 |
+
mreader = MaskFFV1Reader(mask_path, w, h)
|
| 277 |
+
mreader.__enter__()
|
| 278 |
+
read_mask = lambda : mreader.read()
|
| 279 |
+
else:
|
| 280 |
+
mreader = MaskPNGReader(Path(mask_path))
|
| 281 |
+
read_mask = lambda : mreader.read()
|
| 282 |
+
|
| 283 |
+
i = 0
|
| 284 |
+
try:
|
| 285 |
+
while True:
|
| 286 |
+
ok, frame_bgr = cap.read()
|
| 287 |
+
if not ok: break
|
| 288 |
+
mask_u8 = read_mask()
|
| 289 |
+
if mask_u8 is None:
|
| 290 |
+
# out of masks; write original
|
| 291 |
+
writer.write(frame_bgr); i+=1; continue
|
| 292 |
+
|
| 293 |
+
# Optional refine
|
| 294 |
+
if session is not None:
|
| 295 |
+
try:
|
| 296 |
+
frame_rgb = cv2.cvtColor(frame_bgr, cv2.COLOR_BGR2RGB)
|
| 297 |
+
# Provide a float mask 0..1 to session; adapt if your API differs
|
| 298 |
+
mask_f = (mask_u8.astype(np.float32) / 255.0)
|
| 299 |
+
if hasattr(session,"refine_mask"):
|
| 300 |
+
mask_refined = session.refine_mask(frame_rgb, mask_f)
|
| 301 |
+
elif hasattr(session,"process_frame"):
|
| 302 |
+
mask_refined = session.process_frame(frame_rgb, mask_f)
|
| 303 |
+
else:
|
| 304 |
+
mask_refined = mask_f
|
| 305 |
+
if isinstance(mask_refined, torch.Tensor):
|
| 306 |
+
mask_u8 = (mask_refined.detach().clamp(0,1).mul(255).to("cpu").numpy()).astype(np.uint8)
|
| 307 |
+
elif isinstance(mask_refined, np.ndarray):
|
| 308 |
+
mask_u8 = (np.clip(mask_refined,0,1)*255).astype(np.uint8)
|
| 309 |
+
except Exception as e:
|
| 310 |
+
logger.debug(f"MatAnyone refine failed @frame {i}: {e}")
|
| 311 |
+
|
| 312 |
+
# Composite
|
| 313 |
+
m = (mask_u8.astype(np.float32)/255.0)[...,None] # HxWx1
|
| 314 |
+
fr = cv2.cvtColor(frame_bgr, cv2.COLOR_BGR2RGB).astype(np.float32)
|
| 315 |
+
comp = fr*m + bg_np*(1.0-m)
|
| 316 |
+
comp_bgr = cv2.cvtColor(comp.astype(np.uint8), cv2.COLOR_RGB2BGR)
|
| 317 |
+
writer.write(comp_bgr)
|
| 318 |
+
|
| 319 |
+
if i % 50 == 0:
|
| 320 |
+
logger.info(f"[Stage2] frame {i}/{n}")
|
| 321 |
+
i += 1
|
| 322 |
+
finally:
|
| 323 |
+
cap.release(); writer.release()
|
| 324 |
+
if isinstance(mreader, MaskFFV1Reader):
|
| 325 |
+
mreader.__exit__(None,None,None)
|
| 326 |
+
|
| 327 |
+
# Mux audio
|
| 328 |
+
final_out = str(Path(out_path))
|
| 329 |
+
cmd = [
|
| 330 |
+
"ffmpeg","-y","-hide_banner","-loglevel","error",
|
| 331 |
+
"-i", tmp_out, "-i", video_path,
|
| 332 |
+
"-map","0:v:0","-map","1:a:0","-c:v","copy","-c:a","aac","-shortest", final_out
|
| 333 |
+
]
|
| 334 |
+
try:
|
| 335 |
+
r = subprocess.run(cmd, capture_output=True, text=True, timeout=180)
|
| 336 |
+
if r.returncode != 0:
|
| 337 |
+
logger.warning(f"Audio mux failed: {r.stderr.strip()}")
|
| 338 |
+
shutil.move(tmp_out, final_out)
|
| 339 |
+
else:
|
| 340 |
+
os.remove(tmp_out)
|
| 341 |
+
except Exception:
|
| 342 |
+
shutil.move(tmp_out, final_out)
|
| 343 |
+
return final_out
|
| 344 |
+
|
| 345 |
+
# ---------------------------
|
| 346 |
+
# Orchestrator
|
| 347 |
+
# ---------------------------
|
| 348 |
+
def process_two_stage(
|
| 349 |
+
video_path:str,
|
| 350 |
+
background_image: Image.Image,
|
| 351 |
+
workdir: Optional[Path]=None,
|
| 352 |
+
progress: Optional[Callable[[str,float],None]] = None,
|
| 353 |
+
use_matany: bool = True,
|
| 354 |
+
) -> str:
|
| 355 |
+
setup_env()
|
| 356 |
+
if workdir is None:
|
| 357 |
+
workdir = Path.cwd()/ "tmp" / f"job_{uuid.uuid4().hex[:8]}"
|
| 358 |
+
workdir.mkdir(parents=True, exist_ok=True)
|
| 359 |
+
|
| 360 |
+
# Stage 1
|
| 361 |
+
if progress: progress("Stage 1: SAM2 mask pass", 0.05)
|
| 362 |
+
mask_dir = workdir / "sam2_masks"
|
| 363 |
+
meta = stage1_dump_masks(video_path, mask_dir)
|
| 364 |
+
if progress: progress("Stage 1 complete", 0.45)
|
| 365 |
+
|
| 366 |
+
# Stage 2
|
| 367 |
+
if progress: progress("Stage 2: refine + compose", 0.50)
|
| 368 |
+
out_path = workdir / f"final_{int(time.time())}.mp4"
|
| 369 |
+
final_video = stage2_refine_and_compose(video_path, mask_dir, background_image, str(out_path), use_matany=use_matany)
|
| 370 |
+
if progress: progress("Done", 1.0)
|
| 371 |
+
logger.info(f"Output: {final_video}")
|
| 372 |
+
return final_video
|
| 373 |
+
|
| 374 |
+
# ---------------------------
|
| 375 |
+
# CLI
|
| 376 |
+
# ---------------------------
|
| 377 |
+
if __name__ == "__main__":
|
| 378 |
+
import argparse
|
| 379 |
+
parser = argparse.ArgumentParser(description="Two-stage BackgroundFX Pro")
|
| 380 |
+
parser.add_argument("--video", required=True)
|
| 381 |
+
parser.add_argument("--background", required=True)
|
| 382 |
+
parser.add_argument("--outdir", default=None)
|
| 383 |
+
parser.add_argument("--no-matany", action="store_true")
|
| 384 |
+
args = parser.parse_args()
|
| 385 |
+
|
| 386 |
+
bg = Image.open(args.background).convert("RGB")
|
| 387 |
+
out = process_two_stage(args.video, bg, Path(args.outdir) if args.outdir else None, use_matany=not args.no_matany)
|
| 388 |
+
print(out)
|
ui_core_functionality.py
CHANGED
|
@@ -451,7 +451,7 @@ def process_video_pipeline(
|
|
| 451 |
"""Process video using the hardened pipeline"""
|
| 452 |
try:
|
| 453 |
# Lazy import to avoid startup issues
|
| 454 |
-
from
|
| 455 |
|
| 456 |
logger.info(f"🎬 Starting pipeline processing in {job_dir}")
|
| 457 |
progress_tracker.update("Initializing pipeline...")
|
|
|
|
| 451 |
"""Process video using the hardened pipeline"""
|
| 452 |
try:
|
| 453 |
# Lazy import to avoid startup issues
|
| 454 |
+
from two_stage_pipeline import process as pipeline_process
|
| 455 |
|
| 456 |
logger.info(f"🎬 Starting pipeline processing in {job_dir}")
|
| 457 |
progress_tracker.update("Initializing pipeline...")
|