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.

14.9 KB
Raw Blame
"""Đo 1 video tham khảo để AI viết guidance mẫu dựng (THIET-KE gói mẫu §4.1). Chỉ đọc file trên máy.

    python tools/study.py <video> <thư mục ra> [--from 0] [--dur 8] [--no-audio] [--no-whisper] [--no-frames]

Ra trong <thư mục ra>:
    study.json          số đo (bảng màu, độ sáng, điểm cắt, sự kiện hình/giây, chuyển động, mặt người, tiếng)
    sheet.jpg           lưới 4x4, 16 khung cách 0,5 s (đọc trái→phải, trên→dưới), 360 px mỗi ô
    frames/f_01..16.jpg 16 khung rời 540 px (cùng mốc với lưới)
Dòng cuối stdout: "@result {...}" (tóm tắt), các bước in "@progress {...}".

Không đo được bằng code: font, chất liệu, kiểu chuyển động từng phần tử — phần đó AI nhìn khung.
Lời chép (nếu có Whisper) chỉ dùng để tính tốc độ nói, KHÔNG ghi chữ vào study.json (không chép lời thoại người khác).
Cần ffmpeg/ffprobe trong PATH, numpy. Tuỳ chọn: opencv (dò mặt), faster-whisper (tốc độ nói, chỉ khi model đã có trên máy).
"""
from __future__ import annotations

import argparse
import json
import math
import os
import re
import subprocess
import sys
import time
from pathlib import Path

import numpy as np

W_SMALL, H_SMALL = 108, 192  # khung nhỏ để đo (giữ tỉ lệ 9:16, video khác tỉ lệ thì co vào)


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


def run(cmd: list[str], binary: bool = False):
    return subprocess.run(cmd, capture_output=True, **({} if binary else {"text": True, "encoding": "utf-8", "errors": "replace"}))


def probe(video: Path) -> dict:
    p = run(["ffprobe", "-v", "error", "-show_entries", "format=duration:stream=codec_type,width,height,r_frame_rate",
             "-of", "json", str(video)])
    if p.returncode != 0:
        raise SystemExit("ffprobe không đọc được video: " + p.stderr.strip()[-300:])
    j = json.loads(p.stdout or "{}")
    v = next((s for s in j.get("streams", []) if s.get("codec_type") == "video"), None)
    if not v:
        raise SystemExit("file không có hình")
    num, _, den = str(v.get("r_frame_rate", "30/1")).partition("/")
    fps = float(num) / float(den or 1) if float(den or 1) else 30.0
    return {
        "duration": round(float(j.get("format", {}).get("duration", 0) or 0), 3),
        "width": int(v.get("width", 0)), "height": int(v.get("height", 0)), "fps": round(fps, 3),
        "hasAudio": any(s.get("codec_type") == "audio" for s in j.get("streams", [])),
    }


def grab(video: Path, start: float, dur: float, fps: float, w: int, h: int, gray: bool) -> np.ndarray:
    """Khung đã co về w×h (đệm viền đen nếu khác tỉ lệ) ở fps cho trước → mảng (n, h, w[, 3]) uint8."""
    pix = "gray" if gray else "rgb24"
    vf = f"fps={fps},scale={w}:{h}:force_original_aspect_ratio=decrease,pad={w}:{h}:(ow-iw)/2:(oh-ih)/2"
    p = run(["ffmpeg", "-v", "error", "-ss", f"{start}", "-t", f"{dur}", "-i", str(video), "-vf", vf,
             "-f", "rawvideo", "-pix_fmt", pix, "-"], binary=True)
    ch = 1 if gray else 3
    n = len(p.stdout) // (w * h * ch)
    a = np.frombuffer(p.stdout[: n * w * h * ch], dtype=np.uint8)
    return a.reshape((n, h, w) if gray else (n, h, w, 3))


def sheet_and_frames(video: Path, start: float, out: Path, dur: float) -> None:
    step = dur / 16
    fdir = out / "frames"
    fdir.mkdir(parents=True, exist_ok=True)
    for f in fdir.glob("f_*.jpg"):
        f.unlink()
    rate = f"1/{step:.4f}" if step != 0.5 else "2"
    run(["ffmpeg", "-y", "-v", "error", "-ss", f"{start}", "-t", f"{dur}", "-i", str(video), "-vf", f"fps={rate},scale=540:-2",
         "-frames:v", "16", "-q:v", "3", str(fdir / "f_%02d.jpg")])
    run(["ffmpeg", "-y", "-v", "error", "-ss", f"{start}", "-t", f"{dur}", "-i", str(video),
         "-vf", f"fps={rate},scale=360:640:force_original_aspect_ratio=decrease,pad=360:640:(ow-iw)/2:(oh-ih)/2,tile=4x4",
         "-frames:v", "1", "-q:v", "3", str(out / "sheet.jpg")])


