added youtube studio

This commit is contained in:
juancarlos.cavero 2026-02-20 01:11:27 +01:00
parent c902b6c04c
commit 3946c49ad1
9 changed files with 1920 additions and 21 deletions

8
.env.example Normal file
View file

@ -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=...

19
.gitignore vendored
View file

@ -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/
# Cache dirs
.cache/
.config/

View file

@ -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 . .

411
app.py
View file

@ -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):
# """

View file

@ -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() {
<span className="font-medium hidden lg:block">Dashboard</span>
</button>
<button
onClick={() => setActiveTab('thumbnails')}
className={`w-full flex items-center gap-3 px-3 py-3 rounded-xl transition-colors ${activeTab === 'thumbnails' ? 'bg-primary/10 text-primary' : 'text-zinc-400 hover:text-white hover:bg-white/5'}`}
>
<Image size={20} />
<span className="font-medium hidden lg:block">YouTube Studio</span>
</button>
{/* <button
onClick={() => setActiveTab('gallery')}
className={`w-full flex items-center gap-3 px-3 py-3 rounded-xl transition-colors ${activeTab === 'gallery' ? 'bg-primary/10 text-primary' : 'text-zinc-400 hover:text-white hover:bg-white/5'}`}
@ -505,6 +514,11 @@ function App() {
</div>
)}
{/* View: Thumbnails */}
{activeTab === 'thumbnails' && (
<ThumbnailStudio geminiApiKey={apiKey} uploadPostKey={uploadPostKey} uploadUserId={uploadUserId} />
)}
{/* View: Gallery */}
{/* {activeTab === 'gallery' && (
<Gallery />

File diff suppressed because it is too large Load diff

View file

@ -17,6 +17,10 @@ export default defineConfig({
'/videos': {
target: 'http://backend:8000',
changeOrigin: true,
},
'/thumbnails': {
target: 'http://backend:8000',
changeOrigin: true,
}
}
}

32
main.py
View file

@ -477,24 +477,35 @@ def download_youtube_video(url, output_dir="."):
cookies_path = None
print("⚠️ YOUTUBE_COOKIES env var not found.")
ydl_opts_info = {
# Common yt-dlp options to work around YouTube bot detection.
# extractor_args tries multiple player clients in order; tv_embed / android
# avoid the OAuth/PO-token checks that block server IPs.
_COMMON_YDL_OPTS = {
'quiet': False,
'verbose': True,
'no_warnings': False,
'cookiefile': cookies_path if cookies_path else None,
'sleep_interval_requests': 5,
'sleep_interval': 10,
'max_sleep_interval': 30,
'socket_timeout': 30,
'retries': 10,
'fragment_retries': 10,
'nocheckcertificate': True,
'force_ipv4': True,
'cachedir': False,
'extractor_args': {'youtube': {'player_client': ['web']}},
'user_agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
'extractor_args': {
'youtube': {
'player_client': ['tv_embed', 'android', 'mweb', 'web'],
'player_skip': ['webpage', 'configs'],
}
},
'http_headers': {
'User-Agent': (
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
'AppleWebKit/537.36 (KHTML, like Gecko) '
'Chrome/120.0.0.0 Safari/537.36'
),
},
}
with yt_dlp.YoutubeDL(ydl_opts_info) as ydl:
with yt_dlp.YoutubeDL(_COMMON_YDL_OPTS) as ydl:
try:
info = ydl.extract_info(url, download=False)
video_title = info.get('title', 'youtube_video')
@ -544,14 +555,11 @@ Technical Details: {str(e)}
print(f"🗑️ Removed existing file to re-download with H.264 codec")
ydl_opts = {
**_COMMON_YDL_OPTS,
'format': 'bestvideo[vcodec^=avc1][ext=mp4]+bestaudio[ext=m4a]/bestvideo[vcodec^=avc1]+bestaudio/best[ext=mp4]/best',
'outtmpl': output_template,
'merge_output_format': 'mp4',
'quiet': False,
'verbose': True,
'no_warnings': False,
'overwrites': True,
'cookiefile': cookies_path if cookies_path else None
}
with yt_dlp.YoutubeDL(ydl_opts) as ydl:

319
thumbnail.py Normal file
View file

@ -0,0 +1,319 @@
import os
import uuid
import time
import json
from google import genai
from google.genai import types
from PIL import Image
def analyze_video_for_titles(api_key, video_path, transcript=None):
"""
Transcribes a video and uses Gemini to suggest viral YouTube titles.
If transcript is provided, skips Whisper transcription.
Returns: { "titles": [...], "transcript_summary": "...", "language": "...", "segments": [...], "video_duration": ... }
"""
if transcript is None:
from main import transcribe_video
print("🎬 [Thumbnail] Transcribing video...")
transcript = transcribe_video(video_path)
else:
print("🎬 [Thumbnail] Using pre-computed transcript (Whisper already done)...")
print("📤 [Thumbnail] Uploading video to Gemini...")
client = genai.Client(api_key=api_key)
file_upload = client.files.upload(file=video_path)
while True:
file_info = client.files.get(name=file_upload.name)
if file_info.state == "ACTIVE":
break
elif file_info.state == "FAILED":
raise Exception("Video processing failed by Gemini.")
time.sleep(2)
prompt = f"""You are a YouTube title expert who creates viral, click-worthy titles.
Analyze this video and its transcript, then suggest 10 YouTube titles that would maximize CTR (click-through rate).
TRANSCRIPT:
{transcript['text']}
RULES:
- Titles must be under 70 characters
- Use power words, curiosity gaps, and emotional triggers
- Mix styles: how-to, listicle, story-driven, controversial, question-based
- Make them specific to the actual content, not generic
- Include numbers where appropriate
- Consider the language of the video (detected: {transcript['language']})
- Titles should be in the SAME LANGUAGE as the video transcript
Also provide a brief summary of the video content (2-3 sentences).
After generating all 10 titles, pick the TOP 2 you most recommend and explain concisely WHY (CTR potential, emotional hook, uniqueness, etc.). Reference them by their 0-based index in the titles array.
OUTPUT JSON:
{{
"titles": ["title1", "title2", ...],
"transcript_summary": "Brief summary of the video content...",
"language": "{transcript['language']}",
"recommended": [
{{"index": 0, "reason": "Why this title is best..."}},
{{"index": 3, "reason": "Why this title is second best..."}}
]
}}"""
print("🤖 [Thumbnail] Asking Gemini for title suggestions...")
response = client.models.generate_content(
model="gemini-2.5-flash",
contents=[file_upload, prompt],
config=types.GenerateContentConfig(
response_mime_type="application/json"
)
)
# Extract segments and duration from transcript for later use
segments = transcript.get("segments", [])
video_duration = segments[-1]["end"] if segments else 0
try:
text = response.text.strip()
if text.startswith("```json"):
text = text[7:]
if text.startswith("```"):
text = text[3:]
if text.endswith("```"):
text = text[:-3]
text = text.strip()
start_idx = text.find('{')
end_idx = text.rfind('}')
if start_idx != -1 and end_idx != -1:
text = text[start_idx:end_idx + 1]
result = json.loads(text)
result["transcript_summary"] = result.get("transcript_summary", "")
result["language"] = result.get("language", transcript["language"])
result["segments"] = segments
result["video_duration"] = video_duration
return result
except json.JSONDecodeError:
print(f"❌ [Thumbnail] Failed to parse titles JSON: {response.text}")
return {
"titles": ["Could not generate titles - please try again"],
"transcript_summary": transcript["text"][:500],
"language": transcript["language"],
"segments": segments,
"video_duration": video_duration
}
def refine_titles(api_key, context, user_message, conversation_history=None):
"""
Takes video context + user feedback and returns refined title suggestions.
"""
client = genai.Client(api_key=api_key)
history_text = ""
if conversation_history:
for msg in conversation_history:
role = msg.get("role", "user")
history_text += f"\n{role.upper()}: {msg['content']}"
prompt = f"""You are a YouTube title expert. Based on the video context and the user's feedback, suggest 8 new refined YouTube titles.
VIDEO CONTEXT:
{context}
CONVERSATION HISTORY:{history_text}
USER'S NEW REQUEST:
{user_message}
RULES:
- Titles must be under 70 characters
- Incorporate the user's feedback/direction
- Keep titles viral and click-worthy
- If the user asks for a specific style, follow it
- Titles should be in the same language as the original content
OUTPUT JSON:
{{
"titles": ["title1", "title2", ...]
}}"""
response = client.models.generate_content(
model="gemini-2.5-flash",
contents=[prompt],
config=types.GenerateContentConfig(
response_mime_type="application/json"
)
)
try:
text = response.text.strip()
if text.startswith("```json"):
text = text[7:]
if text.startswith("```"):
text = text[3:]
if text.endswith("```"):
text = text[:-3]
text = text.strip()
start_idx = text.find('{')
end_idx = text.rfind('}')
if start_idx != -1 and end_idx != -1:
text = text[start_idx:end_idx + 1]
return json.loads(text)
except json.JSONDecodeError:
print(f"❌ [Thumbnail] Failed to parse refined titles: {response.text}")
return {"titles": ["Could not refine titles - please try again"]}
def generate_thumbnail(api_key, title, session_id, face_image_path=None, bg_image_path=None, extra_prompt="", count=3):
"""
Generates YouTube thumbnails using Gemini image generation.
Returns list of saved image paths (relative URLs).
"""
client = genai.Client(api_key=api_key)
output_dir = os.path.join("output", "thumbnails", session_id)
os.makedirs(output_dir, exist_ok=True)
prompt_parts = []
# Add face image if provided
if face_image_path and os.path.exists(face_image_path):
face_img = Image.open(face_image_path)
prompt_parts.append(face_img)
# Add background image if provided
if bg_image_path and os.path.exists(bg_image_path):
bg_img = Image.open(bg_image_path)
prompt_parts.append(bg_img)
text_prompt = f"""Generate a professional, eye-catching YouTube thumbnail image.
VIDEO TITLE (for context only — DO NOT copy it verbatim onto the thumbnail): "{title}"
TEXT TO SHOW ON THE THUMBNAIL:
- Derive a SHORT, punchy visual hook from the title: 1 to 5 words maximum
- Pick the most emotionally powerful or curiosity-triggering fragment of the title
(a key number, a strong emotion word, a shocking claim, a question word, etc.)
- Example: if the title is "I Made $10,000 in 30 Days With This Strategy", the thumbnail text might be "$10K IN 30 DAYS" or "THIS ACTUALLY WORKS"
- The thumbnail text and the YouTube title should COMPLEMENT each other, not duplicate
- Use ALL CAPS or mixed-case for visual impact depending on what looks better
- Split across 2-3 lines if needed for readability
DESIGN REQUIREMENTS:
- The derived text MUST appear prominently — large, bold, high-contrast typography
- Professional YouTube thumbnail style with vibrant, eye-catching colors
- High contrast and visual impact for small screen sizes
- Clean composition that immediately draws attention
- The text and any face/subject should be the clear focal points"""
if face_image_path and os.path.exists(face_image_path):
text_prompt += "\n- Include the provided face/person image prominently in the thumbnail, showing strong emotion or reaction"
if bg_image_path and os.path.exists(bg_image_path):
text_prompt += "\n- Use the provided background image as the base/backdrop for the thumbnail"
if extra_prompt:
text_prompt += f"\n- Additional instructions: {extra_prompt}"
prompt_parts.append(text_prompt)
thumbnails = []
for i in range(count):
print(f"🎨 [Thumbnail] Generating thumbnail {i + 1}/{count}...")
try:
response = client.models.generate_content(
model="gemini-3-pro-image-preview",
contents=prompt_parts,
config=types.GenerateContentConfig(
response_modalities=["TEXT", "IMAGE"],
image_config=types.ImageConfig(
aspect_ratio="16:9",
image_size="2K"
)
)
)
for part in response.parts:
if part.text is not None:
print(f"📝 [Thumbnail] Gemini text: {part.text}")
elif image := part.as_image():
filename = f"thumb_{i + 1}.jpg"
filepath = os.path.join(output_dir, filename)
image.save(filepath)
thumbnails.append(f"/thumbnails/{session_id}/{filename}")
print(f"✅ [Thumbnail] Saved: {filepath}")
break
except Exception as e:
print(f"❌ [Thumbnail] Generation {i + 1} failed: {e}")
return thumbnails
def generate_youtube_description(api_key, title, transcript_segments, language, video_duration):
"""
Uses Gemini to generate a YouTube description with chapter markers from transcript segments.
Returns: { "description": "full description text with chapters" }
"""
client = genai.Client(api_key=api_key)
# Format segments for the prompt
formatted_segments = []
for seg in transcript_segments:
start = seg.get("start", 0)
mins = int(start // 60)
secs = int(start % 60)
timestamp = f"{mins}:{secs:02d}"
formatted_segments.append(f"[{timestamp}] {seg.get('text', '').strip()}")
segments_text = "\n".join(formatted_segments)
# Format total duration
dur_mins = int(video_duration // 60)
dur_secs = int(video_duration % 60)
duration_str = f"{dur_mins}:{dur_secs:02d}"
prompt = f"""You are a YouTube SEO expert. Generate a complete YouTube video description for the following video.
VIDEO TITLE: "{title}"
VIDEO LANGUAGE: {language}
VIDEO DURATION: {duration_str}
TRANSCRIPT WITH TIMESTAMPS:
{segments_text}
REQUIREMENTS:
1. Write the description in the SAME LANGUAGE as the video ({language})
2. Start with a compelling 2-3 sentence summary/hook
3. Add relevant CTAs (subscribe, like, comment)
4. Generate YouTube CHAPTERS based on the transcript timestamps:
- First chapter MUST start at 0:00
- Minimum 3 chapters, each at least 10 seconds apart
- Chapter titles should be concise and descriptive
- Format: 0:00 Chapter Title
- Place chapters in their own section with a blank line before and after
5. Add 5-10 relevant hashtags at the end
6. Keep the total description under 5000 characters
OUTPUT: Return ONLY the description text (no JSON wrapper, no markdown code blocks). The description should be ready to paste directly into YouTube."""
print("🤖 [Thumbnail] Generating YouTube description with chapters...")
response = client.models.generate_content(
model="gemini-2.5-flash",
contents=[prompt],
)
description = response.text.strip()
# Clean up any accidental markdown wrappers
if description.startswith("```"):
lines = description.split("\n")
description = "\n".join(lines[1:-1] if lines[-1].strip() == "```" else lines[1:])
return {"description": description}