Skip to content

Text to vertical video in 100+ styles: AI codes each scene (HTML/SVG/WebGL), renders a 9:16 MP4 with music and English/Vietnamese voice. MCP, CLI and REST for AI agents.

35.1 KB
Raw Blame
"""LumReels Edit: the Python side, built on the AskEditor pack's core (edit/askeditor/fx, MIT).

    python -X utf8 lumedit.py analyze <proxy.mp4> --out analysis.json
    python -X utf8 lumedit.py render <edl.json> --out base.mp4 [--draft-captions] [--no-check]
    python -X utf8 lumedit.py stills <edl.json> --out preview.jpg [--count 16] [--draft-captions]
    python -X utf8 lumedit.py hear <proxy.mp4> --spans a-b,c-d --out heard.json
    python -X utf8 lumedit.py qc <final.mp4> --out qc.json

Talks to Node line by line: `@progress {json}` while it works, and one `@result {json}` at the end
({"ok": true, ...} or {"ok": false, "error": "..."}). Exit 0 on success, 2 on bad input, 3 when setup
is missing, 1 on any other failure.

Everything in an EDL is in source seconds; the proxy shares the source's time axis. The render is
one pass: AskEditor's Timeline (the kept stretches, with the source sound joined by 20 ms
crossfades) and Framing (a window of the EDL's frame — 9:16, 16:9, 4:3 or 3:4 — following the face), then our zooms and draft captions drawn
on each output frame.
"""

from __future__ import annotations

import argparse
import json
import math
import os
import sys
import time
import traceback
from functools import lru_cache
from pathlib import Path

PACK = Path(__file__).resolve().parents[1] / "askeditor"
sys.path.insert(0, str(PACK))
os.environ.setdefault("GLOG_minloglevel", "2")
os.environ.setdefault("TF_CPP_MIN_LOG_LEVEL", "3")

OUT_W, OUT_H, OUT_FPS = 1080, 1920, 30
SAFE = (120 / 1080, 0.10, 960 / 1080, 0.80)  # x0, y0, x1, y1 as shares of the frame
OUT_RATIO = "9:16"
# The output frame of each ratio (engine/ratio.mjs): the short side is always 1080. Set from edl.output by load_edl.
RATIOS = {"9:16": (1080, 1920), "16:9": (1920, 1080), "4:3": (1440, 1080), "3:4": (1080, 1440)}
SAFES = {"9:16": (120 / 1080, 0.10, 960 / 1080, 0.80), "16:9": (0.06, 0.07, 0.94, 0.90),
         "4:3": (0.06, 0.07, 0.94, 0.90), "3:4": (0.07, 0.07, 0.93, 0.86)}


def set_frame(edl: dict) -> None:
    """The output frame of this EDL (edl.output.ratio; an old EDL without one is 9:16)."""
    global OUT_W, OUT_H, SAFE, OUT_RATIO
    out = edl.get("output") or {}
    ratio = out.get("ratio") or next((r for r, wh in RATIOS.items() if wh == (out.get("width"), out.get("height"))), "9:16")
    if ratio not in RATIOS:
        raise ValueError(f"output ratio {ratio!r} is not supported")
    OUT_RATIO = ratio
    OUT_W, OUT_H = RATIOS[ratio]
    SAFE = SAFES[ratio]


def caption_cy(cy: float) -> float:
    """A caption line's centre (share of the height) written for 9:16, on this frame (edit/edl.mjs frameCy)."""
    if OUT_RATIO == "9:16":
        return cy
    land = OUT_W > OUT_H
    if cy >= 0.62:
        return min(SAFE[3] - 0.06, (0.80 if land else 0.78) + (cy - 0.70) * 0.5)
    return 0.5 + (cy - 0.5) * (0.8 if land else 0.9)


def emit(kind: str, obj: dict) -> None:
    print(f"@{kind} " + json.dumps(obj, ensure_ascii=False), flush=True)


def progress(step: str, **kw) -> None:
    emit("progress", {"step": step, **kw})


# ---- analyze ---------------------------------------------------------------------------------------------

