Files
pricing_review/AdminCost/参考资料/规范与COS4/scripts/parse_ch6_2025.py

232 lines
8.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- 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]))