sentivity commited on
Commit
ddf7c1a
·
verified ·
1 Parent(s): b2eeaef

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +22 -19
app.py CHANGED
@@ -6,10 +6,17 @@ import re
6
  import datetime
7
  from transformers import AutoTokenizer
8
  import numpy as np
 
 
 
 
9
 
10
  # Load tokenizer and sentiment model
11
  MODEL = "cardiffnlp/xlm-twitter-politics-sentiment"
12
  tokenizer = AutoTokenizer.from_pretrained(MODEL)
 
 
 
13
 
14
 
15
  class ScorePredictor(nn.Module):
@@ -44,25 +51,21 @@ def preprocess_text(text):
44
  def predict_sentiment(text):
45
  if not text:
46
  return 0.0
47
- encoded_input = tokenizer(
48
- text.split(),
49
- return_tensors='pt',
50
- padding=True,
51
- truncation=True,
52
- max_length=512
53
- )
54
- input_ids, attention_mask = encoded_input["input_ids"], encoded_input["attention_mask"]
55
- with torch.no_grad():
56
- score = score_model(input_ids, attention_mask)[0].item()
57
-
58
- scaled=score*100
59
- k = 20
60
- midpoint = 0.7
61
-
62
- scaled_score = 1 / (1 + np.exp(-k * (score - midpoint)))
63
- final_output = scaled_score * 100
64
-
65
- return final_output
66
 
67
 
68
 
 
6
  import datetime
7
  from transformers import AutoTokenizer
8
  import numpy as np
9
+ from transformers import AutoModelForSequenceClassification
10
+ from transformers import TFAutoModelForSequenceClassification
11
+ from transformers import AutoConfig
12
+ from scipy.special import softmax
13
 
14
  # Load tokenizer and sentiment model
15
  MODEL = "cardiffnlp/xlm-twitter-politics-sentiment"
16
  tokenizer = AutoTokenizer.from_pretrained(MODEL)
17
+ config = AutoConfig.from_pretrained(MODEL)
18
+ model = AutoModelForSequenceClassification.from_pretrained(MODEL)
19
+ model.save_pretrained(MODEL)
20
 
21
 
22
  class ScorePredictor(nn.Module):
 
51
  def predict_sentiment(text):
52
  if not text:
53
  return 0.0
54
+ text = preprocess(text)
55
+ encoded_input = tokenizer(text, return_tensors='pt')
56
+ output = model(**encoded_input)
57
+ scores = output[0][0].detach().numpy()
58
+ scores = softmax(scores)
59
+ ranking = np.argsort(scores)
60
+ ranking = ranking[::-1]
61
+ negative_index = None
62
+ for i in range(scores.shape[0]):
63
+ if config.id2label[ranking[i]] == 'negative':
64
+ negative_index = ranking[i]
65
+ break
66
+ negative_score = scores[negative_index]
67
+
68
+ return negative_score
 
 
 
 
69
 
70
 
71