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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
demo.launch()
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
import os
|
| 3 |
+
import re
|
| 4 |
+
import json
|
| 5 |
+
import requests
|
| 6 |
+
from pypdf import PdfReader
|
| 7 |
|
| 8 |
+
# ✅ Obtener API Key (con fallback para diagnóstico)
|
| 9 |
+
DEEPSEEK_API_KEY = os.getenv("DEEPSEEK_API_KEY")
|
| 10 |
+
DEEPSEEK_API_URL = "https://api.deepseek.com/v1/chat/completions"
|
| 11 |
+
MODEL = "deepseek-chat"
|
| 12 |
+
|
| 13 |
+
def extract_text_from_pdf(pdf_file):
|
| 14 |
+
try:
|
| 15 |
+
reader = PdfReader(pdf_file)
|
| 16 |
+
text = ""
|
| 17 |
+
for page in reader.pages:
|
| 18 |
+
extracted = page.extract_text()
|
| 19 |
+
if extracted:
|
| 20 |
+
text += extracted + "\n"
|
| 21 |
+
return text[:5000]
|
| 22 |
+
except Exception as e:
|
| 23 |
+
return f"Error al leer PDF: {str(e)}"
|
| 24 |
+
|
| 25 |
+
def generate_smart_objective(objective, age, duration):
|
| 26 |
+
age_group = 'preescolar' if age < 36 else 'escolar' if age < 144 else 'adolescente/adulto'
|
| 27 |
+
time_frame = 'corto plazo' if duration < 30 else 'mediano plazo' if duration < 60 else 'largo plazo'
|
| 28 |
+
return f"El paciente {age_group} logrará {objective} con un 80% de precisión durante {duration} minutos."
|
| 29 |
+
|
| 30 |
+
def call_deepseek_api(prompt):
|
| 31 |
+
if not DEEPSEEK_API_KEY:
|
| 32 |
+
raise Exception("❌ DEEPSEEK_API_KEY no está configurada. Revisa Settings > Variables de entorno.")
|
| 33 |
+
|
| 34 |
+
headers = {
|
| 35 |
+
"Authorization": f"Bearer {DEEPSEEK_API_KEY}",
|
| 36 |
+
"Content-Type": "application/json"
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
data = {
|
| 40 |
+
"model": MODEL,
|
| 41 |
+
"messages": [{"role": "user", "content": prompt}],
|
| 42 |
+
"temperature": 0.3,
|
| 43 |
+
"max_tokens": 4096
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
try:
|
| 47 |
+
response = requests.post(DEEPSEEK_API_URL, headers=headers, json=data, timeout=60)
|
| 48 |
+
response.raise_for_status()
|
| 49 |
+
result = response.json()
|
| 50 |
+
return result["choices"][0]["message"]["content"]
|
| 51 |
+
except Exception as e:
|
| 52 |
+
raise Exception(f"Error de la IA: {str(e)}")
|
| 53 |
+
|
| 54 |
+
def generate_activity(user_desc, objective, duration, session_type, is_pediatric, context, pdf_files):
|
| 55 |
+
if not all([user_desc, objective, duration]):
|
| 56 |
+
return ("⚠️ Error", "Completa todos los campos.", "", "", "", "", "", "")
|
| 57 |
+
|
| 58 |
+
try:
|
| 59 |
+
age = int(re.search(r'\d+', user_desc).group()) if re.search(r'\d+', user_desc) else 60
|
| 60 |
+
is_child = age < 144 or is_pediatric
|
| 61 |
+
dur = int(duration)
|
| 62 |
+
|
| 63 |
+
pdf_text = ""
|
| 64 |
+
if pdf_files:
|
| 65 |
+
for pdf_file in pdf_files:
|
| 66 |
+
pdf_text += f"\n--- {pdf_file.name} ---\n"
|
| 67 |
+
pdf_text += extract_text_from_pdf(pdf_file)
|
| 68 |
+
|
| 69 |
+
prompt = f"""
|
| 70 |
+
Eres un fonoaudiólogo experto. Genera una actividad para:
|
| 71 |
+
PACIENTE: {user_desc}
|
| 72 |
+
OBJETIVO: {objective}
|
| 73 |
+
DURACIÓN: {duration} minutos
|
| 74 |
+
TIPO DE SESIÓN: {session_type}
|
| 75 |
+
SESIÓN PEDIÁTRICA: {'Sí' if is_child else 'No'}
|
| 76 |
+
CONTEXTO: {context or 'Ninguno'}
|
| 77 |
+
REFERENCIAS: {pdf_text[:1000] if pdf_text else 'Ninguna'}
|
| 78 |
+
|
| 79 |
+
RESPONDE EN FORMATO JSON: {{"title": "", "smart_objective": "", "description": "", "materials": "", "procedure": "", "evaluation": "", "adaptations": "", "theoretical_foundation": ""}}
|
| 80 |
+
"""
|
| 81 |
+
|
| 82 |
+
content = call_deepseek_api(prompt)
|
| 83 |
+
|
| 84 |
+
# Modo fallback: si falla el JSON, devuelve texto plano
|
| 85 |
+
try:
|
| 86 |
+
if content.startswith("```json"):
|
| 87 |
+
content = content[7:]
|
| 88 |
+
if content.endswith("```"):
|
| 89 |
+
content = content[:-3]
|
| 90 |
+
data = json.loads(content)
|
| 91 |
+
except:
|
| 92 |
+
return (
|
| 93 |
+
"Actividad Generada",
|
| 94 |
+
"Objetivo generado por IA",
|
| 95 |
+
content,
|
| 96 |
+
"Materiales generados por IA",
|
| 97 |
+
"Procedimiento generado por IA",
|
| 98 |
+
"Evaluación generada por IA",
|
| 99 |
+
"Adaptaciones generadas por IA",
|
| 100 |
+
"Fundamentación generada por IA"
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
return (
|
| 104 |
+
data.get("title", "Actividad Generada"),
|
| 105 |
+
data.get("smart_objective", generate_smart_objective(objective, age, dur)),
|
| 106 |
+
data.get("description", "Descripción generada por IA."),
|
| 107 |
+
data.get("materials", "Materiales generados por IA."),
|
| 108 |
+
data.get("procedure", "Procedimiento generado por IA."),
|
| 109 |
+
data.get("evaluation", "Evaluación generada por IA."),
|
| 110 |
+
data.get("adaptations", "Adaptaciones generadas por IA."),
|
| 111 |
+
data.get("theoretical_foundation", "Fundamentación generada por IA.")
|
| 112 |
+
)
|
| 113 |
+
|
| 114 |
+
except Exception as e:
|
| 115 |
+
return (
|
| 116 |
+
"❌ Error",
|
| 117 |
+
str(e),
|
| 118 |
+
"Por favor verifica tu API Key en Settings > Variables de entorno y reinicia el Space.",
|
| 119 |
+
"Si el problema persiste, contacta al desarrollador.",
|
| 120 |
+
"",
|
| 121 |
+
"",
|
| 122 |
+
"",
|
| 123 |
+
""
|
| 124 |
+
)
|
| 125 |
|
| 126 |
with gr.Blocks() as demo:
|
| 127 |
+
gr.Markdown("# 🧠 Generador IA de Actividades Fonoaudiológicas")
|
| 128 |
+
|
| 129 |
+
with gr.Row():
|
| 130 |
+
with gr.Column():
|
| 131 |
+
user_desc = gr.Textbox(label="👤 Descripción del usuario", placeholder="Ej: Niño de 48 meses...")
|
| 132 |
+
objective = gr.Textbox(label="🎯 Objetivo específico")
|
| 133 |
+
duration = gr.Number(label="⏱️ Duración (minutos)", value=30)
|
| 134 |
+
session_type = gr.Dropdown(["individual", "grupal", "hogar"], label="👥 Tipo de sesión")
|
| 135 |
+
is_pediatric = gr.Checkbox(label="🧸 Sesión Pediátrica")
|
| 136 |
+
context = gr.Textbox(label="📚 Contexto Adicional", lines=3)
|
| 137 |
+
pdf_files = gr.File(label="📖 Subir PDFs", file_types=[".pdf"], file_count="multiple")
|
| 138 |
+
btn = gr.Button("✨ Generar Actividad con IA")
|
| 139 |
+
|
| 140 |
+
with gr.Column():
|
| 141 |
+
title = gr.Textbox(label="Título")
|
| 142 |
+
smart_obj = gr.Textbox(label="📋 Objetivo SMART")
|
| 143 |
+
description = gr.Textbox(label="📝 Descripción", lines=3)
|
| 144 |
+
materials = gr.Textbox(label="🎯 Materiales", lines=3)
|
| 145 |
+
procedure = gr.Textbox(label="⚡ Procedimiento", lines=3)
|
| 146 |
+
evaluation = gr.Textbox(label="📊 Evaluación", lines=3)
|
| 147 |
+
adaptations = gr.Textbox(label="🔧 Adaptaciones", lines=3)
|
| 148 |
+
theory = gr.Textbox(label="📚 Fundamentación Teórica", lines=3)
|
| 149 |
+
|
| 150 |
+
btn.click(
|
| 151 |
+
fn=generate_activity,
|
| 152 |
+
inputs=[user_desc, objective, duration, session_type, is_pediatric, context, pdf_files],
|
| 153 |
+
outputs=[title, smart_obj, description, materials, procedure, evaluation, adaptations, theory]
|
| 154 |
+
)
|
| 155 |
+
|
| 156 |
+
demo.launch()
|
| 157 |
|
| 158 |
demo.launch()
|