"""
edkb_system/skills/clean.py
用途:对 loader/OCR 产出的 markdown 做去重、排版与图注附着等清洗。
依赖:edkb_system.contracts.Context。
逻辑:由 controller 在 blocks→markdown 之后调用;需保留手册页图「图中文字」。
"""
from __future__ import annotations
import base64
import re
from collections import Counter
from edkb_system.contracts import Context
def _dedupe_repeated_headers(lines: list[str]) -> list[str]:
header_patterns = [
re.compile(
r"^(?P
\s*制定部门.+?制/修订日期.+?页码\s*\d+\s*/\s*\d+)(?P.*)$"
),
re.compile(
r"^(?P\s*文件编号\s+.+?文件级别\s+.+?版本\s+.+?)(?P.*)$"
),
re.compile(r"^(?P\s*注:文件在系统签核完成日即为生效日\s*)(?P.*)$"),
]
seen: dict[int, bool] = {}
out: list[str] = []
for ln in lines:
s = ln.rstrip("\n")
handled = False
for i, p in enumerate(header_patterns):
m = p.match(s)
if not m:
continue
rest = (m.group("rest") or "").strip()
if seen.get(i):
if rest:
out.append(rest)
handled = True
break
seen[i] = True
if m.group("head"):
out.append(m.group("head").strip())
if rest:
out.append(rest)
handled = True
break
if not handled:
out.append(ln)
return out
def _join_cross_page_broken_lines(lines: list[str]) -> list[str]:
out: list[str] = []
i = 0
while i < len(lines):
cur = lines[i]
if i + 2 < len(lines):
nxt = lines[i + 1]
nxt2 = lines[i + 2]
if (
not nxt.strip()
and cur.strip()
and nxt2.strip()
and re.search(r"[\u4e00-\u9fff]$", cur.strip())
and re.match(r"^[\u4e00-\u9fff]", nxt2.strip())
and not re.match(r"^\d+\.\d", nxt2.strip())
):
out.append(cur.rstrip() + nxt2.lstrip())
i += 3
continue
out.append(cur)
i += 1
return out
def _split_inline_headings(text: str) -> str:
out_lines: list[str] = []
for ln in text.splitlines():
s = ln.strip()
if not s or s.startswith("|"):
out_lines.append(ln)
continue
ln = re.sub(r"\s+(?=[一二三四五六七八九十]+、)", "\n", ln)
ln = re.sub(r"(? str:
m_start = re.search(r"五、作业流程图", text)
if not m_start:
return text
start = m_start.start()
m_end = re.search(r"(?:\n|\s)六、作业内容", text[start:])
if not m_end:
return text
end = start + m_end.start()
if end <= start:
return text
section = text[start:end]
row_hits = re.findall(r"(?m)^\s*([1-6])\s+.+$", section)
if len(set(row_hits)) < 4:
return text
branch_proc = "不合格控制程序"
if re.search(r"不合格控制程序", section):
branch_proc = "不合格控制程序"
elif re.search(r"NG控制程序", section):
branch_proc = "NG控制程序"
flow_names = {
"1": "备料",
"2": "取样",
"3": "资料确认",
"4": "品质检验",
"5": "判定",
"6": "产品出货",
}
lines: list[str] = [
"五、作业流程图",
"| 序号 | 流程说明 | 责任部门 | 相关记录 |",
"| --- | --- | --- | --- |",
]
for n in ["1", "2", "3", "4", "5", "6"]:
dept = "品保部 OQC" if n in {"2", "3", "4", "5"} else "仓储课"
if n == "1":
record = "出货通知单"
elif n == "2":
record = "出货通知单"
elif n in {"3", "4"}:
record = "出货检验记录"
elif n == "5":
record = "出货检验记录;重工流程单;纠正与预防处理单"
else:
record = "送货单"
lines.append(f"| {n} | {flow_names[n]} | {dept} | {record} |")
lines.extend(
[
"",
"流程分支:",
f"- 判定 = NG:依《{branch_proc}》执行,并回到前序处理。",
"- 判定 = OK:产品出货。",
"",
]
)
replacement = "\n".join(lines)
text = text[:start] + replacement + text[end:]
text = re.sub(
r"\s*(?:NG品|不合格品)\s*NG\s*OK\s*备料\s*资料确认\s*产品出货\s*取样\s*依\s*《?(?:NG控制程序|不合格控制程序|NG控制程\s*序|不合格控制程\s*序)》?\s*执行\s*判定\s*品质检验",
"",
text,
)
return text
def _normalize_revision_history_table(text: str) -> str:
title_pos = text.find("文件修订履历")
if title_pos < 0:
return text
line_start = text.rfind("\n", 0, title_pos) + 1
line_prefix = text[line_start:title_pos].strip()
start = line_start
tail = text[start:]
m_end = re.search(r"\n制定部门[^\n]*页码\s*2\s*/\s*5|\n一、目的", tail)
if m_end:
end = start + m_end.start()
else:
end = min(len(text), start + 1200)
section = text[start:end]
if "| 日期 | 修订章节 |" in section:
return text
date_matches = list(re.finditer(r"\d{4}/\d{1,2}/\d{1,2}", section))
if not date_matches:
return text
chunks: list[str] = []
for i, m in enumerate(date_matches):
chunk_start = m.start()
chunk_end = (
date_matches[i + 1].start() if i + 1 < len(date_matches) else len(section)
)
chunks.append(section[chunk_start:chunk_end])
rows: list[tuple[str, str, str, str, str]] = []
for ch in chunks:
s = " ".join(ch.split())
s = re.sub(r"^日期\s+修订章节\s+主要修订内容\s+版本\s+修改人\s+备注\s*", "", s)
m = re.match(
r"(?P\d{4}/\d{1,2}/\d{1,2})\s+(?P\S+)\s+(?P.+?)\s+(?PV\d+(?:\.\d+)?)\s+(?P\S+)$",
s,
)
if not m:
continue
rows.append(
(
m.group("date"),
m.group("section"),
m.group("content"),
m.group("version"),
m.group("editor"),
)
)
if not rows:
return text
lines = [
"文件修订履历",
"| 日期 | 修订章节 | 主要修订内容 | 版本 | 修改人 | 备注 |",
"| --- | --- | --- | --- | --- | --- |",
]
for d, sec, content, ver, editor in rows:
lines.append(f"| {d} | {sec} | {content} | {ver} | {editor} | |")
replacement = "\n".join(lines)
if line_prefix:
replacement = line_prefix + "\n" + replacement
return text[:start] + replacement + "\n\n" + text[end:]
def _normalize_revision_history_loose(text: str) -> str:
m_head = re.search(
r"(?m)^\s*日期\s+修订章节\s+主要修订内容\s+版本\s+修改人\s+备注(?:\s+.*)?$",
text,
)
if not m_head:
return text
start = m_head.start()
tail = text[start:]
m_end = re.search(r"(?m)^\s*[一二三四五六七八九十]+、", tail)
end = start + m_end.start() if m_end else len(text)
section = text[start:end]
date_matches = list(re.finditer(r"\d{4}/\d{1,2}/\d{1,2}", section))
if not date_matches:
return text
rows: list[tuple[str, str, str, str, str]] = []
for i, m in enumerate(date_matches):
d = m.group(0)
chunk_start = m.start()
chunk_end = (
date_matches[i + 1].start() if i + 1 < len(date_matches) else len(section)
)
chunk = " ".join(section[chunk_start:chunk_end].split())
body = chunk[len(d) :].strip()
if not body:
continue
version_matches = list(re.finditer(r"V\d+(?:\.\d+)?", body))
version = version_matches[-1].group(0) if version_matches else ""
if version_matches:
vm = version_matches[-1]
left = body[: vm.start()].strip()
right = body[vm.end() :].strip()
else:
left = body
right = ""
editor = right.split()[0] if right else ""
left_tokens = left.split()
sec = left_tokens[0] if left_tokens else ""
content = " ".join(left_tokens[1:]).strip() if len(left_tokens) > 1 else left
if not content:
content = left
rows.append((d, sec, content, version, editor))
if not rows:
return text
lines = [
"文件修订履历",
"| 日期 | 修订章节 | 主要修订内容 | 版本 | 修改人 | 备注 |",
"| --- | --- | --- | --- | --- | --- |",
]
for d, sec, content, ver, editor in rows:
lines.append(f"| {d} | {sec} | {content} | {ver} | {editor} | |")
replacement = "\n".join(lines)
return text[:start] + replacement + "\n\n" + text[end:]
def _normalize_related_forms_table(text: str) -> str:
m_title = re.search(r"([一二三四五六七八九十]+、相关表单[::]?)", text)
if not m_title:
return text
start = m_title.start()
title = m_title.group(1)
tail = text[start:]
if re.search(r"\|\s*表单编号\s*\|", tail):
return text
head = re.search(r"表单编号\s+.+", tail)
if not head:
return text
section_start = start + head.start()
section = text[section_start:]
rows: list[tuple[str, str, str, str]] = []
for raw in section.splitlines()[1:20]:
s = " ".join(raw.split())
if not s:
continue
if re.match(r"^[一二三四五六七八九十]+、", s):
if rows:
break
continue
toks = s.split()
if len(toks) < 3:
continue
i = -1
for idx, tok in enumerate(toks[1:], start=1):
if tok.endswith("部") or tok in {
"品保部",
"人事部",
"采购部",
"工程部",
"生产部",
}:
i = idx
break
if i <= 1:
continue
form_id = toks[0]
name = " ".join(toks[1:i]).strip()
dept = toks[i]
remark = " ".join(toks[i + 1 :]).strip()
if not form_id or not name:
continue
rows.append((form_id, name, dept, remark))
if not rows:
return text
lines = [
title.rstrip("::"),
"| 表单编号 | 记录名称 | 保管部门 | 备注 |",
"| --- | --- | --- | --- |",
]
for form_id, name, dept, remark in rows:
lines.append(f"| {form_id} | {name} | {dept} | {remark} |")
replacement = "\n".join(lines)
return text[:start] + replacement + "\n"
def _tighten_numbered_spacing(text: str) -> str:
lines = text.splitlines()
out: list[str] = []
num_pat = re.compile(r"^\s*\d+(?:\.\d+){1,4}(?:\s+|[\u4e00-\u9fff((])")
for i, ln in enumerate(lines):
if not ln.strip() and out:
j = i + 1
nxt = ""
while j < len(lines):
if lines[j].strip():
nxt = lines[j]
break
j += 1
prev = out[-1]
if num_pat.match(prev.strip()) and num_pat.match(nxt.strip()):
continue
out.append(ln)
return "\n".join(out)
def _tighten_alpha_list_spacing(text: str) -> str:
lines = text.splitlines()
out: list[str] = []
alpha_pat = re.compile(r"^[a-zA-Z]\)\s+")
for i, ln in enumerate(lines):
if not ln.strip() and out:
prev = out[-1].strip()
j = i + 1
nxt = ""
while j < len(lines):
if lines[j].strip():
nxt = lines[j].strip()
break
j += 1
if alpha_pat.match(prev) and alpha_pat.match(nxt):
continue
out.append(ln)
return "\n".join(out)
def _remove_soft_blank_lines(text: str) -> str:
lines = text.splitlines()
out: list[str] = []
def is_heading(s: str) -> bool:
return bool(
re.match(r"^[一二三四五六七八九十]+、", s)
or re.match(r"^\d+(?:\.\d+){0,4}(?:\s+|[\u4e00-\u9fff((])", s)
or re.match(r"^[a-zA-Z]\.\s*", s)
or s.startswith("#")
)
for i, ln in enumerate(lines):
if ln.strip():
out.append(ln)
continue
prev = out[-1].strip() if out else ""
j = i + 1
nxt = ""
while j < len(lines):
if lines[j].strip():
nxt = lines[j].strip()
break
j += 1
if not prev or not nxt:
continue
if prev.startswith("|") or nxt.startswith("|"):
out.append(ln)
continue
if (prev.startswith("-") or prev.startswith("*")) and is_heading(nxt):
out.append(ln)
continue
if re.match(r"^[a-zA-Z]\.\s*", prev) or re.match(r"^[a-zA-Z]\.\s*", nxt):
continue
if is_heading(prev) or is_heading(nxt):
continue
# otherwise drop soft blank line
return "\n".join(out)
def _normalize_basic_headings(text: str) -> str:
mapping = {
"目的": "一、目的",
"范围": "二、范围",
"定义": "三、定义",
"职责": "三、职责",
"权责": "四、权责",
"相关文件": "五、相关文件",
"作业内容": "五、作业内容",
}
out: list[str] = []
keys = ["目的", "范围", "定义", "职责", "权责", "相关文件", "作业内容"]
for ln in text.splitlines():
s = ln.strip()
if s in mapping:
out.append(mapping[s])
continue
handled = False
for k in keys:
if s.startswith(k) and not re.match(r"^[一二三四五六七八九十]+、", s):
rest = s[len(k) :].strip()
out.append(mapping[k])
if rest:
out.append(rest)
handled = True
break
if not handled:
out.append(ln)
return "\n".join(out)
def _normalize_doc_meta_lines(text: str) -> str:
lines = text.splitlines()
out: list[str] = []
for ln in lines:
s = " ".join(ln.split())
if (
out
and re.search(r"版本\s+[Vv]$", out[-1].strip())
and re.match(r"^\d+(?:\.\d+)?$", s)
):
out[-1] = out[-1].rstrip() + s
continue
m = re.match(
r"^(?P[^\s].*?)(?P文件编号\s+\S+\s+文件级别\s+\S+\s+版本\s+\S.*)$",
s,
)
if m and m.group("title") and m.group("meta"):
title = m.group("title").strip()
meta = m.group("meta").strip()
if title and title != "文件":
out.append(title)
out.append(meta)
continue
out.append(ln)
return "\n".join(out)
def _dedupe_top_title_lines(text: str) -> str:
lines = text.splitlines()
idxs = [i for i, ln in enumerate(lines) if ln.strip()][:8]
if len(idxs) < 2:
return text
def norm(s: str) -> str:
s = s.strip().lower()
s = re.sub(r"\s+", "", s)
s = re.sub(r"[^\w\u4e00-\u9fff]+", "", s)
return s
base = norm(lines[idxs[0]])
remove: list[int] = []
for i in idxs[1:]:
s = norm(lines[i])
if s and (s == base or s in base or base in s):
remove.append(i)
for i in reversed(remove):
lines.pop(i)
return "\n".join(lines)
def _normalize_doc_meta_table(text: str) -> str:
lines = text.splitlines()
idx_meta = next(
(
i
for i, ln in enumerate(lines)
if "文件编号" in ln and "文件级别" in ln and "版本" in ln
),
None,
)
idx_dept = next(
(
i
for i, ln in enumerate(lines)
if "制定部门" in ln and "制/修订日期" in ln and "页码" in ln
),
None,
)
if idx_meta is None or idx_dept is None:
return text
m1 = re.search(
r"文件编号\s*(\S+)\s*文件级别\s*(\S+)\s*版本\s*(\S+)",
" ".join(lines[idx_meta].split()),
)
m2 = re.search(
r"制定部门\s*(\S+)\s*制/修订日期\s*([0-9./-]+)\s*页码\s*([0-9]+\s*/\s*[0-9]+)",
" ".join(lines[idx_dept].split()),
)
if not m1 or not m2:
return text
block = [
f"| 文件编号 | {m1.group(1)} | 文件级别 | {m1.group(2)} | 版本 | {m1.group(3)} |",
"| --- | --- | --- | --- | --- | --- |",
f"| 制定部门 | {m2.group(1)} | 制/修订日期 | {m2.group(2)} | 页码 | {m2.group(3)} |",
]
lo, hi = sorted([idx_meta, idx_dept])
out = lines[:lo] + block + lines[hi + 1 :]
cleaned: list[str] = []
for ln in out:
s = " ".join(ln.split())
if not ln.strip().startswith("|") and (
("文件编号" in s and "文件级别" in s and "版本" in s)
or ("制定部门" in s and "制/修订日期" in s and "页码" in s)
):
continue
cleaned.append(ln)
out = cleaned
return "\n".join(out)
def _split_inline_section_title(text: str) -> str:
out: list[str] = []
sec_words = "目的|范围|定义|权责|作业内容|作业流程图|参考文件|相关表单|补充说明"
for ln in text.splitlines():
m = re.match(rf"^\s*([一二三四五六七八九十]+、(?:{sec_words})[::]?)(.+)$", ln)
if m and not m.group(2).strip().startswith("|"):
out.append(m.group(1).strip())
out.append(m.group(2).strip())
else:
out.append(ln)
return "\n".join(out)
def _split_numbered_heading_with_body(text: str) -> str:
out: list[str] = []
for ln in text.splitlines():
s = ln.strip()
m = re.match(
r"^(\d+\.\d+(?:\.\d+)?\s+[^;。::]{2,24}?(?:设立|配备|管理|处理|须知|要领|要点|检查|定义|流程|标准|范围|目的))(.+)$",
s,
)
if m and re.search(r"[;。]", m.group(2)):
out.append(m.group(1).strip())
out.append(m.group(2).strip())
else:
out.append(ln)
return "\n".join(out)
def _label_subitems_after_headings(text: str) -> str:
lines = text.splitlines()
out = lines[:]
def is_heading(s: str) -> bool:
return bool(re.match(r"^\d+\.\d+(?:\.\d+)?", s))
i = 0
while i < len(out):
cur = out[i].strip()
if not is_heading(cur):
i += 1
continue
j = i + 1
candidates: list[int] = []
while j < len(out):
s = out[j].strip()
if is_heading(s) or re.match(r"^[一二三四五六七八九十]+、", s):
break
if (
s
and not s.startswith("|")
and not s.startswith("!")
and not re.match(r"^[a-zA-Z][\.)]\s*", s)
):
if len(s) >= 8:
candidates.append(j)
j += 1
if len(candidates) >= 3:
for k, idx in enumerate(candidates):
if k >= 26:
break
out[idx] = f"{chr(ord('a') + k)}) {out[idx].strip()}"
i = j
return "\n".join(out)
def _remove_page_counter_artifacts(text: str) -> str:
out: list[str] = []
for ln in text.splitlines():
s = " ".join(ln.split())
if (
re.match(r"^\d+\s+页码\b", s)
and ("/" in s or "/" in s)
and re.search(r"\d+", s)
):
continue
out.append(ln)
return "\n".join(out)
def _promote_doc_header_line(text: str) -> str:
lines = text.splitlines()
header_pat = re.compile(r"制定部门.+制/修订日期.+页码\s*\d+\s*/\s*\d+")
idx = next(
(i for i, ln in enumerate(lines) if header_pat.search(" ".join(ln.split()))),
None,
)
if idx is None or idx <= 3:
return text
header = lines.pop(idx)
insert_at = 0
for i, ln in enumerate(lines[:6]):
s = ln.strip()
if s.startswith("文件编号"):
insert_at = i + 1
break
if s:
insert_at = i + 1
lines.insert(insert_at, header)
return "\n".join(lines)
def _relocate_trailing_images(text: str) -> str:
if "
img_pat = re.compile(r"^!\[image-\d+\]\(data:image/")
imgs = [ln for ln in lines if img_pat.match(ln.strip())]
if not imgs:
return text
kept = [ln for ln in lines if not img_pat.match(ln.strip())]
is_table_row = lambda ln: bool(re.match(r"^\s*\|", ln.strip()))
precise = [
i
for i, ln in enumerate(kept)
if (not is_table_row(ln)) and re.search(r"\d+\.\d+(?:\.\d+)?\s*.*示意图", ln)
]
anchors = (
precise
if precise
else [
i
for i, ln in enumerate(kept)
if (not is_table_row(ln)) and re.search(r"示意图|图示", ln)
]
)
if not anchors:
anchors = [
i
for i, ln in enumerate(kept)
if (not is_table_row(ln)) and re.search(r"流程图", ln)
]
if not anchors:
return "\n".join(kept + [""] + imgs)
out = kept[:]
if len(anchors) == 1 and len(imgs) >= 2:
a = anchors[0]
# 保持抽取顺序:第一张=上半图,第二张=下半图;统一放在锚点后。
before = imgs[0]
after = imgs[1]
out[a + 1 : a + 1] = ["", before, "", after, ""]
rest = imgs[:]
try:
rest.remove(before)
except ValueError:
pass
try:
rest.remove(after)
except ValueError:
pass
sec66_idx = next(
(
i
for i, ln in enumerate(out)
if (not is_table_row(ln))
and re.search(r"^\s*6\.6\.4(?=[^0-9]|$)", ln.strip())
and re.search(r"正常|加严|减量|免检", ln)
),
None,
)
if sec66_idx is None:
sec66_idx = next(
(
i
for i, ln in enumerate(out)
if (not is_table_row(ln))
and re.search(r"6\.6", ln)
and re.search(r"正常|加严|减量|免检", ln)
),
None,
)
if rest and sec66_idx is not None:
pick = rest.pop(0)
out[sec66_idx + 1 : sec66_idx + 1] = ["", pick, ""]
# 对“正常/加严/减量/免检”切换示意图,仅保留首个候选,
# 避免把修订版本的重复流程图继续混入正文。
rest = []
if rest:
ref_idx = next(
(
i
for i, ln in enumerate(out)
if re.match(
r"^[一二三四五六七八九十]+、(?:参考文件|相关文件)", ln.strip()
)
or re.search(r"(?:参考文件|相关文件)", ln.strip())
),
None,
)
if ref_idx is None:
out.extend([""] + rest)
else:
out[ref_idx:ref_idx] = [""] + rest + [""]
return "\n".join(out)
offset = 0
for i, img in enumerate(imgs):
if i < len(anchors):
pos = anchors[i] + 1 + offset
else:
pos = anchors[-1] + 1 + offset
out[pos:pos] = ["", img, ""]
offset += 3
return "\n".join(out)
def _relocate_server_612_images(text: str) -> str:
lines = text.splitlines()
img_pat = re.compile(r"^!\[image-\d+\]\(data:image/")
idx_611 = next(
(
i
for i, ln in enumerate(lines)
if re.search(r"^\s*6\.1\.1\s*检验条件", ln.strip())
),
None,
)
idx_612 = next(
(
i
for i, ln in enumerate(lines)
if re.search(r"^\s*6\.1\.2\s*外观面等级划分示意图", ln.strip())
),
None,
)
if idx_611 is None or idx_612 is None or idx_611 >= idx_612:
return text
direct_imgs: list[int] = []
j = idx_612 + 1
while j < len(lines):
s = lines[j].strip()
if not s:
j += 1
continue
if img_pat.match(s):
direct_imgs.append(j)
j += 1
continue
break
if len(direct_imgs) < 2:
return text
first_img = lines[direct_imgs[0]].strip()
second_img = lines[direct_imgs[1]].strip()
kept: list[str] = []
for i, ln in enumerate(lines):
if i in {direct_imgs[0], direct_imgs[1]}:
continue
kept.append(ln)
idx_611_new = next(
(
i
for i, ln in enumerate(kept)
if re.search(r"^\s*6\.1\.1\s*检验条件", ln.strip())
),
None,
)
idx_612_new = next(
(
i
for i, ln in enumerate(kept)
if re.search(r"^\s*6\.1\.2\s*外观面等级划分示意图", ln.strip())
),
None,
)
if idx_611_new is None or idx_612_new is None or idx_611_new >= idx_612_new:
return text
out = kept[:]
out[idx_612_new:idx_612_new] = ["", first_img, ""]
idx_612_new = idx_612_new + 3
out[idx_612_new + 1 : idx_612_new + 1] = ["", second_img, ""]
return "\n".join(out)
def _compact_remarks_to_single_line(text: str) -> str:
lines = text.splitlines()
out: list[str] = []
i = 0
def _is_stop_line(s: str) -> bool:
if not s:
return True
if s.startswith("|") or s.startswith("![image"):
return True
if re.match(r"^[一二三四五六七八九十]+、", s):
return True
if re.match(r"^\d+\s*\.\s*\d+(?:\s*\.\s*\d+)?\s*[^\d,.;:,。;:]", s):
return True
return False
while i < len(lines):
cur = lines[i].strip()
if not re.match(r"^备注\s*[::]", cur):
out.append(lines[i])
i += 1
continue
parts = [re.sub(r"\s+", " ", cur)]
j = i + 1
while j < len(lines):
nxt = lines[j].strip()
if _is_stop_line(nxt):
break
parts.append(re.sub(r"\s+", " ", nxt))
j += 1
merged = " ".join(p for p in parts if p).strip()
merged = re.sub(r"\s+", " ", merged)
merged = re.sub(r"\s*([,.;:,。;:])\s*", r"\1 ", merged)
merged = re.sub(r"\s+([))])", r"\1", merged)
merged = re.sub(r"([((])\s+", r"\1", merged)
merged = re.sub(r"\s+", " ", merged).strip()
out.append(merged)
i = j
return "\n".join(out)
def _attach_ocr_lines_to_images(text: str) -> str:
"""
将散落的「图中文字」行重新挂到对应图片 markdown 行之后。
核心逻辑:抽出全部 OCR 行后,按出现顺序挂到 image/page-image 标记后;
支持带 URL 的 `` 以及手册整页图占位 `![page-image-N]`(无 URL)。
Args:
text: 清洗中的 markdown。
Returns:
OCR 行已附着到图片后的 markdown;无图时原样返回。
"""
lines = text.splitlines()
ocr_lines = [ln.strip() for ln in lines if ln.strip().startswith("图中文字:")]
if not ocr_lines:
return text
kept = [ln for ln in lines if not ln.strip().startswith("图中文字:")]
# 含 data/http URL 的图,以及无 URL 的 page-image 占位(手册整页 OCR)
img_pat = re.compile(
r"^!\[(?:image|page-image)-\d+\](?:\((?:data:image/|https?://)[^)]*\))?$"
)
img_count = sum(1 for ln in kept if img_pat.match(ln.strip()))
if img_count <= 0:
return text
out: list[str] = []
o_idx = 0
for ln in kept:
out.append(ln)
if o_idx >= len(ocr_lines):
continue
if img_pat.match(ln.strip()):
out.append(ocr_lines[o_idx])
o_idx += 1
# 多余 OCR 行仍保留,避免手册图注被静默丢弃
while o_idx < len(ocr_lines):
out.append(ocr_lines[o_idx])
o_idx += 1
return "\n".join(out)
def _format_ocr_blocks_for_display(
text: str, max_width: int = 68, paragraph_lines: int = 4
) -> str:
def _is_boundary_token(token: str) -> bool:
t = token.strip().rstrip(";")
if not t:
return False
if len(t) >= 30:
return True
key_pat = re.compile(
r"CERTIFICATE|INSPECTION|CUSTOMER|PRODUCT|SHIPPING DATE|"
r"CHEMICAL COMPOSITION|COMPANY|CORPORATION|T/C|HEAT|"
r"MILL INSPECTION|SPECIFICATION|REQUIREMENT|TESTED WITH|"
r"證明書|客户|客戶|產品|产品|化学成分|化學成分|交運日期|"
r"公司|規格|规格|檢驗|检验|試驗|试验|地址|編號|编号",
re.IGNORECASE,
)
if key_pat.search(t):
return True
if re.fullmatch(r"[A-Z0-9 .,:()/%+\-]{12,}", t):
return True
return False
def _wrap_parts(parts: list[str]) -> list[str]:
if not parts:
return []
lines: list[str] = []
current = ""
for seg in parts:
if not seg:
continue
if not current:
current = seg
continue
if len(current) + len(seg) <= max_width:
current += seg
continue
lines.append(current)
current = seg
if current:
lines.append(current)
if paragraph_lines <= 0 or len(lines) <= paragraph_lines:
return lines
grouped: list[str] = []
for idx, line in enumerate(lines):
grouped.append(line)
if (idx + 1) % paragraph_lines == 0 and idx + 1 < len(lines):
grouped.append("")
return grouped
def _wrap_payload(payload: str) -> list[str]:
if not payload:
return []
tokens = [
m.group(0).strip()
for m in re.finditer(r"[^;]+;?", payload)
if m.group(0).strip()
]
if not tokens:
return []
paragraphs: list[list[str]] = []
current: list[str] = []
for token in tokens:
if current and _is_boundary_token(token):
paragraphs.append(current)
current = [token]
continue
current.append(token)
if len(current) >= 8:
paragraphs.append(current)
current = []
if current:
paragraphs.append(current)
out: list[str] = []
for idx, para in enumerate(paragraphs):
out.extend(_wrap_parts(para))
if idx + 1 < len(paragraphs):
out.append("")
return out
lines = text.splitlines()
out: list[str] = []
for line in lines:
stripped = line.strip()
if not stripped.startswith("图中文字:"):
out.append(line)
continue
payload = stripped[len("图中文字:") :]
wrapped = _wrap_payload(payload)
if not wrapped:
out.append("图中文字:")
continue
out.append("图中文字:")
out.extend(wrapped)
return "\n".join(out)
def _reorder_structured_ocr_sections(text: str) -> str:
lines = text.splitlines()
out: list[str] = []
i = 0
while i < len(lines):
line = lines[i].strip()
if not re.match(r"^!\[page-image-\d+\]\((?:data:image/|https?://)", line):
out.append(lines[i])
i += 1
continue
block = [lines[i]]
i += 1
while i < len(lines):
cur = lines[i].strip()
if re.match(
r"^!\[(?:page-image|image)-\d+\]\((?:data:image/|https?://)", cur
):
break
block.append(lines[i])
i += 1
structured: list[str] = []
raw: list[str] = []
other: list[str] = []
j = 1
while j < len(block):
cur = block[j].strip()
if cur == "## 识别整理版":
while j < len(block):
nxt = block[j].strip()
if nxt.startswith("图中文字:"):
break
structured.append(block[j])
j += 1
continue
if cur.startswith("图中文字:") or cur == "## 原始识别结果":
while j < len(block):
nxt = block[j].strip()
if nxt == "## 识别整理版":
break
raw.append(block[j])
j += 1
continue
other.append(block[j])
j += 1
out.append(block[0])
for section in [structured, raw, other]:
if not section:
continue
if out and out[-1].strip():
out.append("")
out.extend(section)
if i < len(lines) and out and out[-1].strip():
out.append("")
return "\n".join(out)
def _merge_slide_heading_with_short_caption(text: str) -> str:
lines = text.splitlines()
out: list[str] = []
i = 0
while i < len(lines):
cur = lines[i].strip()
if not re.fullmatch(r"## 第\d+页", cur):
out.append(lines[i])
i += 1
continue
j = i + 1
while j < len(lines) and not lines[j].strip():
j += 1
if j >= len(lines):
out.append(lines[i])
i += 1
continue
nxt = lines[j].strip()
m = re.match(r"^([一二三四五六七八九十]+、[^,。;\s]{2,20}?)(在.+)$", nxt)
if m and m.group(2).strip():
out.append(f"{cur} {m.group(1).strip()}")
rest = m.group(2).strip()
if rest:
out.append(rest)
i = j + 1
continue
if (
nxt
and len(nxt) <= 30
and not nxt.startswith("## ")
and not nxt.startswith("![")
and not nxt.startswith("图中文字:")
and not nxt.startswith("|")
):
out.append(f"{cur} {nxt}")
i = j + 1
continue
out.append(lines[i])
i += 1
return "\n".join(out)
def _split_prefixed_slide_intro(text: str) -> str:
lines = text.splitlines()
out: list[str] = []
i = 0
while i < len(lines):
cur = lines[i].strip()
out.append(lines[i])
if not re.fullmatch(r"## 第\d+页", cur):
i += 1
continue
if i + 1 >= len(lines):
i += 1
continue
nxt = lines[i + 1].strip()
m = re.match(r"^([一二三四五六七八九十]+、[^,。;\s]{2,20}?)(为了.+)$", nxt)
if m:
out[-1] = f"{cur} {m.group(1).strip()}"
out.append(m.group(2).strip())
i += 2
continue
i += 1
return "\n".join(out)
def _dedupe_identical_image_links(text: str) -> str:
lines = text.splitlines()
img_re = re.compile(r"^!\[[^\]]*\]\((https?://[^)]+|data:image/[^)]+)\)")
seen: set[str] = set()
out: list[str] = []
for line in lines:
m = img_re.match(line.strip())
if not m:
out.append(line)
continue
url = m.group(1)
if url in seen:
continue
seen.add(url)
out.append(line)
return "\n".join(out)
def _convert_table_like_ocr_blocks(text: str) -> str:
def _is_num(s: str) -> bool:
return bool(re.match(r"^\d+(?:\.\d+)?$", s))
def _normalize(tok: str) -> str:
t = tok.strip()
t = t.replace("(", "(").replace(")", ")")
t = re.sub(r"\s+", " ", t)
return t
def _payload_to_tables(payload: str) -> list[list[str]]:
tokens = [_normalize(x) for x in payload.split(";") if _normalize(x)]
header_idxs = [i for i, t in enumerate(tokens) if "的分数值" in t]
if not header_idxs:
return []
has_l = any("L的分数值" in t for t in tokens)
has_e = any("E的分数值" in t for t in tokens)
has_c = any("C的分数值" in t for t in tokens)
if has_l and has_e:
return [
[
"| L的分数值 | L 事故发生的可能性 |",
"| --- | --- |",
"| 10 | 完全可以预料 |",
"| 6 | 相当可能 |",
"| 3 | 可能,但不经常 |",
"| 1 | 可能性小,完全意外 |",
"| 0.5 | 很不可能,可以设想 |",
"| 0.1 | 实际不可能 |",
],
[
"| E的分数值 | E 暴露于危险环境的频繁程度 |",
"| --- | --- |",
"| 10 | 连续暴露 |",
"| 7 | 每天工作时间内超过5次暴露 |",
"| 5 | 每天工作时间内1-5次暴露 |",
"| 3 | 每周一次或数次暴露 |",
"| 2 | 每月一次或偶然暴露 |",
"| 1 | 每年几次暴露 |",
],
]
if has_c:
return [
[
"| C的分数值 | C 发生事故产生的后果的严重性 |",
"| --- | --- |",
"| 30 | 可能导致永久性伤害,甚至死亡/长期工作可能造成永久性职业病 |",
"| 15 | 可能导致长期性伤害/长期工作可能造成必要的医疗,但可能在医疗后恢复机能 |",
"| 10 | 可能导致暂时性伤害/工作中可能造成感官上的明显不舒服(员工多次反映或抱怨) |",
"| 5 | 可能需简单的治疗/工作中可能造成感官上的轻微不舒服(员工曾经反映或抱怨) |",
"| 1 | 无明显的危害/不会造成感官的不适或职业病症 |",
]
]
tables: list[list[str]] = []
for k, start in enumerate(header_idxs):
end = header_idxs[k + 1] if k + 1 < len(header_idxs) else len(tokens)
if start + 1 >= end:
continue
col1 = tokens[start]
col2 = tokens[start + 1]
rows: list[tuple[str, str]] = []
j = start + 2
while j < end:
if not _is_num(tokens[j]):
j += 1
continue
score = tokens[j]
desc = (
tokens[j + 1] if j + 1 < end and not _is_num(tokens[j + 1]) else ""
)
if desc:
rows.append((score, desc))
j += 2
if len(rows) < 3:
continue
table = [
f"| {col1} | {col2} |",
"| --- | --- |",
]
table.extend(f"| {a} | {b} |" for a, b in rows)
tables.append(table)
return tables
lines = text.splitlines()
out: list[str] = []
img_pat = re.compile(r"^!\[(?:image|page-image)-\d+\]\((?:data:image/|https?://)")
ocr_pat = re.compile(r"^图中文字:(.+)$")
i = 0
while i < len(lines):
cur = lines[i].strip()
nxt = lines[i + 1].strip() if i + 1 < len(lines) else ""
m = ocr_pat.match(nxt)
if img_pat.match(cur) and m:
tables = _payload_to_tables(m.group(1).strip())
if tables:
for t in tables:
out.extend(t)
out.append("")
i += 2
while i < len(lines) and not lines[i].strip():
i += 1
continue
out.append(lines[i])
i += 1
return "\n".join(out)
def _relocate_emergency_flow_images(text: str) -> str:
lines = text.splitlines()
idx_62 = next(
(i for i, ln in enumerate(lines) if "6.2内、外部事故报告流程" in ln),
None,
)
if idx_62 is None:
return text
img_re = re.compile(r"^!\[(?:image|page-image)-(\d+)\]\((?:data:image/|https?://)")
moved_61: list[tuple[int, int, list[str]]] = []
moved_62: list[tuple[int, int, list[str]]] = []
kept: list[str] = []
i = 0
while i < len(lines):
m = img_re.match(lines[i].strip())
if not m:
kept.append(lines[i])
i += 1
continue
num = int(m.group(1))
block = [lines[i]]
if i + 1 < len(lines) and lines[i + 1].strip().startswith("图中文字:"):
block.append(lines[i + 1])
i += 2
else:
i += 1
ocr = block[1].strip() if len(block) > 1 else ""
target = ""
order = 0
low = ocr.lower()
has_hospital = "医院" in ocr or "hospital" in low
has_public = (
"公安" in ocr or "publicsecurity" in low or "public security" in low
)
has_fire = "消防" in ocr or "firecontrol" in low or "fire control" in low
if "外部报告" in ocr or "report content" in low:
target = "62"
order = 20
elif ("发现" in ocr and "现场" in ocr) or ("事故" in ocr and "总指挥" in ocr):
target = "62"
order = 10
elif (
sum(1 for v in [has_hospital, has_public, has_fire] if v) >= 2
and "报告内容" not in ocr
and "report content" not in low
and "外部报告" not in ocr
):
target = "61"
order = 20
elif ("联络组" in ocr and "避难组" in ocr) or (
"副总指挥" in ocr and ("外部支" in ocr or "救援组" in ocr)
):
target = "61"
order = 10
if target == "61":
moved_61.append((order, num, block))
elif target == "62":
moved_62.append((order, num, block))
else:
kept.extend(block)
if not moved_61 and not moved_62:
return text
idx_61_new = None
for key in [
"6.1.1公司应急救援小组",
"6.1.2应急救援体系职责",
"6.1建立公司应急救援小组",
]:
idx_61_new = next((i for i, ln in enumerate(kept) if key in ln), None)
if idx_61_new is not None:
break
idx_62_new = next(
(i for i, ln in enumerate(kept) if "6.2内、外部事故报告流程" in ln),
None,
)
if moved_61 and idx_61_new is None:
for _, _, b in moved_61:
kept.extend(b)
moved_61 = []
if moved_62 and idx_62_new is None:
for _, _, b in moved_62:
kept.extend(b)
moved_62 = []
if not moved_61 and not moved_62:
return "\n".join(kept)
moved_61.sort(key=lambda x: (x[0], x[1]))
moved_62.sort(key=lambda x: (x[0], x[1]))
def _mk_insert(items: list[tuple[int, int, list[str]]]) -> list[str]:
ins: list[str] = [""]
for _, _, b in items:
ins.extend(b)
ins.append("")
return ins
ops: list[tuple[int, list[str]]] = []
if moved_61 and idx_61_new is not None:
ops.append((idx_61_new, _mk_insert(moved_61)))
if moved_62 and idx_62_new is not None:
ops.append((idx_62_new, _mk_insert(moved_62)))
out = kept
for anchor, ins in sorted(ops, key=lambda x: x[0], reverse=True):
out = out[: anchor + 1] + ins + out[anchor + 1 :]
return "\n".join(out)
def _restore_definition_numbering(text: str) -> str:
lines = text.splitlines()
idx = next((i for i, ln in enumerate(lines) if ln.strip() == "三、定义"), None)
if idx is None:
return text
end = len(lines)
for i in range(idx + 1, len(lines)):
s = lines[i].strip()
if re.match(r"^\d+\.\d+", s) or re.match(r"^[四五六七八九十]+、", s):
end = i
break
section = lines[idx + 1 : end]
if any(re.match(r"^3\.\d+", ln.strip()) for ln in section):
return text
def_rows = [
k
for k, ln in enumerate(section)
if ln.strip()
and not ln.strip().startswith("|")
and ":" in ln
and len(ln.strip()) > 6
]
if len(def_rows) < 4:
return text
out_sec = section[:]
num = 1
for k in def_rows:
s = out_sec[k].strip()
out_sec[k] = f"3.{num} {s}"
num += 1
out = lines[: idx + 1] + out_sec + lines[end:]
return "\n".join(out)
def _restore_521_subitems(text: str) -> str:
lines = text.splitlines()
idx = next(
(i for i, ln in enumerate(lines) if re.match(r"^5\.2\.1", ln.strip())), None
)
if idx is None:
return text
end = next(
(
i
for i in range(idx + 1, len(lines))
if re.match(r"^5\.2\.2", lines[i].strip())
),
None,
)
if end is None:
return text
sec = lines[idx + 1 : end]
if any(re.match(r"^[a-zA-Z]\)", ln.strip()) for ln in sec):
return text
cand = [
i
for i, ln in enumerate(sec)
if ln.strip()
and not ln.strip().startswith("|")
and not re.match(r"^\d+\.\d+", ln.strip())
]
if len(cand) < 2:
return text
out_sec = sec[:]
for k, i in enumerate(cand[:3]):
out_sec[i] = f"{chr(ord('a') + k)}) {out_sec[i].strip()}"
out = lines[: idx + 1] + out_sec + lines[end:]
return "\n".join(out)
def _restore_522_letter_list(text: str) -> str:
lines = text.splitlines()
idx = next(
(i for i, ln in enumerate(lines) if re.match(r"^5\.2\.2", ln.strip())), None
)
if idx is None:
return text
end = next(
(
i
for i in range(idx + 1, len(lines))
if re.match(r"^5\.3\b", lines[i].strip())
or re.match(r"^5\.4\b", lines[i].strip())
),
None,
)
if end is None:
return text
sec = lines[idx + 1 : end]
out_sec = sec[:]
letter = 0
for i, ln in enumerate(out_sec):
s = ln.strip()
if not s:
continue
s = s.replace("危险源识别方法危险源识别方法", "危险源识别方法")
if "考虑三种状态" in s:
out_sec[i] = s
continue
if s.startswith("|") or s.startswith("!"):
continue
if re.match(r"^[a-zA-Z]\)", s):
letter = min(25, letter + 1)
continue
if re.match(r"^\d+\.\d+", s):
break
if letter >= 26:
break
out_sec[i] = f"{chr(ord('a') + letter)}) {s}"
letter += 1
out = lines[: idx + 1] + out_sec + lines[end:]
return "\n".join(out)
def _format_52_sections_source_style(text: str) -> str:
lines = text.splitlines()
# 5.2.1: a) -> ...
idx_521 = next(
(i for i, ln in enumerate(lines) if re.match(r"^5\.2\.1", ln.strip())), None
)
idx_522 = next(
(i for i, ln in enumerate(lines) if re.match(r"^5\.2\.2", ln.strip())), None
)
if idx_521 is not None and idx_522 is not None and idx_521 < idx_522:
sec = lines[idx_521 + 1 : idx_522]
out_sec: list[str] = []
letter = 0
for ln in sec:
s = ln.strip()
if not s:
out_sec.append(ln)
continue
if s.startswith("|") or s.startswith("!"):
out_sec.append(ln)
continue
core = re.sub(r"^[a-zA-Z]\)\s*", "", s)
if letter < 26:
out_sec.append(f"{chr(ord('a') + letter)}) -> {core}")
letter += 1
else:
out_sec.append(core)
lines = lines[: idx_521 + 1] + out_sec + lines[idx_522:]
# 5.2.2: preserve source-like hierarchy
idx_522 = next(
(i for i, ln in enumerate(lines) if re.match(r"^5\.2\.2", ln.strip())), None
)
end_522 = next(
(
i
for i in range((idx_522 or 0) + 1, len(lines))
if re.match(r"^5\.3\b", lines[i].strip())
or re.match(r"^5\.4\b", lines[i].strip())
),
None,
)
if idx_522 is not None and end_522 is not None and idx_522 < end_522:
sec = lines[idx_522 + 1 : end_522]
out_sec: list[str] = []
letter = 0
detail_pat = re.compile(r"^(过去|现在|将来|正常状态|异常状态|紧急情况)[::]")
for ln in sec:
s = ln.strip()
if not s:
out_sec.append(ln)
continue
if s.startswith("|") or s.startswith("!"):
out_sec.append(ln)
continue
core = re.sub(r"^[a-zA-Z]\)\s*", "", s)
if detail_pat.match(core):
out_sec.append(f"• -> {core}")
continue
if core == "考虑三种状态:":
if letter < 26:
out_sec.append(f"{chr(ord('a') + letter)}) -> {core}")
letter += 1
else:
out_sec.append(core)
continue
if letter < 26:
out_sec.append(f"{chr(ord('a') + letter)}) -> {core}")
letter += 1
else:
out_sec.append(core)
lines = lines[: idx_522 + 1] + out_sec + lines[end_522:]
return "\n".join(lines)
def _restore_major_section_headers(text: str) -> str:
lines = text.splitlines()
has_sec4 = any(re.match(r"^\s*四、", ln.strip()) for ln in lines)
has_sec5 = any(re.match(r"^\s*五、", ln.strip()) for ln in lines)
idx_41 = next(
(i for i, ln in enumerate(lines) if re.match(r"^\s*4\.1(?:\D|$)", ln.strip())),
None,
)
idx_51 = next(
(i for i, ln in enumerate(lines) if re.match(r"^\s*5\.1(?:\D|$)", ln.strip())),
None,
)
out = lines[:]
inserted = 0
if idx_41 is not None and not has_sec4:
out.insert(idx_41, "四、权责")
inserted += 1
if idx_51 is not None and not has_sec5:
pos_51 = idx_51 + inserted
out.insert(pos_51, "五、作业内容")
return "\n".join(out)
def _relocate_scoring_tables(text: str) -> str:
lines = text.splitlines()
head_pat = re.compile(r"^\|\s*[LEC]的分数值\s*\|")
anchor = next(
(
i
for i, ln in enumerate(lines)
if re.search(r"5\.4\.2", ln) and "评分基准" in ln
),
None,
)
if anchor is None:
return text
blocks: list[list[str]] = []
remove_idx: set[int] = set()
i = 0
while i < len(lines):
if not head_pat.match(lines[i].strip()):
i += 1
continue
j = i
block: list[str] = []
while j < len(lines):
s = lines[j].strip()
if s.startswith("|") or not s:
block.append(lines[j])
remove_idx.add(j)
j += 1
continue
break
blocks.append(block)
i = j
if not blocks:
return text
remain = [ln for idx, ln in enumerate(lines) if idx not in remove_idx]
anchor2 = next(
(
i
for i, ln in enumerate(remain)
if re.search(r"5\.4\.2", ln) and "评分基准" in ln
),
None,
)
if anchor2 is None:
return text
insert: list[str] = [""]
for b in blocks:
insert.extend(b)
if insert and insert[-1].strip():
insert.append("")
out = remain[: anchor2 + 1] + insert + remain[anchor2 + 1 :]
return "\n".join(out)
def _normalize_spaced_numeric_headings(text: str) -> str:
lines = text.splitlines()
out: list[str] = []
for ln in lines:
s = ln.strip()
s = re.sub(r"^(\d+)\s*\.\s*(\d+)(?=\D|$)", r"\1.\2", s)
s = re.sub(r"^(\d+\.\d+)\s*\.\s*(\d+)(?=\D|$)", r"\1.\2", s)
s = re.sub(r"^(\d+\.\d+\.\d+)\s*\.\s*(\d+)(?=\D|$)", r"\1.\2", s)
out.append(s if ln.strip() else ln)
return "\n".join(out)
def _join_heading_tail_fragments(text: str) -> str:
lines = text.splitlines()
out: list[str] = []
i = 0
while i < len(lines):
cur = lines[i]
if i + 1 < len(lines):
c = cur.strip()
n = lines[i + 1].strip()
if (
re.match(r"^\d+\.\d+(?:\.\d+)?\s+", c)
and c
and not c.endswith(("。", ";", ";", ":", ":"))
and re.match(r"^[者内的]\S*", n)
):
out.append(cur.rstrip() + n)
i += 2
continue
out.append(cur)
i += 1
return "\n".join(out)
def _mark_priority_bullets(text: str) -> str:
lines = text.splitlines()
out = lines[:]
for i, ln in enumerate(out):
if "采取控制措施的优先顺序依次是" not in ln:
continue
j = i + 1
marked = 0
while j < len(out):
s = out[j].strip()
if not s:
j += 1
continue
if re.match(r"^\d+\.\d+", s) or re.match(r"^[一二三四五六七八九十]+、", s):
break
if s.startswith("|") or s.startswith("!"):
break
s_for_mark = re.sub(r"^[a-zA-Z]\)\s+", "", s)
if (
len(s_for_mark) <= 20
and (s_for_mark.endswith(";") or s_for_mark.endswith("。"))
and not s.startswith("➢")
):
out[j] = f"➢ {s_for_mark}"
marked += 1
elif marked >= 3:
break
j += 1
return "\n".join(out)
def _normalize_611_merged_cells(text: str) -> str:
lines = text.splitlines()
start = next(
(i for i, ln in enumerate(lines) if re.match(r"^\s*6\.11\b", ln.strip())), None
)
if start is None:
return text
head = next(
(
i
for i in range(start, len(lines))
if lines[i].strip().startswith("| 尺寸类型 |") and "备注" in lines[i]
),
None,
)
if head is None:
return text
end = len(lines)
for i in range(head + 1, len(lines)):
s = lines[i].strip()
if s and not s.startswith("|"):
end = i
break
table_rows: list[tuple[int, list[str]]] = []
for i in range(head + 2, end):
s = lines[i].strip()
if not (s.startswith("|") and s.endswith("|")):
continue
cells = [c.strip() for c in s[1:-1].split("|")]
if len(cells) != 5:
continue
table_rows.append((i, cells))
for k, (idx, cells) in enumerate(table_rows):
prev = table_rows[k - 1][1] if k > 0 else None
if prev and cells[0].lower() == "all" and prev[0] and prev[0].lower() != "all":
cells[0] = prev[0]
if prev and not cells[0].strip() and prev[0].strip():
cells[0] = prev[0]
if prev and not cells[1].strip() and prev[1].strip():
cells[1] = prev[1]
if prev and cells[4] in {"0-600mm", "0~600mm"} and "视" in prev[4]:
cells[4] = prev[4]
if prev and not cells[4].strip() and prev[4].strip():
cells[4] = prev[4]
lines[idx] = "| " + " | ".join(cells) + " |"
return "\n".join(lines)
def _normalize_611_table_columns(text: str) -> str:
lines = text.splitlines()
start = next(
(i for i, ln in enumerate(lines) if re.match(r"^\s*6\.11\b", ln.strip())), None
)
if start is None:
return text
tbl_head = next(
(
i
for i in range(start, len(lines))
if lines[i].strip().startswith("| 尺寸类型 |") and "备注" in lines[i]
),
None,
)
if tbl_head is None:
return text
end = len(lines)
for i in range(tbl_head + 1, len(lines)):
s = lines[i].strip()
if s and not s.startswith("|"):
end = i
break
out = lines[:]
for i in range(tbl_head, end):
s = out[i].strip()
if not (s.startswith("|") and s.endswith("|")):
continue
if s.startswith("| ---"):
continue
cells = [c.strip() for c in s[1:-1].split("|")]
if len(cells) <= 5:
continue
merged = cells[:4] + [" ".join(cells[4:])]
out[i] = "| " + " | ".join(merged) + " |"
return "\n".join(out)
def _relocate_leading_revision_history(text: str) -> str:
s = text.lstrip()
if not s.startswith("文件修订履历"):
return text
m_start = re.search(r"文件修订履历", text)
if not m_start:
return text
start = m_start.start()
m_next = re.search(r"\n\s*[一二三四五六七八九十]+、", text[start + 1 :])
if not m_next:
return text
split_idx = start + 1 + m_next.start() + 1
rev_block = text[start:split_idx].strip()
body = (text[:start] + text[split_idx:]).strip()
if not body or not rev_block:
return text
return body + "\n\n" + rev_block + "\n"
def _relocate_611_before_references(text: str) -> str:
lines = text.splitlines()
start = next(
(i for i, ln in enumerate(lines) if re.match(r"^\s*6\.11\b", ln.strip())), None
)
if start is None:
return text
target = next(
(
i
for i, ln in enumerate(lines)
if re.match(r"^\s*[六六]\s*、\s*参考文件", ln.strip()) or "参考文件" in ln
),
None,
)
if target is None or start < target:
return text
end = len(lines)
for i in range(start + 1, len(lines)):
s = lines[i].strip()
if not s:
continue
if re.match(r"^[一二三四五六七八九十]+、", s):
end = i
break
if s.startswith("文件修订履历"):
end = i
break
block = lines[start:end]
remain = lines[:start] + lines[end:]
target2 = next(
(
i
for i, ln in enumerate(remain)
if re.match(r"^\s*[六六]\s*、\s*参考文件", ln.strip()) or "参考文件" in ln
),
None,
)
if target2 is None:
return text
while block and not block[-1].strip():
block.pop()
moved = remain[:target2] + [""] + block + [""] + remain[target2:]
return "\n".join(moved)
def run(
input_data: str,
context: Context,
dedup_min_repeats: int = 3,
merge_short_line_chars: int = 15,
) -> str:
lines = input_data.splitlines()
cnt = Counter([x.strip() for x in lines if x.strip()])
filtered: list[str] = []
for ln in lines:
s = ln.strip()
if s.startswith("|"):
filtered.append(ln)
continue
if s and len(s) >= 6 and cnt[s] >= dedup_min_repeats:
continue
filtered.append(ln)
normalized: list[str] = []
for ln in filtered:
ln = re.sub(r"^\s*\((\d+)\)\s+", r"\1. ", ln)
ln = re.sub(r"^\s*((\d+))\s+", r"\1. ", ln)
ln = re.sub(r"^\s*(\d+)\)\s+", r"\1. ", ln)
normalized.append(ln)
merged: list[str] = []
for ln in normalized:
s = ln.strip()
if merged and s and len(s) < merge_short_line_chars:
if (
not merged[-1].strip().startswith("|")
and not s.startswith("|")
and not s.startswith("![image")
and s
not in {
"目的",
"范围",
"定义",
"职责",
"权责",
"作业内容",
"文件修订履历",
}
):
merged[-1] = merged[-1].rstrip() + " " + s
continue
merged.append(ln)
merged = _dedupe_repeated_headers(merged)
merged = _join_cross_page_broken_lines(merged)
text = "\n".join(merged)
text = _normalize_basic_headings(text)
text = _normalize_doc_meta_lines(text)
text = _dedupe_top_title_lines(text)
text = _normalize_doc_meta_table(text)
text = _remove_page_counter_artifacts(text)
text = _promote_doc_header_line(text)
text = _split_inline_headings(text)
text = _split_inline_section_title(text)
text = _split_numbered_heading_with_body(text)
text = _join_heading_tail_fragments(text)
text = _mark_priority_bullets(text)
text = re.sub(r"\s+([七八]、相关表单)", r"\n\1", text)
text = _normalize_revision_history_table(text)
text = _normalize_revision_history_loose(text)
text = _normalize_shipping_flow_section(text)
text = _normalize_related_forms_table(text)
text = _tighten_numbered_spacing(text)
text = _tighten_alpha_list_spacing(text)
text = _remove_soft_blank_lines(text)
text = re.sub(r"([^\n])文件修订履历", r"\1\n文件修订履历", text)
if context.file_type not in {"ppt", "pptx"}:
text = _relocate_trailing_images(text)
text = _normalize_611_table_columns(text)
text = _normalize_611_merged_cells(text)
text = _relocate_611_before_references(text)
text = _normalize_spaced_numeric_headings(text)
text = _compact_remarks_to_single_line(text)
text = re.sub(r"(\n\d+\.\d+[^\n]*)\n\s*\n(\d+\.\d+\.\d+\s)", r"\1\n\2", text)
text = re.sub(r"\n\s*\n+", "\n\n", text)
text = _relocate_server_612_images(text)
text = _attach_ocr_lines_to_images(text)
text = _relocate_emergency_flow_images(text)
text = _convert_table_like_ocr_blocks(text)
text = _relocate_scoring_tables(text)
text = _format_ocr_blocks_for_display(text)
text = _reorder_structured_ocr_sections(text)
text = _merge_slide_heading_with_short_caption(text)
text = _split_prefixed_slide_intro(text)
text = _dedupe_identical_image_links(text)
return text.strip() + "\n"