# T20 · cuánto cambian las cifras de las 20 empresas más grandes si la ficha contara también las filas atribuidas por nombre # (vía diccionario de la identidad), con las consultas de la web (app.db, vista por defecto «sin duplicados», sin atípicos). # Imagen de la API, /data = / (ro). Solo NIF de sociedades y nombres de empresa en la salida. import sys, re, json, time sys.path.insert(0, '/app') from app import db, medidas from app.services import screener_queries as q from etl.v2 import privacidad, marcas t0 = time.time() c = db.get_conn() print("conexión", round(time.time() - t0, 1), "s", flush=True) I = '/data/unified_20261108.identidad/adjudicatarios_filas.parquet' c.execute(f"""CREATE TEMP TABLE atr0 AS WITH af AS (SELECT * FROM read_parquet('{I}')), d AS (SELECT adjudicatario_nif, adjudicatario_nombre, min(nif_inferido) nif_inferido, max(nif_inferido) nif_max, bool_and(empresa_via = 'diccionario') solo_dic, bool_or(persona_fisica) pf, sum(filas) filas FROM af GROUP BY 1, 2) SELECT * FROM d WHERE solo_dic AND nif_inferido = nif_max AND NOT pf""") re_emp = re.compile(marcas.RE_NOMBRE_EMPRESA) nombres = [r[0] for r in c.execute("SELECT DISTINCT adjudicatario_nombre FROM atr0").fetchall()] fuera = [n for n in nombres if n and not re_emp.search(n.lower()) and privacidad.es_nombre_persona(n)] c.execute("CREATE TEMP TABLE fuera (nombre VARCHAR)") if fuera: c.executemany("INSERT INTO fuera VALUES (?)", [(n,) for n in fuera]) c.execute("CREATE TEMP TABLE atr AS SELECT * FROM atr0 WHERE adjudicatario_nombre NOT IN (SELECT nombre FROM fuera)") print("pares atribuibles", c.execute("SELECT count(*), sum(filas) FROM atr").fetchone(), "fuera por nombre de persona", len(fuera), flush=True) F = q._filtro(medidas.POR_DEFECTO) imp = medidas.IMPORTE base = c.execute(f"""SELECT adjudicatario_nif, count(*) n, sum({imp}) imp FROM contratos WHERE {db.NIF_IDENTIFICABLE} AND {F} GROUP BY 1""").fetchall() extra = c.execute(f"""SELECT a.nif_inferido, count(*) n, sum({imp}) imp FROM contratos t JOIN atr a ON t.adjudicatario_nif IS NOT DISTINCT FROM a.adjudicatario_nif AND t.adjudicatario_nombre = a.adjudicatario_nombre WHERE {F} GROUP BY 1""").fetchall() B = {r[0]: (r[1], r[2] or 0.0) for r in base} E = {r[0]: (r[1], r[2] or 0.0) for r in extra} top = sorted(B, key=lambda k: -B[k][1])[:20] nuevo = {k: (B.get(k, (0, 0))[0] + E.get(k, (0, 0))[0], B.get(k, (0, 0))[1] + E.get(k, (0, 0))[1]) for k in set(B) | set(E)} top_n = sorted(nuevo, key=lambda k: -nuevo[k][1])[:20] nom = dict(c.execute("SELECT adjudicatario_nif, nombre FROM nombres_adj WHERE adjudicatario_nif IN (SELECT unnest(?))", [list(set(top) | set(top_n))]).fetchall()) if c.execute("SELECT count(*) FROM information_schema.tables WHERE table_name='nombres_adj'").fetchone()[0] else {} out = [] for i, k in enumerate(top, 1): b, e = B[k], E.get(k, (0, 0.0)) out.append(dict(puesto=i, nif=k, nombre=nom.get(k), contratos=b[0], importe=b[1], contratos_atrib=e[0], importe_atrib=e[1], pct_contratos=round(100 * e[0] / b[0], 2) if b[0] else None, pct_importe=round(100 * e[1] / b[1], 2) if b[1] else None, puesto_nuevo=top_n.index(k) + 1 if k in top_n else None)) entran = [dict(nif=k, nombre=nom.get(k), puesto_nuevo=top_n.index(k) + 1, contratos=B.get(k, (0, 0))[0], importe=B.get(k, (0, 0))[1], contratos_atrib=E.get(k, (0, 0))[0], importe_atrib=E.get(k, (0, 0))[1]) for k in top_n if k not in top] tot = dict(contratos_atrib=sum(v[0] for v in E.values()), importe_atrib=sum(v[1] for v in E.values()), nifs_con_atrib=len(E), nifs_solo_atrib=len(set(E) - set(B))) json.dump(dict(top20=out, entran=entran, totales=tot, segundos=round(time.time() - t0, 1)), open('/w/salidas/t20_empresas.json', 'w'), ensure_ascii=False, indent=1, default=str) for o in out: print(o["puesto"], o["nif"], (o["nombre"] or "")[:40], o["contratos"], round(o["importe"] / 1e6, 1), "+", o["contratos_atrib"], round(o["importe_atrib"] / 1e6, 1), f"({o['pct_contratos']} % contr, {o['pct_importe']} % imp)", "->", o["puesto_nuevo"]) print("entran:", [(e["nif"], (e["nombre"] or "")[:30], e["puesto_nuevo"]) for e in entran]) print(tot)