Joshua1808 commited on
Commit
3e92edb
·
1 Parent(s): 2993324

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +86 -7
app.py CHANGED
@@ -133,13 +133,13 @@ def analizar_tweets(search_words, number_of_tweets ):
133
 
134
  probability = np.amax(logits1,axis=1).flatten()
135
  Tweets =['Últimos '+ str(number_of_tweets)+' Tweets'+' de '+search_words]
136
- df = pd.DataFrame(list(zip(text1, flat_predictions,probability)), columns = ['Tweets' , 'Sexista','Probabilidad'])
137
 
138
- df['Sexista']= np.where(df['Sexista']== 0, 'No Sexista', 'Sexista')
139
  df['Tweets'] = df['Tweets'].str.replace('RT|@', '')
140
  #df['Tweets'] = df['Tweets'].apply(lambda x: re.sub(r'[:;][-o^]?[)\]DpP3]|[(/\\]|[\U0001f600-\U0001f64f]|[\U0001f300-\U0001f5ff]|[\U0001f680-\U0001f6ff]|[\U0001f1e0-\U0001f1ff]','', x))
141
 
142
- tabla = st.table(df.reset_index(drop=True).head(30).style.applymap(color_survived, subset=['Sexista']))
143
 
144
  return tabla
145
 
@@ -199,17 +199,95 @@ def analizar_frase(frase):
199
 
200
  return tabla
201
 
202
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
203
  def run():
204
  with st.form("my_form"):
205
  col,buff1, buff2 = st.columns([2,2,1])
206
  st.write("Escoja una Opción")
207
- search_words = col.text_input("Introduzca el termino o usuario para analizar y pulse el check correspondiente")
208
  number_of_tweets = col.number_input('Introduzca número de tweets a analizar. Máximo 50', 0,50,10)
209
  termino=st.checkbox('Término')
210
  usuario=st.checkbox('Usuario')
 
211
  submit_button = col.form_submit_button(label='Analizar')
212
- error=False
 
 
213
  if submit_button:
214
  # Condición para el caso de que esten dos check seleccionados
215
  if ( termino == False and usuario == False):
@@ -225,6 +303,7 @@ def run():
225
 
226
  elif (usuario):
227
  analizar_tweets(search_words,number_of_tweets)
228
-
 
229
 
230
  run()
 
133
 
134
  probability = np.amax(logits1,axis=1).flatten()
135
  Tweets =['Últimos '+ str(number_of_tweets)+' Tweets'+' de '+search_words]
136
+ df = pd.DataFrame(list(zip(text1, flat_predictions,probability)), columns = ['Tweets' , 'Prediccion','Probabilidad'])
137
 
138
+ df['Prediccion']= np.where(df['Prediccion']== 0, 'No Sexista', 'Sexista')
139
  df['Tweets'] = df['Tweets'].str.replace('RT|@', '')
140
  #df['Tweets'] = df['Tweets'].apply(lambda x: re.sub(r'[:;][-o^]?[)\]DpP3]|[(/\\]|[\U0001f600-\U0001f64f]|[\U0001f300-\U0001f5ff]|[\U0001f680-\U0001f6ff]|[\U0001f1e0-\U0001f1ff]','', x))
141
 
142
+ tabla = st.table(df.reset_index(drop=True).head(30).style.applymap(color_survived, subset=['Prediccion']))
143
 
144
  return tabla
145
 
 
199
 
200
  return tabla
201
 
