dfsandovalp01 commited on
Commit
1b8d452
·
verified ·
1 Parent(s): db13bac

Update src/embeddings/mass_modelos_nlp_db.py

Browse files
Files changed (1) hide show
  1. src/embeddings/mass_modelos_nlp_db.py +690 -690
src/embeddings/mass_modelos_nlp_db.py CHANGED
@@ -1,690 +1,690 @@
1
-
2
- # ============================================================================
3
- # Funciones generales PLN
4
- # ============================================================================
5
-
6
- import argparse, os, json, hashlib, pandas as pd, numpy as np
7
- from pathlib import Path
8
- import re
9
-
10
- def md5_text(s: str) -> str:
11
- return hashlib.md5(s.encode('utf-8')).hexdigest()
12
-
13
- def build_ods_fingerprint(model_name: str, instruction: str, ods_texts: list) -> str:
14
- concat = model_name + "\n" + instruction + "\n" + "\n".join(ods_texts)
15
- return md5_text(concat)
16
-
17
- def ensure_out_dir(p: str):
18
- Path(p).mkdir(parents=True, exist_ok=True)
19
-
20
- def load_data(patr_tblinput: str, ods_tblinput: str):
21
- # patr = pd.read_tblinput(patr_tblinput)
22
- # ods = pd.read_tblinput(ods_tblinput)
23
- patr = pd.read_excel(patr_tblinput)#, encoding='cp1252')
24
-
25
-
26
- ods = pd.read_excel(ods_tblinput)#.iloc[:32,:]
27
- # Basic validations
28
- assert {"ID", "INICIATIVAS", "MUNICIPIO"}.issubset(patr.columns), "PATR CSV must include columns: ID, INICIATIVAS"
29
- assert {'OBJETIVO', 'OBJETIVO_META', 'INDICADORES', 'CODIGO_UNSD',
30
- 'ID_OBJETIVO', 'ID_META', 'ID_INDICADORES'}.issubset(ods.columns), "ODS CSV must include columns: OBJETIVO, OBJETIVO_META, INDICADORES, CODIGO_UNSD,ID_OBJETIVO, ID_META, ID_INDICADORES"
31
- return patr, ods
32
-
33
- def make_text_pairs(instruction: str, texts: list):
34
- return [[instruction, t if isinstance(t,str) else ""] for t in texts]
35
-
36
- def compute_embeddings(model, pairs, batch_size: int, normalize: bool):
37
- # SentenceTransformer.encode has normalize_embeddings parameter
38
- return model.encode(
39
- pairs,
40
- batch_size=batch_size,
41
- convert_to_tensor=True,
42
- show_progress_bar=True,
43
- normalize_embeddings=normalize
44
- )
45
-
46
- def cosine_sim_matrix(a, b):
47
- # a: (N,d) tensor, b: (M,d) tensor
48
- from sentence_transformers import util
49
- sims = util.cos_sim(a, b).cpu().numpy()
50
- return sims
51
-
52
- # def save_cache(cache_path: str, meta: dict, emb_np: np.ndarray):
53
- # np.savez(cache_path, embeddings=emb_np, meta=json.dumps(meta, ensure_ascii=False))
54
-
55
- # def load_cache(cache_path: str):
56
- # data = np.load(cache_path, allow_pickle=True)
57
- # emb = data["embeddings"]
58
- # meta = json.loads(str(data["meta"]))
59
- # return emb, meta
60
-
61
- def save_cache(cache_path: str, meta: dict, emb_np: np.ndarray):
62
- np.savez(cache_path, embeddings=emb_np) # solo arrays
63
- with open(cache_path + ".json", "w", encoding="utf-8") as f:
64
- json.dump(meta, f, ensure_ascii=False) # meta en JSON sidecar
65
-
66
- def load_cache(cache_path: str):
67
- emb = np.load(cache_path)["embeddings"]
68
- with open(cache_path + ".json", "r", encoding="utf-8") as f:
69
- meta = json.load(f)
70
- return emb, meta
71
-
72
- # import spacy
73
-
74
- # def limpiar_texto(texto, nlp):
75
- # """
76
- # Limpia nombres propios, entidades y caracteres especiales del texto.
77
- # Conserva la primera palabra de cada oración (aunque esté en mayúscula).
78
- # """
79
- # if not texto or not isinstance(texto, str):
80
- # return ""
81
-
82
- # # 1️⃣ Remover caracteres especiales innecesarios (antes del análisis)
83
- # # Mantiene letras, números, espacios y signos básicos de puntuación.
84
- # texto = re.sub(r"[^A-Za-zÁÉÍÓÚÜÑáéíóúüñ0-9\s.,;:!?()\-]", " ", texto)
85
-
86
- # # 2️⃣ Procesamiento lingüístico
87
- # doc = nlp(texto)
88
- # resultado = []
89
-
90
- # for sent in doc.sents:
91
- # tokens = []
92
- # for i, token in enumerate(sent):
93
- # # eliminar puntuación y símbolos
94
- # if token.is_punct or token.is_space or token.is_digit:
95
- # continue
96
- # # Mantiene primera palabra de cada oración
97
- # if i == 0:
98
- # tokens.append(token.text)
99
- # # Elimina nombres propios o entidades nombradas
100
- # elif token.pos_ == "PROPN" or token.ent_type_ in ["PER", "ORG", "LOC", "GPE"]:
101
- # continue
102
- # else:
103
- # tokens.append(token.text)
104
- # resultado.append(" ".join(tokens))
105
-
106
- # # 3️⃣ Limpiar puntuación repetida y espacios múltiples
107
- # texto_limpio = " ".join(resultado)
108
- # texto_limpio = re.sub(r"\s{2,}", " ", texto_limpio).strip()
109
-
110
- # # 4️⃣ Opcional: eliminar espacios antes de comas o puntos
111
- # texto_limpio = re.sub(r"\s+([,.!?;:])", r"\1", texto_limpio)
112
-
113
- # return texto_limpio
114
-
115
-
116
- # ============================================================================
117
- # Generador de cache para generar embeddings nuevas tablas
118
- # ============================================================================
119
-
120
- def genCache(cache_name:str, tbl_input_dir:str, out_dir:str, instruction:str, batch_size = 32, normalize = True, cache_path = None, force_recompute = False):
121
-
122
- model_name = "hkunlp/instructor-large" #help="HF model name for embeddings.")
123
- # instruction = "Representa el tema central del siguiente objetivo de desarrollo sostenible" #"Instruction for ODS texts.")
124
- ensure_out_dir(out_dir)
125
-
126
- # Load data
127
- input_df = pd.read_excel(tbl_input_dir)
128
- input_texts = (input_df["ods"].fillna("") + ". " + input_df["descripcion"].fillna("")).tolist()
129
-
130
- # Compute fingerprint and cache path
131
- fingerprint = build_ods_fingerprint(model_name, instruction, input_texts)
132
- cache_path = cache_path or os.path.join(out_dir, f"{cache_name}_{fingerprint}.npz")
133
-
134
- # Lazy import model to allow quick --help
135
- from sentence_transformers import SentenceTransformer
136
- import warnings
137
-
138
- # Silenciar warning sobre tied weights que es inofensivo
139
- warnings.filterwarnings('ignore', message='.*tied weights mapping.*')
140
-
141
- model = SentenceTransformer(model_name)
142
- input_pairs = make_text_pairs(instruction, input_texts)
143
- emb_input = compute_embeddings(model, input_pairs, batch_size=batch_size, normalize=normalize)
144
- emb_input_np = emb_input.cpu().numpy()
145
- save_cache(cache_path, {"model": model_name, "instr": instruction, "count": len(input_texts)}, emb_input_np)
146
-
147
- # ============================================================================
148
- # Función generadora tablas
149
- # ============================================================================
150
-
151
- import torch
152
- import pandas as pd
153
- import numpy as np
154
-
155
-
156
- def search_mass(path_df_iniciativas, top_ods, top_meta, top_indicador):
157
-
158
- df_iniciativas = pd.read_excel(path_df_iniciativas)
159
- df_categorias = [categoria for categoria in df_iniciativas.columns if categoria not in ['id_unico', 'iniciativa']]
160
- # patr_tblinput = 'data/raw/Copy of Iniciativas priorizadas PATR 385.xlsx' #"CSV with PATR projects (columns: id, descripcion, ...).")
161
- ods_tblinput = Path('data/raw/v2_tabla_odsDescripcion_revLA 03032026.xlsx') #Entrenamiento 3
162
- # ods_tblinput = Path('data/raw/v2_tabla_odsDescripcion_revLA.xlsx') #Entrenamiento 2
163
- # ods_tblinput = Path('data/raw/v1_tabla_odsDescripcion.xlsx') #Entrenamiento 1
164
- meta_tblinput = Path('data/raw/v1_tabla_lvlMetaOds.xlsx')
165
- indicador_tblinput = Path('data/raw/marco_ods_ids.xlsx')
166
- genero_tblinput = Path('data/raw/genero.xlsx')
167
- poblacional_tblinput = Path('data/raw/poblacional.xlsx')
168
- etnico_tblinput = Path('data/raw/etnico.xlsx')
169
- pilares_tblinput = Path('data/raw/pilares.xlsx' )
170
- categorias_tblinput = Path('data/raw/categorias.xlsx')
171
- estrategias_tblinput = Path('data/raw/estrategias.xlsx')
172
- recomendaciones_tblinput = Path('data/raw/ODS_169_metas_recomendaciones_detalladas.xlsx')
173
- out_dir = 'data/embeddings' # '/content/drive/MyDrive/Compartida/06_Desarrollo de la herramienta IA/01_MPTF /archivos_trabajo/salidas/modelo_instructor/data/out' #"Output directory.")
174
- model_name = "hkunlp/instructor-large" #help="HF model name for embeddings.")
175
- instr_proj = "Representa el propósito de desarrollo sostenible del siguiente proyecto territorial" #"Instruction for PATR projects.")
176
- instr_ods = "Representa el tema central del siguiente ODS" #"Instruction for ODS texts.")
177
- batch_size = 32 #"Batch size for encoding.")
178
- top_k = 5 #"Top-K ODS to retrieve.")
179
- normalize = True #"L2-normalize embeddings during encoding.") # Changed from "store_true" to boolean
180
- cache_path = None #"Path to cache npz for ODS embeddings (auto if not set).")
181
- force_recompute = False #"Ignore cache and recompute ODS embeddings.") # Changed from "store_true" to boolean
182
-
183
-
184
- ensure_out_dir(out_dir)
185
-
186
- #"OBJETIVO","OBJETIVO_META","INDICADORES","CODIGO_UNSD"
187
-
188
- # Load data
189
- # patr_df, ods_df = load_data(patr_tblinput, ods_tblinput)
190
- # patr_df = patr_df[['ID', 'INICIATIVAS']].drop_duplicates().reset_index(drop=True) # Reset index
191
- # patr_texts = patr_df["INICIATIVAS"].fillna("").tolist()
192
- # patr_df = pd.read_excel(patr_tblinput)
193
- ods_df = pd.read_excel(ods_tblinput)
194
- meta_df = pd.read_excel(meta_tblinput)
195
- inidicador_df = pd.read_excel(indicador_tblinput)
196
- genero_df = pd.read_excel(genero_tblinput)
197
- poblacional_df = pd.read_excel(poblacional_tblinput)
198
- etnico_df = pd.read_excel(etnico_tblinput)
199
- pilares_df = pd.read_excel(pilares_tblinput)
200
- estrategias_df = pd.read_excel(estrategias_tblinput)
201
- categorias_df = pd.read_excel(categorias_tblinput)
202
- recomendaciones_df = pd.read_excel(recomendaciones_tblinput)
203
-
204
- # nlp = spacy.load("es_core_news_md")
205
- # query = limpiar_texto(query, nlp)
206
- querys = df_iniciativas['iniciativa'].tolist()
207
- # querys = [limpiar_texto(query, nlp) for query in querys]
208
- # patr_texts = list([query])
209
- patr_texts = querys
210
- patr_ids = df_iniciativas['id_unico'].tolist()
211
- # print(len(patr_texts))
212
- ods_texts = (ods_df["ods"].fillna("") + ". " + ods_df["descripcion"].fillna("")).tolist()
213
- meta_texts = (meta_df["OBJETIVO"].fillna("") + ". " + meta_df["META"].fillna("")).tolist()
214
- indicadores_texts = (inidicador_df["OBJETIVO"].fillna("") + ". " + inidicador_df["INDICADORES"].fillna("")).tolist()
215
- genero_texts = (genero_df["DESCRIPCION"].fillna("")).tolist()
216
- poblacional_texts = (poblacional_df["DESCRIPCION"].fillna("")).tolist()
217
- etnico_texts = (etnico_df["DESCRIPCION"].fillna("")).tolist()
218
- # ods_texts = (ods_df["OBJETIVO"].fillna("") + ". " + ods_df["INDICADORES"].fillna("")).tolist()
219
- pilares_texts = (pilares_df["PILAR"].fillna("") + ". " + pilares_df["DESCRIPCION"].fillna("") + ". " + pilares_df["SUSTENTO"].fillna("")).tolist()
220
- estrategias_texts = (estrategias_df["ESTRATEGIA"].fillna("") + ". " + estrategias_df["DESCRIPCION"].fillna("")).tolist()
221
- categorias_texts = (categorias_df["CATEGORIA"].fillna("") + ". " + categorias_df["DESCRIPCION"].fillna("")).tolist()
222
- # print(len(ods_texts))
223
-
224
- texts = [ods_texts, meta_texts, indicadores_texts, genero_texts, poblacional_texts, etnico_texts, pilares_texts, estrategias_texts, categorias_texts]
225
-
226
- # print('texts')
227
- # print([len(x) for x in texts])
228
- # No se modifica, hace referencia a la instrucción de entrenamiento
229
- instruc_bases = [
230
- "Representa la definición global de los Objetivo de Desarrollo Sostenible (ODS) para su uso como categoría de referencia en la clasificación de iniciativas ciudadanas.",
231
- "Representa la definición global de las metas de los Objetivos de Desarrollo Sostenible (ODS) para su uso como categoría de referencia en la clasificación de iniciativas ciudadanas",
232
- "Representa el tema central del siguiente ODS",
233
- "Representa el tema central del siguiente de enfoque",
234
- "Representa el tema central del siguiente de enfoque poblacional",
235
- "Representa el tema central del siguiente de enfoque etnico",
236
- "Representa el tema de los siguiente ejes temáticos y estratégicos",
237
- "Representa el tema de las siguiente estrategias",
238
- "Representa el tema de las siguientes categorias"
239
- ]
240
-
241
- instruc_iniciativas = [
242
- # "Representa la iniciativa de planificación territorial y construcción de paz en Colombia para clasificarla según su alineación semántica con los Objetivos de Desarrollo Sostenible (ODS)",
243
- "Representa la definición global de los Objetivo de Desarrollo Sostenible (ODS) para su uso como categoría de referencia en la clasificación de iniciativas ciudadanas.",
244
- "Representa la iniciativa de planificación territorial y construcción de paz en Colombia para clasificarla según su alineación semántica con las metas globales de los Objetivos de Desarrollo Sostenible (ODS)",
245
- "Representa la iniciativa de planificación territorial y construcción de paz en Colombia para clasificarla según su alineación semántica con los indicadores globales de los Objetivos de Desarrollo Sostenible (ODS)",
246
- "Representa la iniciativa de proyecto de construcción de paz para clasificar si aplica el Enfoque de Género, detectando acciones afirmativas dirigidas a mujeres rurales, madres cabeza de familia, liderazgo femenino o cierre de brechas de desigualdad entre hombres y mujeres.grupos poblacionales según sexo, identidad de género, orientación sexual o roles de género.mujeres, equidad de género, igualdad de oportunidades, discriminación, violencia basada en género",
247
- "Representa la iniciativa de proyecto de construcción de paz para clasificar si aplica el enfoque poblacional, reconoce explícitamente la diversidad poblacional y plantea acciones diferenciadas según edad, condición o situación social. juventudes, niñez, adultos mayores, personas con discapacidad, víctimas del conflicto, migrantes, refugiados",
248
- "Representa la iniciativa de proyecto de construcción de paz para clasificar si aplica el enfoque etnico, reconoce diversidad étnica y cultural, plantea acciones diferenciadas para estos grupos. Indígenas, negros, afrodescendientes, raizales, palenqueros, rom, resguardos, palenques, consejos comunitarios",
249
- "Representa el siguiente proyecto territorial en terminos de ejes temáticos y estratégicos",
250
- "Representa el siguiente proyecto territorial en terminos de la estrategia",
251
- "Representa el siguiente proyecto territorial en terminos de la categoria"
252
- ]
253
-
254
-
255
-
256
- # Compute fingerprint and cache path
257
- # fingerprint = build_ods_fingerprint(model_name, instr_ods, ods_texts)
258
- # fingerprint = [build_ods_fingerprint(model_name, instr, texts[idx]) for idx, instr in enumerate(instruc_bases)]
259
- ### Entrnamiento 2
260
- fingerprint = ['60001532196339ff1071548f02dd5de7', #v3
261
- # '53d65b93f49c3e21d40de5933bc7c1a0', #v2
262
- 'e0d3b674182b1e8ab9280544bd9e8532','07948e6beafe34049ca8a7309363eee2','9a4c52cf18e95c52566c0b657a25c44f','5a8b0dd04b865e8f1c356a64795b3b67',
263
- 'c0973f650cac27181b3751aa9666819b','0a475def7da8551abdd502e1d042dc00','42e4e8bfb28dc47602e662a27d8b4e76','e0338741fd4e7b08ab7f92a32e08919b']
264
- ### Entrenamiento 1 (con limpieza de texto)
265
- # fingerprint = ['e109a32969828923f9ddf6f4ad59328d','e0d3b674182b1e8ab9280544bd9e8532','07948e6beafe34049ca8a7309363eee2','9a4c52cf18e95c52566c0b657a25c44f','5a8b0dd04b865e8f1c356a64795b3b67',
266
- # 'c0973f650cac27181b3751aa9666819b','0a475def7da8551abdd502e1d042dc00','42e4e8bfb28dc47602e662a27d8b4e76','e0338741fd4e7b08ab7f92a32e08919b']
267
-
268
- #Entrenamiento 2
269
- ods_cache_path = cache_path or os.path.join(out_dir, f"v3_tabla_lvlOds_{fingerprint[0]}.npz")
270
- #Entrenamiento 1 (con revisión temática de textos)
271
- # ods_cache_path = cache_path or os.path.join(out_dir, f"v1_tabla_odsDescripcion_{fingerprint[0]}.npz")
272
- meta_cache_path = cache_path or os.path.join(out_dir, f"v1_tabla_lvlMetaOds_{fingerprint[1]}.npz")
273
- indicadores_cache_path = cache_path or os.path.join(out_dir, f"ods_embeddings_{fingerprint[2]}.npz")
274
- genero_cache_path = cache_path or os.path.join(out_dir, f"tabla_genero_{fingerprint[3]}.npz")
275
- poblacional_cache_path = cache_path or os.path.join(out_dir, f"tabla_poblacional_{fingerprint[4]}.npz")
276
- etnico_cache_path = cache_path or os.path.join(out_dir, f"tabla_etnico_{fingerprint[5]}.npz")
277
- pilaresPdet_cache_path = cache_path or os.path.join(out_dir, f"pilaresPdet_embeddings_{fingerprint[6]}.npz")
278
- estrategiasPdet_cache_path = cache_path or os.path.join(out_dir, f"estrategiasPdet_embeddings_{fingerprint[7]}.npz")
279
- categoriasPdet_cache_path = cache_path or os.path.join(out_dir, f"categoriasPdet_embeddings_{fingerprint[8]}.npz")
280
-
281
- cache_paths = [ods_cache_path, meta_cache_path, indicadores_cache_path, genero_cache_path, poblacional_cache_path, etnico_cache_path, pilaresPdet_cache_path, estrategiasPdet_cache_path, categoriasPdet_cache_path]
282
-
283
- print('cache_paths')
284
- print([x for x in cache_paths])
285
-
286
- # Lazy import model to allow quick --help
287
- from sentence_transformers import SentenceTransformer
288
-
289
- # Load / compute ODS embeddings with cache
290
- ods_use_cache = (not force_recompute) and os.path.exists(ods_cache_path)
291
- meta_use_cache = (not force_recompute) and os.path.exists(meta_cache_path)
292
- indicadores_use_cache = (not force_recompute) and os.path.exists(indicadores_cache_path)
293
- genero_use_cache = (not force_recompute) and os.path.exists(genero_cache_path)
294
- poblacional_use_cache = (not force_recompute) and os.path.exists(poblacional_cache_path)
295
- etnico_use_cache = (not force_recompute) and os.path.exists(etnico_cache_path)
296
- pilaresPdet_use_cache = (not force_recompute) and os.path.exists(pilaresPdet_cache_path)
297
- estrategiasPdet_use_cache = (not force_recompute) and os.path.exists(estrategiasPdet_cache_path)
298
- categoriasPdet_use_cache = (not force_recompute) and os.path.exists(categoriasPdet_cache_path)
299
-
300
- matrix_unfpa = []
301
- caches = [ods_use_cache, meta_use_cache, indicadores_use_cache]
302
- # , genero_use_cache, poblacional_use_cache, etnico_use_cache,
303
- # pilaresPdet_use_cache, estrategiasPdet_use_cache, categoriasPdet_use_cache]
304
-
305
- for idx, i_cache in enumerate(caches):
306
- # print(cache_paths[idx])
307
-
308
- if i_cache:
309
- emb_unfpa_np, meta = load_cache(cache_paths[idx])
310
- # Minimal safety check: same model/instruction length
311
- if meta.get("model_name") != model_name or meta.get("instr") != instruc_bases[idx] or meta.get("count") != len(texts[idx]):
312
- print(f'Diferencias en carga de metadata nlp cache {cache_paths[idx]}:')
313
- print(meta.get("model_name"), model_name)
314
- print(meta.get("instr"), instruc_bases[idx])
315
- print(meta.get("count"),len(texts[idx]))
316
- # i_cache = False
317
-
318
- if not i_cache:
319
- print(f'no se encontro cache de id : {idx}')
320
- # model = SentenceTransformer(model_name)
321
- # ods_pairs = make_text_pairs(instruc_bases[idx], texts[idx])
322
- # emb_ods = compute_embeddings(model, ods_pairs, batch_size=batch_size, normalize=normalize)
323
- # emb_unfpa_np = emb_ods.cpu().numpy()
324
- # save_cache(cache_paths[idx], {"model_name": model_name, "instr": instruc_bases[idx], "count": len(texts[idx])}, emb_unfpa_np)
325
- else:
326
- model = SentenceTransformer(model_name) # still needed for project embeddings
327
-
328
- # Compute PATR embeddings
329
- patr_pairs = make_text_pairs(instruc_iniciativas[idx], patr_texts)
330
- emb_patr = compute_embeddings(model, patr_pairs, batch_size=batch_size, normalize=normalize)
331
-
332
- # Convert ODS (np.ndarray) to torch.Tensor and move it to the same device as emb_patr
333
- emb_unfpa_t = torch.from_numpy(emb_unfpa_np).to(emb_patr.device)
334
-
335
- # Similarity
336
- from sentence_transformers import util
337
- sim_matrix_ = util.cos_sim(emb_patr, emb_unfpa_t).cpu().numpy()
338
-
339
- matrix_unfpa.append(sim_matrix_)
340
-
341
- matrix_unfpa.append(patr_ids)
342
- print([len(x) for x in matrix_unfpa])
343
- print(matrix_unfpa[-1])
344
-
345
- from sklearn.preprocessing import MinMaxScaler
346
-
347
- scaler = MinMaxScaler()
348
-
349
- # matrix_unfpa_norm =
350
-
351
-
352
-
353
- # tops_k = [5,1,1,1] # ods_use_cache, pilaresPdet_use_cache, estrategiasPdet_use_cache, categoriasPdet_use_cache
354
- # IMPORTANTE: Solo procesar los primeros 3 índices (ODS, META, INDICADORES) ya que solo hay 3 matrices en matrix_unfpa
355
- tops_k = [len(ods_texts), len(meta_texts), len(indicadores_texts)]
356
- # tops_k_s = [3,2,2,1,1,1,1,1,1]
357
- res_dfs = []
358
-
359
- for idx, top in enumerate(tops_k):
360
- sim_matrix = matrix_unfpa[idx]
361
- # Top-K per project
362
- # K = min(top_k, sim_matrix.shape[1])
363
- K = min(top, sim_matrix.shape[1])
364
- top_rows = []
365
- for i in range(sim_matrix.shape[0]):
366
- # print(f'i de sim_matrix.shape[0]: {i}')
367
- sims = sim_matrix[i]
368
- # rt descending and take first K
369
- top_idx = np.argsort(-sims)[:K]
370
-
371
- id_unico = matrix_unfpa[-1][i]
372
- # ods_df
373
- # meta_df
374
- # inidicador_df
375
- # genero_df
376
- # poblacional_df
377
- # etnico_df
378
- # pilares_df
379
- # estrategias_df
380
- # categorias_df
381
-
382
- # Reshape the 'similaridad_cos' column as it needs to be 2D for the scaler
383
- similarity_scores = sims.reshape(-1, 1)
384
- # Fit and transform the data
385
- sims_norm = scaler.fit_transform(similarity_scores)
386
-
387
- #### RESULTADOS PARA DESCRIPCION ODS
388
- if idx == 0:
389
- # Calcular el peso total (suma de similaridades normalizadas para esta iniciativa)
390
- suma_sims_norm_ods = np.sum(sims_norm[top_idx, 0])
391
- # Calcular la suma de similaridades sin normalizar
392
- suma_sims_ods = np.sum(sims[top_idx])
393
- peso_acumulado_ods = 0
394
- peso_acumulado_ods_sin_norm = 0
395
-
396
- for rank, j in enumerate(top_idx, start=1):
397
- # Calcular el peso de cada ODS respecto al total (normalizado)
398
- peso_ods = float(sims_norm[j, 0]) / suma_sims_norm_ods if suma_sims_norm_ods > 0 else 0
399
- peso_acumulado_ods += peso_ods
400
-
401
- # Calcular el peso de cada ODS respecto al total (sin normalizar)
402
- peso_ods_sin_norm = float(sims[j]) / suma_sims_ods if suma_sims_ods > 0 else 0
403
- peso_acumulado_ods_sin_norm += peso_ods_sin_norm
404
-
405
- row = {
406
- # "project_id": patr_df.iloc[i, patr_df.columns.get_loc("ID")], # Use iloc with positional index
407
- # "project_text": patr_df.iloc[i, patr_df.columns.get_loc("INICIATIVAS")], # Use iloc with positional index
408
- "INICIATIVA_ID": id_unico,
409
- "ODS_ID": ods_df.iloc[j, ods_df.columns.get_loc("id_ods")], # Use iloc with positional index
410
- "OBJETIVO": ods_df.iloc[j, ods_df.columns.get_loc("ods")], # Use iloc with positional index
411
-
412
- # "ods_texto": ods_texts[j],
413
- "ods_rank": rank,
414
- "ods_similaridad_cos": float(sims[j]),
415
- "ods_similaridad_cos_norm": float(sims_norm[j, 0]),
416
- "ods_peso": peso_ods,
417
- "ods_peso_acumulado": peso_acumulado_ods,
418
- "ods_peso_sin_norm": peso_ods_sin_norm,
419
- "ods_peso_acumulado_sin_norm": peso_acumulado_ods_sin_norm,
420
- # "ods_titulo": ods_df.iloc[j, ods_df.columns.get_loc("INDICADORES")], # Use iloc with positional index
421
- # "ods_texto": ods_texts[j]
422
- }
423
- top_rows.append(row)
424
-
425
- #### RESULTADOS PARA METAS ODS
426
- if idx == 1:
427
- # Calcular el peso total (suma de similaridades normalizadas para esta iniciativa)
428
- suma_sims_norm_meta = np.sum(sims_norm[top_idx, 0])
429
- # Calcular la suma de similaridades sin normalizar
430
- suma_sims_meta = np.sum(sims[top_idx])
431
- peso_acumulado_meta = 0
432
- peso_acumulado_meta_sin_norm = 0
433
-
434
- for rank, j in enumerate(top_idx, start=1):
435
- # Calcular el peso de cada Meta respecto al total (normalizado)
436
- peso_meta = float(sims_norm[j, 0]) / suma_sims_norm_meta if suma_sims_norm_meta > 0 else 0
437
- peso_acumulado_meta += peso_meta
438
-
439
- # Calcular el peso de cada Meta respecto al total (sin normalizar)
440
- peso_meta_sin_norm = float(sims[j]) / suma_sims_meta if suma_sims_meta > 0 else 0
441
- peso_acumulado_meta_sin_norm += peso_meta_sin_norm
442
-
443
- meta_id_value = str(meta_df.iloc[j, meta_df.columns.get_loc("ID_META")])
444
- row = {
445
- # "project_id": patr_df.iloc[i, patr_df.columns.get_loc("ID")], # Use iloc with positional index
446
- # "project_text": patr_df.iloc[i, patr_df.columns.get_loc("INICIATIVAS")], # Use iloc with positional index
447
- "INICIATIVA_ID": id_unico,
448
- "META_ID": meta_id_value, # Use iloc with positional index
449
- "META": meta_df.iloc[j, meta_df.columns.get_loc("META")], # Use iloc with positional index
450
- "ODS_ID": meta_df.iloc[j, meta_df.columns.get_loc("ID_OBJETIVO")],
451
- "META_ID1": meta_id_value.split('.')[1],
452
-
453
- # "ods_texto": ods_texts[j],
454
- "meta_rank": rank,
455
- "meta_similaridad_cos": float(sims[j]),
456
- "meta_similaridad_cos_norm": float(sims_norm[j, 0]),
457
- "meta_peso": peso_meta,
458
- "meta_peso_acumulado": peso_acumulado_meta,
459
- "meta_peso_sin_norm": peso_meta_sin_norm,
460
- "meta_peso_acumulado_sin_norm": peso_acumulado_meta_sin_norm,
461
- # "ods_titulo": ods_df.iloc[j, ods_df.columns.get_loc("INDICADORES")], # Use iloc with positional index
462
- # "ods_texto": ods_texts[j]
463
- }
464
- top_rows.append(row)
465
-
466
- #### RESULTADOS PARA INDICADORES ODS
467
- if idx == 2:
468
- # Calcular el peso total (suma de similaridades normalizadas para esta iniciativa)
469
- suma_sims_norm_indicador = np.sum(sims_norm[top_idx, 0])
470
- # Calcular la suma de similaridades sin normalizar
471
- suma_sims_indicador = np.sum(sims[top_idx])
472
- peso_acumulado_indicador = 0
473
- peso_acumulado_indicador_sin_norm = 0
474
-
475
- for rank, j in enumerate(top_idx, start=1):
476
- # Calcular el peso de cada Indicador respecto al total (normalizado)
477
- peso_indicador = float(sims_norm[j, 0]) / suma_sims_norm_indicador if suma_sims_norm_indicador > 0 else 0
478
- peso_acumulado_indicador += peso_indicador
479
-
480
- # Calcular el peso de cada Indicador respecto al total (sin normalizar)
481
- peso_indicador_sin_norm = float(sims[j]) / suma_sims_indicador if suma_sims_indicador > 0 else 0
482
- peso_acumulado_indicador_sin_norm += peso_indicador_sin_norm
483
-
484
- meta_id_value = str(inidicador_df.iloc[j, inidicador_df.columns.get_loc("ID_META")])
485
- indicador_id_value = str(inidicador_df.iloc[j, inidicador_df.columns.get_loc("ID_INDICADORES")])
486
- row = {
487
- # "project_id": patr_df.iloc[i, patr_df.columns.get_loc("ID")], # Use iloc with positional index
488
- # "project_text": patr_df.iloc[i, patr_df.columns.get_loc("INICIATIVAS")], # Use iloc with positional index
489
- "INICIATIVA_ID": id_unico,
490
- "INDICADOR_ID": indicador_id_value, # Use iloc with positional index
491
- "INDICADOR": inidicador_df.iloc[j, inidicador_df.columns.get_loc("INDICADORES")], # Use iloc with positional index
492
- "ODS_ID": inidicador_df.iloc[j, inidicador_df.columns.get_loc("ID_ODS")],
493
- "META_ID1": meta_id_value,
494
- "META_ID2": meta_id_value.split('.')[1],
495
- "INDICADOR_ID1": indicador_id_value.split('.')[2],
496
- # "ods_texto": ods_texts[j],
497
- "indicador_rank": rank,
498
- "indicador_similaridad_cos": float(sims[j]),
499
- "indicador_similaridad_cos_norm": float(sims_norm[j, 0]),
500
- "indicador_peso": peso_indicador,
501
- "indicador_peso_acumulado": peso_acumulado_indicador,
502
- "indicador_peso_sin_norm": peso_indicador_sin_norm,
503
- "indicador_peso_acumulado_sin_norm": peso_acumulado_indicador_sin_norm,
504
- # "ods_titulo": ods_df.iloc[j, ods_df.columns.get_loc("INDICADORES")], # Use iloc with positional index
505
- # "ods_texto": ods_texts[j]
506
- }
507
- top_rows.append(row)
508
-
509
- #### RESULTADOS PARA ENFOQUE GENERO (idx == 3)
510
- # if idx == 3:
511
- # for rank, j in enumerate(top_idx, start=1):
512
- # row = {
513
- # "INICIATIVA_ID": id_unico,
514
- # "ENFOQUE_GENERO": genero_df.iloc[j, genero_df.columns.get_loc("CATEGORIA")],
515
- # "similaridad_cos": float(sims[j]),
516
- # }
517
- # top_rows.append(row)
518
-
519
- #### RESULTADOS PARA ENFOQUE POBLACIONAL (idx == 4)
520
- # if idx == 4:
521
- # for rank, j in enumerate(top_idx, start=1):
522
- # row = {
523
- # "INICIATIVA_ID": id_unico,
524
- # "ENFOQUE_POBLACIONAL": poblacional_df.iloc[j, poblacional_df.columns.get_loc("CATEGORIA")],
525
- # "similaridad_cos": float(sims[j]),
526
- # }
527
- # top_rows.append(row)
528
-
529
- #### RESULTADOS PARA ENFOQUE ETNICO (idx == 5)
530
- # if idx == 5:
531
- # for rank, j in enumerate(top_idx, start=1):
532
- # row = {
533
- # "INICIATIVA_ID": id_unico,
534
- # "ENFOQUE_POBLACIONAL": etnico_df.iloc[j, etnico_df.columns.get_loc("CATEGORIA")],
535
- # "similaridad_cos": float(sims[j]),
536
- # }
537
- # top_rows.append(row)
538
-
539
- #### RESULTADOS PARA PILARES (idx == 6)
540
- # if idx == 6:
541
- # for rank, j in enumerate(top_idx, start=1):
542
- # row = {
543
- # "INICIATIVA_ID": id_unico,
544
- # "similaridad_cos": float(sims[j]),
545
- # "pilar": pilares_texts[j]
546
- # }
547
- # top_rows.append(row)
548
-
549
- #### RESULTADOS PARA ESTRATEGIAS (idx == 7)
550
- # if idx == 7:
551
- # for rank, j in enumerate(top_idx, start=1):
552
- # row = {
553
- # "INICIATIVA_ID": id_unico,
554
- # "similaridad_cos": float(sims[j]),
555
- # "estrategia": estrategias_texts[j]
556
- # }
557
- # top_rows.append(row)
558
-
559
- #### RESULTADOS PARA CATEGORIAS (idx == 8)
560
- # if idx == 8:
561
- # for rank, j in enumerate(top_idx, start=1):
562
- # row = {
563
- # "INICIATIVA_ID": id_unico,
564
- # "similaridad_cos": float(sims[j]),
565
- # "categoria": categorias_texts[j]
566
- # }
567
- # top_rows.append(row)
568
-
569
-
570
- res_df = pd.DataFrame(top_rows).drop_duplicates()
571
- res_df = res_df.merge(df_iniciativas, 'left', left_on='INICIATIVA_ID', right_on='id_unico', suffixes=('','_y'))
572
- drop_cols = [col for col in res_df.columns if col.endswith('_y')]
573
- res_df = res_df.drop(columns=drop_cols)
574
- res_dfs.append(res_df)
575
-
576
- # Additionally, export a simple edges file (Top-1) for graph visualizations
577
- # edges = []
578
- # df_edges = pd.DataFrame()
579
- # df_edges['source'] = res_dfs[0]['ods_id']
580
- # df_edges['target'] = res_dfs[0]['indicador_id']
581
- # df_edges['weight'] = res_dfs[0]['similaridad_cos']
582
-
583
- # for pid, group in res_df.groupby("project_id"):
584
- # best = group.sort_values("rank").iloc[0]
585
- # edges.append({"source": group["project_id"], "target": group["ods_id"], "weight": group["similaridad_cos"]})
586
- # df_edges = pd.DataFrame(edges)#.to_tblinput(out_edges, index=False, encoding="utf-8
587
-
588
- # html = build_graph(df_edges)
589
- from sklearn.preprocessing import MinMaxScaler
590
-
591
-
592
- # dfs_norm = []
593
- # Initialize the MinMaxScaler
594
- scaler = MinMaxScaler()
595
-
596
- # for i in range(0,3):
597
-
598
- # if i == 0:
599
- # # Reshape the 'similaridad_cos' column as it needs to be 2D for the scaler
600
- # similarity_scores = res_dfs[i]['ods_similaridad_cos'].values.reshape(-1, 1)
601
- # # Fit and transform the data
602
- # res_dfs[i]['ods_similaridad_cos_normalized'] = scaler.fit_transform(similarity_scores)
603
-
604
- # if i == 1:
605
- # # Reshape the 'similaridad_cos' column as it needs to be 2D for the scaler
606
- # similarity_scores = res_dfs[i]['meta_similaridad_cos'].values.reshape(-1, 1)
607
- # # Fit and transform the data
608
- # res_dfs[i]['meta_similaridad_cos_normalized'] = scaler.fit_transform(similarity_scores)
609
-
610
- # if i == 2:
611
- # # Reshape the 'similaridad_cos' column as it needs to be 2D for the scaler
612
- # similarity_scores = res_dfs[i]['indicador_similaridad_cos'].values.reshape(-1, 1)
613
- # # Fit and transform the data
614
- # res_dfs[i]['indicador_similaridad_cos_normalized'] = scaler.fit_transform(similarity_scores)
615
-
616
-
617
- # top_ods, top_meta, top_indicador
618
-
619
- # bdl_ods = res_dfs[0][res_dfs[0].ods_rank <= top_ods].merge(res_dfs[1][res_dfs[1].meta_rank <= top_meta], 'left', left_on=['INICIATIVA_ID','ODS_ID'], right_on=['INICIATIVA_ID','ODS_ID'], suffixes=('','_y'))
620
- # # bdl_ods = res_dfs[0][res_dfs[0].ods_rank.isin([1,2,3])].merge(res_dfs[1].head(2), 'inner', left_on=['INICIATIVA_ID'], right_on=['INICIATIVA_ID'])
621
- # drop_cols = [col for col in bdl_ods.columns if col.endswith('_y')]
622
- # bdl_ods = bdl_ods.drop(columns=drop_cols)
623
- # bdl_ods = bdl_ods.merge(res_dfs[2][res_dfs[2].indicador_rank <= top_indicador],'left', left_on=['INICIATIVA_ID','ODS_ID'], right_on=['INICIATIVA_ID','ODS_ID'], suffixes=('','_y'))
624
- # # bdl_ods = bdl_ods.merge(res_dfs[2].head(2),'inner', left_on=['INICIATIVA_ID'], right_on=['INICIATIVA_ID'])
625
-
626
-
627
- #versión concat
628
- ods_bdl = res_dfs[0][res_dfs[0].ods_rank <= top_ods].reset_index(drop=True)
629
- meta_bdl = res_dfs[1][res_dfs[1].meta_rank <= top_meta].reset_index(drop=True)
630
- indicador_bdl = res_dfs[2][res_dfs[2].indicador_rank <= top_indicador].reset_index(drop=True)
631
-
632
- base_metas = ods_bdl.merge(meta_bdl, 'inner', left_on=['INICIATIVA_ID','ODS_ID'], right_on=['INICIATIVA_ID','ODS_ID'], suffixes=('','_y'))
633
- drop_cols = [col for col in base_metas.columns if col.endswith('_y')]
634
- base_metas = base_metas.drop(columns=drop_cols)
635
-
636
- base_indicadores = ods_bdl.merge(indicador_bdl, 'inner', left_on=['INICIATIVA_ID','ODS_ID'], right_on=['INICIATIVA_ID','ODS_ID'], suffixes=('','_y'))
637
- drop_cols = [col for col in base_indicadores.columns if col.endswith('_y')]
638
- base_indicadores = base_indicadores.drop(columns=drop_cols)
639
-
640
- # meta_ind = pd.concat([base_metas[['INICIATIVA_ID','ODS_ID','meta_rank','META_ID', 'META']], base_indicadores[['indicador_rank','INDICADOR_ID', 'INDICADOR']]], axis=1)
641
-
642
- # bdl_ods = ods_bdl.merge(meta_ind, 'inner', left_on=['INICIATIVA_ID','ODS_ID'], right_on=['INICIATIVA_ID','ODS_ID'], suffixes=('','_y'))
643
- # drop_cols = [col for col in bdl_ods.columns if col.endswith('_y')]
644
- # bdl_ods = bdl_ods.drop(columns=drop_cols)
645
-
646
- bdl_ods = pd.concat([meta_bdl[['INICIATIVA_ID','ODS_ID','meta_rank','META_ID', 'META']], indicador_bdl[['indicador_rank','INDICADOR_ID', 'INDICADOR']]], axis=1)
647
- bdl_ods = pd.concat([ods_bdl[['INICIATIVA_ID','ODS_ID','ods_rank','OBJETIVO']], bdl_ods[['meta_rank','META_ID', 'META', 'indicador_rank','INDICADOR_ID', 'INDICADOR']]], axis=1)
648
-
649
- # Nota: Los siguientes merges con res_dfs[3-8] están deshabilitados porque no se calculan las matrices para esos índices
650
- # Para habilitarlos, primero necesitarías descomentar el procesamiento de genero, poblacional, etnico, pilares, estrategias, categorias en el bucle principal
651
-
652
- # bdl_ods = bdl_ods.merge(res_dfs[3], 'inner', left_on='INICIATIVA_ID', right_on='INICIATIVA_ID', suffixes=('','_y'))
653
- # drop_cols = [col for col in bdl_ods.columns if col.endswith('_y')]
654
- # bdl_ods = bdl_ods.drop(columns=drop_cols)
655
- # bdl_ods = bdl_ods.merge(res_dfs[4], 'inner', left_on='INICIATIVA_ID', right_on='INICIATIVA_ID', suffixes=('','_y'))
656
- # drop_cols = [col for col in bdl_ods.columns if col.endswith('_y')]
657
- # bdl_ods = bdl_ods.drop(columns=drop_cols)
658
- # bdl_ods = bdl_ods.merge(res_dfs[5], 'inner', left_on='INICIATIVA_ID', right_on='INICIATIVA_ID', suffixes=('','_y'))
659
- # drop_cols = [col for col in bdl_ods.columns if col.endswith('_y')]
660
- # bdl_ods = bdl_ods.drop(columns=drop_cols)
661
- # bdl_ods = bdl_ods.merge(res_dfs[6], 'inner', left_on='INICIATIVA_ID', right_on='INICIATIVA_ID', suffixes=('','_y'))
662
- # drop_cols = [col for col in bdl_ods.columns if col.endswith('_y')]
663
- # bdl_ods = bdl_ods.drop(columns=drop_cols)
664
- # bdl_ods = bdl_ods.merge(res_dfs[7], 'inner', left_on='INICIATIVA_ID', right_on='INICIATIVA_ID', suffixes=('','_y'))
665
- # drop_cols = [col for col in bdl_ods.columns if col.endswith('_y')]
666
- # bdl_ods = bdl_ods.drop(columns=drop_cols)
667
- # bdl_ods = bdl_ods.merge(res_dfs[8], 'inner', left_on='INICIATIVA_ID', right_on='INICIATIVA_ID', suffixes=('','_y'))
668
- # drop_cols = [col for col in bdl_ods.columns if col.endswith('_y')]
669
- # bdl_ods = bdl_ods.drop(columns=drop_cols)
670
- # bdl_ods = bdl_ods.merge(res_dfs[9], 'inner', left_on='INICIATIVA_ID', right_on='INICIATIVA_ID')
671
- print(f'Tamaño BDL: {len(bdl_ods)}')
672
-
673
- ## Complementando metas con recomendaciones de indicadores
674
- res_dfs[1] = res_dfs[1].merge(recomendaciones_df[['Meta_ODS', 'Recomendaciones_territoriales']], 'left', left_on='META_ID', right_on='META_ID')
675
-
676
-
677
-
678
-
679
- # return (querys, res_dfs[0], res_dfs[1], res_dfs[2], res_dfs[3], res_dfs[4], res_dfs[5], res_dfs[6], res_dfs[7], res_dfs[8], bdl_ods)
680
- return (res_dfs[0], res_dfs[1], res_dfs[2], df_categorias, 'Ejecución exitosa. Revisa los DataFrames resultantes para análisis detallados.')
681
- # return bdl_ods, ods_bdl, meta_bdl, indicador_bdl
682
-
683
-
684
-
685
- # ============================================================================
686
- # Función para normalizar
687
- # ============================================================================
688
-
689
-
690
-
 
