feat(generate): manual clip count and duration controls (discussion #65)
/api/process (and the process_video MCP tool) now accept optional target_clips (1-15) and clip_min_seconds / clip_max_seconds (5-180), surfaced in the dashboard as a collapsed 'advanced options' section. Blank means the AI decides, keeping the default request byte-identical. Plumbed through the same env overrides the A/B harness already reads: CLIP_TARGET_MIN/MAX (existing) and a new clip_duration_bounds() in clip_selection.py backing CLIP_MIN_SECONDS/MAX_SECONDS. The detail and visual prompts take the band as template placeholders instead of the hardcoded 15-60, and word-snapping enforces the same bounds. All three knobs are honest targets, not guarantees: the model still returns fewer clips when the material doesn't hold them, and the UI copy says so. Verified live: target_clips=2 + band 8-15s on the demo video returned exactly 2 clips of 13.3s and 13.7s (the uncontrolled run gave one 41.7s clip); out-of-range values 400 with a named reason.
This commit is contained in:
parent
d1bf36c666
commit
b81125c572
9 changed files with 271 additions and 13 deletions
43
app.py
43
app.py
|
|
@ -1461,7 +1461,10 @@ async def process_endpoint(
|
||||||
layouts: Optional[str] = Form(None),
|
layouts: Optional[str] = Form(None),
|
||||||
force_low_quality: Optional[str] = Form(None),
|
force_low_quality: Optional[str] = Form(None),
|
||||||
webhook_url: Optional[str] = Form(None),
|
webhook_url: Optional[str] = Form(None),
|
||||||
webhook_secret: Optional[str] = Form(None)
|
webhook_secret: Optional[str] = Form(None),
|
||||||
|
target_clips: Optional[str] = Form(None),
|
||||||
|
clip_min_seconds: Optional[str] = Form(None),
|
||||||
|
clip_max_seconds: Optional[str] = Form(None)
|
||||||
):
|
):
|
||||||
api_key = await resolve_gemini(request)
|
api_key = await resolve_gemini(request)
|
||||||
if not api_key:
|
if not api_key:
|
||||||
|
|
@ -1481,6 +1484,9 @@ async def process_endpoint(
|
||||||
layouts = body.get("layouts")
|
layouts = body.get("layouts")
|
||||||
webhook_url = body.get("webhook_url")
|
webhook_url = body.get("webhook_url")
|
||||||
webhook_secret = body.get("webhook_secret")
|
webhook_secret = body.get("webhook_secret")
|
||||||
|
target_clips = body.get("target_clips")
|
||||||
|
clip_min_seconds = body.get("clip_min_seconds")
|
||||||
|
clip_max_seconds = body.get("clip_max_seconds")
|
||||||
|
|
||||||
# Normalize output format (auto = keep pipeline default).
|
# Normalize output format (auto = keep pipeline default).
|
||||||
if output_format not in ("vertical", "horizontal", "square"):
|
if output_format not in ("vertical", "horizontal", "square"):
|
||||||
|
|
@ -1559,6 +1565,41 @@ async def process_endpoint(
|
||||||
if chosen:
|
if chosen:
|
||||||
print(f"[layouts] job={job_id} enabled={sorted(chosen)}")
|
print(f"[layouts] job={job_id} enabled={sorted(chosen)}")
|
||||||
|
|
||||||
|
# Manual generation controls (discussion #65): optional clip-count target
|
||||||
|
# and duration band, forwarded to the selection prompts via the same env
|
||||||
|
# overrides the A/B harness already reads (clip_selection.py). All three
|
||||||
|
# are honest TARGETS, not guarantees — the model may return fewer clips
|
||||||
|
# when the material doesn't hold them. Bad values 400 instead of silently
|
||||||
|
# producing something the user didn't ask for.
|
||||||
|
def _gen_control(raw, name, lo, hi, integer=False):
|
||||||
|
if raw in (None, ""):
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
val = float(raw)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
raise HTTPException(status_code=400, detail=f"{name} must be a number")
|
||||||
|
if integer and val != int(val):
|
||||||
|
raise HTTPException(status_code=400, detail=f"{name} must be an integer")
|
||||||
|
if not (lo <= val <= hi):
|
||||||
|
raise HTTPException(status_code=400,
|
||||||
|
detail=f"{name} must be between {lo:g} and {hi:g}")
|
||||||
|
return int(val) if integer else val
|
||||||
|
|
||||||
|
n_clips = _gen_control(target_clips, "target_clips", 1, 15, integer=True)
|
||||||
|
min_secs = _gen_control(clip_min_seconds, "clip_min_seconds", 5, 175)
|
||||||
|
max_secs = _gen_control(clip_max_seconds, "clip_max_seconds", 10, 180)
|
||||||
|
if min_secs is not None and max_secs is not None and max_secs < min_secs + 5:
|
||||||
|
raise HTTPException(status_code=400,
|
||||||
|
detail="clip_max_seconds must be at least 5s above clip_min_seconds")
|
||||||
|
if n_clips is not None:
|
||||||
|
env["CLIP_TARGET_MIN"] = env["CLIP_TARGET_MAX"] = str(n_clips)
|
||||||
|
if min_secs is not None:
|
||||||
|
env["CLIP_MIN_SECONDS"] = str(min_secs)
|
||||||
|
if max_secs is not None:
|
||||||
|
env["CLIP_MAX_SECONDS"] = str(max_secs)
|
||||||
|
if n_clips is not None or min_secs is not None or max_secs is not None:
|
||||||
|
print(f"[gen-controls] job={job_id} clips={n_clips} band={min_secs}-{max_secs}")
|
||||||
|
|
||||||
input_path = None
|
input_path = None
|
||||||
if url:
|
if url:
|
||||||
# Keep the downloaded source inside the job dir: the clip editor's
|
# Keep the downloaded source inside the job dir: the clip editor's
|
||||||
|
|
|
||||||
|
|
@ -67,6 +67,30 @@ def clip_count_targets(n_windows):
|
||||||
return low, max(low, high)
|
return low, max(low, high)
|
||||||
|
|
||||||
|
|
||||||
|
def clip_duration_bounds():
|
||||||
|
"""The clip length band (seconds) the selection prompts and word-snapping
|
||||||
|
enforce. ``CLIP_MIN_SECONDS`` / ``CLIP_MAX_SECONDS`` override the classic
|
||||||
|
15-60 — set per job by /api/process when the user asks for a specific
|
||||||
|
length, or by hand for A/B runs. Values are clamped to platform-sane
|
||||||
|
limits and re-ordered so bad input degrades instead of breaking the job.
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
|
||||||
|
def _read(name, default):
|
||||||
|
try:
|
||||||
|
return float(os.environ.get(name, ""))
|
||||||
|
except ValueError:
|
||||||
|
return default
|
||||||
|
|
||||||
|
lo = _read("CLIP_MIN_SECONDS", 15.0)
|
||||||
|
hi = _read("CLIP_MAX_SECONDS", 60.0)
|
||||||
|
lo = min(max(lo, 5.0), 175.0)
|
||||||
|
hi = min(max(hi, 10.0), 180.0)
|
||||||
|
if hi < lo + 5.0: # keep a real band: degenerate ranges starve the model
|
||||||
|
hi = min(180.0, lo + 5.0)
|
||||||
|
return round(lo, 3), round(hi, 3)
|
||||||
|
|
||||||
|
|
||||||
def compact_words(words, precision=2):
|
def compact_words(words, precision=2):
|
||||||
"""Round word timestamps for prompts — full float precision wastes tokens."""
|
"""Round word timestamps for prompts — full float precision wastes tokens."""
|
||||||
return [
|
return [
|
||||||
|
|
|
||||||
|
|
@ -647,6 +647,14 @@ function App() {
|
||||||
// that apiFetch attaches automatically.
|
// that apiFetch attaches automatically.
|
||||||
const headers = apiKey ? { 'X-Gemini-Key': apiKey } : {};
|
const headers = apiKey ? { 'X-Gemini-Key': apiKey } : {};
|
||||||
|
|
||||||
|
// Advanced generation controls: only sent when the user set them, so the
|
||||||
|
// default request stays byte-identical to the pre-feature one.
|
||||||
|
const advanced = {
|
||||||
|
target_clips: data.targetClips || null,
|
||||||
|
clip_min_seconds: data.clipMinSeconds || null,
|
||||||
|
clip_max_seconds: data.clipMaxSeconds || null,
|
||||||
|
};
|
||||||
|
|
||||||
if (data.type === 'url') {
|
if (data.type === 'url') {
|
||||||
headers['Content-Type'] = 'application/json';
|
headers['Content-Type'] = 'application/json';
|
||||||
body = JSON.stringify({
|
body = JSON.stringify({
|
||||||
|
|
@ -654,12 +662,16 @@ function App() {
|
||||||
acknowledged: !!data.acknowledged,
|
acknowledged: !!data.acknowledged,
|
||||||
output_format: data.outputFormat || 'auto',
|
output_format: data.outputFormat || 'auto',
|
||||||
force_low_quality: forceLowQuality,
|
force_low_quality: forceLowQuality,
|
||||||
|
...Object.fromEntries(Object.entries(advanced).filter(([, v]) => v != null)),
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
const formData = new FormData();
|
const formData = new FormData();
|
||||||
formData.append('file', data.payload);
|
formData.append('file', data.payload);
|
||||||
formData.append('acknowledged', data.acknowledged ? 'true' : 'false');
|
formData.append('acknowledged', data.acknowledged ? 'true' : 'false');
|
||||||
formData.append('output_format', data.outputFormat || 'auto');
|
formData.append('output_format', data.outputFormat || 'auto');
|
||||||
|
for (const [k, v] of Object.entries(advanced)) {
|
||||||
|
if (v != null) formData.append(k, v);
|
||||||
|
}
|
||||||
body = formData;
|
body = formData;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
import React, { useState, useEffect, useRef } from 'react';
|
import React, { useState, useEffect, useRef } from 'react';
|
||||||
import { Link2, Upload, FileVideo, X, Info, Loader2 } from 'lucide-react';
|
import { Link2, Upload, FileVideo, X, Info, Loader2, ChevronDown } from 'lucide-react';
|
||||||
import { getApiUrl } from '../config';
|
import { getApiUrl } from '../config';
|
||||||
|
|
||||||
const SUPPORTED_PLATFORMS = [
|
const SUPPORTED_PLATFORMS = [
|
||||||
|
|
@ -16,6 +16,12 @@ export default function MediaInput({ onProcess, isProcessing }) {
|
||||||
const [acknowledged, setAcknowledged] = useState(false);
|
const [acknowledged, setAcknowledged] = useState(false);
|
||||||
const [outputFormat, setOutputFormat] = useState('vertical'); // vertical | horizontal | square
|
const [outputFormat, setOutputFormat] = useState('vertical'); // vertical | horizontal | square
|
||||||
const [showInfo, setShowInfo] = useState(false);
|
const [showInfo, setShowInfo] = useState(false);
|
||||||
|
// Advanced generation controls — empty string means "let the AI decide",
|
||||||
|
// which keeps the default pipeline behavior untouched.
|
||||||
|
const [showAdvanced, setShowAdvanced] = useState(false);
|
||||||
|
const [targetClips, setTargetClips] = useState('');
|
||||||
|
const [clipMinSeconds, setClipMinSeconds] = useState('');
|
||||||
|
const [clipMaxSeconds, setClipMaxSeconds] = useState('');
|
||||||
const infoRef = useRef(null);
|
const infoRef = useRef(null);
|
||||||
|
|
||||||
// Close the compatibility popover on any outside click.
|
// Close the compatibility popover on any outside click.
|
||||||
|
|
@ -58,10 +64,15 @@ export default function MediaInput({ onProcess, isProcessing }) {
|
||||||
const handleSubmit = (e) => {
|
const handleSubmit = (e) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
if (!acknowledged) return;
|
if (!acknowledged) return;
|
||||||
|
const advanced = {
|
||||||
|
targetClips: targetClips || null,
|
||||||
|
clipMinSeconds: clipMinSeconds || null,
|
||||||
|
clipMaxSeconds: clipMaxSeconds || null,
|
||||||
|
};
|
||||||
if (mode === 'url' && url) {
|
if (mode === 'url' && url) {
|
||||||
onProcess({ type: 'url', payload: url, acknowledged: true, outputFormat });
|
onProcess({ type: 'url', payload: url, acknowledged: true, outputFormat, ...advanced });
|
||||||
} else if (mode === 'file' && file) {
|
} else if (mode === 'file' && file) {
|
||||||
onProcess({ type: 'file', payload: file, acknowledged: true, outputFormat });
|
onProcess({ type: 'file', payload: file, acknowledged: true, outputFormat, ...advanced });
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
@ -210,6 +221,59 @@ export default function MediaInput({ onProcess, isProcessing }) {
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* Advanced generation controls — collapsed by default; blank = AI decides */}
|
||||||
|
<div className="mt-4">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setShowAdvanced((v) => !v)}
|
||||||
|
className="flex items-center gap-1.5 text-xs text-muted hover:text-ink2 lowercase transition-colors"
|
||||||
|
>
|
||||||
|
<ChevronDown size={14} className={`transition-transform ${showAdvanced ? 'rotate-180' : ''}`} />
|
||||||
|
advanced options
|
||||||
|
{(targetClips || clipMinSeconds || clipMaxSeconds) && (
|
||||||
|
<span className="text-brass">·</span>
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
{showAdvanced && (
|
||||||
|
<div className="mt-3 grid grid-cols-3 gap-2 animate-fade">
|
||||||
|
<div>
|
||||||
|
<p className="eyebrow mb-1.5">clips to aim for</p>
|
||||||
|
<input
|
||||||
|
type="number" min="1" max="15" step="1"
|
||||||
|
value={targetClips}
|
||||||
|
onChange={(e) => setTargetClips(e.target.value)}
|
||||||
|
placeholder="auto"
|
||||||
|
className="input-field"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<p className="eyebrow mb-1.5">min length (s)</p>
|
||||||
|
<input
|
||||||
|
type="number" min="5" max="175" step="1"
|
||||||
|
value={clipMinSeconds}
|
||||||
|
onChange={(e) => setClipMinSeconds(e.target.value)}
|
||||||
|
placeholder="15"
|
||||||
|
className="input-field"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<p className="eyebrow mb-1.5">max length (s)</p>
|
||||||
|
<input
|
||||||
|
type="number" min="10" max="180" step="1"
|
||||||
|
value={clipMaxSeconds}
|
||||||
|
onChange={(e) => setClipMaxSeconds(e.target.value)}
|
||||||
|
placeholder="60"
|
||||||
|
className="input-field"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<p className="col-span-3 text-[11px] leading-relaxed text-muted">
|
||||||
|
Targets, not guarantees: the AI returns fewer clips when the
|
||||||
|
material doesn't hold them. Leave blank to let it decide.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
<label className="flex items-start gap-2 mt-5 text-xs text-muted cursor-pointer select-none">
|
<label className="flex items-start gap-2 mt-5 text-xs text-muted cursor-pointer select-none">
|
||||||
<input
|
<input
|
||||||
type="checkbox"
|
type="checkbox"
|
||||||
|
|
|
||||||
|
|
@ -9,7 +9,8 @@ from google import genai
|
||||||
from google.genai import types as genai_types
|
from google.genai import types as genai_types
|
||||||
from pydantic import BaseModel
|
from pydantic import BaseModel
|
||||||
|
|
||||||
from clip_selection import clip_count_targets, lookup_model_prices
|
from clip_selection import (clip_count_targets, clip_duration_bounds,
|
||||||
|
lookup_model_prices)
|
||||||
|
|
||||||
load_dotenv()
|
load_dotenv()
|
||||||
|
|
||||||
|
|
@ -63,7 +64,7 @@ class VisualResponse(BaseModel):
|
||||||
|
|
||||||
VISUAL_PROMPT_TEMPLATE = """
|
VISUAL_PROMPT_TEMPLATE = """
|
||||||
You are a senior short-form video editor. This video has NO speech/audio — judge
|
You are a senior short-form video editor. This video has NO speech/audio — judge
|
||||||
it purely by what you SEE. Watch the whole thing and pick the 3–15 MOST engaging
|
it purely by what you SEE. Watch the whole thing and pick the {min_clips}–{max_clips} MOST engaging
|
||||||
visual moments for TikTok / Reels / Shorts (action, reveals, transformations,
|
visual moments for TikTok / Reels / Shorts (action, reveals, transformations,
|
||||||
striking or funny shots, satisfying payoffs, dramatic movement).
|
striking or funny shots, satisfying payoffs, dramatic movement).
|
||||||
|
|
||||||
|
|
@ -71,8 +72,8 @@ TIME CONTRACT — STRICT:
|
||||||
- Timestamps in ABSOLUTE SECONDS from the start (usable with ffmpeg -ss/-to).
|
- Timestamps in ABSOLUTE SECONDS from the start (usable with ffmpeg -ss/-to).
|
||||||
- Only numbers with up to 3 decimals (e.g. 0, 12.5, 47.250).
|
- Only numbers with up to 3 decimals (e.g. 0, 12.5, 47.250).
|
||||||
- 0 <= start < end <= {video_duration}.
|
- 0 <= start < end <= {video_duration}.
|
||||||
- Each clip 15 to 60 seconds long. If the whole video is shorter than 15s,
|
- Each clip {min_secs:g} to {max_secs:g} seconds long. If the whole video is
|
||||||
return one clip spanning the full video.
|
shorter than {min_secs:g}s, return one clip spanning the full video.
|
||||||
- Cut on visual scene changes, never mid-motion.
|
- Cut on visual scene changes, never mid-motion.
|
||||||
|
|
||||||
For each clip write catchy copy in {language} (a scroll-stopping hook, a TikTok
|
For each clip write catchy copy in {language} (a scroll-stopping hook, a TikTok
|
||||||
|
|
@ -241,7 +242,7 @@ Choose the BEST short clips from these shortlisted candidate windows.
|
||||||
|
|
||||||
CLIP RULES:
|
CLIP RULES:
|
||||||
- Return only valid JSON.
|
- Return only valid JSON.
|
||||||
- Each clip must be 15 to 60 seconds long, in absolute seconds from the start of the source video.
|
- Each clip must be {min_secs:g} to {max_secs:g} seconds long, in absolute seconds from the start of the source video.
|
||||||
- Stay within the candidate window boundaries.
|
- Stay within the candidate window boundaries.
|
||||||
- THE 2-SECOND RULE: the clip MUST open on its strongest moment. If the first
|
- THE 2-SECOND RULE: the clip MUST open on its strongest moment. If the first
|
||||||
2 seconds would not stop a cold viewer from scrolling, move the start or skip the clip.
|
2 seconds would not stop a cold viewer from scrolling, move the start or skip the clip.
|
||||||
|
|
@ -515,6 +516,7 @@ def main() -> int:
|
||||||
# derived from it would be meaningless — and the score template has no
|
# derived from it would be meaningless — and the score template has no
|
||||||
# placeholder for one anyway.
|
# placeholder for one anyway.
|
||||||
fmt["min_clips"], fmt["max_clips"] = clip_count_targets(len(payload.get("windows") or []))
|
fmt["min_clips"], fmt["max_clips"] = clip_count_targets(len(payload.get("windows") or []))
|
||||||
|
fmt["min_secs"], fmt["max_secs"] = clip_duration_bounds()
|
||||||
prompt = template.format(**fmt)
|
prompt = template.format(**fmt)
|
||||||
|
|
||||||
_log(f"🤖 Gemini worker request: mode={args.mode} strategy={args.strategy} model={model_name} items={len(payload.get('windows', []))}")
|
_log(f"🤖 Gemini worker request: mode={args.mode} strategy={args.strategy} model={model_name} items={len(payload.get('windows', []))}")
|
||||||
|
|
|
||||||
22
main.py
22
main.py
|
|
@ -23,7 +23,8 @@ from google.genai import types as genai_types
|
||||||
|
|
||||||
import gemini_worker
|
import gemini_worker
|
||||||
import layout_picker
|
import layout_picker
|
||||||
from clip_selection import build_transcript_windows, clip_count_targets, snap_clip_to_words
|
from clip_selection import (build_transcript_windows, clip_count_targets,
|
||||||
|
clip_duration_bounds, snap_clip_to_words)
|
||||||
from ffmpeg_utils import (video_encode_args, audio_encode_args, QUALITY,
|
from ffmpeg_utils import (video_encode_args, audio_encode_args, QUALITY,
|
||||||
QUALITY_FAST, METADATA_SCRUB)
|
QUALITY_FAST, METADATA_SCRUB)
|
||||||
from dotenv import load_dotenv
|
from dotenv import load_dotenv
|
||||||
|
|
@ -1275,9 +1276,11 @@ def get_viral_clips(transcript_result, video_duration):
|
||||||
# --- Pass 2: detailed clip extraction on the shortlist ---
|
# --- Pass 2: detailed clip extraction on the shortlist ---
|
||||||
payload = [{"id": w["id"], "start": w["start"], "end": w["end"], "text": w["text"]} for w in shortlist]
|
payload = [{"id": w["id"], "start": w["start"], "end": w["end"], "text": w["text"]} for w in shortlist]
|
||||||
min_clips, max_clips = clip_count_targets(len(shortlist))
|
min_clips, max_clips = clip_count_targets(len(shortlist))
|
||||||
|
min_secs, max_secs = clip_duration_bounds()
|
||||||
prompt = gemini_worker.DETAIL_PROMPT_TEMPLATE.format(
|
prompt = gemini_worker.DETAIL_PROMPT_TEMPLATE.format(
|
||||||
video_duration=video_duration, language=language,
|
video_duration=video_duration, language=language,
|
||||||
min_clips=min_clips, max_clips=max_clips,
|
min_clips=min_clips, max_clips=max_clips,
|
||||||
|
min_secs=min_secs, max_secs=max_secs,
|
||||||
windows_json=json.dumps(payload, ensure_ascii=False))
|
windows_json=json.dumps(payload, ensure_ascii=False))
|
||||||
detail, cost = _run_gemini_stage(client, model_name, prompt, gemini_worker.DetailResponse)
|
detail, cost = _run_gemini_stage(client, model_name, prompt, gemini_worker.DetailResponse)
|
||||||
if cost:
|
if cost:
|
||||||
|
|
@ -1286,7 +1289,8 @@ def get_viral_clips(transcript_result, video_duration):
|
||||||
shorts = detail.get("shorts") or []
|
shorts = detail.get("shorts") or []
|
||||||
# Snap each proposed clip onto real word boundaries (+ a bit of silence).
|
# Snap each proposed clip onto real word boundaries (+ a bit of silence).
|
||||||
for s in shorts:
|
for s in shorts:
|
||||||
ns, ne = snap_clip_to_words(s.get("start", 0), s.get("end", 0), words, video_duration)
|
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
|
s["start"], s["end"] = ns, ne
|
||||||
|
|
||||||
# Aggregate cost across both passes.
|
# Aggregate cost across both passes.
|
||||||
|
|
@ -1348,8 +1352,20 @@ def get_visual_clips(video_path, video_duration, language="en"):
|
||||||
return None
|
return None
|
||||||
time.sleep(2)
|
time.sleep(2)
|
||||||
|
|
||||||
|
# The vision path has no scoring windows to derive a count from, so the
|
||||||
|
# env targets (user request) apply directly over the classic 3-15.
|
||||||
|
def _env_int(name, default):
|
||||||
|
try:
|
||||||
|
return max(1, int(os.environ.get(name, "")))
|
||||||
|
except ValueError:
|
||||||
|
return default
|
||||||
|
v_min_clips = _env_int("CLIP_TARGET_MIN", 3)
|
||||||
|
v_max_clips = max(v_min_clips, _env_int("CLIP_TARGET_MAX", 15))
|
||||||
|
v_min_secs, v_max_secs = clip_duration_bounds()
|
||||||
prompt = gemini_worker.VISUAL_PROMPT_TEMPLATE.format(
|
prompt = gemini_worker.VISUAL_PROMPT_TEMPLATE.format(
|
||||||
video_duration=video_duration, language=language)
|
video_duration=video_duration, language=language,
|
||||||
|
min_clips=v_min_clips, max_clips=v_max_clips,
|
||||||
|
min_secs=v_min_secs, max_secs=v_max_secs)
|
||||||
config = genai_types.GenerateContentConfig(
|
config = genai_types.GenerateContentConfig(
|
||||||
response_mime_type="application/json",
|
response_mime_type="application/json",
|
||||||
response_schema=gemini_worker.VisualResponse,
|
response_schema=gemini_worker.VisualResponse,
|
||||||
|
|
|
||||||
|
|
@ -93,6 +93,20 @@ TOOLS = [
|
||||||
"type": "boolean",
|
"type": "boolean",
|
||||||
"description": "Set true to proceed after a needs_confirmation low-resolution warning.",
|
"description": "Set true to proceed after a needs_confirmation low-resolution warning.",
|
||||||
},
|
},
|
||||||
|
"target_clips": {
|
||||||
|
"type": "integer", "minimum": 1, "maximum": 15,
|
||||||
|
"description": "How many clips to aim for. A target, not a guarantee: "
|
||||||
|
"fewer come back when the material doesn't hold them. "
|
||||||
|
"Default: the AI decides (usually 2-6).",
|
||||||
|
},
|
||||||
|
"clip_min_seconds": {
|
||||||
|
"type": "number", "minimum": 5, "maximum": 175,
|
||||||
|
"description": "Minimum clip length in seconds (default 15).",
|
||||||
|
},
|
||||||
|
"clip_max_seconds": {
|
||||||
|
"type": "number", "minimum": 10, "maximum": 180,
|
||||||
|
"description": "Maximum clip length in seconds (default 60). Must be ≥ 5s above the minimum.",
|
||||||
|
},
|
||||||
},
|
},
|
||||||
"required": ["source_url", "confirm_rights"],
|
"required": ["source_url", "confirm_rights"],
|
||||||
},
|
},
|
||||||
|
|
@ -261,6 +275,9 @@ async def _tool_process_video(client, args):
|
||||||
"webhook_url": args.get("webhook_url"),
|
"webhook_url": args.get("webhook_url"),
|
||||||
"webhook_secret": args.get("webhook_secret"),
|
"webhook_secret": args.get("webhook_secret"),
|
||||||
}
|
}
|
||||||
|
for k in ("target_clips", "clip_min_seconds", "clip_max_seconds"):
|
||||||
|
if args.get(k) is not None:
|
||||||
|
body[k] = args[k]
|
||||||
resp = await client.post("/api/process", json=body)
|
resp = await client.post("/api/process", json=body)
|
||||||
if resp.status_code >= 400:
|
if resp.status_code >= 400:
|
||||||
return _api_error(resp), True
|
return _api_error(resp), True
|
||||||
|
|
|
||||||
|
|
@ -157,8 +157,9 @@ class TestDetailPromptCarriesTheCount:
|
||||||
low, high = clip_count_targets(5)
|
low, high = clip_count_targets(5)
|
||||||
prompt = gw.DETAIL_PROMPT_TEMPLATE.format(
|
prompt = gw.DETAIL_PROMPT_TEMPLATE.format(
|
||||||
video_duration=300, language="es", min_clips=low, max_clips=high,
|
video_duration=300, language="es", min_clips=low, max_clips=high,
|
||||||
windows_json="[]")
|
min_secs=15.0, max_secs=60.0, windows_json="[]")
|
||||||
assert f"return {low} to {high} clips" in prompt
|
assert f"return {low} to {high} clips" in prompt
|
||||||
|
assert "15 to 60 seconds" in prompt
|
||||||
# The JSON schema example legitimately keeps braces (they are {{ }} in
|
# The JSON schema example legitimately keeps braces (they are {{ }} in
|
||||||
# the template), so assert on unsubstituted placeholders specifically.
|
# the template), so assert on unsubstituted placeholders specifically.
|
||||||
assert re.findall(r"\{[a-z_]+\}", prompt) == []
|
assert re.findall(r"\{[a-z_]+\}", prompt) == []
|
||||||
|
|
|
||||||
81
tests/test_generation_controls.py
Normal file
81
tests/test_generation_controls.py
Normal file
|
|
@ -0,0 +1,81 @@
|
||||||
|
"""Unit tests for the manual generation controls (discussion #65): the
|
||||||
|
clip-duration band helper and the prompt templates it feeds.
|
||||||
|
|
||||||
|
Pure logic only — no API calls, no heavy imports (gemini_worker's templates are
|
||||||
|
read via ast so the ML stack never loads in CI).
|
||||||
|
"""
|
||||||
|
import ast
|
||||||
|
import os
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
import clip_selection
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(autouse=True)
|
||||||
|
def _clean_env(monkeypatch):
|
||||||
|
monkeypatch.delenv("CLIP_MIN_SECONDS", raising=False)
|
||||||
|
monkeypatch.delenv("CLIP_MAX_SECONDS", raising=False)
|
||||||
|
|
||||||
|
|
||||||
|
class TestClipDurationBounds:
|
||||||
|
def test_defaults_are_the_classic_band(self):
|
||||||
|
assert clip_selection.clip_duration_bounds() == (15.0, 60.0)
|
||||||
|
|
||||||
|
def test_env_overrides_apply(self, monkeypatch):
|
||||||
|
monkeypatch.setenv("CLIP_MIN_SECONDS", "20")
|
||||||
|
monkeypatch.setenv("CLIP_MAX_SECONDS", "30")
|
||||||
|
assert clip_selection.clip_duration_bounds() == (20.0, 30.0)
|
||||||
|
|
||||||
|
def test_clamped_to_platform_limits(self, monkeypatch):
|
||||||
|
monkeypatch.setenv("CLIP_MIN_SECONDS", "1")
|
||||||
|
monkeypatch.setenv("CLIP_MAX_SECONDS", "9999")
|
||||||
|
assert clip_selection.clip_duration_bounds() == (5.0, 180.0)
|
||||||
|
|
||||||
|
def test_degenerate_band_keeps_a_real_range(self, monkeypatch):
|
||||||
|
# max below min must widen, not invert or collapse.
|
||||||
|
monkeypatch.setenv("CLIP_MIN_SECONDS", "60")
|
||||||
|
monkeypatch.setenv("CLIP_MAX_SECONDS", "20")
|
||||||
|
lo, hi = clip_selection.clip_duration_bounds()
|
||||||
|
assert lo == 60.0 and hi >= lo + 5.0
|
||||||
|
|
||||||
|
def test_garbage_falls_back_to_defaults(self, monkeypatch):
|
||||||
|
monkeypatch.setenv("CLIP_MIN_SECONDS", "garbage")
|
||||||
|
monkeypatch.setenv("CLIP_MAX_SECONDS", "")
|
||||||
|
assert clip_selection.clip_duration_bounds() == (15.0, 60.0)
|
||||||
|
|
||||||
|
|
||||||
|
def _templates():
|
||||||
|
"""The prompt template constants, read without importing gemini_worker
|
||||||
|
(which pulls google-genai — absent in the thin CI env)."""
|
||||||
|
mod = ast.parse(open(os.path.join(os.path.dirname(__file__), "..",
|
||||||
|
"gemini_worker.py")).read())
|
||||||
|
return {
|
||||||
|
node.targets[0].id: node.value.value
|
||||||
|
for node in mod.body
|
||||||
|
if isinstance(node, ast.Assign) and isinstance(node.value, ast.Constant)
|
||||||
|
and isinstance(node.targets[0], ast.Name)
|
||||||
|
and node.targets[0].id.endswith("_PROMPT_TEMPLATE")
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class TestPromptTemplates:
|
||||||
|
def test_detail_template_carries_the_band(self):
|
||||||
|
text = _templates()["DETAIL_PROMPT_TEMPLATE"].format(
|
||||||
|
video_duration=100, language="es", min_clips=2, max_clips=4,
|
||||||
|
min_secs=10.0, max_secs=20.0, windows_json="[]")
|
||||||
|
assert "10 to 20 seconds" in text
|
||||||
|
assert "return 2 to 4 clips" in text
|
||||||
|
|
||||||
|
def test_visual_template_carries_band_and_count(self):
|
||||||
|
text = _templates()["VISUAL_PROMPT_TEMPLATE"].format(
|
||||||
|
video_duration=100, language="es", min_clips=2, max_clips=4,
|
||||||
|
min_secs=10.0, max_secs=20.0)
|
||||||
|
assert "2–4 MOST engaging" in text
|
||||||
|
assert "10 to 20 seconds" in text
|
||||||
|
|
||||||
|
def test_score_template_needs_no_new_keys(self):
|
||||||
|
# The scoring pass has no count/duration placeholders; formatting with
|
||||||
|
# only its classic keys must keep working.
|
||||||
|
_templates()["SCORE_PROMPT_TEMPLATE"].format(
|
||||||
|
video_duration=100, language="es", windows_json="[]")
|
||||||
Loading…
Reference in a new issue