feat: hand the Thumbnail Studio video and transcript straight to the clip generator

Issue #68: publishing a video to YouTube from the Studio now offers
'create clips from this video'. /api/process accepts a
thumbnail_session_id, hardlinks the session's source under the job's
name (so /api/source, the clip editor and retention treat it like a
normal upload) and forwards the session's transcript via a new
main.py --transcript flag, so the pipeline skips a second Whisper pass.

Any problem with the forwarded transcript (missing file, no segments,
silent source) falls back to transcribing normally, and empty
transcripts are not forwarded at all. Contract pinned by six endpoint
tests plus a fallback case; verified end to end locally against the
running app (speech video: 'Reusing precomputed transcript (4
segments)' in the job log).
This commit is contained in:
juancarlos.cavero 2026-08-20 19:48:13 +02:00
parent d0e1f5adfd
commit e4792fd3b3
5 changed files with 247 additions and 10 deletions

39
app.py
View file

@ -1482,7 +1482,8 @@ async def process_endpoint(
clip_min_seconds: Optional[str] = Form(None), clip_min_seconds: Optional[str] = Form(None),
clip_max_seconds: Optional[str] = Form(None), clip_max_seconds: Optional[str] = Form(None),
auto_hook: Optional[str] = Form(None), auto_hook: Optional[str] = Form(None),
auto_hook_style: Optional[str] = Form(None) auto_hook_style: Optional[str] = Form(None),
thumbnail_session_id: Optional[str] = Form(None)
): ):
api_key = await resolve_gemini(request) api_key = await resolve_gemini(request)
if not api_key: if not api_key:
@ -1507,6 +1508,7 @@ async def process_endpoint(
clip_max_seconds = body.get("clip_max_seconds") clip_max_seconds = body.get("clip_max_seconds")
auto_hook = body.get("auto_hook") auto_hook = body.get("auto_hook")
auto_hook_style = body.get("auto_hook_style") auto_hook_style = body.get("auto_hook_style")
thumbnail_session_id = body.get("thumbnail_session_id")
# 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"):
@ -1518,7 +1520,20 @@ async def process_endpoint(
elif not isinstance(layouts, list): elif not isinstance(layouts, list):
layouts = [] layouts = []
if not url and not file: # Module handover (issue #68): reuse the Thumbnail Studio source video and
# its transcript so publishing to YouTube can flow straight into clip
# generation without re-uploading or re-transcribing.
thumb_session = None
if thumbnail_session_id and not url and not file:
thumb_session = thumbnail_sessions.get(thumbnail_session_id)
if not thumb_session:
raise HTTPException(status_code=404, detail="Thumbnail session not found or expired")
await _assert_job_owner(request, thumb_session)
src = thumb_session.get("video_path")
if not src or not os.path.exists(src):
raise HTTPException(status_code=404, detail="Source video for this session is no longer on disk")
if not url and not file and not thumb_session:
raise HTTPException(status_code=400, detail="Must provide URL or File") raise HTTPException(status_code=400, detail="Must provide URL or File")
# Completion callback: reject unsafe targets NOW (clear 400) — delivery # Completion callback: reject unsafe targets NOW (clear 400) — delivery
@ -1565,7 +1580,7 @@ async def process_endpoint(
"ip": client_ip, "ip": client_ip,
"user_agent": user_agent, "user_agent": user_agent,
"timestamp": time.time(), "timestamp": time.time(),
"source": "url" if url else "file", "source": "thumbnail_session" if thumb_session else ("url" if url else "file"),
} }
job_id = str(uuid.uuid4()) job_id = str(uuid.uuid4())
@ -1636,6 +1651,24 @@ async def process_endpoint(
# re-render path cuts new segments from it, and it ages out with the # re-render path cuts new segments from it, and it ages out with the
# rest of the job (retention window + OUTPUT_MAX_GB cap) either way. # rest of the job (retention window + OUTPUT_MAX_GB cap) either way.
cmd.extend(["-u", url, "--keep-original"]) cmd.extend(["-u", url, "--keep-original"])
elif thumb_session:
# Hardlink (or copy) the session's video under the job's name so source
# lookup, the clip editor and the preview treat it exactly like a normal
# upload; the transcript rides along so the pipeline skips Whisper.
src = thumb_session["video_path"]
input_path = os.path.join(UPLOAD_DIR, f"{job_id}_{os.path.basename(src)}")
try:
os.link(src, input_path)
except OSError:
shutil.copyfile(src, input_path)
cmd.extend(["-i", input_path])
# An empty transcript (e.g. a silent or music-only source) is not worth
# forwarding: main.py would reject it and retranscribe anyway.
if thumb_session.get("transcript_ready") and (thumb_session.get("transcript") or {}).get("segments"):
transcript_path = os.path.join(job_output_dir, "source_transcript.json")
with open(transcript_path, "w") as f:
json.dump(thumb_session["transcript"], f)
cmd.extend(["--transcript", transcript_path])
else: else:
# Save uploaded file with size limit check. # Save uploaded file with size limit check.
# basename() strips any path components from the client-supplied # basename() strips any path components from the client-supplied

View file

@ -646,7 +646,9 @@ function App() {
setStatus('processing'); setStatus('processing');
setLogs(["Starting process..."]); setLogs(["Starting process..."]);
setResults(null); setResults(null);
setProcessingMedia(data); // Studio handovers have no local media object; the preview switches to the
// backend-served source once the job id is known.
setProcessingMedia(data.type === 'thumbnail_session' ? null : data);
setQualityGate(null); setQualityGate(null);
setProjectState(null); setProjectState(null);
setNoSource(false); setNoSource(false);
@ -678,6 +680,16 @@ function App() {
force_low_quality: forceLowQuality, force_low_quality: forceLowQuality,
...Object.fromEntries(Object.entries(advanced).filter(([, v]) => v != null)), ...Object.fromEntries(Object.entries(advanced).filter(([, v]) => v != null)),
}); });
} else if (data.type === 'thumbnail_session') {
// Handover from Thumbnail Studio (issue #68): the video and transcript
// already live server-side, keyed by the Studio session.
headers['Content-Type'] = 'application/json';
body = JSON.stringify({
thumbnail_session_id: data.payload,
acknowledged: !!data.acknowledged,
output_format: data.outputFormat || 'auto',
...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);
@ -703,6 +715,9 @@ function App() {
} }
setJobId(resData.job_id); setJobId(resData.job_id);
if (data.type === 'thumbnail_session') {
setProcessingMedia({ type: 'server', payload: `/api/source/${resData.job_id}` });
}
} catch (e) { } catch (e) {
if (e instanceof QuotaError) { if (e instanceof QuotaError) {
@ -1308,7 +1323,18 @@ function App() {
)} )}
{activeTab === 'thumbnails' && ( {activeTab === 'thumbnails' && (
<ThumbnailStudio geminiApiKey={apiKey} uploadPostKey={uploadPostKey} uploadUserId={uploadUserId} managed={isManaged} /> <ThumbnailStudio
geminiApiKey={apiKey}
uploadPostKey={uploadPostKey}
uploadUserId={uploadUserId}
managed={isManaged}
onCreateClips={(sessionId) => {
setActiveTab('dashboard');
// The Studio source is the user's own upload, published to their
// own channel; the handover carries that same attestation.
handleProcess({ type: 'thumbnail_session', payload: sessionId, acknowledged: true });
}}
/>
)} )}
{/* View: Gallery */} {/* View: Gallery */}

