Joshua1808 commited on
Commit
a933a32
·
1 Parent(s): fb64dd1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +29 -54
app.py CHANGED
@@ -104,10 +104,14 @@ def analizar_tweets(search_words, number_of_tweets ):
104
  text_list = text[0].tolist()
105
  result = []
106
  for text in text_list:
107
- prediction = pipeline_nlp(text)
108
- for predic in prediction:
109
- etiqueta = {'Tweets': text,'Prediccion': predic['label'], 'Probabilidad': predic['score']}
110
- result.append(etiqueta)
 
 
 
 
111
  df = pd.DataFrame(result)
112
  df['Prediccion'] = np.where( df['Prediccion'] == 'LABEL_1', 'Sexista', 'No Sexista')
113
  tabla = st.table(df.reset_index(drop=True).head(30).style.applymap(color_survived, subset=['Prediccion']))
@@ -134,62 +138,31 @@ def analizar_frase(frase):
134
  def tweets_localidad(buscar_localidad):
135
  geolocator = Nominatim(user_agent="nombre_del_usuario")
136
  location = geolocator.geocode(buscar_localidad)
137
- radius = "200km"
138
  tweets = api.search(lang="es",geocode=f"{location.latitude},{location.longitude},{radius}", count = 50)
139
- #for tweet in tweets:
140
- # print(tweet.text)
141
- tweet_list = [i.text for i in tweets]
142
  text= pd.DataFrame(tweet_list)
143
  text[0] = text[0].apply(preprocess_tweet)
144
- text1=text[0].values
145
- print(text1)
146
- 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)
147
- input_ids1=indices1["input_ids"]
148
- attention_masks1=indices1["attention_mask"]
149
- prediction_inputs1= torch.tensor(input_ids1)
150
- prediction_masks1 = torch.tensor(attention_masks1)
151
- batch_size = 25
152
- # Create the DataLoader.
153
- prediction_data1 = TensorDataset(prediction_inputs1, prediction_masks1)
154
- prediction_sampler1 = SequentialSampler(prediction_data1)
155
- prediction_dataloader1 = DataLoader(prediction_data1, sampler=prediction_sampler1, batch_size=batch_size)
156
- #print('Predicting labels for {:,} test sentences...'.format(len(prediction_inputs1)))
157
- # Put model in evaluation mode
158
- model.eval()
159
- # Tracking variables
160
- predictions = []
161
- for batch in prediction_dataloader1:
162
- batch = tuple(t.to(device) for t in batch)
163
- # Unpack the inputs from our dataloader
164
- b_input_ids1, b_input_mask1 = batch
165
-
166
- #Telling the model not to compute or store gradients, saving memory and # speeding up prediction
167
- with torch.no_grad():
168
- # Forward pass, calculate logit predictions
169
- outputs1 = model(b_input_ids1, token_type_ids=None,attention_mask=b_input_mask1)
170
- logits1 = outputs1[0]
171
- # Move logits and labels to CPU
172
- logits1 = logits1.detach().cpu().numpy()
173
- # Store predictions and true labels
174
- predictions.append(logits1)
175
-
176
- #flat_predictions = [item for sublist in predictions for item in sublist]
177
- flat_predictions = [item for sublist in predictions for item in sublist]
178
-
179
- flat_predictions = np.argmax(flat_predictions, axis=1).flatten()
180
-
181
- probability = np.amax(logits1,axis=1).flatten()
182
- Tweets =['Últimos 50 Tweets'+' de '+ buscar_localidad]
183
- df = pd.DataFrame(list(zip(text1, flat_predictions,probability)), columns = ['Tweets' , 'Prediccion','Probabilidad'])
184
 
185
- df['Prediccion']= np.where(df['Prediccion']== 0, 'No Sexista', 'Sexista')
 
 
186
  #df['Tweets'] = df['Tweets'].str.replace('RT|@', '')
187
  #df_filtrado = df[df["Sexista"] == 'Sexista']
