Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -16,7 +16,7 @@ def fetch_tweets(client, query, tweet_fields):
|
|
16 |
try:
|
17 |
tweets = client.search_recent_tweets(
|
18 |
query=query,
|
19 |
-
max_results=10,
|
20 |
tweet_fields=tweet_fields
|
21 |
)
|
22 |
return tweets
|
@@ -36,107 +36,106 @@ def fetch_tweets(client, query, tweet_fields):
|
|
36 |
def post_tweet(api, text):
|
37 |
return api.update_status(status=text)
|
38 |
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
|
|
|
|
47 |
|
48 |
-
# Verificação inicial das variáveis de ambiente
|
49 |
-
missing_vars = []
|
50 |
-
for var in required_vars:
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
|
57 |
-
if missing_vars:
|
58 |
-
|
59 |
|
60 |
-
# Autenticação com Twitter para leitura
|
61 |
-
client = tweepy.Client(
|
62 |
-
|
63 |
-
|
64 |
-
)
|
65 |
|
66 |
-
# Autenticação com Twitter para postagem
|
67 |
-
auth = tweepy.OAuth1UserHandler(
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
)
|
73 |
|
74 |
-
api = tweepy.API(auth, wait_on_rate_limit=True)
|
75 |
|
76 |
-
# Configuração da query e campos do tweet
|
77 |
-
query = 'BBB25 -filter:retweets lang:pt -is:reply'
|
78 |
-
tweet_fields = ['text', 'created_at', 'lang', 'public_metrics']
|
79 |
|
80 |
-
|
81 |
-
|
82 |
-
tweets = fetch_tweets(client, query, tweet_fields)
|
83 |
-
|
84 |
-
if not tweets.data:
|
85 |
-
st.warning("Nenhum tweet encontrado")
|
86 |
-
st.stop()
|
87 |
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
)
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
result = sentiment_pipeline(tweet.text)
|
99 |
-
sentiments.append(result[0]['label'])
|
100 |
-
|
101 |
-
# Adicionar delay entre processamentos
|
102 |
-
time.sleep(1)
|
103 |
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
model = GPT2LMHeadModel.from_pretrained('gpt2')
|
119 |
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
prompt = "Write an informative tweet about BBB25 with a neutral tone in Portuguese."
|
124 |
-
else:
|
125 |
-
prompt = "Write a buzzing tweet about BBB25 with an engaging tone in Portuguese."
|
126 |
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
134 |
|
135 |
-
|
136 |
-
generated_text = generated_text[:280]
|
137 |
-
|
138 |
-
try:
|
139 |
-
# Postar no Twitter com retry
|
140 |
with st.spinner('Postando tweet...'):
|
141 |
post_tweet(api, generated_text)
|
142 |
st.success("Tweet postado com sucesso!")
|
@@ -168,18 +167,22 @@ try:
|
|
168 |
|
169 |
with open('posting_log.txt', 'a') as f:
|
170 |
f.write(f"{str(log_entry)}\n")
|
171 |
-
|
172 |
-
except Exception as e:
|
173 |
-
st.error(f"Erro: {str(e)}")
|
174 |
-
print(f"Erro: {e}")
|
175 |
|
176 |
-
|
177 |
-
st.
|
178 |
-
|
179 |
-
|
180 |
-
|
181 |
-
|
182 |
-
|
183 |
-
|
184 |
-
|
185 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
16 |
try:
|
17 |
tweets = client.search_recent_tweets(
|
18 |
query=query,
|
19 |
+
max_results=10,
|
20 |
tweet_fields=tweet_fields
|
21 |
)
|
22 |
return tweets
|
|
|
36 |
def post_tweet(api, text):
|
37 |
return api.update_status(status=text)
|
38 |
|
39 |
+
def main():
|
40 |
+
try:
|
41 |
+
# Verificar variáveis de ambiente
|
42 |
+
required_vars = [
|
43 |
+
'TWITTER_API_KEY',
|
44 |
+
'TWITTER_API_SECRET_KEY',
|
45 |
+
'TWITTER_ACCESS_TOKEN',
|
46 |
+
'TWITTER_ACCESS_TOKEN_SECRET',
|
47 |
+
'TWITTER_BEARER_TOKEN'
|
48 |
+
]
|
49 |
|
50 |
+
# Verificação inicial das variáveis de ambiente
|
51 |
+
missing_vars = []
|
52 |
+
for var in required_vars:
|
53 |
+
if os.getenv(var) is None:
|
54 |
+
missing_vars.append(var)
|
55 |
+
print(f"Erro: A variável de ambiente '{var}' não está definida.")
|
56 |
+
else:
|
57 |
+
print(f"{var} carregada com sucesso.")
|
58 |
|
59 |
+
if missing_vars:
|
60 |
+
raise ValueError(f"As seguintes variáveis de ambiente são necessárias: {', '.join(missing_vars)}")
|
61 |
|
62 |
+
# Autenticação com Twitter para leitura
|
63 |
+
client = tweepy.Client(
|
64 |
+
bearer_token=os.getenv('TWITTER_BEARER_TOKEN'),
|
65 |
+
wait_on_rate_limit=True
|
66 |
+
)
|
67 |
|
68 |
+
# Autenticação com Twitter para postagem
|
69 |
+
auth = tweepy.OAuth1UserHandler(
|
70 |
+
os.getenv('TWITTER_API_KEY'),
|
71 |
+
os.getenv('TWITTER_API_SECRET_KEY'),
|
72 |
+
os.getenv('TWITTER_ACCESS_TOKEN'),
|
73 |
+
os.getenv('TWITTER_ACCESS_TOKEN_SECRET')
|
74 |
+
)
|
75 |
|
76 |
+
api = tweepy.API(auth, wait_on_rate_limit=True)
|
77 |
|
78 |
+
# Configuração da query e campos do tweet
|
79 |
+
query = 'BBB25 -filter:retweets lang:pt -is:reply'
|
80 |
+
tweet_fields = ['text', 'created_at', 'lang', 'public_metrics']
|
81 |
|
82 |
+
with st.spinner('Buscando tweets...'):
|
83 |
+
tweets = fetch_tweets(client, query, tweet_fields)
|
|
|
|
|
|
|
|
|
|
|
84 |
|
85 |
+
if not tweets.data:
|
86 |
+
st.warning("Nenhum tweet encontrado")
|
87 |
+
return
|
88 |
+
|
89 |
+
# Análise de sentimentos
|
90 |
+
with st.spinner('Analisando sentimentos...'):
|
91 |
+
sentiment_pipeline = pipeline(
|
92 |
+
'sentiment-analysis',
|
93 |
+
model='cardiffnlp/twitter-xlm-roberta-base-sentiment'
|
94 |
+
)
|
|
|
|
|
|
|
|
|
|
|
95 |
|
96 |
+
sentiments = []
|
97 |
+
for tweet in tweets.data:
|
98 |
+
if hasattr(tweet, 'lang') and tweet.lang == 'pt':
|
99 |
+
result = sentiment_pipeline(tweet.text)
|
100 |
+
sentiments.append(result[0]['label'])
|
101 |
+
|
102 |
+
time.sleep(1)
|
103 |
+
|
104 |
+
# Calcular taxas
|
105 |
+
if sentiments:
|
106 |
+
positive = sentiments.count('positive')
|
107 |
+
negative = sentiments.count('negative')
|
108 |
+
neutral = sentiments.count('neutral')
|
109 |
+
total = len(sentiments)
|
|
|
110 |
|
111 |
+
positive_ratio = positive / total
|
112 |
+
negative_ratio = negative / total
|
113 |
+
neutral_ratio = neutral / total
|
|
|
|
|
|
|
114 |
|
115 |
+
# Gerar mensagem com IA
|
116 |
+
with st.spinner('Gerando novo tweet...'):
|
117 |
+
tokenizer = GPT2Tokenizer.from_pretrained('gpt2')
|
118 |
+
model = GPT2LMHeadModel.from_pretrained('gpt2')
|
119 |
+
|
120 |
+
if positive_ratio > 0.6:
|
121 |
+
prompt = "Write an exciting tweet about BBB25 with a positive tone in Portuguese."
|
122 |
+
elif negative_ratio > 0.6:
|
123 |
+
prompt = "Write an informative tweet about BBB25 with a neutral tone in Portuguese."
|
124 |
+
else:
|
125 |
+
prompt = "Write a buzzing tweet about BBB25 with an engaging tone in Portuguese."
|
126 |
+
|
127 |
+
input_ids = tokenizer.encode(prompt, return_tensors='pt')
|
128 |
+
outputs = model.generate(
|
129 |
+
input_ids,
|
130 |
+
max_length=25,
|
131 |
+
do_sample=True,
|
132 |
+
pad_token_id=tokenizer.eos_token_id
|
133 |
+
)
|
134 |
+
|
135 |
+
generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
136 |
+
generated_text = generated_text[:280]
|
137 |
|
138 |
+
# Postar tweet
|
|
|
|
|
|
|
|
|
139 |
with st.spinner('Postando tweet...'):
|
140 |
post_tweet(api, generated_text)
|
141 |
st.success("Tweet postado com sucesso!")
|
|
|
167 |
|
168 |
with open('posting_log.txt', 'a') as f:
|
169 |
f.write(f"{str(log_entry)}\n")
|
|
|
|
|
|
|
|
|
170 |
|
171 |
+
except Exception as e:
|
172 |
+
st.error(f"Erro: {str(e)}")
|
173 |
+
print(f"Erro: {e}")
|
174 |
+
|
175 |
+
finally:
|
176 |
+
# Footer
|
177 |
+
st.markdown("---")
|
178 |
+
st.markdown(
|
179 |
+
"""
|
180 |
+
<div style='text-align: center'>
|
181 |
+
<small>Desenvolvido com ❤️ usando Streamlit e Transformers</small>
|
182 |
+
</div>
|
183 |
+
""",
|
184 |
+
unsafe_allow_html=True
|
185 |
+
)
|
186 |
+
|
187 |
+
if __name__ == "__main__":
|
188 |
+
main()
|