Spaces:
Sleeping
Sleeping
Download api.py from UserArkham/spectrum-api-simple: direct link, hf CLI and curl.
- Browser
- Download file 6.19 kB
-
https://huggingface.co/spaces/UserArkham/spectrum-api-simple/resolve/main/api.py
- Command line
-
hf download hf://spaces/UserArkham/spectrum-api-simple/api.py
-
curl -L -o api.py https://huggingface.co/spaces/UserArkham/spectrum-api-simple/resolve/main/api.py
6.19 kB
| 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 | |
| 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)}"}) | |
| 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) | |
| async def health_check(): | |
| """Health check endpoint""" | |
| return HealthResponse(status="ok") | |
| 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) |