Spaces:
Runtime error
Runtime error
Adnan commited on
Create video_assembler.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306"""TimeLapseForge — Video Assembler ModuleConverts frame sequences into complete videos with transitions,text overlays, and background audio."""
import osimport tempfileimport numpy as npfrom PIL import Image, ImageDraw, ImageFontfrom typing import List, Dict, Optional, Tupleimport imageio
class VideoAssembler: """Assembles frames into a polished timelapse video."""
def __init__(self): self.font = self._load_font()
@staticmethod def _load_font(size: int = 32) -> ImageFont.FreeTypeFont: """Load a font, with fallbacks.""" font_paths = [ "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", "/usr/share/fonts/truetype/liberation/LiberationSans-Bold.ttf", "/usr/share/fonts/TTF/DejaVuSans-Bold.ttf", "C:/Windows/Fonts/arial.ttf", ] for path in font_paths: try: return ImageFont.truetype(path, size) except (IOError, OSError): continue return ImageFont.load_default()
def add_text_overlay( self, image: Image.Image, text: str, position: str = "bottom", font_size: int = 32, text_color: Tuple[int, ...] = (255, 255, 255), bg_color: Tuple[int, ...] = (0, 0, 0, 160), margin: int = 10, ) -> Image.Image: """Add text overlay with semi-transparent background.""" img = image.copy().convert("RGBA") overlay = Image.new("RGBA", img.size, (0, 0, 0, 0)) draw = ImageDraw.Draw(overlay)
font = self._load_font(font_size)
# Calculate text size bbox = draw.textbbox((0, 0), text, font=font) text_w = bbox[2] - bbox[0] text_h = bbox[3] - bbox[1]
# Calculate position img_w, img_h = img.size if position == "top": x = (img_w - text_w) // 2 y = margin elif position == "bottom": x = (img_w - text_w) // 2 y = img_h - text_h - margin * 3 elif position == "top-left": x = margin y = margin elif position == "top-right": x = img_w - text_w - margin y = margin else: # center x = (img_w - text_w) // 2 y = (img_h - text_h) // 2
# Draw background rectangle padding = 8 draw.rectangle( [x - padding, y - padding, x + text_w + padding, y + text_h + padding], fill=bg_color, )
# Draw text draw.text((x, y), text, fill=text_color, font=font)
result = Image.alpha_composite(img, overlay) return result.convert("RGB")
def add_progress_bar( self, image: Image.Image, progress: float, bar_height: int = 6, bar_color: Tuple[int, ...] = (0, 200, 100), bg_color: Tuple[int, ...] = (60, 60, 60), ) -> Image.Image: """Add a progress bar at the bottom of the frame.""" img = image.copy() draw = ImageDraw.Draw(img) w, h = img.size
# Background bar draw.rectangle([0, h - bar_height, w, h], fill=bg_color) # Progress bar bar_width = int(w * progress) draw.rectangle([0, h - bar_height, bar_width, h], fill=bar_color)
return img
def prepare_frames( self, images: List[Image.Image], fps: int = 24, hold_seconds: float = 2.0, add_labels: bool = True, labels: Optional[List[str]] = None, add_progress: bool = True, add_bookend_labels: bool = True, ) -> List[np.ndarray]: """ Prepare frames for video export. Each panel image is repeated for hold_seconds duration. """ frames_per_panel = max(1, int(fps * hold_seconds)) all_frames = []
for i, img in enumerate(images): frame = img.copy()
# Add text label if add_labels and labels and i < len(labels) and labels[i]: frame = self.add_text_overlay(frame, labels[i], position="top-left", font_size=24)
# Add BEFORE / AFTER labels if add_bookend_labels: if i == 0: frame = self.add_text_overlay(frame, "BEFORE", position="bottom", font_size=40) elif i == len(images) - 1: frame = self.add_text_overlay(frame, "AFTER", position="bottom", font_size=40)
# Add progress bar if add_progress: progress = (i + 1) / len(images) frame = self.add_progress_bar(frame, progress)
# Repeat frame for hold duration frame_array = np.array(frame) for _ in range(frames_per_panel): all_frames.append(frame_array)
return all_frames
def create_video( self, images: List[Image.Image], output_path: Optional[str] = None, fps: int = 24, hold_seconds: float = 2.0, add_labels: bool = True, labels: Optional[List[str]] = None, add_progress: bool = True, add_bookend_labels: bool = True, fade_in_frames: int = 15, fade_out_frames: int = 15, ) -> str: """ Create a complete video from panel images. Returns: path to the output video file. """ if output_path is None: output_path = os.path.join(tempfile.gettempdir(), "timelapse_output.mp4")
frames = self.prepare_frames( images, fps, hold_seconds, add_labels, labels, add_progress, add_bookend_labels )
if not frames: raise ValueError("No frames to assemble!")
# Apply fade in for i in range(min(fade_in_frames, len(frames))): alpha = i / fade_in_frames frames[i] = (frames[i].astype(np.float32) * alpha).astype(np.uint8)
# Apply fade out for i in range(min(fade_out_frames, len(frames))): idx = len(frames) - 1 - i alpha = i / fade_out_frames frames[idx] = (frames[idx].astype(np.float32) * alpha).astype(np.uint8)
# Write video using imageio writer = imageio.get_writer( output_path, fps=fps, codec="libx264", quality=8, pixelformat="yuv420p", output_params=["-preset", "medium"], )
for frame in frames: writer.append_data(frame)
writer.close() return output_path
def add_audio_to_video( self, video_path: str, audio_path: str, output_path: Optional[str] = None, ) -> str: """Add background audio/music to the video using moviepy.""" if output_path is None: output_path = video_path.replace(".mp4", "_with_audio.mp4")
try: from moviepy.editor import VideoFileClip, AudioFileClip
video = VideoFileClip(video_path) audio = AudioFileClip(audio_path)
# Loop or trim audio to match video duration if audio.duration < video.duration: # Loop audio from moviepy.editor import concatenate_audioclips loops_needed = int(video.duration / audio.duration) + 1 audio = concatenate_audioclips([audio] * loops_needed)
audio = audio.subclip(0, video.duration)
# Fade audio in and out audio = audio.audio_fadein(2).audio_fadeout(2) final = video.set_audio(audio) final.write_videofile(output_path, codec="libx264", audio_codec="aac", logger=None)
video.close() audio.close() return output_path
except ImportError: print("moviepy not available for audio mixing. Returning video without audio.") return video_path except Exception as e: print(f"Audio mixing failed: {e}. Returning video without audio.") return video_path
def create_comparison_image( self, first: Image.Image, last: Image.Image, orientation: str = "horizontal", gap: int = 4, ) -> Image.Image: """Create a side-by-side or top-bottom comparison image.""" w, h = first.size
if orientation == "horizontal": comp = Image.new("RGB", (w * 2 + gap, h), (30, 30, 30)) comp.paste(first, (0, 0)) comp.paste(last, (w + gap, 0))
# Add labels comp = self.add_text_overlay( comp, "BEFORE", position="top-left", font_size=28 ) draw = ImageDraw.Draw(comp) font = self._load_font(28) draw.text((w + gap + 10, 10), "AFTER", fill=(255, 255, 255), font=font) else: comp = Image.new("RGB", (w, h * 2 + gap), (30, 30, 30)) comp.paste(first, (0, 0)) comp.paste(last, (0, h + gap))
return comp
def create_gif( self, images: List[Image.Image], output_path: Optional[str] = None, duration_per_frame: int = 500, loop: int = 0, ) -> str: """Create an animated GIF from the panels.""" if output_path is None: output_path = os.path.join(tempfile.gettempdir(), "timelapse.gif")
# Resize for GIF (smaller file size) max_size = (480, 480) resized = [] for img in images: r = img.copy() r.thumbnail(max_size, Image.LANCZOS) resized.append(r)
resized[0].save( output_path, save_all=True, append_images=resized[1:], duration=duration_per_frame, loop=loop, optimize=True, ) return output_pathvideo_assembler.pyAdded+306