Download licitabench/build_dataset.py from Changetheblock/LicitaBench: direct link, hf CLI and curl.
- Browser
- Download file 13.1 kB
-
https://huggingface.co/datasets/Changetheblock/LicitaBench/resolve/main/licitabench/build_dataset.py
- Command line
-
hf download hf://datasets/Changetheblock/LicitaBench/licitabench/build_dataset.py
-
curl -L -o build_dataset.py https://huggingface.co/datasets/Changetheblock/LicitaBench/resolve/main/licitabench/build_dataset.py
13.1 kB
| """Construye el dataset de LicitaBench a partir de la copia de la base del agente: | |
| descarga los pliegos públicos, extrae el texto, lo alinea con los campos CODICE | |
| del anuncio (T1), elimina nombres de firmantes y escribe JSONL y parquet. | |
| Uso: | |
| python -m licitabench.build_dataset # todo | |
| python -m licitabench.build_dataset --limite 40 # prueba | |
| python -m licitabench.build_dataset --sin-ocr | |
| Salidas (data/dataset/): | |
| t1.jsonl / t1.parquet items de T1 con etiquetas alineadas y enlaces | |
| documentos.jsonl un registro por documento procesado (aceptado o descartado), con el motivo | |
| estadisticas.json recuento de descartes por motivo y de campos alineados | |
| data/textos/<id>.txt texto extraído sin nombres de firmantes (no se redistribuye por defecto) | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import logging | |
| import sys | |
| import time | |
| from collections import Counter | |
| from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor, as_completed | |
| from pathlib import Path | |
| from typing import Dict, List, Optional, Tuple | |
| from . import alineacion, descarga, fuentes, texto | |
| log = logging.getLogger("licitabench.build") | |
| DIR_DATASET = Path("data/dataset") | |
| DIR_TEXTOS = Path("data/textos") | |
| MIN_CAMPOS_ALINEADOS = 3 # un documento entra en T1 si al menos 3 de los 6 campos casan con el texto | |
| MIN_CHARS_TEXTO = 3000 # por debajo, el PDF no es un pliego legible | |
| def _procesar_texto(args: Tuple[str, str, bool]) -> Tuple[str, Optional[str], Dict]: | |
| """Función para el pool de procesos: extrae texto de un PDF ya descargado.""" | |
| ruta, clave, ocr = args | |
| try: | |
| t, info = texto.extraer(Path(ruta), clave, ocr=ocr) | |
| return clave, t, info | |
| except Exception as e: # pdf corrupto, cifrado... | |
| return clave, None, {"error": f"{type(e).__name__}: {e}"[:200]} | |
| def seleccionar(licitaciones: List[Dict]) -> List[Dict]: | |
| """Licitaciones con al menos un PPA enlazado.""" | |
| return [t for t in licitaciones if fuentes.documentos_ppa(t)] | |
| def construir(limite: Optional[int] = None, ocr: bool = True, hilos_descarga: int = 6, procesos: int = 6, | |
| ruta_db: Path = fuentes.RUTA_DB) -> Dict: | |
| t0 = time.time() | |
| DIR_DATASET.mkdir(parents=True, exist_ok=True) | |
| DIR_TEXTOS.mkdir(parents=True, exist_ok=True) | |
| todas = fuentes.cargar_licitaciones(ruta_db) | |
| candidatas = seleccionar(todas) | |
| if limite: | |
| candidatas = candidatas[:limite] | |
| log.info("licitaciones en origen: %d; con PPA enlazado: %d; a procesar: %d", len(todas), | |
| len(seleccionar(todas)), len(candidatas)) | |
| # 1) Elegir, por licitación, el documento PPA principal (PDF) y descargarlo. | |
| # Si el primero no es PDF o falla, se prueba el siguiente candidato. | |
| registros_doc: List[Dict] = [] | |
| descartes = Counter() | |
| pendientes_texto: List[Tuple[str, str, bool]] = [] | |
| por_clave: Dict[str, Dict] = {} | |
| def _descargar_para(t: Dict) -> List[Dict]: | |
| out = [] | |
| sesion = descarga._sesion() | |
| docs = fuentes.ordenar_candidatos_ppa(fuentes.documentos_ppa(t)) | |
| for d in docs: | |
| nombre = (d.get("filename") or "").lower() | |
| reg = {"id": fuentes.id_corto(t), "tender_id": t.get("tender_id"), "url": d["url"], "filename": d.get("filename"), | |
| "tipo_doc": d.get("type")} | |
| if not nombre.endswith(fuentes.EXTENSIONES_PDF): | |
| reg.update({"estado": "descartado", "motivo": f"extension_{nombre.rsplit('.', 1)[-1] if '.' in nombre else 'sin'}"}) | |
| out.append(reg) | |
| continue | |
| ruta, info = descarga.descargar(d["url"], sesion=sesion) | |
| if ruta is None: | |
| reg.update({"estado": "descartado", "motivo": info.get("motivo", "descarga_fallida")}) | |
| out.append(reg) | |
| continue | |
| reg.update({"estado": "descargado", "ruta": str(ruta), "clave": descarga.sha1_url(d["url"]), | |
| "bytes": info.get("bytes"), "sha256": info.get("sha256")}) | |
| out.append(reg) | |
| break # con un PPA principal basta para la v0 | |
| return out | |
| with ThreadPoolExecutor(max_workers=hilos_descarga) as ex: | |
| futs = {ex.submit(_descargar_para, t): t for t in candidatas} | |
| hechos = 0 | |
| for fut in as_completed(futs): | |
| t = futs[fut] | |
| regs = fut.result() | |
| registros_doc.extend(regs) | |
| hechos += 1 | |
| if hechos % 100 == 0: | |
| log.info("descargas: %d/%d", hechos, len(candidatas)) | |
| descargados = [r for r in regs if r["estado"] == "descargado"] | |
| if not descargados: | |
| descartes["sin_pdf_descargable"] += 1 | |
| continue | |
| r = descargados[0] | |
| por_clave[r["clave"]] = {"tender": t, "reg": r} | |
| pendientes_texto.append((r["ruta"], r["clave"], ocr)) | |
| log.info("PDF descargados: %d; licitaciones sin PDF descargable: %d", len(pendientes_texto), descartes["sin_pdf_descargable"]) | |
| # 2) Extraer texto (pool de procesos: pdfplumber es lento). | |
| textos: Dict[str, Tuple[Optional[str], Dict]] = {} | |
| with ProcessPoolExecutor(max_workers=procesos) as ex: | |
| for i, (clave, txt, info) in enumerate(ex.map(_procesar_texto, pendientes_texto, chunksize=4), 1): | |
| textos[clave] = (txt, info) | |
| if i % 100 == 0: | |
| log.info("textos: %d/%d", i, len(pendientes_texto)) | |
| # 3) Alinear, anonimizar y escribir. | |
| items: List[Dict] = [] | |
| campos_ok = Counter(); campos_motivo = Counter(); idiomas = Counter(); metodos = Counter() | |
| for clave, (txt, info) in textos.items(): | |
| t = por_clave[clave]["tender"]; reg = por_clave[clave]["reg"] | |
| reg["extraccion"] = info | |
| if txt is None: | |
| reg.update({"estado": "descartado", "motivo": "extraccion_fallida"}); descartes["extraccion_fallida"] += 1 | |
| continue | |
| if len(txt) < MIN_CHARS_TEXTO: | |
| reg.update({"estado": "descartado", "motivo": "texto_insuficiente"}); descartes["texto_insuficiente"] += 1 | |
| continue | |
| metodos[info.get("metodo")] += 1 | |
| idioma = texto.detectar_idioma(txt); idiomas[idioma] += 1 | |
| cpv = fuentes.cpv_principal(t) | |
| ali = alineacion.alinear_t1(txt, t, cpv) | |
| n_ok = sum(1 for c in ali.values() if c["ok"]) | |
| for campo, c in ali.items(): | |
| if c["ok"]: | |
| campos_ok[campo] += 1 | |
| else: | |
| campos_motivo[f"{campo}:{c.get('motivo')}"] += 1 | |
| reg["campos_alineados"] = n_ok | |
| if n_ok < MIN_CAMPOS_ALINEADOS: | |
| reg.update({"estado": "descartado", "motivo": f"menos_de_{MIN_CAMPOS_ALINEADOS}_campos_alineados"}) | |
| descartes["pocos_campos_alineados"] += 1 | |
| continue | |
| anon, n_red = texto.eliminar_firmantes(txt) | |
| id_item = fuentes.id_corto(t) | |
| (DIR_TEXTOS / f"{id_item}.txt").write_text(anon, encoding="utf-8") | |
| etiquetas = {campo: (c["valor"] if c["ok"] else None) for campo, c in ali.items()} | |
| item = { | |
| "id": id_item, | |
| "tarea": "T1", | |
| **fuentes.metadatos_publicos(t), | |
| "documento": {"url": reg["url"], "nombre": reg["filename"], "tipo": reg["tipo_doc"], "sha256": reg.get("sha256"), | |
| "paginas": info.get("paginas"), "chars": len(anon), "metodo_extraccion": info.get("metodo"), | |
| "idioma": idioma, "nombres_eliminados": n_red.get("nombres", 0), "dni_eliminados": n_red.get("dni", 0)}, | |
| "etiquetas": etiquetas, | |
| "etiquetas_detalle": {campo: {k: v for k, v in c.items() if k in ("ok", "forma", "tipo_contexto", "codigo", "cobertura", "motivo", "unidad_detectada", "valor_anuncio")} | |
| for campo, c in ali.items()}, | |
| "evidencia": {campo: c.get("evidencia") for campo, c in ali.items() if c["ok"]}, | |
| "n_campos_alineados": n_ok, | |
| "texto_local": str(DIR_TEXTOS / f"{id_item}.txt"), | |
| } | |
| # título y evidencias se publican: se les quitan los nombres de personas | |
| limpios, n_frag = texto.eliminar_nombres_fragmentos({"__titulo": item.get("titulo"), **item["evidencia"]}) | |
| if "titulo" in item: | |
| item["titulo"] = limpios.pop("__titulo") | |
| else: | |
| limpios.pop("__titulo", None) | |
| item["evidencia"] = limpios | |
| item["documento"]["nombres_eliminados_fragmentos"] = n_frag | |
| items.append(item) | |
| reg["estado"] = "aceptado" | |
| items.sort(key=lambda x: x["id"]) | |
| _escribir_jsonl(DIR_DATASET / "t1.jsonl", items) | |
| _escribir_parquet(DIR_DATASET / "t1.parquet", items) | |
| _escribir_jsonl(DIR_DATASET / "documentos.jsonl", sorted(registros_doc, key=lambda r: (r["id"], r["url"]))) | |
| stats = { | |
| "fecha_construccion": time.strftime("%Y-%m-%d"), | |
| "licitaciones_en_origen": len(todas), | |
| "licitaciones_con_ppa": len(seleccionar(todas)), | |
| "licitaciones_procesadas": len(candidatas), | |
| "pdf_descargados": len(pendientes_texto), | |
| "items_t1": len(items), | |
| "descartes": dict(descartes), | |
| "descartes_documento_por_motivo": dict(Counter(r.get("motivo") for r in registros_doc if r["estado"] == "descartado")), | |
| "campos_alineados_ok": dict(Counter(c for i in items for c, v in i["etiquetas"].items() if v is not None)), | |
| "campos_alineados_ok_todos_los_documentos": dict(campos_ok), | |
| "campos_no_alineados_por_motivo": dict(sorted(campos_motivo.items(), key=lambda kv: -kv[1])), | |
| "distribucion_n_campos": dict(sorted(Counter(i["n_campos_alineados"] for i in items).items())), | |
| "idiomas": dict(idiomas), | |
| "metodos_extraccion": dict(metodos), | |
| "tipo_importe_detectado": dict(Counter(i["etiquetas_detalle"]["importe"].get("tipo_contexto") for i in items if i["etiquetas"]["importe"])), | |
| "unidad_duracion_detectada": dict(Counter(i["etiquetas_detalle"]["duracion_meses"].get("unidad_detectada") for i in items if i["etiquetas"]["duracion_meses"])), | |
| "segundos": round(time.time() - t0), | |
| } | |
| (DIR_DATASET / "estadisticas.json").write_text(json.dumps(stats, ensure_ascii=False, indent=2), encoding="utf-8") | |
| log.info("items T1: %d; descartes: %s; %ds", len(items), dict(descartes), stats["segundos"]) | |
| return stats | |
| def _escribir_jsonl(ruta: Path, filas: List[Dict]) -> None: | |
| with ruta.open("w", encoding="utf-8") as f: | |
| for r in filas: | |
| f.write(json.dumps(r, ensure_ascii=False) + "\n") | |
| def _escribir_parquet(ruta: Path, items: List[Dict]) -> None: | |
| """Tabla plana: una fila por item, etiquetas como columnas; detalle y evidencia como JSON.""" | |
| try: | |
| import pyarrow as pa | |
| import pyarrow.parquet as pq | |
| except ImportError: | |
| log.warning("pyarrow no instalado: no se escribe parquet") | |
| return | |
| filas = [] | |
| for i in items: | |
| filas.append({ | |
| "id": i["id"], "expediente": i["expediente"], "titulo": i["titulo"], "enlace_anuncio": i["enlace_anuncio"], | |
| "organo_nif": i["organo_nif"], "tipo_contrato": i["tipo_contrato"], "fecha_publicacion": i["fecha_publicacion"], | |
| "documento_url": i["documento"]["url"], "documento_nombre": i["documento"]["nombre"], "documento_sha256": i["documento"]["sha256"], | |
| "documento_paginas": i["documento"]["paginas"], "documento_chars": i["documento"]["chars"], "idioma": i["documento"]["idioma"], | |
| "importe": i["etiquetas"]["importe"], "plazo_presentacion": i["etiquetas"]["plazo_presentacion"], | |
| "duracion_meses": i["etiquetas"]["duracion_meses"], "cpv_principal": i["etiquetas"]["cpv_principal"], | |
| "procedimiento": i["etiquetas"]["procedimiento"], "organo_contratacion": i["etiquetas"]["organo_contratacion"], | |
| "n_campos_alineados": i["n_campos_alineados"], | |
| "etiquetas_detalle_json": json.dumps(i["etiquetas_detalle"], ensure_ascii=False), | |
| "evidencia_json": json.dumps(i["evidencia"], ensure_ascii=False), | |
| }) | |
| tabla = pa.Table.from_pylist(filas) | |
| pq.write_table(tabla, ruta) | |
| def main(argv=None): | |
| ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) | |
| ap.add_argument("--limite", type=int, default=None, help="procesar solo las N primeras licitaciones con PPA") | |
| ap.add_argument("--sin-ocr", action="store_true", help="no pasar OCR a los PDF que son imagen") | |
| ap.add_argument("--hilos", type=int, default=6, help="descargas en paralelo") | |
| ap.add_argument("--procesos", type=int, default=6, help="procesos para extraer texto") | |
| ap.add_argument("--db", type=Path, default=fuentes.RUTA_DB) | |
| a = ap.parse_args(argv) | |
| logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s", stream=sys.stderr) | |
| stats = construir(limite=a.limite, ocr=not a.sin_ocr, hilos_descarga=a.hilos, procesos=a.procesos, ruta_db=a.db) | |
| print(json.dumps(stats, ensure_ascii=False, indent=2)) | |
| if __name__ == "__main__": | |
| main() | |