feat: 决策240/241——子级工料机二次合并视野与换码贯通、AdminCost 封存及台账更新

This commit is contained in:
lianjianwei2024
2026-10-30 12:39:32 +08:00
parent b79c0df557
commit 386e1ad624
15 changed files with 15885 additions and 29 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,200 @@
# -*- coding: utf-8 -*-
"""把 ch6_blocks.json 组装成可交付 Markdown:正文 + 目录 + 适配对照附录"""
import json, re, os, sqlite3
BASE = r"C:\Users\MZ\AppData\Local\Temp\cos4std"
BLK = os.path.join(BASE, "ch6_blocks.json")
OUT = os.path.join(BASE, "final_ch6.md")
DB = r"D:\PricingReview\AdminCost\data.db"
# 估算/概算专属元素(本项目为计价文件,不纳入)
EST = {
"ConstructionSummary", "ConstructionCost",
"EquipmentProcurementCost", "EquipmentProcurementCostItem",
"OtherInvestmentOfConstructionProject", "OtherInvestmentOfConstructionProjectGroup",
"OtherInvestmentOfConstructionProjectItem",
"ContingencyFee", "ContingencyFeeGroup", "ContingencyFeeItem",
"UrbanRailTransitVehicleProcurementCost", "UrbanRailTransitVehicleProcurementCostGroup",
"UrbanRailTransitVehicleProcurementCostItem",
"InterestDuringConstructionPeriod", "InterestDuringConstructionPeriodGroup",
"InterestDuringConstructionPeriodItem",
"InitialWorkingCapital", "InitialWorkingCapitalGroup", "InitialWorkingCapitalItem",
"InitialWorkingCapitalltem", # OCR 把 Item 识别成 ltem
}
CN_TITLE_FIX = {"其他项目费明细": "SundryCostsItem", "增值稅": "Tax", "增值税": "Tax"}
CN_EXTRA = {
"ProvisionalMaterialEquipmentItem": "材料暂估价明细",
"InitialWorkingCapitalltem": "铺底流动资金明细",
"OtherCost": "扩展项",
"SubdivisionFees": "构成明细",
"IncFees": "子目增加费",
"BidEvaluationMainMaterial": "评标主要材料",
}
def ptitle(t):
t = re.sub(r"\s+", " ", t)
m = re.match(r"^表\s*6\s*[..]\s*(\d+)\s*[..]\s*(\d+)((?:-\d+)?)\s*(.*?)属性定义表", t)
if not m:
return None, None
return "6.%s.%s%s" % (m.group(1), m.group(2), m.group(3)), m.group(4).strip()
def elem_of(rest):
if rest in CN_TITLE_FIX:
return CN_TITLE_FIX[rest]
m = re.search(r"([A-Z][A-Za-z]{2,})", rest)
return m.group(1) if m else rest
def props_of(rows):
out = []
for r in rows:
cs = r["cells"]
if len(cs) > 1:
v = re.sub(r"\s+", "", cs[1])
if re.fullmatch(r"[A-Za-z][A-Za-z0-9]{2,}", v):
out.append(v)
return out
def load_db():
c = sqlite3.connect(DB)
els, props = {}, {}
for r in c.execute("select distinct element from tabs where element is not null and element<>''"):
els[r[0]] = 1
for r in c.execute("""select t.element el, c.std_name sn from columns c join tabs t on t.id=c.tab_id
where t.element is not null and t.element<>'' and c.std_name is not null and c.std_name<>''"""):
props.setdefault(r[0], set()).add(r[1].strip())
return els, props
def cn_names(B):
"""从条文里抽 元素 -> 中文名"""
m = {}
for b in B:
t = b.get("text") or ""
for mm in re.finditer(r"([A-Za-z][A-Za-z]{2,})\s*[((]([\u4e00-\u9fa5、()\-]{2,20})[))]", t):
m.setdefault(mm.group(1), mm.group(2))
for mm in re.finditer(r"([\u4e00-\u9fa5]{2,12})的元素名称\s*([A-Za-z][A-Za-z]{2,})", t):
m.setdefault(mm.group(2), mm.group(1))
return m
def main():
B = json.load(open(BLK, encoding="utf-8"))
els, dbprops = load_db()
CN = cn_names(B)
# 章节 + 表清单
heads = [(re.sub(r"^(6\.[123])\d$", r"\1", b["no"]), b["text"]) for b in B if b["kind"] == "heading"]
tables = []
for b in B:
if b["kind"] == "table":
no, rest = ptitle(b["title"] or "")
tables.append((no, elem_of(rest) if rest else "", b))
lines = []
A = lines.append
A("# 6 工程计价文件")
A("")
A("> **来源**:DBJ/T 15-145-2025《建设工程政府投资项目造价数据标准》(广东省地方标准),2025 版。")
A("> **原文**:4793785.pdf(广东省住房和城乡建设厅发布),第 6 章 = PDF 第 52–146 页 / 印刷页第 44–138 页。")
A("> **转换方式**:该 PDF 为纯扫描件(191 页无文字层),经 300dpi 渲染 + RapidOCR 识别,按版面坐标重建表格。")
A("> **可靠性说明**:中文正文偶有形近字(如“四舍五入”识别为“四舍五保留”)、公式符号有丢失;")
A("> **属性名(英文驼峰)识别准确**,可直接用作字段规范;数值精度、必填列以原文为准。")
A("> 每表末尾“注:”为原文注释,OCR 后已并入正文段落。")
A("")
A("---")
A("")
A("## 目录")
A("")
for no, txt in heads:
A("- **%s %s**" % (no, txt) if no else "- **%s**" % txt)
A("- **附录 A 元素清单与适配判定**")
A("")
A("**属性定义表索引**(共 %d 张)" % len(tables))
A("")
A("| 表号 | 元素 | 属性条数 |")
A("|---|---|---|")
for no, el, b in tables:
A("| %s | %s | %d |" % (no or "—", el or "—", len(b["rows"])))
A("")
A("---")
A("")
# 正文
for b in B:
k = b["kind"]
if k == "heading":
no = b["no"]
if re.fullmatch(r"6\.[123]\d", no):
no = no[:3]
lv = "##" if no.count(".") <= 1 else "###"
A(("%s %s %s" % (lv, no, b["text"])) if no else ("## " + b["text"]))
A("")
elif k == "figure":
A("*%s*" % b["text"])
A("")
elif k == "fignote":
A("> 图内文字(OCR):" + b["text"])
A("")
elif k == "para":
A(b["text"])
A("")
elif k == "table":
A("**%s**" % (b["title"] or "(续表)"))
A("")
cols = b.get("cols") or ["序号", "属性名称", "中文解释", "数据类型", "必填", "备注"]
rows = []
for r in b["rows"]:
cs = list(r["cells"]) + [""] * (len(cols) - len(r["cells"]))
rows.append(cs[: len(cols)])
if cols and cols[0] == "序号" and rows:
if sum(1 for c in rows if not c[0].strip()) * 2 >= len(rows):
for i, c in enumerate(rows, 1):
c[0] = str(i)
A("| " + " | ".join(cols) + " |")
A("|" + "|".join(["---"] * len(cols)) + "|")
for cs in rows:
cs = [x.replace("|", "/").replace("\n", " ") for x in cs]
A("| " + " | ".join(cs) + " |")
A("")
# 附录 A
A("---")
A("")
A("## 附录 A 元素清单与适配判定")
A("")
A("判定口径:本标准 6.2.1 第 3 款规定,施工图预算、招标工程量清单、最高投标限价、投标报价、")
A("签约合同价、过程结算价、竣工结算价七类文件的建设项目,数据内容为**建筑安装工程费**,")
A("子元素为 SystemInfo、ConstructionInfo、SummaryOfCost、ProjectInstallationWorkCost。")
A("故工程费用、设备购置费、工程建设其他费用、预备费、车辆购置费、建设期利息、铺底流动资金")
A("(估算/概算路径)**不纳入**;建安费路径上的全部元素**应纳入**。")
A("")
A("| 表号 | 元素 | 中文名 | 属性条数 | 现有结构 | 判定 |")
A("|---|---|---|---|---|---|")
for no, el, b in tables:
have = "已有" if el in els else "缺"
cn = CN.get(el) or CN_EXTRA.get(el, "")
if el in EST:
jud = "不适用(估算/概算)"
elif el in els:
jud = "已建,需按本表校属性"
else:
jud = "**应补建**"
A("| %s | %s | %s | %d | %s | %s |" % (no or "—", el, cn, len(b["rows"]), have, jud))
A("")
A("> 注:属性条数为 OCR 抽取的英文属性名行数,个别跨行排列的长属性名会被拆成两行,")
A("> 故实际属性数可能比本列多 1–2 条;精确条数以正文表格为准。")
A("")
md = "\n".join(lines)
open(OUT, "w", encoding="utf-8").write(md)
print("md chars", len(md), "tables", len(tables), "heads", len(heads))
return OUT
if __name__ == "__main__":
print(main())

