Commit
Β·
1a8dfaf
1
Parent(s):
f66fbba
Fix import error in thunderbird engine
Browse files- core/thunderbird_engine.py +29 -21
core/thunderbird_engine.py
CHANGED
|
@@ -2,9 +2,10 @@ import os
|
|
| 2 |
import pandas as pd
|
| 3 |
import joblib
|
| 4 |
import random
|
|
|
|
| 5 |
from datetime import datetime
|
| 6 |
from newsapi import NewsApiClient
|
| 7 |
-
import
|
| 8 |
|
| 9 |
# --- CONFIGURATION ---
|
| 10 |
MODEL_PATH = os.path.join(os.path.dirname(__file__), '..', 'models', 'thunderbird_market_predictor_v1.joblib')
|
|
@@ -32,10 +33,17 @@ def get_external_trends() -> dict:
|
|
| 32 |
except Exception as e:
|
| 33 |
print(f" - β οΈ NewsAPI Error: {e}")
|
| 34 |
results["news_headlines"] = [{"title": "News service currently unavailable.", "url": "#"}]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
|
| 36 |
# Simulate other trends for now to allow frontend development
|
| 37 |
results["breakout_keyword"] = "AI in Marketing"
|
| 38 |
-
trending_audios = [{"name": "Espresso - Sabrina Carpenter", "cover_art_url": "https://
|
| 39 |
results["trending_audio"] = random.choice(trending_audios)
|
| 40 |
print(" - β
(Simulated) Found trending keyword and audio.")
|
| 41 |
return results
|
|
@@ -44,13 +52,21 @@ def predict_niche_trends() -> dict:
|
|
| 44 |
"""Loads our trained ML model to predict future interest in market niches."""
|
| 45 |
print("\nπ [Thunderbird Engine] Loading model to predict niche trends...")
|
| 46 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
model_pack = joblib.load(MODEL_PATH)
|
| 48 |
-
model = model_pack['model']
|
| 49 |
encoder = model_pack['encoder']
|
| 50 |
print(f" - β
Model '{os.path.basename(MODEL_PATH)}' loaded successfully.")
|
| 51 |
-
except
|
| 52 |
-
print(f" -
|
| 53 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
|
| 55 |
print(" - β οΈ NOTE: Generating SIMULATED trend data as training set is small.")
|
| 56 |
niches = encoder.get_feature_names_out(['niche'])
|
|
@@ -62,10 +78,9 @@ def predict_niche_trends() -> dict:
|
|
| 62 |
for _ in range(11):
|
| 63 |
points.append(max(20, min(100, points[-1] + random.randint(-10, 10))))
|
| 64 |
predictions[niche_name] = [{"date": date, "value": value} for date, value in zip(dates, points)]
|
| 65 |
-
|
| 66 |
return {"trend_predictions": predictions}
|
| 67 |
|
| 68 |
-
|
| 69 |
def decode_market_trend(topic: str, llm_instance) -> Dict[str, str]:
|
| 70 |
"""
|
| 71 |
Takes a news headline or keyword and generates a strategic 'Agency Brief'.
|
|
@@ -75,9 +90,9 @@ def decode_market_trend(topic: str, llm_instance) -> Dict[str, str]:
|
|
| 75 |
|
| 76 |
# Fallback default agar LLM nahi hai
|
| 77 |
default_response = {
|
| 78 |
-
"summary": "
|
| 79 |
-
"impact": "
|
| 80 |
-
"strategy": "Create content relating to this topic immediately."
|
| 81 |
}
|
| 82 |
|
| 83 |
if not llm_instance:
|
|
@@ -99,11 +114,8 @@ def decode_market_trend(topic: str, llm_instance) -> Dict[str, str]:
|
|
| 99 |
response = llm_instance(prompt, max_tokens=256, temperature=0.7, stop=["[INST]"], echo=False)
|
| 100 |
text = response['choices'][0]['text'].strip()
|
| 101 |
|
| 102 |
-
# Simple clean-up to ensure valid JSON-like structure is parsed,
|
| 103 |
-
# or fall back to regex if model is chatty
|
| 104 |
-
import json
|
| 105 |
try:
|
| 106 |
-
# Try finding the first { and last }
|
| 107 |
start = text.find('{')
|
| 108 |
end = text.rfind('}') + 1
|
| 109 |
if start != -1 and end != 0:
|
|
@@ -116,12 +128,8 @@ def decode_market_trend(topic: str, llm_instance) -> Dict[str, str]:
|
|
| 116 |
except:
|
| 117 |
pass
|
| 118 |
|
| 119 |
-
# Fallback if JSON parsing fails but we have text
|
| 120 |
-
return
|
| 121 |
-
"summary": f"Current buzz around '{topic}'.",
|
| 122 |
-
"impact": "Attention is shifting towards this narrative.",
|
| 123 |
-
"strategy": f"Integrate '{topic}' into upcoming post captions or stories."
|
| 124 |
-
}
|
| 125 |
|
| 126 |
except Exception as e:
|
| 127 |
print(f"β AI Trend Decoding Failed: {e}")
|
|
|
|
| 2 |
import pandas as pd
|
| 3 |
import joblib
|
| 4 |
import random
|
| 5 |
+
import json
|
| 6 |
from datetime import datetime
|
| 7 |
from newsapi import NewsApiClient
|
| 8 |
+
from typing import Dict, Any, Optional # <-- THIS IMPORT WAS MISSING
|
| 9 |
|
| 10 |
# --- CONFIGURATION ---
|
| 11 |
MODEL_PATH = os.path.join(os.path.dirname(__file__), '..', 'models', 'thunderbird_market_predictor_v1.joblib')
|
|
|
|
| 33 |
except Exception as e:
|
| 34 |
print(f" - β οΈ NewsAPI Error: {e}")
|
| 35 |
results["news_headlines"] = [{"title": "News service currently unavailable.", "url": "#"}]
|
| 36 |
+
else:
|
| 37 |
+
# Fallback simulation if no API Key
|
| 38 |
+
results["news_headlines"] = [
|
| 39 |
+
{"title": "TikTok vs YouTube Shorts: The 2025 Battle for Dominance", "url": "#"},
|
| 40 |
+
{"title": "AI in Influencer Marketing: What Agencies Need to Know", "url": "#"},
|
| 41 |
+
{"title": "The Rise of Micro-Influencers in Niche Markets", "url": "#"}
|
| 42 |
+
]
|
| 43 |
|
| 44 |
# Simulate other trends for now to allow frontend development
|
| 45 |
results["breakout_keyword"] = "AI in Marketing"
|
| 46 |
+
trending_audios = [{"name": "Espresso - Sabrina Carpenter", "cover_art_url": "https://i.scdn.co/image/ab67616d0000b2736599b5003b077a93553250df"}]
|
| 47 |
results["trending_audio"] = random.choice(trending_audios)
|
| 48 |
print(" - β
(Simulated) Found trending keyword and audio.")
|
| 49 |
return results
|
|
|
|
| 52 |
"""Loads our trained ML model to predict future interest in market niches."""
|
| 53 |
print("\nπ [Thunderbird Engine] Loading model to predict niche trends...")
|
| 54 |
try:
|
| 55 |
+
if not os.path.exists(MODEL_PATH):
|
| 56 |
+
# Graceful fallback if model is missing during build/deploy
|
| 57 |
+
raise FileNotFoundError("Model file not found")
|
| 58 |
+
|
| 59 |
model_pack = joblib.load(MODEL_PATH)
|
|
|
|
| 60 |
encoder = model_pack['encoder']
|
| 61 |
print(f" - β
Model '{os.path.basename(MODEL_PATH)}' loaded successfully.")
|
| 62 |
+
except Exception as e:
|
| 63 |
+
print(f" - β οΈ Model load skipped (Using Simulation): {e}")
|
| 64 |
+
# Return simulated structure directly
|
| 65 |
+
dates = pd.date_range(end=datetime.now(), periods=12, freq='M').strftime('%Y-%m').tolist()
|
| 66 |
+
return {"trend_predictions": {
|
| 67 |
+
"general": [{"date": d, "value": random.randint(40, 80)} for d in dates],
|
| 68 |
+
"fitness": [{"date": d, "value": random.randint(50, 90)} for d in dates]
|
| 69 |
+
}}
|
| 70 |
|
| 71 |
print(" - β οΈ NOTE: Generating SIMULATED trend data as training set is small.")
|
| 72 |
niches = encoder.get_feature_names_out(['niche'])
|
|
|
|
| 78 |
for _ in range(11):
|
| 79 |
points.append(max(20, min(100, points[-1] + random.randint(-10, 10))))
|
| 80 |
predictions[niche_name] = [{"date": date, "value": value} for date, value in zip(dates, points)]
|
| 81 |
+
|
| 82 |
return {"trend_predictions": predictions}
|
| 83 |
|
|
|
|
| 84 |
def decode_market_trend(topic: str, llm_instance) -> Dict[str, str]:
|
| 85 |
"""
|
| 86 |
Takes a news headline or keyword and generates a strategic 'Agency Brief'.
|
|
|
|
| 90 |
|
| 91 |
# Fallback default agar LLM nahi hai
|
| 92 |
default_response = {
|
| 93 |
+
"summary": f"'{topic}' is currently gaining significant traction online.",
|
| 94 |
+
"impact": "Brands tapping into this can see increased organic reach.",
|
| 95 |
+
"strategy": "Create content relating to this topic immediately using your brand voice."
|
| 96 |
}
|
| 97 |
|
| 98 |
if not llm_instance:
|
|
|
|
| 114 |
response = llm_instance(prompt, max_tokens=256, temperature=0.7, stop=["[INST]"], echo=False)
|
| 115 |
text = response['choices'][0]['text'].strip()
|
| 116 |
|
|
|
|
|
|
|
|
|
|
| 117 |
try:
|
| 118 |
+
# Try finding the first { and last } to parse JSON
|
| 119 |
start = text.find('{')
|
| 120 |
end = text.rfind('}') + 1
|
| 121 |
if start != -1 and end != 0:
|
|
|
|
| 128 |
except:
|
| 129 |
pass
|
| 130 |
|
| 131 |
+
# Fallback if JSON parsing fails but we have text - Return a standard structure
|
| 132 |
+
return default_response
|
|
|
|
|
|
|
|
|
|
|
|
|
| 133 |
|
| 134 |
except Exception as e:
|
| 135 |
print(f"β AI Trend Decoding Failed: {e}")
|