feat/youtube-growth-toolkit #8
8 changed files with 1487 additions and 6 deletions
909
clipwright/layouts/code_layout.py
Normal file
909
clipwright/layouts/code_layout.py
Normal file
|
|
@ -0,0 +1,909 @@
|
|||
"""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)
|
||||
|
|
@ -64,6 +64,7 @@ SAMPLE_WIDTH = int(os.environ.get("LAYOUT_SAMPLE_WIDTH", "1024"))
|
|||
DECISION_FLAGS = {
|
||||
"none": [],
|
||||
"screencast": ["screencast_layout"],
|
||||
"code": ["code_layout"],
|
||||
"split": ["split_layout", "active_speaker"],
|
||||
}
|
||||
|
||||
|
|
@ -83,11 +84,13 @@ def apply(decision):
|
|||
must not quietly undo that.
|
||||
"""
|
||||
from clipwright.layouts import active_speaker
|
||||
from clipwright.layouts import code_layout
|
||||
from clipwright.layouts import screencast_layout
|
||||
from clipwright.layouts import split_layout
|
||||
|
||||
modules = {"split_layout": split_layout,
|
||||
"screencast_layout": screencast_layout,
|
||||
"code_layout": code_layout,
|
||||
"active_speaker": active_speaker}
|
||||
|
||||
touched = []
|
||||
|
|
|
|||
|
|
@ -23,6 +23,7 @@ import tempfile
|
|||
|
||||
from clipwright.layouts import active_speaker
|
||||
from clipwright.layouts import camera_inset
|
||||
from clipwright.layouts import code_layout
|
||||
from clipwright.layouts import punch_in
|
||||
from clipwright.layouts import screencast_layout
|
||||
from clipwright.layouts import layout_ranges
|
||||
|
|
@ -341,12 +342,15 @@ def _run(cmd):
|
|||
|
||||
|
||||
def render(input_video, final_output_video, aspect_ratio, content_ranges=None,
|
||||
force_strategy=None, crop_overrides=None):
|
||||
force_strategy=None, crop_overrides=None, word_times=None):
|
||||
"""Full v2 reframe of one clip. Raises on failure (caller falls back).
|
||||
|
||||
``content_ranges`` comes from screencast_layout.detect_content_ranges() on
|
||||
the SOURCE video, already translated into this clip's timeline. None or []
|
||||
means the layout never triggers, which is the default.
|
||||
the SOURCE video, already translated into this clip's timeline. When it is
|
||||
None, the render computes it itself on ``input_video`` if the screencast
|
||||
module is on (see below); this used to be a dead wire no production caller
|
||||
filled, so the picker's "screencast" option did nothing. Pass [] to force
|
||||
the upgrade off, or a list to supply pre-computed ranges.
|
||||
|
||||
``force_strategy`` ('WIDE' / 'TRACK' / any layout the render loop knows)
|
||||
applies that layout to EVERY scene, skipping the classifier and the layout
|
||||
|
|
@ -357,8 +361,13 @@ def render(input_video, final_output_video, aspect_ratio, content_ranges=None,
|
|||
listed keep the automatic camera, so correcting one bad shot never disturbs
|
||||
the ones the tracker got right. Applied AFTER force_strategy: a per-scene
|
||||
hand position always beats the whole-clip choice for the scenes it names.
|
||||
|
||||
``word_times`` are clip-relative word onsets in seconds (clip start = 0)
|
||||
from the transcript, optional. They steer the punch-in beats toward spoken
|
||||
emphasis; None leaves the audio envelope as the only beat source.
|
||||
"""
|
||||
from clipwright.pipeline import main as m
|
||||
auto_content_ranges = content_ranges is None
|
||||
content_ranges = content_ranges or []
|
||||
|
||||
print(" 🚀 Reframe engine v2 (ffmpeg-native render)")
|
||||
|
|
@ -434,6 +443,57 @@ def render(input_video, final_output_video, aspect_ratio, content_ranges=None,
|
|||
if alternates:
|
||||
print(f" 🎬 Speaker-cut layout on {len(alternates)} scene(s)")
|
||||
|
||||
# The SCREENCAST/WIDE/INSET upgrades gate on content_ranges, which no
|
||||
# production caller ever passed: screencast_layout.detect_content_ranges
|
||||
# was called by tests only, so the picker's "screencast" option silently did
|
||||
# nothing (dead wire found in review). Compute them here, once per render,
|
||||
# when the module is on and nothing overrides the layout. CODE does NOT use
|
||||
# this external-ranges path — it self-detects below.
|
||||
if (auto_content_ranges and screencast_layout.ENABLED
|
||||
and not force_strategy and not passthrough):
|
||||
duration = scene_boundaries[-1][1] / fps if scene_boundaries else 0.0
|
||||
try:
|
||||
content_ranges = screencast_layout.detect_content_ranges(
|
||||
input_video, duration)
|
||||
except Exception as e:
|
||||
print(f" ⚠️ On-screen content check failed ({e}).")
|
||||
content_ranges = []
|
||||
|
||||
# CODE is geometric and self-contained, like split_layout: the pane box is
|
||||
# found once for the whole video (screen recordings are usually one long
|
||||
# scene) and then each scene is verified by sampling frames inside that box.
|
||||
# A scene that cuts to the facecam fails the text check and keeps TRACK.
|
||||
# Inserted before SCREENCAST so a code editor with a webcam wins, and the
|
||||
# screencast loop below skips scenes already claimed here.
|
||||
codes = {}
|
||||
code_pane = None
|
||||
if code_layout.ENABLED and not passthrough and not force_strategy:
|
||||
try:
|
||||
code_pane = code_layout.detect_code_pane(input_video)
|
||||
except Exception as e:
|
||||
print(f" ⚠️ Code-pane check failed ({e}) — using other layouts.")
|
||||
code_pane = None
|
||||
if code_pane:
|
||||
max_w = max(2, int(out_w / code_layout.MIN_SCALE))
|
||||
pane_box = code_layout.clamp_pane_width(code_pane, max_w)
|
||||
scale = out_w / float(pane_box[2])
|
||||
print(f" 💻 Code pane {code_pane['w']}x{code_pane['h']} "
|
||||
f"@ {code_pane['x']},{code_pane['y']} "
|
||||
f"mode={code_pane['mode']} conf={code_pane['confidence']:.2f}"
|
||||
f" -> crop {pane_box[2]}px (scale {scale:.2f})")
|
||||
code_pane = dict(code_pane, x=pane_box[0], y=pane_box[1],
|
||||
w=pane_box[2], h=pane_box[3])
|
||||
for scene_idx, (start_f, end_f) in enumerate(scene_boundaries):
|
||||
if strategies[scene_idx] not in ("TRACK", "GENERAL"):
|
||||
continue
|
||||
if code_layout.scene_shows_code(
|
||||
input_video, code_pane, start_f / fps, end_f / fps):
|
||||
strategies[scene_idx] = "CODE"
|
||||
codes[start_f] = code_pane
|
||||
splits.pop(start_f, None)
|
||||
if codes:
|
||||
print(f" 💻 CODE layout on {len(codes)} scene(s)")
|
||||
|
||||
# SCREENCAST wins over SPLIT on the rare scene that qualifies for both: two
|
||||
# faces beside a chart still means the chart is what the shot is about, and
|
||||
# stacking the two speakers would crop it away entirely.
|
||||
|
|
@ -457,6 +517,9 @@ def render(input_video, final_output_video, aspect_ratio, content_ranges=None,
|
|||
if content_ranges:
|
||||
for scene_idx, (plan, centre) in screencast_layout.detect_screencast_scenes(
|
||||
input_video, scenes, strategies, content_ranges).items():
|
||||
# CODE was detected geometrically and wins over the screen layouts.
|
||||
if strategies[scene_idx] == 'CODE':
|
||||
continue
|
||||
# An inset beats both screen plans: it is the only one that can show
|
||||
# the screen whole AND the person at a readable size.
|
||||
if inset:
|
||||
|
|
@ -492,7 +555,8 @@ def render(input_video, final_output_video, aspect_ratio, content_ranges=None,
|
|||
# Beats are found once per clip; each scene takes the ones inside it.
|
||||
beats = []
|
||||
if punch_in.ENABLED:
|
||||
beats = punch_in.emphasis_times(input_video, len(xs) / fps)
|
||||
beats = punch_in.emphasis_times(input_video, len(xs) / fps,
|
||||
word_times=word_times)
|
||||
if beats:
|
||||
print(f" 🔍 Punch-in on {len(beats)} beat(s)")
|
||||
|
||||
|
|
@ -544,6 +608,22 @@ def render(input_video, final_output_video, aspect_ratio, content_ranges=None,
|
|||
left, right = splits[start_f]
|
||||
graph = split_layout.split_filtergraph(
|
||||
orig_w, orig_h, out_w, out_h, left, right)
|
||||
elif strategy == 'CODE' and start_f in codes:
|
||||
pane = codes[start_f]
|
||||
follow = None
|
||||
if code_layout.FOLLOW_ENABLED:
|
||||
try:
|
||||
series = code_layout.active_line_series(
|
||||
input_video, pane, ss, ss + dur)
|
||||
if series:
|
||||
follow = [(t - ss, y) for t, y in series]
|
||||
except Exception:
|
||||
follow = None
|
||||
graph = code_layout.code_filtergraph(
|
||||
pane, out_w, out_h, follow=follow)
|
||||
if graph is None:
|
||||
graph = general_filtergraph(out_w, out_h,
|
||||
orig_w=orig_w, orig_h=orig_h)
|
||||
elif strategy == 'GENERAL':
|
||||
graph = general_filtergraph(out_w, out_h,
|
||||
orig_w=orig_w, orig_h=orig_h)
|
||||
|
|
|
|||
|
|
@ -24,7 +24,7 @@ import json
|
|||
import os
|
||||
from typing import Optional
|
||||
|
||||
SCREEN_LAYOUTS = {"screencast", "wide", "inset"}
|
||||
SCREEN_LAYOUTS = {"screencast", "code", "wide", "inset"}
|
||||
FRAMES = int(os.environ.get("HOOK_GROUNDING_FRAMES", "3"))
|
||||
WIDTH = int(os.environ.get("HOOK_GROUNDING_WIDTH", "1024"))
|
||||
# Ignore a blip: the screen stretches must cover this share of the clip.
|
||||
|
|
|
|||
169
clipwright/tools/verify_code_layout.py
Normal file
169
clipwright/tools/verify_code_layout.py
Normal file
|
|
@ -0,0 +1,169 @@
|
|||
"""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())
|
||||
|
|
@ -14,6 +14,9 @@ import pytest
|
|||
|
||||
from clipwright.layouts import layout_ranges
|
||||
from clipwright.layouts import layout_picker
|
||||
from clipwright.layouts import code_layout
|
||||
from clipwright.layouts import camera_inset
|
||||
from clipwright.layouts import active_speaker
|
||||
from clipwright.layouts import punch_in
|
||||
from clipwright.layouts import screencast_layout
|
||||
from clipwright.layouts import split_layout
|
||||
|
|
@ -26,6 +29,7 @@ VERTICAL = 9 / 16
|
|||
_FAKE_LAYOUT_MODULES = {
|
||||
"split_layout": "clipwright.layouts.split_layout",
|
||||
"screencast_layout": "clipwright.layouts.screencast_layout",
|
||||
"code_layout": "clipwright.layouts.code_layout",
|
||||
"active_speaker": "clipwright.layouts.active_speaker",
|
||||
}
|
||||
|
||||
|
|
@ -59,6 +63,15 @@ class TestPickerFlagMapping:
|
|||
assert mods["clipwright.layouts.screencast_layout"].ENABLED is True
|
||||
assert mods["clipwright.layouts.split_layout"].ENABLED is False
|
||||
|
||||
def test_code_enables_only_its_module(self, monkeypatch):
|
||||
# The CODE layout is gated by its own module flag; picking it must not
|
||||
# touch SPLIT or SCREENCAST.
|
||||
mods = fake_modules(monkeypatch)
|
||||
assert layout_picker.apply("code") == ["code_layout"]
|
||||
assert mods["clipwright.layouts.code_layout"].ENABLED is True
|
||||
assert mods["clipwright.layouts.screencast_layout"].ENABLED is False
|
||||
assert mods["clipwright.layouts.split_layout"].ENABLED is False
|
||||
|
||||
def test_none_is_inert(self, monkeypatch):
|
||||
mods = fake_modules(monkeypatch)
|
||||
assert layout_picker.apply("none") == []
|
||||
|
|
@ -104,6 +117,7 @@ class TestApiLayoutEnv:
|
|||
def test_explicit_picks_map_to_their_env_vars(self, layout_env):
|
||||
assert layout_env(["split"])["SPLIT_LAYOUT"] == "1"
|
||||
assert layout_env(["screencast"])["SCREENCAST_LAYOUT"] == "1"
|
||||
assert layout_env(["code"])["CODE_LAYOUT"] == "1"
|
||||
assert layout_env(["punch_in"])["PUNCH_IN"] == "1"
|
||||
|
||||
def test_split_implies_the_speaker_signal(self, layout_env):
|
||||
|
|
@ -243,3 +257,77 @@ class TestLayoutRangesRoundTrip:
|
|||
got = layout_ranges.remap(ranges, [{"start": 5, "end": 12}])
|
||||
assert got == [{"start": 0.0, "end": 5.0, "layout": "split"},
|
||||
{"start": 5.0, "end": 7.0, "layout": "track"}]
|
||||
|
||||
|
||||
# --- CODE precedence --------------------------------------------------------
|
||||
|
||||
class _TC:
|
||||
"""Minimal FrameTimecode stand-in: render only reads ``get_frames``."""
|
||||
|
||||
def __init__(self, frame):
|
||||
self._frame = frame
|
||||
|
||||
def get_frames(self):
|
||||
return self._frame
|
||||
|
||||
|
||||
class _DummyCameraman:
|
||||
crop_width = 640
|
||||
crop_height = 360
|
||||
|
||||
|
||||
class TestCodePrecedence:
|
||||
"""CODE self-detects and wins over SCREENCAST on the same scene, while a
|
||||
scene that fails per-scene verification keeps TRACK."""
|
||||
|
||||
def _wire(self, monkeypatch):
|
||||
from clipwright.pipeline import main as m
|
||||
|
||||
# No ML, no ffmpeg, no Gemini: every external call is a stand-in.
|
||||
monkeypatch.setattr(reframe_v2, "_run", lambda cmd: None)
|
||||
monkeypatch.setattr(reframe_v2, "_analyze_trajectory",
|
||||
lambda *a, **k: [0.0] * 60)
|
||||
monkeypatch.setattr(split_layout, "detect_split_scenes",
|
||||
lambda *a, **k: {})
|
||||
monkeypatch.setattr(camera_inset, "detect", lambda *a, **k: None)
|
||||
monkeypatch.setattr(active_speaker, "ENABLED", False)
|
||||
monkeypatch.setattr(punch_in, "ENABLED", False)
|
||||
monkeypatch.setattr(m, "detect_scenes",
|
||||
lambda *a, **k: ([(_TC(0), _TC(30)),
|
||||
(_TC(30), _TC(60))], 30.0))
|
||||
monkeypatch.setattr(m, "get_video_resolution",
|
||||
lambda *a, **k: (2560, 1440))
|
||||
monkeypatch.setattr(m, "analyze_scenes_strategy",
|
||||
lambda *a, **k: ["TRACK", "TRACK"])
|
||||
monkeypatch.setattr(m, "SmoothedCameraman",
|
||||
lambda *a, **k: _DummyCameraman())
|
||||
monkeypatch.setattr(m, "SpeakerTracker", lambda *a, **k: object())
|
||||
|
||||
# SCREENCAST is on and would claim scene 0...
|
||||
monkeypatch.setattr(screencast_layout, "ENABLED", True)
|
||||
monkeypatch.setattr(screencast_layout, "detect_content_ranges",
|
||||
lambda *a, **k: [(0.0, 20.0, "chart", 0.9)])
|
||||
monkeypatch.setattr(screencast_layout, "detect_screencast_scenes",
|
||||
lambda *a, **k: {0: ("SCREENCAST", (100.0, 100.0))})
|
||||
|
||||
# ...but CODE detects the pane and verifies only scene 0.
|
||||
monkeypatch.setattr(code_layout, "ENABLED", True)
|
||||
monkeypatch.setattr(code_layout, "FOLLOW_ENABLED", False)
|
||||
pane = {"x": 300, "y": 100, "w": 1200, "h": 800, "mode": "editor",
|
||||
"confidence": 0.9, "frame_w": 2560, "frame_h": 1440}
|
||||
monkeypatch.setattr(code_layout, "detect_code_pane",
|
||||
lambda *a, **k: dict(pane))
|
||||
monkeypatch.setattr(
|
||||
code_layout, "scene_shows_code",
|
||||
lambda path, pane, start, end, samples=3: start < 0.5)
|
||||
|
||||
def test_code_wins_over_screencast_and_leaves_other_scenes(
|
||||
self, monkeypatch, tmp_path):
|
||||
self._wire(monkeypatch)
|
||||
final = str(tmp_path / "clip.mp4")
|
||||
assert reframe_v2.render("in.mp4", final, VERTICAL) is True
|
||||
|
||||
by_start = {r["start"]: r["layout"] for r in layout_ranges.read(final)}
|
||||
assert by_start[0.0] == "code" # CODE beat the SCREENCAST claim
|
||||
assert by_start[1.0] == "track" # failed verification, untouched
|
||||
assert "screencast" not in set(by_start.values())
|
||||
|
|
|
|||
231
tests/test_code_layout.py
Normal file
231
tests/test_code_layout.py
Normal file
|
|
@ -0,0 +1,231 @@
|
|||
"""Pure tests for the CODE/TERMINAL layout geometry.
|
||||
|
||||
No OpenCV here on purpose: the detection entry points import cv2 lazily, and CI
|
||||
does not install it. Everything asserted below is decided by the pure helpers
|
||||
(projections -> pane, stability, band fitting, sendcmd lines, filtergraph).
|
||||
"""
|
||||
from clipwright.layouts.code_layout import (
|
||||
CAPTION_BAND_RATIO,
|
||||
clamp_pane_width,
|
||||
code_bands,
|
||||
code_filtergraph,
|
||||
fit_window,
|
||||
follow_sendcmd_lines,
|
||||
pane_from_projections,
|
||||
stable_pane,
|
||||
text_column_extent,
|
||||
)
|
||||
|
||||
HD = (1920, 1080)
|
||||
|
||||
|
||||
def _projections(row_span, col_span, h=1080, w=1920):
|
||||
rows = [0.0] * h
|
||||
cols = [0.0] * w
|
||||
for i in range(*row_span):
|
||||
rows[i] = 100.0
|
||||
for i in range(*col_span):
|
||||
cols[i] = 100.0
|
||||
return rows, cols
|
||||
|
||||
|
||||
class TestPaneFromProjections:
|
||||
def test_locates_the_pane_block(self):
|
||||
rows, cols = _projections((100, 400), (200, 1000))
|
||||
assert pane_from_projections(rows, cols, *HD) == (200, 100, 800, 300)
|
||||
|
||||
def test_ignores_mass_below_the_threshold(self):
|
||||
rows, cols = _projections((100, 400), (200, 1000))
|
||||
# A stray edge column far from the pane is under 15% of the max.
|
||||
cols[1500] = 10.0
|
||||
assert pane_from_projections(rows, cols, *HD) == (200, 100, 800, 300)
|
||||
|
||||
def test_rejects_a_narrow_pane(self):
|
||||
rows, cols = _projections((100, 400), (200, 500))
|
||||
assert pane_from_projections(rows, cols, *HD) is None
|
||||
|
||||
def test_rejects_a_short_pane(self):
|
||||
rows, cols = _projections((100, 200), (200, 1000))
|
||||
assert pane_from_projections(rows, cols, *HD) is None
|
||||
|
||||
def test_empty_projections_are_none(self):
|
||||
assert pane_from_projections([], [], *HD) is None
|
||||
assert pane_from_projections([0, 0], [0, 0], *HD) is None
|
||||
|
||||
|
||||
class TestTextColumnExtent:
|
||||
def test_no_chrome_keeps_the_full_text_width(self):
|
||||
cols = [0.0] * 2560
|
||||
for i in range(100, 2400):
|
||||
cols[i] = 100.0
|
||||
x0, x1 = text_column_extent(cols, 2560)
|
||||
assert 90 <= x0 <= 110
|
||||
assert 2390 <= x1 <= 2410
|
||||
|
||||
def test_sidebar_and_minimap_are_masked(self):
|
||||
cols = [0.0] * 2560
|
||||
for i in range(0, 60): # activity bar
|
||||
cols[i] = 90.0
|
||||
for i in range(80, 400): # sidebar
|
||||
cols[i] = 70.0
|
||||
for i in range(500, 2050): # code text
|
||||
cols[i] = 100.0
|
||||
for i in range(2450, 2560): # minimap
|
||||
cols[i] = 110.0
|
||||
x0, x1 = text_column_extent(cols, 2560)
|
||||
# Cut after the sidebar/editor border and before the minimap border.
|
||||
assert 400 <= x0 <= 520
|
||||
assert 2050 <= x1 <= 2450
|
||||
|
||||
def test_too_narrow_is_none(self):
|
||||
cols = [0.0] * 2560
|
||||
for i in range(0, 100):
|
||||
cols[i] = 100.0
|
||||
assert text_column_extent(cols, 2560) is None
|
||||
|
||||
|
||||
class TestClampPaneWidth:
|
||||
def test_narrows_from_the_left_by_default(self):
|
||||
assert clamp_pane_width((300, 100, 2100, 1200), 1440) == (
|
||||
300, 100, 1440, 1200)
|
||||
|
||||
def test_noop_when_it_already_fits(self):
|
||||
assert clamp_pane_width((300, 100, 1200, 1200), 1440) == (
|
||||
300, 100, 1200, 1200)
|
||||
|
||||
def test_centred_anchor_splits_the_difference(self):
|
||||
assert clamp_pane_width((0, 0, 2000, 1000), 1000, anchor="center") == (
|
||||
500, 0, 1000, 1000)
|
||||
|
||||
def test_odd_width_is_made_even(self):
|
||||
_x, _y, w, _h = clamp_pane_width((0, 0, 2000, 1000), 1441)
|
||||
assert w % 2 == 0 and w <= 1441
|
||||
|
||||
|
||||
class TestStablePane:
|
||||
def test_agreement_returns_the_median(self):
|
||||
boxes = [(100, 100, 800, 300), (105, 102, 800, 300),
|
||||
(98, 99, 802, 301), (300, 300, 800, 300)]
|
||||
box = stable_pane(boxes, *HD)
|
||||
assert box is not None
|
||||
assert abs(box[0] - 100) <= 6 and abs(box[1] - 100) <= 4
|
||||
|
||||
def test_a_scattered_set_is_rejected(self):
|
||||
boxes = [(0, 0, 400, 300), (1500, 800, 400, 300),
|
||||
(700, 400, 400, 300)]
|
||||
assert stable_pane(boxes, *HD) is None
|
||||
|
||||
def test_too_few_samples_is_rejected(self):
|
||||
assert stable_pane([], *HD) is None
|
||||
assert stable_pane([(100, 100, 800, 300)], *HD) is None
|
||||
|
||||
|
||||
class TestCodeBands:
|
||||
def test_bands_fill_the_output_and_are_even(self):
|
||||
content_h, caption_h = code_bands(1920)
|
||||
assert content_h + caption_h == 1920
|
||||
assert content_h % 2 == 0 and caption_h % 2 == 0
|
||||
|
||||
def test_caption_reserve_is_about_fifteen_percent(self):
|
||||
_, caption_h = code_bands(1920)
|
||||
assert abs(caption_h / 1920 - CAPTION_BAND_RATIO) <= 0.01
|
||||
|
||||
def test_large_caption_ratio_still_leaves_a_band(self):
|
||||
content_h, caption_h = code_bands(1000, 0.9)
|
||||
assert content_h >= 2 and caption_h >= 2
|
||||
assert content_h + caption_h == 1000
|
||||
|
||||
|
||||
class TestFitWindow:
|
||||
def test_short_pane_fits_without_follow(self):
|
||||
crop_h, scaled_h, needs_follow = fit_window(300, 2.0, 1632)
|
||||
assert crop_h == 300 and scaled_h == 600
|
||||
assert needs_follow is False
|
||||
|
||||
def test_tall_pane_needs_a_follow_window(self):
|
||||
crop_h, scaled_h, needs_follow = fit_window(2000, 2.7, 1632)
|
||||
assert needs_follow is True
|
||||
assert scaled_h == 1632
|
||||
assert crop_h <= 2000 and crop_h % 2 == 0
|
||||
|
||||
def test_scaled_height_never_exceeds_the_band(self):
|
||||
for pane_h, scale in ((300, 2.0), (2000, 2.7), (1080, 0.75)):
|
||||
_, scaled_h, _ = fit_window(pane_h, scale, 1632)
|
||||
assert scaled_h <= 1632 and scaled_h % 2 == 0
|
||||
|
||||
def test_degenerate_pane_is_clamped_not_zero(self):
|
||||
crop_h, scaled_h, _ = fit_window(10, 0.01, 100)
|
||||
assert crop_h >= 2 and scaled_h >= 2
|
||||
|
||||
|
||||
class TestFollowSendcmd:
|
||||
def test_dedupes_change_points_and_is_segment_relative(self):
|
||||
follow = [(1.0, 100.0), (2.0, 100.0), (3.0, 200.0), (4.0, 200.0)]
|
||||
lines = follow_sendcmd_lines(follow, 0, 100, 500, start=1.0)
|
||||
assert len(lines) == 2
|
||||
assert lines[0].startswith("0.0000")
|
||||
assert lines[1].startswith("2.0000")
|
||||
assert "y 50;" in lines[0]
|
||||
assert "y 150;" in lines[1]
|
||||
|
||||
def test_window_is_clamped_to_the_pane(self):
|
||||
lines = follow_sendcmd_lines(
|
||||
[(0.0, -500.0), (1.0, 99999.0)], 100, 100, 500)
|
||||
ys = [int(ln.split(" y ")[1].rstrip(";")) for ln in lines]
|
||||
assert ys == [100, 500]
|
||||
|
||||
def test_points_before_the_segment_start_are_dropped(self):
|
||||
follow = [(0.0, 100.0), (2.0, 300.0)]
|
||||
lines = follow_sendcmd_lines(follow, 0, 100, 500, start=1.0)
|
||||
assert len(lines) == 1
|
||||
assert lines[0].startswith("1.0000")
|
||||
|
||||
|
||||
class TestCodeFiltergraph:
|
||||
def test_graph_crops_scales_and_overlays(self):
|
||||
graph = code_filtergraph((200, 100, 1440, 800), 1080, 1920)
|
||||
assert graph is not None
|
||||
assert "crop=" in graph
|
||||
assert "scale=1080:600" in graph
|
||||
assert "overlay=x=0:y=" in graph
|
||||
assert graph.endswith("[v]")
|
||||
|
||||
def test_no_follow_means_no_sendcmd(self):
|
||||
graph = code_filtergraph((200, 100, 1440, 800), 1080, 1920, follow=None)
|
||||
assert graph is not None
|
||||
assert "sendcmd" not in graph
|
||||
|
||||
def test_follow_on_a_tall_pane_emits_sendcmd(self):
|
||||
pane = (100, 0, 800, 4000)
|
||||
graph = code_filtergraph(pane, 1080, 1920,
|
||||
follow=[(0.0, 500.0), (2.0, 1500.0)])
|
||||
assert graph is not None
|
||||
assert "sendcmd=c=" in graph
|
||||
assert "crop@c=" in graph
|
||||
assert graph.endswith("[v]")
|
||||
|
||||
def test_follow_without_a_window_does_not_emit_sendcmd(self):
|
||||
graph = code_filtergraph((200, 100, 1440, 800), 1080, 1920,
|
||||
follow=[(0.0, 500.0)])
|
||||
assert graph is not None
|
||||
assert "sendcmd" not in graph
|
||||
|
||||
def test_min_scale_fallback_returns_none(self):
|
||||
# out_w / pane_w = 1080 / 2000 = 0.54 < 0.75.
|
||||
assert code_filtergraph((0, 0, 2000, 800), 1080, 1920) is None
|
||||
|
||||
def test_min_scale_can_be_overridden(self):
|
||||
graph = code_filtergraph((0, 0, 2000, 800), 1080, 1920, min_scale=0.5)
|
||||
assert graph is not None
|
||||
|
||||
def test_accepts_a_detector_dict(self):
|
||||
pane = {"x": 200, "y": 100, "w": 1440, "h": 800, "mode": "editor"}
|
||||
assert code_filtergraph(pane, 1080, 1920) is not None
|
||||
|
||||
def test_camera_box_adds_a_third_branch(self):
|
||||
graph = code_filtergraph((200, 100, 1440, 800), 1080, 1920,
|
||||
cam_box=(0, 0, 300, 200))
|
||||
assert graph is not None
|
||||
assert "split=3" in graph
|
||||
assert "[cam]" in graph
|
||||
assert graph.endswith("[v]")
|
||||
|
|
@ -101,7 +101,8 @@ class TestPick:
|
|||
|
||||
class TestValidDecisions:
|
||||
def test_every_valid_decision_maps_to_known_modules(self):
|
||||
known = {"split_layout", "screencast_layout", "active_speaker"}
|
||||
known = {"split_layout", "screencast_layout", "code_layout",
|
||||
"active_speaker"}
|
||||
for decision in layout_picker.VALID:
|
||||
assert set(_module_flags(decision)) <= known
|
||||
|
||||
|
|
|
|||
Loading…
Reference in a new issue