Download licitabench/texto.py from Changetheblock/LicitaBench: direct link, hf CLI and curl.
- Browser
- Download file 13.4 kB
-
https://huggingface.co/datasets/Changetheblock/LicitaBench/resolve/main/licitabench/texto.py
- Command line
-
hf download hf://datasets/Changetheblock/LicitaBench/licitabench/texto.py
-
curl -L -o texto.py https://huggingface.co/datasets/Changetheblock/LicitaBench/resolve/main/licitabench/texto.py
13.4 kB
| """Extracción de texto de los PDF (pdfplumber; OCR con tesseract solo si el PDF es imagen), | |
| limpieza ligera, detección de idioma y eliminación de nombres de firmantes. | |
| El texto extraído se guarda en caché por sha1 de la URL (`data/cache/texto/<clave>.json`). | |
| """ | |
| from __future__ import annotations | |
| import json | |
| import re | |
| import shutil | |
| import subprocess | |
| import tempfile | |
| import unicodedata | |
| from collections import Counter | |
| from pathlib import Path | |
| from typing import Dict, List, Optional, Tuple | |
| CACHE_TEXTO = Path("data/cache/texto") | |
| MAX_PAGINAS = 250 | |
| MAX_PAGINAS_OCR = 40 | |
| UMBRAL_CHARS_POR_PAGINA = 40 # por debajo, la página se considera imagen | |
| IDIOMAS_OCR = "spa+cat+eus+glg" | |
| # ---------------------------------------------------------------- extracción | |
| def _texto_pdfplumber(ruta: Path, max_paginas: int = MAX_PAGINAS) -> Tuple[str, Dict]: | |
| import pdfplumber | |
| partes = [] | |
| with pdfplumber.open(ruta) as pdf: | |
| n = len(pdf.pages) | |
| for i, pagina in enumerate(pdf.pages[:max_paginas]): | |
| try: | |
| t = pagina.extract_text() or "" | |
| except Exception: | |
| t = "" | |
| partes.append(t) | |
| texto = "\n\f".join(partes) | |
| chars = sum(len(p) for p in partes) | |
| paginas_leidas = min(n, max_paginas) | |
| return texto, {"paginas": n, "paginas_leidas": paginas_leidas, "chars": chars, | |
| "chars_por_pagina": (chars / paginas_leidas) if paginas_leidas else 0.0} | |
| def _ocr_tesseract(ruta: Path, max_paginas: int = MAX_PAGINAS_OCR) -> Tuple[str, Dict]: | |
| """OCR página a página con pdftoppm + tesseract. Solo se llama si el PDF es imagen.""" | |
| if not (shutil.which("pdftoppm") and shutil.which("tesseract")): | |
| return "", {"ocr": "no_disponible"} | |
| partes = [] | |
| with tempfile.TemporaryDirectory() as tmp: | |
| subprocess.run(["pdftoppm", "-r", "200", "-l", str(max_paginas), "-png", str(ruta), f"{tmp}/p"], | |
| check=False, capture_output=True, timeout=600) | |
| imagenes = sorted(Path(tmp).glob("p-*.png")) | |
| for img in imagenes: | |
| r = subprocess.run(["tesseract", str(img), "-", "-l", IDIOMAS_OCR, "--psm", "6"], | |
| capture_output=True, text=True, timeout=300) | |
| partes.append(r.stdout or "") | |
| texto = "\n\f".join(partes) | |
| return texto, {"ocr": "tesseract", "paginas_ocr": len(partes), "chars_ocr": len(texto)} | |
| def extraer(ruta_pdf: Path, clave: str, cache: Path = CACHE_TEXTO, ocr: bool = True) -> Tuple[str, Dict]: | |
| """Texto bruto del PDF y metadatos de la extracción. Usa la caché si existe.""" | |
| cache.mkdir(parents=True, exist_ok=True) | |
| f = cache / f"{clave}.json" | |
| if f.exists(): | |
| d = json.loads(f.read_text(encoding="utf-8")) | |
| return d["texto"], d["info"] | |
| texto, info = _texto_pdfplumber(ruta_pdf) | |
| info["metodo"] = "pdfplumber" | |
| if info["chars_por_pagina"] < UMBRAL_CHARS_POR_PAGINA: | |
| info["pdf_imagen"] = True | |
| if ocr: | |
| texto_ocr, info_ocr = _ocr_tesseract(ruta_pdf) | |
| info.update(info_ocr) | |
| if len(texto_ocr) > len(texto): | |
| texto, info["metodo"] = texto_ocr, "tesseract" | |
| texto = limpiar(texto) | |
| info["chars_limpios"] = len(texto) | |
| f.write_text(json.dumps({"texto": texto, "info": info}, ensure_ascii=False), encoding="utf-8") | |
| return texto, info | |
| # ------------------------------------------------------------------ limpieza | |
| _RE_ESPACIOS = re.compile(r"[ \t ]+") | |
| _RE_LINEAS = re.compile(r"\n{3,}") | |
| _RE_GUION_CORTE = re.compile(r"(\w)-\n(\w)") | |
| def limpiar(texto: str) -> str: | |
| texto = texto.replace("\r", "\n") | |
| texto = _RE_ESPACIOS.sub(" ", texto) | |
| texto = "\n".join(l.strip() for l in texto.split("\n")) | |
| texto = _RE_LINEAS.sub("\n\n", texto) | |
| return texto.strip() | |
| def plegar(texto: str) -> str: | |
| """Minúsculas y sin acentos, para comparar.""" | |
| t = unicodedata.normalize("NFKD", texto.lower()) | |
| return "".join(c for c in t if not unicodedata.combining(c)) | |
| # -------------------------------------------------------------------- idioma | |
| _MARCADORES = { | |
| "es": {"el", "la", "los", "las", "del", "con", "para", "por", "que", "una", "contrato", "pliego", "cláusula", "clausula"}, | |
| "ca": {"el", "la", "els", "les", "del", "amb", "per", "que", "una", "contracte", "plec", "clàusula", "aquest", "aquesta", "i"}, | |
| "eu": {"eta", "edo", "bat", "da", "dira", "kontratu", "kontratua", "baldintza", "agiria", "den", "izango"}, | |
| "gl": {"o", "a", "os", "as", "do", "da", "con", "para", "por", "que", "unha", "contrato", "prego", "cláusula", "e"}, | |
| } | |
| _SOLO = { | |
| "ca": {"els", "les", "amb", "aquest", "aquesta", "plec", "contracte", "clàusula", "també", "més"}, | |
| "eu": {"eta", "dira", "kontratu", "kontratua", "baldintza", "izango", "edo"}, | |
| "gl": {"unha", "prego", "pregos", "concello", "xunta", "deputación", "licitación", "ningún", "ningunha"}, | |
| "es": {"pliego", "cláusulas", "clausulas", "contrato", "licitación", "licitacion", "ayuntamiento", "también", "además"}, | |
| } | |
| def detectar_idioma(texto: str, muestra: int = 60000) -> str: | |
| """Heurística por palabras marcadoras. Devuelve 'es', 'ca', 'eu', 'gl' o 'otro'.""" | |
| palabras = re.findall(r"[a-záéíóúàèòïüñç·]+", texto[:muestra].lower()) | |
| if len(palabras) < 50: | |
| return "otro" | |
| c = Counter(palabras) | |
| puntos = {} | |
| for idioma, exclusivas in _SOLO.items(): | |
| puntos[idioma] = sum(c[w] for w in exclusivas) | |
| mejor = max(puntos, key=puntos.get) | |
| return mejor if puntos[mejor] > 0 else "otro" | |
| # ------------------------------------------------------- nombres de firmantes | |
| # Los pliegos llevan nombres de los firmantes (alcaldes, secretarios, interventores) | |
| # en pies de firma y sellos de firma electrónica. No son parte del contenido que el | |
| # benchmark evalúa y se eliminan del texto antes de guardarlo. Es una pasada por | |
| # expresiones regulares: puede dejar algún nombre, por eso el texto no se | |
| # redistribuye hasta que se revise (ver DATASET_CARD.md). | |
| _NOMBRE = r"(?:[A-ZÁÉÍÓÚÑÇ][A-Za-zÁÉÍÓÚÑÇáéíóúñçü'\-\.]+)(?:\s+(?:de|del|la|las|los|y|i|e|da|do|dos|das|von|van)?\s*[A-ZÁÉÍÓÚÑÇ][A-Za-zÁÉÍÓÚÑÇáéíóúñçü'\-\.]+){1,5}" | |
| _PATRONES_NOMBRE = [ | |
| # Sellos de firma electrónica (AutoFirma, Portafirmas, @firma, FNMT...) | |
| re.compile(r"(Firmado|Signat|Sinatura|Firma(?:do)? electr[oó]nicamente|Firmado digitalmente|Signat digitalment|Firmado por|Signat per|Asinado por|Sinado por|Fdo\.?|Fdo\s*:|Firmante|Firmat)\s*(?:digitalmente|electr[oó]nicamente|electrònicament)?\s*(?:por|per|:)?\s*:?\s*" + _NOMBRE, re.U), | |
| # "NOMBRE APELLIDO APELLIDO - DNI 12345678X" (sello AutoFirma) | |
| re.compile(r"\b[A-ZÁÉÍÓÚÑÇ]{2,}(?:\s+[A-ZÁÉÍÓÚÑÇ]{2,}){1,5}\s*[-–]\s*(?:DNI|NIF|NIE)\s*[:.]?\s*\d{7,8}[A-Z]?", re.U), | |
| re.compile(r"\b(?:DNI|NIF|NIE)[ \t]*[:.]?[ \t]*\d{7,8}[A-Z]?[ \t]*[-–][ \t]*[A-ZÁÉÍÓÚÑÇ]{2,}(?:[ \t]+[A-ZÁÉÍÓÚÑÇ]{2,}){1,5}", re.U), | |
| # Tratamientos: D. / Dª / Dña. / Don / Doña / Sr. / Sra. seguidos de nombre propio | |
| re.compile(r"\b(?:D\.|Dª\.?|Dña\.?|Dº\.?|Don|Doña|Sr\.|Sra\.|Sr\s|Sra\s|D\.?/D[ªa]\.?)\s+" + _NOMBRE, re.U), | |
| # Cargo + nombre en pie de firma: "EL ALCALDE, Juan Pérez" / "LA SECRETARIA GENERAL: ..." | |
| re.compile(r"\b(?:EL|LA|L')\s*(?:ALCALDE|ALCALDESA|SECRETARI[OA](?:\s+GENERAL)?|INTERVENTOR[A]?|PRESIDENT[EA]|GERENTE|DIRECTOR[A]?(?:\s+GENERAL)?|CONSEJER[OA]|CONCEJAL[A]?|RECTOR[A]?|TESORER[OA]|SÍNDIC|SÍNDICA|BATLE|BATLESSA|REGIDOR[A]?|CONSELLER[A]?|DIPUTAD[OA])(?:\s+[A-ZÁÉÍÓÚÑÇ ]{0,40})?,?\s*:?\s*(?:D\.|Dª\.?|Dña\.?|Don|Doña)?\s*" + _NOMBRE, re.U), | |
| ] | |
| # DNI/NIE de personas físicas (8 dígitos + letra, o X/Y/Z + 7 dígitos + letra). | |
| # Los NIF de entidades (letra A-W + 7 dígitos + control) se conservan: identifican al órgano. | |
| _RE_DNI = re.compile(r"\b\d{8}[ -]?[A-Z]\b|\b[XYZ][ -]?\d{7}[ -]?[A-Z]\b") | |
| _RE_DNI_PARCIAL = re.compile(r"\b\*{2,4}\d{3,5}\*{1,3}[A-Z]?\b") | |
| _RE_CSV = re.compile(r"\b(?:CSV|Código Seguro de Verificaci[oó]n|Codi Segur de Verificaci[oó])\s*[:.]?\s*[A-Za-z0-9+/=\-]{10,}", re.I) | |
| MARCA_NOMBRE = "[NOMBRE ELIMINADO]" | |
| MARCA_DNI = "[DNI ELIMINADO]" | |
| def eliminar_firmantes(texto: str) -> Tuple[str, Dict]: | |
| """Sustituye nombres de firmantes y DNI por marcas. Devuelve (texto, contadores).""" | |
| n = Counter() | |
| def _sub_nombre(m): | |
| n["nombres"] += 1 | |
| g = m.group(0) | |
| # conserva la palabra de contexto (Firmado por, D., EL ALCALDE...) y borra el nombre | |
| prefijo = m.group(1) if m.lastindex and m.group(1) else "" | |
| if prefijo and g.startswith(prefijo): | |
| return f"{prefijo}: {MARCA_NOMBRE}" | |
| return MARCA_NOMBRE | |
| for pat in _PATRONES_NOMBRE: | |
| texto = pat.sub(_sub_nombre, texto) | |
| texto, k = _RE_DNI.subn(MARCA_DNI, texto); n["dni"] += k | |
| texto, k = _RE_DNI_PARCIAL.subn(MARCA_DNI, texto); n["dni"] += k | |
| texto, k = _RE_CSV.subn("CSV: [ELIMINADO]", texto); n["csv"] += k | |
| return texto, dict(n) | |
| # ------------------------------------------- nombres en fragmentos publicados | |
| # Los fragmentos de evidencia y los títulos sí se publican. Aquí el patrón es más estricto | |
| # que en eliminar_firmantes: exige nombre propio en minúsculas tras el tratamiento, para no | |
| # borrar rótulos como "D. PRESUPUESTO BASE DE LICITACIÓN". | |
| _NO_NOMBRE = r"(?!(?:Cargo|Fecha|Firmado|Firma|Signat|Data|T[eé]cnic[oa]?|Consejer[oa]|Director[a]?|Responsable|Gerente|Alcalde|Alcaldesa|Secretari[oa]?|Concejal[a]?|Pliego|Plec|Document[o]?)\b)" | |
| _PAL = _NO_NOMBRE + r"[A-ZÁÉÍÓÚÑÇ][a-záéíóúñçàèòïü'\-]+" | |
| _NOMBRE_ESTRICTO = _PAL + r"(?:\s+(?:(?:de|del|la|las|los|y|i|e|da|do|Di|De)\s+)*" + _PAL + r"){1,4}" | |
| _NO_MAYUS = r"(?!(?:PLIEGO|PLEC|DATA|DOCUMENTO?S?|FECHA|CARGO|FIRMADO|FIRMA|SIGNATURA|EL|LA|LOS|LAS|CL[AÁ]USULAS|P[AÁ]GINA|CSV|DIRECTOR[A]?|SECRETARI[OA]|GERENTE)\b)" | |
| _PMAY = _NO_MAYUS + r"[A-ZÁÉÍÓÚÑÇ]{2,}" | |
| _MAYUS = _PMAY + r"(?:\s+(?:(?:DE|DEL|LA|LAS|LOS|Y|I)\s+)*" + _PMAY + r"){1,5}" | |
| _TRAT = r"(?:D\.\s?ª|D\.|Dª\.?|Dña\.?|Dº\.?|Don|Doña|Sr\.|Sra\.)" | |
| _RE_FRAG_TRAT = re.compile(r"\b" + _TRAT + r"\s+(" + _NOMBRE_ESTRICTO + r")", re.U) | |
| _RE_FRAG_FIRMA = re.compile(r"((?i:firmado|signat|sinado|asinado)\s+(?i:electr[oó]nicamente\s+|eletr[oó]nicamente\s+|digitalmente\s+|electrònicament\s+)?(?i:por|per)\s*:?\s*)(" + _MAYUS + r"|" + _NOMBRE_ESTRICTO + r")", re.U) | |
| _RE_FRAG_PROFESION = re.compile(r"((?i:arquitect[oa]|ingenier[oa]|t[eé]cnic[oa])\s+(?i:t[eé]cnic[oa]\s+)?(?:D\.|D\.ª|Dª|Dña\.?|Don|Doña)\s+)(" + _MAYUS + r")", re.U) | |
| _DNI = r"(?P<dni>\d{8}[ -]?[A-Z]|[XYZ][ -]?\d{7}[ -]?[A-Z])" | |
| _RE_FRAG_DNI = re.compile(r"\b(?:NIF|DNI|NIE)\W{0,3}" + _DNI + r"\b|\b" + _DNI.replace("dni", "dni2") + r"\W{0,3}(?:FIN|IND|EIN)\b") | |
| _RE_FRAG_OTROS = [ | |
| # "firmado electrónicamente (Ley 40/2015) por NOMBRE APELLIDO" | |
| re.compile(r"((?i:firmado\s+electr[oó]nicamente)\s*\([^)]{0,40}\)\s*(?i:por)\s+)(" + _MAYUS + r")", re.U), | |
| # "Documento firmado por: Cargo: Santander, NOMBRE APELLIDO" | |
| re.compile(r"((?i:firmado\s+por)\s*:\s*Cargo:\s*[A-Za-zÁÉÍÓÚÑáéíóúñ]+,\s*)(" + _MAYUS + r")", re.U), | |
| # tabla de firmas: "Apellido Apellido Nombre 23-06-2026 13:48:10" | |
| re.compile(r"()((?:[A-ZÁÉÍÓÚÑÇ][a-záéíóúñçàèòïü]+\s+){1,3}[A-ZÁÉÍÓÚÑÇ][a-záéíóúñçàèòïü]+)(?=\s+\d{2}-\d{2}-\d{4}\s+\d{2}:\d{2}:\d{2})", re.U), | |
| ] | |
| def eliminar_nombres_fragmentos(fragmentos: Dict[str, Optional[str]]) -> Tuple[Dict[str, Optional[str]], int]: | |
| """Quita nombres de personas de un grupo de fragmentos del mismo documento (título y evidencias). | |
| Un nombre detectado en un fragmento se borra también en los demás, aunque allí aparezca sin | |
| tratamiento o con otra grafía de mayúsculas y acentos. Devuelve (fragmentos, sustituciones).""" | |
| nombres: List[str] = [] | |
| for v in fragmentos.values(): | |
| if not v: | |
| continue | |
| nombres += [m.group(1) for m in _RE_FRAG_TRAT.finditer(v)] | |
| nombres += [m.group(2) for m in _RE_FRAG_FIRMA.finditer(v)] | |
| nombres += [m.group(2) for m in _RE_FRAG_PROFESION.finditer(v)] | |
| for pat in _RE_FRAG_OTROS: | |
| nombres += [m.group(2) for m in pat.finditer(v)] | |
| total = 0 | |
| salida: Dict[str, Optional[str]] = {} | |
| for k, v in fragmentos.items(): | |
| if not v: | |
| salida[k] = v; continue | |
| for nombre in sorted(set(nombres), key=len, reverse=True): | |
| palabras = [re.escape(w) for w in plegar(nombre).split()] | |
| if len(palabras) < 2: | |
| continue | |
| # busca el nombre sobre el texto plegado y corta por posiciones (plegar conserva la longitud) | |
| pat = re.compile(r"\s+".join(palabras)) | |
| pl = plegar(v) | |
| if len(pl) != len(v): | |
| pat = re.compile(r"\s+".join(re.escape(w) for w in nombre.split())) | |
| pl = v | |
| trozos, fin = [], 0 | |
| for m in pat.finditer(pl): | |
| trozos.append(v[fin:m.start()] + MARCA_NOMBRE); fin = m.end(); total += 1 | |
| v = "".join(trozos) + v[fin:] | |
| # DNI junto a su rótulo, también en sellos laterales extraídos al revés ("78088468A FIN") | |
| v, k_dni = _RE_FRAG_DNI.subn(lambda m: m.group(0).replace(m.group("dni") or m.group("dni2"), MARCA_DNI), v) | |
| total += k_dni | |
| salida[k] = v | |
| return salida, total | |