File size: 14,591 Bytes
c39ff08 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 | {
"cells": [
{
"cell_type": "markdown",
"id": "2f8f9886",
"metadata": {},
"source": [
"# US Attention Data -- Exploration Notebook\n",
"\n",
"**Wikipedia pageviews, Google Trends, and GDELT event data tracking global attention in 2025**\n",
"\n",
"Author: [Luke Steuber](https://lukesteuber.com) | Bluesky: [@lukesteuber.com](https://bsky.app/profile/lukesteuber.com)\n",
"\n",
"Dataset: [lukeslp/us-attention-data](https://huggingface.co/datasets/lukeslp/us-attention-data)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "45de0ae5",
"metadata": {},
"outputs": [],
"source": [
"import json\n",
"import pandas as pd\n",
"import matplotlib.pyplot as plt\n",
"import matplotlib.ticker as ticker\n",
"import numpy as np\n",
"from datetime import datetime\n",
"\n",
"plt.style.use('seaborn-v0_8-whitegrid')\n",
"plt.rcParams['figure.figsize'] = (12, 6)\n",
"plt.rcParams['font.size'] = 11\n",
"\n",
"# Load all datasets\n",
"with open('trends_data.json') as f:\n",
" trends = json.load(f)\n",
"with open('wikipedia_pageviews.json') as f:\n",
" wiki_pageviews = json.load(f)\n",
"with open('gdelt_weekly_events.json') as f:\n",
" gdelt_weekly = json.load(f)\n",
"with open('unified_data.json') as f:\n",
" unified = json.load(f)\n",
"with open('weekly_trends.json') as f:\n",
" weekly_trends = json.load(f)\n",
"with open('wikipedia_trending.json') as f:\n",
" wiki_trending = json.load(f)\n",
"with open('events_unified.json') as f:\n",
" events = json.load(f)\n",
"with open('weekly_attention_timeline.json') as f:\n",
" attention_timeline = json.load(f)\n",
"\n",
"print(\"Loaded datasets:\")\n",
"print(f\" Trends terms: {len(trends.get('terms', {}))}\")\n",
"print(f\" Wikipedia countries: {len(wiki_pageviews.get('countries', {}))}\")\n",
"print(f\" GDELT weekly events: {len(gdelt_weekly.get('weekly_events', []))}\")\n",
"print(f\" Unified countries: {len(unified.get('countries', []))}\")\n",
"print(f\" Weekly trends: {len(weekly_trends.get('weeks', []))}\")\n",
"print(f\" Wikipedia trending: {len(wiki_trending)}\")\n",
"print(f\" Unified events: {len(events.get('events', []))}\")\n",
"print(f\" Attention timeline: {len(attention_timeline.get('weekly_timeline', []))}\")"
]
},
{
"cell_type": "markdown",
"id": "e4c9f2e6",
"metadata": {},
"source": [
"## Most Viewed Wikipedia Articles\n",
"\n",
"Which articles drew the most attention across all tracked countries?"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "4b6ee5b7",
"metadata": {},
"outputs": [],
"source": [
"df_trending = pd.DataFrame(wiki_trending)\n",
"top_20 = df_trending.nlargest(20, 'total_views')\n",
"\n",
"fig, ax = plt.subplots(figsize=(14, 8))\n",
"bars = ax.barh(range(len(top_20)), top_20['total_views'].values, color='#1565C0')\n",
"ax.set_yticks(range(len(top_20)))\n",
"ax.set_yticklabels(top_20['title'].values)\n",
"ax.set_xlabel('Total Pageviews')\n",
"ax.set_title('Top 20 Most Viewed Wikipedia Articles (2025)')\n",
"ax.invert_yaxis()\n",
"ax.xaxis.set_major_formatter(ticker.FuncFormatter(lambda x, _: f'{x/1e6:.1f}M'))\n",
"\n",
"for bar, val in zip(bars, top_20['total_views'].values):\n",
" ax.text(bar.get_width() + 1e5, bar.get_y() + bar.get_height()/2,\n",
" f'{val/1e6:.1f}M', va='center', fontsize=9)\n",
"\n",
"plt.tight_layout()\n",
"plt.show()\n",
"\n",
"print(f\"Total trending articles tracked: {len(wiki_trending)}\")\n",
"print(f\"Highest daily peak: {df_trending['peak_views'].max():,} views\")"
]
},
{
"cell_type": "markdown",
"id": "48ce9632",
"metadata": {},
"source": [
"## Google Trends -- Search Interest Over Time\n",
"\n",
"What were people searching for throughout 2025?"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "15d70f10",
"metadata": {},
"outputs": [],
"source": [
"# Weekly trends analysis\n",
"weeks_data = weekly_trends.get('weeks', [])\n",
"df_weeks = pd.DataFrame(weeks_data)\n",
"\n",
"fig, axes = plt.subplots(2, 1, figsize=(16, 10))\n",
"\n",
"# Global intensity over time\n",
"df_weeks['start_date_parsed'] = pd.to_datetime(df_weeks['start_date'])\n",
"axes[0].plot(df_weeks['start_date_parsed'], pd.to_numeric(df_weeks['global_intensity'], errors='coerce'),\n",
" color='#E91E63', linewidth=2, marker='o', markersize=4)\n",
"axes[0].set_ylabel('Global Intensity')\n",
"axes[0].set_title('Google Trends -- Global Search Intensity by Week (2025)')\n",
"axes[0].tick_params(axis='x', rotation=45)\n",
"\n",
"# US intensity\n",
"axes[1].plot(df_weeks['start_date_parsed'], pd.to_numeric(df_weeks['us_intensity'], errors='coerce'),\n",
" color='#2196F3', linewidth=2, marker='s', markersize=4)\n",
"axes[1].set_ylabel('US Intensity')\n",
"axes[1].set_title('Google Trends -- US Search Intensity by Week')\n",
"axes[1].set_xlabel('Week')\n",
"axes[1].tick_params(axis='x', rotation=45)\n",
"\n",
"plt.tight_layout()\n",
"plt.show()\n",
"\n",
"# Show top US searches\n",
"print(\"\\nTop US searches by week (sample):\")\n",
"for week in df_weeks.head(10).itertuples():\n",
" print(f\" Week {week.week}: {week.top_search_us}\")"
]
},
{
"cell_type": "markdown",
"id": "2124bca9",
"metadata": {},
"source": [
"## GDELT Events Timeline\n",
"\n",
"The GDELT Project monitors world events from news sources globally."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "fc1583b5",
"metadata": {},
"outputs": [],
"source": [
"# GDELT weekly event volume\n",
"gdelt_weeks = gdelt_weekly.get('weekly_events', [])\n",
"\n",
"week_dates = []\n",
"event_counts = []\n",
"for w in gdelt_weeks:\n",
" week_dates.append(w['week_start'])\n",
" event_counts.append(len(w.get('events', [])))\n",
"\n",
"fig, ax = plt.subplots(figsize=(16, 6))\n",
"dates = pd.to_datetime(week_dates)\n",
"ax.bar(dates, event_counts, width=5, color='#FF5722', alpha=0.8)\n",
"ax.set_xlabel('Week')\n",
"ax.set_ylabel('Number of Events')\n",
"ax.set_title('GDELT -- Weekly Event Volume (2025)')\n",
"ax.tick_params(axis='x', rotation=45)\n",
"\n",
"plt.tight_layout()\n",
"plt.show()\n",
"\n",
"total_events = sum(event_counts)\n",
"print(f\"Total GDELT events tracked: {total_events:,}\")\n",
"print(f\"Average events per week: {total_events / len(gdelt_weeks):.1f}\")"
]
},
{
"cell_type": "markdown",
"id": "799c4d6e",
"metadata": {},
"source": [
"## Unified Events -- Impact Analysis\n",
"\n",
"Major events tracked across all data sources, scored by impact."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "2c28fb5f",
"metadata": {},
"outputs": [],
"source": [
"df_events = pd.DataFrame(events.get('events', []))\n",
"\n",
"# Impact score distribution\n",
"fig, axes = plt.subplots(1, 2, figsize=(16, 7))\n",
"\n",
"axes[0].hist(pd.to_numeric(df_events['impact_score'], errors='coerce').dropna(),\n",
" bins=20, color='#9C27B0', edgecolor='white', alpha=0.8)\n",
"axes[0].set_xlabel('Impact Score')\n",
"axes[0].set_ylabel('Number of Events')\n",
"axes[0].set_title('Distribution of Event Impact Scores')\n",
"\n",
"# Sentiment direction\n",
"sentiment = df_events['sentiment_direction'].value_counts()\n",
"colors_sent = {'negative': '#F44336', 'positive': '#4CAF50', 'neutral': '#9E9E9E', 'mixed': '#FF9800'}\n",
"bars = axes[1].bar(sentiment.index, sentiment.values,\n",
" color=[colors_sent.get(s, '#607D8B') for s in sentiment.index])\n",
"axes[1].set_ylabel('Number of Events')\n",
"axes[1].set_title('Events by Sentiment Direction')\n",
"\n",
"plt.tight_layout()\n",
"plt.show()\n",
"\n",
"# Top impact events\n",
"top_events = df_events.nlargest(10, 'impact_score')[['name', 'date', 'impact_score', 'sentiment_direction']]\n",
"print(\"\\nTop 10 Highest Impact Events:\")\n",
"for _, row in top_events.iterrows():\n",
" print(f\" [{row['impact_score']}] {row['date']}: {row['name']} ({row['sentiment_direction']})\")"
]
},
{
"cell_type": "markdown",
"id": "0736421c",
"metadata": {},
"source": [
"## Country-Level Attention Comparison\n",
"\n",
"How does media/search attention vary across countries in the unified dataset?"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "ff0fc737",
"metadata": {},
"outputs": [],
"source": [
"# Unified country data\n",
"country_list = unified.get('countries', [])\n",
"df_unified_countries = pd.DataFrame(country_list)\n",
"\n",
"fig, ax = plt.subplots(figsize=(14, 7))\n",
"country_names = df_unified_countries['name'].values\n",
"regions = df_unified_countries['region'].values\n",
"\n",
"region_colors = {}\n",
"unique_regions = list(set(regions))\n",
"cmap = plt.cm.Set2(np.linspace(0, 1, len(unique_regions)))\n",
"for i, r in enumerate(unique_regions):\n",
" region_colors[r] = cmap[i]\n",
"\n",
"bar_colors = [region_colors[r] for r in regions]\n",
"bars = ax.barh(range(len(country_names)), range(len(country_names), 0, -1),\n",
" color=bar_colors)\n",
"\n",
"# Instead, show sentiment timelines for a few key countries\n",
"fig2, ax2 = plt.subplots(figsize=(16, 7))\n",
"highlight_countries = ['US', 'GB', 'FR', 'DE', 'CA', 'MX']\n",
"for c_data in country_list:\n",
" if c_data['code'] in highlight_countries:\n",
" timeline = c_data.get('sentiment_timeline', [])\n",
" if timeline:\n",
" dates = [t.get('date', t.get('week_start', '')) for t in timeline]\n",
" scores = [t.get('score', t.get('sentiment', 0)) for t in timeline]\n",
" if dates and scores:\n",
" ax2.plot(pd.to_datetime(dates[:52]), [float(s) if s else 0 for s in scores[:52]],\n",
" label=c_data['name'], linewidth=2, marker='o', markersize=3)\n",
"\n",
"ax2.set_xlabel('Date')\n",
"ax2.set_ylabel('Sentiment Score')\n",
"ax2.set_title('Sentiment Toward US -- Key Countries Over Time')\n",
"ax2.legend(loc='best')\n",
"ax2.tick_params(axis='x', rotation=45)\n",
"ax2.axhline(y=0, color='gray', linestyle='--', alpha=0.5)\n",
"plt.tight_layout()\n",
"plt.close(fig) # close the placeholder\n",
"plt.show()\n",
"\n",
"print(f\"Countries tracked: {len(country_list)}\")\n",
"print(f\"Regions: {', '.join(unique_regions)}\")"
]
},
{
"cell_type": "markdown",
"id": "1243e131",
"metadata": {},
"source": [
"## Weekly Attention Timeline\n",
"\n",
"Composite attention signal combining Wikipedia, Trends, and GDELT."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "e4926681",
"metadata": {},
"outputs": [],
"source": [
"timeline = attention_timeline.get('weekly_timeline', [])\n",
"\n",
"weeks_parsed = []\n",
"for w in timeline:\n",
" entry = {'week_start': w['week_start']}\n",
" components = w.get('components', {})\n",
" for key in components:\n",
" if isinstance(components[key], (int, float)):\n",
" entry[key] = components[key]\n",
" elif isinstance(components[key], dict):\n",
" for subkey, val in components[key].items():\n",
" if isinstance(val, (int, float)):\n",
" entry[f'{key}_{subkey}'] = val\n",
" weeks_parsed.append(entry)\n",
"\n",
"df_timeline = pd.DataFrame(weeks_parsed)\n",
"df_timeline['week_start'] = pd.to_datetime(df_timeline['week_start'])\n",
"\n",
"# Plot available numeric columns\n",
"numeric_cols = [c for c in df_timeline.columns if c != 'week_start' and df_timeline[c].dtype in ['float64', 'int64']]\n",
"\n",
"fig, ax = plt.subplots(figsize=(16, 7))\n",
"for i, col in enumerate(numeric_cols[:5]):\n",
" ax.plot(df_timeline['week_start'], df_timeline[col],\n",
" label=col.replace('_', ' ').title(), linewidth=1.5, alpha=0.8)\n",
"\n",
"ax.set_xlabel('Week')\n",
"ax.set_ylabel('Score')\n",
"ax.set_title('Weekly Attention Components Over Time')\n",
"ax.legend(loc='best', fontsize=9)\n",
"ax.tick_params(axis='x', rotation=45)\n",
"plt.tight_layout()\n",
"plt.show()\n",
"\n",
"print(f\"Weeks tracked: {len(timeline)}\")\n",
"print(f\"Components available: {numeric_cols[:10]}\")"
]
},
{
"cell_type": "markdown",
"id": "e3d26c53",
"metadata": {},
"source": [
"## Summary Statistics"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "60073285",
"metadata": {},
"outputs": [],
"source": [
"print(\"=\" * 60)\n",
"print(\"US ATTENTION DATA -- SUMMARY\")\n",
"print(\"=\" * 60)\n",
"print(f\"Timeframe: {trends.get('timeframe', 'N/A')}\")\n",
"print(f\"Wikipedia trending: {len(wiki_trending):>10,} articles\")\n",
"print(f\"GDELT weeks tracked: {len(gdelt_weekly.get('weekly_events',[])):>10}\")\n",
"print(f\"Unified events: {len(events.get('events',[])):>10}\")\n",
"print(f\"Countries tracked: {len(unified.get('countries',[])):>10}\")\n",
"print(f\"Weekly trends: {len(weekly_trends.get('weeks',[])):>10}\")\n",
"print(f\"Search terms tracked: {len(trends.get('terms',{})):>10}\")\n",
"print()\n",
"print(\"Data sources:\")\n",
"for src in unified.get('metadata', {}).get('data_sources', []):\n",
" if isinstance(src, dict):\n",
" print(f\" -- {src.get('name', src)}: {src.get('description', '')}\")\n",
" else:\n",
" print(f\" -- {src}\")\n",
"print(\"=\" * 60)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
|