import os, requests, time
from datetime import datetime, timedelta
NA_KEY = os.environ["NEWSAPI_KEY"]
NA_BASE = "https://newsapi.org/v2"
NA_H = {"X-Api-Key": NA_KEY}
MV = os.environ["MAVERA_API_KEY"]
MV_BASE = "https://app.mavera.io/api/v1"
MV_H = {"Authorization": f"Bearer {MV}", "Content-Type": "application/json"}
TOPIC = "artificial intelligence marketing"
WEEKS = 4
# 1. Fetch articles in weekly batches
weekly_data = []
for week in range(WEEKS):
end = datetime.now() - timedelta(weeks=week)
start = end - timedelta(days=7)
r = requests.get(f"{NA_BASE}/everything", headers=NA_H, params={
"q": TOPIC, "from": start.strftime("%Y-%m-%d"),
"to": end.strftime("%Y-%m-%d"), "sortBy": "relevancy",
"language": "en", "pageSize": 25,
})
if not r.ok:
print(f"Week {week}: API error {r.status_code}")
continue
articles = r.json().get("articles", [])
weekly_data.append({
"week_label": f"{start.strftime('%b %d')} – {end.strftime('%b %d')}",
"articles": articles, "count": len(articles),
})
print(f"Week {week}: {len(articles)} articles ({start.strftime('%b %d')} – {end.strftime('%b %d')})")
time.sleep(1)
# 2. Batch sentiment analysis via Mave
sentiment_series = []
for week in weekly_data:
corpus = "\n".join(
f"- [{a.get('source',{}).get('name','')}] {a['title']}: {a.get('description','')[:150]}"
for a in week["articles"][:20]
)
analysis = requests.post(f"{MV_BASE}/mave/chat", headers=MV_H, json={
"message": f"Sentiment analyst. Analyze media coverage for '{TOPIC}' during {week['week_label']}.\n\n"
f"ARTICLES ({week['count']}):\n{corpus}\n\n"
"Return JSON with: overall_sentiment (positive/negative/neutral/mixed), "
"confidence (0-100), positive_pct, negative_pct, neutral_pct, "
"top_positive_theme, top_negative_theme, notable_shift, key_quote."
}).json()
content = analysis.get("content", "")
sentiment_series.append({"week": week["week_label"], "count": week["count"], "analysis": content[:600]})
time.sleep(0.5)
# 3. Trend summary
trend = requests.post(f"{MV_BASE}/mave/chat", headers=MV_H, json={
"message": f"Given these {WEEKS} weeks of sentiment data for '{TOPIC}', identify the overall trend.\n\n"
+ "\n\n".join(f"**{s['week']}** ({s['count']} articles):\n{s['analysis']}" for s in sentiment_series)
+ "\n\nProvide: trend direction (improving/declining/stable), confidence, biggest driver, prediction for next week, recommended action."
}).json()
print(f"\n{'='*60}\nSENTIMENT TREND: {TOPIC}\n{'='*60}")
for s in sentiment_series:
print(f"\n{s['week']} ({s['count']} articles):\n{s['analysis'][:300]}")
print(f"\n{'='*60}\nTREND ANALYSIS\n{'='*60}")
print(trend.get("content", "")[:800])