ihtesham0345 commited on
Commit
6e467d1
·
1 Parent(s): 38098b4

fix: Simplify prompts for 0.5B model reliability + resilient error handling

Browse files

- Reduce output requirements (5 titles, 10 tags, 3 thumbnails, etc.)
- Add v2 JSON repair logic for truncated output
- Always return defaults-filled data instead of 500 errors
- Pass defaults to run_analysis for error resilience
- Remove HTTPException 500 — API always returns 200 with error field

main.py CHANGED
@@ -26,14 +26,10 @@ ERROR_MASK = "An internal error occurred. Please try again later."
26
  def safe_analyze(analyze_fn, content: str):
27
  try:
28
  result = analyze_fn(content)
29
- if isinstance(result, dict) and result.get("error"):
30
- raise HTTPException(status_code=500, detail=str(result["error"]))
31
  return result
32
- except HTTPException:
33
- raise
34
  except Exception as e:
35
  print(f"CRITICAL SERVER ERROR: {e}\n{traceback.format_exc()}")
36
- raise HTTPException(status_code=500, detail=ERROR_MASK)
37
 
38
  # ---------------------------------------------------------------------------
39
  # Root
 
26
  def safe_analyze(analyze_fn, content: str):
27
  try:
28
  result = analyze_fn(content)
 
 
29
  return result
 
 
30
  except Exception as e:
31
  print(f"CRITICAL SERVER ERROR: {e}\n{traceback.format_exc()}")
32
+ return {"error": ERROR_MASK}
33
 
34
  # ---------------------------------------------------------------------------
35
  # Root
services/analyzer.py CHANGED
@@ -1,16 +1,12 @@
1
- from services.utils import run_analysis, validate_and_fill_data_defaults
2
 
3
- SYSTEM_PROMPT = """You are a World-Class SEO Strategist. Return ONLY valid JSON.
4
- RULES:
5
- 1. Estimate 'search_volume' (High/Medium/Low).
6
- 2. 'competition' (Hard/Medium/Easy).
7
- 3. 'relevance' (0-100)."""
8
 
9
  DEFAULTS = {
10
- "core_keywords": [],
11
- "related_phrases": [],
12
- "viral_hashtags": [],
13
- "content_titles": ["Content Strategy Guide", "SEO Optimization Tips", "Viral Content Ideas"],
14
  "strategy_tips": ["Focus on user intent.", "Optimize for long-tail keywords.", "Improve meta tags."],
15
  "target_audience": "General Audience interested in this topic."
16
  }
