A7med4 commited on
Commit
69c8a29
1 Parent(s): 679ba35

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +37 -27
app.py CHANGED
@@ -1,37 +1,47 @@
1
  from flask import Flask, request, jsonify
2
  import nltk
3
  from nltk.sentiment import SentimentIntensityAnalyzer
4
- from transformers import AutoTokenizer, AutoModelForSequenceClassification
5
  from scipy.special import softmax
6
- import pandas as pd
7
 
8
  # Initialize Flask app
9
  app = Flask(__name__)
10
 
11
- # Load NLTK's VADER
12
- nltk.download('vader_lexicon')
 
 
 
 
 
13
  sia = SentimentIntensityAnalyzer()
14
 
15
- # Load the transformer model and tokenizer (e.g., RoBERTa)
16
- tokenizer = AutoTokenizer.from_pretrained('cardiffnlp/twitter-roberta-base-sentiment')
17
- model = AutoModelForSequenceClassification.from_pretrained('cardiffnlp/twitter-roberta-base-sentiment')
 
 
 
18
 
19
  def analyze_sentiment(text):
20
  # VADER sentiment analysis
21
  vader_result = sia.polarity_scores(text)
22
 
23
  # RoBERTa sentiment analysis
24
- encoded_input = tokenizer(text, return_tensors='pt')
25
- output = model(**encoded_input)
26
- scores = output[0][0].detach().numpy()
27
- scores = softmax(scores)
28
- roberta_result = {
29
- 'roberta_neg': scores[0],
30
- 'roberta_neu': scores[1],
31
- 'roberta_pos': scores[2]
 
 
32
  }
33
 
34
- return {**vader_result, **roberta_result}
35
 
36
  def sentiment_to_stars(sentiment_score):
37
  thresholds = [0.2, 0.4, 0.6, 0.8]
@@ -52,21 +62,21 @@ def analyze():
52
  text = data['text']
53
  sentiment_scores = analyze_sentiment(text)
54
  star_rating = sentiment_to_stars(sentiment_scores['roberta_pos'])
55
-
56
- # Log the sentiment scores and star rating
57
- app.logger.info("Sentiment scores: %s", sentiment_scores)
58
- app.logger.info("Star rating: %s", star_rating)
59
-
60
  response = {
61
  'sentiment_scores': sentiment_scores,
62
  'star_rating': star_rating
63
  }
64
-
65
- # Log the complete response before returning it
66
- app.logger.info("Complete response: %s", response)
67
-
68
  return jsonify(response)
69
 
 
 
 
 
70
 
71
- if __name__ == '__main__':
72
- app.run(host='0.0.0.0', port=5000)
 
1
  from flask import Flask, request, jsonify
2
  import nltk
3
  from nltk.sentiment import SentimentIntensityAnalyzer
4
+ from transformers import AutoTokenizer, AutoModelForSequenceClassification, pipeline
5
  from scipy.special import softmax
6
+ import torch
7
 
8
  # Initialize Flask app
9
  app = Flask(__name__)
10
 
11
+ # Check if the VADER lexicon is already downloaded
12
+ try:
13
+ nltk.data.find('sentiment/vader_lexicon.zip')
14
+ except LookupError:
15
+ nltk.download('vader_lexicon')
16
+
17
+ # Load NLTK's VADER lexicon once
18
  sia = SentimentIntensityAnalyzer()
19
 
20
+ # Lazy load transformer model and tokenizer
21
+ def get_transformer_pipeline():
22
+ tokenizer = AutoTokenizer.from_pretrained('cardiffnlp/twitter-roberta-base-sentiment')
23
+ model = AutoModelForSequenceClassification.from_pretrained('cardiffnlp/twitter-roberta-base-sentiment')
24
+ nlp = pipeline('sentiment-analysis', model=model, tokenizer=tokenizer)
25
+ return nlp
26
 
27
  def analyze_sentiment(text):
28
  # VADER sentiment analysis
29
  vader_result = sia.polarity_scores(text)
30
 
31
  # RoBERTa sentiment analysis
32
+ nlp = get_transformer_pipeline()
33
+ roberta_result = nlp(text)[0]
34
+
35
+ sentiment_scores = {
36
+ 'vader_neg': vader_result['neg'],
37
+ 'vader_neu': vader_result['neu'],
38
+ 'vader_pos': vader_result['pos'],
39
+ 'roberta_neg': roberta_result['score'] if roberta_result['label'] == 'LABEL_0' else 0,
40
+ 'roberta_neu': roberta_result['score'] if roberta_result['label'] == 'LABEL_1' else 0,
41
+ 'roberta_pos': roberta_result['score'] if roberta_result['label'] == 'LABEL_2' else 0
42
  }
43
 
44
+ return sentiment_scores
45
 
46
  def sentiment_to_stars(sentiment_score):
47
  thresholds = [0.2, 0.4, 0.6, 0.8]
 
62
  text = data['text']
63
  sentiment_scores = analyze_sentiment(text)
64
  star_rating = sentiment_to_stars(sentiment_scores['roberta_pos'])
65
+
66
+ # Convert float32 values to standard float
67
+ sentiment_scores = {k: float(v) for k, v in sentiment_scores.items()}
68
+
 
69
  response = {
70
  'sentiment_scores': sentiment_scores,
71
  'star_rating': star_rating
72
  }
73
+
 
 
 
74
  return jsonify(response)
75
 
76
+ # Health check endpoint
77
+ @app.route('/')
78
+ def health_check():
79
+ return jsonify({"status": "OK"}), 200
80
 
81
+ if __name__ == "__main__":
82
+ app.run(host="0.0.0.0", port=5000)