"""CPV1-v2 · paso 15 (worker, numpy; el de la v1 con el corte en 2025): caché de entrenamiento. Lee interno/datos/E.tsv, se queda con anio_ref ≤ 2025 (lo único que entra en algún entrenamiento de la v2) y escribe en interno/cache/: filas.npz por fila: texto (id del objeto normalizado distinto), anio, fuente, órgano, tipo, menor, tramo, div, grupo, h tablas.json fuentes, órganos, tipos, divisiones, grupos (los índices de filas.npz) Gw.npz, Gc.npz CSR objeto distinto × variable (recuento tf), palabras (u+b) y caracteres (c), con un prefiltro global de df (u ≥ 3, b ≥ 5, c ≥ 5 objetos distintos: ningún entrenamiento, que es un subconjunto, puede superar su df global) vocab_w.txt, vocab_c.txt las variables en el orden de sus columnas (alfabético, para el desempate de §4.1.4) Usa cpvtexto (el mismo módulo del job) para los términos y las variables.""" import sys, time, json, array, collections import numpy as np import scipy.sparse as sp sys.path.insert(0, '/w/py') import cpvtexto as ct T0 = time.time() def log(*a): print(f'[{time.time()-T0:6.0f}s]', *a, flush=True) E = '/w/interno/datos/E.tsv'; OUT = '/w/interno/cache' import os; os.makedirs(OUT, exist_ok=True) tab = {k: {} for k in ('fuente', 'organo', 'tipo', 'div', 'grupo')} def ix(k, v): d = tab[k] if v not in d: d[v] = len(d) return d[v] textos = {} A = {k: array.array(t) for k, t in (('texto', 'i'), ('anio', 'h'), ('fuente', 'b'), ('organo', 'i'), ('tipo', 'b'), ('menor', 'b'), ('tramo', 'b'), ('div', 'b'), ('grupo', 'h'), ('h', 'Q'))} MEN = {'0': 0, '1': 1} TR = {c: i for i, c in enumerate('abcdefgh' + ct.NULO)} n_sin_terminos = 0 with open(E, encoding='utf-8') as f: cab = f.readline().rstrip('\n').split('\t') I = {c: i for i, c in enumerate(cab)} for n, l in enumerate(f): r = l.rstrip('\n').split('\t') anio = int(r[I['anio_ref']]) if anio > 2025: continue ts = ct.terminos(r[I['objeto']]) if not ts: n_sin_terminos += 1 continue k = ' '.join(ts) t = textos.get(k) if t is None: t = textos[k] = len(textos) A['texto'].append(t); A['anio'].append(anio); A['fuente'].append(ix('fuente', r[I['source']])) org = ct.desescapa(r[I['organo_clave']]) A['organo'].append(ix('organo', org) if org else -1) A['tipo'].append(ix('tipo', r[I['tipo_contrato']] or ct.NULO)) A['menor'].append(MEN.get(r[I['es_menor']], 2)) A['tramo'].append(TR[ct.tramo(r[I['imp_adj_eur']] or None)]) A['div'].append(ix('div', r[I['div']])) g = r[I['grupo']] A['grupo'].append(ix('grupo', g) if g else -1) A['h'].append(int(r[I['h']])) if n % 1000000 == 0: log('filas', n, 'textos', len(textos)) log('filas ≤ 2025', len(A['texto']), 'textos distintos', len(textos), 'sin términos', n_sin_terminos) np.savez(f'{OUT}/filas.npz', **{k: np.frombuffer(v, dtype={'i': np.int32, 'h': np.int16, 'b': np.int8, 'Q': np.uint64}[v.typecode]) for k, v in A.items()}) tablas = {k: sorted(d, key=d.get) for k, d in tab.items()} tablas['tramo'] = list('abcdefgh' + ct.NULO); tablas['menor'] = ['0', '1', ct.NULO] json.dump(tablas, open(f'{OUT}/tablas.json', 'w'), ensure_ascii=False) del A lista = sorted(textos, key=textos.get); del textos # pasada 1: df global por objeto distinto dfw = collections.Counter(); dfc = collections.Counter() for i, k in enumerate(lista): ts = k.split(' ') dfw.update(ct.rasgos_palabras(ts).keys()); dfc.update(ct.rasgos_caracteres(ts).keys()) if i % 500000 == 0: log('df', i, len(dfw), len(dfc)) vw = sorted(f for f, c in dfw.items() if c >= (3 if f[0] == 'u' else 5)); del dfw vc = sorted(f for f, c in dfc.items() if c >= 5); del dfc log('vocabulario global', len(vw), len(vc)) open(f'{OUT}/vocab_w.txt', 'w').write('\n'.join(vw) + '\n'); open(f'{OUT}/vocab_c.txt', 'w').write('\n'.join(vc) + '\n') gw = {f: i for i, f in enumerate(vw)}; gc = {f: i for i, f in enumerate(vc)}; del vw, vc # pasada 2: CSR objeto × variable (tf) def csr(fun, g): ind = array.array('i'); dat = array.array('f'); ptr = array.array('q', [0]) for i, k in enumerate(lista): d = fun(k.split(' ')) row = sorted((g[f], tf) for f, tf in d.items() if f in g) for j, tf in row: ind.append(j); dat.append(tf) ptr.append(len(ind)) if i % 500000 == 0: log('csr', i, len(ind)) return sp.csr_matrix((np.frombuffer(dat, dtype=np.float32), np.frombuffer(ind, dtype=np.int32), np.frombuffer(ptr, dtype=np.int64)), shape=(len(lista), len(g))) Gw = csr(ct.rasgos_palabras, gw); sp.save_npz(f'{OUT}/Gw.npz', Gw, compressed=False); log('Gw', Gw.shape, Gw.nnz); del Gw Gc = csr(ct.rasgos_caracteres, gc); sp.save_npz(f'{OUT}/Gc.npz', Gc, compressed=False); log('Gc', Gc.shape, Gc.nnz) log('fin')