feat(export): 决策263-266 单一骨架导出通路/数据全量入库/空骨架规则标注/导入按内容判族

- 决策 263:定额单价专题(三同合并全字段统一、原价三级链、LME Summary 26 属性收口、x_flags 采集、e2e 回归)
- 决策 264 补记五:原格式导出只保留骨架回灌一条通路;删除 export_cos.export_zip 旧引擎;新增 skeleton_engine(内容判族/唯一结构位/结构旁注/路径指纹);单位级/项目级非数据层 x_attr/x_side 采集与回灌;导出件成员名改 GBK 原始字节(_GbkZipInfo);后台「导出设置」导出空骨架(标注)
- 决策 265:导入按内容判族(zip 内含 ConstructProject→SWT 族,否则 COS 族;裸 XML 同),扩展名不参与拦截;api_scan 取消 EXT_OK 过滤
- 决策 266:结构位统一「自增区域/自增块/自增行」,取消「固定」;min_count(区域1/块行0),导出条数=max;区域数据0条保底1空壳;LME 汇总两形态(带组成闭合块/普通自闭合行)按行硬分派
- 前序未提交:HTML 导出整体移除(export_html.py 删除)、Excel 导出加序号列并移除说明页、.yhy 导入(import_yhy.py)
- 测试:367 passed / 3 skipped;新增 test_topic_price/test_yhy_import/test_import_suffix 等
This commit is contained in:
lianjianwei2024
2026-11-03 23:39:46 +08:00
parent 5470286f66
commit 78e58a40c7
40 changed files with 2700 additions and 1373 deletions

View File

