forked from kamilstanuch/Autocrop-vertical
-
Notifications
You must be signed in to change notification settings - Fork 828
Expand file tree
/
Copy pathhooks.py
More file actions
408 lines (343 loc) · 15 KB
/
Copy pathhooks.py
File metadata and controls
408 lines (343 loc) · 15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
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, METADATA_SCRUB
def _truncate_bytes(text, max_bytes):
"""Trim to a byte budget without splitting a multi-byte character.
Deliberately duplicated from main.truncate_bytes: this module stays free of
main's heavy imports (cv2, mediapipe, torch) so it can be used standalone.
"""
encoded = text.encode("utf-8")
if len(encoded) <= max_bytes:
return text
return encoded[:max_bytes].decode("utf-8", "ignore")
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.
# The uuid alone guarantees that; the source name rides along only as a
# debugging hint, so it is trimmed by BYTES (filesystems cap at 255 bytes,
# and one Bengali or Arabic character costs three). Embedding it untrimmed
# raised OSError 36 and killed the endpoint in prod on 26-jul-2026.
stem = os.path.splitext(os.path.basename(video_path))[0]
hook_filename = (f"temp_hook_{uuid.uuid4().hex[:8]}_"
f"{_truncate_bytes(stem, 80)}.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),
*METADATA_SCRUB,
'-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)