def to_hex(c) -> str:
    return "#" + "".join(f"{int(max(0, min(255, round(x)))):02X}" for x in c)


def palette(frames_rgb: np.ndarray, k: int = 6) -> list[dict]:
    """k-means (tất định: tâm khởi đầu theo phân vị độ sáng) trên điểm ảnh của khung mẫu → [{hex, share}] xếp theo diện tích."""
    px = frames_rgb.reshape(-1, 3).astype(np.float32)
    if len(px) > 60000:
        px = px[:: math.ceil(len(px) / 60000)]
    lum = px @ np.array([0.299, 0.587, 0.114], dtype=np.float32)
    order = np.argsort(lum)
    cent = px[order[np.linspace(0, len(px) - 1, k).astype(int)]].copy()
    for _ in range(14):
        d = ((px[:, None, :] - cent[None, :, :]) ** 2).sum(-1)
        lab = d.argmin(1)
        for j in range(k):
            m = lab == j
            if m.any():
                cent[j] = px[m].mean(0)
    share = np.bincount(lab, minlength=k) / len(lab)
    out = [{"hex": to_hex(cent[j]), "share": round(float(share[j]), 3)} for j in range(k) if share[j] > 0.004]
    return sorted(out, key=lambda x: -x["share"])


def scene_cuts(video: Path, start: float, dur: float, thr: float) -> list[float]:
    p = run(["ffmpeg", "-v", "info", "-ss", f"{start}", "-t", f"{dur}", "-i", str(video), "-an",
             "-vf", f"scale=270:-2,select='gt(scene,{thr})',showinfo", "-f", "null", "-"])
    return [round(float(m), 2) for m in re.findall(r"pts_time:([\d.]+)", p.stderr)]


def motion_stats(gray4: np.ndarray, fps: float) -> dict:
    """Chênh lệch khung ở 4 fps: mức chuyển động 0–1 mỗi bước, đoạn gần đứng im (≥ 0,75 s dưới ngưỡng)."""
    if len(gray4) < 2:
        return {"mean": 0.0, "p90": 0.0, "curve": [], "stillSpans": [], "stillShare": 0.0}
    g = gray4.astype(np.int16)
    diff = np.abs(np.diff(g, axis=0)).mean(axis=(1, 2)) / 255.0
    still_thr = 0.004
    spans, cur = [], None
    for i, d in enumerate(diff):
        t = (i + 1) / fps
        if d < still_thr:
            cur = [i / fps, t] if cur is None else [cur[0], t]
        else:
            if cur and cur[1] - cur[0] >= 0.75:
                spans.append([round(cur[0], 2), round(cur[1], 2)])
            cur = None
    if cur and cur[1] - cur[0] >= 0.75:
        spans.append([round(cur[0], 2), round(cur[1], 2)])
    total = len(diff) / fps
    still = sum(b - a for a, b in spans)
    return {"mean": round(float(diff.mean()), 4), "p90": round(float(np.percentile(diff, 90)), 4),
            "curve": [round(float(x), 4) for x in diff], "stillSpans": spans, "stillShare": round(still / total, 3) if total else 0.0}


def visual_events(gray10: np.ndarray, fps: float) -> dict:
    """"Sự kiện hình": lúc tỉ lệ điểm ảnh đổi mạnh vọt lên (phần tử mới xuất hiện, đổi cảnh). Đếm theo sườn lên, mỗi giây."""
    if len(gray10) < 2:
        return {"count": 0, "perSecond": 0.0, "times": [], "perSecondCurve": []}
    g = gray10.astype(np.int16)
    changed = (np.abs(np.diff(g, axis=0)) > 24).mean(axis=(1, 2))
    base = np.convolve(changed, np.ones(5) / 5, mode="same")
    times, last = [], -1.0
    for i, c in enumerate(changed):
        t = (i + 1) / fps
        prev = changed[i - 1] if i else 0.0
        if c > 0.03 and c > 1.6 * max(prev, 1e-4) and c > 1.2 * base[i] and t - last >= 0.2:
            times.append(round(t, 2))
            last = t
    dur = len(changed) / fps
    curve = [sum(1 for t in times if s <= t < s + 1) for s in range(int(math.ceil(dur)))]
    return {"count": len(times), "perSecond": round(len(times) / dur, 2) if dur else 0.0, "times": times, "perSecondCurve": curve}