View File

@@ -0,0 +1,33 @@
# -*- coding: utf-8 -*-
"""批量 OCR:PDF 52-146(第6章),逐页增量落盘,可断点续跑"""
import os, json, sys, time
sys.path.insert(0, r"C:\Users\MZ\AppData\Local\Temp\cos4std")
from ocr_page import ocr_page, BASE
OUT = os.path.join(BASE, "ocr_ch6.json")
START, END = 52, 146
data = {}
if os.path.exists(OUT):
try:
data = json.load(open(OUT, encoding="utf-8"))
print("resume, have", len(data))
except Exception:
data = {}
t0 = time.time()
for n in range(START, END + 1):
key = "p%03d" % n
if key in data and data[key]:
continue
try:
data[key] = ocr_page(n)
print("%s ok items=%d %.0fs" % (key, len(data[key]), time.time() - t0), flush=True)
except Exception as e:
print("%s FAIL %s" % (key, e), flush=True)
data[key] = []
if n % 5 == 0:
json.dump(data, open(OUT, "w", encoding="utf-8"), ensure_ascii=False)
json.dump(data, open(OUT, "w", encoding="utf-8"), ensure_ascii=False)
print("done", len(data), "%.0fs" % (time.time() - t0))

View File

@@ -0,0 +1,80 @@
# -*- coding: utf-8 -*-
"""PDF 指定页 -> 300dpi PNG -> RapidOCR -> 行文本 / JSON"""
import sys, os, json, io
import pymupdf
from rapidocr_onnxruntime import RapidOCR
BASE = r"C:\Users\MZ\AppData\Local\Temp\cos4std"
PDF = os.path.join(BASE, "std.pdf")
PG = os.path.join(BASE, "pg2")
_ocr = None
def get_ocr():
global _ocr
if _ocr is None:
_ocr = RapidOCR()
return _ocr
def render(pno, dpi=300):
"""pno: 1-based PDF 页码"""
os.makedirs(PG, exist_ok=True)
out = os.path.join(PG, "p%03d.png" % pno)
if not os.path.exists(out):
d = pymupdf.open(PDF)
d[pno - 1].get_pixmap(dpi=dpi).save(out)
d.close()
return out
def ocr_page(pno):
png = render(pno)
res, _ = get_ocr()(png)
items = []
for box, txt, score in (res or []):
xs = [float(p[0]) for p in box]
ys = [float(p[1]) for p in box]
items.append({"t": txt, "x0": min(xs), "x1": max(xs),
"y0": min(ys), "y1": max(ys), "s": round(float(score), 3)})
return items
def to_lines(items, tol=0.6):
"""按 y 中心聚行,行内按 x 排序"""
its = sorted(items, key=lambda a: (a["y0"], a["x0"]))
lines, cur, cy = [], [], None
for a in its:
c = (a["y0"] + a["y1"]) / 2
h = a["y1"] - a["y0"]
if cy is None or abs(c - cy) <= h * tol:
cur.append(a)
cy = c if not cur[:-1] else (cy + c) / 2
else:
lines.append(sorted(cur, key=lambda z: z["x0"]))
cur, cy = [a], c
if cur:
lines.append(sorted(cur, key=lambda z: z["x0"]))
return lines
if __name__ == "__main__":
nos = []
for a in sys.argv[1:]:
if "-" in a:
s, e = a.split("-")
nos.extend(range(int(s), int(e) + 1))
else:
nos.append(int(a))
allout = {}
for n in nos:
its = ocr_page(n)
allout["p%03d" % n] = its
print("=" * 60, "PDF p%d" % n, "items=%d" % len(its))
for ln in to_lines(its):
print(" " + " || ".join(z["t"] for z in ln))
if len(nos) > 1:
with open(os.path.join(BASE, "ocr_pages.json"), "w", encoding="utf-8") as f:
json.dump(allout, f, ensure_ascii=False)
print("-> ocr_pages.json")

