File size: 3,463 Bytes
8ad9255
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e06c835
8ad9255
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from fastapi import FastAPI, HTTPException, UploadFile, File
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel, HttpUrl
from typing import Optional
import uvicorn

from services.analyzer import analyze_content
from services.text_extractor import extract_from_url, extract_from_document

app = FastAPI(
    title="HateShield-BN API",
    description="Bilingual Hate Speech Detection System",
    version="1.0.0"
)

# CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["http://localhost:5173", "http://localhost:3000","https://hate-shield-bn-frontend.vercel.app"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Request models
class TextRequest(BaseModel):
    text: str

class URLRequest(BaseModel):
    url: HttpUrl

# Routes
@app.get("/")
async def root():
    return {
        "message": "HateShield-BN API is running!",
        "version": "1.0.0",
        "endpoints": {
            "text": "/api/analyze/text",
            "url": "/api/analyze/url",
            "document": "/api/analyze/document"
        }
    }

@app.post("/api/analyze/text")
async def analyze_text(request: TextRequest):
    """Analyze text for hate speech"""
    try:
        if not request.text or len(request.text.strip()) == 0:
            raise HTTPException(status_code=400, detail="Text cannot be empty")
        
        result = await analyze_content(request.text)
        return result
    except Exception as e:
        print(f"Error analyzing text: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@app.post("/api/analyze/url")
async def analyze_url(request: URLRequest):
    """Analyze content from URL"""
    try:
        # Note: extract_from_url is now synchronous
        text = extract_from_url(str(request.url))
        
        if not text:
            raise HTTPException(status_code=400, detail="Could not extract text from URL")
        
        result = await analyze_content(text)
        return result
    except HTTPException:
        raise
    except Exception as e:
        print(f"Error analyzing URL: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@app.post("/api/analyze/document")
async def analyze_document(file: UploadFile = File(...)):
    """Analyze uploaded document"""
    try:
        # Check file type
        allowed_types = [".pdf", ".docx", ".txt"]
        file_ext = f".{file.filename.split('.')[-1].lower()}"
        
        if file_ext not in allowed_types:
            raise HTTPException(
                status_code=400, 
                detail=f"File type {file_ext} not supported. Allowed: {', '.join(allowed_types)}"
            )
        
        # Read file content
        content = await file.read()
        
        # Note: extract_from_document is now synchronous
        text = extract_from_document(content, file_ext)
        
        if not text:
            raise HTTPException(status_code=400, detail="Could not extract text from document")
        
        result = await analyze_content(text)
        return result
    except HTTPException:
        raise
    except Exception as e:
        print(f"Error analyzing document: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@app.get("/health")
async def health_check():
    return {"status": "healthy"}

if __name__ == "__main__":
    uvicorn.run(
        "main:app",
        host="0.0.0.0",
        port=8000,
        reload=True
    )