Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 16 additions & 12 deletions backend/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -182,11 +182,15 @@ def _json_object_arg(raw: str | None, name: str):
return parsed


def _transcript_cache_engine(model_size: str | None = None) -> str:
def _transcript_cache_key(model_size: str | None = None) -> dict:
from presets import DEFAULT_PRESET
from services.transcription import resolve_engine_info

return resolve_engine_info(None, model_size or DEFAULT_PRESET["whisper_model"])["engine"]
return resolve_engine_info(None, model_size or DEFAULT_PRESET["whisper_model"])


def _transcript_cache_engine(model_size: str | None = None) -> str:
return _transcript_cache_key(model_size)["engine"]


def _cached_transcript(video_path: str) -> dict:
Expand Down Expand Up @@ -1469,15 +1473,15 @@ def cmd_process(args):
save_cached_transcript_for_video,
)

cache_engine = _transcript_cache_engine(config.get("whisper_model", "base"))
cache_key = _transcript_cache_key(config.get("whisper_model", "small"))

if skip_transcript:
# Reuse an existing transcript so highlight boundaries snap to whole sentences;
# only skip transcription outright when there is none (true no-dialogue footage).
cached = load_cached_transcript_for_video(
video_path,
engine=cache_engine,
model=config.get("whisper_model", "base"),
engine=cache_key["engine"],
model=cache_key["model_size"],
language=config.get("language"),
)
if cached and not config.get("no_cache", False):
Expand Down Expand Up @@ -1526,8 +1530,8 @@ def cmd_process(args):
# different one that happens to share the file.
cached = load_cached_transcript_for_video(
video_path,
engine=cache_engine,
model=config.get("whisper_model", "base"),
engine=cache_key["engine"],
model=cache_key["model_size"],
language=config.get("language"),
)
if cached and not config.get("no_cache", False):
Expand Down Expand Up @@ -1578,7 +1582,7 @@ def _transcribe_progress(pct, msg):
# and AssemblyAI decode the source themselves).
result = transcribe_file(
file_path=video_path,
model_size=config.get("whisper_model", "base"),
model_size=config.get("whisper_model", "small"),
engine=os.environ.get("PODCLI_ENGINE") or None,
language=config.get("language") or None,
enable_diarization=not config.get("no_speakers", False),
Expand All @@ -1601,8 +1605,8 @@ def _transcribe_progress(pct, msg):
save_cached_transcript_for_video(
video_path,
result,
engine=result.get("engine") or cache_engine,
model=config.get("whisper_model", "base"),
engine=result.get("engine") or cache_key["engine"],
model=result.get("model_size") or cache_key["model_size"],
language=config.get("language"),
)

Expand Down Expand Up @@ -5409,7 +5413,7 @@ def main():
help="Also build small playback proxies of each camera and a mic mix on the timeline")
mc_p.add_argument("--transcript", action="store_true",
help="Transcribe the episode with each word credited to whoever's mic was speaking")
mc_p.add_argument("--model", default="base", help="Whisper model for --transcript (default base)")
mc_p.add_argument("--model", default="small", help="Whisper model for --transcript (default small)")
mc_p.add_argument("--engine", choices=["whisper-py", "whispercpp", "assemblyai", "omnilingual"],
help="Transcription engine for --transcript (default: the one podcli is set up with)")
mc_p.add_argument("--activity", action="store_true", help="Report who speaks when (talk time, or spans with --json)")
Expand Down Expand Up @@ -5750,7 +5754,7 @@ def main():
cmp_p.add_argument("--start", type=float, default=0.0, help="Sample start, seconds into the source (default: 0)")
cmp_p.add_argument("--duration", type=float, default=120.0, help="Sample length in seconds (default: 120)")
cmp_p.add_argument("--window", type=float, default=20.0, help="Report window size in seconds (default: 20)")
cmp_p.add_argument("--model-size", default="base", help="Model size for engines that take one (default: base)")
cmp_p.add_argument("--model-size", default="small", help="Model size for engines that take one (default: small)")
cmp_p.add_argument("--language", help="ISO language code. Auto-detect if omitted.")
cmp_p.add_argument("-o", "--output", default="./engine-comparison", help="Output directory for comparison.json/.html")

