feat(hook): auto-burn AI hooks on generated clips + working emoji + editor polish
Auto-hook (opt-in per job, dashboard default ON): - /api/process accepts auto_hook + auto_hook_style; absent means off, so API/MCP/webhook callers keep byte-identical output. - main.py auto_hook_clip burns each clip's viral_hook_text (Gemini already produced it, it was only used to pre-fill the modal) into the canonical clip in place — after reframe, under watermark and captions — so every derived-name convention (subtitled_/recut_ walk-backs, R2 archive, restore) keeps working untouched. Fail-open like auto_caption_clip. - Burned hook recorded as clip.auto_hook in metadata; the hook modal warns before stacking a second one. - MediaInput: 'auto hook titles' toggle + style select in advanced options, persisted in localStorage. Emoji that actually render: - Gemini prompt now asks for 1-2 emojis in viral_hook_text. - Dockerfile installs fonts-noto-color-emoji — without it prod silently stripped every emoji (no candidate font existed in the image). - hooks.py supports fixed-bitmap color fonts (NotoColorEmoji only loads at its 109px strike; Apple Color Emoji at 160): glyphs render at native size and are Lanczos-rescaled to the text size instead of being treated as unavailable. macOS system font added for local dev. Editor polish: - HookModal persists last style/position/size/entrance (always reset to classic before, which read as the picker being broken). - Remotion preview positions aligned to hooks.py (top 20%, bottom 70%). - Warning when a bottom hook will overlap burned/preview captions. - Entrance-animation control greyed out with a note when the clip re-renders on the server, where the hook is static.
This commit is contained in:
parent
8dbc6ce9bd
commit
ac0138269d
9 changed files with 234 additions and 36 deletions
|
|
@ -50,6 +50,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||||
git \
|
git \
|
||||||
fontconfig \
|
fontconfig \
|
||||||
fonts-liberation \
|
fonts-liberation \
|
||||||
|
fonts-noto-color-emoji \
|
||||||
&& rm -rf /var/lib/apt/lists/*
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
# Deno JS runtime — required by yt-dlp for some extractor challenges.
|
# Deno JS runtime — required by yt-dlp for some extractor challenges.
|
||||||
|
|
|
||||||
16
app.py
16
app.py
|
|
@ -1452,7 +1452,9 @@ async def process_endpoint(
|
||||||
webhook_secret: Optional[str] = Form(None),
|
webhook_secret: Optional[str] = Form(None),
|
||||||
target_clips: Optional[str] = Form(None),
|
target_clips: Optional[str] = Form(None),
|
||||||
clip_min_seconds: Optional[str] = Form(None),
|
clip_min_seconds: Optional[str] = Form(None),
|
||||||
clip_max_seconds: Optional[str] = Form(None)
|
clip_max_seconds: Optional[str] = Form(None),
|
||||||
|
auto_hook: Optional[str] = Form(None),
|
||||||
|
auto_hook_style: Optional[str] = Form(None)
|
||||||
):
|
):
|
||||||
api_key = await resolve_gemini(request)
|
api_key = await resolve_gemini(request)
|
||||||
if not api_key:
|
if not api_key:
|
||||||
|
|
@ -1475,6 +1477,8 @@ async def process_endpoint(
|
||||||
target_clips = body.get("target_clips")
|
target_clips = body.get("target_clips")
|
||||||
clip_min_seconds = body.get("clip_min_seconds")
|
clip_min_seconds = body.get("clip_min_seconds")
|
||||||
clip_max_seconds = body.get("clip_max_seconds")
|
clip_max_seconds = body.get("clip_max_seconds")
|
||||||
|
auto_hook = body.get("auto_hook")
|
||||||
|
auto_hook_style = body.get("auto_hook_style")
|
||||||
|
|
||||||
# Normalize output format (auto = keep pipeline default).
|
# Normalize output format (auto = keep pipeline default).
|
||||||
if output_format not in ("vertical", "horizontal", "square"):
|
if output_format not in ("vertical", "horizontal", "square"):
|
||||||
|
|
@ -1553,6 +1557,16 @@ async def process_endpoint(
|
||||||
if chosen:
|
if chosen:
|
||||||
print(f"[layouts] job={job_id} enabled={sorted(chosen)}")
|
print(f"[layouts] job={job_id} enabled={sorted(chosen)}")
|
||||||
|
|
||||||
|
# Auto-hook: burn each clip's Gemini hook text during the render. Off when
|
||||||
|
# the field is absent, so API/MCP/webhook callers keep their old output
|
||||||
|
# byte-for-byte; the dashboard sends an explicit value either way.
|
||||||
|
if str(auto_hook).lower() in ("1", "true", "yes"):
|
||||||
|
env["AUTO_HOOK"] = "1"
|
||||||
|
from hooks import HOOK_STYLES
|
||||||
|
if auto_hook_style in HOOK_STYLES:
|
||||||
|
env["AUTO_HOOK_STYLE"] = auto_hook_style
|
||||||
|
print(f"[auto-hook] job={job_id} style={env.get('AUTO_HOOK_STYLE', 'classic')}")
|
||||||
|
|
||||||
# Manual generation controls (discussion #65): optional clip-count target
|
# Manual generation controls (discussion #65): optional clip-count target
|
||||||
# and duration band, forwarded to the selection prompts via the same env
|
# and duration band, forwarded to the selection prompts via the same env
|
||||||
# overrides the A/B harness already reads (clip_selection.py). All three
|
# overrides the A/B harness already reads (clip_selection.py). All three
|
||||||
|
|
|
||||||
|
|
@ -655,6 +655,10 @@ function App() {
|
||||||
target_clips: data.targetClips || null,
|
target_clips: data.targetClips || null,
|
||||||
clip_min_seconds: data.clipMinSeconds || null,
|
clip_min_seconds: data.clipMinSeconds || null,
|
||||||
clip_max_seconds: data.clipMaxSeconds || null,
|
clip_max_seconds: data.clipMaxSeconds || null,
|
||||||
|
// Sent explicitly both ways: absent means off for raw API callers,
|
||||||
|
// but the dashboard always states the user's choice.
|
||||||
|
auto_hook: data.autoHook ? '1' : '0',
|
||||||
|
auto_hook_style: data.autoHook ? (data.autoHookStyle || 'classic') : null,
|
||||||
};
|
};
|
||||||
|
|
||||||
if (data.type === 'url') {
|
if (data.type === 'url') {
|
||||||
|
|
|
||||||
|
|
@ -33,12 +33,19 @@ const SIZE_OPTIONS = [
|
||||||
{ value: 'L', label: 'Large' },
|
{ value: 'L', label: 'Large' },
|
||||||
];
|
];
|
||||||
|
|
||||||
export default function HookModal({ isOpen, onClose, onGenerate, isProcessing, videoUrl, initialText, durationInSeconds, existingSubtitles }) {
|
// Last-used hook settings, restored on the next open (style always reset to
|
||||||
|
// classic otherwise, which users read as the picker being broken).
|
||||||
|
function loadHookPrefs() {
|
||||||
|
try { return JSON.parse(localStorage.getItem('os_hook_prefs')) || {}; } catch { return {}; }
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function HookModal({ isOpen, onClose, onGenerate, isProcessing, videoUrl, initialText, durationInSeconds, existingSubtitles, hasCaptions, serverRender, burnedHook }) {
|
||||||
|
const prefs = loadHookPrefs();
|
||||||
const [text, setText] = useState(initialText || 'POV: You are using the viral hook feature');
|
const [text, setText] = useState(initialText || 'POV: You are using the viral hook feature');
|
||||||
const [position, setPosition] = useState('top');
|
const [position, setPosition] = useState(prefs.position || 'top');
|
||||||
const [size, setSize] = useState('M');
|
const [size, setSize] = useState(prefs.size || 'M');
|
||||||
const [style, setStyle] = useState('classic');
|
const [style, setStyle] = useState(prefs.style || 'classic');
|
||||||
const [entranceAnimation, setEntranceAnimation] = useState('spring');
|
const [entranceAnimation, setEntranceAnimation] = useState(prefs.entranceAnimation || 'spring');
|
||||||
const [displayDuration, setDisplayDuration] = useState(5);
|
const [displayDuration, setDisplayDuration] = useState(5);
|
||||||
|
|
||||||
if (!isOpen) return null;
|
if (!isOpen) return null;
|
||||||
|
|
@ -159,6 +166,12 @@ export default function HookModal({ isOpen, onClose, onGenerate, isProcessing, v
|
||||||
onChange={setPosition}
|
onChange={setPosition}
|
||||||
size="sm"
|
size="sm"
|
||||||
/>
|
/>
|
||||||
|
{position === 'bottom' && hasCaptions && (
|
||||||
|
<p className="text-[11px] text-warn mt-1.5 leading-relaxed">
|
||||||
|
This clip has captions near the bottom — the hook may
|
||||||
|
overlap them (and TikTok's UI). Top is the safe zone.
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Size Control */}
|
{/* Size Control */}
|
||||||
|
|
@ -173,7 +186,7 @@ export default function HookModal({ isOpen, onClose, onGenerate, isProcessing, v
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Entrance Animation (new) */}
|
{/* Entrance Animation (new) */}
|
||||||
<div>
|
<div className={serverRender ? 'opacity-50' : ''}>
|
||||||
<p className="eyebrow mb-2">Entrance</p>
|
<p className="eyebrow mb-2">Entrance</p>
|
||||||
<SegmentedControl
|
<SegmentedControl
|
||||||
options={ENTRANCE_OPTIONS}
|
options={ENTRANCE_OPTIONS}
|
||||||
|
|
@ -182,6 +195,12 @@ export default function HookModal({ isOpen, onClose, onGenerate, isProcessing, v
|
||||||
columns={2}
|
columns={2}
|
||||||
size="sm"
|
size="sm"
|
||||||
/>
|
/>
|
||||||
|
{serverRender && (
|
||||||
|
<p className="text-[11px] text-muted mt-1.5 leading-relaxed">
|
||||||
|
This clip re-renders on the server, where the hook is
|
||||||
|
static — the entrance animation won't apply.
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Display Duration (new) */}
|
{/* Display Duration (new) */}
|
||||||
|
|
@ -204,6 +223,13 @@ export default function HookModal({ isOpen, onClose, onGenerate, isProcessing, v
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{burnedHook && (
|
||||||
|
<div className="p-3 border border-rule rounded-input text-xs text-warn">
|
||||||
|
This clip already has a hook burned in ("{burnedHook}").
|
||||||
|
Adding another will stack on top of it.
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
<div className="p-3 border border-rule rounded-input text-xs text-muted">
|
<div className="p-3 border border-rule rounded-input text-xs text-muted">
|
||||||
Tip: keep it short and punchy. Using "POV:" or specific questions works best for retention.
|
Tip: keep it short and punchy. Using "POV:" or specific questions works best for retention.
|
||||||
</div>
|
</div>
|
||||||
|
|
@ -214,11 +240,18 @@ export default function HookModal({ isOpen, onClose, onGenerate, isProcessing, v
|
||||||
cancel
|
cancel
|
||||||
</button>
|
</button>
|
||||||
<button
|
<button
|
||||||
onClick={() => onGenerate({
|
onClick={() => {
|
||||||
text, position, size, style,
|
try {
|
||||||
// Remotion data
|
localStorage.setItem('os_hook_prefs', JSON.stringify({
|
||||||
remotion: hookConfig,
|
style, position, size, entranceAnimation,
|
||||||
})}
|
}));
|
||||||
|
} catch { /* ignore */ }
|
||||||
|
onGenerate({
|
||||||
|
text, position, size, style,
|
||||||
|
// Remotion data
|
||||||
|
remotion: hookConfig,
|
||||||
|
});
|
||||||
|
}}
|
||||||
disabled={isProcessing || !text.trim()}
|
disabled={isProcessing || !text.trim()}
|
||||||
className="btn-primary flex-1"
|
className="btn-primary flex-1"
|
||||||
>
|
>
|
||||||
|
|
|
||||||
|
|
@ -22,6 +22,14 @@ export default function MediaInput({ onProcess, isProcessing }) {
|
||||||
const [targetClips, setTargetClips] = useState('');
|
const [targetClips, setTargetClips] = useState('');
|
||||||
const [clipMinSeconds, setClipMinSeconds] = useState('');
|
const [clipMinSeconds, setClipMinSeconds] = useState('');
|
||||||
const [clipMaxSeconds, setClipMaxSeconds] = useState('');
|
const [clipMaxSeconds, setClipMaxSeconds] = useState('');
|
||||||
|
// Auto-hook: burn the AI hook text into every clip. On by default; the
|
||||||
|
// choice persists so turning it off sticks across sessions.
|
||||||
|
const [autoHook, setAutoHook] = useState(() => {
|
||||||
|
try { return localStorage.getItem('os_auto_hook') !== '0'; } catch { return true; }
|
||||||
|
});
|
||||||
|
const [autoHookStyle, setAutoHookStyle] = useState(() => {
|
||||||
|
try { return localStorage.getItem('os_auto_hook_style') || 'classic'; } catch { return 'classic'; }
|
||||||
|
});
|
||||||
const infoRef = useRef(null);
|
const infoRef = useRef(null);
|
||||||
|
|
||||||
// Close the compatibility popover on any outside click.
|
// Close the compatibility popover on any outside click.
|
||||||
|
|
@ -68,7 +76,13 @@ export default function MediaInput({ onProcess, isProcessing }) {
|
||||||
targetClips: targetClips || null,
|
targetClips: targetClips || null,
|
||||||
clipMinSeconds: clipMinSeconds || null,
|
clipMinSeconds: clipMinSeconds || null,
|
||||||
clipMaxSeconds: clipMaxSeconds || null,
|
clipMaxSeconds: clipMaxSeconds || null,
|
||||||
|
autoHook,
|
||||||
|
autoHookStyle,
|
||||||
};
|
};
|
||||||
|
try {
|
||||||
|
localStorage.setItem('os_auto_hook', autoHook ? '1' : '0');
|
||||||
|
localStorage.setItem('os_auto_hook_style', autoHookStyle);
|
||||||
|
} catch { /* ignore */ }
|
||||||
if (mode === 'url' && url) {
|
if (mode === 'url' && url) {
|
||||||
onProcess({ type: 'url', payload: url, acknowledged: true, outputFormat, ...advanced });
|
onProcess({ type: 'url', payload: url, acknowledged: true, outputFormat, ...advanced });
|
||||||
} else if (mode === 'file' && file) {
|
} else if (mode === 'file' && file) {
|
||||||
|
|
@ -230,7 +244,7 @@ export default function MediaInput({ onProcess, isProcessing }) {
|
||||||
>
|
>
|
||||||
<ChevronDown size={14} className={`transition-transform ${showAdvanced ? 'rotate-180' : ''}`} />
|
<ChevronDown size={14} className={`transition-transform ${showAdvanced ? 'rotate-180' : ''}`} />
|
||||||
advanced options
|
advanced options
|
||||||
{(targetClips || clipMinSeconds || clipMaxSeconds) && (
|
{(targetClips || clipMinSeconds || clipMaxSeconds || !autoHook) && (
|
||||||
<span className="text-brass">·</span>
|
<span className="text-brass">·</span>
|
||||||
)}
|
)}
|
||||||
</button>
|
</button>
|
||||||
|
|
@ -270,6 +284,31 @@ export default function MediaInput({ onProcess, isProcessing }) {
|
||||||
Targets, not guarantees: the AI returns fewer clips when the
|
Targets, not guarantees: the AI returns fewer clips when the
|
||||||
material doesn't hold them. Leave blank to let it decide.
|
material doesn't hold them. Leave blank to let it decide.
|
||||||
</p>
|
</p>
|
||||||
|
<div className="col-span-3 flex items-center justify-between gap-3 pt-1 border-t border-rule">
|
||||||
|
<label className="flex items-center gap-2 text-xs text-ink2 cursor-pointer select-none">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={autoHook}
|
||||||
|
onChange={(e) => setAutoHook(e.target.checked)}
|
||||||
|
className="accent-[var(--color-accent)] cursor-pointer"
|
||||||
|
/>
|
||||||
|
auto hook titles on clips
|
||||||
|
</label>
|
||||||
|
{autoHook && (
|
||||||
|
<select
|
||||||
|
value={autoHookStyle}
|
||||||
|
onChange={(e) => setAutoHookStyle(e.target.value)}
|
||||||
|
className="input-field !w-auto text-xs py-1.5"
|
||||||
|
>
|
||||||
|
<option value="classic">Classic</option>
|
||||||
|
<option value="dark">Dark</option>
|
||||||
|
<option value="yellow">Yellow</option>
|
||||||
|
<option value="red">Red</option>
|
||||||
|
<option value="outline">Outline</option>
|
||||||
|
<option value="outline_yellow">Outline+</option>
|
||||||
|
</select>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
|
||||||
|
|
@ -1004,6 +1004,9 @@ export default function ResultCard({ clip, index, jobId, durableUrl, uploadPostK
|
||||||
initialText={clip.viral_hook_text}
|
initialText={clip.viral_hook_text}
|
||||||
durationInSeconds={clip.end && clip.start ? clip.end - clip.start : 30}
|
durationInSeconds={clip.end && clip.start ? clip.end - clip.start : 30}
|
||||||
existingSubtitles={activeLayers.subtitles}
|
existingSubtitles={activeLayers.subtitles}
|
||||||
|
hasCaptions={!!activeLayers.subtitles || /(^|_)subtitled_/.test(serverVideoFile || '')}
|
||||||
|
serverRender={hasServerBurns}
|
||||||
|
burnedHook={clip.auto_hook?.text}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<TranslateModal
|
<TranslateModal
|
||||||
|
|
|
||||||
|
|
@ -20,10 +20,12 @@ const SIZE_SCALE: Record<string, number> = {
|
||||||
L: 1.3,
|
L: 1.3,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Percentages must match hooks.py's overlay_y math (top 20% / bottom 70%),
|
||||||
|
// or the preview drifts from what the server path renders.
|
||||||
const POSITION_STYLE: Record<string, React.CSSProperties> = {
|
const POSITION_STYLE: Record<string, React.CSSProperties> = {
|
||||||
top: { top: "18%", bottom: "auto" },
|
top: { top: "20%", bottom: "auto" },
|
||||||
center: { top: "50%", bottom: "auto", transform: "translateY(-50%)" },
|
center: { top: "50%", bottom: "auto", transform: "translateY(-50%)" },
|
||||||
bottom: { top: "68%", bottom: "auto" },
|
bottom: { top: "70%", bottom: "auto" },
|
||||||
};
|
};
|
||||||
|
|
||||||
// Must mirror hooks.py HOOK_STYLES (the server-side FFmpeg fallback).
|
// Must mirror hooks.py HOOK_STYLES (the server-side FFmpeg fallback).
|
||||||
|
|
|
||||||
88
hooks.py
88
hooks.py
|
|
@ -37,28 +37,41 @@ _EMOJI_RE = re.compile(
|
||||||
"]+"
|
"]+"
|
||||||
)
|
)
|
||||||
|
|
||||||
# Emoji-capable fonts, probed at runtime (Windows, WSL, Linux/Docker).
|
# Emoji-capable fonts, probed at runtime (Windows, WSL, Linux/Docker, macOS).
|
||||||
_EMOJI_FONT_CANDIDATES = [
|
_EMOJI_FONT_CANDIDATES = [
|
||||||
"C:\\Windows\\Fonts\\seguiemj.ttf",
|
"C:\\Windows\\Fonts\\seguiemj.ttf",
|
||||||
"/mnt/c/Windows/Fonts/seguiemj.ttf",
|
"/mnt/c/Windows/Fonts/seguiemj.ttf",
|
||||||
"/usr/share/fonts/truetype/noto/NotoColorEmoji.ttf",
|
"/usr/share/fonts/truetype/noto/NotoColorEmoji.ttf",
|
||||||
"/usr/share/fonts/noto-emoji/NotoColorEmoji.ttf",
|
"/usr/share/fonts/noto-emoji/NotoColorEmoji.ttf",
|
||||||
|
"/System/Library/Fonts/Apple Color Emoji.ttc",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
def _load_emoji_font(font_size):
|
# Bitmap strike sizes color-emoji fonts ship with. NotoColorEmoji (the font
|
||||||
"""Return an emoji-capable font at the requested size, or None.
|
# the Docker image installs) ONLY loads at its strike size — asking for an
|
||||||
|
# arbitrary size raises "invalid pixel size" — so glyphs are rendered at the
|
||||||
|
# native size and rescaled at draw time.
|
||||||
|
_EMOJI_BITMAP_SIZES = [109, 128, 136, 160, 96, 72, 64, 32]
|
||||||
|
|
||||||
Fonts that only support a fixed bitmap size (e.g. NotoColorEmoji) fail to
|
|
||||||
load at arbitrary sizes; those are treated as unavailable rather than
|
def _load_emoji_font(font_size):
|
||||||
breaking the layout with wrongly-sized glyphs."""
|
"""Return (font, native_size) for an emoji-capable font, or None.
|
||||||
|
|
||||||
|
native_size == font_size for scalable fonts (Segoe UI Emoji); for
|
||||||
|
fixed-bitmap fonts (NotoColorEmoji) it is the strike size the font
|
||||||
|
actually loaded at, and the renderer scales glyphs down from it."""
|
||||||
for path in _EMOJI_FONT_CANDIDATES:
|
for path in _EMOJI_FONT_CANDIDATES:
|
||||||
if not os.path.exists(path):
|
if not os.path.exists(path):
|
||||||
continue
|
continue
|
||||||
try:
|
try:
|
||||||
return ImageFont.truetype(path, font_size)
|
return ImageFont.truetype(path, font_size), font_size
|
||||||
except Exception:
|
except Exception:
|
||||||
continue
|
pass
|
||||||
|
for native in _EMOJI_BITMAP_SIZES:
|
||||||
|
try:
|
||||||
|
return ImageFont.truetype(path, native), native
|
||||||
|
except Exception:
|
||||||
|
continue
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -76,28 +89,63 @@ def _split_emoji_runs(text):
|
||||||
return runs
|
return runs
|
||||||
|
|
||||||
|
|
||||||
|
def _emoji_scale(font, emoji_font):
|
||||||
|
"""Draw-time scale factor from the emoji font's native size to the text
|
||||||
|
size. 1.0 for scalable emoji fonts; < 1 for fixed-bitmap strikes."""
|
||||||
|
efont, native = emoji_font
|
||||||
|
target = getattr(font, "size", native)
|
||||||
|
return target / float(native) if native else 1.0
|
||||||
|
|
||||||
|
|
||||||
def _measure_width(draw, text, font, emoji_font):
|
def _measure_width(draw, text, font, emoji_font):
|
||||||
"""Pixel width of a line, measuring emoji runs with the emoji font."""
|
"""Pixel width of a line, measuring emoji runs with the emoji font.
|
||||||
|
|
||||||
|
emoji_font is the (font, native_size) pair from _load_emoji_font, or None."""
|
||||||
width = 0.0
|
width = 0.0
|
||||||
for is_emoji, chunk in _split_emoji_runs(text):
|
for is_emoji, chunk in _split_emoji_runs(text):
|
||||||
use_font = emoji_font if (is_emoji and emoji_font) else font
|
if is_emoji and emoji_font:
|
||||||
width += draw.textlength(chunk, font=use_font)
|
width += (draw.textlength(chunk, font=emoji_font[0])
|
||||||
|
* _emoji_scale(font, emoji_font))
|
||||||
|
else:
|
||||||
|
width += draw.textlength(chunk, font=font)
|
||||||
return width
|
return width
|
||||||
|
|
||||||
|
|
||||||
def _draw_mixed(draw, xy, text, font, emoji_font, fill, outline=None):
|
def _render_emoji_chunk(chunk, emoji_font, scale, fill):
|
||||||
"""Draw a line, rendering emoji runs with the emoji font (in color if
|
"""Rasterize an emoji run at the font's native size, scaled to the text
|
||||||
supported). outline: optional (color, px) stroke drawn under the text."""
|
size. Returns an RGBA image ready to alpha-composite, or None."""
|
||||||
|
efont, native = emoji_font
|
||||||
|
probe = ImageDraw.Draw(Image.new('RGBA', (1, 1)))
|
||||||
|
w = int(probe.textlength(chunk, font=efont))
|
||||||
|
if w <= 0:
|
||||||
|
return None
|
||||||
|
# Emoji glyphs can overshoot the em box slightly; 1.3x covers it.
|
||||||
|
tmp = Image.new('RGBA', (w, int(native * 1.3)), (0, 0, 0, 0))
|
||||||
|
d = ImageDraw.Draw(tmp)
|
||||||
|
try:
|
||||||
|
d.text((0, 0), chunk, font=efont, embedded_color=True)
|
||||||
|
except TypeError:
|
||||||
|
d.text((0, 0), chunk, font=efont, fill=fill)
|
||||||
|
if scale == 1.0:
|
||||||
|
return tmp
|
||||||
|
return tmp.resize((max(int(w * scale), 1), max(int(tmp.height * scale), 1)),
|
||||||
|
Image.LANCZOS)
|
||||||
|
|
||||||
|
|
||||||
|
def _draw_mixed(img, draw, xy, text, font, emoji_font, fill, outline=None):
|
||||||
|
"""Draw a line onto img, rendering emoji runs with the emoji font (in
|
||||||
|
color if supported, rescaled when the font is a fixed-size bitmap).
|
||||||
|
outline: optional (color, px) stroke drawn under the text."""
|
||||||
x, y = xy
|
x, y = xy
|
||||||
stroke_w = outline[1] if outline else 0
|
stroke_w = outline[1] if outline else 0
|
||||||
stroke_fill = outline[0] if outline else None
|
stroke_fill = outline[0] if outline else None
|
||||||
for is_emoji, chunk in _split_emoji_runs(text):
|
for is_emoji, chunk in _split_emoji_runs(text):
|
||||||
if is_emoji and emoji_font:
|
if is_emoji and emoji_font:
|
||||||
try:
|
scale = _emoji_scale(font, emoji_font)
|
||||||
draw.text((x, y), chunk, font=emoji_font, embedded_color=True)
|
rendered = _render_emoji_chunk(chunk, emoji_font, scale, fill)
|
||||||
except TypeError:
|
if rendered is not None:
|
||||||
draw.text((x, y), chunk, font=emoji_font, fill=fill)
|
img.alpha_composite(rendered, (int(x), int(y)))
|
||||||
x += draw.textlength(chunk, font=emoji_font)
|
x += draw.textlength(chunk, font=emoji_font[0]) * scale
|
||||||
else:
|
else:
|
||||||
if stroke_w:
|
if stroke_w:
|
||||||
draw.text((x, y), chunk, font=font, fill=fill,
|
draw.text((x, y), chunk, font=font, fill=fill,
|
||||||
|
|
@ -314,7 +362,7 @@ def create_hook_image(text, target_width, output_image_path="hook_overlay.png",
|
||||||
x = 20 + int(box_width - line_w) // 2
|
x = 20 + int(box_width - line_w) // 2
|
||||||
|
|
||||||
# Draw text in the style's color (emoji runs use the emoji font)
|
# Draw text in the style's color (emoji runs use the emoji font)
|
||||||
_draw_mixed(draw_final, (x, current_y), line, font, emoji_font,
|
_draw_mixed(img, draw_final, (x, current_y), line, font, emoji_font,
|
||||||
fill=text_fill, outline=outline)
|
fill=text_fill, outline=outline)
|
||||||
|
|
||||||
current_y += line_h + line_spacing
|
current_y += line_h + line_spacing
|
||||||
|
|
|
||||||
56
main.py
56
main.py
|
|
@ -72,7 +72,7 @@ OUTPUT — RETURN ONLY VALID JSON (no markdown, no comments). Order clips by pre
|
||||||
"video_description_for_tiktok": "<description for TikTok oriented to get views>",
|
"video_description_for_tiktok": "<description for TikTok oriented to get views>",
|
||||||
"video_description_for_instagram": "<description for Instagram 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>",
|
"video_title_for_youtube_short": "<title for YouTube Short oriented to get views 100 chars max>",
|
||||||
"viral_hook_text": "<SHORT punchy text overlay (max 10 words). MUST BE IN THE SAME LANGUAGE AS THE VIDEO TRANSCRIPT. Examples: 'POV: You realized...', 'Did you know?', 'Stop doing this!'>"
|
"viral_hook_text": "<SHORT punchy text overlay (max 10 words) with 1-2 fitting emojis. MUST BE IN THE SAME LANGUAGE AS THE VIDEO TRANSCRIPT. Examples: 'POV: You realized... 😳', 'Did you know? 🤯', 'Stop doing this! 🚫'>"
|
||||||
}}
|
}}
|
||||||
]
|
]
|
||||||
}}
|
}}
|
||||||
|
|
@ -882,6 +882,47 @@ def auto_caption_clip(clip_path, transcript, clip_start, clip_end):
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def auto_hook_clip(clip_path, clip):
|
||||||
|
"""Burn the clip's Gemini hook text into the finished clip (AUTO_HOOK=1).
|
||||||
|
|
||||||
|
In-place on the canonical clip file, BEFORE the watermark and captions
|
||||||
|
layers, so every existing derived-name convention (subtitled_/recut_
|
||||||
|
walk-backs, R2 archive, restore after redeploy) keeps working untouched.
|
||||||
|
|
||||||
|
Returns the burned hook config dict, or None when skipped or failed — a
|
||||||
|
hook problem must never cost the user the clip itself (same fail-open
|
||||||
|
contract as auto_caption_clip)."""
|
||||||
|
text = (clip.get('viral_hook_text') or '').strip()
|
||||||
|
if not text:
|
||||||
|
return None
|
||||||
|
style = os.environ.get("AUTO_HOOK_STYLE", "classic")
|
||||||
|
try:
|
||||||
|
seconds = float(os.environ.get("AUTO_HOOK_SECONDS", "5"))
|
||||||
|
except ValueError:
|
||||||
|
seconds = 5.0
|
||||||
|
try:
|
||||||
|
from hooks import add_hook_to_video, HOOK_STYLES
|
||||||
|
if style not in HOOK_STYLES:
|
||||||
|
style = "classic"
|
||||||
|
output_dir = os.path.dirname(clip_path)
|
||||||
|
tmp_path = os.path.join(
|
||||||
|
output_dir, f"temp_autohook_{uuid.uuid4().hex[:8]}.mp4")
|
||||||
|
try:
|
||||||
|
add_hook_to_video(clip_path, text, tmp_path, position="top",
|
||||||
|
duration=seconds, style=style)
|
||||||
|
os.replace(tmp_path, clip_path)
|
||||||
|
finally:
|
||||||
|
if os.path.exists(tmp_path):
|
||||||
|
os.remove(tmp_path)
|
||||||
|
print(f" 🪝 Hook burned ({style}, {seconds:g}s): {text}")
|
||||||
|
return {"text": text, "style": style, "position": "top",
|
||||||
|
"duration_seconds": seconds}
|
||||||
|
except Exception as e:
|
||||||
|
print(f" ⚠️ Auto-hook failed ({type(e).__name__}: {e}) — "
|
||||||
|
f"delivering the clip without it.")
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
def render_clip(input_video, final_output_video, output_format="auto",
|
def render_clip(input_video, final_output_video, output_format="auto",
|
||||||
force_strategy=None, crop_overrides=None):
|
force_strategy=None, crop_overrides=None):
|
||||||
"""Route a cut clip through the right renderer for the chosen output format.
|
"""Route a cut clip through the right renderer for the chosen output format.
|
||||||
|
|
@ -1586,6 +1627,13 @@ if __name__ == '__main__':
|
||||||
subprocess.run(cut_command, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
|
subprocess.run(cut_command, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
|
||||||
|
|
||||||
success = render_clip(clip_temp_path, clip_final_path, output_format)
|
success = render_clip(clip_temp_path, clip_final_path, output_format)
|
||||||
|
# Hook first, under the watermark, and captions always
|
||||||
|
# last. Each worker writes only its own clip dict, so the
|
||||||
|
# re-dump after the pool is race-free.
|
||||||
|
if success and os.environ.get("AUTO_HOOK") == "1":
|
||||||
|
burned = auto_hook_clip(clip_final_path, clip)
|
||||||
|
if burned:
|
||||||
|
clip['auto_hook'] = burned
|
||||||
if success and os.environ.get("WATERMARK") == "1":
|
if success and os.environ.get("WATERMARK") == "1":
|
||||||
apply_watermark(clip_final_path)
|
apply_watermark(clip_final_path)
|
||||||
if success:
|
if success:
|
||||||
|
|
@ -1610,6 +1658,12 @@ if __name__ == '__main__':
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f" ❌ Clip {i+1} failed: {type(e).__name__}: {e}")
|
print(f" ❌ Clip {i+1} failed: {type(e).__name__}: {e}")
|
||||||
|
|
||||||
|
# Persist per-clip render results added by the workers (auto_hook)
|
||||||
|
# so the editor can see what is already burned into each clip.
|
||||||
|
if any('auto_hook' in c for c in shorts):
|
||||||
|
with open(metadata_file, 'w') as f:
|
||||||
|
json.dump(clips_data, f, indent=2)
|
||||||
|
|
||||||
# Clean up original if requested
|
# Clean up original if requested
|
||||||
if args.url and not args.keep_original and os.path.exists(input_video):
|
if args.url and not args.keep_original and os.path.exists(input_video):
|
||||||
os.remove(input_video)
|
os.remove(input_video)
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue