Spaces:
Runtime error
Runtime error
File size: 11,044 Bytes
f26a057 be139a9 3d3112d f26a057 be139a9 3d3112d f26a057 3d3112d f26a057 3d3112d f26a057 3d3112d f26a057 3d3112d f26a057 3d3112d f26a057 3d3112d f26a057 3d3112d f26a057 3d3112d f26a057 3d3112d f26a057 3d3112d f26a057 3d3112d f26a057 3d3112d f26a057 3d3112d f26a057 3d3112d f26a057 3d3112d be139a9 3d3112d |
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 |
# app.py
import gradio as gr
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
import json
import os
import sqlite3
from datetime import datetime, timedelta
import pandas as pd
from typing import Dict, List, Optional
class RevalidaDatabase:
def __init__(self):
self.conn = sqlite3.connect('revalida.db')
self.create_tables()
self.load_previous_questions()
def create_tables(self):
"""Cria tabelas necessárias"""
self.conn.execute('''
CREATE TABLE IF NOT EXISTS users (
user_id TEXT PRIMARY KEY,
name TEXT,
study_hours INTEGER,
start_date DATE,
target_date DATE,
weak_areas TEXT
)''')
self.conn.execute('''
CREATE TABLE IF NOT EXISTS study_progress (
user_id TEXT,
date DATE,
topic TEXT,
hours_studied FLOAT,
questions_answered INTEGER,
performance_score FLOAT,
FOREIGN KEY (user_id) REFERENCES users(user_id)
)''')
self.conn.execute('''
CREATE TABLE IF NOT EXISTS previous_questions (
id INTEGER PRIMARY KEY,
year INTEGER,
area TEXT,
question_text TEXT,
options TEXT,
correct_answer TEXT,
explanation TEXT
)''')
self.conn.commit()
def load_previous_questions(self):
"""Carrega questões de provas anteriores do arquivo JSON"""
try:
with open('previous_questions.json', 'r', encoding='utf-8') as f:
questions = json.load(f)
cursor = self.conn.cursor()
for q in questions:
cursor.execute('''
INSERT OR IGNORE INTO previous_questions
(year, area, question_text, options, correct_answer, explanation)
VALUES (?, ?, ?, ?, ?, ?)
''', (q['year'], q['area'], q['question_text'],
json.dumps(q['options']), q['correct_answer'], q['explanation']))
self.conn.commit()
except Exception as e:
print(f"Erro ao carregar questões: {e}")
class StudyPlanGenerator:
def __init__(self, db: RevalidaDatabase):
self.db = db
def create_study_plan(self, user_id: str, available_hours: int,
target_date: str, weak_areas: List[str]) -> Dict:
"""Gera plano de estudos personalizado"""
# Calcula período total de estudo
start_date = datetime.now()
target_date = datetime.strptime(target_date, '%Y-%m-%d')
total_days = (target_date - start_date).days
# Define distribuição de tópicos
topics = {
"Clínica Médica": 0.25,
"Cirurgia": 0.20,
"Pediatria": 0.15,
"Ginecologia e Obstetrícia": 0.15,
"Medicina de Família": 0.15,
"Saúde Mental": 0.10
}
# Ajusta pesos para áreas fracas
for area in weak_areas:
if area in topics:
topics[area] += 0.05
# Normaliza pesos
total_weight = sum(topics.values())
topics = {k: v/total_weight for k, v in topics.items()}
# Gera cronograma
schedule = {}
for week in range(total_days // 7 + 1):
schedule[f"Semana {week+1}"] = {
topic: round(hours * available_hours * topics[topic], 1)
for topic in topics
}
return schedule
class RevalidaBot:
def __init__(self):
self.db = RevalidaDatabase()
self.planner = StudyPlanGenerator(self.db)
# Modelo de linguagem
self.model_id = "meta-llama/Llama-2-7b-chat-hf"
self.tokenizer = AutoTokenizer.from_pretrained(self.model_id)
self.pipeline = pipeline(
"text-generation",
model=self.model_id,
tokenizer=self.tokenizer,
max_length=500
)
# Comandos disponíveis
self.commands = {
"/start": self.start_command,
"/plano": self.create_plan,
"/progresso": self.check_progress,
"/questoes": self.previous_questions,
"/estudo": self.study_mode,
"/ajuda": self.help_command
}
def process_message(self, message: str, user_id: str, history: List) -> str:
"""Processa mensagens recebidas"""
try:
if message.startswith("/"):
command = message.split()[0]
if command in self.commands:
return self.commands[command](message, user_id)
return "Comando não reconhecido. Use /ajuda para ver os comandos disponíveis."
return self.generate_response(message, history)
except Exception as e:
return f"Desculpe, ocorreu um erro: {str(e)}"
def create_plan(self, message: str, user_id: str) -> str:
"""Cria plano de estudos personalizado"""
try:
# Extrai parâmetros da mensagem
# Formato: /plano horas_diarias YYYY-MM-DD área1,área2
parts = message.split()
if len(parts) < 3:
return "Formato: /plano horas_diarias YYYY-MM-DD área1,área2"
hours = int(parts[1])
target_date = parts[2]
weak_areas = parts[3].split(',') if len(parts) > 3 else []
plan = self.planner.create_study_plan(
user_id, hours, target_date, weak_areas
)
# Formata resposta
response = "📚 Seu Plano de Estudos:\n\n"
for week, topics in plan.items():
response += f"{week}:\n"
for topic, hours in topics.items():
response += f"- {topic}: {hours}h\n"
response += "\n"
return response
except Exception as e:
return f"Erro ao criar plano: {str(e)}"
def check_progress(self, message: str, user_id: str) -> str:
"""Verifica progresso do usuário"""
try:
cursor = self.db.conn.cursor()
cursor.execute('''
SELECT topic, SUM(hours_studied) as total_hours,
AVG(performance_score) as avg_score
FROM study_progress
WHERE user_id = ?
GROUP BY topic
''', (user_id,))
progress = cursor.fetchall()
response = "📊 Seu Progresso:\n\n"
for topic, hours, score in progress:
response += f"{topic}:\n"
response += f"- Horas estudadas: {hours:.1f}h\n"
response += f"- Desempenho médio: {score:.1f}%\n\n"
return response
except Exception as e:
return f"Erro ao verificar progresso: {str(e)}"
def previous_questions(self, message: str, user_id: str) -> str:
"""Busca questões de provas anteriores"""
try:
# Formato: /questoes área [ano]
parts = message.split()
if len(parts) < 2:
return "Formato: /questoes área [ano]"
area = parts[1]
year = int(parts[2]) if len(parts) > 2 else None
cursor = self.db.conn.cursor()
if year:
cursor.execute('''
SELECT question_text, options, correct_answer, explanation
FROM previous_questions
WHERE area = ? AND year = ?
ORDER BY RANDOM()
LIMIT 1
''', (area, year))
else:
cursor.execute('''
SELECT question_text, options, correct_answer, explanation
FROM previous_questions
WHERE area = ?
ORDER BY RANDOM()
LIMIT 1
''', (area,))
question = cursor.fetchone()
if not question:
return "Nenhuma questão encontrada com esses critérios."
response = f"📝 Questão:\n\n{question[0]}\n\n"
options = json.loads(question[1])
for letter, text in options.items():
response += f"{letter}) {text}\n"
response += f"\nResposta: {question[2]}\n"
response += f"Explicação: {question[3]}"
return response
except Exception as e:
return f"Erro ao buscar questão: {str(e)}"
def study_mode(self, message: str, user_id: str) -> str:
"""Modo estudo com acompanhamento"""
try:
# Formato: /estudo área horas
parts = message.split()
if len(parts) < 3:
return "Formato: /estudo área horas"
area = parts[1]
hours = float(parts[2])
# Registra estudo
cursor = self.db.conn.cursor()
cursor.execute('''
INSERT INTO study_progress
(user_id, date, topic, hours_studied, questions_answered, performance_score)
VALUES (?, ?, ?, ?, ?, ?)
''', (user_id, datetime.now().date(), area, hours, 0, 0.0))
self.db.conn.commit()
return f"✅ Registrado: {hours}h de estudo em {area}\n\nContinue assim! Use /progresso para ver seu desenvolvimento."
except Exception as e:
return f"Erro ao registrar estudo: {str(e)}"
# Outros métodos necessários...
def create_interface():
"""Cria interface Gradio"""
bot = RevalidaBot()
with gr.Blocks(title="Assistente Revalida") as interface:
gr.Markdown("# 🏥 Assistente Revalida Pro")
gr.Markdown("### Seu mentor personalizado para o Revalida")
with gr.Row():
with gr.Column():
user_id = gr.Textbox(
label="Seu ID (email ou telefone)",
placeholder="Digite seu ID único..."
)
chatbot = gr.Chatbot()
msg = gr.Textbox(
placeholder="Digite sua mensagem ou comando aqui...",
show_label=False
)
clear = gr.ClearButton([msg, chatbot])
def process_message_with_user(message, history):
user = user_id.value if user_id.value else "default_user"
return bot.process_message(message, user, history)
msg.submit(
process_message_with_user,
[msg, chatbot],
[chatbot]
)
return interface
# Inicia a interface
if __name__ == "__main__":
interface = create_interface()
interface.launch() |