| | from flask import Flask, request, jsonify |
| | from transformers import pipeline |
| | import logging |
| |
|
| | |
| | logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') |
| |
|
| | app = Flask(__name__) |
| |
|
| | |
| | |
| | logging.info("Loading sentiment analysis pipeline...") |
| | |
| | |
| | |
| | |
| | |
| | classifier = pipeline("sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english") |
| | logging.info("Sentiment analysis pipeline loaded.") |
| |
|
| | |
| | |
| | |
| | |
| | |
| | label_mapping = { |
| | 'LABEL_0': 'Sad', |
| | 'LABEL_1': 'Happy', |
| | 'LABEL_2': 'Neutral' |
| | } |
| |
|
| | @app.route('/') |
| | def home(): |
| | return "Welcome to the Emotion Prediction API! Use the /predict endpoint." |
| |
|
| | @app.route('/predict', methods=['POST']) |
| | def predict(): |
| | data = request.get_json(force=True) |
| | text = data.get('text', '') |
| |
|
| | if not text: |
| | logging.warning("Received empty text for prediction.") |
| | return jsonify({'error': 'No text provided for prediction'}), 400 |
| |
|
| | try: |
| | |
| | prediction_result = classifier(text)[0] |
| | predicted_label_code = prediction_result['label'] |
| | score = prediction_result['score'] |
| |
|
| | |
| | emotion = label_mapping.get(predicted_label_code, 'Unknown') |
| |
|
| | response = { |
| | 'text': text, |
| | 'predicted_emotion': emotion, |
| | 'confidence': score |
| | } |
| | logging.info(f"Prediction made for text: '{text[:50]}' - Emotion: {emotion}, Confidence: {score:.4f}") |
| | return jsonify(response) |
| |
|
| | except Exception as e: |
| | logging.error(f"Error during prediction for text: '{text[:50]}' - Error: {e}", exc_info=True) |
| | return jsonify({'error': str(e)}), 500 |
| |
|
| | if __name__ == '__main__': |
| | |
| | port = 5000 |
| | logging.info(f"Starting Flask app on port {port}") |
| | app.run(host='0.0.0.0', port=port) |
| |
|