"""E1b encendido A3 (anuncio en la fuente) y A4 (una parecida por anuncio en la fuente), sin red, sobre lo descargado.""" import csv, datetime as dt, html, json, os, re, unicodedata W = '/web-e5' H = f'{W}/interno/e1b/html' def lineas(path): s = open(path, encoding='utf-8', errors='replace').read() s = re.sub(r'', '', s, flags=re.S); s = re.sub(r'', '', s, flags=re.S) s = re.sub(r'', '\n', s); s = re.sub(r'<[^>]+>', '\n', s); s = html.unescape(s) return [re.sub(r'\s+', ' ', l).strip() for l in s.split('\n') if l.strip()] def tras(ls, et): return ls[ls.index(et) + 1] if et in ls else None def todas_tras(ls, et): return [ls[i + 1] for i, l in enumerate(ls) if l == et and i + 1 < len(ls)] def norm(s): s = unicodedata.normalize('NFKD', (s or '').lower()); s = ''.join(c for c in s if not unicodedata.combining(c)) return ' '.join(re.sub(r'[^a-z0-9]+', ' ', s).split()) def ficha(path): if not os.path.exists(path) or os.path.getsize(path) == 0: return None ls = lineas(path) if 'Órgano de contratación' not in ls: return {'legible': False} # el CPV va con «Código CPV» o, en un sistema dinámico de adquisición, con «Categoría / CPV Clasificación» (y su # desplegable «Código Categoría/CPV»): las cifras de las líneas que siguen a la etiqueta hasta la siguiente etiqueta cpvs = [] for et in ('Código CPV', 'Categoría / CPV Clasificación', 'Código Categoría/CPV'): if et in ls: i = ls.index(et) for l in ls[i + 1: i + 12]: if not re.match(r'(\d{8})-|-- Todos --', l): break cpvs += re.findall(r'(\d{8})-', l) return {'legible': True, 'organo': tras(ls, 'Órgano de contratación'), 'estado': tras(ls, 'Estado de la Licitación'), 'cpvs': sorted(set(cpvs)), 'resultados': todas_tras(ls, 'Resultado'), 'licitadores': todas_tras(ls, 'Nº de Licitadores Presentados'), 'fin': tras(ls, 'Fecha fin de presentación de oferta') or tras(ls, 'Fecha fin de presentación de solicitud'), 'lugar': tras(ls, 'Lugar de ejecución')} mu = list(csv.DictReader(open(f'{W}/e1b/salidas/11_muestra.csv'))) cpv = {} for r in csv.DictReader(open(f'{W}/interno/e1b/23_cpv_anuncios.csv')): cpv.setdefault(r['licitacion_id'], set()).update(c for c in re.findall(r'\d{8}', r['cpvs'] or '')) pares = json.load(open(f'{W}/interno/e1b/21_pares.json')) a3, a4 = [], [] for i, r in enumerate(mu, 1): f = ficha(f'{H}/an{i:02d}.html') lic = 'PLACSP:' + r['id_canonical'].split(':', 2)[2] nuestros = cpv.get(lic, set()) if not f or not f['legible']: a3.append({'id': r['id_corto'], 'legible': False}); continue org_ok = norm(f['organo']) == norm(r['organo_nombre']) cpv_ok = bool(f['cpvs']) and set(f['cpvs']) == nuestros and all(c[:2] == r['cpv_div'] for c in f['cpvs']) # contradicción (§5, A3): la ficha da un CPV de otra división o uno que no tenemos; dar menos CPV que los nuestros (solo # el principal) no contradice cpv_contra = (not f['cpvs']) or any(c[:2] != r['cpv_div'] or c not in nuestros for c in f['cpvs']) fin_f = None if f['fin']: m = re.match(r'(\d{2})/(\d{2})/(\d{4})', f['fin']) fin_f = dt.date(int(m[3]), int(m[2]), int(m[1])) if m else None fin_ok = fin_f is not None and fin_f >= dt.date.fromisoformat(r['fecha_fin_ofertas']) a3.append({'id': r['id_corto'], 'legible': True, 'organo_ficha': f['organo'], 'organo_ok': org_ok, 'cpvs_ficha': f['cpvs'], 'cpvs_nuestros': sorted(nuestros), 'cpv_ok': cpv_ok, 'cpv_contradiccion': cpv_contra, 'fin_ficha': str(fin_f), 'fin_nuestro': r['fecha_fin_ofertas'], 'fin_ok': fin_ok, 'estado_ficha': f['estado']}) p = next(p for p in pares if p['anuncio'] == r['id_corto'] and p['k'] == 1) g = ficha(f'{H}/pa{i:02d}.html') if not g or not g['legible']: a4.append({'par': p['par'], 'legible': False}); continue org4 = norm(g['organo']) == norm(r['organo_nombre']) lote = p['lote_u'] != p['licitacion_id'] n_of = int(float(p['num_ofertas'])) ofs = [int(x) for x in g['licitadores'] if re.fullmatch(r'\d+', x)] res = [x for x in g['resultados']] # legible para ofertas: un solo resultado en la ficha y el lote es la licitación entera (con lotes, la ficha no da el lote) legible_of = (len(ofs) == 1 and not lote) clase_ok = legible_of and ((ofs[0] == 1) == (n_of == 1)) des_ficha = any('desiert' in x.lower() for x in res) res_ok = legible_of and (des_ficha == (p['des'] == 'True' and p['adj'] != 'True')) a4.append({'par': p['par'], 'legible': True, 'organo_ficha': g['organo'], 'organo_ok': org4, 'lote': lote, 'ofertas_ficha': ofs, 'ofertas_nuestras': n_of, 'resultados_ficha': res, 'legible_ofertas': legible_of, 'clase_ok': clase_ok if legible_of else None, 'resultado_ok': res_ok if legible_of else None, 'adj': p['adj'], 'des': p['des'], 'lugar_ficha': g['lugar']}) out = {'A3': a3, 'A4': a4, 'A3_resumen': {'legibles': sum(x['legible'] for x in a3), 'organo_mal': sum(1 for x in a3 if x['legible'] and not x['organo_ok']), 'cpv_distinto': sum(1 for x in a3 if x['legible'] and not x['cpv_ok']), 'cpv_contradiccion': sum(1 for x in a3 if x['legible'] and x['cpv_contradiccion']), 'fin_mal': sum(1 for x in a3 if x['legible'] and not x['fin_ok'])}, 'A4_resumen': {'legibles': sum(x['legible'] for x in a4), 'organo_mal': sum(1 for x in a4 if x['legible'] and not x['organo_ok']), 'legibles_ofertas': sum(1 for x in a4 if x.get('legible_ofertas')), 'clase_mal': sum(1 for x in a4 if x.get('clase_ok') is False), 'resultado_mal': sum(1 for x in a4 if x.get('resultado_ok') is False)}} json.dump(out, open(f'{W}/interno/e1b/24_a3_a4.json', 'w'), ensure_ascii=False, indent=1, default=str) print(json.dumps(out['A3_resumen']), json.dumps(out['A4_resumen'])) for x in a3: if x['legible'] and not (x['organo_ok'] and x['cpv_ok'] and x['fin_ok']): print('A3', json.dumps(x, ensure_ascii=False)) for x in a4: if not x['legible'] or not x['organo_ok'] or not x.get('legible_ofertas') or x.get('clase_ok') is False or x.get('resultado_ok') is False: print('A4', json.dumps(x, ensure_ascii=False))