gmail-spam-api / app.py
Aitouaouch's picture
Update app.py
7225f17 verified
Raw History Blame Contribute Delete
2.62 kB
from fastapi import FastAPI, HTTPException, Security
from fastapi.security import APIKeyHeader
from pydantic import BaseModel
from transformers import BertTokenizerFast, BertForSequenceClassification
import torch
import torch.nn.functional as F
import re
import os
from collections import Counter
app = FastAPI()
from fastapi.middleware.cors import CORSMiddleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
API_KEY_NAME = "X-API-Key"
api_key_header = APIKeyHeader(name=API_KEY_NAME, auto_error=False)
async def verify_api_key(api_key: str = Security(api_key_header)):
expected = os.environ.get("API_SECRET_KEY")
if not api_key or api_key != expected:
raise HTTPException(status_code=403, detail="Forbidden")
return api_key
MODEL_NAME = "Aitouaouch/bert_model_for_spam_detection"
tokenizer = BertTokenizerFast.from_pretrained(MODEL_NAME, token=os.environ.get("HF_TOKEN"))
model = BertForSequenceClassification.from_pretrained(MODEL_NAME, token=os.environ.get("HF_TOKEN"))
model.eval()
STOPWORDS = {
"the","a","an","is","it","in","on","at","to","for","of","and","or",
"but","be","are","was","were","this","that","with","from","have","has",
"you","your","we","our","i","my","he","she","they","their","its","will",
"can","not","no","so","do","if","as","by","up","all","more","about","just"
}
class EmailRequest(BaseModel):
subject: str
body: str
domain: str
@app.get("/")
def health():
return {"status": "BERT Spam Detection Running ✅"}
def extract_keywords(text: str, top_n: int = 8) -> list[str]:
words = re.findall(r'\b[a-zA-Z]{4,}\b', text.lower())
filtered = [w for w in words if w not in STOPWORDS]
freq = Counter(filtered)
return [word for word, _ in freq.most_common(top_n)]
@app.post("/predict")
async def predict(request: EmailRequest, api_key: str = Security(verify_api_key)):
text = f"[DOMAIN] {request.domain} [BODY] {request.subject} {request.body}"
inputs = tokenizer(text, return_tensors="pt", truncation=True, padding=True, max_length=256)
with torch.no_grad():
outputs = model(**inputs)
probs = F.softmax(outputs.logits, dim=1)
prediction_idx = torch.argmax(probs, dim=1).item()
confidence = probs[0][prediction_idx].item() * 100
prediction = "spam" if prediction_idx == 1 else "safe"
keywords = extract_keywords(f"{request.subject} {request.body}")
return {
"prediction": prediction,
"confidence": round(confidence, 2),
"keywords": keywords
}