Skip to content

video

Class info

🛈 DocStrings

Video and animated-image inputs: exact seeks, dense samples, pacing checks.

Seek exact media times in Chromium, sample densely, check pacing (static stretches, black/blank frames, cuts, mark overlaps), compose the sheet with marks and a timeline. Ported 1:1 in js/src/video.ts.

CUT_NEIGHBOUR module-attribute

CUT_NEIGHBOUR = 0.25

... while both neighbouring steps change at most a quarter of that is an abrupt cut.

CUT_RATIO module-attribute

CUT_RATIO = 0.4

A step changing at least 40% of pixels ...

SAMPLE_STEP module-attribute

SAMPLE_STEP = 0.25

Dense samples are at most this far apart (seconds), up to MAX_SAMPLES.

STATIC_RATIO module-attribute

STATIC_RATIO = 0.0005

A sample step changing fewer than 0.05% of pixels counts as "no visible change".

UNIFORM_SHARE module-attribute

UNIFORM_SHARE = 0.995

A frame is black/blank if this share of pixels has one colour (4 bits per channel).

abrupt_cuts

abrupt_cuts(samples: Sequence[ActivitySample]) -> list[float]

Sample times where one step changes >= CUT_RATIO and its neighbours little.

Source code in src/framesheet/video.py
def abrupt_cuts(samples: Sequence[ActivitySample]) -> list[float]:
    """Sample times where one step changes >= CUT_RATIO and its neighbours little."""
    out = []
    n = len(samples)
    for k in range(1, n):
        r = samples[k].changed_ratio
        prev = samples[k - 1].changed_ratio if k >= 2 else 0.0  # noqa: PLR2004
        nxt = samples[k + 1].changed_ratio if k + 1 < n else 0.0
        if r >= CUT_RATIO and prev <= r * CUT_NEIGHBOUR and nxt <= r * CUT_NEIGHBOUR:
            out.append(samples[k].t)
    return out

dense_times

dense_times(start: float, end: float, heat_frames: int) -> list[float]

Evenly spaced pacing samples over [start, end] (both ends included).

Source code in src/framesheet/video.py
def dense_times(start: float, end: float, heat_frames: int) -> list[float]:
    """Evenly spaced pacing samples over ``[start, end]`` (both ends included)."""
    if heat_frames <= 0:
        return []
    count = min(MAX_SAMPLES, max(heat_frames, math.ceil((end - start) / SAMPLE_STEP)))
    return [round(start + (end - start) * k / count, 4) for k in range(count + 1)]

frame_stats

frame_stats(image: Image) -> tuple[bool, bool]

(black, blank): one colour (4 bits/channel) covers >= 99.5% of the pixels.

Source code in src/framesheet/video.py
def frame_stats(image: Image.Image) -> tuple[bool, bool]:
    """``(black, blank)``: one colour (4 bits/channel) covers >= 99.5% of the pixels."""
    quantized = image.point(lambda v: v >> 4)
    colors = quantized.getcolors(4096) or []
    count, rgb = max(colors)
    uniform = count / (image.width * image.height) >= UNIFORM_SHARE
    black = uniform and isinstance(rgb, tuple) and max(rgb) <= 1
    return black, uniform and not black

mark_overlaps

mark_overlaps(marks: Marks, start: float, end: float) -> list[Finding]

Span boxes (captions) covering target region boxes while both are active.

