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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
+
import os
|
| 3 |
+
import re
|
| 4 |
+
import json
|
| 5 |
+
import requests
|
| 6 |
+
from PyPDF2 import PdfReader
|
| 7 |
+
import textwrap
|
| 8 |
|
| 9 |
+
# ✅ Configurar API Key de DeepSeek (usa tu API Key desde variables de entorno)
|
| 10 |
+
DEEPSEEK_API_KEY = os.getenv("DEEPSEEK_API_KEY", "sk-a310e25780c14332857b017d7e440314")
|
| 11 |
+
DEEPSEEK_API_URL = "https://api.deepseek.com/v1/chat/completions"
|
| 12 |
+
|
| 13 |
+
# Modelo de DeepSeek (gratis y potente)
|
| 14 |
+
MODEL = "deepseek-chat" # También puedes usar "deepseek-coder" si prefieres
|
| 15 |
+
|
| 16 |
+
def extract_text_from_pdf(pdf_file):
|
| 17 |
+
"""Extrae texto de un archivo PDF"""
|
| 18 |
+
reader = PdfReader(pdf_file)
|
| 19 |
+
text = ""
|
| 20 |
+
for page in reader.pages:
|
| 21 |
+
text += page.extract_text() + "\n"
|
| 22 |
+
return text[:5000] # Limitar para no exceder tokens
|
| 23 |
+
|
| 24 |
+
def generate_smart_objective(objective, age, duration):
|
| 25 |
+
age_group = 'preescolar' if age < 36 else 'escolar' if age < 144 else 'adolescente/adulto'
|
| 26 |
+
time_frame = 'corto plazo' if duration < 30 else 'mediano plazo' if duration < 60 else 'largo plazo'
|
| 27 |
+
return f"El paciente {age_group} logrará {objective} con un 80% de precisión durante {duration} minutos, utilizando apoyo visual/auditivo según necesidad."
|
| 28 |
+
|
| 29 |
+
def analyze_context(context_text):
|
| 30 |
+
"""Analiza el contexto adicional para extraer estrategias, materiales, etc."""
|
| 31 |
+
if not context_text:
|
| 32 |
+
return {}
|
| 33 |
+
info = {}
|
| 34 |
+
keywords = {
|
| 35 |
+
'material': ['visual', 'auditivo', 'táctil', 'digital'],
|
| 36 |
+
'strategy': ['miofuncional', 'bobath', 'prompt', 'mit', 'lsvt', 'vitalstim'],
|
| 37 |
+
'environment': ['domiciliario', 'clínico', 'educativo', 'comunitario']
|
| 38 |
+
}
|
| 39 |
+
for category, words in keywords.items():
|
| 40 |
+
for word in words:
|
| 41 |
+
if word in context_text.lower():
|
| 42 |
+
info[category] = word
|
| 43 |
+
break
|
| 44 |
+
return info
|
| 45 |
+
|
| 46 |
+
def generate_prompt(user_desc, objective, duration, session_type, is_pediatric, context, pdf_text=""):
|
| 47 |
+
age = int(re.search(r'\d+', user_desc).group()) if re.search(r'\d+', user_desc) else 60
|
| 48 |
+
is_child = age < 144 or is_pediatric
|
| 49 |
+
context_info = analyze_context(context)
|
| 50 |
+
|
| 51 |
+
prompt = f"""
|
| 52 |
+
Eres un fonoaudiólogo experto. Genera una actividad terapéutica COMPLETA para:
|
| 53 |
+
PACIENTE: {user_desc}
|
| 54 |
+
OBJETIVO: {objective}
|
| 55 |
+
DURACIÓN: {duration} minutos
|
| 56 |
+
TIPO DE SESIÓN: {session_type}
|
| 57 |
+
SESIÓN PEDIÁTRICA: {'Sí' if is_child else 'No'}
|
| 58 |
+
CONTEXTO ADICIONAL: {context or 'Ninguno'}
|
| 59 |
+
{'REFERENCIAS CIENTÍFICAS: ' + pdf_text if pdf_text else ''}
|
| 60 |
+
|
| 61 |
+
INCLUYE:
|
| 62 |
+
- Título atractivo
|
| 63 |
+
- Objetivo SMART
|
| 64 |
+
- Descripción general
|
| 65 |
+
- Lista de materiales
|
| 66 |
+
- Procedimiento paso a paso (3 fases con tiempos)
|
| 67 |
+
- Métodos de evaluación
|
| 68 |
+
- Adaptaciones sugeridas
|
| 69 |
+
- Fundamentación teórica
|
| 70 |
+
|
| 71 |
+
RESPONDE EN FORMATO JSON con estas claves: title, smart_objective, description, materials, procedure, evaluation, adaptations, theoretical_foundation.
|
| 72 |
+
"""
|
| 73 |
+
return prompt
|
| 74 |
+
|
| 75 |
+
def call_deepseek_api(prompt):
|
| 76 |
+
"""Llama a la API de DeepSeek"""
|
| 77 |
+
headers = {
|
| 78 |
+
"Authorization": f"Bearer {DEEPSEEK_API_KEY}",
|
| 79 |
+
"Content-Type": "application/json"
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
data = {
|
| 83 |
+
"model": MODEL,
|
| 84 |
+
"messages": [{"role": "user", "content": prompt}],
|
| 85 |
+
"temperature": 0.7,
|
| 86 |
+
"max_tokens": 2048
|
| 87 |
+
}
|
| 88 |
|
| 89 |
+
response = requests.post(DEEPSEEK_API_URL, headers=headers, json=data)
|
| 90 |
+
response.raise_for_status()
|
| 91 |
+
|
| 92 |
+
result = response.json()
|
| 93 |
+
return result["choices"][0]["message"]["content"]
|
| 94 |
+
|
| 95 |
+
def generate_activity(user_desc, objective, duration, session_type, is_pediatric, context, pdf_files):
|
| 96 |
+
if not all([user_desc, objective, duration]):
|
| 97 |
+
return "⚠️ Por favor completa todos los campos obligatorios.", "", "", "", "", "", "", ""
|
| 98 |
+
|
| 99 |
+
# Procesar PDFs si existen
|
| 100 |
+
pdf_text = ""
|
| 101 |
+
if pdf_files:
|
| 102 |
+
for pdf_file in pdf_files:
|
| 103 |
+
pdf_text += f"\n--- Contenido de {pdf_file.name} ---\n"
|
| 104 |
+
pdf_text += extract_text_from_pdf(pdf_file)
|
| 105 |
+
|
| 106 |
+
# Generar prompt
|
| 107 |
+
prompt = generate_prompt(user_desc, objective, duration, session_type, is_pediatric, context, pdf_text)
|
| 108 |
+
|
| 109 |
+
try:
|
| 110 |
+
# Llamar a la IA de DeepSeek
|
| 111 |
+
content = call_deepseek_api(prompt)
|
| 112 |
+
|
| 113 |
+
# Limpiar posibles markdown code blocks
|
| 114 |
+
if content.startswith("```json"):
|
| 115 |
+
content = content[7:]
|
| 116 |
+
if content.endswith("```"):
|
| 117 |
+
content = content[:-3]
|
| 118 |
+
|
| 119 |
+
# Parsear respuesta JSON
|
| 120 |
+
data = json.loads(content)
|
| 121 |
+
|
| 122 |
+
return (
|
| 123 |
+
data.get("title", "Actividad Generada con IA"),
|
| 124 |
+
data.get("smart_objective", generate_smart_objective(objective, 60, duration)),
|
| 125 |
+
data.get("description", "Descripción generada por IA."),
|
| 126 |
+
"\n".join(f"• {m}" for m in data.get("materials", ["Material 1", "Material 2"])),
|
| 127 |
+
"\n".join(f"FASE: {p.get('name', 'Fase')} ({p.get('time', 'X')} min)\n{p.get('description', 'Descripción')}" for p in data.get("procedure", [])),
|
| 128 |
+
f"Criterio: {data.get('evaluation', {}).get('criteria', '80% de aciertos')}\nMétodos: {', '.join(data.get('evaluation', {}).get('methods', ['Registro']))}\nRetroalimentación: {data.get('evaluation', {}).get('feedback', 'Personalizada')}",
|
| 129 |
+
"\n".join(f"• {a}" for a in data.get("adaptations", ["Adaptación 1", "Adaptación 2"])),
|
| 130 |
+
"\n".join(f"• {f}" for f in data.get("theoretical_foundation", ["Fundamento 1", "Fundamento 2"]))
|
| 131 |
+
)
|
| 132 |
+
except Exception as e:
|
| 133 |
+
# Modo simulado de respaldo
|
| 134 |
+
age = int(re.search(r'\d+', user_desc).group()) if re.search(r'\d+', user_desc) else 60
|
| 135 |
+
is_child = age < 144 or is_pediatric
|
| 136 |
+
smart_obj = generate_smart_objective(objective, age, duration)
|
| 137 |
+
|
| 138 |
+
return (
|
| 139 |
+
f"{'🎮 Aventura: ' if is_child else '🎯 Actividad: '}{objective}",
|
| 140 |
+
smart_obj,
|
| 141 |
+
f"Actividad {'lúdica' if is_child else 'estructurada'} para {objective}.",
|
| 142 |
+
"• Material 1\n• Material 2\n• Material 3",
|
| 143 |
+
"FASE 1: Calentamiento (5 min)\nPreparación inicial.\nFASE 2: Desarrollo (20 min)\nActividad principal.\nFASE 3: Cierre (5 min)\nEvaluación.",
|
| 144 |
+
"Criterio: 80% de aciertos\nMétodos: Registro, Observación\nRetroalimentación: Personalizada",
|
| 145 |
+
"• Adaptación 1\n• Adaptación 2",
|
| 146 |
+
"• Taxonomía de Bloom\n• Neuroplasticidad"
|
| 147 |
+
)
|
| 148 |
+
|
| 149 |
+
# ✅ Interfaz de Gradio
|
| 150 |
+
with gr.Blocks(title="🧠 Generador IA de Actividades Fonoaudiológicas") as demo:
|
| 151 |
+
gr.Markdown("# 🧠 Generador IA de Actividades Fonoaudiológicas")
|
| 152 |
+
gr.Markdown("### ✨ Potenciado con DeepSeek en Hugging Face")
|
| 153 |
+
|
| 154 |
+
with gr.Row():
|
| 155 |
+
with gr.Column():
|
| 156 |
+
user_desc = gr.Textbox(label="👤 Descripción del usuario (edad en meses y contexto)", placeholder="Ej: Niño de 48 meses con retraso en lenguaje")
|
| 157 |
+
objective = gr.Textbox(label="🎯 Objetivo específico", placeholder="Ej: Mejorar articulación del fonema /r/")
|
| 158 |
+
duration = gr.Number(label="⏱️ Duración (minutos)", value=30, minimum=15, maximum=120)
|
| 159 |
+
session_type = gr.Dropdown(["individual", "grupal", "hogar"], label="👥 Tipo de sesión", value="individual")
|
| 160 |
+
is_pediatric = gr.Checkbox(label="🧸 Sesión Pediátrica (lenguaje lúdico)")
|
| 161 |
+
context = gr.Textbox(label="📚 Contexto Adicional (Opcional)", placeholder="Estrategias, materiales, criterios...", lines=3)
|
| 162 |
+
pdf_files = gr.File(label="📖 Subir PDFs de Referencia (Opcional)", file_types=[".pdf"], file_count="multiple")
|
| 163 |
+
btn = gr.Button("✨ Generar Actividad con IA", variant="primary")
|
| 164 |
+
|
| 165 |
+
with gr.Column():
|
| 166 |
+
title = gr.Textbox(label="Título de la Actividad")
|
| 167 |
+
smart_obj = gr.Textbox(label="📋 Objetivo SMART")
|
| 168 |
+
description = gr.Textbox(label="📝 Descripción", lines=3)
|
| 169 |
+
materials = gr.Textbox(label="🎯 Materiales", lines=3)
|
| 170 |
+
procedure = gr.Textbox(label="⚡ Procedimiento", lines=5)
|
| 171 |
+
evaluation = gr.Textbox(label="📊 Evaluación", lines=3)
|
| 172 |
+
adaptations = gr.Textbox(label="🔧 Adaptaciones", lines=3)
|
| 173 |
+
theory = gr.Textbox(label="📚 Fundamentación Teórica", lines=3)
|
| 174 |
+
|
| 175 |
+
# Conectar botón
|
| 176 |
+
btn.click(
|
| 177 |
+
fn=generate_activity,
|
| 178 |
+
inputs=[user_desc, objective, duration, session_type, is_pediatric, context, pdf_files],
|
| 179 |
+
outputs=[title, smart_obj, description, materials, procedure, evaluation, adaptations, theory]
|
| 180 |
+
)
|
| 181 |
+
|
| 182 |
+
gr.Markdown("### 💡 Desarrollado por Flgo. Cristóbal San Martín | [@tufonoayuda](https://instagram.com/tufonoayuda)")
|
| 183 |
+
|
| 184 |
+
# Lanzar app
|
| 185 |
+
if __name__ == "__main__":
|
| 186 |
+
demo.launch()
|