From 3946c49ad17b95d6d586532c5e6a696997ee45d4 Mon Sep 17 00:00:00 2001 From: "juancarlos.cavero" Date: Fri, 20 Feb 2026 01:11:27 +0100 Subject: [PATCH] added youtube studio --- .env.example | 8 + .gitignore | 19 +- Dockerfile | 3 + app.py | 411 ++++++- dashboard/src/App.jsx | 16 +- dashboard/src/components/ThumbnailStudio.jsx | 1127 ++++++++++++++++++ dashboard/vite.config.js | 4 + main.py | 34 +- thumbnail.py | 319 +++++ 9 files changed, 1920 insertions(+), 21 deletions(-) create mode 100644 .env.example create mode 100644 dashboard/src/components/ThumbnailStudio.jsx create mode 100644 thumbnail.py diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..ae49394 --- /dev/null +++ b/.env.example @@ -0,0 +1,8 @@ +# AWS S3 (optional — for clip backup/gallery) +AWS_ACCESS_KEY_ID=your_aws_access_key_here +AWS_SECRET_ACCESS_KEY=your_aws_secret_key_here +AWS_REGION=eu-west-3 +AWS_S3_BUCKET=your-bucket-name + +# YouTube cookies (optional — paste Netscape-format cookies to bypass bot detection) +# YOUTUBE_COOKIES=... diff --git a/.gitignore b/.gitignore index 98b4320..cfcf3b4 100644 --- a/.gitignore +++ b/.gitignore @@ -12,17 +12,24 @@ __pycache__/ *.pyc -# Temporary files +# Temporary files / runtime dirs temp_* uploads/ +downloads/ +videos/ +output/ +# OS / IDE .DS_Store +.idea/ +.vscode/ +# Secrets .env + +# Generated metadata *_metadata.json -.cache - -.config - -output/ \ No newline at end of file +# Cache dirs +.cache/ +.config/ \ No newline at end of file diff --git a/Dockerfile b/Dockerfile index 2835ea6..95bfd1f 100644 --- a/Dockerfile +++ b/Dockerfile @@ -37,6 +37,9 @@ COPY --from=builder /opt/venv /opt/venv ENV PATH="/opt/venv/bin:$PATH" ENV PYTHONUNBUFFERED=1 +# Always upgrade yt-dlp to latest (YouTube bot-detection changes frequently) +RUN pip install --upgrade --no-cache-dir yt-dlp + # Copy application code COPY . . diff --git a/app.py b/app.py index 5c9e615..7651ddc 100644 --- a/app.py +++ b/app.py @@ -10,7 +10,7 @@ import asyncio from dotenv import load_dotenv from typing import Dict, Optional, List from contextlib import asynccontextmanager -from fastapi import FastAPI, UploadFile, File, Form, HTTPException, Request, Header +from fastapi import FastAPI, UploadFile, File, Form, HTTPException, Request, Header, BackgroundTasks from fastapi.middleware.cors import CORSMiddleware from fastapi.staticfiles import StaticFiles from pydantic import BaseModel @@ -33,6 +33,8 @@ JOB_RETENTION_SECONDS = 3600 # 1 hour retention # Application State job_queue = asyncio.Queue() jobs: Dict[str, Dict] = {} +thumbnail_sessions: Dict[str, Dict] = {} +publish_jobs: Dict[str, Dict] = {} # {publish_id: {status, result, error}} # Semester to limit concurrency to MAX_CONCURRENT_JOBS concurrency_semaphore = asyncio.Semaphore(MAX_CONCURRENT_JOBS) @@ -163,6 +165,11 @@ app.add_middleware( # Mount static files for serving videos app.mount("/videos", StaticFiles(directory=OUTPUT_DIR), name="videos") +# Mount static files for serving thumbnails +THUMBNAILS_DIR = os.path.join(OUTPUT_DIR, "thumbnails") +os.makedirs(THUMBNAILS_DIR, exist_ok=True) +app.mount("/thumbnails", StaticFiles(directory=THUMBNAILS_DIR), name="thumbnails") + class ProcessRequest(BaseModel): url: str @@ -366,6 +373,7 @@ from editor import VideoEditor from subtitles import generate_srt, burn_subtitles, generate_srt_from_video from hooks import add_hook_to_video from translate import translate_video, get_supported_languages +from thumbnail import analyze_video_for_titles, refine_titles, generate_thumbnail, generate_youtube_description class EditRequest(BaseModel): job_id: str @@ -945,6 +953,407 @@ async def get_social_user(api_key: str = Header(..., alias="X-Upload-Post-Key")) except Exception as e: raise HTTPException(status_code=500, detail=str(e)) +# --- Thumbnail Studio Endpoints --- + +@app.post("/api/thumbnail/upload") +async def thumbnail_upload( + file: Optional[UploadFile] = File(None), + url: Optional[str] = Form(None), +): + """Upload video and start background Whisper transcription immediately.""" + if not url and not file: + raise HTTPException(status_code=400, detail="Must provide URL or File") + + session_id = str(uuid.uuid4()) + transcript_event = asyncio.Event() + + # Save file if uploaded directly + video_path = None + if file: + video_path = os.path.join(UPLOAD_DIR, f"thumb_{session_id}_{file.filename}") + with open(video_path, "wb") as buffer: + content = await file.read() + buffer.write(content) + + # Initialize session + thumbnail_sessions[session_id] = { + "video_path": video_path, + "transcript_event": transcript_event, + "transcript_ready": False, + "transcript": None, + "transcript_segments": [], + "video_duration": 0, + "language": "en", + "context": "", + "titles": [], + "conversation": [], + "_url": url, # Store URL for deferred download + } + + async def run_background_whisper(): + try: + vpath = video_path + # Download YouTube video if URL was provided + if not vpath and url: + from main import download_youtube_video + loop = asyncio.get_event_loop() + vpath, _ = await loop.run_in_executor(None, download_youtube_video, url, UPLOAD_DIR) + thumbnail_sessions[session_id]["video_path"] = vpath + + from main import transcribe_video + loop = asyncio.get_event_loop() + transcript = await loop.run_in_executor(None, transcribe_video, vpath) + segments = transcript.get("segments", []) + duration = segments[-1]["end"] if segments else 0 + + thumbnail_sessions[session_id].update({ + "transcript_ready": True, + "transcript": transcript, + "transcript_segments": segments, + "video_duration": duration, + "language": transcript.get("language", "en"), + }) + print(f"✅ [Thumbnail] Background Whisper complete for session {session_id}") + except Exception as e: + print(f"❌ [Thumbnail] Background Whisper failed: {e}") + thumbnail_sessions[session_id]["transcript_error"] = str(e) + finally: + transcript_event.set() + + asyncio.create_task(run_background_whisper()) + + return {"session_id": session_id} + + +@app.post("/api/thumbnail/analyze") +async def thumbnail_analyze( + request: Request, + file: Optional[UploadFile] = File(None), + url: Optional[str] = Form(None), + session_id: Optional[str] = Form(None), + x_gemini_key: Optional[str] = Header(None, alias="X-Gemini-Key") +): + """Analyze a video and suggest viral YouTube titles.""" + api_key = x_gemini_key + if not api_key: + raise HTTPException(status_code=400, detail="Missing X-Gemini-Key header") + + pre_transcript = None + + # Check for pre-existing session with background Whisper + if session_id and session_id in thumbnail_sessions: + session = thumbnail_sessions[session_id] + + # Wait for background Whisper to complete + 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"): + raise HTTPException(status_code=500, detail=f"Transcription failed: {session['transcript_error']}") + + video_path = session["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") + + if session.get("transcript_ready"): + pre_transcript = session["transcript"] + else: + # No pre-existing session — need file or URL + if not url and not file: + raise HTTPException(status_code=400, detail="Must provide URL, File, or session_id") + + session_id = str(uuid.uuid4()) + + if url: + from main import download_youtube_video + video_path, _ = download_youtube_video(url, UPLOAD_DIR) + else: + video_path = os.path.join(UPLOAD_DIR, f"thumb_{session_id}_{file.filename}") + with open(video_path, "wb") as buffer: + content = await file.read() + buffer.write(content) + + try: + # Run analysis in thread pool (skips Whisper if pre_transcript is available) + loop = asyncio.get_event_loop() + result = await loop.run_in_executor(None, analyze_video_for_titles, api_key, video_path, pre_transcript) + + # Store/update session context + if session_id not in thumbnail_sessions: + thumbnail_sessions[session_id] = {} + + thumbnail_sessions[session_id].update({ + "context": result.get("transcript_summary", ""), + "titles": result.get("titles", []), + "language": result.get("language", "en"), + "conversation": thumbnail_sessions[session_id].get("conversation", []), + "video_path": video_path, + "transcript_segments": result.get("segments", []), + "video_duration": result.get("video_duration", 0) + }) + + return { + "session_id": session_id, + "titles": result.get("titles", []), + "context": result.get("transcript_summary", ""), + "language": result.get("language", "en"), + "recommended": result.get("recommended", []) + } + + except Exception as e: + print(f"❌ Thumbnail Analyze Error: {e}") + raise HTTPException(status_code=500, detail=str(e)) + + +class ThumbnailTitlesRequest(BaseModel): + session_id: Optional[str] = None + message: Optional[str] = None + title: Optional[str] = None + +@app.post("/api/thumbnail/titles") +async def thumbnail_titles( + req: ThumbnailTitlesRequest, + x_gemini_key: Optional[str] = Header(None, alias="X-Gemini-Key") +): + """Refine title suggestions or accept a manual title.""" + api_key = x_gemini_key + if not api_key: + raise HTTPException(status_code=400, detail="Missing X-Gemini-Key header") + + # Manual title mode - just create a session with the user's title + if req.title: + session_id = req.session_id or str(uuid.uuid4()) + if session_id not in thumbnail_sessions: + thumbnail_sessions[session_id] = { + "context": "", + "titles": [req.title], + "language": "en", + "conversation": [] + } + return {"session_id": session_id, "titles": [req.title]} + + # Refinement mode + if not req.session_id or req.session_id not in thumbnail_sessions: + raise HTTPException(status_code=404, detail="Session not found") + + if not req.message: + raise HTTPException(status_code=400, detail="Must provide message or title") + + session = thumbnail_sessions[req.session_id] + + # Add user message to conversation history + session["conversation"].append({"role": "user", "content": req.message}) + + try: + loop = asyncio.get_event_loop() + result = await loop.run_in_executor( + None, + refine_titles, + api_key, + session["context"], + req.message, + session["conversation"] + ) + + new_titles = result.get("titles", []) + session["titles"] = new_titles + session["conversation"].append({"role": "assistant", "content": json.dumps(new_titles)}) + + return {"titles": new_titles} + + except Exception as e: + print(f"❌ Thumbnail Titles Error: {e}") + raise HTTPException(status_code=500, detail=str(e)) + + +@app.post("/api/thumbnail/generate") +async def thumbnail_generate( + request: Request, + session_id: str = Form(...), + title: str = Form(...), + extra_prompt: str = Form(""), + count: int = Form(3), + face: Optional[UploadFile] = File(None), + background: Optional[UploadFile] = File(None), + x_gemini_key: Optional[str] = Header(None, alias="X-Gemini-Key") +): + """Generate YouTube thumbnails with Gemini image generation.""" + api_key = x_gemini_key + if not api_key: + raise HTTPException(status_code=400, detail="Missing X-Gemini-Key header") + + # Clamp count + count = min(max(1, count), 6) + + # Save optional uploaded images + face_path = None + bg_path = None + thumb_upload_dir = os.path.join(UPLOAD_DIR, f"thumb_{session_id}") + os.makedirs(thumb_upload_dir, exist_ok=True) + + try: + if face and face.filename: + face_path = os.path.join(thumb_upload_dir, f"face_{face.filename}") + with open(face_path, "wb") as f: + f.write(await face.read()) + + if background and background.filename: + bg_path = os.path.join(thumb_upload_dir, f"bg_{background.filename}") + with open(bg_path, "wb") as f: + f.write(await background.read()) + + # Run generation in thread pool + loop = asyncio.get_event_loop() + thumbnails = await loop.run_in_executor( + None, + generate_thumbnail, + api_key, + title, + session_id, + face_path, + bg_path, + extra_prompt, + count + ) + + return {"thumbnails": thumbnails} + + except Exception as e: + print(f"❌ Thumbnail Generate Error: {e}") + raise HTTPException(status_code=500, detail=str(e)) + + +class ThumbnailDescribeRequest(BaseModel): + session_id: str + title: str + +@app.post("/api/thumbnail/describe") +async def thumbnail_describe( + req: ThumbnailDescribeRequest, + x_gemini_key: Optional[str] = Header(None, alias="X-Gemini-Key") +): + """Generate a YouTube description with chapters from the transcript.""" + api_key = x_gemini_key + if not api_key: + raise HTTPException(status_code=400, detail="Missing X-Gemini-Key header") + + if req.session_id not in thumbnail_sessions: + raise HTTPException(status_code=404, detail="Session not found") + + session = thumbnail_sessions[req.session_id] + segments = session.get("transcript_segments", []) + if not segments: + raise HTTPException(status_code=400, detail="No transcript segments available. Please analyze a video first.") + + try: + loop = asyncio.get_event_loop() + result = await loop.run_in_executor( + None, + generate_youtube_description, + api_key, + req.title, + segments, + session.get("language", "en"), + session.get("video_duration", 0) + ) + return {"description": result.get("description", "")} + + except Exception as e: + print(f"❌ Thumbnail Describe Error: {e}") + raise HTTPException(status_code=500, detail=str(e)) + + +@app.post("/api/thumbnail/publish") +async def thumbnail_publish( + background_tasks: BackgroundTasks, + session_id: str = Form(...), + title: str = Form(...), + description: str = Form(...), + thumbnail_url: str = Form(...), + api_key: str = Form(...), + user_id: str = Form(...), +): + """Kick off a background upload to YouTube via Upload-Post and return immediately.""" + if session_id not in thumbnail_sessions: + raise HTTPException(status_code=404, detail="Session not found") + + session = thumbnail_sessions[session_id] + video_path = session.get("video_path") + if not video_path or not os.path.exists(video_path): + raise HTTPException(status_code=404, detail="Original video file not found") + + # Resolve thumbnail path from URL + thumb_relative = thumbnail_url.lstrip("/") + if thumb_relative.startswith("thumbnails/"): + thumb_path = os.path.join(OUTPUT_DIR, thumb_relative) + else: + thumb_path = os.path.join(THUMBNAILS_DIR, thumb_relative) + + if not os.path.exists(thumb_path): + raise HTTPException(status_code=404, detail=f"Thumbnail file not found: {thumb_path}") + + # Generate a unique ID for this publish job so the frontend can poll + publish_id = str(uuid.uuid4()) + publish_jobs[publish_id] = {"status": "uploading", "result": None, "error": None} + + def do_upload(): + """Runs in a thread via BackgroundTasks — does the actual multipart upload.""" + try: + upload_url = "https://api.upload-post.com/api/upload" + headers = {"Authorization": f"Apikey {api_key}"} + data_payload = { + "user": user_id, + "platform[]": ["youtube"], + "title": title, # required base field (fallback) + "async_upload": "true", + "youtube_title": title, + "youtube_description": description, + "privacyStatus": "public", + } + video_filename = os.path.basename(video_path) + thumb_filename = os.path.basename(thumb_path) + + print(f"📡 [Thumbnail] Publishing to YouTube via Upload-Post... (publish_id={publish_id})") + with open(video_path, "rb") as vf, open(thumb_path, "rb") as tf: + files = { + "video": (video_filename, vf.read(), "video/mp4"), + "thumbnail": (thumb_filename, tf.read(), "image/jpeg"), + } + + # Use a long timeout — video uploads can take several minutes + with httpx.Client(timeout=600.0) as client: + response = client.post(upload_url, headers=headers, data=data_payload, files=files) + + if response.status_code not in [200, 201, 202]: + err = f"Upload-Post API Error ({response.status_code}): {response.text}" + print(f"❌ {err}") + publish_jobs[publish_id]["status"] = "failed" + publish_jobs[publish_id]["error"] = err + else: + print(f"✅ [Thumbnail] Published successfully (publish_id={publish_id})") + publish_jobs[publish_id]["status"] = "done" + publish_jobs[publish_id]["result"] = response.json() + + except Exception as e: + err = str(e) + print(f"❌ Thumbnail Publish Background Error: {err}") + publish_jobs[publish_id]["status"] = "failed" + publish_jobs[publish_id]["error"] = err + + background_tasks.add_task(do_upload) + return {"publish_id": publish_id, "status": "uploading"} + + +@app.get("/api/thumbnail/publish/status/{publish_id}") +async def thumbnail_publish_status(publish_id: str): + """Poll the status of a background publish job.""" + if publish_id not in publish_jobs: + raise HTTPException(status_code=404, detail="Publish job not found") + return publish_jobs[publish_id] + + # @app.get("/api/gallery/clips") # async def get_gallery_clips(limit: int = 20, offset: int = 0, refresh: bool = False): # """ diff --git a/dashboard/src/App.jsx b/dashboard/src/App.jsx index 5c61adf..537286c 100644 --- a/dashboard/src/App.jsx +++ b/dashboard/src/App.jsx @@ -1,10 +1,11 @@ import React, { useState, useEffect } from 'react'; -import { Upload, FileVideo, Sparkles, Youtube, Instagram, Share2, LogOut, ChevronDown, Check, Activity, LayoutDashboard, Settings, PlusCircle, History, Menu, X, Terminal, Shield, LayoutGrid } from 'lucide-react'; +import { Upload, FileVideo, Sparkles, Youtube, Instagram, Share2, LogOut, ChevronDown, Check, Activity, LayoutDashboard, Settings, PlusCircle, History, Menu, X, Terminal, Shield, LayoutGrid, Image } from 'lucide-react'; import KeyInput from './components/KeyInput'; import MediaInput from './components/MediaInput'; import ResultCard from './components/ResultCard'; import ProcessingAnimation from './components/ProcessingAnimation'; // import Gallery from './components/Gallery'; +import ThumbnailStudio from './components/ThumbnailStudio'; import { getApiUrl } from './config'; // Enhanced "Encryption" using XOR + Base64 with a Salt @@ -313,6 +314,14 @@ function App() { Dashboard + + {/* + + + ); + } + + return ( +
inputRef.current?.click()} + onDrop={handleDrop} + onDragOver={handleDragOver} + onDragLeave={() => setIsDragging(false)} + className={`border-2 border-dashed rounded-xl p-6 text-center cursor-pointer transition-all ${isDragging ? 'border-primary/50 bg-primary/5' : 'border-white/10 hover:border-white/20 bg-white/[0.02]' + }`} + > + +