Source code in src/framesheet/video.py
def mark_overlaps(marks: Marks, start: float, end: float) -> list[Finding]:
    """Span boxes (captions) covering ``target`` region boxes while both are active."""
    out = []
    for s in marks.spans:
        for r in marks.regions:
            if s.box is None or r.box is None or r.kind != "target":
                continue
            a, b = max(s.start, r.start, start), min(s.end, r.end, end)
            if a > b:
                continue
            sx, sy = marks.norm(s.box[0], s.box[1])
            sx2, sy2 = marks.norm(s.box[0] + s.box[2], s.box[1] + s.box[3])
            rx, ry = marks.norm(r.box[0], r.box[1])
            rx2, ry2 = marks.norm(r.box[0] + r.box[2], r.box[1] + r.box[3])
            iw, ih = min(sx2, rx2) - max(sx, rx), min(sy2, ry2) - max(sy, ry)
            if iw <= 0 or ih <= 0:
                continue
            share = iw * ih / ((rx2 - rx) * (ry2 - ry))
            out.append(
                Finding(
                    severity="warning",
                    code="video-mark-overlap",
                    message=f'Span "{s.label}" covers target "{r.label or "target"}" for '
                    f"t={a:.2f}-{b:.2f}s ({share:.0%} of the target box).",
                    check="render",
                    times=[round(a, 4), round(b, 4)],
                )
            )
    return out

plan_times

plan_times(
    total: float,
    *,
    start: float | None = None,
    end: float | None = None,
    frames: int = 12,
    every: float | None = None,
    times: Sequence[float] | Literal["marks"] | None = None,
    marks: Marks | None = None,
) -> tuple[float, float, list[float], str]

Range and tile times: (start, end, times, mode).

Source code in src/framesheet/video.py
def plan_times(
    total: float,
    *,
    start: float | None = None,
    end: float | None = None,
    frames: int = 12,
    every: float | None = None,
    times: Sequence[float] | Literal["marks"] | None = None,
    marks: Marks | None = None,
) -> tuple[float, float, list[float], str]:
    """Range and tile times: ``(start, end, times, mode)``."""
    a = 0.0 if start is None else float(start)
    b = total if end is None else float(end)
    if a < 0 or b <= a or b > total + 1e-6:
        msg = f"Invalid range {a:g}-{b:g}s (the media is {total:g}s long)"
        raise ValueError(msg)
    b = min(b, total)
    if times == "marks":
        if marks is None:
            msg = "times='marks' needs marks"
            raise ValueError(msg)
        ts = [p.t for p in marks.points]
        ts += [(r.start + r.end) / 2 for r in marks.regions]
        ts += [(s.start + s.end) / 2 for s in marks.spans]
        ts = [t for t in ts if a <= t <= b]
        if not ts:
            msg = "No mark falls inside the inspected range"
            raise ValueError(msg)
        mode = "times from marks"
    elif times is not None:
        ts = [float(t) for t in times]
        if not ts:
            msg = "times must not be empty"
            raise ValueError(msg)
        if bad := [t for t in ts if not a <= t <= b]:
            msg = f"Times outside the range {a:g}-{b:g}s: {', '.join(f'{t:g}' for t in bad)}"
            raise ValueError(msg)
        mode = "--times"
    elif every is not None:
        if every <= 0:
            msg = "every must be positive"
            raise ValueError(msg)
        n = math.floor((b - a) / every + 1e-9) + 1
        if n > MAX_TILES:
            msg = f"every={every:g}s gives {n} tiles (max {MAX_TILES})"
            raise ValueError(msg)
        ts = [a + k * every for k in range(n)]
        if b - ts[-1] > 1e-6:  # noqa: PLR2004
            ts.append(b)
        mode = f"every {every:g}s"
    else:
        if not 2 <= frames <= MAX_TILES:  # noqa: PLR2004
            msg = "frames must be between 2 and 100"
            raise ValueError(msg)
        ts = [a + (b - a) * i / (frames - 1) for i in range(frames)]
        ts[-1] = b
        mode = "evenly spaced"
    out = sorted({round(t, 4) for t in ts})
    if len(out) > MAX_TILES:
        msg = f"{len(out)} tiles (max {MAX_TILES})"
        raise ValueError(msg)
    return a, b, out, mode

sharpness

sharpness(image: Image) -> float

Mean absolute luma gradient (|dx| + |dy| per pixel, 0-510).

