| from flask import Flask, request, jsonify |
| from transformers import pipeline |
| import torch |
|
|
| app = Flask(__name__) |
|
|
| |
| |
| MODEL_PATH = "./sentiment_analyzer_pro" |
|
|
| |
| |
| print("Loading DistilBERT 3-class model...") |
| try: |
| classifier = pipeline( |
| "sentiment-analysis", |
| model=MODEL_PATH, |
| tokenizer=MODEL_PATH, |
| device=-1 |
| ) |
| print("Model loaded successfully!") |
| except Exception as e: |
| print(f"Error loading model: {e}") |
|
|
| |
| @app.route('/predict', methods=['POST']) |
| def predict_endpoint(): |
| """ |
| Receives JSON input: {"text": "Your review here"} |
| Returns JSON: {"sentiment": "Label", "score": 0.99, "confidence_flag": "High/Low"} |
| """ |
| data = request.get_json() |
| |
| |
| if not data or 'text' not in data: |
| return jsonify({'error': 'No text provided'}), 400 |
| |
| sentence = data['text'] |
| |
| |
| |
| result = classifier(sentence)[0] |
| |
| label = result['label'] |
| score = result['score'] |
| |
| |
| |
| |
| |
| if score < 0.70: |
| final_sentiment = "Neutral / Mixed" |
| confidence_flag = "Low" |
| else: |
| |
| final_sentiment = label.capitalize() |
| confidence_flag = "High" |
| |
| return jsonify({ |
| 'sentiment': final_sentiment, |
| 'score': round(score, 4), |
| 'confidence_flag': confidence_flag |
| }) |
|
|
| |
| @app.route('/', methods=['GET']) |
| def health_check(): |
| return "Sentiment Analyzer Pro API is online." |
|
|
| if __name__ == '__main__': |
| |
| |
| app.run(host='0.0.0.0', port=7860) |