robertou2 commited on
Commit
9298aaa
·
1 Parent(s): 597c4c6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +87 -6
app.py CHANGED
@@ -1,7 +1,23 @@
1
  import tweepy as tw
2
  import streamlit as st
3
  import pandas as pd
4
- from transformers import pipeline
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
  consumer_key = st.secrets["consumer_key"]
7
  consumer_secret = st.secrets["consumer_secret"]
@@ -11,7 +27,35 @@ auth = tw.OAuthHandler(consumer_key, consumer_secret)
11
  auth.set_access_token(access_token, access_token_secret)
12
  api = tw.API(auth, wait_on_rate_limit=True)
13
 
14
- classifier = pipeline('sentiment-analysis')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
  st.title('Analisis de comentarios sexistas en Twitter con Tweepy and HuggingFace Transformers')
16
  st.markdown('Esta app utiliza tweepy para descargar tweets de twitter en base a la información de entrada y procesa los tweets usando transformers de HuggingFace para detectar comentarios sexistas. El resultado y los tweets correspondientes se almacenan en un dataframe para mostrarlo que es lo que se ve como resultado')
17
 
@@ -23,9 +67,46 @@ def run():
23
  if submit_button:
24
  tweets =tw.Cursor(api.search_tweets,q=search_words).items(number_of_tweets)
25
  tweet_list = [i.text for i in tweets]
26
- p = [i for i in classifier(tweet_list)]
27
- q=[p[i]['label'] for i in range(len(p))]
28
- df = pd.DataFrame(list(zip(tweet_list, q)),columns =['Latest'+str(number_of_tweets)+'Tweets'+'on'+search_words, 'sentiment'])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
  st.write(df)
30
-
31
  run()
 
1
  import tweepy as tw
2
  import streamlit as st
3
  import pandas as pd
4
+ import torch
5
+ import numpy as np
6
+ import re
7
+
8
+ from torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSampler
9
+ from transformers import AutoTokenizer, AutoModelForSequenceClassification,AdamW
10
+ tokenizer = AutoTokenizer.from_pretrained('robertou2/twitter_sexismo-finetuned-exist2021')
11
+ model = AutoModelForSequenceClassification.from_pretrained("robertou2/twitter_sexismo-finetuned-exist2021")
12
+
13
+ import torch
14
+ if torch.cuda.is_available():
15
+ device = torch.device("cuda")
16
+ print('I will use the GPU:', torch.cuda.get_device_name(0))
17
+
18
+ else:
19
+ print('No GPU available, using the CPU instead.')
20
+ device = torch.device("cpu")
21
 
22
  consumer_key = st.secrets["consumer_key"]
23
  consumer_secret = st.secrets["consumer_secret"]
 
27
  auth.set_access_token(access_token, access_token_secret)
28
  api = tw.API(auth, wait_on_rate_limit=True)
29
 
30
+
31
+ def preprocess(text):
32
+
33
+ text=text.lower()
34
+ # remove hyperlinks
35
+ text = re.sub(r'https?:\/\/.*[\r\n]*', '', text)
36
+ text = re.sub(r'http?:\/\/.*[\r\n]*', '', text)
37
+ #Replace &amp, &lt, &gt with &,<,> respectively
38
+ text=text.replace(r'&amp;?',r'and')
39
+ text=text.replace(r'&lt;',r'<')
40
+ text=text.replace(r'&gt;',r'>')
41
+ #remove hashtag sign
42
+ #text=re.sub(r"#","",text)
43
+ #remove mentions
44
+ text = re.sub(r"(?:\@)\w+", '', text)
45
+ #text=re.sub(r"@","",text)
46
+ #remove non ascii chars
47
+ text=text.encode("ascii",errors="ignore").decode()
48
+ #remove some puncts (except . ! ?)
49
+ text=re.sub(r'[:"#$%&\*+,-/:;<=>@\\^_`{|}~]+','',text)
50
+ text=re.sub(r'[!]+','!',text)
51
+ text=re.sub(r'[?]+','?',text)
52
+ text=re.sub(r'[.]+','.',text)
53
+ text=re.sub(r"'","",text)
54
+ text=re.sub(r"\(","",text)
55
+ text=re.sub(r"\)","",text)
56
+ text=" ".join(text.split())
57
+ return text
58
+
59
  st.title('Analisis de comentarios sexistas en Twitter con Tweepy and HuggingFace Transformers')
60
  st.markdown('Esta app utiliza tweepy para descargar tweets de twitter en base a la información de entrada y procesa los tweets usando transformers de HuggingFace para detectar comentarios sexistas. El resultado y los tweets correspondientes se almacenan en un dataframe para mostrarlo que es lo que se ve como resultado')
61
 
 
67
  if submit_button:
68
  tweets =tw.Cursor(api.search_tweets,q=search_words).items(number_of_tweets)
69
  tweet_list = [i.text for i in tweets]
70
+ text= pd.DataFrame(tweet_list)
71
+ text[0] = text[0].apply(preprocess)
72
+ text1=text[0].values
73
+ indices1=tokenizer.batch_encode_plus(text1.tolist(),
74
+ max_length=128,
75
+ add_special_tokens=True,
76
+ return_attention_mask=True,
77
+ pad_to_max_length=True,
78
+ truncation=True)
79
+ input_ids1=indices1["input_ids"]
80
+ attention_masks1=indices1["attention_mask"]
81
+ prediction_inputs1= torch.tensor(input_ids1)
82
+ prediction_masks1 = torch.tensor(attention_masks1)
83
+ # Set the batch size.
84
+ batch_size = 25
85
+ # Create the DataLoader.
86
+ prediction_data1 = TensorDataset(prediction_inputs1, prediction_masks1)
87
+ prediction_sampler1 = SequentialSampler(prediction_data1)
88
+ prediction_dataloader1 = DataLoader(prediction_data1, sampler=prediction_sampler1, batch_size=batch_size)
89
+ print('Predicting labels for {:,} test sentences...'.format(len(prediction_inputs1)))
90
+ # Put model in evaluation mode
91
+ model.eval()
92
+ # Tracking variables
93
+ predictions = []
94
+ # Predict
95
+ for batch in prediction_dataloader1:
96
+ batch = tuple(t.to(device) for t in batch)
97
+ # Unpack the inputs from our dataloader
98
+ b_input_ids1, b_input_mask1 = batch
99
+ # Telling the model not to compute or store gradients, saving memory and # speeding up prediction
100
+ with torch.no_grad():
101
+ # Forward pass, calculate logit predictions
102
+ outputs1 = model(b_input_ids1, token_type_ids=None,attention_mask=b_input_mask1)
103
+ logits1 = outputs1[0]
104
+ # Move logits and labels to CPU
105
+ logits1 = logits1.detach().cpu().numpy()
106
+ # Store predictions and true labels
107
+ predictions.append(logits1)
108
+ flat_predictions = [item for sublist in predictions for item in sublist]
109
+ flat_predictions = np.argmax(flat_predictions, axis=1).flatten()#p = [i for i in classifier(tweet_list)]
110
+ df = pd.DataFrame(list(zip(tweet_list, flat_predictions)),columns =['Latest'+str(number_of_tweets)+'Tweets'+' on '+search_words, 'Sexista'])
111
  st.write(df)
 
112
  run()