Source code in src/framesheet/video.py
def sharpness(image: Image.Image) -> float:
    """Mean absolute luma gradient (``|dx| + |dy|`` per pixel, 0-510)."""
    luma = image.convert("L")
    w, h = luma.size
    total = 0
    if w > 1:
        dx = ImageChops.difference(luma.crop((1, 0, w, h)), luma.crop((0, 0, w - 1, h)))
        total += sum(i * c for i, c in enumerate(dx.histogram()))
    if h > 1:
        dy = ImageChops.difference(luma.crop((0, 1, w, h)), luma.crop((0, 0, w, h - 1)))
        total += sum(i * c for i, c in enumerate(dy.histogram()))
    return round(total / (w * h), 3)

static_stretches

static_stretches(samples: Sequence[ActivitySample], threshold: float) -> list[tuple[float, float]]

Maximal runs of sample steps without visible change lasting > threshold s.

Source code in src/framesheet/video.py
def static_stretches(
    samples: Sequence[ActivitySample], threshold: float
) -> list[tuple[float, float]]:
    """Maximal runs of sample steps without visible change lasting > ``threshold`` s."""
    out = []
    run_start: int | None = None
    for k in range(1, len(samples) + 1):
        still = k < len(samples) and samples[k].changed_ratio < STATIC_RATIO
        if still and run_start is None:
            run_start = k - 1
        elif not still and run_start is not None:
            a, b = samples[run_start].t, samples[k - 1].t
            if b - a > threshold:
                out.append((a, b))
            run_start = None
    return out

video_findings

video_findings(
    samples: Sequence[ActivitySample],
    stats: dict[float, tuple[bool, bool]],
    threshold: float,
    marks: Marks | None,
    start: float,
    end: float,
) -> tuple[list[Finding], list[dict[str, Any]]]

Findings plus timeline issues ({"kind", "start", "end"}).

Source code in src/framesheet/video.py
def video_findings(
    samples: Sequence[ActivitySample],
    stats: dict[float, tuple[bool, bool]],
    threshold: float,
    marks: Marks | None,
    start: float,
    end: float,
) -> tuple[list[Finding], list[dict[str, Any]]]:
    """Findings plus timeline issues (``{"kind", "start", "end"}``)."""
    findings: list[Finding] = []
    issues: list[dict[str, Any]] = []
    for a, b in static_stretches(samples, threshold):
        findings.append(
            Finding(
                severity="warning",
                code="video-static-stretch",
                message=f"No visible change for {b - a:.2f}s (t={a:.2f}-{b:.2f}s; under "
                f"{STATIC_RATIO:.2%} of pixels per sample): dead time?",
                check="render",
                times=[a, b],
            )
        )
        issues.append({"kind": "static", "start": a, "end": b})
    times = [s.t for s in samples]
    for kind, index, what in (("black", 0, "black"), ("blank", 1, "one flat colour (blank)")):
        flags = {t: stats[t][index] for t in times}
        hits = [t for t in times if flags[t]]
        if not hits:
            continue
        findings.append(
            Finding(
                severity="warning",
                code=f"video-{kind}-frames",
                message=f"{len(hits)} sampled frame(s) are {what}: t={_listed(hits)}.",
                check="render",
                times=hits,
            )
        )
        issues += [{"kind": kind, "start": a, "end": b} for a, b in _runs(times, flags)]
    if cuts := abrupt_cuts(samples):
        findings.append(
            Finding(
                severity="info",
                code="video-abrupt-cut",
                message=f"Abrupt change (>= {CUT_RATIO:.0%} of pixels in one sample step, "
                f"quiet neighbours) at t={_listed(cuts)}: a hard cut or a jump.",
                check="render",
                times=cuts,
            )
        )
        issues += [{"kind": "cut", "start": t, "end": t} for t in cuts]
    if marks is not None:
        findings += mark_overlaps(marks, start, end)
    issues.sort(key=lambda i: (i["start"], i["kind"]))
    return findings, issues