188
- #df['Tweets'] = df['Tweets'].apply(lambda x: re.sub(r'[:;][-o^]?[)\]DpP3]|[(/\\]|[\U0001f600-\U0001f64f]|[\U0001f300-\U0001f5ff]|[\U0001f680-\U0001f6ff]|[\U0001f1e0-\U0001f1ff]','', x))
189
-
190
  tabla = st.table(df.reset_index(drop=True).head(50).style.applymap(color_survived, subset=['Prediccion']))
191
 
192
- df_sexista = df[df['Sexista']=="Sexista"]
193
  df_no_sexista = df[df['Probabilidad'] > 0]
194
  sexista = len(df_sexista)
195
  no_sexista = len(df_no_sexista)
@@ -202,8 +175,10 @@ def tweets_localidad(buscar_localidad):
202
  plt.ylabel('Cantidad de tweets')
203
  plt.title('Cantidad de tweets sexistas y no sexistas')
204
  plt.show()
205
-
206
- return df
 
 
207
 
208
 
209
 
 
104
  text_list = text[0].tolist()
105
  result = []
106
  for text in text_list:
107
+ if (text.startswith('RT')):
108
+ continue
109
+ else:
110
+ prediction = pipeline_nlp(text)
111
+ for predic in prediction:
112
+ etiqueta = {'Tweets': text,'Prediccion': predic['label'], 'Probabilidad': predic['score']}
113
+ result.append(etiqueta)
114
+
115
  df = pd.DataFrame(result)
116
  df['Prediccion'] = np.where( df['Prediccion'] == 'LABEL_1', 'Sexista', 'No Sexista')
117
  tabla = st.table(df.reset_index(drop=True).head(30).style.applymap(color_survived, subset=['Prediccion']))
 
138
  def tweets_localidad(buscar_localidad):
139
  geolocator = Nominatim(user_agent="nombre_del_usuario")
140
  location = geolocator.geocode(buscar_localidad)
141
+ radius = "10km"
142
  tweets = api.search(lang="es",geocode=f"{location.latitude},{location.longitude},{radius}", count = 50)
143
+ tweet_list = [i.full_text for i in tweets]
 
 
144
  text= pd.DataFrame(tweet_list)
145
  text[0] = text[0].apply(preprocess_tweet)
146
+ text_list = text[0].tolist()
147
+ result = []
148
+ for text in text_list:
149
+ if (text.startswith('RT')):
150
+ continue
151
+ else:
152
+ prediction = pipeline_nlp(text)
153
+ for predic in prediction:
154
+ etiqueta = {'Tweets': text,'Prediccion': predic['label'], 'Probabilidad': predic['score']}
155
+ result.append(etiqueta)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
156
 
157
+ df = pd.DataFrame(result)
158
+ df['Prediccion'] = np.where( df['Prediccion'] == 'LABEL_1', 'Sexista', 'No Sexista')
159
+ tabla = st.table(df.reset_index(drop=True).head(30).style.applymap(color_survived, subset=['Prediccion']))
160
  #df['Tweets'] = df['Tweets'].str.replace('RT|@', '')
161
  #df_filtrado = df[df["Sexista"] == 'Sexista']
162
+
 
163
  tabla = st.table(df.reset_index(drop=True).head(50).style.applymap(color_survived, subset=['Prediccion']))
164
 
165
+ df_sexista = df[df['Prediccion']=="Sexista"]
166
  df_no_sexista = df[df['Probabilidad'] > 0]
167
  sexista = len(df_sexista)
168
  no_sexista = len(df_no_sexista)
 
175
  plt.ylabel('Cantidad de tweets')
176
  plt.title('Cantidad de tweets sexistas y no sexistas')
177
  plt.show()
178
+ st.pyplot()
179
+ st.set_option('deprecation.showPyplotGlobalUse', False)
180
+
181
+ return tabla
182
 
183
 
184