File size: 14,340 Bytes
0875db0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32e190b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
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()