@@ -18,32 +14,7 @@ DEFAULTS = {
18
  def analyze_seo_content(content: str) -> dict:
19
  messages = [
20
  {"role": "system", "content": SYSTEM_PROMPT},
21
- {"role": "user", "content": f"""Analyze topic: "{content[:2000]}"
22
-
23
- REQUIREMENTS:
24
- - **Core Keywords**: 30 high-value keywords.
25
- - **Related Phrases**: 10 variations.
26
- - **Viral Hashtags**: 8 tags.
27
- - **Content Titles**: 3 titles.
28
- - **Strategy Tips**: 3 tips.
29
- - **Target Audience**: Profile.
30
-
31
- JSON OUTPUT STRUCTURE:
32
- {{
33
- "core_keywords": [
34
- {{"keyword": "...", "search_volume": "...", "competition": "...", "relevance": 90}}, ... (Total 30 items)
35
- ],
36
- "related_phrases": ["..."],
37
- "viral_hashtags": [{{"tag": "#...", "post_count": "..."}}],
38
- "content_titles": ["..."],
39
- "strategy_tips": ["..."],
40
- "target_audience": "..."
41
- }}"""}
42
  ]
43
-
44
- data = run_analysis(messages, temperature=0.3)
45
- if isinstance(data, dict) and "error" in data:
46
- return data
47
-
48
- # Apply defaults for missing fields
49
- return validate_and_fill_data_defaults(data, DEFAULTS)
 
1
+ from services.utils import run_analysis
2
 
3
+ SYSTEM_PROMPT = """You are an SEO strategist. Return ONLY valid JSON with keywords, hashtags, content titles, strategy tips, and target audience."""
 
 
 
 
4
 
5
  DEFAULTS = {
6
+ "core_keywords": [{"keyword": "topic guide", "search_volume": "Medium", "competition": "Medium", "relevance": 85}],
7
+ "related_phrases": ["related topic ideas"],
8
+ "viral_hashtags": [{"tag": "#Topic", "post_count": "100K+"}],
9
+ "content_titles": ["Complete Guide", "Top Tips", "Beginners Guide"],
10
  "strategy_tips": ["Focus on user intent.", "Optimize for long-tail keywords.", "Improve meta tags."],
11
  "target_audience": "General Audience interested in this topic."
12
  }
 
14
  def analyze_seo_content(content: str) -> dict:
15
  messages = [
16
  {"role": "system", "content": SYSTEM_PROMPT},
17
+ {"role": "user", "content": f'Topic: "{content[:1500]}"\n\nReturn JSON with:\n- core_keywords: list of {{"keyword": str, "search_volume": str, "competition": str, "relevance": int}} (10 keywords)\n- related_phrases: list of strings (5 phrases)\n- viral_hashtags: list of {{"tag": str, "post_count": str}} (5 hashtags)\n- content_titles: list of strings (3 titles)\n- strategy_tips: list of strings (3 tips)\n- target_audience: string'}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
  ]
19
+
20
+ return run_analysis(messages, defaults=DEFAULTS, temperature=0.3, max_new_tokens=1500)
 
 
 
 
 
services/facebook_analyzer.py CHANGED
@@ -1,50 +1,20 @@
1
- from services.utils import run_analysis, validate_and_fill_data_defaults
2
 
3
- SYSTEM_PROMPT = """You are a Facebook Marketing Expert specializing in organic reach, Facebook Groups, Page growth, and advertising psychology. You understand the Facebook algorithm, meaningful interactions, and ad copy optimization. Return ONLY valid JSON.
4
-
5
- RULES:
6
- 1. Post ideas must specify content type: text, image, video, link, poll, live
7
- 2. Engagement hooks must target emotional triggers (curiosity, outrage, inspiration, humor, nostalgia)
8
- 3. Ad copy must follow AIDA framework (Attention, Interest, Desire, Action)
9
- 4. Hashtags: 3-5 relevant tags maximum
10
- 5. Facebook algorithm prioritizes meaningful interactions (comments > shares > reactions)
11
- 6. Native video gets 10x more reach than external links"""
12
 
13
  DEFAULTS = {
14
- "post_ideas": [],
15
- "engagement_hooks": [],
16
- "hashtags": [],
17
- "ad_copy_suggestions": [],
18
- "best_posting_time": "1-3 PM EST on weekdays",
19
- "page_growth_tips": ["Post consistently", "Engage in relevant Groups", "Go live weekly"]
20
  }
21
 
22
  def analyze_facebook(content: str) -> dict:
23
  messages = [
24
  {"role": "system", "content": SYSTEM_PROMPT},
25
- {"role": "user", "content": f"""Analyze topic for Facebook strategy: "{content[:2000]}"
26
-
27
- REQUIREMENTS:
28
- - **Post Ideas**: 8 post ideas with type (text/image/video/link/poll/live) and full content
29
- - **Engagement Hooks**: 10 hooks targeting different emotional triggers
30
- - **Hashtags**: 5 optimized hashtags
31
- - **Ad Copy Suggestions**: 3 ad copies following AIDA framework
32
- - **Best Posting Time**: Optimal day and time
33
- - **Page Growth Tips**: 5 actionable tips
34
-
35
- JSON OUTPUT STRUCTURE:
36
- {{
37
- "post_ideas": [
38
- {{"type": "video", "content": "..."}}, ... (Total 8 items)
39
- ],
40
- "engagement_hooks": ["..."],
41
- "hashtags": ["..."],
42
- "ad_copy_suggestions": ["..."],
43
- "best_posting_time": "...",
44
- "page_growth_tips": ["..."]
45
- }}"""}
46
  ]
47
- data = run_analysis(messages, temperature=0.35, max_new_tokens=2000)
48
- if isinstance(data, dict) and "error" in data:
49
- return data
50
- return validate_and_fill_data_defaults(data, DEFAULTS)
 
1
+ from services.utils import run_analysis
2
 
3
+ SYSTEM_PROMPT = """You are a Facebook marketing expert. Return ONLY valid JSON with post ideas, engagement hooks, hashtags, ad copy, posting time, and growth tips."""
 
 
 
 
 
 
 
 
4
 
5
  DEFAULTS = {
6
+ "post_ideas": [{"type": "text", "content": "Share your thoughts on this topic below!"}],
7
+ "engagement_hooks": ["What do you think about this?"],
8
+ "hashtags": ["#topic", "#discussion"],
9
+ "ad_copy_suggestions": ["Attention: this is important for your business"],
10
+ "best_posting_time": "1-3 PM EST weekdays",
11
+ "page_growth_tips": ["Post consistently", "Engage in relevant Groups"]
12
  }
13
 
14
  def analyze_facebook(content: str) -> dict:
15
  messages = [
16
  {"role": "system", "content": SYSTEM_PROMPT},
17
+ {"role": "user", "content": f'Topic: "{content[:1500]}"\n\nReturn JSON with:\n- post_ideas: list of {{"type": str, "content": str}} (4 posts, types: text/image/video/link/poll)\n- engagement_hooks: list of strings (5 hooks)\n- hashtags: list of strings (5 hashtags)\n- ad_copy_suggestions: list of strings (3 ad copies)\n- best_posting_time: string\n- page_growth_tips: list of strings (3 tips)'}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
  ]
19
+
20
+ return run_analysis(messages, defaults=DEFAULTS, temperature=0.3, max_new_tokens=1500)
 
 
services/instagram_analyzer.py CHANGED
@@ -1,54 +1,19 @@
1
- from services.utils import run_analysis, validate_and_fill_data_defaults
2
 
3
- SYSTEM_PROMPT = """You are a top Instagram Growth Strategist and Content Creator. You specialize in the Instagram algorithm, visual aesthetics, Reels, Carousels, Stories, and viral marketing. Return ONLY valid JSON.
4
-
5
- RULES:
6
- 1. Captions must have a strong hook in first line, value in middle, CTA at end
7
- 2. Hash tag sets must be tiered: small (10k-50k posts), medium (50k-500k), large (500k+)
8
- 3. Content ideas must specify format: Reel (<90s), Carousel (5-10 slides), Story (interactive)
9
- 4. Growth strategies focused on: collaboration, trending audio, consistent posting, engagement pods
10
- 5. Instagram algorithm prioritizes: saves > shares > comments > likes > reach"""
11
 
12
  DEFAULTS = {
13
- "captions": [],
14
- "hashtag_sets": {"small": [], "medium": [], "large": []},
15
- "content_ideas": {"reels": [], "carousels": [], "stories": []},
16
- "best_posting_time": "9-11 AM EST on weekdays",
17
- "growth_strategies": ["Post consistently", "Use trending audio", "Engage with niche community"]
18
  }
19
 
20
  def analyze_instagram(content: str) -> dict:
21
  messages = [
22
  {"role": "system", "content": SYSTEM_PROMPT},
23
- {"role": "user", "content": f"""Analyze topic for Instagram strategy: "{content[:2000]}"
24
-
25
- REQUIREMENTS:
26
- - **Captions**: 5 full captions with different tones (educational, entertaining, inspirational, behind-the-scenes, promotional)
27
- - **Hashtag Sets**: 10 small-tier, 10 medium-tier, 10 large-tier hashtags
28
- - **Content Ideas**: 4 Reel concepts, 4 Carousel ideas, 4 Story concepts
29
- - **Best Posting Time**: Optimal day and time
30
- - **Growth Strategies**: 5 actionable strategies
31
-
32
- JSON OUTPUT STRUCTURE:
33
- {{
34
- "captions": [
35
- {{"caption": "...", "tone": "..."}}, ... (Total 5 items)
36
- ],
37
- "hashtag_sets": {{
38
- "small": ["#...", "#..."],
39
- "medium": ["#...", "#..."],
40
- "large": ["#...", "#..."]
41
- }},
42
- "content_ideas": {{
43
- "reels": ["..."],
44
- "carousels": ["..."],
45
- "stories": ["..."]
46
- }},
47
- "best_posting_time": "...",
48
- "growth_strategies": ["..."]
49
- }}"""}
50
  ]
51
- data = run_analysis(messages, temperature=0.4, max_new_tokens=2000)
52
- if isinstance(data, dict) and "error" in data:
53
- return data
54
- return validate_and_fill_data_defaults(data, DEFAULTS)
 
1
+ from services.utils import run_analysis
2
 
3
+ SYSTEM_PROMPT = """You are an Instagram growth expert. Return ONLY valid JSON with captions, hashtags, content ideas, posting time, and growth strategies."""
 
 
 
 
 
 
 
4
 
5
  DEFAULTS = {
6
+ "captions": [{"caption": "Check out this amazing content about [TOPIC]!", "tone": "engaging"}],
7
+ "hashtag_sets": {"small": ["#niche"], "medium": ["#topic"], "large": ["#viral"]},
8
+ "content_ideas": {"reels": ["Quick tip video"], "carousels": ["Step-by-step guide"], "stories": ["Poll your audience"]},
9
+ "best_posting_time": "9-11 AM EST weekdays",
10
+ "growth_strategies": ["Post consistently", "Engage with niche community"]
11
  }
12
 
13
  def analyze_instagram(content: str) -> dict:
14
  messages = [
15
  {"role": "system", "content": SYSTEM_PROMPT},
16
+ {"role": "user", "content": f'Topic: "{content[:1500]}"\n\nReturn JSON with:\n- captions: list of {{"caption": str, "tone": str}} (3 captions, tones: educational, entertaining, inspirational)\n- hashtag_sets: {{"small": [str], "medium": [str], "large": [str]}} (5 each)\n- content_ideas: {{"reels": [str], "carousels": [str], "stories": [str]}} (2 each)\n- best_posting_time: string\n- growth_strategies: list of strings (3 strategies)'}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
  ]
18
+
19
+ return run_analysis(messages, defaults=DEFAULTS, temperature=0.35, max_new_tokens=1500)
 
 
services/linkedin_analyzer.py CHANGED
@@ -1,50 +1,20 @@
1
- from services.utils import run_analysis, validate_and_fill_data_defaults
2
 
3
- SYSTEM_PROMPT = """You are a distinguished LinkedIn Content Strategist and Personal Branding Expert. You specialize in B2B networking, professional storytelling, thought leadership, and the LinkedIn algorithm. Return ONLY valid JSON.
4
-
5
- RULES:
6
- 1. Post drafts must follow proven LinkedIn frameworks (hook → story → insight → CTA)
7
- 2. Headlines must be curiosity-driven or contrarian within professional bounds
8
- 3. Hashtags: max 5, mix of broad industry + niche specific
9
- 4. Article topics should position the author as a thought leader
10
- 5. Best post length: 900-1200 characters
11
- 6. LinkedIn algorithm favors: dwell time > comments > reactions > shares"""
12
 
13
  DEFAULTS = {
14
- "post_drafts": [],
15
- "hashtags": [],
16
- "article_topics": [],
17
- "thought_leadership_angles": [],
18
- "best_posting_time": "7-9 AM EST on weekdays (Tue-Thu best)",
19
- "industry_insights": "Focus on providing unique data-driven perspectives in your niche."
20
  }
21
 
22
  def analyze_linkedin(content: str) -> dict:
23
  messages = [
24
  {"role": "system", "content": SYSTEM_PROMPT},
25
- {"role": "user", "content": f"""Analyze topic for LinkedIn strategy: "{content[:2000]}"
26
-
27
- REQUIREMENTS:
28
- - **Post Drafts**: 5 full LinkedIn posts with headline, body, and hook
29
- - **Hashtags**: 5 optimized hashtags
30
- - **Article Topics**: 5 long-form article topic ideas
31
- - **Thought Leadership Angles**: 5 unique perspectives/angles
32
- - **Best Posting Time**: Optimal day and time
33
- - **Industry Insights**: 1 paragraph of key industry observations
34
-
35
- JSON OUTPUT STRUCTURE:
36
- {{
37
- "post_drafts": [
38
- {{"headline": "...", "body": "...", "hook": "..."}}, ... (Total 5 items)
39
- ],
40
- "hashtags": ["..."],
41
- "article_topics": ["..."],
42
- "thought_leadership_angles": ["..."],
43
- "best_posting_time": "...",
44
- "industry_insights": "..."
45
- }}"""}
46
  ]
47
- data = run_analysis(messages, temperature=0.3, max_new_tokens=2000)
48
- if isinstance(data, dict) and "error" in data:
49
- return data
50
- return validate_and_fill_data_defaults(data, DEFAULTS)
 
1
+ from services.utils import run_analysis
2
 
3
+ SYSTEM_PROMPT = """You are a LinkedIn content strategist. Return ONLY valid JSON with post drafts, hashtags, article topics, thought leadership angles, posting time, and industry insights."""
 
 
 
 
 
 
 
 
4
 
5
  DEFAULTS = {
6
+ "post_drafts": [{"headline": "Key Insights on This Topic", "body": "Here are my thoughts on this important subject.", "hook": "Stop scrolling if you care about this"}],
7
+ "hashtags": ["#industry", "#leadership"],
8
+ "article_topics": ["The Future of This Industry"],
9
+ "thought_leadership_angles": ["Unique perspective on current trends"],
10
+ "best_posting_time": "7-9 AM EST Tue-Thu",
11
+ "industry_insights": "This is a growing space with significant potential."
12
  }
13
 
14
  def analyze_linkedin(content: str) -> dict:
15
  messages = [
16
  {"role": "system", "content": SYSTEM_PROMPT},
17
+ {"role": "user", "content": f'Topic: "{content[:1500]}"\n\nReturn JSON with:\n- post_drafts: list of {{"headline": str, "body": str, "hook": str}} (3 posts)\n- hashtags: list of strings (5 hashtags)\n- article_topics: list of strings (3 topics)\n- thought_leadership_angles: list of strings (3 angles)\n- best_posting_time: string\n- industry_insights: string'}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
  ]
19
+
20
+ return run_analysis(messages, defaults=DEFAULTS, temperature=0.3, max_new_tokens=1500)
 
 
services/pinterest_analyzer.py CHANGED
@@ -1,48 +1,19 @@
1
- from services.utils import run_analysis, validate_and_fill_data_defaults
2
 
3
- SYSTEM_PROMPT = """You are a Pinterest SEO Specialist and Visual Marketing Expert who understands how to optimize Pins for search discovery, board strategy, and traffic generation. Return ONLY valid JSON.
4
-
5
- RULES:
6
- 1. Pin ideas must have keyword-optimized titles and descriptions
7
- 2. Board organization: categorize by theme, audience, and funnel stage
8
- 3. SEO keywords: focus on long-tail, search-intent matching keywords
9
- 4. Pinterest is a VISUAL SEARCH ENGINE, not social media
10
- 5. Vertical 2:3 aspect ratio (1000 x 1500px) performs best
11
- 6. Keyword-rich descriptions in every Pin
12
- 7. Fresh content prioritized by algorithm"""
13
 
14
  DEFAULTS = {
15
- "pin_ideas": [],
16
- "board_organization": [],
17
- "seo_keywords": [],
18
- "best_posting_time": "8-11 PM EST on weekends",
19
- "traffic_strategies": ["Create Rich Pins", "Join group boards", "Use Idea Pins", "Seasonal planning"]
20
  }
21
 
22
  def analyze_pinterest(content: str) -> dict:
23
  messages = [
24
  {"role": "system", "content": SYSTEM_PROMPT},
25
- {"role": "user", "content": f"""Analyze topic for Pinterest strategy: "{content[:2000]}"
26
-
27
- REQUIREMENTS:
28
- - **Pin Ideas**: 10 pins with keyword-optimized title, description, and keyword focus
29
- - **Board Organization**: 5 board name suggestions with descriptions
30
- - **SEO Keywords**: 20 long-tail keywords
31
- - **Best Posting Time**: Optimal day and time
32
- - **Traffic Strategies**: 5 strategies for driving traffic from Pinterest
33
-
34
- JSON OUTPUT STRUCTURE:
35
- {{
36
- "pin_ideas": [
37
- {{"title": "...", "description": "...", "keyword_focus": "..."}}, ... (Total 10 items)
38
- ],
39
- "board_organization": ["..."],
40
- "seo_keywords": ["..."],
41
- "best_posting_time": "...",
42
- "traffic_strategies": ["..."]
43
- }}"""}
44
  ]
45
- data = run_analysis(messages, temperature=0.3, max_new_tokens=2000)
46
- if isinstance(data, dict) and "error" in data:
47
- return data
48
- return validate_and_fill_data_defaults(data, DEFAULTS)
 
1
+ from services.utils import run_analysis
2
 
3
+ SYSTEM_PROMPT = """You are a Pinterest SEO specialist. Return ONLY valid JSON with pin ideas, board organization, SEO keywords, posting time, and traffic strategies."""
 
 
 
 
 
 
 
 
 
4
 
5
  DEFAULTS = {
6
+ "pin_ideas": [{"title": "Complete Guide to This Topic", "description": "Learn everything about this topic with our comprehensive guide.", "keyword_focus": "main topic keyword"}],
7
+ "board_organization": ["Topic Guides", "Tips & Tricks"],
8
+ "seo_keywords": ["main topic", "related topic"],
9
+ "best_posting_time": "8-11 PM EST weekends",
10
+ "traffic_strategies": ["Create Rich Pins", "Use keyword-rich descriptions"]
11
  }
12
 
13
  def analyze_pinterest(content: str) -> dict:
14
  messages = [
15
  {"role": "system", "content": SYSTEM_PROMPT},
16
+ {"role": "user", "content": f'Topic: "{content[:1500]}"\n\nReturn JSON with:\n- pin_ideas: list of {{"title": str, "description": str, "keyword_focus": str}} (5 pins)\n- board_organization: list of strings (5 boards)\n- seo_keywords: list of strings (10 keywords)\n- best_posting_time: string\n- traffic_strategies: list of strings (3 strategies)'}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
  ]
18
+
19
+ return run_analysis(messages, defaults=DEFAULTS, temperature=0.3, max_new_tokens=1500)
 
 
services/tiktok_analyzer.py CHANGED
@@ -1,48 +1,19 @@
1
- from services.utils import run_analysis, validate_and_fill_data_defaults
2
 
3
- SYSTEM_PROMPT = """You are a Viral TikTok Strategist who deeply understands the For You Page (FYP) algorithm, trend culture, and short-form video psychology. Return ONLY valid JSON.
4
-
5
- RULES:
6
- 1. Video concepts must specify: hook (first 3 seconds), script snippet, and trending sound suggestion
7
- 2. Trending angles must reference current content patterns (day in life, tutorials, POV, commentary, transitions)
8
- 3. Hashtags: 3-5 mix of trending, niche, and broad
9
- 4. Hooks should create curiosity gaps with 80%+ estimated retention rates
10
- 5. TikTok algorithm: completion rate > rewatches > shares > comments > likes
11
- 6. Vertical 9:16 video, 21-60 seconds optimal length
12
- 7. First 2-3 seconds are CRITICAL for retention"""
13
 
14
  DEFAULTS = {
15
- "video_concepts": [],
16
- "trending_angles": [],
17
- "hashtags": [],
18
  "best_posting_time": "7-9 AM or 7-10 PM local time",
19
- "viral_strategies": ["Participate in trending challenges", "Use trending sounds", "Post 1-3x daily"]
20
  }
21
 
22
  def analyze_tiktok(content: str) -> dict:
23
  messages = [
24
  {"role": "system", "content": SYSTEM_PROMPT},
25
- {"role": "user", "content": f"""Analyze topic for TikTok strategy: "{content[:2000]}"
26
-
27
- REQUIREMENTS:
28
- - **Video Concepts**: 8 concepts with hook, script snippet, and sound suggestion
29
- - **Trending Angles**: 5 trending content angles for this topic
30
- - **Hashtags**: 5 optimized hashtags (trending + niche + broad)
31
- - **Best Posting Time**: Optimal times
32
- - **Viral Strategies**: 5 strategies specific to this topic/niche
33
-
34
- JSON OUTPUT STRUCTURE:
35
- {{
36
- "video_concepts": [
37
- {{"hook": "...", "script_snippet": "...", "sound_suggestion": "..."}}, ... (Total 8 items)
38
- ],
39
- "trending_angles": ["..."],
40
- "hashtags": ["..."],
41
- "best_posting_time": "...",
42
- "viral_strategies": ["..."]
43
- }}"""}
44
  ]
45
- data = run_analysis(messages, temperature=0.45, max_new_tokens=2000)
46
- if isinstance(data, dict) and "error" in data:
47
- return data
48
- return validate_and_fill_data_defaults(data, DEFAULTS)
 
1
+ from services.utils import run_analysis
2
 
3
+ SYSTEM_PROMPT = """You are a TikTok viral strategist. Return ONLY valid JSON with video concepts, trending angles, hashtags, posting time, and viral strategies."""
 
 
 
 
 
 
 
 
 
4
 
5
  DEFAULTS = {
6
+ "video_concepts": [{"hook": "You won't believe this", "script_snippet": "Here's the full story...", "sound_suggestion": "Trending audio"}],
7
+ "trending_angles": ["Educational angle on this topic"],
8
+ "hashtags": ["#fyp", "#trending"],
9
  "best_posting_time": "7-9 AM or 7-10 PM local time",
10
+ "viral_strategies": ["Use trending sounds", "Post 1-3x daily"]
11
  }
12
 
13
  def analyze_tiktok(content: str) -> dict:
14
  messages = [
15
  {"role": "system", "content": SYSTEM_PROMPT},
16
+ {"role": "user", "content": f'Topic: "{content[:1500]}"\n\nReturn JSON with:\n- video_concepts: list of {{"hook": str, "script_snippet": str, "sound_suggestion": str}} (4 concepts)\n- trending_angles: list of strings (3 angles)\n- hashtags: list of strings (5 hashtags)\n- best_posting_time: string\n- viral_strategies: list of strings (3 strategies)'}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
  ]
18
+
19
+ return run_analysis(messages, defaults=DEFAULTS, temperature=0.4, max_new_tokens=1500)
 
 
services/twitter_analyzer.py CHANGED
@@ -1,47 +1,19 @@
1
- from services.utils import run_analysis, validate_and_fill_data_defaults
2
 
3
- SYSTEM_PROMPT = """You are a Viral Twitter/X Strategist who understands the platform's fast-paced, text-first nature. You specialize in thread writing, engagement hacking, and building followings through value-driven content. Return ONLY valid JSON.
4
-
5
- RULES:
6
- 1. Tweet threads must have a compelling hook tweet followed by value tweets and a strong CTA
7
- 2. Viral hooks must fit in 280 characters and create curiosity gaps
8
- 3. Hashtags: 1-2 max, used sparingly
9
- 4. Threads should have 5-10 tweets each
10
- 5. X algorithm prioritizes: replies > retweets > likes > views
11
- 6. Engaging with others' content = 40% of growth strategy"""
12
 
13
  DEFAULTS = {
14
- "tweet_threads": [],
15
- "viral_hooks": [],
16
- "hashtags": [],
17
- "best_posting_time": "7-9 AM EST on weekdays",
18
- "engagement_tactics": ["Reply to industry leaders", "Quote tweet with your take", "Use polls"]
19
  }
20
 
21
  def analyze_twitter(content: str) -> dict:
22
  messages = [
23
  {"role": "system", "content": SYSTEM_PROMPT},
24
- {"role": "user", "content": f"""Analyze topic for X/Twitter strategy: "{content[:2000]}"
25
-
26
- REQUIREMENTS:
27
- - **Tweet Threads**: 3 complete threads (each 5-10 tweets) with different themes/angles
28
- - **Viral Hooks**: 10 single-tweet hooks (under 280 chars each)
29
- - **Hashtags**: 2 optimized hashtags
30
- - **Best Posting Time**: Optimal day and time
31
- - **Engagement Tactics**: 5 specific tactics
32
-
33
- JSON OUTPUT STRUCTURE:
34
- {{
35
- "tweet_threads": [
36
- {{"tweets": ["..."], "theme": "..."}}, ... (Total 3 items)
37
- ],
38
- "viral_hooks": ["..."],
39
- "hashtags": ["..."],
40
- "best_posting_time": "...",
41
- "engagement_tactics": ["..."]
42
- }}"""}
43
  ]
44
- data = run_analysis(messages, temperature=0.35, max_new_tokens=2000)
45
- if isinstance(data, dict) and "error" in data:
46
- return data
47
- return validate_and_fill_data_defaults(data, DEFAULTS)
 
1
+ from services.utils import run_analysis
2
 
3
+ SYSTEM_PROMPT = """You are a Twitter/X content strategist. Return ONLY valid JSON with tweet threads, viral hooks, hashtags, posting time, and engagement tactics."""
 
 
 
 
 
 
 
 
4
 
5
  DEFAULTS = {
6
+ "tweet_threads": [{"tweets": ["Tweet 1 about the topic", "Tweet 2 with more detail", "Tweet 3 with key insight"], "theme": "educational"}],
7
+ "viral_hooks": ["This changes everything"],
8
+ "hashtags": ["#topic"],
9
+ "best_posting_time": "7-9 AM EST weekdays",
10
+ "engagement_tactics": ["Reply to industry leaders", "Use polls"]
11
  }
12
 
13
  def analyze_twitter(content: str) -> dict:
14
  messages = [
15
  {"role": "system", "content": SYSTEM_PROMPT},
16
+ {"role": "user", "content": f'Topic: "{content[:1500]}"\n\nReturn JSON with:\n- tweet_threads: list of {{"tweets": [str], "theme": str}} (2 threads, 3-5 tweets each)\n- viral_hooks: list of strings (5 hooks, under 280 chars)\n- hashtags: list of strings (2 hashtags)\n- best_posting_time: string\n- engagement_tactics: list of strings (3 tactics)'}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
  ]
18
+
19
+ return run_analysis(messages, defaults=DEFAULTS, temperature=0.35, max_new_tokens=1500)
 
 
services/utils.py CHANGED
@@ -1,48 +1,113 @@
1
  import json
 
2
 
3
  def clean_json_string(text: str) -> str:
4
  if "```json" in text:
5
  text = text.split("```json")[1].split("```")[0]
6
  elif "```" in text:
7
- text = text.split("```")[1].split("```")[0]
 
 
 
 
8
  return text.strip()
9
 
10
  def repair_json(json_str: str) -> str:
11
  json_str = json_str.strip()
12
  json_str = json_str.rstrip(", ")
 
13
  open_braces = json_str.count("{")
14
  close_braces = json_str.count("}")
15
  open_brackets = json_str.count("[")
16
  close_brackets = json_str.count("]")
 
17
  if open_braces > close_braces:
18
  json_str += "}" * (open_braces - close_braces)
19
  if open_brackets > close_brackets:
20
  json_str += "]" * (open_brackets - close_brackets)
 
21
  return json_str
22
 
23
- def parse_and_repair(raw_text: str, max_preview=500):
24
  cleaned = clean_json_string(raw_text)
25
  try:
26
  return json.loads(cleaned), None
27
  except json.JSONDecodeError:
28
- print("⚠️ JSON Parse Error. Attempting repair...")
29
  repaired = repair_json(cleaned)
30
  try:
31
  return json.loads(repaired), None
32
- except json.JSONDecodeError as e:
33
- return None, {
34
- "error": "Optimization Failed. The model generated invalid JSON.",
35
- "raw_output": raw_text[:max_preview]
36
- }
 
37
 
38
- def run_analysis(messages, temperature=0.3, max_new_tokens=2000):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
  from services.model_loader import generate_text
40
  raw = generate_text(messages, temperature, max_new_tokens)
41
  if raw is None:
42
- return {"error": "Model failed to load on server startup. Check logs."}
 
 
 
43
  data, err = parse_and_repair(raw)
44
  if err:
45
- return err
 
 
 
 
 
46
  return data
47
 
48
  def validate_and_fill_data_defaults(data: dict, defaults: dict) -> dict:
 
1
  import json
2
+ import re
3
 
4
  def clean_json_string(text: str) -> str:
5
  if "```json" in text:
6
  text = text.split("```json")[1].split("```")[0]
7
  elif "```" in text:
8
+ parts = text.split("```")
9
+ if len(parts) >= 3:
10
+ text = parts[1]
11
+ elif len(parts) >= 2:
12
+ text = parts[1]
13
  return text.strip()
14
 
15
  def repair_json(json_str: str) -> str:
16
  json_str = json_str.strip()
17
  json_str = json_str.rstrip(", ")
18
+
19
  open_braces = json_str.count("{")
20
  close_braces = json_str.count("}")
21
  open_brackets = json_str.count("[")
22
  close_brackets = json_str.count("]")
23
+
24
  if open_braces > close_braces:
25
  json_str += "}" * (open_braces - close_braces)
26
  if open_brackets > close_brackets:
27
  json_str += "]" * (open_brackets - close_brackets)
28
+
29
  return json_str
30
 
31
+ def parse_and_repair(raw_text: str, max_preview=300):
32
  cleaned = clean_json_string(raw_text)
33
  try:
34
  return json.loads(cleaned), None
35
  except json.JSONDecodeError:
36
+ print("⚠️ JSON Parse Error. Attempting repair with v2...")
37
  repaired = repair_json(cleaned)
38
  try:
39
  return json.loads(repaired), None
40
+ except json.JSONDecodeError:
41
+ try:
42
+ repaired = repair_json_v2(repaired)
43
+ return json.loads(repaired), None
44
+ except json.JSONDecodeError as e:
45
+ return None, {"error": str(e), "raw_preview": raw_text[:max_preview]}
46
 
47
+ def repair_json_v2(json_str: str) -> str:
48
+ json_str = json_str.strip()
49
+ json_str = json_str.rstrip(", ")
50
+
51
+ in_string = False
52
+ escape = False
53
+ brace_depth = 0
54
+ bracket_depth = 0
55
+ last_good_pos = 0
56
+
57
+ for i, ch in enumerate(json_str):
58
+ if escape:
59
+ escape = False
60
+ continue
61
+ if ch == '\\':
62
+ escape = True
63
+ continue
64
+ if ch == '"' and not escape:
65
+ in_string = not in_string
66
+ continue
67
+ if in_string:
68
+ continue
69
+
70
+ if ch == '{':
71
+ brace_depth += 1
72
+ elif ch == '}':
73
+ brace_depth -= 1
74
+ elif ch == '[':
75
+ bracket_depth += 1
76
+ elif ch == ']':
77
+ bracket_depth -= 1
78
+
79
+ if brace_depth >= 0 and bracket_depth >= 0:
80
+ last_good_pos = i + 1
81
+
82
+ end = last_good_pos
83
+ trimmed = json_str[:end].rstrip(", ")
84
+
85
+ cb = trimmed.count("{") - trimmed.count("}")
86
+ sb = trimmed.count("[") - trimmed.count("]")
87
+
88
+ if cb > 0:
89
+ trimmed += "}" * cb
90
+ if sb > 0:
91
+ trimmed += "]" * sb
92
+
93
+ return trimmed
94
+
95
+ def run_analysis(messages, defaults=None, temperature=0.3, max_new_tokens=2000):
96
  from services.model_loader import generate_text
97
  raw = generate_text(messages, temperature, max_new_tokens)
98
  if raw is None:
99
+ base = dict(defaults) if defaults else {}
100
+ base["error"] = "Model failed to load on server startup. Check logs."
101
+ return base
102
+
103
  data, err = parse_and_repair(raw)
104
  if err:
105
+ base = dict(defaults) if defaults else {}
106
+ base["error"] = f"JSON parse failed: {err.get('error', 'unknown')}"
107
+ return base
108
+
109
+ if defaults:
110
+ return validate_and_fill_data_defaults(data, defaults)
111
  return data
112
 
113
  def validate_and_fill_data_defaults(data: dict, defaults: dict) -> dict:
services/youtube_analyzer.py CHANGED
@@ -1,52 +1,21 @@
1
- from services.utils import run_analysis, validate_and_fill_data_defaults
2
 
3
- SYSTEM_PROMPT = """You are a world-class YouTube SEO Strategist and Content Consultant. You know the YouTube algorithm inside out — CTR optimization, watch-time retention, keyword ranking, thumbnail psychology, and community engagement. Return ONLY valid JSON.
4
-
5
- RULES:
6
- 1. Video titles must be click-worthy with high CTR potential (use numbers, power words, curiosity gaps, brackets)
7
- 2. Tags must include a mix of broad, mid-tail, and long-tail keywords
8
- 3. Description templates must include keyword placement, timestamps, and call-to-action
9
- 4. Thumbnail ideas should reference proven design principles (contrast, faces with emotion, text overlay)
10
- 5. Engagement strategies focus on: comments, polls, community tab, end screens, cards"""
11
 
12
  DEFAULTS = {
13
- "video_titles": [],
14
- "tags": [],
15
- "description_template": "In this video we explore [TOPIC]. Make sure to like and subscribe!",
16
- "thumbnail_ideas": ["Close-up expressive face with bold text overlay"],
17
- "best_posting_time": "2-4 PM EST on weekdays",
18
- "engagement_strategies": ["Pin a comment with a question", "Use end screens to suggest next video"],
19
- "competition_gap_analysis": "Focus on underserved long-tail subtopics within this niche."
20
  }
21
 
22
  def analyze_youtube(content: str) -> dict:
23
  messages = [
24
  {"role": "system", "content": SYSTEM_PROMPT},
25
- {"role": "user", "content": f"""Analyze topic for YouTube strategy: "{content[:2000]}"
26
-
27
- REQUIREMENTS:
28
- - **Video Titles**: 15 high-CTR titles with expected CTR percentage
29
- - **Tags**: 20 keywords (broad, mid-tail, long-tail)
30
- - **Description Template**: 1 full SEO-optimized description template
31
- - **Thumbnail Ideas**: 5 specific thumbnail concepts
32
- - **Best Posting Time**: Optimal day and time
33
- - **Engagement Strategies**: 5 tactics
34
- - **Competition Gap Analysis**: 1 paragraph
35
-
36
- JSON OUTPUT STRUCTURE:
37
- {{
38
- "video_titles": [
39
- {{"title": "...", "expected_ctr": "..."}}, ... (Total 15 items)
40
- ],
41
- "tags": ["..."],
42
- "description_template": "...",
43
- "thumbnail_ideas": ["..."],
44
- "best_posting_time": "...",
45
- "engagement_strategies": ["..."],
46
- "competition_gap_analysis": "..."
47
- }}"""}
48
  ]
49
- data = run_analysis(messages, temperature=0.3, max_new_tokens=2000)
50
- if isinstance(data, dict) and "error" in data:
51
- return data
52
- return validate_and_fill_data_defaults(data, DEFAULTS)
 
1
+ from services.utils import run_analysis
2
 
3
+ SYSTEM_PROMPT = """You are a YouTube SEO expert. Return ONLY valid JSON with video titles, tags, description, thumbnail ideas, posting time, engagement tips, and competition analysis."""
 
 
 
 
 
 
 
4
 
5
  DEFAULTS = {
6
+ "video_titles": [{"title": "Topic Deep Dive: Complete Guide", "expected_ctr": "8-12%"}],
7
+ "tags": ["tutorial", "guide", "tips"],
8
+ "description_template": "In this video we explore this topic in depth.",
9
+ "thumbnail_ideas": ["Expressive face with bold text overlay"],
10
+ "best_posting_time": "2-4 PM EST weekdays",
11
+ "engagement_strategies": ["Pin a question comment", "Use end screens"],
12
+ "competition_gap_analysis": "Focus on underserved subtopics within this niche."
13
  }
14
 
15
  def analyze_youtube(content: str) -> dict:
16
  messages = [
17
  {"role": "system", "content": SYSTEM_PROMPT},
18
+ {"role": "user", "content": f'Topic: "{content[:1500]}"\n\nReturn JSON with:\n- video_titles: list of {{"title": str, "expected_ctr": str}} (5 titles)\n- tags: list of strings (10 tags)\n- description_template: string\n- thumbnail_ideas: list of strings (3 ideas)\n- best_posting_time: string\n- engagement_strategies: list of strings (3 strategies)\n- competition_gap_analysis: string'}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
  ]
20
+
21
+ return run_analysis(messages, defaults=DEFAULTS, temperature=0.3, max_new_tokens=1500)