InspiraLead / app.py
DHEIVER's picture
Update app.py
0875db0 verified
raw
history blame
14.3 kB
import gradio as gr
from datetime import datetime
import numpy as np
from typing import Dict, List, Tuple, Optional
import matplotlib.pyplot as plt
from wordcloud import WordCloud
import seaborn as sns
import pandas as pd
from collections import Counter
def analyze_sentiment_trend(respostas: list[str]) -> Optional[plt.Figure]:
"""Generate sentiment analysis plot"""
# Create coach instance for sentiment analysis
sentimentos = []
# Convert sentiments to numeric values
valor_sentimento = {
'positive': 1,
'neutral': 0,
'improvement': -1
}
# Analyze each response
for resp in respostas:
palavras_positivas = ["consegui", "superei", "aprendi", "melhorei", "efetivo"]
palavras_negativas = ["difícil", "desafiador", "complicado", "problema", "falha"]
texto_lower = resp.lower()
cont_positivas = sum(1 for word in palavras_positivas if word in texto_lower)
cont_negativas = sum(1 for word in palavras_negativas if word in texto_lower)
if cont_positivas > cont_negativas:
sentimentos.append("positive")
elif cont_negativas > cont_positivas:
sentimentos.append("improvement")
else:
sentimentos.append("neutral")
valores = [valor_sentimento[s] for s in sentimentos]
if not valores:
return None
# Create the plot
fig, ax = plt.subplots(figsize=(8, 4))
sns.lineplot(data=valores, marker='o', ax=ax)
ax.set_title('Tendência de Sentimento nas Respostas')
ax.set_xlabel('Número da Resposta')
ax.set_ylabel('Sentimento')
ax.set_ylim(-1.5, 1.5)
ax.grid(True)
# Add horizontal lines for reference
ax.axhline(y=0, color='gray', linestyle='--', alpha=0.5)
plt.close()
return fig
def generate_word_cloud(respostas: list[str]) -> Optional[plt.Figure]:
"""Generate word cloud visualization"""
if not respostas:
return None
# Combine all responses
texto_completo = ' '.join(respostas)
# Create word cloud
wordcloud = WordCloud(
width=800,
height=400,
background_color='white',
colormap='viridis',
max_words=100
).generate(texto_completo)
# Create the plot
fig, ax = plt.subplots(figsize=(10, 5))
ax.imshow(wordcloud, interpolation='bilinear')
ax.axis('off')
ax.set_title('Nuvem de Palavras das Reflexões')
plt.close()
return fig
def analyze_themes(respostas: list[str]) -> tuple[str, str]:
"""Analyze strong themes and development areas"""
temas_fortes = []
areas_desenvolvimento = []
for resp in respostas:
palavras_positivas = ["consegui", "superei", "aprendi", "melhorei", "efetivo"]
palavras_negativas = ["difícil", "desafiador", "complicado", "problema", "falha"]
texto_lower = resp.lower()
cont_positivas = sum(1 for word in palavras_positivas if word in texto_lower)
cont_negativas = sum(1 for word in palavras_negativas if word in texto_lower)
# Extract specific action
sentences = resp.split('.')
for sentence in sentences:
if any(action in sentence.lower() for action in ["eu", "minha", "realizei", "fiz"]):
if cont_positivas > cont_negativas:
temas_fortes.append("- " + sentence.strip())
elif cont_negativas > cont_positivas:
areas_desenvolvimento.append("- " + sentence.strip())
break
else:
acao = resp.split('.')[0].strip()
if cont_positivas > cont_negativas:
temas_fortes.append("- " + acao)
elif cont_negativas > cont_positivas:
areas_desenvolvimento.append("- " + acao)
temas_fortes_str = "\n".join(temas_fortes[:3]) if temas_fortes else "Análise em andamento..."
areas_desenvolvimento_str = "\n".join(areas_desenvolvimento[:3]) if areas_desenvolvimento else "Análise em andamento..."
return temas_fortes_str, areas_desenvolvimento_str
def analyze_sentiment_trend(respostas: List[str]) -> plt.Figure:
"""Generate sentiment analysis plot"""
coach = EnhancedCoach()
sentimentos = [coach.analisar_sentimento(resp) for resp in respostas]
# Convert sentiments to numeric values
valor_sentimento = {
'positive': 1,
'neutral': 0,
'improvement': -1
}
valores = [valor_sentimento[s] for s in sentimentos]
# Create the plot
fig, ax = plt.subplots(figsize=(8, 4))
sns.lineplot(data=valores, marker='o', ax=ax)
ax.set_title('Tendência de Sentimento nas Respostas')
ax.set_xlabel('Número da Resposta')
ax.set_ylabel('Sentimento')
ax.set_ylim(-1.5, 1.5)
ax.grid(True)
# Add horizontal lines for reference
ax.axhline(y=0, color='gray', linestyle='--', alpha=0.5)
return fig
def generate_word_cloud(respostas: List[str]) -> plt.Figure:
"""Generate word cloud visualization"""
# Combine all responses
texto_completo = ' '.join(respostas)
# Create word cloud
wordcloud = WordCloud(
width=800,
height=400,
background_color='white',
colormap='viridis',
max_words=100
).generate(texto_completo)
# Create the plot
fig, ax = plt.subplots(figsize=(10, 5))
ax.imshow(wordcloud, interpolation='bilinear')
ax.axis('off')
ax.set_title('Nuvem de Palavras das Reflexões')
return fig
def analyze_themes(respostas: List[str]) -> Tuple[str, str]:
"""Analyze strong themes and development areas"""
coach = EnhancedCoach()
temas_fortes = []
areas_desenvolvimento = []
for resp in respostas:
sentimento = coach.analisar_sentimento(resp)
if sentimento == "positive":
temas_fortes.append("- " + coach.extrair_acao_especifica(resp))
elif sentimento == "improvement":
areas_desenvolvimento.append("- " + coach.extrair_acao_especifica(resp))
temas_fortes_str = "\n".join(temas_fortes[:3]) if temas_fortes else "Análise em andamento..."
areas_desenvolvimento_str = "\n".join(areas_desenvolvimento[:3]) if areas_desenvolvimento else "Análise em andamento..."
return temas_fortes_str, areas_desenvolvimento_str
def criar_interface():
coach = EnhancedCoach()
with gr.Blocks(title="Coach de Liderança", theme=gr.themes.Soft()) as app:
with gr.Row():
with gr.Column(scale=2):
gr.Markdown("""
# 🚀 Coach de Liderança
Desenvolva sua liderança através de reflexão guiada e feedback personalizado.
""")
with gr.Column(scale=1):
timer = gr.Number(
value=0,
label="⏱️ Tempo de Reflexão (minutos)",
interactive=False
)
progress = gr.Slider(
value=0,
minimum=0,
maximum=len(PERGUNTAS),
step=1,
label="📊 Progresso",
interactive=False
)
with gr.Tabs() as tabs:
with gr.Tab("💭 Sessão Atual"):
chat = gr.Chatbot(
value=[[None, coach.primeira_pergunta()]],
height=500,
show_label=False,
type="messages"
)
with gr.Row():
with gr.Column(scale=4):
txt = gr.Textbox(
placeholder="Compartilhe sua reflexão aqui...",
lines=4,
label="Sua Resposta"
)
with gr.Column(scale=1, min_width=100):
with gr.Row():
btn = gr.Button("Enviar", variant="primary")
clear = gr.Button("Limpar")
with gr.Row():
tema_atual = gr.Textbox(
value="Autoconhecimento",
label="🎯 Tema Atual",
interactive=False
)
tempo_resposta = gr.Textbox(
value="0:00",
label="⏱️ Tempo nesta resposta",
interactive=False
)
with gr.Tab("📊 Insights"):
with gr.Row():
with gr.Column():
sentiment_chart = gr.Plot(label="Análise de Sentimento")
with gr.Column():
word_cloud = gr.Plot(label="Nuvem de Palavras")
with gr.Row():
temas_fortes = gr.Textbox(
label="💪 Temas com Mais Confiança",
interactive=False,
lines=3
)
areas_desenvolvimento = gr.Textbox(
label="🎯 Áreas para Desenvolvimento",
interactive=False,
lines=3
)
with gr.Tab("📝 Notas & Recursos"):
with gr.Row():
notas = gr.Textbox(
placeholder="Faça anotações durante sua jornada...",
label="📝 Minhas Notas",
lines=5
)
with gr.Row():
with gr.Accordion("📚 Recursos por Tema", open=False):
gr.Markdown("""
### 🎯 Autoconhecimento
- [Artigo] Desenvolvendo Autoconsciência na Liderança
- [Exercício] Reflexão sobre Valores e Propósito
- [Ferramenta] Template de Diário de Liderança
### 💬 Comunicação
- [Guia] Comunicação Assertiva na Liderança
- [Checklist] Preparação para Feedbacks Difíceis
- [Framework] Estrutura de Comunicação Situacional
### 🤔 Tomada de Decisão
- [Modelo] Framework para Decisões Complexas
- [Exercício] Análise de Decisões Passadas
- [Template] Documentação de Decisões Importantes
""")
def atualizar_timer():
"""Update session timer"""
tempo = int((datetime.now() - coach.inicio).total_seconds() / 60)
return tempo
def responder(mensagem, historico):
"""Process user response and update interface"""
if not mensagem.strip():
return {
txt: "",
chat: historico
}
# Format user message
msg_usuario = {
"role": "user",
"content": mensagem
}
# Generate and format coach response
resposta = coach.gerar_resposta(mensagem)
# Update history
historico.append([msg_usuario, resposta])
# Update visualizations
sentiment_analysis = None
word_cloud_plot = None
strong_themes = ""
development_areas = ""
if len(coach.historico_respostas) > 1:
sentiment_analysis = analyze_sentiment_trend(coach.historico_respostas)
word_cloud_plot = generate_word_cloud(coach.historico_respostas)
strong_themes, development_areas = analyze_themes(coach.historico_respostas)
tempo_atual = int((datetime.now() - coach.inicio).total_seconds() / 60)
return {
txt: "",
chat: historico,
timer: tempo_atual,
progress: coach.pergunta_atual,
tema_atual: PERGUNTAS[min(coach.pergunta_atual, len(PERGUNTAS)-1)]["categoria"].title(),
tempo_resposta: "0:00",
sentiment_chart: sentiment_analysis,
word_cloud: word_cloud_plot,
temas_fortes: strong_themes,
areas_desenvolvimento: development_areas
}
def limpar_chat():
"""Reset chat and all related components"""
coach.__init__()
primeira_mensagem = coach.primeira_pergunta()
return {
chat: [[None, primeira_mensagem]],
txt: "",
progress: 0,
tema_atual: "Autoconhecimento",
tempo_resposta: "0:00",
sentiment_chart: None,
word_cloud: None,
temas_fortes: "",
areas_desenvolvimento: ""
}
# Event handlers
txt.submit(
responder,
[txt, chat],
[txt, chat, timer, progress, tema_atual, tempo_resposta,
sentiment_chart, word_cloud, temas_fortes, areas_desenvolvimento]
)
btn.click(
responder,
[txt, chat],
[txt, chat, timer, progress, tema_atual, tempo_resposta,
sentiment_chart, word_cloud, temas_fortes, areas_desenvolvimento]
)
clear.click(
limpar_chat,
None,
[chat, txt, progress, tema_atual, tempo_resposta,
sentiment_chart, word_cloud, temas_fortes, areas_desenvolvimento]
)
# Timer update
gr.on(
triggers=[gr.EventListener(every=1)],
fn=atualizar_timer,
outputs=[timer]
)
return app
if __name__ == "__main__":
app = criar_interface()
app.launch()