robertou2 commited on
Commit
c1547f4
·
1 Parent(s): cfaf3b7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +70 -60
app.py CHANGED
@@ -54,73 +54,83 @@ def preprocess(text):
54
  text=" ".join(text.split())
55
  return text
56
 
57
-
58
- st.title('Analisis de comentarios sexistas en Twitter con Tweepy and HuggingFace Transformers')
59
  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')
 
 
60
 
61
  def run():
62
  with st.form(key='Introduzca Texto'):
63
- search_words = st.text_input('Introduzca el termino o usuario para analizar y pulse el check ')
64
- number_of_tweets = st.number_input('Introduzca número de twweets a analizar. Máximo 50', 0,50,10)
 
 
65
  termino=st.checkbox('Término')
66
  usuario=st.checkbox('Usuario')
67
- submit_button = st.form_submit_button(label='Analizar')
 
68
  if submit_button:
69
  date_since = "2020-09-14"
70
- if (termino):
71
- new_search = search_words + " -filter:retweets"
72
- tweets =tw.Cursor(api.search_tweets,q=new_search,lang="es",since=date_since).items(number_of_tweets)
73
- elif (usuario):
74
- tweets = api.user_timeline(screen_name = search_words,count=number_of_tweets)
75
-
76
- #new_search = search_words + " -filter:retweets"
77
- #tweets = tweepy.Cursor(api.search,q=new_search,lang="es",since=date_since).items(number_of_tweets)
78
- #tweets =tw.Cursor(api.search_tweets,q=search_words).items(number_of_tweets)
79
- #tweets =tw.Cursor(api.search_tweets,q=new_search,lang="es",since=date_since).items(number_of_tweets)
80
- tweet_list = [i.text for i in tweets]
81
- #tweet_list = [strip_undesired_chars(i.text) for i in tweets]
82
- text= pd.DataFrame(tweet_list)
83
- text[0] = text[0].apply(preprocess)
84
- text1=text[0].values
85
- indices1=tokenizer.batch_encode_plus(text1.tolist(),
86
- max_length=128,
87
- add_special_tokens=True,
88
- return_attention_mask=True,
89
- pad_to_max_length=True,
90
- truncation=True)
91
- input_ids1=indices1["input_ids"]
92
- attention_masks1=indices1["attention_mask"]
93
- prediction_inputs1= torch.tensor(input_ids1)
94
- prediction_masks1 = torch.tensor(attention_masks1)
95
- # Set the batch size.
96
- batch_size = 25
97
- # Create the DataLoader.
98
- prediction_data1 = TensorDataset(prediction_inputs1, prediction_masks1)
99
- prediction_sampler1 = SequentialSampler(prediction_data1)
100
- prediction_dataloader1 = DataLoader(prediction_data1, sampler=prediction_sampler1, batch_size=batch_size)
101
- print('Predicting labels for {:,} test sentences...'.format(len(prediction_inputs1)))
102
- # Put model in evaluation mode
103
- model.eval()
104
- # Tracking variables
105
- predictions = []
106
- # Predict
107
- for batch in prediction_dataloader1:
108
- batch = tuple(t.to(device) for t in batch)
109
- # Unpack the inputs from our dataloader
110
- b_input_ids1, b_input_mask1 = batch
111
- # Telling the model not to compute or store gradients, saving memory and # speeding up prediction
112
- with torch.no_grad():
113
- # Forward pass, calculate logit predictions
114
- outputs1 = model(b_input_ids1, token_type_ids=None,attention_mask=b_input_mask1)
115
- logits1 = outputs1[0]
116
- # Move logits and labels to CPU
117
- logits1 = logits1.detach().cpu().numpy()
118
- # Store predictions and true labels
119
- predictions.append(logits1)
120
- flat_predictions = [item for sublist in predictions for item in sublist]
121
- flat_predictions = np.argmax(flat_predictions, axis=1).flatten()#p = [i for i in classifier(tweet_list)]
122
- df = pd.DataFrame(list(zip(tweet_list, flat_predictions)),columns =['Latest'+str(number_of_tweets)+'Tweets'+' on '+search_words, 'Sexista'])
123
- df['Sexista']= np.where(df['Sexista']== 0, 'No Sexista', 'Sexista')
124
- st.table(df)
 
 
 
 
 
125
  #st.write(df)
126
  run()
 
54
  text=" ".join(text.split())
55
  return text
56
 
57
+ st.set_page_config(layout="wide")
58
+ st.title('Analisis de comentarios sexistas en Twitter. Objetivo 5 de los ODS, Lograr la igualdad entre los géneros y empoderar a todas las mujeres y las niñas')
59
  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')
