Update processing/two_stage/two_stage_processor.py
Browse files1234567891011121316 unmodified lines3031323334353617 unmodified lines545556575859607 unmodified lines6869707172737475765 unmodified lines828384858687198 unmodified lines28628728828929029129229329429529614 unmodified lines3113123133143153163177 unmodified lines3253263273283293303313323333343353363373383393403413423433443453463473483 unmodified lines3523533543553563573583593603613623633646 unmodified lines37137237337437537637737837938038111 unmodified lines3933943953963973983994004014024034044054064074084094104114 unmodified lines41641741841942042111 unmodified lines4334344354364374384394404414424434444454464474484494504514524534544554564574586 unmodified lines46546646746846947047147247347447515 unmodified lines49149249349449549649749849950050150213 unmodified lines5165175185195205215225235245255265275285295305315 unmodified lines53753853954054154219 unmodified lines56256356456556656756856957057157232 unmodified lines605606607608609610611118 unmodified lines73073173273373473573678 unmodified lines8158168178188198208218228238248258268278283 unmodified lines83283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998026 unmodified lines100710081009101010111012101317 unmodified lines10311032103310341035103610377 unmodified lines1045104610471048104910501051105210531054105510561057#!/usr/bin/env python3"""EFFICIENT Two-Stage Alpha Channel Processing System β 2025-09-09VIDEO-TO-VIDEO PIPELINE: Direct alpha compositing without green screenStage 1: SAM2 creates reference mask from first 3 framesStage 2: MatAnyone processes entire video β pha.mp4 (alpha matte)Stage 3: Direct alpha compositing with background β final.mp4FEATURES:- No green screen or chroma key needed- Direct alpha channel compositing- Chunked processing for long videos with memory management- Dimension mismatch handling- Memory optimization with light/deep cleanup modes16 unmodified linesimport subprocessfrom pathlib import Pathfrom typing import Optional, Tuple, Dict, Any, Listfrom moviepy.editor import VideoFileClip, CompositeVideoClip, ImageClip, concatenate_videoclipsimport moviepy.video.fx.all as vfx# Setup logging first17 unmodified lines# ==============================================================================class ProcessingConfig:"""Configuration settings for two-stage processing."""# Reference mask creationREFERENCE_FRAMES = 3 # Number of frames to use for reference mask7 unmodified linesVIDEO_CODEC = 'libx264'VIDEO_BITRATE = '8000k'AUDIO_CODEC = 'aac'# Processing limitsMAX_FRAMES_FOR_REFERENCE = 10 # Safety limit# Memory managementCLEAR_CACHE_AFTER_STAGE = True # Clear GPU cache between stages5 unmodified linesSAVE_DEBUG_FILES = TrueDEBUG_FRAME_INTERVAL = 30 # Save every Nth frame for debuggingENABLE_MEMORY_TESTING = False # DISABLED: Memory testing causes predictor deletion# ==============================================================================# CHAPTER 3: MEMORY MANAGEMENT UTILITIES198 unmodified linesreturn cls.PROFILES.get(quality, cls.PROFILES['medium'])# ==============================================================================# CHAPTER 5: CHUNKED VIDEO PROCESSOR# ==============================================================================class ChunkedVideoProcessor:"""Handles splitting and reassembling videos for chunked processing."""def __init__(self, temp_dir: str, config: ProcessingConfig):self.temp_dir = temp_dir14 unmodified linesreturn Falsedef split_video_into_chunks(self, video_path: str) -> List[str]:"""Split video into chunks for processing."""try:with VideoFileClip(video_path) as clip:duration = clip.duration7 unmodified lines# Calculate chunk end timeend_time = min(current_time + chunk_duration, duration)# Create chunkchunk_clip = clip.subclip(current_time, end_time)chunk_path = os.path.join(self.chunks_dir, f"chunk_{chunk_index:03d}.mp4")chunk_clip.write_videofile(chunk_path,codec=self.config.VIDEO_CODEC,audio_codec=self.config.AUDIO_CODEC,verbose=False,logger=None)chunk_clip.close()chunk_paths.append(chunk_path)logger.info(f"Created chunk {chunk_index}: {current_time:.1f}s - {end_time:.1f}s")# Move to next chunk with slight overlap for smooth transitionscurrent_time = end_time - (self.config.CHUNK_OVERLAP_FRAMES / clip.fps)chunk_index += 1logger.info(f"Split video into {len(chunk_paths)} chunks")3 unmodified lineslogger.error(f"Video chunking failed: {e}")raisedef reassemble_chunks(self, processed_chunk_paths: List[str], output_path: str) -> str:"""Reassemble processed chunks into final video."""try:if len(processed_chunk_paths) == 1:# Single chunk, just copyshutil.copy2(processed_chunk_paths[0], output_path)logger.info("Single chunk, copied directly to output")return output_path# Load all chunks6 unmodified lineslogger.info(f"Concatenating {len(chunk_clips)} chunks...")final_clip = concatenate_videoclips(chunk_clips, method="compose")# Write final videofinal_clip.write_videofile(output_path,codec=self.config.VIDEO_CODEC,audio_codec=self.config.AUDIO_CODEC,verbose=False,logger=None)11 unmodified linesraise# ==============================================================================# CHAPTER 6: TWOSTAGEPROCESSOR CLASS DEFINITION# ==============================================================================class TwoStageProcessor:"""Efficient two-stage alpha channel processor with video-to-video pipeline.This processor avoids green screen entirely by using alpha channels:1. SAM2 creates reference mask from first few frames2. MatAnyone processes entire video using reference mask β pha.mp4 (alpha matte)3. Direct alpha compositing with background β final.mp4No chroma key or green screen needed!"""def __init__(self, sam2_handler, matanyone_handler, temp_dir: Optional[str] = None):4 unmodified linesself.config = ProcessingConfig()self.memory_manager = MemoryManager(self.config)self.chunked_processor = ChunkedVideoProcessor(self.temp_dir, self.config)# Ensure temp directory existsos.makedirs(self.temp_dir, exist_ok=True)11 unmodified linescallback: Optional[callable] = None,**kwargs) -> Tuple[str, str]:"""Main processing pipeline - video to video with alpha compositing.Returns:Tuple[str, str]: (final_output_path, status_message)"""try:logger.info(f"π¬ Two-Stage Alpha Pipeline: {video_path}")logger.info(f"π― Background: {background_path}")logger.info(f"π Temp: {self.temp_dir}")logger.info(f"π§ Initial {self.memory_manager.get_gpu_memory_info()}")# Determine if chunking is neededneeds_chunking = self.chunked_processor.should_chunk_video(video_path)if needs_chunking:logger.info("Video exceeds chunk duration, using chunked processing...")result = self._process_chunked_video(video_path, background_path, output_path, quality, callback)else:logger.info("Video within chunk duration, using single-pass processing...")result = self._process_single_video(video_path, background_path, output_path, quality, trim_seconds, callback)# Final memory reportlogger.info(self.memory_manager.get_memory_report())6 unmodified lineslogger.error(f"Traceback: {traceback.format_exc()}")return None, error_msgdef _process_chunked_video(self,video_path: str,background_path: str,output_path: str,quality: str,callback: Optional[callable] = None) -> Tuple[str, str]:"""Process long video using chunked approach."""try:15 unmodified lineslogger.info(f"Processing chunk {i+1}/{total_chunks}: {chunk_path}")logger.info(f"Pre-chunk memory: {self.memory_manager.get_gpu_memory_info()}")# Process this chunk at full resolutionchunk_output = os.path.join(self.temp_dir, f"processed_chunk_{i:03d}.mp4")result_path, status = self._process_single_video(chunk_path, background_path, chunk_output, quality,trim_seconds=None, callback=None # No sub-callbacks for chunks)if result_path and os.path.exists(result_path):13 unmodified lineslogger.info(f"Post-chunk memory: {self.memory_manager.get_gpu_memory_info()}")if callback:callback("Reassembling chunks...", 85)# Reassemble chunksfinal_path = self.chunked_processor.reassemble_chunks(processed_chunks, output_path)if callback:callback("Chunked processing completed!", 100)logger.info(f"β Chunked processing completed: {final_path}")return final_path, f"Success - Processed {total_chunks} chunks"except Exception as e:logger.error(f"Chunked processing failed: {e}")5 unmodified linesoutput_path: str,quality: str,trim_seconds: Optional[int] = None,callback: Optional[callable] = None) -> Tuple[str, str]:"""Process a single video (or chunk) through the pipeline."""try:19 unmodified linesself.memory_manager.cleanup_model(self.matanyone_handler, "MatAnyone", deep_cleanup=False)self.memory_manager.cleanup_stage("MatAnyone", force=True)# Stage 3: Direct alpha compositing (no green screen!)if callback:callback("Alpha compositing with background...", 70)logger.info("STAGE 3: Direct alpha compositing with background...")final_path = self._stage3_alpha_composite(video_path, alpha_video_path, background_path, output_path, quality)# Final memory cleanupself.memory_manager.cleanup_stage("Final")32 unmodified lineslogger.warning(f"Failed to cleanup: {e}")# ==============================================================================# CHAPTER 7: STAGE 1 - REFERENCE MASK CREATION (SAM2)# ==============================================================================def _stage1_create_reference_mask(self, video_path: str) -> str:118 unmodified linesreturn result# ==============================================================================# CHAPTER 8: STAGE 2 - MATANYONE PROCESSING# ==============================================================================def _stage2_matanyone_processing(self, video_path: str, reference_mask_path: str, trim_seconds: Optional[int]) -> str:78 unmodified linesraisedef _trim_video(self, input_path: str, output_path: str, seconds: int):"""Trim video to specified duration."""try:with VideoFileClip(input_path) as clip:trimmed = clip.subclip(0, min(seconds, clip.duration))trimmed.write_videofile(output_path,codec=self.config.VIDEO_CODEC,audio_codec=self.config.AUDIO_CODEC,verbose=False,logger=None)3 unmodified linesraise# ==============================================================================# CHAPTER 9: STAGE 3 - DIRECT ALPHA COMPOSITING (NO GREEN SCREEN!)# ==============================================================================def _stage3_alpha_composite(self, original_video_path: str, alpha_video_path: str,background_path: str, output_path: str, quality: str) -> str:"""Stage 3: Direct alpha compositing without any green screen.Uses the alpha matte from MatAnyone to composite the persondirectly onto the new background."""try:# Get quality profileprofile = QualityManager.get_profile(quality)# Open videosoriginal_cap = cv2.VideoCapture(original_video_path)alpha_cap = cv2.VideoCapture(alpha_video_path)if not original_cap.isOpened():raise RuntimeError(f"Cannot open original video: {original_video_path}")if not alpha_cap.isOpened():raise RuntimeError(f"Cannot open alpha video: {alpha_video_path}")# Get video propertiesfps = original_cap.get(cv2.CAP_PROP_FPS)width = int(original_cap.get(cv2.CAP_PROP_FRAME_WIDTH))height = int(original_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))total_frames = int(original_cap.get(cv2.CAP_PROP_FRAME_COUNT))# Get alpha video dimensionsalpha_width = int(alpha_cap.get(cv2.CAP_PROP_FRAME_WIDTH))alpha_height = int(alpha_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))logger.info(f"Original video: {width}x{height} @ {fps} FPS, {total_frames} frames")logger.info(f"Alpha video dimensions: {alpha_width}x{alpha_height}")# Load and prepare backgroundif background_path.lower().endswith(('.mp4', '.avi', '.mov', '.mkv')):# Video background - process frame by framebg_cap = cv2.VideoCapture(background_path)bg_is_video = Trueelse:# Image backgroundbg_image = cv2.imread(background_path)if bg_image is None:raise RuntimeError(f"Cannot load background image: {background_path}")# Resize to match videobg_image = cv2.resize(bg_image, (width, height))bg_is_video = False# Setup video writerfourcc = cv2.VideoWriter_fourcc(*'mp4v')out = cv2.VideoWriter(output_path, fourcc, fps, (width, height))frame_count = 0while True:# Read framesret_orig, orig_frame = original_cap.read()ret_alpha, alpha_frame = alpha_cap.read()if not ret_orig or not ret_alpha:break# Get background frameif bg_is_video:ret_bg, bg_frame = bg_cap.read()if not ret_bg:# Loop background if it's shorterbg_cap.set(cv2.CAP_PROP_POS_FRAMES, 0)ret_bg, bg_frame = bg_cap.read()bg_frame = cv2.resize(bg_frame, (width, height))else:bg_frame = bg_image.copy()# Convert alpha frame to grayscale maskif len(alpha_frame.shape) == 3:alpha_mask = cv2.cvtColor(alpha_frame, cv2.COLOR_BGR2GRAY)else:alpha_mask = alpha_frame# Handle dimension mismatch - resize alpha to match original if neededif alpha_mask.shape[:2] != orig_frame.shape[:2]:if frame_count == 0: # Log only oncelogger.info(f"Resizing alpha from {alpha_mask.shape[:2]} to {orig_frame.shape[:2]}")alpha_mask = cv2.resize(alpha_mask, (width, height), interpolation=cv2.INTER_LINEAR)# Normalize alpha to 0-1 rangealpha_normalized = alpha_mask.astype(np.float32) / 255.0# Create 3-channel alpha for compositingalpha_3d = np.stack([alpha_normalized] * 3, axis=2)# Composite: background where alpha=0, person where alpha=1orig_frame_float = orig_frame.astype(np.float32)bg_frame_float = bg_frame.astype(np.float32)# Direct alpha compositingcomposite = alpha_3d * orig_frame_float + (1 - alpha_3d) * bg_frame_floatcomposite = np.clip(composite, 0, 255).astype(np.uint8)# Write frameout.write(composite)frame_count += 1# Progress loggingif frame_count % self.config.MEMORY_CHECK_INTERVAL == 0:logger.info(f"Compositing progress: {frame_count}/{total_frames}")if self.memory_manager.should_clear_memory():logger.info("Memory high during compositing, clearing...")self.memory_manager.clear_gpu_cache()# Save debug frame occasionallyif self.config.SAVE_DEBUG_FILES and frame_count % self.config.DEBUG_FRAME_INTERVAL == 0:debug_path = os.path.join(self.temp_dir, f"debug_composite_{frame_count:04d}.png")cv2.imwrite(debug_path, composite)# Cleanuporiginal_cap.release()alpha_cap.release()out.release()if bg_is_video:bg_cap.release()if frame_count == 0:raise RuntimeError("No frames processed for output video")# Verify outputif not os.path.exists(output_path):raise RuntimeError("Output file was not created")file_size = os.path.getsize(output_path) / (1024 * 1024) # MBlogger.info(f"β Alpha compositing completed: {output_path} ({file_size:.1f} MB)")logger.info(f" Processed {frame_count} frames")return output_pathexcept Exception as e:logger.error(f"Stage 3 alpha compositing failed: {e}")raise# ==============================================================================# CHAPTER 10: DEBUG AND UTILITY FUNCTIONS# ==============================================================================def _debug_video_info(self, video_path: str, label: str = "Video"):26 unmodified lines'temp_size_mb': 0,'debug_files': 0,'memory_info': self.memory_manager.get_gpu_memory_info(),'memory_report': self.memory_manager.get_memory_report()}try:17 unmodified linesreturn stats# ==============================================================================# CHAPTER 11: EXPORT INTERFACE AND COMPATIBILITY# ==============================================================================def create_two_stage_processor(sam2_handler, matanyone_handler, **kwargs):7 unmodified lines# Main execution exampleif __name__ == "__main__":# Example usage - replace with your actual handlerslogger.info("TwoStageProcessor (Alpha Channel Version) loaded successfully")logger.info("Use create_two_stage_processor(sam2_handler, matanyone_handler) to initialize")# Print configurationconfig = ProcessingConfig()logger.info(f"Pipeline: SAM2 β MatAnyone β Direct Alpha Compositing")logger.info(f"No green screen or chroma key needed!")logger.info(f"Default config: {config.REFERENCE_FRAMES} reference frames")logger.info(f"Chunked processing: {config.MAX_CHUNK_DURATION}s chunks with {config.CHUNK_OVERLAP_FRAMES} frame overlap")logger.info(f"Memory management: Cache clearing={'ON' if config.CLEAR_CACHE_AFTER_STAGE else 'OFF'}")123456789101112131415161716 unmodified lines3435363738394017 unmodified lines585960616263647 unmodified lines7273747576777879808182838485868788895 unmodified lines9596979899100101102103104198 unmodified lines30330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739814 unmodified lines4134144154164174184197 unmodified lines4274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654663 unmodified lines4704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995006 unmodified lines50750850951051151251351451551651751851952052152252352452552652752852911 unmodified lines5415425435445455465475485495505515525535545555565575585595605615625635644 unmodified lines56957057157257357457511 unmodified lines5875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236 unmodified lines63063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466515 unmodified lines68168268368468568668768868969069169213 unmodified lines7067077087097107117127137147157167177187197207217227235 unmodified lines72973073173273373473519 unmodified lines75575675775875976076176276376476576676776832 unmodified lines801802803804805806807118 unmodified lines92692792892993093193278 unmodified lines1011101210131014101510161017101810191020102110221023102410253 unmodified lines102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119126 unmodified lines121812191220122112221223122412251226122712281229123017 unmodified lines12481249125012511252125312547 unmodified lines1262126312641265126612671268126912701271127212731274127512761277127812791280128112821283#!/usr/bin/env python3"""ENHANCED Two-Stage Alpha Channel Processing System β 2025-09-09VIDEO-TO-VIDEO PIPELINE: Direct alpha compositing without green screenStage 1: SAM2 creates reference mask from first 3 framesStage 2: MatAnyone processes entire video β pha.mp4 (alpha matte)Stage 3: Direct alpha compositing with background β final.mp4FEATURES:- No green screen or chroma key needed- Direct alpha channel compositing- Audio preservation throughout pipeline- Full video duration processing (no truncation)- Alpha matte refinement for cleaner edges- Chunked processing for long videos with memory management- Dimension mismatch handling- Memory optimization with light/deep cleanup modes16 unmodified linesimport subprocessfrom pathlib import Pathfrom typing import Optional, Tuple, Dict, Any, Listfrom moviepy.editor import VideoFileClip, AudioFileClip, CompositeVideoClip, ImageClip, concatenate_videoclips, VideoClipimport moviepy.video.fx.all as vfx# Setup logging first17 unmodified lines# ==============================================================================class ProcessingConfig:"""Configuration settings for two-stage processing with audio support."""# Reference mask creationREFERENCE_FRAMES = 3 # Number of frames to use for reference mask7 unmodified linesVIDEO_CODEC = 'libx264'VIDEO_BITRATE = '8000k'AUDIO_CODEC = 'aac'AUDIO_BITRATE = '192k' # Good quality audio# Alpha refinement settingsALPHA_SMOOTHING = 3 # Median blur kernel size for temporal smoothingALPHA_EDGE_BLUR = 1 # Gaussian blur radius for edge featheringALPHA_CONTRAST = 1.2 # Power curve for sharper alpha transitionsENABLE_DEFRINGING = True # Remove color fringing at edgesDEFRINGE_RADIUS = 1 # Radius for defringing operation# Processing limitsMAX_FRAMES_FOR_REFERENCE = 10 # Safety limitMIN_FINAL_CHUNK_DURATION = 10 # Don't create chunks smaller than this# Memory managementCLEAR_CACHE_AFTER_STAGE = True # Clear GPU cache between stages5 unmodified linesSAVE_DEBUG_FILES = TrueDEBUG_FRAME_INTERVAL = 30 # Save every Nth frame for debuggingENABLE_MEMORY_TESTING = False # DISABLED: Memory testing causes predictor deletion# Audio settingsPRESERVE_ORIGINAL_AUDIO = True # Always try to preserve original audioAUDIO_TEMP_FORMAT = 'm4a' # Temporary audio format# ==============================================================================# CHAPTER 3: MEMORY MANAGEMENT UTILITIES198 unmodified linesreturn cls.PROFILES.get(quality, cls.PROFILES['medium'])# ==============================================================================# CHAPTER 5: ALPHA REFINEMENT UTILITIES# ==============================================================================class AlphaRefiner:"""Utilities for refining alpha mattes for better compositing."""@staticmethoddef refine_alpha_matte(alpha: np.ndarray, config: ProcessingConfig) -> np.ndarray:"""Refine alpha matte for cleaner compositing.Args:alpha: Input alpha matteconfig: Processing configurationReturns:Refined alpha matte"""# Ensure single channelif len(alpha.shape) == 3:alpha = cv2.cvtColor(alpha, cv2.COLOR_BGR2GRAY)# Normalize to 0-1 range if neededif alpha.dtype == np.uint8:alpha = alpha.astype(np.float32) / 255.0# Temporal smoothing to reduce flickeringif config.ALPHA_SMOOTHING > 0:kernel_size = config.ALPHA_SMOOTHING# Ensure odd kernel sizeif kernel_size % 2 == 0:kernel_size += 1alpha = cv2.medianBlur((alpha * 255).astype(np.uint8), kernel_size).astype(np.float32) / 255.0# Edge feathering for softer transitionsif config.ALPHA_EDGE_BLUR > 0:kernel_size = config.ALPHA_EDGE_BLUR * 2 + 1alpha = cv2.GaussianBlur(alpha, (kernel_size, kernel_size), 0)# Apply contrast adjustment for sharper boundariesif config.ALPHA_CONTRAST != 1.0:alpha = np.power(alpha, config.ALPHA_CONTRAST)# Ensure valid rangealpha = np.clip(alpha, 0, 1)return alpha@staticmethoddef defringe_edges(composite: np.ndarray, alpha: np.ndarray, radius: int = 1) -> np.ndarray:"""Remove color fringing at alpha edges.Args:composite: Composited imagealpha: Alpha matte used for compositingradius: Radius for defringing operationReturns:Defringed composite"""# Ensure alpha is single channelif len(alpha.shape) == 3:alpha = cv2.cvtColor(alpha, cv2.COLOR_BGR2GRAY)# Normalize alpha if neededif alpha.dtype == np.uint8:alpha = alpha.astype(np.float32) / 255.0# Create edge mask using morphological operationskernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (radius*2+1, radius*2+1))dilated = cv2.dilate(alpha, kernel)eroded = cv2.erode(alpha, kernel)edge_mask = dilated - eroded# Apply slight blur to edges onlyblurred = cv2.GaussianBlur(composite, (3, 3), 0)# Blend based on edge maskedge_mask_3d = np.stack([edge_mask] * 3, axis=2)result = composite * (1 - edge_mask_3d) + blurred * edge_mask_3dreturn result.astype(np.uint8)# ==============================================================================# CHAPTER 6: ENHANCED CHUNKED VIDEO PROCESSOR# ==============================================================================class ChunkedVideoProcessor:"""Handles splitting and reassembling videos for chunked processing with audio support."""def __init__(self, temp_dir: str, config: ProcessingConfig):self.temp_dir = temp_dir14 unmodified linesreturn Falsedef split_video_into_chunks(self, video_path: str) -> List[str]:"""Split video into chunks for processing, preserving audio."""try:with VideoFileClip(video_path) as clip:duration = clip.duration7 unmodified lines# Calculate chunk end timeend_time = min(current_time + chunk_duration, duration)# Check if remaining duration after this chunk is too smallremaining_after = duration - end_timeif remaining_after > 0 and remaining_after < self.config.MIN_FINAL_CHUNK_DURATION:# Include the remaining portion in this chunkend_time = durationlogger.info(f"Including final {remaining_after:.1f}s in chunk {chunk_index}")# Create chunk with audiochunk_clip = clip.subclip(current_time, end_time)chunk_path = os.path.join(self.chunks_dir, f"chunk_{chunk_index:03d}.mp4")# Write chunk with audio preservationchunk_clip.write_videofile(chunk_path,codec=self.config.VIDEO_CODEC,audio_codec=self.config.AUDIO_CODEC if chunk_clip.audio else None,audio_bitrate=self.config.AUDIO_BITRATE if chunk_clip.audio else None,temp_audiofile=os.path.join(self.temp_dir, f"temp_audio_chunk_{chunk_index}.{self.config.AUDIO_TEMP_FORMAT}"),remove_temp=True,verbose=False,logger=None)chunk_clip.close()chunk_paths.append(chunk_path)logger.info(f"Created chunk {chunk_index}: {current_time:.1f}s - {end_time:.1f}s (duration: {end_time - current_time:.1f}s)")# Move to next chunk with slight overlap for smooth transitionsif end_time < duration: # Not the last chunkoverlap_seconds = self.config.CHUNK_OVERLAP_FRAMES / clip.fpscurrent_time = end_time - overlap_secondselse:current_time = duration # We're donechunk_index += 1logger.info(f"Split video into {len(chunk_paths)} chunks")3 unmodified lineslogger.error(f"Video chunking failed: {e}")raisedef reassemble_chunks(self, processed_chunk_paths: List[str], output_path: str,original_audio_path: Optional[str] = None) -> str:"""Reassemble processed chunks into final video with original audio."""try:if len(processed_chunk_paths) == 1:# Single chunk, just copy or add audioif original_audio_path and os.path.exists(original_audio_path):# Add audio to single chunkwith VideoFileClip(processed_chunk_paths[0]) as video:audio = AudioFileClip(original_audio_path)final = video.set_audio(audio)final.write_videofile(output_path,codec=self.config.VIDEO_CODEC,audio_codec=self.config.AUDIO_CODEC,audio_bitrate=self.config.AUDIO_BITRATE,temp_audiofile=os.path.join(self.temp_dir, "temp_single_audio.m4a"),remove_temp=True,verbose=False,logger=None)final.close()else:shutil.copy2(processed_chunk_paths[0], output_path)logger.info("Single chunk processed")return output_path# Load all chunks6 unmodified lineslogger.info(f"Concatenating {len(chunk_clips)} chunks...")final_clip = concatenate_videoclips(chunk_clips, method="compose")# Add original audio if providedif original_audio_path and os.path.exists(original_audio_path):logger.info("Adding original audio track...")audio_clip = AudioFileClip(original_audio_path)# Ensure audio matches video durationif audio_clip.duration > final_clip.duration:audio_clip = audio_clip.subclip(0, final_clip.duration)final_clip = final_clip.set_audio(audio_clip)# Write final video with audiofinal_clip.write_videofile(output_path,codec=self.config.VIDEO_CODEC,audio_codec=self.config.AUDIO_CODEC if final_clip.audio else None,audio_bitrate=self.config.AUDIO_BITRATE if final_clip.audio else None,temp_audiofile=os.path.join(self.temp_dir, "temp_final_audio.m4a"),remove_temp=True,verbose=False,logger=None)11 unmodified linesraise# ==============================================================================# CHAPTER 7: TWOSTAGEPROCESSOR CLASS DEFINITION# ==============================================================================class TwoStageProcessor:"""Enhanced two-stage alpha channel processor with video-to-video pipeline.This processor avoids green screen entirely by using alpha channels:1. SAM2 creates reference mask from first few frames2. MatAnyone processes entire video using reference mask β pha.mp4 (alpha matte)3. Direct alpha compositing with background β final.mp4Features:- No chroma key or green screen needed- Audio preservation throughout pipeline- Full video duration processing- Alpha matte refinement for cleaner edges- Chunked processing for long videos"""def __init__(self, sam2_handler, matanyone_handler, temp_dir: Optional[str] = None):4 unmodified linesself.config = ProcessingConfig()self.memory_manager = MemoryManager(self.config)self.chunked_processor = ChunkedVideoProcessor(self.temp_dir, self.config)self.alpha_refiner = AlphaRefiner()# Ensure temp directory existsos.makedirs(self.temp_dir, exist_ok=True)11 unmodified linescallback: Optional[callable] = None,**kwargs) -> Tuple[str, str]:"""Main processing pipeline - video to video with alpha compositing and audio.Returns:Tuple[str, str]: (final_output_path, status_message)"""try:logger.info(f"π¬ Enhanced Two-Stage Alpha Pipeline: {video_path}")logger.info(f"π― Background: {background_path}")logger.info(f"π Temp: {self.temp_dir}")logger.info(f"π§ Initial {self.memory_manager.get_gpu_memory_info()}")# Extract and save original audio firstoriginal_audio_path = Noneif self.config.PRESERVE_ORIGINAL_AUDIO:original_audio_path = self._extract_audio(video_path)# Determine if chunking is neededneeds_chunking = self.chunked_processor.should_chunk_video(video_path)if needs_chunking:logger.info("Video exceeds chunk duration, using chunked processing...")result = self._process_chunked_video(video_path, background_path, output_path,quality, original_audio_path, callback)else:logger.info("Video within chunk duration, using single-pass processing...")result = self._process_single_video(video_path, background_path, output_path,quality, trim_seconds, original_audio_path, callback)# Final memory reportlogger.info(self.memory_manager.get_memory_report())6 unmodified lineslogger.error(f"Traceback: {traceback.format_exc()}")return None, error_msgdef _extract_audio(self, video_path: str) -> Optional[str]:"""Extract audio from original video for later reattachment."""try:audio_path = os.path.join(self.temp_dir, f"original_audio.{self.config.AUDIO_TEMP_FORMAT}")with VideoFileClip(video_path) as clip:if clip.audio is not None:clip.audio.write_audiofile(audio_path,codec=self.config.AUDIO_CODEC,bitrate=self.config.AUDIO_BITRATE,verbose=False,logger=None)logger.info(f"β Extracted audio: {audio_path}")return audio_pathelse:logger.warning("Video has no audio track")return Noneexcept Exception as e:logger.warning(f"Could not extract audio: {e}")return Nonedef _process_chunked_video(self,video_path: str,background_path: str,output_path: str,quality: str,original_audio_path: Optional[str],callback: Optional[callable] = None) -> Tuple[str, str]:"""Process long video using chunked approach."""try:15 unmodified lineslogger.info(f"Processing chunk {i+1}/{total_chunks}: {chunk_path}")logger.info(f"Pre-chunk memory: {self.memory_manager.get_gpu_memory_info()}")# Process this chunk at full resolution without audio (add at the end)chunk_output = os.path.join(self.temp_dir, f"processed_chunk_{i:03d}.mp4")result_path, status = self._process_single_video(chunk_path, background_path, chunk_output, quality,trim_seconds=None, original_audio_path=None, callback=None)if result_path and os.path.exists(result_path):13 unmodified lineslogger.info(f"Post-chunk memory: {self.memory_manager.get_gpu_memory_info()}")if callback:callback("Reassembling chunks with audio...", 85)# Reassemble chunks with original audiofinal_path = self.chunked_processor.reassemble_chunks(processed_chunks, output_path, original_audio_path)if callback:callback("Chunked processing completed!", 100)logger.info(f"β Chunked processing completed: {final_path}")return final_path, f"Success - Processed {total_chunks} chunks with audio"except Exception as e:logger.error(f"Chunked processing failed: {e}")5 unmodified linesoutput_path: str,quality: str,trim_seconds: Optional[int] = None,original_audio_path: Optional[str] = None,callback: Optional[callable] = None) -> Tuple[str, str]:"""Process a single video (or chunk) through the pipeline."""try:19 unmodified linesself.memory_manager.cleanup_model(self.matanyone_handler, "MatAnyone", deep_cleanup=False)self.memory_manager.cleanup_stage("MatAnyone", force=True)# Stage 3: Enhanced alpha compositing with audioif callback:callback("Alpha compositing with background...", 70)logger.info("STAGE 3: Enhanced alpha compositing with background...")final_path = self._stage3_enhanced_alpha_composite(video_path, alpha_video_path, background_path,output_path, quality, original_audio_path)# Final memory cleanupself.memory_manager.cleanup_stage("Final")32 unmodified lineslogger.warning(f"Failed to cleanup: {e}")# ==============================================================================# CHAPTER 8: STAGE 1 - REFERENCE MASK CREATION (SAM2)# ==============================================================================def _stage1_create_reference_mask(self, video_path: str) -> str:118 unmodified linesreturn result# ==============================================================================# CHAPTER 9: STAGE 2 - MATANYONE PROCESSING# ==============================================================================def _stage2_matanyone_processing(self, video_path: str, reference_mask_path: str, trim_seconds: Optional[int]) -> str:78 unmodified linesraisedef _trim_video(self, input_path: str, output_path: str, seconds: int):"""Trim video to specified duration with audio preservation."""try:with VideoFileClip(input_path) as clip:trimmed = clip.subclip(0, min(seconds, clip.duration))trimmed.write_videofile(output_path,codec=self.config.VIDEO_CODEC,audio_codec=self.config.AUDIO_CODEC if clip.audio else None,audio_bitrate=self.config.AUDIO_BITRATE if clip.audio else None,verbose=False,logger=None)3 unmodified linesraise# ==============================================================================# CHAPTER 10: STAGE 3 - ENHANCED ALPHA COMPOSITING WITH AUDIO# ==============================================================================def _stage3_enhanced_alpha_composite(self, original_video_path: str,alpha_video_path: str,background_path: str,output_path: str,quality: str,audio_path: Optional[str]) -> str:"""Stage 3: Enhanced alpha compositing with refinement and audio support.Uses MoviePy for better audio handling and applies alpha refinementfor cleaner edges and better compositing quality."""try:# Load videos using MoviePy for better audio supportlogger.info("Loading video clips...")original_clip = VideoFileClip(original_video_path)alpha_clip = VideoFileClip(alpha_video_path)# Load backgroundif background_path.lower().endswith(('.mp4', '.avi', '.mov', '.mkv')):logger.info("Loading video background...")background_clip = VideoFileClip(background_path)background_clip = background_clip.resize(original_clip.size)# Loop background if it's shorter than the foregroundif background_clip.duration < original_clip.duration:logger.info("Looping background video to match duration...")background_clip = background_clip.loop(duration=original_clip.duration)else:logger.info("Loading image background...")background_clip = ImageClip(background_path).set_duration(original_clip.duration)background_clip = background_clip.resize(original_clip.size)# Get video properties for loggingfps = original_clip.fpswidth, height = original_clip.sizeduration = original_clip.durationtotal_frames = int(fps * duration)logger.info(f"Video properties: {width}x{height} @ {fps:.1f} FPS")logger.info(f"Duration: {duration:.1f}s ({total_frames} frames)")# Create enhanced composite function with alpha refinementdef make_frame_enhanced(t):"""Create composite frame at time t with alpha refinement."""try:# Get frames at time torig_frame = original_clip.get_frame(t)alpha_frame = alpha_clip.get_frame(t)bg_frame = background_clip.get_frame(t)# Convert alpha to grayscale if neededif len(alpha_frame.shape) == 3:alpha_mask = cv2.cvtColor(alpha_frame.astype(np.uint8), cv2.COLOR_RGB2GRAY)else:alpha_mask = alpha_frame# Apply alpha refinement for cleaner edgesalpha_refined = self.alpha_refiner.refine_alpha_matte(alpha_mask, self.config)# Handle dimension mismatchif alpha_refined.shape[:2] != orig_frame.shape[:2]:alpha_refined = cv2.resize(alpha_refined,(orig_frame.shape[1], orig_frame.shape[0]),interpolation=cv2.INTER_LINEAR)# Create 3-channel alpha for compositingalpha_3d = np.stack([alpha_refined] * 3, axis=2)# Direct alpha compositingcomposite = alpha_3d * orig_frame + (1 - alpha_3d) * bg_frame# Optional: remove color fringing at edgesif self.config.ENABLE_DEFRINGING:composite = self.alpha_refiner.defringe_edges(composite.astype(np.uint8),alpha_refined,radius=self.config.DEFRINGE_RADIUS)return np.clip(composite, 0, 255).astype(np.uint8)except Exception as e:logger.error(f"Frame processing error at t={t}: {e}")# Return original frame as fallbackreturn original_clip.get_frame(t)# Create composite video with enhanced processinglogger.info("Creating composite video with alpha refinement...")composite_clip = VideoClip(make_frame_enhanced, duration=original_clip.duration)composite_clip = composite_clip.set_fps(original_clip.fps)# Add audio (prioritize provided audio path, then original audio)if audio_path and os.path.exists(audio_path):logger.info(f"Adding audio from: {audio_path}")audio_clip = AudioFileClip(audio_path)# Ensure audio matches video durationif audio_clip.duration > composite_clip.duration:audio_clip = audio_clip.subclip(0, composite_clip.duration)composite_clip = composite_clip.set_audio(audio_clip)elif original_clip.audio is not None:logger.info("Using original video's audio...")composite_clip = composite_clip.set_audio(original_clip.audio)else:logger.warning("No audio available for final output")# Get quality profileprofile = QualityManager.get_profile(quality)# Write final video with audiologger.info(f"Writing final video with quality profile: {quality}")composite_clip.write_videofile(output_path,codec=self.config.VIDEO_CODEC,bitrate=profile['bitrate'],audio_codec=self.config.AUDIO_CODEC if composite_clip.audio else None,audio_bitrate=self.config.AUDIO_BITRATE if composite_clip.audio else None,temp_audiofile=os.path.join(self.temp_dir, f"temp_composite_audio.{self.config.AUDIO_TEMP_FORMAT}"),remove_temp=True,verbose=False,logger=None)# Cleanup clipslogger.info("Cleaning up video clips...")original_clip.close()alpha_clip.close()background_clip.close()composite_clip.close()# Verify outputif not os.path.exists(output_path):raise RuntimeError("Output file was not created")# Verify the output has proper durationwith VideoFileClip(output_path) as verify_clip:output_duration = verify_clip.durationif abs(output_duration - duration) > 1.0: # Allow 1 second tolerancelogger.warning(f"Duration mismatch: expected {duration:.1f}s, got {output_duration:.1f}s")file_size = os.path.getsize(output_path) / (1024 * 1024) # MBlogger.info(f"β Enhanced compositing completed: {output_path}")logger.info(f" File size: {file_size:.1f} MB")logger.info(f" Duration: {output_duration:.1f}s")logger.info(f" Audio: {'Yes' if composite_clip.audio else 'No'}")return output_pathexcept Exception as e:logger.error(f"Stage 3 enhanced compositing failed: {e}")raise# ==============================================================================# CHAPTER 11: DEBUG AND UTILITY FUNCTIONS# ==============================================================================def _debug_video_info(self, video_path: str, label: str = "Video"):26 unmodified lines'temp_size_mb': 0,'debug_files': 0,'memory_info': self.memory_manager.get_gpu_memory_info(),'memory_report': self.memory_manager.get_memory_report(),'config': {'audio_enabled': self.config.PRESERVE_ORIGINAL_AUDIO,'alpha_refinement': self.config.ALPHA_SMOOTHING > 0,'defringing': self.config.ENABLE_DEFRINGING,'chunk_duration': self.config.MAX_CHUNK_DURATION}}try:17 unmodified linesreturn stats# ==============================================================================# CHAPTER 12: EXPORT INTERFACE AND COMPATIBILITY# ==============================================================================def create_two_stage_processor(sam2_handler, matanyone_handler, **kwargs):7 unmodified lines# Main execution exampleif __name__ == "__main__":# Example usage - replace with your actual handlerslogger.info("Enhanced TwoStageProcessor (Alpha Channel Version) loaded successfully")logger.info("Features:")logger.info(" β No green screen or chroma key needed")logger.info(" β Audio preservation throughout pipeline")logger.info(" β Full video duration processing")logger.info(" β Alpha matte refinement for cleaner edges")logger.info(" β Chunked processing for long videos")logger.info("")logger.info("Use create_two_stage_processor(sam2_handler, matanyone_handler) to initialize")# Print configurationconfig = ProcessingConfig()logger.info(f"Pipeline: SAM2 β MatAnyone β Enhanced Alpha Compositing")logger.info(f"Configuration:")logger.info(f" Reference frames: {config.REFERENCE_FRAMES}")logger.info(f" Chunk duration: {config.MAX_CHUNK_DURATION}s with {config.CHUNK_OVERLAP_FRAMES} frame overlap")logger.info(f" Audio: {config.AUDIO_CODEC} @ {config.AUDIO_BITRATE}")logger.info(f" Alpha refinement: Smoothing={config.ALPHA_SMOOTHING}, Edge blur={config.ALPHA_EDGE_BLUR}")logger.info(f" Memory management: Cache clearing={'ON' if config.CLEAR_CACHE_AFTER_STAGE else 'OFF'}")
processing/two_stage/two_stage_processor.py+390-164