View file

@ -70,7 +70,7 @@ function DragDropZone({ label, accept, onFile, file, onClear, icon }) {
); );
} }
export default function ThumbnailStudio({ geminiApiKey, uploadPostKey, uploadUserId, managed = false }) { export default function ThumbnailStudio({ geminiApiKey, uploadPostKey, uploadUserId, managed = false, onCreateClips = null }) {
// Managed (hosted plan): Gemini runs server-side via the bearer token, no BYOK key. // Managed (hosted plan): Gemini runs server-side via the bearer token, no BYOK key.
// Only send X-Gemini-Key for self-host BYOK. apiFetch attaches the bearer token. // Only send X-Gemini-Key for self-host BYOK. apiFetch attaches the bearer token.
const keyHeader = geminiApiKey ? { 'X-Gemini-Key': geminiApiKey } : {}; const keyHeader = geminiApiKey ? { 'X-Gemini-Key': geminiApiKey } : {};
@ -1087,6 +1087,16 @@ export default function ThumbnailStudio({ geminiApiKey, uploadPostKey, uploadUse
<span className="badge-ok">PUBLISHED</span> <span className="badge-ok">PUBLISHED</span>
<p className="text-sm lowercase font-medium text-ink">Published successfully!</p> <p className="text-sm lowercase font-medium text-ink">Published successfully!</p>
<p className="text-xs text-muted">Your video is being uploaded to YouTube asynchronously.</p> <p className="text-xs text-muted">Your video is being uploaded to YouTube asynchronously.</p>
{onCreateClips && sessionId && (
<button
onClick={() => onCreateClips(sessionId)}
className="btn-primary px-4 py-2 text-xs mt-1"
title="Send this video and its transcript to the clip generator"
>
<Video size={14} />
create clips from this video
</button>
)}
</div> </div>
) : ( ) : (
<div className="space-y-2"> <div className="space-y-2">

25
main.py
View file

@ -1515,6 +1515,8 @@ if __name__ == '__main__':
parser.add_argument('--skip-analysis', action='store_true', help="Skip AI analysis and convert the whole video.") parser.add_argument('--skip-analysis', action='store_true', help="Skip AI analysis and convert the whole video.")
parser.add_argument('--format', type=str, default="auto", choices=["auto", "vertical", "horizontal", "square"], parser.add_argument('--format', type=str, default="auto", choices=["auto", "vertical", "horizontal", "square"],
help="Output aspect: vertical/auto (9:16), horizontal (keep 16:9), square (1:1).") help="Output aspect: vertical/auto (9:16), horizontal (keep 16:9), square (1:1).")
parser.add_argument('--transcript', type=str,
help="Path to a precomputed transcript JSON (transcribe_media shape); skips transcription.")
args = parser.parse_args() args = parser.parse_args()
output_format = args.format output_format = args.format
@ -1594,10 +1596,25 @@ if __name__ == '__main__':
# to Gemini vision (picks clips from the imagery instead of the speech). # to Gemini vision (picks clips from the imagery instead of the speech).
from transcribe_backends import NoAudioError from transcribe_backends import NoAudioError
transcript = None transcript = None
try: # Module handover (issue #68): another module already transcribed this
transcript = transcribe_video(input_video) # exact source with the same backend, so reuse its output. Any problem
except NoAudioError as e: # with the file falls back to transcribing normally rather than failing.
print(f"🔇 {e} — switching to visual analysis.") if args.transcript:
try:
with open(args.transcript, 'r') as f:
transcript = json.load(f)
if not transcript.get('segments'):
raise ValueError("transcript has no segments")
print(f"⏩ Reusing precomputed transcript "
f"({len(transcript['segments'])} segments) — skipping transcription.")
except Exception as e:
print(f"⚠️ Could not use precomputed transcript ({e}) — transcribing normally.")
transcript = None
if transcript is None:
try:
transcript = transcribe_video(input_video)
except NoAudioError as e:
print(f"🔇 {e} — switching to visual analysis.")
# 4. Gemini Analysis (transcript-driven, or vision for silent videos) # 4. Gemini Analysis (transcript-driven, or vision for silent videos)
if transcript is not None: if transcript is not None:

View file

@ -0,0 +1,151 @@
"""HTTP tests for the Thumbnail Studio -> clip generator handover (issue #68).
Same conventions as test_rerender_endpoint.py: a real ASGI round-trip against
the imported app (BILLING_ENABLED=0 via conftest). The job is only ENQUEUED —
the worker never runs under ASGITransport (no lifespan) — so these tests own
the /api/process contract for `thumbnail_session_id`: session validation, the
hardlinked source under the job's name, the transcript file ridden along via
--transcript, and the attestation source.
"""
import asyncio
import json
import os
import httpx
import pytest
app_module = pytest.importorskip("app")
TRANSCRIPT = {
"text": "hello world again",
"language": "en",
"segments": [
{
"start": 0.0, "end": 60.0, "text": "hello world again",
"words": [
{"word": "hello", "start": 12.0, "end": 12.5},
{"word": "world", "start": 20.0, "end": 20.4},
{"word": "again", "start": 50.0, "end": 50.5},
],
},
],
}
def _post_process(json_body):
async def _do():
transport = httpx.ASGITransport(app=app_module.app)
async with httpx.AsyncClient(transport=transport,
base_url="http://testserver") as client:
return await client.post(
"/api/process", json=json_body,
headers={"X-Gemini-Key": "test-key"},
)
return asyncio.run(_do())
@pytest.fixture()
def dirs(tmp_path, monkeypatch):
out_root = tmp_path / "output"
up_root = tmp_path / "uploads"
out_root.mkdir()
up_root.mkdir()
monkeypatch.setattr(app_module, "OUTPUT_DIR", str(out_root))
monkeypatch.setattr(app_module, "UPLOAD_DIR", str(up_root))
return out_root, up_root
@pytest.fixture()
def session(dirs, monkeypatch):
"""A Thumbnail Studio session with its video on disk and a ready transcript."""
_, up_root = dirs
video = up_root / "thumb_sess1_source.mp4"
video.write_bytes(b"fake-video-bytes")
sess = {
"user_id": None,
"video_path": str(video),
"transcript_ready": True,
"transcript": TRANSCRIPT,
}
monkeypatch.setitem(app_module.thumbnail_sessions, "sess1", sess)
return sess
def _submitted_job(resp):
assert resp.status_code == 200, resp.text
job_id = resp.json()["job_id"]
return job_id, app_module.jobs[job_id]
def test_handover_links_source_and_transcript(dirs, session):
out_root, up_root = dirs
resp = _post_process({"thumbnail_session_id": "sess1", "acknowledged": True})
job_id, job = _submitted_job(resp)
cmd = job["cmd"]
# Source: hardlinked under the job's name so /api/source, the clip editor
# and retention treat it exactly like a normal upload.
input_path = cmd[cmd.index("-i") + 1]
assert os.path.dirname(input_path) == str(up_root)
assert os.path.basename(input_path).startswith(job_id)
assert os.path.exists(input_path)
assert open(input_path, "rb").read() == b"fake-video-bytes"
# The original session file must still exist (link, not move).
assert os.path.exists(session["video_path"])
# Transcript: written into the job dir and passed via --transcript.
transcript_path = cmd[cmd.index("--transcript") + 1]
assert os.path.dirname(transcript_path) == str(out_root / job_id)
with open(transcript_path) as f:
assert json.load(f) == TRANSCRIPT
assert job["attestation"]["source"] == "thumbnail_session"
def test_handover_without_ready_transcript_still_processes(dirs, session):
session["transcript_ready"] = False
session["transcript"] = None
resp = _post_process({"thumbnail_session_id": "sess1", "acknowledged": True})
_, job = _submitted_job(resp)
assert "-i" in job["cmd"]
assert "--transcript" not in job["cmd"]
def test_empty_transcript_is_not_forwarded(dirs, session):
"""A silent/music-only source yields {"segments": []} — main.py would
reject it, so the endpoint must not bother writing it."""
session["transcript"] = {"text": "", "language": "en", "segments": []}
resp = _post_process({"thumbnail_session_id": "sess1", "acknowledged": True})
_, job = _submitted_job(resp)
assert "--transcript" not in job["cmd"]
def test_unknown_session_404s(dirs):
resp = _post_process({"thumbnail_session_id": "nope", "acknowledged": True})
assert resp.status_code == 404
def test_session_with_missing_video_404s(dirs, session):
os.remove(session["video_path"])
resp = _post_process({"thumbnail_session_id": "sess1", "acknowledged": True})
assert resp.status_code == 404
def test_handover_still_requires_attestation(dirs, session):
resp = _post_process({"thumbnail_session_id": "sess1"})
assert resp.status_code == 400
def test_url_wins_over_session_id(dirs, session, monkeypatch):
"""A request carrying both keeps the historical URL behavior untouched."""
monkeypatch.setattr(app_module, "QUALITY_GATE_MIN_HEIGHT", 0)
resp = _post_process({
"thumbnail_session_id": "sess1",
"url": "https://www.youtube.com/watch?v=dQw4w9WgXcQ",
"acknowledged": True,
})
_, job = _submitted_job(resp)
assert "-u" in job["cmd"]
assert "--transcript" not in job["cmd"]
assert job["attestation"]["source"] == "url"