Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
@@ -6,6 +6,11 @@ from datetime import datetime
|
|
6 |
import time
|
7 |
from tenacity import retry, stop_after_attempt, wait_exponential
|
8 |
|
|
|
|
|
|
|
|
|
|
|
9 |
@retry(
|
10 |
stop=stop_after_attempt(3),
|
11 |
wait=wait_exponential(multiplier=1, min=4, max=10),
|
@@ -13,17 +18,37 @@ from tenacity import retry, stop_after_attempt, wait_exponential
|
|
13 |
)
|
14 |
def fetch_tweets(client, query, tweet_fields):
|
15 |
try:
|
|
|
|
|
|
|
16 |
tweets = client.search_recent_tweets(
|
17 |
query=query,
|
18 |
max_results=10,
|
19 |
tweet_fields=tweet_fields
|
20 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
21 |
return tweets
|
|
|
22 |
except tweepy.errors.TooManyRequests as e:
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
27 |
raise e
|
28 |
|
29 |
@retry(
|
@@ -36,7 +61,11 @@ def post_tweet(api, text):
|
|
36 |
|
37 |
def main():
|
38 |
try:
|
|
|
|
|
39 |
# Verificar variáveis de ambiente
|
|
|
|
|
40 |
required_vars = [
|
41 |
'TWITTER_API_KEY',
|
42 |
'TWITTER_API_SECRET_KEY',
|
@@ -45,18 +74,19 @@ def main():
|
|
45 |
'TWITTER_BEARER_TOKEN'
|
46 |
]
|
47 |
|
48 |
-
# Verificação inicial das variáveis de ambiente
|
49 |
missing_vars = []
|
50 |
for var in required_vars:
|
51 |
if os.getenv(var) is None:
|
52 |
missing_vars.append(var)
|
53 |
-
|
54 |
else:
|
55 |
-
|
56 |
|
57 |
if missing_vars:
|
58 |
-
raise ValueError(f"
|
59 |
|
|
|
|
|
60 |
# Autenticação com Twitter para leitura
|
61 |
client = tweepy.Client(
|
62 |
bearer_token=os.getenv('TWITTER_BEARER_TOKEN'),
|
@@ -73,19 +103,44 @@ def main():
|
|
73 |
|
74 |
api = tweepy.API(auth, wait_on_rate_limit=True)
|
75 |
|
76 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
77 |
query = 'BBB25 lang:pt -is:retweet -is:reply'
|
78 |
tweet_fields = ['text', 'created_at', 'lang', 'public_metrics']
|
79 |
-
|
|
|
|
|
80 |
with st.spinner('Buscando tweets...'):
|
81 |
tweets = fetch_tweets(client, query, tweet_fields)
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
86 |
|
87 |
# Análise de sentimentos
|
88 |
with st.spinner('Analisando sentimentos...'):
|
|
|
89 |
sentiment_pipeline = pipeline(
|
90 |
'sentiment-analysis',
|
91 |
model='cardiffnlp/twitter-xlm-roberta-base-sentiment'
|
@@ -96,6 +151,7 @@ def main():
|
|
96 |
if hasattr(tweet, 'lang') and tweet.lang == 'pt':
|
97 |
result = sentiment_pipeline(tweet.text)
|
98 |
sentiments.append(result[0]['label'])
|
|
|
99 |
|
100 |
time.sleep(1)
|
101 |
|
@@ -106,12 +162,15 @@ def main():
|
|
106 |
neutral = sentiments.count('neutral')
|
107 |
total = len(sentiments)
|
108 |
|
|
|
|
|
109 |
positive_ratio = positive / total
|
110 |
negative_ratio = negative / total
|
111 |
neutral_ratio = neutral / total
|
112 |
|
113 |
# Gerar mensagem com IA
|
114 |
with st.spinner('Gerando novo tweet...'):
|
|
|
115 |
tokenizer = GPT2Tokenizer.from_pretrained('gpt2')
|
116 |
model = GPT2LMHeadModel.from_pretrained('gpt2')
|
117 |
|
@@ -122,6 +181,8 @@ def main():
|
|
122 |
else:
|
123 |
prompt = "Write a buzzing tweet about BBB25 with an engaging tone in Portuguese."
|
124 |
|
|
|
|
|
125 |
input_ids = tokenizer.encode(prompt, return_tensors='pt')
|
126 |
outputs = model.generate(
|
127 |
input_ids,
|
@@ -132,14 +193,17 @@ def main():
|
|
132 |
|
133 |
generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
134 |
generated_text = generated_text[:280]
|
|
|
135 |
|
136 |
# Postar tweet
|
137 |
with st.spinner('Postando tweet...'):
|
|
|
138 |
post_tweet(api, generated_text)
|
139 |
st.success("Tweet postado com sucesso!")
|
|
|
140 |
|
141 |
# Interface Streamlit
|
142 |
-
st.title("
|
143 |
|
144 |
# Mostrar estatísticas
|
145 |
col1, col2, col3 = st.columns(3)
|
@@ -155,6 +219,7 @@ def main():
|
|
155 |
st.write(generated_text)
|
156 |
|
157 |
# Logging
|
|
|
158 |
log_entry = {
|
159 |
'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
|
160 |
'positive_ratio': positive_ratio,
|
@@ -165,13 +230,14 @@ def main():
|
|
165 |
|
166 |
with open('posting_log.txt', 'a') as f:
|
167 |
f.write(f"{str(log_entry)}\n")
|
|
|
168 |
|
169 |
except Exception as e:
|
170 |
st.error(f"Erro: {str(e)}")
|
171 |
-
|
|
|
172 |
|
173 |
finally:
|
174 |
-
# Footer
|
175 |
st.markdown("---")
|
176 |
st.markdown(
|
177 |
"""
|
|
|
6 |
import time
|
7 |
from tenacity import retry, stop_after_attempt, wait_exponential
|
8 |
|
9 |
+
def debug_print(message):
|
10 |
+
"""Função para imprimir mensagens de debug tanto no console quanto no Streamlit"""
|
11 |
+
print(message)
|
12 |
+
st.text(message)
|
13 |
+
|
14 |
@retry(
|
15 |
stop=stop_after_attempt(3),
|
16 |
wait=wait_exponential(multiplier=1, min=4, max=10),
|
|
|
18 |
)
|
19 |
def fetch_tweets(client, query, tweet_fields):
|
20 |
try:
|
21 |
+
debug_print(f"Iniciando busca com query: {query}")
|
22 |
+
debug_print(f"Campos solicitados: {tweet_fields}")
|
23 |
+
|
24 |
tweets = client.search_recent_tweets(
|
25 |
query=query,
|
26 |
max_results=10,
|
27 |
tweet_fields=tweet_fields
|
28 |
)
|
29 |
+
|
30 |
+
if tweets is None:
|
31 |
+
debug_print("Nenhum resultado retornado da API")
|
32 |
+
return None
|
33 |
+
|
34 |
+
if not hasattr(tweets, 'data'):
|
35 |
+
debug_print("Resposta não contém dados")
|
36 |
+
return None
|
37 |
+
|
38 |
+
debug_print(f"Tweets encontrados: {len(tweets.data) if tweets.data else 0}")
|
39 |
return tweets
|
40 |
+
|
41 |
except tweepy.errors.TooManyRequests as e:
|
42 |
+
debug_print(f"Rate limit atingido: {str(e)}")
|
43 |
+
raise e
|
44 |
+
except tweepy.errors.TwitterServerError as e:
|
45 |
+
debug_print(f"Erro do servidor Twitter: {str(e)}")
|
46 |
+
raise e
|
47 |
+
except tweepy.errors.BadRequest as e:
|
48 |
+
debug_print(f"Erro na requisição: {str(e)}")
|
49 |
+
raise e
|
50 |
+
except Exception as e:
|
51 |
+
debug_print(f"Erro inesperado na busca: {str(e)}")
|
52 |
raise e
|
53 |
|
54 |
@retry(
|
|
|
61 |
|
62 |
def main():
|
63 |
try:
|
64 |
+
st.title("Análise de Sentimentos - BBB25")
|
65 |
+
|
66 |
# Verificar variáveis de ambiente
|
67 |
+
debug_print("Verificando variáveis de ambiente...")
|
68 |
+
|
69 |
required_vars = [
|
70 |
'TWITTER_API_KEY',
|
71 |
'TWITTER_API_SECRET_KEY',
|
|
|
74 |
'TWITTER_BEARER_TOKEN'
|
75 |
]
|
76 |
|
|
|
77 |
missing_vars = []
|
78 |
for var in required_vars:
|
79 |
if os.getenv(var) is None:
|
80 |
missing_vars.append(var)
|
81 |
+
debug_print(f"Erro: A variável de ambiente '{var}' não está definida.")
|
82 |
else:
|
83 |
+
debug_print(f"{var} carregada com sucesso.")
|
84 |
|
85 |
if missing_vars:
|
86 |
+
raise ValueError(f"Variáveis de ambiente faltando: {', '.join(missing_vars)}")
|
87 |
|
88 |
+
debug_print("Iniciando autenticação com Twitter...")
|
89 |
+
|
90 |
# Autenticação com Twitter para leitura
|
91 |
client = tweepy.Client(
|
92 |
bearer_token=os.getenv('TWITTER_BEARER_TOKEN'),
|
|
|
103 |
|
104 |
api = tweepy.API(auth, wait_on_rate_limit=True)
|
105 |
|
106 |
+
# Vamos testar a autenticação com uma query simples
|
107 |
+
debug_print("Testando autenticação...")
|
108 |
+
try:
|
109 |
+
test_query = "test"
|
110 |
+
test_response = client.search_recent_tweets(query=test_query, max_results=1)
|
111 |
+
debug_print("Teste de autenticação bem sucedido")
|
112 |
+
except Exception as e:
|
113 |
+
debug_print(f"Erro no teste de autenticação: {str(e)}")
|
114 |
+
raise e
|
115 |
+
|
116 |
+
# Query principal
|
117 |
query = 'BBB25 lang:pt -is:retweet -is:reply'
|
118 |
tweet_fields = ['text', 'created_at', 'lang', 'public_metrics']
|
119 |
+
|
120 |
+
debug_print("Iniciando busca principal de tweets...")
|
121 |
+
|
122 |
with st.spinner('Buscando tweets...'):
|
123 |
tweets = fetch_tweets(client, query, tweet_fields)
|
124 |
+
|
125 |
+
if tweets is None:
|
126 |
+
st.error("Não foi possível obter tweets")
|
127 |
+
return
|
128 |
+
|
129 |
+
if not tweets.data:
|
130 |
+
st.warning("Nenhum tweet encontrado com os critérios especificados")
|
131 |
+
debug_print("Busca retornou vazia")
|
132 |
+
return
|
133 |
+
|
134 |
+
debug_print(f"Encontrados {len(tweets.data)} tweets")
|
135 |
+
|
136 |
+
# Mostrar alguns tweets encontrados para debug
|
137 |
+
st.subheader("Tweets encontrados (preview):")
|
138 |
+
for i, tweet in enumerate(tweets.data[:3]):
|
139 |
+
st.text(f"Tweet {i+1}: {tweet.text[:100]}...")
|
140 |
|
141 |
# Análise de sentimentos
|
142 |
with st.spinner('Analisando sentimentos...'):
|
143 |
+
debug_print("Iniciando análise de sentimentos...")
|
144 |
sentiment_pipeline = pipeline(
|
145 |
'sentiment-analysis',
|
146 |
model='cardiffnlp/twitter-xlm-roberta-base-sentiment'
|
|
|
151 |
if hasattr(tweet, 'lang') and tweet.lang == 'pt':
|
152 |
result = sentiment_pipeline(tweet.text)
|
153 |
sentiments.append(result[0]['label'])
|
154 |
+
debug_print(f"Sentimento analisado: {result[0]['label']}")
|
155 |
|
156 |
time.sleep(1)
|
157 |
|
|
|
162 |
neutral = sentiments.count('neutral')
|
163 |
total = len(sentiments)
|
164 |
|
165 |
+
debug_print(f"Total de sentimentos analisados: {total}")
|
166 |
+
|
167 |
positive_ratio = positive / total
|
168 |
negative_ratio = negative / total
|
169 |
neutral_ratio = neutral / total
|
170 |
|
171 |
# Gerar mensagem com IA
|
172 |
with st.spinner('Gerando novo tweet...'):
|
173 |
+
debug_print("Iniciando geração de texto...")
|
174 |
tokenizer = GPT2Tokenizer.from_pretrained('gpt2')
|
175 |
model = GPT2LMHeadModel.from_pretrained('gpt2')
|
176 |
|
|
|
181 |
else:
|
182 |
prompt = "Write a buzzing tweet about BBB25 with an engaging tone in Portuguese."
|
183 |
|
184 |
+
debug_print(f"Usando prompt: {prompt}")
|
185 |
+
|
186 |
input_ids = tokenizer.encode(prompt, return_tensors='pt')
|
187 |
outputs = model.generate(
|
188 |
input_ids,
|
|
|
193 |
|
194 |
generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
195 |
generated_text = generated_text[:280]
|
196 |
+
debug_print(f"Texto gerado: {generated_text}")
|
197 |
|
198 |
# Postar tweet
|
199 |
with st.spinner('Postando tweet...'):
|
200 |
+
debug_print("Tentando postar tweet...")
|
201 |
post_tweet(api, generated_text)
|
202 |
st.success("Tweet postado com sucesso!")
|
203 |
+
debug_print("Tweet postado com sucesso")
|
204 |
|
205 |
# Interface Streamlit
|
206 |
+
st.title("Resultados da Análise")
|
207 |
|
208 |
# Mostrar estatísticas
|
209 |
col1, col2, col3 = st.columns(3)
|
|
|
219 |
st.write(generated_text)
|
220 |
|
221 |
# Logging
|
222 |
+
debug_print("Salvando log...")
|
223 |
log_entry = {
|
224 |
'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
|
225 |
'positive_ratio': positive_ratio,
|
|
|
230 |
|
231 |
with open('posting_log.txt', 'a') as f:
|
232 |
f.write(f"{str(log_entry)}\n")
|
233 |
+
debug_print("Log salvo com sucesso")
|
234 |
|
235 |
except Exception as e:
|
236 |
st.error(f"Erro: {str(e)}")
|
237 |
+
debug_print(f"Erro fatal: {str(e)}")
|
238 |
+
raise e
|
239 |
|
240 |
finally:
|
|
|
241 |
st.markdown("---")
|
242 |
st.markdown(
|
243 |
"""
|