sentiment / app.py
ruthpark00's picture
Add application file
136a2c7
Raw
History Blame Contribute Delete
3 kB
from flask import Flask, request, jsonify
from transformers import AutoTokenizer, AutoModelForSequenceClassification
import torch
import os
# Flask ์•ฑ ์ดˆ๊ธฐํ™”
app = Flask(__name__)
# Load the BERTweet model and tokenizer
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):
# Converts text into tokens that the model can process
# return_tensors="pt": Returns PyTorch tensors
# truncation=True: Cuts text if it's too long
# padding=True: Adds padding to make sequences uniform length
inputs = tokenizer(text, return_tensors="pt", truncation=True, padding=True)
# Predict with the model
# Passes tokenized input through the model
# Extracts logits (raw prediction scores) from model output
outputs = model(**inputs)
logits = outputs.logits
# Sentiment Classification:
# torch.argmax(): Finds index of highest score ๊ฐ€์žฅ ๋†’์€ ๊ฐ’์˜ ์ธ๋ฑ์Šค๋ฅผ ์ถ”์ถœํ•˜์—ฌ ๊ฐ์„ฑ ๋ ˆ์ด๋ธ”์„ ์„ ํƒ
# Maps this index to a sentiment label using LABELS dictionary
# dim=1: Operates along rows, .item(): Converts tensor to Python scalar
predicted_class = torch.argmax(logits, dim=1).item()
sentiment = LABELS[predicted_class]
return sentiment
# API endpoint to analyze a text
@app.route('/analyze', methods=['POST'])
def analyze():
data = request.get_json()
if 'text' not in data:
return jsonify({'error': 'No text provided'}), 400
# call ๊ฐ์„ฑ ๋ถ„์„ function for ์ž…๋ ฅ ํ…์ŠคํŠธ
text = data['text']
sentiment = analyze_sentiment(text)
return jsonify({'text': text, 'sentiment': sentiment})
# API endpoint to analyze a list of texts
@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
# Perform analysis on each text in the list, process each one, and return a list of sentiment responses
texts = data['texts']
results = [{'text': text, 'sentiment': analyze_sentiment(text)} for text in texts]
# Count negative sentiments
negative_count = sum(1 for result in results if result['sentiment'] == 'Negative')
# Determine if it's a risk (more than half are negative)
risk = negative_count > (len(texts) / 2)
# Return the results as a JSON response
# return jsonify(results)
# Return the results and risk status as a JSON response
return jsonify({
'results': results,
'Negative Sentiment?': risk
})
# run
if __name__ == '__main__':
# ํ™˜๊ฒฝ ๋ณ€์ˆ˜ PORT๋ฅผ ์šฐ์„  ์‚ฌ์šฉ, ์—†์œผ๋ฉด ๊ธฐ๋ณธ๊ฐ’ 5000 ์‚ฌ์šฉ
#port = int(os.getenv('PORT', 5001))
app.run(host='0.0.0.0', port=7860)