Spaces:
Runtime error
Runtime error
import gradio as gr | |
import torch | |
from transformers import pipeline, T5ForConditionalGeneration, T5Tokenizer | |
from keybert import KeyBERT | |
import yake | |
from textblob import TextBlob | |
import pandas as pd | |
import numpy as np | |
from PIL import Image | |
import matplotlib.pyplot as plt | |
import seaborn as sns | |
# Carregando modelos | |
sentiment_analyzer = pipeline("sentiment-analysis", model="nlptown/bert-base-multilingual-uncased-sentiment") | |
text_generator = pipeline("text2text-generation", model="google/flan-t5-small") | |
kw_model = KeyBERT('distilbert-base-nli-mean-tokens') | |
yake_extractor = yake.KeywordExtractor( | |
lan="pt", n=3, dedupLim=0.9, dedupFunc='seqm', windowsSize=1, top=20 | |
) | |
def analyze_sentiment_detailed(text): | |
"""Análise detalhada de sentimento usando múltiplos modelos""" | |
# BERT análise | |
bert_result = sentiment_analyzer(text)[0] | |
score = float(bert_result['score']) | |
label = bert_result['label'] | |
# TextBlob análise para complementar | |
blob = TextBlob(text) | |
polarity = blob.sentiment.polarity | |
subjectivity = blob.sentiment.subjectivity | |
# Criando visualização | |
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4)) | |
# Gráfico de sentimento | |
sentiment_data = pd.DataFrame({ | |
'Métrica': ['BERT Score', 'TextBlob Polarity', 'Subjetividade'], | |
'Valor': [score, polarity, subjectivity] | |
}) | |
sns.barplot(x='Métrica', y='Valor', data=sentiment_data, ax=ax1) | |
ax1.set_title('Análise de Sentimento') | |
# Interpretação | |
interpretation = f""" | |
📊 Análise de Sentimento: | |
- Sentimento (BERT): {label} ({score:.2f}) | |
- Polaridade (TextBlob): {polarity:.2f} | |
- Subjetividade: {subjectivity:.2f} | |
💡 Interpretação: | |
- O texto é {'positivo' if polarity > 0 else 'negativo' if polarity < 0 else 'neutro'} | |
- {'Altamente subjetivo' if subjectivity > 0.5 else 'Relativamente objetivo'} | |
""" | |
return fig, interpretation | |
def generate_marketing_content(prompt, type_content, tone): | |
"""Geração de conteúdo de marketing usando T5""" | |
formatted_prompt = f"Generate {type_content} in {tone} tone: {prompt}" | |
# Gerando conteúdo | |
response = text_generator(formatted_prompt, max_length=200, min_length=50) | |
generated_text = response[0]['generated_text'] | |
# Extração de palavras-chave para sugestões | |
keywords = kw_model.extract_keywords(generated_text, keyphrase_ngram_range=(1, 2), stop_words='english', top_n=5) | |
suggestions = f""" | |
🎯 Sugestões de Hashtags/Keywords: | |
{', '.join([f'#{k[0].replace(" ", "")}' for k in keywords])} | |
📈 Métricas de Conteúdo: | |
- Comprimento: {len(generated_text.split())} palavras | |
- Tom: {tone} | |
- Tipo: {type_content} | |
""" | |
return generated_text, suggestions | |
def analyze_keywords(text, max_keywords=10): | |
"""Análise avançada de palavras-chave usando múltiplos modelos""" | |
# KeyBERT análise | |
keybert_keywords = kw_model.extract_keywords(text, keyphrase_ngram_range=(1, 2), | |
stop_words='english', top_n=max_keywords) | |
# YAKE análise | |
yake_keywords = yake_extractor.extract_keywords(text) | |
# Criando visualização | |
fig, ax = plt.subplots(figsize=(10, 6)) | |
# Combinando e normalizando scores | |
all_keywords = {} | |
for k, v in keybert_keywords: | |
all_keywords[k] = v | |
for k, v in yake_keywords[:max_keywords]: | |
if k in all_keywords: | |
all_keywords[k] = (all_keywords[k] + (1-v))/2 | |
else: | |
all_keywords[k] = 1-v | |
# Plotando | |
keywords_df = pd.DataFrame(list(all_keywords.items()), columns=['Keyword', 'Score']) | |
keywords_df = keywords_df.sort_values('Score', ascending=True) | |
sns.barplot(x='Score', y='Keyword', data=keywords_df, ax=ax) | |
ax.set_title('Análise de Palavras-chave') | |
# Preparando relatório | |
report = f""" | |
🔑 Palavras-chave Principais: | |
{', '.join([f'{k} ({v:.2f})' for k, v in sorted(all_keywords.items(), key=lambda x: x[1], reverse=True)])} | |
💡 Recomendações: | |
- Foque nas palavras-chave com maior pontuação | |
- Use variações das palavras principais | |
- Combine keywords para frases longtail | |
""" | |
return fig, report | |
def analyze_content_engagement(text): | |
"""Análise de potencial de engajamento do conteúdo""" | |
# Análise básica | |
word_count = len(text.split()) | |
sentence_count = len(text.split('.')) | |
avg_word_length = sum(len(word) for word in text.split()) / word_count | |
# Análise de sentimento para tom | |
blob = TextBlob(text) | |
sentiment = blob.sentiment | |
# Criando visualização | |
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5)) | |
# Métricas de texto | |
metrics = pd.DataFrame({ | |
'Métrica': ['Palavras', 'Sentenças', 'Média Palavra'], | |
'Valor': [word_count, sentence_count, avg_word_length] | |
}) | |
sns.barplot(x='Métrica', y='Valor', data=metrics, ax=ax1) | |
ax1.set_title('Métricas do Texto') | |
# Engagement score | |
engagement_factors = { | |
'Comprimento': min(1, word_count/300), | |
'Clareza': min(1, 20/avg_word_length), | |
'Emoção': (sentiment.polarity + 1)/2, | |
'Estrutura': min(1, sentence_count/15) | |
} | |
engagement_df = pd.DataFrame(list(engagement_factors.items()), | |
columns=['Fator', 'Score']) | |
sns.barplot(x='Fator', y='Score', data=engagement_df, ax=ax2) | |
ax2.set_title('Fatores de Engajamento') | |
# Calculando score geral | |
engagement_score = sum(engagement_factors.values())/len(engagement_factors) | |
analysis = f""" | |
📊 Análise de Engajamento: | |
Score Geral: {engagement_score:.2f}/1.0 | |
📝 Métricas do Texto: | |
- Palavras: {word_count} | |
- Sentenças: {sentence_count} | |
- Média de caracteres por palavra: {avg_word_length:.1f} | |
💡 Recomendações: | |
{get_engagement_recommendations(engagement_factors)} | |
""" | |
return fig, analysis | |
def get_engagement_recommendations(factors): | |
"""Gera recomendações baseadas nos fatores de engajamento""" | |
recommendations = [] | |
if factors['Comprimento'] < 0.7: | |
recommendations.append("- Considere aumentar o comprimento do texto") | |
if factors['Clareza'] < 0.7: | |
recommendations.append("- Use palavras mais simples para melhorar clareza") | |
if factors['Emoção'] < 0.5: | |
recommendations.append("- Adicione mais elementos emocionais ao conteúdo") | |
if factors['Estrutura'] < 0.7: | |
recommendations.append("- Melhore a estrutura com mais parágrafos") | |
return '\n'.join(recommendations) if recommendations else "- Conteúdo bem otimizado!" | |
def create_interface(): | |
with gr.Blocks(theme=gr.themes.Soft()) as iface: | |
gr.Markdown( | |
""" | |
# 🚀 Suite de Ferramentas IA para Marketing Digital | |
### Ferramentas open source para otimização de conteúdo e análise | |
""" | |
) | |
with gr.Tab("1. Análise de Sentimento"): | |
with gr.Row(): | |
with gr.Column(): | |
sentiment_text = gr.Textbox( | |
label="Texto para Análise", | |
placeholder="Cole seu texto aqui para análise de sentimento..." | |
) | |
sentiment_btn = gr.Button("Analisar Sentimento") | |
with gr.Column(): | |
sentiment_plot = gr.Plot(label="Visualização") | |
sentiment_output = gr.Textbox(label="Análise Detalhada") | |
sentiment_btn.click( | |
analyze_sentiment_detailed, | |
inputs=[sentiment_text], | |
outputs=[sentiment_plot, sentiment_output] | |
) | |
with gr.Tab("2. Gerador de Conteúdo"): | |
with gr.Row(): | |
with gr.Column(): | |
content_prompt = gr.Textbox( | |
label="Tema/Prompt", | |
placeholder="Descreva o conteúdo que deseja gerar..." | |
) | |
content_type = gr.Dropdown( | |
choices=["social media post", "blog post", "marketing copy", "email"], | |
label="Tipo de Conteúdo" | |
) | |
content_tone = gr.Dropdown( | |
choices=["professional", "casual", "enthusiastic", "formal"], | |
label="Tom do Conteúdo" | |
) | |
content_btn = gr.Button("Gerar Conteúdo") | |
with gr.Column(): | |
generated_content = gr.Textbox(label="Conteúdo Gerado") | |
content_suggestions = gr.Textbox(label="Sugestões e Métricas") | |
content_btn.click( | |
generate_marketing_content, | |
inputs=[content_prompt, content_type, content_tone], | |
outputs=[generated_content, content_suggestions] | |
) | |
with gr.Tab("3. Análise de Keywords"): | |
with gr.Row(): | |
with gr.Column(): | |
keyword_text = gr.Textbox( | |
label="Texto para Análise", | |
placeholder="Cole seu texto para análise de palavras-chave..." | |
) | |
keyword_count = gr.Slider( | |
minimum=5, maximum=20, value=10, | |
label="Número de Keywords" | |
) | |
keyword_btn = gr.Button("Analisar Keywords") | |
with gr.Column(): | |
keyword_plot = gr.Plot(label="Visualização") | |
keyword_report = gr.Textbox(label="Relatório de Keywords") | |
keyword_btn.click( | |
analyze_keywords, | |
inputs=[keyword_text, keyword_count], | |
outputs=[keyword_plot, keyword_report] | |
) | |
with gr.Tab("4. Análise de Engajamento"): | |
with gr.Row(): | |
with gr.Column(): | |
engagement_text = gr.Textbox( | |
label="Conteúdo para Análise", | |
placeholder="Cole seu conteúdo para análise de engajamento..." | |
) | |
engagement_btn = gr.Button("Analisar Engajamento") | |
with gr.Column(): | |
engagement_plot = gr.Plot(label="Métricas de Engajamento") | |
engagement_analysis = gr.Textbox(label="Análise de Engajamento") | |
engagement_btn.click( | |
analyze_content_engagement, | |
inputs=[engagement_text], | |
outputs=[engagement_plot, engagement_analysis] | |
) | |
gr.Markdown( | |
""" | |
### 🛠️ Ferramentas Disponíveis: | |
1. **Análise de Sentimento** | |
- Análise detalhada do tom e sentimento do texto | |
- Visualização de métricas emocionais | |
2. **Gerador de Conteúdo** | |
- Criação de conteúdo otimizado para marketing | |
- Sugestões de hashtags e keywords | |
3. **Análise de Keywords** | |
- Identificação de palavras-chave relevantes | |
- Análise de densidade e importância | |
4. **Análise de Engajamento** | |
- Avaliação do potencial de engajamento | |
- Recomendações para otimização | |
### 📝 Notas: | |
- Todas as ferramentas utilizam modelos open source | |
- Os resultados são gerados localmente | |
- Recomendado para textos em português e inglês | |
""" | |
) | |
return iface | |
if __name__ == "__main__": | |
iface = create_interface() | |
iface.launch(share=True) | |