feat(reframe): optional layouts, and a Gemini-picked layout per video

Four new layouts, all off by default, plus a picker that decides which one a
video gets.

- SPLIT (split_layout.py): two speakers stacked. The test is COEXISTENCE in the
  same frame, not presence measured separately: BlazeFace loses faces in
  profile, which is how someone sits while listening, so a presence test
  rejects conversations for looking like conversations. Coexistence also
  separates a two-shot from a shot/reverse-shot, where stacking would show the
  same person twice.
- SCREENCAST / WIDE (screencast_layout.py): content over the presenter, or full
  width when the content fills the frame and the presenter is composited on top
  of it (stacking there shows the same thing twice).
- ALTERNATE (active_speaker.py): hard cuts to whoever is talking. Mouth activity
  must be normalised per speaker against their own resting state; raw magnitude
  scales with contrast and lighting and handed one person 90-100% of the scene.
- Punch-in (punch_in.py): a 12% push on the beats, riding the TRACK path by
  widening its per-frame crop command from x-only to w/h/x/y.

layout_picker.py chooses between none/screencast/split with one Gemini call per
source video. Measured over the 48-clip corpus against hand-checked labels:
94/92/96% across three runs, 0-1 false positives out of 28, and 2 clips of 48
changing answer between runs. The key is asking for a DECISION between closed
options rather than a measurement: the four previous attempts (Canny, MSER,
coverage, width) all asked for a number and none separated a spreadsheet from a
corner scoreboard.

app.py exposes all of it per job through `layouts` on /api/process. Without that
field the pipeline behaves exactly as before.

83 new tests, 315 green.
This commit is contained in:
juancarlos.cavero 2026-07-31 13:28:45 +02:00
parent be4dd06189
commit 094e13c2f9
15 changed files with 2092 additions and 12 deletions

View file

@ -83,9 +83,60 @@ say "OpenShorts is free" without naming the Cloud price in the same breath: both
are true of different editions and quoting only the first one is what makes AI
answers describe the paid product as free.
### Dual-Mode Video Reframing
### Cómo se elige el layout
`POST /api/process` acepta `layouts`: una lista (JSON) o cadena separada por
comas con `auto`, `split`, `screencast`, `speaker_cut`, `punch_in`. Cada nombre
enciende su variable de entorno para **ese** trabajo (`app.py:layout_env`); sin
`layouts` el pipeline se comporta exactamente como antes.
`auto` activa `layout_picker.py`: **una** llamada a Gemini por vídeo de origen
(no por clip) que elige entre `none` / `screencast` / `split`. Medido sobre el
corpus de 48 contra etiquetas revisadas a mano: 94% / 92% / 96% en tres pasadas,
con 0-1 falsos positivos sobre los 28 clips que no deben tocarse, y solo 2 clips
que cambian de respuesta entre pasadas.
Lo que hace que funcione, y que conviene no deshacer: se le pide una **decisión
entre opciones cerradas**, no una medida. Los cuatro intentos anteriores (Canny,
MSER, cobertura temporal, anchura) le pedían un número y ninguno separó una hoja
de cálculo de un marcador de esquina. La varianza que este repo atribuía a
Gemini era de las medidas continuas, no del modelo.
`layout_picker.apply()` sólo **añade**: una elección explícita del usuario nunca
se desactiva porque el modelo diga `none`.
### Video Reframing Modes
- **TRACK Mode** (single subject): MediaPipe face detection + YOLOv8 fallback with "Heavy Tripod" stabilization
- **GENERAL Mode** (groups/landscapes): Blurred background layout preserving full width
- **SPLIT Mode** (two-shot conversation, `split_layout.py`): both speakers stacked
in half-frames. Off by default (`SPLIT_LAYOUT=1`); v2 engine only, so a
fallback to the v1 loop silently renders GENERAL instead. It upgrades scenes
the classifier already sent to GENERAL, never TRACK ones, and needs both faces
visible **in the same frame** for at least half the sampled frames — that is
what separates a real two-shot from a plano/contraplano, where stacking would
show the same person twice. `SPLIT_TIGHTNESS` (default 0.8) trades a little
upscale for keeping the other speaker out of each half.
- **SCREENCAST / WIDE Modes** (`screencast_layout.py`, `SCREENCAST_LAYOUT=1`):
for scenes whose meaning lives outside the centre. Gemini reports each range's
**width_fraction**, and that is the gate — coverage was tried before and did
not separate a spreadsheet from a corner ticker, while width does (a bug spans
~15% and survives any crop, a spreadsheet spans ~100% and cannot). Content
narrower than 0.5 moves nothing. Between 0.5 and 0.85 there is room beside the
content, so SCREENCAST stacks it over the presenter. Above 0.85 the presenter
is composited **on top of** the content and stacking would show it twice, so
those scenes get WIDE: the GENERAL layout with side-cropping disabled.
- **ALTERNATE Mode** (`active_speaker.py`, `SPEAKER_SIGNAL=1` + `SPEAKER_CUT=1`):
hard cuts to whoever is talking, rendered through the TRACK path as a
trajectory with jumps. `SPEAKER_SIGNAL=1` alone just gates SPLIT on both people
actually speaking. Mouth activity **must** be normalised per speaker before
comparing (`normalise_activity`): raw frame-difference magnitude scales with
local contrast and lighting, and on a real two-shot it handed one speaker
90-100% of the scene.
- **Punch-in** (`punch_in.py`, `PUNCH_IN=1`): not a layout. A ~12% push on the
clip's beats, riding the TRACK path by widening its per-frame crop command
from x-only to w/h/x/y. Beats currently come from the audio envelope;
`emphasis_times` is a plain list of seconds so the transcript's hook words can
replace it without touching the module.
### Key Classes
- `SmoothedCameraman` - Stabilized camera movement with safe zone logic (prevents jitter)

290
active_speaker.py Normal file
View file

@ -0,0 +1,290 @@
"""Who is talking, from mouth movement plus audio energy.
The SPLIT layout shipped without this and it is the thing that decides whether
the format lands or grates: stacking is only worth half the frame when both
people actually take turns. Geometry alone will stack a scene where one person
sits silent for thirty seconds.
Full diarisation is not needed to answer "which of these two faces is moving its
mouth right now". This measures frame-to-frame change in the mouth region of
each known face box, and only trusts the comparison in windows where the audio
says somebody is speaking at all — otherwise a nod, a laugh or a chewed sweet
scores as speech.
The two faces come from split_layout's medians, so no per-frame face detection
runs here: the subjects of a two-shot are seated and the boxes hold.
Everything in this module is pure enough to unit-test except decode_activity(),
which needs ffmpeg.
"""
import os
import subprocess
import numpy as np
# Seconds per decision window. Short enough to catch a one-word interjection,
# long enough that a single blurred frame cannot flip the answer.
WINDOW_SECONDS = 0.4
# Off by default like every other new routing signal here. SPEAKER_SIGNAL=1
# gates SPLIT on both people actually talking; SPEAKER_CUT=1 additionally
# replaces the stack with hard cuts to whoever holds the floor.
ENABLED = os.environ.get("SPEAKER_SIGNAL", "0") == "1"
CUT_MODE = os.environ.get("SPEAKER_CUT", "0") == "1"
# A window counts as speech only if its audio RMS clears this fraction of the
# scene's loudest window. Silence and room tone sit far below it.
AUDIO_FLOOR = 0.18
# The winner's mouth must be this much more active than the other's, relative to
# the pair's total, before the window is attributed. Below it the window is
# "unclear" and simply does not vote — which is the honest answer when both are
# still or both are moving.
MIN_MARGIN = 0.15
# Share of attributed windows each speaker needs before a two-shot counts as a
# conversation. At 0.2 a listener who chips in every fifth window still counts;
# a genuinely silent listener does not.
MIN_SHARE = float(os.environ.get("SPLIT_MIN_SHARE", "0.2"))
ANALYSIS_WIDTH = 480
def mouth_region(box, frame_w, frame_h, scale=1.0):
"""Pixel rect (x0, y0, x1, y1) around the mouth of a face box.
MediaPipe boxes cover brow to chin, so the mouth sits low and central. The
region is deliberately wider than the lips: jaw movement carries as much
signal as the lips themselves and survives a box that drifts a little.
"""
x, y, w, h = [v / scale for v in box]
cx = x + w / 2.0
mouth_y = y + h * 0.72
half_w = w * 0.36
half_h = h * 0.22
x0 = int(max(0, min(cx - half_w, frame_w - 1)))
x1 = int(max(x0 + 1, min(cx + half_w, frame_w)))
y0 = int(max(0, min(mouth_y - half_h, frame_h - 1)))
y1 = int(max(y0 + 1, min(mouth_y + half_h, frame_h)))
return x0, y0, x1, y1
def audio_envelope(video_path, start_s, duration_s, window_s=WINDOW_SECONDS):
"""Per-window RMS of the clip's audio, normalised to its own peak.
Returns [] when the source has no audio track, which makes every window
eligible rather than none: a silent source should fall back to mouth
movement alone, not refuse to decide.
"""
try:
raw = subprocess.run(
["ffmpeg", "-v", "error", "-ss", f"{start_s:.4f}",
"-t", f"{duration_s:.4f}", "-i", video_path,
"-vn", "-ac", "1", "-ar", "8000", "-f", "s16le", "-"],
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
timeout=300).stdout
except (subprocess.SubprocessError, OSError):
return []
if not raw:
return []
samples = np.frombuffer(raw, dtype=np.int16).astype(np.float32)
per_window = max(1, int(8000 * window_s))
n = len(samples) // per_window
if n < 1:
return []
windows = samples[:n * per_window].reshape(n, per_window)
rms = np.sqrt(np.mean(windows ** 2, axis=1))
peak = rms.max()
return (rms / peak).tolist() if peak > 0 else [0.0] * n
def normalise_activity(activity):
"""Rescale each speaker's mouth activity onto its own quiet-to-loud range.
Raw frame-difference magnitude is not comparable between two faces: it
scales with the local contrast, the lighting and the size of the box, so
whichever speaker happens to be better lit wins every window. Measured on a
real two-shot, the raw signal handed one speaker 90-100% of the scene.
Subtracting each speaker's own 20th percentile (their resting state) and
dividing by their own 20-80 spread compares "how active is this mouth for
this person" instead. Windows where nobody speaks are already dropped by the
audio gate, so a silent listener's amplified noise never gets a vote.
"""
if not activity:
return []
columns = np.asarray(activity, dtype=float)
if columns.ndim != 2 or columns.shape[1] < 2:
return activity
low = np.percentile(columns, 20, axis=0)
high = np.percentile(columns, 80, axis=0)
spread = np.where(high - low > 1e-6, high - low, 1.0)
return np.clip((columns - low) / spread, 0.0, None).tolist()
def attribute_windows(activity, loudness, min_margin=MIN_MARGIN):
"""Which speaker owns each window, or None when it is not clear.
``activity`` is [[a0, a1], ...], one mouth-movement score per speaker per
window; ``loudness`` is the normalised audio envelope (or [] for none).
"""
verdicts = []
for i, pair in enumerate(activity):
if loudness and i < len(loudness) and loudness[i] < AUDIO_FLOOR:
verdicts.append(None) # nobody is talking here
continue
a, b = pair
total = a + b
if total <= 0:
verdicts.append(None)
continue
margin = abs(a - b) / total
verdicts.append(None if margin < min_margin else (0 if a > b else 1))
return verdicts
def shares(verdicts):
"""Fraction of attributed windows held by each speaker: (share0, share1).
Returns (0.0, 0.0) when nothing was attributed, so callers see "no evidence"
rather than a spurious 50/50.
"""
counted = [v for v in verdicts if v is not None]
if not counted:
return 0.0, 0.0
n = float(len(counted))
return counted.count(0) / n, counted.count(1) / n
def is_conversation(verdicts, min_share=None):
"""True when both speakers hold enough of the attributed windows."""
min_share = MIN_SHARE if min_share is None else min_share
a, b = shares(verdicts)
return min(a, b) >= min_share
def hold(verdicts, min_windows=3):
"""Smooth the per-window verdicts so the answer cannot flap.
A cut back and forth every 0.4s is unwatchable, and a listener's single
"yeah" should not steal the frame. Unclear windows inherit the current
speaker, and a new speaker must hold ``min_windows`` in a row to take over.
"""
out = []
current = None
pending = None
run = 0
for v in verdicts:
if v is None or v == current:
if v == current:
pending, run = None, 0
out.append(current)
continue
if v == pending:
run += 1
else:
pending, run = v, 1
if current is None or run >= min_windows:
current, pending, run = v, None, 0
out.append(current)
# Nothing was ever confident enough to start: leave it to the caller.
if all(v is None for v in out):
return out
# Backfill the lead-in with whoever spoke first.
first = next(v for v in out if v is not None)
return [first if v is None else v for v in out]
def speaker_xs(held, centres, crop_w, orig_w, n_frames, fps,
window_s=WINDOW_SECONDS):
"""Per-frame crop x that cuts to whoever is speaking.
Reuses the TRACK render path: a camera trajectory with hard jumps is still
just a list of x positions, so no new filtergraph is needed.
"""
xs = []
for f in range(n_frames):
idx = min(int((f / fps) / window_s), len(held) - 1) if held else 0
who = held[idx] if held else 0
cx = centres[who if who is not None else 0][0]
x = int(round(cx - crop_w / 2.0))
xs.append(max(0, min(x, orig_w - crop_w)))
return xs
def verdicts_for_scene(video_path, start_f, end_f, fps, centres):
"""Per-window speaker verdicts for one scene, from its two face centres."""
import split_layout
start_s = start_f / fps
duration_s = (end_f - start_f) / fps
boxes = [split_layout.as_box(c) for c in centres]
activity = decode_activity(video_path, start_s, duration_s, boxes, fps)
loudness = audio_envelope(video_path, start_s, duration_s)
return attribute_windows(normalise_activity(activity), loudness)
def decode_activity(video_path, start_s, duration_s, boxes, fps,
window_s=WINDOW_SECONDS):
"""Mouth-movement score per speaker per window over one scene.
Decodes the scene once at ANALYSIS_WIDTH and measures mean absolute
frame-to-frame change inside each speaker's mouth region.
"""
import cv2
probe = cv2.VideoCapture(video_path)
orig_w = int(probe.get(cv2.CAP_PROP_FRAME_WIDTH))
orig_h = int(probe.get(cv2.CAP_PROP_FRAME_HEIGHT))
probe.release()
if not orig_w or not orig_h:
return []
small_w = min(ANALYSIS_WIDTH, orig_w)
small_w -= small_w % 2
small_h = max(int(orig_h * small_w / orig_w), 2)
small_h += small_h % 2
scale = orig_w / float(small_w)
frame_bytes = small_w * small_h * 3
regions = [mouth_region(b, small_w, small_h, scale) for b in boxes]
proc = subprocess.Popen(
["ffmpeg", "-v", "error", "-ss", f"{start_s:.4f}",
"-t", f"{duration_s:.4f}", "-i", video_path,
"-vf", f"scale={small_w}:{small_h}", "-f", "rawvideo",
"-pix_fmt", "gray", "-"],
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
bufsize=small_w * small_h * 4)
per_window = max(1, int(round(fps * window_s)))
activity, bucket, prev = [], [], None
try:
while True:
buf = proc.stdout.read(small_w * small_h)
if len(buf) < small_w * small_h:
break
frame = np.frombuffer(buf, dtype=np.uint8).reshape(small_h, small_w)
if prev is not None:
bucket.append([
float(np.mean(np.abs(
frame[y0:y1, x0:x1].astype(np.int16)
- prev[y0:y1, x0:x1].astype(np.int16))))
for x0, y0, x1, y1 in regions])
prev = frame
if len(bucket) >= per_window:
activity.append(np.mean(bucket, axis=0).tolist())
bucket = []
finally:
proc.stdout.close()
proc.wait()
if bucket:
activity.append(np.mean(bucket, axis=0).tolist())
return activity

