# -*- coding: utf-8 -*- """工料机骨架库(决策 197,2026-10-25 主人定): 按「后缀+母行字段集」给 cos/cos4 原件建骨架签名组,每组只收**一个代表件**的大骨架 (小骨架形态种类最多的单一件;平手取最新)——绝不跨件拼合(主人定:A 的骨架不加到 B)。 小骨架 = 节点形态模板:自闭合行 / 带子级块(LabourMaterialsEquipmentsMachinesElement×n); 形态 key = (是否自闭合, 母行字段集, 子级字段集),一个项目的骨架大小=形态种类数,与行数无关。 命中标准(主人定):只要「后缀+字段」符合,即按此组代表骨架使用——项目级/单位级工料机 汇总按代表大骨架备全形态槽位(不管本项目当前是否出现某形态,采纳新进数据可能落在 任一形态中);行集合与数值仍按决策 196(本项目快照∪现算,算不出归零)——大骨架管结构, 不管行、不供值。 存储:永久存 history.db(lme_skel_file 件级 / lme_skel_group 组级);不随会话清理。 v1 只报不改:体检提示本件与组代表的缺槽/缺形态差异,不自动改导出件。 """ import json import os import re import zipfile import xml.etree.ElementTree as ET LME_TAG = 'LabourMaterialsEquipmentsMachinesSummary' KID_TAG = 'LabourMaterialsEquipmentsMachinesElement' def suffix_of(name): """文件名 → 规范后缀 cos|cos4;其余格式(SWT/SWZ/xlsx…)返回 None——骨架库只收 cos 族。""" m = re.search(r'\.(cos4?)$', os.path.basename(name or ''), re.I) return m.group(1).lower() if m else None def _time_now(): import time return time.strftime('%Y-%m-%d %H:%M:%S') def extract_shapes(path): """解包扫 LME 块 → {sig, suffix, shapes:[形态...], n_lme}。 形态 = {self_close, m_fields:[...], k_fields:[...], count}。 非 zip / 无 LME 块 / 解析失败 → None(合法:空块件不入组,决策 197 实测组3)。""" suf = suffix_of(os.path.basename(path)) if not suf or not os.path.exists(path): return None m_all, shapes, n = set(), {}, 0 try: with zipfile.ZipFile(path) as z: for nm in z.namelist(): if not nm.lower().endswith('.xml'): continue try: raw = z.read(nm) except Exception: continue if LME_TAG.encode() not in raw: continue try: root = ET.fromstring(raw) except Exception: continue for m in root.iter(LME_TAG): n += 1 mf = set(m.attrib.keys()) m_all |= mf kids = m.findall(KID_TAG) kf = sorted(frozenset().union(*[set(k.attrib) for k in kids])) if kids else [] key = json.dumps([not kids, sorted(mf), kf]) shapes[key] = shapes.get(key, 0) + 1 except Exception: return None if n == 0: return None sig = suf + '|' + ','.join(sorted(m_all)) return {'sig': sig, 'suffix': suf, 'n_lme': n, 'shapes': [{'self_close': bool(json.loads(k)[0]), 'm_fields': json.loads(k)[1], 'k_fields': json.loads(k)[2], 'count': v} for k, v in shapes.items()]} def ensure_tables(con): """建表(IF NOT EXISTS,schema.sql 同款)+轻量补列。history.db 连接。""" con.execute("""CREATE TABLE IF NOT EXISTS lme_skel_file( sha256 TEXT PRIMARY KEY, suffix TEXT, sig TEXT, shapes TEXT, n_lme INTEGER, original_name TEXT, extracted_at TEXT)""") cols = {r[1] for r in con.execute("PRAGMA table_info(lme_skel_file)")} if 'original_name' not in cols: con.execute("ALTER TABLE lme_skel_file ADD COLUMN original_name TEXT") con.execute("""CREATE TABLE IF NOT EXISTS lme_skel_group( sig TEXT PRIMARY KEY, suffix TEXT, m_fields TEXT, rep_sha TEXT, rep_shapes TEXT, rep_nshapes INTEGER, files TEXT, n_files INTEGER, updated_at TEXT)""") con.commit() def extract_and_record(con, sha, path, name=None): """抽取单件并写 lme_skel_file;失败/无块返回 None(不挡调用方)。⚠️ con=history.db 连接。""" info = extract_shapes(path) if info is None: return None con.execute("""INSERT INTO lme_skel_file(sha256,suffix,sig,shapes,n_lme,original_name,extracted_at) VALUES(?,?,?,?,?,?,?) ON CONFLICT(sha256) DO UPDATE SET suffix=excluded.suffix, sig=excluded.sig, shapes=excluded.shapes, n_lme=excluded.n_lme, original_name=COALESCE(excluded.original_name, lme_skel_file.original_name), extracted_at=excluded.extracted_at""", (sha, info['suffix'], info['sig'], json.dumps(info['shapes'], ensure_ascii=False), info['n_lme'], name or os.path.basename(path), _time_now())) con.commit() return info def rebuild_groups(con): """从 lme_skel_file 全量重建 lme_skel_group。 代表 = 形态种类最多的件;平手取 extracted_at 最新(主人可后续指定,当前无改代表入口)。""" rows = con.execute("""SELECT sha256, sig, suffix, shapes, extracted_at FROM lme_skel_file WHERE sig IS NOT NULL""").fetchall() groups = {} for sha, sig, suf, shapes, at in rows: try: sh = json.loads(shapes or '[]') except Exception: sh = [] groups.setdefault(sig, []).append((sha, suf, sh, at or '')) for sig, files in groups.items(): # 形态种类多者优先;平手时间新者优先 files.sort(key=lambda t: (len(t[2]), t[3]), reverse=True) rep = files[0] con.execute("""INSERT INTO lme_skel_group(sig,suffix,m_fields,rep_sha,rep_shapes,rep_nshapes, files,n_files,updated_at) VALUES(?,?,?,?,?,?,?,?,?) ON CONFLICT(sig) DO UPDATE SET suffix=excluded.suffix, m_fields=excluded.m_fields, rep_sha=excluded.rep_sha, rep_shapes=excluded.rep_shapes, rep_nshapes=excluded.rep_nshapes, files=excluded.files, n_files=excluded.n_files, updated_at=excluded.updated_at""", (sig, rep[1], sig.split('|', 1)[1], rep[0], json.dumps(rep[2], ensure_ascii=False), len(rep[2]), json.dumps([f[0] for f in files]), len(files), _time_now())) con.commit() return len(groups) def backfill_attachments(con, src_dir): """历史回填:扫 source_files 目录全部 cos 族件(文件名=sha_原名;无 sha 前缀的样本件按 内容算 sha)。attachments 表只覆盖走过上传入口的件,目录直扫才收得全。 只读原件、只写骨架两表。返回 (n_file, n_group)。""" ensure_tables(con) import hashlib n = 0 seen = set() for fn in os.listdir(src_dir): suf = suffix_of(fn) if suf is None: continue m = re.match(r'^([0-9a-fA-F]{64})_', fn) if m: sha = m.group(1).lower() else: with open(os.path.join(src_dir, fn), 'rb') as f: sha = hashlib.sha256(f.read()).hexdigest() if sha in seen: continue # 同哈希同名对只抽一次 seen.add(sha) pretty = fn.split('_', 1)[1] if m else fn # 剥 sha 前缀,存原名 info = extract_and_record(con, sha, os.path.join(src_dir, fn), name=pretty) if info is not None: n += 1 return n, rebuild_groups(con) def diff_vs_rep(shapes, rep_shapes): """本件形态清单 vs 组代表差异(v1 体检只报):缺形态/多形态/缺字段/多字段。""" def key(sh): return {(bool(s['self_close']), tuple(s['m_fields']), tuple(s['k_fields'])) for s in sh or []} def mfs(sh): out = set() for s in sh or []: out |= set(s.get('m_fields') or []) out |= set(s.get('k_fields') or []) # 子级槽位(如 cos4 的 Express)也算字段差异 return out mine, rep = key(shapes), key(rep_shapes) mf, rfm = mfs(shapes), mfs(rep_shapes) return {'missing_shapes': [{'self_close': k[0], 'm_fields': list(k[1]), 'k_fields': list(k[2])} for k in sorted(rep - mine)], 'extra_shapes': [{'self_close': k[0], 'm_fields': list(k[1]), 'k_fields': list(k[2])} for k in sorted(mine - rep)], 'missing_fields': sorted(rfm - mf), 'extra_fields': sorted(mf - rfm)} def hit_for_sha(con, sha): """件 sha → (本件签名记录, 命中组记录) 或 (None, None)。纯 SQL,不解包。""" f = con.execute("SELECT sha256, suffix, sig, shapes, n_lme FROM lme_skel_file WHERE sha256=?", (sha,)).fetchone() if f is None or not f[2]: return None, None g = con.execute("""SELECT sig, suffix, m_fields, rep_sha, rep_shapes, rep_nshapes, files, n_files FROM lme_skel_group WHERE sig=?""", (f[2],)).fetchone() return f, g