);
}
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 } : {};
const needsKey = !geminiApiKey && !managed;
// Step management
const [step, setStep] = useState(0);
const [mode, setMode] = useState(null); // 'video' or 'manual'
// Step 1 state
const [videoFile, setVideoFile] = useState(null);
const [isAnalyzing, setIsAnalyzing] = useState(false);
// Step 2 state
const [sessionId, setSessionId] = useState(null);
const [titles, setTitles] = useState([]);
const [selectedTitle, setSelectedTitle] = useState('');
const [manualTitle, setManualTitle] = useState('');
const [chatInput, setChatInput] = useState('');
const [chatHistory, setChatHistory] = useState([]);
const [isRefining, setIsRefining] = useState(false);
const [recommended, setRecommended] = useState([]); // [{index, reason}]
const [thumbnailTexts, setThumbnailTexts] = useState([]); // hook text paired with each title
// Step 3 state
const [faceImage, setFaceImage] = useState(null);
const [bgImage, setBgImage] = useState(null);
const [extraPrompt, setExtraPrompt] = useState('');
const [thumbnailCount, setThumbnailCount] = useState(3);
const [burnText, setBurnText] = useState(true); // crisp PIL text vs model-rendered text
const [frames, setFrames] = useState(null); // null = not fetched yet
const [framesLoading, setFramesLoading] = useState(false);
const [selectedFrame, setSelectedFrame] = useState(null);
const [isGenerating, setIsGenerating] = useState(false);
const [generatedThumbnails, setGeneratedThumbnails] = useState([]);
// Description state
const [description, setDescription] = useState('');
const [isDescribing, setIsDescribing] = useState(false);
// Step 4 (Publish) state
const [selectedThumbnail, setSelectedThumbnail] = useState(null);
const [isPublishing, setIsPublishing] = useState(false);
const [publishResult, setPublishResult] = useState(null);
// Background preprocessing state
const [preprocessSessionId, setPreprocessSessionId] = useState(null);
const [isPreprocessing, setIsPreprocessing] = useState(false);
const chatEndRef = useRef(null);
const scrollToBottom = () => {
chatEndRef.current?.scrollIntoView({ behavior: 'smooth' });
};
// --- Background Pre-upload (starts Whisper immediately) ---
const handlePreUpload = async (file) => {
setPreprocessSessionId(null);
setIsPreprocessing(true);
try {
const formData = new FormData();
formData.append('file', file);
const res = await apiFetch('/api/thumbnail/upload', {
method: 'POST',
body: formData
});
if (res.ok) {
const data = await res.json();
setPreprocessSessionId(data.session_id);
console.log(`🎙️ Background Whisper started: ${data.session_id}`);
}
} catch (e) {
console.error('Pre-upload failed:', e);
} finally {
setIsPreprocessing(false);
}
};
// --- Step 1: Analyze Video ---
const handleAnalyze = async () => {
if (needsKey) return alert('Please set your Gemini API key in Settings first.');
setIsAnalyzing(true);
try {
const formData = new FormData();
if (preprocessSessionId) {
// Use pre-uploaded session (Whisper already running/done in background)
formData.append('session_id', preprocessSessionId);
} else if (videoFile) {
formData.append('file', videoFile);
} else {
return alert('Please upload a video file.');
}
const res = await apiFetch('/api/thumbnail/analyze', {
method: 'POST',
headers: keyHeader,
body: formData
});
if (!res.ok) {
const err = await res.text();
throw new Error(err);
}
const data = await res.json();
setSessionId(data.session_id);
setTitles(data.titles || []);
setThumbnailTexts(data.thumbnail_texts || []);
setRecommended(data.recommended || []);
setChatHistory([{
role: 'assistant',
content: `Here are 10 viral title suggestions based on your video. Titles marked TOP PICK are my top picks. Click one to select it, or tell me how to refine them.`
}]);
setStep(1);
} catch (e) {
alert(`Analysis failed: ${e.message}`);
} finally {
setIsAnalyzing(false);
}
};
const handleManualMode = () => {
setMode('manual');
setStep(1);
};
// --- Step 2: Title Selection / Refinement ---
const handleSelectTitle = (title) => {
setSelectedTitle(title);
};
const handleConfirmTitle = () => {
if (mode === 'manual' && manualTitle) {
setSelectedTitle(manualTitle);
// Create session for manual mode
const newSessionId = sessionId || crypto.randomUUID();
setSessionId(newSessionId);
apiFetch('/api/thumbnail/titles', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...keyHeader
},
body: JSON.stringify({ title: manualTitle, session_id: newSessionId })
}).catch(() => { });
}
if (selectedTitle || (mode === 'manual' && manualTitle)) {
setStep(2);
}
};
const handleRefine = async () => {
if (!chatInput.trim() || !sessionId) return;
setIsRefining(true);
const userMsg = chatInput.trim();
setChatInput('');
setChatHistory(prev => [...prev, { role: 'user', content: userMsg }]);
try {
const res = await apiFetch('/api/thumbnail/titles', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...keyHeader
},
body: JSON.stringify({ session_id: sessionId, message: userMsg })
});
if (!res.ok) throw new Error(await res.text());
const data = await res.json();
setTitles(data.titles || []);
setThumbnailTexts(data.thumbnail_texts || []);
setRecommended([]);
setChatHistory(prev => [...prev, {
role: 'assistant',
content: `Here are refined titles based on your feedback. Click one to select it.`
}]);
setTimeout(scrollToBottom, 100);
} catch (e) {
setChatHistory(prev => [...prev, {
role: 'assistant',
content: `Failed to refine: ${e.message}`
}]);
} finally {
setIsRefining(false);
}
};
// --- Step 3: Generate Thumbnails ---
const handleGenerate = async () => {
if (needsKey) return alert('Please set your Gemini API key in Settings first.');
const finalTitle = selectedTitle || manualTitle;
if (!finalTitle) return alert('Please select or enter a title first.');
setIsGenerating(true);
setGeneratedThumbnails([]);
try {
const formData = new FormData();
formData.append('session_id', sessionId || 'manual');
formData.append('title', finalTitle);
formData.append('extra_prompt', extraPrompt);
formData.append('count', thumbnailCount);
formData.append('burn_text', burnText ? 'true' : 'false');
if (selectedFrame && !faceImage) formData.append('frame', selectedFrame);
if (faceImage) formData.append('face', faceImage);
if (bgImage) formData.append('background', bgImage);
const res = await apiFetch('/api/thumbnail/generate', {
method: 'POST',
headers: keyHeader,
body: formData
});
if (!res.ok) {
const errData = await res.json().catch(() => null);
throw new Error(errData?.detail || `Server error ${res.status}`);
}
const data = await res.json();
if (!data.thumbnails || data.thumbnails.length === 0) {
throw new Error('No thumbnails were generated. Your Gemini API key may not have access to image generation.');
}
setGeneratedThumbnails(data.thumbnails);
} catch (e) {
alert(`Generation failed: ${e.message}`);
} finally {
setIsGenerating(false);
}
};
// Frames with a big, sharp face from the uploaded video: one click replaces
// the face upload nobody makes. Fetched once when the generate step opens.
// `frames` is deliberately not a dependency: setting it inside the effect
// would re-run it and the cleanup would discard the response in flight.
const framesRequestedFor = useRef(null);
useEffect(() => {
if (step !== 2 || mode !== 'video' || !sessionId) return;
if (framesRequestedFor.current === sessionId) return;
framesRequestedFor.current = sessionId;
setFrames([]);
setFramesLoading(true);
apiFetch(`/api/thumbnail/frames/${sessionId}`)
.then(res => (res.ok ? res.json() : { frames: [] }))
.then(data => setFrames(data.frames || []))
.catch(() => setFrames([]))
.finally(() => setFramesLoading(false));
}, [step, mode, sessionId]);
const handleDownload = async (url) => {
try {
const response = await fetch(getApiUrl(url));
const blob = await response.blob();
const blobUrl = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = blobUrl;
a.download = url.split('/').pop() || 'thumbnail.png';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(blobUrl);
} catch {
// Fallback: open in new tab if fetch fails
window.open(getApiUrl(url), '_blank');
}
};
// --- Description Generation ---
const handleGenerateDescription = async () => {
if (needsKey) return alert('Please set your Gemini API key in Settings first.');
const finalTitle = selectedTitle || manualTitle;
if (!finalTitle) return alert('Please select a title first.');
if (!sessionId) return alert('No session available.');
setIsDescribing(true);
try {
const res = await apiFetch('/api/thumbnail/describe', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...keyHeader
},
body: JSON.stringify({ session_id: sessionId, title: finalTitle })
});
if (!res.ok) {
const err = await res.text();
throw new Error(err);
}
const data = await res.json();
setDescription(data.description || '');
} catch (e) {
alert(`Description generation failed: ${e.message}`);
} finally {
setIsDescribing(false);
}
};
// --- Publish to YouTube ---
const handlePublish = async () => {
if (!managed && (!uploadPostKey || !uploadUserId)) return alert('Please configure your Upload-Post API key and user in Settings first.');
const finalTitle = selectedTitle || manualTitle;
if (!finalTitle) return alert('No title selected.');
if (!selectedThumbnail) return alert('Please select a thumbnail first.');
if (!description) return alert('Please generate or write a description first.');
setIsPublishing(true);
setPublishResult(null);
try {
const formData = new FormData();
formData.append('session_id', sessionId);
formData.append('title', finalTitle);
formData.append('description', description);
formData.append('thumbnail_url', selectedThumbnail);
formData.append('api_key', uploadPostKey);
formData.append('user_id', uploadUserId);
// Submit the publish job — returns immediately with a publish_id
const res = await apiFetch('/api/thumbnail/publish', {
method: 'POST',
body: formData
});
if (!res.ok) {
const err = await res.text();
throw new Error(err);
}
const { publish_id } = await res.json();
// Poll for status every 2 seconds (upload can take minutes for large videos)
await new Promise((resolve, reject) => {
const interval = setInterval(async () => {
try {
const statusRes = await apiFetch(`/api/thumbnail/publish/status/${publish_id}`);
if (!statusRes.ok) { clearInterval(interval); reject(new Error('Status check failed')); return; }
const statusData = await statusRes.json();
if (statusData.status === 'done') {
clearInterval(interval);
setPublishResult({ success: true, data: statusData.result });
resolve();
} else if (statusData.status === 'failed') {
clearInterval(interval);
reject(new Error(statusData.error || 'Upload failed'));
}
// 'uploading' → keep polling
} catch (e) {
clearInterval(interval);
reject(e);
}
}, 2000);
});
} catch (e) {
setPublishResult({ success: false, error: e.message });
} finally {
setIsPublishing(false);
}
};
const handleReset = () => {
setStep(0);
setMode(null);
setVideoFile(null);
setSessionId(null);
setTitles([]);
setSelectedTitle('');
setManualTitle('');
setChatInput('');
setChatHistory([]);
setFaceImage(null);
setFrames(null);
framesRequestedFor.current = null;
setSelectedFrame(null);
setThumbnailTexts([]);
setBgImage(null);
setExtraPrompt('');
setGeneratedThumbnails([]);
setDescription('');
setIsDescribing(false);
setSelectedThumbnail(null);
setIsPublishing(false);
setPublishResult(null);
setPreprocessSessionId(null);
setIsPreprocessing(false);
setRecommended([]);
};
return (
{/* Header */}
06 · YOUTUBE STUDIO
YouTube Studio
{step > 0 && (
)}
Generate viral titles, AI thumbnails, descriptions and publish directly to YouTube
{/* Gemini API Key Warning (self-host BYOK only; managed uses server key) */}
{needsKey && (
Gemini API Key Required
YouTube Studio requires a Google Gemini API key to function. Please configure it in the Settings tab before using this feature. Gemini's free tier includes 1,500 requests per day.
{framesLoading ? 'Looking for sharp frames with a face...' : 'No usable face found in the video.'}
) : (
<>
{frames.map((f) => (
))}
{selectedFrame ? 'This frame is the person reference (a photo upload below overrides it).' : 'Pick a frame so the thumbnail shows you, not a stranger.'}
>
)}
)}
FACE IMAGE · OPTIONAL
setFaceImage(null)}
icon={Upload}
/>
BACKGROUND · OPTIONAL
setBgImage(null)}
icon={Image}
/>
INSTRUCTIONS · OPTIONAL
TEXT ON THUMBNAIL
{burnText ? 'Text is set in a bold font after the image is painted: always spelled right.' : 'The image model paints the text itself: more integrated, sometimes misspelled.'}
COUNT
({ value: n, label: String(n) }))}
value={thumbnailCount}
onChange={setThumbnailCount}
size="sm"
/>
{/* Right: Generated Thumbnails */}
{generatedThumbnails.length > 0 ? (
Generated Thumbnails — click to select for publishing