Files
momentum-system/youtube_claims/transcription.py
T
momentum devandClaude Opus 5.5 91af4c2e93 feat: nightly Ross-recap learning loop on the owner's local Ollama
Why: the pilot in data/ross showed that Ross Cameron's daily recaps, joined to
the SIP tape and to what our bot saw, answer "which of his trades could we have
taken and why didn't we". It was a set of one-off scripts run by hand; the
server-side youtube_claims pipeline has been dead since ~08-24 (YouTube blocks
the TrueNAS IP) and its captions fallback hid that. This makes the pilot a
nightly, local, cumulative loop without a paid LLM API.

youtube_claims/recap/ (python -m youtube_claims.recap.nightly):
- channel: yt-dlp flat listing of @DaytradeWarrior, m4a audio, faster-whisper
  small.en on CPU, pilot-format bundles (meta + our scanner list + transcript).
- extract: Ollama structured output (JSON schema) per EXTRACT_SPEC, chunked
  with overlap for long transcripts and merged. The verbatim rule is enforced in
  code: every quote must be found (token-level, one-word tolerance) and is
  snapped to the transcript's words; unquoted items, trades with no surviving
  quote, prices never spoken, and passed-on names never said are dropped.
- llm: endpoint pool over RECAP_OLLAMA_HOSTS (round-robin + failover, per-host
  model/ctx/think pins) since the owner runs several Ollama boxes.
- tape/join/ourside: ported join.py/ourside.py -- tickers are price-verified on
  the Alpaca SIP tape (plus an order-free check for his own named ticker), then
  paper (:5433) and live (:5434) event views are attached. Bars cached on disk.
- store + schema.sql: idempotent recap_* tables in the transcripts schema,
  upserted per video_id. report: the pilot's sections + "what changed since last
  run" against the previous day's metrics JSON.
- evaluate: scores any model/prompt against the 36 gold extractions.

Model choice (36 gold videos, final code path, P/R):
  gpt-oss:20b on the workstation GPU, two focused calls, think=low:
    trades P .84 R .70; tickers P .82 R .77; entry +-2% P .54 R .50;
    passed-on P .66 R .76; temperature 16/31; kind 30/36; ~49 s/video.
  tools:latest (4B, server) one call: trades P .81 R .72, tickers P .83 R .85,
    passed-on P .80 R .75, temperature 20/31, but it invents prices
    (entry P .42) and occasionally runs away (5-9 min). Prices drive the tape
    verification, so the more precise local model is the default.
  Iterations: prompt v2 + spoken-price rescale (699 -> 6.99) + split calls took
  gpt-oss trades F1 .74 -> .76-.78 and tickers .78 -> .79-.80; think=medium
  blew the token budget. qwen3-30b-a3b on mason only finished 5 videos (host
  saturated) -- inconclusive.

Also: youtube_claims/transcription.py::_captions_fallback now picks the
youtube-transcript-api shape by feature detection instead of retrying the
removed get_transcript on any error, and transcribe() reports both the whisper
and captions causes -- the IpBlocked error was being masked as AttributeError.

No trading code touched.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 16:23:18 -05:00

84 lines
4.1 KiB
Python

"""Transcription (§6): yt-dlp bestaudio -> faster-whisper (initial_prompt seeded with the
watchlist) with a youtube-transcript-api captions FALLBACK. Whisper is PRIMARY because
auto-captions mangle the load-bearing tokens (tickers/numbers/prices); captions are a
last resort so a blocked/failed download still yields something. Writes transcript JSON."""
import json
import os
import tempfile
from youtube_claims import config
_model = None
def _whisper():
global _model
if _model is None:
from faster_whisper import WhisperModel
_model = WhisperModel(config.WHISPER_MODEL, device=config.WHISPER_DEVICE,
compute_type=config.WHISPER_COMPUTE_TYPE)
return _model
def _download_audio(video_id: str, out_dir: str) -> str | None:
import yt_dlp
tmpl = os.path.join(out_dir, f"{video_id}.%(ext)s")
opts = {"format": config.YT_DLP_FORMAT, "outtmpl": tmpl, "quiet": True, "no_warnings": True,
"ffmpeg_location": config.FFMPEG_LOCATION, # systemd PATH omits /usr/bin
"postprocessors": [{"key": "FFmpegExtractAudio", "preferredcodec": "wav"}]}
with yt_dlp.YoutubeDL(opts) as ydl:
ydl.download([f"https://www.youtube.com/watch?v={video_id}"])
wav = os.path.join(out_dir, f"{video_id}.wav")
return wav if os.path.exists(wav) else None
def _transcribe_whisper(wav: str, watchlist: list[str]) -> list[dict]:
prompt = ("Tickers and companies: " + ", ".join(watchlist)) if watchlist else None
segments, _info = _whisper().transcribe(wav, initial_prompt=prompt, vad_filter=True)
return [{"start": round(s.start, 2), "end": round(s.end, 2), "text": s.text} for s in segments]
def _captions_fallback(video_id: str) -> list[dict]:
"""YouTube captions via youtube-transcript-api. The API shape is chosen by feature
detection, NOT by catching an exception: the old code retried the removed pre-1.0
`get_transcript` after ANY fetch failure, so the real cause (IpBlocked / RequestBlocked
when YouTube blocks the server IP) was replaced by a misleading AttributeError. Errors now
propagate with their real type and message."""
from youtube_transcript_api import YouTubeTranscriptApi
if hasattr(YouTubeTranscriptApi, "fetch"): # >= 1.0: instance API
rows = YouTubeTranscriptApi().fetch(video_id).to_raw_data()
else: # < 1.0: classmethod API
rows = YouTubeTranscriptApi.get_transcript(video_id)
return [{"start": round(x["start"], 2), "end": round(x["start"] + x.get("duration", 0), 2),
"text": x["text"]} for x in rows]
def transcribe(video_id: str, watchlist: list[str] | None = None) -> tuple[list[dict], str, str | None, str]:
"""Returns (segments, source, whisper_model_or_None, transcript_path). Whisper primary,
captions fallback. Raises only if BOTH paths fail (worker handles the retry)."""
watchlist = watchlist if watchlist is not None else config.watchlist()
os.makedirs(config.TRANSCRIPT_DIR, exist_ok=True)
segs, source, model = None, None, None
whisper_err = None
try:
with tempfile.TemporaryDirectory() as td:
wav = _download_audio(video_id, td)
if wav:
segs = _transcribe_whisper(wav, watchlist)
source, model = "whisper", config.WHISPER_MODEL
except Exception as exc: # noqa: BLE001 — fall through to captions
whisper_err = f"{type(exc).__name__}: {exc}"
print(f"[transcribe] whisper path failed for {video_id}: {whisper_err}")
if not segs:
try:
segs = _captions_fallback(video_id)
except Exception as exc: # noqa: BLE001 — report BOTH causes (worker retry/backoff)
raise RuntimeError(f"whisper path: {whisper_err or 'no audio file produced'}; "
f"captions: {type(exc).__name__}: {str(exc)[:500]}") from exc
source = "captions"
path = os.path.join(config.TRANSCRIPT_DIR, f"{video_id}.json")
with open(path, "w") as f:
json.dump({"video_id": video_id, "source": source, "whisper_model": model, "segments": segs}, f)
return segs, source, model, path