JosePezantes commited on
Commit
7d6cb82
·
1 Parent(s): ebb8e7b

Correcciones encabezado y validaciones

Browse files
Files changed (1) hide show
  1. app.py +74 -79
app.py CHANGED
@@ -88,7 +88,7 @@ with colT1:
88
  st.markdown(""" <style> .font2 {
89
  font-size:18px ; font-family: 'Times New Roman'; color: #181618; text-align: justify;}
90
  </style> """, unsafe_allow_html=True)
91
- st.markdown('<p class="font2">La presente herramienta permite ingresar un término o un usuario de twitter para ser analizado. Ademas, permite ingresar un número de tweets para analizar, máximo 50. Si desea analizar lo que publican hacia su usuario de twitter o hacia sus nombres y apellidos seleccione la opción de filtrar por término. Seleccione la opción de filtrar por usuario para analizar los tweets publicados por un usuario en específico. Al dar click en Analizar se presentan los resultados de los datos ingresados en una tabla con su respectiva clasificación.</p>',unsafe_allow_html=True)
92
 
93
  with open("style.css") as f:
94
  st.markdown(f"<style>{f.read()}</style>",unsafe_allow_html=True)
@@ -108,99 +108,94 @@ def run():
108
  submit_button = myform.form_submit_button(label='Analizar')
109
 
110
  if submit_button:
111
-
112
- if (filtro=='Término'):
113
 
114
  if not search_words:
115
- st.error("Campo vacío. Por favor, ingrese un término o usuario.")
116
- return
117
  if number_of_tweets <= 0:
118
- st.error("Por favor, ingrese un número de tweets mayor a 0.")
119
- return
120
- new_search = search_words + " -filter:retweets"
121
- tweets =tw.Cursor(api.search_tweets,q=new_search,lang="es",tweet_mode="extended").items(number_of_tweets)
122
 
123
- elif (filtro=='Usuario'):
124
 
125
- try:
126
- if not search_words:
127
- st.error("Campo vacío. Por favor, ingrese un usuario.")
128
- return
129
 
130
- if not search_words.startswith('@'):
131
- st.error("Por favor, ingrese un usuario válido, iniciando con @")
 
 
 
 
 
 
 
 
 
 
132
  return
133
 
134
- if number_of_tweets <= 0:
135
- st.error("Por favor, ingrese un número de tweets mayor a 0.")
136
- return
137
-
138
- tweets = api.user_timeline(screen_name = search_words,tweet_mode="extended",count=number_of_tweets)
139
 
140
- except tw.errors.NotFound:
141
- st.error('"El usuario ingresado no existe. Por favor, ingrese un usuario existente." ⚠️', icon="⚠️")
142
- return
143
 
144
- except tw.errors.Unauthorized:
145
- st.error('El usuario ingresado es privado. Por favor, ingrese un usuario público ⚠️', icon="⚠️")
146
  return
147
 
148
- tweet_list = [i.full_text for i in tweets]
149
-
150
- text= pd.DataFrame(tweet_list)
151
- #text[0] = text[0].apply(preprocess)
152
- text[0] = text[0].apply(preprocess_tweet)
153
- text1=text[0].values
154
- indices1=tokenizer.batch_encode_plus(text1.tolist(),
155
- max_length=128,
156
- add_special_tokens=True,
157
- return_attention_mask=True,
158
- pad_to_max_length=True,
159
- truncation=True)
160
- input_ids1=indices1["input_ids"]
161
- attention_masks1=indices1["attention_mask"]
162
- prediction_inputs1= torch.tensor(input_ids1)
163
- prediction_masks1 = torch.tensor(attention_masks1)
164
- # Set the batch size.
165
- batch_size = 25
166
- # Create the DataLoader.
167
- prediction_data1 = TensorDataset(prediction_inputs1, prediction_masks1)
168
- prediction_sampler1 = SequentialSampler(prediction_data1)
169
- prediction_dataloader1 = DataLoader(prediction_data1, sampler=prediction_sampler1, batch_size=batch_size)
170
- print('Predicting labels for {:,} test sentences...'.format(len(prediction_inputs1)))
171
- # Put model in evaluation mode
172
- model.eval()
173
- # Tracking variables
174
- predictions = []
175
- # Predict
176
- for batch in prediction_dataloader1:
177
- batch = tuple(t.to(device) for t in batch)
178
- # Unpack the inputs from our dataloader
179
- b_input_ids1, b_input_mask1 = batch
180
- # Telling the model not to compute or store gradients, saving memory and # speeding up prediction
181
- with torch.no_grad():
182
- # Forward pass, calculate logit predictions
183
- outputs1 = model(b_input_ids1, token_type_ids=None,attention_mask=b_input_mask1)
184
- logits1 = outputs1[0]
185
- # Move logits and labels to CPU
186
- logits1 = logits1.detach().cpu().numpy()
187
- # Store predictions and true labels
188
- predictions.append(logits1)
189
- flat_predictions = [item for sublist in predictions for item in sublist]
190
- flat_predictions = np.argmax(flat_predictions, axis=1).flatten()
191
- df = pd.DataFrame(list(zip(tweet_list, flat_predictions)),columns =['Últimos '+ str(number_of_tweets)+' Tweets'+' de '+search_words, 'violencia política de género'])
192
- df['violencia política de género']= np.where(df['violencia política de género']== 0, 'no violencia política de género', 'violencia política de género')
193
- showTable = True
194
 
195
  if (showTable):
196
  df.index+=1
197
  print(df.index)
198
  st.table(df.head(50).style.set_properties(subset=['violencia política de género'], **{'width': '250px'}).applymap(color_survived, subset=['violencia política de género']))
199
 
