From b81125c572338f3faf9c738200c12023c5740b75 Mon Sep 17 00:00:00 2001 From: "juancarlos.cavero" Date: Tue, 18 Aug 2026 19:21:42 +0200 Subject: [PATCH] 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. --- app.py | 43 ++++++++++++- clip_selection.py | 24 ++++++++ dashboard/src/App.jsx | 12 ++++ dashboard/src/components/MediaInput.jsx | 70 ++++++++++++++++++++- gemini_worker.py | 12 ++-- main.py | 22 ++++++- mcp_server.py | 17 ++++++ tests/test_clip_selection.py | 3 +- tests/test_generation_controls.py | 81 +++++++++++++++++++++++++ 9 files changed, 271 insertions(+), 13 deletions(-) create mode 100644 tests/test_generation_controls.py diff --git a/app.py b/app.py index 8607f13..b03f05e 100644 --- a/app.py +++ b/app.py @@ -1461,7 +1461,10 @@ async def process_endpoint( layouts: Optional[str] = Form(None), force_low_quality: 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) if not api_key: @@ -1481,6 +1484,9 @@ async def process_endpoint( layouts = body.get("layouts") webhook_url = body.get("webhook_url") 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). if output_format not in ("vertical", "horizontal", "square"): @@ -1559,6 +1565,41 @@ async def process_endpoint( if 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 if url: # Keep the downloaded source inside the job dir: the clip editor's diff --git a/clip_selection.py b/clip_selection.py index 03b8c87..b0c4650 100644 --- a/clip_selection.py +++ b/clip_selection.py @@ -67,6 +67,30 @@ def clip_count_targets(n_windows): 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): """Round word timestamps for prompts — full float precision wastes tokens.""" return [ diff --git a/dashboard/src/App.jsx b/dashboard/src/App.jsx index aa9e4ef..76ef611 100644 --- a/dashboard/src/App.jsx +++ b/dashboard/src/App.jsx @@ -647,6 +647,14 @@ function App() { // that apiFetch attaches automatically. 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') { headers['Content-Type'] = 'application/json'; body = JSON.stringify({ @@ -654,12 +662,16 @@ function App() { acknowledged: !!data.acknowledged, output_format: data.outputFormat || 'auto', force_low_quality: forceLowQuality, + ...Object.fromEntries(Object.entries(advanced).filter(([, v]) => v != null)), }); } else { const formData = new FormData(); formData.append('file', data.payload); formData.append('acknowledged', data.acknowledged ? 'true' : 'false'); formData.append('output_format', data.outputFormat || 'auto'); + for (const [k, v] of Object.entries(advanced)) { + if (v != null) formData.append(k, v); + } body = formData; } diff --git a/dashboard/src/components/MediaInput.jsx b/dashboard/src/components/MediaInput.jsx index 41f71fe..743c4fa 100644 --- a/dashboard/src/components/MediaInput.jsx +++ b/dashboard/src/components/MediaInput.jsx @@ -1,5 +1,5 @@ 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'; const SUPPORTED_PLATFORMS = [ @@ -16,6 +16,12 @@ export default function MediaInput({ onProcess, isProcessing }) { const [acknowledged, setAcknowledged] = useState(false); const [outputFormat, setOutputFormat] = useState('vertical'); // vertical | horizontal | square 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); // Close the compatibility popover on any outside click. @@ -58,10 +64,15 @@ export default function MediaInput({ onProcess, isProcessing }) { const handleSubmit = (e) => { e.preventDefault(); if (!acknowledged) return; + const advanced = { + targetClips: targetClips || null, + clipMinSeconds: clipMinSeconds || null, + clipMaxSeconds: clipMaxSeconds || null, + }; 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) { - 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 }) { + {/* Advanced generation controls — collapsed by default; blank = AI decides */} +
+ + {showAdvanced && ( +
+
+

clips to aim for

+ setTargetClips(e.target.value)} + placeholder="auto" + className="input-field" + /> +
+
+

min length (s)

+ setClipMinSeconds(e.target.value)} + placeholder="15" + className="input-field" + /> +
+
+

max length (s)

+ setClipMaxSeconds(e.target.value)} + placeholder="60" + className="input-field" + /> +
+

+ Targets, not guarantees: the AI returns fewer clips when the + material doesn't hold them. Leave blank to let it decide. +

+
+ )} +
+