clipwright/clipwright/layouts/code_layout.py
pedro-bento 2dc1ba1eea
All checks were successful
CI / backend-e2e (push) Successful in 1m20s
CI / unit (push) Successful in 45s
CI / dashboard-e2e (push) Successful in 2m31s
feat/youtube-growth-toolkit (#8)
Reviewed-on: #8
Co-authored-by: pedro-bento <mail@pbento.pt>
Co-committed-by: pedro-bento <mail@pbento.pt>
2026-10-05 20:33:56 +01:00

909 lines
35 KiB
Python

"""CODE/TERMINAL vertical layout: an IDE or terminal recording in 9:16.
The case every screen layout here handles badly: a maximized 1440p editor or a
terminal window. The existing SCREENCAST layout treats it as "content over a
presenter", which on a code recording means the output is the whole 1440p frame
shrunk to a 608px strip — 24px of glyph height at best, unreadable on a phone.
What a code recording actually needs is the opposite trade. The viewer has to
read characters, so the *pane* is cropped to one column of code and scaled up to
fill the width, with the source's blur as decorative filler above and below, and
the bottom ~15% left clear for captions. When the pane is taller than the output
band, a crop window has to follow the active line (a `sendcmd` pan) so the line
being typed stays on screen.
Design, following the ``camera_inset`` pattern:
- module ``ENABLED`` read from ``CODE_LAYOUT`` (off by default);
- ``detect_code_pane`` -> geometry (a self-contained edge/row-column detector,
like ``split_layout.detect_split_scenes``: no ``content_ranges`` dead wire);
- pure geometry helpers (``pane_from_projections``, ``stable_pane``,
``fit_window``, ``follow_sendcmd_lines``) so the decisions are unit-testable
without OpenCV;
- ``code_filtergraph`` -> crop -> scale -> overlay on a blurred backdrop.
Everything tunable is an env-overridable constant. The thresholds were set from
first principles and *must* be calibrated against a real 1440p corpus with
``clipwright/tools/verify_code_layout.py`` before the layout is enabled by
default.
Import-time cost is ``numpy`` only; ``cv2`` is imported lazily inside the frame
functions so the unit suite (which has no OpenCV) still collects this module.
"""
import os
import numpy as np
from clipwright.media.ffmpeg_utils import blurred_backdrop
# Off by default: a wrong CODE crop shows a wall of clipped glyphs, which is a
# worse failure than leaving a code clip on the TRACK/WIDE default.
ENABLED = os.environ.get("CODE_LAYOUT", "0") == "1"
# ---------------------------------------------------------------------------
# Env-overridable tuning. See clipwright/tools/verify_code_layout.py for the
# corpus pass that produces real numbers for these; the defaults are estimates.
# ---------------------------------------------------------------------------
# Pan the crop window to keep the active line visible on a tall pane.
FOLLOW_ENABLED = os.environ.get("CODE_FOLLOW", "1") == "1"
# Extra zoom on top of "fit the pane width to the output width". 1.0 keeps the
# whole pane width; >1 crops a narrower column and scales it up (bigger glyphs).
ZOOM = float(os.environ.get("CODE_ZOOM", "1.0"))
# Minimum horizontal scale (out_w / pane_w). Below this the pane is being
# downscaled so far that the text stops being readable, and the caller should
# fall back to SCREENCAST/WIDE. At 1440p maximized, out_w/pane_w == 1080/1440 ==
# 0.75 exactly, so a maximized editor sits on the boundary and a maximized
# ultrawide falls through.
MIN_SCALE = float(os.environ.get("CODE_MIN_SCALE", "0.75"))
# Face/camera band height, as a fraction of out_h, when a cam_box is supplied.
CAMERA_BAND_RATIO = float(os.environ.get("CODE_CAMERA_BAND", "0.18"))
# Bottom band reserved for captions, as a fraction of out_h.
CAPTION_BAND_RATIO = float(os.environ.get("CODE_CAPTION_BAND", "0.15"))
# Pane gates, as a fraction of the frame. A corner panel is not a code pane.
PANE_MIN_WIDTH_FRAC = float(os.environ.get("CODE_PANE_MIN_WIDTH", "0.35"))
PANE_MIN_HEIGHT_FRAC = float(os.environ.get("CODE_PANE_MIN_HEIGHT", "0.25"))
# Edge-density floor inside the pane (fraction of pixels above the Sobel
# threshold). Flat wallpapers and photos fall below it.
EDGE_DENSITY_FLOOR = float(os.environ.get("CODE_EDGE_DENSITY", "0.02"))
# Temporal stability: the pane centre must stay within this fraction of the
# frame across samples, for at least this fraction of them.
STABILITY_TOLERANCE = float(os.environ.get("CODE_STABILITY_TOLERANCE", "0.04"))
STABILITY_MIN_FRAC = float(os.environ.get("CODE_STABILITY_FRAC", "0.6"))
# Detection runs on a copy at most this wide. Sobel/close is O(pixels) and the
# pane geometry does not need full resolution.
DETECT_MAX_WIDTH = int(os.environ.get("CODE_DETECT_WIDTH", "960"))
# Wide-short morphological close: joins glyphs into horizontal line runs
# without merging adjacent text lines (which a square kernel does).
CLOSE_KERNEL = (35, 3)
# Fraction of the projection max that counts as pane edge mass.
PROJ_THRESHOLD_RATIO = float(os.environ.get("CODE_PROJ_THRESHOLD", "0.15"))
# Below this scaled Sobel magnitude a frame contributes no edge map.
SOBEL_FLOOR = float(os.environ.get("CODE_SOBEL_FLOOR", "8.0"))
SOBEL_RATIO = 0.15
# Active-line tracking.
ACTIVE_MAX_WIDTH = int(os.environ.get("CODE_ACTIVE_WIDTH", "480"))
ACTIVE_BAND_FRAC = 0.20
ACTIVE_MIN_CONCENTRATION = float(
os.environ.get("CODE_ACTIVE_CONCENTRATION", "0.35"))
ACTIVE_MIN_MASS = float(os.environ.get("CODE_ACTIVE_MASS", "1500"))
# Editor classification: syntax highlighting raises chroma variance above a
# plain terminal's.
EDITOR_SAT_STD = float(os.environ.get("CODE_EDITOR_SAT_STD", "28"))
GUTTER_FRACTION = 0.12
# IDE chrome masking. A maximized editor's window is the whole 2560px of a 1440p
# source, so a whole-window pane scales at 1080/2560 ~= 0.42 and trips
# MIN_SCALE. What we want is the TEXT COLUMN: the activity bar and sidebar sit
# in the left margin and the minimap in the right, each separated from the code
# by a sustained blank border. The detector searches within these margins for
# that blank run and cuts there; with no chrome (a bare terminal) there is no
# run and the full width is kept. Widths vary by theme and zoom — tune
# CODE_CHROME_* and CODE_TEXT_* from tools/verify_code_layout.py.
CHROME_LEFT_FRAC = float(os.environ.get("CODE_CHROME_LEFT", "0.22"))
CHROME_RIGHT_FRAC = float(os.environ.get("CODE_CHROME_RIGHT", "0.10"))
CHROME_BOTTOM_FRAC = float(os.environ.get("CODE_CHROME_BOTTOM", "0.03"))
# A "gap" is a sustained run of columns below this share of the text max.
GAP_FRAC = float(os.environ.get("CODE_GAP_FRAC", "0.08"))
GAP_PX = int(os.environ.get("CODE_GAP_PX", "4"))
TEXT_CORE_FRAC = float(os.environ.get("CODE_TEXT_CORE", "0.35"))
TEXT_MIN_WIDTH_FRAC = float(os.environ.get("CODE_TEXT_MIN_WIDTH", "0.2"))
# Per-scene verification: share of frames sampled inside the pane that must
# still read as code for the scene to keep CODE (otherwise its other verdict
# stands). A cutaway to the facecam fails the texture/palette checks.
SCENE_CODE_FRAC = float(os.environ.get("CODE_SCENE_FRAC", "0.5"))
# ---------------------------------------------------------------------------
# Pure geometry (no cv2): projections -> pane, stability, band layout, sendcmd.
# ---------------------------------------------------------------------------
def _extent(projection, threshold):
"""First/last index above ``threshold`` (end exclusive), or None."""
idx = np.flatnonzero(np.asarray(projection, dtype=float) > threshold)
if idx.size == 0:
return None
return int(idx[0]), int(idx[-1]) + 1
def pane_from_projections(row_proj, col_proj, frame_w, frame_h,
min_width_frac=PANE_MIN_WIDTH_FRAC,
min_height_frac=PANE_MIN_HEIGHT_FRAC,
threshold_ratio=PROJ_THRESHOLD_RATIO):
"""Locate the code pane from 1-D row/column edge projections.
``row_proj`` is per-row edge mass (length = pane-space height) and
``col_proj`` per-column. The pane is the bounding extent of edge mass above
a fraction of each projection's own max: text lines are many separated rows
of mass, so a "longest contiguous run" would lock onto a single line. The
extent is in the same coordinate space as ``frame_w``/``frame_h`` (detection
passes the downscaled size; the fractions are scale-invariant).
Returns ``(x, y, w, h)`` or None when the box is missing or fails either
size gate.
"""
rows = np.asarray(row_proj, dtype=float)
cols = np.asarray(col_proj, dtype=float)
if rows.size == 0 or cols.size == 0:
return None
if rows.max() <= 0 or cols.max() <= 0:
return None
ry = _extent(rows, threshold_ratio * rows.max())
cx = _extent(cols, threshold_ratio * cols.max())
if ry is None or cx is None:
return None
y0, y1 = ry
x0, x1 = cx
w, h = x1 - x0, y1 - y0
if w < min_width_frac * frame_w or h < min_height_frac * frame_h:
return None
return (x0, y0, w, h)
def _smooth(values, window=9):
v = np.asarray(values, dtype=float)
if window <= 1 or v.size < window:
return v
kernel = np.ones(window, dtype=float) / window
return np.convolve(v, kernel, mode="same")
def _gaps(below, gap_px):
"""(start, end) of every sustained True run in a boolean array."""
out = []
start = None
for i, flag in enumerate(below):
if flag and start is None:
start = i
elif not flag and start is not None:
if i - start >= gap_px:
out.append((start, i))
start = None
if start is not None and len(below) - start >= gap_px:
out.append((start, len(below)))
return out
def text_column_extent(col_proj, frame_w, left_skip_frac=CHROME_LEFT_FRAC,
right_skip_frac=CHROME_RIGHT_FRAC,
core_frac=TEXT_CORE_FRAC,
min_width_frac=TEXT_MIN_WIDTH_FRAC,
gap_frac=GAP_FRAC, gap_px=GAP_PX, smooth=9):
"""(x0, x1) of the editor text column, with IDE chrome cut off.
``col_proj`` is per-column edge mass. The whole extent of edge mass is
first-to-last above ``core_frac`` of the max (text fills nearly every
column across many lines, so a longest-run would lock onto one block). The
left and right margins are then searched for a sustained blank border — the
gap between the sidebar and the code, and between the code and the
minimap — and the extent is cut at the innermost one. A bare terminal has
no such border and keeps its full width. Returns None when no run clears
``min_width_frac``.
"""
cols = _smooth(col_proj, smooth)
if cols.size == 0:
return None
top = float(cols.max())
if top <= 0:
return None
core = cols > core_frac * top
if not core.any():
return None
first = int(np.argmax(core))
last = int(len(core) - np.argmax(core[::-1]))
thr = gap_frac * top
x0 = first
window = cols[first:first + int(round(left_skip_frac * frame_w))]
gaps = _gaps(window < thr, max(2, gap_px))
if gaps:
x0 = first + gaps[-1][1]
x1 = last
rstart = max(x0, last - int(round(right_skip_frac * frame_w)))
window = cols[rstart:last]
gaps = _gaps(window < thr, max(2, gap_px))
if gaps:
x1 = rstart + gaps[-1][0]
if x1 - x0 < min_width_frac * frame_w:
return None
return x0, x1
def clamp_pane_width(pane, max_width, anchor="left"):
"""Narrow a pane to at most ``max_width`` columns.
Used when the text column is still wider than the readable scale allows
(1080 / MIN_SCALE ~= 1440 on a 1440p source): code is left-aligned, so
keeping the left edge keeps indentation and line starts. Returns an even
``(x, y, w, h)`` tuple.
"""
x, y, w, h = _pane_box(pane)
max_width = int(max_width) - (int(max_width) % 2)
if max_width < 2:
max_width = 2
if w <= max_width:
return (x, y, w, h)
nx = x + (w - max_width) // 2 if anchor == "center" else x
nx = max(0, nx - (nx % 2))
return (nx, y, max_width, h)
def _stable_members(boxes, frame_w, frame_h, tolerance):
arr = np.asarray(boxes, dtype=float)
cx = arr[:, 0] + arr[:, 2] / 2.0
cy = arr[:, 1] + arr[:, 3] / 2.0
mid_x, mid_y = float(np.median(cx)), float(np.median(cy))
close = ((np.abs(cx - mid_x) <= tolerance * frame_w)
& (np.abs(cy - mid_y) <= tolerance * frame_h))
return arr, close
def stable_pane(boxes, frame_w, frame_h, tolerance=STABILITY_TOLERANCE,
min_frac=STABILITY_MIN_FRAC):
"""Median box over the samples that agree, or None.
A pane that jumps around the screen is a moving camera or a slideshow, not a
fixed editor window; clustering around the median tolerates one stray sample
without tolerating real movement.
"""
if not boxes:
return None
arr, close = _stable_members(boxes, frame_w, frame_h, tolerance)
if int(close.sum()) < max(2, int(round(min_frac * len(boxes)))):
return None
return tuple(int(round(v)) for v in np.median(arr[close], axis=0))
def stability_fraction(boxes, frame_w, frame_h, tolerance=STABILITY_TOLERANCE):
"""Fraction of samples whose centre agrees with the median."""
if not boxes:
return 0.0
_, close = _stable_members(boxes, frame_w, frame_h, tolerance)
return float(close.mean()) if close.size else 0.0
def edge_density(mask, box):
"""Fraction of set pixels inside ``box`` (mask may be 0/1 or 0/255)."""
x, y, w, h = (int(v) for v in box[:4])
m = np.asarray(mask)
sub = m[max(0, y):y + h, max(0, x):x + w]
if sub.size == 0:
return 0.0
scale = 255.0 if sub.max() > 1 else 1.0
return float(sub.mean()) / scale
def code_bands(out_h, caption_ratio=None):
"""(content_h, caption_h): even, positive, and summing to ``out_h``."""
ratio = CAPTION_BAND_RATIO if caption_ratio is None else caption_ratio
caption_h = int(round(out_h * ratio))
caption_h -= caption_h % 2
caption_h = max(2, min(caption_h, out_h - 2))
content_h = out_h - caption_h
return content_h, caption_h
def fit_window(pane_h, scale, band_h):
"""(crop_h, scaled_h, needs_follow) for a pane of ``pane_h`` at ``scale``.
``crop_h`` is the source window height, ``scaled_h`` its height after
scaling, both even and clamped so ``scaled_h <= band_h``. ``needs_follow``
is True when the pane is taller than the band and only a window can fit.
"""
pane_h = max(2, int(pane_h))
if scale <= 0:
return None
full_scaled = pane_h * scale
if full_scaled <= band_h:
scaled_h = int(round(full_scaled))
scaled_h += scaled_h % 2
scaled_h = max(2, min(scaled_h, band_h))
crop_h = pane_h - (pane_h % 2)
return max(2, crop_h), scaled_h, False
crop_h = int(round(band_h / scale))
crop_h += crop_h % 2
crop_h = max(2, min(crop_h, pane_h - (pane_h % 2)))
scaled_h = band_h - (band_h % 2)
return crop_h, max(2, scaled_h), True
def follow_sendcmd_lines(follow, pane_y, window_h, pane_h, start=0.0,
target="crop@c"):
"""sendcmd lines panning a crop window to the active line.
``follow`` is ``[(timestamp, source_y), ...]`` where ``timestamp`` is in the
source's clock; ``start`` is the segment start, subtracted so the emitted
timestamps are relative to the segment (the render seeks per scene). Only
change-points are emitted: ``y`` is clamped to the pane and deduped.
"""
lines = []
prev = None
lo = int(pane_y)
hi = max(lo, int(pane_y + pane_h - window_h))
for t, y in follow:
rel = float(t) - float(start)
if rel < 0:
continue
top = int(round(float(y) - window_h / 2.0))
top = max(lo, min(top, hi))
top -= top % 2
if top == prev:
continue
lines.append(f"{rel:.4f} {target} y {top};")
prev = top
return lines
def _pane_box(pane):
if isinstance(pane, dict):
return (int(pane["x"]), int(pane["y"]), int(pane["w"]), int(pane["h"]))
return tuple(int(v) for v in pane[:4])
def code_filtergraph(pane, out_w, out_h, follow=None, cam_box=None,
min_scale=MIN_SCALE, caption_ratio=None, zoom=None):
"""Crop the code pane, scale it to ``out_w``, overlay on a blurred backdrop.
``pane`` is an ``(x, y, w, h)`` tuple or a ``detect_code_pane`` dict in
SOURCE coordinates. ``follow`` is a segment-relative
``[(t, source_y), ...]`` series from ``active_line_series``; it produces a
``sendcmd`` pan when the pane is taller than the content band. ``cam_box``
optionally overlays a face in the caption band.
Returns the filtergraph string ending in ``[v]``, or None when
``out_w / pane_w < min_scale`` so the caller can fall back to
SCREENCAST/WIDE.
"""
x, y, w, h = _pane_box(pane)
x = max(0, x - (x % 2))
y = max(0, y - (y % 2))
w = max(2, w - (w % 2))
h = max(2, h - (h % 2))
fit = out_w / float(w)
if fit < min_scale:
return None
z = ZOOM if zoom is None else zoom
scale = fit * max(0.1, float(z))
if scale <= 0:
return None
content_h, caption_h = code_bands(out_h, caption_ratio)
# Horizontal crop window: at zoom 1 this is the whole pane width.
crop_w = int(round(out_w / scale))
crop_w += crop_w % 2
crop_w = max(2, min(crop_w, w))
crop_x = x + (w - crop_w) // 2
crop_x = max(0, crop_x - (crop_x % 2))
fitted = fit_window(h, scale, content_h)
if fitted is None:
return None
crop_h, scaled_h, needs_follow = fitted
y_off = max(0, (content_h - scaled_h) // 2)
window_top = None
if needs_follow:
window_top = y + (h - crop_h) // 2
if follow:
window_top = int(round(float(follow[0][1]) - crop_h / 2.0))
window_top = max(y, min(window_top, y + h - crop_h))
window_top -= window_top % 2
if needs_follow and follow:
lines = follow_sendcmd_lines(follow, y, crop_h, h, start=0.0)
else:
lines = []
if lines:
# Each line is already ';'-terminated; concatenating avoids the empty
# command a second separator would produce.
commands = "".join(lines)
fg = (f"sendcmd=c='{commands}',"
f"crop@c=w={crop_w}:h={crop_h}:x={crop_x}:y={window_top},"
f"scale={out_w}:{scaled_h}[code]")
else:
static_y = (window_top if window_top is not None
else y + (h - crop_h) // 2)
static_y = max(y, min(static_y, y + h - crop_h))
static_y -= static_y % 2
fg = (f"crop=w={crop_w}:h={crop_h}:x={crop_x}:y={static_y},"
f"scale={out_w}:{scaled_h}[code]")
parts = []
if cam_box is not None:
cx, cy, cw, ch = _pane_box(cam_box)
cx = max(0, cx - (cx % 2))
cy = max(0, cy - (cy % 2))
cw = max(2, cw - (cw % 2))
ch = max(2, ch - (ch % 2))
cam_h = int(round(out_h * CAMERA_BAND_RATIO))
cam_h -= cam_h % 2
cam_h = max(2, min(cam_h, caption_h))
parts.append("[0:v]split=3[bga][fga][cama];")
parts.append(f"[bga]{blurred_backdrop(out_w, out_h, 12)}[bg];")
parts.append(f"[fga]{fg};")
parts.append(f"[cama]crop=w={cw}:h={ch}:x={cx}:y={cy},"
f"scale={out_w}:{cam_h}[cam];")
parts.append(f"[bg][code]overlay=x=0:y={y_off}[withcode];")
parts.append(f"[withcode][cam]overlay=x=0:y={out_h - caption_h},"
f"setsar=1[v]")
else:
parts.append("[0:v]split=2[bga][fga];")
parts.append(f"[bga]{blurred_backdrop(out_w, out_h, 12)}[bg];")
parts.append(f"[fga]{fg};")
parts.append(f"[bg][code]overlay=x=0:y={y_off},setsar=1[v]")
return "".join(parts)
# ---------------------------------------------------------------------------
# OpenCV detection (lazy import).
# ---------------------------------------------------------------------------
def _downscale(frame, max_width):
import cv2
h, w = frame.shape[:2]
if w <= max_width:
return frame
factor = max_width / float(w)
return cv2.resize(frame, (max_width, max(2, int(round(h * factor)))),
interpolation=cv2.INTER_AREA)
def _edge_maps(frame, max_width=DETECT_MAX_WIDTH):
"""Sobel edge mask + wide-short close + row/column projections.
Returns a dict with the mask, closed mask, projections and the working
dimensions, or None when the frame has no gradient (black/frozen).
"""
import cv2
small = _downscale(frame, max_width)
gray = cv2.cvtColor(small, cv2.COLOR_BGR2GRAY)
gx = cv2.Sobel(gray, cv2.CV_32F, 1, 0, ksize=3)
gy = cv2.Sobel(gray, cv2.CV_32F, 0, 1, ksize=3)
mag = cv2.magnitude(gx, gy)
top = float(mag.max())
if top <= 1e-6:
return None
threshold = max(SOBEL_FLOOR, SOBEL_RATIO * top)
mask = (mag > threshold).astype(np.uint8) * 255
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, CLOSE_KERNEL)
closed = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)
return {
"mask": mask,
"closed": closed,
"row_proj": closed.sum(axis=1).astype(np.float64),
"col_proj": closed.sum(axis=0).astype(np.float64),
# The close joins glyphs into line runs, which is what the row
# projection needs — but it also bridges the blank IDE chrome borders,
# so the column projection for TEXT-COLUMN masking comes from the RAW
# mask, where the border survives.
"col_proj_raw": mask.sum(axis=0).astype(np.float64),
"w": small.shape[1],
"h": small.shape[0],
}
def _classify_pane(frame, box):
"""Editor vs terminal. Defaults to editor when the signal is weak.
An editor shows a left gutter of stable digit rows (line numbers) and
syntax highlighting raises the crop's saturation variance. A terminal has
neither: text starts at the left margin and is mostly one foreground colour.
"""
import cv2
x, y, w, h = (int(v) for v in box)
crop = frame[max(0, y):y + h, max(0, x):x + w]
if crop.size == 0:
return "editor"
hsv = cv2.cvtColor(crop, cv2.COLOR_BGR2HSV)
sat_std = float(hsv[:, :, 1].std())
gutter_w = max(4, int(w * GUTTER_FRACTION))
gutter = crop[:, :gutter_w]
gg = cv2.cvtColor(gutter, cv2.COLOR_BGR2GRAY)
gx = np.abs(cv2.Sobel(gg, cv2.CV_32F, 1, 0, ksize=3))
per_col = gx.sum(axis=0)
total = float(per_col.sum()) + 1e-6
gutter_peak = float(per_col.max() / total) if per_col.size else 0.0
if sat_std >= EDITOR_SAT_STD and gutter_peak > 0.08:
return "editor"
if sat_std < EDITOR_SAT_STD and gutter_peak <= 0.08:
return "terminal"
return "editor"
def detect_code_pane(video_path, samples=12):
"""Median code pane across sampled frames, or None.
Pipeline per sample: downscale to <= DETECT_MAX_WIDTH, Sobel magnitude mask,
wide-short morphological close (joins glyphs into line runs), row/column
projection -> bounding pane. Gates: pane width/height fractions, in-pane
edge-density floor, and temporal stability of the pane centre.
Returns ``{"x", "y", "w", "h", "mode", "confidence", "frame_w",
"frame_h"}`` in source coordinates, or None meaning "use another layout".
"""
if not ENABLED:
return None
try:
import cv2
except ImportError:
return None
cap = cv2.VideoCapture(video_path)
if not cap.isOpened():
return None
total = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
frame_w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
frame_h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
if total <= 0 or frame_w <= 0 or frame_h <= 0:
cap.release()
return None
n = max(2, int(samples))
boxes = []
densities = []
votes = {"editor": 0, "terminal": 0}
try:
for i in range(n):
cap.set(cv2.CAP_PROP_POS_FRAMES, int(i * total / n))
ok, frame = cap.read()
if not ok:
continue
maps = _edge_maps(frame)
if maps is None:
continue
det_box = pane_from_projections(
maps["row_proj"], maps["col_proj"], maps["w"], maps["h"])
if det_box is None:
continue
# The plain projection returns the whole window; cut it down to the
# text column so a maximized 1440p editor does not scale at 0.42.
# Raw projection: the morphological close would bridge the chrome
# borders this is looking for.
text_cols = text_column_extent(maps["col_proj_raw"], maps["w"])
if text_cols is not None:
x0, x1 = text_cols
else:
x0, x1 = det_box[0], det_box[0] + det_box[2]
y0 = det_box[1]
y1 = det_box[1] + det_box[3]
# Shave the status bar / window border off the bottom.
y1 -= int(round(CHROME_BOTTOM_FRAC * (y1 - y0)))
w, h = x1 - x0, y1 - y0
if (w < PANE_MIN_WIDTH_FRAC * maps["w"]
or h < PANE_MIN_HEIGHT_FRAC * maps["h"]):
continue
det_box = (x0, y0, w, h)
density = edge_density(maps["closed"], det_box)
if density < EDGE_DENSITY_FLOOR:
continue
sx = frame_w / float(maps["w"])
sy = frame_h / float(maps["h"])
box = (int(round(det_box[0] * sx)), int(round(det_box[1] * sy)),
int(round(det_box[2] * sx)), int(round(det_box[3] * sy)))
boxes.append(box)
densities.append(density)
votes[_classify_pane(frame, box)] += 1
finally:
cap.release()
if len(boxes) < 2:
return None
stable = stable_pane(boxes, frame_w, frame_h)
if stable is None:
return None
x, y, w, h = stable
if w < PANE_MIN_WIDTH_FRAC * frame_w or h < PANE_MIN_HEIGHT_FRAC * frame_h:
return None
mode = "editor" if votes["editor"] >= votes["terminal"] else "terminal"
stable_frac = stability_fraction(boxes, frame_w, frame_h)
density = float(np.mean(densities)) if densities else 0.0
confidence = max(0.0, min(1.0, 0.6 * stable_frac
+ 0.4 * min(1.0, density / (4 * EDGE_DENSITY_FLOOR))))
return {"x": x, "y": y, "w": w, "h": h, "mode": mode,
"confidence": confidence, "frame_w": frame_w, "frame_h": frame_h}
def _active_point(row_mass, total, band_frac=ACTIVE_BAND_FRAC,
min_concentration=ACTIVE_MIN_CONCENTRATION):
"""(normalised centroid, concentration, mass) of the top-mass row band.
The centroid is the mass-weighted centre of the busiest ``band_frac`` of
rows, normalised to 0..1 over the region. ``concentration`` is that band's
share of all changed pixels: a caret or highlighted line is concentrated, a
whole-screen redraw is not.
"""
n = len(row_mass)
if n == 0 or total <= 0:
return None
k = max(1, int(round(n * band_frac)))
order = np.argsort(row_mass)[-k:]
band_mass = float(row_mass[order].sum())
if band_mass <= 0:
return None
concentration = band_mass / float(total)
if concentration < min_concentration:
return None
idx = order.astype(float)
cy = float((idx * row_mass[order]).sum() / band_mass)
return (cy / (n - 1) if n > 1 else 0.0), concentration, band_mass
def _median_smooth(values, window=3):
values = np.asarray(values, dtype=float)
if window <= 1 or len(values) < window:
return values
half = window // 2
out = values.copy()
for i in range(len(values)):
lo = max(0, i - half)
hi = min(len(values), i + half + 1)
out[i] = np.median(values[lo:hi])
return out
def active_line_series(video_path, pane, start, end, sample_fps=2.0):
"""Track the active line (caret/current-line highlight) over a range.
Low-res decode at ``sample_fps``; ``absdiff`` between consecutive samples
masked to the pane; per-row changed mass; the top-mass band's centroid is
kept only when it concentrates >= ``ACTIVE_MIN_CONCENTRATION`` of the change
and the band mass clears the floor. The y series is median-smoothed.
Returns ``[(timestamp, source_y), ...]`` in the source's absolute clock (the
caller subtracts the segment start when building sendcmd lines), or None
when fewer than three reliable points are found.
"""
if not ENABLED or not FOLLOW_ENABLED:
return None
try:
import cv2
except ImportError:
return None
if end <= start:
return None
cap = cv2.VideoCapture(video_path)
if not cap.isOpened():
return None
frame_w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
frame_h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
if frame_w <= 0 or frame_h <= 0:
cap.release()
return None
x, y, w, h = _pane_box(pane)
if w <= 0 or h <= 0:
cap.release()
return None
step = 1.0 / max(0.1, float(sample_fps))
points = []
prev_region = None
try:
t = float(start)
while t <= end + 1e-6:
cap.set(cv2.CAP_PROP_POS_MSEC, t * 1000.0)
ok, frame = cap.read()
if not ok:
break
small = _downscale(frame, ACTIVE_MAX_WIDTH)
sw, sh = small.shape[1], small.shape[0]
rx = int(round(x * sw / float(frame_w)))
ry = int(round(y * sh / float(frame_h)))
rw = max(2, int(round(w * sw / float(frame_w))))
rh = max(2, int(round(h * sh / float(frame_h))))
rx = max(0, min(rx, sw - 2))
ry = max(0, min(ry, sh - 2))
rw = max(2, min(rw, sw - rx))
rh = max(2, min(rh, sh - ry))
region = small[ry:ry + rh, rx:rx + rw]
if prev_region is not None and prev_region.shape == region.shape:
diff = cv2.absdiff(region, prev_region)
gray = cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY)
row_mass = gray.sum(axis=1).astype(np.float64)
total = float(row_mass.sum())
if total >= ACTIVE_MIN_MASS:
point = _active_point(row_mass, total)
if point is not None:
points.append((t, y + point[0] * h))
prev_region = region
t += step
finally:
cap.release()
if len(points) < 3:
return None
ys = _median_smooth([p[1] for p in points], 3)
return [(float(ts), float(yy)) for (ts, _), yy in zip(points, ys)]
def _regular_rows(row_proj, min_period=6, max_period=60, min_peak=0.25):
"""True when the row projection has a periodic peak (monospace line pitch).
Autocorrelation of the mean-subtracted projection; a peak in the plausible
line-height band means evenly spaced text lines rather than prose or a UI.
"""
v = np.asarray(row_proj, dtype=float)
if v.size < min_period + 2:
return False
v = v - v.mean()
denom = float((v * v).sum())
if denom <= 0:
return False
ac = np.correlate(v, v, mode="full")[len(v) - 1:]
ac = ac / denom
hi = min(max_period, len(ac) - 1)
if hi <= min_period:
return False
return float(ac[min_period:hi + 1].max()) >= min_peak
def _texture_ok(maps):
"""Edge-density floor + monospace row regularity on an edge-map dict."""
density = edge_density(maps["closed"], (0, 0, maps["w"], maps["h"]))
if density < EDGE_DENSITY_FLOOR:
return False
return _regular_rows(maps["row_proj"])
def _palette_ok(crop):
"""Editor/terminal palette: dark background or mostly monochrome."""
hsv = _hsv(crop)
sat_std = float(hsv[:, :, 1].std())
dark = float((hsv[:, :, 2] < 102).mean())
return bool(dark >= 0.35 or sat_std <= 45.0)
def frame_shows_code(frame, pane):
"""True when the pane region of THIS frame still reads as code.
Text density (edge-density floor + monospace row regularity) plus the
editor/terminal palette. A facecam cutaway puts skin/room inside the pane
rectangle, which fails both the row pitch and the dark/monochrome palette.
"""
try:
import cv2 # noqa: F401
except ImportError:
return False
x, y, w, h = _pane_box(pane)
frame_h, frame_w = frame.shape[:2]
x0 = max(0, min(x, frame_w - 2))
y0 = max(0, min(y, frame_h - 2))
x1 = max(x0 + 2, min(x + w, frame_w))
y1 = max(y0 + 2, min(y + h, frame_h))
crop = frame[y0:y1, x0:x1]
if crop.size == 0:
return False
maps = _edge_maps(crop)
if maps is None:
return False
return _texture_ok(maps) and _palette_ok(crop)
def scene_shows_code(video_path, pane, start, end, samples=3):
"""Sample a scene's frames inside the pane; True on a majority that read
as code. A cutaway to the camera fails and keeps the scene's other verdict.
"""
if end <= start:
return False
try:
import cv2
except ImportError:
return False
cap = cv2.VideoCapture(video_path)
if not cap.isOpened():
return False
frames = []
try:
n = max(1, int(samples))
for i in range(n):
t = start + (end - start) * (i + 0.5) / n
cap.set(cv2.CAP_PROP_POS_MSEC, t * 1000.0)
ok, frame = cap.read()
if ok:
frames.append(frame)
finally:
cap.release()
if len(frames) < 2:
return False
good = sum(1 for f in frames if frame_shows_code(f, pane))
return good >= max(2, int(round(SCENE_CODE_FRAC * len(frames))))
def looks_like_code(frames):
"""Conservative fallback for deployments with no Gemini key.
``frames`` is a list of BGR arrays. True only when all three hold across the
samples: a static pane (centres agree), monospace row regularity, and an
editor/terminal palette (dark or mostly monochrome). This is deliberately
strict — a false positive demotes a real talking-head clip — and callers
MUST NOT invoke it over an explicit operator layout.
"""
if not frames or len(frames) < 2:
return False
planes = []
row_projs = []
sat_stds = []
dark_fracs = []
for frame in frames:
maps = _edge_maps(frame)
if maps is None:
continue
box = pane_from_projections(
maps["row_proj"], maps["col_proj"], maps["w"], maps["h"])
if box is None:
continue
if edge_density(maps["closed"], box) < EDGE_DENSITY_FLOOR:
continue
x, y, w, h = box
crop = frame[y:y + h, x:x + w]
if crop.size == 0:
continue
hsv = _hsv(crop)
planes.append((x, y, w, h, maps["w"], maps["h"]))
row_projs.append(maps["row_proj"])
sat_stds.append(float(hsv[:, :, 1].std()))
dark_fracs.append(float((hsv[:, :, 2] < 102).mean()))
if len(planes) < max(2, int(round(0.6 * len(frames)))):
return False
centres_x = np.array([(p[0] + p[2] / 2.0) / p[4] for p in planes])
centres_y = np.array([(p[1] + p[3] / 2.0) / p[5] for p in planes])
if centres_x.std() > 0.05 or centres_y.std() > 0.05:
return False
median_proj = np.median(np.array(row_projs, dtype=float), axis=0)
if not _regular_rows(median_proj):
return False
sat_std = float(np.median(sat_stds))
dark = float(np.median(dark_fracs))
return bool(dark >= 0.35 or sat_std <= 45.0)
def _hsv(crop):
import cv2
return cv2.cvtColor(crop, cv2.COLOR_BGR2HSV)