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"}'