Upload app.py
Browse files
app.py
ADDED
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from flask import Flask, request, jsonify, render_template
|
2 |
+
from transformers import BertTokenizer, BertForSequenceClassification
|
3 |
+
import torch
|
4 |
+
|
5 |
+
app = Flask(__name__)
|
6 |
+
|
7 |
+
# Load the model and tokenizer
|
8 |
+
model = BertForSequenceClassification.from_pretrained('./model1')
|
9 |
+
tokenizer = BertTokenizer.from_pretrained('./model1')
|
10 |
+
|
11 |
+
def predict_sentiment(text):
|
12 |
+
inputs = tokenizer(text, return_tensors="pt", padding=True, truncation=True)
|
13 |
+
outputs = model(**inputs)
|
14 |
+
probs = torch.nn.functional.softmax(outputs.logits, dim=1)
|
15 |
+
pred = torch.argmax(probs).item()
|
16 |
+
|
17 |
+
if pred == 0:
|
18 |
+
sentiment = "negative"
|
19 |
+
elif pred == 1:
|
20 |
+
sentiment = "neutral"
|
21 |
+
else:
|
22 |
+
sentiment = "positive"
|
23 |
+
|
24 |
+
return sentiment
|
25 |
+
return sentiment
|
26 |
+
|
27 |
+
@app.route('/')
|
28 |
+
def home():
|
29 |
+
return render_template('index.html')
|
30 |
+
|
31 |
+
@app.route('/predict', methods=['POST'])
|
32 |
+
def predict():
|
33 |
+
data = request.json
|
34 |
+
review = data['review']
|
35 |
+
sentiment = predict_sentiment(review)
|
36 |
+
return jsonify({'sentiment': sentiment})
|
37 |
+
|
38 |
+
if __name__ == '__main__':
|
39 |
+
app.run(debug=True)
|