200
- try:
201
- run()
202
- except KeyError:
203
- cole,cole1,cole2 = st.columns([2,3,2])
204
-
205
- with cole1:
206
- st.error('"No se encontraron tweets publicados con los datos ingresados." ⚠️', icon="⚠️")
 
88
  st.markdown(""" <style> .font2 {
89
  font-size:18px ; font-family: 'Times New Roman'; color: #181618; text-align: justify;}
90
  </style> """, unsafe_allow_html=True)
91
+ st.markdown('<p class="font2">La presente herramienta permite ingresar un término o un usuario de twitter para ser analizado. Ademas, permite ingresar un número de tweets para analizar, máximo 50. Si desea analizar lo que publican hacia su usuario de twitter o sus nombres y apellidos seleccione la opción de filtrar por término. Seleccione la opción de filtrar por usuario para analizar los tweets publicados por parte de un usuario de twitter en específico. Al dar click en Analizar se presentan los resultados de los datos ingresados en una tabla con su respectiva clasificación.</p>',unsafe_allow_html=True)
92
 
93
  with open("style.css") as f:
94
  st.markdown(f"<style>{f.read()}</style>",unsafe_allow_html=True)
 
108
  submit_button = myform.form_submit_button(label='Analizar')
109
 
110
  if submit_button:
111
+
112
+ with st.spinner('Analizando tweets...'):
113
 
114
  if not search_words:
115
+ st.error("Campo vacío. Por favor, ingrese un término o usuario.")
116
+ return
117
  if number_of_tweets <= 0:
118
+ st.error("Por favor, ingrese un número de tweets mayor a 0.")
119
+ return
120
+
 
121
 
122
+ if (filtro=='Término'):
123
 
124
+ new_search = search_words + " -filter:retweets"
125
+ tweets =tw.Cursor(api.search_tweets,q=new_search,lang="es",tweet_mode="extended").items(number_of_tweets)
 
 
126
 
127
+ elif (filtro=='Usuario'):
128
+
129
+ try:
130
+
131
+ if not search_words.startswith('@'):
132
+ st.error("Por favor, ingrese un usuario válido, iniciando con @")
133
+ return
134
+
135
+ tweets = api.user_timeline(screen_name = search_words,tweet_mode="extended",count=number_of_tweets)
136
+
137
+ except tw.errors.NotFound:
138
+ st.error('"El usuario ingresado no existe. Por favor, ingrese un usuario existente." ⚠️', icon="⚠️")
139
  return
140
 
141
+ except tw.errors.Unauthorized:
142
+ st.error('El usuario ingresado es privado. Por favor, ingrese un usuario público ⚠️', icon="⚠️")
143
+ return
 
 
144
 
145
+ tweet_list = [i.full_text for i in tweets]
 
 
146
 
147
+ if not tweet_list:
148
+ st.error("No se encontraron tweets con los criterios de búsqueda especificados.")
149
  return
150
 
151
+ text= pd.DataFrame(tweet_list)
152
+ text[0] = text[0].apply(preprocess_tweet)
153
+ text1=text[0].values
154
+ indices1=tokenizer.batch_encode_plus(text1.tolist(),
155
+ max_length=128,
156
+ add_special_tokens=True,
157
+ return_attention_mask=True,
158
+ pad_to_max_length=True,
159
+ truncation=True)
160
+ input_ids1=indices1["input_ids"]
161
+ attention_masks1=indices1["attention_mask"]
162
+ prediction_inputs1= torch.tensor(input_ids1)
163
+ prediction_masks1 = torch.tensor(attention_masks1)
164
+ # Set the batch size.
165
+ batch_size = 25
166
+ # Create the DataLoader.
167
+ prediction_data1 = TensorDataset(prediction_inputs1, prediction_masks1)
168
+ prediction_sampler1 = SequentialSampler(prediction_data1)
169
+ prediction_dataloader1 = DataLoader(prediction_data1, sampler=prediction_sampler1, batch_size=batch_size)
170
+ print('Predicting labels for {:,} test sentences...'.format(len(prediction_inputs1)))
171
+ # Put model in evaluation mode
172
+ model.eval()
173
+ # Tracking variables
174
+ predictions = []
175
+ # Predict
176
+ for batch in prediction_dataloader1:
177
+ batch = tuple(t.to(device) for t in batch)
178
+ # Unpack the inputs from our dataloader
179
+ b_input_ids1, b_input_mask1 = batch
180
+ # Telling the model not to compute or store gradients, saving memory and # speeding up prediction
181
+ with torch.no_grad():
182
+ # Forward pass, calculate logit predictions
183
+ outputs1 = model(b_input_ids1, token_type_ids=None,attention_mask=b_input_mask1)
184
+ logits1 = outputs1[0]
185
+ # Move logits and labels to CPU
186
+ logits1 = logits1.detach().cpu().numpy()
187
+ # Store predictions and true labels
188
+ predictions.append(logits1)
189
+ flat_predictions = [item for sublist in predictions for item in sublist]
190
+ flat_predictions = np.argmax(flat_predictions, axis=1).flatten()
191
+ df = pd.DataFrame(list(zip(tweet_list, flat_predictions)),columns =['Últimos '+ str(number_of_tweets)+' Tweets'+' de '+search_words, 'violencia política de género'])
192
+ df['violencia política de género']= np.where(df['violencia política de género']== 0, 'no violencia política de género', 'violencia política de género')
193
+ showTable = True
194
+ st.success('Análisis completado!', icon="✅")
 
 
195
 
196
  if (showTable):
197
  df.index+=1
198
  print(df.index)
199
  st.table(df.head(50).style.set_properties(subset=['violencia política de género'], **{'width': '250px'}).applymap(color_survived, subset=['violencia política de género']))
200
 
201
+ run()