def cmd_analyze(proxy: Path, out: Path) -> dict:
    from fx.core.clip import Clip
    from fx.core import words as wordsmod

    t0 = time.time()
    clip = Clip(proxy)
    info = clip.info
    progress("words", note=f"chép lời ({os.environ.get('FX_WHISPER') or 'small.en'}, {wordsmod.LANG})")
    ws = clip.words
    t_words = time.time() - t0
    try:  # where whisper ran (cuda float16 | cpu int8 (why)), recorded in the words cache by fx.core.words
        from fx.core import paths as pathsmod
        device = json.loads(pathsmod.beside(proxy.resolve(), "words.json").read_text(encoding="utf-8")).get("device") or "?"
    except (OSError, ValueError):
        device = "?"
    progress("words", note=f"whisper {device}")
    progress("quiet")
    quiet = clip.quiet
    progress("face")
    t1 = time.time()
    face = clip.face
    t_face = time.time() - t1
    fps = info.rate
    faces = []
    step = max(1, int(round(fps / 2)))
    for i in range(0, info.frames, step):
        b = face.box(i) if face.any() else None
        faces.append(None if b is None else [round(i / fps, 2), round(b.x0), round(b.y0), round(b.w), round(b.h)])
    data = {
        "proxy": str(proxy), "duration": round(info.duration, 3), "fps": fps, "frames": info.frames,
        "width": info.width, "height": info.height,
        "words": [{"i": i, "w": w.text, "s": round(w.start, 3), "e": round(w.end, 3), "p": round(w.prob, 3)}
                  for i, w in enumerate(ws)],
        "unsure": [{"w": w.text, "s": round(w.start, 3), "e": round(w.end, 3), "why": w.unsure} for w in clip.unsure],
        "quiet": [[round(a, 3), round(b, 3)] for a, b in quiet],
        "face": {"found_share": round(float(face.found_share), 3) if face.any() else 0.0,
                 "every_half_second": [f for f in faces if f is not None]},
        # The speech-band loudness in 10 ms steps (whole dB), so the planner can put every cut at a real break in
        # the voice instead of at the transcriber's word edges, which run up to 0.2 s off on Vietnamese.
        "env": {"hop": clip.envelope.hop, "floor": round(clip.envelope.floor, 2), "speech": round(clip.envelope.speech, 2),
                "threshold": round(clip.envelope.threshold, 2), "db": [int(round(float(x))) for x in clip.envelope.db]},
        "hesitations": sorted(wordsmod.HESITATIONS),
        "model": wordsmod.model_key("small.en"), "lang": wordsmod.LANG,
        "seconds": {"words": round(t_words, 1), "face": round(t_face, 1), "total": round(time.time() - t0, 1)},
        "whisper_device": device,
    }
    out.write_text(json.dumps(data, ensure_ascii=False, indent=1), encoding="utf-8")
    return {"out": str(out), "words": len(ws), "unsure": len(clip.unsure), "seconds": data["seconds"], "device": device}


# ---- shared: the EDL as AskEditor objects ------------------------------------------------------------------

def load_edl(path: Path) -> dict:
    edl = json.loads(path.read_text(encoding="utf-8"))
    if edl.get("version") != 1:
        raise ValueError(f"EDL version {edl.get('version')!r} is not supported (want 1)")
    set_frame(edl)
    return edl


def build(edl: dict, draft_captions: bool, glass_on: bool = True):
    from fx.core import framing as framing_mod
    from fx.core.clip import Clip
    from fx.core.timeline import Timeline

    clip = Clip(edl["proxy"]["file"])
    info = clip.info
    if abs(info.rate - OUT_FPS) > 0.01:
        raise ValueError(f"the proxy runs at {info.rate} fps; it must be the 30 fps proxy")
    segs = tuple((float(k["start"]), min(float(k["end"]), info.duration)) for k in edl["keep"])
    segs = tuple((a, b) for a, b in segs if b - a > 1e-3)
    tl = hook_timeline(Timeline, segs, edl.get("hook"), info.duration)
    mode = edl["reframe"]["mode"]
    face = clip.face if mode == "face" else None
    # the window follows the face into the EDL's frame; a clip already in that shape (landscape → 16:9) is not cut
    fr = framing_mod.plan(info.width, info.height, info.rate, info.frames, face, shape=OUT_RATIO,
                          size=(OUT_W, OUT_H), mode={"face": "track", "center": "center", "fill": "fill",
                                                     "none": "center"}[mode])
    if (fr.out_w, fr.out_h) != (OUT_W, OUT_H):
        fr.out_w, fr.out_h = OUT_W, OUT_H
    zooms = Zooms(edl, tl, fr, clip)
    # glass_on=False: kính mờ dưới đồ hoạ vẽ ở bước ghép (ffmpeg), dời giờ đồ hoạ không phải render lại nền
    glass = Glass(edl, tl) if glass_on and edl.get("graphics") else None
    squeeze = Squeeze(edl, tl) if any(g.get("squeeze") for g in edl.get("graphics", [])) else None
    caps = DraftCaptions(edl, tl) if draft_captions and edl["captions"]["words"] else None
    quote = QuoteDim(edl, tl) if edl.get("quote") else None
    hook = edl.get("hook") or None
    flash_at = (float(hook["end"]) - float(hook["start"])) if hook and hook.get("flash") else None

    def draw(frame, j, t):
        zooms.apply(frame, j, t)
        if squeeze is not None:
            squeeze.apply(frame, t)
        if quote is not None:
            quote.apply(frame, t)
        if glass is not None:
            glass.apply(frame, t)
        if caps is not None:
            caps.draw(frame, t)
        # chớp trắng 2 khung ở chỗ nối câu móc → clip
        if flash_at is not None and flash_at - 1e-3 <= t < flash_at + 2.0 / OUT_FPS - 1e-3:
            frame[:] = 255

    return clip, tl, fr, draw


