File size: 2,484 Bytes
9f58cb7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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)