File size: 1,364 Bytes
fbb4f7a | 1 2 3 4 5 6 7 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 39 40 41 42 43 44 45 46 | from flask import Flask, request, jsonify
import torch
from transformers import BertTokenizer
from transformers import BertForSequenceClassification
import numpy as np
import json
app = Flask(__name__)
# Load model and tokenizer
with open('dict.json', 'r') as json_file:
target_word_index = json.load(json_file)
model = BertForSequenceClassification.from_pretrained('saved_bert_model')
tokenizer = BertTokenizer.from_pretrained('saved_bert_model')
model.eval()
def predict_category(text):
inputs = tokenizer(text, return_tensors="pt", padding=True, truncation=True, max_length=128).to('cpu')
with torch.no_grad():
outputs = model(**inputs).logits
preds = (outputs.cpu().numpy() > 0.5).astype(int)
return preds
@app.route('/predict', methods=['POST'])
def predict():
data = request.get_json()
text = data.get('text')
predicted_category = predict_category(text)
indices_of_ones = np.where(predicted_category[0] == 1)[0]
target_dic = {v:k for k, v in target_word_index.items()}
categories = [target_dic[v] for v in indices_of_ones]
return jsonify({'predicted_categories': categories})
if __name__ == '__main__':
app.run(debug=True, host="0.0.0.0", port=7860)
# curl -X POST http://localhost:8001/predict -H "Content-Type: application/json" -d '{"text" : "iphone"}'
|