clipwright/main.py
2025-12-21 01:59:15 +01:00

878 lines
33 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import time
import cv2
import scenedetect
import subprocess
import argparse
import re
from scenedetect import VideoManager, SceneManager
from scenedetect.detectors import ContentDetector
from ultralytics import YOLO
import torch
import os
import numpy as np
from tqdm import tqdm
import yt_dlp
import mediapipe as mp
# import whisper (replaced by faster_whisper inside function)
from google import genai
from dotenv import load_dotenv
import json
import warnings
warnings.filterwarnings("ignore", category=UserWarning, module='google.protobuf')
# Load environment variables
load_dotenv()
# --- Constants ---
ASPECT_RATIO = 9 / 16
GEMINI_PROMPT_TEMPLATE = """
You are a senior short-form video editor. Read the ENTIRE transcript and word-level timestamps to choose the 3–15 MOST VIRAL moments for TikTok/IG Reels/YouTube Shorts. Each clip must be between 15 and 60 seconds long.
⚠️ FFMPEG TIME CONTRACT — STRICT REQUIREMENTS:
- Return timestamps in ABSOLUTE SECONDS from the start of the video (usable in: ffmpeg -ss <start> -to <end> -i <input> ...).
- Only NUMBERS with decimal point, up to 3 decimals (examples: 0, 1.250, 17.350).
- Ensure 0 ≤ start < end ≤ VIDEO_DURATION_SECONDS.
- Each clip between 15 and 60 s (inclusive).
- Prefer starting 0.2–0.4 s BEFORE the hook and ending 0.2–0.4 s AFTER the payoff.
- Use silence moments for natural cuts; never cut in the middle of a word or phrase.
- STRICTLY FORBIDDEN to use time formats other than absolute seconds.
VIDEO_DURATION_SECONDS: {video_duration}
TRANSCRIPT_TEXT (raw):
{transcript_text}
WORDS_JSON (array of {{w, s, e}} where s/e are seconds):
{words_json}
STRICT EXCLUSIONS:
- No generic intros/outros or purely sponsorship segments unless they contain the hook.
- No clips < 15 s or > 60 s.
OUTPUT — RETURN ONLY VALID JSON (no markdown, no comments). Order clips by predicted performance (best to worst). In the descriptions, ALWAYS include a CTA like "Follow me and comment X and I'll send you the workflow" (especially if discussing an n8n workflow):
{{
"shorts": [
{{
"start": <number in seconds, e.g., 12.340>,
"end": <number in seconds, e.g., 37.900>,
"video_description_for_tiktok": "<description for TikTok oriented to get views>",
"video_description_for_instagram": "<description for Instagram oriented to get views>",
"video_title_for_youtube_short": "<title for YouTube Short oriented to get views 100 chars max>"
}}
]
}}
"""
# Load the YOLO model once (Keep for backup or scene analysis if needed)
model = YOLO('yolov8n.pt')
# --- MediaPipe Setup ---
# Use Face Mesh for more accurate detection and mouth movement tracking
mp_face_mesh = mp.solutions.face_mesh
face_mesh = mp_face_mesh.FaceMesh(
max_num_faces=5,
refine_landmarks=True,
min_detection_confidence=0.5,
min_tracking_confidence=0.5
)
class SmoothedCameraman:
"""
Handles smooth camera movement to track a subject without jitter.
Includes deadzone and dynamic smoothing.
"""
def __init__(self, output_width, output_height, video_width, video_height, smoothing_factor=0.1):
self.output_width = output_width
self.output_height = output_height
self.video_width = video_width
self.video_height = video_height
self.smoothing_factor = smoothing_factor
self.current_center_x = video_width / 2
self.target_center_x = video_width / 2
# Deadzone: Ignore movements smaller than this (relative to video width)
self.deadzone = video_width * 0.03
# Calculate crop dimensions once
self.crop_height = video_height
self.crop_width = int(self.crop_height * ASPECT_RATIO)
if self.crop_width > video_width:
# Handle case where original video is already narrow/vertical
self.crop_width = video_width
self.crop_height = int(self.crop_width / ASPECT_RATIO)
def update_target(self, face_box):
"""
Updates the target center based on detected face/person.
face_box: [x, y, w, h]
"""
if face_box:
x, y, w, h = face_box
new_target = x + w / 2
# Deadzone logic: Only update if the target has moved significantly
# This prevents jitter when the person is stationary but detection wobbles
if abs(new_target - self.target_center_x) > self.deadzone:
self.target_center_x = new_target
def get_crop_box(self, force_snap=False):
"""
Returns the (x1, y1, x2, y2) for the current frame.
"""
if force_snap:
self.current_center_x = self.target_center_x
else:
# Dynamic Smoothing
diff = self.target_center_x - self.current_center_x
distance = abs(diff)
# Adaptive speed:
# - If very far (scene change or fast move), move FAST.
# - If close (minor adjustment), move SLOW to be smooth.
if distance > self.video_width * 0.15:
speed = 0.15 # Catch up moderately fast, but not instant (reduced from 0.3)
elif distance < self.video_width * 0.05:
speed = 0.05 # Very smooth for small adjustments
else:
speed = self.smoothing_factor
self.current_center_x += diff * speed
# Clamp center to keep crop within bounds
half_crop = self.crop_width / 2
# Ensure we don't go out of left/right bounds
if self.current_center_x - half_crop < 0:
self.current_center_x = half_crop
if self.current_center_x + half_crop > self.video_width:
self.current_center_x = self.video_width - half_crop
x1 = int(self.current_center_x - half_crop)
x2 = int(self.current_center_x + half_crop)
# Final safety check
x1 = max(0, x1)
x2 = min(self.video_width, x2)
# For height, we usually take the full height unless we want to zoom
# Current logic: full height
y1 = 0
y2 = self.video_height
return x1, y1, x2, y2
class SpeakerTracker:
"""
Tracks speakers over time to prevent rapid switching and handle temporary obstructions.
"""
def __init__(self, stabilization_frames=15, cooldown_frames=30):
self.active_speaker_id = None
self.speaker_scores = {} # {id: score}
self.last_seen = {} # {id: frame_number}
self.locked_counter = 0 # How long we've been locked on current speaker
# Hyperparameters
self.stabilization_threshold = stabilization_frames # Frames needed to confirm a new speaker
self.switch_cooldown = cooldown_frames # Minimum frames before switching again
self.last_switch_frame = -1000
# ID tracking
self.next_id = 0
self.known_faces = [] # [{'id': 0, 'center': x, 'last_frame': 123}]
def get_target(self, face_candidates, frame_number, width):
"""
Decides which face to focus on.
face_candidates: list of {'box': [x,y,w,h], 'score': float, 'is_speaking': bool}
"""
current_candidates = []
# 1. Match faces to known IDs (simple distance tracking)
for face in face_candidates:
x, y, w, h = face['box']
center_x = x + w / 2
best_match_id = -1
min_dist = width * 0.2 # Max movement distance
# Try to match with known faces seen recently
for kf in self.known_faces:
if frame_number - kf['last_frame'] > 60: # Forgot faces older than 2s
continue
dist = abs(center_x - kf['center'])
if dist < min_dist:
min_dist = dist
best_match_id = kf['id']
# If no match, assign new ID
if best_match_id == -1:
best_match_id = self.next_id
self.next_id += 1
# Update known face
# Remove old entry for this ID if exists
self.known_faces = [kf for kf in self.known_faces if kf['id'] != best_match_id]
self.known_faces.append({'id': best_match_id, 'center': center_x, 'last_frame': frame_number})
current_candidates.append({
'id': best_match_id,
'box': face['box'],
'score': face['score'],
'is_speaking': face['is_speaking']
})
# 2. Update Scores with decay
# Decay old scores
for pid in list(self.speaker_scores.keys()):
self.speaker_scores[pid] *= 0.9 # Fast decay
if self.speaker_scores[pid] < 0.1:
del self.speaker_scores[pid]
# Add new scores
for cand in current_candidates:
pid = cand['id']
# Boost score if speaking
score_boost = 20.0 if cand['is_speaking'] else 1.0
# Boost score if large (main subject)
# Normalize area (assuming 720p or 1080p, say max area ~ 1M pixels)
# Actually score is already area-based in previous function, so just use it
raw_score = cand['score'] / (width * width * 0.1) # Normalize roughly
self.speaker_scores[pid] = self.speaker_scores.get(pid, 0) + (raw_score * score_boost)
# 3. Determine Best Speaker
if not current_candidates:
return None # No one found
# Sort candidates by accumulated score
best_candidate = None
max_score = -1
for cand in current_candidates:
pid = cand['id']
total_score = self.speaker_scores.get(pid, 0)
# Hysteresis: Bonus for current active speaker
if pid == self.active_speaker_id:
total_score *= 2.0 # Hard stickiness
if total_score > max_score:
max_score = total_score
best_candidate = cand
# 4. Decide Switch
if best_candidate:
target_id = best_candidate['id']
# If it's the same person, just update
if target_id == self.active_speaker_id:
self.locked_counter += 1
return best_candidate['box']
# If it's a NEW person
# Check cooldown
if frame_number - self.last_switch_frame < self.switch_cooldown:
# Too soon to switch, stay with old one if possible
# Find old one in current candidates
old_cand = next((c for c in current_candidates if c['id'] == self.active_speaker_id), None)
if old_cand:
return old_cand['box']
# Check stabilization (do we really want to switch?)
# If the new score is overwhelmingly high (someone started shouting/talking clearly), switch faster
# But normally wait a bit?
# For now, let's just trust the accumulated score buffer + hysteresis
self.active_speaker_id = target_id
self.last_switch_frame = frame_number
self.locked_counter = 0
return best_candidate['box']
return None
def detect_face_candidates(frame):
"""
Returns list of all detected faces with their raw scores and speaking status.
"""
height, width, _ = frame.shape
rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
results = face_mesh.process(rgb_frame)
candidates = []
if not results.multi_face_landmarks:
return []
for face_landmarks in results.multi_face_landmarks:
# Bounding Box
x_min, y_min = width, height
x_max, y_max = 0, 0
# Optimization: Use only silhouette landmarks (every 10th or specific indices)
# Full mesh is 468 points.
for i in range(0, 468, 10):
lm = face_landmarks.landmark[i]
x, y = int(lm.x * width), int(lm.y * height)
if x < x_min: x_min = x
if x > x_max: x_max = x
if y < y_min: y_min = y
if y > y_max: y_max = y
w = x_max - x_min
h = y_max - y_min
# Mouth Openness
upper_lip = face_landmarks.landmark[13]
lower_lip = face_landmarks.landmark[14]
mouth_dist = abs(upper_lip.y - lower_lip.y) * height
mouth_ratio = mouth_dist / h if h > 0 else 0
# Heuristic: Threshold for speaking
is_speaking = mouth_ratio > 0.05 # Increased threshold to reduce false positives
candidates.append({
'box': [x_min, y_min, w, h],
'score': w * h, # Area as base score
'is_speaking': is_speaking
})
return candidates
def detect_person_yolo(frame):
"""
Fallback: Detect largest person using YOLO when face detection fails.
Returns [x, y, w, h] of the person's 'upper body' approximation.
"""
# Use the globally loaded model
results = model(frame, verbose=False, classes=[0]) # class 0 is person
if not results:
return None
best_box = None
max_area = 0
for result in results:
boxes = result.boxes
for box in boxes:
x1, y1, x2, y2 = [int(i) for i in box.xyxy[0]]
w = x2 - x1
h = y2 - y1
area = w * h
if area > max_area:
max_area = area
# Focus on the top 40% of the person (head/chest) for framing
# This approximates where the face is if we can't detect it directly
face_h = int(h * 0.4)
best_box = [x1, y1, w, face_h]
return best_box
def detect_scenes(video_path):
video_manager = VideoManager([video_path])
scene_manager = SceneManager()
scene_manager.add_detector(ContentDetector())
video_manager.set_downscale_factor()
video_manager.start()
scene_manager.detect_scenes(frame_source=video_manager)
scene_list = scene_manager.get_scene_list()
fps = video_manager.get_framerate()
video_manager.release()
return scene_list, fps
def get_video_resolution(video_path):
cap = cv2.VideoCapture(video_path)
if not cap.isOpened():
raise IOError(f"Could not open video file {video_path}")
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
cap.release()
return width, height
def sanitize_filename(filename):
"""Remove invalid characters from filename."""
filename = re.sub(r'[<>:"/\\|?*]', '', filename)
filename = filename.replace(' ', '_')
return filename[:100]
def download_youtube_video(url, output_dir="."):
"""
Downloads a YouTube video using yt-dlp.
Returns the path to the downloaded video and the video title.
"""
print("📥 Downloading video from YouTube...")
step_start_time = time.time()
cookies_path = '/app/cookies.txt'
cookies_env = os.environ.get("YOUTUBE_COOKIES")
if cookies_env:
print("🍪 Found YOUTUBE_COOKIES env var, creating cookies file inside container...")
try:
with open(cookies_path, 'w') as f:
f.write(cookies_env)
print(f"✅ Cookies written to {cookies_path}")
except Exception as e:
print(f"⚠️ Failed to write cookies file: {e}")
cookies_path = None
else:
cookies_path = None
print("⚠️ YOUTUBE_COOKIES env var not found.")
ydl_opts_info = {
'quiet': True,
'no_warnings': True,
'cookiefile': cookies_path if cookies_path else None
}
with yt_dlp.YoutubeDL(ydl_opts_info) as ydl:
info = ydl.extract_info(url, download=False)
video_title = info.get('title', 'youtube_video')
sanitized_title = sanitize_filename(video_title)
output_template = os.path.join(output_dir, f'{sanitized_title}.%(ext)s')
expected_file = os.path.join(output_dir, f'{sanitized_title}.mp4')
if os.path.exists(expected_file):
os.remove(expected_file)
print(f"🗑️ Removed existing file to re-download with H.264 codec")
ydl_opts = {
'format': 'bestvideo[vcodec^=avc1][ext=mp4]+bestaudio[ext=m4a]/bestvideo[vcodec^=avc1]+bestaudio/best[ext=mp4]/best',
'outtmpl': output_template,
'merge_output_format': 'mp4',
'quiet': False,
'no_warnings': True,
'overwrites': True,
'cookiefile': cookies_path if cookies_path else None
}
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
ydl.download([url])
downloaded_file = os.path.join(output_dir, f'{sanitized_title}.mp4')
if not os.path.exists(downloaded_file):
for f in os.listdir(output_dir):
if f.startswith(sanitized_title) and f.endswith('.mp4'):
downloaded_file = os.path.join(output_dir, f)
break
step_end_time = time.time()
print(f"✅ Video downloaded in {step_end_time - step_start_time:.2f}s: {downloaded_file}")
return downloaded_file, sanitized_title
def process_video_to_vertical(input_video, final_output_video):
"""
Core logic to convert horizontal video to vertical using scene detection and Active Speaker Tracking (MediaPipe).
"""
script_start_time = time.time()
# Define temporary file paths based on the output name
base_name = os.path.splitext(final_output_video)[0]
temp_video_output = f"{base_name}_temp_video.mp4"
temp_audio_output = f"{base_name}_temp_audio.aac"
# Clean up previous temp files if they exist
if os.path.exists(temp_video_output): os.remove(temp_video_output)
if os.path.exists(temp_audio_output): os.remove(temp_audio_output)
if os.path.exists(final_output_video): os.remove(final_output_video)
print(f"🎬 Processing clip: {input_video}")
print(" Step 1: Detecting scenes...")
scenes, fps = detect_scenes(input_video)
if not scenes:
print(" ❌ No scenes were detected. Using full video as one scene.")
# If scene detection fails or finds nothing, treat whole video as one scene
cap = cv2.VideoCapture(input_video)
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
cap.release()
from scenedetect import FrameTimecode
scenes = [(FrameTimecode(0, fps), FrameTimecode(total_frames, fps))]
print(f" ✅ Found {len(scenes)} scenes.")
print("\n 🧠 Step 2: Preparing Active Tracking...")
original_width, original_height = get_video_resolution(input_video)
OUTPUT_HEIGHT = original_height
OUTPUT_WIDTH = int(OUTPUT_HEIGHT * ASPECT_RATIO)
if OUTPUT_WIDTH % 2 != 0:
OUTPUT_WIDTH += 1
# Initialize Cameraman
cameraman = SmoothedCameraman(OUTPUT_WIDTH, OUTPUT_HEIGHT, original_width, original_height, smoothing_factor=0.08) # Slower smoothing
# Initialize Speaker Tracker
speaker_tracker = SpeakerTracker(cooldown_frames=45) # 1.5s cooldown before switching again
print("\n ✂️ Step 4: Processing video frames (Tracking & Cropping)...")
command = [
'ffmpeg', '-y', '-f', 'rawvideo', '-vcodec', 'rawvideo',
'-s', f'{OUTPUT_WIDTH}x{OUTPUT_HEIGHT}', '-pix_fmt', 'bgr24',
'-r', str(fps), '-i', '-', '-c:v', 'libx264',
'-preset', 'fast', '-crf', '23', '-an', temp_video_output
]
ffmpeg_process = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
cap = cv2.VideoCapture(input_video)
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
frame_number = 0
current_scene_index = 0
# Pre-calculate scene boundaries for fast lookup
scene_boundaries = []
for s_start, s_end in scenes:
scene_boundaries.append((s_start.get_frames(), s_end.get_frames()))
with tqdm(total=total_frames, desc=" Tracking & Cropping") as pbar:
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
# 1. Check for Scene Change to Snap Camera
is_new_scene = False
# Check if current frame is a start frame of any scene
for s_start, _ in scene_boundaries:
if frame_number == s_start:
is_new_scene = True
break
# Reset tracker on new scene
if is_new_scene:
speaker_tracker = SpeakerTracker(cooldown_frames=45)
# 2. Detect Candidates
candidates = detect_face_candidates(frame)
# 3. Get Target from Tracker
# Tracker handles ID persistence, hysteresis, and cooldown
target_box = speaker_tracker.get_target(candidates, frame_number, original_width)
if target_box:
cameraman.update_target(target_box)
else:
# Fallback: Use YOLO to find the person if face detection fails
person_box = detect_person_yolo(frame)
if person_box:
cameraman.update_target(person_box)
# 4. Get Crop Box (with smoothing, unless new scene)
x1, y1, x2, y2 = cameraman.get_crop_box(force_snap=is_new_scene)
# 4. Crop & Resize
# Ensure coordinates are valid
crop_h = y2 - y1
crop_w = x2 - x1
if crop_h > 0 and crop_w > 0:
cropped_frame = frame[y1:y2, x1:x2]
output_frame = cv2.resize(cropped_frame, (OUTPUT_WIDTH, OUTPUT_HEIGHT))
else:
# Fallback if crop is invalid (shouldn't happen)
output_frame = cv2.resize(frame, (OUTPUT_WIDTH, OUTPUT_HEIGHT))
ffmpeg_process.stdin.write(output_frame.tobytes())
frame_number += 1
pbar.update(1)
ffmpeg_process.stdin.close()
stderr_output = ffmpeg_process.stderr.read().decode()
ffmpeg_process.wait()
cap.release()
if ffmpeg_process.returncode != 0:
print("\n ❌ FFmpeg frame processing failed.")
print(" Stderr:", stderr_output)
return False
print("\n 🔊 Step 5: Extracting audio...")
audio_extract_command = [
'ffmpeg', '-y', '-i', input_video, '-vn', '-acodec', 'copy', temp_audio_output
]
try:
subprocess.run(audio_extract_command, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
except subprocess.CalledProcessError:
print("\n ❌ Audio extraction failed (maybe no audio?). Proceeding without audio.")
pass
print("\n ✨ Step 6: Merging...")
if os.path.exists(temp_audio_output):
merge_command = [
'ffmpeg', '-y', '-i', temp_video_output, '-i', temp_audio_output,
'-c:v', 'copy', '-c:a', 'copy', final_output_video
]
else:
merge_command = [
'ffmpeg', '-y', '-i', temp_video_output,
'-c:v', 'copy', final_output_video
]
try:
subprocess.run(merge_command, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
print(f" ✅ Clip saved to {final_output_video}")
except subprocess.CalledProcessError as e:
print("\n ❌ Final merge failed.")
print(" Stderr:", e.stderr.decode())
return False
# Clean up temp files
if os.path.exists(temp_video_output): os.remove(temp_video_output)
if os.path.exists(temp_audio_output): os.remove(temp_audio_output)
return True
def transcribe_video(video_path):
print("🎙️ Transcribing video with Faster-Whisper (CPU Optimized)...")
from faster_whisper import WhisperModel
# Run on CPU with INT8 quantization for speed
model = WhisperModel("base", device="cpu", compute_type="int8")
segments, info = model.transcribe(video_path, word_timestamps=True)
print(f" Detected language '{info.language}' with probability {info.language_probability:.2f}")
# Convert to openai-whisper compatible format
transcript_segments = []
full_text = ""
for segment in segments:
# Print progress to keep user informed (and prevent timeouts feeling)
print(f" [{segment.start:.2f}s -> {segment.end:.2f}s] {segment.text}")
seg_dict = {
'text': segment.text,
'start': segment.start,
'end': segment.end,
'words': []
}
if segment.words:
for word in segment.words:
seg_dict['words'].append({
'word': word.word,
'start': word.start,
'end': word.end,
'probability': word.probability
})
transcript_segments.append(seg_dict)
full_text += segment.text + " "
return {
'text': full_text.strip(),
'segments': transcript_segments,
'language': info.language
}
def get_viral_clips(transcript_result, video_duration):
print("🤖 Analyzing with Gemini...")
api_key = os.getenv("GEMINI_API_KEY")
if not api_key:
print("❌ Error: GEMINI_API_KEY not found in environment variables.")
return None
client = genai.Client(api_key=api_key)
# We use gemini-2.5-flash as requested.
model_name = 'gemini-2.5-flash'
print(f"🤖 Initializing Gemini with model: {model_name}")
# Extract words
words = []
for segment in transcript_result['segments']:
for word in segment.get('words', []):
words.append({
'w': word['word'],
's': word['start'],
'e': word['end']
})
prompt = GEMINI_PROMPT_TEMPLATE.format(
video_duration=video_duration,
transcript_text=json.dumps(transcript_result['text']),
words_json=json.dumps(words)
)
try:
response = client.models.generate_content(
model=model_name,
contents=prompt
)
# --- Cost Calculation ---
try:
usage = response.usage_metadata
if usage:
# Gemini 2.5 Flash Pricing (Dec 2025)
# Input: $0.10 per 1M tokens
# Output: $0.40 per 1M tokens
input_price_per_million = 0.10
output_price_per_million = 0.40
prompt_tokens = usage.prompt_token_count
output_tokens = usage.candidates_token_count
input_cost = (prompt_tokens / 1_000_000) * input_price_per_million
output_cost = (output_tokens / 1_000_000) * output_price_per_million
total_cost = input_cost + output_cost
cost_analysis = {
"input_tokens": prompt_tokens,
"output_tokens": output_tokens,
"input_cost": input_cost,
"output_cost": output_cost,
"total_cost": total_cost,
"model": model_name
}
print(f"💰 Token Usage ({model_name}):")
print(f" - Input Tokens: {prompt_tokens} (${input_cost:.6f})")
print(f" - Output Tokens: {output_tokens} (${output_cost:.6f})")
print(f" - Total Estimated Cost: ${total_cost:.6f}")
except Exception as e:
print(f"⚠️ Could not calculate cost: {e}")
cost_analysis = None
# ------------------------
# Clean response if it contains markdown code blocks
text = response.text
if text.startswith("```json"):
text = text[7:]
if text.endswith("```"):
text = text[:-3]
text = text.strip()
result_json = json.loads(text)
if cost_analysis:
result_json['cost_analysis'] = cost_analysis
return result_json
except Exception as e:
print(f"❌ Gemini Error: {e}")
return None
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="AutoCrop-Vertical with Viral Clip Detection.")
input_group = parser.add_mutually_exclusive_group(required=True)
input_group.add_argument('-i', '--input', type=str, help="Path to the input video file.")
input_group.add_argument('-u', '--url', type=str, help="YouTube URL to download and process.")
parser.add_argument('-o', '--output', type=str, help="Output directory or file (if processing whole video).")
parser.add_argument('--keep-original', action='store_true', help="Keep the downloaded YouTube video.")
parser.add_argument('--skip-analysis', action='store_true', help="Skip AI analysis and convert the whole video.")
args = parser.parse_args()
script_start_time = time.time()
# 1. Get Input Video
if args.url:
output_dir = args.output if args.output and os.path.isdir(args.output) else "."
if args.output and not os.path.isdir(args.output) and not args.skip_analysis:
# If output is a filename but we expect multiple clips, use its dir
output_dir = os.path.dirname(args.output) or "."
input_video, video_title = download_youtube_video(args.url, output_dir)
else:
input_video = args.input
video_title = os.path.splitext(os.path.basename(input_video))[0]
output_dir = os.path.dirname(args.output) if args.output else os.path.dirname(input_video)
if not os.path.exists(input_video):
print(f"❌ Input file not found: {input_video}")
exit(1)
# 2. Decision: Analyze clips or process whole?
if args.skip_analysis:
print("⏩ Skipping analysis, processing entire video...")
output_file = args.output if args.output else os.path.join(output_dir, f"{video_title}_vertical.mp4")
process_video_to_vertical(input_video, output_file)
else:
# 3. Transcribe
transcript = transcribe_video(input_video)
# Get duration
cap = cv2.VideoCapture(input_video)
fps = cap.get(cv2.CAP_PROP_FPS)
frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
duration = frame_count / fps
cap.release()
# 4. Gemini Analysis
clips_data = get_viral_clips(transcript, duration)
if not clips_data or 'shorts' not in clips_data:
print("❌ Failed to identify clips. Converting whole video as fallback.")
output_file = os.path.join(output_dir, f"{video_title}_vertical.mp4")
process_video_to_vertical(input_video, output_file)
else:
print(f"🔥 Found {len(clips_data['shorts'])} viral clips!")
# Save metadata
metadata_file = os.path.join(output_dir, f"{video_title}_metadata.json")
with open(metadata_file, 'w') as f:
json.dump(clips_data, f, indent=2)
print(f" Saved metadata to {metadata_file}")
# 5. Process each clip
for i, clip in enumerate(clips_data['shorts']):
start = clip['start']
end = clip['end']
print(f"\n🎬 Processing Clip {i+1}: {start}s - {end}s")
print(f" Title: {clip.get('video_title_for_youtube_short', 'No Title')}")
# Cut clip
clip_filename = f"{video_title}_clip_{i+1}.mp4"
clip_temp_path = os.path.join(output_dir, f"temp_{clip_filename}")
clip_final_path = os.path.join(output_dir, clip_filename)
# ffmpeg cut
# Using re-encoding for precision as requested by strict seconds
cut_command = [
'ffmpeg', '-y',
'-ss', str(start),
'-to', str(end),
'-i', input_video,
'-c:v', 'libx264', '-crf', '18', '-preset', 'fast',
'-c:a', 'aac',
clip_temp_path
]
subprocess.run(cut_command, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
# Process vertical
success = process_video_to_vertical(clip_temp_path, clip_final_path)
if success:
print(f" ✅ Clip {i+1} ready: {clip_final_path}")
# Clean up temp cut
if os.path.exists(clip_temp_path):
os.remove(clip_temp_path)
# Clean up original if requested
if args.url and not args.keep_original and os.path.exists(input_video):
os.remove(input_video)
print(f"🗑️ Cleaned up downloaded video.")
total_time = time.time() - script_start_time
print(f"\n⏱️ Total execution time: {total_time:.2f}s")