AFC_TTS / clips_engine.py
afcpk18's picture
Upload 8 files
6a16fb7 verified
Raw History Blame Contribute Delete
46.3 kB
import os
import io
import re
import glob
import html
import json
import time
import shutil
import zipfile
import tarfile
import platform
import tempfile
import threading
import subprocess
import numpy as np
import requests
from PIL import Image
import voice_engine as ve
import video_engine as vid
VERSION = 12
TOOLS = os.path.join(os.path.expanduser("~"), ".cache", "afc_tools")
THEMES = {
"AFC brand": {"primary": "#7A1E2B", "accent": "#C9A227", "dark": "#14213D", "light": "#FAF7F2"},
"Clean teal": {"primary": "#0f766e", "accent": "#fbbf24", "dark": "#0b3b38", "light": "#f0fdfa"},
"Midnight neon": {"primary": "#4f46e5", "accent": "#22d3ee", "dark": "#0f172a", "light": "#f8fafc"},
}
THEME_CHOICES = list(THEMES) + ["Custom"]
STYLES = ["Karaoke pop", "Clean bar", "Kinetic center", "Brand card"]
POSITIONS = ["Auto", "Bottom (safe)", "Middle", "Top"]
INTROS = ["Hook line", "Title", "None"]
ENGINE_CHOICES = ["Auto (HyperFrames → FFmpeg)", "HyperFrames only", "FFmpeg only"]
CAP_MODES = ["Auto", "Whisper word-sync", "Script timing"]
SRT_LANGS = ["English", "Urdu", "Pashto"]
PLATFORMS = {
"TikTok / Reels / Shorts": {"aspects": ["9:16"], "target": 25, "style": "Karaoke pop", "pos": "Bottom (safe)"},
"Instagram feed post": {"aspects": ["4:5"], "target": 30, "style": "Karaoke pop", "pos": "Bottom (safe)"},
"YouTube video": {"aspects": ["16:9"], "target": 45, "style": "Clean bar", "pos": "Bottom (safe)"},
"Facebook / LinkedIn": {"aspects": ["1:1"], "target": 30, "style": "Clean bar", "pos": "Bottom (safe)"},
"WhatsApp status (short)": {"aspects": ["9:16"], "target": 15, "style": "Kinetic center", "pos": "Middle"},
"All formats": {"aspects": ["9:16", "4:5", "1:1", "16:9"], "target": 30, "style": "Karaoke pop", "pos": "Bottom (safe)"},
}
PUNCT_END = re.compile(r"[۔؟!?.]$")
PER_PAGE = {"Karaoke pop": 4, "Clean bar": 6, "Kinetic center": 2, "Brand card": 5}
def sh(cmd, **kw):
return subprocess.run(cmd, capture_output=True, text=True, **kw)
def norm_hex(c, default):
if not c:
return default
c = c.strip()
if c.startswith("#"):
return "#" + "".join(ch * 2 for ch in c[1:]) if len(c) == 4 else (c[:7] if len(c) >= 7 else default)
nums = re.findall(r"[\d.]+", c)
return "#%02X%02X%02X" % tuple(int(float(n)) for n in nums[:3]) if c.startswith("rgb") and len(nums) >= 3 else default
def hex_rgb(h):
h = h.lstrip("#")
return tuple(int(h[i:i + 2], 16) for i in (0, 2, 4))
def ass_color(h, alpha=0):
r, g, b = hex_rgb(h)
return f"&H{alpha:02X}{b:02X}{g:02X}{r:02X}"
def ass_bgr(h):
r, g, b = hex_rgb(h)
return f"&H{b:02X}{g:02X}{r:02X}&"
def ass_time(t):
cs = int(round(max(0.0, t) * 100))
return f"{cs // 360000}:{cs // 6000 % 60:02d}:{cs // 100 % 60:02d}.{cs % 100:02d}"
def ass_safe(s):
return (s or "").replace("{", "(").replace("}", ")").replace("\n", " ")
# ============================ HyperFrames ============================
_HF = {"bin": None, "env": None, "ready": False, "log": "", "thread": None}
def _log(msg):
_HF["log"] += msg + "\n"
def _node_major(node):
try:
return int(sh([node, "-v"], timeout=20).stdout.strip().lstrip("v").split(".")[0])
except Exception:
return 0
def _ensure_node():
n = shutil.which("node")
if n and _node_major(n) >= 22:
return os.path.dirname(n)
for d in glob.glob(os.path.join(TOOLS, "node-v22*", "bin")):
if _node_major(os.path.join(d, "node")) >= 22:
return d
arch = "x64" if platform.machine().lower() in ("x86_64", "amd64") else "arm64"
base = "https://nodejs.org/dist/latest-v22.x/"
m = re.search(rf"(node-v22\.\d+\.\d+-linux-{arch}\.tar\.xz)", requests.get(base + "SHASUMS256.txt", timeout=30).text)
if not m:
raise RuntimeError("Could not find a Node 22 download.")
_log(f"Downloading {m.group(1)} …")
data = requests.get(base + m.group(1), timeout=300).content
os.makedirs(TOOLS, exist_ok=True)
with tarfile.open(fileobj=io.BytesIO(data), mode="r:xz") as t:
t.extractall(TOOLS)
return os.path.join(TOOLS, m.group(1)[:-len(".tar.xz")], "bin")
def _apt_hint(text):
m = re.search(r"apt-get install -y ([\w.+\- ]+)", text or "")
return m.group(1).strip() if m else ""
def setup_hyperframes(progress=None):
_HF.update(ready=False, log="")
P = progress or (lambda *a, **k: None)
try:
P(0.05, desc="Getting Node.js 22…")
node_bin = _ensure_node()
env = os.environ.copy()
env.update(PATH=node_bin + os.pathsep + env.get("PATH", ""), CONTAINER="true", CI="1", NO_COLOR="1")
if not shutil.which("unzip"):
_log("⚠️ 'unzip' is missing: add it to packages.txt.")
prefix = os.path.join(TOOLS, "hf")
os.makedirs(prefix, exist_ok=True)
P(0.25, desc="Installing HyperFrames…")
r = sh([os.path.join(node_bin, "npm"), "install", "--prefix", prefix, "hyperframes", "--no-audit", "--no-fund"], env=env, timeout=900)
_log((r.stdout + r.stderr)[-400:])
hf = os.path.join(prefix, "node_modules", ".bin", "hyperframes")
if not os.path.exists(hf):
raise RuntimeError("npm could not install hyperframes (see log).")
sh([hf, "telemetry", "disable"], env=env, timeout=60)
P(0.55, desc="Downloading headless Chrome…")
r = sh([hf, "browser", "ensure"], env=env, timeout=900)
_log((r.stdout + r.stderr)[-500:])
if r.returncode != 0:
raise RuntimeError("Chrome download failed (see log).")
_HF.update(bin=hf, env=env, ready=True)
P(0.85, desc="Testing a real render…")
try:
_log("✅ " + selftest_hyperframes(force=True)) # 'ready' only if a real render works
except Exception as e:
_HF["ready"] = False
raise RuntimeError(str(e))
except Exception as e:
_log(f"❌ {str(e)[:500]}")
return _HF["ready"], _HF["log"]
def hf_autosetup():
t = _HF.get("thread")
if os.environ.get("HF_AUTOSETUP", "1") == "0" or _HF["ready"] or (t and t.is_alive()):
return
_HF["thread"] = threading.Thread(target=setup_hyperframes, daemon=True)
_HF["thread"].start()
def hf_busy():
t = _HF.get("thread")
return bool(t and t.is_alive())
def hf_brief():
if _HF["ready"]:
return "ready (a real test render passed)"
if hf_busy():
return "installing in the background… FFmpeg renders until then"
return "not ready (FFmpeg renders instead). " + (_HF["log"].strip().splitlines()[-1][:160] if _HF["log"].strip() else "")
def hf_status():
ff = shutil.which("ffmpeg")
icon = "✅" if _HF["ready"] else ("⏳" if hf_busy() else "⚠️")
L = [f"ℹ️ clips_engine version {VERSION}", f"{icon} HyperFrames: {hf_brief()}", f"{'✅' if ff else '❌'} FFmpeg " + ("found" if ff else "missing")]
if not _HF["ready"] and _HF["log"]:
L.append("```\n" + _HF["log"][-800:] + "\n```")
return "\n\n".join(L)
def hf_render(proj, quality, fps):
cmd = [_HF["bin"], "render", "--output", "out.mp4", "--quality", quality, "--fps", str(fps)]
try:
r = sh(cmd, cwd=proj, env=_HF["env"], timeout=900)
except subprocess.TimeoutExpired:
return False, "", "render timed out"
out = os.path.join(proj, "out.mp4")
return (r.returncode == 0 and os.path.exists(out) and os.path.getsize(out) > 2000), out, (r.stdout + "\n" + r.stderr)[-1500:]
# ============================ word timing (Whisper captions) ============================
def whisper_words(audio_path, lang):
return ve.whisper_words(audio_path, lang) # GPU Whisper first, CPU Whisper as the automatic fallback
def rhythm_align(script_words, ww):
cs = np.concatenate([[0.0], np.cumsum([max(1, len(w)) for w in script_words])])
cw = np.concatenate([[0.0], np.cumsum([max(1, len(t)) for t, _, _ in ww])])
xs, ts = [], []
for i, (_, s, e) in enumerate(ww):
xs += [cw[i], cw[i + 1] - 0.01]
ts += [s, max(e, s + 0.02)]
ts = np.maximum.accumulate(np.array(ts))
fx = cs / cs[-1] * cw[-1]
out = []
for j, w in enumerate(script_words):
s = float(np.interp(fx[j], xs, ts))
e = float(np.interp(fx[j + 1] - 0.01, xs, ts))
out.append([w, s, max(e, s + 0.08)])
for j in range(len(out) - 1):
if out[j + 1][1] > out[j][1] + 0.05:
out[j][2] = min(out[j][2], out[j + 1][1])
return [tuple(x) for x in out]
def words_from_cues(cues):
cw = []
for s, e, text, _ in cues:
ws = text.split()
wts = [len(w) + (4 if re.search(r"[۔؟!?.،,]$", w) else 0) for w in ws]
tot, cur, lst = sum(wts) or 1, s, []
for w, x in zip(ws, wts):
d = (e - s) * x / tot
lst.append((w, cur, cur + d))
cur += d
cw.append(lst)
return cw
def recut(cues, words):
out, cw, i = [], [], 0
for _, _, text, emo in cues:
n = len(text.split())
grp = words[i:i + n]
i += n
if grp:
out.append((grp[0][1], grp[-1][2], text, emo))
cw.append(grp)
return out, cw
def cues_from_words(words):
cues, cw, cur = [], [], []
for i, (w, s, e) in enumerate(words):
cur.append((w, s, e))
gap = words[i + 1][1] - e if i + 1 < len(words) else 9
if PUNCT_END.search(w) or gap > 0.7 or len(cur) >= 25:
cues.append((cur[0][1], cur[-1][2], " ".join(x[0] for x in cur), "neutral"))
cw.append(cur)
cur = []
if cur:
cues.append((cur[0][1], cur[-1][2], " ".join(x[0] for x in cur), "neutral"))
cw.append(cur)
return cues, cw
def make_pages(words, per_page):
pages, cur = [], []
for i, (w, s, e) in enumerate(words):
cur.append((w, s, e))
gap = words[i + 1][1] - e if i + 1 < len(words) else 9
if len(cur) >= per_page or PUNCT_END.search(w) or gap > 0.55:
pages.append(cur)
cur = []
if cur:
pages.append(cur)
return pages
def srt_time(t, sep):
ms = int(round(max(0, t) * 1000))
return f"{ms // 3600000:02d}:{ms // 60000 % 60:02d}:{ms // 1000 % 60:02d}{sep}{ms % 1000:03d}"
def write_captions(words, out_dir):
blocks = make_pages(words, 7)
srt = "\n".join(f"{i}\n{srt_time(b[0][1], ',')} --> {srt_time(b[-1][2], ',')}\n{' '.join(w[0] for w in b)}\n" for i, b in enumerate(blocks, 1))
vtt = "WEBVTT\n\n" + "\n".join(f"{srt_time(b[0][1], '.')} --> {srt_time(b[-1][2], '.')}\n{' '.join(w[0] for w in b)}\n" for b in blocks)
js = [{"id": f"w{i}", "text": w, "start": round(s, 3), "end": round(e, 3)} for i, (w, s, e) in enumerate(words)]
paths = []
for name, content in (("captions.srt", srt), ("captions.vtt", vtt), ("transcript.json", json.dumps(js, ensure_ascii=False, indent=1))):
p = os.path.join(out_dir, name)
with open(p, "w", encoding="utf-8") as f:
f.write(content)
paths.append(p)
return paths
def translated_srts(cues, langs, src_lang, out_dir):
paths = []
for L in langs:
if L.lower() == src_lang:
continue
try:
lines, out = [c[2] for c in cues], []
for i in range(0, len(lines), 30):
part = lines[i:i + 30]
sysm = (f"Translate each line into natural spoken {L} ({'Arabic script' if L != 'English' else 'English'}). Keep the meaning. "
'Return ONLY JSON {"lines":["..."]} with exactly ' + str(len(part)) + " items in order.")
raw, _ = ve.llm(sysm, json.dumps(part, ensure_ascii=False), json_mode=True)
got = json.loads(re.search(r"\{.*\}", raw, flags=re.S).group(0))["lines"]
out += ((got + part)[:len(part)]) if len(got) < len(part) else got[:len(part)]
srt = "\n".join(f"{i}\n{srt_time(c[0], ',')} --> {srt_time(c[1], ',')}\n{t}\n" for i, (c, t) in enumerate(zip(cues, out), 1))
p = os.path.join(out_dir, f"captions_{L.lower()}.srt")
with open(p, "w", encoding="utf-8") as f:
f.write(srt)
paths.append(p)
except Exception:
continue
return paths
# ============================ AI planning ============================
def plan_clips(cues, total, target, min_len, max_len):
groups, cur = [], []
for i, c in enumerate(cues):
if cur and (cues[cur[-1]][1] - cues[cur[0]][0] >= target or c[1] - cues[cur[0]][0] > max_len):
groups.append(cur)
cur = []
cur.append(i)
if cur:
groups.append(cur)
if len(groups) > 1 and cues[groups[-1][-1]][1] - cues[groups[-1][0]][0] < min_len:
last = groups.pop()
groups[-1] = groups[-1] + last
raw = [(cues[g[0]][0], cues[g[-1]][1], g) for g in groups]
out = []
for i, (gs, ge, g) in enumerate(raw):
prev_end = out[-1]["end"] if out else 0.0
nxt = raw[i + 1][0] if i + 1 < len(raw) else total
out.append({"idx": g, "start": max(prev_end, gs - 0.15), "end": min(nxt, ge + 0.45, total)})
return out
def ai_insights(texts):
sysm = ("You are a short-form video editor for Pakistani audiences. For each clip text return: title (max 8 words), hook (a punchy "
"first line, max 10 words, that makes people keep watching), alt_hooks (2 alternative hooks), caption (1-2 sentence post text, "
"no hashtags) - all in the SAME language and script as the clip text; hashtags (5, Latin letters, no spaces); score (0-100 for hook "
"strength, emotional pull, clarity and shareability); reason (max 12 words, English). Return ONLY JSON "
'{"clips":[{"title":"","hook":"","alt_hooks":["",""],"caption":"","hashtags":["#a"],"score":80,"reason":""}]} with exactly '
+ str(len(texts)) + " items, in order.")
raw, _ = ve.llm(sysm, json.dumps(texts, ensure_ascii=False), json_mode=True)
data = json.loads(re.search(r"\{.*\}", raw, flags=re.S).group(0))["clips"]
return [{"title": str(d.get("title", "")).strip(), "hook": str(d.get("hook", "")).strip(), "caption": str(d.get("caption", "")).strip(),
"alts": [str(x) for x in (d.get("alt_hooks") or [])[:2]], "tags": " ".join(d.get("hashtags", [])[:5]),
"score": int(float(d.get("score", 60))), "reason": str(d.get("reason", ""))} for d in data[:len(texts)]]
def ai_keypoints(texts):
"""Key phrase (<= 4 words) for the sentences that deserve an on-screen chip."""
if not texts:
return []
sysm = ("For each sentence return a key phrase of at most 4 words that the viewer should remember, in the SAME language and script as the "
"sentence. Return an empty string for sentences without a clear key point (aim for about one phrase every other sentence). "
'Return ONLY JSON {"keys":["..."]} with exactly ' + str(len(texts)) + " items, in order.")
raw, _ = ve.llm(sysm, json.dumps(texts, ensure_ascii=False), json_mode=True)
keys = [str(k).strip() for k in json.loads(re.search(r"\{.*\}", raw, flags=re.S).group(0))["keys"]]
return (keys + [""] * len(texts))[:len(texts)]
def analyze(audio_path, vstate, caption_text, o, progress=None):
P = progress or (lambda *a, **k: None)
log = []
dur = vid.audio_duration(audio_path)
cues = vid.build_cues(dur, vstate, audio_path, caption_text)
exact = bool(vstate and vstate.get("path") == audio_path and vstate.get("timeline"))
lang = ve.BASE[ve.detect_language(" ".join(c[2] for c in cues))] if cues else "urdu"
cw = None
ve.take_notes()
if o["cap_mode"] == "Whisper word-sync" or (o["cap_mode"] == "Auto" and not exact):
try:
P(0.1, desc="Whisper: timing every word…")
ww = whisper_words(audio_path, lang)
if ww and cues:
cues, cw = recut(cues, rhythm_align([w for c in cues for w in c[2].split()], ww))
elif ww:
cues, cw = cues_from_words(ww)
except Exception as e:
log.append(f"Whisper timing skipped: {ve.err_text(e)[:150]}")
log += ve.take_notes()
if cw is None:
if not cues:
raise RuntimeError("No text to caption. Generate the voice in the Voice tab, paste caption text, or choose Whisper word-sync.")
cw = words_from_cues(cues)
groups = plan_clips(cues, dur, o["target"], max(6, o["target"] * 0.4), max(o["target"] * 1.8, 20))
texts = [" ".join(cues[i][2] for i in g["idx"]) for g in groups]
ins = None
if o["ai"]:
try:
P(0.6, desc="Scoring clips and writing hooks…")
ins = ai_insights(texts)
except Exception as e:
log.append(f"AI insights skipped: {str(e)[:120]}")
clips = []
for i, (g, t) in enumerate(zip(groups, texts)):
d = ins[i] if ins and i < len(ins) else {}
title = d.get("title") or " ".join(t.split()[:7])
clips.append({"start": g["start"], "end": g["end"], "text": t, "title": title, "hook": d.get("hook") or title, "alts": d.get("alts", []),
"caption": d.get("caption", ""), "tags": d.get("tags", ""), "score": d.get("score", 60), "reason": d.get("reason", "")})
return {"dur": dur, "words": [w for lst in cw for w in lst], "cues": cues, "lang": lang, "clips": clips, "log": log}
def rows_from_plan(plan, max_clips):
order = sorted(range(len(plan["clips"])), key=lambda i: -plan["clips"][i]["score"])[:max_clips]
return [[i in order, i + 1, round(c["start"], 1), round(c["end"], 1), c["title"], c["score"], c["tags"]] for i, c in enumerate(plan["clips"])]
# ============================ audio ============================
def build_audio(src, start, dur, out, music, mvol, duck, norm):
chain = f"atrim=start={start:.3f}:duration={dur:.3f},asetpts=PTS-STARTPTS" + (",loudnorm=I=-16:TP=-1.5:LRA=11" if norm else "") + ",aresample=44100"
fade = f"afade=t=in:st=0:d=0.2,afade=t=out:st={max(0.0, dur - 0.3):.2f}:d=0.3"
cmd = ["ffmpeg", "-y", "-i", src]
if music:
cmd += ["-stream_loop", "-1", "-i", music]
fc = [f"[0:a]{chain}[v]", f"[1:a]atrim=duration={dur:.3f},asetpts=PTS-STARTPTS,aresample=44100,volume={mvol:.2f}[m]"]
if duck:
fc += ["[v]asplit=2[v1][sc]", "[m][sc]sidechaincompress=threshold=0.04:ratio=8:attack=20:release=500[md]",
"[v1][md]amix=inputs=2:duration=first:normalize=0[mx]"]
else:
fc.append("[v][m]amix=inputs=2:duration=first:normalize=0[mx]")
fc.append(f"[mx]{fade}[a]")
else:
fc = [f"[0:a]{chain},{fade}[a]"]
r = sh(cmd + ["-filter_complex", ";".join(fc), "-map", "[a]", "-ar", "44100", "-ac", "2", out])
if r.returncode != 0:
raise RuntimeError("audio step failed: " + r.stderr[-250:])
return out
# ============================ rendering ============================
POS_ASS = {"Bottom (safe)": (2, 0.19), "Middle": (5, 0.0), "Top": (8, 0.12)}
POS_HTML = {"Bottom (safe)": "bottom:19%", "Middle": "top:42%", "Top": "top:12%"}
POS_DEFAULT = {"Karaoke pop": "bottom:19%", "Clean bar": "bottom:17%", "Kinetic center": "top:40%", "Brand card": "bottom:17%"}
FS_BASE = 0.078
def gradient_png(W, H, theme, work):
a, b = np.array(hex_rgb(theme["primary"]), np.float32), np.array(hex_rgb(theme["dark"]), np.float32)
t = np.linspace(0, 1, H, dtype=np.float32)[:, None, None]
path = os.path.join(work, "bg.png")
Image.fromarray(((a * (1 - t) + b * t) * np.ones((1, W, 1), np.float32)).astype(np.uint8)).save(path)
return path
# caption entrance per emotion: energetic emotions pop in, calm/serious ones fade in softly
_POP = lambda a, b: "\\fscx%d\\fscy%d\\t(0,110,\\fscx%d\\fscy%d)\\t(110,220,\\fscx100\\fscy100)\\fad(50,60)" % (a, a, b, b)
ENTRY = {"excited": _POP(80, 110), "cheerful": _POP(84, 107), "hopeful": _POP(88, 105), "authoritative": _POP(90, 104),
"warm": "\\fscx94\\fscy94\\t(0,200,\\fscx100\\fscy100)\\fad(140,100)", "reassuring": "\\fscx95\\fscy95\\t(0,220,\\fscx100\\fscy100)\\fad(160,110)",
"neutral": "\\fad(100,80)", "serious": "\\fad(260,160)", "concerned": "\\fad(260,160)", "empathetic": "\\fad(300,180)",
"apologetic": "\\fad(300,180)", "calm": "\\fad(340,200)"}
RLE, PDF = "\u202b", "\u202c" # explicit right-to-left embedding: keeps Urdu word order right when English words are mixed in
def _cue_emo(cues, t):
for s_, e_, _, emo in cues or []:
if s_ - 0.08 <= t <= e_ + 0.08:
return emo
return "neutral"
def _stress_set(emo):
d = ve.EMOTIONS.get(emo, ("",))[0] if emo in ve.EMOTIONS else ""
m = re.search(r"stress the words: ([^;]*)", d)
return {re.sub(r"[^\w]", "", w.strip()) for w in m.group(1).split(",") if w.strip()} if m else set()
def _has_latin(w):
return any("a" <= c.lower() <= "z" for c in w)
def _word_rtl(w):
return any(ve.is_arabic_char(c) for c in w if c.isalpha())
def _visual_order(pg):
"""Mixed Urdu + English page: the renderer cannot keep right-to-left order once highlight tags are inside the line,
so the words are placed in their final visual (left-to-right) order here. Returns [(word_tuple, is_rtl_word)]."""
runs = []
for it in pg:
w = it[0]
r = True if _word_rtl(w) else (False if _has_latin(w) else (runs[-1][0] if runs else True))
if runs and runs[-1][0] == r:
runs[-1][1].append(it)
else:
runs.append((r, [it]))
out = []
for r, items in reversed(runs):
for it in (reversed(items) if r else items):
out.append((it, r))
return out
def _is_rtl(words):
return any(ve.is_arabic_char(c) for w in words for c in w if c.isalpha()) # any Urdu/Pashto word makes the line right-to-left
def build_ass(path, W, H, D, pages, title, cta, theme, style, fs_scale, pos, tag="", keys=None, cues=None):
fs = int(min(W, H) * FS_BASE * fs_scale)
prim, sec, outl, ob, al, mv, sc, karaoke, bs = {
"Karaoke pop": (theme["accent"], "#FFFFFF", "#000000", 5, 2, 0.19, 1.0, True, 1),
"Clean bar": ("#FFFFFF", "#FFFFFF", "#000000", 16, 2, 0.17, 0.9, False, 3),
"Kinetic center": (theme["accent"], "#FFFFFF", "#000000", 6, 5, 0.0, 1.4, True, 1),
"Brand card": (theme["primary"], theme["dark"], theme["light"], 20, 2, 0.17, 0.9, True, 3),
}[style]
if pos in POS_ASS:
al, mv = POS_ASS[pos]
box_a = 0x60 if style == "Clean bar" else 0
def sline(name, size, p, s, o, border, outline, align, margin, alpha=0, ml=40):
return (f"Style: {name},Noto Naskh Arabic,{int(size)},{ass_color(p)},{ass_color(s)},{ass_color(o, alpha)},"
f"{ass_color(o, alpha)},-1,0,0,0,100,100,0,0,{border},{outline},0,{align},{ml},40,{int(margin)},1")
head = ("[Script Info]\nScriptType: v4.00+\nPlayResX: %d\nPlayResY: %d\nWrapStyle: 0\n\n[V4+ Styles]\n"
"Format: Name,Fontname,Fontsize,PrimaryColour,SecondaryColour,OutlineColour,BackColour,Bold,Italic,Underline,"
"StrikeOut,ScaleX,ScaleY,Spacing,Angle,BorderStyle,Outline,Shadow,Alignment,MarginL,MarginR,MarginV,Encoding\n" % (W, H))
head += "\n".join([sline("Cap", fs * sc, prim, sec, outl, bs, ob, al, H * mv, box_a),
sline("Title", fs * 1.1, "#FFFFFF", "#FFFFFF", theme["dark"], 1, 5, 8, H * 0.08),
sline("CTA", fs * 0.8, "#FFFFFF", "#FFFFFF", theme["primary"], 3, 18, 2, H * 0.04),
sline("Tag", fs * 0.6, theme["dark"], theme["dark"], theme["accent"], 3, 14, 1, H * 0.27, 0, int(W * 0.05)),
sline("Key", fs * 0.78, theme["dark"], theme["dark"], theme["accent"], 3, 16, 8, H * 0.18)]) \
+ "\n\n[Events]\nFormat: Layer,Start,End,Style,Name,MarginL,MarginR,MarginV,Effect,Text\n"
def emo_at(t):
for a_, b_, _, em in (cues or []):
if a_ - 0.08 <= t <= b_ + 0.08:
return em
return "neutral"
def stress_of(em):
m = re.search(r"stress the words: ([^;]*)", ve.EMOTIONS.get(em, ("",))[0])
return {re.sub(r"[^\w]", "", x) for x in m.group(1).split(",") if x.strip()} if m else set()
def is_rtl_words(words):
ws = [w for w in words if any(c.isalpha() for c in w)]
return bool(ws) and sum(any(ve.is_arabic_char(c) for c in w) for w in ws) / len(ws) >= 0.4
def bidi(txt, words=None):
return "\u202b" + txt + "\u202c" if is_rtl_words(words or txt.split()) else txt # RTL embedding for untagged text
POP = {"excited": r"\fscx80\fscy80\t(0,120,\fscx108\fscy108)\t(120,240,\fscx100\fscy100)\fad(40,60)",
"cheerful": r"\fscx86\fscy86\t(0,130,\fscx106\fscy106)\t(130,250,\fscx100\fscy100)\fad(50,70)",
"hopeful": r"\fscx90\fscy90\t(0,150,\fscx103\fscy103)\t(150,260,\fscx100\fscy100)\fad(60,80)",
"authoritative": r"\fscx92\fscy92\t(0,160,\fscx100\fscy100)\fad(70,70)",
"warm": r"\fscx94\fscy94\t(0,220,\fscx100\fscy100)\fad(140,100)"}
FADE = {"neutral": r"\fad(90,80)", "reassuring": r"\fad(220,140)", "serious": r"\fad(200,120)", "concerned": r"\fad(240,160)",
"empathetic": r"\fad(260,170)", "apologetic": r"\fad(260,170)", "calm": r"\fad(300,200)"}
ev = []
for i, pg in enumerate(pages):
ps, pe = max(0.0, pg[0][1] - 0.05), pg[-1][2] + 0.2
if i + 1 < len(pages):
pe = min(pe, pages[i + 1][0][1] - 0.02)
pe = max(pe, ps + 0.2)
emo = emo_at(ps)
base_e, stress = emo.split("~")[0], stress_of(emo)
words = [w for w, _, _ in pg]
norm = lambda w: re.sub(r"[^\w]", "", w)
has_stress = karaoke and any(norm(w) in stress for w in words)
entry = FADE.get(base_e) or (r"\fad(60,70)" if has_stress else POP.get(base_e, FADE["neutral"]))
if has_stress and base_e in POP:
entry = r"\fad(60,70)" # stress words scale themselves; the page only fades in
rtl_page = is_rtl_words(words)
if karaoke and rtl_page:
# Tags between words make this renderer lay the words out left-to-right, which reverses the reading order of Urdu/Pashto.
# So we place the words in right-to-left VISUAL order ourselves and light each one at its own time.
body = ""
for j in range(len(pg) - 1, -1, -1):
w, s, e = pg[j]
rel = max(0, int(round((s - ps) * 1000)))
extra = ""
if has_stress:
extra = (r"\fscx116\fscy116\3c%s" % ass_bgr(theme["primary"])) if norm(w) in stress else (r"\fscx100\fscy100\3c%s" % ass_bgr(outl))
body += "{\\1c%s\\t(%d,%d,\\1c%s)%s}%s " % (ass_bgr(sec), rel, rel + 90, ass_bgr(prim), extra, ass_safe(w))
body = body.strip()
elif karaoke:
txt = ""
for j, (w, s, e) in enumerate(pg):
nxt = pg[j + 1][1] if j + 1 < len(pg) else e
extra = ""
if has_stress:
extra = (r"\fscx116\fscy116\3c%s" % ass_bgr(theme["primary"])) if norm(w) in stress else (r"\fscx100\fscy100\3c%s" % ass_bgr(outl))
txt += "{\\kf%d%s}%s " % (max(1, int(round((nxt - s) * 100))), extra, ass_safe(w))
body = txt.strip()
else:
body = bidi(ass_safe(" ".join(words)), words) # untagged text: real bidi with an RTL embedding
ev.append(f"Dialogue: 0,{ass_time(ps)},{ass_time(pe)},Cap,,0,0,0,,{{{entry}}}{body}")
tsafe, csafe, gsafe = bidi(ass_safe(title)), bidi(ass_safe(cta)), bidi(ass_safe(tag))
if tsafe:
ev.append(f"Dialogue: 1,{ass_time(0.2)},{ass_time(min(3.2, D * 0.45))},Title,,0,0,0,,{{\\fad(250,350)}}{tsafe}")
if gsafe and D > 3:
ev.append(f"Dialogue: 1,{ass_time(0.7)},{ass_time(min(D - 0.4, 5.0))},Tag,,0,0,0,,{{\\fad(250,300)}} {gsafe} ")
for ks, ke, kt in (keys or []): # key-point chips
if ks + 0.5 < D and ass_safe(kt):
ev.append(f"Dialogue: 1,{ass_time(ks + 0.25)},{ass_time(min(ke, ks + 3.2, D - 0.2))},Key,,0,0,0,,{{\\fad(200,250)}} {bidi(ass_safe(kt))} ")
if csafe:
ev.append(f"Dialogue: 1,{ass_time(max(0, D - 3.4))},{ass_time(D - 0.2)},CTA,,0,0,0,,{{\\fad(300,300)}}{csafe}")
ev.append("Dialogue: 2,%s,%s,Cap,,0,0,0,,{\\an7\\pos(0,%d)\\bord0\\shad0\\1c%s\\p1\\fscx0\\t(0,%d,\\fscx%d)}m 0 0 l 1 0 1 12 0 12"
% (ass_time(0), ass_time(D), H - 12, ass_bgr(theme["accent"]), int(D * 1000), W * 100))
with open(path, "w", encoding="utf-8") as f:
f.write(head + "\n".join(ev) + "\n")
def compose_ffmpeg(base, audio, W, H, D, pages, title, cta, theme, style, fs_scale, pos, logo, out, extras=None):
extras = extras or {}
ass = out + ".ass"
build_ass(ass, W, H, D, pages, title, cta, theme, style, fs_scale, pos, extras.get("tag", ""), extras.get("keys"), extras.get("cues"))
last_err = ""
for use_wave in ([True, False] if extras.get("wave") else [False]):
cmd = ["ffmpeg", "-y"]
cmd += ["-i", base] if base else ["-loop", "1", "-framerate", "24", "-t", f"{D:.2f}", "-i", gradient_png(W, H, theme, os.path.dirname(out))]
cmd += ["-i", audio] + (["-i", logo] if logo else [])
fc = [f"[0:v]scale={W}:{H}:force_original_aspect_ratio=increase,crop={W}:{H},setsar=1,format=yuv420p[v0]"]
last = "v0"
if logo:
fc += [f"[2:v]scale={int(W * 0.16)}:-1[lg]", f"[{last}][lg]overlay=W-w-{int(W * 0.04)}:{int(H * 0.03)}[v1]"]
last = "v1"
if use_wave:
wh = max(40, int(H * 0.08))
fc += [f"[1:a]showwaves=s={W}x{wh}:mode=cline:rate=24:colors=0x{theme['accent'].lstrip('#')}:scale=sqrt,format=rgba[wv]",
f"[{last}][wv]overlay=0:{H - wh - int(H * 0.045)}[v2]"]
last = "v2"
fc.append(f"[{last}]ass={ass},fade=t=in:st=0:d=0.25,fade=t=out:st={max(0.0, D - 0.35):.2f}:d=0.35[v]")
r = sh(cmd + ["-filter_complex", ";".join(fc), "-map", "[v]", "-map", "1:a:0", "-t", f"{D:.2f}", "-c:v", "libx264", "-preset", "veryfast",
"-crf", "23", "-pix_fmt", "yuv420p", "-c:a", "aac", "-b:a", "160k", "-movflags", "+faststart", out])
if r.returncode == 0:
return
last_err = r.stderr[-300:]
raise RuntimeError("FFmpeg render failed: " + last_err)
def make_thumbnail(video, title, theme, out, W, H):
ass = out + ".ass"
fs = int(min(W, H) * 0.095)
with open(ass, "w", encoding="utf-8") as f:
f.write("[Script Info]\nScriptType: v4.00+\nPlayResX: %d\nPlayResY: %d\nWrapStyle: 0\n\n[V4+ Styles]\n"
"Format: Name,Fontname,Fontsize,PrimaryColour,SecondaryColour,OutlineColour,BackColour,Bold,Italic,Underline,StrikeOut,"
"ScaleX,ScaleY,Spacing,Angle,BorderStyle,Outline,Shadow,Alignment,MarginL,MarginR,MarginV,Encoding\n"
"Style: T,Noto Naskh Arabic,%d,&H00FFFFFF,&H00FFFFFF,%s,%s,-1,0,0,0,100,100,0,0,3,22,0,5,60,60,10,1\n\n"
"[Events]\nFormat: Layer,Start,End,Style,Name,MarginL,MarginR,MarginV,Effect,Text\n"
"Dialogue: 0,0:00:00.00,0:00:10.00,T,,0,0,0,,%s\n" % (W, H, fs, ass_color(theme["primary"]), ass_color(theme["primary"]), ass_safe(title)))
r = sh(["ffmpeg", "-y", "-ss", "1.0", "-i", video, "-vf", f"ass={ass}", "-frames:v", "1", "-q:v", "3", out])
if r.returncode != 0 or not os.path.exists(out):
sh(["ffmpeg", "-y", "-ss", "1.0", "-i", video, "-frames:v", "1", "-q:v", "3", out])
def selftest_ffmpeg():
import soundfile as sf
t0 = time.time()
work = tempfile.mkdtemp(prefix="selftest_")
sr = 16000
t = np.linspace(0, 2.0, 2 * sr, endpoint=False)
sf.write(os.path.join(work, "a.wav"), (0.2 * np.sin(2 * np.pi * 220 * t)).astype(np.float32), sr)
out = os.path.join(work, "t.mp4")
compose_ffmpeg(None, os.path.join(work, "a.wav"), 360, 640, 2.0, [[("Test", 0.1, 0.8), ("caption", 0.8, 1.6)]], "Hello", "www.example.com",
THEMES["AFC brand"], "Karaoke pop", 1.0, "Bottom (safe)", None, out, {"tag": "Dr. Test", "wave": True, "keys": [(0.2, 1.5, "Key point")]})
size = os.path.getsize(out)
if size < 3000:
raise RuntimeError("the test clip is empty")
return f"rendered a 2 s captioned clip with waveform and key chip ({size // 1024} KB, {time.time() - t0:.1f}s)"
CSS_PAGES = {
"Karaoke pop": ".page{BOX §POS§;font-size:§FS§px}.w{color:#fff;text-shadow:0 3px 14px rgba(0,0,0,.8)}",
"Clean bar": ".page{BOX §POS§;font-size:§FS95§px;background:rgba(0,0,0,.6);padding:.35em .7em;border-radius:20px}.w{color:#fff}",
"Kinetic center": ".page{BOX §POS§;font-size:§FS15§px}.w{color:#fff;text-shadow:0 6px 28px rgba(0,0,0,.85)}",
"Brand card": ".page{BOX §POS§;font-size:§FS95§px;background:§LIGHT§;padding:.4em .8em;border-radius:22px;border-bottom:10px solid §ACCENT§}.w{color:§DARK§;text-shadow:none}",
}
def html_composition(W, H, D, theme, style, pages, title, cta, has_base, has_logo, rtl, fs_scale, pos):
fs = int(min(W, H) * FS_BASE * fs_scale)
css = (CSS_PAGES[style].replace("BOX", "left:0;right:0;margin:0 auto;width:fit-content;max-width:90%;")
.replace("§POS§", POS_HTML.get(pos, POS_DEFAULT[style])).replace("§FS95§", str(int(fs * 0.9)))
.replace("§FS15§", str(int(fs * 1.4))).replace("§FS§", str(fs)).replace("§LIGHT§", theme["light"])
.replace("§ACCENT§", theme["accent"]).replace("§DARK§", theme["dark"]))
hi = theme["primary"] if style == "Brand card" else theme["accent"]
base_col = theme["dark"] if style == "Brand card" else "#ffffff"
body = [f'<div class="bgfill clip" data-start="0" data-duration="{D:.2f}" data-track-index="0"></div>']
js = []
if has_base:
body.append(f'<video id="base" class="clip" src="base.mp4" data-start="0" data-duration="{D:.2f}" data-track-index="1" muted playsinline></video>')
if has_logo:
body.append(f'<img class="logo clip" src="logo.png" data-start="0" data-duration="{D:.2f}" data-track-index="5">')
if title:
td = min(3.0, D * 0.45)
body.append(f'<div class="title clip" data-start="0.2" data-duration="{td:.2f}" data-track-index="3">{html.escape(title)}</div>')
js += ['tl.from(".title",{opacity:0,y:-40,duration:0.5,ease:"power3.out"},0.2);',
f'tl.to(".title",{{opacity:0,duration:0.4}},{max(0.3, 0.2 + td - 0.45):.2f});']
n = 0
for i, pg in enumerate(pages):
ps, pe = pg[0][1], pg[-1][2] + 0.15
if i + 1 < len(pages):
pe = min(pe, pages[i + 1][0][1] - 0.02)
pe = max(pe, ps + 0.2)
spans = "".join(f'<span class="w" id="w{n + j}">{html.escape(w)}</span> ' for j, (w, _, _) in enumerate(pg))
body.append(f'<div class="page clip" id="p{i}" data-start="{ps:.2f}" data-duration="{pe - ps:.2f}" data-track-index="4">{spans}</div>')
js.append(f'tl.from("#p{i}",{{opacity:0,y:30,duration:0.18,ease:"power2.out"}},{ps:.2f});')
for j, (w, s, e) in enumerate(pg):
js.append(f'tl.to("#w{n + j}",{{color:"{hi}",scale:1.14,duration:0.08}},{s:.2f});')
js.append(f'tl.to("#w{n + j}",{{color:"{base_col}",scale:1,duration:0.12}},{max(e, s + 0.1):.2f});')
n += len(pg)
if cta:
cs = max(0.0, D - 3.4)
body.append(f'<div class="cta clip" data-start="{cs:.2f}" data-duration="{D - cs:.2f}" data-track-index="6">{html.escape(cta)}</div>')
js.append(f'tl.from(".cta",{{opacity:0,y:60,duration:0.4,ease:"power3.out"}},{cs:.2f});')
body.append(f'<div class="bar clip" data-start="0" data-duration="{D:.2f}" data-track-index="7"></div>')
js.append(f'tl.to(".bar",{{width:"100%",duration:{D:.2f},ease:"none"}},0);')
body.append(f'<audio id="voice" src="audio.wav" data-start="0" data-duration="{D:.2f}" data-track-index="9" data-volume="1"></audio>')
page = """<!doctype html>
<html lang="ur" dir="§DIR§"><head><meta charset="utf-8">
<script src="https://cdn.jsdelivr.net/npm/gsap@3/dist/gsap.min.js"></script>
<style>
html,body{margin:0;padding:0;width:§W§px;height:§H§px;background:§DARK§;overflow:hidden}
#root{position:relative;width:§W§px;height:§H§px;overflow:hidden;font-family:'Noto Naskh Arabic','Inter',sans-serif;color:#fff}
.bgfill{position:absolute;left:0;top:0;width:§W§px;height:§H§px;background:linear-gradient(160deg,§PRIMARY§ 0%,§DARK§ 100%)}
#base{position:absolute;left:0;top:0;width:§W§px;height:§H§px;object-fit:cover}
.title{position:absolute;left:6%;right:6%;top:8%;text-align:center;font-size:§TS§px;font-weight:800;line-height:1.4;text-shadow:0 4px 24px rgba(0,0,0,.55)}
.page{position:absolute;text-align:center;font-weight:800;line-height:1.55}
.w{display:inline-block;margin:0 .16em}
.cta{position:absolute;left:0;right:0;bottom:4%;margin:0 auto;width:fit-content;max-width:88%;text-align:center;font-weight:800;font-size:§CS§px;background:§PRIMARY§;color:#fff;padding:.4em .9em;border-radius:18px}
.bar{position:absolute;left:0;bottom:0;height:12px;width:0;background:§ACCENT§}
.logo{position:absolute;top:3%;right:4%;width:16%}
§CSS§
</style></head>
<body>
<div id="root" data-composition-id="main" data-start="0" data-width="§W§" data-height="§H§" data-duration="§D§">
§BODY§
</div>
<script>
const tl = gsap.timeline({ paused: true });
§JS§
window.__timelines = window.__timelines || {};
window.__timelines["main"] = tl;
</script></body></html>"""
for k, v in {"§DIR§": "rtl" if rtl else "ltr", "§W§": str(W), "§H§": str(H), "§D§": f"{D:.2f}", "§DARK§": theme["dark"],
"§PRIMARY§": theme["primary"], "§ACCENT§": theme["accent"], "§TS§": str(int(fs * 1.1)),
"§CS§": str(int(fs * 0.8)), "§CSS§": css, "§BODY§": "\n".join(body), "§JS§": "\n".join(js)}.items():
page = page.replace(k, v)
return page
def selftest_hyperframes(force=False):
import soundfile as sf
if not _HF["ready"] and not force:
raise RuntimeError("not ready yet (" + hf_brief() + ")")
proj = tempfile.mkdtemp(prefix="hftest_")
sr = 16000
t = np.linspace(0, 2.0, 2 * sr, endpoint=False)
sf.write(os.path.join(proj, "audio.wav"), (0.2 * np.sin(2 * np.pi * 220 * t)).astype(np.float32), sr)
with open(os.path.join(proj, "index.html"), "w", encoding="utf-8") as f:
f.write(html_composition(360, 640, 2.0, THEMES["AFC brand"], "Karaoke pop", [[("Test", 0.1, 0.8), ("caption", 0.8, 1.6)]],
"Hello", "example.com", False, False, False, 1.0, "Bottom (safe)"))
t0 = time.time()
ok, path, log = hf_render(proj, "draft", 24)
if not ok:
hint = _apt_hint(log)
if hint:
raise RuntimeError("Chrome needs system libraries. Add these lines to packages.txt and rebuild: " + ", ".join(hint.split()))
raise RuntimeError(log[-220:].replace("\n", " "))
return f"rendered a 2 s clip with HyperFrames ({os.path.getsize(path) // 1024} KB, {time.time() - t0:.1f}s)"
def render_clip(work, name, W, H, D, base, mix_wav, pages, title, cta, theme, style, fs_scale, pos, logo, engine_choice, quality, fps, extras=None):
out, note = os.path.join(work, name), ""
extras = extras or {}
special = extras.get("wave") or extras.get("tag") or extras.get("keys") or extras.get("cues")
use_hf = engine_choice != "FFmpeg only" and _HF["ready"] and not special
if engine_choice != "FFmpeg only" and _HF["ready"] and special:
note = "emotion-aware captions, waveform, name tag and key chips use the FFmpeg renderer"
if use_hf:
proj = tempfile.mkdtemp(dir=work)
try:
shutil.copy(mix_wav, os.path.join(proj, "audio.wav"))
if base:
shutil.copy(base, os.path.join(proj, "base.mp4"))
if logo:
Image.open(logo).convert("RGBA").save(os.path.join(proj, "logo.png"))
rtl = ve.detect_language(" ".join(w for pg in pages for w, _, _ in pg)) in ("urdu", "pashto")
with open(os.path.join(proj, "index.html"), "w", encoding="utf-8") as f:
f.write(html_composition(W, H, D, theme, style, pages, title, cta, bool(base), bool(logo), rtl, fs_scale, pos))
ok, path, log = hf_render(proj, quality, fps)
if ok:
shutil.move(path, out)
return out, "HyperFrames", ""
note = "HyperFrames failed: " + log[-250:].replace("\n", " ")
except Exception as e:
note = f"HyperFrames error: {str(e)[:200]}"
if engine_choice == "HyperFrames only":
raise RuntimeError(note)
elif engine_choice == "HyperFrames only" and not _HF["ready"]:
raise RuntimeError("HyperFrames is not ready yet (" + hf_brief() + "). Choose 'Auto' or wait for the install to finish.")
compose_ffmpeg(base, mix_wav, W, H, D, pages, title, cta, theme, style, fs_scale, pos, logo, out, extras)
return out, "FFmpeg", note
# ============================ render the plan ============================
def render_plan(plan, rows, audio_path, char_path, o, progress=None):
P = progress or (lambda *a, **k: None)
t0, log = time.time(), list(plan.get("log", []))
if hasattr(rows, "values"):
rows = rows.values.tolist()
sel = []
for r in rows:
use = r[0] if isinstance(r[0], bool) else str(r[0]).strip().lower() in ("true", "1", "yes")
try:
s, e = max(0.0, float(r[2])), min(plan["dur"], float(r[3]))
n = int(float(r[1]))
except Exception:
continue
if use and e - s >= 2:
sel.append({"n": n, "start": s, "end": e, "title": str(r[4] or ""), "tags": str(r[6] or ""), "score": r[5],
"meta": plan["clips"][n - 1] if 0 < n <= len(plan["clips"]) else {}})
if not sel:
raise RuntimeError("Tick at least one clip in the plan table (and keep each clip longer than 2 seconds).")
theme = {k: norm_hex(o[k], THEMES["AFC brand"][k]) for k in ("primary", "accent", "dark", "light")}
engine = "FFmpeg only" if o["draft"] else o["engine"]
if engine == "HyperFrames only" and not _HF["ready"]:
raise RuntimeError("HyperFrames is not ready yet (" + hf_brief() + "). Choose 'Auto' or wait for the install to finish.")
work = tempfile.mkdtemp(prefix="clips_")
files, thumbs, rows_out, items, used_clips = [], [], [], [], []
jobs = [(ar, c) for ar in o["aspects"] for c in sel]
for k, (ar, c) in enumerate(jobs):
W, H = vid.ASPECTS[ar]
if o["draft"]:
W, H = vid.scaled((W, H), 0.6)
tag = "x".join(re.search(r"(\d+):(\d+)", ar).groups())
cs, ce = c["start"], c["end"]
D = ce - cs
P(0.05 + 0.9 * k / len(jobs), desc=f"Clip {c['n']} · {tag.replace('x', ':')} ({k + 1}/{len(jobs)})…")
local = [(w, max(0.0, s - cs), min(D, max(e - cs, s - cs + 0.06))) for (w, s, e) in plan["words"] if cs - 0.05 <= s < ce]
if not local:
log.append(f"Clip {c['n']}: no words in this time window, skipped.")
continue
lcues = [(max(0, a - cs), min(D, b - cs), t, em) for (a, b, t, em) in plan["cues"] if b > cs and a < ce]
pages = make_pages(local, PER_PAGE[o["style"]])
mix = build_audio(audio_path, cs, D, os.path.join(work, f"mix_{k}.wav"), o["music"], o["mvol"], o["duck"], o["norm"])
base = None
if char_path:
voice_only = build_audio(audio_path, cs, D, os.path.join(work, f"voice_{k}.wav"), None, 0, False, False)
base = vid.render_quick(char_path, voice_only, (W, H), o["adj"], o["motion"], o["bg_mode"], o["bg_color"], lcues, framing=o["framing"])
extras = {"tag": o.get("tag", ""), "wave": o.get("wave", False), "keys": [], "cues": lcues}
if o.get("keys") and lcues:
try:
ks = ai_keypoints([c_[2] for c_ in lcues])
extras["keys"] = [(c_[0], c_[1], kk) for c_, kk in zip(lcues, ks) if kk]
except Exception as e:
log.append(f"Key-point chips skipped: {str(e)[:80]}")
meta = c["meta"]
intro = {"Hook line": meta.get("hook") or c["title"], "Title": c["title"], "None": ""}[o["intro"]]
name = f"afc_clip{c['n']:02d}_{tag}.mp4"
path, used, note = render_clip(work, name, W, H, D, base, mix, pages, intro, o["cta"], theme, o["style"], o["cap_scale"],
o["pos"], o["logo"], engine, "draft" if o["draft"] else o["quality"], 24 if o["draft"] else o["fps"], extras)
if note:
log.append(f"{name}: {note}")
th = path[:-4] + ".jpg"
make_thumbnail(path, meta.get("hook") or c["title"], theme, th, W, H)
files.append(path)
used_clips.append(c)
if os.path.exists(th):
thumbs.append(th)
rows_out.append([c["n"], tag.replace("x", ":"), c["title"], round(D), used, c["score"], c["tags"]])
items.append({"label": f"{c['n']}. {tag.replace('x', ':')} · {c['title'][:40]}", "path": path})
if not files:
raise RuntimeError("No clips were rendered. " + " ".join(log[-2:]))
P(0.96, desc="Packing the ZIP…")
extra_files = write_captions(plan["words"], work)
if o["srt"]:
extra_files += translated_srts(plan["cues"], o["srt"], plan["lang"], work)
txt = os.path.join(work, "clips_for_posting.txt")
seen = set()
with open(txt, "w", encoding="utf-8") as f:
for r, c in zip(rows_out, used_clips):
if r[0] in seen:
continue
seen.add(r[0])
m = c["meta"]
f.write(f"#{r[0]} {r[2]} (score {r[5]}: {m.get('reason', '')})\nHook: {m.get('hook', '')}\n"
+ "".join(f"Alt hook: {a}\n" for a in m.get("alts", [])) + f"Post: {m.get('caption', '')}\n{r[6]}\n\n")
zp = os.path.join(work, "clips.zip")
with zipfile.ZipFile(zp, "w", zipfile.ZIP_DEFLATED) as z:
for p in files + thumbs + extra_files + [txt]:
z.write(p, os.path.basename(p))
return {"files": files, "zip": zp, "rows": rows_out, "items": items, "log": "\n".join(log) or "All clips rendered cleanly.",
"secs": time.time() - t0}