import os import torch import torch.nn.functional as F import re from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from pydantic import BaseModel from transformers import BertTokenizerFast, BertForSequenceClassification from collections import Counter app = FastAPI() # Autorise tout le monde (CORS) app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"], ) # Chargement du modèle (Public) MODEL_NAME = "Aitouaouch/bert_model_for_spam_detection" print("Chargement du modèle BERT...") tokenizer = BertTokenizerFast.from_pretrained(MODEL_NAME) model = BertForSequenceClassification.from_pretrained(MODEL_NAME) model.eval() print("Modèle prêt !") 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 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.get("/") def health(): return {"message": "Serveur de détection de Spam actif"} @app.post("/predict") async def predict(request: EmailRequest): try: # Préparation du texte 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 } except Exception as e: return {"error": str(e)} if __name__ == "__main__": import uvicorn uvicorn.run(app, host="0.0.0.0", port=7860)