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

View File

@@ -737,14 +737,17 @@ def rows_of(conn, tab_id):
def sheet_payload(conn, tab_id):
if conn.execute("SELECT id FROM tabs WHERE id = ?", (tab_id,)).fetchone() is None:
tab_row = conn.execute(
"SELECT id, element FROM tabs WHERE id = ?", (tab_id,)
).fetchone()
if tab_row is None:
raise AppError(404, "标签不存在")
# 打开工作区时再对一次:行的多少 / 顺序 / 后缀名永远跟后缀设置一致
if sync_rows_to_suffixes(conn):
conn.commit()
columns = []
for r in conn.execute(
"SELECT id, name, kind, width FROM columns WHERE tab_id = ?"
"SELECT id, name, kind, width, std_name FROM columns WHERE tab_id = ?"
" ORDER BY sort_order ASC, id ASC",
(tab_id,),
):
@@ -754,7 +757,8 @@ def sheet_payload(conn, tab_id):
"name": r["name"],
"kind": r["kind"],
"width": r["width"],
"locked": r["kind"] in ("index", "suffix", "anchor", "action", "anchorline"),
"stdName": r["std_name"] or "",
"locked": r["kind"] in ("index", "suffix", "action", "anchorline"),
"hasValues": has_value(conn, r["id"])
if r["kind"] in ("custom", "anchor")
else False,
@@ -786,7 +790,14 @@ def sheet_payload(conn, tab_id):
):
if r["value"]:
cells["%d:%d" % (r["col_id"], r["row_id"])] = r["value"]
return {"tabId": tab_id, "columns": columns, "groups": groups, "rows": rows, "cells": cells}
return {
"tabId": tab_id,
"element": tab_row["element"] or "",
"columns": columns,
"groups": groups,
"rows": rows,
"cells": cells,
}
# ---------------------------------------------------------------- 业务逻辑
@@ -834,9 +845,10 @@ def build_state():
"parentId": r["parent_id"],
"nodeKind": r["node_kind"],
"collapsed": bool(r["collapsed"]),
"element": r["element"] or "",
}
for r in conn.execute(
"SELECT id, name, is_fixed, parent_id, node_kind, collapsed FROM tabs"
"SELECT id, name, is_fixed, parent_id, node_kind, collapsed, element FROM tabs"
" ORDER BY is_fixed DESC, sort_order ASC, id ASC"
)
]

View File

