Spaces:
Running
Running
feat(rag-api): hybrid top stories — 3 from Kafka news.processed + 3 from DuckDuckGo
Browse files- Kafka consumer reads N most recent messages from news.processed topic
by seeking to partition end and reading backwards (no offset tracking)
- SSL cert resolution: env var content > file path env var > /app/certs/ default
- DuckDuckGo fetches 3 live Ethiopia stories in parallel
- Both sources run concurrently via asyncio.gather
- Deduplication by title prefix (60 chars) across both sources
- Fallback: if Kafka unavailable, fills all 6 slots from DuckDuckGo
- Cache TTL reduced to 2 minutes for freshness
- Response includes kafka_count and live_count for debugging
- origin field on each story: 'kafka' or 'live'
- .env +9 -0
- src/api/routes/top_stories.py +273 -156
- src/core/config.py +7 -0
.env
CHANGED
|
@@ -90,6 +90,15 @@ ENABLE_JINA_READER=true
|
|
| 90 |
JINA_READER_TIMEOUT=8.0
|
| 91 |
JINA_READER_MAX_CONCURRENT=5
|
| 92 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
# Live Search Engine Configuration
|
| 94 |
LIVE_SEARCH_PRIMARY=searxng
|
| 95 |
LIVE_SEARCH_FALLBACK=duckduckgo
|
|
|
|
| 90 |
JINA_READER_TIMEOUT=8.0
|
| 91 |
JINA_READER_MAX_CONCURRENT=5
|
| 92 |
|
| 93 |
+
# --- Kafka Settings (Top Stories — read-only consumer) ---
|
| 94 |
+
KAFKA_BOOTSTRAP_SERVERS=kafka-23e11337-weldamedhan2020-b406.i.aivencloud.com:20010
|
| 95 |
+
KAFKA_TOPIC_PROCESSED=news.processed
|
| 96 |
+
# SSL certs are read from /tmp/ — written at startup from env vars or cert files
|
| 97 |
+
# Set these to the content of your Aiven SSL certificates (newlines as \n)
|
| 98 |
+
# KAFKA_SSL_CA=<content of ca.pem>
|
| 99 |
+
# KAFKA_SSL_CERT=<content of service.cert>
|
| 100 |
+
# KAFKA_SSL_KEY=<content of service.key>
|
| 101 |
+
|
| 102 |
# Live Search Engine Configuration
|
| 103 |
LIVE_SEARCH_PRIMARY=searxng
|
| 104 |
LIVE_SEARCH_FALLBACK=duckduckgo
|
src/api/routes/top_stories.py
CHANGED
|
@@ -2,22 +2,18 @@
|
|
| 2 |
Top Stories API Endpoint
|
| 3 |
|
| 4 |
Provides fresh news headlines for the landing page.
|
|
|
|
| 5 |
Fast, cached, and optimized for frontend display.
|
| 6 |
-
|
| 7 |
-
Features:
|
| 8 |
-
- DuckDuckGo news search (fast, no API key)
|
| 9 |
-
- 5-minute cache (reduce API calls)
|
| 10 |
-
- Ethiopia-focused by default
|
| 11 |
-
- Multiple categories support
|
| 12 |
-
- Clean, frontend-ready format
|
| 13 |
"""
|
| 14 |
|
| 15 |
import logging
|
|
|
|
|
|
|
|
|
|
| 16 |
from typing import List, Optional
|
| 17 |
-
from fastapi import APIRouter, Query
|
| 18 |
from pydantic import BaseModel
|
| 19 |
from datetime import datetime
|
| 20 |
-
import asyncio
|
| 21 |
|
| 22 |
logger = logging.getLogger(__name__)
|
| 23 |
|
|
@@ -32,6 +28,7 @@ class TopStory(BaseModel):
|
|
| 32 |
published_at: str
|
| 33 |
category: str = "NEWS"
|
| 34 |
excerpt: Optional[str] = None
|
|
|
|
| 35 |
|
| 36 |
|
| 37 |
class TopStoriesResponse(BaseModel):
|
|
@@ -39,175 +36,315 @@ class TopStoriesResponse(BaseModel):
|
|
| 39 |
stories: List[TopStory]
|
| 40 |
fetched_at: str
|
| 41 |
cache_hit: bool = False
|
|
|
|
|
|
|
| 42 |
|
| 43 |
|
| 44 |
-
# Simple in-memory cache (
|
| 45 |
-
_cache = {}
|
| 46 |
-
_cache_ttl =
|
| 47 |
|
| 48 |
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
region: str = "et-en"
|
| 53 |
-
) -> List[TopStory]:
|
| 54 |
"""
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
max_results: Number of results (default: 10)
|
| 60 |
-
region: DuckDuckGo region (default: "et-en" for Ethiopia)
|
| 61 |
-
|
| 62 |
-
Returns:
|
| 63 |
-
List of TopStory objects
|
| 64 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 65 |
try:
|
| 66 |
from ddgs import DDGS
|
| 67 |
-
|
| 68 |
-
# Run DuckDuckGo search in thread pool (it's synchronous)
|
| 69 |
loop = asyncio.get_event_loop()
|
| 70 |
-
|
| 71 |
def _search():
|
| 72 |
ddgs = DDGS()
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
max_results=max_results
|
| 77 |
-
)
|
| 78 |
-
return list(results)
|
| 79 |
-
|
| 80 |
-
raw_results = await asyncio.wait_for(
|
| 81 |
loop.run_in_executor(None, _search),
|
| 82 |
-
timeout=5.0
|
| 83 |
)
|
| 84 |
-
|
| 85 |
-
# Convert to TopStory format
|
| 86 |
stories = []
|
| 87 |
-
for r in
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
url=r.get("url", "").strip(),
|
| 92 |
-
source=r.get("source", "Unknown").strip(),
|
| 93 |
-
published_at=r.get("date", datetime.utcnow().isoformat()),
|
| 94 |
-
category="NEWS",
|
| 95 |
-
excerpt=r.get("body", "")[:150] if r.get("body") else None
|
| 96 |
-
)
|
| 97 |
-
|
| 98 |
-
# Validate required fields
|
| 99 |
-
if story.title and story.url:
|
| 100 |
-
stories.append(story)
|
| 101 |
-
except Exception as e:
|
| 102 |
-
logger.warning(f"Failed to parse story: {e}")
|
| 103 |
continue
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 108 |
except asyncio.TimeoutError:
|
| 109 |
-
logger.warning("DuckDuckGo
|
| 110 |
return []
|
| 111 |
-
|
| 112 |
except Exception as e:
|
| 113 |
-
logger.error(f"
|
| 114 |
return []
|
| 115 |
|
| 116 |
|
|
|
|
|
|
|
| 117 |
@router.get("/top-stories", response_model=TopStoriesResponse)
|
| 118 |
async def get_top_stories(
|
| 119 |
-
|
| 120 |
-
default="Ethiopia",
|
| 121 |
-
description="Search query for top stories"
|
| 122 |
-
),
|
| 123 |
-
max_results: int = Query(
|
| 124 |
-
default=10,
|
| 125 |
-
ge=1,
|
| 126 |
-
le=20,
|
| 127 |
-
description="Number of stories to return (1-20)"
|
| 128 |
-
),
|
| 129 |
-
category: Optional[str] = Query(
|
| 130 |
-
default=None,
|
| 131 |
-
description="Filter by category (not implemented yet)"
|
| 132 |
-
),
|
| 133 |
-
force_refresh: bool = Query(
|
| 134 |
-
default=False,
|
| 135 |
-
description="Force cache refresh"
|
| 136 |
-
)
|
| 137 |
):
|
| 138 |
"""
|
| 139 |
-
Get top news stories for the landing page.
|
| 140 |
-
|
| 141 |
-
**
|
| 142 |
-
-
|
| 143 |
-
-
|
| 144 |
-
|
| 145 |
-
-
|
| 146 |
-
|
| 147 |
-
**Example:**
|
| 148 |
-
```
|
| 149 |
-
GET /api/v1/top-stories?query=Ethiopia&max_results=10
|
| 150 |
-
```
|
| 151 |
-
|
| 152 |
-
**Response:**
|
| 153 |
-
```json
|
| 154 |
-
{
|
| 155 |
-
"stories": [
|
| 156 |
-
{
|
| 157 |
-
"title": "Ethiopia announces new economic reforms",
|
| 158 |
-
"url": "https://example.com/article",
|
| 159 |
-
"source": "BBC",
|
| 160 |
-
"published_at": "2026-05-04T10:30:00",
|
| 161 |
-
"category": "NEWS",
|
| 162 |
-
"excerpt": "Prime Minister announces..."
|
| 163 |
-
}
|
| 164 |
-
],
|
| 165 |
-
"fetched_at": "2026-05-04T10:35:00",
|
| 166 |
-
"cache_hit": false
|
| 167 |
-
}
|
| 168 |
-
```
|
| 169 |
"""
|
| 170 |
-
cache_key =
|
| 171 |
-
|
| 172 |
-
# Check cache (unless force refresh)
|
| 173 |
if not force_refresh and cache_key in _cache:
|
| 174 |
cached_data, cached_time = _cache[cache_key]
|
| 175 |
age = (datetime.utcnow() - cached_time).total_seconds()
|
| 176 |
-
|
| 177 |
if age < _cache_ttl:
|
| 178 |
-
logger.info(f"
|
| 179 |
return TopStoriesResponse(
|
| 180 |
-
stories=cached_data,
|
| 181 |
fetched_at=cached_time.isoformat(),
|
| 182 |
-
cache_hit=True
|
|
|
|
|
|
|
| 183 |
)
|
| 184 |
-
|
| 185 |
-
# Fetch
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
max_results=max_results
|
| 190 |
)
|
| 191 |
-
|
| 192 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 193 |
now = datetime.utcnow()
|
| 194 |
-
|
| 195 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 196 |
return TopStoriesResponse(
|
| 197 |
-
stories=
|
| 198 |
fetched_at=now.isoformat(),
|
| 199 |
-
cache_hit=False
|
|
|
|
|
|
|
| 200 |
)
|
| 201 |
|
| 202 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 203 |
@router.get("/top-stories/categories")
|
| 204 |
async def get_categories():
|
| 205 |
-
"""
|
| 206 |
-
Get available story categories.
|
| 207 |
-
|
| 208 |
-
**Note:** Currently only "NEWS" is supported.
|
| 209 |
-
Future: POLITICS, ECONOMY, SPORTS, etc.
|
| 210 |
-
"""
|
| 211 |
return {
|
| 212 |
"categories": [
|
| 213 |
{"id": "news", "name": "News", "query": "Ethiopia"},
|
|
@@ -216,23 +353,3 @@ async def get_categories():
|
|
| 216 |
{"id": "sports", "name": "Sports", "query": "Ethiopia sports"},
|
| 217 |
]
|
| 218 |
}
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
@router.post("/top-stories/refresh")
|
| 222 |
-
async def refresh_top_stories():
|
| 223 |
-
"""
|
| 224 |
-
Clear the top stories cache.
|
| 225 |
-
|
| 226 |
-
**Use case:** Admin wants to force refresh all cached stories.
|
| 227 |
-
"""
|
| 228 |
-
global _cache
|
| 229 |
-
old_size = len(_cache)
|
| 230 |
-
_cache.clear()
|
| 231 |
-
|
| 232 |
-
logger.info(f"Cleared top stories cache ({old_size} entries)")
|
| 233 |
-
|
| 234 |
-
return {
|
| 235 |
-
"success": True,
|
| 236 |
-
"message": f"Cleared {old_size} cached entries",
|
| 237 |
-
"cleared_at": datetime.utcnow().isoformat()
|
| 238 |
-
}
|
|
|
|
| 2 |
Top Stories API Endpoint
|
| 3 |
|
| 4 |
Provides fresh news headlines for the landing page.
|
| 5 |
+
Hybrid approach: 3 from Kafka news.processed (pipeline-fresh) + 3 from DuckDuckGo (live).
|
| 6 |
Fast, cached, and optimized for frontend display.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
"""
|
| 8 |
|
| 9 |
import logging
|
| 10 |
+
import asyncio
|
| 11 |
+
import json
|
| 12 |
+
import msgpack
|
| 13 |
from typing import List, Optional
|
| 14 |
+
from fastapi import APIRouter, Query
|
| 15 |
from pydantic import BaseModel
|
| 16 |
from datetime import datetime
|
|
|
|
| 17 |
|
| 18 |
logger = logging.getLogger(__name__)
|
| 19 |
|
|
|
|
| 28 |
published_at: str
|
| 29 |
category: str = "NEWS"
|
| 30 |
excerpt: Optional[str] = None
|
| 31 |
+
origin: str = "kafka" # "kafka" or "live"
|
| 32 |
|
| 33 |
|
| 34 |
class TopStoriesResponse(BaseModel):
|
|
|
|
| 36 |
stories: List[TopStory]
|
| 37 |
fetched_at: str
|
| 38 |
cache_hit: bool = False
|
| 39 |
+
kafka_count: int = 0
|
| 40 |
+
live_count: int = 0
|
| 41 |
|
| 42 |
|
| 43 |
+
# Simple in-memory cache (2 minutes — shorter TTL for freshness)
|
| 44 |
+
_cache: dict = {}
|
| 45 |
+
_cache_ttl = 120 # 2 minutes
|
| 46 |
|
| 47 |
|
| 48 |
+
# ── Kafka: read latest N messages from news.processed ────────────────────────
|
| 49 |
+
|
| 50 |
+
def _fetch_kafka_stories_sync(n: int = 3) -> List[TopStory]:
|
|
|
|
|
|
|
| 51 |
"""
|
| 52 |
+
Read the N most recent messages from the news.processed Kafka topic.
|
| 53 |
+
Uses a temporary consumer that seeks to the end of each partition,
|
| 54 |
+
then reads backwards to get the latest messages.
|
| 55 |
+
Runs synchronously (called via executor).
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 56 |
"""
|
| 57 |
+
import os
|
| 58 |
+
from confluent_kafka import Consumer, TopicPartition
|
| 59 |
+
|
| 60 |
+
bootstrap = os.getenv("KAFKA_BOOTSTRAP_SERVERS", "")
|
| 61 |
+
topic = os.getenv("KAFKA_TOPIC_PROCESSED", "news.processed")
|
| 62 |
+
|
| 63 |
+
if not bootstrap:
|
| 64 |
+
logger.warning("KAFKA_BOOTSTRAP_SERVERS not set — skipping Kafka top stories")
|
| 65 |
+
return []
|
| 66 |
+
|
| 67 |
+
# SSL certs: support both env-var content and file paths
|
| 68 |
+
# Priority: env var content → file path → skip SSL
|
| 69 |
+
def _write_cert(env_content_key: str, env_path_key: str, tmp_path: str) -> bool:
|
| 70 |
+
content = os.getenv(env_content_key, "")
|
| 71 |
+
if content:
|
| 72 |
+
with open(tmp_path, "w") as f:
|
| 73 |
+
f.write(content.replace("\\n", "\n"))
|
| 74 |
+
return True
|
| 75 |
+
file_path = os.getenv(env_path_key, "")
|
| 76 |
+
if file_path and os.path.exists(file_path):
|
| 77 |
+
import shutil
|
| 78 |
+
shutil.copy(file_path, tmp_path)
|
| 79 |
+
return True
|
| 80 |
+
# Try default cert locations (HF Spaces mounts certs here)
|
| 81 |
+
default_paths = [
|
| 82 |
+
f"/app/certs/{os.path.basename(tmp_path)}",
|
| 83 |
+
f"certs/{os.path.basename(tmp_path)}",
|
| 84 |
+
]
|
| 85 |
+
for dp in default_paths:
|
| 86 |
+
if os.path.exists(dp):
|
| 87 |
+
import shutil
|
| 88 |
+
shutil.copy(dp, tmp_path)
|
| 89 |
+
return True
|
| 90 |
+
return False
|
| 91 |
+
|
| 92 |
+
has_ca = _write_cert("KAFKA_SSL_CA", "KAFKA_SSL_CA_PATH", "/tmp/ca.pem")
|
| 93 |
+
has_cert = _write_cert("KAFKA_SSL_CERT", "KAFKA_SSL_CERT_PATH", "/tmp/service.cert")
|
| 94 |
+
has_key = _write_cert("KAFKA_SSL_KEY", "KAFKA_SSL_KEY_PATH", "/tmp/service.key")
|
| 95 |
+
|
| 96 |
+
conf = {
|
| 97 |
+
"bootstrap.servers": bootstrap,
|
| 98 |
+
"group.id": "top-stories-reader",
|
| 99 |
+
"auto.offset.reset": "latest",
|
| 100 |
+
"enable.auto.commit": False,
|
| 101 |
+
"log_level": 0,
|
| 102 |
+
"session.timeout.ms": 10000,
|
| 103 |
+
}
|
| 104 |
+
|
| 105 |
+
if has_ca and has_cert and has_key:
|
| 106 |
+
conf["security.protocol"] = "SSL"
|
| 107 |
+
conf["ssl.ca.location"] = "/tmp/ca.pem"
|
| 108 |
+
conf["ssl.certificate.location"] = "/tmp/service.cert"
|
| 109 |
+
conf["ssl.key.location"] = "/tmp/service.key"
|
| 110 |
+
logger.info("Kafka SSL configured for top stories consumer")
|
| 111 |
+
else:
|
| 112 |
+
logger.warning("Kafka SSL certs not found — connecting without SSL")
|
| 113 |
+
|
| 114 |
+
consumer = Consumer(conf)
|
| 115 |
+
stories: List[TopStory] = []
|
| 116 |
+
|
| 117 |
+
try:
|
| 118 |
+
# Get partition metadata
|
| 119 |
+
meta = consumer.list_topics(topic, timeout=5)
|
| 120 |
+
if topic not in meta.topics:
|
| 121 |
+
logger.warning(f"Kafka topic '{topic}' not found")
|
| 122 |
+
return []
|
| 123 |
+
|
| 124 |
+
partitions = [
|
| 125 |
+
TopicPartition(topic, p)
|
| 126 |
+
for p in meta.topics[topic].partitions.keys()
|
| 127 |
+
]
|
| 128 |
+
|
| 129 |
+
# Get high watermarks and seek to (high - n) per partition
|
| 130 |
+
assigned = []
|
| 131 |
+
for tp in partitions:
|
| 132 |
+
low, high = consumer.get_watermark_offsets(tp, timeout=5)
|
| 133 |
+
if high > 0:
|
| 134 |
+
start = max(low, high - n)
|
| 135 |
+
assigned.append(TopicPartition(topic, tp.partition, start))
|
| 136 |
+
|
| 137 |
+
if not assigned:
|
| 138 |
+
return []
|
| 139 |
+
|
| 140 |
+
consumer.assign(assigned)
|
| 141 |
+
|
| 142 |
+
# Poll until we have n messages or timeout
|
| 143 |
+
import time
|
| 144 |
+
deadline = time.time() + 5.0
|
| 145 |
+
raw_messages = []
|
| 146 |
+
|
| 147 |
+
while len(raw_messages) < n and time.time() < deadline:
|
| 148 |
+
msg = consumer.poll(timeout=1.0)
|
| 149 |
+
if msg is None:
|
| 150 |
+
break
|
| 151 |
+
if msg.error():
|
| 152 |
+
continue
|
| 153 |
+
raw_messages.append(msg)
|
| 154 |
+
|
| 155 |
+
# Parse messages
|
| 156 |
+
seen_titles: set = set()
|
| 157 |
+
for msg in raw_messages:
|
| 158 |
+
try:
|
| 159 |
+
value = msg.value()
|
| 160 |
+
try:
|
| 161 |
+
event = msgpack.unpackb(value, raw=False)
|
| 162 |
+
except Exception:
|
| 163 |
+
event = json.loads(value.decode("utf-8", errors="ignore"))
|
| 164 |
+
|
| 165 |
+
title = event.get("title") or event.get("content", "")[:80]
|
| 166 |
+
url = event.get("url") or event.get("link") or ""
|
| 167 |
+
source = event.get("source") or event.get("publisher") or "ARKI"
|
| 168 |
+
pub_at = event.get("published_at") or event.get("pub_date") or datetime.utcnow().isoformat()
|
| 169 |
+
content = event.get("content") or event.get("text") or ""
|
| 170 |
+
excerpt = content[:150] if content else None
|
| 171 |
+
|
| 172 |
+
if not title or title in seen_titles:
|
| 173 |
+
continue
|
| 174 |
+
seen_titles.add(title)
|
| 175 |
+
|
| 176 |
+
stories.append(TopStory(
|
| 177 |
+
title=title.strip()[:200],
|
| 178 |
+
url=url.strip(),
|
| 179 |
+
source=source.strip(),
|
| 180 |
+
published_at=pub_at,
|
| 181 |
+
category="NEWS",
|
| 182 |
+
excerpt=excerpt,
|
| 183 |
+
origin="kafka",
|
| 184 |
+
))
|
| 185 |
+
|
| 186 |
+
except Exception as e:
|
| 187 |
+
logger.debug(f"Failed to parse Kafka message: {e}")
|
| 188 |
+
continue
|
| 189 |
+
|
| 190 |
+
except Exception as e:
|
| 191 |
+
logger.error(f"Kafka top stories error: {e}")
|
| 192 |
+
finally:
|
| 193 |
+
consumer.close()
|
| 194 |
+
|
| 195 |
+
logger.info(f"Kafka top stories: fetched {len(stories)} from '{topic}'")
|
| 196 |
+
return stories[:n]
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
async def fetch_kafka_stories(n: int = 3) -> List[TopStory]:
|
| 200 |
+
"""Async wrapper — runs Kafka consumer in thread pool"""
|
| 201 |
+
loop = asyncio.get_event_loop()
|
| 202 |
+
try:
|
| 203 |
+
return await asyncio.wait_for(
|
| 204 |
+
loop.run_in_executor(None, _fetch_kafka_stories_sync, n),
|
| 205 |
+
timeout=6.0
|
| 206 |
+
)
|
| 207 |
+
except asyncio.TimeoutError:
|
| 208 |
+
logger.warning("Kafka top stories timeout")
|
| 209 |
+
return []
|
| 210 |
+
except Exception as e:
|
| 211 |
+
logger.error(f"Kafka top stories async error: {e}")
|
| 212 |
+
return []
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
# ── DuckDuckGo: fetch N live stories ─────────────────────────────────────────
|
| 216 |
+
|
| 217 |
+
async def fetch_ddg_stories(n: int = 3) -> List[TopStory]:
|
| 218 |
+
"""Fetch N live stories from DuckDuckGo"""
|
| 219 |
try:
|
| 220 |
from ddgs import DDGS
|
| 221 |
+
|
|
|
|
| 222 |
loop = asyncio.get_event_loop()
|
| 223 |
+
|
| 224 |
def _search():
|
| 225 |
ddgs = DDGS()
|
| 226 |
+
return list(ddgs.news("Ethiopia", region="et-en", max_results=n))
|
| 227 |
+
|
| 228 |
+
raw = await asyncio.wait_for(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 229 |
loop.run_in_executor(None, _search),
|
| 230 |
+
timeout=5.0
|
| 231 |
)
|
| 232 |
+
|
|
|
|
| 233 |
stories = []
|
| 234 |
+
for r in raw:
|
| 235 |
+
title = r.get("title", "").strip()
|
| 236 |
+
url = r.get("url", "").strip()
|
| 237 |
+
if not title or not url:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 238 |
continue
|
| 239 |
+
stories.append(TopStory(
|
| 240 |
+
title=title,
|
| 241 |
+
url=url,
|
| 242 |
+
source=r.get("source", "Unknown").strip(),
|
| 243 |
+
published_at=r.get("date", datetime.utcnow().isoformat()),
|
| 244 |
+
category="NEWS",
|
| 245 |
+
excerpt=r.get("body", "")[:150] if r.get("body") else None,
|
| 246 |
+
origin="live",
|
| 247 |
+
))
|
| 248 |
+
|
| 249 |
+
logger.info(f"DuckDuckGo top stories: fetched {len(stories)}")
|
| 250 |
+
return stories[:n]
|
| 251 |
+
|
| 252 |
except asyncio.TimeoutError:
|
| 253 |
+
logger.warning("DuckDuckGo top stories timeout")
|
| 254 |
return []
|
|
|
|
| 255 |
except Exception as e:
|
| 256 |
+
logger.error(f"DuckDuckGo top stories error: {e}")
|
| 257 |
return []
|
| 258 |
|
| 259 |
|
| 260 |
+
# ── Endpoint ──────────────────────────────────────────────────────────────────
|
| 261 |
+
|
| 262 |
@router.get("/top-stories", response_model=TopStoriesResponse)
|
| 263 |
async def get_top_stories(
|
| 264 |
+
force_refresh: bool = Query(default=False, description="Force cache refresh"),
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 265 |
):
|
| 266 |
"""
|
| 267 |
+
Get top 6 news stories for the landing page.
|
| 268 |
+
|
| 269 |
+
**Sources:**
|
| 270 |
+
- 3 from Kafka `news.processed` topic (pipeline-fresh, multilingual)
|
| 271 |
+
- 3 from DuckDuckGo live search (real-time, English)
|
| 272 |
+
|
| 273 |
+
**Cache:** 2-minute TTL for freshness.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 274 |
"""
|
| 275 |
+
cache_key = "top_stories_hybrid"
|
| 276 |
+
|
|
|
|
| 277 |
if not force_refresh and cache_key in _cache:
|
| 278 |
cached_data, cached_time = _cache[cache_key]
|
| 279 |
age = (datetime.utcnow() - cached_time).total_seconds()
|
|
|
|
| 280 |
if age < _cache_ttl:
|
| 281 |
+
logger.info(f"Top stories cache HIT (age={age:.0f}s)")
|
| 282 |
return TopStoriesResponse(
|
| 283 |
+
stories=cached_data["stories"],
|
| 284 |
fetched_at=cached_time.isoformat(),
|
| 285 |
+
cache_hit=True,
|
| 286 |
+
kafka_count=cached_data["kafka_count"],
|
| 287 |
+
live_count=cached_data["live_count"],
|
| 288 |
)
|
| 289 |
+
|
| 290 |
+
# Fetch both sources in parallel
|
| 291 |
+
kafka_stories, ddg_stories = await asyncio.gather(
|
| 292 |
+
fetch_kafka_stories(3),
|
| 293 |
+
fetch_ddg_stories(3),
|
|
|
|
| 294 |
)
|
| 295 |
+
|
| 296 |
+
# Merge: Kafka first (pipeline-fresh), then DuckDuckGo (live)
|
| 297 |
+
# Deduplicate by title similarity
|
| 298 |
+
all_stories: List[TopStory] = []
|
| 299 |
+
seen_titles: set = set()
|
| 300 |
+
|
| 301 |
+
for story in kafka_stories + ddg_stories:
|
| 302 |
+
title_key = story.title.lower()[:60]
|
| 303 |
+
if title_key not in seen_titles:
|
| 304 |
+
seen_titles.add(title_key)
|
| 305 |
+
all_stories.append(story)
|
| 306 |
+
|
| 307 |
+
# Fallback: if Kafka returned nothing, fill with more DuckDuckGo
|
| 308 |
+
if len(kafka_stories) == 0:
|
| 309 |
+
extra_ddg = await fetch_ddg_stories(6)
|
| 310 |
+
for story in extra_ddg:
|
| 311 |
+
title_key = story.title.lower()[:60]
|
| 312 |
+
if title_key not in seen_titles and len(all_stories) < 6:
|
| 313 |
+
seen_titles.add(title_key)
|
| 314 |
+
all_stories.append(story)
|
| 315 |
+
|
| 316 |
now = datetime.utcnow()
|
| 317 |
+
payload = {
|
| 318 |
+
"stories": all_stories[:6],
|
| 319 |
+
"kafka_count": len(kafka_stories),
|
| 320 |
+
"live_count": len(ddg_stories),
|
| 321 |
+
}
|
| 322 |
+
_cache[cache_key] = (payload, now)
|
| 323 |
+
|
| 324 |
+
logger.info(
|
| 325 |
+
f"Top stories: {len(kafka_stories)} Kafka + {len(ddg_stories)} DuckDuckGo "
|
| 326 |
+
f"= {len(all_stories[:6])} total"
|
| 327 |
+
)
|
| 328 |
+
|
| 329 |
return TopStoriesResponse(
|
| 330 |
+
stories=all_stories[:6],
|
| 331 |
fetched_at=now.isoformat(),
|
| 332 |
+
cache_hit=False,
|
| 333 |
+
kafka_count=len(kafka_stories),
|
| 334 |
+
live_count=len(ddg_stories),
|
| 335 |
)
|
| 336 |
|
| 337 |
|
| 338 |
+
@router.post("/top-stories/refresh")
|
| 339 |
+
async def refresh_top_stories():
|
| 340 |
+
"""Clear the top stories cache"""
|
| 341 |
+
global _cache
|
| 342 |
+
_cache.clear()
|
| 343 |
+
return {"success": True, "cleared_at": datetime.utcnow().isoformat()}
|
| 344 |
+
|
| 345 |
+
|
| 346 |
@router.get("/top-stories/categories")
|
| 347 |
async def get_categories():
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 348 |
return {
|
| 349 |
"categories": [
|
| 350 |
{"id": "news", "name": "News", "query": "Ethiopia"},
|
|
|
|
| 353 |
{"id": "sports", "name": "Sports", "query": "Ethiopia sports"},
|
| 354 |
]
|
| 355 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/core/config.py
CHANGED
|
@@ -93,5 +93,12 @@ class Settings(BaseSettings):
|
|
| 93 |
# Security Settings
|
| 94 |
SECRET_KEY: str = os.getenv("SECRET_KEY", "a_very_secret_key_change_me_in_production")
|
| 95 |
ACCESS_TOKEN_EXPIRE_MINUTES: int = int(os.getenv("ACCESS_TOKEN_EXPIRE_MINUTES", "60"))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 96 |
|
| 97 |
settings = Settings()
|
|
|
|
| 93 |
# Security Settings
|
| 94 |
SECRET_KEY: str = os.getenv("SECRET_KEY", "a_very_secret_key_change_me_in_production")
|
| 95 |
ACCESS_TOKEN_EXPIRE_MINUTES: int = int(os.getenv("ACCESS_TOKEN_EXPIRE_MINUTES", "60"))
|
| 96 |
+
|
| 97 |
+
# Kafka Settings (for Top Stories — read-only consumer)
|
| 98 |
+
KAFKA_BOOTSTRAP_SERVERS: str = os.getenv("KAFKA_BOOTSTRAP_SERVERS", "")
|
| 99 |
+
KAFKA_SSL_CA: str = os.getenv("KAFKA_SSL_CA", "")
|
| 100 |
+
KAFKA_SSL_CERT: str = os.getenv("KAFKA_SSL_CERT", "")
|
| 101 |
+
KAFKA_SSL_KEY: str = os.getenv("KAFKA_SSL_KEY", "")
|
| 102 |
+
KAFKA_TOPIC_PROCESSED: str = os.getenv("KAFKA_TOPIC_PROCESSED", "news.processed")
|
| 103 |
|
| 104 |
settings = Settings()
|