agent-comment / app.py
BugZoid's picture
Update app.py
81a43fe verified
raw
history blame
2.41 kB
import tweepy
from transformers import pipeline, GPT2LMHeadModel, GPT2Tokenizer
import os
# Autenticação com Twitter para leitura
client = tweepy.Client(
bearer_token=os.getenv('TWITTER_BEARER_TOKEN')
)
# Autenticação com Twitter para postagem
auth = tweepy.OAuth1UserHandler(
os.getenv('TWITTER_API_KEY'),
os.getenv('TWITTER_API_SECRET_KEY'),
os.getenv('TWITTER_ACCESS_TOKEN'),
os.getenv('TWITTER_ACCESS_TOKEN_SECRET')
)
api = tweepy.API(auth)
# Coletar tweets
query = 'BBB25 -filter:retweets'
tweets = client.search_recent_tweets(query=query, lang='pt', max_results=100)
# Análise de sentimentos
sentiment_pipeline = pipeline('sentiment-analysis', model='cardiffnlp/twitter-xlm-roberta-base-sentiment')
sentiments = []
for tweet in tweets.data:
result = sentiment_pipeline(tweet.text)
sentiments.append(result[0]['label'])
# Calcular taxas
positive = sentiments.count('positive')
negative = sentiments.count('negative')
total = len(sentiments)
positive_ratio = positive / total
negative_ratio = negative / total
# Gerar mensagem com IA
tokenizer = GPT2Tokenizer.from_pretrained('gpt2')
model = GPT2LMHeadModel.from_pretrained('gpt2')
if positive_ratio > 0.6:
prompt = "Write an exciting tweet about BBB25 with a positive tone in Portuguese."
elif negative_ratio > 0.6:
prompt = "Write an informative tweet about BBB25 with a neutral tone in Portuguese."
else:
prompt = "Write a buzzing tweet about BBB25 with an engaging tone in Portuguese."
input_ids = tokenizer.encode(prompt, return_tensors='pt')
# Gerar texto com limite de tokens correspondente a 280 caracteres
outputs = model.generate(input_ids, max_length=25, do_sample=True)
generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
# Limitar o tweet a 280 caracteres
generated_text = generated_text[:280]
# Postar no Twitter
try:
api.update_status(status=generated_text)
print(f"Postado: {generated_text}")
except Exception as e:
print(f"Erro ao postar: {e}")
# Logging (opcional)
with open('posting_log.txt', 'a') as f:
f.write(f"Positive Ratio: {positive_ratio}, Negative Ratio: {negative_ratio}, Posted: {generated_text}\n")
# Footer
st.markdown("---")
st.markdown(
"""
<div style='text-align: center'>
<small>Desenvolvido com ❤️ usando Streamlit e Transformers</small>
</div>
""",
unsafe_allow_html=True
)