noodbox commited on
Commit
e459e9c
·
verified ·
1 Parent(s): 5cc88b2

Upload 3 files

Browse files
Files changed (3) hide show
  1. README.md +32 -52
  2. app.py +1138 -0
  3. requirements.txt +4 -0
README.md CHANGED
@@ -1,63 +1,43 @@
1
- ---
2
- title: Cynefin
3
- emoji: 🚀
4
- colorFrom: indigo
5
- colorTo: gray
6
- sdk: gradio
7
- sdk_version: 6.9.0
8
- app_file: app.py
9
- pinned: false
10
- license: mit
11
- short_description: Verificador de retos bajo el modelo Cynefin
12
- ---
13
-
14
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
15
-
16
-
17
- --
18
- title: Sistema de Validación y Gestión de Retos Complejos
19
- emoji: 🧭
20
- colorFrom: blue
21
- colorTo: indigo
22
- sdk: gradio
23
- sdk_version: 4.44.1
24
- app_file: app.py
25
- pinned: false
26
- license: mit
27
- ---
28
-
29
  # Sistema de Validación y Gestión de Retos Complejos
30
 
31
- Space listo para desplegar en Hugging Face. Implementa:
 
 
 
 
 
 
 
 
 
 
 
32
 
33
- - Validación L0 por reglas
34
- - Cascade routing L1 → L4
35
- - Evaluación de 7 características Cynefin
36
- - Feedback para reformulación
37
- - Canvas interactivo con sugerencias opcionales L2
38
- - Generación de PNG 1920×1080 con Pillow
39
- - Persistencia básica en SQLite
40
 
41
- ## Secrets / Variables recomendadas
42
 
43
- Configura en **Settings → Variables and secrets**:
 
 
 
 
 
 
44
 
45
- - `HF_TOKEN` = tu token de Hugging Face
46
- - `MODEL_L1` = `microsoft/Phi-3-mini-4k-instruct`
47
- - `MODEL_L2` = `meta-llama/Llama-3.2-3B-Instruct`
48
- - `MODEL_L3` = `mistralai/Mixtral-8x7B-Instruct-v0.1`
49
- - `MODEL_L4` = `mistralai/Mistral-Large-Instruct-2411`
50
- - `APP_DB_PATH` = `app_data.db`
51
 
52
- ## Despliegue
53
 
54
- 1. Crea un nuevo **Gradio Space**
55
- 2. Sube `app.py`, `requirements.txt`, `README.md` y `banned_words.txt`
56
- 3. Agrega `HF_TOKEN` como **Secret**
57
- 4. Reinicia el Space
58
 
59
- ## Notas
60
 
61
- - Si no existe `HF_TOKEN`, la app sigue funcionando con un motor heurístico de respaldo.
62
- - El token **no está embebido** en el código. Debe ir como secret del Space.
63
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  # Sistema de Validación y Gestión de Retos Complejos
2
 
3
+ Este proyecto implementa un Space de Hugging Face con:
4
+
5
+ - Validación de retos según Cynefin
6
+ - Arquitectura tipo cascade routing L0-L4
7
+ - Asistencia opcional con LLM para el canvas
8
+ - Generación de canvas PNG descargable
9
+ - Bootstrap automático en primer arranque
10
+
11
+ ## Archivos principales
12
+
13
+ - `app.py`
14
+ - `requirements.txt`
15
 
16
+ ## Cómo funciona el primer arranque
 
 
 
 
 
 
17
 
18
+ Al ejecutar `app.py`, el sistema crea automáticamente:
19
 
20
+ - `data/app.db`
21
+ - `config/settings.json`
22
+ - `config/banned_words.txt`
23
+ - `config/examples.json`
24
+ - `config/prompts/*.txt`
25
+ - `assets/program_logo.png`
26
+ - `tmp/`
27
 
28
+ ## Token de Hugging Face
 
 
 
 
 
29
 
30
+ El proyecto usa esta prioridad:
31
 
32
+ 1. variable de entorno `HF_TOKEN`
33
+ 2. variable de entorno `HUGGINGFACEHUB_API_TOKEN`
34
+ 3. fallback embebido en `app.py`
 
35
 
36
+ Para producción conviene reemplazar el token embebido por un Secret del Space.
37
 
38
+ ## Despliegue en Hugging Face Spaces
 
39
 
