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.

4.2 KB
Raw Blame
"""Tải/lấy video tham chiếu của mẫu và tách khung hình để viết guidance.

Video tham chiếu là tài liệu RIÊNG trên máy mày: thư mục templates/ref/ và templates/private/
nằm trong .gitignore, không đưa lên repo. Chỉ dùng video mày tự quay/tự dựng hoặc có quyền dùng.

Nguồn danh sách: templates/private/refs.json (mặc định) — mảng các mục
    {"id": "106", "file": "D:/quay/mau-106.mp4"}          # file trên máy
    {"id": "107", "url": "https://..."}                    # link (tải bằng yt-dlp)
(file cũ templates/private/manifest.source.json dạng {"id", "youtube"} vẫn đọc được).

Mỗi mẫu ra: templates/ref/<id>/video.mp4, frames/f_01..16.jpg (2 khung/giây),
sheet.jpg (lưới 4x4 đọc trái→phải, trên→dưới), audio.m4a, info.json.
Chạy lại an toàn: mẫu đã có sheet.jpg thì bỏ qua.
Dùng:
    python tools/fetch_refs.py [id ...]
    python tools/fetch_refs.py --file <video.mp4> <id>     # 1 video trên máy, không cần refs.json
"""
import json, shutil, subprocess, sys
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
REF = ROOT / "templates" / "ref"
PRIVATE = ROOT / "templates" / "private"
SOURCES = [PRIVATE / "refs.json", PRIVATE / "manifest.source.json"]


def run(cmd):
    return subprocess.run(cmd, capture_output=True, text=True, encoding="utf-8", errors="replace")


def load_items():
    items, seen = [], set()
    for f in SOURCES:
        if not f.exists():
            continue
        for it in json.loads(f.read_text(encoding="utf-8")):
            if it["id"] in seen:
                continue
            seen.add(it["id"])
            items.append(it)
    return items


def extract(d, vid):
    p = run(["ffprobe", "-v", "error", "-show_entries", "format=duration:stream=width,height,r_frame_rate,codec_type",
             "-of", "json", str(vid)])
    (d / "info.json").write_text(p.stdout, encoding="utf-8")
    run(["ffmpeg", "-y", "-v", "error", "-i", str(vid), "-vf", "fps=2,scale=540:-2", "-frames:v", "16",
         "-q:v", "3", str(d / "frames" / "f_%02d.jpg")])
    run(["ffmpeg", "-y", "-v", "error", "-i", str(vid), "-vf", "fps=2,scale=360:-2,tile=4x4", "-frames:v", "1",
         "-q:v", "3", str(d / "sheet.jpg")])
    run(["ffmpeg", "-y", "-v", "error", "-i", str(vid), "-vn", "-c:a", "copy", str(d / "audio.m4a")])
    return (d / "sheet.jpg").exists()


def main():
    args = sys.argv[1:]
    if args[:1] == ["--file"]:
        if len(args) != 3:
            sys.exit("Dùng: python tools/fetch_refs.py --file <video.mp4> <id>")
        src, rid = Path(args[1]), args[2].zfill(3)
        d = REF / rid
        (d / "frames").mkdir(parents=True, exist_ok=True)
        shutil.copyfile(src, d / "video.mp4")
        print("ok" if extract(d, d / "video.mp4") else "FAIL", rid)
        return
    items = load_items()
    if not items:
        sys.exit("Chưa có danh sách: tạo templates/private/refs.json hoặc dùng --file <video> <id>")
    only = set(a.zfill(3) for a in args)
    ok, fail = 0, []
    for it in items:
        if only and it["id"] not in only:
            continue
        d = REF / it["id"]
        if (d / "sheet.jpg").exists():
            ok += 1
            continue
        (d / "frames").mkdir(parents=True, exist_ok=True)
        vid = d / "video.mp4"
        if not vid.exists():
            if it.get("file"):
                shutil.copyfile(it["file"], vid)
            elif it.get("url"):
                r = run(["yt-dlp", "-q", "--no-playlist", "-f", "bv*[height<=1280][ext=mp4]+ba[ext=m4a]/b[ext=mp4]/b",
                         "--merge-output-format", "mp4", "-o", str(vid), it["url"]])
                if not vid.exists():
                    fail.append((it["id"], "download: " + r.stderr.strip()[-200:]))
                    continue
            else:
                fail.append((it["id"], "thiếu file/url"))
                continue
        if extract(d, vid):
            ok += 1
            print("ok", it["id"], flush=True)
        else:
            fail.append((it["id"], "ffmpeg"))
    print(f"DONE ok={ok} fail={len(fail)}")
    for f in fail:
        print("FAIL", *f)


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