View File

@@ -0,0 +1,231 @@
# -*- coding: utf-8 -*-
"""DBJ/T 15-145-2025 第6章「工程计价文件」OCR -> 结构化 JSON + Markdown
输入: ocr_ch6.json (p052..p146)
输出: ch6_blocks.json / ch6.md
"""
import os, re, json, sys
BASE = r"C:\Users\MZ\AppData\Local\Temp\cos4std"
OCR = os.path.join(BASE, "ocr_ch6.json")
OUT_JSON = os.path.join(BASE, "ch6_blocks.json")
OUT_MD = os.path.join(BASE, "ch6.md")
COLKEYS = ["序号", "属性名称", "中文解释", "数据类型", "必填", "备注"]
PAGENO_RE = re.compile(r"^\d{1,3}$")
BODY_X0 = 224 # 正文左边距(205~220),表格序号列 x>=226
BODY_X1 = 1408 # 正文右边距(1434~1435),表格右边 <=1400
def to_lines(items, tol=0.85):
"""按 y 中心聚行;tol 放大以合并同一单元格内的上下换行"""
its = sorted(items, key=lambda a: (a["y0"], a["x0"]))
lines, cur, cy = [], [], None
for a in its:
c = (a["y0"] + a["y1"]) / 2
h = max(a["y1"] - a["y0"], 1.0)
if cy is None or abs(c - cy) <= h * tol:
cur.append(a)
cy = c if len(cur) == 1 else (cy + c) / 2
else:
lines.append(sorted(cur, key=lambda z: z["x0"]))
cur, cy = [a], c
if cur:
lines.append(sorted(cur, key=lambda z: z["x0"]))
return lines
def text_of(line):
return "".join(z["t"] for z in line).strip()
def spaced(line):
return " ".join(z["t"] for z in line).strip()
def is_pageno(line, page_h):
return len(line) == 1 and bool(PAGENO_RE.match(line[0]["t"].strip())) and line[0]["y0"] > page_h * 0.86
def is_header(line):
t = text_of(line).replace(" ", "")
if "中文解释" in t and ("数据类型" in t or "必填" in t):
return True
return "属性名称" in t and "中文解释" in t
def is_body(line):
if not line:
return False
return line[0]["x0"] < BODY_X0 and line[-1]["x1"] > BODY_X1
def norm_col(name):
n = name.replace(" ", "")
for k in COLKEYS:
if k in n:
return k
return n
def build():
D = json.load(open(OCR, encoding="utf-8"))
pages = {int(k[1:]): v for k, v in D.items()}
blocks = []
cur = None
for pno in sorted(pages):
items = pages[pno]
if not items:
continue
page_h = max(z["y1"] for z in items)
for ln in to_lines(items):
if is_pageno(ln, page_h):
continue
t = text_of(ln)
sp = re.sub(r"\s+", " ", spaced(ln))
plain = re.sub(r"\s+", "", sp)
# 续表标记
m_cont = re.match(r"^续表\s*6\s*[..]?\s*[\d.]*\s*(.*)$", plain)
if m_cont:
continue
# 表标题
if "属性定义表" in plain and len(plain) < 80:
cur = {"kind": "table", "page": pno, "title": sp, "elems": [], "head": None, "rows": []}
blocks.append(cur)
continue
# 图题
if re.match(r"^图\s*6\s*\.\s*\d+", plain) and ("元素关系" in plain or len(plain) < 60):
blocks.append({"kind": "figure", "page": pno, "text": sp})
continue
# 表头
if is_header(ln):
cs = [( (z["x0"] + z["x1"]) / 2.0, norm_col(z["t"])) for z in ln]
cs.sort()
cols = [n for _, n in cs]
if cur is None or cur["head"] is not None:
cur = {"kind": "table", "page": pno, "title": "", "elems": [], "head": cs, "rows": []}
blocks.append(cur)
else:
cur["head"] = cs
cur["cols"] = cols
continue
# 表格行
if cur is not None and cur["head"]:
if is_body(ln) or re.match(r"^注\s*\d*\s*[::]", plain):
cur = None
else:
xs = [c for c, _ in cur["head"]]
bounds = [(xs[i] + xs[i + 1]) / 2 for i in range(len(xs) - 1)] + [1e9]
row = [""] * len(xs)
for z in ln:
c = (z["x0"] + z["x1"]) / 2.0
i = 0
while i < len(bounds) and c > bounds[i]:
i += 1
i = min(i, len(row) - 1)
row[i] = (row[i] + " " + z["t"]).strip() if row[i] else z["t"]
if any(x.strip() for x in row):
cur["rows"].append({"page": pno, "cells": row})
continue
# 章节标题 vs 条文
m = re.match(r"^(6(?:\.\d{1,3}){0,2})\s*(.*)$", plain)
if m and len(plain) <= 26 and not re.search(r"[。;,、:=;]", plain):
blocks.append({"kind": "heading", "page": pno, "no": m.group(1), "text": m.group(2)})
continue
if re.match(r"^附录[A-Z]", plain) and len(plain) <= 30:
blocks.append({"kind": "heading", "page": pno, "no": "", "text": plain})
continue
if plain in ("工程计价文件",):
continue
is_fignote = bool(blocks and blocks[-1]["kind"] == "figure"
and not re.search(r"[。;]", plain) and len(plain) < 320
and not re.match(r"^\d+\.\d+", plain))
if (not is_fignote and blocks and blocks[-1]["kind"] == "para"
and blocks[-1]["page"] == pno
and not re.match(r"^6?\.?\d+\.\d+", plain)):
blocks[-1]["text"] += plain
continue
blocks.append({"kind": "fignote" if is_fignote else "para", "page": pno, "text": plain})
# 合并跨页续表(title 为空的表并入上一张有标题的表)
merged = []
for b in blocks:
if b["kind"] == "table" and not b["title"] and merged and merged[-1]["kind"] == "table":
prev = merged[-1]
if prev.get("title"):
prev["rows"].extend(b["rows"])
continue
merged.append(b)
return merged
def fix_row(cells):
"""修正常见列错位:序号列混入属性名、属性名落在序号列"""
if not cells:
return cells
c0 = (cells[0] or "").strip()
if c0 and not re.fullmatch(r"\d{1,3}", c0):
m = re.match(r"^(\d{1,3})\s+(\S.*)$", c0)
if m:
cells[0], rest = m.group(1), m.group(2)
else:
cells[0], rest = "", c0
if len(cells) > 1:
cells[1] = (rest + " " + cells[1]).strip() if cells[1].strip() else rest
if len(cells) > 2 and cells[1].strip() and not re.search(r"[A-Za-z]", cells[1]) and not cells[2].strip():
cells[1], cells[2] = "", cells[1]
return cells
def to_md(B):
out = ["# 6 工程计价文件", ""]
for b in B:
if b["kind"] == "fignote":
out.append("> 图内文字(OCR):" + b["text"])
out.append("")
elif b["kind"] == "heading":
if re.fullmatch(r"6\.[123]\d", b["no"]):
b["no"] = b["no"][:3]
lv = "##" if b["no"].count(".") <= 1 else "###"
out.append("%s %s %s" % (lv, b["no"], b["text"]) if b["no"] else "## " + b["text"])
out.append("")
elif b["kind"] == "figure":
out.append("*%s*" % b["text"])
out.append("")
elif b["kind"] == "para":
out.append(b["text"])
out.append("")
elif b["kind"] == "table":
out.append("**%s**" % (b["title"] or "(续表)"))
out.append("")
cols = b.get("cols") or COLKEYS[: len(b["rows"][0]["cells"]) if b["rows"] else 6]
rows = [fix_row(list(r["cells"])) + [""] * (len(cols) - len(r["cells"])) for r in b["rows"]]
rows = [c[: len(cols)] for c in rows]
if cols and cols[0] == "序号" and rows:
blank = sum(1 for c in rows if not c[0].strip())
if blank * 2 >= len(rows):
for i, c in enumerate(rows, 1):
c[0] = str(i)
out.append("| " + " | ".join(cols) + " |")
out.append("|" + "|".join(["---"] * len(cols)) + "|")
for cs in rows:
cs = [c.replace("|", "/").replace("\n", " ") for c in cs]
out.append("| " + " | ".join(cs) + " |")
out.append("")
return "\n".join(out)
if __name__ == "__main__":
B = build()
json.dump(B, open(OUT_JSON, "w", encoding="utf-8"), ensure_ascii=False, indent=1)
md = to_md(B)
open(OUT_MD, "w", encoding="utf-8").write(md)
ntab = sum(1 for b in B if b["kind"] == "table")
print("blocks", len(B), "tables", ntab, "md chars", len(md))
for b in B:
if b["kind"] == "table":
print(" TBL p%-4d rows=%-3d %s" % (b["page"], len(b["rows"]), b["title"][:60]))