Spaces:
Sleeping
Sleeping
Download video_processor.py from Razonir/tiktok-editor: direct link, hf CLI and curl.
- Browser
- Download file 6.22 kB
-
https://huggingface.co/spaces/Razonir/tiktok-editor/resolve/main/video_processor.py
- Command line
-
hf download hf://spaces/Razonir/tiktok-editor/video_processor.py
-
curl -L -o video_processor.py https://huggingface.co/spaces/Razonir/tiktok-editor/resolve/main/video_processor.py
6.22 kB
| import subprocess | |
| import os | |
| import json | |
| import shutil | |
| # --------------------------------------------------------------------------- | |
| # Resolve FFmpeg / ffprobe binaries. | |
| # winget installs them to a versioned path that may not be on PATH yet until | |
| # the user restarts their shell. We search common locations as a fallback. | |
| # --------------------------------------------------------------------------- | |
| _WINGET_BASE = os.path.join( | |
| os.environ.get('LOCALAPPDATA', ''), | |
| r'Microsoft\WinGet\Packages' | |
| ) | |
| def _find_bin(name: str) -> str: | |
| """Return the full path to an FFmpeg binary, or just the bare name.""" | |
| # 1. Already on PATH? | |
| found = shutil.which(name) | |
| if found: | |
| return found | |
| # 2. Search winget packages directory | |
| for root, dirs, files in os.walk(_WINGET_BASE): | |
| if name + '.exe' in files: | |
| return os.path.join(root, name + '.exe') | |
| # 3. Fallback - hope it's on PATH at call time | |
| return name | |
| FFMPEG = _find_bin('ffmpeg') | |
| FFPROBE = _find_bin('ffprobe') | |
| def get_video_info(video_path): | |
| """Get video dimensions using ffprobe.""" | |
| cmd = [ | |
| FFPROBE, '-v', 'quiet', '-print_format', 'json', | |
| '-show_streams', video_path | |
| ] | |
| result = subprocess.run(cmd, capture_output=True, text=True) | |
| data = json.loads(result.stdout) | |
| for stream in data['streams']: | |
| if stream['codec_type'] == 'video': | |
| return stream['width'], stream['height'] | |
| return None, None | |
| def process_stream_to_tiktok(input_path, output_path, config=None): | |
| """ | |
| Convert a gaming stream video to TikTok vertical format. | |
| Layout (1080x1920): | |
| - Top (0-640px): Player 1 camera (bottom-left overlay), scaled to 1080x640 | |
| - Middle (640-1280px): Full game footage, scaled to 1080x640 | |
| - Bottom (1280-1920px): Player 2 camera (bottom-right overlay), scaled to 1080x640 | |
| Args: | |
| input_path: Path to input video file | |
| output_path: Path to save output video | |
| config: Optional dict with cam positions (fractions of video size) | |
| """ | |
| if config is None: | |
| config = {} | |
| # Get video dimensions | |
| vid_w, vid_h = get_video_info(input_path) | |
| if not vid_w: | |
| raise ValueError("Could not read video dimensions") | |
| # Camera crop regions (as fractions of video size) - precise values from image | |
| cam1_x_frac = config.get('cam1_x', 0.008) | |
| cam1_y_frac = config.get('cam1_y', 0.731) | |
| cam1_w_frac = config.get('cam1_w', 0.216) | |
| cam1_h_frac = config.get('cam1_h', 0.222) | |
| cam2_x_frac = config.get('cam2_x', 0.776) | |
| cam2_y_frac = config.get('cam2_y', 0.731) | |
| cam2_w_frac = config.get('cam2_w', 0.216) | |
| cam2_h_frac = config.get('cam2_h', 0.222) | |
| p1_name = config.get('cam1_name', 'Player 1').strip() | |
| p2_name = config.get('cam2_name', 'Player 2').strip() | |
| # Convert fractions to pixels (ensure even numbers for codec compatibility) | |
| def to_even(v): return int(v) & ~1 | |
| c1_x = to_even(cam1_x_frac * vid_w) | |
| c1_y = to_even(cam1_y_frac * vid_h) | |
| c1_w = to_even(cam1_w_frac * vid_w) | |
| c1_h = to_even(cam1_h_frac * vid_h) | |
| c2_x = to_even(cam2_x_frac * vid_w) | |
| c2_y = to_even(cam2_y_frac * vid_h) | |
| c2_w = to_even(cam2_w_frac * vid_w) | |
| c2_h = to_even(cam2_h_frac * vid_h) | |
| # Output dimensions: TikTok 9:16 | |
| out_w = 1080 | |
| panel_h = 640 # Each of 3 panels = 640px, total = 1920 | |
| out_h = panel_h * 3 # 1920 | |
| n1_x = config.get('name1_x', 0.5) | |
| n1_y = config.get('name1_y', 0.9) | |
| n2_x = config.get('name2_x', 0.5) | |
| n2_y = config.get('name2_y', 0.1) | |
| import sys | |
| if sys.platform == 'win32': | |
| font_path = r"C\:/Windows/Fonts/arialbd.ttf" | |
| else: | |
| font_path = "/usr/share/fonts/truetype/liberation/LiberationSans-Bold.ttf" | |
| def get_drawtext(name, nx, ny): | |
| if not name: return "" | |
| safe_name = name.replace("'", "\\'").replace(":", "\\:") | |
| # Calculate dynamic positions (w-text_w is max X, h-text_h is max Y) | |
| # Using format mapping so FFmpeg evaluates it properly. | |
| x_expr = f"{nx}*(w-text_w)" | |
| y_expr = f"{ny}*(h-text_h)" | |
| return f",drawtext=fontfile='{font_path}':text='{safe_name}':fontcolor=white:fontsize=48:x={x_expr}:y={y_expr}:box=1:boxcolor=black@0.6:boxborderw=10" | |
| p1_text = get_drawtext(p1_name, n1_x, n1_y) | |
| p2_text = get_drawtext(p2_name, n2_x, n2_y) | |
| mid_stream = "mid" | |
| mid_filter = f"[game]scale={out_w}:{panel_h}:force_original_aspect_ratio=increase,crop={out_w}:{panel_h}[mid]" | |
| # FFmpeg filter_complex: | |
| # [0:v] split into 3 uses | |
| # cam1 → crop → scale → top panel + drawtext | |
| # game → scale (with padding to fill width) → middle panel (with dynamic subtitles if any) | |
| # cam2 → crop → scale → bottom panel + drawtext | |
| # vstack all three | |
| filter_complex = ( | |
| f"[0:v]split=3[game][raw1][raw2];" | |
| # Player 1 camera (top panel) | |
| f"[raw1]crop={c1_w}:{c1_h}:{c1_x}:{c1_y}," | |
| f"scale={out_w}:{panel_h}:force_original_aspect_ratio=increase," | |
| f"crop={out_w}:{panel_h}{p1_text}[cam1];" | |
| # Game footage (middle panel) | |
| f"{mid_filter};" | |
| # Player 2 camera (bottom panel) | |
| f"[raw2]crop={c2_w}:{c2_h}:{c2_x}:{c2_y}," | |
| f"scale={out_w}:{panel_h}:force_original_aspect_ratio=increase," | |
| f"crop={out_w}:{panel_h}{p2_text}[cam2];" | |
| # Stack vertically | |
| f"[cam1][{mid_stream}][cam2]vstack=inputs=3[out]" | |
| ) | |
| cmd = [ | |
| FFMPEG, '-y', | |
| '-i', input_path, | |
| '-filter_complex', filter_complex, | |
| '-map', '[out]', | |
| '-map', '0:a?', # Include audio if present | |
| '-c:v', 'libx264', | |
| '-preset', 'fast', | |
| '-crf', '23', | |
| '-c:a', 'aac', | |
| '-b:a', '128k', | |
| '-movflags', '+faststart', # Optimize for web streaming | |
| '-t', str(config.get('max_duration', 30)), # Max 30 seconds | |
| output_path | |
| ] | |
| process = subprocess.Popen( | |
| cmd, | |
| stdout=subprocess.PIPE, | |
| stderr=subprocess.PIPE, | |
| text=True | |
| ) | |
| stdout, stderr = process.communicate() | |
| if process.returncode != 0: | |
| raise RuntimeError(f"FFmpeg error:\n{stderr}") | |
| return output_path | |