diff --git a/.env.example b/.env.example
index a41727c..3a687cd 100644
--- a/.env.example
+++ b/.env.example
@@ -54,3 +54,14 @@ AWS_S3_PUBLIC_BUCKET=your-public-bucket-name
# visibly worse at titles.
GEMINI_MODEL_THUMBNAIL=gemini-3.7-flash
GEMINI_IMAGE_MODEL=gemini-3.1-flash-image
+
+# Moment picker on your own model instead of Gemini (self-host). Any
+# OpenAI-compatible chat endpoint: Ollama, LM Studio, vLLM, llama.cpp,
+# LocalAI, OpenRouter. With this set the Gemini key is optional; it is still
+# used, if present, for the frame-based stages (layout picker, silent videos).
+# Ollama needs a context above its 4096 default: OLLAMA_CONTEXT_LENGTH=16384.
+# LLM_BASE_URL=http://host.docker.internal:11434/v1
+# LLM_MODEL=qwen2.5:14b
+# LLM_API_KEY=
+# LLM_SCORE_BATCH=3
+# LLM_TIMEOUT=600
diff --git a/CLAUDE.md b/CLAUDE.md
index 40e2855..6ed4ded 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -120,6 +120,19 @@ Gemini era de las medidas continuas, no del modelo.
`layout_picker.apply()` sólo **añade**: una elección explícita del usuario nunca
se desactiva porque el modelo diga `none`.
+### Local LLM for the moment picker (`llm_backend.py`)
+
+`LLM_BASE_URL` (+ `LLM_MODEL`, `LLM_API_KEY`) routes the two transcript
+passes of `get_viral_clips` to any OpenAI-compatible `/chat/completions`
+instead of Gemini; the response is validated with the same pydantic schemas
+Gemini enforces server-side, so `main.py` sees one shape. `main.score_batch_size`
+drops to 3 windows per call there (local contexts are 4-8k; a truncated
+prompt scores garbage silently). Self-host `/api/process` then accepts a
+request without `X-Gemini-Key` and `/api/config.localLlm` tells the dashboard
+not to demand one. Frame-based stages (`layout_picker`, `screencast_layout`,
+`get_visual_clips`) stay on Gemini and degrade as they always did without a
+key. Never wired in cloud mode: `BILLING_ENABLED` ignores it.
+
### Thumbnail Studio (`thumbnail.py`, `/api/thumbnail/*`)
Titles come from the transcript plus 10 frames at 1024px, never the whole
diff --git a/README.md b/README.md
index f71e3ef..0d09568 100644
--- a/README.md
+++ b/README.md
@@ -82,6 +82,7 @@ All generated videos and avatars are saved to a public gallery with SEO pages fo
### Clip Generator
- **Viral Moment Detection**: Google Gemini 3.1 Flash-Lite analyzes transcripts and scene boundaries to detect 3-15 high-potential moments
+- **Runs fully local if you want**: point `LLM_BASE_URL` at Ollama, LM Studio, vLLM or any OpenAI-compatible server and the moment picker runs on your own model, no Google key needed (see [Run without a Google key](#6-run-without-a-google-key-local-llm-optional))
- **Smart 9:16 Cropping**: AI reframing per scene — TRACK mode (MediaPipe + YOLOv8 face tracking), GENERAL mode (blurred background), SPLIT mode (two speakers stacked, captions on the seam) and SCREENCAST mode (screen over presenter); the layout is picked per video by Gemini or forced from the dashboard
- **Auto Subtitles**: faster-whisper with word-level timestamps, styled and burned into clips
- **AI Voice Dubbing**: ElevenLabs integration for 30+ languages with voice cloning
@@ -163,6 +164,7 @@ Videos generated with OpenShorts AI Shorts — no camera, no studio, no actors:
| **Social auto-publishing** | Yes | Pro only | TikTok only | Paid only | Paid only | No |
| **Schedule uploads** | Yes | Pro only | No | Paid only | Paid only | No |
| **Data privacy** | **Your server** | Their cloud | Their cloud | Their cloud | Their cloud | Their cloud |
+| **Works with a local LLM (Ollama)** | **Yes** | No | No | No | No | No |
---
@@ -173,6 +175,7 @@ Self-hosting OpenShorts is free. You provide the machine and you only pay for th
| Service | Free Tier | Paid Cost | Used For |
|---------|-----------|-----------|----------|
| **Google Gemini** | Free trial with generous limits | < $0.01 per 10-min video | Viral moment detection, script generation, web research |
+| **Local LLM (Ollama, LM Studio, vLLM...)** | **Free, your hardware** | $0 | Viral moment detection instead of Gemini (`LLM_BASE_URL`) |
| **fal.ai** | Pay-per-use | ~$0.50-1.50 per AI Short | Actor generation, talking head video, lip-sync |
| **ElevenLabs** | Free tier available | Pay-per-use | Voiceover, voice dubbing |
| **Upload-Post** | **10 free uploads/month** to all networks (no credit card) | Pay-per-use | Auto-publishing to TikTok, Instagram, YouTube |
@@ -270,6 +273,35 @@ The backend log on the first job reports the chosen encoder and transcription de
---
+### 6. Run without a Google key (local LLM, optional)
+
+The only cloud call in the clip pipeline is the moment picker: it sends the
+transcript (never the video) to Gemini. Point it at any OpenAI-compatible
+server instead and the whole pipeline stays on your box:
+
+```bash
+# .env
+LLM_BASE_URL=http://host.docker.internal:11434/v1 # Ollama on the host
+LLM_MODEL=qwen2.5:14b # any chat model that follows instructions
+# LLM_API_KEY=... # only if your server checks one (vLLM --api-key, OpenRouter)
+```
+
+Works with Ollama, LM Studio, vLLM, llama.cpp server, LocalAI and OpenRouter.
+The dashboard stops asking for a Gemini key when this is set. Two things to
+know:
+
+- **Context length.** A scoring call carries three transcript windows
+ (~2-3k tokens) and the detail call up to ten (~5k on a long podcast).
+ Ollama defaults to a 4096-token context and truncates silently, so run it
+ with `OLLAMA_CONTEXT_LENGTH=16384` (or set `num_ctx` in a Modelfile); raise
+ `LLM_SCORE_BATCH` above 3 only if your context allows it. 7-8B models
+ return valid JSON reliably, 3B ones do not.
+- **What still needs Gemini.** Anything that has to look at frames: the
+ automatic layout picker (`AUTO_LAYOUT`), the on-screen content detector
+ and silent videos (no speech to clip by). Without a Gemini key those fall
+ back to the plain face-tracking crop, and a silent video fails with a
+ message that says so. Add a key alongside `LLM_BASE_URL` and you get both.
+
## Technical Pipeline
### Clip Generator
@@ -402,11 +434,15 @@ lives in [`examples/n8n/`](examples/n8n/).
| `AWS_S3_BUCKET` | Private bucket for clip backup |
| `AWS_S3_PUBLIC_BUCKET` | Public bucket for gallery/avatars |
| `MAX_CONCURRENT_JOBS` | Concurrent processing limit (default: 5) |
+| `LLM_BASE_URL` | OpenAI-compatible server for the moment picker (Ollama, vLLM, LM Studio...). Set it and the Gemini key becomes optional |
+| `LLM_MODEL` | Model name on that server (default `llama3.1:8b`) |
+| `LLM_API_KEY` | Bearer token for that server, if it checks one |
+| `LLM_SCORE_BATCH` | Transcript windows per scoring call (default 3 local, 8 Gemini) |
**Client-side (encrypted in localStorage):**
| Key | Description |
|-----|------------|
-| `GEMINI_API_KEY` | Google Gemini — required |
+| `GEMINI_API_KEY` | Google Gemini — required unless `LLM_BASE_URL` is set (then only for layout picking and silent videos) |
| `FAL_KEY` | fal.ai — required for AI Shorts |
| `ELEVENLABS_API_KEY` | ElevenLabs — required for voiceover/dubbing |
| `UPLOAD_POST_API_KEY` | Upload-Post — required, for social posting |
diff --git a/app.py b/app.py
index 174e7b4..9bc5b7b 100644
--- a/app.py
+++ b/app.py
@@ -1,4 +1,5 @@
import os
+import llm_backend
import re
import sys
import uuid
@@ -1880,6 +1881,9 @@ async def get_config():
"billingEnabled": BILLING_ENABLED,
"googleAuthEnabled": bool(BILLING_ENABLED and cloud.settings.google_auth_enabled),
"jobRetentionSeconds": JOB_RETENTION_SECONDS,
+ # Self-host only: tells the dashboard the Gemini key is optional
+ # because the moment picker runs on an OpenAI-compatible server.
+ "localLlm": None if BILLING_ENABLED else llm_backend.describe(),
}
async def _probe_youtube_quality(url: str) -> dict:
@@ -2117,7 +2121,11 @@ async def process_endpoint(
upload_id: Optional[str] = Form(None),
):
api_key = await resolve_gemini(request)
- if not api_key:
+ if not api_key and not (llm_backend.active() and not BILLING_ENABLED):
+ # Self-host with an OpenAI-compatible server configured needs no
+ # Google key for the core pipeline: the moment picker runs there and
+ # the frame-based stages degrade on their own (layout_picker returns
+ # "none", silent videos fail with a message that says why).
raise gemini_missing_error()
ack_flag = str(acknowledged).lower() in ("1", "true", "yes")
@@ -2241,7 +2249,10 @@ async def process_endpoint(
# probe above already gets this right.
cmd = [sys.executable, "-u", "main.py"] # -u for unbuffered
env = os.environ.copy()
- env["GEMINI_API_KEY"] = api_key # Override with key from request
+ if api_key:
+ env["GEMINI_API_KEY"] = api_key # Override with key from request
+ else:
+ env.pop("GEMINI_API_KEY", None) # local-LLM job: main.py must not find a stale key
# The stdio fix above only covers this process. main.py prints an emoji on
# its first line and configures nothing, so on a cp1252 console the child
# still dies before it renders anything -- the server starts and every job
diff --git a/dashboard/src/App.jsx b/dashboard/src/App.jsx
index 46de13f..92888fa 100644
--- a/dashboard/src/App.jsx
+++ b/dashboard/src/App.jsx
@@ -198,7 +198,7 @@ const pollJob = async (jobId) => {
function App() {
// Cloud auth/billing session (inert when billing is disabled).
- const { billingEnabled, isManaged, isSignedIn, me, plan, refreshMe, jobRetentionSeconds } = useAuth();
+ const { billingEnabled, isManaged, isSignedIn, me, plan, refreshMe, jobRetentionSeconds, localLlm } = useAuth();
const [showLogin, setShowLogin] = useState(false);
const [showTopUp, setShowTopUp] = useState(false);
const [showPlanChoice, setShowPlanChoice] = useState(false);
@@ -705,7 +705,10 @@ function App() {
// Hosted is paid-only (no BYOK core). Self-host uses BYOK keys.
// `keysMissing` now means "self-host BYOK keys missing" — it never fires on hosted.
- const keysMissing = !billingEnabled && (!apiKey || !uploadPostKey);
+ // A self-hosted server running the moment picker on a local LLM
+ // (LLM_BASE_URL) does not need a Gemini key for the core pipeline.
+ const geminiOk = !!apiKey || !!localLlm;
+ const keysMissing = !billingEnabled && (!geminiOk || !uploadPostKey);
const needsPlan = billingEnabled && !isManaged; // hosted, signed-out or no active plan/trial
// Fresh sign-up: show the welcome plan-choice popup once (AuthContext set the
@@ -1167,9 +1170,9 @@ function App() {
>
- {!apiKey && !uploadPostKey
+ {!geminiOk && !uploadPostKey
? 'Gemini & Upload-Post keys missing'
- : !apiKey
+ : !geminiOk
? 'Gemini API Key Missing'
: 'Upload-Post API Key Missing'}
@@ -1187,9 +1190,9 @@ function App() {
Required API keys missing.{' '}
- {!apiKey && !uploadPostKey
+ {!geminiOk && !uploadPostKey
? 'Set your Gemini and Upload-Post API keys to use OpenShorts.'
- : !apiKey
+ : !geminiOk
? 'Set your Gemini API key to use OpenShorts.'
: 'Set your Upload-Post API key to use OpenShorts.'}
@@ -1926,9 +1929,9 @@ function App() {
isOpen={showKeyModal}
onClose={() => setShowKeyModal(false)}
eyebrow="SETUP"
- title={!apiKey && !uploadPostKey
+ title={!geminiOk && !uploadPostKey
? 'Required API Keys Missing'
- : !apiKey
+ : !geminiOk
? 'Gemini API Key Required'
: 'Upload-Post API Key Required'}
footer={
diff --git a/dashboard/src/contexts/AuthContext.jsx b/dashboard/src/contexts/AuthContext.jsx
index 7487efa..70ec3cd 100644
--- a/dashboard/src/contexts/AuthContext.jsx
+++ b/dashboard/src/contexts/AuthContext.jsx
@@ -134,6 +134,7 @@ export function AuthProvider({ children }) {
const value = {
billingEnabled: config.billingEnabled,
+ localLlm: config.localLlm || null,
googleAuthEnabled: config.googleAuthEnabled,
jobRetentionSeconds: config.jobRetentionSeconds || null,
loading,
diff --git a/llm_backend.py b/llm_backend.py
new file mode 100644
index 0000000..4ba16da
--- /dev/null
+++ b/llm_backend.py
@@ -0,0 +1,165 @@
+"""Text-only LLM backend for the moment picker: any OpenAI-compatible server.
+
+Ollama, LM Studio, vLLM, llama.cpp's server, LocalAI and OpenRouter all speak
+``POST {base}/chat/completions``. When ``LLM_BASE_URL`` is set (or
+``LLM_PROVIDER=openai``), the transcript scoring and detail passes in
+``main.get_viral_clips`` go here instead of Gemini, so a self-hosted install
+can run the whole pipeline without a Google key.
+
+What stays on Gemini, because it needs a model that can look at frames or a
+video file: the layout picker (``layout_picker.py``), the on-screen content
+detector (``screencast_layout.py``) and the silent-video path
+(``main.get_visual_clips``). Without a Gemini key those degrade the way they
+already did: the first two return "none", the third fails the job with a clear
+message. Nothing in this module is imported by them.
+
+Structured output: the prompts already spell out the exact JSON shape, so a
+plain ``json_object`` mode is enough for most models. The request first asks
+for ``json_schema`` (Ollama, vLLM, llama.cpp and LM Studio enforce it); a
+server that rejects that field gets the same request again with
+``json_object``, then with no ``response_format`` at all. Whatever comes back
+is validated with the same pydantic model Gemini's ``response_schema`` uses,
+so ``main.py`` sees one shape regardless of provider.
+"""
+from __future__ import annotations
+
+import json
+import os
+from typing import Optional, Tuple, Type
+
+import httpx
+from pydantic import BaseModel
+
+DEFAULT_MODEL = "llama3.1:8b"
+DEFAULT_TIMEOUT = 600.0 # local models on CPU are slow; a scoring batch can take minutes
+
+
+def provider() -> str:
+ """``"openai"`` when a compatible endpoint is configured, else ``"gemini"``."""
+ explicit = (os.environ.get("LLM_PROVIDER") or "").strip().lower()
+ if explicit in ("openai", "ollama", "local", "openai-compatible"):
+ return "openai"
+ if explicit == "gemini":
+ return "gemini"
+ return "openai" if base_url() else "gemini"
+
+
+def base_url() -> str:
+ return (os.environ.get("LLM_BASE_URL") or "").strip().rstrip("/")
+
+
+def model_name() -> str:
+ return (os.environ.get("LLM_MODEL") or "").strip() or DEFAULT_MODEL
+
+
+def active() -> bool:
+ """True when the moment picker should call the OpenAI-compatible server."""
+ return provider() == "openai" and bool(base_url())
+
+
+def describe() -> Optional[dict]:
+ """What ``/api/config`` tells the dashboard, or ``None`` when inactive."""
+ if not active():
+ return None
+ return {"provider": "openai", "model": model_name(), "baseUrl": base_url()}
+
+
+def _timeout() -> float:
+ try:
+ return float(os.environ.get("LLM_TIMEOUT") or DEFAULT_TIMEOUT)
+ except ValueError:
+ return DEFAULT_TIMEOUT
+
+
+def _headers() -> dict:
+ # Ollama ignores the key but the OpenAI client convention (and vLLM with
+ # --api-key) wants the header present; "ollama" is the documented placeholder.
+ key = (os.environ.get("LLM_API_KEY") or "ollama").strip()
+ return {"Authorization": f"Bearer {key}", "Content-Type": "application/json"}
+
+
+def _client(**kwargs) -> httpx.Client:
+ """Factory so tests can swap in ``httpx.MockTransport``."""
+ return httpx.Client(timeout=_timeout(), **kwargs)
+
+
+def _response_formats(schema: Type[BaseModel]):
+ name = getattr(schema, "__name__", "response").lower()
+ yield {"type": "json_schema",
+ "json_schema": {"name": name, "schema": schema.model_json_schema()}}
+ yield {"type": "json_object"}
+ yield None
+
+
+def _is_format_rejection(resp: httpx.Response) -> bool:
+ if resp.status_code not in (400, 422):
+ return False
+ body = resp.text.lower()
+ return "response_format" in body or "json_schema" in body or "json_object" in body \
+ or "format" in body
+
+
+def generate_json(prompt: str, schema: Type[BaseModel], model: Optional[str] = None,
+ ) -> Tuple[dict, Optional[dict]]:
+ """One chat completion that must come back as JSON matching ``schema``.
+
+ Returns ``(parsed_dict, cost_analysis)`` in the exact shape
+ ``main._run_gemini_stage`` returns, so the caller does not branch on the
+ provider. Raises on HTTP errors, empty bodies and schema violations; the
+ retry policy lives in the caller, same as for Gemini.
+ """
+ import gemini_worker # local import: keeps this module free of the google SDK
+
+ url = f"{base_url()}/chat/completions"
+ model = model or model_name()
+ messages = [
+ {"role": "system", "content": "You answer with a single JSON object and nothing else."},
+ {"role": "user", "content": prompt},
+ ]
+ last_rejection: Optional[str] = None
+ with _client() as client:
+ for fmt in _response_formats(schema):
+ body = {"model": model, "messages": messages, "temperature": 0.2, "stream": False}
+ if fmt is not None:
+ body["response_format"] = fmt
+ resp = client.post(url, json=body, headers=_headers())
+ if fmt is not None and _is_format_rejection(resp):
+ # The server does not know this response_format flavour; the
+ # next loop iteration asks for a looser one.
+ last_rejection = resp.text[:200]
+ continue
+ if resp.status_code >= 400:
+ raise RuntimeError(
+ f"LLM server {resp.status_code} from {url}: {resp.text[:300]}")
+ data = resp.json()
+ break
+ else:
+ raise RuntimeError(
+ f"LLM server rejected every response_format variant: {last_rejection}")
+
+ choices = data.get("choices") or []
+ text = ""
+ if choices:
+ msg = choices[0].get("message") or {}
+ text = msg.get("content") or ""
+ if isinstance(text, list): # some servers return content parts
+ text = "".join(p.get("text", "") for p in text if isinstance(p, dict))
+ parsed = gemini_worker._parse_json_response_text(text)
+ # Validate against the same schema Gemini enforces server-side, so a
+ # local model that drops a field fails here with a readable error
+ # (retried by the caller) instead of deep inside the clip pipeline.
+ validated = schema.model_validate(parsed).model_dump()
+
+ usage = data.get("usage") or {}
+ cost = {
+ "input_tokens": int(usage.get("prompt_tokens") or 0),
+ "output_tokens": int(usage.get("completion_tokens") or 0),
+ "thinking_tokens": 0,
+ "input_cost": 0.0,
+ "output_cost": 0.0,
+ "total_cost": 0.0,
+ "model": model,
+ "price_estimated": False,
+ "local": True,
+ }
+ return validated, cost
diff --git a/main.py b/main.py
index 091d5fe..1a67df8 100644
--- a/main.py
+++ b/main.py
@@ -23,6 +23,7 @@ from google.genai import types as genai_types
import gemini_worker
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)
@@ -1440,15 +1441,24 @@ def transcribe_video(video_path):
return transcript
def _run_gemini_stage(client, model_name, prompt, schema):
- """One schema-enforced Gemini call with transient-error backoff.
- Returns (parsed_dict, cost_analysis)."""
- config = genai_types.GenerateContentConfig(
+ """One schema-enforced model call with transient-error backoff.
+ Returns (parsed_dict, cost_analysis).
+
+ With an OpenAI-compatible server configured (``llm_backend.active()``)
+ the call goes there instead of Gemini and ``client`` is unused; the
+ retry policy is shared because a local server has the same failure
+ shapes (connection refused while the model loads, a truncated body,
+ a 5xx from a busy vLLM)."""
+ use_local = llm_backend.active()
+ config = None if use_local else genai_types.GenerateContentConfig(
response_mime_type="application/json",
response_schema=schema,
)
max_attempts = 3
for attempt in range(1, max_attempts + 1):
try:
+ if use_local:
+ return llm_backend.generate_json(prompt, schema, model=model_name)
response = client.models.generate_content(model=model_name, contents=prompt, config=config)
# Policy blocks are deterministic — retrying only burns quota and
# time, and the user deserves the real reason instead of a generic
@@ -1473,11 +1483,16 @@ def _run_gemini_stage(client, model_name, prompt, schema):
'503', 'UNAVAILABLE', '429', 'RESOURCE_EXHAUSTED',
'500', 'INTERNAL', 'overloaded', 'Deadline',
'empty response body', 'did not contain a JSON object',
- 'Failed to parse Gemini JSON response'))
+ 'Failed to parse Gemini JSON response',
+ # OpenAI-compatible servers: model still loading, busy, or a
+ # small model that skipped a required field this time.
+ 'ConnectError', 'ReadTimeout', 'RemoteProtocolError', '502', '504',
+ 'validation error'))
if attempt == max_attempts or not transient:
raise
wait = 5 * (2 ** (attempt - 1))
- print(f"⚠️ Gemini transient error (attempt {attempt}/{max_attempts}), retrying in {wait}s: {msg[:150]}")
+ who = "LLM server" if use_local else "Gemini"
+ print(f"⚠️ {who} transient error (attempt {attempt}/{max_attempts}), retrying in {wait}s: {msg[:150]}")
time.sleep(wait)
@@ -1509,6 +1524,18 @@ def _run_stage_split(client, model_name, items, build_prompt, schema, key, costs
+ _run_stage_split(client, model_name, items[mid:], build_prompt, schema, key, costs, label))
+def score_batch_size():
+ """Transcript windows per scoring call: ``LLM_SCORE_BATCH`` if set, else
+ 8 for Gemini (1M context) and 3 for an OpenAI-compatible server."""
+ raw = os.environ.get("LLM_SCORE_BATCH", "").strip()
+ if raw:
+ try:
+ return max(1, int(raw))
+ except ValueError:
+ pass
+ return 3 if llm_backend.active() else 8
+
+
def get_viral_clips(transcript_result, video_duration):
"""Two-pass clip selection: score transcript windows, then detail the best.
@@ -1517,15 +1544,21 @@ def get_viral_clips(transcript_result, video_duration):
the expensive detail reasoning focused on the shortlist. Cuts are snapped to
word boundaries so clips don't start/end mid-word.
"""
- print("\U0001f916 Analyzing with Gemini (2-pass: score → detail)...")
- api_key = os.getenv("GEMINI_API_KEY")
- if not api_key:
- print("❌ Error: GEMINI_API_KEY not found in environment variables.")
- return None
-
- client = genai.Client(api_key=api_key)
- model_name = os.environ.get("GEMINI_MODEL") or 'gemini-3.1-flash-lite'
language = str(transcript_result.get('language') or 'unknown')
+ if llm_backend.active():
+ # Self-hosted text model: no Google key needed for this stage.
+ client = None
+ model_name = llm_backend.model_name()
+ print(f"\U0001f916 Analyzing with local LLM at {llm_backend.base_url()} (2-pass: score → detail)...")
+ else:
+ print("\U0001f916 Analyzing with Gemini (2-pass: score → detail)...")
+ api_key = os.getenv("GEMINI_API_KEY")
+ if not api_key:
+ print("❌ Error: GEMINI_API_KEY not found in environment variables "
+ "(set it, or point LLM_BASE_URL at an OpenAI-compatible server).")
+ return None
+ client = genai.Client(api_key=api_key)
+ model_name = os.environ.get("GEMINI_MODEL") or 'gemini-3.1-flash-lite'
print(f"\U0001f916 Model: {model_name} | language: {language}")
# Full word list — ground truth for snapping cut points.
@@ -1548,7 +1581,10 @@ def get_viral_clips(transcript_result, video_duration):
# --- Pass 1: score windows in batches, keep the highest-scoring ---
scored = []
- SCORE_BATCH = 8
+ # Local models usually run with a 4-8k context (Ollama defaults to
+ # 4096 unless OLLAMA_CONTEXT_LENGTH says otherwise) and 8 windows of
+ # transcript do not fit; a silently truncated prompt scores garbage.
+ SCORE_BATCH = score_batch_size()
def _payload(ws):
return [{"id": w["id"], "start": w["start"], "end": w["end"], "text": w["text"]} for w in ws]
@@ -1654,7 +1690,12 @@ def get_visual_clips(video_path, video_duration, language="en"):
print("🎥 Silent video — analyzing with Gemini vision (no transcript)...")
api_key = os.getenv("GEMINI_API_KEY")
if not api_key:
- print("❌ Error: GEMINI_API_KEY not found.")
+ if llm_backend.active():
+ print("❌ This video has no usable speech, so it has to be clipped by "
+ "watching it, and that needs Gemini (a text-only LLM server "
+ "cannot see the footage). Add a GEMINI_API_KEY for silent videos.")
+ else:
+ print("❌ Error: GEMINI_API_KEY not found.")
return None
client = genai.Client(api_key=api_key)
model_name = os.environ.get("GEMINI_MODEL") or 'gemini-3.1-flash-lite'
@@ -1885,7 +1926,7 @@ if __name__ == '__main__':
# wrote no metadata.json, so app.py marked the job failed anyway
# (app.py:1087) after burning GPU on a render nobody could see.
raise RuntimeError(
- "Clip detection failed — Gemini did not return usable clips for this video.")
+ "Clip detection failed — the AI model did not return usable clips for this video.")
else:
print(f"🔥 Found {len(clips_data['shorts'])} clips!")
diff --git a/tests/test_llm_backend.py b/tests/test_llm_backend.py
new file mode 100644
index 0000000..972bcb8
--- /dev/null
+++ b/tests/test_llm_backend.py
@@ -0,0 +1,151 @@
+"""The OpenAI-compatible moment-picker backend (llm_backend.py).
+
+Self-hosters asked for a pipeline that never calls Google. The transcript
+passes go to any /chat/completions server when LLM_BASE_URL is set; these
+tests pin the contract main.py relies on: same (parsed, cost) shape as the
+Gemini stage, schema validation, and the response_format fallback ladder.
+"""
+import json
+
+import httpx
+import pytest
+
+import gemini_worker
+import llm_backend
+
+
+@pytest.fixture
+def local(monkeypatch):
+ monkeypatch.setenv("LLM_BASE_URL", "http://llm.test/v1")
+ monkeypatch.setenv("LLM_MODEL", "qwen2.5:14b")
+ monkeypatch.delenv("LLM_PROVIDER", raising=False)
+
+
+def _serve(handler, monkeypatch):
+ """Route llm_backend's httpx client through an in-process handler."""
+ transport = httpx.MockTransport(handler)
+ monkeypatch.setattr(llm_backend, "_client",
+ lambda **kw: httpx.Client(transport=transport, **kw))
+
+
+def _completion(payload, usage=None):
+ return httpx.Response(200, json={
+ "choices": [{"message": {"role": "assistant", "content": json.dumps(payload)}}],
+ "usage": usage or {"prompt_tokens": 120, "completion_tokens": 40},
+ })
+
+
+# --- activation -----------------------------------------------------------
+
+def test_inactive_without_a_base_url(monkeypatch):
+ monkeypatch.delenv("LLM_BASE_URL", raising=False)
+ monkeypatch.delenv("LLM_PROVIDER", raising=False)
+ assert llm_backend.active() is False
+ assert llm_backend.describe() is None
+
+
+def test_base_url_alone_activates_and_describes(local):
+ assert llm_backend.active() is True
+ assert llm_backend.describe() == {
+ "provider": "openai", "model": "qwen2.5:14b", "baseUrl": "http://llm.test/v1"}
+
+
+def test_explicit_gemini_provider_wins_over_base_url(local, monkeypatch):
+ monkeypatch.setenv("LLM_PROVIDER", "gemini")
+ assert llm_backend.active() is False
+
+
+# --- generate_json ---------------------------------------------------------
+
+def test_returns_validated_payload_and_zero_cost(local, monkeypatch):
+ seen = {}
+
+ def handler(request):
+ seen["url"] = str(request.url)
+ seen["body"] = json.loads(request.content)
+ seen["auth"] = request.headers.get("authorization")
+ return _completion({"windows": [{"id": "w0", "start": 0, "end": 90, "score": 88, "reason": "hook"}]})
+
+ _serve(handler, monkeypatch)
+ parsed, cost = llm_backend.generate_json("prompt", gemini_worker.ScoreResponse)
+
+ assert seen["url"] == "http://llm.test/v1/chat/completions"
+ assert seen["body"]["model"] == "qwen2.5:14b"
+ assert seen["body"]["response_format"]["type"] == "json_schema"
+ assert seen["auth"] == "Bearer ollama" # documented placeholder when no key is set
+ assert parsed["windows"][0]["score"] == 88
+ assert cost["total_cost"] == 0.0 and cost["local"] is True
+ assert cost["input_tokens"] == 120 and cost["output_tokens"] == 40
+
+
+def test_falls_back_to_json_object_when_schema_mode_is_rejected(local, monkeypatch):
+ formats = []
+
+ def handler(request):
+ body = json.loads(request.content)
+ fmt = (body.get("response_format") or {}).get("type")
+ formats.append(fmt)
+ if fmt == "json_schema":
+ return httpx.Response(400, json={"error": {"message": "response_format json_schema not supported"}})
+ return _completion({"windows": []})
+
+ _serve(handler, monkeypatch)
+ parsed, _ = llm_backend.generate_json("prompt", gemini_worker.ScoreResponse)
+ assert formats == ["json_schema", "json_object"]
+ assert parsed == {"windows": []}
+
+
+def test_code_fenced_json_is_accepted(local, monkeypatch):
+ """Small models wrap the object in ```json fences even when told not to."""
+ def handler(request):
+ text = "```json\n" + json.dumps({"windows": []}) + "\n```"
+ return httpx.Response(200, json={"choices": [{"message": {"content": text}}], "usage": {}})
+
+ _serve(handler, monkeypatch)
+ parsed, _ = llm_backend.generate_json("prompt", gemini_worker.ScoreResponse)
+ assert parsed == {"windows": []}
+
+
+def test_schema_violation_raises_instead_of_leaking_into_the_pipeline(local, monkeypatch):
+ _serve(lambda r: _completion({"windows": [{"id": "w0"}]}), monkeypatch)
+ with pytest.raises(Exception) as exc:
+ llm_backend.generate_json("prompt", gemini_worker.ScoreResponse)
+ assert "validation error" in str(exc.value)
+
+
+def test_server_errors_surface_with_status_and_url(local, monkeypatch):
+ _serve(lambda r: httpx.Response(503, text="loading model"), monkeypatch)
+ with pytest.raises(RuntimeError) as exc:
+ llm_backend.generate_json("prompt", gemini_worker.ScoreResponse)
+ assert "503" in str(exc.value) and "loading model" in str(exc.value)
+
+
+# --- main.py routing (needs the heavy deps; skipped on minimal CI) ------------
+
+def test_stage_routes_to_local_backend_and_retries_transient(local, monkeypatch):
+ main = pytest.importorskip("main")
+ monkeypatch.setattr(main.time, "sleep", lambda *_: None)
+ calls = {"n": 0}
+
+ def fake_generate(prompt, schema, model=None):
+ calls["n"] += 1
+ if calls["n"] == 1:
+ raise httpx.ConnectError("ConnectError: connection refused")
+ return {"windows": [{"id": "w0", "start": 0, "end": 1, "score": 50, "reason": ""}]}, {"total_cost": 0.0}
+
+ monkeypatch.setattr(llm_backend, "generate_json", fake_generate)
+ parsed, cost = main._run_gemini_stage(None, "qwen2.5:14b", "prompt", gemini_worker.ScoreResponse)
+ assert calls["n"] == 2
+ assert parsed["windows"][0]["score"] == 50
+ assert cost["total_cost"] == 0.0
+
+
+def test_score_batch_shrinks_for_local_models(local, monkeypatch):
+ main = pytest.importorskip("main")
+ monkeypatch.delenv("LLM_SCORE_BATCH", raising=False)
+ assert main.score_batch_size() == 3
+ monkeypatch.setenv("LLM_SCORE_BATCH", "5")
+ assert main.score_batch_size() == 5
+ monkeypatch.delenv("LLM_BASE_URL")
+ monkeypatch.delenv("LLM_SCORE_BATCH")
+ assert main.score_batch_size() == 8