"""E1c (DEFINICIONES_PREVIAS §7.2), adaptado de e1b/py/15_leer_A_r2.py: el resultado del lote (desierto / adjudicado) en vez del número de ofertas. Cotejo A, lectura (sin red): fichas y XML descargados en cotejo/html → A_anuncios.csv, A_parecidas.csv y, para las parecidas que necesitan el XML (con lotes o sin resultado en la ficha), la siguiente ronda de XML (lista_xml.csv). Uso: python3 py/06_leer_A.py """ import csv, datetime as dt, html, json, os, re, sys, unicodedata import xml.etree.ElementTree as ET C = '/e1c/cotejo/' ronda = int(sys.argv[1]) if len(sys.argv) > 1 else 1 CORTE_DATOS = dt.datetime(2026, 10, 11, 23, 15) # UTC; las fechas de la ficha son de Madrid (+2): margen declarado 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, n=1): for i, l in enumerate(ls): if l == et: return ls[i + 1] if n == 1 else ls[i + 1:i + 1 + n] return None def norm(s): if not s: return '' s = unicodedata.normalize('NFKD', s.lower()); s = ''.join(c for c in s if not unicodedata.combining(c)) return ' '.join(re.sub(r'[^a-z0-9]+', ' ', s).split()) def fecha(s): m = re.match(r'(\d{2})/(\d{2})/(\d{4})(?: (\d{2}):(\d{2}))?', s or '') if not m: return None return dt.datetime(int(m[3]), int(m[2]), int(m[1]), int(m[4] or 0), int(m[5] or 0)) TIPOS_RES = re.compile(r'(Adjudicaci|Formalizaci|Desiert|Desistimiento|Renuncia|Resoluci)') 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} i = ls.index('Órgano de contratación') d = {'legible': True, 'organo': ls[i + 1], 'perfil': ls[i + 2] if re.fullmatch(r'\d{6,}', ls[i + 2]) else None, 'ruta': ls[i + 3] if re.fullmatch(r'\d{6,}', ls[i + 2]) else ls[i + 2], 'expediente': tras(ls, 'Expediente'), 'estado': tras(ls, 'Estado de la Licitación'), 'cpvs': re.findall(r'(\d{8})-', tras(ls, 'Código CPV') or ''), 'resultado': tras(ls, 'Resultado'), 'licitadores': tras(ls, 'Nº de Licitadores Presentados'), 'fin_ofertas': tras(ls, 'Fecha fin de presentación de oferta')} s = open(path, encoding='utf-8', errors='replace').read() docs = [] for m in re.finditer(r'(.*?)', s, flags=re.S): f = re.search(r'fechaPub[^>]*>\s*]*>\s*([^<]+)', m.group(1)) t = re.search(r'tipoDocumento[^>]*>\s*]*>\s*([^<]+)', m.group(1)) xml = [html.unescape(a) for a, alt in re.findall(r'href="([^"]+)"[^>]*>\s*]*alt="([^"]+)"', m.group(1)) if 'xml' in alt.lower()] if t: docs.append({'fecha': fecha(f.group(1).strip()) if f else None, 'tipo': html.unescape(t.group(1)).strip(), 'xml': xml[0] if xml else None}) d['docs'] = docs return d def ln(e): return e.tag.split('}')[-1] def xml_resultados(path): """TenderResult del documento: lote, código, ofertas, fecha; y los CPV de los lotes y los ID del órgano.""" try: root = ET.parse(path).getroot() except Exception as e: # noqa: BLE001 return {'error': str(e)[:100]} res, lotes, ids, nombre = [], {}, {}, None for e in root.iter(): if ln(e) == 'TenderResult': r = {'lote': None, 'codigo': None, 'ofertas': None, 'award': None} for c in e.iter(): n = ln(c) if n == 'ProcurementProjectLotID' and r['lote'] is None: r['lote'] = (c.text or '').strip() elif n == 'ResultCode' and r['codigo'] is None: r['codigo'] = (c.text or '').strip() elif n == 'ReceivedTenderQuantity' and r['ofertas'] is None: r['ofertas'] = int(float(c.text)) elif n == 'AwardDate' and r['award'] is None: r['award'] = (c.text or '').strip()[:10] res.append(r) elif ln(e) == 'ProcurementProjectLot': lid = next((c.text.strip() for c in e if ln(c) == 'ID' and c.text), None) lotes[lid] = [c.text.strip() for c in e.iter() if ln(c) == 'ItemClassificationCode' and c.text and c.text.strip()] elif ln(e) == 'PartyIdentification': for c in e: if ln(c) == 'ID' and c.get('schemeName') and c.get('schemeName') not in ids: ids[c.get('schemeName')] = (c.text or '').strip() elif ln(e) == 'PartyName' and nombre is None: nombre = next(((c.text or '').strip() for c in e if ln(c) == 'Name'), None) return {'resultados': res, 'lotes': lotes, 'ids': ids, 'nombre': nombre} RES_OK = {'Adjudicado', 'Formalizado', 'Adjudicado provisionalmente', 'Adjudicado definitivamente', 'Desierto', 'Desierto provisionalmente', 'Desierto definitivamente', 'Licitador mejor valorado:Requerimiento de documentacion'} CODIGOS_OK, CODIGOS_DESIST = {'1', '2', '3', '6', '7', '8', '9', '10'}, {'4', '5'} CODIGOS_ADJ, CODIGOS_DES = {'1', '2', '8', '9', '10'}, {'3', '6', '7'} def clase_ficha(t): t = (t or '').strip() if t.startswith('Desiert'): return 'desierto' if t.startswith(('Adjudicad', 'Formalizad', 'Licitador mejor valorado')): return 'adjudicado' if t.startswith(('Desistimiento', 'Renuncia')): return 'desistido' return 'otro' an = {int(a['anuncio']): a for a in csv.DictReader(open(C + 'muestra_anuncios.csv'))} A = list(csv.DictReader(open(C + 'muestra_A.csv'))) FA = {i: ficha(C + f'html/an{i:02d}.html') for i in an} out_an = [] for i, a in sorted(an.items()): f = FA[i]; r = {'anuncio': i, 'licitacion_id': a['licitacion_id'], 'legible': bool(f and f.get('legible'))} if r['legible']: ffo = fecha(f['fin_ofertas']) if f['fin_ofertas'] else None r.update(organo_fuente=f['organo'], perfil=f['perfil'], organo_nuestro=a['organo_nombre'], cpvs_ficha=' '.join(f['cpvs']), organo_ok=norm(f['organo']) == norm(a['organo_nombre']), cpv_fuente=' '.join(f['cpvs'][:3]), cpv_ok=bool(f['cpvs']) and all(c[:2] == a['cpv_cel'] for c in f['cpvs']), cpv_div=a['cpv_cel'], fin_fuente=f['fin_ofertas'], fin_nuestro=a['ffo'], fin_ok=bool(ffo) and ffo.date().isoformat() == a['ffo'][:10], estado=f['estado'], rectificaciones_posteriores=' | '.join(f"{d['fecha']:%d/%m/%Y} {d['tipo']}" for d in f['docs'] if d['fecha'] and d['fecha'] > CORTE_DATOS and 'ectific' in d['tipo'])) out_an.append(r) pendientes = [] out_p = [] for p in A: i, k = int(p['anuncio']), int(p['k']) lid = p['licitacion_id'].split('/')[-1] lote = p['lote_u'].split('|', 1)[1] if '|' in p['lote_u'] else None f = ficha(C + f'html/lic_{lid}.html'); fa = FA[i] r = {'anuncio': i, 'k': k, 'licitacion_id': p['licitacion_id'], 'lote': lote or '', 'nuestro_ofertas': p['num_ofertas'], 'nuestro_resultado': 'adjudicado' if p['adjudicado'] == 'True' else 'desierto', 'nuestro_cpv': p['cpv_cel'], 'nuestro_fecha_adj': p['fecha_adj'], 'nuestro_anio': p['anio_ref']} if not f or not f.get('legible'): r['estado'] = 'NL'; out_p.append(r); continue r.update(organo_fuente=f['organo'], perfil=f['perfil'], cpvs_ficha=' '.join(f['cpvs'][:4]), resultado_ficha=f['resultado'], licitadores_ficha=f['licitadores']) # órgano frente al del anuncio en la fuente if fa and fa.get('legible'): if f['perfil'] and f['perfil'] == fa['perfil']: r['organo'] = 'mismo_perfil' elif norm(f['organo']) == norm(fa['organo']): r['organo'] = 'mismo_nombre_perfil_distinto' else: r['organo'] = 'ERROR' else: r['organo'] = 'anuncio_no_legible' # resultado, ofertas y CPV: de la ficha si es una licitación sin lotes con resultado directo; si no, del XML xmls = [d for d in sorted([d for d in f['docs'] if d['xml'] and TIPOS_RES.match(d['tipo'])], key=lambda d: d['fecha'] or dt.datetime.min, reverse=True)] fuente_res = None if not lote and f['resultado'] and clase_ficha(f['resultado']) != 'otro': fuente_res = 'ficha' r['fuente_ofertas'] = f['licitadores'] r['fuente_resultado'] = clase_ficha(f['resultado']); r['fuente_texto'] = f['resultado']; r['fuente_cpvs'] = ';'.join(f['cpvs']) else: # XML descargados de esta parecida: html/x__.xml, n = 0, 1, 2 por orden enc = None for n in range(3): xp = C + f'html/x_{lid}_{n}.xml' if not os.path.exists(xp): if n < len(xmls) and n < 3 and enc is None: if n == ronda - 1: pendientes.append({'clave': f'x{i:02d}_{k}_{n}', 'url': xmls[n]['xml'], 'destino': f'html/x_{lid}_{n}.xml'}) break x = xml_resultados(xp) cand = [t for t in x.get('resultados', []) if (t['lote'] == lote if lote else True)] if cand: enc = (n, x, cand); break if enc: n, x, cand = enc fuente_res = f'xml{n}' ofs = [t['ofertas'] for t in cand if t['ofertas'] is not None] r['fuente_ofertas'] = max(ofs) if ofs else None cods = {t['codigo'] for t in cand} r['fuente_codigos'] = ' '.join(sorted(c or '-' for c in cods)) r['fuente_resultado'] = ('adjudicado' if cods & CODIGOS_ADJ else 'desierto' if cods & CODIGOS_DES else 'desistido' if cods & CODIGOS_DESIST else 'otro') r['fuente_award'] = min((t['award'] for t in cand if t['award']), default='') if lote: r['fuente_cpvs'] = ';'.join(x['lotes'].get(lote) or []) if not x['lotes'].get(lote): r['fuente_cpv_nota'] = 'el XML no trae los CPV del lote: no legible (CPV)' else: r['fuente_cpvs'] = ';'.join(f['cpvs']) r['xml_ids'] = json.dumps(x['ids']) else: r['estado'] = 'PENDIENTE_XML' if any(q['destino'].startswith(f'html/x_{lid}_') for q in pendientes) else 'NL_XML' if fuente_res: r['estado'] = 'leida'; r['fuente_res'] = fuente_res # documento de resultado publicado (para el año con solo la ficha) docres = sorted([d for d in f['docs'] if d['fecha'] and TIPOS_RES.match(d['tipo'])], key=lambda d: d['fecha']) r['primer_doc_resultado'] = f"{docres[0]['fecha']:%Y-%m-%d} {docres[0]['tipo']}" if docres else '' r['docs_posteriores_corte'] = ' | '.join(f"{d['fecha']:%d/%m/%Y} {d['tipo']}" for d in f['docs'] if d['fecha'] and d['fecha'] > CORTE_DATOS) out_p.append(r) def escribe(nombre, filas): campos = [] for f in filas: for c in f: if c not in campos: campos.append(c) with open(C + nombre, 'w', newline='') as fh: w = csv.DictWriter(fh, fieldnames=campos); w.writeheader(); w.writerows(filas) escribe('A_anuncios_lectura.csv', out_an); escribe('A_parecidas_lectura.csv', out_p) if pendientes: escribe(f'lista_xml{ronda}.csv', pendientes) print('anuncios legibles', sum(r['legible'] for r in out_an), '| parecidas leídas', sum(r.get('estado') == 'leida' for r in out_p), '| pendientes XML', sum(r.get('estado') == 'PENDIENTE_XML' for r in out_p), '| NL', sum(r.get('estado', '').startswith('NL') for r in out_p), '| peticiones nuevas en ronda', ronda, ':', len(pendientes))