feat(youtube-studio): accept a cadence handoff bundle alongside the video (#11)
The Clip Generator already takes an optional cadence handoff ZIP and uses its edited transcript instead of Whisper. YouTube Studio now does the same: an optional `.zip` on the Analyze Video step rides along as a `handoff` field on POST /api/thumbnail/analyze. - `_read_handoff_transcript` stages the upload under the existing size cap and validates it with `_stage_handoff_bundle`, returning the edited transcript without importing the heavy pipeline. - `thumbnail_analyze` passes that transcript as the pre-transcript and skips the background Whisper wait/error path when a handoff is present; behavior is unchanged when it is not. - The video is still required for frames and publishing; the handoff only replaces transcription. - UI: optional handoff drop zone on Step 0, skipped early Whisper when a bundle is attached, and reset clears it. Reviewed-on: #11 Co-authored-by: pedro-bento <mail@pbento.pt> Co-committed-by: pedro-bento <mail@pbento.pt>
This commit is contained in:
parent
47add55c5f
commit
980dae98e8
3 changed files with 160 additions and 11 deletions
|
|
@ -11,6 +11,7 @@ import shutil
|
||||||
import glob
|
import glob
|
||||||
import time
|
import time
|
||||||
import zipfile
|
import zipfile
|
||||||
|
import tempfile
|
||||||
import itertools
|
import itertools
|
||||||
import functools
|
import functools
|
||||||
import asyncio
|
import asyncio
|
||||||
|
|
@ -2228,6 +2229,39 @@ def _stage_handoff_bundle(bundle_path, job_output_dir):
|
||||||
return manifest_path
|
return manifest_path
|
||||||
|
|
||||||
|
|
||||||
|
async def _read_handoff_transcript(handoff_file) -> dict:
|
||||||
|
"""Stage an uploaded cadence handoff ZIP and return its edited transcript.
|
||||||
|
|
||||||
|
Reads the upload into a throwaway dir under the existing size cap, validates
|
||||||
|
it with :func:`_stage_handoff_bundle` and returns the parsed
|
||||||
|
``source_transcript.json`` it stages. Any non-HTTP failure surfaces as a 400;
|
||||||
|
the temp dir is always removed. Deliberately avoids importing the heavy
|
||||||
|
pipeline so this path stays cheap.
|
||||||
|
"""
|
||||||
|
tmp_dir = tempfile.mkdtemp(prefix="thumb_handoff_")
|
||||||
|
try:
|
||||||
|
bundle_path = os.path.join(tmp_dir, "bundle.zip")
|
||||||
|
limit_bytes = MAX_FILE_SIZE_MB * 1024 * 1024
|
||||||
|
size = 0
|
||||||
|
with open(bundle_path, "wb") as out:
|
||||||
|
while chunk := await handoff_file.read(1024 * 1024):
|
||||||
|
size += len(chunk)
|
||||||
|
if limit_bytes and size > limit_bytes:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=413,
|
||||||
|
detail=f"Handoff bundle too large. Max size {MAX_FILE_SIZE_MB}MB")
|
||||||
|
out.write(chunk)
|
||||||
|
_stage_handoff_bundle(bundle_path, tmp_dir)
|
||||||
|
with open(os.path.join(tmp_dir, "source_transcript.json"), encoding="utf-8") as f:
|
||||||
|
return json.load(f)
|
||||||
|
except HTTPException:
|
||||||
|
raise
|
||||||
|
except Exception as e:
|
||||||
|
raise HTTPException(status_code=400, detail=f"Invalid handoff bundle: {e}")
|
||||||
|
finally:
|
||||||
|
shutil.rmtree(tmp_dir, ignore_errors=True)
|
||||||
|
|
||||||
|
|
||||||
def layout_env(requested):
|
def layout_env(requested):
|
||||||
"""Env overrides for the layouts this job allows. Unknown names are ignored
|
"""Env overrides for the layouts this job allows. Unknown names are ignored
|
||||||
rather than rejected: a newer dashboard must not break an older API.
|
rather than rejected: a newer dashboard must not break an older API.
|
||||||
|
|
@ -4920,6 +4954,7 @@ async def thumbnail_analyze(
|
||||||
url: Optional[str] = Form(None),
|
url: Optional[str] = Form(None),
|
||||||
session_id: Optional[str] = Form(None),
|
session_id: Optional[str] = Form(None),
|
||||||
channel: Optional[str] = Form(None),
|
channel: Optional[str] = Form(None),
|
||||||
|
handoff: Optional[UploadFile] = File(None),
|
||||||
x_gemini_key: Optional[str] = Header(None, alias="X-Gemini-Key")
|
x_gemini_key: Optional[str] = Header(None, alias="X-Gemini-Key")
|
||||||
):
|
):
|
||||||
"""Analyze a video and suggest viral YouTube titles."""
|
"""Analyze a video and suggest viral YouTube titles."""
|
||||||
|
|
@ -4930,6 +4965,11 @@ async def thumbnail_analyze(
|
||||||
# PLAN #1: resolve the channel before any download/upload so a bad slug
|
# PLAN #1: resolve the channel before any download/upload so a bad slug
|
||||||
# fails fast with a 400 instead of after the work.
|
# fails fast with a 400 instead of after the work.
|
||||||
profile = _channel_profile(channel)
|
profile = _channel_profile(channel)
|
||||||
|
|
||||||
|
# Optional cadence handoff bundle: when present its edited transcript
|
||||||
|
# replaces Whisper as the analysis input.
|
||||||
|
handoff_transcript = (
|
||||||
|
await _read_handoff_transcript(handoff) if handoff is not None else None)
|
||||||
pre_transcript = None
|
pre_transcript = None
|
||||||
|
|
||||||
# Check for pre-existing session with background Whisper
|
# Check for pre-existing session with background Whisper
|
||||||
|
|
@ -4937,21 +4977,25 @@ async def thumbnail_analyze(
|
||||||
session = thumbnail_sessions[session_id]
|
session = thumbnail_sessions[session_id]
|
||||||
await _assert_job_owner(request, session)
|
await _assert_job_owner(request, session)
|
||||||
|
|
||||||
# Wait for background Whisper to complete
|
if handoff_transcript is not None:
|
||||||
transcript_event = session.get("transcript_event")
|
pre_transcript = handoff_transcript
|
||||||
if transcript_event:
|
else:
|
||||||
print(f"⏳ [Thumbnail] Waiting for background Whisper to finish...")
|
# Wait for background Whisper to complete
|
||||||
await transcript_event.wait()
|
transcript_event = session.get("transcript_event")
|
||||||
|
if transcript_event:
|
||||||
|
print(f"⏳ [Thumbnail] Waiting for background Whisper to finish...")
|
||||||
|
await transcript_event.wait()
|
||||||
|
|
||||||
if session.get("transcript_error"):
|
if session.get("transcript_error"):
|
||||||
raise HTTPException(status_code=500, detail=f"Transcription failed: {session['transcript_error']}")
|
raise HTTPException(status_code=500, detail=f"Transcription failed: {session['transcript_error']}")
|
||||||
|
|
||||||
|
if session.get("transcript_ready"):
|
||||||
|
pre_transcript = session["transcript"]
|
||||||
|
|
||||||
video_path = session["video_path"]
|
video_path = session["video_path"]
|
||||||
if not video_path or not os.path.exists(video_path):
|
if not video_path or not os.path.exists(video_path):
|
||||||
raise HTTPException(status_code=404, detail="Video file not found in session")
|
raise HTTPException(status_code=404, detail="Video file not found in session")
|
||||||
|
|
||||||
if session.get("transcript_ready"):
|
|
||||||
pre_transcript = session["transcript"]
|
|
||||||
else:
|
else:
|
||||||
# No pre-existing session — need file or URL
|
# No pre-existing session — need file or URL
|
||||||
if not url and not file:
|
if not url and not file:
|
||||||
|
|
@ -4976,6 +5020,8 @@ async def thumbnail_analyze(
|
||||||
raise HTTPException(status_code=413, detail=f"File too large. Max size {MAX_FILE_SIZE_MB}MB")
|
raise HTTPException(status_code=413, detail=f"File too large. Max size {MAX_FILE_SIZE_MB}MB")
|
||||||
buffer.write(chunk)
|
buffer.write(chunk)
|
||||||
|
|
||||||
|
pre_transcript = handoff_transcript
|
||||||
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# Run analysis in thread pool (skips Whisper if pre_transcript is available)
|
# Run analysis in thread pool (skips Whisper if pre_transcript is available)
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
import { useState, useRef, useCallback, useEffect } from 'react';
|
import { useState, useRef, useCallback, useEffect } from 'react';
|
||||||
import { Upload, Image, Loader2, Send, Check, Download, ArrowRight, ArrowLeft, Sparkles, Video, Type, X, Plus, MessageSquare, FileText, Youtube, AlertCircle, Settings } from 'lucide-react';
|
import { Upload, Image, Loader2, Send, Check, Download, ArrowRight, ArrowLeft, Sparkles, Video, Type, X, Plus, MessageSquare, FileText, Youtube, AlertCircle, Settings, FileArchive } from 'lucide-react';
|
||||||
import { getApiUrl } from '../config';
|
import { getApiUrl } from '../config';
|
||||||
import { apiFetch } from '../lib/api';
|
import { apiFetch } from '../lib/api';
|
||||||
import StepIndicator from './ui/StepIndicator';
|
import StepIndicator from './ui/StepIndicator';
|
||||||
|
|
@ -80,6 +80,9 @@ export default function ThumbnailStudio({ geminiApiKey, postizKey, postizUrl, on
|
||||||
|
|
||||||
// Step 1 state
|
// Step 1 state
|
||||||
const [videoFile, setVideoFile] = useState(null);
|
const [videoFile, setVideoFile] = useState(null);
|
||||||
|
// Optional cadence handoff bundle: its edited transcript is used and the
|
||||||
|
// server skips Whisper. The video is still required for frames/publish.
|
||||||
|
const [handoffFile, setHandoffFile] = useState(null);
|
||||||
const [isAnalyzing, setIsAnalyzing] = useState(false);
|
const [isAnalyzing, setIsAnalyzing] = useState(false);
|
||||||
|
|
||||||
// Step 2 state
|
// Step 2 state
|
||||||
|
|
@ -160,8 +163,10 @@ export default function ThumbnailStudio({ geminiApiKey, postizKey, postizUrl, on
|
||||||
if (preprocessSessionId) {
|
if (preprocessSessionId) {
|
||||||
// Use pre-uploaded session (Whisper already running/done in background)
|
// Use pre-uploaded session (Whisper already running/done in background)
|
||||||
formData.append('session_id', preprocessSessionId);
|
formData.append('session_id', preprocessSessionId);
|
||||||
|
if (handoffFile) formData.append('handoff', handoffFile);
|
||||||
} else if (videoFile) {
|
} else if (videoFile) {
|
||||||
formData.append('file', videoFile);
|
formData.append('file', videoFile);
|
||||||
|
if (handoffFile) formData.append('handoff', handoffFile);
|
||||||
} else {
|
} else {
|
||||||
return alert('Please upload a video file.');
|
return alert('Please upload a video file.');
|
||||||
}
|
}
|
||||||
|
|
@ -443,6 +448,7 @@ export default function ThumbnailStudio({ geminiApiKey, postizKey, postizUrl, on
|
||||||
setStep(0);
|
setStep(0);
|
||||||
setMode(null);
|
setMode(null);
|
||||||
setVideoFile(null);
|
setVideoFile(null);
|
||||||
|
setHandoffFile(null);
|
||||||
setSessionId(null);
|
setSessionId(null);
|
||||||
setTitles([]);
|
setTitles([]);
|
||||||
setSelectedTitle('');
|
setSelectedTitle('');
|
||||||
|
|
@ -522,12 +528,26 @@ export default function ThumbnailStudio({ geminiApiKey, postizKey, postizUrl, on
|
||||||
<DragDropZone
|
<DragDropZone
|
||||||
label="Upload video file"
|
label="Upload video file"
|
||||||
accept="video/*"
|
accept="video/*"
|
||||||
onFile={(f) => { setVideoFile(f); setMode('video'); handlePreUpload(f); }}
|
onFile={(f) => { setVideoFile(f); setMode('video'); if (!handoffFile) handlePreUpload(f); }}
|
||||||
file={videoFile}
|
file={videoFile}
|
||||||
onClear={() => { setVideoFile(null); setPreprocessSessionId(null); }}
|
onClear={() => { setVideoFile(null); setPreprocessSessionId(null); }}
|
||||||
icon={Video}
|
icon={Video}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<DragDropZone
|
||||||
|
label="cadence handoff bundle (.zip, optional)"
|
||||||
|
accept=".zip,application/zip"
|
||||||
|
onFile={setHandoffFile}
|
||||||
|
file={handoffFile}
|
||||||
|
onClear={() => setHandoffFile(null)}
|
||||||
|
icon={FileArchive}
|
||||||
|
/>
|
||||||
|
<p className="text-xs lowercase text-muted mt-1.5">
|
||||||
|
uses the bundle's edited transcript, so transcription is skipped
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
{isPreprocessing && (
|
{isPreprocessing && (
|
||||||
<div className="flex items-center gap-2 text-xs lowercase text-muted bg-paper3 rounded-input px-3 py-2">
|
<div className="flex items-center gap-2 text-xs lowercase text-muted bg-paper3 rounded-input px-3 py-2">
|
||||||
<Loader2 size={12} className="animate-spin text-brass" />
|
<Loader2 size={12} className="animate-spin text-brass" />
|
||||||
|
|
|
||||||
83
tests/test_thumbnail_handoff.py
Normal file
83
tests/test_thumbnail_handoff.py
Normal file
|
|
@ -0,0 +1,83 @@
|
||||||
|
"""Thumbnail analyze cadence handoff ingest (server-side).
|
||||||
|
|
||||||
|
Exercises :func:`_read_handoff_transcript` directly: the multipart upload is
|
||||||
|
read into a throwaway dir, validated by ``_stage_handoff_bundle`` and its edited
|
||||||
|
transcript returned so titles/description can skip Whisper. The helper must not
|
||||||
|
pull in the heavy pipeline, so this module deliberately only imports the app.
|
||||||
|
"""
|
||||||
|
import asyncio
|
||||||
|
import io
|
||||||
|
import json
|
||||||
|
import zipfile
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from starlette.datastructures import UploadFile
|
||||||
|
|
||||||
|
app_module = pytest.importorskip("clipwright.api.app")
|
||||||
|
|
||||||
|
|
||||||
|
def _zip_bytes(entries):
|
||||||
|
buf = io.BytesIO()
|
||||||
|
with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
|
||||||
|
for name, data in entries.items():
|
||||||
|
zf.writestr(name, data)
|
||||||
|
return buf.getvalue()
|
||||||
|
|
||||||
|
|
||||||
|
def _manifest_bytes(transcript_ref="rec.transcript.json"):
|
||||||
|
return json.dumps({
|
||||||
|
"schema": "clipwright.handoff/1",
|
||||||
|
"transcript": {"path": transcript_ref},
|
||||||
|
"edited": {"duration": 2.0},
|
||||||
|
}).encode("utf-8")
|
||||||
|
|
||||||
|
|
||||||
|
def _transcript_bytes():
|
||||||
|
return json.dumps({
|
||||||
|
"text": "edited text",
|
||||||
|
"language": "en",
|
||||||
|
"segments": [{"start": 0.0, "end": 2.0, "text": "hi"}],
|
||||||
|
}).encode("utf-8")
|
||||||
|
|
||||||
|
|
||||||
|
def _upload(payload, filename="bundle.zip"):
|
||||||
|
return UploadFile(file=io.BytesIO(payload), filename=filename)
|
||||||
|
|
||||||
|
|
||||||
|
def _read(payload):
|
||||||
|
return asyncio.run(app_module._read_handoff_transcript(_upload(payload)))
|
||||||
|
|
||||||
|
|
||||||
|
def test_valid_bundle_returns_the_edited_transcript():
|
||||||
|
bundle = _zip_bytes({
|
||||||
|
"rec.handoff.json": _manifest_bytes(),
|
||||||
|
"rec.transcript.json": _transcript_bytes(),
|
||||||
|
})
|
||||||
|
|
||||||
|
transcript = _read(bundle)
|
||||||
|
|
||||||
|
assert transcript["language"] == "en"
|
||||||
|
assert transcript["segments"] == [{"start": 0.0, "end": 2.0, "text": "hi"}]
|
||||||
|
|
||||||
|
|
||||||
|
def test_non_zip_is_400():
|
||||||
|
with pytest.raises(app_module.HTTPException) as exc:
|
||||||
|
_read(b"this is not a zip")
|
||||||
|
assert exc.value.status_code == 400
|
||||||
|
assert "ZIP" in exc.value.detail
|
||||||
|
|
||||||
|
|
||||||
|
def test_zip_without_a_manifest_is_400():
|
||||||
|
bundle = _zip_bytes({"rec.transcript.json": _transcript_bytes()})
|
||||||
|
with pytest.raises(app_module.HTTPException) as exc:
|
||||||
|
_read(bundle)
|
||||||
|
assert exc.value.status_code == 400
|
||||||
|
assert "manifest" in exc.value.detail
|
||||||
|
|
||||||
|
|
||||||
|
def test_oversized_bundle_is_413(monkeypatch):
|
||||||
|
monkeypatch.setattr(app_module, "MAX_FILE_SIZE_MB", 1)
|
||||||
|
limit_bytes = app_module.MAX_FILE_SIZE_MB * 1024 * 1024
|
||||||
|
with pytest.raises(app_module.HTTPException) as exc:
|
||||||
|
_read(b"x" * (limit_bytes + 1))
|
||||||
|
assert exc.value.status_code == 413
|
||||||
Loading…
Reference in a new issue