feat(selection): say why each clip was picked, drop clips that overlap a better one

The detail pass now returns a one-sentence `why` per clip (what makes this
moment a clip, not the topic), stored in the metadata and shown under the
title in the dashboard card: the score said how much, nothing said why.
Defaulted in the schema so a small local model that skips it keeps the clip.

After the word snap, clips overlapping an already-kept clip by half the
shorter one are dropped in favour of the higher predicted_score. The prompt's
DIVERSITY rule was the only thing preventing the same moment twice; in ~330
clips over 8 talks it never fired, so this is a guard, not a fix.

Each clip also keeps the model's raw `proposed` boundaries before the snap,
which is what made boundary accuracy measurable: p90 0.4-0.5 s from a word
on 8 talks (21-sep-2026), inside snap_clip_to_words' 1.5 s reach.

Two ideas borrowed from AutoClip were measured with a blind judge on the
same corpus and NOT adopted: quoting per-sentence timestamps in the detail
pass lost 24%/23% (p<0.001, two seeds — it shortens clips and drops the
payoff), and an "end on the reaction, not the line" rule was inert
(47%/53%, p=0.71).
This commit is contained in:
juancarlos.cavero 2026-09-21 22:47:55 +02:00
parent 0db0a3a04b
commit 36dba9b3b1
5 changed files with 94 additions and 3 deletions

View file

@ -196,6 +196,45 @@ def build_transcript_windows(transcript_result, video_duration,
return windows
def dedupe_overlapping(shorts, ratio=0.5):
"""Drop clips that overlap an already-kept clip by ``ratio`` of the
shorter one, keeping the higher ``predicted_score`` (earlier on a tie).
The detail prompt's DIVERSITY rule is the only thing that stopped two
clips from sharing the same seconds, and a rule is not a guarantee: two
picks from one window can cover the same moment with different edges,
and the user then downloads the same short twice. Survivors come back in
transcript order, like ``trim_to_best``.
"""
def _score(c):
try:
return float(c.get("predicted_score") or 0)
except (TypeError, ValueError, AttributeError):
return 0.0
def _span(c):
try:
return float(c.get("start", 0)), float(c.get("end", 0))
except (TypeError, ValueError, AttributeError):
return 0.0, 0.0
indexed = list(enumerate(shorts))
kept = []
for idx, clip in sorted(indexed, key=lambda p: (-_score(p[1]), p[0])):
s, e = _span(clip)
clash = False
for _, other in kept:
os_, oe = _span(other)
overlap = min(e, oe) - max(s, os_)
shorter = max(1e-6, min(e - s, oe - os_))
if overlap > 0 and overlap / shorter >= ratio:
clash = True
break
if not clash:
kept.append((idx, clip))
return [c for _, c in sorted(kept, key=lambda p: p[0])]
def snap_clip_to_words(start, end, words, video_duration,
min_duration=15.0, max_duration=60.0,
search_window=1.5, max_lead=0.35, max_tail=0.45):

View file

@ -816,6 +816,13 @@ export default function ResultCard({ clip, index, jobId, durable, uploadPostKey,
<h3 className="text-base font-medium text-ink leading-tight line-clamp-2 mb-2 break-words" title={clip.video_title_for_youtube_short}>
{clip.video_title_for_youtube_short || "Viral Clip Generated"}
</h3>
{/* The score alone says how much, not why. One line from
the selection pass on what this moment has going for it. */}
{clip.why && (
<p className="text-xs text-muted leading-snug line-clamp-2 mb-2 break-words" title="why openshorts picked this moment">
{clip.why}
</p>
)}
<div className="flex flex-wrap gap-1.5">
{durationReadout && <span className="readout bg-paper3 px-2 py-0.5 rounded-full shrink-0">{durationReadout}</span>}
{resolution && <span className="readout bg-paper3 px-2 py-0.5 rounded-full shrink-0">{resolution}</span>}

View file

@ -40,6 +40,10 @@ class DetailClipModel(BaseModel):
video_description_for_instagram: str
video_title_for_youtube_short: str
viral_hook_text: str
# One sentence on what makes THIS moment a clip, shown under the score in
# the dashboard. Defaulted so a small local model that skips it does not
# fail schema validation and lose the clip.
why: str = ""
class DetailResponse(BaseModel):
@ -327,6 +331,8 @@ COPY RULES — ALL text fields (descriptions, title, hook) MUST be written in TR
without spoiling it, then 3-5 topically relevant hashtags. No generic hashtag spam.
- `video_title_for_youtube_short`: max 100 chars, curiosity-driven, no fake claims.
- `predicted_score`: honest 0-100 estimate of viral potential.
- `why`: one sentence, max 20 words, naming what makes THIS moment worth a
clip — the specific hook, claim, number or payoff, not the topic.
TRANSCRIPT_LANGUAGE: {language}
VIDEO_DURATION_SECONDS: {video_duration}
@ -344,7 +350,8 @@ Return only:
"video_description_for_tiktok": "<description + hashtags>",
"video_description_for_instagram": "<description + hashtags>",
"video_title_for_youtube_short": "<title max 100 chars>",
"viral_hook_text": "<short overlay max 10 words>"
"viral_hook_text": "<short overlay max 10 words>",
"why": "<one sentence, max 20 words>"
}}
]
}}

