nicolasV441's picture
Update app.py
4887448 verified
from fastapi import FastAPI, HTTPException, Query
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
import pandas as pd
import json
from typing import Dict, Any
import dill as pickle
import sys
from Stopwords import filter_review
app = FastAPI()
#Allow CORS for communication with Angular frontend
app.add_middleware(
CORSMiddleware,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Load the model and the vectorizer
try:
with open('./model_1_en.pkl', 'rb') as fin:
model_loaded = pickle.load(fin)
except FileNotFoundError:
print("Error: 'model_1_en.pkl' not found.")
try:
with open('./vectorizer.pkl', 'rb') as fin:
vectorizer = pickle.load(fin)
except FileNotFoundError:
print("Error: 'vectorizer.pkl' not found.")
class Review(BaseModel):
review: str
# Helper function to filter and predict review
def get_prediction(text):
processed_text = filter_review(text)
vectorized_text = vectorizer.transform([processed_text])
prediction = model_loaded.predict(vectorized_text)[0]
return int(prediction) # Convert to int for JSON serialization
# Endpoint to add a new review
@app.post("/review/predict", response_model=Dict[str, Any])
def add_review(review: Review):
try:
# Get the prediction for the new review
prediction = get_prediction(review.review)
if (prediction):
predict = "Positivo"
else:
predict = "Negativo"
return {"status": "success", "review": review, "prediction": predict}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))