File size: 1,874 Bytes
a90e008
 
 
dfe7476
a90e008
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dfe7476
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a90e008
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from preditormodels import PhishingPredictor
import re
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel, field_validator
from config import XGB_MODEL_PATH, BERT_MODEL_PATH
class EmailRequest(BaseModel):
    subject: str
    body: str

    @field_validator("subject", "body", mode="before")
    @classmethod
    def clean_text(cls, v):
        if isinstance(v, str):
            # Remove illegal ASCII control characters
            v = re.sub(r"[\x00-\x08\x0B\x0C\x0E-\x1F]", "", v)
        return v


# FastAPI App


app = FastAPI(title="Phishing Detection API")

# Define the specific origins that are allowed to call this API
origins = [
    "http://localhost:3000",      # React/Frontend local development
    "http://127.0.0.1:5500",      # VS Code Live Server default
    "http://127.0.0.1:8500",      # Your FastAPI local address
    "http://localhost:5500",      # Alternative Live Server address
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,        # Only allow the domains in the list above
    allow_credentials=True,
    allow_methods=["*"],          # Allows all HTTP methods (POST, GET, etc.)
    allow_headers=["*"],          # Allows all headers (Content-Type, etc.)
)


# Load models once
predictor = PhishingPredictor(BERT_MODEL_PATH, XGB_MODEL_PATH)


@app.get("/")
def read_root():
    return {"message": "Phishing Detection API is running."}


@app.post("/predict")
async def get_prediction(email: EmailRequest):
    """
    Predict whether an email is phishing or legitimate.
    """
    try:
        return predictor.predict(email.subject, email.body)
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))



# Run Server

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="127.0.0.1", port=8500)