from flask import Flask, request, jsonify from transformers import BertTokenizer, BertForSequenceClassification, pipeline # Initialize Flask app app = Flask(__name__) # Load pre-trained model and tokenizer model_name = "bert-base-uncased" tokenizer = BertTokenizer.from_pretrained(model_name) model = BertForSequenceClassification.from_pretrained(model_name) # Set up a pipeline nlp_pipeline = pipeline("sentiment-analysis", model=model, tokenizer=tokenizer) def analyze_sentiment(text): """ Analyze the sentiment of the input text using the NLP pipeline. Returns a tuple of sentiment label and confidence score. """ result = nlp_pipeline(text) sentiment = result[0]['label'] confidence = result[0]['score'] return sentiment, confidence @app.route('/analyze', methods=['POST']) def analyze(): """ API endpoint to analyze sentiment. Expects a JSON payload with 'text'. """ if request.is_json: data = request.json text = data.get('text', '') if text: sentiment, confidence = analyze_sentiment(text) response = { "sentiment": sentiment, "confidence": confidence } return jsonify(response), 200 else: return jsonify({"error": "No text provided"}), 400 return jsonify({"error": "Invalid request format, JSON expected"}), 400 if __name__ == '__main__': app.run(debug=True)