65
app.py
View file

@ -1271,6 +1271,55 @@ async def _probe_youtube_quality(url: str) -> dict:
return await loop.run_in_executor(None, _run)
# Layouts the caller can let the renderer choose from, mapped to the env var
# each one is gated on. The renderer only ever picks between layouts that are
# switched on here.
#
# This is opt-in per job, not a detector running on every video, because the
# detection is not good enough to be trusted unprompted: measured over the
# 48-clip corpus, routing every video through the on-screen-content check fixed
# 13 clips and spoiled 13 others (talking heads and corner tickers demoted to a
# layout they do not need). Asking the person who knows what they uploaded costs
# them one click and removes that whole class of error. It is also what OpusClip
# does — its "applicable auto layout" panel lets the user pick which layouts the
# AI may apply.
LAYOUT_ENV = {
"split": "SPLIT_LAYOUT", # two speakers stacked
"screencast": "SCREENCAST_LAYOUT", # slides/screen share over the speaker
"speaker_cut": "SPEAKER_CUT", # hard cuts to whoever is talking
"punch_in": "PUNCH_IN", # small push on the clip's beats
}
# Stacking and cutting both need to know who is speaking.
LAYOUT_IMPLIES = {
"split": ["SPEAKER_SIGNAL"],
"speaker_cut": ["SPEAKER_SIGNAL"],
}
def layout_env(requested):
"""Env overrides for the layouts this job allows. Unknown names are ignored
rather than rejected: a newer dashboard must not break an older API.
The special value "auto" hands the choice to Gemini (one call per video).
It composes with explicit picks: layout_picker only ever adds, so asking for
"auto,punch_in" means "decide the layout yourself, and punch in regardless".
"""
env = {}
for name in requested or []:
key = str(name).strip().lower()
if key == "auto":
env["AUTO_LAYOUT"] = "1"
continue
var = LAYOUT_ENV.get(key)
if not var:
continue
env[var] = "1"
for extra in LAYOUT_IMPLIES.get(key, []):
env[extra] = "1"
return env
@app.post("/api/process")
async def process_endpoint(
request: Request,
@ -1278,6 +1327,7 @@ async def process_endpoint(
url: Optional[str] = Form(None),
acknowledged: Optional[str] = Form(None),
output_format: Optional[str] = Form(None),
layouts: Optional[str] = Form(None),
force_low_quality: Optional[str] = Form(None)
):
api_key = await resolve_gemini(request)
@ -1295,11 +1345,18 @@ async def process_endpoint(
ack_flag = bool(body.get("acknowledged"))
force_low = bool(body.get("force_low_quality"))
output_format = body.get("output_format")
layouts = body.get("layouts")
# Normalize output format (auto = keep pipeline default).
if output_format not in ("vertical", "horizontal", "square"):
output_format = "auto"
# Accepts a JSON list or a comma-separated form field.
if isinstance(layouts, str):
layouts = [p for p in layouts.split(",") if p.strip()]
elif not isinstance(layouts, list):
layouts = []
if not url and not file:
raise HTTPException(status_code=400, detail="Must provide URL or File")
@ -1349,6 +1406,14 @@ async def process_endpoint(
env = os.environ.copy()
env["GEMINI_API_KEY"] = api_key # Override with key from request
# Optional layouts are per job. The renderer reads these at import time in
# the subprocess, so they must be set before Popen — same path WATERMARK
# already takes.
chosen = layout_env(layouts)
env.update(chosen)
if chosen:
print(f"[layouts] job={job_id} enabled={sorted(chosen)}")
input_path = None
if url:
cmd.extend(["-u", url])

View file

@ -81,6 +81,96 @@ to worst by how likely they are to stop a viewer scrolling.
"""
class LayoutChoice(BaseModel):
layout: str
confidence: float
why: str
# Scored 94/92/96% over the 48-clip corpus against hand-checked labels, with
# 0-1 false positives out of the 28 clips that must not be touched. Do not
# reword casually: the wins come from the explicit "none is usually right"
# instruction and from naming the exact decorations (corner bugs, score
# counters, subtitles) that four earlier attempts kept mistaking for content.
LAYOUT_CHOICE_PROMPT = """
You are choosing how to re-frame this landscape video into a vertical 9:16 clip.
Pick ONE layout:
- "none": crop to the speaker and fill the frame. This is the RIGHT answer for
ordinary talking heads, interviews shot in close-up, b-roll, sport, action,
music, and any footage whose meaning survives a centre crop. Corner logos,
score bugs, subscriber counters, lower-thirds and burned-in subtitles do NOT
change this: they are decoration, and losing them costs nothing.
- "screencast": put the screen content on top and the presenter below. ONLY when
the video is built around a screen recording, slides, a spreadsheet, a chart
or a map that the viewer must read to follow it. If you cannot read words or
numbers off the screen that matter to the point being made, it is not this.
- "split": stack two people. ONLY when two people are visible IN THE SAME SHOT
at the same time for most of the video, talking to each other. A video that
cuts between one-person close-ups is NOT this, however many people speak.
"none" is by far the most common correct answer. Choose anything else only if
you would defend it to an editor. If you are unsure, answer "none".
confidence is 0..1. why is at most 12 words.
"""
class WideContentRangeModel(BaseModel):
start: float
end: float
what: str
width_fraction: float
class WideContentResponse(BaseModel):
ranges: List[WideContentRangeModel]
WIDE_CONTENT_PROMPT_TEMPLATE = """
You are preparing a landscape video to be re-framed to a vertical 9:16 crop.
The crop keeps a tall centre strip and THROWS AWAY the left and right sides.
List every time range where on-screen content would be cut by that, and for each
one report HOW MUCH OF THE FRAME WIDTH the content spans.
width_fraction is the single most important field. Measure the content's own
horizontal extent, from its left edge to its right edge, as a fraction of the
full frame width:
- a spreadsheet, slide, screen recording or map filling the picture: 0.9 - 1.0
- a chart or diagram beside a speaker: 0.4 - 0.7
- a lower-third or headline strip across the bottom: 0.6 - 0.9
- a logo, channel bug, score counter or subscriber count in a corner: 0.1 - 0.2
- subtitles centred at the bottom: 0.3 - 0.5
Report what you actually see. Do NOT inflate the number to make a range seem
worth reporting, and do NOT leave out corner graphics — report them with their
true small width_fraction. A range reported honestly at 0.15 is useful; the same
range reported at 0.9 makes the video worse.
COUNT a range when the frame shows:
- a screen recording, slide, spreadsheet, chart, graph or map
- headlines, labels, statistics or comparison tables burned into the picture
- a side-by-side or split-screen layout
- any diagram or product shot where the edges carry the meaning
DO NOT count an ordinary talking head, even against a busy background, and do
not count b-roll, landscapes, crowds or action footage with no graphics.
TIME CONTRACT — STRICT:
- ABSOLUTE SECONDS from the start, numbers only, up to 3 decimals.
- 0 <= start < end <= {video_duration}.
- Merge ranges that are less than 1 second apart.
- Return an EMPTY list if the video never shows such content. An empty list is
the correct, expected answer for most talking-head and b-roll videos — do not
invent ranges to seem useful.
For "what", name the content in three words or fewer (e.g. "stock chart",
"spreadsheet", "corner ticker").
"""
def _configure_stdio() -> None:
for stream_name in ("stdout", "stderr"):
stream = getattr(sys, stream_name, None)

135
layout_picker.py Normal file
View file

@ -0,0 +1,135 @@
"""Ask Gemini which layout a video needs, once per video.
The four previous attempts at this problem asked the model (or a pixel
heuristic) to MEASURE something — edge density, MSER text density, what fraction
of the duration had content on screen, what fraction of the width it spanned —
and let thresholds turn that number into a routing decision. All four failed the
same way: they could not separate a spreadsheet from a corner scoreboard.
This asks for the decision itself. Measured over the 48-clip corpus against
hand-checked labels (`labels-layout.json` in the reframe-testing skill), three
runs:
run 1 45/48 94% 18/20 content found 1 false positive of 28
run 2 44/48 92% 17/20 1 of 28
run 3 46/48 96% 18/20 0 of 28
Two clips out of 48 changed answer between runs. That matters because the
earlier note in this repo said Gemini was too non-deterministic to build on —
the same video scored 1% and 97% coverage on consecutive runs. The variance was
in asking for a continuous measurement, not in the model: a categorical choice
between closed options is stable.
Off by default (``AUTO_LAYOUT=1``). A caller that already switched layouts on
by hand wins: this only ever ADDS, so an explicit choice is never overridden.
"""
import json
import os
import time
ENABLED = os.environ.get("AUTO_LAYOUT", "0") == "1"
# What each decision turns on. Keys match the layout names in the prompt.
DECISION_FLAGS = {
"none": [],
"screencast": ["screencast_layout"],
"split": ["split_layout", "active_speaker"],
}
VALID = set(DECISION_FLAGS)
def _module_flags(decision):
"""Modules to enable for a decision, ignoring anything unrecognised."""
return DECISION_FLAGS.get(str(decision or "none").strip().lower(), [])
def apply(decision):
"""Switch on the modules a decision needs. Returns the modules touched.
Deliberately additive: an operator who set SPLIT_LAYOUT=1 for a job wants
stacking regardless of what the model thinks, and a model that says "none"
must not quietly undo that.
"""
import active_speaker
import screencast_layout
import split_layout
modules = {"split_layout": split_layout,
"screencast_layout": screencast_layout,
"active_speaker": active_speaker}
touched = []
for name in _module_flags(decision):
module = modules.get(name)
if module is not None and not getattr(module, "ENABLED", False):
module.ENABLED = True
touched.append(name)
return touched
def pick(video_path, video_duration):
"""The layout Gemini picks for this video, or "none" on any failure.
Never raises: a missing answer has to degrade to today's routing rather
than break the job.
"""
if not ENABLED:
return "none"
api_key = os.getenv("GEMINI_API_KEY")
if not api_key:
return "none"
model_name = os.environ.get("GEMINI_MODEL") or 'gemini-3.1-flash-lite'
print("🎛️ Choosing a layout for this video…")
try:
# Inside the try on purpose: the contract above is that this never
# raises, and an unimportable SDK is just one more reason to fall back.
from google import genai
from google.genai import types as genai_types
import gemini_worker
client = genai.Client(api_key=api_key)
upload = client.files.upload(file=video_path)
deadline = time.time() + 180
while True:
info = client.files.get(name=upload.name)
state = str(getattr(getattr(info, "state", info), "name", "")).upper()
if state == "ACTIVE":
break
if state == "FAILED" or time.time() > deadline:
print(" ⚠️ Upload not usable — keeping the default layout.")
return "none"
time.sleep(2)
response = client.models.generate_content(
model=model_name,
contents=[upload, gemini_worker.LAYOUT_CHOICE_PROMPT],
config=genai_types.GenerateContentConfig(
response_mime_type="application/json",
response_schema=gemini_worker.LayoutChoice,
))
gemini_worker.raise_if_blocked(response)
answer = json.loads(response.text) or {}
except Exception as e:
print(f" ⚠️ Layout choice failed ({e}) — keeping the default layout.")
return "none"
decision = str(answer.get("layout", "none")).strip().lower()
if decision not in VALID:
print(f" ⚠️ Unknown layout '{decision}' — keeping the default layout.")
return "none"
why = str(answer.get("why", ""))[:80]
confidence = answer.get("confidence")
print(f" 🎬 Layout: {decision} (confianza {confidence}) — {why}")
return decision
def pick_and_apply(video_path, video_duration):
"""Convenience for the pipeline: decide, switch on, report what changed."""
decision = pick(video_path, video_duration)
touched = apply(decision)
if touched:
print(f" ✅ Enabled: {', '.join(touched)}")
return decision

15
main.py
View file

@ -22,6 +22,7 @@ from google import genai
from google.genai import types as genai_types
import gemini_worker
import layout_picker
from clip_selection import build_transcript_windows, snap_clip_to_words
from ffmpeg_utils import (video_encode_args, audio_encode_args, QUALITY,
QUALITY_FAST, METADATA_SCRUB)
@ -1448,6 +1449,20 @@ if __name__ == '__main__':
print(f"❌ Input file not found: {input_video}")
exit(1)
# Layout choice is per SOURCE video, not per clip: one upload and one call
# instead of one per clip, and the answer is a property of the material
# ("this is a screencast"), which does not change between its own clips.
# It runs before any render so the modules are switched on in time.
if layout_picker.ENABLED:
try:
_cap = cv2.VideoCapture(input_video)
_fps = _cap.get(cv2.CAP_PROP_FPS) or 30.0
_duration = int(_cap.get(cv2.CAP_PROP_FRAME_COUNT)) / _fps
_cap.release()
layout_picker.pick_and_apply(input_video, _duration)
except Exception as e:
print(f"⚠️ Layout choice skipped ({e}) — using the default layout.")
# 2. Decision: Analyze clips or process whole?
if args.skip_analysis:
print("⏩ Skipping analysis, processing entire video...")

172
punch_in.py Normal file
View file

@ -0,0 +1,172 @@
"""Punch-in: a short push toward the subject on the beats that carry the clip.
Not a layout. Every other mode here decides WHERE the frame sits; this one
decides when it moves in, which is the difference between a clip that reads as
footage and one that reads as edited. A static crop for 45 seconds is the single
most "unedited" thing a vertical clip can do.
The push is deliberately small. Anything past ~15% starts cropping the speaker's
head on a face-framed shot, and on an upscaled source it also starts showing.
The curve is asymmetric on purpose: fast in, hold, slow out, which is how a
human operator does it and how it reads as intent rather than drift.
It rides the TRACK path, widening the existing per-frame crop command from
x-only to w/h/x/y, so it composes with the camera trajectory instead of fighting
it. Off by default (``PUNCH_IN=1``).
Beat times come from the audio envelope. The transcript would be a better
source (punch on the hook word, not on the loudest syllable), and render() has
no transcript today — ``emphasis_times`` is a plain list of seconds, so wiring
main.py's word timings in later needs no change here.
"""
import os
import numpy as np
ENABLED = os.environ.get("PUNCH_IN", "0") == "1"
# Peak zoom. 1.12 crops 11% off each dimension: visible as intent, still short
# of cutting into a head framed by the TRACK crop.
MAX_ZOOM = float(os.environ.get("PUNCH_IN_ZOOM", "1.12"))
# Envelope, in seconds: snap in, sit there, drift out.
RISE_SECONDS = 0.25
HOLD_SECONDS = 1.30
FALL_SECONDS = 0.55
# Never punch twice inside this window. Two pushes in quick succession read as a
# glitch, and the second one lands before the first has released.
MIN_GAP_SECONDS = 4.0
# Audio-envelope resolution used to find beats.
BEAT_WINDOW = 0.2
# A beat must exceed the clip's median loudness by this much of the gap to its
# peak. Low values punch on every syllable; this keeps it to real emphasis.
BEAT_PROMINENCE = 0.45
def _ease(t):
"""Smoothstep on [0, 1]. Linear ramps look mechanical at this duration."""
t = min(max(t, 0.0), 1.0)
return t * t * (3.0 - 2.0 * t)
def zoom_curve(n_frames, fps, emphasis_times, max_zoom=None,
start_offset=0.0):
"""Per-frame zoom factor (1.0 = untouched) for one scene.
``emphasis_times`` are absolute seconds; ``start_offset`` is where this
scene begins, so callers can pass clip-level beats unchanged.
"""
max_zoom = MAX_ZOOM if max_zoom is None else max_zoom
zooms = [1.0] * max(0, n_frames)
if not zooms or max_zoom <= 1.0:
return zooms
span = RISE_SECONDS + HOLD_SECONDS + FALL_SECONDS
for t in emphasis_times:
local = t - start_offset
if local <= -span or local >= n_frames / fps:
continue
for f in range(max(0, int(local * fps)),
min(n_frames, int((local + span) * fps) + 1)):
dt = f / fps - local
if dt < 0:
continue
if dt < RISE_SECONDS:
amount = _ease(dt / RISE_SECONDS)
elif dt < RISE_SECONDS + HOLD_SECONDS:
amount = 1.0
elif dt < span:
amount = 1.0 - _ease(
(dt - RISE_SECONDS - HOLD_SECONDS) / FALL_SECONDS)
else:
continue
# Overlapping pushes take the strongest rather than compounding.
zooms[f] = max(zooms[f], 1.0 + (max_zoom - 1.0) * amount)
return zooms
def crop_boxes(xs, zooms, crop_w, crop_h, orig_w, orig_h):
"""Per-frame (w, h, x, y), zooming about the tracked crop's own centre.
Keeping the centre fixed is what makes this a push rather than a pan: the
subject stays put and the frame closes in around them.
"""
boxes = []
for i, x in enumerate(xs):
z = zooms[i] if i < len(zooms) else 1.0
w = int(crop_w / z)
h = int(crop_h / z)
w -= w % 2
h -= h % 2
w = max(2, min(w, orig_w))
h = max(2, min(h, orig_h))
cx = x + crop_w / 2.0
cy = crop_h / 2.0
nx = int(round(cx - w / 2.0))
ny = int(round(cy - h / 2.0))
nx = max(0, min(nx, orig_w - w))
ny = max(0, min(ny, orig_h - h))
boxes.append((w, h, nx - (nx % 2), ny - (ny % 2)))
return boxes
def sendcmd_lines(boxes, fps, target="crop@c"):
"""sendcmd lines for per-frame w/h/x/y, deduped to change-points.
Same contract as reframe_v2.dedupe_sendcmd_lines, but four parameters: at
30fps a 45s clip is 1350 frames and writing every parameter every frame
makes a command file large enough to slow the filter down.
"""
lines = []
prev = None
for i, box in enumerate(boxes):
if box == prev:
continue
t = i / fps
w, h, x, y = box
pw, ph, px, py = prev if prev else (None, None, None, None)
if w != pw:
lines.append(f"{t:.4f} {target} w {w};")
if h != ph:
lines.append(f"{t:.4f} {target} h {h};")
if x != px:
lines.append(f"{t:.4f} {target} x {x};")
if y != py:
lines.append(f"{t:.4f} {target} y {y};")
prev = box
return lines
def emphasis_times(video_path, duration, window=BEAT_WINDOW,
min_gap=MIN_GAP_SECONDS, prominence=BEAT_PROMINENCE):
"""Seconds where the audio leaps above its own baseline.
A stand-in for the hook words until the transcript is wired through. Returns
[] for silent or unreadable audio, which simply means no punches.
"""
import active_speaker
envelope = active_speaker.audio_envelope(video_path, 0.0, duration,
window_s=window)
if not envelope:
return []
values = np.asarray(envelope, dtype=float)
baseline = float(np.median(values))
peak = float(values.max())
if peak - baseline <= 1e-6:
return []
threshold = baseline + (peak - baseline) * prominence
times = []
last = -1e9
for i, v in enumerate(values):
t = i * window
if v >= threshold and t - last >= min_gap:
times.append(round(t, 3))
last = t
return times

View file

@ -21,6 +21,10 @@ import os
import subprocess
import tempfile
import active_speaker
import punch_in
import screencast_layout
import split_layout
from ffmpeg_utils import video_encode_args, QUALITY_FAST, METADATA_SCRUB
ANALYSIS_MAX_WIDTH = 640
@ -110,11 +114,23 @@ GENERAL_CONTENT_HEIGHT_RATIO = float(
os.environ.get("GENERAL_CONTENT_HEIGHT_RATIO", "0.42"))
def general_filtergraph(out_w, out_h):
def full_width_content_height(orig_w, orig_h, out_w):
"""Height the source fills when its FULL width is kept (even)."""
fg_h = int(round(out_w * orig_h / float(orig_w)))
return fg_h + (fg_h % 2)
def general_filtergraph(out_w, out_h, content_h=None):
"""Blurred-background 'general shot' layout: bg fills the frame (centre-
cropped, blurred), fg is scaled to a readable share of the height and
centred, overflowing the sides rather than floating small in the middle."""
fg_h = int(out_h * GENERAL_CONTENT_HEIGHT_RATIO)
centred, overflowing the sides rather than floating small in the middle.
``content_h`` overrides the height ratio. Passing the full-width height
turns the side-cropping off entirely, which is what a scene full of charts
or spreadsheets needs: the default 0.42 ratio buys presence by throwing away
~24% of the width, and on that material the discarded columns are the point.
"""
fg_h = content_h if content_h else int(out_h * GENERAL_CONTENT_HEIGHT_RATIO)
fg_h += fg_h % 2
return (
f"[0:v]split=2[bga][fga];"
@ -170,7 +186,11 @@ def _analyze_trajectory(input_video, scenes_boundaries, scene_strategies,
strategy = (scene_strategies[current_scene_index]
if current_scene_index < len(scene_strategies) else 'TRACK')
if strategy == 'GENERAL':
# SPLIT, SCREENCAST and WIDE crops are static (fixed boxes for the
# whole scene), so like GENERAL they need no camera trajectory.
# ALTERNATE gets one written in after this pass.
if strategy in ('GENERAL', 'SPLIT', 'SCREENCAST', 'WIDE',
'ALTERNATE'):
cameraman.current_center_x = orig_w / 2
cameraman.target_center_x = orig_w / 2
xs.append(None)
@ -209,9 +229,15 @@ def _run(cmd):
stderr=subprocess.PIPE, timeout=1800)
def render(input_video, final_output_video, aspect_ratio):
"""Full v2 reframe of one clip. Raises on failure (caller falls back)."""
def render(input_video, final_output_video, aspect_ratio, content_ranges=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.
"""
import main as m
content_ranges = content_ranges or []
print(" 🚀 Reframe engine v2 (ffmpeg-native render)")
scenes, fps = m.detect_scenes(input_video)
@ -231,6 +257,64 @@ def render(input_video, final_output_video, aspect_ratio):
scene_boundaries = [(s.get_frames(), e.get_frames()) for s, e in scenes]
strategies = m.analyze_scenes_strategy(input_video, scenes)
# SPLIT is an upgrade applied on top of the TRACK/GENERAL verdict, keyed by
# the scene's START FRAME rather than its index: scene_frame_ranges() drops
# empty ranges, so indices there don't line up with `scenes`. A surviving
# range always keeps its original start_f (the clamp only bites on scenes
# that begin past the last decoded frame, and those get dropped).
splits = {}
split_scene_of = {}
for scene_idx, centres in split_layout.detect_split_scenes(
input_video, scenes, strategies).items():
strategies[scene_idx] = 'SPLIT'
start_f = scene_boundaries[scene_idx][0]
splits[start_f] = centres
split_scene_of[start_f] = scene_idx
# Geometry alone will stack a scene where one person never speaks. Ask who
# is actually talking before spending half the frame on the other one.
alternates = {}
if splits and active_speaker.ENABLED:
for start_f in list(splits):
scene_idx = split_scene_of[start_f]
end_f = scene_boundaries[scene_idx][1]
verdicts = active_speaker.verdicts_for_scene(
input_video, start_f, end_f, fps, splits[start_f])
if not active_speaker.is_conversation(verdicts):
a, b = active_speaker.shares(verdicts)
print(f" 🔇 Scene {scene_idx}: one speaker holds the floor "
f"({max(a, b):.0%}) — not stacking")
del splits[start_f]
strategies[scene_idx] = 'GENERAL'
elif active_speaker.CUT_MODE:
strategies[scene_idx] = 'ALTERNATE'
alternates[start_f] = (
active_speaker.hold(verdicts), splits.pop(start_f))
if splits:
print(f" 🪞 SPLIT layout on {len(splits)} scene(s)")
if alternates:
print(f" 🎬 Speaker-cut layout on {len(alternates)} 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.
screencasts = {}
wide_count = 0
if content_ranges:
for scene_idx, (plan, centre) in screencast_layout.detect_screencast_scenes(
input_video, scenes, strategies, content_ranges).items():
strategies[scene_idx] = plan
start_f = scene_boundaries[scene_idx][0]
splits.pop(start_f, None)
if plan == 'SCREENCAST':
screencasts[start_f] = centre
else:
wide_count += 1
if screencasts:
print(f" 🖥️ SCREENCAST layout on {len(screencasts)} scene(s)")
if wide_count:
print(f" 📐 Full-width layout on {wide_count} scene(s)")
# The crop geometry comes from the SOURCE dims only — SmoothedCameraman
# derives crop_width/crop_height from video_width/video_height and never
# reads the output pair. So out_w/out_h being the (possibly upscaled)
@ -243,11 +327,30 @@ def render(input_video, final_output_video, aspect_ratio):
if not xs:
raise RuntimeError("analysis produced no frames")
# 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)
if beats:
print(f" 🔍 Punch-in on {len(beats)} beat(s)")
crop_w, crop_h = cameraman.crop_width, cameraman.crop_height
# ALTERNATE renders through the TRACK path: hard cuts between two speakers
# are still just a list of crop x values, so no new filtergraph is needed.
# The trajectory is written here because the analysis pass deliberately
# skips these scenes rather than tracking a face through them.
for start_f, (held, centres) in alternates.items():
end_f = scene_boundaries[split_scene_of[start_f]][1]
end_f = min(end_f, len(xs))
if end_f <= start_f:
continue
xs[start_f:end_f] = active_speaker.speaker_xs(
held, centres, crop_w, orig_w, end_f - start_f, fps)
ranges = scene_frame_ranges(scene_boundaries, strategies, len(xs))
if not ranges:
raise RuntimeError("no usable scene ranges")
crop_w, crop_h = cameraman.crop_width, cameraman.crop_height
workdir = tempfile.mkdtemp(prefix="reframe_v2_")
segments = []
try:
@ -256,16 +359,38 @@ def render(input_video, final_output_video, aspect_ratio):
ss = start_f / fps
dur = (end_f - start_f) / fps
if strategy == 'GENERAL':
if strategy == 'SCREENCAST':
graph = screencast_layout.screencast_filtergraph(
orig_w, orig_h, out_w, out_h, screencasts[start_f])
elif strategy == 'WIDE':
graph = general_filtergraph(
out_w, out_h,
full_width_content_height(orig_w, orig_h, out_w))
elif strategy == 'SPLIT':
left, right = splits[start_f]
graph = split_layout.split_filtergraph(
orig_w, orig_h, out_w, out_h, left, right)
elif strategy == 'GENERAL':
graph = general_filtergraph(out_w, out_h)
else:
seg_xs = [x if x is not None else 0 for x in xs[start_f:end_f]]
cmd_path = os.path.join(workdir, f"cmd_{idx:03d}.txt")
if beats:
zooms = punch_in.zoom_curve(len(seg_xs), fps, beats,
start_offset=ss)
boxes = punch_in.crop_boxes(seg_xs, zooms, crop_w, crop_h,
orig_w, orig_h)
lines = punch_in.sendcmd_lines(boxes, fps)
first = boxes[0]
init = f"w={first[0]}:h={first[1]}:x={first[2]}:y={first[3]}"
else:
lines = dedupe_sendcmd_lines(seg_xs, fps)
init = f"w={crop_w}:h={crop_h}:x={seg_xs[0]}:y=0"
with open(cmd_path, "w") as f:
f.write("\n".join(dedupe_sendcmd_lines(seg_xs, fps)) + "\n")
f.write("\n".join(lines) + "\n")
graph = (
f"[0:v]sendcmd=f='{cmd_path}',"
f"crop@c=w={crop_w}:h={crop_h}:x={seg_xs[0]}:y=0,"
f"crop@c={init},"
f"scale={out_w}:{out_h},setsar=1[v]"
)

316
screencast_layout.py Normal file
View file

@ -0,0 +1,316 @@
"""SCREENCAST layout: full-width content on top, the speaker underneath.
The fourth layout. It targets the failure this repo has now attacked three
times: a screen recording that happens to contain a face gets classified TRACK,
the 9:16 crop keeps a centre strip, and the chart or headline the shot is
actually about comes out sliced mid-word.
The two previous attempts tried to find that content in pixels and both failed
(see the note above analyze_scenes_strategy in main.py): edge density and MSER
text density BOTH score ordinary detailed footage higher than a clean panel of
text, because they measure visual busyness rather than meaning. The third
attempt asked Gemini and detected well, but decided badly: it flagged corner
tickers and demoted well-framed talking heads to the blurred layout.
What is different here is the question asked and what the answer is used for.
- The question is how much of the WIDTH the content spans, not how much of the
duration it covers. Coverage did not separate the cases (screencasts ran
88-97% of the video, a corner-ticker clip 2%, but the failure was on the
ticker anyway). Width is the quantity that actually decides whether a 9:16
crop destroys information: a corner bug spans ~15% of the frame and survives
any crop, a spreadsheet spans ~100% and cannot.
- The answer routes to THIS layout, not to GENERAL. The old wiring's worst
case was shrinking a subject into blurred filler to preserve a corner
counter. Here the worst case is showing the content full width above the
speaker, which is a reasonable frame even when the trigger was wrong.
Off by default (``SCREENCAST_LAYOUT=1``). Needs GEMINI_API_KEY; without one it
is a silent no-op, like every other optional Gemini path here.
"""
import json
import os
import time
import numpy as np
ENABLED = os.environ.get("SCREENCAST_LAYOUT", "0") == "1"
# Fraction of the frame width the content must span. A corner ticker, logo or
# channel bug sits far below this; a screen recording, slide or spreadsheet sits
# near 1.0. This is the axis the previous attempt did not ask about.
MIN_WIDTH_FRACTION = 0.5
# Above this the content fills the frame, so any presenter is composited ON TOP
# of it rather than sitting beside it. Stacking then shows the same content
# twice: measured on an Excel walkthrough where the speaker is keyed into the
# corner, the bottom band came out as a zoomed crop of the same spreadsheet.
# Those scenes get the full-width GENERAL layout instead, which is the fix they
# actually needed — the default GENERAL ratio crops ~24% off the sides, and on a
# spreadsheet the discarded columns are the point.
STACK_MAX_WIDTH_FRACTION = 0.85
# Seconds of overlap before a scene counts as showing the content.
MIN_OVERLAP_SECONDS = 0.25
# The speaker crop below the content needs a face of at least this width
# (fraction of frame width). Smaller than this and the bottom half is mostly
# desktop with a stamp-sized webcam in it, which is worse than GENERAL.
MIN_FACE_WIDTH = 0.05
def content_bands(orig_w, orig_h, out_w, out_h):
"""(content_height, speaker_height) for the stacked screencast frame.
The content keeps its full width, which is the entire point of this layout,
so its height follows from the source aspect: a 16:9 source gives 608px of a
1920px frame. The speaker takes the rest.
"""
content_h = int(round(out_w * orig_h / float(orig_w)))
content_h -= content_h % 2
content_h = max(2, min(content_h, out_h - 2))
speaker_h = out_h - content_h
return content_h, speaker_h
def speaker_crop(orig_w, orig_h, out_w, speaker_h, face_centre):
"""Crop box (w, h, x, y) for the speaker band, framed on the face."""
aspect = out_w / float(speaker_h)
crop_h = orig_h
crop_w = int(round(crop_h * aspect))
if crop_w > orig_w:
crop_w = orig_w
crop_h = int(round(crop_w / aspect))
crop_w -= crop_w % 2
crop_h -= crop_h % 2
cx, cy = face_centre
x = int(round(cx - crop_w / 2.0))
x = max(0, min(x, orig_w - crop_w))
y = int(round(cy - crop_h * 0.42))
y = max(0, min(y, orig_h - crop_h))
return crop_w, crop_h, x - (x % 2), y - (y % 2)
def screencast_filtergraph(orig_w, orig_h, out_w, out_h, face_centre):
"""Full-width content above, face-framed speaker below."""
content_h, speaker_h = content_bands(orig_w, orig_h, out_w, out_h)
cw, ch, cx, cy = speaker_crop(orig_w, orig_h, out_w, speaker_h, face_centre)
return (
f"[0:v]split=2[ca][sa];"
# The content band is the WHOLE frame scaled down. Nothing is cropped
# off the sides, which is the one thing this layout exists to guarantee.
f"[ca]scale={out_w}:{content_h}[content];"
f"[sa]crop=w={cw}:h={ch}:x={cx}:y={cy},scale={out_w}:{speaker_h}[speaker];"
f"[content][speaker]vstack=inputs=2,"
f"pad={out_w}:{out_h}:0:0,setsar=1[v]"
)
def detect_faces_full_res(frame):
"""Face boxes from the UNSCALED frame, in original coordinates.
main.detect_face_candidates() runs detection on a 640px copy, which is the
right trade for a talking head whose face spans a third of the frame. A
presenter inset into a screen recording does not survive it: measured on a
1920x1080 Excel walkthrough, the presenter's ~110px face becomes ~37px at
640 and BlazeFace returned zero detections on every sample. At full width
the same frames detect fine. Six samples per scene, so the cost is paid on
screencast candidates only.
"""
import cv2
import main as m
h, w, _ = frame.shape
rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
with m.DETECT_LOCK:
results = m.face_detection.process(rgb)
if not results.detections:
return []
out = []
for detection in results.detections:
b = detection.location_data.relative_bounding_box
box = [int(b.xmin * w), int(b.ymin * h),
int(b.width * w), int(b.height * h)]
out.append({'box': box, 'score': box[2] * box[3]})
return out
def _face_centre(candidates, frame_w):
"""Centre of the biggest usable face in a frame, or None."""
big = [c for c in candidates if c['box'][2] >= MIN_FACE_WIDTH * frame_w]
if not big:
return None
box = max(big, key=lambda c: c['score'])['box']
return box[0] + box[2] / 2.0, box[1] + box[3] / 2.0
def overlapping_width(scene_start, scene_end, ranges):
"""Widest content the scene overlaps, as a fraction of frame width.
0.0 when the scene overlaps nothing, which leaves its routing untouched.
"""
widest = 0.0
for r in ranges:
start, end = r[0], r[1]
width = r[3] if len(r) > 3 else 1.0
if min(scene_end, end) - max(scene_start, start) > MIN_OVERLAP_SECONDS:
widest = max(widest, width)
return widest
def detect_content_ranges(video_path, video_duration):
"""Time ranges where on-screen content spans most of the frame width.
Returns (start, end, what, width_fraction) tuples, or [] on any failure:
a missing answer must degrade to today's routing rather than break the job.
"""
if not ENABLED:
return []
api_key = os.getenv("GEMINI_API_KEY")
if not api_key:
return []
from google import genai
from google.genai import types as genai_types
import gemini_worker
model_name = os.environ.get("GEMINI_MODEL") or 'gemini-3.1-flash-lite'
print("🔎 Checking for full-width on-screen content…")
try:
client = genai.Client(api_key=api_key)
file_upload = client.files.upload(file=video_path)
deadline = time.time() + 180
while True:
info = client.files.get(name=file_upload.name)
state = str(getattr(getattr(info, "state", info), "name", "")).upper()
if state == "ACTIVE":
break
if state == "FAILED" or time.time() > deadline:
print(" ⚠️ Upload not usable — keeping face-only routing.")
return []
time.sleep(2)
response = client.models.generate_content(
model=model_name,
contents=[file_upload,
gemini_worker.WIDE_CONTENT_PROMPT_TEMPLATE.format(
video_duration=video_duration)],
config=genai_types.GenerateContentConfig(
response_mime_type="application/json",
response_schema=gemini_worker.WideContentResponse,
))
gemini_worker.raise_if_blocked(response)
raw = (json.loads(response.text) or {}).get("ranges") or []
except Exception as e:
print(f" ⚠️ On-screen check failed ({e}) — keeping face-only routing.")
return []
ranges = []
for r in raw:
try:
s = max(0.0, float(r.get("start", 0)))
e = min(float(video_duration), float(r.get("end", 0)))
width = float(r.get("width_fraction", 0))
except (TypeError, ValueError):
continue
# The width gate is the whole point: everything narrower survives a 9:16
# crop and must not move a single scene.
if e - s >= 0.5 and width >= MIN_WIDTH_FRACTION:
ranges.append((s, e, str(r.get("what", ""))[:40], width))
ranges.sort()
if ranges:
print(" 📊 " + ", ".join(
f"{w}@{s:.0f}-{e:.0f}s ({frac:.0%} wide)"
for s, e, w, frac in ranges[:5]))
else:
print(" ✅ No full-width content — routing unchanged.")
return ranges
def detect_screencast_scenes(video_path, scenes, strategies, ranges, samples=6):
"""Route scenes that show wide on-screen content.
Returns ``{scene_index: ('SCREENCAST', centre) | ('WIDE', None)}``:
- SCREENCAST stacks the content over the presenter, for content that
leaves room beside itself (width below STACK_MAX_WIDTH_FRACTION) and
where a presenter is actually found.
- WIDE is the blurred layout with side-cropping disabled, for content that
fills the frame, or that has no presenter to stack.
"""
import cv2
import main as m
if not ENABLED or not ranges:
return {}
cap = cv2.VideoCapture(video_path)
if not cap.isOpened():
return {}
fps = cap.get(cv2.CAP_PROP_FPS) or 30.0
frame_w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) or 0
found = {}
try:
for i, (start, end) in enumerate(scenes):
s_f, e_f = start.get_frames(), end.get_frames()
width = overlapping_width(s_f / fps, e_f / fps, ranges)
if not width:
continue
# Content that fills the frame has the presenter on top of it, so
# there is nothing to stack — just stop cropping the sides.
if width > STACK_MAX_WIDTH_FRACTION:
found[i] = ('WIDE', None)
continue
last_f = e_f - 1
if total_frames:
last_f = min(last_f, total_frames - 1)
if last_f < s_f:
continue
centres = []
for f_idx in np.linspace(s_f, last_f, samples):
cap.set(cv2.CAP_PROP_POS_FRAMES, int(round(f_idx)))
ok, frame = cap.read()
if not ok:
continue
centre = _face_centre(detect_faces_full_res(frame), frame_w)
if centre is None:
# A presenter keyed into the corner of a screen recording is
# often too small for BlazeFace even at full resolution
# (measured: zero detections across an Excel walkthrough
# where the person is plainly visible). YOLO finds the body
# in the same frames, and a body centre frames the speaker
# just as well for this layout.
person = m.detect_person_yolo(frame)
if person:
centre = (person[0] + person[2] / 2.0,
person[1] + person[3] / 2.0)
if centre:
centres.append(centre)
# Half the samples: a webcam inset is static and easy to find, so a
# weaker signal than this means there is no presenter to stack, and
# the content still deserves its full width.
if len(centres) < samples / 2.0:
found[i] = ('WIDE', None)
continue
found[i] = ('SCREENCAST',
(float(np.median([c[0] for c in centres])),
float(np.median([c[1] for c in centres]))))
finally:
cap.release()
return found

249
split_layout.py Normal file
View file

@ -0,0 +1,249 @@
"""SPLIT layout: two speakers stacked one above the other in the 9:16 frame.
The third layout, next to TRACK (crop to one face) and GENERAL (blurred
background). It exists for the one case both of the others handle badly: two
people sharing a wide shot and talking to each other. TRACK picks one of them
and throws away the reaction, which is usually where the hook is; GENERAL keeps
both but shrinks them to a strip floating in blur.
Stacking gives each speaker a half-frame crop, so a 1920x1080 source feeds each
half a 1215x1080 region that scales DOWN to 1080x960. No upscaling, unlike the
single-face crop of a 720p source.
Gated off by default (``SPLIT_LAYOUT=1`` to enable): a wrong SPLIT is a worse
failure than a wrong TRACK, because half the frame is then a person who never
moves.
"""
import os
import numpy as np
ENABLED = os.environ.get("SPLIT_LAYOUT", "0") == "1"
# Fraction of sampled frames that must show BOTH faces at once.
#
# Coexistence in one frame is the thing being tested: it separates a real
# two-shot from a plano/contraplano cut between two cameras, where each face is
# on screen most of the time but never together, and where stacking would show
# the same person twice.
#
# The bar is 0.5 and not higher because BlazeFace loses faces in profile — which
# is exactly how someone sits while listening to the person next to them.
# Measured on a 22s two-shot: 6 of 10 readable samples had both faces, and every
# miss was one speaker turned to face the other, with both plainly in frame. A
# 0.7 bar rejected that scene, i.e. it rejected the conversation for looking
# like a conversation.
MIN_COEXISTENCE = 0.5
# Horizontal separation between the two face centres, as a fraction of frame
# width. Two faces closer than this are people sitting shoulder to shoulder,
# which a single TRACK crop already frames fine — stacking them would show the
# same pair of shoulders twice.
MIN_SEPARATION = 0.20
# Faces smaller than this (width, as a fraction of frame width) are background
# extras, an audience, or a photo on the wall. Stacking onto one would fill half
# the output with a blurry stranger.
MIN_FACE_WIDTH = 0.045
# Below this a stacked layout reads as a glitch rather than a choice: the viewer
# needs a beat to understand the split before it cuts away.
MIN_SCENE_SECONDS = 2.5
# Fraction of the source height each half-crop takes. At 1.0 the crop is as wide
# as the half-frame aspect allows (1215px on a 1920x1080 source), which never
# upscales but leaves the OTHER speaker's shoulder visible in the corner when
# the two sit close together. Tightening drops the neighbour out of frame at the
# cost of some upscale: 0.8 on a 1080p source scales 972 -> 1080, i.e. 1.11x.
SPLIT_TIGHTNESS = float(os.environ.get("SPLIT_TIGHTNESS", "0.8"))
def _two_largest(candidates, frame_w):
"""The two biggest faces in a frame, left first, or None."""
big = [c for c in candidates if c['box'][2] >= MIN_FACE_WIDTH * frame_w]
if len(big) < 2:
return None
big.sort(key=lambda c: c['score'], reverse=True)
a, b = big[0], big[1]
return tuple(sorted((a, b), key=lambda c: c['box'][0]))
def _centre(box):
"""(cx, cy, w, h). The size travels with the centre because active_speaker
needs a mouth region, and re-detecting the faces to get it back would mean a
second pass over the same frames."""
x, y, w, h = box
return x + w / 2.0, y + h / 2.0, float(w), float(h)
def as_box(centre):
"""Inverse of _centre: an [x, y, w, h] box from a (cx, cy, w, h) tuple."""
cx, cy, w, h = centre
return [cx - w / 2.0, cy - h / 2.0, w, h]
def analyze_scene(frames, frame_w):
"""Decide whether these sampled frames show a stackable two-shot.
``frames`` is a list of per-frame face candidate lists (same shape as
``main.detect_face_candidates`` returns). Returns ``(left, right)`` face
centres as (cx, cy) pairs, or None.
"""
if not frames:
return None
lefts, rights = [], []
for candidates in frames:
pair = _two_largest(candidates, frame_w)
if not pair:
continue
left_c, right_c = _centre(pair[0]['box']), _centre(pair[1]['box'])
if (right_c[0] - left_c[0]) < MIN_SEPARATION * frame_w:
continue
lefts.append(left_c)
rights.append(right_c)
if len(lefts) < MIN_COEXISTENCE * len(frames):
return None
# Median, not mean: one frame where the detector latched onto a bystander
# would drag a mean crop off the speaker for the whole scene.
left = tuple(float(np.median([c[i] for c in lefts])) for i in range(4))
right = tuple(float(np.median([c[i] for c in rights])) for i in range(4))
return left, right
def split_geometry(orig_w, orig_h, out_w, out_h, centre):
"""Crop box (w, h, x, y) framing ``centre`` for one half of the stack.
Each half is out_w x out_h/2, so the crop is much wider than the 9:16 one
TRACK uses; on a 16:9 source it is the full height and ~63% of the width.
"""
half_h = out_h // 2
half_h -= half_h % 2
aspect = out_w / float(half_h)
crop_h = int(round(orig_h * max(0.3, min(SPLIT_TIGHTNESS, 1.0))))
crop_w = int(round(crop_h * aspect))
if crop_w > orig_w:
crop_w = orig_w
crop_h = int(round(crop_w / aspect))
crop_w -= crop_w % 2
crop_h -= crop_h % 2
cx, cy = centre[0], centre[1]
x = int(round(cx - crop_w / 2.0))
x = max(0, min(x, orig_w - crop_w))
# Faces sit high in a frame, so centring the crop on the face centre buries
# the speaker's chin at the bottom edge when the crop is shorter than the
# source. Bias the box down a little to keep headroom natural.
y = int(round(cy - crop_h * 0.42))
y = max(0, min(y, orig_h - crop_h))
return crop_w, crop_h, x - (x % 2), y - (y % 2), half_h
def split_filtergraph(orig_w, orig_h, out_w, out_h, left_centre, right_centre):
"""vstack of two face-framed crops. Left-hand speaker goes on top.
Screen position is the only stable ordering available without diarisation:
keying off who speaks first would swap the two halves between scenes of the
same conversation, which reads as an edit mistake.
"""
top_w, top_h, top_x, top_y, half_h = split_geometry(
orig_w, orig_h, out_w, out_h, left_centre)
bot_w, bot_h, bot_x, bot_y, _ = split_geometry(
orig_w, orig_h, out_w, out_h, right_centre)
return (
f"[0:v]split=2[ta][ba];"
f"[ta]crop=w={top_w}:h={top_h}:x={top_x}:y={top_y},"
f"scale={out_w}:{half_h}[top];"
f"[ba]crop=w={bot_w}:h={bot_h}:x={bot_x}:y={bot_y},"
f"scale={out_w}:{half_h}[bot];"
f"[top][bot]vstack=inputs=2,"
# vstack of two half_h halves can be 2px short of out_h after the
# even-rounding above; pad rather than scale so neither half is
# resampled a second time.
f"pad={out_w}:{out_h}:0:0,setsar=1[v]"
)
# One sample per this many seconds of scene, within the bounds below. A fixed
# count made long scenes fragile: on a 22s two-shot, 8 samples put the estimate
# within one profile-turn of flipping the verdict. Sampling in proportion to
# duration makes it stable without moving the bar.
SECONDS_PER_SAMPLE = 1.5
MIN_SAMPLES = 8
MAX_SAMPLES = 24
def detect_split_scenes(video_path, scenes, strategies, samples=None):
"""Upgrade qualifying scenes to SPLIT.
Returns ``{scene_index: (left_centre, right_centre)}``. Only scenes the
existing classifier sent to GENERAL are considered: a GENERAL verdict
already means "more than one face", and leaving TRACK alone keeps this from
touching the single-speaker material that is most of the corpus.
"""
import cv2
import main as m
if not ENABLED:
return {}
cap = cv2.VideoCapture(video_path)
if not cap.isOpened():
return {}
fps = cap.get(cv2.CAP_PROP_FPS) or 30.0
frame_w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
# Scene ends can sit past the last decodable frame (the detector counts from
# container metadata). Seeking there returns nothing, and those misses used
# to look like "the second speaker left", pushing a real two-shot below the
# presence bar: measured 4 of 12 samples lost on a 22s scene.
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) or 0
found = {}
try:
for i, (start, end) in enumerate(scenes):
if i < len(strategies) and strategies[i] != 'GENERAL':
continue
s_f, e_f = start.get_frames(), end.get_frames()
duration = (e_f - s_f) / fps
if duration < MIN_SCENE_SECONDS:
continue
n = samples or int(min(max(duration / SECONDS_PER_SAMPLE,
MIN_SAMPLES), MAX_SAMPLES))
last_f = e_f - 1
if total_frames:
last_f = min(last_f, total_frames - 1)
if last_f < s_f:
continue
sampled = []
for f_idx in np.linspace(s_f, last_f, n):
cap.set(cv2.CAP_PROP_POS_FRAMES, int(round(f_idx)))
ok, frame = cap.read()
if not ok:
continue
if frame.mean() < 16: # fade to black, same as the classifier
continue
sampled.append(m.detect_face_candidates(frame))
# Too few readable samples to call it: defaulting to GENERAL costs a
# nicer layout, defaulting to SPLIT risks half a frame of nobody.
if len(sampled) < max(4, n // 2):
continue
pair = analyze_scene(sampled, frame_w)
if pair:
found[i] = pair
finally:
cap.release()
return found

View file

@ -0,0 +1,125 @@
from active_speaker import (
attribute_windows,
hold,
is_conversation,
mouth_region,
normalise_activity,
shares,
speaker_xs,
)
class TestMouthRegion:
def test_region_sits_below_the_face_centre(self):
box = [800, 300, 200, 200] # centre y = 400
_x0, y0, _x1, y1 = mouth_region(box, 1920, 1080)
assert (y0 + y1) / 2 > 400
def test_region_stays_inside_the_frame(self):
for box in ([0, 0, 100, 100], [1850, 1000, 100, 100]):
x0, y0, x1, y1 = mouth_region(box, 1920, 1080)
assert 0 <= x0 < x1 <= 1920
assert 0 <= y0 < y1 <= 1080
def test_region_is_never_empty(self):
x0, y0, x1, y1 = mouth_region([10, 10, 4, 4], 1920, 1080)
assert x1 > x0 and y1 > y0
def test_scale_maps_back_to_analysis_resolution(self):
# Boxes arrive in original coordinates; the frames analysed are smaller.
big = mouth_region([800, 300, 200, 200], 1920, 1080, scale=1.0)
small = mouth_region([800, 300, 200, 200], 480, 270, scale=4.0)
assert small[0] < big[0] and small[2] < big[2]
class TestNormaliseActivity:
def test_a_brighter_face_does_not_win_every_window(self):
# Same pattern, one speaker's magnitudes 10x the other's. Raw values
# would hand every window to the loud column; this is the measured
# failure that made one speaker hold 90-100% of a real scene.
pattern = [1.0, 5.0, 1.0, 5.0]
activity = [[p * 10, q] for p, q in zip(pattern, reversed(pattern))]
normalised = normalise_activity(activity)
winners = {0 if a > b else 1 for a, b in normalised}
assert winners == {0, 1}
def test_empty_input_is_safe(self):
assert normalise_activity([]) == []
def test_flat_input_does_not_divide_by_zero(self):
out = normalise_activity([[2.0, 2.0]] * 5)
assert all(all(v == v for v in row) for row in out) # no NaN
class TestAttributeWindows:
def test_silence_is_never_attributed(self):
activity = [[0.0, 9.0]]
assert attribute_windows(activity, loudness=[0.01]) == [None]
def test_clear_winner_takes_the_window(self):
assert attribute_windows([[9.0, 1.0]], loudness=[1.0]) == [0]
assert attribute_windows([[1.0, 9.0]], loudness=[1.0]) == [1]
def test_a_tie_is_left_unattributed(self):
assert attribute_windows([[5.0, 5.0]], loudness=[1.0]) == [None]
def test_missing_audio_still_decides(self):
# No audio track: mouth movement alone should still vote.
assert attribute_windows([[9.0, 1.0]], loudness=[]) == [0]
def test_zero_activity_is_unattributed(self):
assert attribute_windows([[0.0, 0.0]], loudness=[1.0]) == [None]
class TestShares:
def test_shares_ignore_unattributed_windows(self):
assert shares([0, 1, None, None]) == (0.5, 0.5)
def test_no_evidence_reports_zero_not_a_tie(self):
assert shares([None, None]) == (0.0, 0.0)
def test_conversation_needs_both_voices(self):
assert is_conversation([0, 1, 0, 1, 0])
assert not is_conversation([0] * 9 + [1])
assert not is_conversation([None, None])
class TestHold:
def test_a_single_interjection_does_not_steal_the_frame(self):
held = hold([0, 0, 0, 1, 0, 0, 0], min_windows=3)
assert set(held) == {0}
def test_a_sustained_turn_takes_over(self):
held = hold([0, 0, 0, 1, 1, 1, 1], min_windows=3)
assert held[-1] == 1
def test_unclear_windows_inherit_the_current_speaker(self):
assert hold([0, None, None, 0], min_windows=3) == [0, 0, 0, 0]
def test_lead_in_is_backfilled(self):
assert hold([None, None, 1, 1, 1], min_windows=1)[0] == 1
def test_all_unclear_stays_unclear(self):
assert hold([None, None, None]) == [None, None, None]
class TestSpeakerXs:
def test_x_follows_the_held_speaker(self):
centres = [(400, 500, 200, 200), (1500, 500, 200, 200)]
xs = speaker_xs([0, 1], centres, crop_w=600, orig_w=1920,
n_frames=60, fps=30.0, window_s=1.0)
assert xs[0] < xs[-1]
def test_x_stays_inside_the_frame(self):
centres = [(10, 500, 200, 200), (1910, 500, 200, 200)]
xs = speaker_xs([0, 1], centres, crop_w=600, orig_w=1920,
n_frames=60, fps=30.0, window_s=1.0)
assert all(0 <= x <= 1920 - 600 for x in xs)
def test_one_value_per_frame(self):
centres = [(400, 500, 200, 200), (1500, 500, 200, 200)]
assert len(speaker_xs([0], centres, 600, 1920, 45, 30.0)) == 45
def test_empty_verdicts_do_not_crash(self):
centres = [(400, 500, 200, 200), (1500, 500, 200, 200)]
assert len(speaker_xs([], centres, 600, 1920, 10, 30.0)) == 10

View file

@ -0,0 +1,99 @@
import sys
import types
import layout_picker
from layout_picker import _module_flags, apply, pick
def fake_modules(monkeypatch, **initial):
"""Install stand-in layout modules so apply() can be tested without them."""
made = {}
for name in ("split_layout", "screencast_layout", "active_speaker"):
module = types.ModuleType(name)
module.ENABLED = initial.get(name, False)
monkeypatch.setitem(sys.modules, name, module)
made[name] = module
return made
class TestDecisionMapping:
def test_none_enables_nothing(self):
assert _module_flags("none") == []
def test_screencast_enables_its_module(self):
assert _module_flags("screencast") == ["screencast_layout"]
def test_split_also_needs_the_speaker_signal(self):
# Stacking without knowing who talks is the failure mode the corpus
# run showed: half a frame given to someone who never speaks.
assert "active_speaker" in _module_flags("split")
def test_unknown_and_empty_decisions_are_inert(self):
for value in ("gameplay", "", None, "SPLIT-SCREEN"):
assert _module_flags(value) == []
def test_decision_is_case_and_space_insensitive(self):
assert _module_flags(" SCREENCAST ") == ["screencast_layout"]
class TestApply:
def test_apply_switches_the_right_module_on(self, monkeypatch):
mods = fake_modules(monkeypatch)
touched = apply("screencast")
assert touched == ["screencast_layout"]
assert mods["screencast_layout"].ENABLED is True
assert mods["split_layout"].ENABLED is False
def test_apply_none_touches_nothing(self, monkeypatch):
mods = fake_modules(monkeypatch)
assert apply("none") == []
assert not any(m.ENABLED for m in mods.values())
def test_apply_never_disables_an_explicit_choice(self, monkeypatch):
# An operator who set SPLIT_LAYOUT=1 gets stacking even if the model
# says "none". The picker only ever adds.
mods = fake_modules(monkeypatch, split_layout=True)
apply("none")
assert mods["split_layout"].ENABLED is True
def test_already_enabled_modules_are_not_reported_as_touched(self, monkeypatch):
fake_modules(monkeypatch, screencast_layout=True)
assert apply("screencast") == []
def test_split_enables_both_modules(self, monkeypatch):
mods = fake_modules(monkeypatch)
assert set(apply("split")) == {"split_layout", "active_speaker"}
assert mods["split_layout"].ENABLED is True
assert mods["active_speaker"].ENABLED is True
class TestPick:
def test_disabled_picker_never_calls_out(self, monkeypatch):
monkeypatch.setattr(layout_picker, "ENABLED", False)
monkeypatch.setenv("GEMINI_API_KEY", "x")
assert pick("video.mp4", 60) == "none"
def test_missing_api_key_degrades_to_none(self, monkeypatch):
monkeypatch.setattr(layout_picker, "ENABLED", True)
monkeypatch.delenv("GEMINI_API_KEY", raising=False)
assert pick("video.mp4", 60) == "none"
def test_a_failed_call_degrades_to_none(self, monkeypatch):
# Import failure inside pick() stands in for any API error; the job
# must keep rendering with today's routing rather than die.
monkeypatch.setattr(layout_picker, "ENABLED", True)
monkeypatch.setenv("GEMINI_API_KEY", "x")
monkeypatch.setitem(sys.modules, "google.genai", None)
assert pick("video.mp4", 60) == "none"
class TestValidDecisions:
def test_every_valid_decision_maps_to_known_modules(self):
known = {"split_layout", "screencast_layout", "active_speaker"}
for decision in layout_picker.VALID:
assert set(_module_flags(decision)) <= known
def test_none_is_a_valid_decision(self):
# The model answers "none" for most videos; it must not be treated as
# an unrecognised value and logged as a warning on every job.
assert "none" in layout_picker.VALID

107
tests/test_punch_in.py Normal file
View file

@ -0,0 +1,107 @@
import punch_in
from punch_in import MAX_ZOOM, crop_boxes, sendcmd_lines, zoom_curve
class TestZoomCurve:
def test_no_beats_means_no_movement(self):
assert set(zoom_curve(90, 30.0, [])) == {1.0}
def test_a_beat_reaches_full_zoom_and_comes_back(self):
zooms = zoom_curve(150, 30.0, [1.0])
assert max(zooms) == MAX_ZOOM
assert zooms[0] == 1.0
assert zooms[-1] == 1.0
def test_the_push_is_faster_in_than_out(self):
zooms = zoom_curve(300, 30.0, [1.0])
peak = zooms.index(max(zooms))
release = next(i for i in range(peak, len(zooms)) if zooms[i] == 1.0)
rise = peak - int(1.0 * 30)
assert rise < (release - peak)
def test_overlapping_beats_do_not_compound(self):
zooms = zoom_curve(300, 30.0, [1.0, 1.2, 1.4])
assert max(zooms) == MAX_ZOOM
def test_beats_outside_the_scene_are_ignored(self):
assert set(zoom_curve(60, 30.0, [45.0])) == {1.0}
def test_start_offset_shifts_a_clip_level_beat_into_the_scene(self):
# Same beat, scene starting at 10s: only the offset version moves.
assert set(zoom_curve(60, 30.0, [10.5])) == {1.0}
assert max(zoom_curve(60, 30.0, [10.5], start_offset=10.0)) > 1.0
def test_zero_length_scene_is_safe(self):
assert zoom_curve(0, 30.0, [1.0]) == []
class TestCropBoxes:
def test_unzoomed_frames_keep_the_tracked_crop(self):
boxes = crop_boxes([100, 100], [1.0, 1.0], 600, 1080, 1920, 1080)
assert boxes[0][0] == 600 and boxes[0][1] == 1080
def test_zoom_shrinks_the_crop(self):
boxes = crop_boxes([100], [1.12], 600, 1080, 1920, 1080)
assert boxes[0][0] < 600 and boxes[0][1] < 1080
def test_the_centre_holds_while_zooming(self):
# A push must not read as a pan: same x in, same centre out.
wide = crop_boxes([600], [1.0], 600, 1080, 1920, 1080)[0]
tight = crop_boxes([600], [1.12], 600, 1080, 1920, 1080)[0]
assert abs((wide[2] + wide[0] / 2) - (tight[2] + tight[0] / 2)) <= 2
def test_boxes_stay_inside_the_frame(self):
for x in (0, 1320):
box = crop_boxes([x], [1.12], 600, 1080, 1920, 1080)[0]
assert 0 <= box[2] <= 1920 - box[0]
assert 0 <= box[3] <= 1080 - box[1]
def test_all_dimensions_are_even(self):
for z in (1.0, 1.03, 1.07, 1.12):
w, h, x, y = crop_boxes([333], [z], 601, 1079, 1920, 1080)[0]
assert w % 2 == 0 and h % 2 == 0 and x % 2 == 0 and y % 2 == 0
class TestSendcmdLines:
def test_first_frame_sets_every_parameter(self):
lines = sendcmd_lines([(600, 1080, 100, 0)], fps=30.0)
assert len(lines) == 4
assert {ln.split()[2] for ln in lines} == {"w", "h", "x", "y"}
def test_repeated_boxes_emit_nothing(self):
box = (600, 1080, 100, 0)
assert len(sendcmd_lines([box, box, box], fps=30.0)) == 4
def test_only_changed_parameters_are_re_emitted(self):
lines = sendcmd_lines([(600, 1080, 100, 0), (600, 1080, 104, 0)],
fps=30.0)
assert len(lines) == 5
assert lines[-1].endswith("x 104;")
def test_timestamps_are_scene_relative(self):
lines = sendcmd_lines([(600, 1080, 100, 0), (598, 1078, 101, 1)],
fps=30.0)
assert lines[0].startswith("0.0000")
assert lines[-1].startswith("0.0333")
class TestEmphasisTimes:
def test_silent_or_unreadable_audio_yields_no_beats(self, monkeypatch):
import active_speaker
monkeypatch.setattr(active_speaker, "audio_envelope",
lambda *a, **k: [])
assert punch_in.emphasis_times("x.mp4", 30.0) == []
def test_flat_audio_yields_no_beats(self, monkeypatch):
import active_speaker
monkeypatch.setattr(active_speaker, "audio_envelope",
lambda *a, **k: [0.5] * 50)
assert punch_in.emphasis_times("x.mp4", 10.0) == []
def test_beats_respect_the_minimum_gap(self, monkeypatch):
import active_speaker
envelope = [1.0 if i % 2 == 0 else 0.0 for i in range(100)]
monkeypatch.setattr(active_speaker, "audio_envelope",
lambda *a, **k: envelope)
times = punch_in.emphasis_times("x.mp4", 20.0, window=0.2, min_gap=4.0)
assert all(b - a >= 4.0 for a, b in zip(times, times[1:]))

View file

@ -0,0 +1,106 @@
import screencast_layout
from screencast_layout import (
content_bands,
overlapping_width,
screencast_filtergraph,
speaker_crop,
)
class TestContentBands:
def test_bands_fill_the_output_exactly(self):
content_h, speaker_h = content_bands(1920, 1080, 1080, 1920)
assert content_h + speaker_h == 1920
def test_sixteen_by_nine_content_keeps_its_full_width(self):
# 1080 wide at 16:9 is 608 tall. Anything else means the sides were cut,
# which is the one thing this layout exists to prevent.
content_h, _ = content_bands(1920, 1080, 1080, 1920)
assert content_h == 608
def test_bands_are_even(self):
for src_h in (1080, 1000, 817):
content_h, speaker_h = content_bands(1920, src_h, 1080, 1920)
assert content_h % 2 == 0 and speaker_h % 2 == 0
def test_tall_source_still_leaves_room_for_the_speaker(self):
# A portrait source would want more height than the frame has.
content_h, speaker_h = content_bands(1080, 1920, 1080, 1920)
assert speaker_h >= 2
assert content_h + speaker_h == 1920
class TestSpeakerCrop:
def test_crop_stays_inside_the_source(self):
w, h, x, y = speaker_crop(1920, 1080, 1080, 1312, (1748, 832))
assert 0 <= x <= 1920 - w
assert 0 <= y <= 1080 - h
def test_crop_is_even(self):
w, h, x, y = speaker_crop(1920, 1080, 1080, 1312, (777, 333))
assert w % 2 == 0 and h % 2 == 0 and x % 2 == 0 and y % 2 == 0
def test_crop_follows_the_face_horizontally(self):
_, _, left_x, _ = speaker_crop(1920, 1080, 1080, 1312, (400, 500))
_, _, right_x, _ = speaker_crop(1920, 1080, 1080, 1312, (1500, 500))
assert left_x < right_x
def test_corner_presenter_is_clamped_not_dropped(self):
w, _h, x, _y = speaker_crop(1920, 1080, 1080, 1312, (1900, 1000))
assert x == 1920 - w
class TestOverlappingWidth:
def test_no_ranges_means_no_width(self):
assert overlapping_width(0, 10, []) == 0.0
def test_returns_the_width_of_an_overlapping_range(self):
assert overlapping_width(5, 15, [(0, 20, "chart", 0.7)]) == 0.7
def test_ignores_ranges_that_do_not_overlap(self):
assert overlapping_width(30, 40, [(0, 20, "chart", 0.9)]) == 0.0
def test_a_brush_of_overlap_does_not_count(self):
# Under MIN_OVERLAP_SECONDS: a scene that merely touches the range.
assert overlapping_width(19.9, 30, [(0, 20, "chart", 0.9)]) == 0.0
def test_widest_overlapping_range_wins(self):
ranges = [(0, 20, "ticker", 0.15), (0, 20, "spreadsheet", 0.95)]
assert overlapping_width(5, 15, ranges) == 0.95
def test_corner_ticker_width_is_reported_not_swallowed(self):
# The gate lives in detect_content_ranges; this function must report
# small widths faithfully so that gate can do its job.
assert overlapping_width(5, 15, [(0, 20, "ticker", 0.15)]) == 0.15
class TestScreencastFiltergraph:
def test_content_band_is_scaled_never_cropped(self):
graph = screencast_filtergraph(1920, 1080, 1080, 1920, (1748, 832))
# [-1]: the first "[ca]" is the split= output label, not the filter.
content = graph.split("[ca]")[-1].split("[content]")[0]
assert "crop" not in content
assert "scale=1080:608" in content
def test_graph_stacks_and_pads_to_the_output(self):
graph = screencast_filtergraph(1920, 1080, 1080, 1920, (1748, 832))
assert "vstack=inputs=2" in graph
assert "pad=1080:1920" in graph
assert graph.endswith("[v]")
def test_speaker_band_is_cropped_around_the_face(self):
graph = screencast_filtergraph(1920, 1080, 1080, 1920, (1748, 832))
speaker = graph.split("[sa]")[-1].split("[speaker]")[0]
assert "crop=" in speaker
assert "scale=1080:1312" in speaker
class TestGating:
def test_disabled_module_detects_nothing(self, monkeypatch):
monkeypatch.setattr(screencast_layout, "ENABLED", False)
assert screencast_layout.detect_content_ranges("x.mp4", 10) == []
def test_no_ranges_means_no_scenes_touched(self, monkeypatch):
monkeypatch.setattr(screencast_layout, "ENABLED", True)
assert screencast_layout.detect_screencast_scenes(
"x.mp4", [], [], []) == {}

135
tests/test_split_layout.py Normal file
View file

@ -0,0 +1,135 @@
import split_layout
from split_layout import (
analyze_scene,
split_filtergraph,
split_geometry,
)
def face(cx, cy, w=200, h=200):
"""A detector candidate centred on (cx, cy), in the shape main.py returns."""
box = [int(cx - w / 2), int(cy - h / 2), w, h]
return {'box': box, 'score': w * h}
def two_shot(left_cx=600, right_cx=1400):
return [face(left_cx, 400), face(right_cx, 400)]
class TestAnalyzeScene:
def test_steady_two_shot_qualifies(self):
frames = [two_shot() for _ in range(10)]
left, right = analyze_scene(frames, frame_w=1920)
assert left[0] == 600
assert right[0] == 1400
def test_single_speaker_is_rejected(self):
frames = [[face(900, 400)] for _ in range(10)]
assert analyze_scene(frames, frame_w=1920) is None
def test_empty_input_is_rejected(self):
assert analyze_scene([], frame_w=1920) is None
def test_faces_sitting_too_close_are_rejected(self):
# 200px apart on a 1920 frame is 10%, under MIN_SEPARATION — one crop
# already frames both.
frames = [two_shot(left_cx=900, right_cx=1100) for _ in range(10)]
assert analyze_scene(frames, frame_w=1920) is None
def test_a_second_face_that_comes_and_goes_is_rejected(self):
frames = [two_shot() for _ in range(4)] + [[face(600, 400)]] * 6
assert analyze_scene(frames, frame_w=1920) is None
def test_occasional_detector_miss_still_qualifies(self):
frames = [two_shot() for _ in range(8)] + [[face(600, 400)]] * 2
assert analyze_scene(frames, frame_w=1920) is not None
def test_profile_turns_do_not_demote_a_real_two_shot(self):
# The measured case: 6 of 10 samples show both faces, the rest catch one
# speaker turned towards the other. Both are in frame throughout.
frames = [two_shot() for _ in range(6)] + [[face(600, 400)]] * 4
assert analyze_scene(frames, frame_w=1920) is not None
def test_shot_reverse_shot_is_rejected(self):
# Two cameras cutting between speakers: each face is on screen most of
# the time, never both at once. Stacking would duplicate one person.
frames = [[face(900, 400)], [face(1000, 400)]] * 5
assert analyze_scene(frames, frame_w=1920) is None
def test_background_extras_are_ignored(self):
# A tiny third face further right must not be picked over the speaker.
frames = [two_shot() + [face(1800, 200, w=40, h=40)] for _ in range(10)]
left, right = analyze_scene(frames, frame_w=1920)
assert (left[0], right[0]) == (600, 1400)
def test_one_stray_detection_does_not_drag_the_crop(self):
# Median, not mean: a single frame latching onto a bystander at x=1900
# would move a mean by ~130px.
frames = [two_shot() for _ in range(9)] + [[face(600, 400), face(1900, 400)]]
_left, right = analyze_scene(frames, frame_w=1920)
assert right[0] == 1400
def test_result_is_ordered_left_then_right(self):
frames = [[face(1400, 400), face(600, 400)] for _ in range(10)]
left, right = analyze_scene(frames, frame_w=1920)
assert left[0] < right[0]
class TestSplitGeometry:
def test_half_frame_crop_never_exceeds_the_source(self):
w, h, x, y, half_h = split_geometry(1920, 1080, 1080, 1920, (600, 400))
assert w <= 1920 and h <= 1080
assert 0 <= x <= 1920 - w
assert 0 <= y <= 1080 - h
assert half_h == 960
def test_crop_is_clamped_inside_the_frame_at_the_edges(self):
for cx in (0, 60, 1860, 1920):
w, _h, x, _y, _half = split_geometry(1920, 1080, 1080, 1920, (cx, 400))
assert 0 <= x <= 1920 - w
def test_dimensions_are_even(self):
w, h, x, y, half_h = split_geometry(1920, 1080, 1080, 1920, (777, 333))
assert w % 2 == 0 and h % 2 == 0
assert x % 2 == 0 and y % 2 == 0 and half_h % 2 == 0
def test_crop_aspect_matches_the_half_frame(self):
w, h, _x, _y, half_h = split_geometry(1920, 1080, 1080, 1920, (900, 400))
assert abs((w / h) - (1080 / half_h)) < 0.02
def test_tightness_trades_width_for_a_closer_frame(self, monkeypatch):
monkeypatch.setattr(split_layout, "SPLIT_TIGHTNESS", 1.0)
wide, _, _, _, _ = split_geometry(1920, 1080, 1080, 1920, (900, 400))
monkeypatch.setattr(split_layout, "SPLIT_TIGHTNESS", 0.75)
tight, _, _, _, _ = split_geometry(1920, 1080, 1080, 1920, (900, 400))
assert tight < wide
def test_tightness_is_bounded(self, monkeypatch):
# An out-of-range env value must not produce a zero-sized crop.
monkeypatch.setattr(split_layout, "SPLIT_TIGHTNESS", 0.0)
w, h, _x, _y, _half = split_geometry(1920, 1080, 1080, 1920, (900, 400))
assert w > 0 and h > 0
def test_portrait_source_falls_back_to_full_width(self):
w, _h, x, _y, _half = split_geometry(1080, 1920, 1080, 1920, (540, 600))
assert w == 1080 and x == 0
class TestSplitFiltergraph:
def test_graph_stacks_two_crops_into_the_output_size(self):
graph = split_filtergraph(1920, 1080, 1080, 1920, (600, 400), (1400, 400))
assert "vstack=inputs=2" in graph
assert "pad=1080:1920" in graph
assert graph.endswith("[v]")
def test_left_speaker_goes_on_top(self):
graph = split_filtergraph(1920, 1080, 1080, 1920, (600, 400), (1400, 400))
top = graph.split("[ta]crop=")[1].split(",")[0]
bottom = graph.split("[ba]crop=")[1].split(",")[0]
top_x = int(top.split("x=")[1].split(":")[0])
bottom_x = int(bottom.split("x=")[1].split(":")[0])
assert top_x < bottom_x
def test_both_halves_scale_to_the_same_size(self):
graph = split_filtergraph(1920, 1080, 1080, 1920, (600, 400), (1400, 400))
assert graph.count("scale=1080:960") == 2