def faces(frames_dir: Path) -> dict:
    try:
        import cv2  # type: ignore
    except Exception:
        return {"available": False, "share": None}
    if not hasattr(cv2, "CascadeClassifier") or not hasattr(cv2, "data"):
        return {"available": False, "share": None}
    casc = cv2.CascadeClassifier(os.path.join(cv2.data.haarcascades, "haarcascade_frontalface_default.xml"))
    files = sorted(frames_dir.glob("f_*.jpg"))
    hits = 0
    for f in files:
        img = cv2.imread(str(f), cv2.IMREAD_GRAYSCALE)
        if img is None:
            continue
        found = casc.detectMultiScale(img, scaleFactor=1.15, minNeighbors=6, minSize=(max(24, img.shape[1] // 12),) * 2)
        hits += 1 if len(found) else 0
    return {"available": True, "share": round(hits / len(files), 3) if files else 0.0, "method": "opencv haar (ước lượng)"}


def audio_stats(video: Path, start: float, dur: float, whisper: bool) -> dict:
    out: dict = {"present": True}
    p = run(["ffmpeg", "-v", "info", "-ss", f"{start}", "-t", f"{dur}", "-i", str(video), "-vn",
             "-af", "ebur128=peak=true", "-f", "null", "-"])
    m = re.findall(r"I:\s*(-?[\d.]+) LUFS", p.stderr)
    out["lufs"] = float(m[-1]) if m else None
    p = run(["ffmpeg", "-v", "info", "-ss", f"{start}", "-t", f"{dur}", "-i", str(video), "-vn",
             "-af", "silencedetect=noise=-38dB:d=0.25", "-f", "null", "-"])
    st = [float(x) for x in re.findall(r"silence_start: (-?[\d.]+)", p.stderr)]
    en = [float(x) for x in re.findall(r"silence_end: ([\d.]+)", p.stderr)]
    sil = sum(max(0.0, e - s) for s, e in zip(st, en)) + (max(0.0, dur - st[-1]) if len(st) > len(en) else 0.0)
    out["silenceShare"] = round(min(1.0, sil / dur), 3) if dur else None
    out["silences"] = len(st)
    if out["lufs"] is not None and out["lufs"] < -60:
        out["present"] = False
    # tốc độ nói: chỉ khi faster-whisper + model đã có sẵn trên máy (không tải mạng)
    out["speech"] = None
    if whisper and out["present"]:
        out["speech"] = speech_rate(video, start, dur)
    # đoán: nhiều khoảng lặng ngắn xen kẽ = lời nói; gần như không lặng = nhạc nền phủ kín
    sp = out["speech"]
    if sp and sp.get("words", 0) >= 3:
        out["narrationGuess"] = True
    elif out["present"]:
        out["narrationGuess"] = None  # không chắc: để AI ghi "(đoán)"
    else:
        out["narrationGuess"] = False
    out["musicBedGuess"] = bool(out["present"] and (out["silenceShare"] or 0) < 0.1)
    return out


def speech_rate(video: Path, start: float, dur: float) -> dict | None:
    try:
        from faster_whisper import WhisperModel  # type: ignore
    except Exception:
        return None
    name = os.environ.get("LUMREELS_STUDY_WHISPER", "small")
    hub = Path(os.environ.get("HF_HOME", Path.home() / ".cache" / "huggingface")) / "hub" / f"models--Systran--faster-whisper-{name}"
    if not hub.exists():
        return None
    wav = None
    try:
        import tempfile
        fd, wav = tempfile.mkstemp(suffix=".wav")
        os.close(fd)
        run(["ffmpeg", "-y", "-v", "error", "-ss", f"{start}", "-t", f"{dur}", "-i", str(video), "-vn", "-ac", "1", "-ar", "16000", wav])
        os.environ.setdefault("HF_HUB_OFFLINE", "1")
        # CPU int8: 8 giây tiếng chạy vài giây, khỏi phụ thuộc thư viện CUDA (máy thiếu cublas thì "auto" hỏng lúc chạy)
        model = WhisperModel(name, device="cpu", compute_type="int8")
        segs, info = model.transcribe(wav, vad_filter=True, word_timestamps=False)
        words, voiced = 0, 0.0
        for s in segs:
            words += len(s.text.split())
            voiced += max(0.0, s.end - s.start)
        return {"words": words, "voicedS": round(voiced, 2), "wpm": round(words / (dur / 60), 1) if dur else None,
                "lang": info.language, "langProb": round(float(info.language_probability), 2), "model": name}
    except Exception as e:  # noqa: BLE001
        return {"error": str(e)[:160]}
    finally:
        if wav and os.path.exists(wav):
            os.remove(wav)


def brightness(frames_rgb: np.ndarray) -> dict:
    lum = (frames_rgb.astype(np.float32) @ np.array([0.299, 0.587, 0.114], dtype=np.float32)) / 255.0
    per = lum.mean(axis=(1, 2))
    sat = frames_rgb.max(-1).astype(np.float32) - frames_rgb.min(-1).astype(np.float32)
    return {"mean": round(float(per.mean()), 3), "min": round(float(per.min()), 3), "max": round(float(per.max()), 3),
            "contrast": round(float(lum.std()), 3), "saturation": round(float(sat.mean() / 255.0), 3)}


def main(argv=None) -> int:
    ap = argparse.ArgumentParser(description="Đo video tham khảo cho guidance mẫu dựng")
    ap.add_argument("video")
    ap.add_argument("out")
    ap.add_argument("--from", dest="start", type=float, default=0.0)
    ap.add_argument("--dur", type=float, default=8.0)
    ap.add_argument("--no-audio", action="store_true")
    ap.add_argument("--no-whisper", action="store_true")
    ap.add_argument("--no-frames", action="store_true", help="không xuất sheet/frames (đo bản dựng thử chỉ cần số)")
    a = ap.parse_args(argv)
    t0 = time.time()
    video = Path(a.video).resolve()
    out = Path(a.out).resolve()
    out.mkdir(parents=True, exist_ok=True)
    info = probe(video)
    start = max(0.0, min(a.start, max(0.0, info["duration"] - 1.0)))
    dur = max(1.0, min(a.dur, info["duration"] - start)) if info["duration"] else a.dur
    emit("progress", {"step": "frames"})
    if not a.no_frames:
        sheet_and_frames(video, start, out, dur)
    emit("progress", {"step": "pixels"})
    rgb16 = grab(video, start + dur / 32, dur, 16 / dur, 64, 114, gray=False)  # 16 khung giữa mỗi ô lưới
    gray10 = grab(video, start, dur, 10, W_SMALL, H_SMALL, gray=True)
    gray4 = gray10[::2] if len(gray10) else gray10  # 5 fps gần 4 fps của thiết kế; dùng chung 1 lần giải mã
    emit("progress", {"step": "cuts"})
    cuts30 = scene_cuts(video, start, dur, 0.30)
    cuts15 = scene_cuts(video, start, dur, 0.15)
    bounds = [0.0] + cuts30 + [round(dur, 2)]
    shots = [round(b - a2, 2) for a2, b in zip(bounds, bounds[1:]) if b - a2 > 0.05]
    res = {
        "tool": "study.py", "version": 1,
        "source": {**info, "from": round(start, 2), "dur": round(dur, 2)},
        "palette": palette(rgb16) if len(rgb16) else [],
        "brightness": brightness(rgb16) if len(rgb16) else None,
        "cuts": {"thr30": cuts30, "thr15": cuts15, "shotLengths": shots,
                 "medianShot": round(float(np.median(shots)), 2) if shots else round(dur, 2)},
        "events": visual_events(gray10, 10),
        "motion": motion_stats(gray4, 5),
        "faces": faces(out / "frames") if not a.no_frames else {"available": False, "share": None},
    }
    if info["hasAudio"] and not a.no_audio:
        emit("progress", {"step": "audio"})
        res["audio"] = audio_stats(video, start, dur, whisper=not a.no_whisper)
    else:
        res["audio"] = {"present": bool(info["hasAudio"]), "measured": False}
    res["seconds"] = round(time.time() - t0, 1)
    (out / "study.json").write_text(json.dumps(res, ensure_ascii=False, indent=1), encoding="utf-8")
    emit("result", {"ok": True, "study": str(out / "study.json"), "seconds": res["seconds"],
                    "events_per_s": res["events"]["perSecond"], "motion": res["motion"]["mean"], "cuts": len(cuts30)})
    return 0


if __name__ == "__main__":
    sys.stdout.reconfigure(encoding="utf-8")
    sys.exit(main())