# -*- coding: utf-8 -*- """格式无关骨架引擎(决策 262,2026-11-03 主人定「引擎写活了,后期还有很多后缀」)。 口径(主人逐条定 + 实件勘察结论): · **后缀不参与拦截**:能不能用由**内容**判定——zip 内 XML(cos/cos4 型)/ 裸 XML(swt/swz 型)。 后期新后缀(st/uuy…)只要是这两种之一,零代码接入。 · **唯一结构位** = (父路径, 标签, 列集):三者相同即同一结构位,只留 1 个样板;值全清空(卡槽)。 · **子节点取并集**:同一结构位的子节点按身份合并(递归);自嵌套按实件最大深度保留有限层。 · **区域/自增块/自增行**不是三种标签,而是同一套结构位的三种出现形态: 区域=全实件恒 1 次;自增块=容器重复;自增行=自闭合行重复。 · **次数不进骨架**:骨架只给结构+列序,重复次数由数据条数决定(0 条不输出)。 实测(2026-11-03):cos4 9507→131、cos 25581→73、swt 463→38、swz 185→37 个唯一结构位。 """ import copy import io import zipfile from xml.etree import ElementTree as ET # --------------------------------------------------------------------------- # 一、格式族判定(按内容,不按后缀) # --------------------------------------------------------------------------- FAMILY_ZIP = "zip" # zip 容器 + 若干 XML 成员(主文件 + 单位工程成员) FAMILY_RAW = "raw" # 裸 XML 单文件(单位工程内嵌) def family_of(blob): """字节 → FAMILY_ZIP / FAMILY_RAW / None(加密壳、二进制、坏件一律 None)。""" if not blob: return None if blob[:2] == b"PK": try: with zipfile.ZipFile(io.BytesIO(blob)) as z: for nm in z.namelist(): if nm.lower().endswith(".xml"): try: ET.fromstring(z.read(nm)) return FAMILY_ZIP except Exception: continue except Exception: return None return None head = blob[:6].lstrip() if head[:5].lower().startswith(b"]*encoding="([^"]+)"', raw[:300]) enc = m.group(1).decode("ascii", "ignore") if m else "utf-8" for e in (enc, "utf-8", "gb18030"): try: raw.decode(e) return raw, e except Exception: continue return raw, "utf-8" def parse_root(raw): """字节 → (根元素, 声明文本)。保留注释节点(原文件有才保留,引擎不造)。""" import re blob, _enc = _decode_bytes(raw) text = blob.decode(_enc, errors="replace") m = re.match(r"\s*<\?xml[^>]*\?>", text) decl = m.group(0) if m else '' body = text[m.end():] if m else text parser = ET.XMLParser(target=ET.TreeBuilder(insert_comments=True)) return ET.fromstring(body, parser=parser), decl # --------------------------------------------------------------------------- # 二、唯一结构收敛(本次核心) # --------------------------------------------------------------------------- def _key(el): return (el.tag, tuple(sorted(el.attrib.keys()))) # 骨架只给格式(列集 + 每层是否自增);**所有值来自数据库**,骨架一个值都不带。 # 主人 2026-11-03 定:「骨架只管导出格式及是不是自增行」——单价行/管理费/费用构成 # 这些值全部随导入进库(s_bills/s_norms 的 x_side),导出时有几行出几行。 _DATA_TAGS = set() _ZERO_RULES = {} def _copy_fixed(c): """(保留占位)固定结构节点深拷贝。""" return copy.deepcopy(c) def collapse_into(node, el): """把源元素 el 的子结构并入样板 node:同身份合并、子节点递归取并集、值清空。""" seen = {} for k in node: if isinstance(k.tag, str): seen[_key(k)] = k for c in el: if not isinstance(c.tag, str): # 注释:原样保留一次 if not any(isinstance(k.tag, type(c.tag)) and k.text == c.text for k in node): node.append(c) continue key = _key(c) sub = seen.get(key) if sub is None: sub = ET.SubElement(node, c.tag) for a in c.attrib: # 列序=首次出现序,值=空卡槽 sub.set(a, "") seen[key] = sub collapse_into(sub, c) return node def collapse(root): """整树 → 唯一结构位树(每个结构位只出现一次,值全空)。""" out = ET.Element(root.tag) for a in root.attrib: out.set(a, "") collapse_into(out, root) return out def paths_of(root): """→ {路径字符串: 出现次数};路径=根到该元素的标签链('A/B/C')。""" out = {} stack = [(root, root.tag)] while stack: el, p = stack.pop() out[p] = out.get(p, 0) + 1 for c in el: if isinstance(c.tag, str): stack.append((c, p + "/" + c.tag)) return out # --------------------------------------------------------------------------- # 三、结构旁注(sidecar):哪些层是清单/定额/工料机/单位工程 # 判定只看结构(重复次数+嵌套关系),不看标签名——新后缀零配置。 # --------------------------------------------------------------------------- def _attrs_by_path(roots): """→ {路径: 列集}(只取出现过的属性名,不看值)。""" out = {} for r in roots: stack = [(r, r.tag)] while stack: el, p = stack.pop() s = out.setdefault(p, set()) s.update(el.attrib.keys()) for c in el: if isinstance(c.tag, str): stack.append((c, p + "/" + c.tag)) return out def derive_meta(roots, unit_tag=None): """多份实件根 → {'v':1,'paths':{path:count},'roles':{...}}。 角色判定只用**结构 + 属性名**(不看标签名、不看后缀),顺序: ①工料机行=重复的自闭合叶行里,属性同时有"数量"和"编号/代码"、次数最多者; ②定额=工料机行的父节点(父是壳也照取——壳在清单层再跳); ③清单=从定额往上最近的非壳容器(壳=只有一个子标签的容器); ④分部=清单上方能重复的容器;⑤单位=根标签里出现最多的那个(zip 族=单位成员根)。 认结构(清单→定额→工料机三层嵌套)的格式适用;数据模型不同的族(如 SWT 工料机是 独立表、不挂在定额下)只认得出部分角色,导出端会回退旧引擎——这是适配器边界。""" counts = {} for r in roots: for p, n in paths_of(r).items(): counts[p] = counts.get(p, 0) + n attrs = _attrs_by_path(roots) parent = {p: p.rsplit("/", 1)[0] for p in counts if "/" in p} has_kid = {p: False for p in counts} for p in counts: if p in parent: has_kid[parent[p]] = True def kids(p): return [q for q in counts if parent.get(q) == p] def is_shell(p): return len({q.rsplit("/", 1)[-1] for q in kids(p)}) == 1 colset = lambda p: {a.lower() for a in attrs.get(p, ())} def is_norm_like(p): """定额样:有 名称/单位/数量/单价(Price 或 Rate 精确名,不用 NoTaxPrice 这类)。""" c = colset(p) return {"name", "unit", "quantity"} <= c and (("price" in c) or ("rate" in c)) # ① 工料机行="定额样"节点的子行(数量+编号),次数最大者;避免把汇总表当定额 rows = [p for p in counts if counts[p] >= 2 and not has_kid[p] and "quantity" in colset(p) and ({"number", "code"} & colset(p)) and is_norm_like(parent.get(p, ""))] lme = max(rows, key=lambda p: counts[p]) if rows else None # ② 定额 = 工料机行父节点 norm = parent.get(lme) if lme else None # ③ 清单 = 从定额往上最近的非壳容器 bill = None p = parent.get(norm) if norm else None while p: if has_kid[p] and not is_shell(p): bill = p break p = parent.get(p) # ④ 分部 = 清单上方能重复的容器 div = None p = parent.get(bill) if bill else None while p: if counts.get(p, 0) >= 2 and not is_shell(p): div = p break p = parent.get(p) # ⑤ 单位 = 调用方指定的单位根(zip 族=单位成员根);否则取出现最多的根标签 from collections import Counter roots_cnt = Counter(r.tag for r in roots) unit = unit_tag or (roots_cnt.most_common(1)[0][0] if roots_cnt else None) # 单位级工料机汇总行:单位之下、不在清单/定额链上、重复的自闭合叶行 lme_sum = None if unit: sub = [q for q in counts if q.startswith(unit + "/") and counts[q] >= 2 and not has_kid[q] and not (norm and q.startswith(norm))] lme_sum = max(sub, key=lambda q: counts[q]) if sub else None return {"v": 1, "paths": counts, "roles": {"unit": unit, "bill": bill, "div": div, "norm": norm, "lme": lme, "lme_sum": lme_sum}} # --------------------------------------------------------------------------- # 四、分层列集指纹与匹配度(字段越像分越高 + 区域越像分越高) # --------------------------------------------------------------------------- def layer_cols(roots): """多份实件根 → {'v':2,'p':{路径:[列名…]}}(每层列集并集,首见列序)。""" out = {} for r in roots: stack = [(r, r.tag)] while stack: el, p = stack.pop() cols = out.setdefault(p, []) for a in el.attrib: if a not in cols: cols.append(a) for c in el: if isinstance(c.tag, str): stack.append((c, p + "/" + c.tag)) return {"v": 2, "p": out} def _finger_paths(fp): """兼容新旧两种指纹 → {path: set(cols)}。旧= {tag:[...]};新= {'v':2,'p':{path:[...]}}。""" if not isinstance(fp, dict): return {} if fp.get("v") == 2 and isinstance(fp.get("p"), dict): return {k: set(v) for k, v in fp["p"].items()} return {k: set(v) for k, v in fp.items() if isinstance(v, (list, tuple, set))} def _root_path(paths): for p in paths: if "/" not in p: return p, paths[p] return None, set() def match_score(src_fp, skel_fp): """0~100:字段匹配(同层列集重合,根层权重最高)+ 区域匹配(骨架的结构区域在原件里有没有)。 根标签不同=不同格式族,直接压低到 10 分以下。""" src = _finger_paths(src_fp) skel = _finger_paths(skel_fp) if not src or not skel: return 0.0 sroot, scols = _root_path(src) kroot, kcols = _root_path(skel) if sroot != kroot: return 10.0 * (len(scols & kcols) / max(1, len(scols | kcols))) # 字段:逐层 Jaccard,根层×3、二三层×2、其余×1 num = den = 0.0 for p, cols in skel.items(): if p not in src: continue depth = p.count("/") w = 3.0 if depth == 0 else (2.0 if depth <= 2 else 1.0) num += w * len(cols & src[p]) / max(1, len(cols | src[p])) den += w field = (num / den * 100.0) if den else 0.0 # 区域:骨架里出现过的结构位,原件里覆盖多少(只看骨架,不看原件多出来的) cover = sum(1 for p in skel if p in src) / max(1, len(skel)) return round(field * 0.65 + cover * 100.0 * 0.35, 2) # --------------------------------------------------------------------------- # 五、从实件提炼空骨架(主驱动:family 判定,不看后缀) # --------------------------------------------------------------------------- def _members(blob): """→ [(成员名, 字节)];裸 XML 时 → [('(single)', blob)]。""" if family_of(blob) == FAMILY_ZIP: with zipfile.ZipFile(io.BytesIO(blob)) as z: return [(nm, z.read(nm)) for nm in z.namelist() if nm.lower().endswith(".xml")] return [("(single)", blob)] def split_roots(blob): """→ (主根列表, 单位根列表, family)。zip:单位根=多数成员根标签;raw:整件即主根。 单位工程判定不靠标签名,靠"同一个根标签在多个成员里重复出现"。""" fam = family_of(blob) if fam is None: return [], [], None members = _members(blob) roots = [] for nm, raw in members: try: r, _d = parse_root(raw) except Exception: continue roots.append((nm, r)) if fam == FAMILY_RAW: return [r for _n, r in roots], [], fam # zip:根标签计数,出现 ≥2 次的当单位成员 from collections import Counter cnt = Counter(r.tag for _n, r in roots) unit_tag = None for t, n in cnt.most_common(): if n >= 2: unit_tag = t break if unit_tag is None and len(roots) > 1: unit_tag = cnt.most_common()[-1][0] units = [r for _n, r in roots if r.tag == unit_tag] mains = [r for _n, r in roots if r.tag != unit_tag] if not mains: mains = [roots[0][1]] units = [r for _n, r in roots[1:]] return mains, units, fam def build_blank(blob, ind_unit=" "): """实件 → (空骨架单 XML 文本, meta)。meta 给导出用(角色路径)。 zip 族:主文件骨架 + 首条单位索引行内嵌单位骨架(连接展示); raw 族:整件收敛。两种家族同一个收敛器,零后缀配置。""" mains, units, fam = split_roots(blob) if fam is None or not mains: return None, None main = collapse(mains[0]) if not units: roots_for_meta = mains text = _serialize(main, ind_unit) return text, derive_meta(roots_for_meta) unit_best = max(units, key=lambda r: len(list(r.iter()))) unit = collapse(unit_best) # 2026-11-04 决策267:单位骨架取**全成员并集**——只取一个成员会丢别的成员才有的 # 层/列(实测:本项目分部 13 列、某个成员只有 7 列,导致导出丢列)。值仍为空。 for _u in units: if _u is unit_best: continue try: collapse_into(unit, collapse(_u)) except Exception: continue # 连接:主骨架里第一条带 FileName 的索引行 → 换成单位骨架 placed = False for par in main.iter(): for k in list(par): if not isinstance(k.tag, str): continue if "FileName" in k.attrib: idx = list(par).index(k) par.remove(k) par.insert(idx, unit) placed = True break if placed: break if not placed: # 退化样例(Project.xml 没有单位索引行):单位骨架直接挂主根,导出端仍能按它建成员 main.append(unit) text = _serialize(main, ind_unit) meta = derive_meta(mains + units, unit_tag=unit_best.tag) # 决策 264:记下被替换掉的**索引行**(导出时按它复制成 N 行),否则项目索引无法还原 meta["index_row"] = {"tag": None, "attrs": []} for par in collapse(mains[0]).iter(): for k in par: if isinstance(k.tag, str) and "FileName" in k.attrib: meta["index_row"] = {"tag": k.tag, "attrs": list(k.attrib.keys())} break else: continue break return text, meta def _ind_unit(root): """缩进单位:优先从实件文本锚定(4 空格常见);此处按层给 4 空格, 真实缩进由 refine_blank 传入的件锚定(见 classic_skeleton._blank_ind_unit)。""" return " " def serialize(el, depth=0, ind=" ", keep_values=False, first=True, note_fn=None): """唯一结构位树 → 文本行(一行一层、叶自闭合、无空行)。 属性值按 XML 规则转义(数据里的 & < > " 会原样出现,不转义整件就坏)。 note_fn(el)→字符串:在开标签后追加 XML 注释(骨架库「空骨架+导出规则标注」用)。""" pad = "" if first else "\n" + ind * depth if keep_values: from xml.sax.saxutils import escape # 决策 263 补记(2026-11-04 主人报「项目特征导出后不点开换行乱」): # 属性值里的字面 LF 在 XML 解析时按规范归一成空格——必须写 实体才能保住换行 # (老引擎外科手术保留原 实体无此问题;v2 全量序列化必须显式转) attrs = "".join(' %s="%s"' % (k, escape(str(v), {'"': """}).replace("\n", " ")) for k, v in el.attrib.items()) else: attrs = "".join(' %s=""' % k for k, _ in el.attrib.items()) kids = [k for k in el if isinstance(k.tag, str)] note = note_fn(el) if note_fn else "" note = ("" % str(note).replace("--", "-")) if note else "" out = [pad + "<" + el.tag + attrs] if not kids: out[0] += " />" + note return "".join(out) out[0] += ">" + note for k in kids: out.append(serialize(k, depth + 1, ind, keep_values, first=False, note_fn=note_fn)) out.append("\n" + ind * depth + "") return "".join(out) def _serialize(root, ind=" ", keep_values=False): decl = '' return decl + "\n" + serialize(root, 0, ind, keep_values) + "\n"