File size: 10,990 Bytes
198ccb0 |
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 |
"""API endpoints for advanced analytics."""
import logging
from typing import List, Dict, Optional
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel, Field, validator
from analysis.predictive_intervals import (
calculate_predictive_interval,
rank_by_predictive_interval,
get_top_positive_by_interval,
get_top_negative_by_interval
)
from analysis.category_analytics import CategoryAnalytics
from analysis.thread_analysis import ThreadAnalyzer
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Create router
router = APIRouter(prefix="/analytics", tags=["analytics"])
# Global analyzers (lazy loaded)
category_analytics: Optional[CategoryAnalytics] = None
thread_analyzer: Optional[ThreadAnalyzer] = None
def get_category_analytics() -> CategoryAnalytics:
"""Get or create category analytics instance."""
global category_analytics
if category_analytics is None:
category_analytics = CategoryAnalytics()
return category_analytics
def get_thread_analyzer() -> ThreadAnalyzer:
"""Get or create thread analyzer instance."""
global thread_analyzer
if thread_analyzer is None:
thread_analyzer = ThreadAnalyzer()
return thread_analyzer
# Request/Response Models
class SentimentCounts(BaseModel):
"""Sentiment counts for an item."""
id: str = Field(..., description="Item identifier")
positive_count: int = Field(..., description="Number of positive comments", ge=0)
negative_count: int = Field(..., description="Number of negative comments", ge=0)
neutral_count: int = Field(0, description="Number of neutral comments", ge=0)
class PredictiveIntervalRequest(BaseModel):
"""Request model for predictive interval calculation."""
data: List[SentimentCounts] = Field(..., description="List of items with sentiment counts", min_items=1)
confidence_level: float = Field(0.95, description="Confidence level", ge=0.90, le=0.99)
class Config:
json_schema_extra = {
"example": {
"data": [
{"id": "news_1", "positive_count": 80, "negative_count": 20, "neutral_count": 0},
{"id": "news_2", "positive_count": 1, "negative_count": 0, "neutral_count": 0}
],
"confidence_level": 0.95
}
}
class PredictiveIntervalResponse(BaseModel):
"""Response model for predictive interval calculation."""
ranked_data: List[Dict] = Field(..., description="Items ranked by predictive interval")
top_positive: List[Dict] = Field(..., description="Top positive items")
top_negative: List[Dict] = Field(..., description="Top negative items")
class CategorySentimentRequest(BaseModel):
"""Request model for category sentiment analysis."""
data: List[Dict[str, str]] = Field(..., description="List of items with category and text", min_items=1)
class Config:
json_schema_extra = {
"example": {
"data": [
{"category": "politics", "text": "Отличная новость!"},
{"category": "politics", "text": "Ужасная ситуация..."},
{"category": "economy", "text": "Нормально"}
]
}
}
class CategorySentimentResponse(BaseModel):
"""Response model for category sentiment analysis."""
category_stats: Dict[str, Dict] = Field(..., description="Statistics per category")
top_positive_categories: List[Dict] = Field(..., description="Top positive categories")
top_negative_categories: List[Dict] = Field(..., description="Top negative categories")
class ThreadAnalysisRequest(BaseModel):
"""Request model for thread analysis."""
data: List[Dict[str, str]] = Field(..., description="List of comments with news_id and text", min_items=1)
class Config:
json_schema_extra = {
"example": {
"data": [
{"news_id": "1", "text": "Отлично!"},
{"news_id": "1", "text": "Ужасно!"},
{"news_id": "2", "text": "Нормально"}
]
}
}
class ThreadAnalysisResponse(BaseModel):
"""Response model for thread analysis."""
thread_stats: List[Dict] = Field(..., description="Thread statistics per news item")
correlation: Dict = Field(..., description="Correlation analysis results")
# API Endpoints
@router.post("/predictive-intervals", response_model=PredictiveIntervalResponse)
async def calculate_predictive_intervals(request: PredictiveIntervalRequest):
"""
Calculate predictive intervals for ranking items by positive sentiment.
Uses Beta distribution to account for uncertainty when sample sizes are small.
Useful for ranking news articles or categories by positive sentiment.
Args:
request: Request with sentiment counts and confidence level
Returns:
Ranked items with predictive intervals
"""
try:
# Convert to list of dicts
data = [
{
"id": item.id,
"positive_count": item.positive_count,
"negative_count": item.negative_count,
"neutral_count": item.neutral_count
}
for item in request.data
]
# Rank by predictive interval
ranked_data = rank_by_predictive_interval(
data,
confidence_level=request.confidence_level
)
# Get top positive and negative
top_positive = get_top_positive_by_interval(
data,
top_k=10,
confidence_level=request.confidence_level
)
top_negative = get_top_negative_by_interval(
data,
top_k=10,
confidence_level=request.confidence_level
)
return PredictiveIntervalResponse(
ranked_data=ranked_data,
top_positive=top_positive,
top_negative=top_negative
)
except Exception as e:
logger.error(f"Error calculating predictive intervals: {e}")
raise HTTPException(
status_code=500,
detail=f"Predictive interval calculation failed: {str(e)}"
)
@router.post("/category-sentiment", response_model=CategorySentimentResponse)
async def analyze_category_sentiment(request: CategorySentimentRequest):
"""
Analyze sentiment distribution across categories.
Calculates sentiment statistics for each category and ranks them
using predictive intervals.
Args:
request: Request with category and text data
Returns:
Category sentiment statistics and rankings
"""
try:
analytics = get_category_analytics()
# Analyze category sentiment
category_stats = analytics.analyze_category_sentiment(
request.data,
category_key="category",
text_key="text"
)
# Get top categories
top_positive = analytics.get_top_positive_categories(
category_stats,
top_k=10
)
top_negative = analytics.get_top_negative_categories(
category_stats,
top_k=10
)
return CategorySentimentResponse(
category_stats=category_stats,
top_positive_categories=top_positive,
top_negative_categories=top_negative
)
except Exception as e:
logger.error(f"Error analyzing category sentiment: {e}")
raise HTTPException(
status_code=500,
detail=f"Category sentiment analysis failed: {str(e)}"
)
@router.post("/thread-analysis", response_model=ThreadAnalysisResponse)
async def analyze_thread_correlation(request: ThreadAnalysisRequest):
"""
Analyze correlation between thread length and sentiment temperature.
Thread length is the number of comments under a news article.
Temperature is the probability that a comment is negative.
Args:
request: Request with news_id and text data
Returns:
Thread statistics and correlation analysis
"""
try:
analyzer = get_thread_analyzer()
# Calculate thread lengths and temperatures
thread_lengths = analyzer.calculate_thread_lengths(
request.data,
news_id_key="news_id"
)
temperatures = analyzer.calculate_temperature(
request.data,
news_id_key="news_id",
text_key="text"
)
# Analyze correlation
correlation_results = analyzer.analyze_correlation(
thread_lengths,
temperatures
)
# Convert numpy types to native Python types for JSON serialization
def convert_to_python(obj):
"""Recursively convert numpy types to Python native types."""
import numpy as np
if isinstance(obj, np.integer):
return int(obj)
elif isinstance(obj, np.floating):
return float(obj)
elif isinstance(obj, np.bool_):
return bool(obj)
elif isinstance(obj, dict):
return {k: convert_to_python(v) for k, v in obj.items()}
elif isinstance(obj, (list, tuple)):
return [convert_to_python(item) for item in obj]
return obj
correlation_results = convert_to_python(correlation_results)
# Create thread statistics
common_ids = set(thread_lengths.keys()) & set(temperatures.keys())
thread_stats = [
{
"news_id": news_id,
"thread_length": int(thread_lengths[news_id]),
"temperature": float(temperatures[news_id])
}
for news_id in common_ids
]
return ThreadAnalysisResponse(
thread_stats=thread_stats,
correlation=correlation_results
)
except Exception as e:
logger.error(f"Error analyzing thread correlation: {e}")
raise HTTPException(
status_code=500,
detail=f"Thread analysis failed: {str(e)}"
)
@router.get("/health")
async def analytics_health():
"""
Health check for analytics service.
Returns:
Status of analytics components
"""
try:
return {
"status": "healthy",
"category_analytics_loaded": category_analytics is not None,
"thread_analyzer_loaded": thread_analyzer is not None
}
except Exception as e:
logger.error(f"Error checking analytics health: {e}")
return {
"status": "unhealthy",
"error": str(e)
}
|