169 lines
6.6 KiB
Python
169 lines
6.6 KiB
Python
"""Calibration tool for the CODE/TERMINAL layout.
|
|
|
|
Usage (from the repo root):
|
|
|
|
python -m clipwright.tools.verify_code_layout path/to/recording.mp4 \
|
|
--start 12.0 --duration 8 --out-dir output/code_layout
|
|
|
|
It forces the layout on (ignoring ``CODE_LAYOUT``), detects the pane, prints
|
|
pane / confidence / mode, writes:
|
|
|
|
- ``debug_bands.png`` — a schematic of the 9:16 output with the code band and
|
|
the caption reserve marked;
|
|
- ``still.png`` — a real render through ``code_filtergraph`` at ``--start``.
|
|
|
|
Exit codes: 0 on a detected pane and a rendered still; 1 when nothing detects
|
|
(so a corpus sweep can flag misses); 2 when cv2 is unavailable.
|
|
|
|
The detection thresholds in ``code_layout`` are estimates from first
|
|
principles. Run this across a set of real 1440p IDE and terminal recordings and
|
|
tune ``CODE_*`` from what actually lands here.
|
|
"""
|
|
import argparse
|
|
import os
|
|
import subprocess
|
|
import sys
|
|
|
|
DEFAULT_OUT = "output/code_layout"
|
|
|
|
|
|
def _parse_args(argv):
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("video", help="path to the source recording")
|
|
parser.add_argument("--start", type=float, default=0.0,
|
|
help="segment start in seconds")
|
|
parser.add_argument("--duration", type=float, default=6.0,
|
|
help="seconds of active-line tracking to sample")
|
|
parser.add_argument("--samples", type=int, default=12,
|
|
help="frames sampled for pane detection")
|
|
parser.add_argument("--out-w", type=int, default=1080)
|
|
parser.add_argument("--out-h", type=int, default=1920)
|
|
parser.add_argument("--out-dir", default=DEFAULT_OUT)
|
|
parser.add_argument("--no-follow", action="store_true",
|
|
help="skip active-line tracking (static window)")
|
|
return parser.parse_args(argv)
|
|
|
|
|
|
def _draw_bands(path, pane, out_w, out_h, graph):
|
|
"""Schematic of the output: backdrop, code band, caption reserve."""
|
|
import cv2
|
|
import numpy as np
|
|
|
|
canvas = np.full((out_h, out_w, 3), 32, dtype=np.uint8)
|
|
content_h, caption_h = _bands(out_h)
|
|
scale = out_w / float(pane["w"])
|
|
scaled_h = min(content_h, int(round(pane["h"] * scale)))
|
|
y_off = max(0, (content_h - scaled_h) // 2)
|
|
|
|
cv2.rectangle(canvas, (0, y_off), (out_w - 1, y_off + scaled_h),
|
|
(40, 160, 40), thickness=-1)
|
|
cv2.rectangle(canvas, (0, out_h - caption_h), (out_w - 1, out_h - 1),
|
|
(160, 90, 40), thickness=-1)
|
|
cv2.putText(canvas, f"pane {pane['w']}x{pane['h']} @ {pane['x']},{pane['y']}",
|
|
(16, 40), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 255, 255), 2)
|
|
cv2.putText(canvas, f"code band h={scaled_h}",
|
|
(16, y_off + max(30, scaled_h // 2)),
|
|
cv2.FONT_HERSHEY_SIMPLEX, 0.9, (255, 255, 255), 2)
|
|
cv2.putText(canvas, "caption reserve",
|
|
(16, out_h - caption_h + max(30, caption_h // 2)),
|
|
cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 255, 255), 2)
|
|
if "sendcmd" in graph:
|
|
cv2.putText(canvas, "sendcmd follow ON",
|
|
(16, out_h - 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7,
|
|
(80, 220, 255), 2)
|
|
cv2.imwrite(path, canvas)
|
|
|
|
|
|
def _bands(out_h):
|
|
from clipwright.layouts import code_layout
|
|
return code_layout.code_bands(out_h)
|
|
|
|
|
|
def _render_still(video, start, graph, out_path):
|
|
cmd = [
|
|
"ffmpeg", "-y", "-loglevel", "error",
|
|
"-ss", f"{start:.4f}", "-i", video,
|
|
"-frames:v", "1",
|
|
"-filter_complex", graph, "-map", "[v]",
|
|
out_path,
|
|
]
|
|
proc = subprocess.run(cmd, capture_output=True, text=True)
|
|
if proc.returncode != 0:
|
|
print(f"❌ ffmpeg failed:\n{proc.stderr}")
|
|
return False
|
|
return os.path.exists(out_path) and os.path.getsize(out_path) > 0
|
|
|
|
|
|
def main(argv=None):
|
|
args = _parse_args(argv if argv is not None else sys.argv[1:])
|
|
try:
|
|
import cv2 # noqa: F401 (presence check only)
|
|
except ImportError:
|
|
print("❌ OpenCV (cv2) is required to run this tool.")
|
|
return 2
|
|
|
|
from clipwright.layouts import code_layout
|
|
code_layout.ENABLED = True
|
|
code_layout.FOLLOW_ENABLED = True
|
|
|
|
if not os.path.exists(args.video):
|
|
print(f"❌ No such video: {args.video}")
|
|
return 1
|
|
|
|
os.makedirs(args.out_dir, exist_ok=True)
|
|
|
|
pane = code_layout.detect_code_pane(args.video, samples=args.samples)
|
|
if pane is None:
|
|
print("❌ No code pane detected — nothing to render. "
|
|
"Tune CODE_PANE_MIN_* / CODE_EDGE_DENSITY / CODE_STABILITY_*.")
|
|
return 1
|
|
|
|
print(f"✅ Pane: x={pane['x']} y={pane['y']} w={pane['w']} h={pane['h']} "
|
|
f"({pane['w']}x{pane['h']})")
|
|
print(f" mode={pane['mode']} confidence={pane['confidence']:.2f} "
|
|
f"frame={pane['frame_w']}x{pane['frame_h']}")
|
|
|
|
# Mirror reframe_v2: if the text column is still wider than the readable
|
|
# scale allows, crop it to out_w / MIN_SCALE rather than falling back.
|
|
max_w = max(2, int(args.out_w / code_layout.MIN_SCALE))
|
|
clamped = code_layout.clamp_pane_width(pane, max_w)
|
|
if clamped[2] != pane["w"]:
|
|
print(f" clamped text column {pane['w']} -> {clamped[2]}px "
|
|
f"(CODE_MIN_SCALE={code_layout.MIN_SCALE})")
|
|
pane = dict(pane, x=clamped[0], y=clamped[1], w=clamped[2], h=clamped[3])
|
|
print(f" scale: {args.out_w / float(pane['w']):.2f}")
|
|
|
|
follow = None
|
|
if not args.no_follow:
|
|
series = code_layout.active_line_series(
|
|
args.video, pane, args.start, args.start + args.duration)
|
|
if series:
|
|
# code_filtergraph expects timestamps relative to the segment start.
|
|
follow = [(t - args.start, y) for t, y in series]
|
|
print(f" follow: {len(follow)} points over "
|
|
f"{follow[0][0]:.1f}-{follow[-1][0]:.1f}s")
|
|
else:
|
|
print(" follow: no reliable active-line series (static window)")
|
|
|
|
graph = code_layout.code_filtergraph(pane, args.out_w, args.out_h,
|
|
follow=follow)
|
|
if graph is None:
|
|
scale = args.out_w / float(max(1, pane["w"]))
|
|
print(f"❌ Scale {scale:.2f} < CODE_MIN_SCALE "
|
|
f"({code_layout.MIN_SCALE}) — this clip falls back to "
|
|
f"SCREENCAST/WIDE.")
|
|
return 1
|
|
|
|
debug_path = os.path.join(args.out_dir, "debug_bands.png")
|
|
still_path = os.path.join(args.out_dir, "still.png")
|
|
_draw_bands(debug_path, pane, args.out_w, args.out_h, graph)
|
|
if not _render_still(args.video, args.start, graph, still_path):
|
|
return 1
|
|
|
|
print(f"🖼️ wrote {debug_path}")
|
|
print(f"🖼️ wrote {still_path}")
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|