Update inference.py
Browse files- inference.py +39 -38
inference.py
CHANGED
|
@@ -1,38 +1,39 @@
|
|
| 1 |
-
import joblib
|
| 2 |
-
from sklearn.feature_extraction.text import TfidfVectorizer
|
| 3 |
-
from sklearn.linear_model import LogisticRegression
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
vectorizer = joblib.load('vectorizer.joblib')
|
| 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 |
-
|
|
|
|
|
|
| 1 |
+
import joblib
|
| 2 |
+
from sklearn.feature_extraction.text import TfidfVectorizer
|
| 3 |
+
from sklearn.linear_model import LogisticRegression
|
| 4 |
+
|
| 5 |
+
class Handler:
|
| 6 |
+
def __init__(self, model_dir):
|
| 7 |
+
self.vectorizer = joblib.load(f'{model_dir}/vectorizer.joblib')
|
| 8 |
+
self.model = joblib.load(f'{model_dir}/logistic_classifier.joblib')
|
| 9 |
+
|
| 10 |
+
# Function to predict rating for a new review
|
| 11 |
+
def predict_rating(review):
|
| 12 |
+
review_tfidf = vectorizer.transform([review])
|
| 13 |
+
predicted_rating = logistic_classifier.predict(review_tfidf)[0]
|
| 14 |
+
return predicted_rating
|
| 15 |
+
|
| 16 |
+
# Function to map numerical rating to description
|
| 17 |
+
def map_rating_to_description(rating):
|
| 18 |
+
if rating == 1:
|
| 19 |
+
return "Poor"
|
| 20 |
+
elif rating == 2:
|
| 21 |
+
return "Unsatisfactory"
|
| 22 |
+
elif rating == 3:
|
| 23 |
+
return "Average"
|
| 24 |
+
elif rating == 4:
|
| 25 |
+
return "Satisfactory"
|
| 26 |
+
elif rating == 5:
|
| 27 |
+
return "Outstanding"
|
| 28 |
+
else:
|
| 29 |
+
return "Invalid rating"
|
| 30 |
+
|
| 31 |
+
# Define the inference function
|
| 32 |
+
def inference(request):
|
| 33 |
+
review = request.get("review", "")
|
| 34 |
+
predicted_rating = predict_rating(review)
|
| 35 |
+
predicted_description = map_rating_to_description(predicted_rating)
|
| 36 |
+
return {
|
| 37 |
+
"predicted_rating": int(predicted_rating),
|
| 38 |
+
"predicted_description": predicted_description
|
| 39 |
+
}
|