Spaces:
Runtime error
Runtime error
Joshua1808
commited on
Commit
•
f999d6b
1
Parent(s):
a9c03b9
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,173 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 pysentimiento.preprocessing import preprocess_tweet
|
9 |
+
|
10 |
+
from torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSampler
|
11 |
+
from transformers import AutoTokenizer, AutoModelForSequenceClassification,AdamW
|
12 |
+
tokenizer = AutoTokenizer.from_pretrained('hackathon-pln-es/twitter_sexismo-finetuned-robertuito-exist2021')
|
13 |
+
model = AutoModelForSequenceClassification.from_pretrained("hackathon-pln-es/twitter_sexismo-finetuned-robertuito-exist2021")
|
14 |
+
|
15 |
+
import torch
|
16 |
+
if torch.cuda.is_available():
|
17 |
+
device = torch.device("cuda")
|
18 |
+
print('I will use the GPU:', torch.cuda.get_device_name(0))
|
19 |
+
|
20 |
+
else:
|
21 |
+
print('No GPU available, using the CPU instead.')
|
22 |
+
device = torch.device("cpu")
|
23 |
+
|
24 |
+
consumer_key = st.secrets["consumer_key"]
|
25 |
+
consumer_secret = st.secrets["consumer_secret"]
|
26 |
+
access_token = st.secrets["access_token"]
|
27 |
+
access_token_secret = st.secrets["access_token_secret"]
|
28 |
+
auth = tw.OAuthHandler(consumer_key, consumer_secret)
|
29 |
+
auth.set_access_token(access_token, access_token_secret)
|
30 |
+
api = tw.API(auth, wait_on_rate_limit=True)
|
31 |
+
|
32 |
+
def preprocess(text):
|
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 &, <, > with &,<,> respectively
|
38 |
+
text=text.replace(r'&?',r'and')
|
39 |
+
text=text.replace(r'<',r'<')
|
40 |
+
text=text.replace(r'>',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 |
+
def highlight_survived(s):
|
60 |
+
return ['background-color: red']*len(s) if (s.Sexista == 1) else ['background-color: green']*len(s)
|
61 |
+
|
62 |
+
def color_survived(val):
|
63 |
+
color = 'red' if val=='Sexista' else 'white'
|
64 |
+
return f'background-color: {color}'
|
65 |
+
|
66 |
+
st.set_page_config(layout="wide")
|
67 |
+
st.markdown('<style>body{background-color: Blue;}</style>',unsafe_allow_html=True)
|
68 |
+
|
69 |
+
#background-color: Blue;
|
70 |
+
|
71 |
+
colT1,colT2 = st.columns([2,8])
|
72 |
+
with colT2:
|
73 |
+
#st.title('Analisis de comentarios sexistas en Twitter')
|
74 |
+
st.markdown(""" <style> .font {
|
75 |
+
font-size:40px ; font-family: 'Cooper Black'; color: #FF9633;}
|
76 |
+
</style> """, unsafe_allow_html=True)
|
77 |
+
st.markdown('<p class="font">Análisis de comentarios sexistas en Twitter</p>', unsafe_allow_html=True)
|
78 |
+
|
79 |
+
st.markdown(""" <style> .font1 {
|
80 |
+
font-size:28px ; font-family: 'Times New Roman'; color: #8d33ff;}
|
81 |
+
</style> """, unsafe_allow_html=True)
|
82 |
+
st.markdown('<p class="font1">Objetivo 5 de los ODS. Lograr la igualdad entre los géneros y empoderar a todas las mujeres y las niñas</p>', unsafe_allow_html=True)
|
83 |
+
#st.header('Objetivo 5 de los ODS, Lograr la igualdad entre los géneros y empoderar a todas las mujeres y las niñas')
|
84 |
+
with colT1:
|
85 |
+
st.image("https://upload.wikimedia.org/wikipedia/commons/thumb/c/c7/Sustainable_Development_Goal-es-13.jpg/1200px-Sustainable_Development_Goal-es-13.jpg",width=200)
|
86 |
+
|
87 |
+
st.markdown(""" <style> .font2 {
|
88 |
+
font-size:16px ; font-family: 'Times New Roman'; color: #3358ff;}
|
89 |
+
</style> """, unsafe_allow_html=True)
|
90 |
+
st.markdown('<p class="font2">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.La finalidad del proyecto es, en línea con el Objetivo 5 de los ODS, eliminar todas las formas de violencia contra todas las mujeres y las niñas en los ámbitos público y privado, incluidas la trata y la explotación sexual y otros tipos de explotación. Los comentarios sexistas son una forma de violencia contra la mujer. Está aplicación puede ayudar a hacer un estudio sistemático de la misma.</p>',unsafe_allow_html=True)
|
91 |
+
|
92 |
+
|
93 |
+
def run():
|
94 |
+
with st.form(key='Introduzca Texto'):
|
95 |
+
col,buff1, buff2 = st.columns([2,2,1])
|
96 |
+
#col.text_input('smaller text window:')
|
97 |
+
search_words = col.text_input("Introduzca el termino o usuario para analizar y pulse el check correspondiente")
|
98 |
+
number_of_tweets = col.number_input('Introduzca número de twweets a analizar. Máximo 50', 0,50,10)
|
99 |
+
termino=st.checkbox('Término')
|
100 |
+
usuario=st.checkbox('Usuario')
|
101 |
+
submit_button = col.form_submit_button(label='Analizar')
|
102 |
+
error=False
|
103 |
+
if submit_button:
|
104 |
+
date_since = "2020-09-14"
|
105 |
+
if ( termino == False and usuario == False):
|
106 |
+
st.text('Error no se ha seleccionado ningun check')
|
107 |
+
error=True
|
108 |
+
elif ( termino == True and usuario == True):
|
109 |
+
st.text('Error se han seleccionado los dos check')
|
110 |
+
error=True
|
111 |
+
|
112 |
+
|
113 |
+
if (error == False):
|
114 |
+
if (termino):
|
115 |
+
new_search = search_words + " -filter:retweets"
|
116 |
+
tweets =tw.Cursor(api.search_tweets,q=new_search,lang="es",since=date_since).items(number_of_tweets)
|
117 |
+
elif (usuario):
|
118 |
+
tweets = api.user_timeline(screen_name = search_words,count=number_of_tweets)
|
119 |
+
|
120 |
+
tweet_list = [i.text for i in tweets]
|
121 |
+
#tweet_list = [strip_undesired_chars(i.text) for i in tweets]
|
122 |
+
text= pd.DataFrame(tweet_list)
|
123 |
+
#text[0] = text[0].apply(preprocess)
|
124 |
+
text[0] = text[0].apply(preprocess_tweet)
|
125 |
+
text1=text[0].values
|
126 |
+
indices1=tokenizer.batch_encode_plus(text1.tolist(),
|
127 |
+
max_length=128,
|
128 |
+
add_special_tokens=True,
|
129 |
+
return_attention_mask=True,
|
130 |
+
pad_to_max_length=True,
|
131 |
+
truncation=True)
|
132 |
+
input_ids1=indices1["input_ids"]
|
133 |
+
attention_masks1=indices1["attention_mask"]
|
134 |
+
prediction_inputs1= torch.tensor(input_ids1)
|
135 |
+
prediction_masks1 = torch.tensor(attention_masks1)
|
136 |
+
# Set the batch size.
|
137 |
+
batch_size = 25
|
138 |
+
# Create the DataLoader.
|
139 |
+
prediction_data1 = TensorDataset(prediction_inputs1, prediction_masks1)
|
140 |
+
prediction_sampler1 = SequentialSampler(prediction_data1)
|
141 |
+
prediction_dataloader1 = DataLoader(prediction_data1, sampler=prediction_sampler1, batch_size=batch_size)
|
142 |
+
print('Predicting labels for {:,} test sentences...'.format(len(prediction_inputs1)))
|
143 |
+
# Put model in evaluation mode
|
144 |
+
model.eval()
|
145 |
+
# Tracking variables
|
146 |
+
predictions = []
|
147 |
+
# Predict
|
148 |
+
for batch in prediction_dataloader1:
|
149 |
+
batch = tuple(t.to(device) for t in batch)
|
150 |
+
# Unpack the inputs from our dataloader
|
151 |
+
b_input_ids1, b_input_mask1 = batch
|
152 |
+
# Telling the model not to compute or store gradients, saving memory and # speeding up prediction
|
153 |
+
with torch.no_grad():
|
154 |
+
# Forward pass, calculate logit predictions
|
155 |
+
outputs1 = model(b_input_ids1, token_type_ids=None,attention_mask=b_input_mask1)
|
156 |
+
logits1 = outputs1[0]
|
157 |
+
# Move logits and labels to CPU
|
158 |
+
logits1 = logits1.detach().cpu().numpy()
|
159 |
+
# Store predictions and true labels
|
160 |
+
predictions.append(logits1)
|
161 |
+
flat_predictions = [item for sublist in predictions for item in sublist]
|
162 |
+
flat_predictions = np.argmax(flat_predictions, axis=1).flatten()#p = [i for i in classifier(tweet_list)]
|
163 |
+
df = pd.DataFrame(list(zip(tweet_list, flat_predictions)),columns =['Últimos '+ str(number_of_tweets)+' Tweets'+' de '+search_words, 'Sexista'])
|
164 |
+
df['Sexista']= np.where(df['Sexista']== 0, 'No Sexista', 'Sexista')
|
165 |
+
|
166 |
+
|
167 |
+
st.table(df.reset_index(drop=True).head(20).style.applymap(color_survived, subset=['Sexista']))
|
168 |
+
|
169 |
+
|
170 |
+
#st.dataframe(df.style.apply(highlight_survived, axis=1))
|
171 |
+
#st.table(df)
|
172 |
+
#st.write(df)
|
173 |
+
run()
|