Expand Down
2 changes: 1 addition & 1 deletion backend/clip_studio.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ def _transcribe(video: str, language: str | None, engine: str | None):
label = "AssemblyAI" if is_assemblyai_engine(engine or os.environ.get("PODCLI_ENGINE", "")) else "Whisper"
print(f" [transcribe] running {label}...", flush=True)
res = transcribe_file(
file_path=video, model_size="base", engine=engine, language=language,
file_path=video, model_size="small", engine=engine, language=language,
enable_diarization=False,
progress_callback=lambda p, m: print(f" {p}% {m}", flush=True),
)
Expand Down
10 changes: 5 additions & 5 deletions backend/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ def handle_resolve_transcribe_engine(task_id: str, params: dict):
emit_result(
task_id,
"success",
data=resolve_engine_info(params.get("engine"), params.get("model_size", "base")),
data=resolve_engine_info(params.get("engine"), params.get("model_size", "small")),
)


Expand All @@ -89,7 +89,7 @@ def handle_transcribe(task_id: str, params: dict):
emit_progress(task_id, "transcribing", 0, "Starting transcription...")
file_path = params["file_path"]
engine = params.get("engine")
model_size = params.get("model_size", "base")
model_size = params.get("model_size", "small")
language = params.get("language")
previous_engine = os.environ.get("PODCLI_ENGINE")
previous_assemblyai_key = os.environ.get("ASSEMBLYAI_API_KEY")
Expand Down Expand Up @@ -122,7 +122,7 @@ def handle_transcribe(task_id: str, params: dict):
try:
result = transcribe_file(
file_path=file_path,
model_size=params.get("model_size", "base"),
model_size=params.get("model_size", "small"),
engine=engine,
language=params.get("language"),
enable_diarization=params.get("enable_diarization", True),
Expand Down Expand Up @@ -163,7 +163,7 @@ def handle_transcribe(task_id: str, params: dict):
# Pulls energy data so the packed view includes peak moments for clip reasoning.
try:
cache_hash = compute_cache_hash(file_path) + cache_key_suffix(
engine=result.get("engine") or engine, model=model_size, language=language
engine=result.get("engine") or engine, model=result.get("model_size") or model_size, language=language
)
packed_path, packed_md = write_packed(
result,
Expand Down Expand Up @@ -1150,7 +1150,7 @@ def handle_compare_engines(task_id: str, params: dict):
start_seconds=params.get("start_seconds", 0.0) or 0.0,
duration_seconds=params.get("duration_seconds", 120.0) or 120.0,
window_seconds=params.get("window_seconds", 20.0) or 20.0,
model_size=params.get("model_size", "base"),
model_size=params.get("model_size", "small"),
language=params.get("language"),
output_dir=output_dir,
)
Expand Down
2 changes: 1 addition & 1 deletion backend/presets.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@
"video_path": "",
"transcript_path": "",
"output_dir": "",
"whisper_model": "base",
"whisper_model": "small",
"top_clips": 5,
"max_clip_duration": MAX_CLIP_DURATION,
"min_clip_duration": MIN_CLIP_DURATION,
Expand Down
47 changes: 29 additions & 18 deletions backend/services/claude_suggest.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,9 @@ def _load_existing_shorts(episodes_path: str) -> list[str]:
return shorts


DURATION_SLACK = 0.15


# (filename, max_chars) that reach the selection prompt, highest priority first.
# Shared with kb_signature so the suggestion cache and the prompt cannot drift.
class ClipBounds:
Expand Down Expand Up @@ -141,6 +144,9 @@ def of(cls, fmt=None, dur_min=None, dur_max=None) -> "ClipBounds":
def keeps(self, seconds: float) -> bool:
return self.dur_min <= seconds <= self.dur_max

def keeps_with_slack(self, seconds: float, slack: float = DURATION_SLACK) -> bool:
return self.dur_min * (1 - slack) <= seconds <= self.dur_max * (1 + slack)


KB_FILES = [
("04-shorts-creation-guide.md", 4000), # moment selection criteria, content types
Expand Down Expand Up @@ -225,6 +231,11 @@ def _sample_transcript(transcript_text: str, limit: int = CODEX_TRANSCRIPT_LIMIT
# truncation would have thrown away.
if lines[-1] not in sampled[-1:]:
sampled.append(lines[-1])
print(
f"Codex transcript sampled: dropped {len(lines) - len(sampled)} of {len(lines)} lines",
file=sys.stderr,
flush=True,
)
return "\n".join(sampled)


Expand Down Expand Up @@ -483,6 +494,10 @@ def _split_prompt_for_cache(prompt: str, transcript_text: str) -> tuple[str, str
return transcript_text, prompt[: -len(marker)]


FULL_PROMPT_CHAR_BUDGET = 400000
CANDIDATE_OVERSAMPLE = 2


def _build_transcript_text(segments: list[dict]) -> str:
"""Serialize transcript segments into the prompt-friendly text format."""
lines = []
Expand All @@ -505,22 +520,15 @@ def _segments_duration_seconds(segments: list[dict]) -> float:

def _should_bucket_initial_selection(segments: list[dict]) -> bool:
"""
Use bucketed AI search for long or dense transcripts.
Bucket the search only when the transcript text is too big for one prompt.

This keeps initial clip discovery from spending many minutes on a single
whole-episode prompt for long podcasts.
A single prompt lets the model compare moments across the whole episode,
so buckets are the fallback for transcripts past FULL_PROMPT_CHAR_BUDGET.
"""
if not segments:
return False

duration_seconds = _segments_duration_seconds(segments)
transcript_chars = sum(len(str(seg.get("text", ""))) for seg in segments)

return bool(
duration_seconds >= 45 * 60
or len(segments) >= 180
or transcript_chars >= 18000
)
return len(_build_transcript_text(segments)) > FULL_PROMPT_CHAR_BUDGET


def _dedupe_clips_by_range(clips: list[dict]) -> list[dict]:
Expand Down Expand Up @@ -898,7 +906,7 @@ def records(payload: object) -> list[dict]:
keep_segments = [{"start": start_sec, "end": end_sec}]

kept_duration = sum(seg["end"] - seg["start"] for seg in keep_segments)
if not bounds.keeps(kept_duration):
if not bounds.keeps_with_slack(kept_duration):
continue

clip_start = keep_segments[0]["start"] if keep_segments else start_sec
Expand Down Expand Up @@ -959,22 +967,25 @@ def suggest_initial_with_claude(
"""
Initial clip discovery entry point.

For long podcasts, search transcript buckets first so the AI can return
quickly and cover the full timeline instead of timing out on one giant
prompt.
The whole transcript goes in one prompt when it fits FULL_PROMPT_CHAR_BUDGET,
and the model is asked for twice as many candidates as needed so the final
cut ranks them against each other. Past the budget, every timeline bucket
is asked for the same number of candidates and one global ranking picks the
winners.
"""
exclude_clips = exclude_clips or []
if not _should_bucket_initial_selection(segments):
return suggest_with_claude(
candidates = suggest_with_claude(
segments=segments,
top_n=top_n,
top_n=top_n * CANDIDATE_OVERSAMPLE,
exclude_clips=exclude_clips,
progress_callback=progress_callback,
error_sink=error_sink,
timeout=180,
reaction_times=reaction_times,
bounds=bounds,
)
return _select_top_by_score(candidates, top_n) if candidates else None

start_bound = float(segments[0].get("start", 0))
end_bound = float(segments[-1].get("end", segments[-1].get("start", 0)))
Expand Down Expand Up @@ -1013,7 +1024,7 @@ def suggest_initial_with_claude(
progress_callback(0, f"Long episode detected: searching {len(buckets)} timeline buckets...")

aggregated: list[dict] = []
per_bucket_top_n = max(2, math.ceil(top_n / max(1, len(buckets))))
per_bucket_top_n = max(2, top_n)

for idx, bucket in enumerate(buckets):
bucket_label = (
Expand Down
2 changes: 1 addition & 1 deletion backend/services/engine_comparison.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ def compare_engines(
start_seconds: float = 0.0,
duration_seconds: Optional[float] = None,
window_seconds: float = 20.0,
model_size: str = "base",
model_size: str = "small",
language: Optional[str] = None,
output_dir: Optional[str] = None,
transcribe_fn=None,
Expand Down
2 changes: 1 addition & 1 deletion backend/services/multicam.py
Original file line number Diff line number Diff line change
Expand Up @@ -1878,7 +1878,7 @@ def build_preview(session: MulticamSession, progress_callback: ProgressCallback
return latest


def transcript(session: MulticamSession, *, model_size: str = "base", engine: Optional[str] = None,
def transcript(session: MulticamSession, *, model_size: str = "small", engine: Optional[str] = None,
language: Optional[str] = None, progress_callback: ProgressCallback = None) -> dict:
"""Words on the timeline, each credited to the person who said it.

Expand Down
2 changes: 1 addition & 1 deletion backend/services/multicam_cloud.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ def _request(method: str, path: str, body: Optional[dict] = None) -> dict:
raise MulticamCloudError(str(exc)) from None


def push(session: mc.MulticamSession, *, model_size: str = "base", engine: Optional[str] = None,
def push(session: mc.MulticamSession, *, model_size: str = "small", engine: Optional[str] = None,
progress_callback: ProgressCallback = None) -> mc.MulticamSession:
"""Builds what the editor plays, sends it, and remembers which cloud edit this session became."""
if not podcli_cloud.signed_in():
Expand Down
40 changes: 35 additions & 5 deletions backend/services/transcription.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,9 @@ def _whispercpp_cli() -> Optional[str]:
# builds); provisioning always fetches large-v3, so resolve the same way here.
_WHISPERCPP_MODEL_ALIASES = {"large": "large-v3"}

DEFAULT_MODEL_SIZE = "small"
FALLBACK_MODEL_SIZE = "base"


def _whispercpp_model(model_size: str) -> str:
resolved = _WHISPERCPP_MODEL_ALIASES.get(model_size, model_size)
Expand All @@ -66,8 +69,20 @@ def _whispercpp_model(model_size: str) -> str:
)


def resolve_whispercpp_model_size(model_size: str) -> str:
if (
model_size == DEFAULT_MODEL_SIZE
and not os.path.exists(_whispercpp_model(DEFAULT_MODEL_SIZE))
and os.path.exists(_whispercpp_model(FALLBACK_MODEL_SIZE))
):
return FALLBACK_MODEL_SIZE
return model_size


def _whispercpp_ready(model_size: str) -> bool:
return _whispercpp_cli() is not None and os.path.exists(_whispercpp_model(model_size))
return _whispercpp_cli() is not None and os.path.exists(
_whispercpp_model(resolve_whispercpp_model_size(model_size))
)


def _omnilingual_model() -> str:
Expand Down Expand Up @@ -125,6 +140,16 @@ def _default_whisper_threads() -> int:
def _transcribe_with_whispercpp(file_path, model_size, language, progress_callback, wav_path=None):
from services import transcription_whispercpp as wcpp

requested_size = model_size
model_size = resolve_whispercpp_model_size(model_size)
if model_size != requested_size:
print(
f"Whisper model '{requested_size}' is not installed, using '{model_size}' instead. "
f"Run `podcli setup --model {requested_size}` to download it.",
file=sys.stderr,
flush=True,
)

if progress_callback:
progress_callback(10, "Transcribing with whisper.cpp...")

Expand Down Expand Up @@ -684,23 +709,27 @@ def _resolve_whisper_py_fallback(requested: Optional[str], model_size: str, prob
return False, None, e


def resolve_engine_info(requested: Optional[str], model_size: str = "base") -> dict:
def resolve_engine_info(requested: Optional[str], model_size: str = DEFAULT_MODEL_SIZE) -> dict:
"""Predict which engine transcribe_file will actually use, without doing
any transcription work. Callers cache transcripts by engine; the cache
key has to match what transcribe_file resolves to, not the raw request,
or an unset engine writes under one key and reads under another.
"""
requested = requested if requested is not None else os.environ.get("PODCLI_ENGINE", "")
engine = normalize_engine(requested)
if engine == "whispercpp":
return {"engine": engine, "model_size": resolve_whispercpp_model_size(model_size)}
if engine != "whisper-py":
return {"engine": engine, "model_size": model_size}
fall_back, _model, _error = _resolve_whisper_py_fallback(requested, model_size, probe_model=False)
return {"engine": "whispercpp" if fall_back else "whisper-py", "model_size": model_size}
if fall_back:
return {"engine": "whispercpp", "model_size": resolve_whispercpp_model_size(model_size)}
return {"engine": "whisper-py", "model_size": model_size}


def transcribe_file(
file_path: str,
model_size: str = "base",
model_size: str = DEFAULT_MODEL_SIZE,
engine: Optional[str] = None,
language: Optional[str] = None,
enable_diarization: bool = True,
Expand Down Expand Up @@ -786,7 +815,7 @@ def transcribe_file(

def _transcribe_file_inner(
file_path: str,
model_size: str = "base",
model_size: str = DEFAULT_MODEL_SIZE,
engine: Optional[str] = None,
language: Optional[str] = None,
enable_diarization: bool = True,
Expand Down Expand Up @@ -844,6 +873,7 @@ def _transcribe_file_inner(
file_path, model_size, language, progress_callback, wav_path=wav_path
)
base["engine"] = "whispercpp"
base["model_size"] = resolve_whispercpp_model_size(model_size)
# whisper.cpp is the no-torch path: importing torch for diarization can
# hard-crash native runtimes. Skip diarization, keep face analysis (OpenCV).
# Never possible on this engine, see the omnilingual branch above.
Expand Down
Loading
Loading