"""ETIQ-3 · V-INT2 · impl. 1 · remisión de la información de control interno a la CCM (Anexo 1.1 y 1.4), por ayuntamiento y ejercicio (2022-2025), desde el texto -layout de los cuatro informes; columna por la posición de la marca frente a las cabeceras de la página. Casado a NIF por DIR3 (Unidades_EELL, AY nivel 1, provincia 28, nombre normalizado). Uso (host, sin red): python3 -I v2_remision_i1.py """ import csv, re, sys, unicodedata, collections DT, XL, XM, OUT = sys.argv[1:5] sys.path.insert(0, XM) from xlsx_min import hojas # noqa INF = {2022: '036_if_controlinterno_eell_2022', 2023: '065_if-sellado-control-interno-2023-aprobado-cjo-24072025', 2024: '066_if-controlinterno-eell-2024-sellado-aprobadocjo30012026', 2025: '067_informe-control-interno-2025-sellado-aprobadocjo29072026'} FILA = re.compile(r'^(\s*-?\s*)([A-ZÁÉÍÓÚÑÜ][^\d✓]*?)\s{2,}(\d{1,3}(?:\.\d{3})*|\d+)\s+(.*)$') def norm(s): s = unicodedata.normalize('NFD', s.lower()) s = ''.join(c for c in s if unicodedata.category(c) != 'Mn') s = re.sub(r'[^a-z0-9]+', ' ', s).strip() s = re.sub(r'^(ayuntamiento de |ayuntamiento del )', '', s) m = re.match(r'^(.*) (el|la|los|las)$', s) # «Escorial, El» -> «el escorial» if m: s = m.group(2) + ' ' + m.group(1) return s def cabeceras_pagina(lineas): """Columnas (estado, centro) de la cabecera de una página (la línea con «No rendidas/No remitidas» y las 3 de encima).""" for j, l in enumerate(lineas): if re.search(r'No rendidas|No remitidas', l): cols = [] for k in range(max(j - 3, 0), min(j + 2, len(lineas))): for m in re.finditer(r'En plazo|Fuera de plazo|Remitidas(?! totales)|No rendidas|No remitidas', lineas[k]): nom = m.group(0) nom = 'no' if nom.startswith('No r') else ('fuera' if nom.startswith('Fuera') else 'si') cols.append((nom, (m.start() + m.end()) / 2)) return cols return None filas = [] for ej, base in INF.items(): T = open(f'{DT}/{base}.txt', encoding='utf-8').read() L = T.split('\n') ini = next(i for i, l in enumerate(L) if re.match(r'^\s*Anexo 1(\.1)?\s*$', l)) fin = next(i for i in range(ini + 1, len(L)) if re.match(r'^\s*Anexo (1\.2|2|2\.1)\s*$', L[i])) bloque = '\n'.join(L[ini:fin]) corte = re.search(r'MANCOMUNIDAD|Mancomunidad', bloque) if corte: bloque = bloque[:corte.start()] for pagina in bloque.split('\f'): PL = pagina.split('\n') cols = cabeceras_pagina(PL) for k, l in enumerate(PL): m = FILA.match(l) if not m: # nombre partido en dos líneas: «Nombre ... de» / « 361 X» / «Buitrago» m2 = re.match(r'^(\s*-?\s*)(\d{1,3}(?:\.\d{3})*|\d+)\s+([X✓].*)$', l) if m2 and k > 0 and k + 1 < len(PL) and re.search(r'[A-Za-zÁÉÍÓÚÑáéíóúñ]', PL[k - 1]) and not re.search(r'\d', PL[k - 1]): nom = (PL[k - 1].strip(' -') + ' ' + PL[k + 1].strip(' -')).strip() l = ' ' * 0 + nom + ' ' + m2.group(2) + l[m2.end(2):] l = l.rjust(len(PL[k])) # conserva la posición de la marca m = FILA.match(l) if not m: continue if not cols: print('SIN CABECERA', ej, repr(l[:100])); continue resto = m.group(4) marcas = [(mm.start() + len(l) - len(resto) + 0.5) for mm in re.finditer(r'[X✓]', resto)] if len(marcas) != 1: print('aviso', ej, repr(l[:90]), marcas) continue est = min(cols, key=lambda c: abs(c[1] - marcas[0]))[0] filas.append({'ejercicio': ej, 'entidad': m.group(2).strip(), 'poblacion': int(m.group(3).replace('.', '')), 'estado': {'si': 'en_plazo', 'fuera': 'fuera_plazo', 'no': 'no_remitida'}[est], 'anexo': '1.1'}) # Anexo 1.4 (2024 y 2025): remitidas fuera de plazo dentro de la ventana del informe i14 = [i for i, l in enumerate(L) if re.match(r'^\s*Anexo 1\.4\s*$', l)] if i14: tardias = set() for l in L[i14[0]:i14[0] + 80]: mm = re.match(r'^\s*([A-ZÁÉÍÓÚÑÜ][^\d]*?)\s{2,}(\d\d/\d\d/\d{4})\s*$', l) if mm: tardias.add(norm(mm.group(1))) if re.match(r'^\s*Total ayuntamientos', l): break for f in filas: if f['ejercicio'] == ej and norm(f['entidad']) in tardias: if f['estado'] != 'no_remitida': print('aviso: en 1.4 pero no «no remitida» en 1.1', ej, f['entidad'], f['estado']) f['estado_11'] = f['estado']; f['estado'] = 'fuera_plazo'; f['anexo'] = '1.1+1.4' tardias.discard(norm(f['entidad'])) if tardias: print('aviso: 1.4 sin fila en 1.1', ej, sorted(tardias)) # casado a DIR3 / NIF h = hojas(XL)['Unidades EELL'] d3 = collections.defaultdict(list) for r in h[1:]: r = r + [None] * 20 if r[4] == 'AY' and r[5] == '1' and r[15] == 'V' and r[6] == '28': d3[norm(r[2] or '')].append((r[1], r[17] or '')) STOP = {'de', 'del', 'la', 'el', 'los', 'las', 'y', 'e'} def clave2(x): return ' '.join(sorted(t for t in x.split() if t not in STOP)) d3b = collections.defaultdict(list) for k, v in d3.items(): d3b[clave2(k)] += v cnt = collections.Counter() for f in filas: n = norm(f['entidad']) c = d3.get(n, []) or d3b.get(clave2(n), []) if not c: c = [u for k, v in d3.items() for u in v if k.startswith(n + ' ')] if len(c) == 1: f['dir3'], f['nif'], f['ine'] = c[0][0], c[0][1], c[0][0][3:8] cnt[(f['ejercicio'], 'casado')] += 1 else: f['dir3'] = f['nif'] = f['ine'] = '' cnt[(f['ejercicio'], 'sin casar' if not c else 'ambiguo')] += 1 print('sin casar', f['ejercicio'], f['entidad'], len(c)) with open(OUT, 'w', newline='') as fh: w = csv.DictWriter(fh, ['ejercicio', 'entidad', 'poblacion', 'estado', 'anexo', 'dir3', 'nif', 'ine'], delimiter='\t', extrasaction='ignore') w.writeheader(); w.writerows(filas) print(sorted(cnt.items())) res = collections.Counter((f['ejercicio'], f['estado']) for f in filas) print(sorted(res.items())) # control: Cuadro II.1 de cada informe (ayuntamientos). 2024 y 2025: «remitidas a 30/04» = en plazo del Anexo 1.1 CTRL = {2022: (100, 31, 48), 2023: (88, 25, 66), 2024: (91, None, 88), 2025: (99, None, 80)} for ej, (a, b, c) in CTRL.items(): n11 = collections.Counter(f['estado'] if f['anexo'] == '1.1' else ('en_plazo' if f.get('estado_11') == 'en_plazo' else 'no_remitida') for f in filas if f['ejercicio'] == ej) ok = n11['en_plazo'] == a and (b is None or n11['fuera_plazo'] == b) and (n11['no_remitida'] + (n11['fuera_plazo'] if b is None else 0)) == c print('control Cuadro II.1', ej, dict(n11), 'esperado', (a, b, c), 'OK' if ok else 'DISTINTO')