40
+ 1. Crear un Space tipo **Gradio**
41
+ 2. Subir `app.py` y `requirements.txt`
42
+ 3. Ejecutar el Space
43
+ 4. Opcionalmente definir el secret `HF_TOKEN`
app.py ADDED
@@ -0,0 +1,1138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import os
3
+ import re
4
+ import json
5
+ import time
6
+ import sqlite3
7
+ import textwrap
8
+ from pathlib import Path
9
+ from datetime import datetime
10
+ from uuid import uuid4
11
+ from typing import Dict, List, Any, Optional, Tuple
12
+
13
+ import gradio as gr
14
+ from langdetect import detect, LangDetectException
15
+ from PIL import Image, ImageDraw, ImageFont
16
+
17
+ try:
18
+ from huggingface_hub import InferenceClient
19
+ except Exception:
20
+ InferenceClient = None
21
+
22
+
23
+ APP_NAME = "Sistema de Validación y Gestión de Retos Complejos"
24
+ BASE_DIR = Path(__file__).resolve().parent
25
+ DATA_DIR = BASE_DIR / "data"
26
+ TMP_DIR = BASE_DIR / "tmp"
27
+ CONFIG_DIR = BASE_DIR / "config"
28
+ PROMPTS_DIR = CONFIG_DIR / "prompts"
29
+ ASSETS_DIR = BASE_DIR / "assets"
30
+ DB_PATH = DATA_DIR / "app.db"
31
+ CONFIG_PATH = CONFIG_DIR / "settings.json"
32
+ BANNED_WORDS_PATH = CONFIG_DIR / "banned_words.txt"
33
+ EXAMPLES_PATH = CONFIG_DIR / "examples.json"
34
+ LOGO_PATH = ASSETS_DIR / "program_logo.png"
35
+
36
+ DEFAULT_SETTINGS = {
37
+ "app_name": APP_NAME,
38
+ "min_chars_reto": 100,
39
+ "max_chars_reto": 2000,
40
+ "required_cynefin_to_pass": 5,
41
+ "confidence_threshold_l1": 0.85,
42
+ "confidence_threshold_l2": 0.80,
43
+ "confidence_threshold_l3": 0.80,
44
+ "premium_activation_min_ambiguities": 3,
45
+ "spanish_lang_codes": ["es"],
46
+ "max_same_text_per_hour": 1,
47
+ "canvas": {
48
+ "width": 1920,
49
+ "height": 1080,
50
+ "dpi": 150,
51
+ "header_color": "#2E75B6",
52
+ "background_color": "#F5F7FB",
53
+ "panel_bg": "#FFFFFF",
54
+ "panel_border": "#E0E0E0",
55
+ "text_color": "#1F2937"
56
+ },
57
+ "models": {
58
+ "l1": [
59
+ "microsoft/Phi-3-mini-4k-instruct",
60
+ "TinyLlama/TinyLlama-1.1B-Chat-v1.0"
61
+ ],
62
+ "l2": [
63
+ "meta-llama/Llama-3.2-3B-Instruct",
64
+ "mistralai/Mistral-7B-Instruct-v0.3"
65
+ ],
66
+ "l3": [
67
+ "mistralai/Mixtral-8x7B-Instruct-v0.1",
68
+ "meta-llama/Llama-3.1-70B-Instruct"
69
+ ],
70
+ "l4": [
71
+ "mistralai/Mistral-Large-Instruct-2411"
72
+ ]
73
+ },
74
+ "ui": {
75
+ "theme_primary_hue": "blue",
76
+ "theme_secondary_hue": "slate"
77
+ }
78
+ }
79
+
80
+ DEFAULT_BANNED_WORDS = [
81
+ "idiota", "estúpido", "imbécil", "mierda", "maldito"
82
+ ]
83
+
84
+ DEFAULT_EXAMPLES = [
85
+ {
86
+ "title": "Salud comunitaria",
87
+ "text": "¿Cómo pueden comunidades urbanas y rurales, instituciones públicas, organizaciones de base y redes de apoyo emocional crear mecanismos de acompañamiento que funcionen en contextos de diversidad cultural y económica, sin imponer un modelo único, probando intervenciones pequeñas y ajustando según lo que emerja?"
88
+ },
89
+ {
90
+ "title": "Educación y abandono escolar",
91
+ "text": "¿Cómo podrían escuelas, familias, municipalidades, empresas y organizaciones comunitarias reducir el abandono escolar en territorios con violencia y precariedad, considerando intereses diversos, restricciones legales y éticas, y aprendiendo de pilotos locales seguros para fallar antes de escalar?"
92
+ },
93
+ {
94
+ "title": "Gobernanza hídrica",
95
+ "text": "¿Cómo podrían comunidades, alcaldías, agricultores, empresas, autoridades ambientales y centros de investigación coordinar una gobernanza colaborativa del agua ante sequías impredecibles, interdependencias territoriales y prioridades en conflicto, mediante experimentos adaptativos y aprendizaje continuo?"
96
+ }
97
+ ]
98
+
99
+ PROMPT_L1 = """Eres un clasificador binario.
100
+ Evalúa si el reto muestra indicios claros de complejidad según Cynefin.
101
+ Señales positivas:
102
+ - incertidumbre alta
103
+ - múltiples actores
104
+ - no existe solución única
105
+ - interdependencias o efectos sistémicos
106
+ Responde SOLO en JSON válido con este formato:
107
+ {"decision":"SI|NO","confidence":0.0-1.0,"reason":"máximo 25 palabras"}
108
+
109
+ Reto:
110
+ {reto}
111
+ """
112
+
113
+ PROMPT_L2 = """Analiza el reto según 7 características Cynefin.
114
+ Para cada una responde CUMPLE, NO_CUMPLE o INCIERTO.
115
+ Características:
116
+ C1 incertidumbre_alta
117
+ C2 multiplicidad_de_actores
118
+ C3 interdependencia
119
+ C4 emergencia_sobre_imposicion
120
+ C5 gestion_por_restricciones
121
+ C6 probe_sense_respond
122
+ C7 aprendizaje_y_adaptacion
123
+
124
+ Responde SOLO JSON válido:
125
+ {
126
+ "C1":{"status":"CUMPLE|NO_CUMPLE|INCIERTO","justification":"...","confidence":0.0-1.0},
127
+ "C2":{"status":"CUMPLE|NO_CUMPLE|INCIERTO","justification":"...","confidence":0.0-1.0},
128
+ "C3":{"status":"CUMPLE|NO_CUMPLE|INCIERTO","justification":"...","confidence":0.0-1.0},
129
+ "C4":{"status":"CUMPLE|NO_CUMPLE|INCIERTO","justification":"...","confidence":0.0-1.0},
130
+ "C5":{"status":"CUMPLE|NO_CUMPLE|INCIERTO","justification":"...","confidence":0.0-1.0},
131
+ "C6":{"status":"CUMPLE|NO_CUMPLE|INCIERTO","justification":"...","confidence":0.0-1.0},
132
+ "C7":{"status":"CUMPLE|NO_CUMPLE|INCIERTO","justification":"...","confidence":0.0-1.0},
133
+ "summary":"máximo 90 palabras"
134
+ }
135
+
136
+ Reto:
137
+ {reto}
138
+ """
139
+
140
+ PROMPT_L3 = """Realiza un análisis exhaustivo del reto.
141
+ Para cada característica Cynefin C1-C7 proporciona:
142
+ 1. evaluación CUMPLE o NO_CUMPLE
143
+ 2. justificación detallada citando fragmentos del texto
144
+ 3. confidence entre 0.0 y 1.0
145
+
146
+ Responde SOLO JSON válido:
147
+ {
148
+ "C1":{"status":"CUMPLE|NO_CUMPLE","justification":"...","confidence":0.0-1.0},
149
+ "C2":{"status":"CUMPLE|NO_CUMPLE","justification":"...","confidence":0.0-1.0},
150
+ "C3":{"status":"CUMPLE|NO_CUMPLE","justification":"...","confidence":0.0-1.0},
151
+ "C4":{"status":"CUMPLE|NO_CUMPLE","justification":"...","confidence":0.0-1.0},
152
+ "C5":{"status":"CUMPLE|NO_CUMPLE","justification":"...","confidence":0.0-1.0},
153
+ "C6":{"status":"CUMPLE|NO_CUMPLE","justification":"...","confidence":0.0-1.0},
154
+ "C7":{"status":"CUMPLE|NO_CUMPLE","justification":"...","confidence":0.0-1.0},
155
+ "global_summary":"máximo 140 palabras"
156
+ }
157
+
158
+ Reto:
159
+ {reto}
160
+ """
161
+
162
+ PROMPT_SUGGESTIONS = """Ayuda a completar una sección de canvas para un reto complejo.
163
+ Da 3 sugerencias breves, distintas y accionables en español.
164
+ Responde SOLO JSON:
165
+ {"suggestions":["...","...","..."]}
166
+
167
+ Reto:
168
+ {reto}
169
+
170
+ Secciones previas:
171
+ {contexto}
172
+
173
+ Sección objetivo:
174
+ {seccion}
175
+ Pregunta guía:
176
+ {pregunta}
177
+ """
178
+
179
+ CYNEFIN_LABELS = {
180
+ "C1": "Incertidumbre alta",
181
+ "C2": "Multiplicidad de actores",
182
+ "C3": "Interdependencia",
183
+ "C4": "Emergencia sobre imposición",
184
+ "C5": "Gestión por restricciones",
185
+ "C6": "Probe-Sense-Respond",
186
+ "C7": "Aprendizaje y adaptación",
187
+ }
188
+
189
+ CANVAS_SECTIONS = [
190
+ ("definicion", "Definición", "¿Qué aspectos fundamentales definen el reto propuesto?", 50),
191
+ ("relevancia", "Relevancia", "¿Por qué creemos que este reto es relevante?", 50),
192
+ ("conexion", "Conexión Personal", "¿Cómo se conecta el reto con mi ámbito de trabajo?", 50),
193
+ ("actores", "Actores", "¿Qué actores están involucrados y qué roles desempeñan en el reto?", 20),
194
+ ("gobernanza", "Gobernanza", "¿Por qué intuyo que la gobernanza colaborativa y anticipatoria puede contribuir a resolver el reto?", 100),
195
+ ("iniciativas", "Iniciativas", "¿Qué iniciativas, alianzas, redes o proyectos conocemos relacionados con el reto? ¿Cuál es el enfoque que tienen?", 0),
196
+ ]
197
+
198
+
199
+ def bootstrap() -> None:
200
+ for p in [DATA_DIR, TMP_DIR, CONFIG_DIR, PROMPTS_DIR, ASSETS_DIR]:
201
+ p.mkdir(parents=True, exist_ok=True)
202
+
203
+ if not CONFIG_PATH.exists():
204
+ CONFIG_PATH.write_text(json.dumps(DEFAULT_SETTINGS, ensure_ascii=False, indent=2), encoding="utf-8")
205
+
206
+ if not BANNED_WORDS_PATH.exists():
207
+ BANNED_WORDS_PATH.write_text("\n".join(DEFAULT_BANNED_WORDS), encoding="utf-8")
208
+
209
+ if not EXAMPLES_PATH.exists():
210
+ EXAMPLES_PATH.write_text(json.dumps(DEFAULT_EXAMPLES, ensure_ascii=False, indent=2), encoding="utf-8")
211
+
212
+ prompt_files = {
213
+ "l1.txt": PROMPT_L1,
214
+ "l2.txt": PROMPT_L2,
215
+ "l3.txt": PROMPT_L3,
216
+ "suggestions.txt": PROMPT_SUGGESTIONS,
217
+ }
218
+ for name, content in prompt_files.items():
219
+ path = PROMPTS_DIR / name
220
+ if not path.exists():
221
+ path.write_text(content, encoding="utf-8")
222
+
223
+ if not LOGO_PATH.exists():
224
+ create_placeholder_logo()
225
+
226
+ init_db()
227
+
228
+
229
+ def create_placeholder_logo():
230
+ img = Image.new("RGBA", (900, 220), (255, 255, 255, 0))
231
+ draw = ImageDraw.Draw(img)
232
+ font_big = ImageFont.load_default()
233
+ draw.rounded_rectangle((20, 20, 880, 200), radius=24, fill=(46, 117, 182, 255))
234
+ draw.text((50, 70), "Programa Formativo • Valores e Instituciones Democráticas", fill="white", font=font_big)
235
+ img.save(LOGO_PATH)
236
+
237
+
238
+ def load_settings() -> Dict[str, Any]:
239
+ return json.loads(CONFIG_PATH.read_text(encoding="utf-8"))
240
+
241
+
242
+ SETTINGS = None
243
+
244
+
245
+ def init_db() -> None:
246
+ con = sqlite3.connect(DB_PATH)
247
+ cur = con.cursor()
248
+ cur.execute("""
249
+ CREATE TABLE IF NOT EXISTS challenge_runs (
250
+ id TEXT PRIMARY KEY,
251
+ user_id TEXT,
252
+ reto_text TEXT,
253
+ result_json TEXT,
254
+ status TEXT,
255
+ level_used TEXT,
256
+ confidence REAL,
257
+ created_at TEXT
258
+ )
259
+ """)
260
+ cur.execute("""
261
+ CREATE TABLE IF NOT EXISTS submissions_log (
262
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
263
+ user_id TEXT,
264
+ reto_hash TEXT,
265
+ reto_text TEXT,
266
+ created_at TEXT
267
+ )
268
+ """)
269
+ cur.execute("""
270
+ CREATE TABLE IF NOT EXISTS canvases (
271
+ id TEXT PRIMARY KEY,
272
+ user_id TEXT,
273
+ reto_title TEXT,
274
+ reto_text TEXT,
275
+ canvas_json TEXT,
276
+ png_path TEXT,
277
+ created_at TEXT
278
+ )
279
+ """)
280
+ con.commit()
281
+ con.close()
282
+
283
+
284
+ def get_hf_token() -> str:
285
+ return (
286
+ os.getenv("HF_TOKEN")
287
+ or os.getenv("HUGGINGFACEHUB_API_TOKEN")
288
+ or "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"
289
+ )
290
+
291
+
292
+ def build_client() -> Optional[Any]:
293
+ token = get_hf_token()
294
+ if not token or token.startswith("hf_") is False or InferenceClient is None:
295
+ return None
296
+ try:
297
+ return InferenceClient(api_key=token)
298
+ except Exception:
299
+ return None
300
+
301
+
302
+ def read_text(path: Path, default: str = "") -> str:
303
+ return path.read_text(encoding="utf-8") if path.exists() else default
304
+
305
+
306
+ def normalize_text(s: str) -> str:
307
+ s = re.sub(r"\s+", " ", (s or "").strip().lower())
308
+ return s
309
+
310
+
311
+ def hash_text(text: str) -> str:
312
+ import hashlib
313
+ return hashlib.sha256(normalize_text(text).encode("utf-8")).hexdigest()
314
+
315
+
316
+ def get_banned_words() -> List[str]:
317
+ return [w.strip().lower() for w in read_text(BANNED_WORDS_PATH).splitlines() if w.strip()]
318
+
319
+
320
+ def detect_spanish(text: str) -> bool:
321
+ try:
322
+ return detect(text) == "es"
323
+ except LangDetectException:
324
+ return False
325
+
326
+
327
+ def contains_offensive_content(text: str) -> bool:
328
+ lowered = normalize_text(text)
329
+ return any(word in lowered for word in get_banned_words())
330
+
331
+
332
+ def repeated_submission(user_id: str, text: str) -> bool:
333
+ reto_hash = hash_text(text)
334
+ con = sqlite3.connect(DB_PATH)
335
+ cur = con.cursor()
336
+ cur.execute("""
337
+ SELECT COUNT(*) FROM submissions_log
338
+ WHERE user_id = ?
339
+ AND reto_hash = ?
340
+ AND datetime(created_at) >= datetime('now', '-1 hour')
341
+ """, (user_id, reto_hash))
342
+ count = cur.fetchone()[0]
343
+ con.close()
344
+ max_same = load_settings().get("max_same_text_per_hour", 1)
345
+ return count >= max_same
346
+
347
+
348
+ def log_submission(user_id: str, text: str) -> None:
349
+ con = sqlite3.connect(DB_PATH)
350
+ cur = con.cursor()
351
+ cur.execute("""
352
+ INSERT INTO submissions_log (user_id, reto_hash, reto_text, created_at)
353
+ VALUES (?, ?, ?, ?)
354
+ """, (user_id, hash_text(text), text, datetime.utcnow().isoformat()))
355
+ con.commit()
356
+ con.close()
357
+
358
+
359
+ def l0_validate(user_id: str, reto: str) -> Tuple[bool, str]:
360
+ s = load_settings()
361
+ text = (reto or "").strip()
362
+ if len(text) < s["min_chars_reto"]:
363
+ return False, "El reto debe tener al menos 100 caracteres para poder evaluarlo adecuadamente."
364
+ if len(text) > s["max_chars_reto"]:
365
+ return False, "El reto no debe exceder 2000 caracteres."
366
+ if not detect_spanish(text):
367
+ return False, "El reto debe estar escrito en español."
368
+ if "?" not in text and "¿" not in text:
369
+ return False, "El reto debe estar formulado como una pregunta."
370
+ if contains_offensive_content(text):
371
+ return False, "El contenido no cumple con las políticas de uso del sistema."
372
+ if repeated_submission(user_id, text):
373
+ return False, "Ya has enviado este reto recientemente."
374
+ return True, "OK"
375
+
376
+
377
+ def extract_json(raw: str) -> Dict[str, Any]:
378
+ raw = (raw or "").strip()
379
+ if not raw:
380
+ return {}
381
+ try:
382
+ return json.loads(raw)
383
+ except Exception:
384
+ pass
385
+ match = re.search(r"\{.*\}", raw, flags=re.S)
386
+ if match:
387
+ try:
388
+ return json.loads(match.group(0))
389
+ except Exception:
390
+ return {}
391
+ return {}
392
+
393
+
394
+ def hf_generate_json(model: str, prompt: str, max_new_tokens: int = 700) -> Dict[str, Any]:
395
+ client = build_client()
396
+ if client is None:
397
+ return {}
398
+ try:
399
+ # Works with current HF router style for many instruct models
400
+ response = client.chat.completions.create(
401
+ model=model,
402
+ messages=[
403
+ {"role": "system", "content": "Responde solamente JSON válido, sin markdown."},
404
+ {"role": "user", "content": prompt},
405
+ ],
406
+ max_tokens=max_new_tokens,
407
+ temperature=0.2,
408
+ )
409
+ text = response.choices[0].message.content
410
+ return extract_json(text)
411
+ except Exception:
412
+ try:
413
+ text = client.text_generation(
414
+ prompt,
415
+ model=model,
416
+ max_new_tokens=max_new_tokens,
417
+ temperature=0.2,
418
+ return_full_text=False,
419
+ )
420
+ return extract_json(text)
421
+ except Exception:
422
+ return {}
423
+
424
+
425
+ def keyword_score(text: str, patterns: List[str]) -> int:
426
+ t = normalize_text(text)
427
+ return sum(1 for p in patterns if p in t)
428
+
429
+
430
+ def heuristic_l1(reto: str) -> Dict[str, Any]:
431
+ score = 0
432
+ score += keyword_score(reto, ["actores", "comunidades", "instituciones", "diversidad", "intereses", "perspectivas"])
433
+ score += keyword_score(reto, ["incertidumbre", "impredecible", "complejo", "no lineal", "emerge", "emergente"])
434
+ score += keyword_score(reto, ["adaptación", "aprendizaje", "experiment", "piloto", "iter", "restric"])
435
+ decision = "SI" if score >= 2 else "NO"
436
+ confidence = min(0.55 + (score * 0.10), 0.92) if decision == "SI" else min(0.60 + ((2-score) * 0.08), 0.90)
437
+ return {"decision": decision, "confidence": round(confidence, 2), "reason": f"Heurística local con {score} señales"}
438
+
439
+
440
+ def heuristic_l2(reto: str) -> Dict[str, Any]:
441
+ t = normalize_text(reto)
442
+ signals = {
443
+ "C1": ["incertid", "impredec", "sin solución única", "no hay solución única", "ambigu", "emerge"],
444
+ "C2": ["actores", "comunidades", "instituciones", "gobierno", "empresa", "familias", "organizaciones"],
445
+ "C3": ["interdepend", "sistém", "múltiples dimensiones", "afecta", "territorial"],
446
+ "C4": ["colabor", "co-crea", "aprendizaje colectivo", "participa", "emerge"],
447
+ "C5": ["ético", "legal", "restric", "límite", "condiciones habilitadoras"],
448
+ "C6": ["piloto", "experimento", "iter", "probar", "seguro para fallar", "observ"],
449
+ "C7": ["aprendiz", "adapt", "resilien", "patrones", "ajuste continuo"],
450
+ }
451
+ result = {}
452
+ for cid, pats in signals.items():
453
+ hits = sum(1 for p in pats if p in t)
454
+ if hits >= 2:
455
+ status = "CUMPLE"
456
+ conf = 0.84
457
+ elif hits == 1:
458
+ status = "INCIERTO"
459
+ conf = 0.62
460
+ else:
461
+ status = "NO_CUMPLE"
462
+ conf = 0.70
463
+ result[cid] = {
464
+ "status": status,
465
+ "justification": f"Detección heurística local con {hits} señales.",
466
+ "confidence": conf
467
+ }
468
+ result["summary"] = "Evaluación generada con heurísticas locales por ausencia o fallo del modelo remoto."
469
+ return result
470
+
471
+
472
+ def evaluate_l1(reto: str) -> Dict[str, Any]:
473
+ settings = load_settings()
474
+ prompt = read_text(PROMPTS_DIR / "l1.txt", PROMPT_L1).format(reto=reto)
475
+ for model in settings["models"]["l1"]:
476
+ out = hf_generate_json(model, prompt, max_new_tokens=120)
477
+ if out.get("decision") in {"SI", "NO"}:
478
+ out["model"] = model
479
+ out["level"] = "L1"
480
+ return out
481
+ out = heuristic_l1(reto)
482
+ out["model"] = "heuristic-local"
483
+ out["level"] = "L1"
484
+ return out
485
+
486
+
487
+ def evaluate_l2(reto: str) -> Dict[str, Any]:
488
+ settings = load_settings()
489
+ prompt = read_text(PROMPTS_DIR / "l2.txt", PROMPT_L2).format(reto=reto)
490
+ for model in settings["models"]["l2"]:
491
+ out = hf_generate_json(model, prompt, max_new_tokens=900)
492
+ if out.get("C1"):
493
+ out["model"] = model
494
+ out["level"] = "L2"
495
+ return out
496
+ out = heuristic_l2(reto)
497
+ out["model"] = "heuristic-local"
498
+ out["level"] = "L2"
499
+ return out
500
+
501
+
502
+ def evaluate_l3(reto: str) -> Dict[str, Any]:
503
+ settings = load_settings()
504
+ prompt = read_text(PROMPTS_DIR / "l3.txt", PROMPT_L3).format(reto=reto)
505
+ for model in settings["models"]["l3"]:
506
+ out = hf_generate_json(model, prompt, max_new_tokens=1300)
507
+ if out.get("C1"):
508
+ out["model"] = model
509
+ out["level"] = "L3"
510
+ return out
511
+ out = heuristic_l2(reto)
512
+ for cid in [f"C{i}" for i in range(1, 8)]:
513
+ if cid in out:
514
+ if out[cid]["status"] == "INCIERTO":
515
+ out[cid]["status"] = "NO_CUMPLE"
516
+ out[cid]["confidence"] = 0.58
517
+ out[cid]["justification"] = "Fallback local sin evidencia suficiente."
518
+ out["global_summary"] = "Fallback local activado por fallo del modelo remoto."
519
+ out["model"] = "heuristic-local"
520
+ out["level"] = "L3"
521
+ return out
522
+
523
+
524
+ def evaluate_l4(reto: str) -> Dict[str, Any]:
525
+ settings = load_settings()
526
+ prompt = read_text(PROMPTS_DIR / "l3.txt", PROMPT_L3).format(reto=reto)
527
+ for model in settings["models"]["l4"]:
528
+ out = hf_generate_json(model, prompt, max_new_tokens=1400)
529
+ if out.get("C1"):
530
+ out["model"] = model
531
+ out["level"] = "L4"
532
+ return out
533
+ return evaluate_l3(reto)
534
+
535
+
536
+ def count_statuses(result: Dict[str, Any]) -> Dict[str, int]:
537
+ counts = {"CUMPLE": 0, "NO_CUMPLE": 0, "INCIERTO": 0}
538
+ for cid in [f"C{i}" for i in range(1, 8)]:
539
+ item = result.get(cid, {})
540
+ status = item.get("status")
541
+ if status in counts:
542
+ counts[status] += 1
543
+ return counts
544
+
545
+
546
+ def avg_confidence(result: Dict[str, Any]) -> float:
547
+ vals = []
548
+ for cid in [f"C{i}" for i in range(1, 8)]:
549
+ conf = result.get(cid, {}).get("confidence")
550
+ if isinstance(conf, (int, float)):
551
+ vals.append(float(conf))
552
+ return round(sum(vals) / len(vals), 3) if vals else 0.0
553
+
554
+
555
+ def build_feedback_table(result: Dict[str, Any]) -> str:
556
+ rows = []
557
+ for cid in [f"C{i}" for i in range(1, 8)]:
558
+ item = result.get(cid, {})
559
+ status = item.get("status", "N/D")
560
+ emoji = "✓" if status == "CUMPLE" else "⚠" if status == "INCIERTO" else "✗"
561
+ just = item.get("justification", "")
562
+ rows.append(f"| {emoji} | {cid} | {CYNEFIN_LABELS[cid]} | {status} | {just} |")
563
+ return "\n".join([
564
+ "| Indicador | ID | Característica | Estado | Justificación |",
565
+ "|---|---|---|---|---|",
566
+ *rows
567
+ ])
568
+
569
+
570
+ def save_run(user_id: str, reto_text: str, status: str, level_used: str, confidence: float, result_json: Dict[str, Any]) -> str:
571
+ run_id = str(uuid4())
572
+ con = sqlite3.connect(DB_PATH)
573
+ cur = con.cursor()
574
+ cur.execute("""
575
+ INSERT INTO challenge_runs (id, user_id, reto_text, result_json, status, level_used, confidence, created_at)
576
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
577
+ """, (
578
+ run_id, user_id, reto_text, json.dumps(result_json, ensure_ascii=False), status, level_used, confidence, datetime.utcnow().isoformat()
579
+ ))
580
+ con.commit()
581
+ con.close()
582
+ return run_id
583
+
584
+
585
+ def validate_reto(reto: str, session: Dict[str, Any]) -> Tuple[str, str, Dict[str, Any], gr.update]:
586
+ session = session or {}
587
+ user_id = session.get("user_id") or str(uuid4())
588
+ session["user_id"] = user_id
589
+
590
+ ok, msg = l0_validate(user_id, reto)
591
+ if not ok:
592
+ return (
593
+ f"### Validación L0\n\n❌ **Error**\n\n{msg}",
594
+ "",
595
+ session,
596
+ gr.update(visible=False)
597
+ )
598
+
599
+ start = time.time()
600
+ log_submission(user_id, reto)
601
+
602
+ # L1
603
+ l1 = evaluate_l1(reto)
604
+ if l1.get("decision") == "NO":
605
+ status = "rejected"
606
+ elapsed = time.time() - start
607
+ payload = {
608
+ "level_used": "L1",
609
+ "elapsed_seconds": round(elapsed, 2),
610
+ "l1": l1,
611
+ "reason": "El reto no parece ser lo suficientemente complejo."
612
+ }
613
+ save_run(user_id, reto, status, "L1", float(l1.get("confidence", 0.0)), payload)
614
+ session["reto_validado"] = False
615
+ session["reto_text"] = reto
616
+ return (
617
+ "### Resultado de Validación\n\n❌ **Tu reto no cumple con suficientes características de complejidad.**\n\n"
618
+ f"Motivo inicial\n\n- {l1.get('reason', 'Clasificación rápida negativa')}\n\n"
619
+ "Sugerencia\n\n- Incorpora incertidumbre real, varios actores y la idea de aprendizaje adaptativo.",
620
+ "",
621
+ session,
622
+ gr.update(visible=False)
623
+ )
624
+
625
+ if float(l1.get("confidence", 0.0)) >= load_settings()["confidence_threshold_l1"]:
626
+ # Acepta con evidencia mínima y dispara L2 solo para feedback estructurado
627
+ l2 = evaluate_l2(reto)
628
+ counts = count_statuses(l2)
629
+ avg_conf = avg_confidence(l2)
630
+ passed = counts["CUMPLE"] >= load_settings()["required_cynefin_to_pass"]
631
+ level_used = "L2"
632
+ status = "accepted" if passed else "rejected"
633
+ elapsed = time.time() - start
634
+ payload = {"l1": l1, "l2": l2, "elapsed_seconds": round(elapsed, 2)}
635
+ save_run(user_id, reto, status, level_used, avg_conf, payload)
636
+ session["reto_validado"] = passed
637
+ session["reto_text"] = reto
638
+ session["validation_result"] = payload
639
+ summary = build_feedback_table(l2)
640
+ if passed:
641
+ return (
642
+ "### Resultado de Validación\n\n✅ **¡Excelente! Tu reto cumple con las características de un reto complejo.**\n\n"
643
+ f"- Nivel usado: **{level_used}**\n- Modelo: **{l2.get('model','N/D')}**\n- Confianza promedio: **{avg_conf:.0%}**\n- Tiempo: **{payload['elapsed_seconds']} s**\n\n"
644
+ + summary,
645
+ reto,
646
+ session,
647
+ gr.update(visible=True)
648
+ )
649
+ return (
650
+ "### Resultado de Validación\n\n❌ **Tu reto no cumple con suficientes características de complejidad.**\n\n"
651
+ f"- Nivel usado: **{level_used}**\n- Confianza promedio: **{avg_conf:.0%}**\n\n"
652
+ + summary,
653
+ "",
654
+ session,
655
+ gr.update(visible=False)
656
+ )
657
+
658
+ # L2
659
+ l2 = evaluate_l2(reto)
660
+ counts = count_statuses(l2)
661
+ avg_conf = avg_confidence(l2)
662
+ if counts["CUMPLE"] >= load_settings()["required_cynefin_to_pass"] and counts["INCIERTO"] == 0:
663
+ level_used = "L2"
664
+ elapsed = time.time() - start
665
+ payload = {"l1": l1, "l2": l2, "elapsed_seconds": round(elapsed, 2)}
666
+ save_run(user_id, reto, "accepted", level_used, avg_conf, payload)
667
+ session["reto_validado"] = True
668
+ session["reto_text"] = reto
669
+ session["validation_result"] = payload
670
+ return (
671
+ "### Resultado de Validación\n\n✅ **¡Excelente! Tu reto cumple con las características de un reto complejo.**\n\n"
672
+ f"- Nivel usado: **L2**\n- Modelo: **{l2.get('model','N/D')}**\n- Confianza promedio: **{avg_conf:.0%}**\n- Tiempo: **{payload['elapsed_seconds']} s**\n\n"
673
+ + build_feedback_table(l2),
674
+ reto,
675
+ session,
676
+ gr.update(visible=True)
677
+ )
678
+
679
+ if counts["CUMPLE"] < load_settings()["required_cynefin_to_pass"] and avg_conf >= load_settings()["confidence_threshold_l2"]:
680
+ elapsed = time.time() - start
681
+ payload = {"l1": l1, "l2": l2, "elapsed_seconds": round(elapsed, 2)}
682
+ save_run(user_id, reto, "rejected", "L2", avg_conf, payload)
683
+ session["reto_validado"] = False
684
+ session["reto_text"] = reto
685
+ return (
686
+ "### Resultado de Validación\n\n❌ **Tu reto no cumple con suficientes características de complejidad.**\n\n"
687
+ f"- Nivel usado: **L2**\n- Confianza promedio: **{avg_conf:.0%}**\n\n"
688
+ + build_feedback_table(l2),
689
+ "",
690
+ session,
691
+ gr.update(visible=False)
692
+ )
693
+
694
+ # L3
695
+ l3 = evaluate_l3(reto)
696
+ counts3 = count_statuses(l3)
697
+ avg_conf3 = avg_confidence(l3)
698
+
699
+ if counts3["CUMPLE"] >= load_settings()["required_cynefin_to_pass"] and avg_conf3 >= 0.70:
700
+ elapsed = time.time() - start
701
+ payload = {"l1": l1, "l2": l2, "l3": l3, "elapsed_seconds": round(elapsed, 2)}
702
+ save_run(user_id, reto, "accepted", "L3", avg_conf3, payload)
703
+ session["reto_validado"] = True
704
+ session["reto_text"] = reto
705
+ session["validation_result"] = payload
706
+ return (
707
+ "### Resultado de Validación\n\n✅ **¡Excelente! Tu reto cumple con las características de un reto complejo.**\n\n"
708
+ f"- Nivel usado: **L3**\n- Modelo: **{l3.get('model','N/D')}**\n- Confianza promedio: **{avg_conf3:.0%}**\n- Tiempo: **{payload['elapsed_seconds']} s**\n\n"
709
+ + build_feedback_table(l3),
710
+ reto,
711
+ session,
712
+ gr.update(visible=True)
713
+ )
714
+
715
+ low_conf = sum(1 for i in range(1, 8) if float(l3.get(f"C{i}", {}).get("confidence", 0.0)) < 0.70)
716
+ if low_conf >= load_settings()["premium_activation_min_ambiguities"]:
717
+ l4 = evaluate_l4(reto)
718
+ counts4 = count_statuses(l4)
719
+ avg_conf4 = avg_confidence(l4)
720
+ passed = counts4["CUMPLE"] >= load_settings()["required_cynefin_to_pass"]
721
+ elapsed = time.time() - start
722
+ payload = {"l1": l1, "l2": l2, "l3": l3, "l4": l4, "elapsed_seconds": round(elapsed, 2)}
723
+ save_run(user_id, reto, "accepted" if passed else "rejected", "L4", avg_conf4, payload)
724
+ session["reto_validado"] = passed
725
+ session["reto_text"] = reto
726
+ session["validation_result"] = payload
727
+ if passed:
728
+ return (
729
+ "### Resultado de Validación\n\n✅ **¡Excelente! Tu reto cumple con las características de un reto complejo.**\n\n"
730
+ f"- Nivel usado: **L4**\n- Modelo: **{l4.get('model','N/D')}**\n- Confianza promedio: **{avg_conf4:.0%}**\n- Tiempo: **{payload['elapsed_seconds']} s**\n\n"
731
+ + build_feedback_table(l4),
732
+ reto,
733
+ session,
734
+ gr.update(visible=True)
735
+ )
736
+ return (
737
+ "### Resultado de Validación\n\n❌ **Tu reto no cumple con suficientes características de complejidad.**\n\n"
738
+ f"- Nivel usado: **L4**\n- Confianza promedio: **{avg_conf4:.0%}**\n\n"
739
+ + build_feedback_table(l4),
740
+ "",
741
+ session,
742
+ gr.update(visible=False)
743
+ )
744
+
745
+ elapsed = time.time() - start
746
+ payload = {"l1": l1, "l2": l2, "l3": l3, "elapsed_seconds": round(elapsed, 2)}
747
+ save_run(user_id, reto, "rejected", "L3", avg_conf3, payload)
748
+ session["reto_validado"] = False
749
+ session["reto_text"] = reto
750
+ return (
751
+ "### Resultado de Validación\n\n❌ **Tu reto no cumple con suficientes características de complejidad.**\n\n"
752
+ f"- Nivel usado: **L3**\n- Confianza promedio: **{avg_conf3:.0%}**\n\n"
753
+ + build_feedback_table(l3),
754
+ "",
755
+ session,
756
+ gr.update(visible=False)
757
+ )
758
+
759
+
760
+ def actor_count(text: str) -> int:
761
+ pieces = [p.strip() for p in re.split(r"[,\n;]+", text or "") if p.strip()]
762
+ return len(pieces)
763
+
764
+
765
+ def validate_canvas_fields(definicion, relevancia, conexion, actores, gobernanza) -> Optional[str]:
766
+ if len((definicion or "").strip()) < 50:
767
+ return "La sección Definición requiere al menos 50 caracteres."
768
+ if len((relevancia or "").strip()) < 50:
769
+ return "La sección Relevancia requiere al menos 50 caracteres."
770
+ if len((conexion or "").strip()) < 50:
771
+ return "La sección Conexión Personal requiere al menos 50 caracteres."
772
+ if actor_count(actores) < 2:
773
+ return "La sección Actores requiere al menos 2 actores mencionados."
774
+ if len((gobernanza or "").strip()) < 100:
775
+ return "La sección Gobernanza requiere al menos 100 caracteres."
776
+ return None
777
+
778
+
779
+ def load_font(size: int, bold: bool = False):
780
+ candidates = [
781
+ "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf" if bold else "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
782
+ "/usr/share/fonts/truetype/liberation2/LiberationSans-Bold.ttf" if bold else "/usr/share/fonts/truetype/liberation2/LiberationSans-Regular.ttf",
783
+ ]
784
+ for path in candidates:
785
+ if Path(path).exists():
786
+ return ImageFont.truetype(path, size)
787
+ return ImageFont.load_default()
788
+
789
+
790
+ def wrap_text(draw, text, font, max_width):
791
+ words = (text or "").split()
792
+ lines = []
793
+ current = ""
794
+ for word in words:
795
+ test = current + (" " if current else "") + word
796
+ bbox = draw.textbbox((0, 0), test, font=font)
797
+ width = bbox[2] - bbox[0]
798
+ if width <= max_width:
799
+ current = test
800
+ else:
801
+ if current:
802
+ lines.append(current)
803
+ current = word
804
+ if current:
805
+ lines.append(current)
806
+ return lines
807
+
808
+
809
+ def draw_panel(draw, xy, title, body, font_title, font_body, colors):
810
+ x1, y1, x2, y2 = xy
811
+ draw.rounded_rectangle(xy, radius=18, fill=colors["panel_bg"], outline=colors["panel_border"], width=2)
812
+ draw.text((x1 + 24, y1 + 20), title, fill=colors["text_color"], font=font_title)
813
+ available_width = (x2 - x1) - 48
814
+ lines = wrap_text(draw, body, font_body, available_width)
815
+ max_lines = max(4, int(((y2 - y1) - 90) / 28))
816
+ if len(lines) > max_lines:
817
+ lines = lines[:max_lines]
818
+ if lines:
819
+ lines[-1] = lines[-1][:max(0, len(lines[-1]) - 3)] + "..."
820
+ y = y1 + 68
821
+ for line in lines:
822
+ draw.text((x1 + 24, y), line, fill=colors["text_color"], font=font_body)
823
+ y += 28
824
+
825
+
826
+ def generate_canvas_image(reto: str, definicion: str, relevancia: str, conexion: str, actores: str, gobernanza: str, iniciativas: str, user_id: str) -> Path:
827
+ s = load_settings()["canvas"]
828
+ W, H = s["width"], s["height"]
829
+ img = Image.new("RGBA", (W, H), s["background_color"])
830
+ draw = ImageDraw.Draw(img)
831
+
832
+ font_header = load_font(36, bold=True)
833
+ font_title = load_font(24, bold=True)
834
+ font_body = load_font(18, bold=False)
835
+ font_footer = load_font(18, bold=False)
836
+
837
+ colors = {
838
+ "header_color": s["header_color"],
839
+ "panel_bg": s["panel_bg"],
840
+ "panel_border": s["panel_border"],
841
+ "text_color": s["text_color"],
842
+ }
843
+
844
+ # Header
845
+ draw.rounded_rectangle((40, 30, W - 40, 180), radius=24, fill=colors["header_color"])
846
+ header_lines = textwrap.wrap(reto, width=72)[:3]
847
+ y = 58
848
+ for line in header_lines:
849
+ draw.text((80, y), line, fill="white", font=font_header)
850
+ y += 42
851
+
852
+ # Grid
853
+ left_x1, left_x2 = 40, 930
854
+ right_x1, right_x2 = 990, W - 40
855
+
856
+ draw_panel(draw, (left_x1, 220, left_x2, 450), "1. Definición", definicion, font_title, font_body, colors)
857
+ draw_panel(draw, (left_x1, 470, left_x2, 700), "2. Relevancia", relevancia, font_title, font_body, colors)
858
+ draw_panel(draw, (left_x1, 720, left_x2, 940), "3. Conexión Personal", conexion, font_title, font_body, colors)
859
+
860
+ draw_panel(draw, (right_x1, 220, right_x2, 450), "4. Actores", actores, font_title, font_body, colors)
861
+ draw_panel(draw, (right_x1, 470, right_x2, 940), "5. Gobernanza", gobernanza, font_title, font_body, colors)
862
+
863
+ if (iniciativas or "").strip():
864
+ draw_panel(draw, (40, 960, W - 40, H - 100), "6. Iniciativas", iniciativas, font_title, font_body, colors)
865
+
866
+ # Footer
867
+ footer_y = H - 70
868
+ footer_text = f"Generado el {datetime.now().strftime('%Y-%m-%d %H:%M')} • {APP_NAME}"
869
+ draw.text((60, footer_y), footer_text, fill=colors["text_color"], font=font_footer)
870
+
871
+ if LOGO_PATH.exists():
872
+ try:
873
+ logo = Image.open(LOGO_PATH).convert("RGBA")
874
+ logo.thumbnail((260, 60))
875
+ img.alpha_composite(logo, (W - logo.width - 60, H - logo.height - 30))
876
+ except Exception:
877
+ pass
878
+
879
+ out = TMP_DIR / f"canvas_{user_id}_{int(time.time())}.png"
880
+ img.save(out, "PNG", dpi=(s["dpi"], s["dpi"]))
881
+ return out
882
+
883
+
884
+ def save_canvas(user_id: str, reto: str, canvas_dict: Dict[str, Any], png_path: Path) -> str:
885
+ canvas_id = str(uuid4())
886
+ con = sqlite3.connect(DB_PATH)
887
+ cur = con.cursor()
888
+ cur.execute("""
889
+ INSERT INTO canvases (id, user_id, reto_title, reto_text, canvas_json, png_path, created_at)
890
+ VALUES (?, ?, ?, ?, ?, ?, ?)
891
+ """, (
892
+ canvas_id,
893
+ user_id,
894
+ reto[:180],
895
+ reto,
896
+ json.dumps(canvas_dict, ensure_ascii=False),
897
+ str(png_path),
898
+ datetime.utcnow().isoformat()
899
+ ))
900
+ con.commit()
901
+ con.close()
902
+ return canvas_id
903
+
904
+
905
+ def preview_canvas(reto, definicion, relevancia, conexion, actores, gobernanza, iniciativas, session):
906
+ session = session or {}
907
+ if not session.get("reto_validado"):
908
+ return "Primero valida un reto complejo.", None, session
909
+ err = validate_canvas_fields(definicion, relevancia, conexion, actores, gobernanza)
910
+ if err:
911
+ return err, None, session
912
+ user_id = session.get("user_id", str(uuid4()))
913
+ png = generate_canvas_image(reto, definicion, relevancia, conexion, actores, gobernanza, iniciativas, user_id)
914
+ session["last_canvas_preview"] = str(png)
915
+ return "Vista previa generada correctamente.", str(png), session
916
+
917
+
918
+ def generate_canvas(reto, definicion, relevancia, conexion, actores, gobernanza, iniciativas, session):
919
+ session = session or {}
920
+ if not session.get("reto_validado"):
921
+ return "Primero valida un reto complejo.", None, session
922
+ err = validate_canvas_fields(definicion, relevancia, conexion, actores, gobernanza)
923
+ if err:
924
+ return err, None, session
925
+
926
+ user_id = session.get("user_id", str(uuid4()))
927
+ png = generate_canvas_image(reto, definicion, relevancia, conexion, actores, gobernanza, iniciativas, user_id)
928
+ canvas_dict = {
929
+ "definicion": definicion,
930
+ "relevancia": relevancia,
931
+ "conexion": conexion,
932
+ "actores": actores,
933
+ "gobernanza": gobernanza,
934
+ "iniciativas": iniciativas,
935
+ }
936
+ save_canvas(user_id, reto, canvas_dict, png)
937
+ session["last_canvas_preview"] = str(png)
938
+ return "Canvas generado y guardado correctamente.", str(png), session
939
+
940
+
941
+ def build_context_from_sections(values: Dict[str, str]) -> str:
942
+ lines = []
943
+ for key, title, _, _ in CANVAS_SECTIONS:
944
+ v = (values.get(key) or "").strip()
945
+ if v:
946
+ lines.append(f"{title}: {v}")
947
+ return "\n".join(lines) if lines else "Sin contexto previo"
948
+
949
+
950
+ def suggest_for_section(section_key: str, reto: str, definicion, relevancia, conexion, actores, gobernanza, iniciativas):
951
+ field_map = {
952
+ "definicion": ("Definición", "¿Qué aspectos fundamentales definen el reto propuesto?"),
953
+ "relevancia": ("Relevancia", "¿Por qué creemos que este reto es relevante?"),
954
+ "conexion": ("Conexión Personal", "¿Cómo se conecta el reto con mi ámbito de trabajo?"),
955
+ "actores": ("Actores", "¿Qué actores están involucrados y qué roles desempeñan en el reto?"),
956
+ "gobernanza": ("Gobernanza", "¿Por qué intuyo que la gobernanza colaborativa y anticipatoria puede contribuir a resolver el reto?"),
957
+ "iniciativas": ("Iniciativas", "¿Qué iniciativas, alianzas, redes o proyectos conocemos relacionados con el reto? ¿Cuál es el enfoque que tienen?"),
958
+ }
959
+ if section_key not in field_map:
960
+ return "Selecciona una sección válida."
961
+
962
+ values = {
963
+ "definicion": definicion,
964
+ "relevancia": relevancia,
965
+ "conexion": conexion,
966
+ "actores": actores,
967
+ "gobernanza": gobernanza,
968
+ "iniciativas": iniciativas,
969
+ }
970
+ seccion, pregunta = field_map[section_key]
971
+ contexto = build_context_from_sections(values)
972
+ prompt = read_text(PROMPTS_DIR / "suggestions.txt", PROMPT_SUGGESTIONS).format(
973
+ reto=reto, contexto=contexto, seccion=seccion, pregunta=pregunta
974
+ )
975
+
976
+ settings = load_settings()
977
+ for model in settings["models"]["l2"]:
978
+ out = hf_generate_json(model, prompt, max_new_tokens=300)
979
+ if isinstance(out.get("suggestions"), list) and out["suggestions"]:
980
+ return "\n\n".join([f"{i+1}. {s}" for i, s in enumerate(out["suggestions"][:3])])
981
+
982
+ # Fallback local
983
+ fallbacks = {
984
+ "definicion": [
985
+ "Delimita el reto como un sistema abierto con incertidumbre y sin respuesta única.",
986
+ "Identifica tensiones entre actores, capacidades institucionales y contexto territorial.",
987
+ "Aclara qué dimensión del problema vuelve inviable una solución lineal."
988
+ ],
989
+ "relevancia": [
990
+ "Explica por qué el reto afecta resultados públicos, legitimidad y coordinación.",
991
+ "Muestra consecuencias sistémicas si no se interviene a tiempo.",
992
+ "Conecta el reto con impactos sociales, económicos o institucionales."
993
+ ],
994
+ "conexion": [
995
+ "Describe qué rol tienes frente al reto y qué capacidades puedes movilizar.",
996
+ "Explica qué decisiones o procesos de tu trabajo se ven afectados.",
997
+ "Vincula el reto con tus responsabilidades, redes y márgenes de acción."
998
+ ],
999
+ "actores": [
1000
+ "Lista actores públicos, privados y comunitarios y su interés en el reto.",
1001
+ "Distingue quién habilita, quién bloquea, quién implementa y quién recibe impacto.",
1002
+ "Incluye al menos dos actores con roles distintos y posibles tensiones."
1003
+ ],
1004
+ "gobernanza": [
1005
+ "Explica por qué la coordinación entre actores puede producir respuestas emergentes.",
1006
+ "Describe cómo pequeñas pruebas ayudarían a aprender antes de escalar.",
1007
+ "Menciona restricciones éticas, legales o institucionales que orientan la acción."
1008
+ ],
1009
+ "iniciativas": [
1010
+ "Anota programas, alianzas o pilotos previos relacionados con el reto.",
1011
+ "Describe brevemente su enfoque y qué aprendizaje podrían aportar.",
1012
+ "Incluye redes, proyectos territoriales o marcos institucionales existentes."
1013
+ ],
1014
+ }
1015
+ return "\n\n".join([f"{i+1}. {s}" for i, s in enumerate(fallbacks[section_key])])
1016
+
1017
+
1018
+ def load_examples_text():
1019
+ try:
1020
+ examples = json.loads(EXAMPLES_PATH.read_text(encoding="utf-8"))
1021
+ return [[ex["text"]] for ex in examples]
1022
+ except Exception:
1023
+ return [[DEFAULT_EXAMPLES[0]["text"]]]
1024
+
1025
+
1026
+ def reset_session():
1027
+ return {}, "", "", "", "", "", "", "", "", None, gr.update(visible=False)
1028
+
1029
+
1030
+ def build_app():
1031
+ examples = load_examples_text()
1032
+ theme = gr.themes.Soft(primary_hue="blue", secondary_hue="slate")
1033
+
1034
+ css = """
1035
+ .app-title {font-size: 28px; font-weight: 700; margin-bottom: 6px;}
1036
+ .app-subtitle {color: #475569; margin-bottom: 16px;}
1037
+ .ok-box {border: 1px solid #dbeafe; background: #eff6ff; border-radius: 12px; padding: 12px;}
1038
+ """
1039
+
1040
+ with gr.Blocks(theme=theme, css=css, title=APP_NAME) as demo:
1041
+ session = gr.State({"user_id": str(uuid4())})
1042
+
1043
+ gr.Markdown(f"<div class='app-title'>{APP_NAME}</div>")
1044
+ gr.Markdown(
1045
+ "<div class='app-subtitle'>Validación de retos complejos según Cynefin con cascade routing y generación de canvas PNG.</div>"
1046
+ )
1047
+
1048
+ with gr.Tab("1. Validación del reto"):
1049
+ reto_input = gr.Textbox(
1050
+ label="Describe tu reto complejo",
1051
+ placeholder="Ejemplo: ¿Cómo pueden las comunidades locales crear redes de apoyo emocional y social que funcionen en contextos de diversidad cultural y económica, sin imponer modelos únicos?",
1052
+ lines=8,
1053
+ max_lines=12,
1054
+ info="Mínimo 100 caracteres. Debe estar en español y formulado como pregunta.",
1055
+ )
1056
+ gr.Examples(examples=examples, inputs=[reto_input], label="Ejemplos de retos")
1057
+ with gr.Row():
1058
+ validate_btn = gr.Button("Validar reto", variant="primary")
1059
+ clear_btn = gr.Button("Limpiar")
1060
+ validation_md = gr.Markdown()
1061
+ reto_validado_hidden = gr.Textbox(visible=False)
1062
+ continue_btn = gr.Button("Continuar al Canvas", visible=False)
1063
+
1064
+ with gr.Tab("2. Canvas interactivo"):
1065
+ gr.Markdown("Completa el canvas. La ayuda con IA usa el nivel L2 solo cuando la solicitas.")
1066
+ reto_title = gr.Textbox(label="Reto validado", lines=3, interactive=True)
1067
+ with gr.Row():
1068
+ section_selector = gr.Dropdown(
1069
+ choices=[(title, key) for key, title, _, _ in CANVAS_SECTIONS],
1070
+ value="definicion",
1071
+ label="Sección para sugerencias"
1072
+ )
1073
+ suggest_btn = gr.Button("Ayúdame a completar")
1074
+ suggestions_box = gr.Markdown()
1075
+
1076
+ definicion = gr.Textbox(label="1. Definición", lines=4)
1077
+ relevancia = gr.Textbox(label="2. Relevancia", lines=4)
1078
+ conexion = gr.Textbox(label="3. Conexión Personal", lines=4)
1079
+ actores = gr.Textbox(label="4. Actores", lines=4, info="Menciona al menos dos actores separados por coma o salto de línea.")
1080
+ gobernanza = gr.Textbox(label="5. Gobernanza", lines=6)
1081
+ iniciativas = gr.Textbox(label="6. Iniciativas", lines=4)
1082
+
1083
+ with gr.Row():
1084
+ preview_btn = gr.Button("Vista previa del canvas")
1085
+ generate_btn = gr.Button("Generar Canvas", variant="primary")
1086
+
1087
+ canvas_status = gr.Markdown()
1088
+ canvas_image = gr.Image(label="Vista previa PNG", type="filepath")
1089
+ canvas_file = gr.File(label="Descargar PNG")
1090
+
1091
+ validate_btn.click(
1092
+ fn=validate_reto,
1093
+ inputs=[reto_input, session],
1094
+ outputs=[validation_md, reto_title, session, continue_btn]
1095
+ )
1096
+
1097
+ continue_btn.click(
1098
+ fn=lambda reto: reto,
1099
+ inputs=[reto_title],
1100
+ outputs=[reto_title]
1101
+ )
1102
+
1103
+ suggest_btn.click(
1104
+ fn=suggest_for_section,
1105
+ inputs=[section_selector, reto_title, definicion, relevancia, conexion, actores, gobernanza, iniciativas],
1106
+ outputs=[suggestions_box]
1107
+ )
1108
+
1109
+ preview_btn.click(
1110
+ fn=preview_canvas,
1111
+ inputs=[reto_title, definicion, relevancia, conexion, actores, gobernanza, iniciativas, session],
1112
+ outputs=[canvas_status, canvas_image, session]
1113
+ )
1114
+
1115
+ generate_btn.click(
1116
+ fn=generate_canvas,
1117
+ inputs=[reto_title, definicion, relevancia, conexion, actores, gobernanza, iniciativas, session],
1118
+ outputs=[canvas_status, canvas_file, session]
1119
+ ).then(
1120
+ fn=lambda f: f,
1121
+ inputs=[canvas_file],
1122
+ outputs=[canvas_image]
1123
+ )
1124
+
1125
+ clear_btn.click(
1126
+ fn=reset_session,
1127
+ outputs=[session, reto_input, reto_title, definicion, relevancia, conexion, actores, gobernanza, iniciativas, canvas_image, continue_btn]
1128
+ )
1129
+
1130
+ return demo
1131
+
1132
+
1133
+ bootstrap()
1134
+ SETTINGS = load_settings()
1135
+ app = build_app()
1136
+
1137
+ if __name__ == "__main__":
1138
+ app.launch()
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ gradio>=4.44.1
2
+ huggingface_hub>=0.34.0
3
+ langdetect==1.0.9
4
+ Pillow>=10.4.0