From 29681bab827a80d3723c9bce32a84beebaab38a1 Mon Sep 17 00:00:00 2001 From: "juancarlos.cavero" Date: Sun, 15 Mar 2026 20:41:35 +0100 Subject: [PATCH] added video ugc generator --- app.py | 271 +++- dashboard/src/App.jsx | 78 ++ dashboard/src/components/SaaShortsTab.jsx | 1194 ++++++++++++++++++ requirements.txt | 1 + saasshorts.py | 1369 +++++++++++++++++++++ 5 files changed, 2909 insertions(+), 4 deletions(-) create mode 100644 dashboard/src/components/SaaShortsTab.jsx create mode 100644 saasshorts.py diff --git a/app.py b/app.py index dbe73ff..139b1d0 100644 --- a/app.py +++ b/app.py @@ -99,6 +99,20 @@ async def cleanup_jobs(): if job_id in jobs: del jobs[job_id] + # Cleanup SaaSShorts jobs from memory + try: + saas_expired = [ + jid for jid, jdata in list(saas_jobs.items()) + if jdata.get("status") in ("completed", "failed") + and jdata.get("output_dir") + and os.path.isdir(jdata["output_dir"]) + and now - os.path.getmtime(jdata["output_dir"]) > JOB_RETENTION_SECONDS + ] + for jid in saas_expired: + del saas_jobs[jid] + except NameError: + pass + # Cleanup Uploads for filename in os.listdir(UPLOAD_DIR): file_path = os.path.join(UPLOAD_DIR, filename) @@ -1379,7 +1393,7 @@ async def thumbnail_publish_status(publish_id: str): # async def get_gallery_clips(limit: int = 20, offset: int = 0, refresh: bool = False): # """ # Fetch clips from S3 for the gallery with pagination. -# +# # Args: # limit: Number of clips to return (default 20, max 100) # offset: Starting position for pagination @@ -1388,13 +1402,13 @@ async def thumbnail_publish_status(publish_id: str): # try: # # Clamp limit to reasonable values # limit = min(max(1, limit), 100) -# +# # # Get clips (uses cache internally) # all_clips = list_all_clips(limit=limit + offset, force_refresh=refresh) -# +# # # Apply offset for pagination # clips = all_clips[offset:offset + limit] -# +# # return { # "clips": clips, # "total": len(all_clips), @@ -1405,3 +1419,252 @@ async def thumbnail_publish_status(publish_id: str): # except Exception as e: # print(f"❌ Gallery Error: {e}") # raise HTTPException(status_code=500, detail=str(e)) + + +# ═══════════════════════════════════════════════════════════════════════ +# SaaSShorts: AI UGC Video Generator for SaaS Products +# ═══════════════════════════════════════════════════════════════════════ + +from saasshorts import ( + scrape_website, + research_saas_online, + analyze_saas, + generate_scripts, + generate_full_video, + generate_actor_images, + get_elevenlabs_voices, + DEFAULT_VOICES, +) + +# State for SaaSShorts jobs (separate from video processing jobs) +saas_jobs: Dict[str, Dict] = {} + + +class SaaSAnalyzeRequest(BaseModel): + url: str + num_scripts: int = 3 + style: str = "ugc" + language: str = "en" + actor_gender: str = "female" + + +@app.post("/api/saasshorts/analyze") +async def saasshorts_analyze( + req: SaaSAnalyzeRequest, + x_gemini_key: Optional[str] = Header(None, alias="X-Gemini-Key"), +): + """Scrape a SaaS URL, analyze it, and generate video scripts.""" + gemini_key = x_gemini_key or os.environ.get("GEMINI_API_KEY") + if not gemini_key: + raise HTTPException(status_code=400, detail="Missing Gemini API Key") + + try: + loop = asyncio.get_event_loop() + + def run_analysis(): + # Phase 1a: Scrape the website directly + scraped = scrape_website(req.url) + # Phase 1b: Research across the web with Google Search grounding + web_research = research_saas_online(req.url, gemini_key) + # Phase 1c: Combine both sources into deep analysis + analysis = analyze_saas(scraped, gemini_key, web_research=web_research) + # Phase 1d: Generate scripts based on analysis + scripts = generate_scripts(analysis, gemini_key, req.num_scripts, req.style, req.language, req.actor_gender) + return { + "analysis": analysis, + "scripts": scripts, + "web_research": web_research, + } + + result = await loop.run_in_executor(None, run_analysis) + return result + + except Exception as e: + raise HTTPException(status_code=500, detail=str(e)) + + +class SaaSActorRequest(BaseModel): + actor_description: str + num_options: int = 3 + + +@app.post("/api/saasshorts/actor-options") +async def saasshorts_actor_options( + req: SaaSActorRequest, + x_fal_key: Optional[str] = Header(None, alias="X-Fal-Key"), +): + """Generate multiple actor image options for the user to choose from.""" + fal_key = x_fal_key + if not fal_key: + raise HTTPException(status_code=400, detail="Missing fal.ai API Key") + + try: + job_id = str(uuid.uuid4()) + out_dir = os.path.join(OUTPUT_DIR, f"saas_actors_{job_id}") + os.makedirs(out_dir, exist_ok=True) + + loop = asyncio.get_running_loop() + paths = await loop.run_in_executor( + None, + generate_actor_images, + req.actor_description, fal_key, out_dir, "actor", req.num_options, + ) + + urls = [f"/videos/saas_actors_{job_id}/{os.path.basename(p)}" for p in paths] + return {"images": urls} + + except Exception as e: + raise HTTPException(status_code=500, detail=str(e)) + + +class SaaSGenerateRequest(BaseModel): + script: dict + voice_id: Optional[str] = None + actor_description: Optional[str] = None + selected_actor_url: Optional[str] = None # Pre-selected actor image URL + retry_job_id: Optional[str] = None + + +@app.post("/api/saasshorts/generate") +async def saasshorts_generate( + req: SaaSGenerateRequest, + x_fal_key: Optional[str] = Header(None, alias="X-Fal-Key"), + x_elevenlabs_key: Optional[str] = Header(None, alias="X-ElevenLabs-Key"), +): + """Generate a SaaS UGC video from a script. Returns a job_id for polling.""" + fal_key = x_fal_key + elevenlabs_key = x_elevenlabs_key + + if not fal_key: + raise HTTPException(status_code=400, detail="Missing fal.ai API Key (X-Fal-Key header)") + if not elevenlabs_key: + raise HTTPException(status_code=400, detail="Missing ElevenLabs API Key (X-ElevenLabs-Key header)") + + # Support retry: reuse output_dir so cached assets (image, voice, head, broll) are kept + reused = False + if req.retry_job_id: + # Check memory first, then disk + old_dir = os.path.join(OUTPUT_DIR, f"saas_{req.retry_job_id}") + if req.retry_job_id in saas_jobs: + old_dir = saas_jobs[req.retry_job_id]["output_dir"] + + if os.path.isdir(old_dir): + job_id = req.retry_job_id + job_output_dir = old_dir + reused = True + # Clear the 0-byte final video so pipeline re-generates it + for f in os.listdir(old_dir): + fp = os.path.join(old_dir, f) + if f.endswith("_final.mp4") and os.path.getsize(fp) == 0: + os.remove(fp) + saas_jobs[job_id] = { + "status": "processing", + "logs": [f"Retrying job {job_id[:8]}... reusing cached assets from disk."], + "result": None, + "output_dir": job_output_dir, + } + + if not reused: + job_id = str(uuid.uuid4()) + job_output_dir = os.path.join(OUTPUT_DIR, f"saas_{job_id}") + os.makedirs(job_output_dir, exist_ok=True) + saas_jobs[job_id] = { + "status": "processing", + "logs": ["SaaSShorts job started."], + "result": None, + "output_dir": job_output_dir, + } + + # If user selected a pre-generated actor, copy it into the job output dir + selected_actor_path = None + if req.selected_actor_url: + src = os.path.join(OUTPUT_DIR, req.selected_actor_url.replace("/videos/", "")) + if os.path.exists(src): + selected_actor_path = src + + config = { + "fal_key": fal_key, + "elevenlabs_key": elevenlabs_key, + "voice_id": req.voice_id or "21m00Tcm4TlvDq8ikWAM", + "actor_description": req.actor_description, + "selected_actor_path": selected_actor_path, + } + + async def run_generation(): + await concurrency_semaphore.acquire() + try: + loop = asyncio.get_running_loop() + + def log_msg(msg): + print(f"[SaaSShorts Job {job_id[:8]}] {msg}") + if job_id in saas_jobs: + saas_jobs[job_id]["logs"].append(msg) + + def run(): + return generate_full_video(req.script, config, job_output_dir, log_msg) + + result = await loop.run_in_executor(None, run) + + if job_id in saas_jobs: + video_filename = result["video_filename"] + saas_jobs[job_id]["status"] = "completed" + saas_jobs[job_id]["result"] = { + "video_url": f"/videos/saas_{job_id}/{video_filename}", + "video_filename": video_filename, + "duration": result.get("duration", 0), + "cost_estimate": result.get("cost_estimate", {}), + "script": req.script, + } + saas_jobs[job_id]["logs"].append("Video generation completed!") + + except Exception as e: + print(f"[SaaSShorts] ❌ Job {job_id} failed: {e}") + if job_id in saas_jobs: + saas_jobs[job_id]["status"] = "failed" + saas_jobs[job_id]["logs"].append(f"Error: {str(e)}") + finally: + concurrency_semaphore.release() + + asyncio.create_task(run_generation()) + + return {"job_id": job_id, "status": "processing"} + + +@app.get("/api/saasshorts/status/{job_id}") +async def saasshorts_status(job_id: str): + """Poll SaaSShorts job status.""" + if job_id not in saas_jobs: + raise HTTPException(status_code=404, detail="SaaSShorts job not found") + + job = saas_jobs[job_id] + return { + "status": job["status"], + "logs": job["logs"], + "result": job.get("result"), + } + + +@app.get("/api/saasshorts/voices") +async def saasshorts_voices( + x_elevenlabs_key: Optional[str] = Header(None, alias="X-ElevenLabs-Key"), +): + """List available ElevenLabs voices.""" + if x_elevenlabs_key: + try: + loop = asyncio.get_event_loop() + voices = await loop.run_in_executor( + None, get_elevenlabs_voices, x_elevenlabs_key + ) + if voices: + return {"voices": voices, "source": "elevenlabs"} + except Exception: + pass + + # Fallback to default voices + return { + "voices": [ + {"voice_id": vid, "name": name, "category": "default"} + for name, vid in DEFAULT_VOICES.items() + ], + "source": "defaults", + } diff --git a/dashboard/src/App.jsx b/dashboard/src/App.jsx index 767c2f2..1695127 100644 --- a/dashboard/src/App.jsx +++ b/dashboard/src/App.jsx @@ -6,6 +6,7 @@ import ResultCard from './components/ResultCard'; import ProcessingAnimation from './components/ProcessingAnimation'; // import Gallery from './components/Gallery'; import ThumbnailStudio from './components/ThumbnailStudio'; +import SaaShortsTab from './components/SaaShortsTab'; import { getApiUrl } from './config'; // Enhanced "Encryption" using XOR + Base64 with a Salt @@ -145,6 +146,13 @@ function App() { return ''; }); + // fal.ai API State - Load encrypted + const [falKey, setFalKey] = useState(() => { + const stored = localStorage.getItem('falKey_v1'); + if (stored) return decrypt(stored); + return ''; + }); + const [uploadUserId, setUploadUserId] = useState(() => localStorage.getItem('uploadUserId') || ''); const [userProfiles, setUserProfiles] = useState([]); // List of {username, connected: []} const [jobId, setJobId] = useState(null); @@ -239,6 +247,12 @@ function App() { } }, [elevenLabsKey]); + useEffect(() => { + if (falKey) { + localStorage.setItem('falKey_v1', encrypt(falKey)); + } + }, [falKey]); + useEffect(() => { if (uploadPostKey && userProfiles.length === 0) { fetchUserProfiles(); @@ -366,6 +380,14 @@ function App() { Dashboard + + + +