@@ -27,14 +27,18 @@ import tempfile
import zipfile
import xml.etree.ElementTree as ET
# cos 族 = 易达两代格式,同一条代码路径(决策 105);其余后缀注册即收
import skeleton_engine as _se # 决策 262:格式无关骨架引擎(族判定/收敛/旁注/匹配)
# 决策 262(2026-11-03 主人定「引擎写活了,后期还有很多后缀」):
# **后缀不再参与拦截**——能不能用由内容判定(zip 内 XML / 裸 XML),见 skeleton_engine。
# 这里只保留"从文件名取后缀"的能力;当前已实件验过的四种=cos/cos4/swt/swz。
_COS_RE = re.compile(r"\.(cos4?)$", re.I)
def suffix_of(name):
"""文件名 → 规范后缀 cos|cos4;本次未注册的格式返回 None(不收不挡)。"""
m = _COS_RE.search(os.path.basename(name or ""))
return m.group(1).lower() if m else None
"""文件名 → 小写后缀(任意后缀都返回;能不能用由 skeleton_engine.family_of 按内容判)。"""
ext = os.path.splitext(os.path.basename(name or ""))[1]
return ext[1:].lower() if ext else None
def _now():
@@ -57,6 +61,10 @@ def _ensure_table(con):
# 决策 260 补记三/四:该骨架的**空骨架**(单 XML 空数据模板字节)——由本件
# 自动总结(值全空、列集按样板自增行规整),「每件一个小骨架」并存
con.execute("ALTER TABLE classic_skel ADD COLUMN x_blank BLOB")
if "x_meta" not in _cols:
# 决策 262:结构旁注(角色路径 unit/bill/norm/lme + 各路径出现次数)——
# 骨架文件只放结构,重复次数与数据源这类"文件里没有的语义"单独存这里
con.execute("ALTER TABLE classic_skel ADD COLUMN x_meta TEXT")
if "x_layer_cols" not in _cols:
# 决策 260 补记八(2026-11-03 主人定「根据第一行的列选骨架」):该骨架的
# **分层列集指纹** JSON——{标签: 列集并集},入库时预计算;导出/打开项目时
@@ -75,88 +83,36 @@ _MATCH_LAYERS = ("ConstructionProject", "UnitWorks", "WorkElement", "Norm",
def layer_cols_of(z_or_blob):
"""一份实件(zip 或字节)→ {标签: 该层列集并集}(全成员汇总)。"""
"""一份实件 → **分层列集指纹**(决策 262:路径键、格式无关、不含次数)。
返回 {'v':2,'p':{路径:[列名…]}};认不出格式(加密壳/坏件)→ {}。
旧指纹(标签键)由 match_score 兼容读,pick_frame 见非 v2 会重算回写。"""
try:
z = z_or_blob if isinstance(z_or_blob, zipfile.ZipFile) \
else zipfile.ZipFile(io.BytesIO(z_or_blob))
blob = z_or_blob if isinstance(z_or_blob, (bytes, bytearray)) \
else (z_or_blob.read() if hasattr(z_or_blob, "read") else None)
except Exception:
return {}
if not blob:
return {}
try:
mains, units, fam = _se.split_roots(blob)
except Exception:
return {}
if fam is None:
return {}
try:
return _se.layer_cols(mains + units)
except Exception:
return {}
out = {}
for nm in z.namelist():
if not nm.lower().endswith(".xml"):
continue
try:
root = ET.fromstring(z.read(nm))
except Exception:
continue
for el in root.iter():
if el.tag is ET.Comment:
continue
if el.tag not in _MATCH_LAYERS:
continue
s = out.setdefault(el.tag, set())
s.update(el.attrib.keys())
return out
def match_score(src_cols, skel_cols):
"""分层匹配度(0~100):第一层(根)权重最高,逐层下探;每层=列集 Jaccard×100。
根列集完全一致→直接满分命中(主人定「第一行相同才下探」)。"""
if not skel_cols:
"""匹配度 0~100(决策 262,主人定「字段越匹配分越高、区域越匹配分越高」):
字段=同层列集重合(根层权重最高);区域=骨架结构位在原件里的覆盖率;
根标签不同=不同格式族,直接压到 10 分以下。"""
try:
return _se.match_score(src_cols, skel_cols)
except Exception:
return 0.0
root_t = _MATCH_LAYERS[0]
sy = src_cols.get(root_t) or set()
sk = skel_cols.get(root_t) or set()
if sy and sk:
if sy == sk:
base = 100.0 # 第一行完全一致:满分命中
else:
inter = len(sy & sk)
base = inter / max(1, len(sy | sk)) * 60.0 # 根不一致:上限 60
else:
base = 30.0 # 某方缺根层:低分
# 下探层:平均 Jaccard
rest = [t for t in _MATCH_LAYERS[1:] if (src_cols.get(t) or skel_cols.get(t))]
if rest:
acc = 0.0
for t in rest:
a = src_cols.get(t) or set()
b = skel_cols.get(t) or set()
if a or b:
acc += len(a & b) / max(1, len(a | b))
base = base * 0.7 + (acc / len(rest)) * 100.0 * 0.3
return round(base, 2)
# ---------------------------------------------------------------------------
# 空骨架提炼引擎(决策 260 补记三/四,2026-11-02 主人定「每个骨架实件各自总结出
# 一个小骨架(空数据模板);引擎做成活的——后期很多不同后缀文件」)
# 流程(共用):骨架实件 → 按 SKEL_RULES[后缀] 提炼 → 单 XML 空数据模板(值全空)
# → 与主人样板对比无误 → 数据回灌。新后缀接入=加一份 SKEL_RULES 配置,引擎零改动。
# 骨架正定义见术语表「导出骨架」:标签=卡槽、属性=列(值留空)、数据按需自动增行、
# 自闭合行=自增行(数据行样板),排序列=模板节点顺序,不提供任何数值。
# ---------------------------------------------------------------------------
SKEL_RULES = {
"cos4": {
# 项目成员识别:body 含任一标识标签
"proj_ident": ("<SectionalWorks", "<ConstructionProject"),
# 单位成员根标签
"unit_root": "UnitWorks",
# 引用行样例保留数(连接时内嵌的单位子树数)
"keep_refs": 1,
},
# cos 与 cos4 同构(决策 105:易达两代格式同一条代码路径)
"cos": {
"proj_ident": ("<SectionalWorks", "<ConstructionProject"),
"unit_root": "UnitWorks",
"keep_refs": 1,
},
# "swt": {...} # 后期注册:SWT 锚点集与规则(决策 122 单 Rate 口径)
# "swz": {...}
}
_BLANK_KEEP_REFS_DEFAULT = 1
def _blank_parse(xml_text):
@@ -321,72 +277,42 @@ def _blank_ind_unit(xml_text):
def refine_blank(con, blob, suffix="cos4"):
"""骨架实件(zip 字节)→ 该件的**空数据模板**(单 XML 字节,值全空、列集按自增行规整)。
"""骨架实件(zip 或裸 XML 字节)→ 该件的**空数据模板**(单 XML 字节,值全空)。
规律(决策 260,主人样板《骨架结构-空数据模板.xml》同款):实件 zip = Project.xml +
N 个单位成员;提炼 = ①值全清空(声明按骨架豁免;注释原文件有才保留,引擎不造);
②Project.xml 引用行只留样例;③单位成员取最全 1 个;④样例引用行位置内嵌单位成员
完整子树(2 个 xml 连接展示);⑤**自增行规整**——同类行列集统一到样板自增行列序。
suffix 走 SKEL_RULES——新后缀加配置即接入(活引擎)。con 供样板基准表(skel_ref_件)。"""
rule = SKEL_RULES.get((suffix or "").lower())
if not rule:
return None
src = zipfile.ZipFile(io.BytesIO(blob))
proj_nm = None
unit_best = None # (元素数, 内部名, xml文本)
texts = {}
for nm in src.namelist():
if not nm.lower().endswith(".xml"):
continue
txt, enc = _decode_pair(src.read(nm))
texts[nm] = (txt, enc)
body = re.sub(r"^.*?\?>", "", txt, count=1, flags=re.S).lstrip()
if any(k in body for k in rule["proj_ident"]):
proj_nm = nm
elif body.startswith("<" + rule["unit_root"]):
n = len(re.findall(r"<[A-Za-z_]", txt))
if unit_best is None or n > unit_best[0]:
unit_best = (n, nm, txt)
if not proj_nm or unit_best is None:
return None
base, tag_base = _blank_ref_base(con, suffix)
# Project.xml:清值+规整+引用行只留样例(ET 树上做;引用行嵌在 SectionalWorks
# 等容器内——递归收集 (父节点, 引用行) 对,从各自父节点删多余、留首条样例)
pr, decl = _blank_parse(texts[proj_nm][0])
_blank_normalize(pr, base, tag_base, "", is_root=True)
keep = rule.get("keep_refs", _BLANK_KEEP_REFS_DEFAULT)
uroot = rule["unit_root"]
pairs = []
for par in pr.iter():
for k in list(par):
if k.tag == uroot:
pairs.append((par, k))
for par, k in pairs[keep:]:
par.remove(k)
# 单位成员:清值+规整(取最全 1 个的文本重新解析)
ur, _uenc = _blank_parse(unit_best[2])
# 缩进单位从实件锚定(主人 2026-11-03 定「注意换行对齐」):取成员里最内层
# 子标签相对父标签的缩进步进(易达 4 空格;SWT 等其他后缀按各自实件自动适配)
ind_unit = _blank_ind_unit(unit_best[2])
_blank_normalize(ur, base, tag_base, "")
# 连接:首条样例引用行的位置 → 内嵌单位成员完整子树(引用行属性列集=成员根列集,
# 同源同构;其余样例引用行保留)
if not pairs:
return None
ref_par, ref_k = pairs[0]
pos = list(ref_par).index(ref_k)
ref_par.remove(ref_k)
ref_par.insert(pos, ur)
# 序列化(缩进按实件锚定、LF、无自造注释;声明按骨架原样,编码回写按声明)
out = [decl]
_blank_ser(pr, 0, out, is_root=True, ind_unit=ind_unit)
enc_m = re.search(r'encoding="([^"]*)"', decl)
enc = enc_m.group(1) if enc_m else "utf-8"
text = "\n".join(out) + "\n"
决策 262(2026-11-03 主人定「引擎写活了,后期还有很多后缀」)起改由
skeleton_engine 统一提炼——**不看后缀,按内容判族**:
· zip 内 XML(cos/cos4 型):主文件骨架 + 首条单位索引行内嵌单位骨架(连接展示);
· 裸 XML(swt/swz 型):整件收敛。
收敛口径=唯一结构位(父路径+标签+列集)只留一个样板、子节点取并集、值全清空;
缩进按实件锚定(主人 2026-11-03 定「注意换行对齐」)。con 保留给旧样板基准表用。"""
blank, _meta = refine_blank_ex(blob, suffix)
return blank
def refine_blank_ex(blob, suffix="cos4"):
"""→ (空骨架字节, 结构旁注 meta)。meta 随骨架入库(x_meta),导出端按它定位层。
认不出格式族(加密壳/二进制)→ (None, None)。"""
try:
return text.encode(enc)
ind = " "
text0 = None
try:
members = _se._members(blob)
if members:
raw0, _e0 = _decode_pair(members[-1][1])
text0 = raw0
except Exception:
text0 = None
if text0:
ind = _blank_ind_unit(text0)
text, meta = _se.build_blank(blob, ind_unit=ind)
except Exception:
return text.encode("utf-8")
return None, None
if not text:
return None, None
try:
return text.encode("utf-8"), meta
except Exception:
return None, None
def blank_from_frame(blob):
@@ -450,16 +376,16 @@ def extract(path):
return None
shapes, n_nodes = set(), 0
try:
with zipfile.ZipFile(path) as z:
members = 0
for nm in z.namelist():
if not nm.lower().endswith(".xml"):
continue
s, n = _shapes_of_bytes(z.read(nm))
if n:
members += 1
shapes |= s
n_nodes += n
blob = open(path, "rb").read()
if _se.family_of(blob) is None: # 决策 262:内容判族,后缀不拦截
return None
members = 0
for _nm, raw in _se._members(blob):
s, n = _shapes_of_bytes(raw)
if n:
members += 1
shapes |= s
n_nodes += n
except Exception:
return None
if not members or not shapes:
@@ -530,10 +456,12 @@ def seed_frame(con, path, name):
with open(path, "rb") as f:
blob = f.read()
_blank = None
_meta = None
try:
_blank = refine_blank(con, blob, info["suffix"]) # 决策 260 补记四:入库即总结该件空骨架(单 XML 空数据模板)
# 决策 262:入库即提炼空骨架 + 结构旁注(meta 供导出端定位层,不写进骨架文件)
_blank, _meta = refine_blank_ex(blob, info["suffix"])
except Exception:
_blank = None
_blank, _meta = None, None
# 决策 260 补记八:入库即预计算**分层列集指纹**(导出/打开项目时算匹配度用)
_layer_cols = {}
try:
@@ -541,19 +469,21 @@ def seed_frame(con, path, name):
except Exception:
_layer_cols = {}
con.execute("""INSERT INTO classic_skel(sig,suffix,rep_sha,original_name,
n_shapes,n_nodes,blob,extracted_at,is_frame,x_blank,x_layer_cols)
VALUES(?,?,?,?,?,?,?,?,1,?,?)
n_shapes,n_nodes,blob,extracted_at,is_frame,x_blank,x_layer_cols,x_meta)
VALUES(?,?,?,?,?,?,?,?,1,?,?,?)
ON CONFLICT(sig) DO UPDATE SET rep_sha=excluded.rep_sha,
original_name=excluded.original_name, n_shapes=excluded.n_shapes,
n_nodes=excluded.n_nodes, blob=excluded.blob,
extracted_at=excluded.extracted_at, is_frame=1,
x_blank=COALESCE(excluded.x_blank, x_blank),
x_layer_cols=COALESCE(excluded.x_layer_cols, x_layer_cols)""",
x_layer_cols=COALESCE(excluded.x_layer_cols, x_layer_cols),
x_meta=COALESCE(excluded.x_meta, x_meta)""",
(info["sig"], info["suffix"],
hashlib.sha256(blob).hexdigest(), name,
info["n_shapes"], info["n_nodes"], blob, _now(), _blank,
json.dumps({k: sorted(v) for k, v in _layer_cols.items()},
ensure_ascii=False) if _layer_cols else None))
info["n_shapes"], info["n_nodes"], blob, _now(),
_blank if isinstance(_blank, (bytes, bytearray)) else None,
json.dumps(_layer_cols, ensure_ascii=False) if _layer_cols else None,
json.dumps(_meta, ensure_ascii=False) if _meta else None))
con.commit()
return info["sig"]
@@ -608,8 +538,8 @@ def frame_blob(con, sig):
def frame_blank(con, sig):
"""取一件骨架的**空骨架**(决策 260 补记三「每件一个小骨架」):x_blank 有→直接回;
无(存量件)→ 现场总结并回写(惰性补齐,幂等)。→ (空骨架 XML 字节, original_name)。"""
row = con.execute("SELECT sig, blob, original_name, x_blank, suffix FROM classic_skel WHERE sig=?",
(sig,)).fetchone()
row = con.execute("SELECT sig, blob, original_name, x_blank, suffix, x_meta "
"FROM classic_skel WHERE sig=?", (sig,)).fetchone()
if not row:
return None, None
blank = row["x_blank"]
@@ -621,11 +551,34 @@ def frame_blank(con, sig):
if blank:
con.execute("UPDATE classic_skel SET x_blank=? WHERE sig=?", (blank, sig))
con.commit()
try: # 决策 262:顺带补齐结构旁注(幂等)
if not row["x_meta"]:
_b2, _m2 = refine_blank_ex(row["blob"], row["suffix"])
if _m2:
con.execute("UPDATE classic_skel SET x_meta=? WHERE sig=?",
(json.dumps(_m2, ensure_ascii=False), sig))
con.commit()
except Exception:
pass
if not blank:
return None, row["original_name"]
return bytes(blank), row["original_name"]
def frame_meta(con, sig):
"""取一件骨架的**结构旁注**(决策 262):{v,paths,roles};无→None(可惰性补齐)。"""
try:
row = con.execute("SELECT x_meta FROM classic_skel WHERE sig=?", (sig,)).fetchone()
except Exception:
return None
if not row or not row["x_meta"]:
return None
try:
return json.loads(row["x_meta"])
except Exception:
return None
def seed_pack(con, path):
"""骨架包安装(2026-11-02 主人定两阶段架构:阶段二上市版「后台直接上传骨架包、
租户客户端接收」——本函数是包→库的共用解包口,阶段一后台手动传包同走这里)。
@@ -637,7 +590,7 @@ def seed_pack(con, path):
with zipfile.ZipFile(path) as z:
for info in z.infolist():
nm = info.filename
if not _COS_RE.search(nm):
if not _se.family_of(z.read(info)): # 决策 262:按内容认,不按后缀
continue
try: # zip 成员名常见 GBK 存 KB:cp437 转回
nm2 = nm.encode("cp437").decode("gbk")
@@ -692,18 +645,19 @@ def pick_frame(con, suffix, src_path=None, src_blob=None):
s = None
try:
if f["x_layer_cols"]:
skel_cols = {k: set(v) for k, v in json.loads(f["x_layer_cols"]).items()}
s = match_score(src_cols, skel_cols)
skel_cols = json.loads(f["x_layer_cols"])
# 决策 262:只认新指纹(v2 路径键);旧标签键指纹→按 v2 重算回写
if isinstance(skel_cols, dict) and skel_cols.get("v") == 2:
s = match_score(src_cols, skel_cols)
except Exception:
s = None
if s is None:
# 旧骨架无指纹 → 现场算(并回写)
# 旧骨架/旧指纹 → 现场算(并回写 v2 指纹)
try:
skel_cols = layer_cols_of(f["blob"])
s = match_score(src_cols, skel_cols)
con.execute("UPDATE classic_skel SET x_layer_cols=? WHERE sig=?",
(json.dumps({k: sorted(v) for k, v in skel_cols.items()},
ensure_ascii=False), f["sig"]))
(json.dumps(skel_cols, ensure_ascii=False), f["sig"]))
con.commit()
except Exception:
s = -1.0

View File

@@ -151,6 +151,7 @@ def _price_map(sc, sid):
out = {}
for r in sc.execute("""SELECT id, code, name, spec, unit, kind, qty, ntp, taxrate, taxp,
ntp_org, ntp_expr, taxp_org, taxp_expr, x_flags,
x_org_ntp0, x_org_taxp0,
COALESCE(x_merged_hide,0) AS hid, x_remark
FROM s_lme_proj WHERE session_id=?""", (sid,)):
out[r["code"]] = dict(r)
@@ -324,6 +325,14 @@ def _dyn_rows(sc, sid, uw_id=None):
ntp, rate, taxp = r.get("ntp"), r.get("taxrate"), r.get("taxp")
_pk6 = lambda a, b: (a if a is not None else b)
org4 = tuple(_pk6(r.get(k), p.get(k)) for k in ("ntp_org", "ntp_expr", "taxp_org", "taxp_expr"))
# 定额单价专题(2026-11-03 主人定):原价第③级兜底=第一次外部采纳价(x_org_*0,
# 采纳落价时列空才写);①单位级 → ②项目级 → ③此列;Expr(调价式)无采纳源、不兜底。
_o = list(org4)
if _o[0] is None and p.get("x_org_ntp0") is not None:
_o[0] = p["x_org_ntp0"]
if _o[2] is None and p.get("x_org_taxp0") is not None:
_o[2] = p["x_org_taxp0"]
org4 = tuple(_o)
# s_lme_lib 快照兜底(手工会话没有源文件:单位级/项目级行都没有,组成子行
# 折旧费/检修费等的名称/单位/单价从这里来——2026-10-28 主人实测映射源价全空)
lb = lbm.get(code)

View File

@@ -1046,6 +1046,29 @@ def _lme_apply_price(newtag, px):
for attr in ("NoTaxPrice", "NoTaxPriceExpress", "NoTaxOrgPrice", "TaxRate",
"TaxPrice", "TaxPriceExpress", "TaxOrgPrice"):
_set(attr, px.get(attr))
# 定额单价专题(2026-11-03 主人定「合并=勾选谁按哪一行的字段」):合并统一全列回写——
# Kind + 文字/标志属性(x_flags JSON,决策 259 全采);恒空链键(Remark/PriceSource/
# Delivery/Location/ProducingArea/Supplier/Character)不回写;骨架无该属性=卡槽无 →
# 不写(_set 内属性存在才设=「按源数据+骨架过滤输出」)。
_kd = px.get("Kind")
if _kd is not None:
try:
_set("Kind", str(int(_kd)))
except (TypeError, ValueError):
pass
_fl = px.get("_flags")
if isinstance(_fl, dict):
for k, v in _fl.items():
if k in ("Remark", "PriceSource", "Delivery", "Location", "ProducingArea",
"Supplier", "Character") or v is None:
continue
_set(k, str(v))
# 恒空链:合并回写行上源文件残留的 Remark/询价类属性清空(2026-11-03 主人定「恒空」;
# 源行自带值也不保留——真件实测 CL01 源行 Remark="原始备注" 残留)。_set 只动骨架有槽的。
for k in ("Remark", "PriceSource", "Delivery", "Location", "ProducingArea",
"Supplier", "Character"):
if re.search(r'\b' + k + r'="', newtag) and _attr(newtag, k):
newtag = _attr_set(newtag, k, "")
for tot, pattr in (("NoTaxOrgTotal", "NoTaxOrgPrice"), ("NoTaxTotal", "NoTaxPriceExpress"),
("TaxOrgTotal", "TaxOrgPrice"), ("TaxTotal", "TaxPriceExpress")):
if not re.search(r'\b' + tot + r'="', newtag):
@@ -1835,137 +1858,3 @@ def _resolve_recode_chains(m):
if tail != k:
out[k] = tail
return out
def export_zip(src_bytes, proj_name, src_name, unit_plans, added_summaries, hidden_codes, res_by_norm,
price_updates=None, added_lme_by_uw=None, sync_rows=None, recode_map=None, recode_children=None,
recode_ident=None, field_updates=None, added_children=None, added_org=None,
progress=None):
"""src_bytes=原文件字节;unit_plans={uw键(Number,Name): plan};
plan={"pairs":{...}, "news":{...}, "norms_by_bill":{...}, "added_lme":[(码,名,规格,单位,量,税率,除税,含税,类别)]}。
recode_map/recode_children:合并改码映射与子级替换数据(规格 第11/12 条,api_server 落库读出);
recode_map 进通道前先压平改码链(决策 174 补)。
added_children:采纳新增行的子级组成 {码:[(子码,含量)]}(决策 204:带子级整组照原生结构导出)。
added_org:采纳新增行三恒值 {码:(除税定额价,含税定额价,税率)}(决策 205 主人定:按原数据回填,不编造)。
progress=可选回调 progress(done, total)——每个 zip 条目处理完报一次(决策 92 导出进度条)。
返回 (新zip字节, 建议文件名)。"""
recode_map = _resolve_recode_chains(recode_map) if recode_map else recode_map
ext = _source_ext(src_name)
out_name = (proj_name or "工程") + "-审核版" + ext
zin = zipfile.ZipFile(io.BytesIO(src_bytes))
zout = io.BytesIO()
entries = zin.infolist()
# 2026-10-20 主人定:先扫全项目,取「同一清单标签下最大最全的合格块」当骨架。
# 只按清单块起止位置认,不依赖字段名——COS/COS4/广联达/易达骨架不同也能用。
bill_tmpls, bill_scores = {}, {}
for item in entries:
raw0 = zin.read(item.filename)
try:
txt0, _enc0 = _decode(raw0)
except Exception:
continue
if "<WorkElement" not in txt0 and "<UnitWorksPreliminaryWorkElement" not in txt0:
continue
for tag in ("WorkElement", "UnitWorksPreliminaryWorkElement"):
blk0 = _largest_bill_block(
txt0, tag,
prelim=(tag == "UnitWorksPreliminaryWorkElement"))
if not blk0:
continue
sc0 = _bill_block_score(blk0)
if tag not in bill_tmpls or sc0 > bill_scores[tag]:
bill_tmpls[tag] = blk0
bill_scores[tag] = sc0
if progress:
progress(0, len(entries))
# 决策 187:两遍式——第一遍处理单位 xml 并**收集成品文本**(Project 聚合的数据源),
# Project.xml 延迟到第二遍(保证 Project=各单位之和);条目按原顺序写出,框架零变动。
finals = {} # filename → 变换后 raw
unit_final_texts = [] # 各单位成品文本(Project 聚合用)
with zipfile.ZipFile(zout, "w", zipfile.ZIP_DEFLATED) as zo:
for _ei, item in enumerate(entries, 1):
raw = zin.read(item.filename)
base = item.filename.rsplit("/", 1)[-1]
if base.lower() == "project.xml":
finals[item.filename] = raw # 延迟处理
continue
txt, enc = _decode(raw)
if "<WorkElement" in txt or "<UnitWorksPreliminaryWorkElement" in txt:
keys = []
for m in re.finditer(r'<UnitWorks\b', txt):
e = _open_tag_end(txt, m.start())
if e < 0:
continue
ot = txt[m.start():e]
k = (_attr(ot, "Number") or "", _attr(ot, "Name") or "")
if k in unit_plans and k not in keys:
keys.append(k)
for k in keys:
plan = unit_plans[k]
txt = transform_unit(txt, k, plan["pairs"], plan["news"],
plan["norms_by_bill"], res_by_norm,
bill_tmpls=bill_tmpls)
# 决策 74(主人口径 5.1/5.2/5.3):本单位汇总=被查找对象——
# 同步行按编码写回本单位汇总(改价/名称规格单位不一致项);采纳新增品类行追加进本单位汇总
added_rows = []
for k in keys:
added_rows.extend(unit_plans[k].get("added_lme") or [])
# 单位汇总只接受**合并改价**(被查找对象的精准更新)+ 编辑过的名称/规格/单位
# (field_updates,2026-10-22)——全字段 sync 是项目级的事——
# 否则零编辑也会大面积误改(已实测踩坑)
upd = {c: v for c, v in (price_updates or {}).items()}
# 决策 174:recode_map 有映射也要进(该单位没有合并改价码时,变体码节点
# 照样要换码——此前整个跳过=该单位文件变体码全残留)
if upd or added_rows or field_updates or recode_map or recode_ident:
txt = transform_unit_summaries(txt, upd, added_rows, recode_map, recode_children,
field_updates=field_updates, recode_ident=recode_ident,
added_children=added_children, added_org=added_org)
# 决策 188 数量模型:本单位的现算数量写回导出件(Project 聚合随之正确)——
# 放在 if 外:该单位即使没有其他编辑通道,数量也要按现算写(2026-10-24 实测漏)。
# 一个 xml 可能含多个 uw:各 uw 的数量图合并(同码相加)。
qu = {}
for k in keys:
for _c, _q in (unit_plans[k].get("qty_updates") or {}).items():
qu[_c] = qu.get(_c, 0.0) + float(_q or 0)
if qu:
txt = _apply_qty_updates(txt, qu)
# 决策 244 补五:分部 Total/费用表合计按现算回填(api 层算好随 plan 带入;
# 旧调用方 plan 无此键 → 原样,fail-open)
txt = _apply_div_totals(txt, {k: unit_plans[k] for k in keys})
if recode_map: # 2026-10-22:定额消耗量行编码替换(Summary 块外)
txt = _recode_norm_lme_rows(txt, recode_map)
# 决策 244 补记三:传现算图(码不在图=没被引用、或现算 0 → 都不导);
# 现算链故障(_live_ok=False)退回老行为(按节点 Quantity==0 判)
txt = _drop_zero_qty_summary_rows(
txt, qu if all(unit_plans[k].get("_live_ok", True) for k in keys) else None) # 决策 199/244
txt = _merge_norm_lme_elements(txt) # 决策 200:定额尾表同码并一条
raw = _encode(txt, enc)
unit_final_texts.append(txt) # 决策 187:成品收集
finals[item.filename] = raw
if progress:
progress(_ei, len(entries))
# 第二遍:Project.xml 聚合重建(决策 187 取代 sync 修补——广联达拒导入根治)
for item in entries:
base = item.filename.rsplit("/", 1)[-1]
if base.lower() != "project.xml":
continue
raw = finals.get(item.filename) or zin.read(item.filename)
txt, enc = _decode(raw)
txt = transform_project(txt, added_summaries, hidden_codes, sync_rows,
recode_map=recode_map, recode_children=recode_children,
recode_ident=recode_ident, unit_texts=unit_final_texts,
added_org=added_org)
if recode_map: # 决策 174:Project.xml 的块外元素行同口径换码
txt = _recode_norm_lme_rows(txt, recode_map)
finals[item.filename] = _encode(txt, enc)
# 按原条目顺序写出(zip 条目序=源框架不动)
for item in entries:
raw = finals.get(item.filename) or zin.read(item.filename)
# 条目名按原始字节保真回写(修单位工程名乱码)
zi = _RawNameZipInfo(item.filename, date_time=item.date_time)
zi.compress_type = zipfile.ZIP_DEFLATED
zi.external_attr = item.external_attr
zi.create_system = item.create_system
zi.extra = _safe_extra(item.extra) # 附加块保真(NTFS 时间戳等,见 _safe_extra)
zo.writestr(zi, raw)
return zout.getvalue(), out_name

View File

@@ -1,268 +0,0 @@
# -*- coding: utf-8 -*-
"""HTML 导出(2026-11-03 主人定):导出「界面可以看到的一模一样的数据,包含审核的备注内容」,
全部已有数据渲染成一个自包含 .html 单文件(内嵌样式,浏览器直接打开)。
层级与数据源(与工作台同一套会话库 + 决策 188 现算引擎,显示=导出):
· 项目标题 / 目录树概览(s_sections → s_unit_works,树序=单项入库序+编号自然序,231 补记十)
· 项目级工料机汇总(dyn_lme.dyn_rows 现算,前 11 列=界面项目级卡同形,决策 147/259)
· 项目汇总分析(s_proj_summary 原样树,决策 244)
· 单位工程:分部分项表(分部→清单→定额子行,审核备注列 x_remark)+措施项目表
+单位级工料机汇总(dyn_lme.dyn_uw_rows 现算 9 列)
· 临删行保留并打删除线(界面所见);没算的数值留空(填空三分类)
只读会话库,不碰源文件;cos/cos4/xlsx 通道一概不经过这里。"""
import io
import html as _h
import dyn_lme
def _fmt_money(v):
if v is None or v == "":
return ""
try:
return "{:,.2f}".format(float(v))
except (TypeError, ValueError):
return str(v)
def _fmt_qty(v):
if v is None or v == "":
return ""
try:
f = float(v)
s = ("%f" % f).rstrip("0").rstrip(".")
return s if s else "0"
except (TypeError, ValueError):
return str(v)
def _e(v):
return _h.escape("" if v is None else str(v), quote=True)
def _tree_order(sc, sid):
"""单位工程树序(=export_excel_bytes 同款:单项入库序+组内编号自然序)。"""
from formats.skeleton import _natkey
sec_order = {r["id"]: i for i, r in enumerate(
sc.execute("SELECT id FROM s_sections WHERE session_id=? ORDER BY id", (sid,)).fetchall())}
uws = sorted(sc.execute("SELECT * FROM s_unit_works WHERE session_id=?", (sid,)).fetchall(),
key=lambda r: (sec_order.get(r["section_id"], len(sec_order)),
_natkey(r["Number"] or ""), r["id"]))
secs = sc.execute("SELECT * FROM s_sections WHERE session_id=? ORDER BY id", (sid,)).fetchall()
return secs, uws
def _proj_lme_table(sc, sid):
"""项目级工料机汇总表(dyn_rows 前 11 列,与界面卡同形)。"""
try:
rows = dyn_lme.dyn_rows(sc, sid, None) or []
except Exception:
rows = []
if not rows:
return "<p class='empty'>没有数据</p>"
out = ["<table class='grid'><thead><tr>",
"<th>编码</th><th>名称</th><th>规格型号</th><th>单位</th><th>类别</th>",
"<th>消耗量</th><th>除税编制价</th><th>税率(%)</th><th>含税编制价</th><th>备注</th>",
"</tr></thead><tbody>"]
for r in rows:
out.append("<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td class='n'>%s</td>"
"<td class='n'>%s</td><td class='n'>%s</td><td class='n'>%s</td><td>%s</td></tr>"
% (_e(r[1]), _e(r[2]), _e(r[3]), _e(r[4]), _e(r[9]),
_fmt_qty(r[5]), _fmt_money(r[6]), _fmt_qty(r[7]), _fmt_money(r[8]), _e(r[10])))
out.append("</tbody></table>")
return "".join(out)
def _uw_lme_table(sc, sid, uw_id):
"""单位级工料机汇总表(dyn_uw_rows 前 9 列=界面形状:码/名/规/单/类别/量/除税/税率/含税)。"""
try:
rows = dyn_lme.dyn_uw_rows(sc, sid, uw_id) or []
except Exception:
rows = []
if not rows:
return "<p class='empty'>没有数据</p>"
out = ["<table class='grid'><thead><tr>",
"<th>编码</th><th>名称</th><th>规格型号</th><th>单位</th><th>类别</th>",
"<th>数量</th><th>除税价</th><th>税率(%)</th><th>含税价</th>",
"</tr></thead><tbody>"]
for r in rows:
out.append("<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td class='n'>%s</td>"
"<td class='n'>%s</td><td class='n'>%s</td><td class='n'>%s</td></tr>"
% (_e(r[0]), _e(r[1]), _e(r[2]), _e(r[3]), _e(r[4]),
_fmt_qty(r[5]), _fmt_money(r[6]), _fmt_qty(r[7]), _fmt_money(r[8])))
out.append("</tbody></table>")
return "".join(out)
def _proj_summary_table(sc, sid):
"""项目汇总分析(s_proj_summary 原样树,决策 244;无表/无数据=空卡)。"""
try:
rows = sc.execute("""SELECT Kind, Number, Code, Name, Formula, Rate, Total, Remark
FROM s_proj_summary WHERE session_id=? ORDER BY id""",
(sid,)).fetchall()
except Exception:
rows = []
if not rows:
return "<p class='empty'>没有数据</p>"
out = ["<table class='grid'><thead><tr><th>序号</th><th>编码</th><th>名称</th>",
"<th>计算公式/说明</th><th>费率(%)</th><th>金额</th><th>备注</th>",
"</tr></thead><tbody>"]
for r in rows:
num = r["Number"] or ""
out.append("<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td class='n'>%s</td>"
"<td class='n'>%s</td><td>%s</td></tr>"
% (_e(num), _e(r["Code"]), _e(r["Name"]), _e(r["Formula"]),
_fmt_qty(r["Rate"]), _fmt_money(r["Total"]), _e(r["Remark"])))
out.append("</tbody></table>")
return "".join(out)
def _bills_tables(sc, uw_id):
"""单位工程的 分部分项+措施 两张表(分部树递归照 export_excel_bytes 同款挂接)。"""
ds_all = [dict(r) for r in sc.execute(
"SELECT * FROM s_divides WHERE uw_id=? ORDER BY x_seq, id", (uw_id,)).fetchall()]
bills = [dict(r) for r in sc.execute(
"""SELECT * FROM s_bills WHERE uw_id=?
ORDER BY CASE WHEN x_seq IS NULL THEN 1 ELSE 0 END, x_seq, id""", (uw_id,)).fetchall()]
def b_total(b):
try:
if b.get("Quantity") is not None and b.get("Price") is not None:
return round(float(b["Quantity"]) * float(b["Price"]), 2)
except (TypeError, ValueError):
pass
return b.get("Total")
def norm_rows_html(bill_id):
out = []
for n in sc.execute("""SELECT Number, Name, Unit, Quantity, Price, Total, x_tdel
FROM s_norms WHERE bill_id=? ORDER BY id""", (bill_id,)).fetchall():
out.append("<tr%s><td class='ind'>└ %s</td><td>%s</td><td></td><td>%s</td>"
"<td class='n'>%s</td><td class='n'>%s</td><td class='n'>%s</td><td></td></tr>"
% ((" class='tdel'" if n["x_tdel"] else ""),
_e(n["Number"]), _e(n["Name"]), _e(n["Unit"]),
_fmt_qty(n["Quantity"]), _fmt_money(n["Price"]), _fmt_money(n["Total"])))
return "".join(out)
def bill_html(b):
return ("<tr%s><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td class='n'>%s</td>"
"<td class='n'>%s</td><td class='n'>%s</td><td>%s</td></tr>%s"
% ((" class='tdel'" if b.get("x_tdel") else ""),
_e(b.get("Number")), _e(b.get("Name")), _e(b.get("Attr")), _e(b.get("Unit")),
_fmt_qty(b.get("Quantity")), _fmt_money(b.get("Price")),
_fmt_money(b_total(b)), _e(b.get("x_remark")), norm_rows_html(b["id"])))
def table(head_html, rows_html):
if not rows_html:
return "<p class='empty'>没有数据</p>"
return "<table class='grid'><thead><tr>%s</tr></thead><tbody>%s</tbody></table>" % (
head_html, rows_html)
head = ("<th>编码</th><th>名称</th><th>项目特征</th><th>单位</th><th>工程数量</th>"
"<th>单价</th><th>合价</th><th>审核备注</th>")
# 分部分项:分部树递归(子分部/清单挂上级名下,同 231 补记十树口径)
ds = [d for d in ds_all if d.get("Kind") != "prelim"]
ids = {d["id"] for d in ds}
kids, roots = {}, []
for d in ds:
p = d.get("parent_id")
(kids.setdefault(p, []).append(d)) if p in ids else roots.append(d)
by_div = {}
for b in bills:
if b.get("Kind") == "prelim":
continue
by_div.setdefault(b.get("div_id"), []).append(b)
def walk(d, out):
out.append("<tr class='div'><td></td><td colspan='7'>▣ %s</td></tr>" % _e(d.get("Name")))
for b in by_div.get(d["id"], []):
out.append(bill_html(b))
for sub in kids.get(d["id"], []):
walk(sub, out)
fb_rows = []
for d in roots:
walk(d, fb_rows)
for b in by_div.get(None, []): # 无分部挂靠的清单:落首个一级分部名下兜底(同 Excel 通道)
if roots:
fb_rows.insert(0, bill_html(b))
else:
fb_rows.append(bill_html(b))
# 措施项目:清单平铺(带上级分部名列省略,界面措施区同数据)
prelim_rows = [bill_html(b) for b in bills if b.get("Kind") == "prelim"]
return (table(head, "".join(fb_rows)), table(head, "".join(prelim_rows)))
_CSS = """
body{font-family:"Microsoft YaHei",Arial,sans-serif;margin:24px;color:#243b53;background:#f7f9fc}
h1{font-size:22px;border-bottom:2px solid #1f66d1;padding-bottom:8px}
h2{font-size:18px;margin:28px 0 10px;color:#1f66d1}
h3{font-size:15px;margin:20px 0 8px;background:#eaf1fb;padding:6px 10px;border-left:4px solid #1f66d1}
h4{font-size:13px;margin:14px 0 6px;color:#5b6b80}
table.grid{border-collapse:collapse;width:100%;font-size:12px;background:#fff}
table.grid th,table.grid td{border:1px solid #c9d6e8;padding:4px 7px;text-align:left;vertical-align:top}
table.grid th{background:#eaf1fb;color:#243b53;white-space:nowrap}
td.n,th.n{text-align:right;white-space:nowrap}
tr.div td{background:#f2f6fc;font-weight:600}
tr.tdel td{text-decoration:line-through;color:#98a6b8;background:#fafbfc}
td.ind{padding-left:22px;color:#5b6b80}
p.empty{color:#98a6b8;font-size:12px;margin:6px 0}
.meta{color:#8a97a8;font-size:12px;margin:4px 0 18px}
.toc li{margin:2px 0;font-size:13px}
"""
def export(sc, sid):
"""HTML 导出入口:返回 (字节, 文件名, 错误)。"""
srow = sc.execute("SELECT * FROM sessions WHERE id=?", (sid,)).fetchone()
if not srow:
return None, None, "会话不存在"
proj = (srow["Name"] if "Name" in srow.keys() else srow["name"]) or "工程"
secs, uws = _tree_order(sc, sid)
if not uws:
return None, None, "本工程还没有单位工程,无数据可导出"
secs_by_id = {r["id"]: r for r in secs}
out = ["<!DOCTYPE html><html lang='zh-CN'><head><meta charset='utf-8'>",
"<title>%s-审核版</title><style>%s</style></head><body>" % (_e(proj), _CSS)]
out.append("<h1>%s <span style='font-size:13px;color:#8a97a8'>(审核版 HTML 导出)</span></h1>" % _e(proj))
# 目录树概览
out.append("<h2>目录树</h2><ul class='toc'>")
cur_sec = None
for i, u in enumerate(uws):
s = secs_by_id.get(u["section_id"])
if s is not None and s["id"] != cur_sec:
cur_sec = s["id"]
out.append("<li><b>%s %s</b></li><ul>" % (_e(s["Number"]), _e(s["Name"])))
out.append("<li>%s %s <span class='meta'>合价 %s</span></li>"
% (_e(u["Number"]), _e(u["Name"]), _fmt_money(u["Total"])))
nxt = uws[i + 1] if i + 1 < len(uws) else None
if s is not None and (nxt is None or nxt["section_id"] != cur_sec):
out.append("</ul>")
out.append("</ul>")
# 项目级:汇总分析 + 工料机汇总(界面原数据卡同数据)
out.append("<h2>项目汇总分析</h2>")
out.append(_proj_summary_table(sc, sid))
out.append("<h2>项目级工料机汇总</h2>")
out.append(_proj_lme_table(sc, sid))
# 单位工程明细
for u in uws:
out.append("<h3>%s %s <span style='font-weight:400'>合价 %s</span></h3>"
% (_e(u["Number"]), _e(u["Name"]), _fmt_money(u["Total"])))
fb, prelim = _bills_tables(sc, u["id"])
out.append("<h4>分部分项</h4>")
out.append(fb)
out.append("<h4>措施项目</h4>")
out.append(prelim)
out.append("<h4>单位级工料机汇总</h4>")
out.append(_uw_lme_table(sc, sid, u["id"]))
out.append("<p class='meta'>导出时间:%s 数据与工作台显示同源(含审核备注)</p>" %
__import__("datetime").datetime.now().strftime("%Y-%m-%d %H:%M"))
out.append("</body></html>")
return "".join(out).encode("utf-8"), proj + "-审核版.html", None

File diff suppressed because it is too large Load Diff

View File

@@ -136,7 +136,8 @@ def build_plan(sc, sid):
JOIN s_norms n ON n.id=nr.norm_id
JOIN s_bills b ON b.id=n.bill_id
WHERE b.session_id=?""", (sid,)):
res_by_norm.setdefault(r["norm_id"], []).append((r["res_code"], r["qty"]))
res_by_norm.setdefault(r["norm_id"], []).append(
(r["res_code"], r["qty"], r["express"]))
for bill_id, ns in norms_by_bill.items():
for n in ns:
n["res"] = res_by_norm.get(n["id"], [])

View File

@@ -27,16 +27,23 @@ REGION = ("广东省", "珠海市", "香洲区")
# 改过滤规则、改层级记账方式、修了会导致旧数据错/缺的 bug),就把号往上加一位。
# 只改界面 / 只改查询,不动入库结构 —— 不用改号,否则会白白提示全库重导。
# 格式建议 YYYY.MM.DD-N(同一天多次改口径就 +1)。
PARSER_VER = "2026.11.02-1" # 2026.11.02-1:lme_uw 尾部追加 x_flags(文字/标志属性 JSON 全采)——「骨架不能创造数据」原则落地(决策 259,老批次需重导/升级才带 flags)
PARSER_VER = "2026.11.03-4" # 2026.11.03-4:项目级非数据层整棵采集(x_side:SummaryOfCost 两处/AddiCost/ProjectInstallationWorkCostSummary…;老批次需重导);-3:单位工程非数据层 x_attr;-2:清单/定额固定子块 x_side;-1:x_flags 补采 ProviderBase/Weight;2026.11.02-1:lme_uw 尾部追加 x_flags(决策 259)
# LME_SUM 行的文字/标志属性集(2026-11-02 主人定「原文件有按原文件导,没有则不导出」):
# 数值属性(量/价/合价)另有专列,不在此列;Remark 属数据性质备注,一并按原文件采。
# 2026-11-03 主人定补:ProviderBase/Weight 同口径(按源数据、卡槽决定输出)。
_LME_SUM_FLAGS = ("LossRate", "Class", "Concrete", "ExtKind", "AddiKind", "MainMaterial",
"ProvisionalMaterial", "Provider", "PriceSource", "Delivery", "Location",
"ProducingArea", "Supplier", "Character", "Remark")
"ProvisionalMaterial", "Provider", "ProviderBase", "Weight", "PriceSource",
"Delivery", "Location", "ProducingArea", "Supplier", "Character", "Remark")
# 2026.10.10-1:clean_attr 剥号加小数点护栏(x_attr_norm 口径变,老批次需重导)
# 2026.10.08-1:清单节点开始采集源文件备注 Remark(老批次需重导才有)
# 2026-11-03 主人定「所有值来自数据库,骨架只管导出格式/是否自增」:
# 清单/定额下这些**结构固定子块**(单价计算行、管理费费率、费用构成、表达式行)的值
# 随导入原样入库(x_side JSON,文档序),导出按骨架列闸门回填,行数按库。
_SIDE_TAGS = ("SummaryOfBasicCost", "ExpressElement", "ManageFees", "UnitPriceCalculationOfItem")
# ---------- 归一化 ----------
def norm(s):
s = (s or "").strip()
@@ -166,6 +173,68 @@ def _encode_attr_newlines(txt):
return "".join(out)
def _side_tree(el):
"""元素 → {tag, attrs(原值), kids}(导出按骨架列闸门重建)。"""
node = {"tag": el.tag, "attrs": {k: v for k, v in el.attrib.items()}, "kids": []}
for c in el:
if isinstance(c.tag, str):
node["kids"].append(_side_tree(c))
return node
def _capture_unit_side(txt, out):
"""单位工程里**非数据层**的结构整棵采集(带值):AttrInfo/AddiInfo/SummaryOfCost(含 AddiCost)/
UnitWorksSummary/Sundry/Tax/ProvisionalMaterialEquipment 等。
骨架里这些层标注为「自增块/自增行」,导出按这份数据重建(行数=数据行数)。"""
try:
r = ET.fromstring(txt)
except Exception:
return
for u in r.iter("UnitWorks"):
if not (u.attrib.get("Name") or "").strip():
continue
idx = out.get("cur_uw", -1)
if idx < 0:
return
out.setdefault("uw_side", {})[idx] = [
_side_tree(c) for c in u
if isinstance(c.tag, str)
and c.tag not in ("DivisionalAndElementalWorks", "DivisionalWorks",
"Preliminaries", "WorkElement", "Norm",
"LabourMaterialsEquipmentsMachinesElement",
"LabourMaterialsEquipmentsMachinesSummary")]
return
def _side_tree_filtered(el, skip):
"""同 _side_tree,但递归跳过数据层标签(项目级:SectionalWorks/UnitWorks/清单定额等)。"""
node = {"tag": el.tag, "attrs": {k: v for k, v in el.attrib.items()}, "kids": []}
for c in el:
if isinstance(c.tag, str) and c.tag not in skip:
node["kids"].append(_side_tree_filtered(c, skip))
return node
_PROJ_SKIP = {"SectionalWorks", "UnitWorks", "DivisionalAndElementalWorks",
"DivisionalWorks", "WorkElement", "Norm",
"LabourMaterialsEquipmentsMachinesElement",
"LabourMaterialsEquipmentsMachinesSummary"}
def _capture_proj_side(root):
"""项目级非数据层整棵采集(带值):根属性 / SummaryOfCost(项目级与单项级两处)/
ProjectInstallationWorkCostSummary / Tax / Sundry / ProvisionalMaterialEquipment…
每项记绝对路径(标签链),导出按路径对位重建。数据层(单项工程/单位/清单/定额)不入。"""
recs = [{"path": [], "node": {"tag": root.tag,
"attrs": {k: v for k, v in root.attrib.items()}, "kids": []}}]
for c in root:
if not isinstance(c.tag, str) or c.tag in _PROJ_SKIP:
continue
recs.append({"path": [root.tag, c.tag],
"node": _side_tree_filtered(c, _PROJ_SKIP)})
return recs
def parse_std(path, out):
out.setdefault("lme_res", {}) # 机械台班 / 配合比的**下一级组成**:编码 → [(子编码, 含量)]
z = zipfile.ZipFile(path)
@@ -183,6 +252,8 @@ def parse_std(path, out):
out["bulid_unit"] = r.attrib.get("BulidUnit", "")
out["total"] = proj_total(r) # 2026-09-30:根节点常无 Total,改三级兜底
out["info"] = {k: v for k, v in r.attrib.items() if (v or "").strip() != ""}
# 2026-11-03:项目级非数据层整棵采集(SummaryOfCost 两处/AddiCost/ProjectInstallationWorkCostSummary…)
out["proj_side"] = _capture_proj_side(r)
# 2026-10-07 主人定:项目特征信息**只从 Project.xml 收**(根节点下的 AttrInfoItem /
# AddiInfoItem 编制信息条目)。此前从各单位工程 XML 收——那是同一表单的逐工程拷贝,
# 「项目级」卡片理应取项目级文件。名称去重、最多 60 条(口径不变)。
@@ -300,6 +371,10 @@ def parse_std(path, out):
out["cur_div"] = None
out["div_stack"] = []
out["in_prelim"] = False
# 工程特征树捕获(2026-11-03:单位工程 AttrInfo 整棵入库,导出按数据循环)
out["_attr_depth"] = None
out["_attr_stack"] = []
out["_attr_roots"] = []
# ⚠️ 2026-09-29 修:UnitWorks 是**容器**标签(每个数据 xml 的根元素就是它),
# 它下面所有 WorkElement / Norm 的 end 事件都排在它自己 end 之前。
# 只监听 end 的话,cur_uw 要到整个文件扫完才被赋值 —— 结果是每条清单挂的
@@ -317,6 +392,14 @@ def parse_std(path, out):
# 绝不能拿最后一条清单去接(那才是原来最致命的错挂)。
for event, el in ET.iterparse(io.StringIO(txt), events=("start", "end")):
if event == "start":
out.setdefault("_stack", []).append(el.tag)
if el.tag == "AttrInfo" and out.get("_attr_depth") is None:
out["_attr_depth"] = len(out["_stack"])
elif (isinstance(el.tag, str) and el.tag.endswith("InfoItem")
and out.get("_attr_depth") is not None):
# 单位工程工程特征:AttrInfo 下的 InfoItem 按层级建树(导出按块/行循环)
out.setdefault("_attr_stack", []).append(
(len(out["_stack"]), {"tag": el.tag, "attrs": dict(el.attrib), "kids": []}))
if el.tag == "UnitWorks" and (el.attrib.get("Name") or "").strip():
out["uw"].append((el.attrib.get("Number", ""), el.attrib.get("Name", ""),
f(el.attrib.get("Total"))))
@@ -478,6 +561,20 @@ def parse_std(path, out):
if _n >= 0 and v.strip():
# 主人定(补记十五改):导入什么就是什么,原样整串入库,导出原样回填
out.setdefault("norm_adj", {}).setdefault(_n, []).append(v)
elif tag in _SIDE_TAGS:
# 2026-11-03:结构固定子块的值随导入入库(文档序、属性原样)——导出端按
# 骨架列闸门回填;行数由库决定(库里 8 行就导 8 行,不是骨架样板 1 行)。
_st = out.get("_stack") or []
_par = _st[-2] if len(_st) >= 2 else None
rec = {"tag": tag, "attrs": {k: v for k, v in a.items()}}
if _par == "Norm":
_n = out.get("cur_norm", -1)
if _n >= 0:
out.setdefault("norm_side", {}).setdefault(_n, []).append(rec)
elif _par in ("WorkElement", "UnitWorksPreliminaryWorkElement"):
_b = out.get("cur_bill", -1)
if _b >= 0:
out.setdefault("bill_side", {}).setdefault(_b, []).append(rec)
elif tag == "SummaryOfCost":
# 2026-09-30:单位工程造价构成。同样因为 clear 会清空 attrib,只能在自己的 end 里读。
# 归栈顶那个 UnitWorks(嵌套时内层优先),且每个单位工程只认它的第一个 SummaryOfCost。
@@ -541,7 +638,22 @@ def parse_std(path, out):
json.dumps({k: a.get(k) for k in _LME_SUM_FLAGS if a.get(k) is not None},
ensure_ascii=False) if any(a.get(k) is not None for k in _LME_SUM_FLAGS) else None))
out["cur_lme"] = "" # 出这条汇总:后面的 Element 不再算它的组成
if isinstance(tag, str) and tag.endswith("InfoItem") and out.get("_attr_stack"):
_lvl, _node = out["_attr_stack"].pop()
if out["_attr_stack"]:
out["_attr_stack"][-1][1]["kids"].append(_node)
else:
out.setdefault("_attr_roots", []).append(_node)
if tag == "AttrInfo" and out.get("_attr_depth") is not None:
out.setdefault("uw_attr", {})[out.get("cur_uw", -1)] = out.get("_attr_roots") or []
out["_attr_roots"] = []
out["_attr_stack"] = []
out["_attr_depth"] = None
_st = out.get("_stack")
if _st:
_st.pop()
el.clear()
_capture_unit_side(txt, out)
return "2025标准"
@@ -846,26 +958,26 @@ def _zip_swt_member(z):
def parse_file(path, out):
"""按文件头分派解析器:zip=COS4/.COS;swt/swz=深圳数据交换标准(XML 或压缩包内 XML);
散装 xml 仍拒绝。扩展名 .SWT/.SWZ 不分大小写。"""
"""**按内容分派解析器,扩展名不参与拦截**(2026-11-03 主人定 A 方案):
zip 包内有无 ConstructProject → 有=SWT 族、无=COS 族;裸 XML 根节点 ConstructProject=SWT 族。
同族新后缀(.cos5/.xml/.abc…)零代码可开;不认识的散装 XML 仍明确报错。"""
st = sniff(path)
if st == "zip":
# 2026-10-19:.SWZ/.SWT 若是压缩包,先看里面有没有 ConstructProject;
# 有就按 SWT 解析,没有才回落到 COS4(parse_std)。
if str(path).lower().endswith((".swz", ".swt")):
try:
with zipfile.ZipFile(path) as z:
member = _zip_swt_member(z)
if member:
with z.open(member) as f:
return parse_swt(f, out)
except (zipfile.BadZipFile, OSError):
pass
# 不再看后缀:任何 zip 先找 ConstructProject 成员(SWT 族),没有才按 COS 族解析
try:
with zipfile.ZipFile(path) as z:
member = _zip_swt_member(z)
if member:
with z.open(member) as f:
return parse_swt(f, out)
except (zipfile.BadZipFile, OSError):
pass
return parse_std(path, out)
if st == "swt":
return parse_swt(path, out)
if st == "xml":
raise ValueError("已不再支持 xml 格式,请导出为 COS4(或 .COS)后打开")
raise ValueError("这个 XML 不是已知的计价结构(当前支持:COS/COS4 压缩包、SWT/SWZ 数据交换标准;"
"同族新后缀可直接打开,扩展名不拦)")
if st == "encrypted":
raise ValueError("这是加密件,无法解析")
raise ValueError("文件头无法识别,不是计价文件")
@@ -913,19 +1025,22 @@ def save(con, kind, out, fn, sha, mtime, meta=None, bid=None):
info_json = json.dumps(_info, ensure_ascii=False) if _info else None
_feat = out.get("feat") or []
feat_json = json.dumps([{"n": n, "v": v} for n, v in _feat], ensure_ascii=False) if _feat else None
_pside = out.get("proj_side") or []
side_json = json.dumps(_pside, ensure_ascii=False) if _pside else None
if bid is None:
cur.execute("""INSERT INTO batches(kind, Name, FileKind, BulidUnit, x_province, x_city, x_district,
x_period_start_m, x_period_end_m, x_enabled, x_total, x_rows_bill, x_rows_lme, x_imported_at,
x_src_hash, x_note, x_parser_ver, x_info, x_feat) VALUES(?,?,?,?,?,?,?,?,?,1,?,?,?,?,?,?,?,?,?)""",
x_src_hash, x_note, x_parser_ver, x_info, x_feat, x_side)
VALUES(?,?,?,?,?,?,?,?,?,1,?,?,?,?,?,?,?,?,?,?)""",
(kind, name, fk, bu, prov, city, dist, p_from, p_to, out["total"], 0, 0,
time.strftime("%Y-%m-%d %H:%M:%S"), sha, "", PARSER_VER, info_json, feat_json))
time.strftime("%Y-%m-%d %H:%M:%S"), sha, "", PARSER_VER, info_json, feat_json, side_json))
bid = cur.lastrowid
else:
cur.execute("""UPDATE batches SET kind=?, Name=?, FileKind=?, BulidUnit=?, x_province=?, x_city=?,
x_district=?, x_period_start_m=?, x_period_end_m=?, x_total=?, x_rows_bill=0, x_rows_lme=0,
x_imported_at=?, x_parser_ver=?, x_info=?, x_feat=? WHERE id=?""",
x_imported_at=?, x_parser_ver=?, x_info=?, x_feat=?, x_side=? WHERE id=?""",
(kind, name, fk, bu, prov, city, dist, p_from, p_to, out["total"],
time.strftime("%Y-%m-%d %H:%M:%S"), PARSER_VER, info_json, feat_json, bid))
time.strftime("%Y-%m-%d %H:%M:%S"), PARSER_VER, info_json, feat_json, side_json, bid))
if cur.rowcount != 1:
raise RuntimeError("原位升级失败:批次 #%s 不存在" % bid)
@@ -959,14 +1074,16 @@ def save(con, kind, out, fn, sha, mtime, meta=None, bid=None):
_um = (out.get("uw_meta") or {}).get(i) or (None, None)
cur.execute("""INSERT INTO unit_works(batch_id, section_id, Number, Name, Specialty, Total,
Construction, DivisionalAndElementalWorks, Preliminaries,
CostForHSE, SundryCosts, Tax, Code, Unit, Scale, ztotal)
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
CostForHSE, SundryCosts, Tax, Code, Unit, Scale, ztotal, x_attr)
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
(bid, num2sec.get(num), num, nm, (out.get("uw_spec") or {}).get(i),
total, c.get("Construction"),
c.get("DivisionalAndElementalWorks"), c.get("Preliminaries"),
c.get("CostForHSE"), c.get("SundryCosts"), c.get("Tax"),
(out.get("uw_code") or {}).get(i), _um[0], _um[1],
_z if _z is not None else total))
_z if _z is not None else total,
(lambda v: json.dumps(v, ensure_ascii=False) if v is not None else None)(
(out.get("uw_side") or {}).get(i))))
uw_ids.append(cur.lastrowid)
# 决策 244:单位工程「汇总分析」/「其他项目」两卡源数据原样入库(老格式无这些键 → 空转)
@@ -1038,10 +1155,12 @@ def save(con, kind, out, fn, sha, mtime, meta=None, bid=None):
divid = div_ids[_dv] if (_dv is not None and 0 <= _dv < len(div_ids)) else None
cur.execute("""INSERT INTO bills(batch_id, uw_id, div_id, Number, Name, Attr, Unit,
Quantity, Price, Total, Kind, src_remark,
x_name_norm, x_attr_norm, x_unit_norm, x_hash_exact, x_hash_semi, x_setkey, x_seq)
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
x_name_norm, x_attr_norm, x_unit_norm, x_hash_exact, x_hash_semi, x_setkey, x_seq, x_side)
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
(bid, uwid, divid, num, name, attr, unit, qty, price, total, kb, srk,
norm(name), clean_attr(attr), norm(unit), h, hs, match.bill_setkey(name, unit), xseq))
norm(name), clean_attr(attr), norm(unit), h, hs, match.bill_setkey(name, unit), xseq,
(lambda v: json.dumps(v, ensure_ascii=False) if v is not None else None)(
(out.get("bill_side") or {}).get(i))))
n_bill += 1
bill_ids.append(cur.lastrowid)
seen_bill.add(h)
@@ -1057,11 +1176,13 @@ def save(con, kind, out, fn, sha, mtime, meta=None, bid=None):
bqty = out["bills"][idx][4] if 0 <= idx < len(out["bills"]) else None
coef = (round(qty * unit_prefix(unit) / bqty, 6)
if (qty is not None and bqty not in (None, 0)) else None)
cur.execute("""INSERT INTO norms(bill_id, Number, Name, Unit, Quantity, Price, Total, x_qty_coef, x_adjust)
VALUES(?,?,?,?,?,?,?,?,?)""",
cur.execute("""INSERT INTO norms(bill_id, Number, Name, Unit, Quantity, Price, Total, x_qty_coef, x_adjust, x_side)
VALUES(?,?,?,?,?,?,?,?,?,?)""",
(bid2, num, name, unit, qty, price, total, coef,
(lambda vals: json.dumps(vals, ensure_ascii=False) if vals else None)(
out.get("norm_adj", {}).get(norm_idx, []))))
out.get("norm_adj", {}).get(norm_idx, [])),
(lambda v: json.dumps(v, ensure_ascii=False) if v is not None else None)(
(out.get("norm_side") or {}).get(norm_idx))))
norm_ids.append(cur.lastrowid)
# 定额消耗工料机(对应 s_norm_res)。
@@ -1261,3 +1382,4 @@ def main():
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,128 @@
# -*- coding: utf-8 -*-
""".yhy 专有格式导入(2026-11-03 主人定):**id 整体平移法**——
每表全部 id 统一加 offset(offset=库内该表当前 max(id)+1−导出件最小 id),
父 id/平面 id 引用按被引用表的同款 offset 一并平移,数据行原样保真(含全部 x_* 状态列)。
引用映射(与 export_yhy 的导出面一致;@SID=换成新会话 id):
s_sections.id
s_unit_works.section_id → s_sections.id
s_divides.uw_id → s_unit_works.id;s_divides.parent_id → s_divides.id(自引用)
s_bills.uw_id → s_unit_works.id;s_bills.div_id → s_divides.id
s_norms.bill_id → s_bills.id;s_norms.x_src_norm_id → s_norms.id(自引用)
s_norm_res.norm_id → s_norms.id
s_lme_uw.uw_id / s_sundry.uw_id / s_uw_summary.uw_id → s_unit_works.id
其余带 session_id 表只换 session_id。s_settings/s_remarks/s_edit_log 不在导出面(导入天然无关)。
sessions 行=新会话:name/期次/地区/建设单位/单价类型用弹框传入覆盖(「名称等一切按弹框」,
2026-11-03 主人定),其余列(x_info/x_feat/src_name/x_manual 等)原样保真;x_batch_id 跨库
引用置空。同名工程拒绝(决策 242)。导入不 commit——事务由调用方提交/回滚(api_server 模式)。"""
import json
import zipfile
from datetime import datetime
# (表名, {引用列: 被引用表});顺序=依赖序(被引用表先插)。
_TABLES = [
("s_sections", {"session_id": "@SID"}),
("s_unit_works", {"session_id": "@SID", "section_id": "s_sections"}),
("s_divides", {"session_id": "@SID", "uw_id": "s_unit_works", "parent_id": "s_divides"}),
("s_bills", {"session_id": "@SID", "uw_id": "s_unit_works", "div_id": "s_divides"}),
("s_norms", {"bill_id": "s_bills", "x_src_norm_id": "s_norms"}),
("s_norm_res", {"norm_id": "s_norms"}),
("s_lme_lib", {"session_id": "@SID"}),
("s_lme_proj", {"session_id": "@SID"}),
("s_lme_res", {"session_id": "@SID"}),
("s_lme_uw", {"session_id": "@SID", "uw_id": "s_unit_works"}),
("s_lmes", {"session_id": "@SID"}),
("s_proj_summary", {"session_id": "@SID"}),
("s_sundry", {"session_id": "@SID", "uw_id": "s_unit_works"}),
("s_uw_summary", {"session_id": "@SID", "uw_id": "s_unit_works"}),
]
def _read_zip(zip_path):
z = zipfile.ZipFile(zip_path)
man = json.loads(z.read("manifest.json").decode("utf-8"))
if man.get("magic") != "YHY":
raise ValueError("这不是本软件导出的 .yhy 工程包")
sessions = json.loads(z.read("sessions.json").decode("utf-8"))
rows = {}
for name in z.namelist():
if name.startswith("rows/") and name.endswith(".json"):
rows[name[5:-5]] = json.loads(z.read(name).decode("utf-8"))
return man, sessions, rows
def run(con, zip_path, name=None, overrides=None):
"""导入 .yhy:成功 {ok,sid,name,manual,tables,msg};失败 {ok:False,msg}。不 commit。"""
ov = overrides or {}
try:
man, sess_rows, rows = _read_zip(zip_path)
except (zipfile.BadZipFile, KeyError, ValueError) as e:
return {"ok": False, "msg": str(e)}
if not sess_rows:
return {"ok": False, "msg": "工程包里没有会话数据"}
src = sess_rows[0]
new_name = (name or "").strip() or src.get("name") or "工程"
if con.execute("SELECT 1 FROM sessions WHERE name=?", (new_name,)).fetchone():
return {"ok": False, "msg": "同名工程已存在:%s(请换个名称再导入)" % new_name}
new_sid = con.execute("SELECT COALESCE(MAX(id),0)+1 FROM sessions").fetchone()[0]
# 每表 offset=库内当前 max(id)+1−导出件最小 id(空库导入时 offset=0,id 原样)
offsets = {}
for t, _refs in _TABLES:
ids = [r.get("id") for r in rows.get(t, []) if isinstance(r.get("id"), int)]
if ids:
cur = con.execute("SELECT COALESCE(MAX(id),0) FROM %s" % t).fetchone()[0]
offsets[t] = cur + 1 - min(ids)
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
# ① sessions 新行(弹框字段覆盖)
cols = [c[1] for c in con.execute("PRAGMA table_info('sessions')")]
srow = dict(src)
srow["id"] = new_sid
srow["name"] = new_name
srow["imported_at"] = now
srow["x_batch_id"] = None # 跨库批次引用置空
for k in ("period_from", "period_to", "province", "city", "district",
"bulid_unit", "file_kind"):
if k in cols and ov.get(k) not in (None, ""):
srow[k] = ov[k]
if "base_period_m" in cols and ov.get("period_from") is not None:
srow["base_period_m"] = ov["period_from"]
use = [c for c in cols if c in srow]
con.execute("INSERT INTO sessions(%s) VALUES(%s)" % (",".join(use), ",".join("?" * len(use))),
[_json_safe(srow[c]) for c in use])
# ② 各数据表(id 平移+引用平移+换 sid)
stat = {}
for t, refs in _TABLES:
data = rows.get(t) or []
if not data:
continue
off = offsets.get(t, 0)
tcols = [c[1] for c in con.execute("PRAGMA table_info('%s')" % t)]
use = [c for c in tcols if c in data[0]]
sql = "INSERT INTO %s(%s) VALUES(%s)" % (t, ",".join(use), ",".join("?" * len(use)))
for r in data:
vals = []
for c in use:
v = r.get(c)
if c == "id":
v = (v or 0) + off
elif c == "session_id":
v = new_sid
elif c in refs and refs[c] != "@SID" and isinstance(v, int):
v = v + offsets.get(refs[c], 0)
vals.append(_json_safe(v))
con.execute(sql, vals)
stat[t] = len(data)
return {"ok": True, "sid": new_sid, "session_id": new_sid, "name": new_name,
"manual": bool(src.get("x_manual")), "tables": stat,
"msg": "导入完成:%s(新会话 #%d)" % (new_name, new_sid)}
def _json_safe(v):
if isinstance(v, bool):
return int(v)
return v

View File

@@ -165,7 +165,7 @@ def template_bytes():
for i, w in enumerate([18, 11, 7, 16, 42, 7, 9, 9], 1):
ws1.column_dimensions[get_column_letter(i)].width = w
_head(ws1, h1)
for row in ws1.iter_rows(min_row=2, min_col=5, max_col=5):
for row in ws1.iter_rows(min_row=2, min_col=6, max_col=6):
for cell in row:
cell.alignment = Alignment(wrap_text=True, vertical="top")
@@ -462,7 +462,7 @@ def template_project_bytes():
for i, w in enumerate([18, 11, 7, 16, 42, 7, 9, 9], 1):
ws1.column_dimensions[get_column_letter(i)].width = w
_head(ws1, h1)
for row in ws1.iter_rows(min_row=2, min_col=5, max_col=5):
for row in ws1.iter_rows(min_row=2, min_col=6, max_col=6):
for cell in row:
cell.alignment = Alignment(wrap_text=True, vertical="top")
@@ -862,8 +862,8 @@ def save_tree(con, body):
# 分部分项 10 列 / 措施项目 8 列——只带清单、不带定额(主人定);
# 合价=工程量×单价现算;备注=审核备注;导出件可直接回导入(多出的合价/备注列解析端忽略)。
# ---------------------------------------------------------------------------
_FB_HEAD_X = ["上一级名称", "编码", "类型", "名称", "项目特征", "单位", "工程量", "单价", "合价", "备注"]
_CS_HEAD_X = ["名称", "编码", "项目特征", "单位", "工程量", "单价", "合价", "备注"]
_FB_HEAD_X = ["序号", "上一级名称", "编码", "类型", "名称", "项目特征", "单位", "工程量", "单价", "合价", "备注"]
_CS_HEAD_X = ["序号", "名称", "编码", "项目特征", "单位", "工程量", "单价", "合价", "备注"]
def _safe_sheet_name(name):
@@ -938,7 +938,7 @@ def _proj_lme_workbook(sc, sid):
def _unit_workbook(u, divs, bills):
"""单单位工程 xlsx 字节(决策 231 架子:填写说明+分部分项10列+措施8列,合价/备注)。
"""单单位工程 xlsx 字节(2026-11-03 主人定:填写说明去除;分部分项11列+措施9列,首列序号照工作台口径)。
决策 233:自 export_excel_bytes 抽出——整包 zip 与单单位工程导出(export_unit_xlsx)同一产出。"""
def b_total(b):
@@ -963,10 +963,12 @@ def _unit_workbook(u, divs, bills):
continue
by_div.setdefault(b["div_id"], []).append(b)
seq = [0] # 清单行序号跨分部连续、分部行留空(照工作台序号列口径,2026-11-03 主人定)
def walk(d, parent_name, out):
out.append([parent_name, "", "分部", d["Name"] or "", "", "", "", "", "", ""])
out.append(["", parent_name, "", "分部", d["Name"] or "", "", "", "", "", "", ""])
for b in by_div.get(d["id"], []):
out.append([d["Name"] or "", b["Number"] or "", "清单", b["Name"] or "",
seq[0] += 1
out.append([seq[0], d["Name"] or "", b["Number"] or "", "清单", b["Name"] or "",
b["Attr"] or "", b["Unit"] or "", b["Quantity"], b["Price"],
b_total(b), b["x_remark"] or ""])
for sub in kids.get(d["id"], []):
@@ -977,32 +979,22 @@ def _unit_workbook(u, divs, bills):
walk(d, "单位工程", out)
for b in by_div.get(None, []): # 无分部挂靠的清单:落在首个一级分部名下兜底
pn = roots[0]["Name"] if roots else "单位工程"
out.append([pn, b["Number"] or "", "清单", b["Name"] or "", b["Attr"] or "",
seq[0] += 1
out.append([seq[0], pn, b["Number"] or "", "清单", b["Name"] or "", b["Attr"] or "",
b["Unit"] or "", b["Quantity"], b["Price"], b_total(b),
b["x_remark"] or ""])
return out
import io as _io
wb = Workbook()
ws0 = wb.active
ws0.title = "填写说明"
ws0.column_dimensions["A"].width = 90
for i, (t, bold) in enumerate([
("「%s」导出件(决策 231)" % u["Name"], True),
("", False),
("一、本件由软件导出,可直接在「导入Excel」里对同一单位工程回导(整单位工程覆盖)。", False),
("二、合价=工程量×单价(软件现算);备注=审核备注。", False),
("三、只到清单级:不导定额、不导工料机。", False),
], 1):
c = ws0.cell(row=i, column=1, value=t)
if bold:
c.font = Font(bold=True)
# 2026-11-03 主人定:填写说明 sheet 去除,分部分项为首 sheet
ws1 = wb.active
ws1.title = FB_SHEET
h1 = _FB_HEAD_X
ws1 = wb.create_sheet(FB_SHEET)
ws1.append(h1)
for r in fb_rows(u["id"]):
ws1.append(r)
for i, w in enumerate([18, 11, 7, 16, 42, 7, 9, 9, 12, 18], 1):
for i, w in enumerate([8, 18, 11, 7, 16, 42, 7, 9, 9, 12, 18], 1):
ws1.column_dimensions[get_column_letter(i)].width = w
for c, _h in enumerate(h1, 1):
cell = ws1.cell(row=1, column=c)
@@ -1010,19 +1002,21 @@ def _unit_workbook(u, divs, bills):
cell.fill = PatternFill("solid", fgColor="DCE6F1")
cell.alignment = Alignment(horizontal="center", vertical="center")
ws1.freeze_panes = "A2"
for row in ws1.iter_rows(min_row=2, min_col=5, max_col=5):
for row in ws1.iter_rows(min_row=2, min_col=6, max_col=6):
for cell in row:
cell.alignment = Alignment(wrap_text=True, vertical="top")
h2 = _CS_HEAD_X
ws2 = wb.create_sheet(CS_SHEET)
ws2.append(h2)
_cs_seq = [0]
for b in bills.get(u["id"], []):
if b["Kind"] != "prelim":
continue
ws2.append([b["Name"] or "", b["Number"] or "", b["Attr"] or "",
_cs_seq[0] += 1
ws2.append([_cs_seq[0], b["Name"] or "", b["Number"] or "", b["Attr"] or "",
b["Unit"] or "", b["Quantity"], b["Price"], b_total(b),
b["x_remark"] or ""])
for i, w in enumerate([20, 11, 36, 7, 9, 10, 12, 18], 1):
for i, w in enumerate([8, 20, 11, 36, 7, 9, 10, 12, 18], 1):
ws2.column_dimensions[get_column_letter(i)].width = w
for c, _h in enumerate(h2, 1):
cell = ws2.cell(row=1, column=c)
@@ -1030,7 +1024,7 @@ def _unit_workbook(u, divs, bills):
cell.fill = PatternFill("solid", fgColor="DCE6F1")
cell.alignment = Alignment(horizontal="center", vertical="center")
ws2.freeze_panes = "A2"
for row in ws2.iter_rows(min_row=2, min_col=3, max_col=3):
for row in ws2.iter_rows(min_row=2, min_col=4, max_col=4):
for cell in row:
cell.alignment = Alignment(wrap_text=True, vertical="top")
bio = _io.BytesIO()

View File

@@ -493,6 +493,13 @@ def connect():
("s_norm_res", ("express TEXT",)),
# 2026-10-18:定额换算调整记录(JSON,采纳携带;决策 106 补记十三)
("s_norms", ("x_adjust TEXT",)),
# 2026-11-03:结构固定子块原样值(单价行/管理费/费用构成/表达式行,JSON 文档序)
("s_bills", ("x_side TEXT",)),
("s_norms", ("x_side TEXT",)),
# 2026-11-03:单位工程工程特征树(AttrInfo 原样,导出按数据循环)
("s_unit_works", ("x_attr TEXT",)),
# 2026-11-03:项目级非数据层结构树
("sessions", ("x_side TEXT",)),
):
for col in cols:
try:
@@ -547,7 +554,7 @@ def open_project(con, files, meta, job, sid=None):
stat = {"bill": 0, "norm": 0, "lme": 0, "uw": 0}
bill_ids = []
ptotal = None # 工程总造价:多文件时取最后一个有值的
pinfo, pfeat = None, None # 项目根节点属性 / 项目特征条目(项目级标签卡用)
pinfo, pfeat, pside = None, None, None # 项目根属性 / 项目特征 / 项目级非数据层结构树
num2sec, sec_built = {}, set() # 2026-09-30:单位工程编号 → 单项工程 id
for path, name in files:
out = {"uw": [], "bills": [], "norms": [], "lmes": [],
@@ -567,6 +574,8 @@ def open_project(con, files, meta, job, sid=None):
pinfo = out["info"] # 项目根节点属性(编号/专业/计价标准/单位…)
if out.get("feat"):
pfeat = out["feat"] # 项目特征条目 [(名称, 值)]
if out.get("proj_side"):
pside = out["proj_side"] # 项目级非数据层结构(SummaryOfCost/AddiCost…)
# 单项工程先入(2026-09-30):记下「单位工程编号 → 单项工程 id」,单位工程靠编号归位。
# 没有单项工程层的格式(如三溪 .COS)这里就是空的,树退化成两层,不硬造。
@@ -597,14 +606,16 @@ def open_project(con, files, meta, job, sid=None):
cur.execute("""INSERT INTO s_unit_works(session_id, section_id, Number, Name,
Specialty, Total, Construction, DivisionalAndElementalWorks,
Preliminaries, CostForHSE, SundryCosts, Tax,
Code, Unit, Scale, ztotal)
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
Code, Unit, Scale, ztotal, x_attr)
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
(sid, num2sec.get(num), num, nm, (out.get("uw_spec") or {}).get(i),
total, c.get("Construction"),
c.get("DivisionalAndElementalWorks"), c.get("Preliminaries"),
c.get("CostForHSE"), c.get("SundryCosts"), c.get("Tax"),
(out.get("uw_code") or {}).get(i), _um[0], _um[1],
_z if _z is not None else total))
_z if _z is not None else total,
(lambda v: json.dumps(v, ensure_ascii=False) if v is not None else None)(
(out.get("uw_side") or {}).get(i))))
uw_ids.append(cur.lastrowid)
stat["uw"] += 1
@@ -686,12 +697,14 @@ def open_project(con, files, meta, job, sid=None):
cur.execute("""INSERT INTO s_bills(session_id, uw_id, div_id, Number, Name, Attr, Unit,
Quantity, Price, Total, Kind, src_remark,
x_name_norm, x_attr_norm, x_unit_norm, x_hash_exact, x_hash_semi, x_seq,
x_price0)
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
x_price0, x_side)
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
(sid, uwid, divid, num, nm, attr, unit, qty, price, total, kb, srk,
norm(nm), norm(attr), norm(unit),
md5(norm(num)[:9], nm, unit), md5(norm(num)[:9], unit), xseq,
price)) # 决策 217:x_price0=第一次导进来的单价,此后改价/采纳不更新
price, # 决策 217:x_price0=第一次导进来的单价,此后改价/采纳不更新
(lambda v: json.dumps(v, ensure_ascii=False) if v is not None else None)(
(out.get("bill_side") or {}).get(i))))
# 决策 27(2026-10-10):编码只取前 9 位(后 3 位是项目内顺序码,无对比意义);
# 与 history.db.bills(import_job)同口径,启动迁移重算老数据
bill_ids.append(cur.lastrowid)
@@ -705,10 +718,12 @@ def open_project(con, files, meta, job, sid=None):
for norm_idx, (idx, num, nm, unit, qty, price, total) in enumerate(out["norms"]):
bid = bill_ids[idx0 + idx] if 0 <= idx < len(out["bills"]) else None
vals = adj.get(norm_idx, [])
cur.execute("""INSERT INTO s_norms(bill_id, Number, Name, Unit, Quantity, Price, Total, x_adjust)
VALUES(?,?,?,?,?,?,?,?)""",
cur.execute("""INSERT INTO s_norms(bill_id, Number, Name, Unit, Quantity, Price, Total, x_adjust, x_side)
VALUES(?,?,?,?,?,?,?,?,?)""",
(bid, num, nm, unit, qty, price, total,
json.dumps(vals, ensure_ascii=False) if vals else None))
json.dumps(vals, ensure_ascii=False) if vals else None,
(lambda v: json.dumps(v, ensure_ascii=False) if v is not None else None)(
(out.get("norm_side") or {}).get(norm_idx))))
norm_ids.append(cur.lastrowid)
stat["norm"] += 1
@@ -793,11 +808,12 @@ def open_project(con, files, meta, job, sid=None):
x_ntp0=ntp, x_rate0=taxrate, x_taxp0=taxp
WHERE session_id=?""", (sid,))
# 这几样都要**解析完**才知道(sessions 行在解析之前就插好了),所以这里补一笔
if ptotal is not None or pinfo or pfeat:
cur.execute("UPDATE sessions SET x_total=?, x_info=?, x_feat=? WHERE id=?",
if ptotal is not None or pinfo or pfeat or pside:
cur.execute("UPDATE sessions SET x_total=?, x_info=?, x_feat=?, x_side=? WHERE id=?",
(ptotal,
json.dumps(pinfo, ensure_ascii=False) if pinfo else None,
json.dumps([{"n": n, "v": v} for n, v in pfeat], ensure_ascii=False) if pfeat else None,
json.dumps(pside, ensure_ascii=False) if pside else None,
sid))
stat["total"] = ptotal
stat["feat"] = len(pfeat or [])
@@ -806,3 +822,4 @@ def open_project(con, files, meta, job, sid=None):
stat["lremark"] = restore_lme_remarks(con, sid) # 工料机采纳备注按 rkey 回填(2026-10-08)
con.commit()
return sid, stat

View File

@@ -0,0 +1,427 @@
# -*- 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"<?xml") or head[:1] == b"<":
try:
ET.fromstring(blob)
return FAMILY_RAW
except Exception:
return None
return None
def _decode_bytes(raw):
"""按声明解码,声明缺失/错时退 utf-8、gb18030。返回 (bytes, encoding)。"""
import re
m = re.match(rb'(?:\xef\xbb\xbf|\s)*<\?xml[^>]*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 '<?xml version="1.0" encoding="utf-8"?>'
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)
# 连接:主骨架里第一条带 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 + [unit_best], 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
attrs = "".join(' %s="%s"' % (k, escape(str(v), {'"': "&quot;"}))
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 = ("<!-- %s -->" % 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 + "</" + el.tag + ">")
return "".join(out)
def _serialize(root, ind=" ", keep_values=False):
decl = '<?xml version="1.0" encoding="utf-8"?>'
return decl + "\n" + serialize(root, 0, ind, keep_values) + "\n"