# ---- the hook pulled to the front ---------------------------------------------------------------------------

def hook_timeline(Timeline, segs, hook, duration):
    """The output plays the hook (edl.hook, source seconds) first, then the kept stretches. Playing (to_source,
    sample_ranges, joins) works on any order of segments; only source → output needs care: a moment inside a kept
    stretch lands there (after the hook), a moment only in the hook (repeat: false) lands at 0 … hook length."""
    if not hook:
        return Timeline(segs)
    from dataclasses import dataclass

    @dataclass(frozen=True)
    class HookTimeline(Timeline):
        def _play(self, t):
            (h0, h1), rest = self.segments[0], self.segments[1:]
            acc = h1 - h0
            for a, b in rest:
                if t < a - 1e-9:
                    break
                if t <= b + 1e-9:
                    return acc + (t - a)
                acc += b - a
            if h0 - 1e-9 <= t <= h1 + 1e-9:
                return t - h0
            return None

        def to_output_nearest(self, t):
            got = self.to_output(t)
            if got is not None:
                return got
            best, best_d = 0.0, math.inf
            for a, b in self.segments[1:]:
                for src in (a, b):
                    if abs(src - t) < best_d:
                        best, best_d = self.to_output(src), abs(src - t)
            return best

    h = (float(hook["start"]), min(float(hook["end"]), duration))
    return HookTimeline((h,) + tuple(segs))