+ Get your API key from fal.ai to enable AI actor video generation. +

+ + 1. Sign Up + Create fal.ai account + + + 2. API Key + Generate key + +
+
+ + Keys are only stored in your browser. Sent to backend only to process requests. + +

+ + )} + {/* View: SaaS Shorts */} + {activeTab === 'saasshorts' && ( + + )} + {/* View: Thumbnails */} {activeTab === 'thumbnails' && ( diff --git a/dashboard/src/components/SaaShortsTab.jsx b/dashboard/src/components/SaaShortsTab.jsx new file mode 100644 index 0000000..d388473 --- /dev/null +++ b/dashboard/src/components/SaaShortsTab.jsx @@ -0,0 +1,1194 @@ +import React, { useState, useEffect } from 'react'; +import { Globe, Sparkles, Download, Copy, Check, ChevronRight, ChevronLeft, Loader2, AlertCircle, Volume2, User, Film, Terminal, ChevronDown, RefreshCw, Zap, Target, TrendingUp, MessageSquare, Eye } from 'lucide-react'; +import { getApiUrl } from '../config'; + +const STYLE_OPTIONS = [ + { id: 'ugc', label: 'UGC Natural', desc: 'Authentic, talking to camera' }, + { id: 'educational', label: 'Educational', desc: 'Clear explanations' }, + { id: 'shock', label: 'Shock/Discovery', desc: 'Surprising opener' }, + { id: 'story', label: 'Storytelling', desc: 'Mini narrative arc' }, + { id: 'comparison', label: 'Before/After', desc: 'Comparison style' }, +]; + +const CACHE_KEY = 'saasshorts_cache'; +const CACHE_MAX_AGE = 24 * 60 * 60 * 1000; // 24 hours + +function loadCache() { + try { + const raw = localStorage.getItem(CACHE_KEY); + if (!raw) return null; + const cache = JSON.parse(raw); + if (Date.now() - cache.timestamp > CACHE_MAX_AGE) { + localStorage.removeItem(CACHE_KEY); + return null; + } + return cache; + } catch { return null; } +} + +function saveCache(url, analysis, webResearch, scripts) { + try { + localStorage.setItem(CACHE_KEY, JSON.stringify({ + url, analysis, webResearch, scripts, timestamp: Date.now(), + })); + } catch { /* localStorage full */ } +} + +export default function SaaShortsTab({ geminiApiKey, elevenLabsKey, falKey }) { + // Wizard state + const [step, setStep] = useState(() => { + const cache = loadCache(); + return cache ? 1 : 0; + }); + + // Step 0: URL input + const [url, setUrl] = useState(() => loadCache()?.url || ''); + const [style, setStyle] = useState('ugc'); + const [language, setLanguage] = useState('en'); + const [actorGender, setActorGender] = useState('female'); + const [numScripts, setNumScripts] = useState(3); + const [analyzing, setAnalyzing] = useState(false); + const [analyzeError, setAnalyzeError] = useState(''); + const [fromCache, setFromCache] = useState(() => !!loadCache()); + + // Step 1: Analysis results + const [analysis, setAnalysis] = useState(() => loadCache()?.analysis || null); + const [webResearch, setWebResearch] = useState(() => loadCache()?.webResearch || null); + const [scripts, setScripts] = useState(() => loadCache()?.scripts || []); + const [selectedScript, setSelectedScript] = useState(0); + + // Step 2: Configure + const [voices, setVoices] = useState([]); + const [selectedVoice, setSelectedVoice] = useState('21m00Tcm4TlvDq8ikWAM'); + const [actorDescription, setActorDescription] = useState(''); + const [editedNarration, setEditedNarration] = useState(''); + const [actorOptions, setActorOptions] = useState([]); + const [selectedActor, setSelectedActor] = useState(null); + const [generatingActors, setGeneratingActors] = useState(false); + + // Step 3: Generate + const [generating, setGenerating] = useState(false); + const [jobId, setJobId] = useState(null); + const [genLogs, setGenLogs] = useState([]); + const [genStatus, setGenStatus] = useState('idle'); + const [genResult, setGenResult] = useState(null); + + // UI + const [copied, setCopied] = useState(''); + const [logsExpanded, setLogsExpanded] = useState(true); + + // Pre-fill from cache on mount + useEffect(() => { + if (fromCache && scripts.length > 0 && !actorDescription) { + setActorDescription(scripts[0].actor_description || ''); + setEditedNarration(scripts[0].full_narration || ''); + } + }, []); + + // Fetch voices on mount + useEffect(() => { + if (elevenLabsKey) { + fetchVoices(); + } + }, [elevenLabsKey]); + + // Poll generation status + useEffect(() => { + let interval; + if (jobId && genStatus === 'processing') { + interval = setInterval(async () => { + try { + const res = await fetch(getApiUrl(`/api/saasshorts/status/${jobId}`)); + if (res.status === 404) { + // Job lost (server restart) — treat as failed so Retry appears + setGenStatus('failed'); + setGenerating(false); + setGenLogs((prev) => [...prev, 'Job lost after server restart. Click Retry to resume from cached assets.']); + clearInterval(interval); + return; + } + if (!res.ok) return; + const data = await res.json(); + if (data.logs) setGenLogs(data.logs); + if (data.status === 'completed') { + setGenStatus('completed'); + setGenResult(data.result); + setGenerating(false); + setStep(4); + clearInterval(interval); + } else if (data.status === 'failed') { + setGenStatus('failed'); + setGenerating(false); + clearInterval(interval); + } + } catch (e) { + console.error('Poll error:', e); + } + }, 2000); + } + return () => clearInterval(interval); + }, [jobId, genStatus]); + + const fetchVoices = async () => { + try { + const res = await fetch(getApiUrl('/api/saasshorts/voices'), { + headers: { 'X-ElevenLabs-Key': elevenLabsKey }, + }); + if (res.ok) { + const data = await res.json(); + setVoices(data.voices || []); + } + } catch (e) { + console.error('Voices fetch error:', e); + } + }; + + const handleAnalyze = async () => { + if (!url.trim()) return; + if (!geminiApiKey) { + setAnalyzeError('Gemini API key required. Set it in Settings.'); + return; + } + + setAnalyzing(true); + setAnalyzeError(''); + + try { + const res = await fetch(getApiUrl('/api/saasshorts/analyze'), { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'X-Gemini-Key': geminiApiKey, + }, + body: JSON.stringify({ url: url.trim(), num_scripts: numScripts, style, language, actor_gender: actorGender }), + }); + + if (!res.ok) { + let msg = 'Analysis failed'; + try { const err = await res.json(); msg = err.detail || msg; } catch { msg = await res.text() || msg; } + throw new Error(msg); + } + + const data = await res.json(); + setAnalysis(data.analysis); + setWebResearch(data.web_research || null); + setScripts(data.scripts); + setSelectedScript(0); + setFromCache(false); + + // Cache results + saveCache(url.trim(), data.analysis, data.web_research, data.scripts); + + // Pre-fill actor description and narration from first script + if (data.scripts.length > 0) { + setActorDescription(data.scripts[0].actor_description || ''); + setEditedNarration(data.scripts[0].full_narration || ''); + } + + setStep(1); + } catch (e) { + setAnalyzeError(e.message); + } finally { + setAnalyzing(false); + } + }; + + const handleSelectScript = (idx) => { + setSelectedScript(idx); + if (scripts[idx]) { + setActorDescription(scripts[idx].actor_description || ''); + setEditedNarration(scripts[idx].full_narration || ''); + } + }; + + const handleGenerate = async () => { + if (!falKey) { + alert('fal.ai API key required. Set it in Settings.'); + return; + } + if (!elevenLabsKey) { + alert('ElevenLabs API key required. Set it in Settings.'); + return; + } + + setGenerating(true); + setGenLogs(['Starting video generation...']); + setGenStatus('processing'); + setGenResult(null); + setStep(3); + + try { + // Update script with edited narration + const scriptToSend = { ...scripts[selectedScript] }; + if (editedNarration !== scriptToSend.full_narration) { + scriptToSend.full_narration = editedNarration; + } + + const res = await fetch(getApiUrl('/api/saasshorts/generate'), { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'X-Fal-Key': falKey, + 'X-ElevenLabs-Key': elevenLabsKey, + }, + body: JSON.stringify({ + script: scriptToSend, + voice_id: selectedVoice, + actor_description: actorDescription || undefined, + selected_actor_url: selectedActor || undefined, + }), + }); + + if (!res.ok) { + let msg = 'Generation failed'; + try { const err = await res.json(); msg = err.detail || msg; } catch { msg = await res.text() || msg; } + throw new Error(msg); + } + + const data = await res.json(); + setJobId(data.job_id); + } catch (e) { + setGenStatus('failed'); + setGenLogs((prev) => [...prev, `Error: ${e.message}`]); + setGenerating(false); + } + }; + + const handleRetry = async () => { + if (!jobId) return; + setGenerating(true); + setGenLogs(['Retrying from cached assets...']); + setGenStatus('processing'); + setGenResult(null); + + try { + const scriptToSend = { ...scripts[selectedScript] }; + if (editedNarration !== scriptToSend.full_narration) { + scriptToSend.full_narration = editedNarration; + } + + const res = await fetch(getApiUrl('/api/saasshorts/generate'), { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'X-Fal-Key': falKey, + 'X-ElevenLabs-Key': elevenLabsKey, + }, + body: JSON.stringify({ + script: scriptToSend, + voice_id: selectedVoice, + actor_description: actorDescription || undefined, + retry_job_id: jobId, + }), + }); + + if (!res.ok) { + let msg = 'Retry failed'; + try { const err = await res.json(); msg = err.detail || msg; } catch { msg = await res.text() || msg; } + throw new Error(msg); + } + + const data = await res.json(); + setJobId(data.job_id); + } catch (e) { + setGenStatus('failed'); + setGenLogs((prev) => [...prev, `Retry error: ${e.message}`]); + setGenerating(false); + } + }; + + const handleCopy = (text, label) => { + navigator.clipboard.writeText(text); + setCopied(label); + setTimeout(() => setCopied(''), 2000); + }; + + const handleReset = () => { + setStep(0); + setUrl(''); + setAnalyzeError(''); + setAnalysis(null); + setWebResearch(null); + setScripts([]); + setFromCache(false); + localStorage.removeItem(CACHE_KEY); + setSelectedScript(0); + setJobId(null); + setGenLogs([]); + setGenStatus('idle'); + setGenResult(null); + setGenerating(false); + setActorDescription(''); + setEditedNarration(''); + }; + + // ─── Render Steps ───────────────────────────────────────────────── + + return ( +
+
+ {/* Header */} +
+
+

+
+ +
+ SaaS Shorts +

+

+ Generate viral UGC videos for your SaaS with AI actors +

+
+ {step > 0 && ( + + )} +
+ + {/* Progress Steps */} +
+ {['URL & Style', 'Analysis', 'Configure', 'Generate', 'Result'].map((label, i) => ( + + {i > 0 &&
} +
+ + {i < step ? : i + 1} + + {label} +
+ + ))} +
+ + {/* ── Step 0: URL Input ────────────────────────────────── */} + {step === 0 && ( +
+
+
+ +
+
+ + setUrl(e.target.value)} + placeholder="https://your-saas.com" + className="input-field pl-10" + onKeyDown={(e) => e.key === 'Enter' && handleAnalyze()} + /> +
+
+
+ +
+ +
+ {[ + { id: 'en', label: 'English', flag: '🇺🇸' }, + { id: 'es', label: 'Español', flag: '🇪🇸' }, + ].map((l) => ( + + ))} +
+ + +
+ {[ + { id: 'female', label: 'Woman', icon: '👩' }, + { id: 'male', label: 'Man', icon: '👨' }, + ].map((g) => ( + + ))} +
+ + +
+ {STYLE_OPTIONS.map((s) => ( + + ))} +
+
+ +
+ +
+ {[1, 2, 3, 5].map((n) => ( + + ))} +
+
+ + {analyzeError && ( +
+ + {analyzeError} +
+ )} + + +
+ + {/* Info cards */} +
+
+ +

Deep Research

+

AI scrapes your website + searches Google for reviews, Reddit threads, competitors & real user feedback.

+
+
+ +

Pain Point Scripts

+

Generates hook-problem-solution scripts targeting your audience's real pain points.

+
+
+ +

AI Actor Videos

+

Realistic AI-generated actors with lip-sync, b-roll, and viral subtitles. ~$2.50/video.

+
+
+
+ )} + + {/* ── Step 1: Analysis Results ─────────────────────────── */} + {step === 1 && analysis && ( +
+ {/* Analysis Summary */} +
+
+

+ + {analysis.product_name || 'Analysis'} +

+
+ {fromCache && ( + + Cached + + + )} + + {analysis.industry} + +
+
+

{analysis.one_liner}

+ +
+
+

Pain Points

+
+ {(analysis.pain_points || []).map((pp, i) => ( +
+ +
+ {pp.pain} + {pp.source && pp.source !== 'website' && ( + {pp.source} + )} +
+
+ ))} +
+
+
+

Emotional Hooks

+
+ {(analysis.emotional_hooks || []).map((h, i) => ( +
+ + {h} +
+ ))} +
+
+
+
+ + {/* Web Research Results */} + {webResearch && ( +
+

+ + Web Research (Google Search) + {webResearch.grounding_sources && ( + + {webResearch.grounding_sources.length} sources + + )} +

+ + {/* Real user reviews */} + {webResearch.real_reviews && webResearch.real_reviews.length > 0 && ( +
+

Real User Reviews

+
+ {webResearch.real_reviews.slice(0, 5).map((review, i) => ( +
+

"{review.quote}"

+
+ {review.source} + {review.sentiment} +
+
+ ))} +
+
+ )} + + {/* Competitors */} + {webResearch.competitors && webResearch.competitors.length > 0 && ( +
+

Competitors

+
+ {webResearch.competitors.map((c, i) => ( + + {c.name} + + ))} +
+
+ )} + + {/* Sources */} + {webResearch.grounding_sources && webResearch.grounding_sources.length > 0 && ( +
+

Sources

+
+ {webResearch.grounding_sources.slice(0, 8).map((src, i) => ( + + {src.title || (() => { try { return new URL(src.url).hostname; } catch { return src.url; } })()} + + ))} +
+
+ )} +
+ )} + + {/* Scripts */} +
+

+ + Generated Scripts + {scripts.length} scripts +

+ +
+ {scripts.map((script, i) => ( +
handleSelectScript(i)} + className={`glass-panel p-5 cursor-pointer transition-all ${ + selectedScript === i + ? 'border-violet-500/50 bg-violet-500/5 ring-1 ring-violet-500/20' + : 'hover:bg-white/5' + }`} + > +
+
+ + {i + 1} + +
+

{script.title}

+ {script.duration_seconds}s · {script.style} · {script.target_platform} +
+
+ {selectedScript === i && ( + Selected + )} +
+ + {/* Segments preview */} +
+ {(script.segments || []).map((seg, j) => ( +
+ ))} +
+ +
+ {(script.segments || []).map((seg, j) => ( +
+ + {seg.type} + + {seg.narration} +
+ ))} +
+ + {/* Hook text & hashtags */} +
+ + Hook: "{script.hook_text}" + + {(script.hashtags || []).slice(0, 4).map((tag, j) => ( + {tag} + ))} +
+
+ ))} +
+
+ +
+ + +
+
+ )} + + {/* ── Step 2: Configure ────────────────────────────────── */} + {step === 2 && scripts[selectedScript] && ( +
+
+

Configure Video

+

+ Script: {scripts[selectedScript].title} +

+ + {/* Voice Selection */} +
+ + {(() => { + // Filter voices by language/accent + const filtered = voices.length > 0 + ? voices.filter((v) => { + const gender = (v.labels?.gender || '').toLowerCase(); + // Filter by gender only — for Spanish, multilingual_v2 makes any voice work + return !gender || gender === actorGender; + }) + .sort((a, b) => { + const aAccent = (a.labels?.accent || '').toLowerCase(); + const bAccent = (b.labels?.accent || '').toLowerCase(); + if (language === 'es') { + // Spanish/latin accents first, then everything else + const aScore = (aAccent.includes('spanish') || aAccent.includes('latin')) ? 0 : 1; + const bScore = (bAccent.includes('spanish') || bAccent.includes('latin')) ? 0 : 1; + return aScore - bScore; + } + // English: american/british first + const aScore = (aAccent.includes('american') || aAccent.includes('british')) ? 0 : 1; + const bScore = (bAccent.includes('american') || bAccent.includes('british')) ? 0 : 1; + return aScore - bScore; + }) + : []; + + if (filtered.length > 0) { + return ( +
+ {filtered.map((v) => ( + + )} + {selectedVoice === v.voice_id && } + + ))} +
+ ); + } + + // Fallback defaults by gender + language + const defaults = { + 'en-female': [ + { id: '21m00Tcm4TlvDq8ikWAM', name: 'Rachel (calm)' }, + { id: 'EXAVITQu4vr4xnSDxMaL', name: 'Bella (soft)' }, + ], + 'en-male': [ + { id: '29vD33N1CtxCmqQRPOHJ', name: 'Drew (confident)' }, + { id: 'TxGEqnHWrfWFTfGW9XjX', name: 'Josh (deep)' }, + { id: 'yoZ06aMxZJJ28mfd3POQ', name: 'Sam (raspy)' }, + ], + 'es-female': [ + { id: 'EXAVITQu4vr4xnSDxMaL', name: 'Bella (suave)' }, + { id: '21m00Tcm4TlvDq8ikWAM', name: 'Rachel (calmada)' }, + ], + 'es-male': [ + { id: 'ErXwobaYiN019PkySvjV', name: 'Antoni (cálido)' }, + { id: '29vD33N1CtxCmqQRPOHJ', name: 'Drew (confiado)' }, + ], + }; + const key = `${language}-${actorGender}`; + const opts = defaults[key] || defaults['en-female']; + return ( + + ); + })()} +

+ {language === 'es' + ? `Voces ${actorGender === 'female' ? 'femeninas' : 'masculinas'} · Todas hablan español con modelo multilingual · Click altavoz para preview` + : `${actorGender === 'female' ? 'Female' : 'Male'} voices · Click speaker to preview`} +

+
+ + {/* Actor Description + Mandatory Selection */} +
+ +