diff --git a/app.py b/app.py index e222316..6d95cc0 100644 --- a/app.py +++ b/app.py @@ -1482,7 +1482,8 @@ async def process_endpoint( clip_min_seconds: Optional[str] = Form(None), clip_max_seconds: 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) if not api_key: @@ -1507,6 +1508,7 @@ async def process_endpoint( clip_max_seconds = body.get("clip_max_seconds") auto_hook = body.get("auto_hook") auto_hook_style = body.get("auto_hook_style") + thumbnail_session_id = body.get("thumbnail_session_id") # Normalize output format (auto = keep pipeline default). if output_format not in ("vertical", "horizontal", "square"): @@ -1518,7 +1520,20 @@ async def process_endpoint( elif not isinstance(layouts, list): 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") # Completion callback: reject unsafe targets NOW (clear 400) — delivery @@ -1565,7 +1580,7 @@ async def process_endpoint( "ip": client_ip, "user_agent": user_agent, "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()) @@ -1636,6 +1651,24 @@ async def process_endpoint( # 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. 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: # Save uploaded file with size limit check. # basename() strips any path components from the client-supplied diff --git a/dashboard/src/App.jsx b/dashboard/src/App.jsx index 3cfc1cb..21abbc7 100644 --- a/dashboard/src/App.jsx +++ b/dashboard/src/App.jsx @@ -646,7 +646,9 @@ function App() { setStatus('processing'); setLogs(["Starting process..."]); 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); setProjectState(null); setNoSource(false); @@ -678,6 +680,16 @@ function App() { force_low_quality: forceLowQuality, ...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 { const formData = new FormData(); formData.append('file', data.payload); @@ -703,6 +715,9 @@ function App() { } setJobId(resData.job_id); + if (data.type === 'thumbnail_session') { + setProcessingMedia({ type: 'server', payload: `/api/source/${resData.job_id}` }); + } } catch (e) { if (e instanceof QuotaError) { @@ -1308,7 +1323,18 @@ function App() { )} {activeTab === 'thumbnails' && ( - + { + 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 */} diff --git a/dashboard/src/components/ThumbnailStudio.jsx b/dashboard/src/components/ThumbnailStudio.jsx index 80af66a..42abe76 100644 --- a/dashboard/src/components/ThumbnailStudio.jsx +++ b/dashboard/src/components/ThumbnailStudio.jsx @@ -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. // Only send X-Gemini-Key for self-host BYOK. apiFetch attaches the bearer token. const keyHeader = geminiApiKey ? { 'X-Gemini-Key': geminiApiKey } : {}; @@ -1087,6 +1087,16 @@ export default function ThumbnailStudio({ geminiApiKey, uploadPostKey, uploadUse PUBLISHED

Published successfully!

Your video is being uploaded to YouTube asynchronously.

+ {onCreateClips && sessionId && ( + + )} ) : (
diff --git a/main.py b/main.py index 5ccea2d..ec2a2a7 100644 --- a/main.py +++ b/main.py @@ -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('--format', type=str, default="auto", choices=["auto", "vertical", "horizontal", "square"], 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() output_format = args.format @@ -1594,10 +1596,25 @@ if __name__ == '__main__': # to Gemini vision (picks clips from the imagery instead of the speech). from transcribe_backends import NoAudioError transcript = None - try: - transcript = transcribe_video(input_video) - except NoAudioError as e: - print(f"🔇 {e} — switching to visual analysis.") + # Module handover (issue #68): another module already transcribed this + # exact source with the same backend, so reuse its output. Any problem + # with the file falls back to transcribing normally rather than failing. + 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) if transcript is not None: diff --git a/tests/test_process_handover.py b/tests/test_process_handover.py new file mode 100644 index 0000000..ee9f4a5 --- /dev/null +++ b/tests/test_process_handover.py @@ -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"