feat: podcast demo mode with ALWRITY_ENABLED_FEATURES support
- Add ALWRITY_ENABLED_FEATURES env var for feature gating - Podcast-only mode: skip LLM bootstrap, scheduler, persona services - Enhance video generation prompt with scene context, analysis, narration - Add voice cloning support via custom_voice_id in WaveSpeed - Add text-to-speech for research results (browser speechSynthesis) - Fix render queue to sync images from script phase - Add WaveSpeed LLM pricing (gpt-oss-120b) - Fix podcast bible generation error handling - Refactor RouterManager for feature-based router loading
This commit is contained in:
@@ -116,6 +116,10 @@ class RouterManager:
|
|||||||
if "all" in enabled_features:
|
if "all" in enabled_features:
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
# Skip core routers in podcast-only mode (they require non-podcast features)
|
||||||
|
if enabled_features == {"podcast"}:
|
||||||
|
return False
|
||||||
|
|
||||||
# If no required features specified, include by default
|
# If no required features specified, include by default
|
||||||
if not required_features:
|
if not required_features:
|
||||||
return True
|
return True
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ Centralized constants and directory configuration for podcast module.
|
|||||||
|
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Literal
|
from typing import Literal
|
||||||
|
from loguru import logger
|
||||||
from services.story_writer.audio_generation_service import StoryAudioGenerationService
|
from services.story_writer.audio_generation_service import StoryAudioGenerationService
|
||||||
|
|
||||||
# Directory paths
|
# Directory paths
|
||||||
@@ -45,11 +46,14 @@ def get_podcast_media_dir(
|
|||||||
}[media_type]
|
}[media_type]
|
||||||
|
|
||||||
if user_id:
|
if user_id:
|
||||||
tenant_media_dir = ROOT_DIR / "workspace" / f"workspace_{_sanitize_user_id(user_id)}" / "media" / media_subdir
|
sanitized = _sanitize_user_id(user_id)
|
||||||
|
tenant_media_dir = ROOT_DIR / "workspace" / f"workspace_{sanitized}" / "media" / media_subdir
|
||||||
resolved_dir = tenant_media_dir.resolve()
|
resolved_dir = tenant_media_dir.resolve()
|
||||||
else:
|
else:
|
||||||
resolved_dir = (DATA_MEDIA_DIR / media_subdir).resolve()
|
resolved_dir = (DATA_MEDIA_DIR / media_subdir).resolve()
|
||||||
|
|
||||||
|
logger.debug(f"[Podcast] get_podcast_media_dir: type={media_type}, user_id={user_id}, sanitized={user_id and _sanitize_user_id(user_id)}, resolved={resolved_dir}")
|
||||||
|
|
||||||
if ensure_exists:
|
if ensure_exists:
|
||||||
resolved_dir.mkdir(parents=True, exist_ok=True)
|
resolved_dir.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
@@ -61,7 +65,9 @@ def get_podcast_media_read_dirs(media_type: MediaType, user_id: str | None = Non
|
|||||||
dirs: list[Path] = []
|
dirs: list[Path] = []
|
||||||
if user_id:
|
if user_id:
|
||||||
dirs.append(get_podcast_media_dir(media_type, user_id))
|
dirs.append(get_podcast_media_dir(media_type, user_id))
|
||||||
|
logger.debug(f"[Podcast] get_podcast_media_read_dirs: added user dir for {user_id}")
|
||||||
dirs.append(get_podcast_media_dir(media_type, None))
|
dirs.append(get_podcast_media_dir(media_type, None))
|
||||||
|
logger.debug(f"[Podcast] get_podcast_media_read_dirs: dirs={dirs}")
|
||||||
return dirs
|
return dirs
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -5,10 +5,11 @@ Analysis endpoint for podcast ideas.
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends, HTTPException
|
from fastapi import APIRouter, Depends, HTTPException
|
||||||
from typing import Dict, Any
|
from typing import Dict, Any, Optional, List
|
||||||
import json
|
import json
|
||||||
import uuid
|
import uuid
|
||||||
from sqlalchemy.orm import Session
|
from sqlalchemy.orm import Session
|
||||||
|
from pydantic import BaseModel
|
||||||
|
|
||||||
from services.database import get_db
|
from services.database import get_db
|
||||||
from middleware.auth_middleware import get_current_user
|
from middleware.auth_middleware import get_current_user
|
||||||
@@ -258,6 +259,10 @@ Return JSON with:
|
|||||||
- top_keywords: 5 podcast-relevant keywords/phrases
|
- top_keywords: 5 podcast-relevant keywords/phrases
|
||||||
- suggested_outlines: 2 items, each with title (<=60 chars) and 4-6 short segments (bullet-friendly, factual)
|
- suggested_outlines: 2 items, each with title (<=60 chars) and 4-6 short segments (bullet-friendly, factual)
|
||||||
- title_suggestions: 3 concise episode titles
|
- title_suggestions: 3 concise episode titles
|
||||||
|
- episode_hook: one compelling 15-30 second opening hook/angle that grabs attention
|
||||||
|
- key_takeaways: 3-5 actionable insights listeners will learn
|
||||||
|
- guest_talking_points: (if guest included) 3-4 suggested questions/angles for guest interview
|
||||||
|
- listener_cta: one clear call-to-action for listeners
|
||||||
- research_queries: array of {{"query": "string", "rationale": "string"}}
|
- research_queries: array of {{"query": "string", "rationale": "string"}}
|
||||||
- exa_suggested_config: suggested Exa search options with:
|
- exa_suggested_config: suggested Exa search options with:
|
||||||
- exa_search_type: "auto" | "neural" | "keyword"
|
- exa_search_type: "auto" | "neural" | "keyword"
|
||||||
@@ -271,7 +276,10 @@ Return JSON with:
|
|||||||
Requirements:
|
Requirements:
|
||||||
- Keep language factual, actionable, and suited for spoken audio.
|
- Keep language factual, actionable, and suited for spoken audio.
|
||||||
- Avoid narrative fiction tone.
|
- Avoid narrative fiction tone.
|
||||||
- Prefer 2024-2025 context.
|
- For research queries: Mix of time-sensitive and evergreen queries:
|
||||||
|
- 2-3 queries should focus on latest 2025-2026 developments, trends, and data (use year in query)
|
||||||
|
- 2-3 queries should be evergreen/fundamental (concepts, definitions, best practices, proven strategies) - do NOT include years in these
|
||||||
|
- Today's date is April 2026.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
try:
|
try:
|
||||||
@@ -305,6 +313,10 @@ Requirements:
|
|||||||
top_keywords = data.get("top_keywords") or []
|
top_keywords = data.get("top_keywords") or []
|
||||||
suggested_outlines = data.get("suggested_outlines") or []
|
suggested_outlines = data.get("suggested_outlines") or []
|
||||||
title_suggestions = data.get("title_suggestions") or []
|
title_suggestions = data.get("title_suggestions") or []
|
||||||
|
episode_hook = data.get("episode_hook") or ""
|
||||||
|
key_takeaways = data.get("key_takeaways") or []
|
||||||
|
guest_talking_points = data.get("guest_talking_points") or []
|
||||||
|
listener_cta = data.get("listener_cta") or ""
|
||||||
research_queries = data.get("research_queries") or []
|
research_queries = data.get("research_queries") or []
|
||||||
exa_suggested_config = data.get("exa_suggested_config") or None
|
exa_suggested_config = data.get("exa_suggested_config") or None
|
||||||
|
|
||||||
@@ -314,6 +326,10 @@ Requirements:
|
|||||||
top_keywords=top_keywords,
|
top_keywords=top_keywords,
|
||||||
suggested_outlines=suggested_outlines,
|
suggested_outlines=suggested_outlines,
|
||||||
title_suggestions=title_suggestions,
|
title_suggestions=title_suggestions,
|
||||||
|
episode_hook=episode_hook,
|
||||||
|
key_takeaways=key_takeaways,
|
||||||
|
guest_talking_points=guest_talking_points,
|
||||||
|
listener_cta=listener_cta,
|
||||||
research_queries=research_queries,
|
research_queries=research_queries,
|
||||||
exa_suggested_config=exa_suggested_config,
|
exa_suggested_config=exa_suggested_config,
|
||||||
bible=bible_obj.model_dump() if bible_obj else None,
|
bible=bible_obj.model_dump() if bible_obj else None,
|
||||||
@@ -321,3 +337,106 @@ Requirements:
|
|||||||
avatar_prompt=final_avatar_prompt,
|
avatar_prompt=final_avatar_prompt,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class RegenerateQueriesRequest(BaseModel):
|
||||||
|
idea: str
|
||||||
|
feedback: str
|
||||||
|
existing_analysis: Optional[Dict[str, Any]] = None
|
||||||
|
bible: Optional[Dict[str, Any]] = None
|
||||||
|
|
||||||
|
|
||||||
|
class RegenerateQueriesResponse(BaseModel):
|
||||||
|
research_queries: List[Dict[str, str]]
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/regenerate-queries", response_model=RegenerateQueriesResponse)
|
||||||
|
async def regenerate_research_queries(
|
||||||
|
request: RegenerateQueriesRequest,
|
||||||
|
current_user: Dict[str, Any] = Depends(get_current_user),
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Regenerate research queries based on user feedback and existing analysis.
|
||||||
|
"""
|
||||||
|
user_id = require_authenticated_user(current_user)
|
||||||
|
|
||||||
|
# Build context from existing analysis
|
||||||
|
idea = request.idea
|
||||||
|
feedback = request.feedback
|
||||||
|
|
||||||
|
# Get topic, keywords, audience from existing analysis if provided
|
||||||
|
topic = idea
|
||||||
|
keywords = ""
|
||||||
|
audience = ""
|
||||||
|
if request.existing_analysis:
|
||||||
|
topic = request.existing_analysis.get("title_suggestions", [idea])[0] if request.existing_analysis.get("title_suggestions") else idea
|
||||||
|
keywords = ", ".join(request.existing_analysis.get("top_keywords", [])[:5])
|
||||||
|
audience = request.existing_analysis.get("audience", "")
|
||||||
|
|
||||||
|
# Serialize Bible context if provided
|
||||||
|
bible_context = ""
|
||||||
|
if request.bible:
|
||||||
|
try:
|
||||||
|
bible_service = PodcastBibleService()
|
||||||
|
from models.podcast_bible_models import PodcastBible
|
||||||
|
bible_data = PodcastBible(**request.bible)
|
||||||
|
bible_context = bible_service.serialize_bible(bible_data)
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f"Failed to serialize bible for query regeneration: {e}")
|
||||||
|
|
||||||
|
prompt = f"""
|
||||||
|
You are a research strategist for podcast content. Given a podcast idea, existing analysis, and user feedback,
|
||||||
|
generate 7 new research queries that address the user's specific needs.
|
||||||
|
|
||||||
|
{f"USER FEEDBACK: {feedback}" if feedback else ""}
|
||||||
|
|
||||||
|
{f"EXISTING ANALYSIS CONTEXT:\n- Topic: {topic}\n- Keywords: {keywords}\n- Audience: {audience}\n" if request.existing_analysis else ""}
|
||||||
|
{f"PODCAST BIBLE CONTEXT:\n{bible_context}\n" if bible_context else ""}
|
||||||
|
|
||||||
|
Podcast Idea: "{idea}"
|
||||||
|
|
||||||
|
TASK:
|
||||||
|
Generate exactly 7 research queries that:
|
||||||
|
1. Incorporate the user's feedback direction
|
||||||
|
2. Build on the existing analysis context
|
||||||
|
3. Mix of time-sensitive (2025-2026) and evergreen topics
|
||||||
|
4. Are highly specific to the podcast topic
|
||||||
|
|
||||||
|
Return JSON with:
|
||||||
|
- research_queries: array of {{"query": "string", "rationale": "string"}}
|
||||||
|
|
||||||
|
Requirements:
|
||||||
|
- At least 2-3 queries should focus on latest 2025-2026 developments (include year in query)
|
||||||
|
- At least 2-3 queries should be evergreen (concepts, definitions, best practices - NO year)
|
||||||
|
- Queries should be specific and actionable, not generic
|
||||||
|
"""
|
||||||
|
|
||||||
|
try:
|
||||||
|
from services.llm_providers.main_text_generation import llm_text_gen
|
||||||
|
|
||||||
|
raw = llm_text_gen(
|
||||||
|
prompt=prompt,
|
||||||
|
user_id=user_id,
|
||||||
|
json_struct={"research_queries": [{"query": "string", "rationale": "string"}]},
|
||||||
|
preferred_provider=None,
|
||||||
|
flow_type="premium_tool",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Parse response
|
||||||
|
if isinstance(raw, dict):
|
||||||
|
queries = raw.get("research_queries", [])
|
||||||
|
else:
|
||||||
|
# Try to parse as JSON
|
||||||
|
try:
|
||||||
|
parsed = json.loads(raw) if isinstance(raw, str) else raw
|
||||||
|
queries = parsed.get("research_queries", []) if isinstance(parsed, dict) else []
|
||||||
|
except:
|
||||||
|
queries = []
|
||||||
|
|
||||||
|
return RegenerateQueriesResponse(research_queries=queries[:7])
|
||||||
|
|
||||||
|
except HTTPException:
|
||||||
|
raise
|
||||||
|
except Exception as exc:
|
||||||
|
logger.error(f"[Regenerate Queries] Failed for user {user_id}: {exc}")
|
||||||
|
raise HTTPException(status_code=500, detail=f"Regenerate queries failed: {exc}")
|
||||||
|
|
||||||
|
|||||||
@@ -126,12 +126,14 @@ async def generate_podcast_audio(
|
|||||||
|
|
||||||
try:
|
try:
|
||||||
audio_service = get_podcast_audio_service(user_id)
|
audio_service = get_podcast_audio_service(user_id)
|
||||||
|
logger.warning(f"[Podcast] Generating audio with service dir: {audio_service.output_dir}")
|
||||||
result: StoryAudioResult = audio_service.generate_ai_audio(
|
result: StoryAudioResult = audio_service.generate_ai_audio(
|
||||||
scene_number=0,
|
scene_number=0,
|
||||||
scene_title=request.scene_title,
|
scene_title=request.scene_title,
|
||||||
text=request.text.strip(),
|
text=request.text.strip(),
|
||||||
user_id=user_id,
|
user_id=user_id,
|
||||||
voice_id=request.voice_id or "Wise_Woman",
|
voice_id=request.voice_id or "Wise_Woman",
|
||||||
|
custom_voice_id=request.custom_voice_id,
|
||||||
speed=request.speed or 1.0, # Normal speed (was 0.9, but too slow - causing duration issues)
|
speed=request.speed or 1.0, # Normal speed (was 0.9, but too slow - causing duration issues)
|
||||||
volume=request.volume or 1.0,
|
volume=request.volume or 1.0,
|
||||||
pitch=request.pitch or 0.0, # Normal pitch (0.0 = neutral)
|
pitch=request.pitch or 0.0, # Normal pitch (0.0 = neutral)
|
||||||
@@ -149,6 +151,8 @@ async def generate_podcast_audio(
|
|||||||
if result.get("audio_url") and "/api/story/audio/" in result.get("audio_url", ""):
|
if result.get("audio_url") and "/api/story/audio/" in result.get("audio_url", ""):
|
||||||
audio_filename = result.get("audio_filename", "")
|
audio_filename = result.get("audio_filename", "")
|
||||||
result["audio_url"] = f"/api/podcast/audio/{audio_filename}"
|
result["audio_url"] = f"/api/podcast/audio/{audio_filename}"
|
||||||
|
|
||||||
|
logger.warning(f"[Podcast] Audio generated - path: {result.get('audio_path')}, url: {result.get('audio_url')}")
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
raise HTTPException(status_code=500, detail=f"Audio generation failed: {exc}")
|
raise HTTPException(status_code=500, detail=f"Audio generation failed: {exc}")
|
||||||
|
|
||||||
@@ -387,7 +391,9 @@ async def serve_podcast_audio(
|
|||||||
raise HTTPException(status_code=400, detail="Invalid filename")
|
raise HTTPException(status_code=400, detail="Invalid filename")
|
||||||
|
|
||||||
user_id = require_authenticated_user(current_user)
|
user_id = require_authenticated_user(current_user)
|
||||||
|
logger.warning(f"[Podcast] serve_podcast_audio called: user_id={user_id}, filename={filename}")
|
||||||
audio_path = _resolve_podcast_media_file(filename, "audio", user_id)
|
audio_path = _resolve_podcast_media_file(filename, "audio", user_id)
|
||||||
|
logger.warning(f"[Podcast] Resolved audio path: {audio_path}")
|
||||||
|
|
||||||
return FileResponse(audio_path, media_type="audio/mpeg")
|
return FileResponse(audio_path, media_type="audio/mpeg")
|
||||||
|
|
||||||
|
|||||||
@@ -104,6 +104,16 @@ async def generate_podcast_scene_image(
|
|||||||
# Otherwise, generate from scratch with podcast-optimized prompt
|
# Otherwise, generate from scratch with podcast-optimized prompt
|
||||||
image_prompt = "" # Initialize prompt variable
|
image_prompt = "" # Initialize prompt variable
|
||||||
|
|
||||||
|
# Emotion to lighting mapping for visual tone
|
||||||
|
emotion_lighting = {
|
||||||
|
"happy": "warm, bright lighting, cheerful atmosphere",
|
||||||
|
"excited": "dynamic, energetic lighting with highlights",
|
||||||
|
"serious": "professional, balanced lighting, authoritative feel",
|
||||||
|
"curious": "soft, inviting lighting, thoughtful atmosphere",
|
||||||
|
"confident": "strong, dramatic lighting, authoritative look",
|
||||||
|
"neutral": "professional, balanced lighting"
|
||||||
|
}
|
||||||
|
|
||||||
if base_avatar_bytes:
|
if base_avatar_bytes:
|
||||||
# Use Ideogram Character API for consistent character generation
|
# Use Ideogram Character API for consistent character generation
|
||||||
# Use custom prompt if provided, otherwise build scene-specific prompt
|
# Use custom prompt if provided, otherwise build scene-specific prompt
|
||||||
@@ -127,6 +137,28 @@ async def generate_podcast_scene_image(
|
|||||||
if bible_obj.host.look:
|
if bible_obj.host.look:
|
||||||
prompt_parts.append(f"Host Look: {bible_obj.host.look}")
|
prompt_parts.append(f"Host Look: {bible_obj.host.look}")
|
||||||
|
|
||||||
|
# Scene emotion for visual tone
|
||||||
|
emotion_lighting = {
|
||||||
|
"happy": "warm, bright lighting, cheerful atmosphere",
|
||||||
|
"excited": "dynamic, energetic lighting with highlights",
|
||||||
|
"serious": "professional, balanced lighting, authoritative feel",
|
||||||
|
"curious": "soft, inviting lighting, thoughtful atmosphere",
|
||||||
|
"confident": "strong, dramatic lighting, authoritative look",
|
||||||
|
"neutral": "professional, balanced lighting"
|
||||||
|
}
|
||||||
|
scene_emotion = request.scene_emotion
|
||||||
|
if scene_emotion and scene_emotion in emotion_lighting:
|
||||||
|
prompt_parts.append(emotion_lighting[scene_emotion])
|
||||||
|
|
||||||
|
# AI Analysis context for visual relevance
|
||||||
|
if request.analysis:
|
||||||
|
keywords = request.analysis.get("topKeywords", [])[:5]
|
||||||
|
if keywords:
|
||||||
|
prompt_parts.append(f"Keywords: {', '.join(keywords)}")
|
||||||
|
audience = request.analysis.get("audience", "")
|
||||||
|
if audience:
|
||||||
|
prompt_parts.append(f"Target: {audience}")
|
||||||
|
|
||||||
# Scene content insights for visual context
|
# Scene content insights for visual context
|
||||||
if request.scene_content:
|
if request.scene_content:
|
||||||
content_preview = request.scene_content[:200].replace("\n", " ").strip()
|
content_preview = request.scene_content[:200].replace("\n", " ").strip()
|
||||||
@@ -139,6 +171,12 @@ async def generate_podcast_scene_image(
|
|||||||
visual_keywords.append("modern tech studio setting")
|
visual_keywords.append("modern tech studio setting")
|
||||||
if any(word in content_lower for word in ["business", "growth", "strategy", "market"]):
|
if any(word in content_lower for word in ["business", "growth", "strategy", "market"]):
|
||||||
visual_keywords.append("professional business studio")
|
visual_keywords.append("professional business studio")
|
||||||
|
if any(word in content_lower for word in ["nature", "outdoor", "environment", "green"]):
|
||||||
|
visual_keywords.append("natural outdoor setting")
|
||||||
|
if any(word in content_lower for word in ["medical", "health", "wellness"]):
|
||||||
|
visual_keywords.append("clean medical studio")
|
||||||
|
if any(word in content_lower for word in ["education", "learning", "students"]):
|
||||||
|
visual_keywords.append("classroom or educational setting")
|
||||||
if visual_keywords:
|
if visual_keywords:
|
||||||
prompt_parts.append(", ".join(visual_keywords))
|
prompt_parts.append(", ".join(visual_keywords))
|
||||||
|
|
||||||
@@ -265,6 +303,19 @@ async def generate_podcast_scene_image(
|
|||||||
if request.scene_title:
|
if request.scene_title:
|
||||||
prompt_parts.append(f"Scene theme: {request.scene_title}")
|
prompt_parts.append(f"Scene theme: {request.scene_title}")
|
||||||
|
|
||||||
|
# Scene emotion for visual tone (no avatar branch)
|
||||||
|
if request.scene_emotion and request.scene_emotion in emotion_lighting:
|
||||||
|
prompt_parts.append(emotion_lighting[request.scene_emotion])
|
||||||
|
|
||||||
|
# AI Analysis context (no avatar branch)
|
||||||
|
if request.analysis:
|
||||||
|
keywords = request.analysis.get("topKeywords", [])[:5]
|
||||||
|
if keywords:
|
||||||
|
prompt_parts.append(f"Keywords: {', '.join(keywords)}")
|
||||||
|
audience = request.analysis.get("audience", "")
|
||||||
|
if audience:
|
||||||
|
prompt_parts.append(f"Target: {audience}")
|
||||||
|
|
||||||
# Content context for visual relevance
|
# Content context for visual relevance
|
||||||
if request.scene_content:
|
if request.scene_content:
|
||||||
content_preview = request.scene_content[:150].replace("\n", " ").strip()
|
content_preview = request.scene_content[:150].replace("\n", " ").strip()
|
||||||
@@ -276,6 +327,12 @@ async def generate_podcast_scene_image(
|
|||||||
visual_keywords.append("modern technology aesthetic")
|
visual_keywords.append("modern technology aesthetic")
|
||||||
if any(word in content_lower for word in ["business", "growth", "strategy", "market"]):
|
if any(word in content_lower for word in ["business", "growth", "strategy", "market"]):
|
||||||
visual_keywords.append("professional business environment")
|
visual_keywords.append("professional business environment")
|
||||||
|
if any(word in content_lower for word in ["nature", "outdoor", "environment"]):
|
||||||
|
visual_keywords.append("natural outdoor setting")
|
||||||
|
if any(word in content_lower for word in ["medical", "health", "wellness"]):
|
||||||
|
visual_keywords.append("clean medical studio")
|
||||||
|
if any(word in content_lower for word in ["education", "learning", "students"]):
|
||||||
|
visual_keywords.append("classroom or educational setting")
|
||||||
if visual_keywords:
|
if visual_keywords:
|
||||||
prompt_parts.append(", ".join(visual_keywords))
|
prompt_parts.append(", ".join(visual_keywords))
|
||||||
|
|
||||||
@@ -379,6 +436,7 @@ async def generate_podcast_scene_image(
|
|||||||
provider=result.provider,
|
provider=result.provider,
|
||||||
model=result.model,
|
model=result.model,
|
||||||
cost=cost,
|
cost=cost,
|
||||||
|
image_prompt=image_prompt,
|
||||||
)
|
)
|
||||||
|
|
||||||
except HTTPException:
|
except HTTPException:
|
||||||
|
|||||||
@@ -27,7 +27,10 @@ async def create_project(
|
|||||||
db: Session = Depends(get_db),
|
db: Session = Depends(get_db),
|
||||||
current_user: Dict[str, Any] = Depends(get_current_user),
|
current_user: Dict[str, Any] = Depends(get_current_user),
|
||||||
):
|
):
|
||||||
"""Create a new podcast project."""
|
"""Create a new podcast project.
|
||||||
|
|
||||||
|
If a project with the same idea already exists, return 409 conflict with existing project info.
|
||||||
|
"""
|
||||||
try:
|
try:
|
||||||
user_id = current_user.get("user_id") or current_user.get("id")
|
user_id = current_user.get("user_id") or current_user.get("id")
|
||||||
if not user_id:
|
if not user_id:
|
||||||
@@ -40,6 +43,19 @@ async def create_project(
|
|||||||
if existing:
|
if existing:
|
||||||
raise HTTPException(status_code=400, detail="Project ID already exists")
|
raise HTTPException(status_code=400, detail="Project ID already exists")
|
||||||
|
|
||||||
|
# Check for duplicate idea (case-insensitive partial match)
|
||||||
|
existing_idea = service.get_project_by_idea(user_id, request.idea)
|
||||||
|
if existing_idea:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=409,
|
||||||
|
detail={
|
||||||
|
"message": "A project with similar idea already exists",
|
||||||
|
"existing_project_id": existing_idea.project_id,
|
||||||
|
"existing_idea": existing_idea.idea,
|
||||||
|
"existing_status": existing_idea.status,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
project = service.create_project(
|
project = service.create_project(
|
||||||
user_id=user_id,
|
user_id=user_id,
|
||||||
project_id=request.project_id,
|
project_id=request.project_id,
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ from fastapi import APIRouter, Depends, HTTPException
|
|||||||
from typing import Dict, Any, List
|
from typing import Dict, Any, List
|
||||||
from types import SimpleNamespace
|
from types import SimpleNamespace
|
||||||
import json
|
import json
|
||||||
|
import re
|
||||||
|
|
||||||
from middleware.auth_middleware import get_current_user
|
from middleware.auth_middleware import get_current_user
|
||||||
from api.story_writer.utils.auth import require_authenticated_user
|
from api.story_writer.utils.auth import require_authenticated_user
|
||||||
@@ -36,10 +37,16 @@ async def podcast_research_exa(
|
|||||||
Uses Podcast Bible and Analysis context for hyper-personalization.
|
Uses Podcast Bible and Analysis context for hyper-personalization.
|
||||||
"""
|
"""
|
||||||
user_id = require_authenticated_user(current_user)
|
user_id = require_authenticated_user(current_user)
|
||||||
|
logger.warning(f"[Podcast Research] ========== REQUEST START ==========")
|
||||||
|
logger.warning(f"[Podcast Research] User: {user_id}, Topic: {request.topic[:80]}...")
|
||||||
|
logger.warning(f"[Podcast Research] Queries count: {len(request.queries) if request.queries else 0}")
|
||||||
|
|
||||||
|
|
||||||
queries = [q.strip() for q in request.queries if q and q.strip()]
|
queries = [q.strip() for q in request.queries if q and q.strip()]
|
||||||
if not queries:
|
if not queries:
|
||||||
raise HTTPException(status_code=400, detail="At least one query is required for research.")
|
raise HTTPException(status_code=400, detail="At least one query is required for research.")
|
||||||
|
|
||||||
|
logger.warning(f"[Podcast Research] EXACT queries being sent to Exa: {queries}")
|
||||||
|
|
||||||
exa_cfg = request.exa_config or PodcastExaConfig()
|
exa_cfg = request.exa_config or PodcastExaConfig()
|
||||||
cfg = SimpleNamespace(
|
cfg = SimpleNamespace(
|
||||||
@@ -52,6 +59,7 @@ async def podcast_research_exa(
|
|||||||
)
|
)
|
||||||
|
|
||||||
provider = ExaResearchProvider()
|
provider = ExaResearchProvider()
|
||||||
|
logger.warning(f"[Podcast Research] Provider initialized, starting Exa search...")
|
||||||
|
|
||||||
# --- Context Building ---
|
# --- Context Building ---
|
||||||
bible_service = PodcastBibleService()
|
bible_service = PodcastBibleService()
|
||||||
@@ -68,9 +76,16 @@ async def podcast_research_exa(
|
|||||||
if request.analysis:
|
if request.analysis:
|
||||||
analysis_context = f"""
|
analysis_context = f"""
|
||||||
PODCAST ANALYSIS CONTEXT:
|
PODCAST ANALYSIS CONTEXT:
|
||||||
Audience: {request.analysis.get('audience', 'General')}
|
========================
|
||||||
|
Topic: {request.topic}
|
||||||
|
Target Audience: {request.analysis.get('audience', 'General')}
|
||||||
Content Type: {request.analysis.get('content_type', 'Informative')}
|
Content Type: {request.analysis.get('content_type', 'Informative')}
|
||||||
Top Keywords: {', '.join(request.analysis.get('top_keywords', []))}
|
Top Keywords: {', '.join(request.analysis.get('top_keywords', []))}
|
||||||
|
|
||||||
|
Episode Hook (Intro): {request.analysis.get('episode_hook', 'N/A')}
|
||||||
|
Key Takeaways: {', '.join(request.analysis.get('key_takeaways', [])) or 'N/A'}
|
||||||
|
Guest Talking Points: {', '.join(request.analysis.get('guest_talking_points', [])) or 'N/A'}
|
||||||
|
Listener CTA: {request.analysis.get('listener_cta', 'N/A')}
|
||||||
"""
|
"""
|
||||||
|
|
||||||
# Exa search params
|
# Exa search params
|
||||||
@@ -84,6 +99,7 @@ Top Keywords: {', '.join(request.analysis.get('top_keywords', []))}
|
|||||||
|
|
||||||
try:
|
try:
|
||||||
# 1. RUN EXA SEARCH
|
# 1. RUN EXA SEARCH
|
||||||
|
logger.warning(f"[Podcast Research] Calling Exa search with topic: {request.topic[:100]}...")
|
||||||
result = await provider.search(
|
result = await provider.search(
|
||||||
prompt=request.topic,
|
prompt=request.topic,
|
||||||
topic=request.topic,
|
topic=request.topic,
|
||||||
@@ -92,8 +108,9 @@ Top Keywords: {', '.join(request.analysis.get('top_keywords', []))}
|
|||||||
config=cfg,
|
config=cfg,
|
||||||
user_id=user_id,
|
user_id=user_id,
|
||||||
)
|
)
|
||||||
|
logger.warning(f"[Podcast Research] Exa search completed, got {len(result.get('sources', []))} sources")
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
logger.error(f"[Podcast Exa Research] Search failed for user {user_id}: {exc}")
|
logger.error(f"[Podcast Exa Research] Search failed for user {user_id}: {exc}", exc_info=True)
|
||||||
raise HTTPException(status_code=500, detail=f"Exa research failed: {exc}")
|
raise HTTPException(status_code=500, detail=f"Exa research failed: {exc}")
|
||||||
|
|
||||||
# 2. EXTRACT INSIGHTS VIA LLM
|
# 2. EXTRACT INSIGHTS VIA LLM
|
||||||
@@ -104,46 +121,77 @@ Top Keywords: {', '.join(request.analysis.get('top_keywords', []))}
|
|||||||
key_insights = []
|
key_insights = []
|
||||||
|
|
||||||
if raw_content and sources:
|
if raw_content and sources:
|
||||||
logger.info(f"[Podcast Research] Extracting insights from {len(sources)} sources for user {user_id}")
|
logger.warning(f"[Podcast Research] Extracting insights from {len(sources)} sources for user {user_id}")
|
||||||
|
|
||||||
|
# Build list of research queries used for this search
|
||||||
|
queries_used = ", ".join([f"Query {i+1}: {q}" for i, q in enumerate(queries)]) if queries else "No specific queries"
|
||||||
|
|
||||||
prompt = f"""
|
prompt = f"""
|
||||||
You are an expert research analyst for a high-end podcast production team.
|
You are an expert research analyst and content strategist for a high-end podcast production team.
|
||||||
Your task is to analyze the following research data and extract deep, actionable insights for a podcast episode.
|
Your task is to analyze the research data and extract deep, podcast-ready insights.
|
||||||
|
|
||||||
PODCAST CONTEXT:
|
PODCAST CONTEXT:
|
||||||
Topic: {request.topic}
|
================
|
||||||
|
Main Topic: {request.topic}
|
||||||
|
|
||||||
|
RESEARCH QUERIES USED:
|
||||||
|
=====================
|
||||||
|
{queries_used}
|
||||||
|
|
||||||
|
PODCAST BIBLE & BRAND CONTEXT:
|
||||||
|
==============================
|
||||||
{bible_context}
|
{bible_context}
|
||||||
|
|
||||||
|
PODCAST ANALYSIS (from AI Analysis phase):
|
||||||
|
==========================================
|
||||||
{analysis_context}
|
{analysis_context}
|
||||||
|
|
||||||
RESEARCH DATA (from {len(sources)} sources):
|
RESEARCH DATA (from {len(sources)} sources):
|
||||||
|
============================================
|
||||||
{raw_content}
|
{raw_content}
|
||||||
|
|
||||||
TASK:
|
YOUR TASK:
|
||||||
1. Provide a comprehensive summary (2-3 paragraphs) of the most important findings. Use Markdown for formatting (bolding, lists).
|
==========
|
||||||
2. Extract 3-5 "Key Insights". Each insight should have a title and a detailed explanation.
|
As a podcast research expert, analyze this data and create content that will:
|
||||||
3. For each insight, identify which source indices (e.g. 1, 2) it was derived from.
|
1. Engage the specific target audience identified above
|
||||||
|
2. Support the episode hook and key takeaways already planned
|
||||||
|
3. Provide talking points that complement the guest's expertise
|
||||||
|
4. Include a compelling call-to-action for listeners
|
||||||
|
|
||||||
NOTE: The research data includes "Key Highlights", "Summaries", and "Excerpts" from various sources.
|
REQUIRED OUTPUT (JSON):
|
||||||
Pay special attention to the "Key Highlights" sections as they contain the most relevant information extracted by the neural search engine.
|
=======================
|
||||||
|
|
||||||
Return JSON structure:
|
|
||||||
{{
|
{{
|
||||||
"summary": "Detailed markdown summary...",
|
"summary": "2-3 paragraph comprehensive summary in Markdown. Start with a hook that matches the episode intro. Include specific data points, expert quotes, and trends.",
|
||||||
"key_insights": [
|
"key_insights": [
|
||||||
{{
|
{{
|
||||||
"title": "Insight Title",
|
"title": "Catchy, engaging title for this insight",
|
||||||
"content": "Detailed markdown content...",
|
"content": "3-4 sentences with specific facts, quotes, or data. Write in a conversational tone suitable for a podcast host to discuss.",
|
||||||
"source_indices": [1, 2]
|
"source_indices": [1, 2, 3],
|
||||||
|
"podcast_talking_points": ["Point 1 host can expand on", "Counter-point or follow-up", "Question to ask guest"]
|
||||||
}}
|
}}
|
||||||
]
|
],
|
||||||
|
"expert_quotes": [
|
||||||
|
{{
|
||||||
|
"quote": "Direct quote from source",
|
||||||
|
"source_index": 1,
|
||||||
|
"context": "Why this quote matters for the podcast"
|
||||||
|
}}
|
||||||
|
],
|
||||||
|
"listener_cta_suggestions": ["Specific action listener can take", "Resource to share", "Next episode preview"]
|
||||||
}}
|
}}
|
||||||
|
|
||||||
Requirements:
|
QUALITY STANDARDS:
|
||||||
- Ensure insights are deep, not just superficial facts. Look for trends, expert opinions, and specific data points.
|
==================
|
||||||
- Tone should be professional, insightful, and ready for a podcast host to discuss.
|
- INSIGHTS MUST BE DEEP, not superficial - avoid generic statements
|
||||||
- Avoid generic filler.
|
- Include SPECIFIC DATA POINTS, percentages, statistics when available
|
||||||
|
- Extract EXPERT QUOTES that hosts can reference
|
||||||
|
- Identify GAPS in the research where more depth is needed
|
||||||
|
- Make content naturally flow into the planned episode hook and CTA
|
||||||
|
- Write in a CONVERSATIONAL tone - how a host would actually speak
|
||||||
|
- Flag any CONTROVERSIAL or debatable claims for host to address
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
|
logger.warning(f"[Podcast Research] Calling LLM for insight extraction...")
|
||||||
llm_response = llm_text_gen(
|
llm_response = llm_text_gen(
|
||||||
prompt=prompt,
|
prompt=prompt,
|
||||||
user_id=user_id,
|
user_id=user_id,
|
||||||
@@ -151,15 +199,45 @@ Requirements:
|
|||||||
preferred_provider=None,
|
preferred_provider=None,
|
||||||
flow_type="premium_tool",
|
flow_type="premium_tool",
|
||||||
)
|
)
|
||||||
|
logger.warning(f"[Podcast Research] LLM response received, length: {len(llm_response) if llm_response else 0}")
|
||||||
|
|
||||||
# Normalize response
|
# Normalize response - handle both string and dict responses
|
||||||
|
data = None
|
||||||
if isinstance(llm_response, str):
|
if isinstance(llm_response, str):
|
||||||
data = json.loads(llm_response)
|
try:
|
||||||
|
# Try to fix common JSON issues
|
||||||
|
fixed_response = llm_response.strip()
|
||||||
|
# Remove markdown code blocks if present
|
||||||
|
if fixed_response.startswith("```"):
|
||||||
|
fixed_response = fixed_response.split("```")[1]
|
||||||
|
if fixed_response.startswith("json"):
|
||||||
|
fixed_response = fixed_response[4:]
|
||||||
|
fixed_response = fixed_response.strip()
|
||||||
|
data = json.loads(fixed_response)
|
||||||
|
except json.JSONDecodeError as json_err:
|
||||||
|
logger.warning(f"[Podcast Research] Failed to parse JSON: {json_err}. Response preview: {llm_response[:500]}...")
|
||||||
|
# Try to extract JSON from response using regex
|
||||||
|
json_match = re.search(r'\{.*\}', llm_response, re.DOTALL)
|
||||||
|
if json_match:
|
||||||
|
try:
|
||||||
|
data = json.loads(json_match.group())
|
||||||
|
logger.warning("[Podcast Research] Successfully extracted JSON via regex")
|
||||||
|
except:
|
||||||
|
pass
|
||||||
else:
|
else:
|
||||||
data = llm_response
|
data = llm_response
|
||||||
|
|
||||||
summary = data.get("summary", "")
|
if data:
|
||||||
key_insights = [PodcastResearchInsight(**insight) for insight in data.get("key_insights", [])]
|
try:
|
||||||
|
summary = data.get("summary", "")
|
||||||
|
key_insights = [PodcastResearchInsight(**insight) for insight in data.get("key_insights", [])]
|
||||||
|
except Exception as insight_err:
|
||||||
|
logger.warning(f"[Podcast Research] Failed to parse insights: {insight_err}. Data keys: {list(data.keys()) if isinstance(data, dict) else 'not a dict'}")
|
||||||
|
summary = data.get("summary", "") if isinstance(data, dict) else ""
|
||||||
|
key_insights = []
|
||||||
|
else:
|
||||||
|
summary = ""
|
||||||
|
key_insights = []
|
||||||
except HTTPException:
|
except HTTPException:
|
||||||
raise
|
raise
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
@@ -183,21 +261,32 @@ Requirements:
|
|||||||
logger.warning(f"[Podcast Exa Research] Failed to track usage: {track_err}")
|
logger.warning(f"[Podcast Exa Research] Failed to track usage: {track_err}")
|
||||||
|
|
||||||
sources_payload = []
|
sources_payload = []
|
||||||
|
seen_urls = set()
|
||||||
for src in sources:
|
for src in sources:
|
||||||
|
url = src.get("url", "")
|
||||||
|
# Skip duplicates
|
||||||
|
if url and url in seen_urls:
|
||||||
|
continue
|
||||||
|
if url:
|
||||||
|
seen_urls.add(url)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
sources_payload.append(PodcastExaSource(**src))
|
sources_payload.append(PodcastExaSource(**src))
|
||||||
except Exception:
|
except Exception:
|
||||||
sources_payload.append(PodcastExaSource(**{
|
sources_payload.append(PodcastExaSource(**{
|
||||||
"title": src.get("title", ""),
|
"title": src.get("title", ""),
|
||||||
"url": src.get("url", ""),
|
"url": url,
|
||||||
"excerpt": src.get("excerpt", ""),
|
"excerpt": src.get("excerpt") or (src.get("highlights")[0] if src.get("highlights") else "") or src.get("summary", ""),
|
||||||
"published_at": src.get("published_at"),
|
"published_at": src.get("published_at"),
|
||||||
|
"publishedDate": src.get("publishedDate"),
|
||||||
"highlights": src.get("highlights"),
|
"highlights": src.get("highlights"),
|
||||||
"summary": src.get("summary"),
|
"summary": src.get("summary"),
|
||||||
"source_type": src.get("source_type"),
|
"source_type": src.get("source_type"),
|
||||||
"index": src.get("index"),
|
"index": src.get("index"),
|
||||||
"image": src.get("image"),
|
"image": src.get("image"),
|
||||||
"author": src.get("author"),
|
"author": src.get("author"),
|
||||||
|
"text": src.get("text"),
|
||||||
|
"credibility_score": src.get("credibility_score"),
|
||||||
}))
|
}))
|
||||||
|
|
||||||
return PodcastExaResearchResponse(
|
return PodcastExaResearchResponse(
|
||||||
|
|||||||
@@ -1,11 +1,12 @@
|
|||||||
"""
|
"""
|
||||||
Podcast Script Handlers
|
Podcast Script Handlers
|
||||||
|
|
||||||
Script generation endpoint.
|
Script generation and approval endpoints.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends, HTTPException
|
from fastapi import APIRouter, Depends, HTTPException
|
||||||
from typing import Dict, Any
|
from typing import Dict, Any, Optional
|
||||||
|
from pydantic import BaseModel, Field
|
||||||
import json
|
import json
|
||||||
|
|
||||||
from middleware.auth_middleware import get_current_user
|
from middleware.auth_middleware import get_current_user
|
||||||
@@ -24,6 +25,29 @@ from ..models import (
|
|||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
|
|
||||||
|
|
||||||
|
class SceneApprovalRequest(BaseModel):
|
||||||
|
project_id: str = Field(..., min_length=1)
|
||||||
|
scene_id: str = Field(..., min_length=1)
|
||||||
|
approved: bool = True
|
||||||
|
notes: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/script/approve")
|
||||||
|
async def approve_podcast_scene(
|
||||||
|
request: SceneApprovalRequest,
|
||||||
|
current_user: Dict[str, Any] = Depends(get_current_user),
|
||||||
|
) -> Dict[str, Any]:
|
||||||
|
"""Persist scene approval metadata for auditing (podcast-specific)."""
|
||||||
|
user_id = require_authenticated_user(current_user)
|
||||||
|
logger.warning(f"[Podcast] Scene approval recorded user={user_id} project={request.project_id} scene={request.scene_id} approved={request.approved}")
|
||||||
|
return {
|
||||||
|
"success": True,
|
||||||
|
"project_id": request.project_id,
|
||||||
|
"scene_id": request.scene_id,
|
||||||
|
"approved": request.approved,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
@router.post("/script", response_model=PodcastScriptResponse)
|
@router.post("/script", response_model=PodcastScriptResponse)
|
||||||
async def generate_podcast_script(
|
async def generate_podcast_script(
|
||||||
request: PodcastScriptRequest,
|
request: PodcastScriptRequest,
|
||||||
@@ -33,6 +57,10 @@ async def generate_podcast_script(
|
|||||||
Generate a podcast script outline (scenes + lines) using podcast-oriented prompting.
|
Generate a podcast script outline (scenes + lines) using podcast-oriented prompting.
|
||||||
"""
|
"""
|
||||||
user_id = require_authenticated_user(current_user)
|
user_id = require_authenticated_user(current_user)
|
||||||
|
logger.warning(f"[ScriptGen] ========== SCRIPT GENERATION START ==========")
|
||||||
|
logger.warning(f"[ScriptGen] Topic: {request.idea[:60]}...")
|
||||||
|
logger.warning(f"[ScriptGen] Duration: {request.duration_minutes} min, Speakers: {request.speakers}")
|
||||||
|
logger.warning(f"[ScriptGen] Has research: {bool(request.research)}, Has bible: {bool(request.bible)}, Has analysis: {bool(request.analysis)}")
|
||||||
|
|
||||||
# Build comprehensive research context for higher-quality scripts
|
# Build comprehensive research context for higher-quality scripts
|
||||||
research_context = ""
|
research_context = ""
|
||||||
@@ -77,55 +105,53 @@ async def generate_podcast_script(
|
|||||||
# Extract Analysis and Outline context for grounding
|
# Extract Analysis and Outline context for grounding
|
||||||
analysis_context = ""
|
analysis_context = ""
|
||||||
if request.analysis:
|
if request.analysis:
|
||||||
analysis_context = f"""
|
try:
|
||||||
TARGET AUDIENCE: {request.analysis.get('audience', 'General')}
|
audience = request.analysis.get('audience', '') or ''
|
||||||
CONTENT TYPE: {request.analysis.get('contentType', 'Conversational')}
|
content_type = request.analysis.get('contentType', '') or ''
|
||||||
TOP KEYWORDS: {', '.join(request.analysis.get('topKeywords', []))}
|
keywords = request.analysis.get('topKeywords', []) or []
|
||||||
"""
|
analysis_context = f"ANALYSIS: Audience={audience} | Type={content_type} | Keywords={', '.join(keywords[:8])}"
|
||||||
|
except:
|
||||||
|
pass
|
||||||
|
|
||||||
outline_context = ""
|
outline_context = ""
|
||||||
if request.outline:
|
if request.outline:
|
||||||
outline_context = f"""
|
try:
|
||||||
REFINED EPISODE OUTLINE (Follow this structure closely):
|
title = request.outline.get('title', '') or ''
|
||||||
Title: {request.outline.get('title', 'N/A')}
|
segments = request.outline.get('segments', []) or []
|
||||||
Segments: {' | '.join(request.outline.get('segments', []))}
|
outline_context = f"OUTLINE: {title} - {' | '.join(segments[:5])}"
|
||||||
"""
|
except:
|
||||||
|
pass
|
||||||
|
|
||||||
prompt = f"""You are an expert podcast script planner. Create natural, conversational podcast scenes.
|
prompt = f"""Create a podcast script with scenes and dialogue.
|
||||||
|
|
||||||
{f"PODCAST BIBLE (Hyper-Personalization Context):\n{bible_context}\n" if bible_context else ""}
|
{f"BIBLE: {bible_context[:1500]}" if bible_context else ""}
|
||||||
{f"ANALYSIS CONTEXT:\n{analysis_context}\n" if analysis_context else ""}
|
{f"{analysis_context}" if analysis_context else ""}
|
||||||
{f"REFINED OUTLINE:\n{outline_context}\n" if outline_context else ""}
|
{f"{outline_context}" if outline_context else ""}
|
||||||
|
{f"RESEARCH: {research_context[:1200]}" if research_context else ""}
|
||||||
|
|
||||||
Podcast Idea: "{request.idea}"
|
Topic: "{request.idea}"
|
||||||
Duration: ~{request.duration_minutes} minutes
|
Duration: {request.duration_minutes} min | Speakers: {request.speakers}
|
||||||
Speakers: {request.speakers} (Host + optional Guest)
|
|
||||||
|
|
||||||
{f"RESEARCH CONTEXT:\n{research_context}\n" if research_context else ""}
|
Return JSON with scenes array. Each scene:
|
||||||
|
- id: string
|
||||||
|
- title: short title (<=50 chars)
|
||||||
|
- duration: seconds (total/5)
|
||||||
|
- emotion: neutral|happy|excited|serious|curious|confident
|
||||||
|
- lines: array of {{speaker, text, emphasis}}
|
||||||
|
- Use 2-4 LINES PER SCENE (shorter script = lower TTS costs)
|
||||||
|
- Each line: 1-3 sentences, conversational
|
||||||
|
- Plain text only, no markdown
|
||||||
|
|
||||||
Return JSON with:
|
COST OPTIMIZATION:
|
||||||
- scenes: array of scenes. Each scene has:
|
- 5-6 scenes max for {request.duration_minutes} min episode
|
||||||
- id: string
|
- Concise, information-dense dialogue
|
||||||
- title: short scene title (<= 60 chars)
|
- Skip filler words and redundant phrases
|
||||||
- duration: duration in seconds (evenly split across total duration)
|
- Focus on unique insights from research
|
||||||
- emotion: string (one of: "neutral", "happy", "excited", "serious", "curious", "confident")
|
- Make every line count toward value delivery
|
||||||
- lines: array of {{"speaker": "...", "text": "...", "emphasis": boolean}}
|
|
||||||
* Write natural, conversational dialogue
|
|
||||||
* Each line can be a sentence or a few sentences that flow together
|
|
||||||
* Use plain text only - no markdown formatting (no asterisks, underscores, etc.)
|
|
||||||
* Mark "emphasis": true for key statistics or important points
|
|
||||||
|
|
||||||
Guidelines:
|
|
||||||
- Write for spoken delivery: conversational, natural, with contractions.
|
|
||||||
- Follow the interaction tone specified in the Bible.
|
|
||||||
- Ensure the Host persona matches the background and personality traits from the Bible.
|
|
||||||
- Structure the intro and outro scenes according to the Bible's "Intro Format" and "Outro Format".
|
|
||||||
- Adhere to any constraints mentioned in the Bible.
|
|
||||||
- Use insights from the Research Context to ground the conversation in facts.
|
|
||||||
- IMPORTANT: Follow the REFINED OUTLINE segments as the primary structure for the episode.
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
try:
|
try:
|
||||||
|
logger.warning(f"[ScriptGen] Calling LLM to generate script (prompt length: {len(prompt)})...")
|
||||||
raw = llm_text_gen(
|
raw = llm_text_gen(
|
||||||
prompt=prompt,
|
prompt=prompt,
|
||||||
user_id=user_id,
|
user_id=user_id,
|
||||||
@@ -133,6 +159,7 @@ Guidelines:
|
|||||||
preferred_provider=None,
|
preferred_provider=None,
|
||||||
flow_type="premium_tool",
|
flow_type="premium_tool",
|
||||||
)
|
)
|
||||||
|
logger.warning(f"[ScriptGen] LLM response received, length: {len(raw) if raw else 0}")
|
||||||
except HTTPException:
|
except HTTPException:
|
||||||
raise
|
raise
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
|
|||||||
@@ -140,17 +140,20 @@ def _execute_podcast_video_task(
|
|||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.warning(f"[Podcast] Failed to fetch project context for video generation: {e}")
|
logger.warning(f"[Podcast] Failed to fetch project context for video generation: {e}")
|
||||||
|
|
||||||
# Prepare scene data for animation
|
# Prepare scene data for animation - include all context for enhanced prompt
|
||||||
scene_data = {
|
scene_data = {
|
||||||
"scene_number": scene_number,
|
"scene_number": scene_number,
|
||||||
"title": request.scene_title,
|
"title": request.scene_title,
|
||||||
"scene_id": request.scene_id,
|
"scene_id": request.scene_id,
|
||||||
|
"image_prompt": request.scene_image_prompt,
|
||||||
|
"description": request.scene_narration,
|
||||||
|
"lines": [{"text": request.scene_narration}] if request.scene_narration else [],
|
||||||
}
|
}
|
||||||
story_context = {
|
story_context = {
|
||||||
"project_id": request.project_id,
|
"project_id": request.project_id,
|
||||||
"type": "podcast",
|
"type": "podcast",
|
||||||
"bible": project_bible,
|
"bible": project_bible,
|
||||||
"analysis": project_analysis,
|
"analysis": request.analysis or project_analysis, # Use passed analysis or fallback to DB
|
||||||
}
|
}
|
||||||
|
|
||||||
animation_result = animate_scene_with_voiceover(
|
animation_result = animate_scene_with_voiceover(
|
||||||
|
|||||||
@@ -63,6 +63,10 @@ class PodcastAnalyzeResponse(BaseModel):
|
|||||||
top_keywords: list[str]
|
top_keywords: list[str]
|
||||||
suggested_outlines: list[Dict[str, Any]]
|
suggested_outlines: list[Dict[str, Any]]
|
||||||
title_suggestions: list[str]
|
title_suggestions: list[str]
|
||||||
|
episode_hook: Optional[str] = None
|
||||||
|
key_takeaways: Optional[list[str]] = None
|
||||||
|
guest_talking_points: Optional[list[str]] = None
|
||||||
|
listener_cta: Optional[str] = None
|
||||||
research_queries: Optional[List[Dict[str, str]]] = None
|
research_queries: Optional[List[Dict[str, str]]] = None
|
||||||
exa_suggested_config: Optional[Dict[str, Any]] = None
|
exa_suggested_config: Optional[Dict[str, Any]] = None
|
||||||
bible: Optional[Dict[str, Any]] = None
|
bible: Optional[Dict[str, Any]] = None
|
||||||
@@ -142,12 +146,15 @@ class PodcastExaSource(BaseModel):
|
|||||||
url: str = ""
|
url: str = ""
|
||||||
excerpt: str = ""
|
excerpt: str = ""
|
||||||
published_at: Optional[str] = None
|
published_at: Optional[str] = None
|
||||||
|
publishedDate: Optional[str] = None # Exa format
|
||||||
highlights: Optional[List[str]] = None
|
highlights: Optional[List[str]] = None
|
||||||
summary: Optional[str] = None
|
summary: Optional[str] = None
|
||||||
source_type: Optional[str] = None
|
source_type: Optional[str] = None
|
||||||
index: Optional[int] = None
|
index: Optional[int] = None
|
||||||
image: Optional[str] = None
|
image: Optional[str] = None
|
||||||
author: Optional[str] = None
|
author: Optional[str] = None
|
||||||
|
text: Optional[str] = None # Exa full text
|
||||||
|
credibility_score: Optional[float] = None # Exa scores
|
||||||
|
|
||||||
|
|
||||||
class PodcastResearchInsight(BaseModel):
|
class PodcastResearchInsight(BaseModel):
|
||||||
@@ -155,6 +162,9 @@ class PodcastResearchInsight(BaseModel):
|
|||||||
title: str
|
title: str
|
||||||
content: str
|
content: str
|
||||||
source_indices: List[int] = []
|
source_indices: List[int] = []
|
||||||
|
podcast_talking_points: Optional[List[str]] = [] # Talking points for host to expand on
|
||||||
|
expert_quotes: Optional[List[Dict[str, str]]] = [] # Quotes from sources
|
||||||
|
listener_cta_suggestions: Optional[List[str]] = [] # CTA suggestions
|
||||||
|
|
||||||
|
|
||||||
class PodcastExaResearchResponse(BaseModel):
|
class PodcastExaResearchResponse(BaseModel):
|
||||||
@@ -178,6 +188,7 @@ class PodcastAudioRequest(BaseModel):
|
|||||||
scene_title: str
|
scene_title: str
|
||||||
text: str
|
text: str
|
||||||
voice_id: Optional[str] = "Wise_Woman"
|
voice_id: Optional[str] = "Wise_Woman"
|
||||||
|
custom_voice_id: Optional[str] = None # Voice clone ID for custom voice
|
||||||
speed: Optional[float] = 1.0
|
speed: Optional[float] = 1.0
|
||||||
volume: Optional[float] = 1.0
|
volume: Optional[float] = 1.0
|
||||||
pitch: Optional[float] = 0.0
|
pitch: Optional[float] = 0.0
|
||||||
@@ -263,7 +274,9 @@ class PodcastImageRequest(BaseModel):
|
|||||||
scene_id: str
|
scene_id: str
|
||||||
scene_title: str
|
scene_title: str
|
||||||
scene_content: Optional[str] = None # Optional: scene lines text for context
|
scene_content: Optional[str] = None # Optional: scene lines text for context
|
||||||
|
scene_emotion: Optional[str] = None # Optional: scene emotion for visual tone
|
||||||
idea: Optional[str] = None # Optional: podcast idea for context
|
idea: Optional[str] = None # Optional: podcast idea for context
|
||||||
|
analysis: Optional[Dict[str, Any]] = Field(None, description="AI analysis for visual context (keywords, audience)")
|
||||||
base_avatar_url: Optional[str] = None # Base avatar image URL for scene variations
|
base_avatar_url: Optional[str] = None # Base avatar image URL for scene variations
|
||||||
bible: Optional[Dict[str, Any]] = Field(None, description="Podcast Bible for hyper-personalization")
|
bible: Optional[Dict[str, Any]] = Field(None, description="Podcast Bible for hyper-personalization")
|
||||||
width: int = 1024
|
width: int = 1024
|
||||||
@@ -285,6 +298,7 @@ class PodcastImageResponse(BaseModel):
|
|||||||
provider: str
|
provider: str
|
||||||
model: Optional[str] = None
|
model: Optional[str] = None
|
||||||
cost: float
|
cost: float
|
||||||
|
image_prompt: Optional[str] = None # Return the prompt used for generation
|
||||||
|
|
||||||
|
|
||||||
class PodcastVideoGenerationRequest(BaseModel):
|
class PodcastVideoGenerationRequest(BaseModel):
|
||||||
@@ -295,6 +309,9 @@ class PodcastVideoGenerationRequest(BaseModel):
|
|||||||
audio_url: str = Field(..., description="URL to the generated audio file")
|
audio_url: str = Field(..., description="URL to the generated audio file")
|
||||||
avatar_image_url: Optional[str] = Field(None, description="URL to scene image (required for video generation)")
|
avatar_image_url: Optional[str] = Field(None, description="URL to scene image (required for video generation)")
|
||||||
bible: Optional[Dict[str, Any]] = Field(None, description="Podcast Bible for hyper-personalization")
|
bible: Optional[Dict[str, Any]] = Field(None, description="Podcast Bible for hyper-personalization")
|
||||||
|
analysis: Optional[Dict[str, Any]] = Field(None, description="Podcast Analysis for context (content type, audience, takeaways, guest)")
|
||||||
|
scene_image_prompt: Optional[str] = Field(None, description="Original image generation prompt for visual context")
|
||||||
|
scene_narration: Optional[str] = Field(None, description="Scene narration/script lines for context")
|
||||||
resolution: str = Field("720p", description="Video resolution (480p or 720p)")
|
resolution: str = Field("720p", description="Video resolution (480p or 720p)")
|
||||||
prompt: Optional[str] = Field(None, description="Optional animation prompt override")
|
prompt: Optional[str] = Field(None, description="Optional animation prompt override")
|
||||||
seed: Optional[int] = Field(-1, description="Random seed; -1 for random")
|
seed: Optional[int] = Field(-1, description="Random seed; -1 for random")
|
||||||
|
|||||||
@@ -9,59 +9,26 @@ builtins.Dict = typing.Dict
|
|||||||
builtins.Any = typing.Any
|
builtins.Any = typing.Any
|
||||||
builtins.Union = typing.Union
|
builtins.Union = typing.Union
|
||||||
|
|
||||||
# Import onboarding models VERY early to ensure they're available before any services
|
# Load environment variables FIRST before any other imports
|
||||||
from models.onboarding import APIKey, WebsiteAnalysis, ResearchPreferences, PersonaData, CompetitorAnalysis
|
|
||||||
|
|
||||||
|
|
||||||
from fastapi import FastAPI, HTTPException, Depends, Request, BackgroundTasks
|
|
||||||
from fastapi.middleware.cors import CORSMiddleware
|
|
||||||
from fastapi.staticfiles import StaticFiles
|
|
||||||
from fastapi.responses import FileResponse
|
|
||||||
from pydantic import BaseModel
|
|
||||||
from typing import Dict, Any, Optional
|
|
||||||
import os
|
|
||||||
from loguru import logger
|
|
||||||
from dotenv import load_dotenv
|
|
||||||
import asyncio
|
|
||||||
from datetime import datetime
|
|
||||||
|
|
||||||
# Import OnboardingSession right after basic imports to ensure it's available
|
|
||||||
from models.onboarding import OnboardingSession
|
|
||||||
|
|
||||||
from services.subscription import monitoring_middleware
|
|
||||||
|
|
||||||
# Import remaining onboarding models
|
|
||||||
from models import APIKey, WebsiteAnalysis, ResearchPreferences, PersonaData, CompetitorAnalysis
|
|
||||||
|
|
||||||
# Import modular utilities
|
|
||||||
from alwrity_utils import HealthChecker, RateLimiter, FrontendServing, RouterManager
|
|
||||||
from alwrity_utils import OnboardingManager
|
|
||||||
|
|
||||||
# Load environment variables
|
|
||||||
# Try multiple locations for .env file
|
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
from dotenv import load_dotenv
|
||||||
backend_dir = Path(__file__).parent
|
backend_dir = Path(__file__).parent
|
||||||
project_root = backend_dir.parent
|
project_root = backend_dir.parent
|
||||||
|
load_dotenv(backend_dir / '.env')
|
||||||
|
load_dotenv(project_root / '.env')
|
||||||
|
load_dotenv()
|
||||||
|
|
||||||
# Load from backend/.env first (higher priority), then root .env
|
# Set LOG_LEVEL early to WARNING to suppress DEBUG persona logs in podcast mode
|
||||||
load_dotenv(backend_dir / '.env') # backend/.env
|
import os
|
||||||
load_dotenv(project_root / '.env') # root .env (fallback)
|
if os.getenv("ALWRITY_ENABLED_FEATURES", "").strip().lower() == "podcast":
|
||||||
load_dotenv() # CWD .env (fallback)
|
os.environ["LOG_LEVEL"] = "WARNING"
|
||||||
|
|
||||||
|
|
||||||
def get_enabled_features() -> set:
|
def get_enabled_features() -> set:
|
||||||
"""Get enabled features from ALWRITY_ENABLED_FEATURES env var.
|
"""Get enabled features from ALWRITY_ENABLED_FEATURES env var."""
|
||||||
|
|
||||||
Values:
|
|
||||||
- "all" - enable all features (default)
|
|
||||||
- comma-separated: "podcast,core"
|
|
||||||
- single feature: "podcast"
|
|
||||||
"""
|
|
||||||
env_value = os.getenv("ALWRITY_ENABLED_FEATURES", "all").strip().lower()
|
env_value = os.getenv("ALWRITY_ENABLED_FEATURES", "all").strip().lower()
|
||||||
|
|
||||||
if not env_value or env_value == "all":
|
if not env_value or env_value == "all":
|
||||||
return {"all"}
|
return {"all"}
|
||||||
|
|
||||||
return {f.strip() for f in env_value.split(",") if f.strip()}
|
return {f.strip() for f in env_value.split(",") if f.strip()}
|
||||||
|
|
||||||
|
|
||||||
@@ -71,6 +38,32 @@ def is_podcast_only_demo_mode() -> bool:
|
|||||||
return "podcast" in enabled and "all" not in enabled
|
return "podcast" in enabled and "all" not in enabled
|
||||||
|
|
||||||
|
|
||||||
|
# Import onboarding models (after env is loaded)
|
||||||
|
from models.onboarding import APIKey, WebsiteAnalysis, ResearchPreferences, PersonaData, CompetitorAnalysis
|
||||||
|
|
||||||
|
|
||||||
|
# Import FastAPI and related
|
||||||
|
from fastapi import FastAPI, HTTPException, Depends, Request, BackgroundTasks
|
||||||
|
from fastapi.middleware.cors import CORSMiddleware
|
||||||
|
from fastapi.staticfiles import StaticFiles
|
||||||
|
from fastapi.responses import FileResponse
|
||||||
|
from pydantic import BaseModel
|
||||||
|
from typing import Dict, Any, Optional
|
||||||
|
import os
|
||||||
|
import asyncio
|
||||||
|
from datetime import datetime
|
||||||
|
from loguru import logger
|
||||||
|
|
||||||
|
|
||||||
|
# Import modular utilities (skip OnboardingManager import in podcast-only mode)
|
||||||
|
from alwrity_utils import HealthChecker, RateLimiter, FrontendServing, RouterManager
|
||||||
|
if not is_podcast_only_demo_mode():
|
||||||
|
from alwrity_utils import OnboardingManager
|
||||||
|
|
||||||
|
# Import monitoring middleware
|
||||||
|
from services.subscription import monitoring_middleware
|
||||||
|
|
||||||
|
|
||||||
def should_include_non_podcast_features() -> bool:
|
def should_include_non_podcast_features() -> bool:
|
||||||
"""Check if non-podcast features should be included."""
|
"""Check if non-podcast features should be included."""
|
||||||
enabled = get_enabled_features()
|
enabled = get_enabled_features()
|
||||||
@@ -94,8 +87,10 @@ from api.component_logic import router as component_logic_router
|
|||||||
# Import subscription API endpoints
|
# Import subscription API endpoints
|
||||||
from api.subscription import router as subscription_router
|
from api.subscription import router as subscription_router
|
||||||
|
|
||||||
# Import Step 3 onboarding routes
|
# Import Step 3 onboarding routes (skip in podcast-only mode)
|
||||||
from api.onboarding_utils.step3_routes import router as step3_routes
|
step3_routes = None
|
||||||
|
if not PODCAST_ONLY_DEMO_MODE:
|
||||||
|
from api.onboarding_utils.step3_routes import router as step3_routes
|
||||||
|
|
||||||
# Import SEO tools router
|
# Import SEO tools router
|
||||||
from routers.seo_tools import router as seo_tools_router
|
from routers.seo_tools import router as seo_tools_router
|
||||||
@@ -218,7 +213,9 @@ router_manager = RouterManager(app)
|
|||||||
router_group_status: Dict[str, Dict[str, Any]] = {}
|
router_group_status: Dict[str, Dict[str, Any]] = {}
|
||||||
|
|
||||||
onboarding_manager = None
|
onboarding_manager = None
|
||||||
|
# Only create OnboardingManager if NOT in podcast-only mode
|
||||||
if not PODCAST_ONLY_DEMO_MODE:
|
if not PODCAST_ONLY_DEMO_MODE:
|
||||||
|
from alwrity_utils import OnboardingManager
|
||||||
onboarding_manager = OnboardingManager(app)
|
onboarding_manager = OnboardingManager(app)
|
||||||
|
|
||||||
# Middleware Order (FastAPI executes in REVERSE order of registration - LIFO):
|
# Middleware Order (FastAPI executes in REVERSE order of registration - LIFO):
|
||||||
@@ -575,9 +572,12 @@ async def startup_event():
|
|||||||
if startup_report.get("status") != "healthy":
|
if startup_report.get("status") != "healthy":
|
||||||
logger.error(f"Startup readiness finished with failures: {startup_report.get('errors', [])}")
|
logger.error(f"Startup readiness finished with failures: {startup_report.get('errors', [])}")
|
||||||
|
|
||||||
# Start task scheduler
|
# Start task scheduler only if NOT in podcast-only mode
|
||||||
from services.scheduler import get_scheduler
|
if not is_podcast_only_demo_mode():
|
||||||
await get_scheduler().start()
|
from services.scheduler import get_scheduler
|
||||||
|
await get_scheduler().start()
|
||||||
|
else:
|
||||||
|
logger.info("[Podcast] Skipping scheduler startup (podcast-only mode)")
|
||||||
|
|
||||||
# Check Wix API key configuration
|
# Check Wix API key configuration
|
||||||
wix_api_key = os.getenv('WIX_API_KEY')
|
wix_api_key = os.getenv('WIX_API_KEY')
|
||||||
|
|||||||
@@ -62,6 +62,7 @@ class VoiceCloneResult:
|
|||||||
def generate_audio(
|
def generate_audio(
|
||||||
text: str,
|
text: str,
|
||||||
voice_id: str = "Wise_Woman",
|
voice_id: str = "Wise_Woman",
|
||||||
|
custom_voice_id: Optional[str] = None,
|
||||||
speed: float = 1.0,
|
speed: float = 1.0,
|
||||||
volume: float = 1.0,
|
volume: float = 1.0,
|
||||||
pitch: float = 0.0,
|
pitch: float = 0.0,
|
||||||
@@ -173,6 +174,7 @@ def generate_audio(
|
|||||||
audio_bytes = client.generate_speech(
|
audio_bytes = client.generate_speech(
|
||||||
text=text,
|
text=text,
|
||||||
voice_id=voice_id,
|
voice_id=voice_id,
|
||||||
|
custom_voice_id=custom_voice_id,
|
||||||
speed=speed,
|
speed=speed,
|
||||||
volume=volume,
|
volume=volume,
|
||||||
pitch=pitch,
|
pitch=pitch,
|
||||||
|
|||||||
@@ -67,7 +67,7 @@ def llm_text_gen(
|
|||||||
resolved_flow_type = flow_type or ("sif_agent" if preferred_hf_models else "premium_tool")
|
resolved_flow_type = flow_type or ("sif_agent" if preferred_hf_models else "premium_tool")
|
||||||
flow_tag = f"flow_type={resolved_flow_type}"
|
flow_tag = f"flow_type={resolved_flow_type}"
|
||||||
|
|
||||||
logger.info(f"[llm_text_gen][{flow_tag}] Starting text generation")
|
logger.warning(f"[llm_text_gen][{flow_tag}] Starting text generation")
|
||||||
logger.debug(f"[llm_text_gen] Prompt length: {len(prompt)} characters")
|
logger.debug(f"[llm_text_gen] Prompt length: {len(prompt)} characters")
|
||||||
|
|
||||||
# Set default values for LLM parameters
|
# Set default values for LLM parameters
|
||||||
@@ -94,7 +94,7 @@ def llm_text_gen(
|
|||||||
primary_provider = provider_list[0]
|
primary_provider = provider_list[0]
|
||||||
if primary_provider in ['wavespeed', 'wave']:
|
if primary_provider in ['wavespeed', 'wave']:
|
||||||
gpt_provider = "wavespeed"
|
gpt_provider = "wavespeed"
|
||||||
model = os.getenv('WAVESPEED_TEXT_MODEL', 'openai/gpt-oss-120b:cerebras')
|
model = os.getenv('WAVESPEED_TEXT_MODEL', 'openai/gpt-oss-120b')
|
||||||
elif primary_provider in ['gemini', 'google']:
|
elif primary_provider in ['gemini', 'google']:
|
||||||
gpt_provider = "google"
|
gpt_provider = "google"
|
||||||
model = "gemini-2.0-flash-001"
|
model = "gemini-2.0-flash-001"
|
||||||
@@ -111,7 +111,7 @@ def llm_text_gen(
|
|||||||
elif preferred_provider:
|
elif preferred_provider:
|
||||||
if preferred_provider in ['wavespeed', 'wave']:
|
if preferred_provider in ['wavespeed', 'wave']:
|
||||||
gpt_provider = "wavespeed"
|
gpt_provider = "wavespeed"
|
||||||
model = os.getenv('WAVESPEED_TEXT_MODEL', 'openai/gpt-oss-120b:cerebras')
|
model = os.getenv('WAVESPEED_TEXT_MODEL', 'openai/gpt-oss-120b')
|
||||||
elif preferred_provider in ['openai', 'gpt']:
|
elif preferred_provider in ['openai', 'gpt']:
|
||||||
gpt_provider = "openai"
|
gpt_provider = "openai"
|
||||||
model = os.getenv('OPENAI_MODEL', 'gpt-4o-mini')
|
model = os.getenv('OPENAI_MODEL', 'gpt-4o-mini')
|
||||||
@@ -166,7 +166,7 @@ def llm_text_gen(
|
|||||||
if api_key_manager.get_api_key("wavespeed"):
|
if api_key_manager.get_api_key("wavespeed"):
|
||||||
available_providers.append("wavespeed")
|
available_providers.append("wavespeed")
|
||||||
|
|
||||||
logger.info(
|
logger.warning(
|
||||||
f"[llm_text_gen][{flow_tag}] Provider preflight: env_provider='{env_provider or 'auto'}', "
|
f"[llm_text_gen][{flow_tag}] Provider preflight: env_provider='{env_provider or 'auto'}', "
|
||||||
f"provider_list={provider_list}, strict_provider_mode={strict_provider_mode}, "
|
f"provider_list={provider_list}, strict_provider_mode={strict_provider_mode}, "
|
||||||
f"available_providers={available_providers}, preferred_provider={preferred_provider or 'none'}, "
|
f"available_providers={available_providers}, preferred_provider={preferred_provider or 'none'}, "
|
||||||
@@ -278,7 +278,12 @@ def llm_text_gen(
|
|||||||
UsageSummary.billing_period == current_period
|
UsageSummary.billing_period == current_period
|
||||||
).first()
|
).first()
|
||||||
|
|
||||||
# No separate log here - we'll create unified log after API call and usage tracking
|
# Log subscription details before making the API call
|
||||||
|
if usage:
|
||||||
|
total_llm_calls = (usage.gemini_calls or 0) + (usage.openai_calls or 0) + (usage.anthropic_calls or 0) + (usage.mistral_calls or 0) + (usage.wavespeed_calls or 0)
|
||||||
|
logger.info(f"[llm_text_gen] Subscription check passed for user {user_id}: provider={actual_provider_name or gpt_provider}, tokens_requested={estimated_total_tokens}, current_usage=${usage.total_cost or 0:.4f}, calls_used={total_llm_calls}")
|
||||||
|
else:
|
||||||
|
logger.info(f"[llm_text_gen] Subscription check passed for user {user_id}: provider={actual_provider_name or gpt_provider}, tokens_requested={estimated_total_tokens}, new_user_no_usage_record")
|
||||||
|
|
||||||
finally:
|
finally:
|
||||||
db.close()
|
db.close()
|
||||||
@@ -363,7 +368,7 @@ def llm_text_gen(
|
|||||||
from services.llm_providers.wavespeed_provider import wavespeed_text_response
|
from services.llm_providers.wavespeed_provider import wavespeed_text_response
|
||||||
response_text = wavespeed_text_response(
|
response_text = wavespeed_text_response(
|
||||||
prompt=prompt,
|
prompt=prompt,
|
||||||
model=model or "openai/gpt-oss-120b:cerebras",
|
model=model or "openai/gpt-oss-120b",
|
||||||
temperature=temperature,
|
temperature=temperature,
|
||||||
max_tokens=max_tokens,
|
max_tokens=max_tokens,
|
||||||
top_p=top_p,
|
top_p=top_p,
|
||||||
|
|||||||
@@ -15,14 +15,31 @@ class PodcastBibleService:
|
|||||||
"""Service for generating and managing the Podcast Bible."""
|
"""Service for generating and managing the Podcast Bible."""
|
||||||
|
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
self.personalization_service = PersonalizationService()
|
try:
|
||||||
|
from services.product_marketing.personalization_service import PersonalizationService
|
||||||
|
self.personalization_service = PersonalizationService()
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f"Failed to initialize PersonalizationService: {e}")
|
||||||
|
self.personalization_service = None
|
||||||
|
|
||||||
def generate_bible(self, user_id: str, project_id: str) -> PodcastBible:
|
def generate_bible(self, user_id: str, project_id: str) -> PodcastBible:
|
||||||
"""Generate a Podcast Bible from onboarding data."""
|
"""Generate a Podcast Bible from onboarding data."""
|
||||||
logger.info(f"Generating Podcast Bible for user {user_id}")
|
logger.info(f"Generating Podcast Bible for user {user_id}")
|
||||||
|
|
||||||
try:
|
try:
|
||||||
preferences = self.personalization_service.get_user_preferences(user_id) or {}
|
if not self.personalization_service:
|
||||||
|
logger.warning("PersonalizationService not available, using default bible")
|
||||||
|
return self._get_default_bible(project_id)
|
||||||
|
|
||||||
|
try:
|
||||||
|
preferences = self.personalization_service.get_user_preferences(user_id)
|
||||||
|
except Exception as pref_err:
|
||||||
|
logger.warning(f"Failed to get user preferences: {pref_err}, using defaults")
|
||||||
|
return self._get_default_bible(project_id)
|
||||||
|
|
||||||
|
if not preferences:
|
||||||
|
logger.info(f"No preferences found for user {user_id}, using defaults")
|
||||||
|
return self._get_default_bible(project_id)
|
||||||
if not isinstance(preferences, dict):
|
if not isinstance(preferences, dict):
|
||||||
logger.warning(f"Podcast Bible preferences payload is non-dict for user {user_id}, using defaults")
|
logger.warning(f"Podcast Bible preferences payload is non-dict for user {user_id}, using defaults")
|
||||||
preferences = {}
|
preferences = {}
|
||||||
@@ -129,18 +146,23 @@ class PodcastBibleService:
|
|||||||
name="AI Host",
|
name="AI Host",
|
||||||
background="Industry Professional",
|
background="Industry Professional",
|
||||||
expertise_level="Expert",
|
expertise_level="Expert",
|
||||||
|
personality_traits=["Professional", "Informative"],
|
||||||
vocal_style="Authoritative",
|
vocal_style="Authoritative",
|
||||||
vocal_characteristics=["Deep", "Steady"]
|
vocal_characteristics=["Deep", "Steady"],
|
||||||
|
look="A professional individual dressed in business-casual attire."
|
||||||
),
|
),
|
||||||
audience=AudienceDNA(
|
audience=AudienceDNA(
|
||||||
expertise_level="Intermediate",
|
expertise_level="Intermediate",
|
||||||
interests=["Industry Trends", "Technology"],
|
interests=["Industry Trends", "Technology"],
|
||||||
pain_points=["Staying Competitive", "Operational Efficiency"]
|
pain_points=["Staying Competitive", "Operational Efficiency"],
|
||||||
|
demographics=None
|
||||||
),
|
),
|
||||||
brand=BrandDNA(
|
brand=BrandDNA(
|
||||||
industry="General Business",
|
industry="General Business",
|
||||||
tone="Professional",
|
tone="Professional",
|
||||||
communication_style="Analytical"
|
communication_style="Analytical",
|
||||||
|
key_messages=[],
|
||||||
|
competitor_context=None
|
||||||
),
|
),
|
||||||
visual_style=VisualStyle(
|
visual_style=VisualStyle(
|
||||||
environment="Professional modern office studio",
|
environment="Professional modern office studio",
|
||||||
|
|||||||
@@ -156,6 +156,12 @@ def _check_production_api_key_loading(
|
|||||||
if deploy_env == "local":
|
if deploy_env == "local":
|
||||||
_record_check(checks, "production_api_key_loading", True, "skipped in local deploy mode")
|
_record_check(checks, "production_api_key_loading", True, "skipped in local deploy mode")
|
||||||
return
|
return
|
||||||
|
|
||||||
|
# Also skip in podcast-only mode (no production API keys needed)
|
||||||
|
enabled_features = os.getenv("ALWRITY_ENABLED_FEATURES", "all").strip().lower()
|
||||||
|
if enabled_features == "podcast":
|
||||||
|
_record_check(checks, "production_api_key_loading", True, "skipped in podcast-only mode")
|
||||||
|
return
|
||||||
|
|
||||||
test_tenant_id = os.getenv("ALWRITY_STARTUP_TEST_TENANT_ID", "").strip()
|
test_tenant_id = os.getenv("ALWRITY_STARTUP_TEST_TENANT_ID", "").strip()
|
||||||
if not test_tenant_id:
|
if not test_tenant_id:
|
||||||
|
|||||||
@@ -46,6 +46,7 @@ class StoryAudioGenerationService:
|
|||||||
return _get_story_media_write_dir("audio", user_id=user_id, db=db)
|
return _get_story_media_write_dir("audio", user_id=user_id, db=db)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.warning(f"[StoryAudioGeneration] Failed to resolve user workspace path for {user_id}: {e}")
|
logger.warning(f"[StoryAudioGeneration] Failed to resolve user workspace path for {user_id}: {e}")
|
||||||
|
# Don't fall back to default - keep using the already-set output_dir for podcast
|
||||||
return self.output_dir
|
return self.output_dir
|
||||||
|
|
||||||
def _generate_audio_filename(self, scene_number: int, scene_title: str) -> str:
|
def _generate_audio_filename(self, scene_number: int, scene_title: str) -> str:
|
||||||
@@ -318,6 +319,7 @@ class StoryAudioGenerationService:
|
|||||||
text: str,
|
text: str,
|
||||||
user_id: str,
|
user_id: str,
|
||||||
voice_id: str = "Wise_Woman",
|
voice_id: str = "Wise_Woman",
|
||||||
|
custom_voice_id: Optional[str] = None,
|
||||||
speed: float = 1.0,
|
speed: float = 1.0,
|
||||||
volume: float = 1.0,
|
volume: float = 1.0,
|
||||||
pitch: float = 0.0,
|
pitch: float = 0.0,
|
||||||
@@ -364,6 +366,7 @@ class StoryAudioGenerationService:
|
|||||||
result = generate_audio(
|
result = generate_audio(
|
||||||
text=text.strip(),
|
text=text.strip(),
|
||||||
voice_id=voice_id,
|
voice_id=voice_id,
|
||||||
|
custom_voice_id=custom_voice_id,
|
||||||
speed=speed,
|
speed=speed,
|
||||||
volume=volume,
|
volume=volume,
|
||||||
pitch=pitch,
|
pitch=pitch,
|
||||||
@@ -378,8 +381,8 @@ class StoryAudioGenerationService:
|
|||||||
enable_sync_mode=enable_sync_mode,
|
enable_sync_mode=enable_sync_mode,
|
||||||
)
|
)
|
||||||
|
|
||||||
# Determine output directory (user workspace or default)
|
# Use the output_dir that was set when service was created (already handles podcast vs story)
|
||||||
output_dir = self._get_user_audio_dir(user_id, db)
|
output_dir = self.output_dir
|
||||||
|
|
||||||
# Save audio to file
|
# Save audio to file
|
||||||
audio_filename = self._generate_audio_filename(scene_number, scene_title)
|
audio_filename = self._generate_audio_filename(scene_number, scene_title)
|
||||||
|
|||||||
@@ -442,9 +442,34 @@ class PricingService:
|
|||||||
"description": "AI Audio Generation default pricing"
|
"description": "AI Audio Generation default pricing"
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
|
|
||||||
|
# WaveSpeed LLM Text Generation Pricing (via Cerebras)
|
||||||
|
wavespeed_llm_pricing = [
|
||||||
|
{
|
||||||
|
"provider": APIProvider.WAVESPEED,
|
||||||
|
"model_name": "openai/gpt-oss-120b",
|
||||||
|
"cost_per_input_token": 0.0000006, # $0.60 per 1M input tokens
|
||||||
|
"cost_per_output_token": 0.0000006, # $0.60 per 1M output tokens
|
||||||
|
"description": "WaveSpeed GPT-OSS 120B (Cerebras) - Fast text generation"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"provider": APIProvider.WAVESPEED,
|
||||||
|
"model_name": "openai/gpt-oss-120b:cerebras",
|
||||||
|
"cost_per_input_token": 0.0000006,
|
||||||
|
"cost_per_output_token": 0.0000006,
|
||||||
|
"description": "WaveSpeed GPT-OSS 120B (Cerebras) - Fast text generation"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"provider": APIProvider.WAVESPEED,
|
||||||
|
"model_name": "openai/gpt-oss-20b",
|
||||||
|
"cost_per_input_token": 0.0000002, # $0.20 per 1M input tokens
|
||||||
|
"cost_per_output_token": 0.0000002, # $0.20 per 1M output tokens
|
||||||
|
"description": "WaveSpeed GPT-OSS 20B (Cerebras) - Cost-effective text generation"
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
# Combine all pricing data (include video pricing in search_pricing list)
|
# Combine all pricing data (include video pricing in search_pricing list)
|
||||||
all_pricing = gemini_pricing + openai_pricing + anthropic_pricing + mistral_pricing + search_pricing
|
all_pricing = gemini_pricing + openai_pricing + anthropic_pricing + mistral_pricing + search_pricing + wavespeed_llm_pricing
|
||||||
|
|
||||||
# Insert or update pricing data
|
# Insert or update pricing data
|
||||||
for pricing_data in all_pricing:
|
for pricing_data in all_pricing:
|
||||||
|
|||||||
@@ -241,6 +241,7 @@ class WaveSpeedClient:
|
|||||||
self,
|
self,
|
||||||
text: str,
|
text: str,
|
||||||
voice_id: str,
|
voice_id: str,
|
||||||
|
custom_voice_id: Optional[str] = None,
|
||||||
speed: float = 1.0,
|
speed: float = 1.0,
|
||||||
volume: float = 1.0,
|
volume: float = 1.0,
|
||||||
pitch: float = 0.0,
|
pitch: float = 0.0,
|
||||||
@@ -255,6 +256,7 @@ class WaveSpeedClient:
|
|||||||
Args:
|
Args:
|
||||||
text: Text to convert to speech (max 10000 characters)
|
text: Text to convert to speech (max 10000 characters)
|
||||||
voice_id: Voice ID (e.g., "Wise_Woman", "Friendly_Person", etc.)
|
voice_id: Voice ID (e.g., "Wise_Woman", "Friendly_Person", etc.)
|
||||||
|
custom_voice_id: Custom voice clone ID for using cloned voice
|
||||||
speed: Speech speed (0.5-2.0, default: 1.0)
|
speed: Speech speed (0.5-2.0, default: 1.0)
|
||||||
volume: Speech volume (0.1-10.0, default: 1.0)
|
volume: Speech volume (0.1-10.0, default: 1.0)
|
||||||
pitch: Speech pitch (-12 to 12, default: 0.0)
|
pitch: Speech pitch (-12 to 12, default: 0.0)
|
||||||
@@ -269,6 +271,7 @@ class WaveSpeedClient:
|
|||||||
return self.speech.generate_speech(
|
return self.speech.generate_speech(
|
||||||
text=text,
|
text=text,
|
||||||
voice_id=voice_id,
|
voice_id=voice_id,
|
||||||
|
custom_voice_id=custom_voice_id,
|
||||||
speed=speed,
|
speed=speed,
|
||||||
volume=volume,
|
volume=volume,
|
||||||
pitch=pitch,
|
pitch=pitch,
|
||||||
|
|||||||
@@ -40,6 +40,7 @@ class SpeechGenerator:
|
|||||||
self,
|
self,
|
||||||
text: str,
|
text: str,
|
||||||
voice_id: str,
|
voice_id: str,
|
||||||
|
custom_voice_id: Optional[str] = None,
|
||||||
speed: float = 1.0,
|
speed: float = 1.0,
|
||||||
volume: float = 1.0,
|
volume: float = 1.0,
|
||||||
pitch: float = 0.0,
|
pitch: float = 0.0,
|
||||||
@@ -54,6 +55,7 @@ class SpeechGenerator:
|
|||||||
Args:
|
Args:
|
||||||
text: Text to convert to speech (max 10000 characters)
|
text: Text to convert to speech (max 10000 characters)
|
||||||
voice_id: Voice ID (e.g., "Wise_Woman", "Friendly_Person", etc.)
|
voice_id: Voice ID (e.g., "Wise_Woman", "Friendly_Person", etc.)
|
||||||
|
custom_voice_id: Custom voice clone ID for using cloned voice
|
||||||
speed: Speech speed (0.5-2.0, default: 1.0)
|
speed: Speech speed (0.5-2.0, default: 1.0)
|
||||||
volume: Speech volume (0.1-10.0, default: 1.0)
|
volume: Speech volume (0.1-10.0, default: 1.0)
|
||||||
pitch: Speech pitch (-12 to 12, default: 0.0)
|
pitch: Speech pitch (-12 to 12, default: 0.0)
|
||||||
@@ -77,6 +79,11 @@ class SpeechGenerator:
|
|||||||
if not sanitized_voice_id:
|
if not sanitized_voice_id:
|
||||||
raise ValueError("Voice ID cannot be empty after sanitization")
|
raise ValueError("Voice ID cannot be empty after sanitization")
|
||||||
|
|
||||||
|
# Sanitize custom_voice_id if provided
|
||||||
|
sanitized_custom_voice_id = None
|
||||||
|
if custom_voice_id:
|
||||||
|
sanitized_custom_voice_id = str(custom_voice_id).strip() or None
|
||||||
|
|
||||||
# Ensure numeric parameters are proper floats and within valid ranges
|
# Ensure numeric parameters are proper floats and within valid ranges
|
||||||
sanitized_speed = max(0.5, min(2.0, float(speed))) if speed is not None else 1.0
|
sanitized_speed = max(0.5, min(2.0, float(speed))) if speed is not None else 1.0
|
||||||
sanitized_volume = max(0.1, min(10.0, float(volume))) if volume is not None else 1.0
|
sanitized_volume = max(0.1, min(10.0, float(volume))) if volume is not None else 1.0
|
||||||
@@ -112,6 +119,10 @@ class SpeechGenerator:
|
|||||||
"enable_sync_mode": bool(enable_sync_mode),
|
"enable_sync_mode": bool(enable_sync_mode),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# Add custom voice clone ID if provided
|
||||||
|
if sanitized_custom_voice_id:
|
||||||
|
payload["custom_voice_id"] = sanitized_custom_voice_id
|
||||||
|
|
||||||
# Add optional parameters with proper type validation
|
# Add optional parameters with proper type validation
|
||||||
optional_params = [
|
optional_params = [
|
||||||
"english_normalization",
|
"english_normalization",
|
||||||
@@ -179,6 +190,20 @@ class SpeechGenerator:
|
|||||||
|
|
||||||
if response.status_code != 200:
|
if response.status_code != 200:
|
||||||
logger.error(f"[WaveSpeed] Speech generation failed: {response.status_code} {response.text}")
|
logger.error(f"[WaveSpeed] Speech generation failed: {response.status_code} {response.text}")
|
||||||
|
|
||||||
|
# Check for custom voice ID specific errors
|
||||||
|
response_text = response.text.lower()
|
||||||
|
if "custom_voice" in response_text or "voice_id" in response_text:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail={
|
||||||
|
"error": "Invalid voice clone ID",
|
||||||
|
"message": "The custom voice ID is invalid or expired. Please create a new voice clone or use a predefined voice.",
|
||||||
|
"status_code": response.status_code,
|
||||||
|
"response": response.text,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
status_code=502,
|
status_code=502,
|
||||||
detail={
|
detail={
|
||||||
|
|||||||
@@ -26,20 +26,24 @@ def _generate_simple_infinitetalk_prompt(
|
|||||||
story_context: Dict[str, Any],
|
story_context: Dict[str, Any],
|
||||||
) -> Optional[str]:
|
) -> Optional[str]:
|
||||||
"""
|
"""
|
||||||
Generate a balanced, concise prompt for InfiniteTalk.
|
Generate an enhanced prompt for InfiniteTalk video generation.
|
||||||
InfiniteTalk is audio-driven, so the prompt should describe the scene and suggest
|
Includes scene content, analysis, bible context, and visual elements.
|
||||||
subtle motion, but avoid overly elaborate cinematic descriptions.
|
|
||||||
|
|
||||||
Returns None if no meaningful prompt can be generated.
|
Returns None if no meaningful prompt can be generated.
|
||||||
"""
|
"""
|
||||||
title = (scene_data.get("title") or "").strip()
|
title = (scene_data.get("title") or "").strip()
|
||||||
description = (scene_data.get("description") or "").strip()
|
description = (scene_data.get("description") or "").strip()
|
||||||
image_prompt = (scene_data.get("image_prompt") or "").strip()
|
image_prompt = (scene_data.get("image_prompt") or "").strip()
|
||||||
|
lines = scene_data.get("lines", [])
|
||||||
|
narration = ""
|
||||||
|
if lines:
|
||||||
|
# Combine first few lines for context
|
||||||
|
narration = " ".join([str(l.get("text", "")) for l in lines[:3]])[:150]
|
||||||
|
|
||||||
# Build a balanced prompt: scene description + simple motion hint
|
# Build enhanced prompt with multiple context sources
|
||||||
parts = []
|
parts = []
|
||||||
|
|
||||||
# Add scene context
|
# Add main scene title
|
||||||
if title and len(title) > 5 and title.lower() not in ("scene", "podcast", "episode"):
|
if title and len(title) > 5 and title.lower() not in ("scene", "podcast", "episode"):
|
||||||
parts.append(title)
|
parts.append(title)
|
||||||
|
|
||||||
@@ -48,60 +52,70 @@ def _generate_simple_infinitetalk_prompt(
|
|||||||
if analysis:
|
if analysis:
|
||||||
content_type = analysis.get("content_type")
|
content_type = analysis.get("content_type")
|
||||||
if content_type:
|
if content_type:
|
||||||
parts.append(f"Style: {content_type}")
|
parts.append(f"Content type: {content_type}")
|
||||||
|
|
||||||
# Audience helps define the formality/vibe
|
# Add key takeaways if available
|
||||||
|
key_takeaways = analysis.get("keyTakeaways", [])
|
||||||
|
if key_takeaways and isinstance(key_takeaways, list) and len(key_takeaways) > 0:
|
||||||
|
takeaway = str(key_takeaways[0])[:80]
|
||||||
|
if takeaway:
|
||||||
|
parts.append(f"Key insight: {takeaway}")
|
||||||
|
|
||||||
|
# Audience
|
||||||
audience = analysis.get("audience")
|
audience = analysis.get("audience")
|
||||||
if audience:
|
if audience:
|
||||||
# Just use first few words of audience to keep it short
|
short_audience = " ".join(audience.split()[:3])
|
||||||
short_audience = " ".join(audience.split()[:3])
|
parts.append(f"Target audience: {short_audience}")
|
||||||
parts.append(f"For: {short_audience}")
|
|
||||||
|
# Guest info
|
||||||
# Add bible context if available
|
guest_name = analysis.get("guestName")
|
||||||
|
guest_expertise = analysis.get("guestExpertise")
|
||||||
|
if guest_name:
|
||||||
|
parts.append(f"Guest: {guest_name}")
|
||||||
|
if guest_expertise:
|
||||||
|
parts.append(f"Expertise: {guest_expertise}")
|
||||||
|
|
||||||
|
# Add bible context
|
||||||
bible = story_context.get("bible", {})
|
bible = story_context.get("bible", {})
|
||||||
if bible:
|
if bible:
|
||||||
host_persona = bible.get("host_persona")
|
host_persona = bible.get("host_persona")
|
||||||
tone = bible.get("tone")
|
tone = bible.get("tone")
|
||||||
|
visual_style = bible.get("visual_style")
|
||||||
|
background = bible.get("background")
|
||||||
|
|
||||||
if host_persona:
|
if host_persona:
|
||||||
parts.append(f"Host: {host_persona}")
|
parts.append(f"Host persona: {host_persona}")
|
||||||
if tone:
|
if tone:
|
||||||
parts.append(f"Tone: {tone}")
|
parts.append(f"Tone: {tone}")
|
||||||
|
if visual_style:
|
||||||
elif description:
|
parts.append(f"Visual style: {visual_style}")
|
||||||
# Take first sentence or first 60 chars
|
if background:
|
||||||
desc_part = description.split('.')[0][:60].strip()
|
parts.append(f"Background: {background}")
|
||||||
if desc_part:
|
|
||||||
parts.append(desc_part)
|
# Add original image prompt as fallback context
|
||||||
elif image_prompt:
|
if image_prompt and len(parts) < 3:
|
||||||
# Take first sentence or first 60 chars
|
img_part = image_prompt.split('.')[0][:100].strip()
|
||||||
img_part = image_prompt.split('.')[0][:60].strip()
|
|
||||||
if img_part:
|
if img_part:
|
||||||
parts.append(img_part)
|
parts.append(f"Visual context: {img_part}")
|
||||||
|
|
||||||
|
# Add narration snippet if available
|
||||||
|
if narration and len(parts) < 4:
|
||||||
|
parts.append(f"Discussing: {narration}")
|
||||||
|
|
||||||
if not parts:
|
if not parts:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
# Add a simple, subtle motion suggestion (not elaborate camera movements)
|
# Build prompt with visual quality keywords
|
||||||
# Keep it natural and audio-driven
|
quality_keywords = "Cinematic lighting, high detail, 4k quality, smooth motion"
|
||||||
motion_hints = [
|
|
||||||
"with subtle movement",
|
|
||||||
"with gentle motion",
|
|
||||||
"with natural animation",
|
|
||||||
]
|
|
||||||
|
|
||||||
# Combine scene description with subtle motion hint
|
# Combine parts into final prompt
|
||||||
if len(parts[0]) < 80:
|
prompt = f"{'. '.join(parts)}. {quality_keywords}. With subtle natural movement."
|
||||||
# Room for a motion hint
|
|
||||||
prompt = f"{parts[0]}, {motion_hints[0]}"
|
|
||||||
else:
|
|
||||||
# Just use the description if it's already long enough
|
|
||||||
prompt = parts[0]
|
|
||||||
|
|
||||||
# Keep it concise - max 120 characters (allows for scene + motion hint)
|
# Allow more room for detailed prompts - max 350 characters
|
||||||
prompt = prompt[:120].strip()
|
prompt = prompt[:350].strip()
|
||||||
|
|
||||||
# Clean up trailing commas or incomplete sentences
|
# Clean up trailing punctuation
|
||||||
if prompt.endswith(','):
|
if prompt.endswith(',') or prompt.endswith('.'):
|
||||||
prompt = prompt[:-1].strip()
|
prompt = prompt[:-1].strip()
|
||||||
|
|
||||||
return prompt if len(prompt) >= 15 else None
|
return prompt if len(prompt) >= 15 else None
|
||||||
|
|||||||
@@ -50,6 +50,10 @@ def should_bootstrap_linguistic_models() -> bool:
|
|||||||
if "all" in enabled_features:
|
if "all" in enabled_features:
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
# Podcast-only mode doesn't need linguistic models
|
||||||
|
if enabled_features == {"podcast"}:
|
||||||
|
return False
|
||||||
|
|
||||||
# Map old profile names to features for backwards compatibility
|
# Map old profile names to features for backwards compatibility
|
||||||
feature_mapping = {
|
feature_mapping = {
|
||||||
"podcast": "podcast",
|
"podcast": "podcast",
|
||||||
@@ -64,14 +68,18 @@ def should_bootstrap_linguistic_models() -> bool:
|
|||||||
|
|
||||||
|
|
||||||
def should_bootstrap_local_llm_models() -> bool:
|
def should_bootstrap_local_llm_models() -> bool:
|
||||||
"""Decide whether to bootstrap local LLM models based on enabled features."""
|
"""Decide whether to bootstrap local LLM models based on enabled features.
|
||||||
|
|
||||||
|
SIF/Story Writer requires local LLM - skip if only podcast is enabled.
|
||||||
|
"""
|
||||||
enabled_features = get_enabled_features()
|
enabled_features = get_enabled_features()
|
||||||
|
|
||||||
if "all" in enabled_features:
|
if "all" in enabled_features:
|
||||||
return True
|
return True
|
||||||
|
|
||||||
# Skip LLM bootstrap for lean deployments
|
# SIF/Story Writer requires local LLM - only bootstrap if explicitly needed
|
||||||
return "core" in enabled_features or "podcast" in enabled_features
|
# Skip for lean deployments (podcast-only, content-planning only, etc.)
|
||||||
|
return False # Default to skip unless "all" is enabled
|
||||||
|
|
||||||
|
|
||||||
def bootstrap_linguistic_models() -> BootstrapResult:
|
def bootstrap_linguistic_models() -> BootstrapResult:
|
||||||
@@ -209,6 +217,10 @@ def bootstrap_local_llm_models() -> BootstrapResult:
|
|||||||
# Bootstrap linguistic models BEFORE any imports that might need them
|
# Bootstrap linguistic models BEFORE any imports that might need them
|
||||||
BOOTSTRAP_RESULTS = []
|
BOOTSTRAP_RESULTS = []
|
||||||
|
|
||||||
|
# Load .env file early so ALWRITY_ENABLED_FEATURES is available
|
||||||
|
from dotenv import load_dotenv
|
||||||
|
load_dotenv()
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
enabled_features = get_enabled_features()
|
enabled_features = get_enabled_features()
|
||||||
features_str = ",".join(sorted(enabled_features))
|
features_str = ",".join(sorted(enabled_features))
|
||||||
|
|||||||
@@ -1,10 +1,7 @@
|
|||||||
import React from 'react';
|
import React, { useState, useEffect } from 'react';
|
||||||
import { BrowserRouter as Router, Routes, Route, Navigate, useLocation } from 'react-router-dom';
|
import { BrowserRouter as Router, Routes, Route, Navigate } from 'react-router-dom';
|
||||||
import { Box, CircularProgress, Typography } from '@mui/material';
|
import { Box, CircularProgress, Typography } from '@mui/material';
|
||||||
import { CopilotKit } from "@copilotkit/react-core";
|
|
||||||
import { ClerkProvider, useAuth } from '@clerk/clerk-react';
|
import { ClerkProvider, useAuth } from '@clerk/clerk-react';
|
||||||
import "@copilotkit/react-ui/styles.css";
|
|
||||||
import { shouldSkipOnboarding } from './utils/demoMode';
|
|
||||||
import Wizard from './components/OnboardingWizard/Wizard';
|
import Wizard from './components/OnboardingWizard/Wizard';
|
||||||
import MainDashboard from './components/MainDashboard/MainDashboard';
|
import MainDashboard from './components/MainDashboard/MainDashboard';
|
||||||
import SEODashboard from './components/SEODashboard/SEODashboard';
|
import SEODashboard from './components/SEODashboard/SEODashboard';
|
||||||
@@ -57,18 +54,11 @@ import GSCAuthCallback from './components/SEODashboard/components/GSCAuthCallbac
|
|||||||
import Landing from './components/Landing/Landing';
|
import Landing from './components/Landing/Landing';
|
||||||
import ErrorBoundary from './components/shared/ErrorBoundary';
|
import ErrorBoundary from './components/shared/ErrorBoundary';
|
||||||
import ErrorBoundaryTest from './components/shared/ErrorBoundaryTest';
|
import ErrorBoundaryTest from './components/shared/ErrorBoundaryTest';
|
||||||
import CopilotKitDegradedBanner from './components/shared/CopilotKitDegradedBanner';
|
|
||||||
import { OnboardingProvider } from './contexts/OnboardingContext';
|
import { OnboardingProvider } from './contexts/OnboardingContext';
|
||||||
import { SubscriptionProvider, useSubscription } from './contexts/SubscriptionContext';
|
import { SubscriptionProvider } from './contexts/SubscriptionContext';
|
||||||
import { CopilotKitHealthProvider } from './contexts/CopilotKitHealthContext';
|
import InitialRouteHandler from './components/App/InitialRouteHandler';
|
||||||
import { useOAuthTokenAlerts } from './hooks/useOAuthTokenAlerts';
|
import TokenInstaller from './components/App/TokenInstaller';
|
||||||
|
import { ConditionalCopilotKit, AuthenticatedCopilotWrapper } from './components/App/CopilotWrappers';
|
||||||
import { setAuthTokenGetter, setClerkSignOut } from './api/client';
|
|
||||||
import { setMediaAuthTokenGetter } from './utils/fetchMediaBlobUrl';
|
|
||||||
import { setBillingAuthTokenGetter } from './services/billingService';
|
|
||||||
import { useOnboarding } from './contexts/OnboardingContext';
|
|
||||||
import { useState, useEffect } from 'react';
|
|
||||||
import ConnectionErrorPage from './components/shared/ConnectionErrorPage';
|
|
||||||
|
|
||||||
// interface OnboardingStatus {
|
// interface OnboardingStatus {
|
||||||
// onboarding_required: boolean;
|
// onboarding_required: boolean;
|
||||||
@@ -78,401 +68,6 @@ import ConnectionErrorPage from './components/shared/ConnectionErrorPage';
|
|||||||
// completion_percentage?: number;
|
// completion_percentage?: number;
|
||||||
// }
|
// }
|
||||||
|
|
||||||
// Conditional CopilotKit wrapper that only shows sidebar on content-planning route
|
|
||||||
const ConditionalCopilotKit: React.FC<{ children: React.ReactNode }> = ({ children }) => {
|
|
||||||
// Do not render CopilotSidebar here. Let specific pages/components control it.
|
|
||||||
return <>{children}</>;
|
|
||||||
};
|
|
||||||
|
|
||||||
// Wrapper to only enable CopilotKit checks/provider when user is authenticated
|
|
||||||
// This prevents CopilotKit from running on the Landing page
|
|
||||||
const AuthenticatedCopilotWrapper: React.FC<{
|
|
||||||
children: React.ReactNode;
|
|
||||||
apiKey: string;
|
|
||||||
}> = ({ children, apiKey }) => {
|
|
||||||
const { isSignedIn } = useAuth();
|
|
||||||
const location = useLocation();
|
|
||||||
|
|
||||||
// Exclude CopilotKit from running on:
|
|
||||||
// 1. Landing page (handled by !isSignedIn)
|
|
||||||
// 2. Onboarding pages (to prevent health check timeouts)
|
|
||||||
const shouldExcludeCopilot = !isSignedIn || location.pathname.startsWith('/onboarding');
|
|
||||||
|
|
||||||
if (shouldExcludeCopilot) {
|
|
||||||
return <>{children}</>;
|
|
||||||
}
|
|
||||||
|
|
||||||
const hasKey = apiKey && apiKey.trim();
|
|
||||||
|
|
||||||
if (hasKey) {
|
|
||||||
// Enhanced error handler that updates health context
|
|
||||||
const handleCopilotKitError = (e: any) => {
|
|
||||||
console.error("CopilotKit Error:", e);
|
|
||||||
|
|
||||||
// Try to get health context if available
|
|
||||||
// We'll use a custom event to notify health context since we can't access it directly here
|
|
||||||
const errorMessage = e?.error?.message || e?.message || 'CopilotKit error occurred';
|
|
||||||
const errorType = errorMessage.toLowerCase();
|
|
||||||
|
|
||||||
// Differentiate between fatal and transient errors
|
|
||||||
const isFatalError =
|
|
||||||
errorType.includes('cors') ||
|
|
||||||
errorType.includes('ssl') ||
|
|
||||||
errorType.includes('certificate') ||
|
|
||||||
errorType.includes('403') ||
|
|
||||||
errorType.includes('forbidden') ||
|
|
||||||
errorType.includes('ERR_CERT_COMMON_NAME_INVALID');
|
|
||||||
|
|
||||||
// Dispatch event for health context to listen to
|
|
||||||
window.dispatchEvent(new CustomEvent('copilotkit-error', {
|
|
||||||
detail: {
|
|
||||||
error: e,
|
|
||||||
errorMessage,
|
|
||||||
isFatal: isFatalError,
|
|
||||||
}
|
|
||||||
}));
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<CopilotKitHealthProvider initialHealthStatus={true}>
|
|
||||||
<CopilotKitDegradedBanner />
|
|
||||||
<ErrorBoundary
|
|
||||||
context="CopilotKit"
|
|
||||||
showDetails={process.env.NODE_ENV === 'development'}
|
|
||||||
fallback={
|
|
||||||
<Box sx={{ p: 3, textAlign: 'center' }}>
|
|
||||||
<Typography variant="h6" color="warning" gutterBottom>
|
|
||||||
Chat Unavailable
|
|
||||||
</Typography>
|
|
||||||
<Typography variant="body2" color="textSecondary">
|
|
||||||
CopilotKit encountered an error. The app continues to work with manual controls.
|
|
||||||
</Typography>
|
|
||||||
</Box>
|
|
||||||
}
|
|
||||||
>
|
|
||||||
<CopilotKit
|
|
||||||
publicApiKey={apiKey}
|
|
||||||
showDevConsole={false}
|
|
||||||
onError={handleCopilotKitError}
|
|
||||||
>
|
|
||||||
{children}
|
|
||||||
</CopilotKit>
|
|
||||||
</ErrorBoundary>
|
|
||||||
</CopilotKitHealthProvider>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<CopilotKitHealthProvider initialHealthStatus={false}>
|
|
||||||
<CopilotKitDegradedBanner />
|
|
||||||
{children}
|
|
||||||
</CopilotKitHealthProvider>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
// Component to handle initial routing based on subscription and onboarding status
|
|
||||||
// Flow: Subscription → Onboarding → Dashboard
|
|
||||||
const InitialRouteHandler: React.FC = () => {
|
|
||||||
const { loading, error, isOnboardingComplete, initializeOnboarding, data } = useOnboarding();
|
|
||||||
const { subscription, loading: subscriptionLoading, checkSubscription } = useSubscription();
|
|
||||||
const location = useLocation();
|
|
||||||
const [connectionError, setConnectionError] = useState<{
|
|
||||||
hasError: boolean;
|
|
||||||
error: Error | null;
|
|
||||||
}>({
|
|
||||||
hasError: false,
|
|
||||||
error: null,
|
|
||||||
});
|
|
||||||
|
|
||||||
// Poll for OAuth token alerts and show toast notifications
|
|
||||||
// Only enabled when user is authenticated (has subscription)
|
|
||||||
useOAuthTokenAlerts({
|
|
||||||
enabled: subscription?.active === true,
|
|
||||||
interval: 60000, // Poll every 1 minute
|
|
||||||
});
|
|
||||||
|
|
||||||
// Check subscription on mount (non-blocking - don't wait for it to route)
|
|
||||||
useEffect(() => {
|
|
||||||
// Delay subscription check slightly to allow auth token getter to be installed first
|
|
||||||
const timeoutId = setTimeout(async () => {
|
|
||||||
// Retry logic for initial subscription check
|
|
||||||
const maxRetries = 3;
|
|
||||||
for (let attempt = 0; attempt < maxRetries; attempt++) {
|
|
||||||
try {
|
|
||||||
await checkSubscription();
|
|
||||||
break; // Success
|
|
||||||
} catch (err) {
|
|
||||||
console.error(`App: Subscription check attempt ${attempt + 1} failed:`, err);
|
|
||||||
|
|
||||||
// If it's a connection error and we have retries left, wait and retry
|
|
||||||
const isConnectionError = err instanceof Error && (err.name === 'NetworkError' || err.name === 'ConnectionError');
|
|
||||||
|
|
||||||
if (isConnectionError && attempt < maxRetries - 1) {
|
|
||||||
const delay = 1000 * Math.pow(2, attempt); // 1s, 2s
|
|
||||||
await new Promise(resolve => setTimeout(resolve, delay));
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
// If final attempt or not a connection error, handle it
|
|
||||||
if (attempt === maxRetries - 1 || !isConnectionError) {
|
|
||||||
if (isConnectionError) {
|
|
||||||
setConnectionError({
|
|
||||||
hasError: true,
|
|
||||||
error: err as Error,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
// Don't block routing on other errors
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}, 100); // Small delay to ensure TokenInstaller has run
|
|
||||||
|
|
||||||
return () => clearTimeout(timeoutId);
|
|
||||||
}, []); // Remove checkSubscription dependency to prevent loop
|
|
||||||
|
|
||||||
// Handle post-Stripe-checkout redirect in demo mode
|
|
||||||
const urlParams = new URLSearchParams(location.search);
|
|
||||||
const isCheckoutSuccess = urlParams.get('subscription') === 'success';
|
|
||||||
|
|
||||||
// Initialize onboarding only after subscription is confirmed
|
|
||||||
useEffect(() => {
|
|
||||||
if (subscription && !subscriptionLoading) {
|
|
||||||
// Check if user is new (no subscription record at all)
|
|
||||||
const isNewUser = !subscription || subscription.plan === 'none';
|
|
||||||
|
|
||||||
console.log('InitialRouteHandler: Subscription data received:', {
|
|
||||||
plan: subscription.plan,
|
|
||||||
active: subscription.active,
|
|
||||||
isNewUser,
|
|
||||||
subscriptionLoading
|
|
||||||
});
|
|
||||||
|
|
||||||
if (subscription.active && !isNewUser) {
|
|
||||||
console.log('InitialRouteHandler: Subscription confirmed, initializing onboarding...');
|
|
||||||
|
|
||||||
// Don't initialize onboarding if checkout was successful - early return handles redirect
|
|
||||||
if (!isCheckoutSuccess) {
|
|
||||||
initializeOnboarding();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}, [subscription, subscriptionLoading, initializeOnboarding, isCheckoutSuccess]);
|
|
||||||
|
|
||||||
// Early return for checkout success in demo mode
|
|
||||||
if (isCheckoutSuccess && subscription?.active && shouldSkipOnboarding()) {
|
|
||||||
console.log('InitialRouteHandler: Early redirect - Stripe checkout success in demo mode → Podcast Maker');
|
|
||||||
return <Navigate to="/podcast-maker" replace />;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Handle connection error - show connection error page
|
|
||||||
if (connectionError.hasError) {
|
|
||||||
const handleRetry = () => {
|
|
||||||
setConnectionError({
|
|
||||||
hasError: false,
|
|
||||||
error: null,
|
|
||||||
});
|
|
||||||
// Re-trigger the subscription check using context
|
|
||||||
checkSubscription().catch((err) => {
|
|
||||||
if (err instanceof Error && (err.name === 'NetworkError' || err.name === 'ConnectionError')) {
|
|
||||||
setConnectionError({
|
|
||||||
hasError: true,
|
|
||||||
error: err,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleGoHome = () => {
|
|
||||||
window.location.href = '/';
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<ConnectionErrorPage
|
|
||||||
onRetry={handleRetry}
|
|
||||||
onGoHome={handleGoHome}
|
|
||||||
message={connectionError.error?.message || "Backend service is not available. Please check if the server is running."}
|
|
||||||
title="Connection Error"
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Loading state - only wait for onboarding init when user has active subscription
|
|
||||||
// In demo mode, skip waiting for onboarding data entirely
|
|
||||||
// This allows no-subscription/inactive flows to continue even when onboarding data is still null.
|
|
||||||
const isDemoMode = shouldSkipOnboarding();
|
|
||||||
const isActiveSubscriber = Boolean(subscription && subscription.active && subscription.plan !== 'none');
|
|
||||||
const waitingForOnboardingInit = !isDemoMode && isActiveSubscriber && (loading || !data);
|
|
||||||
if (waitingForOnboardingInit) {
|
|
||||||
return (
|
|
||||||
<Box
|
|
||||||
display="flex"
|
|
||||||
flexDirection="column"
|
|
||||||
alignItems="center"
|
|
||||||
justifyContent="center"
|
|
||||||
minHeight="100vh"
|
|
||||||
gap={2}
|
|
||||||
>
|
|
||||||
<CircularProgress size={60} />
|
|
||||||
<Typography variant="h6" color="textSecondary">
|
|
||||||
Preparing your workspace...
|
|
||||||
</Typography>
|
|
||||||
</Box>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Error state
|
|
||||||
if (error) {
|
|
||||||
return (
|
|
||||||
<Box
|
|
||||||
display="flex"
|
|
||||||
flexDirection="column"
|
|
||||||
alignItems="center"
|
|
||||||
justifyContent="center"
|
|
||||||
minHeight="100vh"
|
|
||||||
gap={2}
|
|
||||||
p={3}
|
|
||||||
>
|
|
||||||
<Typography variant="h5" color="error" gutterBottom>
|
|
||||||
Error
|
|
||||||
</Typography>
|
|
||||||
<Typography variant="body1" color="textSecondary" textAlign="center">
|
|
||||||
{error}
|
|
||||||
</Typography>
|
|
||||||
</Box>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Decision tree for SIGNED-IN users:
|
|
||||||
// Priority: Subscription → Onboarding → Dashboard (as per user flow: Landing → Subscription → Onboarding → Dashboard)
|
|
||||||
|
|
||||||
// 1. If subscription is still loading, show loading state
|
|
||||||
if (subscriptionLoading) {
|
|
||||||
return (
|
|
||||||
<Box
|
|
||||||
display="flex"
|
|
||||||
flexDirection="column"
|
|
||||||
alignItems="center"
|
|
||||||
justifyContent="center"
|
|
||||||
minHeight="100vh"
|
|
||||||
gap={2}
|
|
||||||
>
|
|
||||||
<CircularProgress size={60} />
|
|
||||||
<Typography variant="h6" color="textSecondary">
|
|
||||||
Checking subscription...
|
|
||||||
</Typography>
|
|
||||||
</Box>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 2. No subscription data yet - handle gracefully
|
|
||||||
// If onboarding is complete, allow access to dashboard (user already went through flow)
|
|
||||||
// If onboarding not complete, check if subscription check is still loading or failed
|
|
||||||
if (!subscription) {
|
|
||||||
if (isOnboardingComplete) {
|
|
||||||
console.log('InitialRouteHandler: Onboarding complete but no subscription data → Dashboard (allow access)');
|
|
||||||
return <Navigate to="/dashboard" replace />;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Onboarding not complete and no subscription data
|
|
||||||
// If subscription check is still loading, show loading state
|
|
||||||
if (subscriptionLoading) {
|
|
||||||
return (
|
|
||||||
<Box
|
|
||||||
display="flex"
|
|
||||||
flexDirection="column"
|
|
||||||
alignItems="center"
|
|
||||||
justifyContent="center"
|
|
||||||
minHeight="100vh"
|
|
||||||
gap={2}
|
|
||||||
>
|
|
||||||
<CircularProgress size={60} />
|
|
||||||
<Typography variant="h6" color="textSecondary">
|
|
||||||
Checking subscription...
|
|
||||||
</Typography>
|
|
||||||
</Box>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Subscription check completed but returned null/undefined
|
|
||||||
// In demo mode, allow access to podcast-maker even with no subscription data
|
|
||||||
if (!subscription) {
|
|
||||||
if (isOnboardingComplete) {
|
|
||||||
console.log('InitialRouteHandler: Onboarding complete but no subscription data → Dashboard (allow access)');
|
|
||||||
return <Navigate to="/dashboard" replace />;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Onboarding not complete and no subscription data
|
|
||||||
// If subscription check is still loading, show loading state
|
|
||||||
if (subscriptionLoading) {
|
|
||||||
return (
|
|
||||||
<Box
|
|
||||||
display="flex"
|
|
||||||
flexDirection="column"
|
|
||||||
alignItems="center"
|
|
||||||
justifyContent="center"
|
|
||||||
minHeight="100vh"
|
|
||||||
gap={2}
|
|
||||||
>
|
|
||||||
<CircularProgress size={60} />
|
|
||||||
<Typography variant="h6" color="textSecondary">
|
|
||||||
Checking subscription...
|
|
||||||
</Typography>
|
|
||||||
</Box>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// In demo mode, redirect to podcast-maker even without subscription
|
|
||||||
if (shouldSkipOnboarding()) {
|
|
||||||
console.log('InitialRouteHandler: Demo mode - no subscription but allowing access to podcast-maker');
|
|
||||||
return <Navigate to="/podcast-maker" replace />;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Subscription check completed but returned null/undefined
|
|
||||||
// This likely means no subscription - redirect to pricing
|
|
||||||
console.log('InitialRouteHandler: No subscription data after check → Pricing page');
|
|
||||||
return <Navigate to="/pricing" replace />;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 3. Check subscription status first
|
|
||||||
const isNewUser = !subscription || subscription.plan === 'none';
|
|
||||||
|
|
||||||
// No active subscription → Show modal (SubscriptionContext handles this)
|
|
||||||
// Don't redirect immediately - let the modal show first
|
|
||||||
// User can click "Renew Subscription" button in modal to go to pricing
|
|
||||||
// Or click "Maybe Later" to dismiss (but they still can't use features)
|
|
||||||
if (isNewUser || !subscription.active) {
|
|
||||||
console.log('InitialRouteHandler: No active subscription - modal will be shown by SubscriptionContext');
|
|
||||||
// Note: SubscriptionContext will show the modal automatically when subscription is inactive
|
|
||||||
// We still redirect to pricing for new users, but allow existing users with expired subscriptions
|
|
||||||
// to see the modal first. The modal has a "Renew Subscription" button that navigates to pricing.
|
|
||||||
// For new users (no subscription at all), redirect to pricing immediately
|
|
||||||
if (isNewUser) {
|
|
||||||
console.log('InitialRouteHandler: New user (no subscription) → Pricing page');
|
|
||||||
return <Navigate to="/pricing" replace />;
|
|
||||||
}
|
|
||||||
// For existing users with inactive subscription, show modal but don't redirect immediately
|
|
||||||
// The modal will be shown by SubscriptionContext, and user can click "Renew Subscription"
|
|
||||||
// Allow access to dashboard (modal will be shown and block functionality)
|
|
||||||
console.log('InitialRouteHandler: Inactive subscription - allowing access to show modal');
|
|
||||||
// Continue to onboarding/dashboard flow - modal will be shown by SubscriptionContext
|
|
||||||
}
|
|
||||||
|
|
||||||
// 4. Has active subscription, check onboarding status
|
|
||||||
if (!isOnboardingComplete) {
|
|
||||||
// In demo mode, skip onboarding and go directly to podcast-maker
|
|
||||||
if (shouldSkipOnboarding()) {
|
|
||||||
console.log('InitialRouteHandler: Demo mode - skipping onboarding → Podcast Maker');
|
|
||||||
return <Navigate to="/podcast-maker" replace />;
|
|
||||||
}
|
|
||||||
console.log('InitialRouteHandler: Subscription active but onboarding incomplete → Onboarding');
|
|
||||||
return <Navigate to="/onboarding" replace />;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 5. Has subscription AND completed onboarding → Dashboard
|
|
||||||
console.log('InitialRouteHandler: All set (subscription + onboarding) → Dashboard');
|
|
||||||
return <Navigate to="/dashboard" replace />;
|
|
||||||
};
|
|
||||||
|
|
||||||
// Root route that chooses Landing (signed out) or InitialRouteHandler (signed in)
|
// Root route that chooses Landing (signed out) or InitialRouteHandler (signed in)
|
||||||
const RootRoute: React.FC = () => {
|
const RootRoute: React.FC = () => {
|
||||||
const { isSignedIn } = useAuth();
|
const { isSignedIn } = useAuth();
|
||||||
@@ -482,64 +77,6 @@ const RootRoute: React.FC = () => {
|
|||||||
return <Landing />;
|
return <Landing />;
|
||||||
};
|
};
|
||||||
|
|
||||||
// Installs Clerk auth token getter into axios clients and stores user_id
|
|
||||||
// Must render under ClerkProvider
|
|
||||||
const TokenInstaller: React.FC = () => {
|
|
||||||
const { getToken, userId, isSignedIn, signOut } = useAuth();
|
|
||||||
|
|
||||||
// Store user_id in localStorage when user signs in
|
|
||||||
useEffect(() => {
|
|
||||||
if (isSignedIn && userId) {
|
|
||||||
console.log('TokenInstaller: Storing user_id in localStorage:', userId);
|
|
||||||
localStorage.setItem('user_id', userId);
|
|
||||||
|
|
||||||
// Trigger event to notify SubscriptionContext that user is authenticated
|
|
||||||
window.dispatchEvent(new CustomEvent('user-authenticated', { detail: { userId } }));
|
|
||||||
} else if (!isSignedIn) {
|
|
||||||
// Clear user_id when signed out
|
|
||||||
console.log('TokenInstaller: Clearing user_id from localStorage');
|
|
||||||
localStorage.removeItem('user_id');
|
|
||||||
}
|
|
||||||
}, [isSignedIn, userId]);
|
|
||||||
|
|
||||||
// Install token getter for API calls
|
|
||||||
useEffect(() => {
|
|
||||||
const tokenGetter = async () => {
|
|
||||||
try {
|
|
||||||
const template = process.env.REACT_APP_CLERK_JWT_TEMPLATE;
|
|
||||||
// If a template is provided and it's not a placeholder, request a template-specific JWT
|
|
||||||
if (template && template !== 'your_jwt_template_name_here') {
|
|
||||||
// @ts-ignore Clerk types allow options object
|
|
||||||
return await getToken({ template });
|
|
||||||
}
|
|
||||||
return await getToken();
|
|
||||||
} catch {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// Set token getter for main API client
|
|
||||||
setAuthTokenGetter(tokenGetter);
|
|
||||||
|
|
||||||
// Set token getter for billing API client (same function)
|
|
||||||
setBillingAuthTokenGetter(tokenGetter);
|
|
||||||
|
|
||||||
// Set token getter for media blob URL fetcher (for authenticated image/video requests)
|
|
||||||
setMediaAuthTokenGetter(tokenGetter);
|
|
||||||
}, [getToken]);
|
|
||||||
|
|
||||||
// Install Clerk signOut function for handling expired tokens
|
|
||||||
useEffect(() => {
|
|
||||||
if (signOut) {
|
|
||||||
setClerkSignOut(async () => {
|
|
||||||
await signOut();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}, [signOut]);
|
|
||||||
|
|
||||||
return null;
|
|
||||||
};
|
|
||||||
|
|
||||||
const App: React.FC = () => {
|
const App: React.FC = () => {
|
||||||
// React Hooks MUST be at the top before any conditionals
|
// React Hooks MUST be at the top before any conditionals
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ export interface AssetResponse {
|
|||||||
export interface VoiceCloneResponse {
|
export interface VoiceCloneResponse {
|
||||||
success: boolean;
|
success: boolean;
|
||||||
custom_voice_id?: string;
|
custom_voice_id?: string;
|
||||||
|
voice_name?: string;
|
||||||
preview_audio_url?: string;
|
preview_audio_url?: string;
|
||||||
asset_id?: number;
|
asset_id?: number;
|
||||||
message?: string;
|
message?: string;
|
||||||
|
|||||||
@@ -1,10 +1,11 @@
|
|||||||
import React, { useState, useEffect } from "react";
|
import React, { useState, useEffect } from "react";
|
||||||
import { Stack, Box, Typography, Divider, Chip, Paper, alpha, CircularProgress, TextField, IconButton, Select, MenuItem, FormControl, InputLabel, Switch, FormControlLabel } from "@mui/material";
|
import { Stack, Box, Typography, Divider, Chip, Paper, alpha, CircularProgress, Button, Checkbox } from "@mui/material";
|
||||||
import { Psychology as PsychologyIcon, Insights as InsightsIcon, Search as SearchIcon, Person as PersonIcon, AutoAwesome as AutoAwesomeIcon, Edit as EditIcon, Save as SaveIcon, Close as CloseIcon, Add as AddIcon, EditNote as EditNoteIcon } from "@mui/icons-material";
|
import { Psychology as PsychologyIcon, Insights as InsightsIcon, Search as SearchIcon, Person as PersonIcon, AutoAwesome as AutoAwesomeIcon, Edit as EditIcon, Save as SaveIcon, Close as CloseIcon, Add as AddIcon, EditNote as EditNoteIcon, Input as InputIcon, Groups as GroupsIcon, ListAlt as ListAltIcon, RecordVoiceOver as VoiceIcon, Lightbulb as TipsIcon, Quiz as TalkIcon } from "@mui/icons-material";
|
||||||
import { PodcastAnalysis, PodcastEstimate } from "./types";
|
import { PodcastAnalysis, PodcastEstimate } from "./types";
|
||||||
import { GlassyCard, glassyCardSx, SecondaryButton } from "./ui";
|
import { GlassyCard, glassyCardSx, SecondaryButton } from "./ui";
|
||||||
import { Refresh as RefreshIcon } from "@mui/icons-material";
|
import { Refresh as RefreshIcon } from "@mui/icons-material";
|
||||||
import { aiApiClient } from "../../api/client";
|
import { aiApiClient } from "../../api/client";
|
||||||
|
import { InputsTab, AudienceTab, OutlineTab, TitlesTab, HookTab, TakeawaysTab, GuestTab, CTATab } from "./AnalysisPanel/tabs";
|
||||||
|
|
||||||
interface AnalysisPanelProps {
|
interface AnalysisPanelProps {
|
||||||
analysis: PodcastAnalysis | null;
|
analysis: PodcastAnalysis | null;
|
||||||
@@ -16,6 +17,19 @@ interface AnalysisPanelProps {
|
|||||||
avatarPrompt?: string | null;
|
avatarPrompt?: string | null;
|
||||||
onRegenerate?: () => void;
|
onRegenerate?: () => void;
|
||||||
onUpdateAnalysis?: (updatedAnalysis: PodcastAnalysis) => void;
|
onUpdateAnalysis?: (updatedAnalysis: PodcastAnalysis) => void;
|
||||||
|
onRunResearch?: () => void;
|
||||||
|
isResearchRunning?: boolean;
|
||||||
|
selectedQueries?: Set<string>;
|
||||||
|
onToggleQuery?: (queryId: string) => void;
|
||||||
|
queries?: { id: string; query: string; rationale: string }[];
|
||||||
|
}
|
||||||
|
|
||||||
|
type TabId = 'inputs' | 'audience' | 'content' | 'outline' | 'titles' | 'hook' | 'takeaways' | 'cta' | 'guest';
|
||||||
|
|
||||||
|
interface TabConfig {
|
||||||
|
id: TabId;
|
||||||
|
label: string;
|
||||||
|
icon: React.ReactNode;
|
||||||
}
|
}
|
||||||
|
|
||||||
const inputStyles = {
|
const inputStyles = {
|
||||||
@@ -54,8 +68,14 @@ export const AnalysisPanel: React.FC<AnalysisPanelProps> = ({
|
|||||||
avatarUrl,
|
avatarUrl,
|
||||||
avatarPrompt,
|
avatarPrompt,
|
||||||
onRegenerate,
|
onRegenerate,
|
||||||
onUpdateAnalysis
|
onUpdateAnalysis,
|
||||||
|
onRunResearch,
|
||||||
|
isResearchRunning,
|
||||||
|
selectedQueries,
|
||||||
|
onToggleQuery,
|
||||||
|
queries
|
||||||
}) => {
|
}) => {
|
||||||
|
const [activeTab, setActiveTab] = useState<TabId>('inputs');
|
||||||
const [avatarBlobUrl, setAvatarBlobUrl] = useState<string | null>(null);
|
const [avatarBlobUrl, setAvatarBlobUrl] = useState<string | null>(null);
|
||||||
const [avatarLoading, setAvatarLoading] = useState(false);
|
const [avatarLoading, setAvatarLoading] = useState(false);
|
||||||
const [avatarError, setAvatarError] = useState(false);
|
const [avatarError, setAvatarError] = useState(false);
|
||||||
@@ -64,6 +84,38 @@ export const AnalysisPanel: React.FC<AnalysisPanelProps> = ({
|
|||||||
const [isEditing, setIsEditing] = useState(false);
|
const [isEditing, setIsEditing] = useState(false);
|
||||||
const [editedAnalysis, setEditedAnalysis] = useState<PodcastAnalysis | null>(null);
|
const [editedAnalysis, setEditedAnalysis] = useState<PodcastAnalysis | null>(null);
|
||||||
|
|
||||||
|
const tabs: TabConfig[] = [
|
||||||
|
{ id: 'inputs', label: 'Your Inputs', icon: <InputIcon /> },
|
||||||
|
{ id: 'audience', label: 'Audience', icon: <GroupsIcon /> },
|
||||||
|
{ id: 'content', label: 'Content', icon: <ListAltIcon /> },
|
||||||
|
{ id: 'outline', label: 'Outline', icon: <ListAltIcon /> },
|
||||||
|
{ id: 'titles', label: 'Titles', icon: <EditNoteIcon /> },
|
||||||
|
{ id: 'hook', label: 'Hook', icon: <AutoAwesomeIcon /> },
|
||||||
|
{ id: 'takeaways', label: 'Takeaways', icon: <TipsIcon /> },
|
||||||
|
{ id: 'guest', label: 'Guest', icon: <PersonIcon /> },
|
||||||
|
{ id: 'cta', label: 'CTA', icon: <VoiceIcon /> },
|
||||||
|
];
|
||||||
|
|
||||||
|
const tabButtonStyles = (isActive: boolean) => ({
|
||||||
|
background: isActive
|
||||||
|
? "linear-gradient(135deg, #667eea 0%, #764ba2 100%)"
|
||||||
|
: "transparent",
|
||||||
|
color: isActive ? "#fff" : "#64748b",
|
||||||
|
border: isActive ? "none" : "1px solid rgba(0,0,0,0.1)",
|
||||||
|
borderRadius: 2,
|
||||||
|
px: 2,
|
||||||
|
py: 1,
|
||||||
|
fontSize: "0.75rem",
|
||||||
|
fontWeight: 600,
|
||||||
|
textTransform: "none" as const,
|
||||||
|
transition: "all 0.2s ease",
|
||||||
|
"&:hover": {
|
||||||
|
background: isActive
|
||||||
|
? "linear-gradient(135deg, #764ba2 0%, #667eea 100%)"
|
||||||
|
: "rgba(102,126,234,0.08)",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
// Sync editedAnalysis with analysis initially
|
// Sync editedAnalysis with analysis initially
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (analysis && !editedAnalysis) {
|
if (analysis && !editedAnalysis) {
|
||||||
@@ -325,622 +377,183 @@ export const AnalysisPanel: React.FC<AnalysisPanelProps> = ({
|
|||||||
|
|
||||||
<Divider sx={{ borderColor: "rgba(0,0,0,0.06)" }} />
|
<Divider sx={{ borderColor: "rgba(0,0,0,0.06)" }} />
|
||||||
|
|
||||||
{/* Inputs Section */}
|
{/* AI Futuristic Tab Navigation */}
|
||||||
{(idea || duration || speakers || avatarUrl || avatarPrompt) && (
|
<Stack direction="row" flexWrap="wrap" gap={1} sx={{ mb: 2 }}>
|
||||||
<>
|
{tabs.map((tab) => (
|
||||||
<Box>
|
<Button
|
||||||
<Typography
|
key={tab.id}
|
||||||
variant="subtitle1"
|
onClick={() => setActiveTab(tab.id)}
|
||||||
|
startIcon={tab.icon}
|
||||||
|
sx={tabButtonStyles(activeTab === tab.id)}
|
||||||
|
>
|
||||||
|
{tab.label}
|
||||||
|
</Button>
|
||||||
|
))}
|
||||||
|
</Stack>
|
||||||
|
|
||||||
|
{/* Tab Content */}
|
||||||
|
<Box sx={{ minHeight: 300 }}>
|
||||||
|
{activeTab === 'inputs' && (
|
||||||
|
<InputsTab
|
||||||
|
idea={idea}
|
||||||
|
duration={duration}
|
||||||
|
speakers={speakers}
|
||||||
|
avatarUrl={avatarUrl}
|
||||||
|
avatarPrompt={avatarPrompt}
|
||||||
|
avatarBlobUrl={avatarBlobUrl}
|
||||||
|
avatarLoading={avatarLoading}
|
||||||
|
avatarError={avatarError}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{activeTab === 'audience' && (
|
||||||
|
<AudienceTab
|
||||||
|
analysis={currentAnalysis}
|
||||||
|
isEditing={isEditing}
|
||||||
|
editedAnalysis={editedAnalysis}
|
||||||
|
setEditedAnalysis={setEditedAnalysis}
|
||||||
|
handleRemoveKeyword={handleRemoveKeyword}
|
||||||
|
handleAddKeyword={handleAddKeyword}
|
||||||
|
handleRemoveTitle={handleRemoveTitle}
|
||||||
|
handleAddTitle={handleAddTitle}
|
||||||
|
handleUpdateOutline={handleUpdateOutline}
|
||||||
|
updateExaConfig={updateExaConfig}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{activeTab === 'outline' && (
|
||||||
|
<OutlineTab
|
||||||
|
analysis={currentAnalysis}
|
||||||
|
isEditing={isEditing}
|
||||||
|
onUpdateOutline={handleUpdateOutline}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{activeTab === 'titles' && (
|
||||||
|
<TitlesTab
|
||||||
|
analysis={currentAnalysis}
|
||||||
|
isEditing={isEditing}
|
||||||
|
handleRemoveTitle={handleRemoveTitle}
|
||||||
|
handleAddTitle={handleAddTitle}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{activeTab === 'hook' && (
|
||||||
|
<HookTab analysis={currentAnalysis} />
|
||||||
|
)}
|
||||||
|
|
||||||
|
{activeTab === 'takeaways' && (
|
||||||
|
<TakeawaysTab analysis={currentAnalysis} />
|
||||||
|
)}
|
||||||
|
|
||||||
|
{activeTab === 'guest' && (
|
||||||
|
<GuestTab analysis={currentAnalysis} />
|
||||||
|
)}
|
||||||
|
|
||||||
|
{activeTab === 'cta' && (
|
||||||
|
<CTATab analysis={currentAnalysis} />
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
{/* Research Section - Separate from tabs */}
|
||||||
|
<Divider sx={{ borderColor: "rgba(0,0,0,0.06)", my: 2 }} />
|
||||||
|
|
||||||
|
<Box>
|
||||||
|
<Stack direction="row" justifyContent="space-between" alignItems="center" sx={{ mb: 2 }}>
|
||||||
|
<Typography variant="subtitle1" sx={{ color: "#0f172a", fontWeight: 700, display: "flex", alignItems: "center", gap: 1 }}>
|
||||||
|
<SearchIcon sx={{ color: "#4f46e5" }} />
|
||||||
|
Research Queries
|
||||||
|
{selectedQueries && selectedQueries.size > 0 && (
|
||||||
|
<Chip
|
||||||
|
label={`${selectedQueries.size} selected`}
|
||||||
|
size="small"
|
||||||
|
sx={{ ml: 1, height: 20, fontSize: "0.65rem", bgcolor: "#4f46e5", color: "#fff" }}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</Typography>
|
||||||
|
{onRunResearch && (
|
||||||
|
<Button
|
||||||
|
variant="contained"
|
||||||
|
size="small"
|
||||||
|
onClick={onRunResearch}
|
||||||
|
disabled={isResearchRunning || !selectedQueries || selectedQueries.size === 0}
|
||||||
|
startIcon={isResearchRunning ? <CircularProgress size={16} color="inherit" /> : <SearchIcon />}
|
||||||
sx={{
|
sx={{
|
||||||
color: "#0f172a",
|
background: "linear-gradient(135deg, #667eea 0%, #764ba2 100%)",
|
||||||
fontWeight: 700,
|
color: "#fff",
|
||||||
mb: 1.5,
|
fontWeight: 600,
|
||||||
display: "flex",
|
fontSize: "0.75rem",
|
||||||
alignItems: "center",
|
px: 2,
|
||||||
gap: 0.5,
|
py: 0.75,
|
||||||
|
borderRadius: 2,
|
||||||
|
textTransform: "none",
|
||||||
|
"&:hover": {
|
||||||
|
background: "linear-gradient(135deg, #764ba2 0%, #667eea 100%)",
|
||||||
|
},
|
||||||
|
"&:disabled": {
|
||||||
|
background: "#94a3b8",
|
||||||
|
}
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
Your Inputs
|
{isResearchRunning ? "Running..." : "Run Research"}
|
||||||
</Typography>
|
</Button>
|
||||||
<Box
|
)}
|
||||||
sx={{
|
</Stack>
|
||||||
display: "grid",
|
|
||||||
gridTemplateColumns: { xs: "1fr", md: avatarUrl ? "1fr 1fr" : "1fr" },
|
{!analysis?.research_queries || analysis.research_queries.length === 0 ? (
|
||||||
gap: 3,
|
<Typography variant="body2" sx={{ color: "#64748b", fontStyle: "italic" }}>
|
||||||
alignItems: "flex-start",
|
No research queries yet. Click "Regenerate Analysis" to generate research queries based on your podcast idea.
|
||||||
}}
|
</Typography>
|
||||||
>
|
) : (
|
||||||
{/* Left Column: Text Inputs */}
|
<Stack spacing={1.5}>
|
||||||
<Stack spacing={1.5}>
|
{(queries || analysis.research_queries?.map((rq, idx) => ({ id: `query-${idx}`, ...rq }))).map((rq: { id: string; query: string; rationale: string }, idx: number) => {
|
||||||
{idea && (
|
const queryId = rq.id;
|
||||||
<Box>
|
const isSelected = selectedQueries?.has(queryId) || false;
|
||||||
<Typography variant="caption" sx={{ color: "#64748b", fontWeight: 600, display: "block", mb: 0.5 }}>
|
return (
|
||||||
Podcast Idea
|
<Paper
|
||||||
</Typography>
|
key={idx}
|
||||||
<Typography variant="body2" sx={{ color: "#0f172a", wordBreak: "break-word" }}>
|
elevation={0}
|
||||||
{idea}
|
sx={{
|
||||||
</Typography>
|
p: 2,
|
||||||
</Box>
|
bgcolor: isSelected ? "#f0f9ff" : "#f8fafc",
|
||||||
)}
|
border: `1px solid ${isSelected ? 'rgba(79,70,229,0.4)' : 'rgba(0,0,0,0.08)'}`,
|
||||||
<Stack direction="row" spacing={2} flexWrap="wrap">
|
borderRadius: 2,
|
||||||
{duration !== undefined && (
|
transition: "all 0.2s ease",
|
||||||
<Box>
|
cursor: onToggleQuery ? "pointer" : "default",
|
||||||
<Typography variant="caption" sx={{ color: "#64748b", fontWeight: 600, display: "block", mb: 0.5 }}>
|
"&:hover": onToggleQuery ? {
|
||||||
Duration
|
borderColor: "rgba(79,70,229,0.3)",
|
||||||
</Typography>
|
bgcolor: "#f8fafc"
|
||||||
<Chip
|
} : {}
|
||||||
label={`${duration} minutes`}
|
}}
|
||||||
size="small"
|
onClick={() => onToggleQuery?.(queryId)}
|
||||||
sx={{ background: "#f1f5f9", color: "#0f172a", border: "1px solid rgba(0,0,0,0.08)" }}
|
>
|
||||||
/>
|
<Stack direction="row" alignItems="flex-start" gap={1.5}>
|
||||||
</Box>
|
<Checkbox
|
||||||
)}
|
checked={isSelected}
|
||||||
{speakers !== undefined && (
|
onChange={() => onToggleQuery?.(queryId)}
|
||||||
<Box>
|
|
||||||
<Typography variant="caption" sx={{ color: "#64748b", fontWeight: 600, display: "block", mb: 0.5 }}>
|
|
||||||
Speakers
|
|
||||||
</Typography>
|
|
||||||
<Chip
|
|
||||||
label={`${speakers} ${speakers === 1 ? "speaker" : "speakers"}`}
|
|
||||||
size="small"
|
|
||||||
sx={{ background: "#f1f5f9", color: "#0f172a", border: "1px solid rgba(0,0,0,0.08)" }}
|
|
||||||
/>
|
|
||||||
</Box>
|
|
||||||
)}
|
|
||||||
</Stack>
|
|
||||||
|
|
||||||
{/* AI Prompt Used for Avatar Generation */}
|
|
||||||
{avatarUrl && (
|
|
||||||
<Box>
|
|
||||||
<Typography
|
|
||||||
variant="caption"
|
|
||||||
sx={{
|
sx={{
|
||||||
color: "#64748b",
|
color: "#64748b",
|
||||||
fontWeight: 600,
|
"&.Mui-checked": {
|
||||||
display: "flex",
|
color: "#4f46e5",
|
||||||
alignItems: "center",
|
},
|
||||||
gap: 0.5,
|
padding: 0.5,
|
||||||
mb: 0.75,
|
|
||||||
}}
|
}}
|
||||||
>
|
/>
|
||||||
<AutoAwesomeIcon sx={{ fontSize: 14 }} />
|
<Chip label={idx + 1} size="small" sx={{ minWidth: 24, bgcolor: "#4f46e5", color: "#fff" }} />
|
||||||
AI Generation Prompt
|
<Box>
|
||||||
</Typography>
|
<Typography variant="body2" sx={{ color: "#0f172a", fontWeight: 600, mb: 0.5 }}>
|
||||||
{avatarPrompt ? (
|
{rq.query}
|
||||||
<Paper
|
|
||||||
sx={{
|
|
||||||
p: 1.5,
|
|
||||||
background: "#f8fafc",
|
|
||||||
border: "1px solid rgba(0,0,0,0.08)",
|
|
||||||
borderRadius: 1.5,
|
|
||||||
maxHeight: 200,
|
|
||||||
overflow: "auto",
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<Typography
|
|
||||||
variant="caption"
|
|
||||||
sx={{
|
|
||||||
color: "#475569",
|
|
||||||
fontFamily: "monospace",
|
|
||||||
fontSize: "0.75rem",
|
|
||||||
lineHeight: 1.6,
|
|
||||||
whiteSpace: "pre-wrap",
|
|
||||||
wordBreak: "break-word",
|
|
||||||
display: "block",
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{avatarPrompt}
|
|
||||||
</Typography>
|
|
||||||
</Paper>
|
|
||||||
) : (
|
|
||||||
<Paper
|
|
||||||
sx={{
|
|
||||||
p: 1.5,
|
|
||||||
background: "#f1f5f9",
|
|
||||||
border: "1px solid rgba(0,0,0,0.08)",
|
|
||||||
borderRadius: 1.5,
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<Typography
|
|
||||||
variant="caption"
|
|
||||||
sx={{
|
|
||||||
color: "#64748b",
|
|
||||||
fontStyle: "italic",
|
|
||||||
fontSize: "0.75rem",
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
Prompt not available (avatar was uploaded or generated before this feature was added)
|
|
||||||
</Typography>
|
|
||||||
</Paper>
|
|
||||||
)}
|
|
||||||
</Box>
|
|
||||||
)}
|
|
||||||
</Stack>
|
|
||||||
|
|
||||||
{/* Right Column: Presenter Avatar */}
|
|
||||||
{avatarUrl && (
|
|
||||||
<Box>
|
|
||||||
<Typography
|
|
||||||
variant="caption"
|
|
||||||
sx={{
|
|
||||||
color: "#64748b",
|
|
||||||
fontWeight: 600,
|
|
||||||
display: "flex",
|
|
||||||
alignItems: "center",
|
|
||||||
gap: 0.5,
|
|
||||||
mb: 1,
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<PersonIcon sx={{ fontSize: 16 }} />
|
|
||||||
Presenter Avatar
|
|
||||||
</Typography>
|
|
||||||
<Box
|
|
||||||
sx={{
|
|
||||||
width: "100%",
|
|
||||||
maxWidth: { xs: "100%", md: 300 },
|
|
||||||
borderRadius: 2,
|
|
||||||
overflow: "hidden",
|
|
||||||
border: "1px solid rgba(102,126,234,0.2)",
|
|
||||||
background: alpha("#667eea", 0.05),
|
|
||||||
position: "relative",
|
|
||||||
aspectRatio: "1",
|
|
||||||
boxShadow: "0 4px 12px rgba(0,0,0,0.08)",
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{avatarLoading ? (
|
|
||||||
<Box
|
|
||||||
sx={{
|
|
||||||
display: "flex",
|
|
||||||
alignItems: "center",
|
|
||||||
justifyContent: "center",
|
|
||||||
height: "100%",
|
|
||||||
background: "#f8fafc",
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<CircularProgress size={40} />
|
|
||||||
</Box>
|
|
||||||
) : avatarError ? (
|
|
||||||
<Box
|
|
||||||
sx={{
|
|
||||||
display: "flex",
|
|
||||||
alignItems: "center",
|
|
||||||
justifyContent: "center",
|
|
||||||
height: "100%",
|
|
||||||
background: "#fef2f2",
|
|
||||||
color: "#dc2626",
|
|
||||||
p: 2,
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<Typography variant="caption" sx={{ textAlign: "center" }}>
|
|
||||||
Failed to load avatar
|
|
||||||
</Typography>
|
|
||||||
</Box>
|
|
||||||
) : avatarBlobUrl ? (
|
|
||||||
<Box
|
|
||||||
component="img"
|
|
||||||
src={avatarBlobUrl}
|
|
||||||
alt="Podcast Presenter"
|
|
||||||
sx={{
|
|
||||||
width: "100%",
|
|
||||||
height: "100%",
|
|
||||||
objectFit: "cover",
|
|
||||||
display: "block",
|
|
||||||
}}
|
|
||||||
onError={(e) => {
|
|
||||||
console.error('[AnalysisPanel] Avatar image failed to load:', {
|
|
||||||
src: e.currentTarget.src,
|
|
||||||
avatarUrl,
|
|
||||||
avatarBlobUrl,
|
|
||||||
});
|
|
||||||
setAvatarError(true);
|
|
||||||
}}
|
|
||||||
onLoad={() => {
|
|
||||||
console.log('[AnalysisPanel] Avatar image loaded successfully');
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
) : null}
|
|
||||||
</Box>
|
|
||||||
</Box>
|
|
||||||
)}
|
|
||||||
</Box>
|
|
||||||
</Box>
|
|
||||||
<Divider sx={{ borderColor: "rgba(0,0,0,0.06)" }} />
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<Box sx={{ display: "grid", gridTemplateColumns: { xs: "1fr", md: "1fr 1fr" }, gap: 3 }}>
|
|
||||||
<Stack spacing={3}>
|
|
||||||
<Box>
|
|
||||||
<Typography variant="subtitle2" sx={{ mb: 1, display: "flex", alignItems: "center", gap: 0.5 }}>
|
|
||||||
<InsightsIcon fontSize="small" sx={{ color: "#4f46e5" }} />
|
|
||||||
Target Audience
|
|
||||||
</Typography>
|
|
||||||
{isEditing ? (
|
|
||||||
<TextField
|
|
||||||
fullWidth
|
|
||||||
multiline
|
|
||||||
rows={2}
|
|
||||||
size="small"
|
|
||||||
value={currentAnalysis.audience}
|
|
||||||
onChange={(e) => setEditedAnalysis({ ...currentAnalysis, audience: e.target.value })}
|
|
||||||
placeholder="Describe your target audience..."
|
|
||||||
sx={inputStyles}
|
|
||||||
/>
|
|
||||||
) : (
|
|
||||||
<Typography variant="body2" sx={{ color: "#0f172a" }}>
|
|
||||||
{currentAnalysis.audience}
|
|
||||||
</Typography>
|
|
||||||
)}
|
|
||||||
</Box>
|
|
||||||
|
|
||||||
<Box>
|
|
||||||
<Typography variant="subtitle2" sx={{ mb: 1, color: "#0f172a" }}>Content Type</Typography>
|
|
||||||
{isEditing ? (
|
|
||||||
<TextField
|
|
||||||
fullWidth
|
|
||||||
size="small"
|
|
||||||
value={currentAnalysis.contentType}
|
|
||||||
onChange={(e) => setEditedAnalysis({ ...currentAnalysis, contentType: e.target.value })}
|
|
||||||
placeholder="e.g. Interview, Narrative, Solo..."
|
|
||||||
sx={inputStyles}
|
|
||||||
/>
|
|
||||||
) : (
|
|
||||||
<Chip label={currentAnalysis.contentType} size="small" sx={{ background: "#eef2ff", color: "#0f172a", border: "1px solid rgba(0,0,0,0.06)" }} />
|
|
||||||
)}
|
|
||||||
</Box>
|
|
||||||
|
|
||||||
<Box>
|
|
||||||
<Typography variant="subtitle2" sx={{ mb: 1, color: "#0f172a" }}>Top Keywords</Typography>
|
|
||||||
<Stack direction="row" spacing={0.5} flexWrap="wrap" useFlexGap sx={{ mb: isEditing ? 1.5 : 0 }}>
|
|
||||||
{currentAnalysis.topKeywords.map((k) => (
|
|
||||||
<Chip
|
|
||||||
key={k}
|
|
||||||
label={k}
|
|
||||||
size="small"
|
|
||||||
variant="outlined"
|
|
||||||
onDelete={isEditing ? () => handleRemoveKeyword(k) : undefined}
|
|
||||||
sx={{
|
|
||||||
borderColor: "rgba(0,0,0,0.1)",
|
|
||||||
color: "#0f172a",
|
|
||||||
background: "#f8fafc",
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
))}
|
|
||||||
</Stack>
|
|
||||||
{isEditing && (
|
|
||||||
<TextField
|
|
||||||
fullWidth
|
|
||||||
size="small"
|
|
||||||
placeholder="Add keyword and press Enter..."
|
|
||||||
sx={inputStyles}
|
|
||||||
onKeyDown={(e) => {
|
|
||||||
if (e.key === 'Enter') {
|
|
||||||
e.preventDefault();
|
|
||||||
handleAddKeyword((e.target as HTMLInputElement).value);
|
|
||||||
(e.target as HTMLInputElement).value = '';
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
InputProps={{
|
|
||||||
endAdornment: (
|
|
||||||
<IconButton size="small" onClick={(e) => {
|
|
||||||
const input = (e.currentTarget.parentElement?.parentElement?.querySelector('input') as HTMLInputElement);
|
|
||||||
handleAddKeyword(input.value);
|
|
||||||
input.value = '';
|
|
||||||
}}>
|
|
||||||
<AddIcon fontSize="small" sx={{ color: '#4f46e5' }} />
|
|
||||||
</IconButton>
|
|
||||||
)
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
</Box>
|
|
||||||
|
|
||||||
<Box>
|
|
||||||
<Typography variant="subtitle2" sx={{ mb: 1, color: "#111827", fontWeight: 700, display: "flex", alignItems: "center", gap: 1 }}>
|
|
||||||
<EditNoteIcon fontSize="small" sx={{ color: "#4f46e5" }} />
|
|
||||||
Suggested Episode Outlines
|
|
||||||
</Typography>
|
|
||||||
<Stack spacing={2}>
|
|
||||||
{currentAnalysis.suggestedOutlines.map((o) => (
|
|
||||||
<Paper
|
|
||||||
key={o.id}
|
|
||||||
elevation={0}
|
|
||||||
sx={{
|
|
||||||
p: 2,
|
|
||||||
background: isEditing ? "#ffffff" : "#f8fafc",
|
|
||||||
border: "1px solid",
|
|
||||||
borderColor: isEditing ? "#e2e8f0" : "rgba(0,0,0,0.04)",
|
|
||||||
borderRadius: 2,
|
|
||||||
wordBreak: "break-word",
|
|
||||||
position: 'relative',
|
|
||||||
transition: "all 0.2s ease",
|
|
||||||
"&:hover": {
|
|
||||||
borderColor: "#4f46e5",
|
|
||||||
boxShadow: "0 4px 12px rgba(79, 70, 229, 0.05)"
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{isEditing ? (
|
|
||||||
<Stack spacing={2}>
|
|
||||||
<TextField
|
|
||||||
fullWidth
|
|
||||||
size="small"
|
|
||||||
label="Outline Title"
|
|
||||||
value={o.title}
|
|
||||||
onChange={(e) => handleUpdateOutline(o.id, 'title', e.target.value)}
|
|
||||||
sx={inputStyles}
|
|
||||||
/>
|
|
||||||
<TextField
|
|
||||||
fullWidth
|
|
||||||
multiline
|
|
||||||
size="small"
|
|
||||||
label="Segments"
|
|
||||||
value={o.segments.join(' • ')}
|
|
||||||
onChange={(e) => handleUpdateOutline(o.id, 'segments', e.target.value.split(/•|,/).map(s => s.trim()).filter(Boolean))}
|
|
||||||
helperText="Use • or comma to separate segments"
|
|
||||||
sx={inputStyles}
|
|
||||||
/>
|
|
||||||
</Stack>
|
|
||||||
) : (
|
|
||||||
<>
|
|
||||||
<Typography variant="body1" sx={{ fontWeight: 800, mb: 1, color: "#111827" }}>
|
|
||||||
{o.title}
|
|
||||||
</Typography>
|
</Typography>
|
||||||
<Stack spacing={1}>
|
<Typography variant="caption" sx={{ color: "#64748b" }}>
|
||||||
{o.segments.map((segment, idx) => (
|
Rationale: {rq.rationale}
|
||||||
<Box key={idx} sx={{ display: "flex", alignItems: "flex-start", gap: 1 }}>
|
</Typography>
|
||||||
<Box sx={{ mt: 1, width: 6, height: 6, borderRadius: "50%", bgcolor: "#4f46e5", flexShrink: 0 }} />
|
</Box>
|
||||||
<Typography variant="body2" sx={{ color: "#4b5563", lineHeight: 1.5 }}>
|
</Stack>
|
||||||
{segment}
|
|
||||||
</Typography>
|
|
||||||
</Box>
|
|
||||||
))}
|
|
||||||
</Stack>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</Paper>
|
</Paper>
|
||||||
))}
|
);
|
||||||
</Stack>
|
})}
|
||||||
</Box>
|
</Stack>
|
||||||
</Stack>
|
)}
|
||||||
|
|
||||||
<Stack spacing={3}>
|
|
||||||
{currentAnalysis.exaSuggestedConfig && (
|
|
||||||
<Box>
|
|
||||||
<Typography variant="subtitle2" sx={{ mb: 1, color: "#0f172a", display: "flex", alignItems: "center", gap: 0.5 }}>
|
|
||||||
<SearchIcon fontSize="small" sx={{ color: "#4f46e5" }} />
|
|
||||||
Exa Research Suggestions
|
|
||||||
</Typography>
|
|
||||||
|
|
||||||
{isEditing ? (
|
|
||||||
<Stack spacing={2} sx={{ p: 2, border: '1px solid #e2e8f0', borderRadius: 2, bgcolor: '#ffffff' }}>
|
|
||||||
<Stack direction="row" spacing={2}>
|
|
||||||
<FormControl fullWidth size="small" sx={inputStyles}>
|
|
||||||
<InputLabel>Search Type</InputLabel>
|
|
||||||
<Select
|
|
||||||
value={currentAnalysis.exaSuggestedConfig.exa_search_type || 'auto'}
|
|
||||||
label="Search Type"
|
|
||||||
onChange={(e) => updateExaConfig('exa_search_type', e.target.value)}
|
|
||||||
>
|
|
||||||
<MenuItem value="auto">Auto</MenuItem>
|
|
||||||
<MenuItem value="neural">Neural</MenuItem>
|
|
||||||
<MenuItem value="keyword">Keyword</MenuItem>
|
|
||||||
</Select>
|
|
||||||
</FormControl>
|
|
||||||
<FormControl fullWidth size="small" sx={inputStyles}>
|
|
||||||
<InputLabel>Category</InputLabel>
|
|
||||||
<Select
|
|
||||||
value={currentAnalysis.exaSuggestedConfig.exa_category || 'news'}
|
|
||||||
label="Category"
|
|
||||||
onChange={(e) => updateExaConfig('exa_category', e.target.value)}
|
|
||||||
>
|
|
||||||
<MenuItem value="news">News</MenuItem>
|
|
||||||
<MenuItem value="research paper">Research Paper</MenuItem>
|
|
||||||
<MenuItem value="company">Company</MenuItem>
|
|
||||||
<MenuItem value="pdf">PDF</MenuItem>
|
|
||||||
<MenuItem value="tweet">Tweet</MenuItem>
|
|
||||||
</Select>
|
|
||||||
</FormControl>
|
|
||||||
</Stack>
|
|
||||||
|
|
||||||
<Stack direction="row" spacing={2} alignItems="center">
|
|
||||||
<FormControl fullWidth size="small" sx={inputStyles}>
|
|
||||||
<InputLabel>Date Range</InputLabel>
|
|
||||||
<Select
|
|
||||||
value={currentAnalysis.exaSuggestedConfig.date_range || 'all_time'}
|
|
||||||
label="Date Range"
|
|
||||||
onChange={(e) => updateExaConfig('date_range', e.target.value)}
|
|
||||||
>
|
|
||||||
<MenuItem value="all_time">All Time</MenuItem>
|
|
||||||
<MenuItem value="last_month">Last Month</MenuItem>
|
|
||||||
<MenuItem value="last_year">Last Year</MenuItem>
|
|
||||||
</Select>
|
|
||||||
</FormControl>
|
|
||||||
<TextField
|
|
||||||
type="number"
|
|
||||||
label="Max Sources"
|
|
||||||
size="small"
|
|
||||||
value={currentAnalysis.exaSuggestedConfig.max_sources || 10}
|
|
||||||
onChange={(e) => updateExaConfig('max_sources', parseInt(e.target.value))}
|
|
||||||
sx={{ ...inputStyles, width: 120 }}
|
|
||||||
/>
|
|
||||||
</Stack>
|
|
||||||
|
|
||||||
<FormControlLabel
|
|
||||||
control={
|
|
||||||
<Switch
|
|
||||||
size="small"
|
|
||||||
checked={currentAnalysis.exaSuggestedConfig.include_statistics || false}
|
|
||||||
onChange={(e) => updateExaConfig('include_statistics', e.target.checked)}
|
|
||||||
sx={{ '& .MuiSwitch-track': { bgcolor: '#4f46e5' } }}
|
|
||||||
/>
|
|
||||||
}
|
|
||||||
label={<Typography variant="body2" sx={{ color: '#111827', fontWeight: 500 }}>Include Statistics</Typography>}
|
|
||||||
/>
|
|
||||||
|
|
||||||
<Stack spacing={1}>
|
|
||||||
<TextField
|
|
||||||
fullWidth
|
|
||||||
size="small"
|
|
||||||
label="Prefer Domains"
|
|
||||||
placeholder="e.g. techcrunch.com, wired.com (press Enter)"
|
|
||||||
sx={inputStyles}
|
|
||||||
onKeyDown={(e) => {
|
|
||||||
if (e.key === 'Enter') {
|
|
||||||
e.preventDefault();
|
|
||||||
const val = (e.target as HTMLInputElement).value.trim();
|
|
||||||
if (val) {
|
|
||||||
const domains = currentAnalysis.exaSuggestedConfig?.exa_include_domains || [];
|
|
||||||
updateExaConfig('exa_include_domains', [...domains, val]);
|
|
||||||
(e.target as HTMLInputElement).value = '';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
<Stack direction="row" spacing={0.5} flexWrap="wrap" useFlexGap>
|
|
||||||
{(currentAnalysis.exaSuggestedConfig.exa_include_domains || []).map(d => (
|
|
||||||
<Chip key={d} label={d} size="small" onDelete={() => {
|
|
||||||
const domains = currentAnalysis.exaSuggestedConfig?.exa_include_domains?.filter(item => item !== d);
|
|
||||||
updateExaConfig('exa_include_domains', domains);
|
|
||||||
}} sx={{ bgcolor: '#f3f4f6', color: '#111827' }} />
|
|
||||||
))}
|
|
||||||
</Stack>
|
|
||||||
</Stack>
|
|
||||||
</Stack>
|
|
||||||
) : (
|
|
||||||
<>
|
|
||||||
<Stack direction="row" spacing={0.5} flexWrap="wrap" useFlexGap sx={{ mb: 1 }}>
|
|
||||||
{currentAnalysis.exaSuggestedConfig.exa_search_type && (
|
|
||||||
<Chip
|
|
||||||
label={`Search: ${currentAnalysis.exaSuggestedConfig.exa_search_type}`}
|
|
||||||
size="small"
|
|
||||||
sx={{ background: "#eef2ff", color: "#0f172a", border: "1px solid rgba(0,0,0,0.06)" }}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
{currentAnalysis.exaSuggestedConfig.exa_category && (
|
|
||||||
<Chip
|
|
||||||
label={`Category: ${currentAnalysis.exaSuggestedConfig.exa_category}`}
|
|
||||||
size="small"
|
|
||||||
sx={{ background: "#eef2ff", color: "#0f172a", border: "1px solid rgba(0,0,0,0.06)" }}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
{currentAnalysis.exaSuggestedConfig.date_range && (
|
|
||||||
<Chip
|
|
||||||
label={`Date: ${currentAnalysis.exaSuggestedConfig.date_range}`}
|
|
||||||
size="small"
|
|
||||||
sx={{ background: "#eef2ff", color: "#0f172a", border: "1px solid rgba(0,0,0,0.06)" }}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
{typeof currentAnalysis.exaSuggestedConfig.include_statistics === "boolean" && (
|
|
||||||
<Chip
|
|
||||||
label={currentAnalysis.exaSuggestedConfig.include_statistics ? "Include stats" : "No stats needed"}
|
|
||||||
size="small"
|
|
||||||
sx={{ background: "#eef2ff", color: "#0f172a", border: "1px solid rgba(0,0,0,0.06)" }}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
{currentAnalysis.exaSuggestedConfig.max_sources && (
|
|
||||||
<Chip
|
|
||||||
label={`Max sources: ${currentAnalysis.exaSuggestedConfig.max_sources}`}
|
|
||||||
size="small"
|
|
||||||
sx={{ background: "#eef2ff", color: "#0f172a", border: "1px solid rgba(0,0,0,0.06)" }}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
</Stack>
|
|
||||||
|
|
||||||
{(currentAnalysis.exaSuggestedConfig.exa_include_domains?.length || currentAnalysis.exaSuggestedConfig.exa_exclude_domains?.length) && (
|
|
||||||
<Stack direction="row" spacing={2} flexWrap="wrap" useFlexGap>
|
|
||||||
{currentAnalysis.exaSuggestedConfig.exa_include_domains?.length ? (
|
|
||||||
<Box>
|
|
||||||
<Typography variant="caption" sx={{ color: "#475569", fontWeight: 600, display: "block", mb: 0.5 }}>
|
|
||||||
Prefer domains
|
|
||||||
</Typography>
|
|
||||||
<Stack direction="row" spacing={0.5} flexWrap="wrap" useFlexGap>
|
|
||||||
{currentAnalysis.exaSuggestedConfig.exa_include_domains.map((d) => (
|
|
||||||
<Chip key={d} label={d} size="small" sx={{ background: "#f8fafc", color: "#0f172a", border: "1px solid rgba(0,0,0,0.08)" }} />
|
|
||||||
))}
|
|
||||||
</Stack>
|
|
||||||
</Box>
|
|
||||||
) : null}
|
|
||||||
|
|
||||||
{currentAnalysis.exaSuggestedConfig.exa_exclude_domains?.length ? (
|
|
||||||
<Box>
|
|
||||||
<Typography variant="caption" sx={{ color: "#475569", fontWeight: 600, display: "block", mb: 0.5 }}>
|
|
||||||
Avoid domains
|
|
||||||
</Typography>
|
|
||||||
<Stack direction="row" spacing={0.5} flexWrap="wrap" useFlexGap>
|
|
||||||
{currentAnalysis.exaSuggestedConfig.exa_exclude_domains.map((d) => (
|
|
||||||
<Chip key={d} label={d} size="small" sx={{ background: "#fff7ed", color: "#b45309", border: "1px solid rgba(180,83,9,0.25)" }} />
|
|
||||||
))}
|
|
||||||
</Stack>
|
|
||||||
</Box>
|
|
||||||
) : null}
|
|
||||||
</Stack>
|
|
||||||
)}
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</Box>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<Box>
|
|
||||||
<Typography variant="subtitle2" sx={{ mb: 1, color: "#0f172a" }}>Title Suggestions</Typography>
|
|
||||||
<Stack direction="row" spacing={0.5} flexWrap="wrap" useFlexGap sx={{ mb: isEditing ? 1.5 : 0 }}>
|
|
||||||
{currentAnalysis.titleSuggestions.map((t) => (
|
|
||||||
<Chip
|
|
||||||
key={t}
|
|
||||||
label={t}
|
|
||||||
size="small"
|
|
||||||
onDelete={isEditing ? () => handleRemoveTitle(t) : undefined}
|
|
||||||
sx={{
|
|
||||||
cursor: isEditing ? "default" : "pointer",
|
|
||||||
color: "#0f172a",
|
|
||||||
background: "#f8fafc",
|
|
||||||
maxWidth: "100%",
|
|
||||||
whiteSpace: "normal",
|
|
||||||
height: "auto",
|
|
||||||
lineHeight: 1.3,
|
|
||||||
"& .MuiChip-label": {
|
|
||||||
whiteSpace: "normal",
|
|
||||||
wordBreak: "break-word",
|
|
||||||
textAlign: "left",
|
|
||||||
paddingTop: 0.25,
|
|
||||||
paddingBottom: 0.25,
|
|
||||||
},
|
|
||||||
"&:hover": isEditing ? {} : {
|
|
||||||
background: alpha("#667eea", 0.15),
|
|
||||||
border: "1px solid rgba(102,126,234,0.35)",
|
|
||||||
},
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
))}
|
|
||||||
</Stack>
|
|
||||||
{isEditing && (
|
|
||||||
<TextField
|
|
||||||
fullWidth
|
|
||||||
size="small"
|
|
||||||
placeholder="Add title suggestion..."
|
|
||||||
sx={inputStyles}
|
|
||||||
onKeyDown={(e) => {
|
|
||||||
if (e.key === 'Enter') {
|
|
||||||
e.preventDefault();
|
|
||||||
handleAddTitle((e.target as HTMLInputElement).value);
|
|
||||||
(e.target as HTMLInputElement).value = '';
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
InputProps={{
|
|
||||||
endAdornment: (
|
|
||||||
<IconButton size="small" onClick={(e) => {
|
|
||||||
const input = (e.currentTarget.parentElement?.parentElement?.querySelector('input') as HTMLInputElement);
|
|
||||||
handleAddTitle(input.value);
|
|
||||||
input.value = '';
|
|
||||||
}}>
|
|
||||||
<AddIcon fontSize="small" sx={{ color: '#4f46e5' }} />
|
|
||||||
</IconButton>
|
|
||||||
)
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
</Box>
|
|
||||||
</Stack>
|
|
||||||
</Box>
|
</Box>
|
||||||
</Stack>
|
</Stack>
|
||||||
</GlassyCard>
|
</GlassyCard>
|
||||||
|
|||||||
@@ -0,0 +1,92 @@
|
|||||||
|
import React from "react";
|
||||||
|
import { Stack, Button, Typography, Box } from "@mui/material";
|
||||||
|
import { Input as InputIcon, Groups as GroupsIcon, ListAlt as ListAltIcon, EditNote as EditNoteIcon, Search as SearchIcon, AutoAwesome as AutoAwesomeIcon, Lightbulb as TipsIcon, Quiz as TalkIcon, RecordVoiceOver as VoiceIcon } from "@mui/icons-material";
|
||||||
|
|
||||||
|
export type TabId = "inputs" | "audience" | "content" | "outline" | "titles" | "research" | "hook" | "takeaways" | "guest" | "cta";
|
||||||
|
|
||||||
|
interface TabConfig {
|
||||||
|
id: TabId;
|
||||||
|
label: string;
|
||||||
|
icon: React.ReactNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const ANALYSIS_TABS: TabConfig[] = [
|
||||||
|
{ id: "inputs", label: "Your Inputs", icon: <InputIcon /> },
|
||||||
|
{ id: "audience", label: "Audience", icon: <GroupsIcon /> },
|
||||||
|
{ id: "content", label: "Content", icon: <ListAltIcon /> },
|
||||||
|
{ id: "outline", label: "Outline", icon: <ListAltIcon /> },
|
||||||
|
{ id: "titles", label: "Titles", icon: <EditNoteIcon /> },
|
||||||
|
{ id: "research", label: "Research", icon: <SearchIcon /> },
|
||||||
|
{ id: "hook", label: "Hook", icon: <AutoAwesomeIcon /> },
|
||||||
|
{ id: "takeaways", label: "Takeaways", icon: <TipsIcon /> },
|
||||||
|
{ id: "guest", label: "Guest", icon: <TalkIcon /> },
|
||||||
|
{ id: "cta", label: "CTA", icon: <VoiceIcon /> },
|
||||||
|
];
|
||||||
|
|
||||||
|
const getTabButtonStyles = (isActive: boolean) => ({
|
||||||
|
background: isActive
|
||||||
|
? "linear-gradient(135deg, #667eea 0%, #764ba2 100%)"
|
||||||
|
: "transparent",
|
||||||
|
color: isActive ? "#fff" : "#64748b",
|
||||||
|
border: isActive ? "none" : "1px solid rgba(0,0,0,0.1)",
|
||||||
|
borderRadius: 2,
|
||||||
|
px: 2,
|
||||||
|
py: 1,
|
||||||
|
fontSize: "0.75rem",
|
||||||
|
fontWeight: 600,
|
||||||
|
textTransform: "none" as const,
|
||||||
|
transition: "all 0.2s ease",
|
||||||
|
"&:hover": {
|
||||||
|
background: isActive
|
||||||
|
? "linear-gradient(135deg, #764ba2 0%, #667eea 100%)"
|
||||||
|
: "rgba(102,126,234,0.08)",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
interface AnalysisTabNavProps {
|
||||||
|
activeTab: TabId;
|
||||||
|
onTabChange: (tab: TabId) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const AnalysisTabNav: React.FC<AnalysisTabNavProps> = ({ activeTab, onTabChange }) => {
|
||||||
|
return (
|
||||||
|
<Stack direction="row" flexWrap="wrap" gap={1}>
|
||||||
|
{ANALYSIS_TABS.map((tab) => (
|
||||||
|
<Button
|
||||||
|
key={tab.id}
|
||||||
|
onClick={() => onTabChange(tab.id)}
|
||||||
|
startIcon={tab.icon}
|
||||||
|
sx={getTabButtonStyles(activeTab === tab.id)}
|
||||||
|
>
|
||||||
|
{tab.label}
|
||||||
|
</Button>
|
||||||
|
))}
|
||||||
|
</Stack>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const AnalysisTabContent: React.FC<{ children: React.ReactNode; title?: string; icon?: React.ReactNode }> = ({
|
||||||
|
children,
|
||||||
|
title,
|
||||||
|
icon,
|
||||||
|
}) => (
|
||||||
|
<Box>
|
||||||
|
{title && (
|
||||||
|
<Typography
|
||||||
|
variant="subtitle2"
|
||||||
|
sx={{
|
||||||
|
mb: 2,
|
||||||
|
color: "#0f172a",
|
||||||
|
fontWeight: 700,
|
||||||
|
display: "flex",
|
||||||
|
alignItems: "center",
|
||||||
|
gap: 0.5,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{icon}
|
||||||
|
{title}
|
||||||
|
</Typography>
|
||||||
|
)}
|
||||||
|
{children}
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
@@ -0,0 +1,211 @@
|
|||||||
|
import React from "react";
|
||||||
|
import { Stack, Box, Typography, Chip, TextField, IconButton, Paper, Divider } from "@mui/material";
|
||||||
|
import { Groups as GroupsIcon, Insights as InsightsIcon, Search as SearchIcon, EditNote as EditNoteIcon, Add as AddIcon } from "@mui/icons-material";
|
||||||
|
import { PodcastAnalysis } from "../../types";
|
||||||
|
import { AnalysisTabContent } from "../AnalysisTabNav";
|
||||||
|
|
||||||
|
interface AudienceTabProps {
|
||||||
|
analysis: PodcastAnalysis;
|
||||||
|
isEditing?: boolean;
|
||||||
|
editedAnalysis?: PodcastAnalysis | null;
|
||||||
|
setEditedAnalysis?: (analysis: PodcastAnalysis) => void;
|
||||||
|
handleRemoveKeyword?: (keyword: string) => void;
|
||||||
|
handleAddKeyword?: (keyword: string) => void;
|
||||||
|
handleRemoveTitle?: (title: string) => void;
|
||||||
|
handleAddTitle?: (title: string) => void;
|
||||||
|
handleUpdateOutline?: (id: string | number, field: 'title' | 'segments', value: any) => void;
|
||||||
|
updateExaConfig?: (field: string, value: any) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
const inputStyles = {
|
||||||
|
'& .MuiInputBase-input': { color: '#111827 !important', fontWeight: 500 },
|
||||||
|
'& .MuiInputLabel-root': { color: '#4b5563 !important' },
|
||||||
|
'& .MuiOutlinedInput-root': {
|
||||||
|
bgcolor: '#ffffff !important',
|
||||||
|
'& fieldset': { borderColor: '#d1d5db !important' },
|
||||||
|
'&:hover fieldset': { borderColor: '#4f46e5 !important' },
|
||||||
|
'&.Mui-focused fieldset': { borderColor: '#4f46e5 !important' },
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
export const AudienceTab: React.FC<AudienceTabProps> = ({
|
||||||
|
analysis,
|
||||||
|
isEditing,
|
||||||
|
editedAnalysis,
|
||||||
|
setEditedAnalysis,
|
||||||
|
handleRemoveKeyword,
|
||||||
|
handleAddKeyword,
|
||||||
|
handleRemoveTitle,
|
||||||
|
handleAddTitle,
|
||||||
|
handleUpdateOutline,
|
||||||
|
updateExaConfig
|
||||||
|
}) => {
|
||||||
|
const currentAnalysis = editedAnalysis || analysis;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<AnalysisTabContent title="Target Audience" icon={<GroupsIcon />}>
|
||||||
|
<Stack spacing={3}>
|
||||||
|
<Box>
|
||||||
|
<Typography variant="caption" sx={{ color: "#64748b", fontWeight: 600, display: "block", mb: 0.5 }}>
|
||||||
|
Audience Description
|
||||||
|
</Typography>
|
||||||
|
{isEditing ? (
|
||||||
|
<TextField
|
||||||
|
fullWidth
|
||||||
|
multiline
|
||||||
|
rows={2}
|
||||||
|
size="small"
|
||||||
|
value={currentAnalysis.audience}
|
||||||
|
onChange={(e) => setEditedAnalysis?.({ ...currentAnalysis, audience: e.target.value })}
|
||||||
|
placeholder="Describe your target audience..."
|
||||||
|
sx={inputStyles}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<Typography variant="body2" sx={{ color: "#0f172a" }}>
|
||||||
|
{currentAnalysis.audience}
|
||||||
|
</Typography>
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
<Box>
|
||||||
|
<Typography variant="caption" sx={{ color: "#64748b", fontWeight: 600, display: "block", mb: 1 }}>
|
||||||
|
Content Type
|
||||||
|
</Typography>
|
||||||
|
{isEditing ? (
|
||||||
|
<TextField
|
||||||
|
fullWidth
|
||||||
|
size="small"
|
||||||
|
value={currentAnalysis.contentType}
|
||||||
|
onChange={(e) => setEditedAnalysis?.({ ...currentAnalysis, contentType: e.target.value })}
|
||||||
|
placeholder="e.g. Interview, Narrative, Solo..."
|
||||||
|
sx={inputStyles}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<Chip label={currentAnalysis.contentType} size="small" sx={{ background: "#eef2ff", color: "#4f46e5", border: "1px solid rgba(79,70,229,0.2)" }} />
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
<Box>
|
||||||
|
<Typography variant="caption" sx={{ color: "#64748b", fontWeight: 600, display: "block", mb: 1 }}>
|
||||||
|
Top Keywords
|
||||||
|
</Typography>
|
||||||
|
<Stack direction="row" flexWrap="wrap" useFlexGap sx={{ mb: isEditing ? 1.5 : 0 }}>
|
||||||
|
{currentAnalysis.topKeywords.map((k: string) => (
|
||||||
|
<Chip
|
||||||
|
key={k}
|
||||||
|
label={k}
|
||||||
|
size="small"
|
||||||
|
variant="outlined"
|
||||||
|
onDelete={isEditing ? () => handleRemoveKeyword?.(k) : undefined}
|
||||||
|
sx={{
|
||||||
|
borderColor: "rgba(0,0,0,0.1)",
|
||||||
|
color: "#0f172a",
|
||||||
|
background: "#f8fafc",
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</Stack>
|
||||||
|
{isEditing && (
|
||||||
|
<TextField
|
||||||
|
fullWidth
|
||||||
|
size="small"
|
||||||
|
placeholder="Add keyword and press Enter..."
|
||||||
|
sx={inputStyles}
|
||||||
|
onKeyDown={(e) => {
|
||||||
|
if (e.key === 'Enter') {
|
||||||
|
e.preventDefault();
|
||||||
|
handleAddKeyword?.((e.target as HTMLInputElement).value);
|
||||||
|
(e.target as HTMLInputElement).value = '';
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
InputProps={{
|
||||||
|
endAdornment: (
|
||||||
|
<IconButton size="small" onClick={(e) => {
|
||||||
|
const input = (e.currentTarget.parentElement?.parentElement?.querySelector('input') as HTMLInputElement);
|
||||||
|
handleAddKeyword?.(input.value);
|
||||||
|
input.value = '';
|
||||||
|
}}>
|
||||||
|
<AddIcon fontSize="small" sx={{ color: '#4f46e5' }} />
|
||||||
|
</IconButton>
|
||||||
|
)
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
{currentAnalysis.exaSuggestedConfig && (
|
||||||
|
<Box>
|
||||||
|
<Divider sx={{ mb: 2 }} />
|
||||||
|
<Typography variant="subtitle2" sx={{ mb: 1, color: "#0f172a", display: "flex", alignItems: "center", gap: 0.5 }}>
|
||||||
|
<SearchIcon fontSize="small" sx={{ color: "#4f46e5" }} />
|
||||||
|
Exa Research Config
|
||||||
|
</Typography>
|
||||||
|
<Stack direction="row" flexWrap="wrap" useFlexGap>
|
||||||
|
{currentAnalysis.exaSuggestedConfig.exa_search_type && (
|
||||||
|
<Chip label={`Search: ${currentAnalysis.exaSuggestedConfig.exa_search_type}`} size="small" sx={{ background: "#eef2ff", color: "#0f172a" }} />
|
||||||
|
)}
|
||||||
|
{currentAnalysis.exaSuggestedConfig.exa_category && (
|
||||||
|
<Chip label={`Category: ${currentAnalysis.exaSuggestedConfig.exa_category}`} size="small" sx={{ background: "#eef2ff", color: "#0f172a" }} />
|
||||||
|
)}
|
||||||
|
{currentAnalysis.exaSuggestedConfig.date_range && (
|
||||||
|
<Chip label={`Date: ${currentAnalysis.exaSuggestedConfig.date_range}`} size="small" sx={{ background: "#eef2ff", color: "#0f172a" }} />
|
||||||
|
)}
|
||||||
|
{currentAnalysis.exaSuggestedConfig.max_sources && (
|
||||||
|
<Chip label={`Max: ${currentAnalysis.exaSuggestedConfig.max_sources}`} size="small" sx={{ background: "#eef2ff", color: "#0f172a" }} />
|
||||||
|
)}
|
||||||
|
</Stack>
|
||||||
|
</Box>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<Box>
|
||||||
|
<Typography variant="caption" sx={{ color: "#64748b", fontWeight: 600, display: "block", mb: 1 }}>
|
||||||
|
Title Suggestions
|
||||||
|
</Typography>
|
||||||
|
<Stack direction="row" flexWrap="wrap" useFlexGap sx={{ mb: isEditing ? 1.5 : 0 }}>
|
||||||
|
{currentAnalysis.titleSuggestions.map((t: string) => (
|
||||||
|
<Chip
|
||||||
|
key={t}
|
||||||
|
label={t}
|
||||||
|
size="small"
|
||||||
|
onDelete={isEditing ? () => handleRemoveTitle?.(t) : undefined}
|
||||||
|
sx={{
|
||||||
|
color: "#0f172a",
|
||||||
|
background: "#f8fafc",
|
||||||
|
maxWidth: "100%",
|
||||||
|
whiteSpace: "normal",
|
||||||
|
height: "auto",
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</Stack>
|
||||||
|
{isEditing && (
|
||||||
|
<TextField
|
||||||
|
fullWidth
|
||||||
|
size="small"
|
||||||
|
placeholder="Add title suggestion..."
|
||||||
|
sx={inputStyles}
|
||||||
|
onKeyDown={(e) => {
|
||||||
|
if (e.key === 'Enter') {
|
||||||
|
e.preventDefault();
|
||||||
|
handleAddTitle?.((e.target as HTMLInputElement).value);
|
||||||
|
(e.target as HTMLInputElement).value = '';
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
InputProps={{
|
||||||
|
endAdornment: (
|
||||||
|
<IconButton size="small" onClick={(e) => {
|
||||||
|
const input = (e.currentTarget.parentElement?.parentElement?.querySelector('input') as HTMLInputElement);
|
||||||
|
handleAddTitle?.(input.value);
|
||||||
|
input.value = '';
|
||||||
|
}}>
|
||||||
|
<AddIcon fontSize="small" sx={{ color: '#4f46e5' }} />
|
||||||
|
</IconButton>
|
||||||
|
)
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
</Stack>
|
||||||
|
</AnalysisTabContent>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
import React from "react";
|
||||||
|
import { Box, Typography, Paper } from "@mui/material";
|
||||||
|
import { Psychology as PsychologyIcon } from "@mui/icons-material";
|
||||||
|
import { PodcastAnalysis } from "../../types";
|
||||||
|
import { AnalysisTabContent } from "../AnalysisTabNav";
|
||||||
|
|
||||||
|
interface CTATabProps {
|
||||||
|
analysis: PodcastAnalysis;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const CTATab: React.FC<CTATabProps> = ({ analysis }) => {
|
||||||
|
if (!analysis.listener_cta) {
|
||||||
|
return (
|
||||||
|
<AnalysisTabContent title="Listener CTA" icon={<PsychologyIcon />}>
|
||||||
|
<Typography variant="body2" sx={{ color: "#64748b" }}>
|
||||||
|
No listener call-to-action generated yet.
|
||||||
|
</Typography>
|
||||||
|
</AnalysisTabContent>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<AnalysisTabContent title="Listener CTA" icon={<PsychologyIcon />}>
|
||||||
|
<Paper elevation={0} sx={{ p: 3, bgcolor: "#fff7ed", border: "1px solid rgba(249,115,22,0.2)", borderRadius: 2 }}>
|
||||||
|
<Typography variant="body1" sx={{ color: "#c2410c", fontWeight: 500, lineHeight: 1.6 }}>
|
||||||
|
{analysis.listener_cta}
|
||||||
|
</Typography>
|
||||||
|
</Paper>
|
||||||
|
<Typography variant="caption" sx={{ color: "#64748b", mt: 1, display: "block" }}>
|
||||||
|
This is a call-to-action for listeners to take action after the episode.
|
||||||
|
</Typography>
|
||||||
|
</AnalysisTabContent>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
import React from "react";
|
||||||
|
import { Stack, Box, Typography, Chip, Paper } from "@mui/material";
|
||||||
|
import { Quiz as TalkIcon } from "@mui/icons-material";
|
||||||
|
import { PodcastAnalysis } from "../../types";
|
||||||
|
import { AnalysisTabContent } from "../AnalysisTabNav";
|
||||||
|
|
||||||
|
interface GuestTabProps {
|
||||||
|
analysis: PodcastAnalysis;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const GuestTab: React.FC<GuestTabProps> = ({ analysis }) => {
|
||||||
|
if (!analysis.guest_talking_points || analysis.guest_talking_points.length === 0) {
|
||||||
|
return (
|
||||||
|
<AnalysisTabContent title="Guest Talking Points" icon={<TalkIcon />}>
|
||||||
|
<Typography variant="body2" sx={{ color: "#64748b" }}>
|
||||||
|
No guest talking points generated yet. Add a guest speaker to get interview questions.
|
||||||
|
</Typography>
|
||||||
|
</AnalysisTabContent>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<AnalysisTabContent title="Guest Talking Points" icon={<TalkIcon />}>
|
||||||
|
<Stack spacing={2}>
|
||||||
|
{analysis.guest_talking_points.map((point: string, idx: number) => (
|
||||||
|
<Paper key={idx} elevation={0} sx={{ p: 2, bgcolor: "#faf5ff", border: "1px solid rgba(168,85,247,0.2)", borderRadius: 2, display: "flex", alignItems: "flex-start", gap: 1.5 }}>
|
||||||
|
<Chip label="Q" size="small" sx={{ minWidth: 24, bgcolor: "#a855f7", color: "#fff" }} />
|
||||||
|
<Typography variant="body2" sx={{ color: "#6b21a8" }}>
|
||||||
|
{point}
|
||||||
|
</Typography>
|
||||||
|
</Paper>
|
||||||
|
))}
|
||||||
|
</Stack>
|
||||||
|
</AnalysisTabContent>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
import React from "react";
|
||||||
|
import { Box, Typography, Paper } from "@mui/material";
|
||||||
|
import { AutoAwesome as AutoAwesomeIcon } from "@mui/icons-material";
|
||||||
|
import { PodcastAnalysis } from "../../types";
|
||||||
|
import { AnalysisTabContent } from "../AnalysisTabNav";
|
||||||
|
|
||||||
|
interface HookTabProps {
|
||||||
|
analysis: PodcastAnalysis;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const HookTab: React.FC<HookTabProps> = ({ analysis }) => {
|
||||||
|
if (!analysis.episode_hook) {
|
||||||
|
return (
|
||||||
|
<AnalysisTabContent title="Episode Hook" icon={<AutoAwesomeIcon />}>
|
||||||
|
<Typography variant="body2" sx={{ color: "#64748b" }}>
|
||||||
|
No episode hook generated yet.
|
||||||
|
</Typography>
|
||||||
|
</AnalysisTabContent>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<AnalysisTabContent title="Episode Hook" icon={<AutoAwesomeIcon />}>
|
||||||
|
<Paper elevation={0} sx={{ p: 3, bgcolor: "#f0f9ff", border: "1px solid rgba(59,130,246,0.2)", borderRadius: 2 }}>
|
||||||
|
<Typography variant="body1" sx={{ color: "#0369a1", fontStyle: "italic", fontSize: "1.1rem", lineHeight: 1.6 }}>
|
||||||
|
"{analysis.episode_hook}"
|
||||||
|
</Typography>
|
||||||
|
</Paper>
|
||||||
|
<Typography variant="caption" sx={{ color: "#64748b", mt: 1, display: "block" }}>
|
||||||
|
This is a 15-30 second opening hook to grab listener attention.
|
||||||
|
</Typography>
|
||||||
|
</AnalysisTabContent>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -0,0 +1,191 @@
|
|||||||
|
import React from "react";
|
||||||
|
import { Box, Stack, Typography, Chip, Paper, CircularProgress, alpha } from "@mui/material";
|
||||||
|
import { Input as InputIcon, Person as PersonIcon, AutoAwesome as AutoAwesomeIcon } from "@mui/icons-material";
|
||||||
|
import { AnalysisTabContent } from "../AnalysisTabNav";
|
||||||
|
|
||||||
|
interface InputsTabProps {
|
||||||
|
idea?: string;
|
||||||
|
duration?: number;
|
||||||
|
speakers?: number;
|
||||||
|
avatarUrl?: string | null;
|
||||||
|
avatarPrompt?: string | null;
|
||||||
|
avatarBlobUrl?: string | null;
|
||||||
|
avatarLoading?: boolean;
|
||||||
|
avatarError?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const InputsTab: React.FC<InputsTabProps> = ({ idea, duration, speakers, avatarUrl, avatarPrompt, avatarBlobUrl, avatarLoading, avatarError }) => {
|
||||||
|
if (!idea && !duration && !speakers && !avatarUrl && !avatarPrompt) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<AnalysisTabContent title="Your Inputs" icon={<InputIcon />}>
|
||||||
|
<Box
|
||||||
|
sx={{
|
||||||
|
display: "grid",
|
||||||
|
gridTemplateColumns: { xs: "1fr", md: avatarUrl ? "1fr 1fr" : "1fr" },
|
||||||
|
gap: 3,
|
||||||
|
alignItems: "flex-start",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Stack spacing={1.5}>
|
||||||
|
{idea && (
|
||||||
|
<Box>
|
||||||
|
<Typography variant="caption" sx={{ color: "#64748b", fontWeight: 600, display: "block", mb: 0.5 }}>
|
||||||
|
Podcast Idea
|
||||||
|
</Typography>
|
||||||
|
<Typography variant="body2" sx={{ color: "#0f172a", wordBreak: "break-word" }}>
|
||||||
|
{idea}
|
||||||
|
</Typography>
|
||||||
|
</Box>
|
||||||
|
)}
|
||||||
|
<Stack direction="row" spacing={2} flexWrap="wrap">
|
||||||
|
{duration !== undefined && (
|
||||||
|
<Box>
|
||||||
|
<Typography variant="caption" sx={{ color: "#64748b", fontWeight: 600, display: "block", mb: 0.5 }}>
|
||||||
|
Duration
|
||||||
|
</Typography>
|
||||||
|
<Chip
|
||||||
|
label={`${duration} minutes`}
|
||||||
|
size="small"
|
||||||
|
sx={{ background: "#f1f5f9", color: "#0f172a", border: "1px solid rgba(0,0,0,0.08)" }}
|
||||||
|
/>
|
||||||
|
</Box>
|
||||||
|
)}
|
||||||
|
{speakers !== undefined && (
|
||||||
|
<Box>
|
||||||
|
<Typography variant="caption" sx={{ color: "#64748b", fontWeight: 600, display: "block", mb: 0.5 }}>
|
||||||
|
Speakers
|
||||||
|
</Typography>
|
||||||
|
<Chip
|
||||||
|
label={`${speakers} ${speakers === 1 ? "speaker" : "speakers"}`}
|
||||||
|
size="small"
|
||||||
|
sx={{ background: "#f1f5f9", color: "#0f172a", border: "1px solid rgba(0,0,0,0.08)" }}
|
||||||
|
/>
|
||||||
|
</Box>
|
||||||
|
)}
|
||||||
|
</Stack>
|
||||||
|
|
||||||
|
{avatarPrompt && (
|
||||||
|
<Box>
|
||||||
|
<Typography
|
||||||
|
variant="caption"
|
||||||
|
sx={{
|
||||||
|
color: "#64748b",
|
||||||
|
fontWeight: 600,
|
||||||
|
display: "flex",
|
||||||
|
alignItems: "center",
|
||||||
|
gap: 0.5,
|
||||||
|
mb: 0.75,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<AutoAwesomeIcon sx={{ fontSize: 14 }} />
|
||||||
|
AI Generation Prompt
|
||||||
|
</Typography>
|
||||||
|
<Paper
|
||||||
|
sx={{
|
||||||
|
p: 1.5,
|
||||||
|
background: "#f8fafc",
|
||||||
|
border: "1px solid rgba(0,0,0,0.08)",
|
||||||
|
borderRadius: 1.5,
|
||||||
|
maxHeight: 200,
|
||||||
|
overflow: "auto",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Typography
|
||||||
|
variant="caption"
|
||||||
|
sx={{
|
||||||
|
color: "#475569",
|
||||||
|
fontFamily: "monospace",
|
||||||
|
fontSize: "0.75rem",
|
||||||
|
lineHeight: 1.6,
|
||||||
|
whiteSpace: "pre-wrap",
|
||||||
|
wordBreak: "break-word",
|
||||||
|
display: "block",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{avatarPrompt}
|
||||||
|
</Typography>
|
||||||
|
</Paper>
|
||||||
|
</Box>
|
||||||
|
)}
|
||||||
|
</Stack>
|
||||||
|
|
||||||
|
{avatarUrl && (
|
||||||
|
<Box>
|
||||||
|
<Typography
|
||||||
|
variant="caption"
|
||||||
|
sx={{
|
||||||
|
color: "#64748b",
|
||||||
|
fontWeight: 600,
|
||||||
|
display: "flex",
|
||||||
|
alignItems: "center",
|
||||||
|
gap: 0.5,
|
||||||
|
mb: 1,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<PersonIcon sx={{ fontSize: 16 }} />
|
||||||
|
Presenter Avatar
|
||||||
|
</Typography>
|
||||||
|
<Box
|
||||||
|
sx={{
|
||||||
|
width: "100%",
|
||||||
|
maxWidth: { xs: "100%", md: 300 },
|
||||||
|
borderRadius: 2,
|
||||||
|
overflow: "hidden",
|
||||||
|
border: "1px solid rgba(102,126,234,0.2)",
|
||||||
|
background: alpha("#667eea", 0.05),
|
||||||
|
position: "relative",
|
||||||
|
aspectRatio: "1",
|
||||||
|
boxShadow: "0 4px 12px rgba(0,0,0,0.08)",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{avatarLoading ? (
|
||||||
|
<Box
|
||||||
|
sx={{
|
||||||
|
display: "flex",
|
||||||
|
alignItems: "center",
|
||||||
|
justifyContent: "center",
|
||||||
|
height: "100%",
|
||||||
|
background: "#f8fafc",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<CircularProgress size={40} />
|
||||||
|
</Box>
|
||||||
|
) : avatarError ? (
|
||||||
|
<Box
|
||||||
|
sx={{
|
||||||
|
display: "flex",
|
||||||
|
alignItems: "center",
|
||||||
|
justifyContent: "center",
|
||||||
|
height: "100%",
|
||||||
|
background: "#fef2f2",
|
||||||
|
color: "#dc2626",
|
||||||
|
p: 2,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Typography variant="caption" sx={{ textAlign: "center" }}>
|
||||||
|
Failed to load avatar
|
||||||
|
</Typography>
|
||||||
|
</Box>
|
||||||
|
) : avatarBlobUrl ? (
|
||||||
|
<Box
|
||||||
|
component="img"
|
||||||
|
src={avatarBlobUrl}
|
||||||
|
alt="Podcast Presenter"
|
||||||
|
sx={{
|
||||||
|
width: "100%",
|
||||||
|
height: "100%",
|
||||||
|
objectFit: "cover",
|
||||||
|
display: "block",
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
) : null}
|
||||||
|
</Box>
|
||||||
|
</Box>
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
</AnalysisTabContent>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
import React from "react";
|
||||||
|
import { Stack, Box, Typography, Chip, TextField, IconButton } from "@mui/material";
|
||||||
|
import { ListAlt as ListAltIcon, Add as AddIcon } from "@mui/icons-material";
|
||||||
|
import { PodcastAnalysis } from "../../types";
|
||||||
|
import { AnalysisTabContent } from "../AnalysisTabNav";
|
||||||
|
|
||||||
|
interface OutlineTabProps {
|
||||||
|
analysis: PodcastAnalysis;
|
||||||
|
isEditing?: boolean;
|
||||||
|
onUpdateOutline?: (id: string | number, field: 'title' | 'segments', value: any) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const OutlineTab: React.FC<OutlineTabProps> = ({ analysis, isEditing, onUpdateOutline }) => {
|
||||||
|
return (
|
||||||
|
<AnalysisTabContent title="Episode Outline" icon={<ListAltIcon />}>
|
||||||
|
<Stack spacing={3}>
|
||||||
|
{analysis.suggestedOutlines?.map((outline: { id?: string | number; title: string; segments: string[] }, idx: number) => (
|
||||||
|
<Box key={outline.id || idx} sx={{ p: 2, bgcolor: "#f8fafc", borderRadius: 2, border: "1px solid rgba(0,0,0,0.08)" }}>
|
||||||
|
<Stack direction="row" justifyContent="space-between" alignItems="center" sx={{ mb: 1.5 }}>
|
||||||
|
<Typography variant="subtitle2" sx={{ color: "#0f172a", fontWeight: 700 }}>
|
||||||
|
Option {idx + 1}: {outline.title}
|
||||||
|
</Typography>
|
||||||
|
</Stack>
|
||||||
|
<Stack spacing={1}>
|
||||||
|
{outline.segments?.map((segment: string, sIdx: number) => (
|
||||||
|
<Box key={sIdx} sx={{ display: "flex", alignItems: "flex-start", gap: 1 }}>
|
||||||
|
<Chip label={sIdx + 1} size="small" sx={{ minWidth: 24, bgcolor: "#4f46e5", color: "#fff" }} />
|
||||||
|
<Typography variant="body2" sx={{ color: "#475569" }}>
|
||||||
|
{segment}
|
||||||
|
</Typography>
|
||||||
|
</Box>
|
||||||
|
))}
|
||||||
|
</Stack>
|
||||||
|
</Box>
|
||||||
|
))}
|
||||||
|
</Stack>
|
||||||
|
</AnalysisTabContent>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
import React from "react";
|
||||||
|
import { Stack, Box, Typography, Chip, Paper } from "@mui/material";
|
||||||
|
import { Search as SearchIcon } from "@mui/icons-material";
|
||||||
|
import { PodcastAnalysis } from "../../types";
|
||||||
|
import { AnalysisTabContent } from "../AnalysisTabNav";
|
||||||
|
|
||||||
|
interface ResearchTabProps {
|
||||||
|
analysis: PodcastAnalysis;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const ResearchTab: React.FC<ResearchTabProps> = ({ analysis }) => {
|
||||||
|
if (!analysis.research_queries || analysis.research_queries.length === 0) {
|
||||||
|
return (
|
||||||
|
<AnalysisTabContent title="Research Queries" icon={<SearchIcon />}>
|
||||||
|
<Typography variant="body2" sx={{ color: "#64748b" }}>
|
||||||
|
No research queries generated yet.
|
||||||
|
</Typography>
|
||||||
|
</AnalysisTabContent>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<AnalysisTabContent title="Research Queries" icon={<SearchIcon />}>
|
||||||
|
<Stack spacing={2}>
|
||||||
|
{analysis.research_queries.map((rq: { query: string; rationale: string }, idx: number) => (
|
||||||
|
<Paper key={idx} elevation={0} sx={{ p: 2, bgcolor: "#f8fafc", border: "1px solid rgba(0,0,0,0.08)", borderRadius: 2 }}>
|
||||||
|
<Stack direction="row" alignItems="flex-start" gap={1.5}>
|
||||||
|
<Chip label={idx + 1} size="small" sx={{ minWidth: 24, bgcolor: "#4f46e5", color: "#fff" }} />
|
||||||
|
<Box>
|
||||||
|
<Typography variant="body2" sx={{ color: "#0f172a", fontWeight: 600, mb: 0.5 }}>
|
||||||
|
{rq.query}
|
||||||
|
</Typography>
|
||||||
|
<Typography variant="caption" sx={{ color: "#64748b" }}>
|
||||||
|
Rationale: {rq.rationale}
|
||||||
|
</Typography>
|
||||||
|
</Box>
|
||||||
|
</Stack>
|
||||||
|
</Paper>
|
||||||
|
))}
|
||||||
|
</Stack>
|
||||||
|
</AnalysisTabContent>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
import React from "react";
|
||||||
|
import { Stack, Box, Typography, Chip, Paper } from "@mui/material";
|
||||||
|
import { Lightbulb as TipsIcon } from "@mui/icons-material";
|
||||||
|
import { PodcastAnalysis } from "../../types";
|
||||||
|
import { AnalysisTabContent } from "../AnalysisTabNav";
|
||||||
|
|
||||||
|
interface TakeawaysTabProps {
|
||||||
|
analysis: PodcastAnalysis;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const TakeawaysTab: React.FC<TakeawaysTabProps> = ({ analysis }) => {
|
||||||
|
if (!analysis.key_takeaways || analysis.key_takeaways.length === 0) {
|
||||||
|
return (
|
||||||
|
<AnalysisTabContent title="Key Takeaways" icon={<TipsIcon />}>
|
||||||
|
<Typography variant="body2" sx={{ color: "#64748b" }}>
|
||||||
|
No key takeaways generated yet.
|
||||||
|
</Typography>
|
||||||
|
</AnalysisTabContent>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<AnalysisTabContent title="Key Takeaways" icon={<TipsIcon />}>
|
||||||
|
<Stack spacing={2}>
|
||||||
|
{analysis.key_takeaways.map((takeaway: string, idx: number) => (
|
||||||
|
<Paper key={idx} elevation={0} sx={{ p: 2, bgcolor: "#f0fdf4", border: "1px solid rgba(34,197,94,0.2)", borderRadius: 2, display: "flex", alignItems: "flex-start", gap: 1.5 }}>
|
||||||
|
<Chip label={idx + 1} size="small" sx={{ minWidth: 24, bgcolor: "#22c55e", color: "#fff" }} />
|
||||||
|
<Typography variant="body2" sx={{ color: "#166534" }}>
|
||||||
|
{takeaway}
|
||||||
|
</Typography>
|
||||||
|
</Paper>
|
||||||
|
))}
|
||||||
|
</Stack>
|
||||||
|
</AnalysisTabContent>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
import React from "react";
|
||||||
|
import { Stack, Box, Typography, Chip, TextField, IconButton } from "@mui/material";
|
||||||
|
import { EditNote as EditNoteIcon, Add as AddIcon } from "@mui/icons-material";
|
||||||
|
import { PodcastAnalysis } from "../../types";
|
||||||
|
import { AnalysisTabContent } from "../AnalysisTabNav";
|
||||||
|
|
||||||
|
interface TitlesTabProps {
|
||||||
|
analysis: PodcastAnalysis;
|
||||||
|
isEditing?: boolean;
|
||||||
|
handleRemoveTitle?: (title: string) => void;
|
||||||
|
handleAddTitle?: (title: string) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
const inputStyles = {
|
||||||
|
'& .MuiInputBase-input': { color: '#111827 !important', fontWeight: 500 },
|
||||||
|
'& .MuiInputLabel-root': { color: '#4b5563 !important' },
|
||||||
|
'& .MuiOutlinedInput-root': {
|
||||||
|
bgcolor: '#ffffff !important',
|
||||||
|
'& fieldset': { borderColor: '#d1d5db !important' },
|
||||||
|
'&:hover fieldset': { borderColor: '#4f46e5 !important' },
|
||||||
|
'&.Mui-focused fieldset': { borderColor: '#4f46e5 !important' },
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
export const TitlesTab: React.FC<TitlesTabProps> = ({ analysis, isEditing, handleRemoveTitle, handleAddTitle }) => {
|
||||||
|
return (
|
||||||
|
<AnalysisTabContent title="Episode Titles" icon={<EditNoteIcon />}>
|
||||||
|
<Stack spacing={2}>
|
||||||
|
<Stack direction="row" flexWrap="wrap" useFlexGap sx={{ mb: isEditing ? 1.5 : 0 }}>
|
||||||
|
{analysis.titleSuggestions?.map((title: string, idx: number) => (
|
||||||
|
<Chip
|
||||||
|
key={idx}
|
||||||
|
label={title}
|
||||||
|
size="small"
|
||||||
|
onDelete={isEditing ? () => handleRemoveTitle?.(title) : undefined}
|
||||||
|
sx={{
|
||||||
|
color: "#0f172a",
|
||||||
|
background: "#f8fafc",
|
||||||
|
maxWidth: "100%",
|
||||||
|
whiteSpace: "normal",
|
||||||
|
height: "auto",
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</Stack>
|
||||||
|
{isEditing && (
|
||||||
|
<TextField
|
||||||
|
fullWidth
|
||||||
|
size="small"
|
||||||
|
placeholder="Add title suggestion..."
|
||||||
|
sx={inputStyles}
|
||||||
|
onKeyDown={(e) => {
|
||||||
|
if (e.key === 'Enter') {
|
||||||
|
e.preventDefault();
|
||||||
|
handleAddTitle?.((e.target as HTMLInputElement).value);
|
||||||
|
(e.target as HTMLInputElement).value = '';
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
InputProps={{
|
||||||
|
endAdornment: (
|
||||||
|
<IconButton size="small" onClick={(e) => {
|
||||||
|
const input = (e.currentTarget.parentElement?.parentElement?.querySelector('input') as HTMLInputElement);
|
||||||
|
handleAddTitle?.(input.value);
|
||||||
|
input.value = '';
|
||||||
|
}}>
|
||||||
|
<AddIcon fontSize="small" sx={{ color: '#4f46e5' }} />
|
||||||
|
</IconButton>
|
||||||
|
)
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</Stack>
|
||||||
|
</AnalysisTabContent>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
export { HookTab } from "./HookTab";
|
||||||
|
export { CTATab } from "./CTATab";
|
||||||
|
export { GuestTab } from "./GuestTab";
|
||||||
|
export { TakeawaysTab } from "./TakeawaysTab";
|
||||||
|
export { ResearchTab } from "./ResearchTab";
|
||||||
|
export { TitlesTab } from "./TitlesTab";
|
||||||
|
export { OutlineTab } from "./OutlineTab";
|
||||||
|
export { AudienceTab } from "./AudienceTab";
|
||||||
|
export { InputsTab } from "./InputsTab";
|
||||||
@@ -5,6 +5,7 @@ import { useSubscription } from "../../contexts/SubscriptionContext";
|
|||||||
import { podcastApi } from "../../services/podcastApi";
|
import { podcastApi } from "../../services/podcastApi";
|
||||||
import { fetchMediaBlobUrl, clearMediaCache } from "../../utils/fetchMediaBlobUrl";
|
import { fetchMediaBlobUrl, clearMediaCache } from "../../utils/fetchMediaBlobUrl";
|
||||||
import { getLatestBrandAvatar } from "../../api/brandAssets";
|
import { getLatestBrandAvatar } from "../../api/brandAssets";
|
||||||
|
import { VoiceSelector } from "../shared/VoiceSelector";
|
||||||
|
|
||||||
// Imported Components
|
// Imported Components
|
||||||
import { CreateHeader } from "./CreateStep/CreateHeader";
|
import { CreateHeader } from "./CreateStep/CreateHeader";
|
||||||
@@ -43,6 +44,7 @@ export const CreateModal: React.FC<CreateModalProps> = ({ onCreate, open, defaul
|
|||||||
const [enhancingTopic, setEnhancingTopic] = useState(false);
|
const [enhancingTopic, setEnhancingTopic] = useState(false);
|
||||||
const [enhanceTopicProgressIndex, setEnhanceTopicProgressIndex] = useState(0);
|
const [enhanceTopicProgressIndex, setEnhanceTopicProgressIndex] = useState(0);
|
||||||
const [knobs, setKnobs] = useState<Knobs>({ ...defaultKnobs });
|
const [knobs, setKnobs] = useState<Knobs>({ ...defaultKnobs });
|
||||||
|
const [selectedVoiceId, setSelectedVoiceId] = useState<string>("Wise_Woman");
|
||||||
const [placeholderIndex, setPlaceholderIndex] = useState(0);
|
const [placeholderIndex, setPlaceholderIndex] = useState(0);
|
||||||
const [avatarTab, setAvatarTab] = useState(0);
|
const [avatarTab, setAvatarTab] = useState(0);
|
||||||
const [loadingBrandAvatar, setLoadingBrandAvatar] = useState(false);
|
const [loadingBrandAvatar, setLoadingBrandAvatar] = useState(false);
|
||||||
@@ -318,11 +320,17 @@ export const CreateModal: React.FC<CreateModalProps> = ({ onCreate, open, defaul
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Include selected voice in knobs
|
||||||
|
const finalKnobs = {
|
||||||
|
...knobs,
|
||||||
|
voice_id: selectedVoiceId,
|
||||||
|
};
|
||||||
|
|
||||||
onCreate({
|
onCreate({
|
||||||
ideaOrUrl: finalUrl || finalIdea,
|
ideaOrUrl: finalUrl || finalIdea,
|
||||||
speakers,
|
speakers,
|
||||||
duration,
|
duration,
|
||||||
knobs,
|
knobs: finalKnobs,
|
||||||
budgetCap,
|
budgetCap,
|
||||||
files: { voiceFile, avatarFile },
|
files: { voiceFile, avatarFile },
|
||||||
avatarUrl: finalAvatarUrl,
|
avatarUrl: finalAvatarUrl,
|
||||||
@@ -342,6 +350,7 @@ export const CreateModal: React.FC<CreateModalProps> = ({ onCreate, open, defaul
|
|||||||
setEnhancingTopic(false);
|
setEnhancingTopic(false);
|
||||||
setEnhanceTopicProgressIndex(0);
|
setEnhanceTopicProgressIndex(0);
|
||||||
setKnobs({ ...defaultKnobs });
|
setKnobs({ ...defaultKnobs });
|
||||||
|
setSelectedVoiceId("Wise_Woman");
|
||||||
setPlaceholderIndex(0);
|
setPlaceholderIndex(0);
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -565,6 +574,12 @@ export const CreateModal: React.FC<CreateModalProps> = ({ onCreate, open, defaul
|
|||||||
setCameraSelfieOpen={setCameraSelfieOpen}
|
setCameraSelfieOpen={setCameraSelfieOpen}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
<VoiceSelector
|
||||||
|
value={selectedVoiceId}
|
||||||
|
onChange={setSelectedVoiceId}
|
||||||
|
showVoiceClone={true}
|
||||||
|
/>
|
||||||
|
|
||||||
<CreateActions
|
<CreateActions
|
||||||
reset={reset}
|
reset={reset}
|
||||||
submit={submit}
|
submit={submit}
|
||||||
|
|||||||
@@ -1,11 +1,32 @@
|
|||||||
import React, { useState, useEffect } from "react";
|
import React, { useState, useEffect } from "react";
|
||||||
import { Stack, Alert, Typography, alpha, IconButton, Collapse } from "@mui/material";
|
import {
|
||||||
|
Stack,
|
||||||
|
Alert,
|
||||||
|
Typography,
|
||||||
|
alpha,
|
||||||
|
Collapse,
|
||||||
|
Dialog,
|
||||||
|
DialogTitle,
|
||||||
|
DialogContent,
|
||||||
|
DialogActions,
|
||||||
|
List,
|
||||||
|
ListItem,
|
||||||
|
ListItemIcon,
|
||||||
|
ListItemText,
|
||||||
|
CircularProgress,
|
||||||
|
Box,
|
||||||
|
LinearProgress,
|
||||||
|
} from "@mui/material";
|
||||||
import {
|
import {
|
||||||
Info as InfoIcon,
|
Info as InfoIcon,
|
||||||
Refresh as RefreshIcon,
|
Refresh as RefreshIcon,
|
||||||
AutoAwesome as AutoAwesomeIcon,
|
AutoAwesome as AutoAwesomeIcon,
|
||||||
ExpandMore as ExpandMoreIcon,
|
CheckCircle as CheckCircleIcon,
|
||||||
ExpandLess as ExpandLessIcon,
|
Analytics as AnalyticsIcon,
|
||||||
|
Title as TitleIcon,
|
||||||
|
ListAlt as ListAltIcon,
|
||||||
|
Psychology as PsychologyIcon,
|
||||||
|
RecordVoiceOver as RecordVoiceOverIcon,
|
||||||
} from "@mui/icons-material";
|
} from "@mui/icons-material";
|
||||||
import { PrimaryButton, SecondaryButton } from "../ui";
|
import { PrimaryButton, SecondaryButton } from "../ui";
|
||||||
|
|
||||||
@@ -16,64 +37,191 @@ interface CreateActionsProps {
|
|||||||
isSubmitting: boolean;
|
isSubmitting: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const CreateActions: React.FC<CreateActionsProps> = ({
|
// ============================================================================
|
||||||
reset,
|
// Constants & Data
|
||||||
submit,
|
// ============================================================================
|
||||||
canSubmit,
|
|
||||||
isSubmitting,
|
const ANALYSIS_FEATURES = [
|
||||||
}) => {
|
{ icon: <AnalyticsIcon />, text: "Target audience & content type analysis" },
|
||||||
|
{ icon: <ListAltIcon />, text: "5 high-impact keywords for discoverability" },
|
||||||
|
{ icon: <TitleIcon />, text: "3 catchy episode title suggestions" },
|
||||||
|
{ icon: <PsychologyIcon />, text: "2 detailed episode outlines with segments" },
|
||||||
|
{ icon: <RecordVoiceOverIcon />, text: "4-6 research queries for AI-powered research" },
|
||||||
|
{ icon: <CheckCircleIcon />, text: "Episode hook, key takeaways & listener CTA" },
|
||||||
|
];
|
||||||
|
|
||||||
|
const ANALYSIS_PROGRESS_STEPS = [
|
||||||
|
"Analyzing target audience & content type",
|
||||||
|
"Generating keywords & title suggestions",
|
||||||
|
"Creating episode outlines",
|
||||||
|
"Generating research queries",
|
||||||
|
"Creating hook, takeaways & CTA",
|
||||||
|
];
|
||||||
|
|
||||||
|
const INFO_BANNER_TEXT =
|
||||||
|
"Podcast avatar Image is required. Brand avatar is default. You can choose from asset library or upload your picture. If not, AI Avatar will be generated automatically.";
|
||||||
|
|
||||||
|
// ============================================================================
|
||||||
|
// Styles
|
||||||
|
// ============================================================================
|
||||||
|
|
||||||
|
const styles = {
|
||||||
|
dialog: {
|
||||||
|
background: "linear-gradient(135deg, #1e293b 0%, #0f172a 100%)",
|
||||||
|
border: "1px solid rgba(167, 139, 250, 0.3)",
|
||||||
|
borderRadius: 3,
|
||||||
|
},
|
||||||
|
infoAlert: {
|
||||||
|
background: alpha("#f0f4ff", 0.6),
|
||||||
|
border: "1px solid rgba(99, 102, 241, 0.15)",
|
||||||
|
borderRadius: 2,
|
||||||
|
boxShadow: "0 1px 3px rgba(99, 102, 241, 0.08)",
|
||||||
|
},
|
||||||
|
progressDot: {
|
||||||
|
width: 6,
|
||||||
|
height: 6,
|
||||||
|
borderRadius: "50%",
|
||||||
|
bgcolor: "#a78bfa",
|
||||||
|
},
|
||||||
|
dialogContent: {
|
||||||
|
color: "rgba(255,255,255,0.8)",
|
||||||
|
minHeight: 200,
|
||||||
|
py: 3,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
// ============================================================================
|
||||||
|
// Sub-Components
|
||||||
|
// ============================================================================
|
||||||
|
|
||||||
|
const InfoBanner: React.FC<{ showInfo: boolean; setShowInfo: (v: boolean) => void }> = ({
|
||||||
|
showInfo,
|
||||||
|
setShowInfo,
|
||||||
|
}) => (
|
||||||
|
<Collapse in={showInfo}>
|
||||||
|
<Alert
|
||||||
|
severity="info"
|
||||||
|
icon={<InfoIcon sx={{ color: "#6366f1", fontSize: "1.125rem" }} />}
|
||||||
|
onClose={() => setShowInfo(false)}
|
||||||
|
sx={styles.infoAlert}
|
||||||
|
>
|
||||||
|
<Typography variant="body2" sx={{ fontSize: "0.875rem", color: "#475569", lineHeight: 1.6, fontWeight: 400 }}>
|
||||||
|
{INFO_BANNER_TEXT}
|
||||||
|
</Typography>
|
||||||
|
</Alert>
|
||||||
|
</Collapse>
|
||||||
|
);
|
||||||
|
|
||||||
|
const ShowTipsLink: React.FC<{ onClick: () => void }> = ({ onClick }) => (
|
||||||
|
<Stack direction="row" alignItems="center" spacing={1}>
|
||||||
|
<InfoIcon sx={{ fontSize: 16, color: "#6366f1" }} />
|
||||||
|
<Typography variant="caption" sx={{ color: "#6366f1", cursor: "pointer", "&:hover": { textDecoration: "underline" } }} onClick={onClick}>
|
||||||
|
Show tips
|
||||||
|
</Typography>
|
||||||
|
</Stack>
|
||||||
|
);
|
||||||
|
|
||||||
|
const AnalysisProgressView: React.FC = () => (
|
||||||
|
<Stack spacing={3} alignItems="center" sx={styles.dialogContent} justifyContent="center">
|
||||||
|
<Box sx={{ position: "relative", display: "flex", alignItems: "center", justifyContent: "center" }}>
|
||||||
|
<CircularProgress size={80} thickness={3} sx={{ color: "#a78bfa" }} />
|
||||||
|
<Box sx={{ position: "absolute", display: "flex", flexDirection: "column", alignItems: "center" }}>
|
||||||
|
<AutoAwesomeIcon sx={{ color: "#a78bfa", fontSize: 32 }} />
|
||||||
|
</Box>
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
<Typography variant="h6" sx={{ color: "#fff", textAlign: "center" }}>
|
||||||
|
Analyzing Your Podcast Idea
|
||||||
|
</Typography>
|
||||||
|
|
||||||
|
<LinearProgress
|
||||||
|
sx={{
|
||||||
|
width: "100%",
|
||||||
|
height: 8,
|
||||||
|
borderRadius: 4,
|
||||||
|
bgcolor: "rgba(255,255,255,0.1)",
|
||||||
|
"& .MuiLinearProgress-bar": { bgcolor: "#a78bfa", borderRadius: 4 },
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<Stack spacing={1} sx={{ width: "100%" }}>
|
||||||
|
<Typography variant="body2" sx={{ color: "rgba(255,255,255,0.7)", textAlign: "center" }}>
|
||||||
|
This may take a few moments...
|
||||||
|
</Typography>
|
||||||
|
<Stack spacing={0.5} alignItems="flex-start" sx={{ pl: 2 }}>
|
||||||
|
{ANALYSIS_PROGRESS_STEPS.map((step, idx) => (
|
||||||
|
<Typography key={idx} variant="caption" sx={{ color: "rgba(255,255,255,0.5)", display: "flex", alignItems: "center", gap: 0.5 }}>
|
||||||
|
<Box sx={styles.progressDot} /> {step}
|
||||||
|
</Typography>
|
||||||
|
))}
|
||||||
|
</Stack>
|
||||||
|
</Stack>
|
||||||
|
</Stack>
|
||||||
|
);
|
||||||
|
|
||||||
|
const WhatYoullGetView: React.FC = () => (
|
||||||
|
<>
|
||||||
|
<Typography variant="body2" sx={{ mb: 2, color: "rgba(255,255,255,0.7)" }}>
|
||||||
|
Click "Start Analysis" to begin AI-powered podcast planning. Here's what we'll generate for you:
|
||||||
|
</Typography>
|
||||||
|
<List>
|
||||||
|
{ANALYSIS_FEATURES.map((feature, index) => (
|
||||||
|
<ListItem key={index} sx={{ px: 0, py: 0.5 }}>
|
||||||
|
<ListItemIcon sx={{ minWidth: 36, color: "#a78bfa" }}>{feature.icon}</ListItemIcon>
|
||||||
|
<ListItemText
|
||||||
|
primary={feature.text}
|
||||||
|
primaryTypographyProps={{ sx: { color: "rgba(255,255,255,0.9)", fontSize: "0.9rem" } }}
|
||||||
|
/>
|
||||||
|
</ListItem>
|
||||||
|
))}
|
||||||
|
</List>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
|
||||||
|
// ============================================================================
|
||||||
|
// Main Component
|
||||||
|
// ============================================================================
|
||||||
|
|
||||||
|
export const CreateActions: React.FC<CreateActionsProps> = ({ reset, submit, canSubmit, isSubmitting }) => {
|
||||||
const [showInfo, setShowInfo] = useState(true);
|
const [showInfo, setShowInfo] = useState(true);
|
||||||
|
const [showAnalysisModal, setShowAnalysisModal] = useState(false);
|
||||||
|
const [analysisStarted, setAnalysisStarted] = useState(false);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const timer = setTimeout(() => {
|
const timer = setTimeout(() => setShowInfo(false), 8000);
|
||||||
setShowInfo(false);
|
|
||||||
}, 8000);
|
|
||||||
return () => clearTimeout(timer);
|
return () => clearTimeout(timer);
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
// Close modal when analysis completes
|
||||||
|
useEffect(() => {
|
||||||
|
if (!isSubmitting && analysisStarted) {
|
||||||
|
setShowAnalysisModal(false);
|
||||||
|
setAnalysisStarted(false);
|
||||||
|
}
|
||||||
|
}, [isSubmitting, analysisStarted]);
|
||||||
|
|
||||||
|
const handleSubmitClick = () => {
|
||||||
|
if (canSubmit && !isSubmitting) setShowAnalysisModal(true);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleStartAnalysis = () => {
|
||||||
|
setAnalysisStarted(true);
|
||||||
|
submit();
|
||||||
|
};
|
||||||
|
|
||||||
|
const showProgressInModal = showAnalysisModal && (analysisStarted || isSubmitting);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Stack spacing={2}>
|
<Stack spacing={2}>
|
||||||
{/* Collapsible Info Banner */}
|
<InfoBanner showInfo={showInfo} setShowInfo={setShowInfo} />
|
||||||
<Collapse in={showInfo}>
|
{!showInfo && <ShowTipsLink onClick={() => setShowInfo(true)} />}
|
||||||
<Alert
|
|
||||||
severity="info"
|
|
||||||
icon={<InfoIcon sx={{ color: "#6366f1", fontSize: "1.125rem" }} />}
|
|
||||||
onClose={() => setShowInfo(false)}
|
|
||||||
sx={{
|
|
||||||
background: alpha("#f0f4ff", 0.6),
|
|
||||||
border: "1px solid rgba(99, 102, 241, 0.15)",
|
|
||||||
borderRadius: 2,
|
|
||||||
boxShadow: "0 1px 3px rgba(99, 102, 241, 0.08)",
|
|
||||||
"& .MuiAlert-message": {
|
|
||||||
width: "100%",
|
|
||||||
},
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<Typography variant="body2" sx={{ fontSize: "0.875rem", color: "#475569", lineHeight: 1.6, fontWeight: 400 }}>
|
|
||||||
Podcast avatar Image is required. Brand avatar is default. You can choose from asset library or upload your picture. If not, AI Avatar will be generated automatically.
|
|
||||||
</Typography>
|
|
||||||
</Alert>
|
|
||||||
</Collapse>
|
|
||||||
|
|
||||||
{!showInfo && (
|
|
||||||
<Stack direction="row" alignItems="center" spacing={1}>
|
|
||||||
<InfoIcon sx={{ fontSize: 16, color: "#6366f1" }} />
|
|
||||||
<Typography
|
|
||||||
variant="caption"
|
|
||||||
sx={{ color: "#6366f1", cursor: "pointer", "&:hover": { textDecoration: "underline" } }}
|
|
||||||
onClick={() => setShowInfo(true)}
|
|
||||||
>
|
|
||||||
Show tips
|
|
||||||
</Typography>
|
|
||||||
</Stack>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<Stack direction="row" justifyContent="flex-end" spacing={1}>
|
<Stack direction="row" justifyContent="flex-end" spacing={1}>
|
||||||
<SecondaryButton onClick={reset} startIcon={<RefreshIcon />}>
|
<SecondaryButton onClick={reset} startIcon={<RefreshIcon />}>
|
||||||
Reset
|
Reset
|
||||||
</SecondaryButton>
|
</SecondaryButton>
|
||||||
<PrimaryButton
|
<PrimaryButton
|
||||||
onClick={submit}
|
onClick={handleSubmitClick}
|
||||||
disabled={!canSubmit || isSubmitting}
|
disabled={!canSubmit || isSubmitting}
|
||||||
loading={isSubmitting}
|
loading={isSubmitting}
|
||||||
startIcon={<AutoAwesomeIcon />}
|
startIcon={<AutoAwesomeIcon />}
|
||||||
@@ -82,6 +230,43 @@ export const CreateActions: React.FC<CreateActionsProps> = ({
|
|||||||
{isSubmitting ? "Analyzing..." : "Analyze & Continue"}
|
{isSubmitting ? "Analyzing..." : "Analyze & Continue"}
|
||||||
</PrimaryButton>
|
</PrimaryButton>
|
||||||
</Stack>
|
</Stack>
|
||||||
|
|
||||||
|
<Dialog
|
||||||
|
open={showAnalysisModal}
|
||||||
|
onClose={() => !isSubmitting && setShowAnalysisModal(false)}
|
||||||
|
maxWidth="sm"
|
||||||
|
fullWidth
|
||||||
|
PaperProps={{ sx: styles.dialog }}
|
||||||
|
>
|
||||||
|
<DialogTitle sx={{ color: "#fff", display: "flex", alignItems: "center", gap: 1 }}>
|
||||||
|
{isSubmitting ? (
|
||||||
|
<Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
|
||||||
|
<CircularProgress size={24} sx={{ color: "#a78bfa" }} />
|
||||||
|
Analyzing Your Podcast Idea
|
||||||
|
</Box>
|
||||||
|
) : (
|
||||||
|
<Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
|
||||||
|
<AutoAwesomeIcon sx={{ color: "#a78bfa" }} />
|
||||||
|
What You'll Get
|
||||||
|
</Box>
|
||||||
|
)}
|
||||||
|
</DialogTitle>
|
||||||
|
|
||||||
|
<DialogContent sx={styles.dialogContent}>
|
||||||
|
{showProgressInModal ? <AnalysisProgressView /> : <WhatYoullGetView />}
|
||||||
|
</DialogContent>
|
||||||
|
|
||||||
|
<DialogActions sx={{ px: 3, pb: 3 }}>
|
||||||
|
{showProgressInModal ? null : (
|
||||||
|
<>
|
||||||
|
<SecondaryButton onClick={() => setShowAnalysisModal(false)}>Cancel</SecondaryButton>
|
||||||
|
<PrimaryButton onClick={handleStartAnalysis} startIcon={<AutoAwesomeIcon />}>
|
||||||
|
Start Analysis
|
||||||
|
</PrimaryButton>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</DialogActions>
|
||||||
|
</Dialog>
|
||||||
</Stack>
|
</Stack>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import { Stack, Typography, Divider, Chip, Tooltip, IconButton, alpha, Box } fro
|
|||||||
import { OpenInNew as OpenInNewIcon, ContentCopy as ContentCopyIcon, ExpandMore as ExpandMoreIcon, ExpandLess as ExpandLessIcon } from "@mui/icons-material";
|
import { OpenInNew as OpenInNewIcon, ContentCopy as ContentCopyIcon, ExpandMore as ExpandMoreIcon, ExpandLess as ExpandLessIcon } from "@mui/icons-material";
|
||||||
import { Fact } from "./types";
|
import { Fact } from "./types";
|
||||||
import { GlassyCard, glassyCardSx } from "./ui";
|
import { GlassyCard, glassyCardSx } from "./ui";
|
||||||
|
import { TextToSpeechButton } from "../shared/TextToSpeechButton";
|
||||||
|
|
||||||
interface FactCardProps {
|
interface FactCardProps {
|
||||||
fact: Fact;
|
fact: Fact;
|
||||||
@@ -162,6 +163,7 @@ export const FactCard: React.FC<FactCardProps> = ({ fact }) => {
|
|||||||
<ContentCopyIcon fontSize="small" />
|
<ContentCopyIcon fontSize="small" />
|
||||||
</IconButton>
|
</IconButton>
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
|
<TextToSpeechButton text={fact.quote} size="small" />
|
||||||
</Stack>
|
</Stack>
|
||||||
|
|
||||||
{/* Confidence and Date */}
|
{/* Confidence and Date */}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import React from 'react';
|
import React, { useState } from 'react';
|
||||||
import {
|
import {
|
||||||
Box,
|
Box,
|
||||||
Typography,
|
Typography,
|
||||||
@@ -26,6 +26,8 @@ interface PodcastBiblePanelProps {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export const PodcastBiblePanel: React.FC<PodcastBiblePanelProps> = ({ bible, onUpdate }) => {
|
export const PodcastBiblePanel: React.FC<PodcastBiblePanelProps> = ({ bible, onUpdate }) => {
|
||||||
|
const [panelExpanded, setPanelExpanded] = useState(false);
|
||||||
|
|
||||||
if (!bible) return null;
|
if (!bible) return null;
|
||||||
|
|
||||||
const handleUpdateHost = (field: string, value: any) => {
|
const handleUpdateHost = (field: string, value: any) => {
|
||||||
@@ -51,136 +53,157 @@ export const PodcastBiblePanel: React.FC<PodcastBiblePanelProps> = ({ bible, onU
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<Box sx={{ mt: 2 }}>
|
<Box sx={{ mt: 2 }}>
|
||||||
<Stack direction="row" alignItems="center" spacing={1} sx={{ mb: 2 }}>
|
<Accordion
|
||||||
<AutoFixHighIcon color="primary" />
|
expanded={panelExpanded}
|
||||||
<Typography variant="h6" fontWeight="bold" color="#1e293b">
|
onChange={() => setPanelExpanded(!panelExpanded)}
|
||||||
Podcast Bible
|
sx={{ borderRadius: 2, '&:before': { display: 'none' }, boxShadow: '0 1px 3px rgba(0,0,0,0.1)' }}
|
||||||
</Typography>
|
>
|
||||||
<Tooltip title="Hyper-personalized context derived from your onboarding data. This grounds all research and script generation.">
|
<AccordionSummary
|
||||||
<IconButton size="small">
|
expandIcon={<ExpandMoreIcon />}
|
||||||
<InfoIcon fontSize="small" sx={{ color: '#94a3b8' }} />
|
sx={{
|
||||||
</IconButton>
|
bgcolor: panelExpanded ? 'rgba(99,102,241,0.05)' : 'transparent',
|
||||||
</Tooltip>
|
borderRadius: panelExpanded ? '16px 16px 0 0' : 2,
|
||||||
</Stack>
|
}}
|
||||||
|
>
|
||||||
|
<Stack direction="row" alignItems="center" spacing={1} sx={{ width: '100%' }}>
|
||||||
|
<AutoFixHighIcon color="primary" />
|
||||||
|
<Typography variant="h6" fontWeight="bold" color="#1e293b" sx={{ flex: 1 }}>
|
||||||
|
Podcast Bible
|
||||||
|
</Typography>
|
||||||
|
{!panelExpanded && (
|
||||||
|
<Typography variant="caption" color="text.secondary">
|
||||||
|
Host • Audience • Brand
|
||||||
|
</Typography>
|
||||||
|
)}
|
||||||
|
<Tooltip title="Hyper-personalized context derived from your onboarding data. This grounds all research and script generation.">
|
||||||
|
<IconButton size="small" onClick={(e) => e.stopPropagation()}>
|
||||||
|
<InfoIcon fontSize="small" sx={{ color: '#94a3b8' }} />
|
||||||
|
</IconButton>
|
||||||
|
</Tooltip>
|
||||||
|
</Stack>
|
||||||
|
</AccordionSummary>
|
||||||
|
|
||||||
|
<AccordionDetails sx={{ bgcolor: 'rgba(99,102,241,0.02)' }}>
|
||||||
|
<Stack spacing={2}>
|
||||||
|
{/* Host Persona */}
|
||||||
|
<Accordion sx={{ borderRadius: 2, '&:before': { display: 'none' }, boxShadow: '0 1px 3px rgba(0,0,0,0.08)', bgcolor: '#fff' }}>
|
||||||
|
<AccordionSummary expandIcon={<ExpandMoreIcon />}>
|
||||||
|
<Stack direction="row" spacing={1} alignItems="center">
|
||||||
|
<PsychologyIcon sx={{ color: '#6366f1' }} />
|
||||||
|
<Typography fontWeight="600">Host Persona</Typography>
|
||||||
|
</Stack>
|
||||||
|
</AccordionSummary>
|
||||||
|
<AccordionDetails>
|
||||||
|
<Stack spacing={2}>
|
||||||
|
<TextField
|
||||||
|
fullWidth
|
||||||
|
label="Host Background"
|
||||||
|
size="small"
|
||||||
|
value={bible.host?.background || ''}
|
||||||
|
onChange={(e) => handleUpdateHost('background', e.target.value)}
|
||||||
|
multiline
|
||||||
|
rows={2}
|
||||||
|
/>
|
||||||
|
<Stack direction="row" spacing={2}>
|
||||||
|
<TextField
|
||||||
|
fullWidth
|
||||||
|
label="Expertise Level"
|
||||||
|
size="small"
|
||||||
|
value={bible.host?.expertise_level || ''}
|
||||||
|
onChange={(e) => handleUpdateHost('expertise_level', e.target.value)}
|
||||||
|
/>
|
||||||
|
<TextField
|
||||||
|
fullWidth
|
||||||
|
label="Vocal Style"
|
||||||
|
size="small"
|
||||||
|
value={bible.host?.vocal_style || ''}
|
||||||
|
onChange={(e) => handleUpdateHost('vocal_style', e.target.value)}
|
||||||
|
/>
|
||||||
|
</Stack>
|
||||||
|
</Stack>
|
||||||
|
</AccordionDetails>
|
||||||
|
</Accordion>
|
||||||
|
|
||||||
<Stack spacing={2}>
|
{/* Audience DNA */}
|
||||||
{/* Host Persona */}
|
<Accordion sx={{ borderRadius: 2, '&:before': { display: 'none' }, boxShadow: '0 1px 3px rgba(0,0,0,0.1)' }}>
|
||||||
<Accordion defaultExpanded sx={{ borderRadius: 2, '&:before': { display: 'none' }, boxShadow: '0 1px 3px rgba(0,0,0,0.1)' }}>
|
<AccordionSummary expandIcon={<ExpandMoreIcon />}>
|
||||||
<AccordionSummary expandIcon={<ExpandMoreIcon />}>
|
<Stack direction="row" spacing={1} alignItems="center">
|
||||||
<Stack direction="row" spacing={1} alignItems="center">
|
<GroupsIcon sx={{ color: '#ec4899' }} />
|
||||||
<PsychologyIcon sx={{ color: '#6366f1' }} />
|
<Typography fontWeight="600">Audience DNA</Typography>
|
||||||
<Typography fontWeight="600">Host Persona</Typography>
|
</Stack>
|
||||||
</Stack>
|
</AccordionSummary>
|
||||||
</AccordionSummary>
|
<AccordionDetails>
|
||||||
<AccordionDetails>
|
<Stack spacing={2}>
|
||||||
<Stack spacing={2}>
|
<TextField
|
||||||
<TextField
|
fullWidth
|
||||||
fullWidth
|
label="Audience Expertise"
|
||||||
label="Host Background"
|
size="small"
|
||||||
size="small"
|
value={bible.audience?.expertise_level || ''}
|
||||||
value={bible.host?.background || ''}
|
onChange={(e) => handleUpdateAudience('expertise_level', e.target.value)}
|
||||||
onChange={(e) => handleUpdateHost('background', e.target.value)}
|
/>
|
||||||
multiline
|
<Box>
|
||||||
rows={2}
|
<Typography variant="caption" color="text.secondary" sx={{ mb: 1, display: 'block' }}>
|
||||||
/>
|
Interests
|
||||||
<Stack direction="row" spacing={2}>
|
</Typography>
|
||||||
<TextField
|
<Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 0.5 }}>
|
||||||
fullWidth
|
{bible.audience?.interests?.map((interest: string, idx: number) => (
|
||||||
label="Expertise Level"
|
<Chip key={idx} label={interest} size="small" variant="outlined" />
|
||||||
size="small"
|
))}
|
||||||
value={bible.host?.expertise_level || ''}
|
</Box>
|
||||||
onChange={(e) => handleUpdateHost('expertise_level', e.target.value)}
|
</Box>
|
||||||
/>
|
<Box>
|
||||||
<TextField
|
<Typography variant="caption" color="text.secondary" sx={{ mb: 1, display: 'block' }}>
|
||||||
fullWidth
|
Pain Points
|
||||||
label="Vocal Style"
|
</Typography>
|
||||||
size="small"
|
<Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 0.5 }}>
|
||||||
value={bible.host?.vocal_style || ''}
|
{bible.audience?.pain_points?.map((point: string, idx: number) => (
|
||||||
onChange={(e) => handleUpdateHost('vocal_style', e.target.value)}
|
<Chip key={idx} label={point} size="small" color="error" variant="outlined" />
|
||||||
/>
|
))}
|
||||||
</Stack>
|
</Box>
|
||||||
</Stack>
|
</Box>
|
||||||
</AccordionDetails>
|
</Stack>
|
||||||
</Accordion>
|
</AccordionDetails>
|
||||||
|
</Accordion>
|
||||||
|
|
||||||
{/* Audience DNA */}
|
{/* Brand DNA */}
|
||||||
<Accordion sx={{ borderRadius: 2, '&:before': { display: 'none' }, boxShadow: '0 1px 3px rgba(0,0,0,0.1)' }}>
|
<Accordion sx={{ borderRadius: 2, '&:before': { display: 'none' }, boxShadow: '0 1px 3px rgba(0,0,0,0.1)' }}>
|
||||||
<AccordionSummary expandIcon={<ExpandMoreIcon />}>
|
<AccordionSummary expandIcon={<ExpandMoreIcon />}>
|
||||||
<Stack direction="row" spacing={1} alignItems="center">
|
<Stack direction="row" spacing={1} alignItems="center">
|
||||||
<GroupsIcon sx={{ color: '#ec4899' }} />
|
<BrandIcon sx={{ color: '#10b981' }} />
|
||||||
<Typography fontWeight="600">Audience DNA</Typography>
|
<Typography fontWeight="600">Brand DNA</Typography>
|
||||||
</Stack>
|
</Stack>
|
||||||
</AccordionSummary>
|
</AccordionSummary>
|
||||||
<AccordionDetails>
|
<AccordionDetails>
|
||||||
<Stack spacing={2}>
|
<Stack spacing={2}>
|
||||||
<TextField
|
<TextField
|
||||||
fullWidth
|
fullWidth
|
||||||
label="Audience Expertise"
|
label="Industry"
|
||||||
size="small"
|
size="small"
|
||||||
value={bible.audience?.expertise_level || ''}
|
value={bible.brand?.industry || ''}
|
||||||
onChange={(e) => handleUpdateAudience('expertise_level', e.target.value)}
|
onChange={(e) => handleUpdateBrand('industry', e.target.value)}
|
||||||
/>
|
/>
|
||||||
<Box>
|
<Stack direction="row" spacing={2}>
|
||||||
<Typography variant="caption" color="text.secondary" sx={{ mb: 1, display: 'block' }}>
|
<TextField
|
||||||
Interests
|
fullWidth
|
||||||
</Typography>
|
label="Tone"
|
||||||
<Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 0.5 }}>
|
size="small"
|
||||||
{bible.audience?.interests?.map((interest: string, idx: number) => (
|
value={bible.brand?.tone || ''}
|
||||||
<Chip key={idx} label={interest} size="small" variant="outlined" />
|
onChange={(e) => handleUpdateBrand('tone', e.target.value)}
|
||||||
))}
|
/>
|
||||||
</Box>
|
<TextField
|
||||||
</Box>
|
fullWidth
|
||||||
<Box>
|
label="Style"
|
||||||
<Typography variant="caption" color="text.secondary" sx={{ mb: 1, display: 'block' }}>
|
size="small"
|
||||||
Pain Points
|
value={bible.brand?.communication_style || ''}
|
||||||
</Typography>
|
onChange={(e) => handleUpdateBrand('communication_style', e.target.value)}
|
||||||
<Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 0.5 }}>
|
/>
|
||||||
{bible.audience?.pain_points?.map((point: string, idx: number) => (
|
</Stack>
|
||||||
<Chip key={idx} label={point} size="small" color="error" variant="outlined" />
|
</Stack>
|
||||||
))}
|
</AccordionDetails>
|
||||||
</Box>
|
</Accordion>
|
||||||
</Box>
|
</Stack>
|
||||||
</Stack>
|
</AccordionDetails>
|
||||||
</AccordionDetails>
|
</Accordion>
|
||||||
</Accordion>
|
|
||||||
|
|
||||||
{/* Brand DNA */}
|
|
||||||
<Accordion sx={{ borderRadius: 2, '&:before': { display: 'none' }, boxShadow: '0 1px 3px rgba(0,0,0,0.1)' }}>
|
|
||||||
<AccordionSummary expandIcon={<ExpandMoreIcon />}>
|
|
||||||
<Stack direction="row" spacing={1} alignItems="center">
|
|
||||||
<BrandIcon sx={{ color: '#10b981' }} />
|
|
||||||
<Typography fontWeight="600">Brand DNA</Typography>
|
|
||||||
</Stack>
|
|
||||||
</AccordionSummary>
|
|
||||||
<AccordionDetails>
|
|
||||||
<Stack spacing={2}>
|
|
||||||
<TextField
|
|
||||||
fullWidth
|
|
||||||
label="Industry"
|
|
||||||
size="small"
|
|
||||||
value={bible.brand?.industry || ''}
|
|
||||||
onChange={(e) => handleUpdateBrand('industry', e.target.value)}
|
|
||||||
/>
|
|
||||||
<Stack direction="row" spacing={2}>
|
|
||||||
<TextField
|
|
||||||
fullWidth
|
|
||||||
label="Tone"
|
|
||||||
size="small"
|
|
||||||
value={bible.brand?.tone || ''}
|
|
||||||
onChange={(e) => handleUpdateBrand('tone', e.target.value)}
|
|
||||||
/>
|
|
||||||
<TextField
|
|
||||||
fullWidth
|
|
||||||
label="Style"
|
|
||||||
size="small"
|
|
||||||
value={bible.brand?.communication_style || ''}
|
|
||||||
onChange={(e) => handleUpdateBrand('communication_style', e.target.value)}
|
|
||||||
/>
|
|
||||||
</Stack>
|
|
||||||
</Stack>
|
|
||||||
</AccordionDetails>
|
|
||||||
</Accordion>
|
|
||||||
</Stack>
|
|
||||||
</Box>
|
</Box>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import React, { useState, useCallback } from "react";
|
import React, { useState, useCallback } from "react";
|
||||||
import { Box, Paper, Stack, Alert, Divider, CircularProgress, alpha } from "@mui/material";
|
import { Box, Paper, Stack, Alert, Divider, CircularProgress, alpha, Dialog, DialogTitle, DialogContent, DialogActions, Button, Typography } from "@mui/material";
|
||||||
import { usePodcastProjectState } from "../../hooks/usePodcastProjectState";
|
import { usePodcastProjectState } from "../../hooks/usePodcastProjectState";
|
||||||
import { CreateModal } from "./CreateModal";
|
import { CreateModal } from "./CreateModal";
|
||||||
import { AnalysisPanel } from "./AnalysisPanel";
|
import { AnalysisPanel } from "./AnalysisPanel";
|
||||||
@@ -78,7 +78,7 @@ const PodcastDashboard: React.FC = () => {
|
|||||||
}, [resetState]);
|
}, [resetState]);
|
||||||
|
|
||||||
if (showProjectList) {
|
if (showProjectList) {
|
||||||
return <ProjectList onSelectProject={handleSelectProject} />;
|
return <ProjectList onSelectProject={handleSelectProject} onBack={() => setShowProjectList(false)} />;
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -197,19 +197,13 @@ const PodcastDashboard: React.FC = () => {
|
|||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{(workflow.isAnalyzing || workflow.isResearching) && (
|
{(workflow.isAnalyzing || workflow.isResearching || workflow.isGeneratingScript) && (
|
||||||
<Alert
|
<Stack direction="row" spacing={2} alignItems="center" sx={{ py: 1.5 }}>
|
||||||
severity="warning"
|
<CircularProgress size={20} sx={{ color: "#667eea" }} />
|
||||||
icon={<CircularProgress size={20} />}
|
<Typography variant="body2" sx={{ color: "#64748b" }}>
|
||||||
sx={{
|
{workflow.isAnalyzing ? "Analyzing your idea with AI..." : workflow.isGeneratingScript ? "Generating script with AI..." : "Running research... This may take a moment."}
|
||||||
background: "#fef3c7",
|
</Typography>
|
||||||
border: "1px solid #fde68a",
|
</Stack>
|
||||||
}}
|
|
||||||
>
|
|
||||||
<Box component="span" sx={{ fontSize: "0.875rem" }}>
|
|
||||||
{workflow.isAnalyzing ? "Analyzing your idea with AI..." : "Running research... This may take a moment."}
|
|
||||||
</Box>
|
|
||||||
</Alert>
|
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Create Modal */}
|
{/* Create Modal */}
|
||||||
@@ -238,6 +232,11 @@ const PodcastDashboard: React.FC = () => {
|
|||||||
avatarPrompt={project?.avatarPrompt}
|
avatarPrompt={project?.avatarPrompt}
|
||||||
onRegenerate={() => setShowRegenModal(true)}
|
onRegenerate={() => setShowRegenModal(true)}
|
||||||
onUpdateAnalysis={(updated) => projectState.setAnalysis(updated)}
|
onUpdateAnalysis={(updated) => projectState.setAnalysis(updated)}
|
||||||
|
onRunResearch={() => workflow.handleRunResearch()}
|
||||||
|
isResearchRunning={workflow.isResearching}
|
||||||
|
selectedQueries={selectedQueries}
|
||||||
|
onToggleQuery={workflow.toggleQuery}
|
||||||
|
queries={queries}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
@@ -251,6 +250,11 @@ const PodcastDashboard: React.FC = () => {
|
|||||||
onToggleQuery={workflow.toggleQuery}
|
onToggleQuery={workflow.toggleQuery}
|
||||||
onProviderChange={setResearchProvider}
|
onProviderChange={setResearchProvider}
|
||||||
onRunResearch={workflow.handleRunResearch}
|
onRunResearch={workflow.handleRunResearch}
|
||||||
|
onRegenerateQueries={workflow.handleRegenerateQueries}
|
||||||
|
onUpdateQuery={workflow.handleUpdateQuery}
|
||||||
|
onDeleteQuery={workflow.handleDeleteQuery}
|
||||||
|
analysis={analysis}
|
||||||
|
idea={project?.idea || ""}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
@@ -259,6 +263,7 @@ const PodcastDashboard: React.FC = () => {
|
|||||||
research={research}
|
research={research}
|
||||||
canGenerateScript={workflow.canGenerateScript}
|
canGenerateScript={workflow.canGenerateScript}
|
||||||
onGenerateScript={workflow.handleGenerateScript}
|
onGenerateScript={workflow.handleGenerateScript}
|
||||||
|
isGeneratingScript={workflow.isGeneratingScript}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
@@ -332,6 +337,55 @@ const PodcastDashboard: React.FC = () => {
|
|||||||
}}
|
}}
|
||||||
isSubmitting={workflow.isAnalyzing}
|
isSubmitting={workflow.isAnalyzing}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
{/* Duplicate Project Dialog */}
|
||||||
|
<Dialog
|
||||||
|
open={workflow.showDuplicateDialog}
|
||||||
|
onClose={() => workflow.setShowDuplicateDialog(false)}
|
||||||
|
maxWidth="sm"
|
||||||
|
fullWidth
|
||||||
|
PaperProps={{
|
||||||
|
sx: {
|
||||||
|
background: "linear-gradient(135deg, #1e293b 0%, #0f172a 100%)",
|
||||||
|
border: "1px solid rgba(167, 139, 250, 0.3)",
|
||||||
|
borderRadius: 3,
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<DialogTitle sx={{ color: "#fff", display: "flex", alignItems: "center", gap: 1 }}>
|
||||||
|
Duplicate Project Found
|
||||||
|
</DialogTitle>
|
||||||
|
<DialogContent sx={{ color: "rgba(255,255,255,0.8)" }}>
|
||||||
|
<Alert severity="warning" sx={{ mb: 2, bgcolor: "rgba(245,158,11,0.1)", border: "1px solid rgba(245,158,11,0.3)" }}>
|
||||||
|
A project with a similar idea already exists. You can edit the existing project or create a new one (which will overwrite the previous).
|
||||||
|
</Alert>
|
||||||
|
<Box sx={{ p: 2, bgcolor: "rgba(255,255,255,0.05)", borderRadius: 2 }}>
|
||||||
|
<strong style={{ color: "#fff" }}>Existing project idea:</strong>
|
||||||
|
<p style={{ color: "rgba(255,255,255,0.7)", marginTop: 8 }}>
|
||||||
|
{workflow.duplicateProjectInfo.idea}
|
||||||
|
</p>
|
||||||
|
</Box>
|
||||||
|
</DialogContent>
|
||||||
|
<DialogActions sx={{ px: 3, pb: 3 }}>
|
||||||
|
<Button
|
||||||
|
onClick={() => {
|
||||||
|
workflow.setShowDuplicateDialog(false);
|
||||||
|
// Load existing project
|
||||||
|
loadProjectFromDb(workflow.duplicateProjectInfo.projectId);
|
||||||
|
}}
|
||||||
|
sx={{ color: "#a78bfa" }}
|
||||||
|
>
|
||||||
|
Edit Existing
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
onClick={() => workflow.setShowDuplicateDialog(false)}
|
||||||
|
variant="contained"
|
||||||
|
sx={{ bgcolor: "#ef4444", "&:hover": { bgcolor: "#dc2626" } }}
|
||||||
|
>
|
||||||
|
Create New (Overwrite)
|
||||||
|
</Button>
|
||||||
|
</DialogActions>
|
||||||
|
</Dialog>
|
||||||
</Box>
|
</Box>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import React from "react";
|
import React, { useState } from "react";
|
||||||
import {
|
import {
|
||||||
Stack,
|
Stack,
|
||||||
Typography,
|
Typography,
|
||||||
@@ -16,11 +16,17 @@ import {
|
|||||||
MenuItem,
|
MenuItem,
|
||||||
Box,
|
Box,
|
||||||
alpha,
|
alpha,
|
||||||
|
Dialog,
|
||||||
|
DialogTitle,
|
||||||
|
DialogContent,
|
||||||
|
DialogActions,
|
||||||
|
TextField,
|
||||||
|
IconButton,
|
||||||
} from "@mui/material";
|
} from "@mui/material";
|
||||||
import { Search as SearchIcon, AutoAwesome as AutoAwesomeIcon } from "@mui/icons-material";
|
import { Search as SearchIcon, AutoAwesome as AutoAwesomeIcon, Refresh as RefreshIcon, Edit as EditIcon, Delete as DeleteIcon, CheckCircle as CheckCircleIcon } from "@mui/icons-material";
|
||||||
import { ResearchProvider } from "../../../services/blogWriterApi";
|
import { ResearchProvider } from "../../../services/blogWriterApi";
|
||||||
import { Query } from "../types";
|
import { Query } from "../types";
|
||||||
import { GlassyCard, glassyCardSx, PrimaryButton } from "../ui";
|
import { GlassyCard, glassyCardSx, PrimaryButton, SecondaryButton } from "../ui";
|
||||||
|
|
||||||
interface QuerySelectionProps {
|
interface QuerySelectionProps {
|
||||||
queries: Query[];
|
queries: Query[];
|
||||||
@@ -30,6 +36,11 @@ interface QuerySelectionProps {
|
|||||||
onToggleQuery: (id: string) => void;
|
onToggleQuery: (id: string) => void;
|
||||||
onProviderChange: (provider: ResearchProvider) => void;
|
onProviderChange: (provider: ResearchProvider) => void;
|
||||||
onRunResearch: () => void;
|
onRunResearch: () => void;
|
||||||
|
onRegenerateQueries: (feedback: string) => Promise<void>;
|
||||||
|
onUpdateQuery: (id: string, newQuery: string, newRationale: string) => void;
|
||||||
|
onDeleteQuery: (id: string) => void;
|
||||||
|
analysis: any;
|
||||||
|
idea: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const QuerySelection: React.FC<QuerySelectionProps> = ({
|
export const QuerySelection: React.FC<QuerySelectionProps> = ({
|
||||||
@@ -40,9 +51,51 @@ export const QuerySelection: React.FC<QuerySelectionProps> = ({
|
|||||||
onToggleQuery,
|
onToggleQuery,
|
||||||
onProviderChange,
|
onProviderChange,
|
||||||
onRunResearch,
|
onRunResearch,
|
||||||
|
onRegenerateQueries,
|
||||||
|
onUpdateQuery,
|
||||||
|
onDeleteQuery,
|
||||||
|
analysis,
|
||||||
|
idea,
|
||||||
}) => {
|
}) => {
|
||||||
|
const [showRegenDialog, setShowRegenDialog] = useState(false);
|
||||||
|
const [regenFeedback, setRegenFeedback] = useState("");
|
||||||
|
const [isRegenerating, setIsRegenerating] = useState(false);
|
||||||
|
const [editingId, setEditingId] = useState<string | null>(null);
|
||||||
|
const [editQuery, setEditQuery] = useState("");
|
||||||
|
const [editRationale, setEditRationale] = useState("");
|
||||||
const selectedCount = selectedQueries.size;
|
const selectedCount = selectedQueries.size;
|
||||||
|
|
||||||
|
const handleRegenerate = async () => {
|
||||||
|
if (!regenFeedback.trim()) return;
|
||||||
|
setIsRegenerating(true);
|
||||||
|
try {
|
||||||
|
await onRegenerateQueries(regenFeedback);
|
||||||
|
setShowRegenDialog(false);
|
||||||
|
setRegenFeedback("");
|
||||||
|
} finally {
|
||||||
|
setIsRegenerating(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const startEdit = (q: Query) => {
|
||||||
|
setEditingId(q.id);
|
||||||
|
setEditQuery(q.query);
|
||||||
|
setEditRationale(q.rationale);
|
||||||
|
};
|
||||||
|
|
||||||
|
const saveEdit = () => {
|
||||||
|
if (editingId && editQuery.trim()) {
|
||||||
|
onUpdateQuery(editingId, editQuery.trim(), editRationale.trim());
|
||||||
|
setEditingId(null);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const cancelEdit = () => {
|
||||||
|
setEditingId(null);
|
||||||
|
setEditQuery("");
|
||||||
|
setEditRationale("");
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<GlassyCard
|
<GlassyCard
|
||||||
sx={{
|
sx={{
|
||||||
@@ -55,10 +108,22 @@ export const QuerySelection: React.FC<QuerySelectionProps> = ({
|
|||||||
>
|
>
|
||||||
<Stack spacing={3}>
|
<Stack spacing={3}>
|
||||||
<Stack direction="row" justifyContent="space-between" alignItems="center" flexWrap="wrap" gap={2}>
|
<Stack direction="row" justifyContent="space-between" alignItems="center" flexWrap="wrap" gap={2}>
|
||||||
<Typography variant="h6" sx={{ display: "flex", alignItems: "center", gap: 1, color: "#0f172a", fontWeight: 700 }}>
|
<Stack direction="row" alignItems="center" spacing={1}>
|
||||||
<SearchIcon />
|
<Typography variant="h6" sx={{ display: "flex", alignItems: "center", gap: 1, color: "#0f172a", fontWeight: 700 }}>
|
||||||
Research Queries
|
<SearchIcon />
|
||||||
</Typography>
|
Research Queries
|
||||||
|
</Typography>
|
||||||
|
<Tooltip title="Regenerate research queries with custom feedback">
|
||||||
|
<PrimaryButton
|
||||||
|
size="small"
|
||||||
|
startIcon={<RefreshIcon />}
|
||||||
|
onClick={() => setShowRegenDialog(true)}
|
||||||
|
sx={{ py: 0.5, px: 1.5, fontSize: "0.75rem" }}
|
||||||
|
>
|
||||||
|
Regenerate
|
||||||
|
</PrimaryButton>
|
||||||
|
</Tooltip>
|
||||||
|
</Stack>
|
||||||
<Stack direction="row" spacing={2} alignItems="center">
|
<Stack direction="row" spacing={2} alignItems="center">
|
||||||
<FormControl size="small" sx={{ minWidth: 180 }}>
|
<FormControl size="small" sx={{ minWidth: 180 }}>
|
||||||
<InputLabel>Provider</InputLabel>
|
<InputLabel>Provider</InputLabel>
|
||||||
@@ -123,26 +188,70 @@ export const QuerySelection: React.FC<QuerySelectionProps> = ({
|
|||||||
|
|
||||||
<List>
|
<List>
|
||||||
{queries.map((q) => (
|
{queries.map((q) => (
|
||||||
<ListItem key={q.id} disablePadding>
|
<ListItem
|
||||||
<ListItemButton
|
key={q.id}
|
||||||
onClick={() => onToggleQuery(q.id)}
|
disablePadding
|
||||||
disabled={isResearching}
|
secondaryAction={
|
||||||
sx={{
|
editingId === q.id ? (
|
||||||
borderRadius: 2,
|
<Stack direction="row" spacing={0.5}>
|
||||||
mb: 1,
|
<IconButton size="small" onClick={saveEdit} sx={{ color: "#22c55e" }}>
|
||||||
border: "1px solid rgba(0,0,0,0.08)",
|
<CheckCircleIcon />
|
||||||
background: "#f8fafc",
|
</IconButton>
|
||||||
"&:hover": { background: alpha("#667eea", 0.08) },
|
<IconButton size="small" onClick={cancelEdit} sx={{ color: "#ef4444" }}>
|
||||||
}}
|
<DeleteIcon />
|
||||||
>
|
</IconButton>
|
||||||
<Checkbox checked={selectedQueries.has(q.id)} edge="start" />
|
</Stack>
|
||||||
<ListItemText
|
) : (
|
||||||
primary={q.query}
|
<Stack direction="row" spacing={0.5} onClick={(e) => e.stopPropagation()}>
|
||||||
secondary={q.rationale}
|
<IconButton size="small" onClick={() => startEdit(q)} sx={{ color: "#6366f1" }}>
|
||||||
primaryTypographyProps={{ variant: "body2", fontWeight: 600, color: "#0f172a" }}
|
<EditIcon />
|
||||||
secondaryTypographyProps={{ variant: "caption", sx: { color: "#475569" } }}
|
</IconButton>
|
||||||
/>
|
<IconButton size="small" onClick={() => onDeleteQuery(q.id)} sx={{ color: "#ef4444" }}>
|
||||||
</ListItemButton>
|
<DeleteIcon />
|
||||||
|
</IconButton>
|
||||||
|
</Stack>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{editingId === q.id ? (
|
||||||
|
<Box sx={{ width: "100%", p: 1.5, bgcolor: "#f0f9ff", borderRadius: 2, border: "1px solid #bae6fd" }}>
|
||||||
|
<TextField
|
||||||
|
fullWidth
|
||||||
|
size="small"
|
||||||
|
label="Query"
|
||||||
|
value={editQuery}
|
||||||
|
onChange={(e) => setEditQuery(e.target.value)}
|
||||||
|
sx={{ mb: 1 }}
|
||||||
|
/>
|
||||||
|
<TextField
|
||||||
|
fullWidth
|
||||||
|
size="small"
|
||||||
|
label="Rationale"
|
||||||
|
value={editRationale}
|
||||||
|
onChange={(e) => setEditRationale(e.target.value)}
|
||||||
|
/>
|
||||||
|
</Box>
|
||||||
|
) : (
|
||||||
|
<ListItemButton
|
||||||
|
onClick={() => onToggleQuery(q.id)}
|
||||||
|
disabled={isResearching}
|
||||||
|
sx={{
|
||||||
|
borderRadius: 2,
|
||||||
|
mb: 1,
|
||||||
|
border: "1px solid rgba(0,0,0,0.08)",
|
||||||
|
background: selectedQueries.has(q.id) ? alpha("#667eea", 0.08) : "#f8fafc",
|
||||||
|
"&:hover": { background: alpha("#667eea", 0.12) },
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Checkbox checked={selectedQueries.has(q.id)} edge="start" />
|
||||||
|
<ListItemText
|
||||||
|
primary={q.query}
|
||||||
|
secondary={q.rationale}
|
||||||
|
primaryTypographyProps={{ variant: "body2", fontWeight: 600, color: "#0f172a" }}
|
||||||
|
secondaryTypographyProps={{ variant: "caption", sx: { color: "#475569" } }}
|
||||||
|
/>
|
||||||
|
</ListItemButton>
|
||||||
|
)}
|
||||||
</ListItem>
|
</ListItem>
|
||||||
))}
|
))}
|
||||||
</List>
|
</List>
|
||||||
@@ -163,6 +272,69 @@ export const QuerySelection: React.FC<QuerySelectionProps> = ({
|
|||||||
</PrimaryButton>
|
</PrimaryButton>
|
||||||
</Box>
|
</Box>
|
||||||
</Stack>
|
</Stack>
|
||||||
|
|
||||||
|
{/* Regenerate Queries Dialog */}
|
||||||
|
<Dialog
|
||||||
|
open={showRegenDialog}
|
||||||
|
onClose={() => setShowRegenDialog(false)}
|
||||||
|
maxWidth="sm"
|
||||||
|
fullWidth
|
||||||
|
PaperProps={{
|
||||||
|
sx: {
|
||||||
|
background: "linear-gradient(135deg, #1e293b 0%, #0f172a 100%)",
|
||||||
|
border: "1px solid rgba(167, 139, 250, 0.3)",
|
||||||
|
borderRadius: 3,
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<DialogTitle sx={{ color: "#fff", display: "flex", alignItems: "center", gap: 1 }}>
|
||||||
|
<RefreshIcon sx={{ color: "#a78bfa" }} />
|
||||||
|
Regenerate Research Queries
|
||||||
|
</DialogTitle>
|
||||||
|
<DialogContent sx={{ color: "rgba(255,255,255,0.8)" }}>
|
||||||
|
<Typography variant="body2" sx={{ mb: 2, color: "rgba(255,255,255,0.7)" }}>
|
||||||
|
Provide custom directions to regenerate research queries. You can specify:
|
||||||
|
</Typography>
|
||||||
|
<Box sx={{ pl: 2, mb: 2 }}>
|
||||||
|
<Typography variant="caption" sx={{ color: "rgba(255,255,255,0.6)", display: "block", mb: 0.5 }}>
|
||||||
|
• Specific topics or angles you want to explore
|
||||||
|
</Typography>
|
||||||
|
<Typography variant="caption" sx={{ color: "rgba(255,255,255,0.6)", display: "block", mb: 0.5 }}>
|
||||||
|
• Questions you want answered
|
||||||
|
</Typography>
|
||||||
|
<Typography variant="caption" sx={{ color: "rgba(255,255,255,0.6)", display: "block", mb: 0.5 }}>
|
||||||
|
• Areas where you need more depth
|
||||||
|
</Typography>
|
||||||
|
</Box>
|
||||||
|
<TextField
|
||||||
|
fullWidth
|
||||||
|
multiline
|
||||||
|
rows={4}
|
||||||
|
placeholder="e.g., I want to focus more on competitive landscape and pricing strategies. Also need stats on market growth in 2025..."
|
||||||
|
value={regenFeedback}
|
||||||
|
onChange={(e) => setRegenFeedback(e.target.value)}
|
||||||
|
sx={{
|
||||||
|
"& .MuiOutlinedInput-root": {
|
||||||
|
color: "#fff",
|
||||||
|
"& fieldset": { borderColor: "rgba(255,255,255,0.2)" },
|
||||||
|
"&:hover fieldset": { borderColor: "rgba(255,255,255,0.3)" },
|
||||||
|
"&.Mui-focused fieldset": { borderColor: "#a78bfa" },
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</DialogContent>
|
||||||
|
<DialogActions sx={{ px: 3, pb: 3 }}>
|
||||||
|
<SecondaryButton onClick={() => setShowRegenDialog(false)}>Cancel</SecondaryButton>
|
||||||
|
<PrimaryButton
|
||||||
|
onClick={handleRegenerate}
|
||||||
|
disabled={!regenFeedback.trim() || isRegenerating}
|
||||||
|
loading={isRegenerating}
|
||||||
|
startIcon={<RefreshIcon />}
|
||||||
|
>
|
||||||
|
Generate New Queries
|
||||||
|
</PrimaryButton>
|
||||||
|
</DialogActions>
|
||||||
|
</Dialog>
|
||||||
</GlassyCard>
|
</GlassyCard>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import React, { useMemo, useCallback } from "react";
|
import React, { useMemo, useCallback } from "react";
|
||||||
import { Stack, Typography, Chip, Divider, Box, alpha, Paper } from "@mui/material";
|
import { Stack, Typography, Chip, Divider, Box, alpha, Paper, Stepper, Step, StepLabel, CircularProgress } from "@mui/material";
|
||||||
import {
|
import {
|
||||||
Insights as InsightsIcon,
|
Insights as InsightsIcon,
|
||||||
Search as SearchIcon,
|
Search as SearchIcon,
|
||||||
@@ -7,21 +7,26 @@ import {
|
|||||||
EditNote as EditNoteIcon,
|
EditNote as EditNoteIcon,
|
||||||
Article as ArticleIcon,
|
Article as ArticleIcon,
|
||||||
AutoAwesome as AutoAwesomeIcon,
|
AutoAwesome as AutoAwesomeIcon,
|
||||||
|
ArrowForward as ArrowForwardIcon,
|
||||||
|
CheckCircle as CheckCircleIcon,
|
||||||
} from "@mui/icons-material";
|
} from "@mui/icons-material";
|
||||||
import { Research, ResearchInsight } from "../types";
|
import { Research, ResearchInsight } from "../types";
|
||||||
import { GlassyCard, glassyCardSx, PrimaryButton } from "../ui";
|
import { GlassyCard, glassyCardSx, PrimaryButton } from "../ui";
|
||||||
import { FactCard } from "../FactCard";
|
import { FactCard } from "../FactCard";
|
||||||
|
import { TextToSpeechButton } from "../../shared/TextToSpeechButton";
|
||||||
|
|
||||||
interface ResearchSummaryProps {
|
interface ResearchSummaryProps {
|
||||||
research: Research;
|
research: Research;
|
||||||
canGenerateScript: boolean;
|
canGenerateScript: boolean;
|
||||||
onGenerateScript: () => void;
|
onGenerateScript: () => void;
|
||||||
|
isGeneratingScript?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const ResearchSummary: React.FC<ResearchSummaryProps> = ({
|
export const ResearchSummary: React.FC<ResearchSummaryProps> = ({
|
||||||
research,
|
research,
|
||||||
canGenerateScript,
|
canGenerateScript,
|
||||||
onGenerateScript,
|
onGenerateScript,
|
||||||
|
isGeneratingScript = false,
|
||||||
}) => {
|
}) => {
|
||||||
// Simple markdown-to-HTML converter
|
// Simple markdown-to-HTML converter
|
||||||
const renderMarkdown = useCallback((text: string) => {
|
const renderMarkdown = useCallback((text: string) => {
|
||||||
@@ -51,6 +56,34 @@ export const ResearchSummary: React.FC<ResearchSummaryProps> = ({
|
|||||||
return (
|
return (
|
||||||
<GlassyCard sx={glassyCardSx}>
|
<GlassyCard sx={glassyCardSx}>
|
||||||
<Stack spacing={3}>
|
<Stack spacing={3}>
|
||||||
|
{/* Step Indicator */}
|
||||||
|
<Box sx={{ mb: 1 }}>
|
||||||
|
<Stepper activeStep={1} alternativeLabel>
|
||||||
|
<Step completed>
|
||||||
|
<StepLabel
|
||||||
|
StepIconComponent={() => <CheckCircleIcon sx={{ color: "#22c55e", fontSize: 24 }} />}
|
||||||
|
>
|
||||||
|
Analysis
|
||||||
|
</StepLabel>
|
||||||
|
</Step>
|
||||||
|
<Step active>
|
||||||
|
<StepLabel>
|
||||||
|
Research
|
||||||
|
</StepLabel>
|
||||||
|
</Step>
|
||||||
|
<Step>
|
||||||
|
<StepLabel>
|
||||||
|
Script
|
||||||
|
</StepLabel>
|
||||||
|
</Step>
|
||||||
|
<Step>
|
||||||
|
<StepLabel>
|
||||||
|
Render
|
||||||
|
</StepLabel>
|
||||||
|
</Step>
|
||||||
|
</Stepper>
|
||||||
|
</Box>
|
||||||
|
|
||||||
<Stack direction="row" justifyContent="space-between" alignItems="center" flexWrap="wrap" gap={2}>
|
<Stack direction="row" justifyContent="space-between" alignItems="center" flexWrap="wrap" gap={2}>
|
||||||
<Stack direction="row" alignItems="center" spacing={2} sx={{ flex: 1 }}>
|
<Stack direction="row" alignItems="center" spacing={2} sx={{ flex: 1 }}>
|
||||||
<Typography variant="h6" sx={{ display: "flex", alignItems: "center", gap: 1, color: "#0f172a", fontWeight: 700 }}>
|
<Typography variant="h6" sx={{ display: "flex", alignItems: "center", gap: 1, color: "#0f172a", fontWeight: 700 }}>
|
||||||
@@ -115,11 +148,31 @@ export const ResearchSummary: React.FC<ResearchSummaryProps> = ({
|
|||||||
|
|
||||||
<PrimaryButton
|
<PrimaryButton
|
||||||
onClick={onGenerateScript}
|
onClick={onGenerateScript}
|
||||||
disabled={!canGenerateScript}
|
disabled={!canGenerateScript || isGeneratingScript}
|
||||||
startIcon={<EditNoteIcon />}
|
startIcon={isGeneratingScript ? <CircularProgress size={18} color="inherit" /> : <EditNoteIcon />}
|
||||||
|
endIcon={isGeneratingScript ? undefined : <ArrowForwardIcon />}
|
||||||
tooltip={!canGenerateScript ? "Complete research to generate script" : "Generate AI-powered script from research"}
|
tooltip={!canGenerateScript ? "Complete research to generate script" : "Generate AI-powered script from research"}
|
||||||
|
sx={{
|
||||||
|
background: "linear-gradient(135deg, #667eea 0%, #764ba2 100%)",
|
||||||
|
color: "#fff",
|
||||||
|
fontWeight: 700,
|
||||||
|
fontSize: "1rem",
|
||||||
|
px: 4,
|
||||||
|
py: 1.5,
|
||||||
|
borderRadius: 2,
|
||||||
|
textTransform: "none",
|
||||||
|
boxShadow: "0 4px 14px rgba(102, 126, 234, 0.4)",
|
||||||
|
"&:hover": {
|
||||||
|
background: "linear-gradient(135deg, #764ba2 0%, #667eea 100%)",
|
||||||
|
boxShadow: "0 6px 20px rgba(102, 126, 234, 0.5)",
|
||||||
|
},
|
||||||
|
"&:disabled": {
|
||||||
|
background: "#94a3b8",
|
||||||
|
boxShadow: "none",
|
||||||
|
}
|
||||||
|
}}
|
||||||
>
|
>
|
||||||
Generate Script
|
{isGeneratingScript ? "Generating Script..." : "Generate Script to Continue"}
|
||||||
</PrimaryButton>
|
</PrimaryButton>
|
||||||
</Stack>
|
</Stack>
|
||||||
|
|
||||||
@@ -139,6 +192,9 @@ export const ResearchSummary: React.FC<ResearchSummaryProps> = ({
|
|||||||
<Typography variant="subtitle2" sx={{ mb: 1.5, color: "#64748b", fontWeight: 700, fontSize: "0.75rem", textTransform: "uppercase", letterSpacing: "0.05em", display: "flex", alignItems: "center", gap: 1 }}>
|
<Typography variant="subtitle2" sx={{ mb: 1.5, color: "#64748b", fontWeight: 700, fontSize: "0.75rem", textTransform: "uppercase", letterSpacing: "0.05em", display: "flex", alignItems: "center", gap: 1 }}>
|
||||||
<AutoAwesomeIcon fontSize="small" sx={{ color: "#667eea", fontSize: "1rem" }} />
|
<AutoAwesomeIcon fontSize="small" sx={{ color: "#667eea", fontSize: "1rem" }} />
|
||||||
Executive Summary
|
Executive Summary
|
||||||
|
<Box sx={{ ml: 'auto' }}>
|
||||||
|
<TextToSpeechButton text={research.summary} size="small" showSettings />
|
||||||
|
</Box>
|
||||||
</Typography>
|
</Typography>
|
||||||
<Box sx={{
|
<Box sx={{
|
||||||
lineHeight: 1.6,
|
lineHeight: 1.6,
|
||||||
|
|||||||
@@ -5,6 +5,9 @@ import { useBudgetTracking } from "../../../hooks/useBudgetTracking";
|
|||||||
import { CreateProjectPayload, Script } from "../types";
|
import { CreateProjectPayload, Script } from "../types";
|
||||||
import { usePodcastProjectState } from "../../../hooks/usePodcastProjectState";
|
import { usePodcastProjectState } from "../../../hooks/usePodcastProjectState";
|
||||||
import { sanitizeExaConfig, announceError, getStepLabel } from "./utils";
|
import { sanitizeExaConfig, announceError, getStepLabel } from "./utils";
|
||||||
|
import { clearSceneMediaCache, clearMediaCache } from "../../../utils/mediaCache";
|
||||||
|
|
||||||
|
const createId = (prefix: string) => `${prefix}_${Date.now()}_${Math.random().toString(36).slice(2, 9)}`;
|
||||||
|
|
||||||
type PodcastProjectStateReturn = ReturnType<typeof usePodcastProjectState>;
|
type PodcastProjectStateReturn = ReturnType<typeof usePodcastProjectState>;
|
||||||
|
|
||||||
@@ -41,18 +44,22 @@ export const usePodcastWorkflow = ({ projectState, onError }: UsePodcastWorkflow
|
|||||||
setResearchProvider,
|
setResearchProvider,
|
||||||
setBudgetCap,
|
setBudgetCap,
|
||||||
updateRenderJob,
|
updateRenderJob,
|
||||||
|
setRenderJobs,
|
||||||
initializeProject,
|
initializeProject,
|
||||||
setBible,
|
setBible,
|
||||||
} = projectState;
|
} = projectState;
|
||||||
|
|
||||||
const [isAnalyzing, setIsAnalyzing] = useState(false);
|
const [isAnalyzing, setIsAnalyzing] = useState(false);
|
||||||
const [isResearching, setIsResearching] = useState(false);
|
const [isResearching, setIsResearching] = useState(false);
|
||||||
|
const [isGeneratingScript, setIsGeneratingScript] = useState(false);
|
||||||
const [announcement, setAnnouncement] = useState("");
|
const [announcement, setAnnouncement] = useState("");
|
||||||
const [announcementSeverity, setAnnouncementSeverity] = useState<"info" | "error" | "success">("info");
|
const [announcementSeverity, setAnnouncementSeverity] = useState<"info" | "error" | "success">("info");
|
||||||
const [showResumeAlert, setShowResumeAlert] = useState(false);
|
const [showResumeAlert, setShowResumeAlert] = useState(false);
|
||||||
const [showPreflightDialog, setShowPreflightDialog] = useState(false);
|
const [showPreflightDialog, setShowPreflightDialog] = useState(false);
|
||||||
const [preflightResponse, setPreflightResponse] = useState<any>(null);
|
const [preflightResponse, setPreflightResponse] = useState<any>(null);
|
||||||
const [preflightOperationName, setPreflightOperationName] = useState<string>("");
|
const [preflightOperationName, setPreflightOperationName] = useState<string>("");
|
||||||
|
const [showDuplicateDialog, setShowDuplicateDialog] = useState(false);
|
||||||
|
const [duplicateProjectInfo, setDuplicateProjectInfo] = useState<{projectId: string; idea: string}>({ projectId: "", idea: "" });
|
||||||
|
|
||||||
const budgetTracking = useBudgetTracking(budgetCap || 50);
|
const budgetTracking = useBudgetTracking(budgetCap || 50);
|
||||||
const preflightCheck = usePreflightCheck({
|
const preflightCheck = usePreflightCheck({
|
||||||
@@ -113,7 +120,27 @@ export const usePodcastWorkflow = ({ projectState, onError }: UsePodcastWorkflow
|
|||||||
// This allows the analysis to be personalized using the Bible context
|
// This allows the analysis to be personalized using the Bible context
|
||||||
const projectId = project?.id || `podcast_${Date.now()}_${Math.floor(Math.random() * 1000)}`;
|
const projectId = project?.id || `podcast_${Date.now()}_${Math.floor(Math.random() * 1000)}`;
|
||||||
setAnnouncement("Initializing project and brand context...");
|
setAnnouncement("Initializing project and brand context...");
|
||||||
const dbProject = project ? null : await initializeProject(payload, projectId, avatarUrl);
|
|
||||||
|
let dbProject: any = null;
|
||||||
|
try {
|
||||||
|
dbProject = project ? null : await initializeProject(payload, projectId, avatarUrl);
|
||||||
|
} catch (initError: any) {
|
||||||
|
const errorStr = initError?.message || "";
|
||||||
|
if (errorStr.includes("DUPLICATE_IDEA")) {
|
||||||
|
try {
|
||||||
|
const dupData = JSON.parse(errorStr);
|
||||||
|
const existingId = dupData.existing_project_id;
|
||||||
|
const existingIdea = dupData.existing_idea;
|
||||||
|
setAnnouncement("");
|
||||||
|
// Throw error to trigger UI modal
|
||||||
|
throw new Error(`DUPLICATE_IDEA:${existingId}:${existingIdea}`);
|
||||||
|
} catch (parseErr) {
|
||||||
|
console.error("Failed to parse duplicate idea error:", parseErr);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
throw initError;
|
||||||
|
}
|
||||||
|
|
||||||
const bible = dbProject?.bible || projectState.bible;
|
const bible = dbProject?.bible || projectState.bible;
|
||||||
|
|
||||||
setAnnouncement(feedback ? "Regenerating analysis using your feedback..." : "Analyzing your idea — AI suggestions incoming");
|
setAnnouncement(feedback ? "Regenerating analysis using your feedback..." : "Analyzing your idea — AI suggestions incoming");
|
||||||
@@ -131,7 +158,7 @@ export const usePodcastWorkflow = ({ projectState, onError }: UsePodcastWorkflow
|
|||||||
analysis: result.analysis,
|
analysis: result.analysis,
|
||||||
estimate: result.estimate,
|
estimate: result.estimate,
|
||||||
queries: result.queries,
|
queries: result.queries,
|
||||||
selected_queries: result.queries.map(q => q.id),
|
selected_queries: [], // Don't auto-select - user must choose manually
|
||||||
avatar_url: result.avatar_url,
|
avatar_url: result.avatar_url,
|
||||||
avatar_prompt: result.avatar_prompt,
|
avatar_prompt: result.avatar_prompt,
|
||||||
});
|
});
|
||||||
@@ -152,7 +179,7 @@ export const usePodcastWorkflow = ({ projectState, onError }: UsePodcastWorkflow
|
|||||||
setAnalysis(result.analysis);
|
setAnalysis(result.analysis);
|
||||||
setEstimate(result.estimate);
|
setEstimate(result.estimate);
|
||||||
setQueries(result.queries);
|
setQueries(result.queries);
|
||||||
setSelectedQueries(new Set(result.queries.map((q) => q.id)));
|
setSelectedQueries(new Set()); // Start with none selected - user must choose manually
|
||||||
setKnobs(payload.knobs);
|
setKnobs(payload.knobs);
|
||||||
setBudgetCap(payload.budgetCap);
|
setBudgetCap(payload.budgetCap);
|
||||||
|
|
||||||
@@ -192,6 +219,18 @@ export const usePodcastWorkflow = ({ projectState, onError }: UsePodcastWorkflow
|
|||||||
setAnnouncement("Analysis complete");
|
setAnnouncement("Analysis complete");
|
||||||
}
|
}
|
||||||
} catch (error: any) {
|
} catch (error: any) {
|
||||||
|
// Handle duplicate idea error
|
||||||
|
const errorMessage = error?.message || String(error);
|
||||||
|
if (errorMessage.startsWith("DUPLICATE_IDEA:")) {
|
||||||
|
const parts = errorMessage.split(":");
|
||||||
|
const existingId = parts[1] || "";
|
||||||
|
const existingIdea = parts.slice(2).join(":") || "existing project";
|
||||||
|
setAnnouncement("");
|
||||||
|
setShowDuplicateDialog(true);
|
||||||
|
setDuplicateProjectInfo({ projectId: existingId, idea: existingIdea });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (error?.response?.status === 429 || error?.response?.data?.detail) {
|
if (error?.response?.status === 429 || error?.response?.data?.detail) {
|
||||||
const errorDetail = error.response.data.detail;
|
const errorDetail = error.response.data.detail;
|
||||||
if (typeof errorDetail === 'object' && errorDetail.error && errorDetail.error.includes('limit')) {
|
if (typeof errorDetail === 'object' && errorDetail.error && errorDetail.error.includes('limit')) {
|
||||||
@@ -240,6 +279,8 @@ export const usePodcastWorkflow = ({ projectState, onError }: UsePodcastWorkflow
|
|||||||
|
|
||||||
setPreflightOperationName("Research");
|
setPreflightOperationName("Research");
|
||||||
const approvedQueries = queries.filter((q) => selectedQueries.has(q.id));
|
const approvedQueries = queries.filter((q) => selectedQueries.has(q.id));
|
||||||
|
console.log('[Research] User selected queries:', Array.from(selectedQueries));
|
||||||
|
console.log('[Research] Filtered approvedQueries for API:', approvedQueries.map(q => q.query));
|
||||||
const preflightResult = await preflightCheck.check({
|
const preflightResult = await preflightCheck.check({
|
||||||
provider: researchProvider === "exa" ? "exa" : "gemini",
|
provider: researchProvider === "exa" ? "exa" : "gemini",
|
||||||
operation_type: researchProvider === "exa" ? "exa_neural_search" : "google_grounding",
|
operation_type: researchProvider === "exa" ? "exa_neural_search" : "google_grounding",
|
||||||
@@ -261,6 +302,8 @@ export const usePodcastWorkflow = ({ projectState, onError }: UsePodcastWorkflow
|
|||||||
setShowRenderQueue(false);
|
setShowRenderQueue(false);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
console.log('[Research] Starting research with:', { topic: project.idea, approvedQueries, provider: researchProvider });
|
||||||
|
console.log('[Research] Calling podcastApi.runResearch...');
|
||||||
const { research: mapped, raw } = await podcastApi.runResearch({
|
const { research: mapped, raw } = await podcastApi.runResearch({
|
||||||
projectId: project.id,
|
projectId: project.id,
|
||||||
topic: project.idea,
|
topic: project.idea,
|
||||||
@@ -273,6 +316,7 @@ export const usePodcastWorkflow = ({ projectState, onError }: UsePodcastWorkflow
|
|||||||
setAnnouncement(message);
|
setAnnouncement(message);
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
console.log('[Research] Response received:', { mapped, raw });
|
||||||
setResearch(mapped);
|
setResearch(mapped);
|
||||||
setRawResearch(raw);
|
setRawResearch(raw);
|
||||||
setAnnouncement("Research complete — review fact cards below");
|
setAnnouncement("Research complete — review fact cards below");
|
||||||
@@ -281,6 +325,7 @@ export const usePodcastWorkflow = ({ projectState, onError }: UsePodcastWorkflow
|
|||||||
? researchError.message
|
? researchError.message
|
||||||
: "Research failed. Please try again or switch to Standard Research.";
|
: "Research failed. Please try again or switch to Standard Research.";
|
||||||
|
|
||||||
|
console.error('[Research] Error caught:', researchError);
|
||||||
if (errorMessage.includes("Exa") || errorMessage.includes("exa")) {
|
if (errorMessage.includes("Exa") || errorMessage.includes("exa")) {
|
||||||
setAnnouncement(`Deep research failed: ${errorMessage}. Try Standard Research instead.`);
|
setAnnouncement(`Deep research failed: ${errorMessage}. Try Standard Research instead.`);
|
||||||
} else if (errorMessage.includes("timeout")) {
|
} else if (errorMessage.includes("timeout")) {
|
||||||
@@ -321,8 +366,18 @@ export const usePodcastWorkflow = ({ projectState, onError }: UsePodcastWorkflow
|
|||||||
setScriptData(null);
|
setScriptData(null);
|
||||||
setShowRenderQueue(false);
|
setShowRenderQueue(false);
|
||||||
setShowScriptEditor(true);
|
setShowScriptEditor(true);
|
||||||
|
setIsGeneratingScript(true);
|
||||||
|
setAnnouncement("Generating script with AI... Creating scenes and dialogue based on your research...");
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
console.log('[ScriptGen] Starting script generation with:', {
|
||||||
|
idea: project.idea,
|
||||||
|
speakers: project.speakers,
|
||||||
|
duration: project.duration,
|
||||||
|
hasResearch: !!rawResearch,
|
||||||
|
hasOutline: !!analysis?.suggestedOutlines?.[0],
|
||||||
|
});
|
||||||
|
|
||||||
const result = await podcastApi.generateScript({
|
const result = await podcastApi.generateScript({
|
||||||
projectId: project.id,
|
projectId: project.id,
|
||||||
idea: project.idea,
|
idea: project.idea,
|
||||||
@@ -331,35 +386,55 @@ export const usePodcastWorkflow = ({ projectState, onError }: UsePodcastWorkflow
|
|||||||
speakers: project.speakers,
|
speakers: project.speakers,
|
||||||
durationMinutes: project.duration,
|
durationMinutes: project.duration,
|
||||||
bible: projectState.bible,
|
bible: projectState.bible,
|
||||||
outline: analysis?.suggestedOutlines?.[0], // Pass the first (possibly refined) outline
|
outline: analysis?.suggestedOutlines?.[0],
|
||||||
analysis: analysis, // Pass full analysis context
|
analysis: analysis,
|
||||||
|
onProgress: (message) => {
|
||||||
|
console.log('[ScriptGen] Progress:', message);
|
||||||
|
setAnnouncement(message);
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
console.log('[ScriptGen] Script generated:', { sceneCount: result.scenes?.length });
|
||||||
setScriptData(result);
|
setScriptData(result);
|
||||||
|
setIsGeneratingScript(false);
|
||||||
|
setAnnouncement("Script generated! Review and edit your scenes below.");
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
setIsGeneratingScript(false);
|
||||||
announceError(setAnnouncement, setAnnouncementSeverityFn, error);
|
announceError(setAnnouncement, setAnnouncementSeverityFn, error);
|
||||||
}
|
}
|
||||||
}, [showScriptEditor, project, research, preflightCheck, setScriptData, setShowRenderQueue, setShowScriptEditor, rawResearch, projectState.knobs, projectState.bible])
|
}, [showScriptEditor, project, research, preflightCheck, setScriptData, setShowRenderQueue, setShowScriptEditor, rawResearch, projectState.knobs, projectState.bible])
|
||||||
|
|
||||||
const handleProceedToRendering = useCallback((script: Script) => {
|
const handleProceedToRendering = useCallback((script: Script) => {
|
||||||
|
// Clear media cache for all scenes before proceeding to remove old blobs
|
||||||
|
script.scenes.forEach((scene) => {
|
||||||
|
clearSceneMediaCache(scene.id);
|
||||||
|
});
|
||||||
|
// Also clear global media cache to ensure clean slate
|
||||||
|
clearMediaCache();
|
||||||
|
|
||||||
|
// Clear all render jobs to start fresh (removes old videos/images)
|
||||||
|
setRenderJobs([]);
|
||||||
|
|
||||||
setScriptData(script);
|
setScriptData(script);
|
||||||
if (renderJobs.length === 0) {
|
// Create new render jobs with current script scene data
|
||||||
script.scenes.forEach((scene) => {
|
script.scenes.forEach((scene) => {
|
||||||
const hasExistingAudio = Boolean(scene.audioUrl);
|
const hasExistingAudio = Boolean(scene.audioUrl);
|
||||||
updateRenderJob(scene.id, {
|
const hasExistingImage = Boolean(scene.imageUrl);
|
||||||
sceneId: scene.id,
|
updateRenderJob(scene.id, {
|
||||||
title: scene.title,
|
sceneId: scene.id,
|
||||||
status: hasExistingAudio ? ("completed" as const) : ("idle" as const),
|
title: scene.title,
|
||||||
progress: hasExistingAudio ? 100 : 0,
|
status: hasExistingAudio ? ("completed" as const) : ("idle" as const),
|
||||||
previewUrl: null,
|
progress: hasExistingAudio ? 100 : 0,
|
||||||
finalUrl: hasExistingAudio ? scene.audioUrl : null,
|
previewUrl: null,
|
||||||
jobId: null,
|
finalUrl: hasExistingAudio ? scene.audioUrl : null,
|
||||||
});
|
imageUrl: hasExistingImage ? scene.imageUrl : null,
|
||||||
|
videoUrl: null,
|
||||||
|
jobId: null,
|
||||||
});
|
});
|
||||||
}
|
});
|
||||||
setShowRenderQueue(true);
|
setShowRenderQueue(true);
|
||||||
setShowScriptEditor(false);
|
setShowScriptEditor(false);
|
||||||
}, [renderJobs.length, setScriptData, updateRenderJob, setShowRenderQueue, setShowScriptEditor]);
|
}, [setScriptData, setRenderJobs, updateRenderJob, setShowRenderQueue, setShowScriptEditor]);
|
||||||
|
|
||||||
const toggleQuery = useCallback((id: string) => {
|
const toggleQuery = useCallback((id: string) => {
|
||||||
if (isResearching) return;
|
if (isResearching) return;
|
||||||
@@ -370,6 +445,22 @@ export const usePodcastWorkflow = ({ projectState, onError }: UsePodcastWorkflow
|
|||||||
setSelectedQueries(next);
|
setSelectedQueries(next);
|
||||||
}, [isResearching, selectedQueries, setSelectedQueries]);
|
}, [isResearching, selectedQueries, setSelectedQueries]);
|
||||||
|
|
||||||
|
const handleUpdateQuery = useCallback((id: string, newQuery: string, newRationale: string) => {
|
||||||
|
const updated = queries.map(q => q.id === id ? { ...q, query: newQuery, rationale: newRationale } : q);
|
||||||
|
setQueries(updated);
|
||||||
|
}, [queries, setQueries]);
|
||||||
|
|
||||||
|
const handleDeleteQuery = useCallback((id: string) => {
|
||||||
|
const updated = queries.filter(q => q.id !== id);
|
||||||
|
setQueries(updated);
|
||||||
|
// Also remove from selected if it was selected
|
||||||
|
if (selectedQueries.has(id)) {
|
||||||
|
const newSelected = new Set(selectedQueries);
|
||||||
|
newSelected.delete(id);
|
||||||
|
setSelectedQueries(newSelected);
|
||||||
|
}
|
||||||
|
}, [queries, selectedQueries, setQueries, setSelectedQueries]);
|
||||||
|
|
||||||
const activeStep = useMemo(() => {
|
const activeStep = useMemo(() => {
|
||||||
if (showRenderQueue) return 3;
|
if (showRenderQueue) return 3;
|
||||||
if (showScriptEditor) return 2;
|
if (showScriptEditor) return 2;
|
||||||
@@ -397,6 +488,37 @@ export const usePodcastWorkflow = ({ projectState, onError }: UsePodcastWorkflow
|
|||||||
await handleCreate(payload, feedback);
|
await handleCreate(payload, feedback);
|
||||||
}, [project, projectState.knobs, projectState.budgetCap, handleCreate]);
|
}, [project, projectState.knobs, projectState.budgetCap, handleCreate]);
|
||||||
|
|
||||||
|
// Regenerate only research queries (keeps other sections intact)
|
||||||
|
const handleRegenerateQueries = useCallback(async (feedback: string) => {
|
||||||
|
if (!project || !analysis) return;
|
||||||
|
|
||||||
|
setAnnouncement("Regenerating research queries...");
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await podcastApi.regenerateResearchQueries({
|
||||||
|
idea: project.idea,
|
||||||
|
feedback: feedback,
|
||||||
|
existing_analysis: analysis,
|
||||||
|
bible: projectState.bible,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Convert to Query format
|
||||||
|
const newQueries = response.research_queries.map((rq, idx) => ({
|
||||||
|
id: createId("q"),
|
||||||
|
query: rq.query,
|
||||||
|
rationale: rq.rationale,
|
||||||
|
needsRecentStats: /202[45]|latest|trend/i.test(rq.query),
|
||||||
|
}));
|
||||||
|
|
||||||
|
setQueries(newQueries);
|
||||||
|
setSelectedQueries(new Set()); // Don't auto-select - user must choose manually
|
||||||
|
setAnnouncement("Research queries regenerated");
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Failed to regenerate queries:", error);
|
||||||
|
setAnnouncement("Failed to regenerate queries");
|
||||||
|
}
|
||||||
|
}, [project, analysis, projectState.bible, setQueries, setSelectedQueries]);
|
||||||
|
|
||||||
const setAnnouncementSeverityFn = useCallback((severity: "info" | "error" | "success") => {
|
const setAnnouncementSeverityFn = useCallback((severity: "info" | "error" | "success") => {
|
||||||
setAnnouncementSeverity(severity);
|
setAnnouncementSeverity(severity);
|
||||||
}, []);
|
}, []);
|
||||||
@@ -405,12 +527,15 @@ export const usePodcastWorkflow = ({ projectState, onError }: UsePodcastWorkflow
|
|||||||
// State
|
// State
|
||||||
isAnalyzing,
|
isAnalyzing,
|
||||||
isResearching,
|
isResearching,
|
||||||
|
isGeneratingScript,
|
||||||
announcement,
|
announcement,
|
||||||
announcementSeverity,
|
announcementSeverity,
|
||||||
showResumeAlert,
|
showResumeAlert,
|
||||||
showPreflightDialog,
|
showPreflightDialog,
|
||||||
preflightResponse,
|
preflightResponse,
|
||||||
preflightOperationName,
|
preflightOperationName,
|
||||||
|
showDuplicateDialog,
|
||||||
|
duplicateProjectInfo,
|
||||||
activeStep,
|
activeStep,
|
||||||
canGenerateScript,
|
canGenerateScript,
|
||||||
// Handlers
|
// Handlers
|
||||||
@@ -425,8 +550,13 @@ export const usePodcastWorkflow = ({ projectState, onError }: UsePodcastWorkflow
|
|||||||
setShowResumeAlert,
|
setShowResumeAlert,
|
||||||
setShowPreflightDialog,
|
setShowPreflightDialog,
|
||||||
setPreflightResponse,
|
setPreflightResponse,
|
||||||
|
setShowDuplicateDialog,
|
||||||
|
setDuplicateProjectInfo,
|
||||||
setResearchProvider,
|
setResearchProvider,
|
||||||
getStepLabel,
|
getStepLabel,
|
||||||
|
handleRegenerateQueries: handleRegenerateQueries,
|
||||||
|
handleUpdateQuery,
|
||||||
|
handleDeleteQuery,
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ import { CreateProjectPayload, Knobs } from "../types";
|
|||||||
export const DEFAULT_KNOBS: Knobs = {
|
export const DEFAULT_KNOBS: Knobs = {
|
||||||
voice_emotion: "neutral",
|
voice_emotion: "neutral",
|
||||||
voice_speed: 1,
|
voice_speed: 1,
|
||||||
|
voice_id: "Wise_Woman",
|
||||||
|
custom_voice_id: undefined,
|
||||||
resolution: "720p",
|
resolution: "720p",
|
||||||
scene_length_target: 45,
|
scene_length_target: 45,
|
||||||
sample_rate: 24000,
|
sample_rate: 24000,
|
||||||
|
|||||||
@@ -22,10 +22,12 @@ import {
|
|||||||
Mic as MicIcon,
|
Mic as MicIcon,
|
||||||
PlayArrow as PlayArrowIcon,
|
PlayArrow as PlayArrowIcon,
|
||||||
Delete as DeleteIcon,
|
Delete as DeleteIcon,
|
||||||
|
Edit as EditIcon,
|
||||||
Star as StarIcon,
|
Star as StarIcon,
|
||||||
StarBorder as StarBorderIcon,
|
StarBorder as StarBorderIcon,
|
||||||
Refresh as RefreshIcon,
|
Refresh as RefreshIcon,
|
||||||
Search as SearchIcon,
|
Search as SearchIcon,
|
||||||
|
ArrowBack as ArrowBackIcon,
|
||||||
} from "@mui/icons-material";
|
} from "@mui/icons-material";
|
||||||
import { podcastApi } from "../../services/podcastApi";
|
import { podcastApi } from "../../services/podcastApi";
|
||||||
import { GlassyCard, glassyCardSx, PrimaryButton, SecondaryButton } from "./ui";
|
import { GlassyCard, glassyCardSx, PrimaryButton, SecondaryButton } from "./ui";
|
||||||
@@ -45,9 +47,10 @@ interface Project {
|
|||||||
|
|
||||||
interface ProjectListProps {
|
interface ProjectListProps {
|
||||||
onSelectProject: (projectId: string) => void;
|
onSelectProject: (projectId: string) => void;
|
||||||
|
onBack?: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const ProjectList: React.FC<ProjectListProps> = ({ onSelectProject }) => {
|
export const ProjectList: React.FC<ProjectListProps> = ({ onSelectProject, onBack }) => {
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const [projects, setProjects] = useState<Project[]>([]);
|
const [projects, setProjects] = useState<Project[]>([]);
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
@@ -175,6 +178,9 @@ export const ProjectList: React.FC<ProjectListProps> = ({ onSelectProject }) =>
|
|||||||
</Typography>
|
</Typography>
|
||||||
</Box>
|
</Box>
|
||||||
<Stack direction="row" spacing={1}>
|
<Stack direction="row" spacing={1}>
|
||||||
|
<SecondaryButton onClick={onBack || (() => navigate(-1))} startIcon={<ArrowBackIcon />}>
|
||||||
|
Back
|
||||||
|
</SecondaryButton>
|
||||||
<SecondaryButton onClick={loadProjects} startIcon={<RefreshIcon />} disabled={loading}>
|
<SecondaryButton onClick={loadProjects} startIcon={<RefreshIcon />} disabled={loading}>
|
||||||
Refresh
|
Refresh
|
||||||
</SecondaryButton>
|
</SecondaryButton>
|
||||||
@@ -248,7 +254,7 @@ export const ProjectList: React.FC<ProjectListProps> = ({ onSelectProject }) =>
|
|||||||
>
|
>
|
||||||
<Stack spacing={2}>
|
<Stack spacing={2}>
|
||||||
<Stack direction="row" justifyContent="space-between" alignItems="flex-start">
|
<Stack direction="row" justifyContent="space-between" alignItems="flex-start">
|
||||||
<Box flex={1}>
|
<Box flex={1} onClick={() => onSelectProject(project.project_id)} sx={{ cursor: "pointer" }}>
|
||||||
<Typography variant="h6" sx={{ mb: 1 }}>
|
<Typography variant="h6" sx={{ mb: 1 }}>
|
||||||
{project.idea.length > 100 ? `${project.idea.substring(0, 100)}...` : project.idea}
|
{project.idea.length > 100 ? `${project.idea.substring(0, 100)}...` : project.idea}
|
||||||
</Typography>
|
</Typography>
|
||||||
@@ -270,14 +276,25 @@ export const ProjectList: React.FC<ProjectListProps> = ({ onSelectProject }) =>
|
|||||||
</Typography>
|
</Typography>
|
||||||
</Stack>
|
</Stack>
|
||||||
</Box>
|
</Box>
|
||||||
<Stack direction="row" spacing={1}>
|
<Stack direction="row" spacing={0.5}>
|
||||||
|
<Tooltip title="Edit project">
|
||||||
|
<IconButton
|
||||||
|
onClick={(e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
onSelectProject(project.project_id);
|
||||||
|
}}
|
||||||
|
sx={{ color: "#a78bfa" }}
|
||||||
|
>
|
||||||
|
<EditIcon />
|
||||||
|
</IconButton>
|
||||||
|
</Tooltip>
|
||||||
<Tooltip title={project.is_favorite ? "Remove from favorites" : "Add to favorites"}>
|
<Tooltip title={project.is_favorite ? "Remove from favorites" : "Add to favorites"}>
|
||||||
<IconButton
|
<IconButton
|
||||||
onClick={(e) => {
|
onClick={(e) => {
|
||||||
e.stopPropagation();
|
e.stopPropagation();
|
||||||
handleToggleFavorite(project.project_id, project.is_favorite);
|
handleToggleFavorite(project.project_id, project.is_favorite);
|
||||||
}}
|
}}
|
||||||
sx={{ color: project.is_favorite ? "#fbbf24" : "rgba(255,255,255,0.5)" }}
|
sx={{ color: project.is_favorite ? "#fbbf24" : "#a78bfa" }}
|
||||||
>
|
>
|
||||||
{project.is_favorite ? <StarIcon /> : <StarBorderIcon />}
|
{project.is_favorite ? <StarIcon /> : <StarBorderIcon />}
|
||||||
</IconButton>
|
</IconButton>
|
||||||
@@ -289,7 +306,7 @@ export const ProjectList: React.FC<ProjectListProps> = ({ onSelectProject }) =>
|
|||||||
setProjectToDelete(project.project_id);
|
setProjectToDelete(project.project_id);
|
||||||
setDeleteDialogOpen(true);
|
setDeleteDialogOpen(true);
|
||||||
}}
|
}}
|
||||||
sx={{ color: "rgba(255,255,255,0.5)" }}
|
sx={{ color: "#ef4444" }}
|
||||||
>
|
>
|
||||||
<DeleteIcon />
|
<DeleteIcon />
|
||||||
</IconButton>
|
</IconButton>
|
||||||
|
|||||||
@@ -63,6 +63,7 @@ export const RenderQueue: React.FC<RenderQueueProps> = ({
|
|||||||
knobs,
|
knobs,
|
||||||
projectId,
|
projectId,
|
||||||
bible,
|
bible,
|
||||||
|
analysis,
|
||||||
budgetCap,
|
budgetCap,
|
||||||
avatarImageUrl,
|
avatarImageUrl,
|
||||||
onUpdateJob,
|
onUpdateJob,
|
||||||
|
|||||||
@@ -46,33 +46,39 @@ export const VideoRegenerateModal: React.FC<VideoRegenerateModalProps> = ({
|
|||||||
// Use a more intelligent default prompt based on context if available
|
// Use a more intelligent default prompt based on context if available
|
||||||
const [prompt, setPrompt] = useState(initialPrompt);
|
const [prompt, setPrompt] = useState(initialPrompt);
|
||||||
|
|
||||||
// Update prompt when context changes or modal opens
|
// Update prompt when modal opens - build enhanced prompt from context
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (open) {
|
if (open) {
|
||||||
let smartPrompt = initialPrompt;
|
// Always build an enhanced prompt from available context
|
||||||
|
const parts = [];
|
||||||
|
|
||||||
// If the initial prompt is generic/empty, try to build a better one
|
// Add scene context
|
||||||
if (!smartPrompt || smartPrompt === "Professional podcast scene with subtle movement") {
|
if (sceneTitle) parts.push(`Scene: ${sceneTitle}`);
|
||||||
const parts = [];
|
|
||||||
|
// Add bible/persona context
|
||||||
// Add scene context
|
if (bible?.host_persona) parts.push(`Host Persona: ${bible.host_persona}`);
|
||||||
if (sceneTitle) parts.push(`Scene: ${sceneTitle}`);
|
if (bible?.tone) parts.push(`Tone: ${bible.tone}`);
|
||||||
|
if (bible?.visual_style) parts.push(`Visual Style: ${bible.visual_style}`);
|
||||||
// Add bible/persona context
|
if (bible?.background) parts.push(`Background: ${bible.background}`);
|
||||||
if (bible?.host_persona) parts.push(`Host Persona: ${bible.host_persona}`);
|
|
||||||
if (bible?.tone) parts.push(`Tone: ${bible.tone}`);
|
// Add analysis context
|
||||||
|
if (analysis?.content_type) parts.push(`Content Type: ${analysis.content_type}`);
|
||||||
// Add analysis context
|
if (analysis?.audience) parts.push(`Target: ${analysis.audience}`);
|
||||||
if (analysis?.content_type) parts.push(`Style: ${analysis.content_type}`);
|
if (analysis?.guestName) parts.push(`Guest: ${analysis.guestName}`);
|
||||||
|
if (analysis?.keyTakeaways?.length) parts.push(`Key: ${analysis.keyTakeaways[0]}`);
|
||||||
// Combine into a descriptive prompt
|
|
||||||
if (parts.length > 0) {
|
// Build enhanced prompt
|
||||||
smartPrompt = `Professional talking head video for podcast. ${parts.join(". ")}. Cinematic lighting, 4k, high detail.`;
|
let smartPrompt = "";
|
||||||
}
|
if (parts.length > 0) {
|
||||||
|
smartPrompt = `Professional podcast video. ${parts.join(". ")}. Cinematic lighting, high detail, 4k quality, smooth subtle motion.`;
|
||||||
|
} else {
|
||||||
|
// Fallback to initial prompt
|
||||||
|
smartPrompt = initialPrompt || "Professional podcast scene with subtle movement";
|
||||||
}
|
}
|
||||||
|
|
||||||
setPrompt(smartPrompt);
|
setPrompt(smartPrompt);
|
||||||
}
|
}
|
||||||
}, [open, initialPrompt, sceneTitle, bible, analysis]);
|
}, [open, sceneTitle, bible, analysis]);
|
||||||
|
|
||||||
const [resolution, setResolution] = useState<"480p" | "720p">(initialResolution);
|
const [resolution, setResolution] = useState<"480p" | "720p">(initialResolution);
|
||||||
const [seed, setSeed] = useState<string>(initialSeed != null && initialSeed !== -1 ? String(initialSeed) : "");
|
const [seed, setSeed] = useState<string>(initialSeed != null && initialSeed !== -1 ? String(initialSeed) : "");
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ interface UseRenderQueueProps {
|
|||||||
knobs: Knobs;
|
knobs: Knobs;
|
||||||
projectId: string;
|
projectId: string;
|
||||||
bible?: any | null;
|
bible?: any | null;
|
||||||
|
analysis?: any | null;
|
||||||
budgetCap?: number;
|
budgetCap?: number;
|
||||||
avatarImageUrl?: string | null;
|
avatarImageUrl?: string | null;
|
||||||
onUpdateJob: (sceneId: string, updates: Partial<Job>) => void;
|
onUpdateJob: (sceneId: string, updates: Partial<Job>) => void;
|
||||||
@@ -23,6 +24,7 @@ export const useRenderQueue = ({
|
|||||||
knobs,
|
knobs,
|
||||||
projectId,
|
projectId,
|
||||||
bible,
|
bible,
|
||||||
|
analysis,
|
||||||
budgetCap,
|
budgetCap,
|
||||||
avatarImageUrl,
|
avatarImageUrl,
|
||||||
onUpdateJob,
|
onUpdateJob,
|
||||||
@@ -54,27 +56,32 @@ export const useRenderQueue = ({
|
|||||||
};
|
};
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
// Initialize jobs if empty (audio/image only)
|
// Initialize jobs if empty (audio/image only) OR sync with script scenes
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (jobs.length === 0 && script.scenes.length > 0) {
|
// Always sync jobs with script scenes - this ensures render queue shows current audio/image
|
||||||
const initialJobs: Job[] = script.scenes.map((s) => {
|
if (script.scenes.length > 0) {
|
||||||
|
script.scenes.forEach((s) => {
|
||||||
const hasExistingAudio = Boolean(s.audioUrl);
|
const hasExistingAudio = Boolean(s.audioUrl);
|
||||||
return {
|
const hasExistingImage = Boolean(s.imageUrl);
|
||||||
|
const isReady = hasExistingAudio;
|
||||||
|
|
||||||
|
// Create job from scene data
|
||||||
|
const jobFromScene: Job = {
|
||||||
sceneId: s.id,
|
sceneId: s.id,
|
||||||
title: s.title,
|
title: s.title,
|
||||||
status: hasExistingAudio ? ("completed" as const) : ("idle" as const),
|
status: isReady ? ("completed" as const) : ("idle" as const),
|
||||||
progress: hasExistingAudio ? 100 : 0,
|
progress: isReady ? 100 : 0,
|
||||||
previewUrl: null,
|
previewUrl: null,
|
||||||
finalUrl: hasExistingAudio ? s.audioUrl || null : null,
|
finalUrl: hasExistingAudio ? s.audioUrl || null : null,
|
||||||
imageUrl: s.imageUrl || null,
|
imageUrl: hasExistingImage ? s.imageUrl || null : null,
|
||||||
jobId: null,
|
jobId: null,
|
||||||
};
|
};
|
||||||
});
|
|
||||||
initialJobs.forEach((job) => {
|
// Update job with scene's audio/image data
|
||||||
onUpdateJob(job.sceneId, job);
|
onUpdateJob(s.id, jobFromScene);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}, [jobs.length, script.scenes.length, onUpdateJob, script.scenes]);
|
}, [script.scenes, onUpdateJob]);
|
||||||
|
|
||||||
// Load final video URL from project on mount (for persistence across reloads)
|
// Load final video URL from project on mount (for persistence across reloads)
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -95,6 +102,7 @@ export const useRenderQueue = ({
|
|||||||
}, [projectId]);
|
}, [projectId]);
|
||||||
|
|
||||||
// Always try to attach existing videos to scenes (even after reloads)
|
// Always try to attach existing videos to scenes (even after reloads)
|
||||||
|
// But skip if job already has imageUrl - indicates user just came from script phase
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (script.scenes.length === 0) return;
|
if (script.scenes.length === 0) return;
|
||||||
|
|
||||||
@@ -122,6 +130,23 @@ export const useRenderQueue = ({
|
|||||||
|
|
||||||
const job = jobs.find((j) => j.sceneId === scene.id);
|
const job = jobs.find((j) => j.sceneId === scene.id);
|
||||||
|
|
||||||
|
// Skip if job already has imageUrl from script phase - don't override with old video
|
||||||
|
if (job?.imageUrl) {
|
||||||
|
console.log("[useRenderQueue] Skipping old video - job has imageUrl from script phase:", scene.id, "imageUrl:", job.imageUrl);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Job has no imageUrl - this could be from page reload or old state
|
||||||
|
console.log("[useRenderQueue] Job missing imageUrl, checking for old video:", scene.id, "job:", job);
|
||||||
|
|
||||||
|
// Only attach old video if job has NO content at all (no image, no video, no audio)
|
||||||
|
// If job has finalUrl (audio) or imageUrl from script phase, don't attach old video
|
||||||
|
const isJobEmpty = !job || (!job.imageUrl && !job.videoUrl && !job.finalUrl);
|
||||||
|
if (!isJobEmpty) {
|
||||||
|
console.log("[useRenderQueue] Skipping old video - job has content already:", scene.id, "job:", job);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
// Avoid redundant updates
|
// Avoid redundant updates
|
||||||
if (job?.videoUrl === videoUrl) return;
|
if (job?.videoUrl === videoUrl) return;
|
||||||
|
|
||||||
@@ -569,6 +594,9 @@ export const useRenderQueue = ({
|
|||||||
audioUrl,
|
audioUrl,
|
||||||
avatarImageUrl: sceneImageUrl,
|
avatarImageUrl: sceneImageUrl,
|
||||||
bible: bible,
|
bible: bible,
|
||||||
|
analysis: analysis, // Pass analysis for enhanced prompt
|
||||||
|
sceneImagePrompt: scene.imagePrompt || undefined, // Original image generation prompt
|
||||||
|
sceneNarration: scene.lines?.map((l: any) => l.text).join(" ").slice(0, 200) || undefined,
|
||||||
resolution: targetResolution,
|
resolution: targetResolution,
|
||||||
prompt: settings?.prompt || undefined,
|
prompt: settings?.prompt || undefined,
|
||||||
seed: settings?.seed ?? -1,
|
seed: settings?.seed ?? -1,
|
||||||
|
|||||||
@@ -21,9 +21,11 @@ import {
|
|||||||
} from "@mui/material";
|
} from "@mui/material";
|
||||||
import { HelpOutline as HelpOutlineIcon, Close as CloseIcon } from "@mui/icons-material";
|
import { HelpOutline as HelpOutlineIcon, Close as CloseIcon } from "@mui/icons-material";
|
||||||
import { PrimaryButton, SecondaryButton } from "../ui";
|
import { PrimaryButton, SecondaryButton } from "../ui";
|
||||||
|
import { VoiceSelector } from "../../shared/VoiceSelector";
|
||||||
|
|
||||||
export type AudioGenerationSettings = {
|
export type AudioGenerationSettings = {
|
||||||
voiceId: string;
|
voiceId: string;
|
||||||
|
customVoiceId?: string;
|
||||||
speed: number;
|
speed: number;
|
||||||
volume: number;
|
volume: number;
|
||||||
pitch: number;
|
pitch: number;
|
||||||
@@ -156,26 +158,12 @@ export const AudioRegenerateModal: React.FC<AudioRegenerateModalProps> = ({
|
|||||||
</IconButton>
|
</IconButton>
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
</Stack>
|
</Stack>
|
||||||
<FormControl fullWidth>
|
<VoiceSelector
|
||||||
<Select
|
value={settings.voiceId}
|
||||||
value={settings.voiceId}
|
onChange={(voiceId) => setSettings({ ...settings, voiceId })}
|
||||||
onChange={(e) => setSettings({ ...settings, voiceId: e.target.value })}
|
showVoiceClone={true}
|
||||||
sx={{
|
disabled={false}
|
||||||
backgroundColor: alpha("#ffffff", 0.05),
|
/>
|
||||||
color: "white",
|
|
||||||
"& .MuiOutlinedInput-notchedOutline": { borderColor: "rgba(255,255,255,0.2)" },
|
|
||||||
"&:hover .MuiOutlinedInput-notchedOutline": { borderColor: "rgba(255,255,255,0.3)" },
|
|
||||||
"&.Mui-focused .MuiOutlinedInput-notchedOutline": { borderColor: "#667eea" },
|
|
||||||
"& .MuiSvgIcon-root": { color: "rgba(255,255,255,0.7)" },
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{VOICE_OPTIONS.map((v) => (
|
|
||||||
<MenuItem key={v} value={v}>
|
|
||||||
{v}
|
|
||||||
</MenuItem>
|
|
||||||
))}
|
|
||||||
</Select>
|
|
||||||
</FormControl>
|
|
||||||
</Box>
|
</Box>
|
||||||
|
|
||||||
{/* Speed / Volume / Pitch */}
|
{/* Speed / Volume / Pitch */}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import React, { useState, useEffect } from "react";
|
import React, { useState, useEffect } from "react";
|
||||||
import { Stack, Box, Typography, Divider, Chip, alpha, CircularProgress, LinearProgress, IconButton, Tooltip } from "@mui/material";
|
import { Stack, Box, Typography, Divider, Chip, alpha, CircularProgress, LinearProgress, IconButton, Tooltip, Dialog, DialogContent } from "@mui/material";
|
||||||
import {
|
import {
|
||||||
EditNote as EditNoteIcon,
|
EditNote as EditNoteIcon,
|
||||||
CheckCircle as CheckCircleIcon,
|
CheckCircle as CheckCircleIcon,
|
||||||
@@ -8,6 +8,8 @@ import {
|
|||||||
PlayArrow as PlayArrowIcon,
|
PlayArrow as PlayArrowIcon,
|
||||||
Image as ImageIcon,
|
Image as ImageIcon,
|
||||||
Delete as DeleteIcon,
|
Delete as DeleteIcon,
|
||||||
|
Fullscreen as FullscreenIcon,
|
||||||
|
Close as CloseIcon,
|
||||||
} from "@mui/icons-material";
|
} from "@mui/icons-material";
|
||||||
import { Scene, Line, Knobs } from "../types";
|
import { Scene, Line, Knobs } from "../types";
|
||||||
import { GlassyCard, glassyCardSx, PrimaryButton } from "../ui";
|
import { GlassyCard, glassyCardSx, PrimaryButton } from "../ui";
|
||||||
@@ -31,6 +33,11 @@ interface SceneEditorProps {
|
|||||||
idea?: string; // Podcast idea for image generation context
|
idea?: string; // Podcast idea for image generation context
|
||||||
avatarUrl?: string | null; // Base avatar URL for consistent scene image generation
|
avatarUrl?: string | null; // Base avatar URL for consistent scene image generation
|
||||||
totalScenes?: number; // Total number of scenes in the script
|
totalScenes?: number; // Total number of scenes in the script
|
||||||
|
analysis?: {
|
||||||
|
audience?: string;
|
||||||
|
contentType?: string;
|
||||||
|
topKeywords?: string[];
|
||||||
|
} | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const SceneEditor: React.FC<SceneEditorProps> = ({
|
export const SceneEditor: React.FC<SceneEditorProps> = ({
|
||||||
@@ -46,6 +53,7 @@ export const SceneEditor: React.FC<SceneEditorProps> = ({
|
|||||||
idea,
|
idea,
|
||||||
avatarUrl,
|
avatarUrl,
|
||||||
totalScenes,
|
totalScenes,
|
||||||
|
analysis,
|
||||||
}) => {
|
}) => {
|
||||||
const [localGenerating, setLocalGenerating] = useState(false);
|
const [localGenerating, setLocalGenerating] = useState(false);
|
||||||
const [generatingImage, setGeneratingImage] = useState(false);
|
const [generatingImage, setGeneratingImage] = useState(false);
|
||||||
@@ -56,8 +64,10 @@ export const SceneEditor: React.FC<SceneEditorProps> = ({
|
|||||||
const [imageLoading, setImageLoading] = useState(false);
|
const [imageLoading, setImageLoading] = useState(false);
|
||||||
const [showRegenerateModal, setShowRegenerateModal] = useState(false);
|
const [showRegenerateModal, setShowRegenerateModal] = useState(false);
|
||||||
const [showAudioModal, setShowAudioModal] = useState(false);
|
const [showAudioModal, setShowAudioModal] = useState(false);
|
||||||
|
const [showImagePreview, setShowImagePreview] = useState(false);
|
||||||
const [audioSettings, setAudioSettings] = useState<AudioGenerationSettings>({
|
const [audioSettings, setAudioSettings] = useState<AudioGenerationSettings>({
|
||||||
voiceId: "Wise_Woman",
|
voiceId: "Wise_Woman",
|
||||||
|
customVoiceId: undefined,
|
||||||
speed: 1.0,
|
speed: 1.0,
|
||||||
volume: 1.0,
|
volume: 1.0,
|
||||||
pitch: 0.0,
|
pitch: 0.0,
|
||||||
@@ -300,7 +310,8 @@ export const SceneEditor: React.FC<SceneEditorProps> = ({
|
|||||||
const effectiveSettings = settings || audioSettings;
|
const effectiveSettings = settings || audioSettings;
|
||||||
const result = await podcastApi.renderSceneAudio({
|
const result = await podcastApi.renderSceneAudio({
|
||||||
scene: currentScene,
|
scene: currentScene,
|
||||||
voiceId: effectiveSettings.voiceId || "Wise_Woman",
|
voiceId: effectiveSettings.voiceId || knobs.voice_id || "Wise_Woman",
|
||||||
|
customVoiceId: effectiveSettings.customVoiceId || knobs.custom_voice_id,
|
||||||
emotion: effectiveSettings.emotion || scene.emotion || knobs.voice_emotion || "neutral",
|
emotion: effectiveSettings.emotion || scene.emotion || knobs.voice_emotion || "neutral",
|
||||||
speed: effectiveSettings.speed ?? knobs.voice_speed ?? 1.0,
|
speed: effectiveSettings.speed ?? knobs.voice_speed ?? 1.0,
|
||||||
volume: effectiveSettings.volume ?? 1.0,
|
volume: effectiveSettings.volume ?? 1.0,
|
||||||
@@ -323,6 +334,24 @@ export const SceneEditor: React.FC<SceneEditorProps> = ({
|
|||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Failed to approve and generate audio:", error);
|
console.error("Failed to approve and generate audio:", error);
|
||||||
|
|
||||||
|
// Provide user-friendly error message based on error type
|
||||||
|
let userMessage = "Failed to generate audio. Please try again.";
|
||||||
|
|
||||||
|
if (error instanceof Error) {
|
||||||
|
const errorMsg = error.message.toLowerCase();
|
||||||
|
|
||||||
|
if (errorMsg.includes("429") || errorMsg.includes("quota") || errorMsg.includes("limit")) {
|
||||||
|
userMessage = "Audio generation limit reached. Please check your subscription and try again.";
|
||||||
|
} else if (errorMsg.includes("voice") || errorMsg.includes("custom_voice")) {
|
||||||
|
userMessage = "Invalid voice. Please select a different voice and try again.";
|
||||||
|
} else if (errorMsg.includes("timeout") || errorMsg.includes("timed out")) {
|
||||||
|
userMessage = "Audio generation timed out. Please try again.";
|
||||||
|
} else if (errorMsg.includes("network") || errorMsg.includes("connection")) {
|
||||||
|
userMessage = "Network error. Please check your connection and try again.";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// On error, revert approval only if we just approved it in this call
|
// On error, revert approval only if we just approved it in this call
|
||||||
if (!wasAlreadyApproved) {
|
if (!wasAlreadyApproved) {
|
||||||
onUpdateScene({ ...scene, approved: false, audioUrl: undefined });
|
onUpdateScene({ ...scene, approved: false, audioUrl: undefined });
|
||||||
@@ -379,11 +408,12 @@ export const SceneEditor: React.FC<SceneEditorProps> = ({
|
|||||||
sceneId: scene.id,
|
sceneId: scene.id,
|
||||||
sceneTitle: scene.title,
|
sceneTitle: scene.title,
|
||||||
sceneContent: sceneContent,
|
sceneContent: sceneContent,
|
||||||
baseAvatarUrl: avatarUrl || undefined, // Pass base avatar URL for character consistency
|
sceneEmotion: scene.emotion,
|
||||||
|
baseAvatarUrl: avatarUrl || undefined,
|
||||||
idea: idea,
|
idea: idea,
|
||||||
|
analysis: analysis || undefined,
|
||||||
width: 1024,
|
width: 1024,
|
||||||
height: 1024,
|
height: 1024,
|
||||||
// Pass custom settings if provided
|
|
||||||
customPrompt: settings?.prompt,
|
customPrompt: settings?.prompt,
|
||||||
style: settings?.style,
|
style: settings?.style,
|
||||||
renderingSpeed: settings?.renderingSpeed,
|
renderingSpeed: settings?.renderingSpeed,
|
||||||
@@ -398,8 +428,12 @@ export const SceneEditor: React.FC<SceneEditorProps> = ({
|
|||||||
setImageGenerationStatus("Finalizing image...");
|
setImageGenerationStatus("Finalizing image...");
|
||||||
setImageGenerationProgress(95);
|
setImageGenerationProgress(95);
|
||||||
|
|
||||||
// Update scene with image URL
|
// Update scene with image URL and the prompt used
|
||||||
const updatedScene = { ...scene, imageUrl: result.image_url };
|
const updatedScene = {
|
||||||
|
...scene,
|
||||||
|
imageUrl: result.image_url,
|
||||||
|
imagePrompt: result.image_prompt || undefined,
|
||||||
|
};
|
||||||
onUpdateScene(updatedScene);
|
onUpdateScene(updatedScene);
|
||||||
|
|
||||||
const elapsed = Math.floor((Date.now() - startTime) / 1000);
|
const elapsed = Math.floor((Date.now() - startTime) / 1000);
|
||||||
@@ -725,11 +759,25 @@ export const SceneEditor: React.FC<SceneEditorProps> = ({
|
|||||||
: "1px solid rgba(245, 158, 11, 0.2)",
|
: "1px solid rgba(245, 158, 11, 0.2)",
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<Stack direction="row" alignItems="center" spacing={1.5} sx={{ mb: 1.5 }}>
|
<Stack direction="row" alignItems="center" spacing={1.5} sx={{ mb: 1.5, width: "100%" }}>
|
||||||
<ImageIcon sx={{ color: imageBlobUrl && !imageLoading ? "#667eea" : "#d97706", fontSize: "1.25rem" }} />
|
<ImageIcon sx={{ color: imageBlobUrl && !imageLoading ? "#667eea" : "#d97706", fontSize: "1.25rem" }} />
|
||||||
<Typography variant="subtitle2" sx={{ color: imageBlobUrl && !imageLoading ? "#667eea" : "#d97706", fontWeight: 600 }}>
|
<Typography variant="subtitle2" sx={{ color: imageBlobUrl && !imageLoading ? "#667eea" : "#d97706", fontWeight: 600, flex: 1 }}>
|
||||||
{imageBlobUrl && !imageLoading ? "Image Generated" : "Loading Image..."}
|
{imageBlobUrl && !imageLoading ? "Image Generated" : "Loading Image..."}
|
||||||
</Typography>
|
</Typography>
|
||||||
|
{imageBlobUrl && !imageLoading && (
|
||||||
|
<Tooltip title="View full size">
|
||||||
|
<IconButton
|
||||||
|
size="small"
|
||||||
|
onClick={() => setShowImagePreview(true)}
|
||||||
|
sx={{
|
||||||
|
color: "#667eea",
|
||||||
|
"&:hover": { background: "rgba(102, 126, 234, 0.1)" },
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<FullscreenIcon fontSize="small" />
|
||||||
|
</IconButton>
|
||||||
|
</Tooltip>
|
||||||
|
)}
|
||||||
</Stack>
|
</Stack>
|
||||||
{imageBlobUrl && !imageLoading ? (
|
{imageBlobUrl && !imageLoading ? (
|
||||||
<Box
|
<Box
|
||||||
@@ -805,6 +853,49 @@ export const SceneEditor: React.FC<SceneEditorProps> = ({
|
|||||||
initialSettings={audioSettings}
|
initialSettings={audioSettings}
|
||||||
isGenerating={generating}
|
isGenerating={generating}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
{/* Full-size Image Preview Modal */}
|
||||||
|
<Dialog
|
||||||
|
open={showImagePreview}
|
||||||
|
onClose={() => setShowImagePreview(false)}
|
||||||
|
maxWidth="lg"
|
||||||
|
PaperProps={{
|
||||||
|
sx: {
|
||||||
|
background: "rgba(0, 0, 0, 0.9)",
|
||||||
|
borderRadius: 3,
|
||||||
|
maxHeight: "90vh",
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<DialogContent sx={{ p: 0, position: "relative" }}>
|
||||||
|
<IconButton
|
||||||
|
onClick={() => setShowImagePreview(false)}
|
||||||
|
sx={{
|
||||||
|
position: "absolute",
|
||||||
|
top: 8,
|
||||||
|
right: 8,
|
||||||
|
color: "#fff",
|
||||||
|
background: "rgba(0, 0, 0, 0.5)",
|
||||||
|
zIndex: 1,
|
||||||
|
"&:hover": { background: "rgba(0, 0, 0, 0.7)" },
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<CloseIcon />
|
||||||
|
</IconButton>
|
||||||
|
<Box
|
||||||
|
component="img"
|
||||||
|
src={imageBlobUrl || ""}
|
||||||
|
alt={scene.title}
|
||||||
|
sx={{
|
||||||
|
width: "100%",
|
||||||
|
height: "auto",
|
||||||
|
maxHeight: "85vh",
|
||||||
|
objectFit: "contain",
|
||||||
|
display: "block",
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
</GlassyCard>
|
</GlassyCard>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -49,7 +49,7 @@ export const ScriptEditor: React.FC<ScriptEditorProps> = ({
|
|||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
const [approvingSceneId, setApprovingSceneId] = useState<string | null>(null);
|
const [approvingSceneId, setApprovingSceneId] = useState<string | null>(null);
|
||||||
const [generatingAudioId, setGeneratingAudioId] = useState<string | null>(null);
|
const [generatingAudioId, setGeneratingAudioId] = useState<string | null>(null);
|
||||||
const [showScriptFormatInfo, setShowScriptFormatInfo] = useState(true);
|
const [showScriptFormatInfo, setShowScriptFormatInfo] = useState(false);
|
||||||
const [combiningAudio, setCombiningAudio] = useState(false);
|
const [combiningAudio, setCombiningAudio] = useState(false);
|
||||||
const [combinedAudioResult, setCombinedAudioResult] = useState<{
|
const [combinedAudioResult, setCombinedAudioResult] = useState<{
|
||||||
url: string;
|
url: string;
|
||||||
@@ -622,6 +622,7 @@ export const ScriptEditor: React.FC<ScriptEditorProps> = ({
|
|||||||
}}
|
}}
|
||||||
idea={idea}
|
idea={idea}
|
||||||
avatarUrl={avatarUrl}
|
avatarUrl={avatarUrl}
|
||||||
|
analysis={analysis}
|
||||||
/>
|
/>
|
||||||
</GlassyCard>
|
</GlassyCard>
|
||||||
))}
|
))}
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
export type Knobs = {
|
export type Knobs = {
|
||||||
voice_emotion: string;
|
voice_emotion: string;
|
||||||
voice_speed: number;
|
voice_speed: number;
|
||||||
|
voice_id: string;
|
||||||
|
custom_voice_id?: string;
|
||||||
resolution: string;
|
resolution: string;
|
||||||
scene_length_target: number;
|
scene_length_target: number;
|
||||||
sample_rate: number;
|
sample_rate: number;
|
||||||
@@ -64,6 +66,7 @@ export type Scene = {
|
|||||||
emotion?: string; // Scene-specific emotion
|
emotion?: string; // Scene-specific emotion
|
||||||
audioUrl?: string; // Generated audio URL for this scene
|
audioUrl?: string; // Generated audio URL for this scene
|
||||||
imageUrl?: string; // Generated image URL for this scene (for video generation)
|
imageUrl?: string; // Generated image URL for this scene (for video generation)
|
||||||
|
imagePrompt?: string; // Original image generation prompt for video context
|
||||||
};
|
};
|
||||||
|
|
||||||
export type Script = {
|
export type Script = {
|
||||||
@@ -104,6 +107,10 @@ export type PodcastAnalysis = {
|
|||||||
suggestedOutlines: { id: number | string; title: string; segments: string[] }[];
|
suggestedOutlines: { id: number | string; title: string; segments: string[] }[];
|
||||||
suggestedKnobs: Knobs;
|
suggestedKnobs: Knobs;
|
||||||
titleSuggestions: string[];
|
titleSuggestions: string[];
|
||||||
|
episode_hook?: string;
|
||||||
|
key_takeaways?: string[];
|
||||||
|
guest_talking_points?: string[];
|
||||||
|
listener_cta?: string;
|
||||||
research_queries?: { query: string; rationale: string }[];
|
research_queries?: { query: string; rationale: string }[];
|
||||||
exaSuggestedConfig?: {
|
exaSuggestedConfig?: {
|
||||||
exa_search_type?: "auto" | "keyword" | "neural";
|
exa_search_type?: "auto" | "keyword" | "neural";
|
||||||
|
|||||||
@@ -7,9 +7,11 @@ interface PrimaryButtonProps {
|
|||||||
disabled?: boolean;
|
disabled?: boolean;
|
||||||
loading?: boolean;
|
loading?: boolean;
|
||||||
startIcon?: React.ReactNode;
|
startIcon?: React.ReactNode;
|
||||||
|
endIcon?: React.ReactNode;
|
||||||
tooltip?: string;
|
tooltip?: string;
|
||||||
ariaLabel?: string;
|
ariaLabel?: string;
|
||||||
sx?: SxProps<Theme>;
|
sx?: SxProps<Theme>;
|
||||||
|
size?: "small" | "medium" | "large";
|
||||||
}
|
}
|
||||||
|
|
||||||
export const PrimaryButton: React.FC<PrimaryButtonProps> = ({
|
export const PrimaryButton: React.FC<PrimaryButtonProps> = ({
|
||||||
@@ -18,24 +20,32 @@ export const PrimaryButton: React.FC<PrimaryButtonProps> = ({
|
|||||||
disabled = false,
|
disabled = false,
|
||||||
loading = false,
|
loading = false,
|
||||||
startIcon,
|
startIcon,
|
||||||
|
endIcon,
|
||||||
tooltip,
|
tooltip,
|
||||||
ariaLabel,
|
ariaLabel,
|
||||||
sx,
|
sx,
|
||||||
|
size = "medium",
|
||||||
}) => {
|
}) => {
|
||||||
|
const sizeStyles = {
|
||||||
|
small: { px: 1.5, py: 0.5, fontSize: "0.75rem" },
|
||||||
|
medium: { px: 3, py: 1, fontSize: "0.875rem" },
|
||||||
|
large: { px: 4, py: 1.5, fontSize: "1rem" },
|
||||||
|
};
|
||||||
|
|
||||||
const button = (
|
const button = (
|
||||||
<Button
|
<Button
|
||||||
variant="contained"
|
variant="contained"
|
||||||
onClick={onClick}
|
onClick={onClick}
|
||||||
disabled={disabled || loading}
|
disabled={disabled || loading}
|
||||||
startIcon={loading ? <CircularProgress size={16} /> : startIcon}
|
startIcon={loading ? <CircularProgress size={16} /> : startIcon}
|
||||||
|
endIcon={loading ? undefined : endIcon}
|
||||||
aria-label={ariaLabel}
|
aria-label={ariaLabel}
|
||||||
sx={{
|
sx={{
|
||||||
background: "linear-gradient(135deg, #667eea 0%, #764ba2 100%)",
|
background: "linear-gradient(135deg, #667eea 0%, #764ba2 100%)",
|
||||||
color: "white",
|
color: "white",
|
||||||
fontWeight: 600,
|
fontWeight: 600,
|
||||||
textTransform: "none",
|
textTransform: "none",
|
||||||
px: 3,
|
...sizeStyles[size],
|
||||||
py: 1,
|
|
||||||
"&:hover": {
|
"&:hover": {
|
||||||
background: "linear-gradient(135deg, #764ba2 0%, #667eea 100%)",
|
background: "linear-gradient(135deg, #764ba2 0%, #667eea 100%)",
|
||||||
},
|
},
|
||||||
|
|||||||
169
frontend/src/components/shared/TextToSpeechButton.tsx
Normal file
169
frontend/src/components/shared/TextToSpeechButton.tsx
Normal file
@@ -0,0 +1,169 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import { IconButton, Tooltip, CircularProgress, Box, Menu, MenuItem, ListItemIcon, ListItemText, FormControl, Select, Slider, Typography } from '@mui/material';
|
||||||
|
import { VolumeUp as VolumeUpIcon, Stop as StopIcon, PlayArrow as PlayArrowIcon, Settings as SettingsIcon } from '@mui/icons-material';
|
||||||
|
import { useTextToSpeech, SpeechSynthesisOptions } from '../../hooks/useTextToSpeech';
|
||||||
|
|
||||||
|
interface TextToSpeechButtonProps {
|
||||||
|
text: string;
|
||||||
|
textToSpeak?: string; // Optional different text to speak (e.g., shorter version)
|
||||||
|
options?: SpeechSynthesisOptions;
|
||||||
|
size?: 'small' | 'medium' | 'large';
|
||||||
|
showSettings?: boolean;
|
||||||
|
disabled?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const TextToSpeechButton: React.FC<TextToSpeechButtonProps> = ({
|
||||||
|
text,
|
||||||
|
textToSpeak,
|
||||||
|
options,
|
||||||
|
size = 'medium',
|
||||||
|
showSettings = false,
|
||||||
|
disabled = false,
|
||||||
|
}) => {
|
||||||
|
const { speak, stop, isSpeaking, isSupported, voices, pause, resume, isPaused } = useTextToSpeech();
|
||||||
|
|
||||||
|
const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null);
|
||||||
|
const [selectedVoice, setSelectedVoice] = React.useState<SpeechSynthesisVoice | null>(null);
|
||||||
|
const [rate, setRate] = React.useState(1);
|
||||||
|
const [pitch, setPitch] = React.useState(1);
|
||||||
|
const [volume, setVolume] = React.useState(1);
|
||||||
|
|
||||||
|
const handleClick = (event: React.MouseEvent<HTMLElement>) => {
|
||||||
|
if (showSettings) {
|
||||||
|
setAnchorEl(event.currentTarget);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleClose = () => {
|
||||||
|
setAnchorEl(null);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleSpeak = () => {
|
||||||
|
const textToUse = textToSpeak || text;
|
||||||
|
if (!textToUse.trim()) return;
|
||||||
|
|
||||||
|
if (isSpeaking) {
|
||||||
|
stop();
|
||||||
|
} else {
|
||||||
|
speak(textToUse, {
|
||||||
|
voice: selectedVoice || undefined,
|
||||||
|
rate,
|
||||||
|
pitch,
|
||||||
|
volume,
|
||||||
|
...options,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if (!isSupported) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const iconSize = size === 'small' ? 18 : size === 'medium' ? 24 : 30;
|
||||||
|
const buttonSize = size === 'small' ? 'small' : size === 'medium' ? 'medium' : 'large';
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Box sx={{ display: 'inline-flex', alignItems: 'center' }}>
|
||||||
|
<Tooltip title={isSpeaking ? "Stop" : "Read aloud"}>
|
||||||
|
<IconButton
|
||||||
|
onClick={handleSpeak}
|
||||||
|
size={buttonSize}
|
||||||
|
disabled={disabled || !text.trim()}
|
||||||
|
sx={{
|
||||||
|
color: isSpeaking ? '#ef4444' : '#667eea',
|
||||||
|
backgroundColor: isSpeaking ? 'rgba(239, 68, 68, 0.1)' : 'rgba(102, 126, 234, 0.1)',
|
||||||
|
'&:hover': {
|
||||||
|
backgroundColor: isSpeaking ? 'rgba(239, 68, 68, 0.2)' : 'rgba(102, 126, 234, 0.2)',
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{isSpeaking ? <StopIcon sx={{ fontSize: iconSize }} /> : <VolumeUpIcon sx={{ fontSize: iconSize }} />}
|
||||||
|
</IconButton>
|
||||||
|
</Tooltip>
|
||||||
|
|
||||||
|
{showSettings && (
|
||||||
|
<>
|
||||||
|
<Tooltip title="Voice settings">
|
||||||
|
<IconButton
|
||||||
|
onClick={handleClick}
|
||||||
|
size={buttonSize}
|
||||||
|
sx={{ ml: 0.5, color: 'rgba(0,0,0,0.5)' }}
|
||||||
|
>
|
||||||
|
<SettingsIcon sx={{ fontSize: iconSize * 0.75 }} />
|
||||||
|
</IconButton>
|
||||||
|
</Tooltip>
|
||||||
|
|
||||||
|
<Menu
|
||||||
|
anchorEl={anchorEl}
|
||||||
|
open={Boolean(anchorEl)}
|
||||||
|
onClose={handleClose}
|
||||||
|
PaperProps={{ sx: { p: 2, minWidth: 280 } }}
|
||||||
|
>
|
||||||
|
<Typography variant="subtitle2" sx={{ mb: 1, fontWeight: 600 }}>
|
||||||
|
Voice Settings
|
||||||
|
</Typography>
|
||||||
|
|
||||||
|
{/* Voice Selection */}
|
||||||
|
<FormControl fullWidth size="small" sx={{ mb: 2 }}>
|
||||||
|
<Typography variant="caption" sx={{ mb: 0.5, display: 'block' }}>Voice</Typography>
|
||||||
|
<Select
|
||||||
|
value={selectedVoice?.name || ''}
|
||||||
|
onChange={(e) => {
|
||||||
|
const voice = voices.find(v => v.name === e.target.value);
|
||||||
|
setSelectedVoice(voice || null);
|
||||||
|
}}
|
||||||
|
displayEmpty
|
||||||
|
>
|
||||||
|
<MenuItem value="">
|
||||||
|
<em>Default</em>
|
||||||
|
</MenuItem>
|
||||||
|
{voices.map((voice) => (
|
||||||
|
<MenuItem key={voice.name} value={voice.name}>
|
||||||
|
{voice.name.split(' ')[0]}
|
||||||
|
</MenuItem>
|
||||||
|
))}
|
||||||
|
</Select>
|
||||||
|
</FormControl>
|
||||||
|
|
||||||
|
{/* Speed */}
|
||||||
|
<Typography variant="caption">Speed: {rate}x</Typography>
|
||||||
|
<Slider
|
||||||
|
value={rate}
|
||||||
|
min={0.5}
|
||||||
|
max={2}
|
||||||
|
step={0.1}
|
||||||
|
onChange={(_, value) => setRate(value as number)}
|
||||||
|
size="small"
|
||||||
|
sx={{ mb: 2 }}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{/* Pitch */}
|
||||||
|
<Typography variant="caption">Pitch: {pitch}</Typography>
|
||||||
|
<Slider
|
||||||
|
value={pitch}
|
||||||
|
min={0.5}
|
||||||
|
max={2}
|
||||||
|
step={0.1}
|
||||||
|
onChange={(_, value) => setPitch(value as number)}
|
||||||
|
size="small"
|
||||||
|
sx={{ mb: 2 }}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{/* Volume */}
|
||||||
|
<Typography variant="caption">Volume: {Math.round(volume * 100)}%</Typography>
|
||||||
|
<Slider
|
||||||
|
value={volume}
|
||||||
|
min={0}
|
||||||
|
max={1}
|
||||||
|
step={0.1}
|
||||||
|
onChange={(_, value) => setVolume(value as number)}
|
||||||
|
size="small"
|
||||||
|
/>
|
||||||
|
</Menu>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default TextToSpeechButton;
|
||||||
321
frontend/src/components/shared/VoiceSelector.tsx
Normal file
321
frontend/src/components/shared/VoiceSelector.tsx
Normal file
@@ -0,0 +1,321 @@
|
|||||||
|
import React, { useState, useEffect, useMemo } from "react";
|
||||||
|
import {
|
||||||
|
Box,
|
||||||
|
Typography,
|
||||||
|
Select,
|
||||||
|
MenuItem,
|
||||||
|
FormControl,
|
||||||
|
InputLabel,
|
||||||
|
Stack,
|
||||||
|
Button,
|
||||||
|
Chip,
|
||||||
|
CircularProgress,
|
||||||
|
Tooltip,
|
||||||
|
alpha,
|
||||||
|
IconButton,
|
||||||
|
ListItemIcon,
|
||||||
|
ListItemText,
|
||||||
|
} from "@mui/material";
|
||||||
|
import {
|
||||||
|
Mic,
|
||||||
|
PlayArrow,
|
||||||
|
Pause,
|
||||||
|
CloudUpload,
|
||||||
|
HelpOutline,
|
||||||
|
AutoAwesome,
|
||||||
|
CheckCircle,
|
||||||
|
} from "@mui/icons-material";
|
||||||
|
import { getLatestVoiceClone, VoiceCloneResponse } from "../../api/brandAssets";
|
||||||
|
|
||||||
|
export type VoiceOption = {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
personality?: string;
|
||||||
|
isCustom?: boolean;
|
||||||
|
previewUrl?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
interface VoiceSelectorProps {
|
||||||
|
value: string;
|
||||||
|
onChange: (voiceId: string) => void;
|
||||||
|
disabled?: boolean;
|
||||||
|
showVoiceClone?: boolean;
|
||||||
|
compact?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
const PREDEFINED_VOICES: VoiceOption[] = [
|
||||||
|
{ id: "Wise_Woman", name: "Wise Woman", personality: "Authoritative, trustworthy female voice - perfect for educational content" },
|
||||||
|
{ id: "Friendly_Person", name: "Friendly Person", personality: "Warm, approachable voice - great for welcoming introductions" },
|
||||||
|
{ id: "Inspirational_girl", name: "Inspirational Girl", personality: "Motivational, uplifting female voice - ideal for inspiration" },
|
||||||
|
{ id: "Deep_Voice_Man", name: "Deep Voice Man", personality: "Powerful, commanding male voice - excellent for serious topics" },
|
||||||
|
{ id: "Calm_Woman", name: "Calm Woman", personality: "Soothing, composed female voice - perfect for meditation or sensitive topics" },
|
||||||
|
{ id: "Casual_Guy", name: "Casual Guy", personality: "Relaxed, conversational male voice - great for vlogs and tutorials" },
|
||||||
|
{ id: "Lively_Girl", name: "Lively Girl", personality: "Energetic, enthusiastic female voice - ideal for exciting announcements" },
|
||||||
|
{ id: "Patient_Man", name: "Patient Man", personality: "Gentle, understanding male voice - perfect for explanations" },
|
||||||
|
{ id: "Young_Knight", name: "Young Knight", personality: "Brave, confident male voice - great for adventure and gaming" },
|
||||||
|
{ id: "Determined_Man", name: "Determined Man", personality: "Strong, resolute male voice - excellent for motivational speeches" },
|
||||||
|
{ id: "Lovely_Girl", name: "Lovely Girl", personality: "Sweet, charming female voice - ideal for storytelling" },
|
||||||
|
{ id: "Decent_Boy", name: "Decent Boy", personality: "Honest, sincere male voice - perfect for testimonials" },
|
||||||
|
{ id: "Imposing_Manner", name: "Imposing Manner", personality: "Formal, dignified male voice - great for corporate content" },
|
||||||
|
{ id: "Elegant_Man", name: "Elegant Man", personality: "Refined, sophisticated male voice - ideal for luxury content" },
|
||||||
|
{ id: "Abbess", name: "Abbess", personality: "Spiritual, serene female voice - perfect for meditation" },
|
||||||
|
{ id: "Sweet_Girl_2", name: "Sweet Girl 2", personality: "Gentle, melodic female voice - excellent for children's content" },
|
||||||
|
{ id: "Exuberant_Girl", name: "Exuberant Girl", personality: "Joyful, expressive female voice - ideal for celebrations" },
|
||||||
|
];
|
||||||
|
|
||||||
|
const VOICE_CLONE_ID = "MY_VOICE_CLONE";
|
||||||
|
|
||||||
|
export const VoiceSelector: React.FC<VoiceSelectorProps> = ({
|
||||||
|
value,
|
||||||
|
onChange,
|
||||||
|
disabled = false,
|
||||||
|
showVoiceClone = true,
|
||||||
|
compact = false,
|
||||||
|
}) => {
|
||||||
|
const [voiceClone, setVoiceClone] = useState<VoiceCloneResponse | null>(null);
|
||||||
|
const [loadingVoiceClone, setLoadingVoiceClone] = useState(false);
|
||||||
|
const [playingPreview, setPlayingPreview] = useState<string | null>(null);
|
||||||
|
|
||||||
|
const voiceOptions = useMemo(() => {
|
||||||
|
const options: VoiceOption[] = [...PREDEFINED_VOICES];
|
||||||
|
|
||||||
|
if (showVoiceClone && voiceClone?.success && voiceClone.custom_voice_id) {
|
||||||
|
options.unshift({
|
||||||
|
id: VOICE_CLONE_ID,
|
||||||
|
name: voiceClone.voice_name || voiceClone.custom_voice_id || "My Voice Clone",
|
||||||
|
personality: "Your own voice - cloned from audio sample",
|
||||||
|
isCustom: true,
|
||||||
|
previewUrl: voiceClone.preview_audio_url,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return options;
|
||||||
|
}, [showVoiceClone, voiceClone]);
|
||||||
|
|
||||||
|
const selectedVoice = useMemo(() => {
|
||||||
|
if (value === VOICE_CLONE_ID && voiceClone?.success) {
|
||||||
|
return voiceOptions.find(v => v.id === VOICE_CLONE_ID);
|
||||||
|
}
|
||||||
|
return voiceOptions.find(v => v.id === value) || voiceOptions[0];
|
||||||
|
}, [value, voiceOptions, voiceClone]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!showVoiceClone) return;
|
||||||
|
|
||||||
|
const fetchVoiceClone = async () => {
|
||||||
|
try {
|
||||||
|
setLoadingVoiceClone(true);
|
||||||
|
const result = await getLatestVoiceClone();
|
||||||
|
setVoiceClone(result);
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Failed to fetch voice clone:", error);
|
||||||
|
} finally {
|
||||||
|
setLoadingVoiceClone(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
fetchVoiceClone();
|
||||||
|
}, [showVoiceClone]);
|
||||||
|
|
||||||
|
const handlePreview = (voice: VoiceOption) => {
|
||||||
|
if (!voice.previewUrl) return;
|
||||||
|
|
||||||
|
if (playingPreview === voice.id) {
|
||||||
|
const audio = document.getElementById(`voice-preview-${voice.id}`) as HTMLAudioElement;
|
||||||
|
if (audio) {
|
||||||
|
audio.pause();
|
||||||
|
audio.currentTime = 0;
|
||||||
|
}
|
||||||
|
setPlayingPreview(null);
|
||||||
|
} else {
|
||||||
|
setPlayingPreview(voice.id);
|
||||||
|
const audio = new Audio(voice.previewUrl);
|
||||||
|
audio.id = `voice-preview-${voice.id}`;
|
||||||
|
audio.onerror = () => {
|
||||||
|
console.error("Failed to load voice preview audio");
|
||||||
|
setPlayingPreview(null);
|
||||||
|
};
|
||||||
|
audio.onended = () => setPlayingPreview(null);
|
||||||
|
audio.play().catch((err) => {
|
||||||
|
console.error("Failed to play voice preview:", err);
|
||||||
|
setPlayingPreview(null);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleChange = (newValue: string) => {
|
||||||
|
if (newValue === VOICE_CLONE_ID && voiceClone?.success) {
|
||||||
|
onChange(voiceClone.custom_voice_id || VOICE_CLONE_ID);
|
||||||
|
} else {
|
||||||
|
onChange(newValue);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const isVoiceCloneSelected = value === VOICE_CLONE_ID ||
|
||||||
|
(voiceClone?.success && voiceClone.custom_voice_id && value === voiceClone.custom_voice_id);
|
||||||
|
|
||||||
|
if (compact) {
|
||||||
|
return (
|
||||||
|
<FormControl fullWidth size="small">
|
||||||
|
<InputLabel>Voice</InputLabel>
|
||||||
|
<Select
|
||||||
|
value={isVoiceCloneSelected ? VOICE_CLONE_ID : value}
|
||||||
|
onChange={(e) => handleChange(e.target.value)}
|
||||||
|
label="Voice"
|
||||||
|
disabled={disabled}
|
||||||
|
startAdornment={
|
||||||
|
<ListItemIcon sx={{ minWidth: 32 }}>
|
||||||
|
<Mic fontSize="small" sx={{ color: isVoiceCloneSelected ? "#667eea" : "inherit" }} />
|
||||||
|
</ListItemIcon>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{voiceOptions.map((voice) => (
|
||||||
|
<MenuItem key={voice.id} value={voice.id}>
|
||||||
|
<ListItemText
|
||||||
|
primary={voice.name}
|
||||||
|
secondary={voice.isCustom ? "Custom voice clone" : voice.personality?.split(' - ')[0]}
|
||||||
|
/>
|
||||||
|
</MenuItem>
|
||||||
|
))}
|
||||||
|
</Select>
|
||||||
|
</FormControl>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Box>
|
||||||
|
<Stack direction="row" spacing={1} alignItems="center" sx={{ mb: 1 }}>
|
||||||
|
<Typography variant="subtitle1" sx={{ fontWeight: 600 }}>
|
||||||
|
Voice
|
||||||
|
</Typography>
|
||||||
|
<Tooltip title="Choose a system voice or your custom cloned voice" arrow>
|
||||||
|
<IconButton size="small" sx={{ color: "rgba(0,0,0,0.5)" }}>
|
||||||
|
<HelpOutline fontSize="small" />
|
||||||
|
</IconButton>
|
||||||
|
</Tooltip>
|
||||||
|
{showVoiceClone && loadingVoiceClone && (
|
||||||
|
<CircularProgress size={16} sx={{ ml: 1 }} />
|
||||||
|
)}
|
||||||
|
</Stack>
|
||||||
|
|
||||||
|
<FormControl fullWidth>
|
||||||
|
<Select
|
||||||
|
value={isVoiceCloneSelected ? VOICE_CLONE_ID : value}
|
||||||
|
onChange={(e) => handleChange(e.target.value)}
|
||||||
|
disabled={disabled}
|
||||||
|
renderValue={(selected) => {
|
||||||
|
const voice = voiceOptions.find(v =>
|
||||||
|
v.id === selected ||
|
||||||
|
(selected === VOICE_CLONE_ID && v.isCustom)
|
||||||
|
);
|
||||||
|
return (
|
||||||
|
<Stack direction="row" spacing={1} alignItems="center">
|
||||||
|
<Mic fontSize="small" sx={{ color: voice?.isCustom ? "#667eea" : "inherit" }} />
|
||||||
|
<Typography>{voice?.name}</Typography>
|
||||||
|
{voice?.isCustom && (
|
||||||
|
<Chip
|
||||||
|
label="Cloned"
|
||||||
|
size="small"
|
||||||
|
sx={{
|
||||||
|
bgcolor: alpha("#667eea", 0.1),
|
||||||
|
color: "#667eea",
|
||||||
|
height: 20,
|
||||||
|
fontSize: "0.7rem",
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</Stack>
|
||||||
|
);
|
||||||
|
}}
|
||||||
|
MenuProps={{
|
||||||
|
PaperProps: {
|
||||||
|
sx: {
|
||||||
|
maxHeight: 400,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{showVoiceClone && voiceClone?.success && voiceClone.custom_voice_id && (
|
||||||
|
<MenuItem value={VOICE_CLONE_ID} sx={{ borderBottom: '1px solid rgba(0,0,0,0.1)' }}>
|
||||||
|
<ListItemIcon>
|
||||||
|
<AutoAwesome sx={{ color: "#667eea" }} />
|
||||||
|
</ListItemIcon>
|
||||||
|
<ListItemText
|
||||||
|
primary={
|
||||||
|
<Stack direction="row" spacing={1} alignItems="center">
|
||||||
|
<Typography fontWeight={600} sx={{ color: "#667eea" }}>
|
||||||
|
My Voice Clone
|
||||||
|
</Typography>
|
||||||
|
<Chip
|
||||||
|
icon={<CheckCircle sx={{ fontSize: "14px !important" }} />}
|
||||||
|
label="Active"
|
||||||
|
size="small"
|
||||||
|
sx={{
|
||||||
|
bgcolor: alpha("#10b981", 0.1),
|
||||||
|
color: "#10b981",
|
||||||
|
height: 20,
|
||||||
|
fontSize: "0.65rem",
|
||||||
|
'& .MuiChip-icon': { color: "#10b981" }
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</Stack>
|
||||||
|
}
|
||||||
|
secondary={
|
||||||
|
voiceClone.preview_audio_url && (
|
||||||
|
<Button
|
||||||
|
size="small"
|
||||||
|
startIcon={playingPreview === VOICE_CLONE_ID ? <Pause /> : <PlayArrow />}
|
||||||
|
onClick={(e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
handlePreview({
|
||||||
|
id: VOICE_CLONE_ID,
|
||||||
|
name: voiceClone.voice_name || "My Voice Clone",
|
||||||
|
previewUrl: voiceClone.preview_audio_url
|
||||||
|
});
|
||||||
|
}}
|
||||||
|
sx={{ mt: 0.5, textTransform: 'none' }}
|
||||||
|
>
|
||||||
|
{playingPreview === VOICE_CLONE_ID ? "Stop" : "Preview"}
|
||||||
|
</Button>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</MenuItem>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<MenuItem disabled sx={{ opacity: 0.6 }}>
|
||||||
|
<Typography variant="caption">System Voices</Typography>
|
||||||
|
</MenuItem>
|
||||||
|
|
||||||
|
{voiceOptions.filter(v => !v.isCustom).map((voice) => (
|
||||||
|
<MenuItem key={voice.id} value={voice.id}>
|
||||||
|
<ListItemText
|
||||||
|
primary={voice.name}
|
||||||
|
secondary={voice.personality?.split(' - ')[0]}
|
||||||
|
/>
|
||||||
|
</MenuItem>
|
||||||
|
))}
|
||||||
|
</Select>
|
||||||
|
</FormControl>
|
||||||
|
|
||||||
|
{selectedVoice?.personality && (
|
||||||
|
<Typography variant="caption" sx={{ color: "text.secondary", mt: 0.5, display: 'block' }}>
|
||||||
|
{selectedVoice.personality}
|
||||||
|
</Typography>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{showVoiceClone && !voiceClone?.success && (
|
||||||
|
<Box sx={{ mt: 2, p: 2, bgcolor: alpha("#f8fafc", 0.5), borderRadius: 2, border: '1px dashed rgba(0,0,0,0.1)' }}>
|
||||||
|
<Stack direction="row" spacing={1} alignItems="center">
|
||||||
|
<CloudUpload sx={{ color: "#64748b" }} />
|
||||||
|
<Typography variant="body2" sx={{ color: "#64748b" }}>
|
||||||
|
Don't see your voice? Go to Onboarding → Voice Cloning to create your custom voice clone.
|
||||||
|
</Typography>
|
||||||
|
</Stack>
|
||||||
|
</Box>
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default VoiceSelector;
|
||||||
@@ -61,6 +61,8 @@ export interface PodcastProjectState {
|
|||||||
const DEFAULT_KNOBS: Knobs = {
|
const DEFAULT_KNOBS: Knobs = {
|
||||||
voice_emotion: "neutral",
|
voice_emotion: "neutral",
|
||||||
voice_speed: 1,
|
voice_speed: 1,
|
||||||
|
voice_id: "Wise_Woman",
|
||||||
|
custom_voice_id: undefined,
|
||||||
resolution: "720p",
|
resolution: "720p",
|
||||||
scene_length_target: 45,
|
scene_length_target: 45,
|
||||||
sample_rate: 24000,
|
sample_rate: 24000,
|
||||||
@@ -338,7 +340,12 @@ export const usePodcastProjectState = () => {
|
|||||||
budget_cap: payload.budgetCap,
|
budget_cap: payload.budgetCap,
|
||||||
avatar_url: finalAvatarUrl,
|
avatar_url: finalAvatarUrl,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error: any) {
|
||||||
|
const errorStr = error?.message || "";
|
||||||
|
if (errorStr.includes("DUPLICATE_IDEA")) {
|
||||||
|
// Re-throw duplicate idea error for UI handling
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
console.error('Error creating project in database:', error);
|
console.error('Error creating project in database:', error);
|
||||||
// Continue anyway - localStorage fallback
|
// Continue anyway - localStorage fallback
|
||||||
}
|
}
|
||||||
|
|||||||
190
frontend/src/hooks/useTextToSpeech.ts
Normal file
190
frontend/src/hooks/useTextToSpeech.ts
Normal file
@@ -0,0 +1,190 @@
|
|||||||
|
import { useState, useCallback, useRef, useEffect, useMemo } from 'react';
|
||||||
|
|
||||||
|
export interface SpeechSynthesisOptions {
|
||||||
|
voice?: SpeechSynthesisVoice;
|
||||||
|
rate?: number; // 0.1 to 10
|
||||||
|
pitch?: number; // 0 to 2
|
||||||
|
volume?: number; // 0 to 1
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface UseTextToSpeechReturn {
|
||||||
|
speak: (text: string, options?: SpeechSynthesisOptions) => void;
|
||||||
|
stop: () => void;
|
||||||
|
pause: () => void;
|
||||||
|
resume: () => void;
|
||||||
|
isSupported: boolean;
|
||||||
|
isSpeaking: boolean;
|
||||||
|
isPaused: boolean;
|
||||||
|
voices: SpeechSynthesisVoice[];
|
||||||
|
currentText: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Singleton to manage global speech synthesis state
|
||||||
|
let globalIsSpeaking = false;
|
||||||
|
let globalIsPaused = false;
|
||||||
|
let globalCurrentText: string | null = null;
|
||||||
|
let globalOnStateChange: ((state: { isSpeaking: boolean; isPaused: boolean; currentText: string | null }) => void) | null = null;
|
||||||
|
|
||||||
|
const notifyStateChange = () => {
|
||||||
|
if (globalOnStateChange) {
|
||||||
|
globalOnStateChange({
|
||||||
|
isSpeaking: globalIsSpeaking,
|
||||||
|
isPaused: globalIsPaused,
|
||||||
|
currentText: globalCurrentText,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export const useTextToSpeech = (): UseTextToSpeechReturn => {
|
||||||
|
const [voices, setVoices] = useState<SpeechSynthesisVoice[]>([]);
|
||||||
|
const synthRef = useRef<SpeechSynthesis | null>(null);
|
||||||
|
|
||||||
|
const isSupported = typeof window !== 'undefined' && 'speechSynthesis' in window;
|
||||||
|
|
||||||
|
// Initialize singleton listener
|
||||||
|
useEffect(() => {
|
||||||
|
globalOnStateChange = (state) => {
|
||||||
|
// Force re-render by using state setter (handled through component-local state)
|
||||||
|
};
|
||||||
|
return () => {
|
||||||
|
globalOnStateChange = null;
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// Load available voices
|
||||||
|
useEffect(() => {
|
||||||
|
if (!isSupported) return;
|
||||||
|
|
||||||
|
synthRef.current = window.speechSynthesis;
|
||||||
|
|
||||||
|
const loadVoices = () => {
|
||||||
|
const availableVoices = synthRef.current?.getVoices() || [];
|
||||||
|
setVoices(availableVoices);
|
||||||
|
};
|
||||||
|
|
||||||
|
loadVoices();
|
||||||
|
|
||||||
|
// Voices may load asynchronously
|
||||||
|
synthRef.current.onvoiceschanged = loadVoices;
|
||||||
|
|
||||||
|
// Cleanup on unmount - stop any ongoing speech
|
||||||
|
return () => {
|
||||||
|
if (synthRef.current) {
|
||||||
|
synthRef.current.cancel();
|
||||||
|
synthRef.current.onvoiceschanged = null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}, [isSupported]);
|
||||||
|
|
||||||
|
const stop = useCallback(() => {
|
||||||
|
if (synthRef.current) {
|
||||||
|
synthRef.current.cancel();
|
||||||
|
}
|
||||||
|
globalIsSpeaking = false;
|
||||||
|
globalIsPaused = false;
|
||||||
|
globalCurrentText = null;
|
||||||
|
notifyStateChange();
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const pause = useCallback(() => {
|
||||||
|
if (synthRef.current && globalIsSpeaking && !globalIsPaused) {
|
||||||
|
synthRef.current.pause();
|
||||||
|
globalIsPaused = true;
|
||||||
|
notifyStateChange();
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const resume = useCallback(() => {
|
||||||
|
if (synthRef.current && globalIsPaused) {
|
||||||
|
synthRef.current.resume();
|
||||||
|
globalIsPaused = false;
|
||||||
|
notifyStateChange();
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const speak = useCallback((text: string, options?: SpeechSynthesisOptions) => {
|
||||||
|
if (!isSupported || !synthRef.current || !text?.trim()) return;
|
||||||
|
|
||||||
|
// Stop any current speech first
|
||||||
|
synthRef.current.cancel();
|
||||||
|
|
||||||
|
const utterance = new SpeechSynthesisUtterance(text);
|
||||||
|
|
||||||
|
// Apply options
|
||||||
|
if (options?.voice) {
|
||||||
|
utterance.voice = options.voice;
|
||||||
|
}
|
||||||
|
if (options?.rate !== undefined) {
|
||||||
|
utterance.rate = Math.max(0.1, Math.min(10, options.rate));
|
||||||
|
}
|
||||||
|
if (options?.pitch !== undefined) {
|
||||||
|
utterance.pitch = Math.max(0, Math.min(2, options.pitch));
|
||||||
|
}
|
||||||
|
if (options?.volume !== undefined) {
|
||||||
|
utterance.volume = Math.max(0, Math.min(1, options.volume));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Set up event handlers
|
||||||
|
utterance.onstart = () => {
|
||||||
|
globalIsSpeaking = true;
|
||||||
|
globalIsPaused = false;
|
||||||
|
globalCurrentText = text;
|
||||||
|
notifyStateChange();
|
||||||
|
};
|
||||||
|
|
||||||
|
utterance.onend = () => {
|
||||||
|
globalIsSpeaking = false;
|
||||||
|
globalIsPaused = false;
|
||||||
|
globalCurrentText = null;
|
||||||
|
notifyStateChange();
|
||||||
|
};
|
||||||
|
|
||||||
|
utterance.onerror = (event) => {
|
||||||
|
console.error('Speech synthesis error:', event.error);
|
||||||
|
globalIsSpeaking = false;
|
||||||
|
globalIsPaused = false;
|
||||||
|
globalCurrentText = null;
|
||||||
|
notifyStateChange();
|
||||||
|
};
|
||||||
|
|
||||||
|
utterance.onpause = () => {
|
||||||
|
globalIsPaused = true;
|
||||||
|
notifyStateChange();
|
||||||
|
};
|
||||||
|
utterance.onresume = () => {
|
||||||
|
globalIsPaused = false;
|
||||||
|
notifyStateChange();
|
||||||
|
};
|
||||||
|
|
||||||
|
synthRef.current.speak(utterance);
|
||||||
|
}, [isSupported]);
|
||||||
|
|
||||||
|
// Use local state for reactivity but sync with global state
|
||||||
|
const [localIsSpeaking, setLocalIsSpeaking] = useState(false);
|
||||||
|
const [localIsPaused, setLocalIsPaused] = useState(false);
|
||||||
|
const [localCurrentText, setLocalCurrentText] = useState<string | null>(null);
|
||||||
|
|
||||||
|
// Sync with global state periodically
|
||||||
|
useEffect(() => {
|
||||||
|
const interval = setInterval(() => {
|
||||||
|
setLocalIsSpeaking(globalIsSpeaking);
|
||||||
|
setLocalIsPaused(globalIsPaused);
|
||||||
|
setLocalCurrentText(globalCurrentText);
|
||||||
|
}, 100);
|
||||||
|
return () => clearInterval(interval);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return {
|
||||||
|
speak,
|
||||||
|
stop,
|
||||||
|
pause,
|
||||||
|
resume,
|
||||||
|
isSupported,
|
||||||
|
isSpeaking: localIsSpeaking,
|
||||||
|
isPaused: localIsPaused,
|
||||||
|
voices,
|
||||||
|
currentText: localCurrentText,
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
export default useTextToSpeech;
|
||||||
@@ -24,6 +24,8 @@ import { TaskStatus } from "./storyWriterApi";
|
|||||||
const DEFAULT_KNOBS: Knobs = {
|
const DEFAULT_KNOBS: Knobs = {
|
||||||
voice_emotion: "neutral",
|
voice_emotion: "neutral",
|
||||||
voice_speed: 1,
|
voice_speed: 1,
|
||||||
|
voice_id: "Wise_Woman",
|
||||||
|
custom_voice_id: undefined,
|
||||||
resolution: "720p",
|
resolution: "720p",
|
||||||
scene_length_target: 45,
|
scene_length_target: 45,
|
||||||
sample_rate: 24000,
|
sample_rate: 24000,
|
||||||
@@ -119,31 +121,46 @@ const mapPersonaQueries = (persona: ResearchPersona | undefined, seed: string):
|
|||||||
return generated.slice(0, 6);
|
return generated.slice(0, 6);
|
||||||
};
|
};
|
||||||
|
|
||||||
const mapSourcesToFacts = (sources: ExaSource[]): Fact[] => {
|
|
||||||
if (!sources || !sources.length) return [];
|
|
||||||
return sources.slice(0, 12).map((source: ExaSource, idx: number) => ({
|
|
||||||
id: source.url || createId("fact"),
|
|
||||||
quote: source.excerpt || source.title || "Insight",
|
|
||||||
url: source.url || "",
|
|
||||||
date: source.published_at || "Unknown",
|
|
||||||
confidence: typeof (source as any).credibility_score === "number" ? (source as any).credibility_score : Math.max(0.5, 0.85 - idx * 0.02),
|
|
||||||
image: source.image,
|
|
||||||
author: source.author,
|
|
||||||
highlights: source.highlights,
|
|
||||||
}));
|
|
||||||
};
|
|
||||||
|
|
||||||
type ExaSource = {
|
type ExaSource = {
|
||||||
title?: string;
|
title?: string;
|
||||||
url?: string;
|
url?: string;
|
||||||
excerpt?: string;
|
excerpt?: string;
|
||||||
published_at?: string;
|
published_at?: string;
|
||||||
|
publishedDate?: string; // Exa format
|
||||||
highlights?: string[];
|
highlights?: string[];
|
||||||
summary?: string;
|
summary?: string;
|
||||||
source_type?: string;
|
source_type?: string;
|
||||||
index?: number;
|
index?: number;
|
||||||
image?: string;
|
image?: string;
|
||||||
author?: string;
|
author?: string;
|
||||||
|
text?: string; // Exa full text content
|
||||||
|
credibility_score?: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
const mapSourcesToFacts = (sources: ExaSource[]): Fact[] => {
|
||||||
|
if (!sources || !sources.length) return [];
|
||||||
|
|
||||||
|
// Deduplicate by URL
|
||||||
|
const seenUrls = new Set<string>();
|
||||||
|
const uniqueSources = sources.filter(s => {
|
||||||
|
if (!s.url || seenUrls.has(s.url)) return false;
|
||||||
|
seenUrls.add(s.url);
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
|
||||||
|
return uniqueSources.slice(0, 12).map((source: ExaSource, idx: number) => ({
|
||||||
|
id: source.url || `fact-${idx}`,
|
||||||
|
quote: source.excerpt || source.highlights?.[0] || source.summary || source.title || "Insight",
|
||||||
|
url: source.url || "",
|
||||||
|
// Use published_at (backend format) or publishedDate (Exa format)
|
||||||
|
date: source.published_at || source.publishedDate || "Unknown",
|
||||||
|
confidence: source.credibility_score || Math.max(0.5, 0.85 - idx * 0.02),
|
||||||
|
image: source.image,
|
||||||
|
author: source.author,
|
||||||
|
highlights: source.highlights,
|
||||||
|
// Include full text if available
|
||||||
|
fullText: source.text,
|
||||||
|
}));
|
||||||
};
|
};
|
||||||
|
|
||||||
type ExaResearchResult = {
|
type ExaResearchResult = {
|
||||||
@@ -180,7 +197,9 @@ const mapExaResearchResponse = (response: any): Research => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const ensurePreflight = async (operation: PreflightOperation) => {
|
const ensurePreflight = async (operation: PreflightOperation) => {
|
||||||
|
console.log('[podcastApi] Running preflight for:', operation);
|
||||||
const result = await checkPreflight(operation);
|
const result = await checkPreflight(operation);
|
||||||
|
console.log('[podcastApi] Preflight result:', result);
|
||||||
if (!result.can_proceed) {
|
if (!result.can_proceed) {
|
||||||
const message = result.operations[0]?.message || "Pre-flight validation failed";
|
const message = result.operations[0]?.message || "Pre-flight validation failed";
|
||||||
throw new Error(message);
|
throw new Error(message);
|
||||||
@@ -222,6 +241,10 @@ export const podcastApi = {
|
|||||||
suggestedOutlines: outlines,
|
suggestedOutlines: outlines,
|
||||||
suggestedKnobs: { ...DEFAULT_KNOBS, ...payload.knobs },
|
suggestedKnobs: { ...DEFAULT_KNOBS, ...payload.knobs },
|
||||||
titleSuggestions: (analysisResp.data?.title_suggestions || []).filter(Boolean),
|
titleSuggestions: (analysisResp.data?.title_suggestions || []).filter(Boolean),
|
||||||
|
episode_hook: analysisResp.data?.episode_hook || "",
|
||||||
|
key_takeaways: analysisResp.data?.key_takeaways || [],
|
||||||
|
guest_talking_points: analysisResp.data?.guest_talking_points || [],
|
||||||
|
listener_cta: analysisResp.data?.listener_cta || "",
|
||||||
research_queries: analysisResp.data?.research_queries || [],
|
research_queries: analysisResp.data?.research_queries || [],
|
||||||
exaSuggestedConfig: analysisResp.data?.exa_suggested_config || undefined,
|
exaSuggestedConfig: analysisResp.data?.exa_suggested_config || undefined,
|
||||||
};
|
};
|
||||||
@@ -241,6 +264,9 @@ export const podcastApi = {
|
|||||||
queries = mapPersonaQueries(researchConfig?.research_persona, storyIdea);
|
queries = mapPersonaQueries(researchConfig?.research_persona, storyIdea);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Note: selectedQueries should be set to empty Set by the caller (workflow)
|
||||||
|
// so users can manually choose which queries to run
|
||||||
|
|
||||||
const projectId = createId("podcast");
|
const projectId = createId("podcast");
|
||||||
const estimate = estimateCosts({
|
const estimate = estimateCosts({
|
||||||
minutes: payload.duration,
|
minutes: payload.duration,
|
||||||
@@ -303,13 +329,20 @@ export const podcastApi = {
|
|||||||
actual_provider_name: "exa",
|
actual_provider_name: "exa",
|
||||||
});
|
});
|
||||||
|
|
||||||
const response = await aiApiClient.post("/api/podcast/research/exa", {
|
let response;
|
||||||
topic: params.topic || keywords[0],
|
try {
|
||||||
queries: keywords,
|
response = await aiApiClient.post("/api/podcast/research/exa", {
|
||||||
exa_config: sanitizedExaConfig,
|
topic: params.topic || keywords[0],
|
||||||
bible: params.bible,
|
queries: keywords,
|
||||||
analysis: params.analysis,
|
exa_config: sanitizedExaConfig,
|
||||||
});
|
bible: params.bible,
|
||||||
|
analysis: params.analysis,
|
||||||
|
}, { timeout: 300000 }); // 5 minute timeout for research
|
||||||
|
console.log('[podcastApi] Exa research response received:', response.status, response.data);
|
||||||
|
} catch (error: any) {
|
||||||
|
console.error('[podcastApi] Exa research error:', error?.response?.status, error?.response?.data, error?.message);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
|
||||||
const exaResult = response.data as ExaResearchResult;
|
const exaResult = response.data as ExaResearchResult;
|
||||||
if (params.onProgress) {
|
if (params.onProgress) {
|
||||||
@@ -329,6 +362,7 @@ export const podcastApi = {
|
|||||||
bible?: any;
|
bible?: any;
|
||||||
outline?: any;
|
outline?: any;
|
||||||
analysis?: PodcastAnalysis | null;
|
analysis?: PodcastAnalysis | null;
|
||||||
|
onProgress?: (message: string) => void;
|
||||||
}): Promise<Script> {
|
}): Promise<Script> {
|
||||||
await ensurePreflight({
|
await ensurePreflight({
|
||||||
provider: "gemini",
|
provider: "gemini",
|
||||||
@@ -337,6 +371,10 @@ export const podcastApi = {
|
|||||||
actual_provider_name: "gemini",
|
actual_provider_name: "gemini",
|
||||||
});
|
});
|
||||||
|
|
||||||
|
if (params.onProgress) {
|
||||||
|
params.onProgress("Analyzing research data and extracting key insights...");
|
||||||
|
}
|
||||||
|
|
||||||
const response = await aiApiClient.post("/api/podcast/script", {
|
const response = await aiApiClient.post("/api/podcast/script", {
|
||||||
idea: params.idea,
|
idea: params.idea,
|
||||||
duration_minutes: params.durationMinutes,
|
duration_minutes: params.durationMinutes,
|
||||||
@@ -347,6 +385,10 @@ export const podcastApi = {
|
|||||||
analysis: params.analysis,
|
analysis: params.analysis,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
if (params.onProgress) {
|
||||||
|
params.onProgress("Creating podcast structure with scenes and dialogue...");
|
||||||
|
}
|
||||||
|
|
||||||
const scenes = response.data?.scenes || [];
|
const scenes = response.data?.scenes || [];
|
||||||
const scriptScenes: Scene[] = scenes.map((scene: any) => ({
|
const scriptScenes: Scene[] = scenes.map((scene: any) => ({
|
||||||
id: scene.id || createId("scene"),
|
id: scene.id || createId("scene"),
|
||||||
@@ -406,6 +448,7 @@ export const podcastApi = {
|
|||||||
async renderSceneAudio(params: {
|
async renderSceneAudio(params: {
|
||||||
scene: Scene;
|
scene: Scene;
|
||||||
voiceId?: string;
|
voiceId?: string;
|
||||||
|
customVoiceId?: string;
|
||||||
emotion?: string; // Fallback if scene doesn't have emotion
|
emotion?: string; // Fallback if scene doesn't have emotion
|
||||||
speed?: number;
|
speed?: number;
|
||||||
volume?: number;
|
volume?: number;
|
||||||
@@ -498,6 +541,7 @@ export const podcastApi = {
|
|||||||
scene_title: params.scene.title,
|
scene_title: params.scene.title,
|
||||||
text: textToUse,
|
text: textToUse,
|
||||||
voice_id: params.voiceId || "Wise_Woman",
|
voice_id: params.voiceId || "Wise_Woman",
|
||||||
|
custom_voice_id: params.customVoiceId || null,
|
||||||
speed: params.speed ?? 1.0, // Normal speed (was 0.9, but too slow - causing duration issues)
|
speed: params.speed ?? 1.0, // Normal speed (was 0.9, but too slow - causing duration issues)
|
||||||
volume: params.volume ?? 1.0,
|
volume: params.volume ?? 1.0,
|
||||||
pitch: params.pitch ?? 0.0,
|
pitch: params.pitch ?? 0.0,
|
||||||
@@ -522,7 +566,7 @@ export const podcastApi = {
|
|||||||
},
|
},
|
||||||
|
|
||||||
async approveScene(params: { projectId: string; sceneId: string; notes?: string }) {
|
async approveScene(params: { projectId: string; sceneId: string; notes?: string }) {
|
||||||
await aiApiClient.post("/api/story/script/approve", {
|
await aiApiClient.post("/api/podcast/script/approve", {
|
||||||
project_id: params.projectId,
|
project_id: params.projectId,
|
||||||
scene_id: params.sceneId,
|
scene_id: params.sceneId,
|
||||||
approved: true,
|
approved: true,
|
||||||
@@ -564,8 +608,22 @@ export const podcastApi = {
|
|||||||
budget_cap: number;
|
budget_cap: number;
|
||||||
avatar_url?: string | null;
|
avatar_url?: string | null;
|
||||||
}): Promise<any> {
|
}): Promise<any> {
|
||||||
const response = await aiApiClient.post("/api/podcast/projects", params);
|
try {
|
||||||
return response.data;
|
const response = await aiApiClient.post("/api/podcast/projects", params);
|
||||||
|
return response.data;
|
||||||
|
} catch (error: any) {
|
||||||
|
if (error?.response?.status === 409) {
|
||||||
|
// Duplicate idea detected - throw specific error for UI handling
|
||||||
|
const conflictData = error.response.data?.detail || {};
|
||||||
|
throw new Error(JSON.stringify({
|
||||||
|
type: "DUPLICATE_IDEA",
|
||||||
|
existing_project_id: conflictData.existing_project_id,
|
||||||
|
existing_idea: conflictData.existing_idea,
|
||||||
|
message: conflictData.message,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
async updateProject(projectId: string, updates: any): Promise<any> {
|
async updateProject(projectId: string, updates: any): Promise<any> {
|
||||||
@@ -582,6 +640,16 @@ export const podcastApi = {
|
|||||||
return response.data;
|
return response.data;
|
||||||
},
|
},
|
||||||
|
|
||||||
|
async regenerateResearchQueries(params: {
|
||||||
|
idea: string;
|
||||||
|
feedback: string;
|
||||||
|
existing_analysis?: any;
|
||||||
|
bible?: any;
|
||||||
|
}): Promise<{ research_queries: { query: string; rationale: string }[] }> {
|
||||||
|
const response = await aiApiClient.post("/api/podcast/regenerate-queries", params);
|
||||||
|
return response.data;
|
||||||
|
},
|
||||||
|
|
||||||
async saveAudioToAssetLibrary(params: {
|
async saveAudioToAssetLibrary(params: {
|
||||||
audioUrl: string;
|
audioUrl: string;
|
||||||
filename: string;
|
filename: string;
|
||||||
@@ -624,6 +692,9 @@ export const podcastApi = {
|
|||||||
audioUrl: string;
|
audioUrl: string;
|
||||||
avatarImageUrl?: string;
|
avatarImageUrl?: string;
|
||||||
bible?: any;
|
bible?: any;
|
||||||
|
analysis?: any;
|
||||||
|
sceneImagePrompt?: string;
|
||||||
|
sceneNarration?: string;
|
||||||
resolution?: string;
|
resolution?: string;
|
||||||
prompt?: string;
|
prompt?: string;
|
||||||
seed?: number;
|
seed?: number;
|
||||||
@@ -636,6 +707,9 @@ export const podcastApi = {
|
|||||||
audio_url: params.audioUrl,
|
audio_url: params.audioUrl,
|
||||||
avatar_image_url: params.avatarImageUrl,
|
avatar_image_url: params.avatarImageUrl,
|
||||||
bible: params.bible,
|
bible: params.bible,
|
||||||
|
analysis: params.analysis,
|
||||||
|
scene_image_prompt: params.sceneImagePrompt,
|
||||||
|
scene_narration: params.sceneNarration,
|
||||||
resolution: params.resolution || "720p",
|
resolution: params.resolution || "720p",
|
||||||
prompt: params.prompt,
|
prompt: params.prompt,
|
||||||
seed: params.seed ?? -1,
|
seed: params.seed ?? -1,
|
||||||
@@ -697,9 +771,15 @@ export const podcastApi = {
|
|||||||
sceneId: string;
|
sceneId: string;
|
||||||
sceneTitle: string;
|
sceneTitle: string;
|
||||||
sceneContent?: string;
|
sceneContent?: string;
|
||||||
|
sceneEmotion?: string;
|
||||||
baseAvatarUrl?: string;
|
baseAvatarUrl?: string;
|
||||||
bible?: any;
|
bible?: any;
|
||||||
idea?: string;
|
idea?: string;
|
||||||
|
analysis?: {
|
||||||
|
audience?: string;
|
||||||
|
contentType?: string;
|
||||||
|
topKeywords?: string[];
|
||||||
|
};
|
||||||
width?: number;
|
width?: number;
|
||||||
height?: number;
|
height?: number;
|
||||||
customPrompt?: string;
|
customPrompt?: string;
|
||||||
@@ -716,14 +796,17 @@ export const podcastApi = {
|
|||||||
provider: string;
|
provider: string;
|
||||||
model?: string;
|
model?: string;
|
||||||
cost: number;
|
cost: number;
|
||||||
|
image_prompt?: string;
|
||||||
}> {
|
}> {
|
||||||
const response = await aiApiClient.post("/api/podcast/image", {
|
const response = await aiApiClient.post("/api/podcast/image", {
|
||||||
scene_id: params.sceneId,
|
scene_id: params.sceneId,
|
||||||
scene_title: params.sceneTitle,
|
scene_title: params.sceneTitle,
|
||||||
scene_content: params.sceneContent,
|
scene_content: params.sceneContent,
|
||||||
|
scene_emotion: params.sceneEmotion || null,
|
||||||
base_avatar_url: params.baseAvatarUrl || null,
|
base_avatar_url: params.baseAvatarUrl || null,
|
||||||
bible: params.bible,
|
bible: params.bible,
|
||||||
idea: params.idea || null,
|
idea: params.idea || null,
|
||||||
|
analysis: params.analysis || null,
|
||||||
width: params.width || 1024,
|
width: params.width || 1024,
|
||||||
height: params.height || 1024,
|
height: params.height || 1024,
|
||||||
custom_prompt: params.customPrompt || null,
|
custom_prompt: params.customPrompt || null,
|
||||||
|
|||||||
Reference in New Issue
Block a user