Spaces:
Sleeping
Sleeping
Update routes/scout_router.py
Browse files- routes/scout_router.py +172 -43
routes/scout_router.py
CHANGED
|
@@ -1,14 +1,16 @@
|
|
| 1 |
"""
|
| 2 |
-
routes/scout_router.py [
|
| 3 |
-
|
| 4 |
-
Changes:
|
| 5 |
-
-
|
| 6 |
-
|
| 7 |
-
-
|
| 8 |
-
-
|
| 9 |
-
|
| 10 |
-
-
|
| 11 |
-
|
|
|
|
|
|
|
| 12 |
"""
|
| 13 |
|
| 14 |
from fastapi import APIRouter, HTTPException
|
|
@@ -25,11 +27,25 @@ router = APIRouter()
|
|
| 25 |
|
| 26 |
# ββ Request / Response Models βββββββββββββββββββββββββββββββββββββββββββββββ
|
| 27 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
class ScoutRequest(BaseModel):
|
| 29 |
niche: str
|
| 30 |
channel_name: str
|
| 31 |
-
subreddits: list[str]
|
| 32 |
angle: Literal["safe_bet", "viral_play", "both"] = "both"
|
|
|
|
|
|
|
|
|
|
| 33 |
|
| 34 |
|
| 35 |
class TopicScores(BaseModel):
|
|
@@ -47,9 +63,11 @@ class PlatformStrategy(BaseModel):
|
|
| 47 |
class TopicCard(BaseModel):
|
| 48 |
title: str
|
| 49 |
angle: Literal["Safe Bet", "Viral Play"]
|
|
|
|
| 50 |
scores: TopicScores
|
| 51 |
competition_level: Literal["Low", "Medium", "High"]
|
| 52 |
trend_source: str
|
|
|
|
| 53 |
why_now: str # Specific timely context, not generic
|
| 54 |
hook_idea: str # Exact first sentence of the video
|
| 55 |
content_angles: list[str] # 4 specific approaches to this topic
|
|
@@ -61,6 +79,7 @@ class ScoutReport(BaseModel):
|
|
| 61 |
topics: list[TopicCard]
|
| 62 |
scout_summary: str
|
| 63 |
scout_insights: list[str] # 2-3 meta-level strategic observations
|
|
|
|
| 64 |
|
| 65 |
|
| 66 |
# ββ Blue Ocean Scorer ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
@@ -84,44 +103,123 @@ async def calculate_blue_ocean(topic: str) -> tuple[int, str, int]:
|
|
| 84 |
return 50, "Medium", 50
|
| 85 |
|
| 86 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
# ββ Main Route βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 88 |
|
| 89 |
@router.post("/topics", response_model=ScoutReport)
|
| 90 |
async def scout_topics(req: ScoutRequest):
|
| 91 |
"""
|
| 92 |
-
Cross-platform trend scan β
|
| 93 |
-
with scores, platform strategies, and meta insights.
|
|
|
|
| 94 |
"""
|
| 95 |
|
| 96 |
-
|
|
|
|
|
|
|
|
|
|
| 97 |
try:
|
| 98 |
-
trends = await aggregate_trends(
|
|
|
|
|
|
|
| 99 |
except Exception as e:
|
| 100 |
raise HTTPException(status_code=500, detail=f"Trend fetch failed: {e}")
|
| 101 |
|
| 102 |
-
reddit_posts
|
| 103 |
-
google_trends
|
| 104 |
-
web_snippets
|
|
|
|
|
|
|
|
|
|
| 105 |
|
| 106 |
reddit_titles = [p["title"] for p in reddit_posts]
|
| 107 |
reddit_scores = [p.get("score", 0) for p in reddit_posts]
|
| 108 |
top_reddit_score = max(reddit_scores) if reddit_scores else 0
|
| 109 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 110 |
# 2. Specificity-first AI prompt
|
| 111 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 112 |
|
| 113 |
HARD RULES β violations make the output useless:
|
| 114 |
NEVER say: "this topic is trending" β say WHY it's trending and WHAT shift/event caused it
|
| 115 |
NEVER say: "add beginner content" β say "step-by-step for someone switching from X to Y in the last 30 days"
|
|
|
|
|
|
|
| 116 |
For hook_idea: write the EXACT first sentence the creator says on camera, not a description of one
|
| 117 |
For content_angles: be specific enough that the creator can start writing a script from it
|
|
|
|
|
|
|
| 118 |
|
| 119 |
-
Return a JSON array of EXACTLY
|
| 120 |
[
|
| 121 |
-
{
|
| 122 |
"title": "specific, optimized video title β not generic",
|
| 123 |
"angle": "Safe Bet" | "Viral Play",
|
| 124 |
-
"
|
|
|
|
|
|
|
| 125 |
"why_now": "one sentence with SPECIFIC context β name the event, platform shift, or emerging pattern causing this",
|
| 126 |
"hook_idea": "the exact first sentence the creator says to open the video",
|
| 127 |
"content_angles": [
|
|
@@ -130,13 +228,13 @@ Return a JSON array of EXACTLY 3 objects:
|
|
| 130 |
"Case study: [specific real-world example]",
|
| 131 |
"Comparison: [specific A vs B with stakes]"
|
| 132 |
],
|
| 133 |
-
"platform_strategy": {
|
| 134 |
"youtube_long": "specific angle for 8-15 min deep-dive",
|
| 135 |
"shorts": "specific 30-60s hook moment extracted from this topic",
|
| 136 |
"community_post": "specific poll or curiosity question to post 2 days before publishing"
|
| 137 |
-
},
|
| 138 |
"creator_fit_score": 0-100
|
| 139 |
-
}
|
| 140 |
]
|
| 141 |
|
| 142 |
Safe Bet = proven search demand, predictable views, lower viral ceiling
|
|
@@ -144,33 +242,57 @@ Viral Play = contrarian/emotional/timely, higher ceiling but riskier
|
|
| 144 |
|
| 145 |
Return ONLY valid JSON array. No markdown, no preamble."""
|
| 146 |
|
| 147 |
-
|
| 148 |
-
|
|
|
|
|
|
|
|
|
|
| 149 |
Angle Preference: {req.angle}
|
| 150 |
|
| 151 |
Reddit Hot Posts (sorted by engagement):
|
| 152 |
-
{chr(10).join(f' [{reddit_scores[i] if i < len(reddit_scores) else 0} pts] {t}' for i, t in enumerate(reddit_titles[:8]))}
|
| 153 |
Top Reddit score this week: {top_reddit_score}
|
| 154 |
|
| 155 |
Google Trending Searches:
|
| 156 |
-
{', '.join(google_trends[:10])}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 157 |
|
| 158 |
Web Discussions:
|
| 159 |
-
{chr(10).join(f' - {w["title"] if isinstance(w, dict) else w}' for w in web_snippets[:6])}"""
|
| 160 |
|
| 161 |
try:
|
| 162 |
-
ai_response = await ask_groq(system_prompt, user_prompt, max_tokens=
|
| 163 |
clean = ai_response.strip().lstrip("```json").lstrip("```").rstrip("```").strip()
|
| 164 |
raw_topics = json.loads(clean)
|
|
|
|
|
|
|
| 165 |
except Exception as e:
|
| 166 |
raise HTTPException(status_code=500, detail=f"AI topic generation failed: {e}")
|
| 167 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 168 |
# 3. Blue Ocean scores + meta insights in parallel
|
| 169 |
-
bo_tasks = [calculate_blue_ocean(t
|
| 170 |
|
| 171 |
topics_summary = "\n".join(f"- {t.get('title', '')}" for t in raw_topics)
|
| 172 |
insights_system = "You are a YouTube niche strategist. Return ONLY a JSON array of strings. No markdown."
|
| 173 |
-
insights_prompt = f"""Given these
|
| 174 |
{topics_summary}
|
| 175 |
|
| 176 |
Give 2-3 strategic meta-observations about the niche RIGHT NOW.
|
|
@@ -192,11 +314,11 @@ Return: ["observation 1", "observation 2", "observation 3"]"""
|
|
| 192 |
if not isinstance(scout_insights, list):
|
| 193 |
scout_insights = [str(scout_insights)]
|
| 194 |
except Exception:
|
| 195 |
-
scout_insights = [f"Cross-platform scan complete for '{
|
| 196 |
|
| 197 |
# 4. Assemble final topic cards
|
| 198 |
topic_cards = []
|
| 199 |
-
for i, topic in enumerate(raw_topics
|
| 200 |
try:
|
| 201 |
bo = bo_results[i] if not isinstance(bo_results[i], Exception) else (50, "Medium", 50)
|
| 202 |
bo_score, competition, trend_score = bo
|
|
@@ -205,10 +327,12 @@ Return: ["observation 1", "observation 2", "observation 3"]"""
|
|
| 205 |
|
| 206 |
fit_score = max(0, min(100, int(topic.get("creator_fit_score", 75))))
|
| 207 |
ps_raw = topic.get("platform_strategy", {})
|
|
|
|
| 208 |
|
| 209 |
topic_cards.append(TopicCard(
|
| 210 |
title=topic.get("title", ""),
|
| 211 |
angle=topic.get("angle", "Safe Bet"),
|
|
|
|
| 212 |
scores=TopicScores(
|
| 213 |
trend_score=trend_score,
|
| 214 |
competition_score=bo_score,
|
|
@@ -216,6 +340,7 @@ Return: ["observation 1", "observation 2", "observation 3"]"""
|
|
| 216 |
),
|
| 217 |
competition_level=competition,
|
| 218 |
trend_source=topic.get("trend_source", "Multi-source"),
|
|
|
|
| 219 |
why_now=topic.get("why_now", ""),
|
| 220 |
hook_idea=topic.get("hook_idea", ""),
|
| 221 |
content_angles=topic.get("content_angles", [])[:4],
|
|
@@ -226,19 +351,23 @@ Return: ["observation 1", "observation 2", "observation 3"]"""
|
|
| 226 |
),
|
| 227 |
))
|
| 228 |
|
| 229 |
-
# Filter by angle preference
|
| 230 |
if req.angle == "safe_bet":
|
| 231 |
-
|
|
|
|
| 232 |
elif req.angle == "viral_play":
|
| 233 |
-
|
|
|
|
| 234 |
|
| 235 |
return ScoutReport(
|
| 236 |
-
niche=
|
| 237 |
topics=topic_cards,
|
| 238 |
scout_summary=(
|
| 239 |
-
f"Scanned {
|
| 240 |
-
f"
|
| 241 |
-
f"{len(topic_cards)} high-probability topics identified
|
|
|
|
| 242 |
),
|
| 243 |
scout_insights=scout_insights[:3] if isinstance(scout_insights, list) else [],
|
| 244 |
-
|
|
|
|
|
|
| 1 |
"""
|
| 2 |
+
routes/scout_router.py [v3 - 7-Pillar Blueprint + 4 Topics + User Topic + Multi-source Demand]
|
| 3 |
+
|
| 4 |
+
Changes over v2:
|
| 5 |
+
- Consumes the full 7-Pillar Creator DNA (creator_type, sub_type, niche,
|
| 6 |
+
sub_niche, language, target_audience, format) as a targeted search blueprint
|
| 7 |
+
- Returns EXACTLY 4 topics (was 3)
|
| 8 |
+
- user_topic: creator can hand in a topic on their mind. When supplied, exactly
|
| 9 |
+
ONE of the 4 cards is built around it and flagged is_user_topic=true
|
| 10 |
+
- Scans Reddit, X (Twitter), YouTube, Google Trends + search, and News β and
|
| 11 |
+
every card states where_demand (which platforms the demand is coming from)
|
| 12 |
+
- Search runs ONLY on request (the frontend fires this on button click)
|
| 13 |
+
- Backward compatible: niche / channel_name / subreddits / angle still accepted
|
| 14 |
"""
|
| 15 |
|
| 16 |
from fastapi import APIRouter, HTTPException
|
|
|
|
| 27 |
|
| 28 |
# ββ Request / Response Models βββββββββββββββββββββββββββββββββββββββββββββββ
|
| 29 |
|
| 30 |
+
class CreatorBlueprint(BaseModel):
|
| 31 |
+
"""The 7-Pillar Creator DNA, used to target the trend scan for THIS creator."""
|
| 32 |
+
creator_type: str = ""
|
| 33 |
+
sub_type: str = "" # may be "None"
|
| 34 |
+
niche: str = ""
|
| 35 |
+
sub_niche: str = "" # may be "None"
|
| 36 |
+
language: str = "English"
|
| 37 |
+
target_audience: str = ""
|
| 38 |
+
format: str = "" # "Personality" | "Faceless"
|
| 39 |
+
|
| 40 |
+
|
| 41 |
class ScoutRequest(BaseModel):
|
| 42 |
niche: str
|
| 43 |
channel_name: str
|
| 44 |
+
subreddits: list[str] = []
|
| 45 |
angle: Literal["safe_bet", "viral_play", "both"] = "both"
|
| 46 |
+
# ββ v3 additions ββ
|
| 47 |
+
blueprint: Optional[CreatorBlueprint] = None
|
| 48 |
+
user_topic: Optional[str] = None # a topic the creator already has in mind
|
| 49 |
|
| 50 |
|
| 51 |
class TopicScores(BaseModel):
|
|
|
|
| 63 |
class TopicCard(BaseModel):
|
| 64 |
title: str
|
| 65 |
angle: Literal["Safe Bet", "Viral Play"]
|
| 66 |
+
is_user_topic: bool = False # True for the card built from user_topic
|
| 67 |
scores: TopicScores
|
| 68 |
competition_level: Literal["Low", "Medium", "High"]
|
| 69 |
trend_source: str
|
| 70 |
+
where_demand: str # WHERE the demand is coming from (platforms)
|
| 71 |
why_now: str # Specific timely context, not generic
|
| 72 |
hook_idea: str # Exact first sentence of the video
|
| 73 |
content_angles: list[str] # 4 specific approaches to this topic
|
|
|
|
| 79 |
topics: list[TopicCard]
|
| 80 |
scout_summary: str
|
| 81 |
scout_insights: list[str] # 2-3 meta-level strategic observations
|
| 82 |
+
sources_scanned: list[str] # which platforms actually returned signal
|
| 83 |
|
| 84 |
|
| 85 |
# ββ Blue Ocean Scorer ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
|
|
| 103 |
return 50, "Medium", 50
|
| 104 |
|
| 105 |
|
| 106 |
+
# ββ Blueprint helpers ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 107 |
+
|
| 108 |
+
def _clean(v: str) -> str:
|
| 109 |
+
v = (v or "").strip()
|
| 110 |
+
return "" if v.lower() in ("", "none", "n/a", "unknown") else v
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def build_blueprint_block(req: ScoutRequest) -> str:
|
| 114 |
+
"""Render the 7-Pillar DNA as a compact block for the AI prompt."""
|
| 115 |
+
bp = req.blueprint
|
| 116 |
+
if not bp:
|
| 117 |
+
return f"Creator Niche: {req.niche}\nChannel: {req.channel_name}"
|
| 118 |
+
|
| 119 |
+
rows = [
|
| 120 |
+
("Creator Type", _clean(bp.creator_type)),
|
| 121 |
+
("Sub-Type", _clean(bp.sub_type)),
|
| 122 |
+
("Niche", _clean(bp.niche) or req.niche),
|
| 123 |
+
("Sub-Niche", _clean(bp.sub_niche)),
|
| 124 |
+
("Language", _clean(bp.language) or "English"),
|
| 125 |
+
("Target Audience", _clean(bp.target_audience)),
|
| 126 |
+
("Format", _clean(bp.format)),
|
| 127 |
+
]
|
| 128 |
+
lines = [f" {k}: {v}" for k, v in rows if v]
|
| 129 |
+
return "7-PILLAR CREATOR DNA (target every topic to THIS creator):\n" + "\n".join(lines)
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def interest_keywords(req: ScoutRequest) -> list[str]:
|
| 133 |
+
"""Keywords fed to Google Trends so 'trending' is grounded in real velocity."""
|
| 134 |
+
bp = req.blueprint
|
| 135 |
+
kws = []
|
| 136 |
+
if bp:
|
| 137 |
+
kws += [_clean(bp.sub_niche), _clean(bp.niche)]
|
| 138 |
+
kws += [req.niche]
|
| 139 |
+
if req.user_topic:
|
| 140 |
+
kws.insert(0, req.user_topic.strip())
|
| 141 |
+
seen, out = set(), []
|
| 142 |
+
for k in kws:
|
| 143 |
+
k = (k or "").strip()
|
| 144 |
+
if k and k.lower() not in seen:
|
| 145 |
+
seen.add(k.lower())
|
| 146 |
+
out.append(k)
|
| 147 |
+
return out[:5]
|
| 148 |
+
|
| 149 |
+
|
| 150 |
# ββ Main Route βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 151 |
|
| 152 |
@router.post("/topics", response_model=ScoutReport)
|
| 153 |
async def scout_topics(req: ScoutRequest):
|
| 154 |
"""
|
| 155 |
+
Cross-platform trend scan β 4 high-probability topic recommendations
|
| 156 |
+
with scores, platform strategies, demand sourcing, and meta insights.
|
| 157 |
+
Runs only when called (frontend fires this on the creator's button click).
|
| 158 |
"""
|
| 159 |
|
| 160 |
+
niche = (req.blueprint.niche if req.blueprint and _clean(req.blueprint.niche) else req.niche) or req.niche
|
| 161 |
+
user_topic = (req.user_topic or "").strip()
|
| 162 |
+
|
| 163 |
+
# 1. Aggregate all free trend sources in parallel (Reddit, Trends, X, News, Web)
|
| 164 |
try:
|
| 165 |
+
trends = await aggregate_trends(
|
| 166 |
+
niche, req.subreddits, interest_keywords=interest_keywords(req)
|
| 167 |
+
)
|
| 168 |
except Exception as e:
|
| 169 |
raise HTTPException(status_code=500, detail=f"Trend fetch failed: {e}")
|
| 170 |
|
| 171 |
+
reddit_posts = trends.get("reddit", [])[:10]
|
| 172 |
+
google_trends = trends.get("google_trending", [])[:10]
|
| 173 |
+
web_snippets = trends.get("web_discussions", [])[:8]
|
| 174 |
+
x_snippets = trends.get("x_discussions", [])[:8]
|
| 175 |
+
news_snippets = trends.get("news", [])[:8]
|
| 176 |
+
niche_interest = trends.get("niche_interest", {}) or {}
|
| 177 |
|
| 178 |
reddit_titles = [p["title"] for p in reddit_posts]
|
| 179 |
reddit_scores = [p.get("score", 0) for p in reddit_posts]
|
| 180 |
top_reddit_score = max(reddit_scores) if reddit_scores else 0
|
| 181 |
|
| 182 |
+
# Which platforms actually returned signal (for honesty in the UI)
|
| 183 |
+
sources_scanned = []
|
| 184 |
+
if reddit_titles: sources_scanned.append("Reddit")
|
| 185 |
+
if google_trends: sources_scanned.append("Google Trends")
|
| 186 |
+
if x_snippets: sources_scanned.append("X")
|
| 187 |
+
if news_snippets: sources_scanned.append("News")
|
| 188 |
+
if web_snippets: sources_scanned.append("Web")
|
| 189 |
+
sources_scanned.append("YouTube") # always probed via Blue Ocean
|
| 190 |
+
|
| 191 |
+
blueprint_block = build_blueprint_block(req)
|
| 192 |
+
|
| 193 |
# 2. Specificity-first AI prompt
|
| 194 |
+
user_topic_rule = (
|
| 195 |
+
f'\n The creator already has a topic in mind: "{user_topic}". '
|
| 196 |
+
f'The FIRST object MUST be built around THIS topic (sharpen it into a real '
|
| 197 |
+
f'video angle, do not discard it) and you MUST set "is_user_topic": true on it. '
|
| 198 |
+
f'The other 3 are discovered from the trend signals with "is_user_topic": false.'
|
| 199 |
+
if user_topic else
|
| 200 |
+
'\n Set "is_user_topic": false on every object (no creator-supplied topic this run).'
|
| 201 |
+
)
|
| 202 |
+
|
| 203 |
+
system_prompt = f"""You are a senior YouTube content strategist who turns a creator's DNA into underserved, high-probability video topics.
|
| 204 |
|
| 205 |
HARD RULES β violations make the output useless:
|
| 206 |
NEVER say: "this topic is trending" β say WHY it's trending and WHAT shift/event caused it
|
| 207 |
NEVER say: "add beginner content" β say "step-by-step for someone switching from X to Y in the last 30 days"
|
| 208 |
+
Every topic must fit the creator's 7-Pillar DNA β respect their niche, sub-niche, format and audience
|
| 209 |
+
For where_demand: name the SPECIFIC platforms the demand is coming from and the signal (e.g. "Reddit r/X (3 hot threads) + a Google Trends spike + 2 news items this week")
|
| 210 |
For hook_idea: write the EXACT first sentence the creator says on camera, not a description of one
|
| 211 |
For content_angles: be specific enough that the creator can start writing a script from it
|
| 212 |
+
Respect the creator's Format: if Faceless, angles must not assume an on-camera personality; if Personality, lean into their on-camera presence
|
| 213 |
+
Write titles/hooks in the creator's Language.{user_topic_rule}
|
| 214 |
|
| 215 |
+
Return a JSON array of EXACTLY 4 objects:
|
| 216 |
[
|
| 217 |
+
{{
|
| 218 |
"title": "specific, optimized video title β not generic",
|
| 219 |
"angle": "Safe Bet" | "Viral Play",
|
| 220 |
+
"is_user_topic": true | false,
|
| 221 |
+
"trend_source": "Reddit" | "X" | "Google Trends" | "News" | "Web" | "Multi-source",
|
| 222 |
+
"where_demand": "specific platforms + signal where audience demand is visible right now",
|
| 223 |
"why_now": "one sentence with SPECIFIC context β name the event, platform shift, or emerging pattern causing this",
|
| 224 |
"hook_idea": "the exact first sentence the creator says to open the video",
|
| 225 |
"content_angles": [
|
|
|
|
| 228 |
"Case study: [specific real-world example]",
|
| 229 |
"Comparison: [specific A vs B with stakes]"
|
| 230 |
],
|
| 231 |
+
"platform_strategy": {{
|
| 232 |
"youtube_long": "specific angle for 8-15 min deep-dive",
|
| 233 |
"shorts": "specific 30-60s hook moment extracted from this topic",
|
| 234 |
"community_post": "specific poll or curiosity question to post 2 days before publishing"
|
| 235 |
+
}},
|
| 236 |
"creator_fit_score": 0-100
|
| 237 |
+
}}
|
| 238 |
]
|
| 239 |
|
| 240 |
Safe Bet = proven search demand, predictable views, lower viral ceiling
|
|
|
|
| 242 |
|
| 243 |
Return ONLY valid JSON array. No markdown, no preamble."""
|
| 244 |
|
| 245 |
+
trend_interest_str = ", ".join(
|
| 246 |
+
f"{k}: {v}" for k, v in list(niche_interest.items())[:5]
|
| 247 |
+
) or "no strong single-keyword spike detected"
|
| 248 |
+
|
| 249 |
+
user_prompt = f"""{blueprint_block}
|
| 250 |
Angle Preference: {req.angle}
|
| 251 |
|
| 252 |
Reddit Hot Posts (sorted by engagement):
|
| 253 |
+
{chr(10).join(f' [{reddit_scores[i] if i < len(reddit_scores) else 0} pts] {t}' for i, t in enumerate(reddit_titles[:8])) or ' (no reddit signal)'}
|
| 254 |
Top Reddit score this week: {top_reddit_score}
|
| 255 |
|
| 256 |
Google Trending Searches:
|
| 257 |
+
{', '.join(google_trends[:10]) or '(none)'}
|
| 258 |
+
|
| 259 |
+
Google Trends interest for niche keywords (last 7 days):
|
| 260 |
+
{trend_interest_str}
|
| 261 |
+
|
| 262 |
+
X (Twitter) Chatter:
|
| 263 |
+
{chr(10).join(f' - {(w.get("title") or w.get("snippet"))[:160] if isinstance(w, dict) else w}' for w in x_snippets[:6]) or ' (no X signal)'}
|
| 264 |
+
|
| 265 |
+
Recent News:
|
| 266 |
+
{chr(10).join(f' - {(w.get("title") or "")[:160] if isinstance(w, dict) else w}' for w in news_snippets[:6]) or ' (no news signal)'}
|
| 267 |
|
| 268 |
Web Discussions:
|
| 269 |
+
{chr(10).join(f' - {w["title"] if isinstance(w, dict) else w}' for w in web_snippets[:6]) or ' (none)'}"""
|
| 270 |
|
| 271 |
try:
|
| 272 |
+
ai_response = await ask_groq(system_prompt, user_prompt, max_tokens=2000)
|
| 273 |
clean = ai_response.strip().lstrip("```json").lstrip("```").rstrip("```").strip()
|
| 274 |
raw_topics = json.loads(clean)
|
| 275 |
+
if not isinstance(raw_topics, list):
|
| 276 |
+
raise ValueError("AI did not return a JSON array")
|
| 277 |
except Exception as e:
|
| 278 |
raise HTTPException(status_code=500, detail=f"AI topic generation failed: {e}")
|
| 279 |
|
| 280 |
+
# Make sure the user's topic is first and flagged even if the model slipped
|
| 281 |
+
if user_topic and raw_topics:
|
| 282 |
+
flagged = [t for t in raw_topics if t.get("is_user_topic")]
|
| 283 |
+
if not flagged:
|
| 284 |
+
raw_topics[0]["is_user_topic"] = True
|
| 285 |
+
# move the flagged one to the front
|
| 286 |
+
raw_topics.sort(key=lambda t: 0 if t.get("is_user_topic") else 1)
|
| 287 |
+
|
| 288 |
+
raw_topics = raw_topics[:4]
|
| 289 |
+
|
| 290 |
# 3. Blue Ocean scores + meta insights in parallel
|
| 291 |
+
bo_tasks = [calculate_blue_ocean(t.get("title", "")) for t in raw_topics]
|
| 292 |
|
| 293 |
topics_summary = "\n".join(f"- {t.get('title', '')}" for t in raw_topics)
|
| 294 |
insights_system = "You are a YouTube niche strategist. Return ONLY a JSON array of strings. No markdown."
|
| 295 |
+
insights_prompt = f"""Given these topic ideas for a '{niche}' creator:
|
| 296 |
{topics_summary}
|
| 297 |
|
| 298 |
Give 2-3 strategic meta-observations about the niche RIGHT NOW.
|
|
|
|
| 314 |
if not isinstance(scout_insights, list):
|
| 315 |
scout_insights = [str(scout_insights)]
|
| 316 |
except Exception:
|
| 317 |
+
scout_insights = [f"Cross-platform scan complete for '{niche}' niche."]
|
| 318 |
|
| 319 |
# 4. Assemble final topic cards
|
| 320 |
topic_cards = []
|
| 321 |
+
for i, topic in enumerate(raw_topics):
|
| 322 |
try:
|
| 323 |
bo = bo_results[i] if not isinstance(bo_results[i], Exception) else (50, "Medium", 50)
|
| 324 |
bo_score, competition, trend_score = bo
|
|
|
|
| 327 |
|
| 328 |
fit_score = max(0, min(100, int(topic.get("creator_fit_score", 75))))
|
| 329 |
ps_raw = topic.get("platform_strategy", {})
|
| 330 |
+
is_user = bool(topic.get("is_user_topic", False))
|
| 331 |
|
| 332 |
topic_cards.append(TopicCard(
|
| 333 |
title=topic.get("title", ""),
|
| 334 |
angle=topic.get("angle", "Safe Bet"),
|
| 335 |
+
is_user_topic=is_user,
|
| 336 |
scores=TopicScores(
|
| 337 |
trend_score=trend_score,
|
| 338 |
competition_score=bo_score,
|
|
|
|
| 340 |
),
|
| 341 |
competition_level=competition,
|
| 342 |
trend_source=topic.get("trend_source", "Multi-source"),
|
| 343 |
+
where_demand=topic.get("where_demand", ""),
|
| 344 |
why_now=topic.get("why_now", ""),
|
| 345 |
hook_idea=topic.get("hook_idea", ""),
|
| 346 |
content_angles=topic.get("content_angles", [])[:4],
|
|
|
|
| 351 |
),
|
| 352 |
))
|
| 353 |
|
| 354 |
+
# Filter by angle preference β but NEVER drop the creator's own topic
|
| 355 |
if req.angle == "safe_bet":
|
| 356 |
+
kept = [t for t in topic_cards if t.angle == "Safe Bet" or t.is_user_topic]
|
| 357 |
+
topic_cards = kept or topic_cards
|
| 358 |
elif req.angle == "viral_play":
|
| 359 |
+
kept = [t for t in topic_cards if t.angle == "Viral Play" or t.is_user_topic]
|
| 360 |
+
topic_cards = kept or topic_cards
|
| 361 |
|
| 362 |
return ScoutReport(
|
| 363 |
+
niche=niche,
|
| 364 |
topics=topic_cards,
|
| 365 |
scout_summary=(
|
| 366 |
+
f"Scanned {', '.join(sources_scanned)} "
|
| 367 |
+
f"({len(reddit_titles)} Reddit posts, top score {top_reddit_score} pts). "
|
| 368 |
+
f"{len(topic_cards)} high-probability topics identified"
|
| 369 |
+
+ (f", including your topic \"{user_topic}\"." if user_topic else ".")
|
| 370 |
),
|
| 371 |
scout_insights=scout_insights[:3] if isinstance(scout_insights, list) else [],
|
| 372 |
+
sources_scanned=sources_scanned,
|
| 373 |
+
)
|