Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from fastapi import FastAPI
|
2 |
+
from pydantic import BaseModel
|
3 |
+
import joblib
|
4 |
+
import nltk
|
5 |
+
from nltk.corpus import stopwords
|
6 |
+
from nltk.stem import PorterStemmer
|
7 |
+
import re
|
8 |
+
|
9 |
+
nltk.download('stopwords')
|
10 |
+
|
11 |
+
app = FastAPI()
|
12 |
+
|
13 |
+
# Load the model pipeline
|
14 |
+
pipeline = joblib.load('spam_classifier_pipeline.joblib')
|
15 |
+
|
16 |
+
class EmailRequest(BaseModel):
|
17 |
+
subject: str
|
18 |
+
body: str
|
19 |
+
|
20 |
+
def preprocess_text(text):
|
21 |
+
text = text.lower()
|
22 |
+
text = re.sub(r'[^a-zA-Z\s]', '', text)
|
23 |
+
words = text.split()
|
24 |
+
stop_words = set(stopwords.words('english'))
|
25 |
+
words = [word for word in words if word not in stop_words]
|
26 |
+
stemmer = PorterStemmer()
|
27 |
+
words = [stemmer.stem(word) for word in words]
|
28 |
+
return ' '.join(words)
|
29 |
+
|
30 |
+
@app.post("/predict")
|
31 |
+
async def predict(email: EmailRequest):
|
32 |
+
processed_text = preprocess_text(email.subject + ' ' + email.body)
|
33 |
+
prediction = pipeline.predict([processed_text])[0]
|
34 |
+
return {'prediction': ['ham', 'not_spam', 'spam'][prediction]}
|
35 |
+
|
36 |
+
@app.get("/")
|
37 |
+
async def root():
|
38 |
+
return {"message": "Spam Classification API"}
|