Video2Guide / app /pipeline /image_input.py
Claude
Claude Opus 4.8
Add AI slide-to-transcript alignment for untimestamped images
e646192
Raw History Blame Contribute Delete
10.7 kB
"""Build a scene-frame list from pre-exported slide images instead of
detecting scenes in a video.
This is the "images + transcript" input mode: the user uploads a handful
of still frames (typically PNG exports pulled from a lecture video at each
slide change), each named with an ``HH-MM-SS`` timestamp, plus one SRT/VTT
that covers them all. Each image becomes one segment of the study guide,
anchored at its timestamp; the transcript is aligned to those anchors by
the same downstream code the video path uses.
Compared with scene detection this is deterministic (no seeking, no merge
threshold), needs no video upload, and gives the author exact control over
which slides appear. The parser is deliberately strict: a filename we
can't read a plausible timestamp from is an error, never a silently
misplaced slide.
"""
from __future__ import annotations
import re
from dataclasses import dataclass
from pathlib import Path
from .types import SceneFrame
class ImageInputError(ValueError):
"""Raised when the uploaded images can't be turned into a valid,
ordered set of timestamped segments. The HTTP layer surfaces the
message to the user (400)."""
# A time is HH-MM-SS where the two separators are the SAME delimiter
# (one of ':', '.', '-', '_'). The backreference (\2) matters: without it
# a date-then-time name like "2024-01-15_00-05-30.png" would let the
# date's fields fuse with the time's ("01-15_00" β†’ 01:15:00) and swallow
# the real time. Requiring a consistent delimiter means "01-15_00" (mixed
# '-' then '_') can't match, so only the true "00-05-30" does.
#
# The whole thing is inside a zero-width lookahead so finditer yields
# OVERLAPPING candidates β€” e.g. "frame-12-00-05-30" offers both
# "12-00-05" and "00-05-30", and the in-range filter keeps the right one.
# (?<!\d) / (?!\d) keep us from slicing a fragment out of a longer digit
# run (a resolution, a year).
_TIME_RE = re.compile(
r"(?<!\d)(?=(\d{1,2})([:._-])(\d{2})\2(\d{2})(?!\d))"
)
@dataclass
class ParsedImage:
timestamp: float
path: Path
original_name: str
def _candidate_seconds(filename: str) -> list[tuple[int, float]]:
"""Every HH-MM-SS-shaped timestamp in the filename as (position, seconds).
A name may carry other metadata (a date, a counter, a resolution), so
there can be more than one candidate, at different positions, and they
may overlap. Callers disambiguate using position (the time is
conventionally the trailing field) and the transcript's duration (a
real slide timestamp must fall inside it).
"""
out: list[tuple[int, float]] = []
for m in _TIME_RE.finditer(filename):
h, _delim, mm_s, ss_s = m.group(1), m.group(2), m.group(3), m.group(4)
mm, ss = int(mm_s), int(ss_s)
# Reject impossible clock fields (e.g. minutes/seconds β‰₯ 60).
if mm >= 60 or ss >= 60:
continue
out.append((m.start(), int(h) * 3600 + mm * 60 + ss))
return out
def parse_timestamp_from_name(
filename: str, *, max_seconds: float | None = None
) -> float:
"""Extract the slide's timestamp (seconds) from its filename.
Prefers the LAST plausible ``HH-MM-SS`` in the name β€” exports usually
append the time after any prefix/date. When ``max_seconds`` (the
transcript's duration) is given, only candidates within
``[0, max_seconds]`` are considered valid, which rules out a date or
counter fragment being mistaken for a time. Raises ImageInputError
when nothing usable is found.
"""
candidates = _candidate_seconds(filename)
if not candidates:
raise ImageInputError(
f"Couldn't read an HH-MM-SS timestamp from the filename "
f"'{filename}'. Name each image with its time, e.g. "
f"'00-05-30.png'."
)
if max_seconds is not None:
in_range = [(pos, sec) for pos, sec in candidates if 0 <= sec <= max_seconds]
if not in_range:
raise ImageInputError(
f"The timestamp read from '{filename}' falls outside the "
f"transcript's range (0–{int(max_seconds)}s). Check the "
f"filename's time."
)
# Latest-positioned in-range match β€” the time is conventionally the
# trailing field, after any date/counter prefix.
return max(in_range, key=lambda pc: pc[0])[1]
return max(candidates, key=lambda pc: pc[0])[1]
def build_frames_from_images(
images: list[Path],
*,
transcript_end: float | None = None,
) -> list[SceneFrame]:
"""Turn timestamp-named images into an ordered SceneFrame list.
``transcript_end`` is the last cue's end (seconds); when given it bounds
timestamp parsing and becomes the end of the final segment. It is
optional β€” with no transcript there's no known timeline end, so parsing
runs without the range guard and the last slide simply runs to its own
timestamp. Each image anchors a segment that runs to the next image's
timestamp. Raises ImageInputError on an empty set, an unparseable name,
a duplicate timestamp, or (when a transcript bound is given) a timestamp
past the transcript.
"""
if not images:
raise ImageInputError("No images were provided.")
parsed: list[ParsedImage] = []
for path in images:
ts = parse_timestamp_from_name(path.name, max_seconds=transcript_end)
parsed.append(ParsedImage(timestamp=ts, path=path, original_name=path.name))
parsed.sort(key=lambda p: p.timestamp)
# Reject duplicate timestamps rather than silently ordering them β€”
# two slides at the same second is almost certainly a naming mistake.
for a, b in zip(parsed, parsed[1:]):
if a.timestamp == b.timestamp:
raise ImageInputError(
f"Two images share the timestamp {int(a.timestamp)}s "
f"('{a.original_name}' and '{b.original_name}'). Each slide "
f"needs a distinct time."
)
# Without a transcript the final segment has no known end; run it to its
# own start (the meta-time then shows just that timestamp).
tail = transcript_end if transcript_end is not None else parsed[-1].timestamp
frames: list[SceneFrame] = []
n = len(parsed)
for i, p in enumerate(parsed):
end = parsed[i + 1].timestamp if i + 1 < n else tail
# A slide placed at/after the tail can't form a positive window;
# clamp its end so the segment is at least non-degenerate.
if end <= p.timestamp:
end = p.timestamp
frames.append(
SceneFrame(
index=i,
start_seconds=float(p.timestamp),
end_seconds=float(end),
image_path=p.path,
)
)
return frames
def all_have_timestamps(images: list[Path], max_seconds: float | None = None) -> bool:
"""True when every image filename yields a parseable (in-range) timestamp.
Used to decide between the time-based path and the align/even-split path
when a transcript is present."""
for p in images:
try:
parse_timestamp_from_name(p.name, max_seconds=max_seconds)
except ImageInputError:
return False
return True
def _natural_key(name: str):
"""Sort key so 'slide2' precedes 'slide10' (numeric runs compare as
numbers, not lexically)."""
return [
int(part) if part.isdigit() else part.lower()
for part in re.split(r"(\d+)", name)
]
def order_by_name(images: list[Path]) -> list[Path]:
"""Images sorted by natural filename order (slide2 before slide10)."""
return sorted(images, key=lambda p: _natural_key(p.name))
def build_frames_from_starts(
images_in_order: list[Path],
starts: list[float],
*,
transcript_end: float,
) -> list[SceneFrame]:
"""Build timed frames from an explicit per-slide start-time list (parallel
to ``images_in_order``). Each slide runs to the next slide's start; the
last runs to ``transcript_end``. Starts are clamped to be non-decreasing
and within [0, transcript_end] so a stray value can't invert a window."""
if not images_in_order:
raise ImageInputError("No images were provided.")
if len(starts) != len(images_in_order):
raise ImageInputError("Slide-start count does not match the number of images.")
# Clamp: non-decreasing, within range.
clean: list[float] = []
prev = 0.0
for s in starts:
v = max(0.0, min(float(s), transcript_end))
v = max(v, prev)
clean.append(v)
prev = v
frames: list[SceneFrame] = []
n = len(images_in_order)
for i, path in enumerate(images_in_order):
end = clean[i + 1] if i + 1 < n else transcript_end
if end <= clean[i]:
end = clean[i]
frames.append(
SceneFrame(
index=i,
start_seconds=float(clean[i]),
end_seconds=float(end),
image_path=path,
)
)
return frames
def build_frames_even_split(
images: list[Path],
*,
transcript_start: float,
transcript_end: float,
) -> list[SceneFrame]:
"""Order images by filename and spread them evenly across the transcript's
timespan β€” the no-AI fallback when slides lack timestamps. Approximate
(assumes even pacing); the editor lets the author move narration."""
ordered = order_by_name(images)
if not ordered:
raise ImageInputError("No images were provided.")
n = len(ordered)
span = max(transcript_end - transcript_start, 0.0)
starts = [transcript_start + span * i / n for i in range(n)]
return build_frames_from_starts(ordered, starts, transcript_end=transcript_end)
def build_frames_ordered_by_name(images: list[Path]) -> list[SceneFrame]:
"""Turn images into a SceneFrame list ordered by filename, with no
timestamp parsing β€” for the no-transcript case where slides just need
an order, not a time. Filenames need no ``HH-MM-SS``.
Positions are synthetic (one per slide) purely to preserve order; the
frames are marked so the guide suppresses the misleading time labels.
Raises ImageInputError on an empty set.
"""
if not images:
raise ImageInputError("No images were provided.")
ordered = sorted(images, key=lambda p: _natural_key(p.name))
frames: list[SceneFrame] = []
for i, path in enumerate(ordered):
frames.append(
SceneFrame(
index=i,
start_seconds=float(i),
end_seconds=float(i + 1),
image_path=path,
)
)
return frames