Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -1,177 +1,226 @@
|
|
1 |
-
# app.py
|
2 |
import gradio as gr
|
3 |
-
from transformers import
|
4 |
import json
|
5 |
-
import os
|
6 |
import sqlite3
|
7 |
from datetime import datetime, timedelta
|
8 |
import pandas as pd
|
|
|
9 |
from typing import Dict, List, Optional
|
|
|
|
|
|
|
|
|
10 |
|
11 |
-
class
|
12 |
-
|
13 |
-
self.conn = sqlite3.connect('revalida.db')
|
14 |
-
self.create_tables()
|
15 |
-
self.load_previous_questions()
|
16 |
|
17 |
-
def
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
self.conn.execute('''
|
30 |
-
CREATE TABLE IF NOT EXISTS study_progress (
|
31 |
-
user_id TEXT,
|
32 |
-
date DATE,
|
33 |
-
topic TEXT,
|
34 |
-
hours_studied FLOAT,
|
35 |
-
questions_answered INTEGER,
|
36 |
-
performance_score FLOAT,
|
37 |
-
FOREIGN KEY (user_id) REFERENCES users(user_id)
|
38 |
-
)''')
|
39 |
-
|
40 |
-
self.conn.execute('''
|
41 |
-
CREATE TABLE IF NOT EXISTS previous_questions (
|
42 |
-
id INTEGER PRIMARY KEY,
|
43 |
-
year INTEGER,
|
44 |
-
area TEXT,
|
45 |
-
question_text TEXT,
|
46 |
-
options TEXT,
|
47 |
-
correct_answer TEXT,
|
48 |
-
explanation TEXT
|
49 |
-
)''')
|
50 |
|
51 |
-
self.
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
except Exception as e:
|
68 |
-
print(f"Erro ao carregar questões: {e}")
|
69 |
|
70 |
-
class
|
71 |
-
|
72 |
-
self.db = db
|
73 |
|
74 |
-
def
|
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 |
-
for week in range(total_days // 7 + 1):
|
105 |
-
schedule[f"Semana {week+1}"] = {
|
106 |
-
topic: round(hours * available_hours * topics[topic], 1)
|
107 |
-
for topic in topics
|
108 |
-
}
|
109 |
|
110 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
111 |
|
112 |
-
class
|
|
|
|
|
113 |
def __init__(self):
|
114 |
self.db = RevalidaDatabase()
|
115 |
self.planner = StudyPlanGenerator(self.db)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
116 |
|
117 |
-
# Modelo de linguagem
|
118 |
-
self.model_id = "meta-llama/Llama-2-7b-chat-hf"
|
119 |
-
self.tokenizer = AutoTokenizer.from_pretrained(self.model_id)
|
120 |
-
self.pipeline = pipeline(
|
121 |
-
"text-generation",
|
122 |
-
model=self.model_id,
|
123 |
-
tokenizer=self.tokenizer,
|
124 |
-
max_length=500
|
125 |
-
)
|
126 |
-
|
127 |
-
# Comandos disponíveis
|
128 |
self.commands = {
|
129 |
"/start": self.start_command,
|
130 |
"/plano": self.create_plan,
|
131 |
"/progresso": self.check_progress,
|
132 |
"/questoes": self.previous_questions,
|
133 |
"/estudo": self.study_mode,
|
|
|
|
|
|
|
134 |
"/ajuda": self.help_command
|
135 |
}
|
136 |
-
|
137 |
-
def
|
138 |
-
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
139 |
try:
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
|
|
|
|
|
|
145 |
|
146 |
-
|
|
|
|
|
|
|
|
|
|
|
147 |
|
148 |
except Exception as e:
|
149 |
-
return f"
|
150 |
|
151 |
def create_plan(self, message: str, user_id: str) -> str:
|
152 |
-
"""
|
153 |
try:
|
154 |
-
# Extrai parâmetros da mensagem
|
155 |
-
# Formato: /plano horas_diarias YYYY-MM-DD área1,área2
|
156 |
parts = message.split()
|
157 |
if len(parts) < 3:
|
158 |
-
return "
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
163 |
|
164 |
-
|
165 |
-
user_id, hours, target_date, weak_areas
|
166 |
-
)
|
167 |
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
|
|
|
|
|
|
|
|
|
|
|
175 |
|
176 |
return response
|
177 |
|
@@ -179,108 +228,120 @@ class RevalidaBot:
|
|
179 |
return f"Erro ao criar plano: {str(e)}"
|
180 |
|
181 |
def check_progress(self, message: str, user_id: str) -> str:
|
182 |
-
"""Verifica progresso
|
183 |
try:
|
184 |
-
|
185 |
-
cursor.execute('''
|
186 |
-
SELECT topic, SUM(hours_studied) as total_hours,
|
187 |
-
AVG(performance_score) as avg_score
|
188 |
-
FROM study_progress
|
189 |
-
WHERE user_id = ?
|
190 |
-
GROUP BY topic
|
191 |
-
''', (user_id,))
|
192 |
|
193 |
-
|
194 |
-
|
195 |
-
response = "📊 Seu Progresso:\n\n"
|
196 |
-
for topic, hours, score in progress:
|
197 |
-
response += f"{topic}:\n"
|
198 |
-
response += f"- Horas estudadas: {hours:.1f}h\n"
|
199 |
-
response += f"- Desempenho médio: {score:.1f}%\n\n"
|
200 |
-
|
201 |
-
return response
|
202 |
-
|
203 |
-
except Exception as e:
|
204 |
-
return f"Erro ao verificar progresso: {str(e)}"
|
205 |
|
206 |
-
|
207 |
-
|
208 |
-
|
209 |
-
|
210 |
-
parts = message.split()
|
211 |
-
if len(parts) < 2:
|
212 |
-
return "Formato: /questoes área [ano]"
|
213 |
-
|
214 |
-
area = parts[1]
|
215 |
-
year = int(parts[2]) if len(parts) > 2 else None
|
216 |
-
|
217 |
-
cursor = self.db.conn.cursor()
|
218 |
-
if year:
|
219 |
-
cursor.execute('''
|
220 |
-
SELECT question_text, options, correct_answer, explanation
|
221 |
-
FROM previous_questions
|
222 |
-
WHERE area = ? AND year = ?
|
223 |
-
ORDER BY RANDOM()
|
224 |
-
LIMIT 1
|
225 |
-
''', (area, year))
|
226 |
-
else:
|
227 |
-
cursor.execute('''
|
228 |
-
SELECT question_text, options, correct_answer, explanation
|
229 |
-
FROM previous_questions
|
230 |
-
WHERE area = ?
|
231 |
-
ORDER BY RANDOM()
|
232 |
-
LIMIT 1
|
233 |
-
''', (area,))
|
234 |
|
235 |
-
|
236 |
-
|
237 |
-
|
|
|
238 |
|
239 |
-
|
240 |
-
|
241 |
-
for letter, text in options.items():
|
242 |
-
response += f"{letter}) {text}\n"
|
243 |
-
response += f"\nResposta: {question[2]}\n"
|
244 |
-
response += f"Explicação: {question[3]}"
|
245 |
|
246 |
return response
|
247 |
|
248 |
except Exception as e:
|
249 |
-
return f"Erro ao
|
250 |
|
251 |
def study_mode(self, message: str, user_id: str) -> str:
|
252 |
-
"""
|
253 |
try:
|
254 |
-
# Formato: /estudo área horas
|
255 |
parts = message.split()
|
256 |
if len(parts) < 3:
|
257 |
-
return "
|
|
|
|
|
|
|
|
|
258 |
|
259 |
area = parts[1]
|
260 |
-
|
261 |
|
262 |
-
# Registra estudo
|
263 |
cursor = self.db.conn.cursor()
|
264 |
cursor.execute('''
|
265 |
INSERT INTO study_progress
|
266 |
-
(user_id, date, topic,
|
267 |
VALUES (?, ?, ?, ?, ?, ?)
|
268 |
-
''', (user_id, datetime.now().date(), area,
|
269 |
self.db.conn.commit()
|
270 |
|
271 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
272 |
|
273 |
except Exception as e:
|
274 |
return f"Erro ao registrar estudo: {str(e)}"
|
275 |
|
276 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
277 |
|
278 |
def create_interface():
|
279 |
-
"""
|
280 |
-
bot =
|
281 |
|
282 |
-
with gr.Blocks(title="Assistente Revalida") as interface:
|
283 |
-
gr.Markdown("# 🏥
|
284 |
gr.Markdown("### Seu mentor personalizado para o Revalida")
|
285 |
|
286 |
with gr.Row():
|
@@ -297,19 +358,15 @@ def create_interface():
|
|
297 |
)
|
298 |
clear = gr.ClearButton([msg, chatbot])
|
299 |
|
300 |
-
def
|
301 |
-
|
302 |
-
|
|
|
303 |
|
304 |
-
msg.submit(
|
305 |
-
process_message_with_user,
|
306 |
-
[msg, chatbot],
|
307 |
-
[chatbot]
|
308 |
-
)
|
309 |
|
310 |
return interface
|
311 |
|
312 |
-
# Inicia a interface
|
313 |
if __name__ == "__main__":
|
314 |
interface = create_interface()
|
315 |
interface.launch()
|
|
|
|
|
1 |
import gradio as gr
|
2 |
+
from transformers import pipeline
|
3 |
import json
|
|
|
4 |
import sqlite3
|
5 |
from datetime import datetime, timedelta
|
6 |
import pandas as pd
|
7 |
+
import random
|
8 |
from typing import Dict, List, Optional
|
9 |
+
from performance_system import PerformanceAnalyzer
|
10 |
+
from simulado_system import SimuladoSystem, CasoClinicoSystem
|
11 |
+
from database.db_manager import RevalidaDatabase
|
12 |
+
from performance_system import PerformanceAnalyzer, StudyMaterialGenerator, ProgressTracker
|
13 |
|
14 |
+
class MotivationalCoach:
|
15 |
+
"""Classe para gerenciar mensagens e estratégias motivacionais"""
|
|
|
|
|
|
|
16 |
|
17 |
+
def __init__(self):
|
18 |
+
self.frases_motivacionais = [
|
19 |
+
"🌟 Cada hora de estudo te aproxima mais do seu objetivo!",
|
20 |
+
"💪 Você está construindo seu futuro a cada dia!",
|
21 |
+
"🎯 Mantenha o foco! O Revalida é só uma etapa da sua jornada de sucesso!",
|
22 |
+
"⭐ Sua dedicação é inspiradora! Continue assim!",
|
23 |
+
"🌈 Acredite no seu potencial! Você está no caminho certo!",
|
24 |
+
"📚 Conhecimento é poder, e você está ficando mais forte a cada dia!",
|
25 |
+
"🌅 Um novo dia, uma nova oportunidade de aprender!",
|
26 |
+
"🎓 Sua aprovação no Revalida está cada vez mais próxima!"
|
27 |
+
]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
28 |
|
29 |
+
self.dicas_estudo = [
|
30 |
+
"📌 Faça pequenas pausas a cada 45 minutos de estudo",
|
31 |
+
"💡 Revise o conteúdo do dia antes de dormir",
|
32 |
+
"🎯 Estabeleça metas diárias pequenas e alcançáveis",
|
33 |
+
"📊 Alterne entre diferentes tópicos para manter o interesse",
|
34 |
+
"🌟 Pratique questões antigas do Revalida regularmente",
|
35 |
+
"💪 Mantenha uma rotina regular de estudos",
|
36 |
+
"🧠 Use mapas mentais para conectar conceitos",
|
37 |
+
"📝 Faça resumos ativos do conteúdo estudado"
|
38 |
+
]
|
39 |
+
|
40 |
+
def get_motivational_message(self) -> str:
|
41 |
+
return random.choice(self.frases_motivacionais)
|
42 |
+
|
43 |
+
def get_study_tip(self) -> str:
|
44 |
+
return random.choice(self.dicas_estudo)
|
|
|
|
|
45 |
|
46 |
+
class StudyAnalytics:
|
47 |
+
"""Classe para análise avançada do progresso do estudante"""
|
|
|
48 |
|
49 |
+
def __init__(self, db_connection):
|
50 |
+
self.conn = db_connection
|
51 |
+
|
52 |
+
def calculate_study_metrics(self, user_id: str) -> Dict:
|
53 |
+
"""Calcula métricas avançadas de estudo"""
|
54 |
+
cursor = self.conn.cursor()
|
55 |
|
56 |
+
# Horas totais de estudo
|
57 |
+
cursor.execute('''
|
58 |
+
SELECT SUM(horas_estudadas) FROM study_progress
|
59 |
+
WHERE user_id = ?
|
60 |
+
''', (user_id,))
|
61 |
+
total_horas = cursor.fetchone()[0] or 0
|
62 |
|
63 |
+
# Desempenho por área
|
64 |
+
cursor.execute('''
|
65 |
+
SELECT topic, AVG(performance_score)
|
66 |
+
FROM study_progress
|
67 |
+
WHERE user_id = ?
|
68 |
+
GROUP BY topic
|
69 |
+
''', (user_id,))
|
70 |
+
desempenho_por_area = dict(cursor.fetchall())
|
|
|
71 |
|
72 |
+
# Consistência de estudos (dias consecutivos)
|
73 |
+
cursor.execute('''
|
74 |
+
SELECT date FROM study_progress
|
75 |
+
WHERE user_id = ?
|
76 |
+
ORDER BY date DESC
|
77 |
+
''', (user_id,))
|
78 |
+
datas = [row[0] for row in cursor.fetchall()]
|
79 |
+
dias_consecutivos = self.calculate_streak(datas)
|
80 |
|
81 |
+
return {
|
82 |
+
"total_horas": total_horas,
|
83 |
+
"desempenho_por_area": desempenho_por_area,
|
84 |
+
"dias_consecutivos": dias_consecutivos
|
85 |
+
}
|
86 |
+
|
87 |
+
@staticmethod
|
88 |
+
def calculate_streak(dates: List[str]) -> int:
|
89 |
+
if not dates:
|
90 |
+
return 0
|
91 |
|
92 |
+
dates = [datetime.strptime(d, '%Y-%m-%d').date() for d in dates]
|
93 |
+
dates.sort(reverse=True)
|
|
|
|
|
|
|
|
|
|
|
94 |
|
95 |
+
streak = 1
|
96 |
+
for i in range(len(dates)-1):
|
97 |
+
if (dates[i] - dates[i+1]).days == 1:
|
98 |
+
streak += 1
|
99 |
+
else:
|
100 |
+
break
|
101 |
+
return streak
|
102 |
|
103 |
+
class CRMJABot:
|
104 |
+
"""Assistente de estudos aprimorado para o Revalida"""
|
105 |
+
|
106 |
def __init__(self):
|
107 |
self.db = RevalidaDatabase()
|
108 |
self.planner = StudyPlanGenerator(self.db)
|
109 |
+
self.coach = MotivationalCoach()
|
110 |
+
self.analytics = StudyAnalytics(self.db.conn)
|
111 |
+
self.performance = PerformanceAnalyzer(self.db.conn)
|
112 |
+
self.material_gen = StudyMaterialGenerator(self.db.conn)
|
113 |
+
self.tracker = ProgressTracker(self.db.conn)
|
114 |
+
|
115 |
+
try:
|
116 |
+
self.qa_pipeline = pipeline(
|
117 |
+
"question-answering",
|
118 |
+
model="pierreguillou/bert-base-cased-squad-v1.1-portuguese",
|
119 |
+
device=-1
|
120 |
+
)
|
121 |
+
except Exception as e:
|
122 |
+
print(f"Erro ao carregar o modelo: {e}")
|
123 |
+
self.qa_pipeline = None
|
124 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
125 |
self.commands = {
|
126 |
"/start": self.start_command,
|
127 |
"/plano": self.create_plan,
|
128 |
"/progresso": self.check_progress,
|
129 |
"/questoes": self.previous_questions,
|
130 |
"/estudo": self.study_mode,
|
131 |
+
"/dica": self.get_tip,
|
132 |
+
"/motiva": self.get_motivation,
|
133 |
+
"/resumo": self.get_summary,
|
134 |
"/ajuda": self.help_command
|
135 |
}
|
136 |
+
|
137 |
+
def start_command(self, message: str, user_id: str) -> str:
|
138 |
+
"""Mensagem inicial de boas-vindas"""
|
139 |
+
return f"""🌟 Olá! Eu sou o crmjaBot, seu assistente pessoal para o Revalida!
|
140 |
+
|
141 |
+
Estou aqui para te ajudar a alcançar seu objetivo de aprovação! Vamos juntos nessa jornada?
|
142 |
+
|
143 |
+
Comandos principais:
|
144 |
+
📚 /plano - Criar plano de estudos personalizado
|
145 |
+
📊 /progresso - Verificar seu progresso
|
146 |
+
📝 /questoes - Praticar questões anteriores
|
147 |
+
⏱ /estudo - Registrar sessão de estudo
|
148 |
+
💡 /dica - Receber dica de estudo
|
149 |
+
🌟 /motiva - Mensagem motivacional
|
150 |
+
📋 /resumo - Resumo do seu desempenho
|
151 |
+
❓ /ajuda - Ver todos os comandos
|
152 |
+
|
153 |
+
{self.coach.get_motivational_message()}
|
154 |
+
|
155 |
+
Como posso te ajudar hoje?"""
|
156 |
+
|
157 |
+
def get_tip(self, message: str, user_id: str) -> str:
|
158 |
+
"""Fornece dica de estudo"""
|
159 |
+
return f"💡 Dica do dia:\n\n{self.coach.get_study_tip()}"
|
160 |
+
|
161 |
+
def get_motivation(self, message: str, user_id: str) -> str:
|
162 |
+
"""Fornece mensagem motivacional"""
|
163 |
+
return f"✨ Mensagem motivacional:\n\n{self.coach.get_motivational_message()}"
|
164 |
+
|
165 |
+
def get_summary(self, message: str, user_id: str) -> str:
|
166 |
+
"""Fornece resumo completo do progresso"""
|
167 |
try:
|
168 |
+
metrics = self.analytics.calculate_study_metrics(user_id)
|
169 |
+
|
170 |
+
response = f"""📊 Resumo do seu desempenho:
|
171 |
+
|
172 |
+
⏱ Total de horas estudadas: {metrics['total_horas']:.1f}h
|
173 |
+
🎯 Sequência atual: {metrics['dias_consecutivos']} dias consecutivos
|
174 |
+
|
175 |
+
📈 Desempenho por área:"""
|
176 |
|
177 |
+
for area, score in metrics['desempenho_por_area'].items():
|
178 |
+
response += f"\n- {area}: {score:.1f}%"
|
179 |
+
|
180 |
+
response += f"\n\n{self.coach.get_motivational_message()}"
|
181 |
+
|
182 |
+
return response
|
183 |
|
184 |
except Exception as e:
|
185 |
+
return f"Erro ao gerar resumo: {str(e)}"
|
186 |
|
187 |
def create_plan(self, message: str, user_id: str) -> str:
|
188 |
+
"""Criar plano de estudos personalizado com elementos motivacionais"""
|
189 |
try:
|
|
|
|
|
190 |
parts = message.split()
|
191 |
if len(parts) < 3:
|
192 |
+
return """📚 Para criar seu plano personalizado, preciso de algumas informações:
|
193 |
+
|
194 |
+
Formato: /plano horas_diarias AAAA-MM-DD área1,área2
|
195 |
+
|
196 |
+
Exemplo: /plano 4 2024-07-15 ClínicaMédica,Cirurgia
|
197 |
+
|
198 |
+
As áreas disponíveis são:
|
199 |
+
- ClínicaMédica
|
200 |
+
- Cirurgia
|
201 |
+
- Pediatria
|
202 |
+
- GinecologiaObstetrícia
|
203 |
+
- MedicinaFamília
|
204 |
+
- SaúdeMental"""
|
205 |
+
|
206 |
+
horas = int(parts[1])
|
207 |
+
data_alvo = parts[2]
|
208 |
+
areas_fracas = parts[3].split(',') if len(parts) > 3 else []
|
209 |
|
210 |
+
plano = self.planner.create_study_plan(user_id, horas, data_alvo, areas_fracas)
|
|
|
|
|
211 |
|
212 |
+
response = f"""✨ Seu Plano de Estudos Personalizado está pronto!
|
213 |
+
|
214 |
+
{self.coach.get_motivational_message()}
|
215 |
+
|
216 |
+
📚 Distribuição semanal:"""
|
217 |
+
|
218 |
+
for semana, topicos in plano.items():
|
219 |
+
response += f"\n\n📅 {semana}:"
|
220 |
+
for topico, horas in topicos.items():
|
221 |
+
response += f"\n ▪ {topico}: {horas}h"
|
222 |
+
|
223 |
+
response += f"\n\n💡 Dica: {self.coach.get_study_tip()}"
|
224 |
|
225 |
return response
|
226 |
|
|
|
228 |
return f"Erro ao criar plano: {str(e)}"
|
229 |
|
230 |
def check_progress(self, message: str, user_id: str) -> str:
|
231 |
+
"""Verifica o progresso com feedback motivacional"""
|
232 |
try:
|
233 |
+
metrics = self.analytics.calculate_study_metrics(user_id)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
234 |
|
235 |
+
response = f"""📊 Seu Progresso:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
236 |
|
237 |
+
⭐ Incrível! Você já estudou {metrics['total_horas']:.1f} horas no total!
|
238 |
+
🎯 Sequência atual: {metrics['dias_consecutivos']} dias consecutivos
|
239 |
+
|
240 |
+
📈 Desempenho por área:"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
241 |
|
242 |
+
for area, score in metrics['desempenho_por_area'].items():
|
243 |
+
response += f"\n ▪ {area}: {score:.1f}%"
|
244 |
+
|
245 |
+
response += f"\n\n{self.coach.get_motivational_message()}"
|
246 |
|
247 |
+
if metrics['dias_consecutivos'] >= 7:
|
248 |
+
response += "\n\n🏆 Parabéns pela dedicação consistente!"
|
|
|
|
|
|
|
|
|
249 |
|
250 |
return response
|
251 |
|
252 |
except Exception as e:
|
253 |
+
return f"Erro ao verificar progresso: {str(e)}"
|
254 |
|
255 |
def study_mode(self, message: str, user_id: str) -> str:
|
256 |
+
"""Registra sessão de estudo com feedback motivacional"""
|
257 |
try:
|
|
|
258 |
parts = message.split()
|
259 |
if len(parts) < 3:
|
260 |
+
return """📚 Para registrar seu estudo:
|
261 |
+
|
262 |
+
Formato: /estudo área horas
|
263 |
+
|
264 |
+
Exemplo: /estudo ClínicaMédica 2.5"""
|
265 |
|
266 |
area = parts[1]
|
267 |
+
horas = float(parts[2])
|
268 |
|
|
|
269 |
cursor = self.db.conn.cursor()
|
270 |
cursor.execute('''
|
271 |
INSERT INTO study_progress
|
272 |
+
(user_id, date, topic, horas_estudadas, questions_answered, performance_score)
|
273 |
VALUES (?, ?, ?, ?, ?, ?)
|
274 |
+
''', (user_id, datetime.now().date(), area, horas, 0, 0.0))
|
275 |
self.db.conn.commit()
|
276 |
|
277 |
+
metrics = self.analytics.calculate_study_metrics(user_id)
|
278 |
+
|
279 |
+
response = f"""✅ Ótimo trabalho! Registrei {horas}h de estudo em {area}
|
280 |
+
|
281 |
+
⭐ Total de horas estudadas: {metrics['total_horas']:.1f}h
|
282 |
+
🎯 Sequência atual: {metrics['dias_consecutivos']} dias
|
283 |
+
|
284 |
+
{self.coach.get_motivational_message()}
|
285 |
+
|
286 |
+
💡 Dica: {self.coach.get_study_tip()}"""
|
287 |
+
|
288 |
+
return response
|
289 |
|
290 |
except Exception as e:
|
291 |
return f"Erro ao registrar estudo: {str(e)}"
|
292 |
|
293 |
+
def generate_response(self, message: str, history: List) -> str:
|
294 |
+
"""Gera resposta personalizada usando o pipeline de QA"""
|
295 |
+
if not self.qa_pipeline:
|
296 |
+
return f"""Desculpe, o modelo de linguagem não está disponível no momento.
|
297 |
+
|
298 |
+
{self.coach.get_motivational_message()}
|
299 |
+
|
300 |
+
Use /ajuda para ver os comandos disponíveis!"""
|
301 |
+
|
302 |
+
try:
|
303 |
+
context = "\n".join([h[1] for h in history[-3:]] if history else "")
|
304 |
+
|
305 |
+
result = self.qa_pipeline(
|
306 |
+
question=message,
|
307 |
+
context=context or "Você é o crmjaBot, um assistente motivacional e educacional para o Revalida."
|
308 |
+
)
|
309 |
+
|
310 |
+
return f"""{result['answer']}
|
311 |
+
|
312 |
+
{self.coach.get_motivational_message()}"""
|
313 |
+
except Exception as e:
|
314 |
+
return f"Erro ao gerar resposta: {str(e)}"
|
315 |
+
|
316 |
+
def help_command(self, message: str, user_id: str) -> str:
|
317 |
+
"""Mostra todos os comandos disponíveis"""
|
318 |
+
return """🤖 Comandos do crmjaBot:
|
319 |
+
|
320 |
+
📚 Estudos:
|
321 |
+
/plano - Criar plano de estudos personalizado
|
322 |
+
/estudo - Registrar sessão de estudo
|
323 |
+
/questoes - Praticar questões anteriores
|
324 |
+
|
325 |
+
📊 Acompanhamento:
|
326 |
+
/progresso - Ver seu progresso
|
327 |
+
/resumo - Resumo completo do desempenho
|
328 |
+
|
329 |
+
✨ Motivacional:
|
330 |
+
/dica - Receber dica de estudo
|
331 |
+
/motiva - Mensagem motivacional
|
332 |
+
|
333 |
+
❓ Ajuda:
|
334 |
+
/start - Iniciar/reiniciar bot
|
335 |
+
/ajuda - Ver esta mensagem
|
336 |
+
|
337 |
+
Estou aqui para te ajudar! Como posso ser útil hoje?"""
|
338 |
|
339 |
def create_interface():
|
340 |
+
"""Criar interface Gradio"""
|
341 |
+
bot = CRMJABot()
|
342 |
|
343 |
+
with gr.Blocks(title="crmjaBot - Assistente Revalida") as interface:
|
344 |
+
gr.Markdown("# 🏥 crmjaBot")
|
345 |
gr.Markdown("### Seu mentor personalizado para o Revalida")
|
346 |
|
347 |
with gr.Row():
|
|
|
358 |
)
|
359 |
clear = gr.ClearButton([msg, chatbot])
|
360 |
|
361 |
+
def respond(message, history):
|
362 |
+
bot_message = bot.process_message(message, user_id.value or "default_user", history)
|
363 |
+
history.append((message, bot_message))
|
364 |
+
return "", history
|
365 |
|
366 |
+
msg.submit(respond, [msg, chatbot], [msg, chatbot])
|
|
|
|
|
|
|
|
|
367 |
|
368 |
return interface
|
369 |
|
|
|
370 |
if __name__ == "__main__":
|
371 |
interface = create_interface()
|
372 |
interface.launch()
|