Spaces:
Sleeping
Sleeping
File size: 20,842 Bytes
eda316b 5cd4a32 eda316b 5cd4a32 eda316b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 | """Stage 2.25 - Hook detection.
The clip-selection LLM returns a ``hook_start_sec`` / ``hook_end_sec`` pair
per clip, but in practice it almost always echoes the ``[0.0, 3.0]``
placeholder from the prompt instead of localising the real hook sentence.
That placeholder is toxic to Stage 2.5 pruning -- the clamp refuses to
trim past ``hook_start_sec``, so every ``trim_start_sec > 0`` the pruner
returns gets zeroed out silently.
This module is a dedicated Stage 2.25 that runs between clip selection and
content pruning. For each clip it:
1. Prepares a clip-relative segment listing (same format as pruning uses).
2. Asks Gemini, in one batched JSON call, to localise the hook sentence of
every clip with `hook_start_sec`, `hook_end_sec`, `hook_text`, `reason`.
3. Validates the returned window against the clip's duration + the "real
hook" heuristics, then overwrites ``clip.hook_start_sec`` /
``clip.hook_end_sec`` on a copy of the clip.
The stage is:
- **Cached** (``hooks.json`` / ``hooks.meta.json`` in ``work_dir``) on
``transcript_sha256 + clips_sha256 + gemini_model``.
- **Never fatal.** Any failure (API error, malformed JSON, clip not
returned, window that still looks like the 0.0-3.0 placeholder) falls
back to the original clip with its original hook -- pruning will then
skip hook protection via the fingerprint guard in
:func:`humeo.content_pruning._looks_like_default_hook`.
The stage writes three artifacts to ``work_dir`` for audit:
- ``hooks.meta.json``: cache key (version, fingerprints, model).
- ``hooks.json``: structured per-clip hook windows actually applied.
- ``hooks_raw.json``: verbatim Gemini response text (for prompt tuning).
"""
from __future__ import annotations
import hashlib
import json
import logging
import time
from pathlib import Path
from typing import Any, Callable, TypeVar
from google import genai
from openai import OpenAI
from pydantic import BaseModel, Field, ValidationError
from humeo_core.schemas import Clip
from humeo.config import GEMINI_MODEL, PipelineConfig
from humeo.content_pruning import _looks_like_default_hook, _segments_within_clip
from humeo.env import (
OPENROUTER_BASE_URL,
current_llm_provider,
model_name_for_provider,
openrouter_default_headers,
resolve_gemini_api_key,
resolve_llm_provider,
resolve_openrouter_api_keys,
)
from humeo.gemini_generate import gemini_generate_config
from humeo.hook_library import (
format_hook_examples,
hook_library_fingerprint,
resolve_hook_library_path,
retrieve_hook_examples,
)
from humeo.prompt_loader import hook_detection_system_prompt
logger = logging.getLogger(__name__)
T = TypeVar("T")
HOOK_META_VERSION = 2
HOOK_META_FILENAME = "hooks.meta.json"
HOOK_ARTIFACT_FILENAME = "hooks.json"
HOOK_RAW_FILENAME = "hooks_raw.json"
LLM_MAX_ATTEMPTS = 3
LLM_RETRY_DELAY_SEC = 2.0
# Hook window validation thresholds. The prompt asks for 1.5-7.0s windows;
# we enforce 1.0-10.0s to be lenient on rounding while still rejecting
# obvious "LLM returned the whole paragraph" mistakes.
_MIN_HOOK_DURATION_SEC = 1.0
_MAX_HOOK_DURATION_SEC = 10.0
def _openai_message_text(content: object) -> str:
if isinstance(content, str):
return content
if isinstance(content, list):
parts: list[str] = []
for item in content:
if isinstance(item, dict) and item.get("type") == "text":
text = item.get("text")
if isinstance(text, str):
parts.append(text)
return "".join(parts)
return ""
class _HookDecision(BaseModel):
"""Per-clip hook window returned by Gemini (clip-relative seconds)."""
clip_id: str
hook_start_sec: float = Field(ge=0.0)
hook_end_sec: float = Field(ge=0.0)
hook_text: str = ""
reason: str = ""
class _HookResponse(BaseModel):
hooks: list[_HookDecision] = Field(default_factory=list)
def _retry_llm(name: str, fn: Callable[[], T], attempts: int = LLM_MAX_ATTEMPTS) -> T:
last: Exception | None = None
for i in range(attempts):
try:
return fn()
except Exception as e: # noqa: BLE001 - rethrown below
last = e
if i < attempts - 1:
logger.warning("%s attempt %d/%d failed: %s", name, i + 1, attempts, e)
time.sleep(LLM_RETRY_DELAY_SEC * (i + 1))
assert last is not None
raise last
# ---------------------------------------------------------------------------
# Prompt construction
# ---------------------------------------------------------------------------
def _build_user_message(clips: list[Clip], transcript: dict) -> str:
"""Render clip-relative segments + selector-guessed hook text for each clip."""
blocks: list[str] = []
for clip in clips:
segs = _segments_within_clip(transcript, clip)
header_lines = [
f"clip_id: {clip.clip_id}",
f"duration_sec: {clip.duration_sec:.2f}",
f"topic: {clip.topic}",
]
if clip.viral_hook:
header_lines.append(f"viral_hook_text: {clip.viral_hook}")
if clip.hook_start_sec is not None and clip.hook_end_sec is not None:
header_lines.append(
f"selector_hook_window_sec: [{clip.hook_start_sec:.2f}, "
f"{clip.hook_end_sec:.2f}] (may be a placeholder; verify)"
)
header = "\n".join(header_lines)
body = "\n".join(
f"[{seg['start']:.2f}s - {seg['end']:.2f}s] {seg['text']}" for seg in segs
)
if not body:
body = "(no segments overlap this clip window)"
blocks.append(f"{header}\n---\n{body}")
return "\n\n===\n\n".join(blocks)
# ---------------------------------------------------------------------------
# Validation
# ---------------------------------------------------------------------------
def _validate_hook_window(
clip: Clip, hook_start: float, hook_end: float
) -> tuple[float, float] | None:
"""Return a valid (hook_start, hook_end) or None if rejected.
Rules:
- ``0 <= hook_start < hook_end <= duration_sec``
- hook duration between ``_MIN_HOOK_DURATION_SEC`` and ``_MAX_HOOK_DURATION_SEC``
- NOT the ``(0.0, 3.0)`` placeholder fingerprint (we'd rather keep the
selector's value untouched than re-apply the same fake hook).
"""
if hook_start < 0.0 or hook_end <= hook_start:
return None
if hook_end > clip.duration_sec + 1e-3:
# Clamp trailing rounding to duration; reject anything beyond.
if hook_end - clip.duration_sec > 0.5:
return None
hook_end = clip.duration_sec
dur = hook_end - hook_start
if dur < _MIN_HOOK_DURATION_SEC or dur > _MAX_HOOK_DURATION_SEC:
return None
if _looks_like_default_hook(hook_start, hook_end):
return None
return float(hook_start), float(hook_end)
# ---------------------------------------------------------------------------
# Apply decisions -> new clips
# ---------------------------------------------------------------------------
def apply_hook_decisions(
clips: list[Clip],
decisions: list[_HookDecision],
) -> list[Clip]:
"""Return new clips whose hook fields reflect validated decisions.
Clips without a matching valid decision are returned unchanged (their
original hook metadata, placeholder or not, is preserved).
"""
by_id = {d.clip_id: d for d in decisions}
out: list[Clip] = []
changed = 0
rejected = 0
for clip in clips:
d = by_id.get(clip.clip_id)
if d is None:
out.append(clip)
continue
validated = _validate_hook_window(clip, d.hook_start_sec, d.hook_end_sec)
if validated is None:
logger.info(
"Clip %s: rejected hook window [%.2f, %.2f] (failed validation); "
"keeping selector hook.",
clip.clip_id,
d.hook_start_sec,
d.hook_end_sec,
)
rejected += 1
out.append(clip)
continue
hs, he = validated
if (
clip.hook_start_sec is not None
and clip.hook_end_sec is not None
and abs(clip.hook_start_sec - hs) < 1e-3
and abs(clip.hook_end_sec - he) < 1e-3
):
out.append(clip)
continue
changed += 1
logger.info(
"Clip %s: hook set to [%.2f, %.2f] (was [%s, %s]) -- %s",
clip.clip_id,
hs,
he,
f"{clip.hook_start_sec:.2f}" if clip.hook_start_sec is not None else "None",
f"{clip.hook_end_sec:.2f}" if clip.hook_end_sec is not None else "None",
d.reason[:120] if d.reason else "(no reason)",
)
out.append(
clip.model_copy(update={"hook_start_sec": hs, "hook_end_sec": he})
)
logger.info(
"Hook detection: updated %d / %d clips (%d rejected, %d kept as-is).",
changed,
len(clips),
rejected,
len(clips) - changed - rejected,
)
return out
# ---------------------------------------------------------------------------
# Cache
# ---------------------------------------------------------------------------
def _clips_fingerprint(clips: list[Clip]) -> str:
payload = json.dumps(
[
{"id": c.clip_id, "s": round(c.start_time_sec, 3), "e": round(c.end_time_sec, 3)}
for c in clips
],
sort_keys=True,
ensure_ascii=False,
)
return hashlib.sha256(payload.encode("utf-8")).hexdigest()
def _resolved_gemini_model(config: PipelineConfig) -> str:
return (config.gemini_model or GEMINI_MODEL).strip()
def _hook_meta(
*,
transcript_fp: str,
clips_fp: str,
config: PipelineConfig,
) -> dict[str, Any]:
return {
"version": HOOK_META_VERSION,
"transcript_sha256": transcript_fp,
"clips_sha256": clips_fp,
"gemini_model": _resolved_gemini_model(config),
"llm_backend": current_llm_provider() or "google",
"hook_library_sha256": hook_library_fingerprint(resolve_hook_library_path(config)),
}
def _hook_cache_valid(
work_dir: Path,
*,
transcript_fp: str,
clips_fp: str,
config: PipelineConfig,
) -> bool:
meta_path = work_dir / HOOK_META_FILENAME
if not meta_path.is_file():
return False
try:
with open(meta_path, encoding="utf-8") as f:
meta = json.load(f)
except Exception:
return False
if meta.get("version") != HOOK_META_VERSION:
return False
if meta.get("transcript_sha256") != transcript_fp:
return False
if meta.get("clips_sha256") != clips_fp:
return False
current_provider = current_llm_provider()
meta_provider = meta.get("llm_backend")
if current_provider == "openrouter":
if meta_provider != "openrouter":
return False
elif current_provider == "google":
if meta_provider not in (None, "google"):
return False
if meta.get("gemini_model") != _resolved_gemini_model(config):
return False
if meta.get("hook_library_sha256", "") != hook_library_fingerprint(resolve_hook_library_path(config)):
return False
return True
def _load_cached_hooks(
work_dir: Path, clips: list[Clip]
) -> list[Clip] | None:
artifact = work_dir / HOOK_ARTIFACT_FILENAME
if not artifact.is_file():
return None
try:
with open(artifact, "r", encoding="utf-8") as f:
data = json.load(f)
cached = {item["clip_id"]: item for item in data.get("hooks", [])}
except Exception as e: # noqa: BLE001 - surfaced as warning below
logger.warning("Hook cache artifact unreadable (%s); re-running.", e)
return None
out: list[Clip] = []
for clip in clips:
c = cached.get(clip.clip_id)
if c is None:
out.append(clip)
continue
hs = c.get("hook_start_sec")
he = c.get("hook_end_sec")
if hs is None or he is None:
out.append(clip)
continue
out.append(
clip.model_copy(
update={"hook_start_sec": float(hs), "hook_end_sec": float(he)}
)
)
return out
def _write_cache(
work_dir: Path,
*,
clips_with_hooks: list[Clip],
decisions: list[_HookDecision],
meta: dict[str, Any],
raw_response: str,
) -> None:
work_dir.mkdir(parents=True, exist_ok=True)
reasons = {d.clip_id: d for d in decisions}
payload = {
"hooks": [
{
"clip_id": c.clip_id,
"hook_start_sec": c.hook_start_sec,
"hook_end_sec": c.hook_end_sec,
"hook_text": (reasons.get(c.clip_id).hook_text if reasons.get(c.clip_id) else ""),
"reason": (reasons.get(c.clip_id).reason if reasons.get(c.clip_id) else ""),
}
for c in clips_with_hooks
]
}
(work_dir / HOOK_ARTIFACT_FILENAME).write_text(
json.dumps(payload, indent=2), encoding="utf-8"
)
(work_dir / HOOK_RAW_FILENAME).write_text(raw_response, encoding="utf-8")
with open(work_dir / HOOK_META_FILENAME, "w", encoding="utf-8") as f:
json.dump(meta, f, indent=2)
f.write("\n")
logger.info(
"Wrote %s, %s and %s",
HOOK_META_FILENAME,
HOOK_ARTIFACT_FILENAME,
HOOK_RAW_FILENAME,
)
# ---------------------------------------------------------------------------
# Gemini call
# ---------------------------------------------------------------------------
def _parse_decisions(raw_json: str) -> list[_HookDecision]:
data = json.loads(raw_json)
if isinstance(data, dict) and "hooks" in data:
try:
return _HookResponse.model_validate(data).hooks
except ValidationError as e:
logger.warning("Hook response failed validation: %s", e)
return []
if isinstance(data, list):
out: list[_HookDecision] = []
for item in data:
try:
out.append(_HookDecision.model_validate(item))
except ValidationError:
continue
return out
return []
def request_hook_decisions(
clips: list[Clip],
transcript: dict,
*,
gemini_model: str | None = None,
hook_library_path: Path | None = None,
) -> tuple[list[_HookDecision], str]:
"""Ask Gemini to localise the hook sentence for each clip.
Returns ``(decisions, raw_response)``. ``raw_response`` is the literal
JSON text from Gemini (cached to ``hooks_raw.json`` for audit). On
transport/parse failure this raises; callers should catch and treat as
no-op.
"""
if not clips:
return [], '{"hooks": []}'
example_query = " ".join(
filter(None, [*(clip.topic for clip in clips[:4]), *(clip.viral_hook for clip in clips[:4])])
)
hook_examples = format_hook_examples(
retrieve_hook_examples(example_query, path=hook_library_path, limit=8)
)
system = hook_detection_system_prompt(hook_examples=hook_examples)
user_text = _build_user_message(clips, transcript)
provider = resolve_llm_provider()
model_name = model_name_for_provider((gemini_model or GEMINI_MODEL).strip(), provider)
def _call() -> str:
logger.info(
"%s hook detection (model=%s, clips=%d)...", provider, model_name, len(clips)
)
if provider == "google":
client = genai.Client(api_key=resolve_gemini_api_key())
response = client.models.generate_content(
model=model_name,
contents=user_text,
config=gemini_generate_config(
system_instruction=system,
temperature=0.2,
response_mime_type="application/json",
),
)
if not response.text:
raise RuntimeError("Gemini returned empty response text for hook detection")
return response.text
keys = resolve_openrouter_api_keys()
last_error: Exception | None = None
for key_idx, api_key in enumerate(keys, start=1):
try:
client = OpenAI(
api_key=api_key,
base_url=OPENROUTER_BASE_URL,
default_headers=openrouter_default_headers(),
)
response = client.chat.completions.create(
model=model_name,
messages=[
{"role": "system", "content": system},
{"role": "user", "content": user_text},
],
temperature=0.2,
response_format={"type": "json_object"},
)
text = _openai_message_text(response.choices[0].message.content)
if not text:
raise RuntimeError("OpenRouter returned empty response text for hook detection")
if key_idx > 1:
logger.info("OpenRouter hook detection succeeded with fallback key %d/%d", key_idx, len(keys))
return text
except Exception as exc:
last_error = exc
if key_idx < len(keys):
logger.warning(
"OpenRouter hook detection failed with key %d/%d: %s; trying fallback",
key_idx,
len(keys),
exc,
)
assert last_error is not None
raise last_error
raw = _retry_llm("Gemini hook detection", _call)
decisions = _parse_decisions(raw)
return decisions, raw
# ---------------------------------------------------------------------------
# Public stage entrypoint
# ---------------------------------------------------------------------------
def run_hook_detection_stage(
work_dir: Path,
clips: list[Clip],
transcript: dict,
*,
transcript_fp: str,
config: PipelineConfig,
) -> list[Clip]:
"""Run Stage 2.25 hook detection and return clips with localised hooks.
- Disabled (``config.detect_hooks is False``): return clips unchanged.
- Cache hit: read ``hooks.json`` and apply cached windows.
- LLM failure: log a warning and return clips unchanged. The downstream
content pruner's fingerprint guard will treat any remaining placeholder
hooks as "no hook" so pruning still runs.
"""
if not config.detect_hooks:
logger.info("Hook detection disabled (detect_hooks=False); skipping Stage 2.25.")
return clips
if not clips:
return clips
clips_fp = _clips_fingerprint(clips)
if not config.force_hook_detection and _hook_cache_valid(
work_dir,
transcript_fp=transcript_fp,
clips_fp=clips_fp,
config=config,
):
cached = _load_cached_hooks(work_dir, clips)
if cached is not None:
logger.info(
"Hook detection cache hit (%d clips); skipping LLM.", len(clips)
)
return cached
try:
decisions, raw = request_hook_decisions(
clips,
transcript,
gemini_model=config.gemini_model,
hook_library_path=resolve_hook_library_path(config),
)
except Exception as e: # noqa: BLE001 - pipeline must not die here
logger.warning(
"Hook detection call failed (%s); continuing with selector hooks. "
"Content pruning will treat any [0.0, 3.0] placeholder as 'no hook'.",
e,
)
return clips
updated = apply_hook_decisions(clips, decisions)
meta = _hook_meta(
transcript_fp=transcript_fp, clips_fp=clips_fp, config=config
)
try:
_write_cache(
work_dir,
clips_with_hooks=updated,
decisions=decisions,
meta=meta,
raw_response=raw,
)
except Exception as e: # noqa: BLE001 - cache failure is not fatal
logger.warning("Failed to write hook cache (%s); continuing.", e)
return updated
|