class QuoteDim:
    """edl.quote: while the quote is on screen the video dims to `dimTo` and blurs `blurPx`, eased in over `dimIn` s;
    held to the end when the quote closes the clip, else eased back out in 0.4 s (the quote block itself is drawn in
    the HyperFrames layer)."""

    def __init__(self, edl: dict, tl):
        q = edl["quote"]
        self.t0 = tl.to_output_nearest(float(q["start"]))
        q1 = tl.to_output_nearest(float(q["end"]))
        self.t1 = tl.duration + 1.0 if q1 >= tl.duration - 2.0 else min(tl.duration, q1 + 0.8)
        self.dim, self.blur, self.din = float(q["dimTo"]), float(q["blurPx"]), max(0.1, float(q["dimIn"]))

    def apply(self, frame, t: float) -> None:
        if not (self.t0 <= t < self.t1):
            return
        e = min(_ease((t - self.t0) / self.din), _ease((self.t1 - t) / 0.4))
        if e <= 0.01:
            return
        import cv2
        import numpy as np

        img = frame
        sigma = self.blur * e
        if sigma > 0.3:
            small = cv2.resize(frame, (OUT_W // 4, OUT_H // 4), interpolation=cv2.INTER_AREA)
            img = cv2.resize(cv2.GaussianBlur(small, (0, 0), sigma / 4), (OUT_W, OUT_H), interpolation=cv2.INTER_LINEAR)
        k = 1.0 - (1.0 - self.dim) * e
        frame[:] = (img.astype(np.float32) * k).astype(np.uint8)


# ---- zooms ---------------------------------------------------------------------------------------------------

def _ease(x: float) -> float:
    x = min(1.0, max(0.0, x))
    return x * x * (3 - 2 * x)


class Zooms:
    """Each zoom of the EDL on the output picture: a punch (in fast, hold, out) or a slow push, about
    the face where the zoom begins (or the upper middle of the frame when no face is found)."""

    PUNCH_IN, PUNCH_OUT = 0.08, 0.12

    def __init__(self, edl: dict, tl, fr, clip):
        self.items = []
        fps = clip.info.rate
        hook = edl.get("hook") or None
        hd = float(hook["end"]) - float(hook["start"]) if hook else 0.0
        for z in edl["zooms"]:
            at = float(z["at"])
            t_out = [(tl.to_output_nearest(at), float(z["dur"]))]
            # câu móc lặp lại: cú zoom trong câu móc chạy cả ở đầu clip (không tràn qua chỗ nối)
            if hook and hook.get("repeat") and float(hook["start"]) <= at <= float(hook["end"]):
                t_h = at - float(hook["start"])
                t_out.append((t_h, min(float(z["dur"]), hd - t_h)))
            for t0, dur in t_out:
                k = tl.source_frame(int(round(t0 * fps)), fps, clip.info.frames)
                cx, cy = OUT_W / 2, OUT_H * 0.40
                head = clip.face.head(k) if clip.face.any() else None
                if head is not None:
                    r = fr.to_output(head, k)
                    cx, cy = (r.x0 + r.x1) / 2, (r.y0 + r.y1) / 2
                self.items.append((t0, max(0.2, dur), float(z["scale"]), z["kind"], cx, cy))
        self.items.sort(key=lambda x: x[0])

    def scale_at(self, t: float):
        for t0, dur, s, kind, cx, cy in self.items:
            if t0 <= t < t0 + dur:
                u = t - t0
                if kind == "punch":
                    k = _ease(u / self.PUNCH_IN) if u < self.PUNCH_IN else 1.0
                    if u > dur - self.PUNCH_OUT:
                        k = min(k, _ease((dur - u) / self.PUNCH_OUT))
                else:  # push: a slow ease in over the whole stretch, a short way back at the end
                    back = min(0.3, dur * 0.2)
                    k = _ease(u / (dur - back)) if u < dur - back else _ease((dur - u) / back)
                return 1.0 + (s - 1.0) * k, cx, cy
        return 1.0, 0.0, 0.0

    def apply(self, frame, j: int, t: float) -> None:
        s, cx, cy = self.scale_at(t)
        if s <= 1.001:
            return
        import cv2
        import numpy as np

        w, h = OUT_W / s, OUT_H / s
        x0 = min(max(cx - w / 2, 0.0), OUT_W - w)
        y0 = min(max(cy - h * 0.42, 0.0), OUT_H - h)
        m = np.array([[s, 0.0, -x0 * s], [0.0, s, -y0 * s]], np.float64)
        frame[:] = cv2.warpAffine(frame, m, (OUT_W, OUT_H), flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_REPLICATE)


# ---- squeeze the picture while a graphic needs the room above a close face ----------------------------------------

class Squeeze:
    """edit/graphics.mjs sets `squeeze` {scale, anchorY} on a graphic when the face fills the frame: during that
    graphic the whole picture shrinks about (centre, anchorY) — the chin stays put, the top of the head comes down —
    eased in 0.3 s and out 0.25 s; around it, the same picture blurred and darkened."""

    IN, OUT_ = 0.3, 0.25

    def __init__(self, edl: dict, tl):
        self.items = [(tl.to_output_nearest(float(g["start"])), tl.to_output_nearest(float(g["end"])),
                       float(g["squeeze"]["scale"]), float(g["squeeze"]["anchorY"]))
                      for g in edl.get("graphics", []) if g.get("squeeze")]

    def at(self, t: float):
        for t0, t1, k, ay in self.items:
            if t0 <= t < t1:
                e = min(_ease((t - t0) / self.IN), _ease((t1 - t) / self.OUT_))
                return 1.0 - (1.0 - k) * e, ay
        return 1.0, 0.0

    def apply(self, frame, t: float) -> None:
        s, ay = self.at(t)
        if s > 0.999:
            return
        import cv2
        import numpy as np

        small = cv2.resize(frame, (OUT_W // 10, OUT_H // 10), interpolation=cv2.INTER_AREA)
        bg = cv2.resize(cv2.GaussianBlur(small, (0, 0), 4), (OUT_W, OUT_H), interpolation=cv2.INTER_LINEAR)
        m = np.array([[s, 0.0, OUT_W / 2 * (1 - s)], [0.0, s, ay * (1 - s)]], np.float64)
        fg = cv2.warpAffine(frame, m, (OUT_W, OUT_H), flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT)
        x0, y0 = int(np.ceil(OUT_W / 2 * (1 - s))), int(np.ceil(ay * (1 - s)))
        x1, y1 = int(np.floor(x0 + OUT_W * s)) - 1, int(np.floor(y0 + OUT_H * s)) - 1
        out = (bg.astype(np.float32) * 0.5).astype(np.uint8)
        out[y0:y1, x0:x1] = fg[y0:y1, x0:x1]
        frame[:] = out


# ---- frosted glass under the graphics (edit/graphics.mjs draws the card itself in the HyperFrames layer) ----------

class Glass:
    """Blurs the video under each graphic's card (rounded box), fading in/out with the card, so the semi-dark card of the
    overlay reads as frosted glass. Price tags and stickers are solid and get no glass."""

    ENTER, LEAVE, RADIUS = 0.15, 0.22, 38

    def __init__(self, edl: dict, tl):
        import numpy as np

        self.items = []
        for g in edl.get("graphics", []):
            b = g.get("box")
            # thẻ ghim (pinFirst) thu về 0,8× sau 3 s: vùng kính cố định sẽ lệch khỏi thẻ, nên không làm kính
            if not b or g["type"] in ("price_tag", "sticker") or (g.get("data") or {}).get("pin"):
                continue
            x0, y0 = max(0, int(round(b["x"]))), max(0, int(round(b["y"])))
            x1, y1 = min(OUT_W, int(round(b["x"] + b["w"]))), min(OUT_H, int(round(b["y"] + b["h"])))
            if x1 - x0 < 8 or y1 - y0 < 8:
                continue
            r = max(4, int(self.RADIUS * float(b.get("scale", 1))))
            yy, xx = np.mgrid[0:y1 - y0, 0:x1 - x0]
            w, h = x1 - x0, y1 - y0
            dx = np.maximum(np.maximum(r - xx, xx - (w - 1 - r)), 0)
            dy = np.maximum(np.maximum(r - yy, yy - (h - 1 - r)), 0)
            mask = np.clip(r + 0.5 - np.sqrt(dx * dx + dy * dy), 0, 1).astype(np.float32)[..., None]
            self.items.append((tl.to_output_nearest(float(g["start"])), tl.to_output_nearest(float(g["end"])), x0, y0, x1, y1, mask))

    def apply(self, frame, t: float) -> None:
        import cv2
        import numpy as np

        for t0, t1, x0, y0, x1, y1, mask in self.items:
            if not (t0 <= t < t1):
                continue
            a = min(_ease((t - t0) / self.ENTER), _ease((t1 - t) / self.LEAVE))
            if a <= 0.01:
                continue
            reg = frame[y0:y1, x0:x1]
            small = cv2.resize(reg, ((x1 - x0) // 4 or 1, (y1 - y0) // 4 or 1), interpolation=cv2.INTER_AREA)
            blur = cv2.resize(cv2.GaussianBlur(small, (0, 0), 6), (x1 - x0, y1 - y0), interpolation=cv2.INTER_LINEAR)
            m = mask * a
            frame[y0:y1, x0:x1] = (reg.astype(np.float32) * (1 - m) + blur.astype(np.float32) * m).astype(np.uint8)


# ---- draft captions (PIL) -------------------------------------------------------------------------------------

STYLE_DRAFT = {
    # text colour, highlight colour, active-word colour (None = no karaoke), size, uppercase
    "sach-gon": ((255, 255, 255), (252, 232, 2), None, 76, False),
    "phu-de-nay-mau": ((255, 255, 255), (252, 232, 2), (252, 232, 2), 92, True),
}


@lru_cache(maxsize=8)
def _font(size: int):
    from PIL import ImageFont

    path = PACK / "fonts" / "BeVietnamPro" / "BeVietnamPro-800.ttf"
    if not path.exists():
        raise FileNotFoundError("Be Vietnam Pro is missing: run node edit/setup.mjs")
    return ImageFont.truetype(str(path), size)


MIN_CARD, MERGE_BELOW = 0.25, 0.1


def caption_cards(edl: dict, tl) -> list[dict]:
    """The caption words in cards of at most maxWords, broken at a sentence end or a pause, timed
    in output seconds. Shared by the draft and (through the same rule in Node) the main captions."""
    cap = edl["captions"]
    most = int(cap["maxWords"])
    cards, cur = [], []
    words = cap["words"]
    for n, w in enumerate(words):
        cur.append(w)
        nxt = words[n + 1] if n + 1 < len(words) else None
        ends = w["w"].rstrip().endswith((".", "?", "!", ",", ":", ";", "…"))
        gap = (nxt["start"] - w["end"]) if nxt else 99
        if len(cur) >= most or ends or gap > 0.45 or nxt is None:
            cards.append(cur)
            cur = []
    out = []
    for c in cards:
        out.append({"words": c, "start": tl.to_output_nearest(c[0]["start"]),
                    "end": tl.to_output_nearest(c[-1]["end"])})
    out.sort(key=lambda c: c["start"])
    # Same rule as finishCards in edit/captions-hf.mjs: bridge short gaps, at least MIN_CARD on screen,
    # never past the next card's start (two cards are never on screen together), a card squeezed
    # under MERGE_BELOW joins the next one.
    for a, b in zip(out, out[1:]):
        if 0 <= b["start"] - a["end"] < 0.4:
            a["end"] = b["start"]
    for c in out:
        c["end"] = max(c["end"], c["start"] + MIN_CARD)
    for a, b in zip(out, out[1:]):
        a["end"] = min(a["end"], b["start"])
    merged = []
    for k, c in enumerate(out):
        nxt = out[k + 1] if k + 1 < len(out) else None
        if nxt is not None and c["end"] - c["start"] < MERGE_BELOW:
            nxt["words"] = c["words"] + nxt["words"]
            nxt["start"] = c["start"]
            continue
        merged.append(c)
    for c in merged:
        c["word_out"] = [max(c["start"], tl.to_output_nearest(w["start"])) for w in c["words"]]
    for a, b in zip(merged, merged[1:]):
        if a["end"] > b["start"] + 1e-6:
            raise ValueError(f"captions overlap at {b['start']:.2f} s")
    return merged


class DraftCaptions:
    def __init__(self, edl: dict, tl):
        cap = edl["captions"]
        self.cards = caption_cards(edl, tl)
        self.hi = set(cap["highlights"])
        self.base, self.hcol, self.active, self.size, self.upper = STYLE_DRAFT.get(cap["style"], STYLE_DRAFT["sach-gon"])
        self.cy = OUT_H * caption_cy(0.70 if cap["position"] == "lower" else 0.58)
        self.cache: dict = {}

    def sprite(self, ci: int, active: int):
        key = (ci, active)
        if key in self.cache:
            return self.cache[key]
        import numpy as np
        from PIL import Image, ImageDraw

        card = self.cards[ci]
        font = _font(self.size)
        maxw = (SAFE[2] - SAFE[0]) * OUT_W - 20
        # trailing , . ; : are not shown (? ! … stay), as in the HyperFrames captions
        toks = [((w["w"].rstrip(",.;:") or w["w"]), w["i"]) for w in card["words"]]
        toks = [(t.upper() if self.upper else t, i) for t, i in toks]
        space = font.getlength(" ")
        lines, line, lw = [], [], 0.0
        for text, i in toks:
            tw = font.getlength(text)
            if line and lw + space + tw > maxw:
                lines.append(line)
                line, lw = [], 0.0
            line.append((text, i, tw))
            lw += (space if len(line) > 1 else 0) + tw
        if line:
            lines.append(line)
        lh = int(self.size * 1.22)
        stroke = max(4, self.size // 11)
        W, H = int(maxw + 2 * stroke + 8), lh * len(lines) + 2 * stroke + 8
        img = Image.new("RGBA", (W, H), (0, 0, 0, 0))
        d = ImageDraw.Draw(img)
        for li, ln in enumerate(lines):
            total = sum(t[2] for t in ln) + space * (len(ln) - 1)
            x = (W - total) / 2
            y = stroke + 4 + li * lh
            for k, (text, i, tw) in enumerate(ln):
                col = self.base
                if i in self.hi:
                    col = self.hcol
                if self.active is not None and i == active:
                    col = self.active
                d.text((x, y), text, font=font, fill=col + (255,), stroke_width=stroke, stroke_fill=(0, 0, 0, 255))
                x += tw + space
        arr = np.asarray(img)
        self.cache[key] = arr
        return arr

    def rect(self, ci: int):
        a = self.sprite(ci, -1)
        h, w = a.shape[:2]
        x0 = int(round((OUT_W - w) / 2))
        y0 = int(round(min(self.cy - h / 2, SAFE[3] * OUT_H - h)))
        return x0, y0, w, h

    def draw(self, frame, t: float) -> None:
        import numpy as np

        for ci, c in enumerate(self.cards):
            if c["start"] <= t < c["end"]:
                active = -1
                for w, wo in zip(c["words"], c["word_out"]):
                    if t >= wo:
                        active = w["i"]
                spr = self.sprite(ci, active)
                x0, y0, w, h = self.rect(ci)
                region = frame[y0:y0 + h, x0:x0 + w]
                alpha = spr[:, :, 3:4].astype(np.float32) / 255.0
                region[:] = (spr[:, :, :3] * alpha + region * (1 - alpha)).astype(np.uint8)
                return


# ---- render / stills --------------------------------------------------------------------------------------------

def cmd_render(edl_path: Path, out: Path, draft_captions: bool, check: bool, glass_on: bool = True,
               clean_out: Path | None = None) -> dict:
    from fx.core import render as rmod
    from fx.core import video as vmod

    edl = load_edl(edl_path)
    t0 = time.time()
    clip, tl, fr, draw = build(edl, draft_captions, glass_on)
    n = tl.output_frames(clip.info.rate)
    last = [0.0]
    # clean_out: cùng lượt đọc, ghi thêm bản 540×960 TRƯỚC zoom/thu hình/kính/chữ nháp (Studio xem trước, zoom chạy bằng CSS)
    clean = vmod.FrameWriter(clean_out, OUT_W // 2, OUT_H // 2, clip.info.fps, audio=None, crf=26, preset="veryfast") if clean_out else None

    def drawing(frame, j, t):
        if clean is not None:
            import cv2

            clean.write(cv2.resize(frame, (OUT_W // 2, OUT_H // 2), interpolation=cv2.INTER_AREA))
        draw(frame, j, t)
        now = time.time()
        if now - last[0] > 2.0 or j == n - 1:
            last[0] = now
            progress("render", done=j + 1, total=n, pct=round(100 * (j + 1) / n))

    out.parent.mkdir(parents=True, exist_ok=True)
    fade = float(edl["audio"]["crossfadeMs"]) / 1000.0
    try:
        res = rmod.render(clip, tl, fr, drawing, out, fade=fade, crf=18)
    except BaseException:
        if clean is not None:
            clean.abort()
        raise
    if clean is not None:
        clean.close()
    t_render = time.time() - t0
    result = {"out": res["path"], "frames": res["frames"], "seconds_out": res["seconds_out"],
              "joins": len(tl.joins), "framing": fr.note, "seconds": {"render": round(t_render, 1)}}
    if check:
        progress("overcut-check", note="nghe lại bản cắt, so từng chữ")
        from fx.effects.clean_cut import overcut_check

        t1 = time.time()
        kept = [w for w in clip.words if tl.to_output((w.start + w.end) / 2) is not None]
        oc = overcut_check(clip, kept, tl, Path(out), None)
        result["overcut"] = {k: oc[k] for k in ("verdict", "lost", "chopped", "left_at_cut", "matched", "kept",
                                                 "joins", "joins_cut_in_silence", "median_start_offset_s")}
        result["seconds"]["overcut_check"] = round(time.time() - t1, 1)
    return result


def cmd_stills(edl_path: Path, out: Path, count: int, draft_captions: bool) -> dict:
    from PIL import Image, ImageDraw

    from fx.core import render as rmod

    edl = load_edl(edl_path)
    clip, tl, fr, draw = build(edl, draft_captions)
    dur = tl.duration
    times = [dur * (i + 0.5) / count for i in range(count)]
    frames = rmod.still_frames(clip, tl, fr, draw, times)
    cols = int(math.ceil(math.sqrt(count)))
    rows = int(math.ceil(count / cols))
    tw, th = OUT_W // 4, OUT_H // 4  # 9:16 → 270×480
    sheet = Image.new("RGB", (cols * tw + (cols + 1) * 6, rows * (th + 32) + (rows + 1) * 6), (24, 24, 24))
    d = ImageDraw.Draw(sheet)
    for n, (t, f) in enumerate(frames):
        img = Image.fromarray(f).resize((tw, th), Image.LANCZOS)
        x, y = 6 + (n % cols) * (tw + 6), 6 + (n // cols) * (th + 32)
        sheet.paste(img, (x, y))
        d.text((x + 4, y + th + 6), f"{t:5.2f} s", fill=(230, 230, 230))
    sheet.save(out, quality=88)
    return {"out": str(out), "times": [round(t, 2) for t in times]}


# What a graphic must keep clear of: the detector's own box (BlazeFace's box already runs wide of the cheeks and
# below the chin) grown upward for the hair. Measured on the founder's review clip (28/11/2026): `head()` (+60% up,
# +20% sides) came out about twice the visible head and left no room for any graphic in a close talking-head shot.
GRAPHIC_HEAD = {"left": 0.04, "top": 0.20, "right": 0.04, "bottom": 0.04}


def _graphic_head(face, k: int, near: int):
    """The face at source frame k from the detector's own boxes (the nearest within `near` frames; the detector runs
    on every frame but misses some), so B-roll without a face leaves the whole frame to the graphics; None when no
    face is there. Boxes of implausible size are ignored."""
    import numpy as np

    from fx.core.layout import Rect

    lo, hi = max(0, k - near), min(face.n - 1, k + near)
    best = None
    for i in range(lo, hi + 1):
        x = face.raw[i, 0]
        if not np.isnan(x) and not (0.05 * face.height <= face.raw[i, 3] <= 0.7 * face.height):
            continue
        if np.isnan(x) or (best is not None and abs(i - k) >= abs(best - k)):
            continue
        best = i
    if best is None:
        return None
    x, y, w, h, _ = face.raw[best]
    g = GRAPHIC_HEAD
    return Rect(x - g["left"] * w, y - g["top"] * h, x + w + g["right"] * w, y + h + g["bottom"] * h)


def cmd_faces(edl_path: Path, out: Path, step: float) -> dict:
    """Head box in OUTPUT pixels (after reframe and zoom) every `step` s of the output: what graphics must avoid."""
    edl = load_edl(edl_path)
    clip, tl, fr, _draw = build(edl, False)
    zooms = Zooms(edl, tl, fr, clip)
    fps = clip.info.rate
    rows = []
    n = int(tl.duration / step) + 1
    face = clip.face if clip.face.any() else None
    near = int(round(0.5 * fps))
    for m in range(n):
        t = min(tl.duration, m * step)
        k = tl.source_frame(int(round(t * fps)), fps, clip.info.frames)
        head = _graphic_head(face, k, near) if face is not None else None
        if head is None:
            rows.append([round(t, 3), None])
            continue
        r = fr.to_output(head, k)
        x0, y0, x1, y1 = r.x0, r.y0, r.x1, r.y1
        s, cx, cy = zooms.scale_at(t)
        if s > 1.001:
            w, h = OUT_W / s, OUT_H / s
            ox = min(max(cx - w / 2, 0.0), OUT_W - w)
            oy = min(max(cy - h * 0.42, 0.0), OUT_H - h)
            x0, x1, y0, y1 = (x0 - ox) * s, (x1 - ox) * s, (y0 - oy) * s, (y1 - oy) * s
        bx = [round(max(0, x0)), round(max(0, y0)), round(min(OUT_W, x1)), round(min(OUT_H, y1))]
        rows.append([round(t, 3), bx if bx[2] - bx[0] > 8 and bx[3] - bx[1] > 8 else None])
    data = {"step": step, "found_share": round(float(clip.face.found_share), 3) if clip.face.any() else 0.0, "boxes": rows}
    out.write_text(json.dumps(data), encoding="utf-8")
    return {"out": str(out), "samples": len(rows)}


# ---- hear stretches again on their own ------------------------------------------------------------------------

def cmd_hear(proxy: Path, spans_arg: str, out: Path) -> dict:
    """Each span of the proxy heard on its own (the pack's second listen, cached in the words cache): what the
    planner uses to check a figure before it goes on a graphic. spans_arg: "a-b,c-d" in source seconds."""
    from fx.core import words as wordsmod

    spans = []
    for part in spans_arg.split(","):
        a, b = part.split("-")
        spans.append((round(float(a), 2), round(float(b), 2)))
    heard = wordsmod.relisten(proxy, spans, "small.en")
    data = {k: [{"text": seg["text"], "avg_logprob": round(float(seg["avg_logprob"]), 3),
                 "words": [{"w": w.text, "s": round(w.start, 3), "e": round(w.end, 3), "p": round(w.prob, 3)} for w in seg["words"]]}
                for seg in segs] for k, segs in heard.items()}
    out.write_text(json.dumps(data, ensure_ascii=False, indent=1), encoding="utf-8")
    return {"out": str(out), "spans": len(data)}


# ---- qc ---------------------------------------------------------------------------------------------------------

def cmd_qc(video_path: Path, out: Path) -> dict:
    from fx.effects import qc_check

    r = qc_check.check(video_path, None, "reels", False, out.with_suffix(".md"))
    findings = [{"check": f.check, "level": f.level, "what": f.what, "fix": f.fix} for f in r["findings"]]
    data = {"verdict": r["verdict"], "findings": findings, "report": str(r["report"]), "sheet": str(r["sheet"]),
            "seconds": round(r["seconds"], 1)}
    out.write_text(json.dumps(data, ensure_ascii=False, indent=1), encoding="utf-8")
    return data


def main(argv=None) -> int:
    ap = argparse.ArgumentParser(prog="lumedit")
    sub = ap.add_subparsers(dest="cmd", required=True)
    a = sub.add_parser("analyze"); a.add_argument("proxy"); a.add_argument("--out", required=True)
    r = sub.add_parser("render"); r.add_argument("edl"); r.add_argument("--out", required=True)
    r.add_argument("--draft-captions", action="store_true"); r.add_argument("--no-check", action="store_true")
    r.add_argument("--no-glass", action="store_true"); r.add_argument("--clean-out", default=None)
    s = sub.add_parser("stills"); s.add_argument("edl"); s.add_argument("--out", required=True)
    s.add_argument("--count", type=int, default=16); s.add_argument("--draft-captions", action="store_true")
    f = sub.add_parser("faces"); f.add_argument("edl"); f.add_argument("--out", required=True)
    f.add_argument("--step", type=float, default=0.25)
    h = sub.add_parser("hear"); h.add_argument("proxy"); h.add_argument("--spans", required=True)
    h.add_argument("--out", required=True)
    q = sub.add_parser("qc"); q.add_argument("video"); q.add_argument("--out", required=True)
    args = ap.parse_args(argv)
    try:
        if args.cmd == "analyze":
            res = cmd_analyze(Path(args.proxy).resolve(), Path(args.out).resolve())
        elif args.cmd == "render":
            res = cmd_render(Path(args.edl).resolve(), Path(args.out).resolve(), args.draft_captions, not args.no_check,
                             not args.no_glass, Path(args.clean_out).resolve() if args.clean_out else None)
        elif args.cmd == "stills":
            res = cmd_stills(Path(args.edl).resolve(), Path(args.out).resolve(), args.count, args.draft_captions)
        elif args.cmd == "hear":
            res = cmd_hear(Path(args.proxy).resolve(), args.spans, Path(args.out).resolve())
        elif args.cmd == "faces":
            res = cmd_faces(Path(args.edl).resolve(), Path(args.out).resolve(), args.step)
        else:
            res = cmd_qc(Path(args.video).resolve(), Path(args.out).resolve())
    except (ValueError, KeyError, FileNotFoundError) as e:
        emit("result", {"ok": False, "error": f"{type(e).__name__}: {e}"})
        traceback.print_exc()
        return 2
    except Exception as e:  # noqa: BLE001
        from fx.core.paths import NeedSetup

        emit("result", {"ok": False, "error": f"{type(e).__name__}: {e}"})
        traceback.print_exc()
        return 3 if isinstance(e, NeedSetup) else 1
    emit("result", {"ok": True, **res})
    return 0


if __name__ == "__main__":
    sys.exit(main())