amitbhatt6075 commited on
Commit
dc00ece
Β·
1 Parent(s): 7cb42ac

fix: Remove dotenv and rely only on Hugging Face secrets

Browse files
Files changed (2) hide show
  1. core/thunderbird_engine.py +85 -31
  2. requirements.txt +0 -0
core/thunderbird_engine.py CHANGED
@@ -3,49 +3,103 @@ import pandas as pd
3
  import joblib
4
  import json
5
  from datetime import datetime
 
 
6
  from typing import Dict, Any, Optional
 
7
 
8
- # --- STABLE IMPORTS (No dotenv) ---
9
- try:
10
- from newsapi import NewsApiClient
11
- except ImportError:
12
- NewsApiClient = None
13
 
14
- try:
15
- from core.utils import get_supabase_client
16
- except ImportError:
17
- get_supabase_client = None
 
 
18
 
19
- # --- CONFIGURATION (Directly from OS/Secrets) ---
20
- MODEL_PATH = os.path.join(os.path.dirname(__file__), '..', 'models', 'thunderbird_market_predictor_v1.joblib')
21
- NEWS_API_KEY = os.environ.get("NEWS_API_KEY") # THIS WILL NOW READ FROM HUGGING FACE SECRETS
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
 
23
  def get_external_trends() -> dict:
24
- """
25
- STABLE VERSION: Fetches only from reliable sources (NewsAPI via HF Secrets).
26
- """
27
- print("πŸš€ [Thunderbird Engine] Fetching trends (Stable Mode, from HF Secrets)...")
28
- results = {
29
- "news_headlines": [],
30
- "breakout_keyword": None,
31
- "trending_audio": None,
32
- "platform_shifts": None
33
- }
34
 
35
- # NewsAPI Logic
36
- if NEWS_API_KEY and NewsApiClient:
37
  try:
38
- print(" - βœ… NEWS_API_KEY found in server secrets. Attempting fetch...")
39
  newsapi = NewsApiClient(api_key=NEWS_API_KEY)
40
  top_headlines = newsapi.get_everything(q='("influencer marketing")', language='en', sort_by='relevancy', page_size=5)
41
  if top_headlines.get('articles'):
42
  results["news_headlines"] = [{"title": a['title'], "url": a['url']} for a in top_headlines['articles']]
43
- print(" - βœ… News headlines fetched successfully.")
44
- except Exception as e:
45
- print(f" - ⚠️ NewsAPI call failed: {e}")
46
- else:
47
- print(" - ℹ️ NEWS_API_KEY not found in Hugging Face secrets. Skipping headlines.")
48
-
 
 
 
 
 
 
 
 
49
  return results
50
 
51
  def predict_niche_trends() -> dict:
 
3
  import joblib
4
  import json
5
  from datetime import datetime
6
+ from newsapi import NewsApiClient
7
+ from serpapi import GoogleSearch
8
  from typing import Dict, Any, Optional
9
+ from core.utils import get_supabase_client
10
 
11
+ # --- CONFIGURATION ---
12
+ MODEL_PATH = os.path.join(os.path.dirname(__file__), '..', 'models', 'thunderbird_market_predictor_v1.joblib')
13
+ NEWS_API_KEY = os.getenv("NEWS_API_KEY")
14
+ SERPAPI_KEY = os.getenv("SERPAPI_KEY")
 
15
 
16
+ def get_real_trends_from_serpapi() -> Dict[str, Any]:
17
+ """Uses the reliable SerpApi to get Google and TikTok Trends."""
18
+ trends = {"breakout_keyword": None, "trending_audio": None}
19
+ if not SERPAPI_KEY:
20
+ print(" - ⚠️ SERPAPI_KEY not set. Real-time trends will be unavailable.")
21
+ return trends
22
 
