| from flask import Flask, request, jsonify
|
| from transformers import AutoTokenizer, AutoModelForSequenceClassification
|
| import torch
|
| import os
|
|
|
|
|
|
|
| app = Flask(__name__)
|
|
|
|
|
| tokenizer = AutoTokenizer.from_pretrained("finiteautomata/bertweet-base-sentiment-analysis")
|
| model = AutoModelForSequenceClassification.from_pretrained("finiteautomata/bertweet-base-sentiment-analysis")
|
|
|
| LABELS = ['Negative', 'Neutral', 'Positive']
|
|
|
| def analyze_sentiment(text):
|
|
|
|
|
|
|
|
|
| inputs = tokenizer(text, return_tensors="pt", truncation=True, padding=True)
|
|
|
|
|
|
|
|
|
| outputs = model(**inputs)
|
| logits = outputs.logits
|
|
|
|
|
|
|
|
|
|
|
| predicted_class = torch.argmax(logits, dim=1).item()
|
| sentiment = LABELS[predicted_class]
|
|
|
| return sentiment
|
|
|
|
|
| @app.route('/analyze', methods=['POST'])
|
| def analyze():
|
| data = request.get_json()
|
|
|
| if 'text' not in data:
|
| return jsonify({'error': 'No text provided'}), 400
|
|
|
|
|
| text = data['text']
|
| sentiment = analyze_sentiment(text)
|
|
|
| return jsonify({'text': text, 'sentiment': sentiment})
|
|
|
|
|
| @app.route('/analyze_texts', methods=['POST'])
|
| def analyze_texts():
|
| data = request.get_json()
|
|
|
| if 'texts' not in data:
|
| return jsonify({'error': 'No texts provided'}), 400
|
|
|
|
|
| texts = data['texts']
|
| results = [{'text': text, 'sentiment': analyze_sentiment(text)} for text in texts]
|
|
|
|
|
| negative_count = sum(1 for result in results if result['sentiment'] == 'Negative')
|
|
|
|
|
| risk = negative_count > (len(texts) / 2)
|
|
|
|
|
|
|
|
|
| return jsonify({
|
| 'results': results,
|
| 'Negative Sentiment?': risk
|
| })
|
|
|
|
|
|
|
| if __name__ == '__main__':
|
|
|
|
|
| app.run(host='0.0.0.0', port=7860)
|
|
|