13
main.py
View file

@ -27,8 +27,8 @@ import hook_grounding
import layout_picker
import llm_backend
from clip_selection import (build_transcript_windows, clip_count_targets,
clip_duration_bounds, snap_clip_to_words,
trim_to_best)
clip_duration_bounds, dedupe_overlapping,
snap_clip_to_words, trim_to_best)
from ffmpeg_utils import (video_encode_args, audio_encode_args, cut_clip, QUALITY,
QUALITY_FAST, METADATA_SCRUB)
from dotenv import load_dotenv
@ -1738,9 +1738,18 @@ def get_viral_clips(transcript_result, video_duration):
f"{max_clips + dropped}.")
# Snap each proposed clip onto real word boundaries (+ a bit of silence).
for s in shorts:
# Keep the model's raw proposal: it is how boundary accuracy is
# measured (distance to the nearest word before the snap; p90 was
# 0.4-0.5 s on 8 talks, 21-sep-2026, so the snap reaches it).
s["proposed"] = [s.get("start", 0), s.get("end", 0)]
ns, ne = snap_clip_to_words(s.get("start", 0), s.get("end", 0), words, video_duration,
min_duration=min_secs, max_duration=max_secs)
s["start"], s["end"] = ns, ne
deduped = dedupe_overlapping(shorts)
if len(deduped) < len(shorts):
print(f" Dropped {len(shorts) - len(deduped)} clip(s) overlapping a "
f"better-scored one.")
shorts = deduped
# Aggregate cost across both passes.
cost_analysis = None

View file

@ -6,6 +6,7 @@ import pytest
from clip_selection import (
build_transcript_windows,
clip_count_targets,
dedupe_overlapping,
snap_clip_to_words,
compact_words,
lookup_model_prices,
@ -215,3 +216,31 @@ class TestTrimToBest:
def test_max_clips_is_never_below_one(self):
shorts = [self._clip(0, 10), self._clip(50, 20)]
assert len(trim_to_best(shorts, 0)) == 1
class TestDedupeOverlapping:
"""Two picks from one window can cover the same seconds with different
edges; the DIVERSITY rule in the prompt is not a guarantee."""
@staticmethod
def _clip(start, end, score):
return {"start": start, "end": end, "predicted_score": score}
def test_keeps_the_better_scored_of_two_overlapping(self):
a, b = self._clip(10, 40, 70), self._clip(20, 50, 85) # 20 s shared of 30 s
assert dedupe_overlapping([a, b]) == [b]
assert dedupe_overlapping([b, a]) == [b]
def test_small_overlap_keeps_both_in_input_order(self):
# 5 s shared of 30 s: under the ratio, both survive, order untouched
# (the detail pass already hands clips back in transcript order).
a, b = self._clip(10, 40, 70), self._clip(35, 65, 85)
assert dedupe_overlapping([a, b]) == [a, b]
def test_tie_keeps_the_earlier(self):
a, b = self._clip(10, 40, 80), self._clip(15, 45, 80)
assert dedupe_overlapping([a, b]) == [a]
def test_disjoint_untouched(self):
clips = [self._clip(0, 30, 50), self._clip(30, 60, 60), self._clip(100, 130, 40)]
assert dedupe_overlapping(clips) == clips