60
+ st.markdown('La finalidad del proyecto es en línea con el Objetivo 5 de los ODS, Lograr la igualdad entre los géneros y empoderar a todas las mujeres y las niñas.Una vez analizados los tweets, los que resulten sexistas se pueden contestar para intentar reeducar a las personas que bien por su educación o circustancias presenten un comportamiento contrario al del Objetivo 5 antes mencionado. Igualmente en casos más graves se pueden realizar otras acciones')
61
+
62
 
63
  def run():
64
  with st.form(key='Introduzca Texto'):
65
+ col,buff1, buff2 = st.columns([2,2,1])
66
+ #col.text_input('smaller text window:')
67
+ search_words = col.text_input('Introduzca el termino o usuario para analizar y pulse el check ')
68
+ number_of_tweets = col.number_input('Introduzca número de twweets a analizar. Máximo 50', 0,50,10)
69
  termino=st.checkbox('Término')
70
  usuario=st.checkbox('Usuario')
71
+ submit_button = col.form_submit_button(label='Analizar')
72
+ error=False
73
  if submit_button:
74
  date_since = "2020-09-14"
75
+ if ( termino == False and usuario == False):
76
+ st.text('Error no se ha seleccionado ningun check')
77
+ error=True
78
+ elif ( termino == True and usuario == True):
79
+ st.text('Error se han seleccionado los dos check')
80
+ error=True
81
+
82
+
83
+ if (error == False):
84
+ if (termino):
85
+ new_search = search_words + " -filter:retweets"
86
+ tweets =tw.Cursor(api.search_tweets,q=new_search,lang="es",since=date_since).items(number_of_tweets)
87
+ elif (usuario):
88
+ tweets = api.user_timeline(screen_name = search_words,count=number_of_tweets)
89
+
90
+ tweet_list = [i.text for i in tweets]
91
+ #tweet_list = [strip_undesired_chars(i.text) for i in tweets]
92
+ text= pd.DataFrame(tweet_list)
93
+ text[0] = text[0].apply(preprocess)
94
+ text1=text[0].values
95
+ indices1=tokenizer.batch_encode_plus(text1.tolist(),
96
+ max_length=128,
97
+ add_special_tokens=True,
98
+ return_attention_mask=True,
99
+ pad_to_max_length=True,
100
+ truncation=True)
101
+ input_ids1=indices1["input_ids"]
102
+ attention_masks1=indices1["attention_mask"]
103
+ prediction_inputs1= torch.tensor(input_ids1)
104
+ prediction_masks1 = torch.tensor(attention_masks1)
105
+ # Set the batch size.
106
+ batch_size = 25
107
+ # Create the DataLoader.
108
+ prediction_data1 = TensorDataset(prediction_inputs1, prediction_masks1)
109
+ prediction_sampler1 = SequentialSampler(prediction_data1)
110
+ prediction_dataloader1 = DataLoader(prediction_data1, sampler=prediction_sampler1, batch_size=batch_size)
111
+ print('Predicting labels for {:,} test sentences...'.format(len(prediction_inputs1)))
112
+ # Put model in evaluation mode
113
+ model.eval()
114
+ # Tracking variables
115
+ predictions = []
116
+ # Predict
117
+ for batch in prediction_dataloader1:
118
+ batch = tuple(t.to(device) for t in batch)
119
+ # Unpack the inputs from our dataloader
120
+ b_input_ids1, b_input_mask1 = batch
121
+ # Telling the model not to compute or store gradients, saving memory and # speeding up prediction
122
+ with torch.no_grad():
123
+ # Forward pass, calculate logit predictions
124
+ outputs1 = model(b_input_ids1, token_type_ids=None,attention_mask=b_input_mask1)
125
+ logits1 = outputs1[0]
126
+ # Move logits and labels to CPU
127
+ logits1 = logits1.detach().cpu().numpy()
128
+ # Store predictions and true labels
129
+ predictions.append(logits1)
130
+ flat_predictions = [item for sublist in predictions for item in sublist]
131
+ flat_predictions = np.argmax(flat_predictions, axis=1).flatten()#p = [i for i in classifier(tweet_list)]
132
+ df = pd.DataFrame(list(zip(tweet_list, flat_predictions)),columns =['Latest'+str(number_of_tweets)+'Tweets'+' on '+search_words, 'Sexista'])
133
+ df['Sexista']= np.where(df['Sexista']== 0, 'No Sexista', 'Sexista')
134
+ st.table(df)
135
  #st.write(df)
136
  run()