feat(clips): word-aligned punch-ins + hook-first boundaries
This commit is contained in:
parent
196628e812
commit
14de254ab6
4 changed files with 521 additions and 26 deletions
|
|
@ -14,11 +14,14 @@ 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.
|
||||
Beat times come from the audio envelope, aligned to the clip-relative word
|
||||
onsets the transcript provides (``emphasis_times(word_times=...)``). The
|
||||
envelope finds the emphasis; the word onset says exactly when it started, so
|
||||
each peak snaps to the nearest word instead of sitting on the loudest
|
||||
syllable. A clip with no envelope beats falls back to the word onsets alone,
|
||||
and without ``word_times`` the beat derivation is exactly what it always was.
|
||||
"""
|
||||
import bisect
|
||||
import os
|
||||
|
||||
import numpy as np
|
||||
|
|
@ -59,6 +62,11 @@ BEAT_WINDOW = 0.2
|
|||
MIN_GAP_SECONDS = 18.0
|
||||
BEAT_PROMINENCE = 0.60
|
||||
|
||||
# How far an envelope peak may move to land on a word onset. The envelope frame
|
||||
# is coarse (BEAT_WINDOW); the word's start is exact, so the tolerance is a bit
|
||||
# wider than the frame rather than equal to it.
|
||||
WORD_SNAP_SECONDS = 0.5
|
||||
|
||||
|
||||
def _ease(t):
|
||||
"""Smoothstep on [0, 1]. Linear ramps look mechanical at this duration."""
|
||||
|
|
@ -155,32 +163,72 @@ def sendcmd_lines(boxes, fps, target="crop@c"):
|
|||
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.
|
||||
def _snap_to_word(t, words, snap):
|
||||
"""``t`` moved to the closest onset in the sorted ``words``, if within
|
||||
``snap``. Without a word in range the envelope beat is left where it is."""
|
||||
i = bisect.bisect_left(words, t)
|
||||
best, best_d = t, snap
|
||||
for j in (i - 1, i):
|
||||
if 0 <= j < len(words):
|
||||
d = abs(words[j] - t)
|
||||
if d <= best_d:
|
||||
best, best_d = words[j], d
|
||||
return best
|
||||
|
||||
A stand-in for the hook words until the transcript is wired through. Returns
|
||||
[] for silent or unreadable audio, which simply means no punches.
|
||||
|
||||
def merge_beats(audio_beats, word_times, min_gap=MIN_GAP_SECONDS,
|
||||
snap=WORD_SNAP_SECONDS):
|
||||
"""Punch beats: envelope emphasis, snapped onto the words that carry it.
|
||||
|
||||
The envelope finds where the energy jumped; a word onset is the precise
|
||||
instant to push. Each envelope beat is snapped to the nearest word onset
|
||||
within ``snap`` seconds, which is what turns "the loudest syllable" into
|
||||
"the word that was loud". With no envelope beats at all — silent or flat
|
||||
audio — the word onsets themselves become the beats. The result is thinned
|
||||
to ``min_gap`` so two pushes never overlap. Pure: no audio, no I/O, which
|
||||
is what makes the beat timing testable without a clip.
|
||||
"""
|
||||
words = sorted(word_times or [])
|
||||
if audio_beats:
|
||||
candidates = [_snap_to_word(b, words, snap) if words else b
|
||||
for b in audio_beats]
|
||||
else:
|
||||
candidates = list(words)
|
||||
|
||||
times = []
|
||||
last = -1e9
|
||||
for t in sorted(candidates):
|
||||
if t - last >= min_gap:
|
||||
times.append(round(t, 3))
|
||||
last = t
|
||||
return times
|
||||
|
||||
|
||||
def emphasis_times(video_path, duration, window=BEAT_WINDOW,
|
||||
min_gap=MIN_GAP_SECONDS, prominence=BEAT_PROMINENCE,
|
||||
word_times=None):
|
||||
"""Seconds where the clip should punch in.
|
||||
|
||||
Audio envelope peaks, merged with ``word_times`` — optional clip-relative
|
||||
word onsets in seconds (clip start = 0), as produced from the transcript.
|
||||
Returns [] for silent, word-less input, which simply means no punches.
|
||||
"""
|
||||
from clipwright.layouts import active_speaker
|
||||
|
||||
envelope = active_speaker.audio_envelope(video_path, 0.0, duration,
|
||||
window_s=window)
|
||||
if not envelope:
|
||||
return []
|
||||
audio_beats = []
|
||||
if envelope:
|
||||
values = np.asarray(envelope, dtype=float)
|
||||
baseline = float(np.median(values))
|
||||
peak = float(values.max())
|
||||
if peak - baseline > 1e-6:
|
||||
threshold = baseline + (peak - baseline) * prominence
|
||||
last = -1e9
|
||||
for i, v in enumerate(values):
|
||||
t = i * window
|
||||
if v >= threshold and t - last >= min_gap:
|
||||
audio_beats.append(t)
|
||||
last = t
|
||||
|
||||
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
|
||||
return merge_beats(audio_beats, word_times, min_gap=min_gap)
|
||||
|
|
|
|||
|
|
@ -5,6 +5,8 @@ Standard-library only so both main.py and gemini_worker.py can import it and
|
|||
the logic stays unit-testable without the heavy video dependencies.
|
||||
"""
|
||||
|
||||
import re
|
||||
|
||||
# USD per 1M tokens (input, output incl. thinking), from ai.google.dev pricing.
|
||||
MODEL_PRICES = {
|
||||
"gemini-3.5-flash": (1.50, 9.00),
|
||||
|
|
@ -348,3 +350,185 @@ def snap_clip_to_words(start, end, words, video_duration,
|
|||
if new_end <= new_start or new_end - new_start < min_duration:
|
||||
return original
|
||||
return (round(new_start, 3), round(new_end, 3))
|
||||
|
||||
|
||||
# --- Hook-first boundaries (#2a) -------------------------------------------
|
||||
# The first seconds decide the swipe. A model-proposed clip routinely opens on
|
||||
# wind-up ("so today we're going to...") and buries the question, the number or
|
||||
# the stakes 3-8s in. Word timestamps are ground truth, so the start can be
|
||||
# moved onto the first strong spoken hook deterministically — no LLM, no key.
|
||||
#
|
||||
# These are the signal vocabularies the scan combines. A token matching ANY set
|
||||
# is a hook; the EARLIEST such token inside the allowed trim window wins. They
|
||||
# are deliberately conservative: a miss leaves the clip untouched, a false
|
||||
# positive only advances the start a bounded amount (see the env caps).
|
||||
_HOOK_INTERROGATIVES = frozenset({
|
||||
"what", "why", "how", "when", "where", "who", "whom", "whose", "which",
|
||||
"is", "are", "was", "were", "do", "does", "did", "can", "could", "would",
|
||||
"should", "will", "shall",
|
||||
})
|
||||
_HOOK_IMPERATIVES = frozenset({
|
||||
"look", "watch", "imagine", "think", "stop", "try", "check", "see",
|
||||
"listen", "remember", "forget", "consider", "notice", "suppose", "picture",
|
||||
"keep", "take", "put", "go", "come", "use", "make", "let", "dont", "show",
|
||||
"tell", "explain", "build", "create", "write", "read", "open", "close",
|
||||
"click", "press", "type", "install", "run", "fix", "never", "always",
|
||||
})
|
||||
_HOOK_NUMBERS = frozenset({
|
||||
"zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
|
||||
"nine", "ten", "eleven", "twelve", "hundred", "thousand", "million",
|
||||
"billion", "half", "quarter", "twice", "once", "double", "triple",
|
||||
"dozen", "percent", "first", "second", "third",
|
||||
})
|
||||
_HOOK_CONTRAST = frozenset({
|
||||
"but", "until", "actually", "instead", "except", "however", "though",
|
||||
"although", "whereas", "yet", "still", "suddenly", "wait", "unless",
|
||||
"otherwise", "despite", "nevertheless", "contrary", "opposite", "reverse",
|
||||
})
|
||||
_HOOK_STAKES = frozenset({
|
||||
"never", "always", "first", "worst", "bug", "bugs", "crash", "crashes",
|
||||
"crashed", "crashing", "broke", "broken", "break", "wrong", "lost", "lose",
|
||||
"losing", "fail", "failed", "fails", "failure", "dies", "death", "dead",
|
||||
"kill", "killed", "destroy", "destroyed", "ruin", "ruined", "disaster",
|
||||
"mistake", "error", "errors", "segfault", "danger", "dangerous", "scared",
|
||||
"terrified", "panic", "emergency", "critical", "fatal", "illegal",
|
||||
"corrupt", "corrupted", "hacked", "stolen", "missing", "gone", "worse",
|
||||
})
|
||||
# Pure hesitation / connective words that are never hooks. The scan simply
|
||||
# walks past them, so they end up in the trimmed wind-up; they must not count.
|
||||
_HOOK_FILLER = frozenset({
|
||||
"uh", "um", "erm", "ah", "eh", "hmm", "mmm", "so", "well", "okay", "ok",
|
||||
"yeah", "yep", "right", "and", "then", "like", "basically", "just",
|
||||
"you", "know", "i", "mean", "we", "the", "a", "an", "it", "that", "this",
|
||||
})
|
||||
|
||||
# Conservative defaults: HOOK_FIRST is on, but a start only ever moves a few
|
||||
# seconds and never more than a quarter of the clip.
|
||||
_HOOK_FIRST_DEFAULT_MAX_TRIM = 4.0
|
||||
_HOOK_FIRST_DEFAULT_MAX_FRACTION = 0.25
|
||||
# A trim smaller than this is noise; leaving the clip alone is kinder than a
|
||||
# sub-frame jitter that only complicates the render.
|
||||
_MIN_HOOK_TRIM = 0.2
|
||||
|
||||
|
||||
def _env_float(name, default):
|
||||
"""Read a float env var, falling back to ``default`` on garbage/absence."""
|
||||
import os
|
||||
|
||||
raw = os.environ.get(name)
|
||||
if raw is None or str(raw).strip() == "":
|
||||
return default
|
||||
try:
|
||||
return float(raw)
|
||||
except (TypeError, ValueError):
|
||||
return default
|
||||
|
||||
|
||||
def hook_first_enabled():
|
||||
"""Whether to move clip starts onto the first spoken hook.
|
||||
|
||||
``HOOK_FIRST`` defaults ON (conservatively capped); set it to ``0`` /
|
||||
``false`` / ``no`` / ``off`` to disable the pass for A/B runs.
|
||||
"""
|
||||
import os
|
||||
|
||||
raw = os.environ.get("HOOK_FIRST")
|
||||
if raw is None:
|
||||
return True
|
||||
return str(raw).strip().lower() not in ("", "0", "false", "no", "off")
|
||||
|
||||
|
||||
def _hook_token(raw):
|
||||
"""Normalise a Whisper word to a bare lowercase token.
|
||||
|
||||
Words are inconsistent about a leading space (" word" vs "word") and carry
|
||||
trailing punctuation ("crash!"), so both are stripped before matching.
|
||||
"""
|
||||
token = str(raw or "").strip().lower()
|
||||
token = re.sub(r"^[^0-9a-z]+", "", token)
|
||||
token = re.sub(r"[^0-9a-z]+$", "", token)
|
||||
return token
|
||||
|
||||
|
||||
def _is_hook_token(token):
|
||||
"""True when a normalised token carries one of the hook signals."""
|
||||
if not token or token in _HOOK_FILLER:
|
||||
return False
|
||||
if any(ch.isdigit() for ch in token):
|
||||
return True
|
||||
return (token in _HOOK_INTERROGATIVES
|
||||
or token in _HOOK_IMPERATIVES
|
||||
or token in _HOOK_NUMBERS
|
||||
or token in _HOOK_CONTRAST
|
||||
or token in _HOOK_STAKES)
|
||||
|
||||
|
||||
def find_hook_start(words, clip_start, clip_end, min_duration=15.0,
|
||||
max_trim=None, max_fraction=None):
|
||||
"""The strongest deterministic start for a clip, or ``None``.
|
||||
|
||||
Scans the opening of ``[clip_start, clip_end]`` for the EARLIEST word that
|
||||
matches a hook signal (question, imperative, number/quantity, contrast or
|
||||
stakes — see the vocabularies above). Leading hesitation, silence and
|
||||
filler do not match, so they fall into the trimmed wind-up. Returns the
|
||||
hook word's start when it is a legal trim, else ``None`` (no change — a
|
||||
clip without a clear hook is left exactly where snapping put it).
|
||||
|
||||
``words`` is the whole-video ``[{'w','s','e'}, ...]`` list (same shape
|
||||
``snap_clip_to_words`` takes). The trim is bounded three ways so the pass
|
||||
can never wreck a clip:
|
||||
|
||||
* ``max_trim`` seconds (env ``HOOK_FIRST_MAX_TRIM``, default 4.0)
|
||||
* ``max_fraction`` of the clip's duration (env ``HOOK_FIRST_MAX_FRACTION``,
|
||||
default 0.25)
|
||||
* the remaining clip must still be at least ``min_duration`` seconds.
|
||||
"""
|
||||
try:
|
||||
clip_start = float(clip_start)
|
||||
clip_end = float(clip_end)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
duration = clip_end - clip_start
|
||||
if duration <= 0:
|
||||
return None
|
||||
|
||||
if max_trim is None:
|
||||
max_trim = _env_float("HOOK_FIRST_MAX_TRIM",
|
||||
_HOOK_FIRST_DEFAULT_MAX_TRIM)
|
||||
if max_fraction is None:
|
||||
max_fraction = _env_float("HOOK_FIRST_MAX_FRACTION",
|
||||
_HOOK_FIRST_DEFAULT_MAX_FRACTION)
|
||||
try:
|
||||
max_trim = max(0.0, float(max_trim))
|
||||
max_fraction = max(0.0, float(max_fraction))
|
||||
min_duration = float(min_duration)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
cap = min(max_trim, max_fraction * duration)
|
||||
if cap < _MIN_HOOK_TRIM:
|
||||
return None
|
||||
latest = clip_start + cap
|
||||
|
||||
hook_start = None
|
||||
for word in words or []:
|
||||
try:
|
||||
word_start = float(word.get("s", 0))
|
||||
except (AttributeError, TypeError, ValueError):
|
||||
continue
|
||||
if word_start < clip_start or word_start > latest:
|
||||
continue
|
||||
if word_start >= clip_end:
|
||||
continue
|
||||
if _is_hook_token(_hook_token(word.get("w"))):
|
||||
if hook_start is None or word_start < hook_start:
|
||||
hook_start = word_start
|
||||
|
||||
if hook_start is None:
|
||||
return None
|
||||
trim = hook_start - clip_start
|
||||
if trim < _MIN_HOOK_TRIM:
|
||||
return None
|
||||
if clip_end - hook_start < min_duration:
|
||||
return None
|
||||
return round(hook_start, 3)
|
||||
|
|
|
|||
170
tests/test_hook_start.py
Normal file
170
tests/test_hook_start.py
Normal file
|
|
@ -0,0 +1,170 @@
|
|||
"""Hook-first clip boundaries: the pure ``find_hook_start`` pass (#2a).
|
||||
|
||||
The first two seconds decide the swipe, so the pass moves a clip's start off
|
||||
its wind-up and onto the earliest strong spoken token. It is deterministic and
|
||||
word-based (no LLM) and must fail safe: no clear hook -> no change, and the
|
||||
trim is capped by seconds, by fraction of the clip, and by the minimum clip
|
||||
duration.
|
||||
"""
|
||||
|
||||
from clipwright.pipeline.clip_selection import (
|
||||
find_hook_start,
|
||||
hook_first_enabled,
|
||||
)
|
||||
|
||||
|
||||
def _w(word, s, e):
|
||||
return {"w": word, "s": s, "e": e}
|
||||
|
||||
|
||||
class TestPicksEarliestHook:
|
||||
def test_picks_the_earliest_hook_after_the_wind_up(self):
|
||||
words = [
|
||||
_w(" so", 0.0, 0.3),
|
||||
_w(" uh", 0.3, 0.6),
|
||||
_w(" why", 1.2, 1.6), # interrogative — first hook
|
||||
_w(" do", 1.6, 1.8),
|
||||
_w(" we", 1.8, 2.0),
|
||||
]
|
||||
assert find_hook_start(words, 0.0, 30.0, min_duration=15.0,
|
||||
max_trim=5.0, max_fraction=0.5) == 1.2
|
||||
|
||||
def test_earliest_wins_across_signal_categories(self):
|
||||
words = [
|
||||
_w(" okay", 0.0, 0.3),
|
||||
_w(" 3", 0.8, 1.1), # number
|
||||
_w(" but", 1.4, 1.7), # contrast
|
||||
_w(" crash", 2.0, 2.4), # stakes
|
||||
]
|
||||
assert find_hook_start(words, 0.0, 30.0, min_duration=15.0,
|
||||
max_trim=5.0, max_fraction=0.5) == 0.8
|
||||
|
||||
def test_start_is_absolute_not_relative_to_the_clip(self):
|
||||
words = [_w(" huh", 100.0, 100.3), _w(" why", 103.0, 103.4)]
|
||||
assert find_hook_start(words, 100.0, 140.0, min_duration=15.0,
|
||||
max_trim=5.0, max_fraction=0.5) == 103.0
|
||||
|
||||
def test_a_clip_already_on_its_hook_is_left_alone(self):
|
||||
# trim ~0 is noise; returning None means "do not touch".
|
||||
words = [_w(" bug", 10.0, 10.3), _w(" but", 12.0, 12.3)]
|
||||
assert find_hook_start(words, 10.0, 40.0, min_duration=15.0,
|
||||
max_trim=5.0, max_fraction=0.5) is None
|
||||
|
||||
|
||||
class TestTrimCaps:
|
||||
def test_respects_max_trim_seconds(self):
|
||||
words = [_w(" uh", 0.0, 0.3), _w(" why", 6.0, 6.4)]
|
||||
assert find_hook_start(words, 0.0, 30.0, min_duration=15.0,
|
||||
max_trim=4.0, max_fraction=1.0) is None
|
||||
# Just inside the cap it fires.
|
||||
words[1] = _w(" why", 3.9, 4.3)
|
||||
assert find_hook_start(words, 0.0, 30.0, min_duration=15.0,
|
||||
max_trim=4.0, max_fraction=1.0) == 3.9
|
||||
|
||||
def test_respects_max_fraction_of_the_clip(self):
|
||||
words = [_w(" uh", 0.0, 0.3), _w(" why", 4.0, 4.4)]
|
||||
# duration 20, 10% -> 2.0s cap, so a 4.0s hook is out of reach.
|
||||
assert find_hook_start(words, 0.0, 20.0, min_duration=5.0,
|
||||
max_trim=100.0, max_fraction=0.1) is None
|
||||
# 50% -> 10s cap, the same hook is reachable.
|
||||
assert find_hook_start(words, 0.0, 20.0, min_duration=5.0,
|
||||
max_trim=100.0, max_fraction=0.5) == 4.0
|
||||
|
||||
def test_zero_cap_never_moves(self):
|
||||
words = [_w(" why", 1.0, 1.4)]
|
||||
assert find_hook_start(words, 0.0, 30.0, min_duration=15.0,
|
||||
max_trim=0.0, max_fraction=1.0) is None
|
||||
|
||||
def test_min_duration_wins_over_the_caps(self):
|
||||
# Hook at 2.0 is within the trim cap but would leave 14s < 15s.
|
||||
words = [_w(" why", 2.0, 2.4)]
|
||||
assert find_hook_start(words, 0.0, 16.0, min_duration=15.0,
|
||||
max_trim=5.0, max_fraction=0.5) is None
|
||||
|
||||
def test_degenerate_bounds_do_not_crash(self):
|
||||
words = [_w(" why", 1.0, 1.4)]
|
||||
assert find_hook_start(words, 5.0, 5.0, min_duration=15.0) is None
|
||||
assert find_hook_start(words, 0.0, 0.0, min_duration=15.0) is None
|
||||
|
||||
|
||||
class TestNoHook:
|
||||
def test_returns_none_without_a_hook(self):
|
||||
words = [
|
||||
_w(" and", 0.0, 0.3),
|
||||
_w(" then", 0.3, 0.6),
|
||||
_w(" we", 0.6, 0.9),
|
||||
_w(" the", 0.9, 1.2),
|
||||
]
|
||||
assert find_hook_start(words, 0.0, 30.0, min_duration=15.0,
|
||||
max_trim=5.0, max_fraction=0.5) is None
|
||||
|
||||
def test_filler_alone_is_not_a_hook(self):
|
||||
words = [_w(" um", 0.0, 0.2), _w(" okay", 0.2, 0.5),
|
||||
_w(" yeah", 0.5, 0.8)]
|
||||
assert find_hook_start(words, 0.0, 30.0, min_duration=15.0) is None
|
||||
|
||||
def test_empty_or_malformed_words_fail_safe(self):
|
||||
assert find_hook_start(None, 0.0, 30.0, min_duration=15.0) is None
|
||||
assert find_hook_start([], 0.0, 30.0, min_duration=15.0) is None
|
||||
assert find_hook_start(["junk", {"no_s": 1}], 1.0, 30.0,
|
||||
min_duration=15.0) is None
|
||||
|
||||
def test_clip_bounds_that_do_not_parse(self):
|
||||
assert find_hook_start([_w(" why", 1.0, 1.4)], None, 30.0) is None
|
||||
|
||||
|
||||
class TestTokenNormalisation:
|
||||
def test_words_without_leading_spaces_still_match(self):
|
||||
words = [_w("uh", 0.0, 0.3), _w("Why", 1.0, 1.4)]
|
||||
assert find_hook_start(words, 0.0, 30.0, min_duration=15.0,
|
||||
max_trim=5.0, max_fraction=0.5) == 1.0
|
||||
|
||||
def test_case_and_trailing_punctuation_are_stripped(self):
|
||||
words = [_w(" Uh,", 0.0, 0.3), _w("CRASH!", 1.0, 1.4)]
|
||||
assert find_hook_start(words, 0.0, 30.0, min_duration=15.0,
|
||||
max_trim=5.0, max_fraction=0.5) == 1.0
|
||||
|
||||
def test_numeric_tokens_are_hooks(self):
|
||||
assert find_hook_start([_w(" 2024", 1.0, 1.4)], 0.0, 30.0,
|
||||
min_duration=15.0, max_trim=5.0,
|
||||
max_fraction=0.5) == 1.0
|
||||
|
||||
def test_empty_word_text_is_ignored(self):
|
||||
words = [_w("", 0.5, 0.6), _w(" ", 0.6, 0.7), _w(" how", 1.0, 1.4)]
|
||||
assert find_hook_start(words, 0.0, 30.0, min_duration=15.0,
|
||||
max_trim=5.0, max_fraction=0.5) == 1.0
|
||||
|
||||
|
||||
class TestEnvConfig:
|
||||
def test_reads_max_trim_from_env(self, monkeypatch):
|
||||
monkeypatch.setenv("HOOK_FIRST_MAX_TRIM", "1.0")
|
||||
monkeypatch.setenv("HOOK_FIRST_MAX_FRACTION", "1.0")
|
||||
words = [_w(" uh", 0.0, 0.3), _w(" why", 2.0, 2.4)]
|
||||
assert find_hook_start(words, 0.0, 30.0, min_duration=15.0) is None
|
||||
words[1] = _w(" why", 0.8, 1.2)
|
||||
assert find_hook_start(words, 0.0, 30.0, min_duration=15.0) == 0.8
|
||||
|
||||
def test_reads_max_fraction_from_env(self, monkeypatch):
|
||||
monkeypatch.setenv("HOOK_FIRST_MAX_TRIM", "100")
|
||||
monkeypatch.setenv("HOOK_FIRST_MAX_FRACTION", "0.1")
|
||||
words = [_w(" uh", 0.0, 0.3), _w(" why", 4.0, 4.4)]
|
||||
assert find_hook_start(words, 0.0, 20.0, min_duration=5.0) is None
|
||||
|
||||
def test_garbage_env_falls_back_to_defaults(self, monkeypatch):
|
||||
monkeypatch.setenv("HOOK_FIRST_MAX_TRIM", "not-a-number")
|
||||
monkeypatch.setenv("HOOK_FIRST_MAX_FRACTION", "")
|
||||
words = [_w(" why", 3.5, 3.9)]
|
||||
assert find_hook_start(words, 0.0, 30.0, min_duration=15.0) == 3.5
|
||||
|
||||
def test_enabled_is_on_by_default(self, monkeypatch):
|
||||
monkeypatch.delenv("HOOK_FIRST", raising=False)
|
||||
assert hook_first_enabled() is True
|
||||
|
||||
def test_enabled_can_be_switched_off(self, monkeypatch):
|
||||
for raw in ("0", "false", "FALSE", "no", "off"):
|
||||
monkeypatch.setenv("HOOK_FIRST", raw)
|
||||
assert hook_first_enabled() is False
|
||||
|
||||
def test_enabled_explicit_true(self, monkeypatch):
|
||||
monkeypatch.setenv("HOOK_FIRST", "1")
|
||||
assert hook_first_enabled() is True
|
||||
93
tests/test_punch_in_beats.py
Normal file
93
tests/test_punch_in_beats.py
Normal file
|
|
@ -0,0 +1,93 @@
|
|||
"""Word-aligned punch-in beats: the pure derivation in punch_in.emphasis_times.
|
||||
|
||||
#2b moved beat timing from audio-envelope-only to the envelope snapped onto
|
||||
clip-relative word onsets. These tests pin the merge itself (no audio file
|
||||
needed) and the one behaviour that must not change: no word times -> exactly
|
||||
the old audio-only result.
|
||||
"""
|
||||
import pytest
|
||||
|
||||
from clipwright.layouts import punch_in
|
||||
from clipwright.layouts.punch_in import merge_beats
|
||||
|
||||
|
||||
class TestMergeBeats:
|
||||
def test_no_words_is_audio_only(self):
|
||||
assert merge_beats([1.0, 15.0], [], min_gap=4.0) == [1.0, 15.0]
|
||||
assert merge_beats([1.0, 15.0], None, min_gap=4.0) == [1.0, 15.0]
|
||||
|
||||
def test_envelope_beat_snaps_to_a_nearby_word(self):
|
||||
# The envelope peak sits 0.2s off the spoken word: the word is exact.
|
||||
assert merge_beats([10.0], [10.2], min_gap=4.0) == [10.2]
|
||||
|
||||
def test_a_distant_word_does_not_move_the_envelope_beat(self):
|
||||
# 5.0 is nowhere near either peak, so neither peak is re-timed.
|
||||
assert merge_beats([1.0, 30.0], [5.0], min_gap=4.0) == [1.0, 30.0]
|
||||
|
||||
def test_words_become_beats_when_audio_has_none(self):
|
||||
assert merge_beats([], [3.0, 40.0], min_gap=18.0) == [3.0, 40.0]
|
||||
|
||||
def test_beats_are_thinned_to_the_minimum_gap(self):
|
||||
# 2 and 4 collide at gap 10; the earliest wins, 20 keeps its own slot.
|
||||
assert merge_beats([2.0, 4.0, 20.0], [], min_gap=10.0) == [2.0, 20.0]
|
||||
|
||||
def test_result_is_sorted_and_rounded(self):
|
||||
assert merge_beats([12.3456], [], min_gap=4.0) == [12.346]
|
||||
assert merge_beats([], [3.0, 12.3456], min_gap=4.0) == [3.0, 12.346]
|
||||
|
||||
|
||||
class TestEmphasisTimesWithWords:
|
||||
def _envelope_spike(self, monkeypatch, beat_index=10, value=1.0, length=50):
|
||||
from clipwright.layouts import active_speaker
|
||||
envelope = [0.0] * length
|
||||
envelope[beat_index] = value
|
||||
monkeypatch.setattr(active_speaker, "audio_envelope",
|
||||
lambda *a, **k: envelope)
|
||||
return beat_index * 0.2 # window defaults to BEAT_WINDOW
|
||||
|
||||
def test_silent_audio_with_words_still_yields_word_beats(self, monkeypatch):
|
||||
from clipwright.layouts import active_speaker
|
||||
monkeypatch.setattr(active_speaker, "audio_envelope",
|
||||
lambda *a, **k: [])
|
||||
assert punch_in.emphasis_times("x.mp4", 30.0, word_times=[4.0]) == [4.0]
|
||||
|
||||
def test_no_words_keeps_the_old_audio_only_result(self, monkeypatch):
|
||||
beat = self._envelope_spike(monkeypatch, beat_index=10)
|
||||
assert punch_in.emphasis_times("x.mp4", 20.0) == [round(beat, 3)]
|
||||
|
||||
def test_word_snaps_the_envelope_spike_onto_itself(self, monkeypatch):
|
||||
beat = self._envelope_spike(monkeypatch, beat_index=10)
|
||||
times = punch_in.emphasis_times("x.mp4", 20.0, word_times=[beat + 0.1])
|
||||
assert times == [round(beat + 0.1, 3)]
|
||||
|
||||
def test_empty_word_list_is_backward_compatible(self, monkeypatch):
|
||||
beat = self._envelope_spike(monkeypatch, beat_index=5)
|
||||
assert (punch_in.emphasis_times("x.mp4", 20.0, word_times=[])
|
||||
== [round(beat, 3)])
|
||||
|
||||
|
||||
class TestClipWordOnsets:
|
||||
def _onsets(self, transcript, start, end):
|
||||
pytest.importorskip("clipwright.pipeline.main")
|
||||
from clipwright.pipeline.main import clip_word_onsets
|
||||
return clip_word_onsets(transcript, start, end)
|
||||
|
||||
def test_words_become_clip_relative_seconds(self):
|
||||
transcript = {"segments": [{"words": [
|
||||
{"word": "a", "start": 100.0, "end": 100.5},
|
||||
{"word": "b", "start": 102.0, "end": 102.5},
|
||||
{"word": "c", "start": 111.0, "end": 111.5}, # after the clip
|
||||
]}]}
|
||||
assert self._onsets(transcript, 100.0, 110.0) == [0.0, 2.0]
|
||||
|
||||
def test_boundary_words_are_clamped_into_the_clip(self):
|
||||
transcript = {"segments": [{"words": [
|
||||
{"word": "x", "start": 98.0, "end": 101.0}, # starts before
|
||||
{"word": "y", "start": 109.0, "end": 112.0}, # ends after
|
||||
]}]}
|
||||
assert self._onsets(transcript, 100.0, 110.0) == [0.0, 9.0]
|
||||
|
||||
def test_no_transcript_or_words_is_empty(self):
|
||||
assert self._onsets(None, 0.0, 10.0) == []
|
||||
assert self._onsets({"segments": []}, 0.0, 10.0) == []
|
||||
assert self._onsets({"segments": [{"text": "hi"}]}, 0.0, 10.0) == []
|
||||
Loading…
Reference in a new issue