@@ -307,6 +307,20 @@
.wrap.sheet-view{gap:0;}
.sheet-bar{display:flex;align-items:center;gap:12px;margin:0 0 6px;min-height:30px;}
.sheet-bar .spacer{margin-left:auto;}
.sheet-bar .view-sw{display:inline-flex;}
.sheet-bar .btn.on{border-color:#2b6cb8;color:#1d4e89;background:#eaf2fd;}
/* 字段对照矩阵 */
table.sheet.mx td.mx-std{color:#6b7280;font-size:12px;white-space:nowrap;}
td.mx-cell{cursor:text;min-width:110px;height:28px;}
td.mx-cell[contenteditable="true"]{outline:2px solid #2b6cb8;background:#fff;}
td.mx-cell .mx-empty{color:#c9cfd8;}
/* 值设置弹框 */
.val-pick{margin:8px 0 4px;font-size:13px;}
.val-pick select{font:inherit;padding:2px 6px;}
.val-grid{max-height:52vh;overflow:auto;border:1px solid #e3e7ee;margin-top:6px;}
.val-grid table{border-collapse:collapse;width:100%;}
.val-grid th,.val-grid td{border-bottom:1px solid #eef1f5;padding:5px 8px;font-size:13px;text-align:left;white-space:nowrap;}
.val-grid input{width:110px;font:inherit;padding:2px 6px;border:1px solid #d5dae2;}
.sheet-rule{height:2px;border-radius:1px;background:var(--accent);margin:0 0 5px;}
.save-flag{font-size:12px;color:#15803d;opacity:0;transition:opacity .25s;}
.save-flag.show{opacity:1;}
@@ -618,6 +632,19 @@
</div>
</div>
<div class="mask" id="valMask" hidden>
<div class="modal tab-order-modal">
<h3>值设置(按后缀 / 省份分别配)</h3>
<div class="to-hint">同一个值列,每个后缀(省份格式)可以配各自的锚点和值,防止各省枚举不统一;留空=该后缀不设值。</div>
<div class="val-pick"><label>值列:</label><select id="valCol"></select></div>
<div class="val-grid" id="valGrid"></div>
<div class="modal-actions">
<button class="btn primary" id="valOk" type="button">保存</button>
<button class="btn ghost" id="valClose" type="button">取消</button>
</div>
</div>
</div>
<div class="mask" id="confirmMask" hidden>
<div class="modal confirm-modal">
<h3 id="confirmTitle">确认操作</h3>
@@ -667,6 +694,11 @@
tabOrderClose: document.getElementById("tabOrderClose"),
colOrderMask: document.getElementById("colOrderMask"),
colOrderList: document.getElementById("colOrderList"),
valMask: document.getElementById("valMask"),
valCol: document.getElementById("valCol"),
valGrid: document.getElementById("valGrid"),
valOk: document.getElementById("valOk"),
valClose: document.getElementById("valClose"),
colOrderClose: document.getElementById("colOrderClose"),
confirmMask: document.getElementById("confirmMask"),
confirmTitle: document.getElementById("confirmTitle"),
@@ -1157,7 +1189,7 @@
/* ---------------- 标签页表格 ---------------- */
var COL_DEFAULT_W = { index: 54, suffix: 190, action: 84, anchorline: 90 };
var COL_DEFAULT_W = { index: 54, suffix: 190, action: 84, anchorline: 200 };
function colWidth(c) {
if (!c) return 0;
@@ -1326,6 +1358,223 @@
.catch(function (err) { toast(err.message, true); });
}
/* ---------------- 字段对照视图 + 值设置 ---------------- */
var VIEW = { mode: localStorage.getItem("adminCostViewMode") || "table", maps: null, mapIdx: {} };
var MX = { td: null };
var VS = { colId: null, busy: false };
function mxKey(elName, std, sf) { return elName + "\u0001" + std + "\u0001" + sf; }
function loadMappings(force) {
if (VIEW.maps && !force) return Promise.resolve();
return api("/api/mappings").then(function (list) {
VIEW.maps = list || [];
VIEW.mapIdx = {};
VIEW.maps.forEach(function (m) {
VIEW.mapIdx[mxKey(m.element, m.stdField, m.sourceSystem)] = m;
});
});
}
function setViewMode(mode) {
if (VIEW.mode === mode) { renderSheet(); return; }
VIEW.mode = mode;
localStorage.setItem("adminCostViewMode", mode);
renderSheet();
}
function sheetBarHtml() {
var sh = S.sheet;
var sw = sh && sh.element
? '<span class="view-sw">' +
'<button class="btn ghost small' + (VIEW.mode !== "matrix" ? " on" : "") +
'" type="button" data-act="view-table">属性表</button>' +
'<button class="btn ghost small' + (VIEW.mode === "matrix" ? " on" : "") +
'" type="button" data-act="view-matrix">字段对照</button>' +
"</span>"
: "";
return '<div class="sheet-bar">' +
sw +
'<span class="spacer"></span>' +
'<span class="save-flag" id="saveFlag">已保存</span>' +
'<button class="btn ghost small" type="button" data-act="add-col">+ 添加列</button>' +
'<button class="btn ghost small" type="button" data-act="col-order" ' +
'title="调整列的左右顺序">列排序</button>' +
'<button class="btn ghost small" type="button" data-act="val-set" ' +
'title="按后缀(省份)分别配置锚点+值,防止各省枚举不统一">值设置</button>' +
"</div>";
}
function renderMatrix() {
var sh = S.sheet;
if (!sh) return;
if (!VIEW.maps) {
el.content.classList.add("sheet-mode");
el.content.innerHTML = '<div class="wrap sheet-view">' + sheetBarHtml() +
'<div class="sheet-rule"></div><div class="sheet-wrap">' +
'<div class="to-empty">对照数据加载中…</div></div></div>';
loadMappings(true).then(function () {
if (VIEW.mode === "matrix") renderMatrix();
});
return;
}
var sfx = (sh.rows || []).map(function (r) { return { name: r.name }; });
var cols = (sh.columns || []).filter(function (c) {
return c.kind === "custom" || c.kind === "anchor";
});
var head = "<tr><th>属性(中文名)</th><th>英文属性</th>" +
sfx.map(function (x) { return "<th>" + esc(x.name) + "</th>"; }).join("") + "</tr>";
var body = cols.map(function (c) {
var std = c.stdName || "";
var tds = sfx.map(function (x) {
var m = VIEW.mapIdx[mxKey(sh.element, std, x.name)];
var v = m ? (m.sourcePath || "") : "";
return '<td class="mx-cell" tabindex="0" data-el="' + esc(sh.element) +
'" data-std="' + esc(std) + '" data-sf="' + esc(x.name) +
'" data-mid="' + (m ? m.id : "") + '" data-orig="' + esc(v) +
'" title="点击填写「' + esc(x.name) + '」里这个字段的叫法">' +
(v ? esc(v) : '<span class="mx-empty">+</span>') + "</td>";
}).join("");
return "<tr><td>" + esc(c.name) + '</td><td class="mx-std">' + esc(std) + "</td>" + tds + "</tr>";
}).join("");
el.content.classList.add("sheet-mode");
el.content.innerHTML = '<div class="wrap sheet-view">' + sheetBarHtml() +
'<div class="sheet-rule"></div>' +
'<div class="sheet-wrap"><table class="sheet mx"><thead>' + head + "</thead><tbody>" +
(body || '<tr><td colspan="9" class="to-empty">这个标签还没有可对照的属性列。</td></tr>') +
"</tbody></table></div></div>";
}
function mxPaint(td, text, mid) {
td.setAttribute("data-orig", text);
if (mid !== null) td.setAttribute("data-mid", mid);
td.innerHTML = text ? esc(text) : '<span class="mx-empty">+</span>';
}
function mxEdit(td) {
if (!td.getAttribute("data-std")) { toast("这一列没有英文属性名,不能对照", true); return; }
if (MX.td === td) return;
mxCommit();
if (MX.td) return;
MX.td = td;
td.textContent = td.getAttribute("data-orig") || "";
td.contentEditable = "true";
td.focus();
}
function mxCommit() {
var td = MX.td;
if (!td) return;
MX.td = null;
td.contentEditable = "false";
var text = (td.textContent || "").trim();
var orig = td.getAttribute("data-orig") || "";
var mid = td.getAttribute("data-mid") || "";
if (text === orig) { mxPaint(td, orig, null); return; }
if (!text && !mid) { mxPaint(td, "", null); return; }
var key = mxKey(td.getAttribute("data-el"), td.getAttribute("data-std"), td.getAttribute("data-sf"));
var call;
if (!text && mid) call = api("/api/mappings/" + mid, { method: "DELETE" }).then(function () { return ""; });
else if (mid) call = api("/api/mappings/" + mid, { method: "PATCH", body: { sourcePath: text } }).then(function () { return mid; });
else call = api("/api/mappings", { method: "POST", body: {
element: td.getAttribute("data-el"),
stdField: td.getAttribute("data-std"),
sourceSystem: td.getAttribute("data-sf"),
sourcePath: text
} }).then(function (res) { return res.id; });
call.then(function (newMid) {
if (text) {
var m = VIEW.mapIdx[key] || {};
m.id = newMid;
m.element = td.getAttribute("data-el");
m.stdField = td.getAttribute("data-std");
m.sourceSystem = td.getAttribute("data-sf");
m.sourcePath = text;
VIEW.mapIdx[key] = m;
} else {
delete VIEW.mapIdx[key];
}
mxPaint(td, text, text ? newMid : "");
toast("已保存");
}).catch(function (err) {
mxPaint(td, orig, mid || "");
toast(err.message, true);
});
}
function openValSet() {
var sh = S.sheet;
if (!sh) { toast("先打开一个标签页", true); return; }
var vcols = (sh.columns || []).filter(function (c) { return isValueCol(c); });
if (!vcols.length) { toast("这个标签还没有「值列」(设了值标记的字段列)", true); return; }
VS.colId = vcols[0].id;
el.valCol.innerHTML = vcols.map(function (c) {
return '<option value="' + c.id + '">' + esc(c.name) + "</option>";
}).join("");
renderValGrid();
el.valMask.hidden = false;
}
function renderValGrid() {
var sh = S.sheet;
var rows = (sh && sh.rows) || [];
el.valGrid.innerHTML = "<table><thead><tr><th>后缀</th><th>锚点</th><th>值</th><th>存的是</th></tr></thead><tbody>" +
rows.map(function (r) {
var raw = (sh.cells || {})[VS.colId + ":" + r.suffixId] || "";
var p = parseValCell(raw);
return '<tr data-sid="' + r.suffixId + '" data-a0="' + esc(p.a) + '" data-v0="' + esc(p.v) + '">' +
"<td>" + esc(r.name) + "</td>" +
'<td><input data-part="a" value="' + esc(p.a) + '" placeholder="如 Kind"></td>' +
'<td><input data-part="v" value="' + esc(p.v) + '" placeholder="如 1"></td>' +
'<td class="val-cur">' + (raw ? esc(raw) : "") + "</td></tr>";
}).join("") + "</tbody></table>";
}
function saveValSet() {
if (VS.busy) return;
var sh = S.sheet, cid = String(VS.colId);
var trs = el.valGrid.querySelectorAll("tbody tr");
var jobs = [];
for (var i = 0; i < trs.length; i++) {
var tr = trs[i];
var a = tr.querySelector('[data-part="a"]').value.trim();
var v = tr.querySelector('[data-part="v"]').value.trim();
if (a === tr.getAttribute("data-a0") && v === tr.getAttribute("data-v0")) continue;
jobs.push({
sid: parseInt(tr.getAttribute("data-sid"), 10),
str: (!a && !v) ? "" : JSON.stringify({ a: a, v: v })
});
}
if (!jobs.length) { el.valMask.hidden = true; return; }
VS.busy = true;
el.valOk.disabled = true;
var chain = Promise.resolve();
jobs.forEach(function (j) {
var vals = {};
vals[cid] = j.str;
chain = chain.then(function () {
return api("/api/cells/batch", {
method: "POST",
body: { suffix_id: j.sid, values: vals }
}).then(function () {
S.sheet.cells[cid + ":" + j.sid] = j.str;
});
});
});
chain.then(function () {
VS.busy = false;
el.valOk.disabled = false;
el.valMask.hidden = true;
renderSheet();
toast("值设置已保存(" + jobs.length + " 个后缀)");
}).catch(function (err) {
VS.busy = false;
el.valOk.disabled = false;
toast(err.message, true);
});
}
/* ---------------- 统一确认弹框 ---------------- */
var CF = { resolve: null };
@@ -1404,11 +1653,13 @@
(editing ? "再点一次退出编辑" : "点这里开始编辑,然后双击单元格") + '">编辑</button></td>';
} else {
var val = s.cells[c.id + ":" + r.suffixId] || "";
if (c.kind === "anchorline") val = r.anchor ? "1" : "";
if (c.kind === "anchorline") val = r.anchor ? (s.element || "1") : "";
var extra = c.kind === "anchorline" ? " c-anchorline-cell" : "";
var vcol = isValueCol(c);
var tip = vcol ? "双击编辑「" + esc(c.name) + "」(锚点 / 值)"
: "双击编辑「" + esc(c.name) + "」";
var tip = c.kind === "anchorline"
? "点击切换锚定:锚定后这里显示节点名,左侧目录生成记录行"
: vcol ? "双击编辑「" + esc(c.name) + "」(锚点 / 值)"
: "双击编辑「" + esc(c.name) + "」";
tr += '<td class="c-cell' + extra + (vcol ? " c-value-cell" : "") + '"' + cid + st +
' data-cell-col="' + c.id + '" data-cell-suffix="' + r.suffixId + '"' +
(c.kind === "anchorline"
@@ -1427,6 +1678,7 @@
var tab = activeTab();
var s = S.sheet;
if (!tab || !s) { el.content.innerHTML = ""; return; }
if (VIEW.mode === "matrix" && s.element) { renderMatrix(); return; }
var cols = s.columns;
var colCount = cols.length;
@@ -1484,13 +1736,7 @@
el.content.classList.add("sheet-mode");
el.content.innerHTML = '<div class="wrap sheet-view">' +
'<div class="sheet-bar">' +
'<span class="spacer"></span>' +
'<span class="save-flag" id="saveFlag">已保存</span>' +
'<button class="btn ghost small" type="button" data-act="add-col">+ 添加列</button>' +
'<button class="btn ghost small" type="button" data-act="col-order" ' +
'title="调整列的左右顺序">列排序</button>' +
"</div>" +
sheetBarHtml() +
'<div class="sheet-rule"></div>' +
'<div class="sheet-wrap"><table class="sheet' + (fillGap ? " auto-w" : "") +
'"><thead><tr>' + head + "</tr></thead><tbody>" + body + "</tbody></table></div>" +
@@ -2330,6 +2576,9 @@
if (kind === "add-group") openModal("addGroup");
else if (kind === "add-col") openModal("addColumn");
else if (kind === "col-order") openColOrder();
else if (kind === "view-table") setViewMode("table");
else if (kind === "view-matrix") setViewMode("matrix");
else if (kind === "val-set") openValSet();
return;
}
@@ -2561,6 +2810,32 @@
parseInt(mv.getAttribute("data-dir"), 10));
});
/* 值设置弹框 + 字段对照矩阵的编辑事件 */
el.valCol.addEventListener("change", function () {
VS.colId = parseInt(this.value, 10);
renderValGrid();
});
el.valOk.addEventListener("click", saveValSet);
el.valClose.addEventListener("click", function () { el.valMask.hidden = true; });
el.valMask.addEventListener("mousedown", function (e) {
if (e.target === el.valMask) el.valMask.hidden = true;
});
el.content.addEventListener("click", function (e) {
var td = e.target.closest("td.mx-cell");
if (td) { mxEdit(td); return; }
if (MX.td) mxCommit();
});
el.content.addEventListener("keydown", function (e) {
if (!MX.td) return;
if (e.key === "Enter") { e.preventDefault(); mxCommit(); }
else if (e.key === "Escape") {
var td = MX.td;
MX.td = null;
td.contentEditable = "false";
mxPaint(td, td.getAttribute("data-orig") || "", null);
}
});
el.confirmOk.addEventListener("click", function () { closeConfirm(true); });
el.confirmCancel.addEventListener("click", function () { closeConfirm(false); }); el.confirmMask.addEventListener("mousedown", function (e) {
if (e.target === el.confirmMask) closeConfirm(false);

1
AdminCost/state.json Normal file

File diff suppressed because one or more lines are too long

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]))