- transcribe_backends.py: parakeet-tdt-0.6b-v3 (onnx-asr, VAD+timestamps) as selectable backend (TRANSCRIBE_BACKEND), token->word reconstruction keeping the leading-space convention, absolute timestamps, native floats, language detection via py3langid, and automatic whisper fallback (errors, empty output, or language outside parakeet's 25). - whisper singleton + ASR GPU semaphore (model stays resident; GPU decodes serialized; CPU path behavior unchanged). - ffmpeg_utils.py: central encoder args (FFMPEG_ENCODER=x264|nvenc|auto with cached probe + fallback); migrated the 9 hardcoded libx264 call sites. - saasshorts now honors WHISPER_* config instead of hardcoded base/cpu/int8. - Dockerfile: ARG GPU=1 installs CUDA user-space libs (cuBLAS/cuDNN9) + onnx-asr/onnxruntime-gpu; LD_LIBRARY_PATH + NVIDIA_DRIVER_CAPABILITIES. - Validated on prod GPU (RTX 4000 Ada, driver 580): 94s clip transcribed in 6.5s, word timestamps within ~0.1s of whisper, fallback path exercised.
389 lines
14 KiB
Python
389 lines
14 KiB
Python
import os
|
|
import re
|
|
import textwrap
|
|
import subprocess
|
|
import urllib.request
|
|
import uuid
|
|
from PIL import Image, ImageDraw, ImageFont, ImageFilter
|
|
|
|
from ffmpeg_utils import video_encode_args, QUALITY
|
|
|
|
FONT_URL = "https://github.com/googlefonts/noto-fonts/raw/main/hinted/ttf/NotoSerif/NotoSerif-Bold.ttf"
|
|
FONT_DIR = "fonts"
|
|
FONT_PATH = os.path.join(FONT_DIR, "NotoSerif-Bold.ttf")
|
|
|
|
# Codepoint ranges NotoSerif has no glyphs for (would render as tofu boxes).
|
|
_EMOJI_RE = re.compile(
|
|
"["
|
|
"\U0001F000-\U0001FAFF" # emoticons, symbols, transport, supplemental
|
|
"\U00002600-\U000027BF" # misc symbols + dingbats
|
|
"\U0001F1E6-\U0001F1FF" # regional indicators (flags)
|
|
"\U00002B00-\U00002BFF" # arrows, stars
|
|
"\U0000FE0E\U0000FE0F" # variation selectors
|
|
"\U0000200D" # zero-width joiner
|
|
"\U000020E3" # combining keycap
|
|
"]+"
|
|
)
|
|
|
|
# Emoji-capable fonts, probed at runtime (Windows, WSL, Linux/Docker).
|
|
_EMOJI_FONT_CANDIDATES = [
|
|
"C:\\Windows\\Fonts\\seguiemj.ttf",
|
|
"/mnt/c/Windows/Fonts/seguiemj.ttf",
|
|
"/usr/share/fonts/truetype/noto/NotoColorEmoji.ttf",
|
|
"/usr/share/fonts/noto-emoji/NotoColorEmoji.ttf",
|
|
]
|
|
|
|
|
|
def _load_emoji_font(font_size):
|
|
"""Return an emoji-capable font at the requested size, or None.
|
|
|
|
Fonts that only support a fixed bitmap size (e.g. NotoColorEmoji) fail to
|
|
load at arbitrary sizes; those are treated as unavailable rather than
|
|
breaking the layout with wrongly-sized glyphs."""
|
|
for path in _EMOJI_FONT_CANDIDATES:
|
|
if not os.path.exists(path):
|
|
continue
|
|
try:
|
|
return ImageFont.truetype(path, font_size)
|
|
except Exception:
|
|
continue
|
|
return None
|
|
|
|
|
|
def _split_emoji_runs(text):
|
|
"""Split text into (is_emoji, chunk) runs."""
|
|
runs = []
|
|
pos = 0
|
|
for m in _EMOJI_RE.finditer(text):
|
|
if m.start() > pos:
|
|
runs.append((False, text[pos:m.start()]))
|
|
runs.append((True, m.group()))
|
|
pos = m.end()
|
|
if pos < len(text):
|
|
runs.append((False, text[pos:]))
|
|
return runs
|
|
|
|
|
|
def _measure_width(draw, text, font, emoji_font):
|
|
"""Pixel width of a line, measuring emoji runs with the emoji font."""
|
|
width = 0.0
|
|
for is_emoji, chunk in _split_emoji_runs(text):
|
|
use_font = emoji_font if (is_emoji and emoji_font) else font
|
|
width += draw.textlength(chunk, font=use_font)
|
|
return width
|
|
|
|
|
|
def _draw_mixed(draw, xy, text, font, emoji_font, fill, outline=None):
|
|
"""Draw a line, rendering emoji runs with the emoji font (in color if
|
|
supported). outline: optional (color, px) stroke drawn under the text."""
|
|
x, y = xy
|
|
stroke_w = outline[1] if outline else 0
|
|
stroke_fill = outline[0] if outline else None
|
|
for is_emoji, chunk in _split_emoji_runs(text):
|
|
if is_emoji and emoji_font:
|
|
try:
|
|
draw.text((x, y), chunk, font=emoji_font, embedded_color=True)
|
|
except TypeError:
|
|
draw.text((x, y), chunk, font=emoji_font, fill=fill)
|
|
x += draw.textlength(chunk, font=emoji_font)
|
|
else:
|
|
if stroke_w:
|
|
draw.text((x, y), chunk, font=font, fill=fill,
|
|
stroke_width=stroke_w, stroke_fill=stroke_fill)
|
|
else:
|
|
draw.text((x, y), chunk, font=font, fill=fill)
|
|
x += draw.textlength(chunk, font=font)
|
|
|
|
|
|
def _break_long_word(draw, word, font, emoji_font, max_width):
|
|
"""Character-level hard wrap for a single word wider than max_width."""
|
|
pieces = []
|
|
current = ""
|
|
for ch in word:
|
|
if current and _measure_width(draw, current + ch, font, emoji_font) > max_width:
|
|
pieces.append(current)
|
|
current = ch
|
|
else:
|
|
current += ch
|
|
if current:
|
|
pieces.append(current)
|
|
return pieces
|
|
|
|
def download_font_if_needed():
|
|
"""Downloads a serif font for the hook text if not present."""
|
|
if not os.path.exists(FONT_DIR):
|
|
os.makedirs(FONT_DIR)
|
|
if not os.path.exists(FONT_PATH):
|
|
print(f"⬇️ Downloading font from {FONT_URL}...")
|
|
try:
|
|
# Add user agent to avoid 403s slightly
|
|
req = urllib.request.Request(
|
|
FONT_URL,
|
|
headers={'User-Agent': 'Mozilla/5.0'}
|
|
)
|
|
with urllib.request.urlopen(req) as response, open(FONT_PATH, 'wb') as out_file:
|
|
out_file.write(response.read())
|
|
print("✅ Font downloaded.")
|
|
except Exception as e:
|
|
print(f"❌ Failed to download font: {e}")
|
|
|
|
# Hook visual styles. Each maps to box fill (RGBA, alpha 0 = no box), text
|
|
# color, and an optional text outline (color, px) for box-less looks.
|
|
HOOK_STYLES = {
|
|
# White card, black serif text (original look).
|
|
"classic": {"box": (255, 255, 255, 240), "text": (0, 0, 0), "outline": None, "shadow": True},
|
|
# Dark card, white text.
|
|
"dark": {"box": (18, 18, 20, 235), "text": (255, 255, 255), "outline": None, "shadow": True},
|
|
# Bright yellow card, black text (high-contrast TikTok look).
|
|
"yellow": {"box": (255, 214, 0, 245), "text": (0, 0, 0), "outline": None, "shadow": True},
|
|
# Red "breaking" card, white text.
|
|
"red": {"box": (220, 38, 38, 245), "text": (255, 255, 255), "outline": None, "shadow": True},
|
|
# No box: white text with a thick black outline (caption/MrBeast style).
|
|
"outline": {"box": (0, 0, 0, 0), "text": (255, 255, 255), "outline": ((0, 0, 0), 8), "shadow": False},
|
|
# No box: yellow text with black outline.
|
|
"outline_yellow": {"box": (0, 0, 0, 0), "text": (255, 214, 0), "outline": ((0, 0, 0), 8), "shadow": False},
|
|
}
|
|
|
|
|
|
def create_hook_image(text, target_width, output_image_path="hook_overlay.png", font_scale=1.0, style="classic"):
|
|
"""
|
|
Generates a hook overlay image using pixel-based wrapping.
|
|
target_width: The max width the box should occupy (e.g. 85% of video)
|
|
style: one of HOOK_STYLES (classic/dark/yellow/red/outline/outline_yellow)
|
|
"""
|
|
download_font_if_needed()
|
|
|
|
look = HOOK_STYLES.get(style, HOOK_STYLES["classic"])
|
|
box_fill = look["box"]
|
|
text_fill = look["text"]
|
|
outline = look["outline"]
|
|
has_box = box_fill[3] > 0
|
|
draw_shadow = look["shadow"]
|
|
|
|
# Configuration
|
|
padding_x = 30 # Balanced padding
|
|
padding_y = 25
|
|
line_spacing = 20 # Increased spacing
|
|
cornerradius = 20
|
|
shadow_offset = (5, 5)
|
|
shadow_blur = 10
|
|
|
|
# Font Size Calculation (approx 5% of width - tuned to match Noto Serif Bold metrics in browser)
|
|
base_font_size = int(target_width * 0.05)
|
|
font_size = int(base_font_size * font_scale)
|
|
|
|
try:
|
|
font = ImageFont.truetype(FONT_PATH, font_size)
|
|
except Exception as e:
|
|
print(f"⚠️ Warning: Could not load font {FONT_PATH}, using default. Error: {e}")
|
|
font = ImageFont.load_default()
|
|
|
|
# Emoji handling: render with an emoji-capable font if one exists,
|
|
# otherwise strip emoji instead of drawing tofu boxes.
|
|
emoji_font = None
|
|
if _EMOJI_RE.search(text):
|
|
emoji_font = _load_emoji_font(font_size)
|
|
if emoji_font is None:
|
|
text = _EMOJI_RE.sub("", text)
|
|
text = re.sub(r"[ \t]{2,}", " ", text).strip()
|
|
|
|
# Wrap text logic (Pixel-based)
|
|
dummy_img = Image.new('RGBA', (1, 1))
|
|
draw = ImageDraw.Draw(dummy_img)
|
|
|
|
max_text_width = target_width - (2 * padding_x)
|
|
|
|
# Handle manual newlines first
|
|
paragraphs = text.split('\n')
|
|
lines = []
|
|
|
|
for p in paragraphs:
|
|
if not p.strip():
|
|
lines.append("")
|
|
continue
|
|
|
|
words = p.split()
|
|
current_line = []
|
|
|
|
for word in words:
|
|
# Test if adding word fits
|
|
test_line = ' '.join(current_line + [word])
|
|
w = _measure_width(draw, test_line, font, emoji_font)
|
|
|
|
if w <= max_text_width:
|
|
current_line.append(word)
|
|
continue
|
|
|
|
# Word doesn't fit on the current line
|
|
if current_line:
|
|
lines.append(' '.join(current_line))
|
|
current_line = []
|
|
|
|
if _measure_width(draw, word, font, emoji_font) <= max_text_width:
|
|
current_line = [word]
|
|
else:
|
|
# Single word wider than the box: hard-wrap it character-wise
|
|
# so it can't get cut off at the edges.
|
|
pieces = _break_long_word(draw, word, font, emoji_font, max_text_width)
|
|
lines.extend(pieces[:-1])
|
|
current_line = [pieces[-1]] if pieces else []
|
|
|
|
if current_line:
|
|
lines.append(' '.join(current_line))
|
|
|
|
# Recalculate true width/height
|
|
max_line_width = 0
|
|
text_heights = []
|
|
|
|
for line in lines:
|
|
if not line:
|
|
text_heights.append(font_size) # Use font size for empty line height
|
|
continue
|
|
|
|
w = _measure_width(draw, line, font, emoji_font)
|
|
bbox = draw.textbbox((0, 0), line, font=font)
|
|
h = bbox[3] - bbox[1]
|
|
max_line_width = max(max_line_width, int(w))
|
|
text_heights.append(h)
|
|
|
|
# Box dimensions
|
|
# We want the box to fit the text exactly + padding
|
|
# Ensure min width for aesthetic reasons if text is short (at least 30% of target)
|
|
box_width = max(max_line_width + (2 * padding_x), int(target_width * 0.3))
|
|
|
|
# Total Text Height: sum(heights) + spacing * (n-1)
|
|
if not text_heights:
|
|
total_text_height = font_size
|
|
else:
|
|
total_text_height = sum(text_heights) + (len(text_heights) - 1) * line_spacing
|
|
|
|
box_height = total_text_height + (2 * padding_y)
|
|
|
|
# Create Final Image with Rounded Corners and Shadow
|
|
# 1. Canvas for Shadow (larger than box)
|
|
canvas_w = box_width + 40
|
|
canvas_h = box_height + 40
|
|
|
|
img = Image.new('RGBA', (canvas_w, canvas_h), (0, 0, 0, 0))
|
|
draw = ImageDraw.Draw(img)
|
|
|
|
# 2. Draw Shadow (only for boxed styles)
|
|
if draw_shadow and has_box:
|
|
shadow_box = [
|
|
(20 + shadow_offset[0], 20 + shadow_offset[1]),
|
|
(20 + box_width + shadow_offset[0], 20 + box_height + shadow_offset[1])
|
|
]
|
|
draw.rounded_rectangle(shadow_box, radius=cornerradius, fill=(0, 0, 0, 100))
|
|
# 3. Blur Shadow
|
|
img = img.filter(ImageFilter.GaussianBlur(5))
|
|
|
|
# 4. Draw Box (sharper, on top of blurred shadow)
|
|
draw_final = ImageDraw.Draw(img)
|
|
|
|
if has_box:
|
|
main_box = [
|
|
(20, 20),
|
|
(20 + box_width, 20 + box_height)
|
|
]
|
|
draw_final.rounded_rectangle(main_box, radius=cornerradius, fill=box_fill)
|
|
|
|
# 5. Draw Text
|
|
current_y = 20 + padding_y - 2 # Minor visual adjustment
|
|
for i, line in enumerate(lines):
|
|
if not line:
|
|
current_y += font_size + line_spacing
|
|
continue
|
|
|
|
line_w = _measure_width(draw_final, line, font, emoji_font)
|
|
bbox = draw_final.textbbox((0, 0), line, font=font)
|
|
line_h = text_heights[i] if i < len(text_heights) else bbox[3] - bbox[1]
|
|
|
|
# Center X
|
|
x = 20 + int(box_width - line_w) // 2
|
|
|
|
# Draw text in the style's color (emoji runs use the emoji font)
|
|
_draw_mixed(draw_final, (x, current_y), line, font, emoji_font,
|
|
fill=text_fill, outline=outline)
|
|
|
|
current_y += line_h + line_spacing
|
|
|
|
img.save(output_image_path)
|
|
return output_image_path, canvas_w, canvas_h
|
|
|
|
def add_hook_to_video(video_path, text, output_path, position="top", font_scale=1.0, duration=None, style="classic"):
|
|
"""
|
|
Overlays text hook onto video.
|
|
position: 'top', 'center', 'bottom'
|
|
font_scale: float multiplier (1.0 = default)
|
|
style: hook look (see HOOK_STYLES)
|
|
"""
|
|
if not os.path.exists(video_path):
|
|
raise FileNotFoundError(f"Video {video_path} not found")
|
|
|
|
# 1. Probe video width to scale text properly
|
|
try:
|
|
cmd = ['ffprobe', '-v', 'error', '-show_entries', 'stream=width,height', '-of', 'csv=s=x:p=0', video_path]
|
|
res = subprocess.check_output(cmd, timeout=60).decode().strip()
|
|
# Takes first stream if multiple
|
|
dims = res.split('\n')[0].split('x')
|
|
video_width = int(dims[0])
|
|
video_height = int(dims[1])
|
|
except Exception as e:
|
|
print(f"⚠️ FFprobe failed: {e}. Assuming 1080x1920")
|
|
video_width = 1080
|
|
video_height = 1920
|
|
|
|
# 2. Generate Image
|
|
# Box check: Don't let it be wider than 90% of screen
|
|
target_box_width = int(video_width * 0.9)
|
|
|
|
# Unique per invocation so parallel jobs can't overwrite each other's overlay.
|
|
hook_filename = f"temp_hook_{uuid.uuid4().hex[:8]}_{os.path.basename(video_path)}.png"
|
|
|
|
try:
|
|
img_path, box_w, box_h = create_hook_image(text, target_box_width, hook_filename, font_scale=font_scale, style=style)
|
|
|
|
# 3. Calculate Overlay Position
|
|
overlay_x = (video_width - box_w) // 2
|
|
|
|
if position == "center":
|
|
overlay_y = (video_height - box_h) // 2
|
|
elif position == "bottom":
|
|
# Bottom 20% mark (approx)
|
|
overlay_y = int(video_height * 0.70)
|
|
else:
|
|
# Top 20% mark
|
|
overlay_y = int(video_height * 0.20)
|
|
|
|
# 4. FFmpeg Command
|
|
print(f"🎬 Overlaying hook: '{text}' at {overlay_x},{overlay_y}")
|
|
|
|
ffmpeg_cmd = [
|
|
'ffmpeg', '-y',
|
|
'-i', video_path,
|
|
'-i', img_path,
|
|
'-filter_complex', f"[0:v][1:v]overlay={overlay_x}:{overlay_y}"
|
|
+ (f":enable='between(t,0,{float(duration)})'" if duration else ""),
|
|
'-c:a', 'copy',
|
|
*video_encode_args(QUALITY),
|
|
'-movflags', '+faststart',
|
|
output_path
|
|
]
|
|
|
|
subprocess.run(ffmpeg_cmd, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=1800)
|
|
print(f"✅ Hook added to {output_path}")
|
|
return True
|
|
|
|
except subprocess.TimeoutExpired:
|
|
print("❌ FFmpeg hook overlay timed out after 1800s.")
|
|
raise RuntimeError("FFmpeg hook overlay timed out after 1800s.")
|
|
except subprocess.CalledProcessError as e:
|
|
print(f"❌ FFmpeg Error: {e.stderr.decode() if e.stderr else 'Unknown'}")
|
|
raise e
|
|
except Exception as e:
|
|
print(f"❌ Hook Gen Error: {e}")
|
|
raise e
|
|
finally:
|
|
# Cleanup temp image
|
|
if os.path.exists(hook_filename):
|
|
os.remove(hook_filename)
|