1
+
2
+ # ============================================================================
3
+ # Funciones generales PLN
4
+ # ============================================================================
5
+
6
+ import argparse, os, json, hashlib, pandas as pd, numpy as np
7
+ from pathlib import Path
8
+ import re
9
+
10
+ def md5_text(s: str) -> str:
11
+ return hashlib.md5(s.encode('utf-8')).hexdigest()
12
+
13
+ def build_ods_fingerprint(model_name: str, instruction: str, ods_texts: list) -> str:
14
+ concat = model_name + "\n" + instruction + "\n" + "\n".join(ods_texts)
15
+ return md5_text(concat)
16
+
17
+ def ensure_out_dir(p: str):
18
+ Path(p).mkdir(parents=True, exist_ok=True)
19
+
20
+ def load_data(patr_tblinput: str, ods_tblinput: str):
21
+ # patr = pd.read_tblinput(patr_tblinput)
22
+ # ods = pd.read_tblinput(ods_tblinput)
23
+ patr = pd.read_excel(patr_tblinput)#, encoding='cp1252')
24
+
25
+
26
+ ods = pd.read_excel(ods_tblinput)#.iloc[:32,:]
27
+ # Basic validations
28
+ assert {"ID", "INICIATIVAS", "MUNICIPIO"}.issubset(patr.columns), "PATR CSV must include columns: ID, INICIATIVAS"
29
+ assert {'OBJETIVO', 'OBJETIVO_META', 'INDICADORES', 'CODIGO_UNSD',
30
+ 'ID_OBJETIVO', 'ID_META', 'ID_INDICADORES'}.issubset(ods.columns), "ODS CSV must include columns: OBJETIVO, OBJETIVO_META, INDICADORES, CODIGO_UNSD,ID_OBJETIVO, ID_META, ID_INDICADORES"
31
+ return patr, ods
32
+
33
+ def make_text_pairs(instruction: str, texts: list):
34
+ return [[instruction, t if isinstance(t,str) else ""] for t in texts]
35
+
36
+ def compute_embeddings(model, pairs, batch_size: int, normalize: bool):
37
+ # SentenceTransformer.encode has normalize_embeddings parameter
38
+ return model.encode(
39
+ pairs,
40
+ batch_size=batch_size,
41
+ convert_to_tensor=True,
42
+ show_progress_bar=True,
43
+ normalize_embeddings=normalize
44
+ )
45
+
46
+ def cosine_sim_matrix(a, b):
47
+ # a: (N,d) tensor, b: (M,d) tensor
48
+ from sentence_transformers import util
49
+ sims = util.cos_sim(a, b).cpu().numpy()
50
+ return sims
51
+
52
+ # def save_cache(cache_path: str, meta: dict, emb_np: np.ndarray):
53
+ # np.savez(cache_path, embeddings=emb_np, meta=json.dumps(meta, ensure_ascii=False))
54
+
55
+ # def load_cache(cache_path: str):
56
+ # data = np.load(cache_path, allow_pickle=True)
57
+ # emb = data["embeddings"]
58
+ # meta = json.loads(str(data["meta"]))
59
+ # return emb, meta
60
+
61
+ def save_cache(cache_path: str, meta: dict, emb_np: np.ndarray):
62
+ np.savez(cache_path, embeddings=emb_np) # solo arrays
63
+ with open(cache_path + ".json", "w", encoding="utf-8") as f:
64
+ json.dump(meta, f, ensure_ascii=False) # meta en JSON sidecar
65
+
66
+ def load_cache(cache_path: str):
67
+ emb = np.load(cache_path)["embeddings"]
68
+ with open(cache_path + ".json", "r", encoding="utf-8") as f:
69
+ meta = json.load(f)
70
+ return emb, meta
71
+
72
+ # import spacy
73
+
74
+ # def limpiar_texto(texto, nlp):
75
+ # """
76
+ # Limpia nombres propios, entidades y caracteres especiales del texto.
77
+ # Conserva la primera palabra de cada oración (aunque esté en mayúscula).
78
+ # """
79
+ # if not texto or not isinstance(texto, str):
80
+ # return ""
81
+
82
+ # # 1️⃣ Remover caracteres especiales innecesarios (antes del análisis)
83
+ # # Mantiene letras, números, espacios y signos básicos de puntuación.
84
+ # texto = re.sub(r"[^A-Za-zÁÉÍÓÚÜÑáéíóúüñ0-9\s.,;:!?()\-]", " ", texto)
85
+
86
+ # # 2️⃣ Procesamiento lingüístico
87
+ # doc = nlp(texto)
88
+ # resultado = []
89
+
90
+ # for sent in doc.sents:
91
+ # tokens = []
92
+ # for i, token in enumerate(sent):
93
+ # # eliminar puntuación y símbolos
94
+ # if token.is_punct or token.is_space or token.is_digit:
95
+ # continue
96
+ # # Mantiene primera palabra de cada oración
97
+ # if i == 0:
98
+ # tokens.append(token.text)
99
+ # # Elimina nombres propios o entidades nombradas
100
+ # elif token.pos_ == "PROPN" or token.ent_type_ in ["PER", "ORG", "LOC", "GPE"]:
101
+ # continue
102
+ # else:
103
+ # tokens.append(token.text)
104
+ # resultado.append(" ".join(tokens))
105
+
106
+ # # 3️⃣ Limpiar puntuación repetida y espacios múltiples
107
+ # texto_limpio = " ".join(resultado)
108
+ # texto_limpio = re.sub(r"\s{2,}", " ", texto_limpio).strip()
109
+
110
+ # # 4️⃣ Opcional: eliminar espacios antes de comas o puntos
111
+ # texto_limpio = re.sub(r"\s+([,.!?;:])", r"\1", texto_limpio)
112
+
113
+ # return texto_limpio
114
+
115
+
116
+ # ============================================================================
117
+ # Generador de cache para generar embeddings nuevas tablas
118
+ # ============================================================================
119
+
120
+ def genCache(cache_name:str, tbl_input_dir:str, out_dir:str, instruction:str, batch_size = 32, normalize = True, cache_path = None, force_recompute = False):
121
+
122
+ model_name = "hkunlp/instructor-large" #help="HF model name for embeddings.")
123
+ # instruction = "Representa el tema central del siguiente objetivo de desarrollo sostenible" #"Instruction for ODS texts.")
124
+ ensure_out_dir(out_dir)
125
+
126
+ # Load data
127
+ input_df = pd.read_excel(tbl_input_dir)
128
+ input_texts = (input_df["ods"].fillna("") + ". " + input_df["descripcion"].fillna("")).tolist()
129
+
130
+ # Compute fingerprint and cache path
131
+ fingerprint = build_ods_fingerprint(model_name, instruction, input_texts)
132
+ cache_path = cache_path or os.path.join(out_dir, f"{cache_name}_{fingerprint}.npz")
133
+
134
+ # Lazy import model to allow quick --help
135
+ from sentence_transformers import SentenceTransformer
136
+ import warnings
137
+
138
+ # Silenciar warning sobre tied weights que es inofensivo
139
+ warnings.filterwarnings('ignore', message='.*tied weights mapping.*')
140
+
141
+ model = SentenceTransformer(model_name)
142
+ input_pairs = make_text_pairs(instruction, input_texts)
143
+ emb_input = compute_embeddings(model, input_pairs, batch_size=batch_size, normalize=normalize)
144
+ emb_input_np = emb_input.cpu().numpy()
145
+ save_cache(cache_path, {"model": model_name, "instr": instruction, "count": len(input_texts)}, emb_input_np)
146
+
147
+ # ============================================================================
148
+ # Función generadora tablas
149
+ # ============================================================================
150
+
151
+ import torch
152
+ import pandas as pd
153
+ import numpy as np
154
+
155
+
156
+ def search_mass(path_df_iniciativas, top_ods, top_meta, top_indicador):
157
+
158
+ df_iniciativas = pd.read_excel(path_df_iniciativas)
159
+ df_categorias = [categoria for categoria in df_iniciativas.columns if categoria not in ['id_unico', 'iniciativa']]
160
+ # patr_tblinput = 'data/raw/Copy of Iniciativas priorizadas PATR 385.xlsx' #"CSV with PATR projects (columns: id, descripcion, ...).")
161
+ ods_tblinput = Path('data/raw/v2_tabla_odsDescripcion_revLA 03032026.xlsx') #Entrenamiento 3
162
+ # ods_tblinput = Path('data/raw/v2_tabla_odsDescripcion_revLA.xlsx') #Entrenamiento 2
163
+ # ods_tblinput = Path('data/raw/v1_tabla_odsDescripcion.xlsx') #Entrenamiento 1
164
+ meta_tblinput = Path('data/raw/v1_tabla_lvlMetaOds.xlsx')
165
+ indicador_tblinput = Path('data/raw/marco_ods_ids.xlsx')
166
+ genero_tblinput = Path('data/raw/genero.xlsx')
167
+ poblacional_tblinput = Path('data/raw/poblacional.xlsx')
168
+ etnico_tblinput = Path('data/raw/etnico.xlsx')
169
+ pilares_tblinput = Path('data/raw/pilares.xlsx' )
170
+ categorias_tblinput = Path('data/raw/categorias.xlsx')
171
+ estrategias_tblinput = Path('data/raw/estrategias.xlsx')
172
+ recomendaciones_tblinput = Path('data/raw/ODS_169_metas_recomendaciones_detalladas.xlsx')
173
+ out_dir = 'data/embeddings' # '/content/drive/MyDrive/Compartida/06_Desarrollo de la herramienta IA/01_MPTF /archivos_trabajo/salidas/modelo_instructor/data/out' #"Output directory.")
174
+ model_name = "hkunlp/instructor-large" #help="HF model name for embeddings.")
175
+ instr_proj = "Representa el propósito de desarrollo sostenible del siguiente proyecto territorial" #"Instruction for PATR projects.")
176
+ instr_ods = "Representa el tema central del siguiente ODS" #"Instruction for ODS texts.")
177
+ batch_size = 32 #"Batch size for encoding.")
178
+ top_k = 5 #"Top-K ODS to retrieve.")
179
+ normalize = True #"L2-normalize embeddings during encoding.") # Changed from "store_true" to boolean
180
+ cache_path = None #"Path to cache npz for ODS embeddings (auto if not set).")
181
+ force_recompute = False #"Ignore cache and recompute ODS embeddings.") # Changed from "store_true" to boolean
182
+
183
+
184
+ ensure_out_dir(out_dir)
185
+
186
+ #"OBJETIVO","OBJETIVO_META","INDICADORES","CODIGO_UNSD"
187
+
188
+ # Load data
189
+ # patr_df, ods_df = load_data(patr_tblinput, ods_tblinput)
190
+ # patr_df = patr_df[['ID', 'INICIATIVAS']].drop_duplicates().reset_index(drop=True) # Reset index
191
+ # patr_texts = patr_df["INICIATIVAS"].fillna("").tolist()
192
+ # patr_df = pd.read_excel(patr_tblinput)
193
+ ods_df = pd.read_excel(ods_tblinput)
194
+ meta_df = pd.read_excel(meta_tblinput)
195
+ inidicador_df = pd.read_excel(indicador_tblinput)
196
+ genero_df = pd.read_excel(genero_tblinput)
197
+ poblacional_df = pd.read_excel(poblacional_tblinput)
198
+ etnico_df = pd.read_excel(etnico_tblinput)
199
+ pilares_df = pd.read_excel(pilares_tblinput)
200
+ estrategias_df = pd.read_excel(estrategias_tblinput)
201
+ categorias_df = pd.read_excel(categorias_tblinput)
202
+ recomendaciones_df = pd.read_excel(recomendaciones_tblinput)
203
+
204
+ # nlp = spacy.load("es_core_news_md")
205
+ # query = limpiar_texto(query, nlp)
206
+ querys = df_iniciativas['iniciativa'].tolist()
207
+ # querys = [limpiar_texto(query, nlp) for query in querys]
208
+ # patr_texts = list([query])
209
+ patr_texts = querys
210
+ patr_ids = df_iniciativas['id_unico'].tolist()
211
+ # print(len(patr_texts))
212
+ ods_texts = (ods_df["ods"].fillna("") + ". " + ods_df["descripcion"].fillna("")).tolist()
213
+ meta_texts = (meta_df["OBJETIVO"].fillna("") + ". " + meta_df["META"].fillna("")).tolist()
214
+ indicadores_texts = (inidicador_df["OBJETIVO"].fillna("") + ". " + inidicador_df["INDICADORES"].fillna("")).tolist()
215
+ genero_texts = (genero_df["DESCRIPCION"].fillna("")).tolist()
216
+ poblacional_texts = (poblacional_df["DESCRIPCION"].fillna("")).tolist()
217
+ etnico_texts = (etnico_df["DESCRIPCION"].fillna("")).tolist()
218
+ # ods_texts = (ods_df["OBJETIVO"].fillna("") + ". " + ods_df["INDICADORES"].fillna("")).tolist()
219
+ pilares_texts = (pilares_df["PILAR"].fillna("") + ". " + pilares_df["DESCRIPCION"].fillna("") + ". " + pilares_df["SUSTENTO"].fillna("")).tolist()
220
+ estrategias_texts = (estrategias_df["ESTRATEGIA"].fillna("") + ". " + estrategias_df["DESCRIPCION"].fillna("")).tolist()
221
+ categorias_texts = (categorias_df["CATEGORIA"].fillna("") + ". " + categorias_df["DESCRIPCION"].fillna("")).tolist()
222
+ # print(len(ods_texts))
223
+
224
+ texts = [ods_texts, meta_texts, indicadores_texts, genero_texts, poblacional_texts, etnico_texts, pilares_texts, estrategias_texts, categorias_texts]
225
+
226
+ # print('texts')
227
+ # print([len(x) for x in texts])
228
+ # No se modifica, hace referencia a la instrucción de entrenamiento
229
+ instruc_bases = [
230
+ "Representa la definición global de los Objetivo de Desarrollo Sostenible (ODS) para su uso como categoría de referencia en la clasificación de iniciativas ciudadanas.",
231
+ "Representa la definición global de las metas de los Objetivos de Desarrollo Sostenible (ODS) para su uso como categoría de referencia en la clasificación de iniciativas ciudadanas",
232
+ "Representa el tema central del siguiente ODS",
233
+ "Representa el tema central del siguiente de enfoque",
234
+ "Representa el tema central del siguiente de enfoque poblacional",
235
+ "Representa el tema central del siguiente de enfoque etnico",
236
+ "Representa el tema de los siguiente ejes temáticos y estratégicos",
237
+ "Representa el tema de las siguiente estrategias",
238
+ "Representa el tema de las siguientes categorias"
239
+ ]
240
+
241
+ instruc_iniciativas = [
242
+ # "Representa la iniciativa de planificación territorial y construcción de paz en Colombia para clasificarla según su alineación semántica con los Objetivos de Desarrollo Sostenible (ODS)",
243
+ "Representa la definición global de los Objetivo de Desarrollo Sostenible (ODS) para su uso como categoría de referencia en la clasificación de iniciativas ciudadanas.",
244
+ "Representa la iniciativa de planificación territorial y construcción de paz en Colombia para clasificarla según su alineación semántica con las metas globales de los Objetivos de Desarrollo Sostenible (ODS)",
245
+ "Representa la iniciativa de planificación territorial y construcción de paz en Colombia para clasificarla según su alineación semántica con los indicadores globales de los Objetivos de Desarrollo Sostenible (ODS)",
246
+ "Representa la iniciativa de proyecto de construcción de paz para clasificar si aplica el Enfoque de Género, detectando acciones afirmativas dirigidas a mujeres rurales, madres cabeza de familia, liderazgo femenino o cierre de brechas de desigualdad entre hombres y mujeres.grupos poblacionales según sexo, identidad de género, orientación sexual o roles de género.mujeres, equidad de género, igualdad de oportunidades, discriminación, violencia basada en género",
247
+ "Representa la iniciativa de proyecto de construcción de paz para clasificar si aplica el enfoque poblacional, reconoce explícitamente la diversidad poblacional y plantea acciones diferenciadas según edad, condición o situación social. juventudes, niñez, adultos mayores, personas con discapacidad, víctimas del conflicto, migrantes, refugiados",
248
+ "Representa la iniciativa de proyecto de construcción de paz para clasificar si aplica el enfoque etnico, reconoce diversidad étnica y cultural, plantea acciones diferenciadas para estos grupos. Indígenas, negros, afrodescendientes, raizales, palenqueros, rom, resguardos, palenques, consejos comunitarios",
249
+ "Representa el siguiente proyecto territorial en terminos de ejes temáticos y estratégicos",
250
+ "Representa el siguiente proyecto territorial en terminos de la estrategia",
251
+ "Representa el siguiente proyecto territorial en terminos de la categoria"
252
+ ]
253
+
254
+
255
+
256
+ # Compute fingerprint and cache path
257
+ # fingerprint = build_ods_fingerprint(model_name, instr_ods, ods_texts)
258
+ # fingerprint = [build_ods_fingerprint(model_name, instr, texts[idx]) for idx, instr in enumerate(instruc_bases)]
259
+ ### Entrnamiento 2
260
+ fingerprint = ['60001532196339ff1071548f02dd5de7', #v3
261
+ # '53d65b93f49c3e21d40de5933bc7c1a0', #v2
262
+ 'e0d3b674182b1e8ab9280544bd9e8532','07948e6beafe34049ca8a7309363eee2','9a4c52cf18e95c52566c0b657a25c44f','5a8b0dd04b865e8f1c356a64795b3b67',
263
+ 'c0973f650cac27181b3751aa9666819b','0a475def7da8551abdd502e1d042dc00','42e4e8bfb28dc47602e662a27d8b4e76','e0338741fd4e7b08ab7f92a32e08919b']
264
+ ### Entrenamiento 1 (con limpieza de texto)
265
+ # fingerprint = ['e109a32969828923f9ddf6f4ad59328d','e0d3b674182b1e8ab9280544bd9e8532','07948e6beafe34049ca8a7309363eee2','9a4c52cf18e95c52566c0b657a25c44f','5a8b0dd04b865e8f1c356a64795b3b67',
266
+ # 'c0973f650cac27181b3751aa9666819b','0a475def7da8551abdd502e1d042dc00','42e4e8bfb28dc47602e662a27d8b4e76','e0338741fd4e7b08ab7f92a32e08919b']
267
+
268
+ #Entrenamiento 2
269
+ ods_cache_path = cache_path or os.path.join(out_dir, f"v3_tabla_lvlOds_{fingerprint[0]}.npz")
270
+ #Entrenamiento 1 (con revisión temática de textos)
271
+ # ods_cache_path = cache_path or os.path.join(out_dir, f"v1_tabla_odsDescripcion_{fingerprint[0]}.npz")
272
+ meta_cache_path = cache_path or os.path.join(out_dir, f"v1_tabla_lvlMetaOds_{fingerprint[1]}.npz")
273
+ indicadores_cache_path = cache_path or os.path.join(out_dir, f"ods_embeddings_{fingerprint[2]}.npz")
274
+ genero_cache_path = cache_path or os.path.join(out_dir, f"tabla_genero_{fingerprint[3]}.npz")
275
+ poblacional_cache_path = cache_path or os.path.join(out_dir, f"tabla_poblacional_{fingerprint[4]}.npz")
276
+ etnico_cache_path = cache_path or os.path.join(out_dir, f"tabla_etnico_{fingerprint[5]}.npz")
277
+ pilaresPdet_cache_path = cache_path or os.path.join(out_dir, f"pilaresPdet_embeddings_{fingerprint[6]}.npz")
278
+ estrategiasPdet_cache_path = cache_path or os.path.join(out_dir, f"estrategiasPdet_embeddings_{fingerprint[7]}.npz")
279
+ categoriasPdet_cache_path = cache_path or os.path.join(out_dir, f"categoriasPdet_embeddings_{fingerprint[8]}.npz")
280
+
281
+ cache_paths = [ods_cache_path, meta_cache_path, indicadores_cache_path, genero_cache_path, poblacional_cache_path, etnico_cache_path, pilaresPdet_cache_path, estrategiasPdet_cache_path, categoriasPdet_cache_path]
282
+
283
+ print('cache_paths')
284
+ print([x for x in cache_paths])
285
+
286
+ # Lazy import model to allow quick --help
287
+ from sentence_transformers import SentenceTransformer
288
+
289
+ # Load / compute ODS embeddings with cache
290
+ ods_use_cache = (not force_recompute) and os.path.exists(ods_cache_path)
291
+ meta_use_cache = (not force_recompute) and os.path.exists(meta_cache_path)
292
+ indicadores_use_cache = (not force_recompute) and os.path.exists(indicadores_cache_path)
293
+ genero_use_cache = (not force_recompute) and os.path.exists(genero_cache_path)
294
+ poblacional_use_cache = (not force_recompute) and os.path.exists(poblacional_cache_path)
295
+ etnico_use_cache = (not force_recompute) and os.path.exists(etnico_cache_path)
296
+ pilaresPdet_use_cache = (not force_recompute) and os.path.exists(pilaresPdet_cache_path)
297
+ estrategiasPdet_use_cache = (not force_recompute) and os.path.exists(estrategiasPdet_cache_path)
298
+ categoriasPdet_use_cache = (not force_recompute) and os.path.exists(categoriasPdet_cache_path)
299
+
300
+ matrix_unfpa = []
301
+ caches = [ods_use_cache, meta_use_cache, indicadores_use_cache]
302
+ # , genero_use_cache, poblacional_use_cache, etnico_use_cache,
303
+ # pilaresPdet_use_cache, estrategiasPdet_use_cache, categoriasPdet_use_cache]
304
+
305
+ for idx, i_cache in enumerate(caches):
306
+ # print(cache_paths[idx])
307
+
308
+ if i_cache:
309
+ emb_unfpa_np, meta = load_cache(cache_paths[idx])
310
+ # Minimal safety check: same model/instruction length
311
+ if meta.get("model_name") != model_name or meta.get("instr") != instruc_bases[idx] or meta.get("count") != len(texts[idx]):
312
+ print(f'Diferencias en carga de metadata nlp cache {cache_paths[idx]}:')
313
+ print(meta.get("model_name"), model_name)
314
+ print(meta.get("instr"), instruc_bases[idx])
315
+ print(meta.get("count"),len(texts[idx]))
316
+ # i_cache = False
317
+
318
+ if not i_cache:
319
+ print(f'no se encontro cache de id : {idx}')
320
+ # model = SentenceTransformer(model_name)
321
+ # ods_pairs = make_text_pairs(instruc_bases[idx], texts[idx])
322
+ # emb_ods = compute_embeddings(model, ods_pairs, batch_size=batch_size, normalize=normalize)
323
+ # emb_unfpa_np = emb_ods.cpu().numpy()
324
+ # save_cache(cache_paths[idx], {"model_name": model_name, "instr": instruc_bases[idx], "count": len(texts[idx])}, emb_unfpa_np)
325
+ else:
326
+ model = SentenceTransformer(model_name) # still needed for project embeddings
327
+
328
+ # Compute PATR embeddings
329
+ patr_pairs = make_text_pairs(instruc_iniciativas[idx], patr_texts)
330
+ emb_patr = compute_embeddings(model, patr_pairs, batch_size=batch_size, normalize=normalize)
331
+
332
+ # Convert ODS (np.ndarray) to torch.Tensor and move it to the same device as emb_patr
333
+ emb_unfpa_t = torch.from_numpy(emb_unfpa_np).to(emb_patr.device)
334
+
335
+ # Similarity
336
+ from sentence_transformers import util
337
+ sim_matrix_ = util.cos_sim(emb_patr, emb_unfpa_t).cpu().numpy()
338
+
339
+ matrix_unfpa.append(sim_matrix_)
340
+
341
+ matrix_unfpa.append(patr_ids)
342
+ print([len(x) for x in matrix_unfpa])
343
+ print(matrix_unfpa[-1])
344
+
345
+ from sklearn.preprocessing import MinMaxScaler
346
+
347
+ scaler = MinMaxScaler()
348
+
349
+ # matrix_unfpa_norm =
350
+
351
+
352
+
353
+ # tops_k = [5,1,1,1] # ods_use_cache, pilaresPdet_use_cache, estrategiasPdet_use_cache, categoriasPdet_use_cache
354
+ # IMPORTANTE: Solo procesar los primeros 3 índices (ODS, META, INDICADORES) ya que solo hay 3 matrices en matrix_unfpa
355
+ tops_k = [len(ods_texts), len(meta_texts), len(indicadores_texts)]
356
+ # tops_k_s = [3,2,2,1,1,1,1,1,1]
357
+ res_dfs = []
358
+
359
+ for idx, top in enumerate(tops_k):
360
+ sim_matrix = matrix_unfpa[idx]
361
+ # Top-K per project
362
+ # K = min(top_k, sim_matrix.shape[1])
363
+ K = min(top, sim_matrix.shape[1])
364
+ top_rows = []
365
+ for i in range(sim_matrix.shape[0]):
366
+ # print(f'i de sim_matrix.shape[0]: {i}')
367
+ sims = sim_matrix[i]
368
+ # rt descending and take first K
369
+ top_idx = np.argsort(-sims)[:K]
370
+
371
+ id_unico = matrix_unfpa[-1][i]
372
+ # ods_df
373
+ # meta_df
374
+ # inidicador_df
375
+ # genero_df
376
+ # poblacional_df
377
+ # etnico_df
378
+ # pilares_df
379
+ # estrategias_df
380
+ # categorias_df
381
+
382
+ # Reshape the 'similaridad_cos' column as it needs to be 2D for the scaler
383
+ similarity_scores = sims.reshape(-1, 1)
384
+ # Fit and transform the data
385
+ sims_norm = scaler.fit_transform(similarity_scores)
386
+
387
+ #### RESULTADOS PARA DESCRIPCION ODS
388
+ if idx == 0:
389
+ # Calcular el peso total (suma de similaridades normalizadas para esta iniciativa)
390
+ suma_sims_norm_ods = np.sum(sims_norm[top_idx, 0])
391
+ # Calcular la suma de similaridades sin normalizar
392
+ suma_sims_ods = np.sum(sims[top_idx])
393
+ peso_acumulado_ods = 0
394
+ peso_acumulado_ods_sin_norm = 0
395
+
396
+ for rank, j in enumerate(top_idx, start=1):
397
+ # Calcular el peso de cada ODS respecto al total (normalizado)
398
+ peso_ods = float(sims_norm[j, 0]) / suma_sims_norm_ods if suma_sims_norm_ods > 0 else 0
399
+ peso_acumulado_ods += peso_ods
400
+
401
+ # Calcular el peso de cada ODS respecto al total (sin normalizar)
402
+ peso_ods_sin_norm = float(sims[j]) / suma_sims_ods if suma_sims_ods > 0 else 0
403
+ peso_acumulado_ods_sin_norm += peso_ods_sin_norm
404
+
405
+ row = {
406
+ # "project_id": patr_df.iloc[i, patr_df.columns.get_loc("ID")], # Use iloc with positional index
407
+ # "project_text": patr_df.iloc[i, patr_df.columns.get_loc("INICIATIVAS")], # Use iloc with positional index
408
+ "INICIATIVA_ID": id_unico,
409
+ "ODS_ID": ods_df.iloc[j, ods_df.columns.get_loc("id_ods")], # Use iloc with positional index
410
+ "OBJETIVO": ods_df.iloc[j, ods_df.columns.get_loc("ods")], # Use iloc with positional index
411
+
412
+ # "ods_texto": ods_texts[j],
413
+ "ods_rank": rank,
414
+ "ods_similaridad_cos": float(sims[j]),
415
+ "ods_similaridad_cos_norm": float(sims_norm[j, 0]),
416
+ "ods_peso": peso_ods,
417
+ "ods_peso_acumulado": peso_acumulado_ods,
418
+ "ods_peso_sin_norm": peso_ods_sin_norm,
419
+ "ods_peso_acumulado_sin_norm": peso_acumulado_ods_sin_norm,
420
+ # "ods_titulo": ods_df.iloc[j, ods_df.columns.get_loc("INDICADORES")], # Use iloc with positional index
421
+ # "ods_texto": ods_texts[j]
422
+ }
423
+ top_rows.append(row)
424
+
425
+ #### RESULTADOS PARA METAS ODS
426
+ if idx == 1:
427
+ # Calcular el peso total (suma de similaridades normalizadas para esta iniciativa)
428
+ suma_sims_norm_meta = np.sum(sims_norm[top_idx, 0])
429
+ # Calcular la suma de similaridades sin normalizar
430
+ suma_sims_meta = np.sum(sims[top_idx])
431
+ peso_acumulado_meta = 0
432
+ peso_acumulado_meta_sin_norm = 0
433
+
434
+ for rank, j in enumerate(top_idx, start=1):
435
+ # Calcular el peso de cada Meta respecto al total (normalizado)
436
+ peso_meta = float(sims_norm[j, 0]) / suma_sims_norm_meta if suma_sims_norm_meta > 0 else 0
437
+ peso_acumulado_meta += peso_meta
438
+
439
+ # Calcular el peso de cada Meta respecto al total (sin normalizar)
440
+ peso_meta_sin_norm = float(sims[j]) / suma_sims_meta if suma_sims_meta > 0 else 0
441
+ peso_acumulado_meta_sin_norm += peso_meta_sin_norm
442
+
443
+ meta_id_value = str(meta_df.iloc[j, meta_df.columns.get_loc("ID_META")])
444
+ row = {
445
+ # "project_id": patr_df.iloc[i, patr_df.columns.get_loc("ID")], # Use iloc with positional index
446
+ # "project_text": patr_df.iloc[i, patr_df.columns.get_loc("INICIATIVAS")], # Use iloc with positional index
447
+ "INICIATIVA_ID": id_unico,
448
+ "META_ID": meta_id_value, # Use iloc with positional index
449
+ "META": meta_df.iloc[j, meta_df.columns.get_loc("META")], # Use iloc with positional index
450
+ "ODS_ID": meta_df.iloc[j, meta_df.columns.get_loc("ID_OBJETIVO")],
451
+ "META_ID1": meta_id_value.split('.')[1],
452
+
453
+ # "ods_texto": ods_texts[j],
454
+ "meta_rank": rank,
455
+ "meta_similaridad_cos": float(sims[j]),
456
+ "meta_similaridad_cos_norm": float(sims_norm[j, 0]),
457
+ "meta_peso": peso_meta,
458
+ "meta_peso_acumulado": peso_acumulado_meta,
459
+ "meta_peso_sin_norm": peso_meta_sin_norm,
460
+ "meta_peso_acumulado_sin_norm": peso_acumulado_meta_sin_norm,
461
+ # "ods_titulo": ods_df.iloc[j, ods_df.columns.get_loc("INDICADORES")], # Use iloc with positional index
462
+ # "ods_texto": ods_texts[j]
463
+ }
464
+ top_rows.append(row)
465
+
466
+ #### RESULTADOS PARA INDICADORES ODS
467
+ if idx == 2:
468
+ # Calcular el peso total (suma de similaridades normalizadas para esta iniciativa)
469
+ suma_sims_norm_indicador = np.sum(sims_norm[top_idx, 0])
470
+ # Calcular la suma de similaridades sin normalizar
471
+ suma_sims_indicador = np.sum(sims[top_idx])
472
+ peso_acumulado_indicador = 0
473
+ peso_acumulado_indicador_sin_norm = 0
474
+
475
+ for rank, j in enumerate(top_idx, start=1):
476
+ # Calcular el peso de cada Indicador respecto al total (normalizado)
477
+ peso_indicador = float(sims_norm[j, 0]) / suma_sims_norm_indicador if suma_sims_norm_indicador > 0 else 0
478
+ peso_acumulado_indicador += peso_indicador
479
+
480
+ # Calcular el peso de cada Indicador respecto al total (sin normalizar)
481
+ peso_indicador_sin_norm = float(sims[j]) / suma_sims_indicador if suma_sims_indicador > 0 else 0
482
+ peso_acumulado_indicador_sin_norm += peso_indicador_sin_norm
483
+
484
+ meta_id_value = str(inidicador_df.iloc[j, inidicador_df.columns.get_loc("ID_META")])
485
+ indicador_id_value = str(inidicador_df.iloc[j, inidicador_df.columns.get_loc("ID_INDICADORES")])
486
+ row = {
487
+ # "project_id": patr_df.iloc[i, patr_df.columns.get_loc("ID")], # Use iloc with positional index
488
+ # "project_text": patr_df.iloc[i, patr_df.columns.get_loc("INICIATIVAS")], # Use iloc with positional index
489
+ "INICIATIVA_ID": id_unico,
490
+ "INDICADOR_ID": indicador_id_value, # Use iloc with positional index
491
+ "INDICADOR": inidicador_df.iloc[j, inidicador_df.columns.get_loc("INDICADORES")], # Use iloc with positional index
492
+ "ODS_ID": inidicador_df.iloc[j, inidicador_df.columns.get_loc("ID_ODS")],
493
+ "META_ID1": meta_id_value,
494
+ "META_ID2": meta_id_value.split('.')[1],
495
+ "INDICADOR_ID1": indicador_id_value.split('.')[2],
496
+ # "ods_texto": ods_texts[j],
497
+ "indicador_rank": rank,
498
+ "indicador_similaridad_cos": float(sims[j]),
499
+ "indicador_similaridad_cos_norm": float(sims_norm[j, 0]),
500
+ "indicador_peso": peso_indicador,
501
+ "indicador_peso_acumulado": peso_acumulado_indicador,
502
+ "indicador_peso_sin_norm": peso_indicador_sin_norm,
503
+ "indicador_peso_acumulado_sin_norm": peso_acumulado_indicador_sin_norm,
504
+ # "ods_titulo": ods_df.iloc[j, ods_df.columns.get_loc("INDICADORES")], # Use iloc with positional index
505
+ # "ods_texto": ods_texts[j]
506
+ }
507
+ top_rows.append(row)
508
+
509
+ #### RESULTADOS PARA ENFOQUE GENERO (idx == 3)
510
+ # if idx == 3:
511
+ # for rank, j in enumerate(top_idx, start=1):
512
+ # row = {
513
+ # "INICIATIVA_ID": id_unico,
514
+ # "ENFOQUE_GENERO": genero_df.iloc[j, genero_df.columns.get_loc("CATEGORIA")],
515
+ # "similaridad_cos": float(sims[j]),
516
+ # }
517
+ # top_rows.append(row)
518
+
519
+ #### RESULTADOS PARA ENFOQUE POBLACIONAL (idx == 4)
520
+ # if idx == 4:
521
+ # for rank, j in enumerate(top_idx, start=1):
522
+ # row = {
523
+ # "INICIATIVA_ID": id_unico,
524
+ # "ENFOQUE_POBLACIONAL": poblacional_df.iloc[j, poblacional_df.columns.get_loc("CATEGORIA")],
525
+ # "similaridad_cos": float(sims[j]),
526
+ # }
527
+ # top_rows.append(row)
528
+
529
+ #### RESULTADOS PARA ENFOQUE ETNICO (idx == 5)
530
+ # if idx == 5:
531
+ # for rank, j in enumerate(top_idx, start=1):
532
+ # row = {
533
+ # "INICIATIVA_ID": id_unico,
534
+ # "ENFOQUE_POBLACIONAL": etnico_df.iloc[j, etnico_df.columns.get_loc("CATEGORIA")],
535
+ # "similaridad_cos": float(sims[j]),
536
+ # }
537
+ # top_rows.append(row)
538
+
539
+ #### RESULTADOS PARA PILARES (idx == 6)
540
+ # if idx == 6:
541
+ # for rank, j in enumerate(top_idx, start=1):
542
+ # row = {
543
+ # "INICIATIVA_ID": id_unico,
544
+ # "similaridad_cos": float(sims[j]),
545
+ # "pilar": pilares_texts[j]
546
+ # }
547
+ # top_rows.append(row)
548
+
549
+ #### RESULTADOS PARA ESTRATEGIAS (idx == 7)
550
+ # if idx == 7:
551
+ # for rank, j in enumerate(top_idx, start=1):
552
+ # row = {
553
+ # "INICIATIVA_ID": id_unico,
554
+ # "similaridad_cos": float(sims[j]),
555
+ # "estrategia": estrategias_texts[j]
556
+ # }
557
+ # top_rows.append(row)
558
+
559
+ #### RESULTADOS PARA CATEGORIAS (idx == 8)
560
+ # if idx == 8:
561
+ # for rank, j in enumerate(top_idx, start=1):
562
+ # row = {
563
+ # "INICIATIVA_ID": id_unico,
564
+ # "similaridad_cos": float(sims[j]),
565
+ # "categoria": categorias_texts[j]
566
+ # }
567
+ # top_rows.append(row)
568
+
569
+
570
+ res_df = pd.DataFrame(top_rows).drop_duplicates()
571
+ res_df = res_df.merge(df_iniciativas, 'left', left_on='INICIATIVA_ID', right_on='id_unico', suffixes=('','_y'))
572
+ drop_cols = [col for col in res_df.columns if col.endswith('_y')]
573
+ res_df = res_df.drop(columns=drop_cols)
574
+ res_dfs.append(res_df)
575
+
576
+ # Additionally, export a simple edges file (Top-1) for graph visualizations
577
+ # edges = []
578
+ # df_edges = pd.DataFrame()
579
+ # df_edges['source'] = res_dfs[0]['ods_id']
580
+ # df_edges['target'] = res_dfs[0]['indicador_id']
581
+ # df_edges['weight'] = res_dfs[0]['similaridad_cos']
582
+
583
+ # for pid, group in res_df.groupby("project_id"):
584
+ # best = group.sort_values("rank").iloc[0]
585
+ # edges.append({"source": group["project_id"], "target": group["ods_id"], "weight": group["similaridad_cos"]})
586
+ # df_edges = pd.DataFrame(edges)#.to_tblinput(out_edges, index=False, encoding="utf-8
587
+
588
+ # html = build_graph(df_edges)
589
+ from sklearn.preprocessing import MinMaxScaler
590
+
591
+
592
+ # dfs_norm = []
593
+ # Initialize the MinMaxScaler
594
+ scaler = MinMaxScaler()
595
+
596
+ # for i in range(0,3):
597
+
598
+ # if i == 0:
599
+ # # Reshape the 'similaridad_cos' column as it needs to be 2D for the scaler
600
+ # similarity_scores = res_dfs[i]['ods_similaridad_cos'].values.reshape(-1, 1)
601
+ # # Fit and transform the data
602
+ # res_dfs[i]['ods_similaridad_cos_normalized'] = scaler.fit_transform(similarity_scores)
603
+
604
+ # if i == 1:
605
+ # # Reshape the 'similaridad_cos' column as it needs to be 2D for the scaler
606
+ # similarity_scores = res_dfs[i]['meta_similaridad_cos'].values.reshape(-1, 1)
607
+ # # Fit and transform the data
608
+ # res_dfs[i]['meta_similaridad_cos_normalized'] = scaler.fit_transform(similarity_scores)
609
+
610
+ # if i == 2:
611
+ # # Reshape the 'similaridad_cos' column as it needs to be 2D for the scaler
612
+ # similarity_scores = res_dfs[i]['indicador_similaridad_cos'].values.reshape(-1, 1)
613
+ # # Fit and transform the data
614
+ # res_dfs[i]['indicador_similaridad_cos_normalized'] = scaler.fit_transform(similarity_scores)
615
+
616
+
617
+ # top_ods, top_meta, top_indicador
618
+
619
+ # bdl_ods = res_dfs[0][res_dfs[0].ods_rank <= top_ods].merge(res_dfs[1][res_dfs[1].meta_rank <= top_meta], 'left', left_on=['INICIATIVA_ID','ODS_ID'], right_on=['INICIATIVA_ID','ODS_ID'], suffixes=('','_y'))
620
+ # # bdl_ods = res_dfs[0][res_dfs[0].ods_rank.isin([1,2,3])].merge(res_dfs[1].head(2), 'inner', left_on=['INICIATIVA_ID'], right_on=['INICIATIVA_ID'])
621
+ # drop_cols = [col for col in bdl_ods.columns if col.endswith('_y')]
622
+ # bdl_ods = bdl_ods.drop(columns=drop_cols)
623
+ # bdl_ods = bdl_ods.merge(res_dfs[2][res_dfs[2].indicador_rank <= top_indicador],'left', left_on=['INICIATIVA_ID','ODS_ID'], right_on=['INICIATIVA_ID','ODS_ID'], suffixes=('','_y'))
624
+ # # bdl_ods = bdl_ods.merge(res_dfs[2].head(2),'inner', left_on=['INICIATIVA_ID'], right_on=['INICIATIVA_ID'])
625
+
626
+
627
+ #versión concat
628
+ ods_bdl = res_dfs[0][res_dfs[0].ods_rank <= top_ods].reset_index(drop=True)
629
+ meta_bdl = res_dfs[1][res_dfs[1].meta_rank <= top_meta].reset_index(drop=True)
630
+ indicador_bdl = res_dfs[2][res_dfs[2].indicador_rank <= top_indicador].reset_index(drop=True)
631
+
632
+ base_metas = ods_bdl.merge(meta_bdl, 'inner', left_on=['INICIATIVA_ID','ODS_ID'], right_on=['INICIATIVA_ID','ODS_ID'], suffixes=('','_y'))
633
+ drop_cols = [col for col in base_metas.columns if col.endswith('_y')]
634
+ base_metas = base_metas.drop(columns=drop_cols)
635
+
636
+ base_indicadores = ods_bdl.merge(indicador_bdl, 'inner', left_on=['INICIATIVA_ID','ODS_ID'], right_on=['INICIATIVA_ID','ODS_ID'], suffixes=('','_y'))
637
+ drop_cols = [col for col in base_indicadores.columns if col.endswith('_y')]
638
+ base_indicadores = base_indicadores.drop(columns=drop_cols)
639
+
640
+ # meta_ind = pd.concat([base_metas[['INICIATIVA_ID','ODS_ID','meta_rank','META_ID', 'META']], base_indicadores[['indicador_rank','INDICADOR_ID', 'INDICADOR']]], axis=1)
641
+
642
+ # bdl_ods = ods_bdl.merge(meta_ind, 'inner', left_on=['INICIATIVA_ID','ODS_ID'], right_on=['INICIATIVA_ID','ODS_ID'], suffixes=('','_y'))
643
+ # drop_cols = [col for col in bdl_ods.columns if col.endswith('_y')]
644
+ # bdl_ods = bdl_ods.drop(columns=drop_cols)
645
+
646
+ bdl_ods = pd.concat([meta_bdl[['INICIATIVA_ID','ODS_ID','meta_rank','META_ID', 'META']], indicador_bdl[['indicador_rank','INDICADOR_ID', 'INDICADOR']]], axis=1)
647
+ bdl_ods = pd.concat([ods_bdl[['INICIATIVA_ID','ODS_ID','ods_rank','OBJETIVO']], bdl_ods[['meta_rank','META_ID', 'META', 'indicador_rank','INDICADOR_ID', 'INDICADOR']]], axis=1)
648
+
649
+ # Nota: Los siguientes merges con res_dfs[3-8] están deshabilitados porque no se calculan las matrices para esos índices
650
+ # Para habilitarlos, primero necesitarías descomentar el procesamiento de genero, poblacional, etnico, pilares, estrategias, categorias en el bucle principal
651
+
652
+ # bdl_ods = bdl_ods.merge(res_dfs[3], 'inner', left_on='INICIATIVA_ID', right_on='INICIATIVA_ID', suffixes=('','_y'))
653
+ # drop_cols = [col for col in bdl_ods.columns if col.endswith('_y')]
654
+ # bdl_ods = bdl_ods.drop(columns=drop_cols)
655
+ # bdl_ods = bdl_ods.merge(res_dfs[4], 'inner', left_on='INICIATIVA_ID', right_on='INICIATIVA_ID', suffixes=('','_y'))
656
+ # drop_cols = [col for col in bdl_ods.columns if col.endswith('_y')]
657
+ # bdl_ods = bdl_ods.drop(columns=drop_cols)
658
+ # bdl_ods = bdl_ods.merge(res_dfs[5], 'inner', left_on='INICIATIVA_ID', right_on='INICIATIVA_ID', suffixes=('','_y'))
659
+ # drop_cols = [col for col in bdl_ods.columns if col.endswith('_y')]
660
+ # bdl_ods = bdl_ods.drop(columns=drop_cols)
661
+ # bdl_ods = bdl_ods.merge(res_dfs[6], 'inner', left_on='INICIATIVA_ID', right_on='INICIATIVA_ID', suffixes=('','_y'))
662
+ # drop_cols = [col for col in bdl_ods.columns if col.endswith('_y')]
663
+ # bdl_ods = bdl_ods.drop(columns=drop_cols)
664
+ # bdl_ods = bdl_ods.merge(res_dfs[7], 'inner', left_on='INICIATIVA_ID', right_on='INICIATIVA_ID', suffixes=('','_y'))
665
+ # drop_cols = [col for col in bdl_ods.columns if col.endswith('_y')]
666
+ # bdl_ods = bdl_ods.drop(columns=drop_cols)
667
+ # bdl_ods = bdl_ods.merge(res_dfs[8], 'inner', left_on='INICIATIVA_ID', right_on='INICIATIVA_ID', suffixes=('','_y'))
668
+ # drop_cols = [col for col in bdl_ods.columns if col.endswith('_y')]
669
+ # bdl_ods = bdl_ods.drop(columns=drop_cols)
670
+ # bdl_ods = bdl_ods.merge(res_dfs[9], 'inner', left_on='INICIATIVA_ID', right_on='INICIATIVA_ID')
671
+ print(f'Tamaño BDL: {len(bdl_ods)}')
672
+
673
+ ## Complementando metas con recomendaciones de indicadores
674
+ res_dfs[1] = res_dfs[1].merge(recomendaciones_df[['Meta_ODS', 'Recomendaciones_territoriales']], 'left', left_on='META_ID', right_on='Meta_ODS')
675
+
676
+
677
+
678
+
679
+ # return (querys, res_dfs[0], res_dfs[1], res_dfs[2], res_dfs[3], res_dfs[4], res_dfs[5], res_dfs[6], res_dfs[7], res_dfs[8], bdl_ods)
680
+ return (res_dfs[0], res_dfs[1], res_dfs[2], df_categorias, 'Ejecución exitosa. Revisa los DataFrames resultantes para análisis detallados.')
681
+ # return bdl_ods, ods_bdl, meta_bdl, indicador_bdl
682
+
683
+
684
+
685
+ # ============================================================================
686
+ # Función para normalizar
687
+ # ============================================================================
688
+
689
+
690
+