{label}

+

Drop or click to upload

+ e.target.files[0] && onFile(e.target.files[0])} + /> +
+ ); +} + +export default function ThumbnailStudio({ geminiApiKey, uploadPostKey, uploadUserId }) { + // 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}] + + // Step 3 state + const [faceImage, setFaceImage] = useState(null); + const [bgImage, setBgImage] = useState(null); + const [extraPrompt, setExtraPrompt] = useState(''); + const [thumbnailCount, setThumbnailCount] = useState(3); + 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 fetch(getApiUrl('/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 (!geminiApiKey) 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 fetch(getApiUrl('/api/thumbnail/analyze'), { + method: 'POST', + headers: { 'X-Gemini-Key': geminiApiKey }, + 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 || []); + setRecommended(data.recommended || []); + setChatHistory([{ + role: 'assistant', + content: `Here are 10 viral title suggestions based on your video. Titles marked ⭐ 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); + fetch(getApiUrl('/api/thumbnail/titles'), { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'X-Gemini-Key': geminiApiKey + }, + 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 fetch(getApiUrl('/api/thumbnail/titles'), { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'X-Gemini-Key': geminiApiKey + }, + 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 || []); + 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 (!geminiApiKey) 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); + if (faceImage) formData.append('face', faceImage); + if (bgImage) formData.append('background', bgImage); + + const res = await fetch(getApiUrl('/api/thumbnail/generate'), { + method: 'POST', + headers: { 'X-Gemini-Key': geminiApiKey }, + body: formData + }); + + if (!res.ok) { + const err = await res.text(); + throw new Error(err); + } + + const data = await res.json(); + setGeneratedThumbnails(data.thumbnails || []); + } catch (e) { + alert(`Generation failed: ${e.message}`); + } finally { + setIsGenerating(false); + } + }; + + const handleDownload = async (url) => { + const a = document.createElement('a'); + a.href = getApiUrl(url); + a.download = url.split('/').pop(); + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + }; + + // --- Description Generation --- + const handleGenerateDescription = async () => { + if (!geminiApiKey) 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 fetch(getApiUrl('/api/thumbnail/describe'), { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'X-Gemini-Key': geminiApiKey + }, + 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 (!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 fetch(getApiUrl('/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 fetch(getApiUrl(`/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); + setBgImage(null); + setExtraPrompt(''); + setGeneratedThumbnails([]); + setDescription(''); + setIsDescribing(false); + setSelectedThumbnail(null); + setIsPublishing(false); + setPublishResult(null); + setPreprocessSessionId(null); + setIsPreprocessing(false); + setRecommended([]); + }; + + return ( +
+
+ {/* Header */} +
+

+
+ +
+ YouTube Studio +

+ {step > 0 && ( + + )} +
+

Generate viral titles, AI thumbnails, descriptions and publish directly to YouTube

+ + + + {/* ===== STEP 0: Input Mode Selection ===== */} + {step === 0 && ( +
+ {/* Mode A: Video Analysis */} +
+
+
+
+
+

Analyze Video

+

AI suggests viral titles from your content

+
+
+ + { setVideoFile(f); setMode('video'); handlePreUpload(f); }} + file={videoFile} + onClear={() => { setVideoFile(null); setPreprocessSessionId(null); }} + icon={Video} + /> + + {isPreprocessing && ( +
+ + Pre-processing video (Whisper transcription starting)... +
+ )} + {preprocessSessionId && !isPreprocessing && ( +
+ + Video uploaded — transcription running in background +
+ )} + + +
+ + {/* Mode B: Manual Title */} +
+
+
+ +
+
+

Write Your Own

+

Skip analysis, enter your title directly

+
+
+ +
+ setManualTitle(e.target.value)} + placeholder="Enter your YouTube title..." + className="input-field text-sm mb-4" + maxLength={70} + /> +

{manualTitle.length}/70 characters

+
+ + +
+
+ )} + + {/* ===== STEP 1: Title Selection ===== */} + {step === 1 && ( +
+ {/* Left: Chat / Controls */} +
+ {mode === 'manual' ? ( +
+

Your Title

+ setManualTitle(e.target.value)} + className="input-field text-sm" + maxLength={70} + /> +

{manualTitle.length}/70 characters

+ +
+ ) : ( +
+
+ + Title Refinement Chat +
+ + {/* Chat messages */} +
+ {chatHistory.map((msg, i) => ( +
+
+ {msg.content} +
+
+ ))} +
+
+ + {/* Chat input */} +
+ setChatInput(e.target.value)} + onKeyDown={(e) => e.key === 'Enter' && !e.shiftKey && handleRefine()} + placeholder="Make them more clickbait..." + className="input-field text-xs flex-1" + disabled={isRefining} + /> + +
+
+ )} + + {mode !== 'manual' && selectedTitle && ( + + )} +
+ + {/* Right: Title Cards */} +
+ {selectedTitle && ( +
+ + Selected: {selectedTitle} +
+ )} + + {titles.length > 0 && ( +
+ {titles.map((title, i) => { + const rec = recommended.find(r => r.index === i); + const recRank = recommended.findIndex(r => r.index === i); + return ( + + ); + })} +
+ )} + + {isRefining && ( +
+ + Refining titles... +
+ )} +
+
+ )} + + {/* ===== STEP 2: Thumbnail Generation ===== */} + {step === 2 && ( +
+ {/* Left: Controls */} +
+
+

Selected Title

+
+ {selectedTitle || manualTitle} +
+ + +
+ +
+

Face Image (optional)

+ setFaceImage(null)} + icon={Upload} + /> +
+ +
+

Background Image (optional)

+ setBgImage(null)} + icon={Image} + /> +
+ +
+

Extra Instructions (optional)

+