crmjarevalida / study_generators.py
danielraynaud's picture
Update study_generators.py
716f72e verified
import json
from datetime import datetime, timedelta
from typing import Dict, List, Optional
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class StudyMaterialGenerator:
def __init__(self, db_connection):
self.db_connection = db_connection
def generate_daily_questions(self, user_id: str, num_questions: int = 10) -> List[Dict]:
"""Gera questões diárias baseadas no perfil do usuário"""
try:
conn = self.db.get_connection()
cursor = conn.cursor()
# Busca áreas fracas do usuário
user_profile = self.db.get_user_profile(user_id)
weak_areas = user_profile.get('weak_areas', []) if user_profile else []
# Prioriza questões das áreas fracas
query = '''
SELECT * FROM previous_questions
WHERE area IN (?)
ORDER BY RANDOM()
LIMIT ?
'''
cursor.execute(query, (','.join(weak_areas), num_questions))
questions = cursor.fetchall()
return [dict(q) for q in questions]
except Exception as e:
logger.error(f"Erro ao gerar questões: {e}")
return []
def generate_materials(self, user_id, topic, hours) -> Dict:
"""Gera material de estudo para um tópico específico"""
try:
conn = self.db.get_connection()
cursor = conn.cursor()
# Busca casos clínicos relacionados
cursor.execute('''
SELECT * FROM clinical_cases
WHERE area = ?
ORDER BY RANDOM()
LIMIT 3
''', (topic,))
cases = cursor.fetchall()
return {
'topic': topic,
'clinical_cases': [dict(case) for case in cases],
'key_points': self._generate_key_points(topic),
'references': self._get_references(topic)
}
except Exception as e:
logger.error(f"Erro ao gerar material: {e}")
return {}
def _generate_key_points(self, topic: str) -> List[str]:
"""Gera pontos-chave para um tópico"""
# Implementar lógica para extrair pontos-chave
return []
def _get_references(self, topic: str) -> List[str]:
"""Busca referências para um tópico"""
# Implementar lógica para buscar referências
return []
class StudyPlanGenerator:
def __init__(self, db):
self.db = db
def generate_plan(self, user_id: str, duration_days: int = 30) -> Dict:
"""Gera um plano de estudos personalizado"""
try:
# Busca perfil do usuário
user_profile = self.db.get_user_profile(user_id)
if not user_profile:
return {}
# Calcula distribuição de tempo
weak_areas = user_profile.get('weak_areas', [])
study_hours = user_profile.get('study_hours', 4)
plan = {
'user_id': user_id,
'duration_days': duration_days,
'daily_schedule': self._create_daily_schedule(study_hours, weak_areas),
'weekly_goals': self._create_weekly_goals(weak_areas),
'start_date': datetime.now().date(),
'end_date': (datetime.now() + timedelta(days=duration_days)).date()
}
# Salva o plano no banco
self._save_plan(user_id, plan)
return plan
except Exception as e:
logger.error(f"Erro ao gerar plano: {e}")
return {}
def _create_daily_schedule(self, hours: int, areas: List[str]) -> Dict:
"""Cria cronograma diário"""
schedule = {}
hours_per_area = hours / len(areas) if areas else hours
for area in areas:
schedule[area] = {
'hours': hours_per_area,
'questions_goal': int(hours_per_area * 10), # 10 questões por hora
'review_time': hours_per_area * 0.2 # 20% do tempo para revisão
}
return schedule
def _create_weekly_goals(self, areas: List[str]) -> List[Dict]:
"""Cria metas semanais"""
goals = []
for area in areas:
goals.append({
'area': area,
'questions_target': 70, # 10 questões por dia
'mock_exam_target': 1, # 1 simulado por semana
'review_sessions': 2 # 2 sessões de revisão
})
return goals
def _save_plan(self, user_id: str, plan: Dict) -> None:
"""Salva o plano no banco de dados"""
try:
conn = self.db.get_connection()
cursor = conn.cursor()
cursor.execute('''
INSERT INTO study_sessions
(user_id, start_time, end_time, topic, activity_type, notes)
VALUES (?, ?, ?, ?, ?, ?)
''', (
user_id,
datetime.now(),
datetime.now() + timedelta(days=plan['duration_days']),
'multiple',
'study_plan',
json.dumps(plan)
))
conn.commit()
except Exception as e:
logger.error(f"Erro ao salvar plano: {e}")