clipwright/main.py

591 lines
22 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 yt_dlp
# import whisper (replaced by faster_whisper inside function)
from google import genai
from google import genai
from dotenv import load_dotenv
import json
# 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
model = YOLO('yolov8n.pt')
# Load the Haar Cascade for face detection once
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
def analyze_scene_content(video_path, scene_start_time, scene_end_time):
"""
Analyzes the middle frame of a scene to detect people and faces.
"""
cap = cv2.VideoCapture(video_path)
if not cap.isOpened():
print(f"Error: Could not open video {video_path}")
return []
fps = cap.get(cv2.CAP_PROP_FPS)
start_frame = scene_start_time.get_frames()
end_frame = scene_end_time.get_frames()
middle_frame_number = int(start_frame + (end_frame - start_frame) / 2)
cap.set(cv2.CAP_PROP_POS_FRAMES, middle_frame_number)
ret, frame = cap.read()
if not ret:
cap.release()
return []
results = model([frame], verbose=False)
detected_objects = []
for result in results:
boxes = result.boxes
for box in boxes:
if box.cls[0] == 0:
x1, y1, x2, y2 = [int(i) for i in box.xyxy[0]]
person_box = [x1, y1, x2, y2]
person_roi_gray = cv2.cvtColor(frame[y1:y2, x1:x2], cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(person_roi_gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))
face_box = None
if len(faces) > 0:
fx, fy, fw, fh = faces[0]
face_box = [x1 + fx, y1 + fy, x1 + fx + fw, y1 + fy + fh]
detected_objects.append({'person_box': person_box, 'face_box': face_box})
cap.release()
return detected_objects
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_enclosing_box(boxes):
if not boxes:
return None
min_x = min(box[0] for box in boxes)
min_y = min(box[1] for box in boxes)
max_x = max(box[2] for box in boxes)
max_y = max(box[3] for box in boxes)
return [min_x, min_y, max_x, max_y]
def decide_cropping_strategy(scene_analysis, frame_height):
num_people = len(scene_analysis)
if num_people == 0:
return 'LETTERBOX', None
if num_people == 1:
target_box = scene_analysis[0]['face_box'] or scene_analysis[0]['person_box']
return 'TRACK', target_box
person_boxes = [obj['person_box'] for obj in scene_analysis]
group_box = get_enclosing_box(person_boxes)
group_width = group_box[2] - group_box[0]
max_width_for_crop = frame_height * ASPECT_RATIO
if group_width < max_width_for_crop:
return 'TRACK', group_box
else:
return 'LETTERBOX', None
def calculate_crop_box(target_box, frame_width, frame_height):
target_center_x = (target_box[0] + target_box[2]) / 2
crop_height = frame_height
crop_width = int(crop_height * ASPECT_RATIO)
x1 = int(target_center_x - crop_width / 2)
y1 = 0
x2 = int(target_center_x + crop_width / 2)
y2 = frame_height
if x1 < 0:
x1 = 0
x2 = crop_width
if x2 > frame_width:
x2 = frame_width
x1 = frame_width - crop_width
return x1, y1, x2, y2
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()
ydl_opts_info = {
'quiet': True,
'no_warnings': True,
}
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,
}
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.
"""
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: Analyzing scene content...")
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
scenes_analysis = []
for i, (start_time, end_time) in enumerate(scenes):
analysis = analyze_scene_content(input_video, start_time, end_time)
strategy, target_box = decide_cropping_strategy(analysis, original_height)
scenes_analysis.append({
'start_frame': start_time.get_frames(),
'end_frame': end_time.get_frames(),
'analysis': analysis,
'strategy': strategy,
'target_box': target_box
})
print("\n ✂️ Step 4: Processing video frames...")
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
with tqdm(total=total_frames, desc=" Applying Plan") as pbar:
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
if current_scene_index < len(scenes_analysis) - 1 and \
frame_number >= scenes_analysis[current_scene_index + 1]['start_frame']:
current_scene_index += 1
scene_data = scenes_analysis[current_scene_index]
strategy = scene_data['strategy']
target_box = scene_data['target_box']
if strategy == 'TRACK':
crop_box = calculate_crop_box(target_box, original_width, original_height)
processed_frame = frame[crop_box[1]:crop_box[3], crop_box[0]:crop_box[2]]
output_frame = cv2.resize(processed_frame, (OUTPUT_WIDTH, OUTPUT_HEIGHT))
else: # LETTERBOX
scale_factor = OUTPUT_WIDTH / original_width
scaled_height = int(original_height * scale_factor)
scaled_frame = cv2.resize(frame, (OUTPUT_WIDTH, scaled_height))
output_frame = np.zeros((OUTPUT_HEIGHT, OUTPUT_WIDTH, 3), dtype=np.uint8)
y_offset = (OUTPUT_HEIGHT - scaled_height) // 2
output_frame[y_offset:y_offset + scaled_height, :] = scaled_frame
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.")
# Create silent audio? Or just skip audio merge
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
# Debug: Print masked key to verify it's loaded correctly
print(f"🔑 Loaded API Key: {api_key[:4]}...{api_key[-4:]} (Length: {len(api_key)})")
if not api_key.startswith("AIza"):
print("\n⚠️ WARNING: The API Key does not start with 'AIza'. Google AI Studio keys typically start with 'AIza'.")
print(" Please check that you copied the 'API Key' and not a Client ID, Secret, or Token.")
print(" Get your key here: https://aistudio.google.com/app/apikey\n")
client = genai.Client(api_key=api_key)
# We use gemini-2.5-flash because 'gemini-3-flash' does not exist in the public API yet.
# If you have access to a preview model, change this string.
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
)
# 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()
return json.loads(text)
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")