File size: 1,674 Bytes
135aa7a
 
 
 
297336b
135aa7a
 
 
 
 
 
 
 
 
 
 
105b4a8
135aa7a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
297336b
 
 
 
 
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
from fastapi import FastAPI
from pydantic import BaseModel
import pickle
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse

# Load the pre-trained model and vectorizer
with open("spam_classifier_model.pkl", "rb") as model_file:
    model = pickle.load(model_file)

with open("tfidf_vectorizer.pkl", "rb") as vectorizer_file:
    vectorizer = pickle.load(vectorizer_file)

# FastAPI app instance
app = FastAPI()

# Allow all origins to make requests (for development p/#urposes)
origins = [
    "*",  # Allows all origins, can be restricted to specific domains in production
]

# Add CORS middleware to the FastAPI app
app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,  # Allow all origins
    allow_credentials=True,
    allow_methods=["*"],  # Allow all methods (GET, POST, etc.)
    allow_headers=["*"],  # Allow all headers
)

# Request body model for email input
class Email(BaseModel):
    text: str

# Prediction endpoint
@app.post("/predict/")
def predict_spam_or_ham(email: Email):
    # Transform the text using the loaded vectorizer
    text_tfidf = vectorizer.transform([email.text])
    
    # Make a prediction using the model
    prediction = model.predict(text_tfidf)
    
    # Return the result as a dictionary
    result = "spam" if prediction == 1 else "ham"
    return {"prediction": result}

# Root endpoint
@app.get("/")
def get_info():
    info = "Welcome to Dang Minh EMail Spam Classifier Model, this is a personal project to practice my knowledge in NLP and MLops"
    return { 
        "info": info
    }

@app.get("/app")
def serve_frontend():
    return FileResponse("web/index.html")