Spaces:
Sleeping
Sleeping
File size: 6,193 Bytes
b059916 6665a4d | 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 | from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from typing import List, Optional
import pandas as pd
import re
import random
# Initialize FastAPI app
app = FastAPI(
title="Spectrum News Bias Classifier API",
description="API for classifying political bias in news content",
version="1.0.0"
)
# Add CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["GET", "POST"],
allow_headers=["Content-Type", "Authorization"],
)
# Load data files
try:
allsides_data = pd.read_csv("allsides_data.csv")
blacklist_data = pd.read_csv("blacklist.csv")
print("✅ Data files loaded successfully")
except Exception as e:
print(f"⚠️ Warning: Could not load data files: {e}")
allsides_data = None
blacklist_data = None
# Request/Response models
class PoliticalRequest(BaseModel):
headline: str
class PoliticalResponse(BaseModel):
political_leaning: str # "left" | "center" | "right"
confidence: Optional[float] = None
explanation: Optional[str] = None
class BatchPoliticalRequest(BaseModel):
headlines: List[str]
class BatchResult(BaseModel):
headline: str
political_leaning: str
confidence: Optional[float] = None
class BatchPoliticalResponse(BaseModel):
results: List[BatchResult]
class HealthResponse(BaseModel):
status: str
# Simple bias classification logic
def classify_political_bias(headline: str) -> dict:
"""Simple keyword-based political bias classification"""
if not headline or not headline.strip():
return {
"political_leaning": "center",
"confidence": 0.0,
"explanation": "Empty headline provided"
}
headline_lower = headline.lower()
# Define bias keywords
left_keywords = [
'progressive', 'liberal', 'democrat', 'biden', 'climate change',
'social justice', 'inequality', 'diversity', 'healthcare', 'welfare',
'gun control', 'abortion rights', 'immigration reform', 'minimum wage'
]
right_keywords = [
'conservative', 'republican', 'trump', 'traditional', 'patriot',
'free market', 'law and order', 'family values', 'second amendment',
'border security', 'tax cuts', 'deregulation', 'america first'
]
center_keywords = [
'bipartisan', 'moderate', 'compromise', 'balanced', 'pragmatic',
'consensus', 'middle ground', 'nonpartisan', 'centrist'
]
# Count keyword matches
left_score = sum(1 for keyword in left_keywords if keyword in headline_lower)
right_score = sum(1 for keyword in right_keywords if keyword in headline_lower)
center_score = sum(1 for keyword in center_keywords if keyword in headline_lower)
# Determine bias based on scores
max_score = max(left_score, right_score, center_score)
if max_score == 0:
# No keywords found, use simple heuristics
if any(word in headline_lower for word in ['spending', 'investment', 'program']):
political_leaning = "left"
confidence = 0.4
elif any(word in headline_lower for word in ['cut', 'reduce', 'eliminate']):
political_leaning = "right"
confidence = 0.4
else:
political_leaning = "center"
confidence = 0.3
else:
if left_score == max_score:
political_leaning = "left"
elif right_score == max_score:
political_leaning = "right"
else:
political_leaning = "center"
confidence = min(0.9, max_score * 0.2 + 0.5)
# Add some randomness to make it more realistic
confidence += random.uniform(-0.1, 0.1)
confidence = max(0.1, min(0.95, confidence))
return {
"political_leaning": political_leaning,
"confidence": round(confidence, 2),
"explanation": f"Classified as {political_leaning} based on content analysis"
}
# API Endpoints
@app.post("/predict_political", response_model=PoliticalResponse)
async def predict_political(request: PoliticalRequest):
"""Predict political leaning of a news headline"""
try:
result = classify_political_bias(request.headline)
return PoliticalResponse(**result)
except Exception as e:
raise HTTPException(status_code=500, detail={"error": f"Classification error: {str(e)}"})
@app.post("/predict_political/batch", response_model=BatchPoliticalResponse)
async def predict_political_batch(request: BatchPoliticalRequest):
"""Predict political leaning for multiple headlines"""
if len(request.headlines) > 100:
raise HTTPException(status_code=400, detail={"error": "Maximum 100 headlines per batch"})
results = []
for headline in request.headlines:
try:
result = classify_political_bias(headline)
results.append(BatchResult(
headline=headline,
political_leaning=result['political_leaning'],
confidence=result['confidence']
))
except Exception:
# Fallback to center on error
results.append(BatchResult(
headline=headline,
political_leaning="center",
confidence=0.0
))
return BatchPoliticalResponse(results=results)
@app.get("/health", response_model=HealthResponse)
async def health_check():
"""Health check endpoint"""
return HealthResponse(status="ok")
@app.get("/")
async def root():
"""Root endpoint with API information"""
return {
"message": "Spectrum News Bias Classifier API",
"version": "1.0.0",
"endpoints": {
"POST /predict_political": "Classify single headline",
"POST /predict_political/batch": "Classify multiple headlines",
"GET /health": "Health check",
"GET /docs": "API documentation"
},
"status": "running"
}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000) |