Spaces:
Sleeping
Sleeping
Update api.py
Browse files
api.py
CHANGED
|
@@ -1,280 +1,189 @@
|
|
| 1 |
-
from fastapi import FastAPI, HTTPException
|
| 2 |
-
from fastapi.middleware.cors import CORSMiddleware
|
| 3 |
-
from pydantic import BaseModel
|
| 4 |
-
from typing import
|
| 5 |
-
import pandas as pd
|
| 6 |
-
import
|
| 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 |
-
class
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
class
|
| 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 |
-
connections = []
|
| 190 |
-
for i in range(start_idx, min(end_idx, total_connections)):
|
| 191 |
-
connection_date = datetime.now() - timedelta(days=random.randint(1, 365))
|
| 192 |
-
|
| 193 |
-
connections.append(Connection(
|
| 194 |
-
id=f"conn_{i+1}",
|
| 195 |
-
name=f"User {i+1}",
|
| 196 |
-
avatar=f"https://api.dicebear.com/7.x/avataaars/svg?seed={i+1}",
|
| 197 |
-
relationship="Connected",
|
| 198 |
-
strength=random.randint(20, 100),
|
| 199 |
-
interactions=random.randint(5, 50),
|
| 200 |
-
insights=[f"Insight {j+1}" for j in range(random.randint(1, 3))],
|
| 201 |
-
karma=random.randint(100, 1000),
|
| 202 |
-
connectionDate=connection_date.isoformat()
|
| 203 |
-
))
|
| 204 |
-
|
| 205 |
-
# Apply filtering (basic implementation)
|
| 206 |
-
if filter == "recent":
|
| 207 |
-
recent_date = datetime.now() - timedelta(days=30)
|
| 208 |
-
connections = [c for c in connections if datetime.fromisoformat(c.connectionDate.replace('Z', '+00:00').replace('+00:00', '')) > recent_date]
|
| 209 |
-
elif filter == "active":
|
| 210 |
-
connections = [c for c in connections if c.interactions > 20]
|
| 211 |
-
|
| 212 |
-
return ConnectionsResponse(
|
| 213 |
-
data=connections,
|
| 214 |
-
page=page,
|
| 215 |
-
pageSize=pageSize,
|
| 216 |
-
total=total_connections
|
| 217 |
-
)
|
| 218 |
-
|
| 219 |
-
except Exception as e:
|
| 220 |
-
raise HTTPException(status_code=500, detail={"error": f"Failed to load connections: {str(e)}"})
|
| 221 |
-
|
| 222 |
-
@app.get("/users/{userId}/connections/stats", response_model=ConnectionsStats)
|
| 223 |
-
async def get_connections_stats(userId: str):
|
| 224 |
-
"""
|
| 225 |
-
Get connection statistics for a user
|
| 226 |
-
"""
|
| 227 |
-
|
| 228 |
-
try:
|
| 229 |
-
# Mock stats (replace with your database logic)
|
| 230 |
-
return ConnectionsStats(
|
| 231 |
-
total=150,
|
| 232 |
-
close=25,
|
| 233 |
-
active=80,
|
| 234 |
-
influence=750
|
| 235 |
-
)
|
| 236 |
-
|
| 237 |
-
except Exception as e:
|
| 238 |
-
raise HTTPException(status_code=500, detail={"error": f"Failed to load stats: {str(e)}"})
|
| 239 |
-
|
| 240 |
-
@app.post("/users/{userId}/connections/import", response_model=ImportResponse)
|
| 241 |
-
async def import_connections(
|
| 242 |
-
userId: str,
|
| 243 |
-
connection_csv: UploadFile = File(...),
|
| 244 |
-
connection1_csv: UploadFile = File(None)
|
| 245 |
-
):
|
| 246 |
-
"""
|
| 247 |
-
Import connections from CSV files
|
| 248 |
-
"""
|
| 249 |
-
|
| 250 |
-
try:
|
| 251 |
-
imported_count = 0
|
| 252 |
-
|
| 253 |
-
# Process first CSV file
|
| 254 |
-
if connection_csv:
|
| 255 |
-
content = await connection_csv.read()
|
| 256 |
-
df = pd.read_csv(io.StringIO(content.decode('utf-8')))
|
| 257 |
-
imported_count += len(df)
|
| 258 |
-
|
| 259 |
-
# Process second CSV file if provided
|
| 260 |
-
if connection1_csv:
|
| 261 |
-
content = await connection1_csv.read()
|
| 262 |
-
df = pd.read_csv(io.StringIO(content.decode('utf-8')))
|
| 263 |
-
imported_count += len(df)
|
| 264 |
-
|
| 265 |
-
# Here you would save the connections to your database
|
| 266 |
-
# For now, just return success
|
| 267 |
-
|
| 268 |
-
return ImportResponse(ok=True, imported=imported_count)
|
| 269 |
-
|
| 270 |
-
except Exception as e:
|
| 271 |
-
raise HTTPException(status_code=500, detail={"error": f"Import failed: {str(e)}"})
|
| 272 |
-
|
| 273 |
-
@app.get("/health", response_model=HealthResponse)
|
| 274 |
-
async def health_check():
|
| 275 |
-
"""Health check endpoint"""
|
| 276 |
-
return HealthResponse(status="ok")
|
| 277 |
-
|
| 278 |
-
if __name__ == "__main__":
|
| 279 |
-
import uvicorn
|
| 280 |
uvicorn.run(app, host="0.0.0.0", port=8000)
|
|
|
|
| 1 |
+
from fastapi import FastAPI, HTTPException
|
| 2 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 3 |
+
from pydantic import BaseModel
|
| 4 |
+
from typing import List, Optional
|
| 5 |
+
import pandas as pd
|
| 6 |
+
import re
|
| 7 |
+
import random
|
| 8 |
+
|
| 9 |
+
# Initialize FastAPI app
|
| 10 |
+
app = FastAPI(
|
| 11 |
+
title="Spectrum News Bias Classifier API",
|
| 12 |
+
description="API for classifying political bias in news content",
|
| 13 |
+
version="1.0.0"
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
# Add CORS middleware
|
| 17 |
+
app.add_middleware(
|
| 18 |
+
CORSMiddleware,
|
| 19 |
+
allow_origins=["*"],
|
| 20 |
+
allow_credentials=True,
|
| 21 |
+
allow_methods=["GET", "POST"],
|
| 22 |
+
allow_headers=["Content-Type", "Authorization"],
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
# Load data files
|
| 26 |
+
try:
|
| 27 |
+
allsides_data = pd.read_csv("allsides_data.csv")
|
| 28 |
+
blacklist_data = pd.read_csv("blacklist.csv")
|
| 29 |
+
print("✅ Data files loaded successfully")
|
| 30 |
+
except Exception as e:
|
| 31 |
+
print(f"⚠️ Warning: Could not load data files: {e}")
|
| 32 |
+
allsides_data = None
|
| 33 |
+
blacklist_data = None
|
| 34 |
+
|
| 35 |
+
# Request/Response models
|
| 36 |
+
class PoliticalRequest(BaseModel):
|
| 37 |
+
headline: str
|
| 38 |
+
|
| 39 |
+
class PoliticalResponse(BaseModel):
|
| 40 |
+
political_leaning: str # "left" | "center" | "right"
|
| 41 |
+
confidence: Optional[float] = None
|
| 42 |
+
explanation: Optional[str] = None
|
| 43 |
+
|
| 44 |
+
class BatchPoliticalRequest(BaseModel):
|
| 45 |
+
headlines: List[str]
|
| 46 |
+
|
| 47 |
+
class BatchResult(BaseModel):
|
| 48 |
+
headline: str
|
| 49 |
+
political_leaning: str
|
| 50 |
+
confidence: Optional[float] = None
|
| 51 |
+
|
| 52 |
+
class BatchPoliticalResponse(BaseModel):
|
| 53 |
+
results: List[BatchResult]
|
| 54 |
+
|
| 55 |
+
class HealthResponse(BaseModel):
|
| 56 |
+
status: str
|
| 57 |
+
|
| 58 |
+
# Simple bias classification logic
|
| 59 |
+
def classify_political_bias(headline: str) -> dict:
|
| 60 |
+
"""Simple keyword-based political bias classification"""
|
| 61 |
+
|
| 62 |
+
if not headline or not headline.strip():
|
| 63 |
+
return {
|
| 64 |
+
"political_leaning": "center",
|
| 65 |
+
"confidence": 0.0,
|
| 66 |
+
"explanation": "Empty headline provided"
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
headline_lower = headline.lower()
|
| 70 |
+
|
| 71 |
+
# Define bias keywords
|
| 72 |
+
left_keywords = [
|
| 73 |
+
'progressive', 'liberal', 'democrat', 'biden', 'climate change',
|
| 74 |
+
'social justice', 'inequality', 'diversity', 'healthcare', 'welfare',
|
| 75 |
+
'gun control', 'abortion rights', 'immigration reform', 'minimum wage'
|
| 76 |
+
]
|
| 77 |
+
|
| 78 |
+
right_keywords = [
|
| 79 |
+
'conservative', 'republican', 'trump', 'traditional', 'patriot',
|
| 80 |
+
'free market', 'law and order', 'family values', 'second amendment',
|
| 81 |
+
'border security', 'tax cuts', 'deregulation', 'america first'
|
| 82 |
+
]
|
| 83 |
+
|
| 84 |
+
center_keywords = [
|
| 85 |
+
'bipartisan', 'moderate', 'compromise', 'balanced', 'pragmatic',
|
| 86 |
+
'consensus', 'middle ground', 'nonpartisan', 'centrist'
|
| 87 |
+
]
|
| 88 |
+
|
| 89 |
+
# Count keyword matches
|
| 90 |
+
left_score = sum(1 for keyword in left_keywords if keyword in headline_lower)
|
| 91 |
+
right_score = sum(1 for keyword in right_keywords if keyword in headline_lower)
|
| 92 |
+
center_score = sum(1 for keyword in center_keywords if keyword in headline_lower)
|
| 93 |
+
|
| 94 |
+
# Determine bias based on scores
|
| 95 |
+
max_score = max(left_score, right_score, center_score)
|
| 96 |
+
|
| 97 |
+
if max_score == 0:
|
| 98 |
+
# No keywords found, use simple heuristics
|
| 99 |
+
if any(word in headline_lower for word in ['spending', 'investment', 'program']):
|
| 100 |
+
political_leaning = "left"
|
| 101 |
+
confidence = 0.4
|
| 102 |
+
elif any(word in headline_lower for word in ['cut', 'reduce', 'eliminate']):
|
| 103 |
+
political_leaning = "right"
|
| 104 |
+
confidence = 0.4
|
| 105 |
+
else:
|
| 106 |
+
political_leaning = "center"
|
| 107 |
+
confidence = 0.3
|
| 108 |
+
else:
|
| 109 |
+
if left_score == max_score:
|
| 110 |
+
political_leaning = "left"
|
| 111 |
+
elif right_score == max_score:
|
| 112 |
+
political_leaning = "right"
|
| 113 |
+
else:
|
| 114 |
+
political_leaning = "center"
|
| 115 |
+
|
| 116 |
+
confidence = min(0.9, max_score * 0.2 + 0.5)
|
| 117 |
+
|
| 118 |
+
# Add some randomness to make it more realistic
|
| 119 |
+
confidence += random.uniform(-0.1, 0.1)
|
| 120 |
+
confidence = max(0.1, min(0.95, confidence))
|
| 121 |
+
|
| 122 |
+
return {
|
| 123 |
+
"political_leaning": political_leaning,
|
| 124 |
+
"confidence": round(confidence, 2),
|
| 125 |
+
"explanation": f"Classified as {political_leaning} based on content analysis"
|
| 126 |
+
}
|
| 127 |
+
|
| 128 |
+
# API Endpoints
|
| 129 |
+
@app.post("/predict_political", response_model=PoliticalResponse)
|
| 130 |
+
async def predict_political(request: PoliticalRequest):
|
| 131 |
+
"""Predict political leaning of a news headline"""
|
| 132 |
+
|
| 133 |
+
try:
|
| 134 |
+
result = classify_political_bias(request.headline)
|
| 135 |
+
return PoliticalResponse(**result)
|
| 136 |
+
|
| 137 |
+
except Exception as e:
|
| 138 |
+
raise HTTPException(status_code=500, detail={"error": f"Classification error: {str(e)}"})
|
| 139 |
+
|
| 140 |
+
@app.post("/predict_political/batch", response_model=BatchPoliticalResponse)
|
| 141 |
+
async def predict_political_batch(request: BatchPoliticalRequest):
|
| 142 |
+
"""Predict political leaning for multiple headlines"""
|
| 143 |
+
|
| 144 |
+
if len(request.headlines) > 100:
|
| 145 |
+
raise HTTPException(status_code=400, detail={"error": "Maximum 100 headlines per batch"})
|
| 146 |
+
|
| 147 |
+
results = []
|
| 148 |
+
|
| 149 |
+
for headline in request.headlines:
|
| 150 |
+
try:
|
| 151 |
+
result = classify_political_bias(headline)
|
| 152 |
+
results.append(BatchResult(
|
| 153 |
+
headline=headline,
|
| 154 |
+
political_leaning=result['political_leaning'],
|
| 155 |
+
confidence=result['confidence']
|
| 156 |
+
))
|
| 157 |
+
except Exception:
|
| 158 |
+
# Fallback to center on error
|
| 159 |
+
results.append(BatchResult(
|
| 160 |
+
headline=headline,
|
| 161 |
+
political_leaning="center",
|
| 162 |
+
confidence=0.0
|
| 163 |
+
))
|
| 164 |
+
|
| 165 |
+
return BatchPoliticalResponse(results=results)
|
| 166 |
+
|
| 167 |
+
@app.get("/health", response_model=HealthResponse)
|
| 168 |
+
async def health_check():
|
| 169 |
+
"""Health check endpoint"""
|
| 170 |
+
return HealthResponse(status="ok")
|
| 171 |
+
|
| 172 |
+
@app.get("/")
|
| 173 |
+
async def root():
|
| 174 |
+
"""Root endpoint with API information"""
|
| 175 |
+
return {
|
| 176 |
+
"message": "Spectrum News Bias Classifier API",
|
| 177 |
+
"version": "1.0.0",
|
| 178 |
+
"endpoints": {
|
| 179 |
+
"POST /predict_political": "Classify single headline",
|
| 180 |
+
"POST /predict_political/batch": "Classify multiple headlines",
|
| 181 |
+
"GET /health": "Health check",
|
| 182 |
+
"GET /docs": "API documentation"
|
| 183 |
+
},
|
| 184 |
+
"status": "running"
|
| 185 |
+
}
|
| 186 |
+
|
| 187 |
+
if __name__ == "__main__":
|
| 188 |
+
import uvicorn
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 189 |
uvicorn.run(app, host="0.0.0.0", port=8000)
|