GabrielVillareral commited on
Commit
4b90381
·
verified ·
1 Parent(s): 696a732

Addition of the api

Browse files
Files changed (1) hide show
  1. api.py +55 -0
api.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, HTTPException, Query
2
+ from fastapi.middleware.cors import CORSMiddleware
3
+ from pydantic import BaseModel
4
+ import pandas as pd
5
+ import json
6
+ from typing import Dict, Any
7
+ import dill as pickle
8
+ import sys
9
+
10
+ from Stopwords import filter_review
11
+
12
+ app = FastAPI()
13
+
14
+ #Allow CORS for communication with Angular frontend
15
+ app.add_middleware(
16
+ CORSMiddleware,
17
+ allow_credentials=True,
18
+ allow_methods=["*"],
19
+ allow_headers=["*"],
20
+ )
21
+
22
+ # Load the model and the vectorizer
23
+ try:
24
+ with open('./model_1_en.pkl', 'rb') as fin:
25
+ model_loaded = pickle.load(fin)
26
+ except FileNotFoundError:
27
+ print("Error: 'model_1_en.pkl' not found.")
28
+
29
+ try:
30
+ with open('./vectorizer.pkl', 'rb') as fin:
31
+ vectorizer = pickle.load(fin)
32
+ except FileNotFoundError:
33
+ print("Error: 'vectorizer.pkl' not found.")
34
+
35
+ class Review(BaseModel):
36
+ review: str
37
+
38
+ # Helper function to filter and predict review
39
+ def get_prediction(text):
40
+ processed_text = filter_review(text)
41
+ vectorized_text = vectorizer.transform([processed_text])
42
+ prediction = model_loaded.predict(vectorized_text)[0]
43
+ return int(prediction) # Convert to int for JSON serialization
44
+
45
+ # Endpoint to add a new review
46
+
47
+ @app.post("/review/predict", response_model=Dict[str, Any])
48
+ def add_review(review: Review):
49
+ try:
50
+ # Get the prediction for the new review
51
+ prediction = get_prediction(review.review)
52
+
53
+ return {"status": "success", "review": review, "prediction": prediction}
54
+ except Exception as e:
55
+ raise HTTPException(status_code=500, detail=str(e))