202
+ def tweets_localidad(buscar_localidad):
203
+ location = geolocator.geocode(buscar_localidad)
204
+ radius = "200km"
205
+ tweets = api.search(lang="es",geocode=f"{location.latitude},{location.longitude},{radius}", count = 50)
206
+ #for tweet in tweets:
207
+ # print(tweet.text)
208
+ tweet_list = [i.text for i in tweets]
209
+ text= pd.DataFrame(tweet_list)
210
+ text[0] = text[0].apply(preprocess_tweet)
211
+ text1=text[0].values
212
+ print(text1)
213
+ indices1=tokenizer.batch_encode_plus(text1.tolist(), max_length=128,add_special_tokens=True, return_attention_mask=True,pad_to_max_length=True,truncation=True)
214
+ input_ids1=indices1["input_ids"]
215
+ attention_masks1=indices1["attention_mask"]
216
+ prediction_inputs1= torch.tensor(input_ids1)
217
+ prediction_masks1 = torch.tensor(attention_masks1)
218
+ batch_size = 25
219
+ # Create the DataLoader.
220
+ prediction_data1 = TensorDataset(prediction_inputs1, prediction_masks1)
221
+ prediction_sampler1 = SequentialSampler(prediction_data1)
222
+ prediction_dataloader1 = DataLoader(prediction_data1, sampler=prediction_sampler1, batch_size=batch_size)
223
+ #print('Predicting labels for {:,} test sentences...'.format(len(prediction_inputs1)))
224
+ # Put model in evaluation mode
225
+ model.eval()
226
+ # Tracking variables
227
+ predictions = []
228
+ for batch in prediction_dataloader1:
229
+ batch = tuple(t.to(device) for t in batch)
230
+ # Unpack the inputs from our dataloader
231
+ b_input_ids1, b_input_mask1 = batch
232
+
233
+ #Telling the model not to compute or store gradients, saving memory and # speeding up prediction
234
+ with torch.no_grad():
235
+ # Forward pass, calculate logit predictions
236
+ outputs1 = model(b_input_ids1, token_type_ids=None,attention_mask=b_input_mask1)
237
+ logits1 = outputs1[0]
238
+ # Move logits and labels to CPU
239
+ logits1 = logits1.detach().cpu().numpy()
240
+ # Store predictions and true labels
241
+ predictions.append(logits1)
242
+
243
+ #flat_predictions = [item for sublist in predictions for item in sublist]
244
+ flat_predictions = [item for sublist in predictions for item in sublist]
245
+
246
+ flat_predictions = np.argmax(flat_predictions, axis=1).flatten()
247
+
248
+ probability = np.amax(logits1,axis=1).flatten()
249
+ Tweets =['Últimos 50 Tweets'+' de '+ buscar_localidad]
250
+ df = pd.DataFrame(list(zip(text1, flat_predictions,probability)), columns = ['Tweets' , 'Prediccion','Probabilidad'])
251
+
252
+ df['Prediccion']= np.where(df['Prediccion']== 0, 'No Sexista', 'Sexista')
253
+ #df['Tweets'] = df['Tweets'].str.replace('RT|@', '')
254
+ #df_filtrado = df[df["Sexista"] == 'Sexista']
255
+ #df['Tweets'] = df['Tweets'].apply(lambda x: re.sub(r'[:;][-o^]?[)\]DpP3]|[(/\\]|[\U0001f600-\U0001f64f]|[\U0001f300-\U0001f5ff]|[\U0001f680-\U0001f6ff]|[\U0001f1e0-\U0001f1ff]','', x))
256
+
257
+ tabla = st.table(df.reset_index(drop=True).head(50).style.applymap(color_survived, subset=['Prediccion']))
258
+
259
+ df_sexista = df[df['Sexista']=="Sexista"]
260
+ df_no_sexista = df[df['Probabilidad'] > 0]
261
+ sexista = len(df_sexista)
262
+ no_sexista = len(df_no_sexista)
263
+
264
+ # Crear un gráfico de barras
265
+ labels = ['Sexista ', ' No sexista']
266
+ counts = [sexista, no_sexista]
267
+ plt.bar(labels, counts)
268
+ plt.xlabel('Categoría')
269
+ plt.ylabel('Cantidad de tweets')
270
+ plt.title('Cantidad de tweets sexistas y no sexistas')
271
+ plt.show()
272
+
273
+ return df
274
+
275
+
276
+
277
+
278
  def run():
279
  with st.form("my_form"):
280
  col,buff1, buff2 = st.columns([2,2,1])
281
  st.write("Escoja una Opción")
282
+ search_words = col.text_input("Introduzca el termino, usuario o localidad para analizar y pulse el check correspondiente")
283
  number_of_tweets = col.number_input('Introduzca número de tweets a analizar. Máximo 50', 0,50,10)
284
  termino=st.checkbox('Término')
285
  usuario=st.checkbox('Usuario')
286
+ localidad=st.checkbox('Localidad')
287
  submit_button = col.form_submit_button(label='Analizar')
288
+ error =False
289
+
290
+
291
  if submit_button:
292
  # Condición para el caso de que esten dos check seleccionados
293
  if ( termino == False and usuario == False):
 
303
 
304
  elif (usuario):
305
  analizar_tweets(search_words,number_of_tweets)
306
+ elif (localidad):
307
+ tweets_localidad(search_words)
308
 
309
  run()