| from fastapi import FastAPI |
| from pydantic import BaseModel |
| import joblib |
| import pandas as pd |
| import re |
| from collections import Counter |
| from fastapi.middleware.cors import CORSMiddleware |
|
|
| |
| app = FastAPI(title="Enterprise Spam Classifier API") |
|
|
| |
| app.add_middleware( |
| CORSMiddleware, |
| allow_origins=["*"], |
| allow_methods=["*"], |
| allow_headers=["*"], |
| ) |
|
|
| |
| model = joblib.load('spam_model.pkl') |
| features = joblib.load('feature_names.pkl') |
|
|
| |
| class EmailPayload(BaseModel): |
| content: str |
|
|
| @app.post("/predict") |
| def predict_spam(payload: EmailPayload): |
| |
| text = payload.content.lower() |
| words = re.findall(r'\b\w+\b', text) |
| word_counts = Counter(words) |
| |
| |
| input_data = {feature: [word_counts.get(feature, 0)] for feature in features} |
| df_input = pd.DataFrame(input_data) |
| |
| |
| prediction = model.predict(df_input)[0] |
| probabilities = model.predict_proba(df_input)[0] |
| confidence = probabilities.max() |
| |
| return { |
| "prediction": "Spam" if prediction == 1 else "Not Spam", |
| "confidence": float(confidence), |
| "status": 200 |
| } |