23
+ try:
24
+ # 1. Get Google Trends Breakout Keyword
25
+ print(" - Fetching Google Trends via SerpApi...")
26
+ params = {"engine": "google_trends_trending_now", "frequency": "daily", "api_key": SERPAPI_KEY}
27
+ search = GoogleSearch(params)
28
+ results = search.get_dict()
29
+ if results.get("trending_searches"):
30
+ trends["breakout_keyword"] = results["trending_searches"][0]["title"]
31
+ print(f" - βœ… REAL Breakout Keyword found: {trends['breakout_keyword']}")
32
+
33
+ # 2. Get TikTok Trending Audio (Best Effort)
34
+ print(" - Fetching TikTok Trends via SerpApi...")
35
+ params = {"engine": "tiktok_trending", "api_key": SERPAPI_KEY}
36
+ search = GoogleSearch(params)
37
+ results = search.get_dict()
38
+ if results.get("trending_videos"):
39
+ for video in results["trending_videos"]:
40
+ if video.get("music"):
41
+ trends["trending_audio"] = {
42
+ "name": video["music"].get("title", "Unknown Audio"),
43
+ "coverArtUrl": video["music"].get("cover_thumb")
44
+ }
45
+ print(f" - βœ… REAL Trending Audio found: {trends['trending_audio']['name']}")
46
+ break
47
+ except Exception as e:
48
+ print(f" - ❌ SerpApi failed: {e}")
49
+
50
+ return trends
51
+
52
+ def get_platform_shifts() -> Optional[Dict[str, str]]:
53
+ """Calculates REAL 7-day shift from Supabase."""
54
+ print(" - Calculating REAL platform shifts from DB...")
55
+ shifts = { "instagram_shift": "0%", "tiktok_shift": "0%", "youtube_shift": "0%" }
56
+ try:
57
+ supabase = get_supabase_client()
58
+ response = supabase.rpc('get_platform_trend_data_last_14_days').execute()
59
+ if not response.data or len(response.data) < 2: return None
60
+
61
+ df = pd.DataFrame(response.data); df['date'] = pd.to_datetime(df['date'])
62
+ seven_days_ago = datetime.now() - pd.Timedelta(days=7)
63
+ recent = df[df['date'] >= seven_days_ago]; prev = df[df['date'] < seven_days_ago]
64
+ if prev.empty or recent.empty: return None
65
+
66
+ avg_recent = recent.groupby('platform')['usage_count'].mean()
67
+ avg_prev = prev.groupby('platform')['usage_count'].mean()
68
+ for p in ['instagram', 'tiktok', 'youtube']:
69
+ if p in avg_recent and p in avg_prev and avg_prev[p] > 0:
70
+ change = ((avg_recent[p] - avg_prev[p]) / avg_prev[p]) * 100
71
+ shifts[f"{p}_shift"] = f"{'+' if change > 0 else ''}{round(change)}%"
72
+ return shifts
73
+ except Exception as e:
74
+ print(f" - ❌ DB Error calculating shifts: {e}")
75
+ return None
76
 
77
  def get_external_trends() -> dict:
78
+ """Fetches REAL data, using a slow direct request for Google Trends."""
79
+ print("πŸš€ [Thunderbird Engine] Fetching REAL external trends (pytrends-only)...")
80
+ results = { "news_headlines": [], "breakout_keyword": None, "trending_audio": None, "platform_shifts": None }
 
 
 
 
 
 
 
81
 
82
+ # NewsAPI
83
+ if NEWS_API_KEY:
84
  try:
 
85
  newsapi = NewsApiClient(api_key=NEWS_API_KEY)
86
  top_headlines = newsapi.get_everything(q='("influencer marketing")', language='en', sort_by='relevancy', page_size=5)
87
  if top_headlines.get('articles'):
88
  results["news_headlines"] = [{"title": a['title'], "url": a['url']} for a in top_headlines['articles']]
89
+ except Exception: pass
90
+
91
+ # Google Trends (Direct and slow)
92
+ try:
93
+ print(" - Connecting to Google Trends directly...")
94
+ pytrends = TrendReq(hl='en-US', tz=360, timeout=(10, 25), retries=2, backoff_factor=10)
95
+ trending_df = pytrends.trending_searches(pn='united_states')
96
+ if not trending_df.empty:
97
+ results["breakout_keyword"] = trending_df.iloc[0,0]
98
+ print(f" - βœ… REAL Breakout Keyword found: {results['breakout_keyword']}")
99
+ except Exception as e:
100
+ print(f" - ⚠️ Google Trends failed: {e}")
101
+
102
+ results["platform_shifts"] = get_platform_shifts()
103
  return results
104
 
105
  def predict_niche_trends() -> dict:
requirements.txt CHANGED
Binary files a/requirements.txt and b/requirements.txt differ