from __future__ import annotations
import base64
import hashlib
import io
import struct
import mimetypes
import os
import re
import shutil
import subprocess
import zipfile
import xml.etree.ElementTree as ET
from pathlib import Path
from edkb_system.contracts import Block, Context
from edkb_system.skills.soffice_util import convert_with_soffice, soffice_candidates
from edkb_system.skills.word_bridge import convert_with_word
_IMAGE_URI_CACHE: dict[tuple[str, str], str] = {}
_IMAGE_URI_CACHE_MAX = 512
def _to_data_uri(blob: bytes, content_type: str | None = None) -> str:
ct = content_type or "image/png"
b64 = base64.b64encode(blob).decode("ascii")
return f"data:{ct};base64,{b64}"
def _to_preferred_image_data_uri(blob: bytes, content_type: str | None = None) -> str:
ct = str(content_type or "image/png").strip().lower() or "image/png"
cache_key = (hashlib.sha1(blob).hexdigest(), ct)
cached = _IMAGE_URI_CACHE.get(cache_key)
if cached:
return cached
if ct in {"image/jpeg", "image/jpg"}:
uri = _to_data_uri(blob, "image/jpeg")
if len(_IMAGE_URI_CACHE) >= _IMAGE_URI_CACHE_MAX:
_IMAGE_URI_CACHE.clear()
_IMAGE_URI_CACHE[cache_key] = uri
return uri
try:
from PIL import Image
with Image.open(io.BytesIO(blob)) as im:
if im.mode in {"RGB", "L"} and ct in {"image/png", "image/bmp"}:
uri = _to_data_uri(blob, ct)
else:
rgb = Image.new("RGB", im.size, (255, 255, 255))
rgba = im.convert("RGBA")
rgb.paste(rgba, mask=rgba.split()[3])
out = io.BytesIO()
rgb.save(out, format="JPEG", quality=90)
uri = _to_data_uri(out.getvalue(), "image/jpeg")
if len(_IMAGE_URI_CACHE) >= _IMAGE_URI_CACHE_MAX:
_IMAGE_URI_CACHE.clear()
_IMAGE_URI_CACHE[cache_key] = uri
return uri
except Exception:
uri = _to_data_uri(blob, content_type)
if len(_IMAGE_URI_CACHE) >= _IMAGE_URI_CACHE_MAX:
_IMAGE_URI_CACHE.clear()
_IMAGE_URI_CACHE[cache_key] = uri
return uri
def _build_image_uri_map(doc) -> dict[str, str]:
image_uri_by_rid: dict[str, str] = {}
rel_items = list(doc.part.rels.items())
rel_items.sort(
key=lambda kv: int((kv[0] or "rId0").replace("rId", "") or 0)
if (kv[0] or "").startswith("rId")
else 0
)
for rid, rel in rel_items:
reltype = getattr(rel, "reltype", "") or ""
if "image" not in reltype:
continue
try:
part = rel.target_part
blob = part.blob
content_type = getattr(part, "content_type", None)
image_uri_by_rid[str(rid)] = _to_preferred_image_data_uri(blob, content_type)
except Exception:
continue
return image_uri_by_rid
def _image_dimensions(blob: bytes, ext: str) -> tuple[int, int]:
e = (ext or "").lower().lstrip(".")
if e == "png" and len(blob) >= 24 and blob.startswith(b"\x89PNG"):
return int.from_bytes(blob[16:20], "big"), int.from_bytes(blob[20:24], "big")
if e in {"jpg", "jpeg"} and blob.startswith(b"\xff\xd8"):
i = 2
n = len(blob)
while i + 9 < n:
if blob[i] != 0xFF:
i += 1
continue
marker = blob[i + 1]
if marker in {0xC0, 0xC2}:
h = struct.unpack(">H", blob[i + 5 : i + 7])[0]
w = struct.unpack(">H", blob[i + 7 : i + 9])[0]
return w, h
if i + 4 > n:
break
seg_len = struct.unpack(">H", blob[i + 2 : i + 4])[0]
if seg_len <= 2:
break
i += 2 + seg_len
return 0, 0
def _is_sparse_line_artifact(blob: bytes, ext: str) -> bool:
e = (ext or "").lower().lstrip(".")
if e not in {"png", "jpg", "jpeg"}:
return False
try:
from PIL import Image
import numpy as np
with Image.open(io.BytesIO(blob)) as im:
g = im.convert("L")
w, h = g.size
if w <= 0 or h <= 0 or (w * h) < 60000:
return False
hist = g.histogram()
total = max(w * h, 1)
dominant_ratio = max(hist) / total
uniq = sum(1 for c in hist if c)
if dominant_ratio < 0.99 or uniq > 3:
return False
if max(w, h) > 1200:
scale = max(w, h) / 1200.0
nw = max(1, int(w / scale))
nh = max(1, int(h / scale))
g = g.resize((nw, nh))
a = np.asarray(g, dtype=np.int16)
gx = np.abs(np.diff(a, axis=1))
gy = np.abs(np.diff(a, axis=0))
edge_ratio = (np.count_nonzero(gx > 12) + np.count_nonzero(gy > 12)) / max(
a.shape[0] * a.shape[1], 1
)
return edge_ratio < 0.02
except Exception:
return False
def _split_tall_image(blob: bytes, ext: str) -> list[bytes]:
e = (ext or "").lower().lstrip(".")
if e not in {"png", "jpg", "jpeg"}:
return [blob]
try:
from PIL import Image
with Image.open(io.BytesIO(blob)) as im:
w, h = im.size
if w <= 0 or h <= 0 or (h / max(w, 1)) < 1.8:
return [blob]
g = im.convert("L")
def _pix(x: int, y: int) -> int:
v = g.getpixel((x, y))
if isinstance(v, tuple):
return int(v[0])
return int(v if v is not None else 255)
corners = [
_pix(0, 0),
_pix(w - 1, 0),
_pix(0, h - 1),
_pix(w - 1, h - 1),
]
bg = sorted(corners)[len(corners) // 2]
row_content: list[float] = []
for y in range(h):
hist = g.crop((0, y, w, y + 1)).histogram()
near_bg = 0
lo_bg = max(0, bg - 8)
hi_bg = min(255, bg + 8)
for i in range(lo_bg, hi_bg + 1):
near_bg += hist[i]
row_content.append((w - near_bg) / max(w, 1))
lo = int(h * 0.30)
hi = int(h * 0.80)
if hi <= lo:
return [blob]
best_len = 0
best_mid = None
cur_start = None
for y in range(lo, hi):
if row_content[y] < 0.03:
if cur_start is None:
cur_start = y
else:
if cur_start is not None:
ln = y - cur_start
if ln > best_len:
best_len = ln
best_mid = (cur_start + y) // 2
cur_start = None
if cur_start is not None:
ln = hi - cur_start
if ln > best_len:
best_len = ln
best_mid = (cur_start + hi) // 2
if best_mid is None or best_len < 10:
return [blob]
cut = best_mid
def _row_non_bg(y: int) -> int:
hist = g.crop((0, y, w, y + 1)).histogram()
near_bg = 0
lo_bg = max(0, bg - 8)
hi_bg = min(255, bg + 8)
for i in range(lo_bg, hi_bg + 1):
near_bg += hist[i]
return w - near_bg
top_end = cut
for y in range(max(0, cut - 60), min(h, cut + 1)):
if _row_non_bg(y) > 2:
top_end = y
top_end = min(h, top_end + 6)
bot_start = cut
for y in range(cut, min(h, cut + 80)):
if _row_non_bg(y) > 2:
bot_start = y
break
bot_start = max(0, bot_start - 6)
if bot_start <= top_end:
top = im.crop((0, 0, w, max(1, cut)))
bot = im.crop((0, min(h - 1, cut), w, h))
else:
top = im.crop((0, 0, w, max(1, top_end)))
bot = im.crop((0, min(h - 1, bot_start), w, h))
out: list[bytes] = []
for part in [top, bot]:
b = io.BytesIO()
part.save(b, format="PNG")
out.append(b.getvalue())
return out if len(out) == 2 else [blob]
except Exception:
return [blob]
def _extract_image_uris_from_paragraph(
para, doc, image_uri_by_rid: dict[str, str] | None = None
) -> list[str]:
uris: list[str] = []
seen_rids: set[str] = set()
try:
rids = para._element.xpath(".//a:blip/@r:embed")
except Exception:
return uris
for rid in rids:
rid = str(rid)
if rid in seen_rids:
continue
seen_rids.add(rid)
try:
if image_uri_by_rid and rid in image_uri_by_rid:
uris.append(image_uri_by_rid[rid])
continue
part = doc.part.related_parts[rid]
blob = part.blob
content_type = getattr(part, "content_type", None)
uris.append(_to_preferred_image_data_uri(blob, content_type))
except Exception:
continue
return uris
def _extract_all_image_uris_from_doc(
doc, image_uri_by_rid: dict[str, str] | None = None
) -> list[str]:
if image_uri_by_rid:
return list(dict.fromkeys(image_uri_by_rid.values()))
uris: list[str] = []
seen: set[str] = set()
for uri in _build_image_uri_map(doc).values():
if uri in seen:
continue
seen.add(uri)
uris.append(uri)
return uris
def _extract_image_uris_from_table(
table, doc, image_uri_by_rid: dict[str, str] | None = None
) -> list[str]:
uris: list[str] = []
seen: set[str] = set()
try:
for row in table.rows:
for cell in row.cells:
for para in cell.paragraphs:
for uri in _extract_image_uris_from_paragraph(
para, doc, image_uri_by_rid
):
if uri in seen:
continue
seen.add(uri)
uris.append(uri)
except Exception:
return uris
return uris
def _load_numbering_schema(
docx_path: Path,
) -> tuple[dict[str, str], dict[tuple[str, int], dict]]:
ns = {"w": "http://schemas.openxmlformats.org/wordprocessingml/2006/main"}
num_to_abs: dict[str, str] = {}
levels: dict[tuple[str, int], dict] = {}
try:
with zipfile.ZipFile(docx_path) as zf:
xml = zf.read("word/numbering.xml")
root = ET.fromstring(xml)
except Exception:
return num_to_abs, levels
for num in root.findall("w:num", ns):
nid = num.attrib.get("{%s}numId" % ns["w"])
aid_elem = num.find("w:abstractNumId", ns)
aid = aid_elem.attrib.get("{%s}val" % ns["w"]) if aid_elem is not None else None
if nid and aid:
num_to_abs[nid] = aid
for absn in root.findall("w:abstractNum", ns):
aid = absn.attrib.get("{%s}abstractNumId" % ns["w"])
if not aid:
continue
for lvl in absn.findall("w:lvl", ns):
ilvl_s = lvl.attrib.get("{%s}ilvl" % ns["w"], "0")
try:
ilvl = int(ilvl_s)
except Exception:
ilvl = 0
fmt_elem = lvl.find("w:numFmt", ns)
txt_elem = lvl.find("w:lvlText", ns)
start_elem = lvl.find("w:start", ns)
num_fmt = (
fmt_elem.attrib.get("{%s}val" % ns["w"], "decimal")
if fmt_elem is not None
else "decimal"
)
lvl_text = (
txt_elem.attrib.get("{%s}val" % ns["w"], f"%{ilvl + 1}")
if txt_elem is not None
else f"%{ilvl + 1}"
)
start = (
int(start_elem.attrib.get("{%s}val" % ns["w"], "1"))
if start_elem is not None
else 1
)
levels[(aid, ilvl)] = {
"num_fmt": num_fmt,
"lvl_text": lvl_text,
"start": start,
}
return num_to_abs, levels
def _to_roman(n: int) -> str:
vals = [
(1000, "M"),
(900, "CM"),
(500, "D"),
(400, "CD"),
(100, "C"),
(90, "XC"),
(50, "L"),
(40, "XL"),
(10, "X"),
(9, "IX"),
(5, "V"),
(4, "IV"),
(1, "I"),
]
out = []
x = max(1, n)
for v, s in vals:
while x >= v:
out.append(s)
x -= v
return "".join(out)
def _to_chinese_num(n: int) -> str:
digits = "零一二三四五六七八九"
if n <= 0:
return str(n)
if n < 10:
return digits[n]
if n < 20:
return "十" + (digits[n % 10] if n % 10 else "")
if n < 100:
tens, ones = divmod(n, 10)
return digits[tens] + "十" + (digits[ones] if ones else "")
return str(n)
def _format_counter(n: int, fmt: str) -> str:
f = (fmt or "decimal").lower()
if f in {"decimal", "decimalzero"}:
return str(n)
if f == "lowerletter":
return chr(ord("a") + max(0, (n - 1) % 26))
if f == "upperletter":
return chr(ord("A") + max(0, (n - 1) % 26))
if f == "lowerroman":
return _to_roman(n).lower()
if f == "upperroman":
return _to_roman(n)
if "chinese" in f:
return _to_chinese_num(n)
if f == "bullet":
return "•"
return str(n)
def _next_list_marker(
num_id: str,
ilvl: int,
num_to_abs: dict[str, str],
levels: dict[tuple[str, int], dict],
states: dict[str, dict[int, int]],
) -> str:
abs_id = num_to_abs.get(str(num_id))
if not abs_id:
return ""
lvl_cfg = levels.get(
(abs_id, ilvl), {"num_fmt": "decimal", "lvl_text": f"%{ilvl + 1}", "start": 1}
)
state = states.setdefault(str(num_id), {})
for k in list(state.keys()):
if k > ilvl:
state.pop(k, None)
for lv in range(ilvl):
if lv not in state:
state[lv] = int(levels.get((abs_id, lv), {}).get("start", 1))
start = int(lvl_cfg.get("start", 1))
if ilvl not in state:
state[ilvl] = start - 1
state[ilvl] += 1
if (lvl_cfg.get("num_fmt") or "").lower() == "bullet":
return "•"
tmpl = str(lvl_cfg.get("lvl_text") or f"%{ilvl + 1}")
for n in range(1, 10):
token = f"%{n}"
if token not in tmpl:
continue
lv = n - 1
val = state.get(lv, int(levels.get((abs_id, lv), {}).get("start", 1)))
fmt = str(levels.get((abs_id, lv), {}).get("num_fmt", "decimal"))
tmpl = tmpl.replace(token, _format_counter(val, fmt))
if any(ord(c) >= 0xF000 for c in tmpl):
return "•"
return tmpl.strip()
_WORD_EXPORT_IMAGE_NAME_RE = re.compile(
r"image\d+\.(?:png|jpg|jpeg|gif|bmp|webp)", re.IGNORECASE
)
def _word_export_source_stem_from_html(html_path: Path) -> str:
suffix = ".word_export.html"
name = html_path.name
if name.lower().endswith(suffix):
return name[: -len(suffix)]
return html_path.stem
def _word_export_candidate_dirs(source_stem: str, out_dir: Path) -> list[Path]:
candidate_dirs: list[Path] = []
for d in [
out_dir / f"{source_stem}.word_export_files",
out_dir / f"{source_stem}.word_export.files",
]:
if d.exists() and d.is_dir():
candidate_dirs.append(d)
for d in sorted(out_dir.glob(f"{source_stem}.word_export*")):
if d.exists() and d.is_dir() and d not in candidate_dirs:
candidate_dirs.append(d)
return candidate_dirs
def _collect_word_export_image_files(
source_stem: str, out_dir: Path
) -> dict[str, Path]:
files_by_name: dict[str, Path] = {}
for d in _word_export_candidate_dirs(source_stem, out_dir):
for p in sorted(d.glob("*")):
if not p.is_file():
continue
if p.suffix.lower() not in {
".png",
".jpg",
".jpeg",
".gif",
".bmp",
".webp",
}:
continue
files_by_name.setdefault(p.name.lower(), p)
return files_by_name
def _image_file_to_uris(image_file: Path) -> list[str]:
if not image_file.is_file():
return []
ct = mimetypes.guess_type(str(image_file))[0] or "image/png"
uris: list[str] = []
try:
blob = image_file.read_bytes()
parts = _split_tall_image(blob, image_file.suffix)
for part in parts:
w, h = _image_dimensions(part, image_file.suffix)
if w > 0 and h > 0 and (max(w, h) <= 32 or (w * h) < 2000):
continue
if _is_sparse_line_artifact(part, image_file.suffix):
continue
uris.append(_to_preferred_image_data_uri(part, ct))
except Exception:
return uris
return uris
def _ordered_image_names_from_word_html(html_path: Path) -> list[str]:
ordered_names: list[str] = []
if not html_path.exists():
return ordered_names
try:
from bs4 import BeautifulSoup
html = _decode_word_html(html_path.read_bytes())
soup = BeautifulSoup(html, "html.parser")
def _node_is_deleted_change(node) -> bool:
if node is None:
return False
try:
if str(getattr(node, "name", "") or "").lower() == "del":
return True
classes = node.get("class") or []
for c in classes:
if str(c).lower() in {"msodel"}:
return True
except Exception:
return False
return False
def _img_in_deleted_context(img) -> bool:
cur = img
hops = 0
while cur is not None and hops < 8:
hops += 1
if _node_is_deleted_change(cur):
return True
cur = getattr(cur, "parent", None)
return False
for img in soup.find_all("img"):
src_attr = img.get("src")
src = str(src_attr or "").strip()
if not src:
continue
name = src.replace("\\", "/").split("/")[-1].lower()
if not _WORD_EXPORT_IMAGE_NAME_RE.fullmatch(name):
continue
style = " ".join(
[
str(img.get("style") or ""),
str(
getattr(getattr(img, "parent", None), "get", lambda *_: "")(
"style"
)
or ""
),
]
).lower()
has_change_ctx = _img_in_deleted_context(img)
w = int(str(img.get("width") or "0").strip() or 0)
h = int(str(img.get("height") or "0").strip() or 0)
if w > 0 and h > 0 and (max(w, h) <= 32 or (w * h) < 2000):
continue
if has_change_ctx:
continue
if "position:absolute" in style and w > 0 and h > 0 and (w * h) < 60000:
continue
if name not in ordered_names:
ordered_names.append(name)
except Exception:
try:
html_bytes = html_path.read_bytes()
for m in re.finditer(
rb"image\d+\.(?:png|jpg|jpeg|gif|bmp|webp)",
html_bytes,
re.IGNORECASE,
):
name = m.group(0).decode("ascii", "ignore").lower()
if name and name not in ordered_names:
ordered_names.append(name)
except Exception:
pass
return ordered_names
def _ordered_word_export_files(
files_by_name: dict[str, Path], ordered_names: list[str]
) -> list[Path]:
ordered_files: list[Path] = []
if ordered_names:
for name in ordered_names:
p = files_by_name.get(name)
if p is None:
continue
ordered_files.append(p)
else:
for name in sorted(files_by_name.keys()):
ordered_files.append(files_by_name[name])
return ordered_files
def _word_html_has_standard_image_refs(html_path: Path) -> bool:
if not html_path.exists():
return False
try:
raw = html_path.read_bytes()
except Exception:
return False
return (
re.search(
rb"image\d+\.(?:png|jpg|jpeg|gif|bmp|webp)",
raw,
re.IGNORECASE,
)
is not None
)
def _select_word_export_files(
files_by_name: dict[str, Path],
ordered_names: list[str],
html_path: Path,
) -> list[Path]:
has_refs = _word_html_has_standard_image_refs(html_path)
if has_refs and not ordered_names:
return []
return _ordered_word_export_files(files_by_name, ordered_names)
def _extract_images_with_word(source_path: Path, out_dir: Path) -> list[str]:
html_path = out_dir / f"{source_path.stem}.word_export.html"
assets_dir = out_dir / f"{source_path.stem}.word_export_files"
assets_dir_dot = out_dir / f"{source_path.stem}.word_export.files"
out_dir.mkdir(parents=True, exist_ok=True)
cached_files_by_name = _collect_word_export_image_files(source_path.stem, out_dir)
if html_path.exists():
ordered_names = _ordered_image_names_from_word_html(html_path)
has_refs = _word_html_has_standard_image_refs(html_path)
# Cached negative result: html has no refs (or refs all filtered), and no asset files.
# Avoid reopening Word on every run for no-image docs.
if not cached_files_by_name:
if (not has_refs) or (has_refs and not ordered_names):
return []
if cached_files_by_name:
ordered_files = _select_word_export_files(
cached_files_by_name,
ordered_names,
html_path,
)
cached_uris: list[str] = []
for p in ordered_files:
cached_uris.extend(_image_file_to_uris(p))
if cached_uris:
return cached_uris
if (not has_refs) or (has_refs and not ordered_names):
return []
if html_path.exists():
html_path.unlink()
if assets_dir.exists():
shutil.rmtree(assets_dir)
if assets_dir_dot.exists():
shutil.rmtree(assets_dir_dot)
convert_with_word(source_path.resolve(), html_path.resolve(), 10)
files_by_name = _collect_word_export_image_files(source_path.stem, out_dir)
if not files_by_name:
return []
ordered_names = _ordered_image_names_from_word_html(html_path)
ordered_files = _select_word_export_files(files_by_name, ordered_names, html_path)
uris: list[str] = []
for p in ordered_files:
uris.extend(_image_file_to_uris(p))
return uris
def _decode_word_html(raw: bytes) -> str:
for enc in ("utf-8", "gb18030", "cp936", "latin1"):
try:
return raw.decode(enc)
except Exception:
continue
return raw.decode("latin1", "ignore")
def _norm_text(s: str) -> str:
return re.sub(r"\s+", " ", (s or "").replace("\xa0", " ")).strip()
def _xml_local_name(tag: str) -> str:
if not tag:
return ""
if "}" in tag:
return tag.rsplit("}", 1)[-1]
if ":" in tag:
return tag.rsplit(":", 1)[-1]
return tag
def _extract_text_from_ooxml_node(node) -> str:
parts: list[str] = []
def walk(el) -> None:
name = _xml_local_name(getattr(el, "tag", ""))
if name in {
"del",
"moveFrom",
"moveFromRangeStart",
"moveFromRangeEnd",
"commentRangeStart",
"commentRangeEnd",
"drawing",
"pict",
"object",
"txbxContent",
"instrText",
}:
return
if name == "t":
txt = getattr(el, "text", None)
if txt:
parts.append(str(txt))
elif name == "tab":
parts.append("\t")
elif name in {"br", "cr"}:
parts.append("\n")
for ch in list(el):
walk(ch)
try:
walk(node)
except Exception:
return ""
return "".join(parts)
def _paragraph_text_without_revisions(para) -> str:
try:
txt = _extract_text_from_ooxml_node(para._p)
except Exception:
txt = para.text or ""
return " ".join((txt or "").split())
def _cell_paragraph_texts_without_revisions(cell) -> list[str]:
chunks: list[str] = []
try:
for para in cell.paragraphs:
t = _paragraph_text_without_revisions(para)
if t:
chunks.append(t)
except Exception:
fallback = " ".join((cell.text or "").split())
return [fallback] if fallback else []
return chunks
def _cell_text_without_revisions(cell) -> str:
return "\n".join(_cell_paragraph_texts_without_revisions(cell)).strip()
def _drop_deleted_revision_nodes(root) -> None:
try:
for n in root.find_all("del"):
n.decompose()
except Exception:
pass
try:
for n in root.find_all(
class_=lambda c: c
and any(
str(x).lower() == "msodel" for x in (c if isinstance(c, list) else [c])
)
):
n.decompose()
except Exception:
pass
def _extract_word_html_items(html_path: Path) -> list[tuple[str, str]]:
if not html_path.exists():
return []
try:
from bs4 import BeautifulSoup
except Exception:
return []
try:
html = _decode_word_html(html_path.read_bytes())
except Exception:
return []
soup = BeautifulSoup(html, "html.parser")
body = soup.body or soup
_drop_deleted_revision_nodes(body)
items: list[tuple[str, str]] = []
for el in body.find_all(["p", "table"]):
if el.name == "p":
txt = _norm_text(el.get_text(" ", strip=True))
if txt:
items.append(("paragraph", txt))
continue
rows: list[list[str]] = []
for tr in el.find_all("tr"):
row = [
_norm_text(td.get_text(" ", strip=True))
for td in tr.find_all(["th", "td"])
]
while row and not row[-1]:
row.pop()
if any(row):
rows.append(row)
if not rows:
continue
width = max(len(r) for r in rows)
norm = [r + [""] * (width - len(r)) for r in rows]
lines = [
"| " + " | ".join(norm[0]) + " |",
"| " + " | ".join(["---"] * width) + " |",
]
for r in norm[1:]:
lines.append("| " + " | ".join(r) + " |")
items.append(("table", "\n".join(lines)))
return items
def _extract_workflow_table_from_word_html(html_path: Path) -> tuple[str, list[str]]:
if not html_path.exists():
return "", []
try:
from bs4 import BeautifulSoup
except Exception:
return "", []
try:
html = _decode_word_html(html_path.read_bytes())
except Exception:
return "", []
source_stem = _word_export_source_stem_from_html(html_path)
files_by_name = _collect_word_export_image_files(source_stem, html_path.parent)
if not files_by_name:
return "", []
soup = BeautifulSoup(html, "html.parser")
body = soup.body or soup
_drop_deleted_revision_nodes(body)
uri_cache: dict[str, list[str]] = {}
for table in body.find_all("table"):
rows: list[list[str]] = []
used_uris: list[str] = []
has_images = False
for tr in table.find_all("tr"):
row: list[str] = []
for td in tr.find_all(["th", "td"]):
txt = _norm_text(td.get_text(" ", strip=True))
cell_uris: list[str] = []
for img in td.find_all("img"):
src = str(img.get("src") or "").strip()
if not src:
continue
name = src.replace("\\", "/").split("/")[-1].lower()
if not _WORD_EXPORT_IMAGE_NAME_RE.fullmatch(name):
continue
style = " ".join(
[
str(img.get("style") or ""),
str(
getattr(
getattr(img, "parent", None), "get", lambda *_: ""
)("style")
or ""
),
]
).lower()
w = int(str(img.get("width") or "0").strip() or 0)
h = int(str(img.get("height") or "0").strip() or 0)
if w > 0 and h > 0 and (max(w, h) <= 32 or (w * h) < 2000):
continue
if (
"position:absolute" in style
and w > 0
and h > 0
and w < 80
and h > 260
):
continue
image_file = files_by_name.get(name)
if image_file is None:
continue
if name not in uri_cache:
uri_cache[name] = _image_file_to_uris(image_file)
for uri in uri_cache[name]:
if uri not in cell_uris:
cell_uris.append(uri)
if cell_uris:
has_images = True
used_uris.extend(cell_uris)
imgs_md = "
".join(f"" for u in cell_uris)
row.append((txt + "
" if txt else "") + imgs_md)
else:
row.append(txt)
while row and not row[-1]:
row.pop()
if any(row):
rows.append(row)
if not rows or not has_images:
continue
header_text = " ".join(_norm_text(c) for c in rows[0] if c)
header_low = header_text.lower()
if "workflow" not in header_low and "工作流程" not in header_text:
continue
if "operation requirements" not in header_low and "作业要求" not in header_text:
continue
workflow_idx = next(
(
i
for i, c in enumerate(rows[0])
if "workflow" in c.lower() or "工作流程" in c
),
None,
)
if workflow_idx is not None:
img_md_pat = re.compile(
r"!\[table-image\]\(data:image/[a-zA-Z0-9.+-]+;base64,[A-Za-z0-9+/=]+\)"
)
for ridx in range(1, len(rows)):
row = rows[ridx]
while len(row) <= workflow_idx:
row.append("")
if row[workflow_idx].strip():
continue
for cidx, cell in enumerate(row):
if cidx == workflow_idx or "
if not imgs:
continue
cleaned = cell
for imd in imgs:
cleaned = cleaned.replace(imd, "")
cleaned = re.sub(r"(?:\s*
\s*){2,}", "
", cleaned).strip()
cleaned = re.sub(
r"^(?:
\s*)+|(?:\s*
)+$", "", cleaned
).strip()
row[cidx] = cleaned
row[workflow_idx] = "
".join(imgs)
break
width = max(len(r) for r in rows)
norm = [r + [""] * (width - len(r)) for r in rows]
lines = [
"| " + " | ".join(norm[0]) + " |",
"| " + " | ".join(["---"] * width) + " |",
]
for r in norm[1:]:
lines.append("| " + " | ".join(r) + " |")
return "\n".join(lines), used_uris
return "", []
def _remove_consumed_uris(all_uris: list[str], consumed_uris: list[str]) -> list[str]:
if not consumed_uris:
return all_uris
counts: dict[str, int] = {}
for uri in consumed_uris:
counts[uri] = counts.get(uri, 0) + 1
kept: list[str] = []
for uri in all_uris:
remain = counts.get(uri, 0)
if remain > 0:
counts[uri] = remain - 1
continue
kept.append(uri)
return kept
def _extract_org_side_nodes_from_word_html(html_path: Path) -> str:
if not html_path.exists():
return ""
try:
from bs4 import BeautifulSoup
except Exception:
return ""
try:
html = _decode_word_html(html_path.read_bytes())
except Exception:
return ""
soup = BeautifulSoup(html, "html.parser")
_drop_deleted_revision_nodes(soup)
labels: dict[str, str] = {}
for td in soup.find_all("td"):
txt = _norm_text(td.get_text(" ", strip=True))
if not txt:
continue
low = txt.lower()
if "report content" in low or "external report" in low or "外部报告" in txt:
continue
if re.search(r"\b(?:120|110|119)\b", txt):
continue
if "hospital" in low or "医院" in txt:
labels["hospital"] = txt
if "fire control" in low or "firecontrol" in low or "消防" in txt:
labels["fire"] = txt
if "public security" in low or "publicsecurity" in low or "公安" in txt:
labels["public"] = txt
if not labels:
return ""
ordered = [
labels.get("hospital", "医院 hospital"),
labels.get("fire", "消防 fire control"),
labels.get("public", "公安 Public Security"),
]
ordered = [re.sub(r"\s+", " ", x).strip(" ;;") for x in ordered if x]
if not ordered:
return ""
return "外部支援补充节点:" + ";".join(ordered)
def _inject_org_side_nodes_after_612(parsed: list[Block], text: str, idx: int) -> int:
if not text:
return idx
joined = "\n".join(
b.text for b in parsed if b.type in {"paragraph", "heading", "table"} and b.text
)
low = joined.lower()
if all(k in low for k in ["hospital", "fire control", "public security"]):
return idx
anchor = next(
(
i
for i, b in enumerate(parsed)
if b.type in {"paragraph", "heading"}
and b.text
and (
"6.1.1公司应急救援小组" in b.text
or re.match(r"^\s*6\.1\.1", b.text.strip())
)
),
None,
)
if anchor is None:
anchor = next(
(
i
for i, b in enumerate(parsed)
if b.type in {"paragraph", "heading"}
and b.text
and (
"6.1.2应急救援体系职责" in b.text
or re.match(r"^\s*6\.1\.2", b.text.strip())
)
),
None,
)
if anchor is None:
return idx
idx += 1
ay = float(parsed[anchor].bbox[3]) if parsed[anchor].bbox else float(anchor)
y = ay + 0.001
block = Block(
id=f"docx-{idx}",
page=1,
type="paragraph",
text=text,
bbox=(0.0, y, 100.0, y + 0.001),
)
parsed.insert(anchor + 1, block)
return idx
def _inject_word_workflow_table_images(
parsed: list[Block], html_path: Path
) -> list[str]:
table_md, consumed_uris = _extract_workflow_table_from_word_html(html_path)
if not table_md:
return []
target_idx = next(
(
i
for i, b in enumerate(parsed)
if b.type == "table"
and "![table-image]" not in (b.text or "")
and ("工作流程" in (b.text or "") or "workflow" in (b.text or "").lower())
and (
"作业要求" in (b.text or "")
or "operation requirements" in (b.text or "").lower()
)
),
None,
)
if target_idx is None:
return []
parsed[target_idx].text = table_md
return consumed_uris
def _extract_missing_611_blocks_from_word_html(
html_path: Path,
existing_text: str,
start_idx: int,
) -> list[Block]:
if "6.11" in existing_text:
return []
items = _extract_word_html_items(html_path)
if not items:
return []
paras = [v for k, v in items if k == "paragraph"]
cand = [i for i, p in enumerate(paras) if "6.11" in p]
if not cand:
return []
sec_start = None
for i in cand:
lo = max(0, i - 20)
if any("6.10" in paras[k] for k in range(lo, i)):
sec_start = i
break
if sec_start is None:
sec_start = cand[-1]
section: list[str] = []
j = sec_start
while j < len(paras):
nxt = paras[j]
if j > sec_start and re.match(r"^[一二三四五六七八九十]+、", nxt):
break
if j > sec_start and ("参考文件" in nxt or "相关表单" in nxt):
break
if (
j > sec_start
and re.match(r"^6\.\d{1,2}(?:\.\d+)?", nxt)
and not nxt.startswith("6.11")
):
break
section.append(nxt)
j += 1
section = [
ln
for ln in section
if ln
and not re.fullmatch(r"\d{4}/\d{1,2}/\d{1,2}(?:\s+\d{4}/\d{1,2}/\d{1,2})*", ln)
and not re.fullmatch(r"V\d+(?:\.\d+)?(?:\s+V\d+(?:\.\d+)?)*", ln)
]
out: list[Block] = []
idx = start_idx
heading = section[0] if section else ""
body = section[1:] if len(section) >= 2 else []
if heading and heading not in existing_text:
idx += 1
out.append(
Block(
id=f"docx-611-{idx}",
page=1,
type="paragraph",
text=heading,
bbox=(0.0, float(idx), 100.0, float(idx) + 1),
)
)
header_i = None
for i in range(0, max(0, len(body) - 4)):
h = body[i : i + 5]
if len(h) < 5:
continue
if "备注" in h[4] and ("设备" in h[2] or "设备" in h[3]):
header_i = i
break
if header_i is not None:
cells = body[header_i:]
header = cells[:5]
rows_raw = cells[5:]
rows: list[list[str]] = []
for i in range(0, len(rows_raw), 5):
chunk = rows_raw[i : i + 5]
if len(chunk) == 5:
rows.append(chunk)
if rows:
lines = [
"| " + " | ".join(header) + " |",
"| " + " | ".join(["---"] * 5) + " |",
]
for r in rows:
lines.append("| " + " | ".join(r) + " |")
table_md = "\n".join(lines)
if table_md not in existing_text:
idx += 1
out.append(
Block(
id=f"docx-611-table-{idx}",
page=1,
type="table",
text=table_md,
bbox=(0.0, float(idx), 100.0, float(idx) + 1),
)
)
elif body:
for p in body:
if p and p not in existing_text:
idx += 1
out.append(
Block(
id=f"docx-611-{idx}",
page=1,
type="paragraph",
text=p,
bbox=(0.0, float(idx), 100.0, float(idx) + 1),
)
)
return out
def _extract_missing_634_badge_table_from_word_html(
html_path: Path,
existing_text: str,
start_idx: int,
) -> list[Block]:
if "站别" in existing_text and "佩戴袖章标示" in existing_text:
return []
items = _extract_word_html_items(html_path)
if not items:
return []
anchors = [i for i, (k, v) in enumerate(items) if k == "paragraph" and "6.3.4" in v]
if not anchors:
return []
anchor_idx = anchors[-1]
table_md = None
for k, v in items[anchor_idx + 1 : anchor_idx + 40]:
if k != "table":
continue
if "站别" in v and "上岗证名称" in v and "佩戴袖章标示" in v:
table_md = v
break
if not table_md:
return []
idx = start_idx + 1
return [
Block(
id=f"docx-634-{idx}",
page=1,
type="table",
text=table_md,
bbox=(0.0, float(idx), 100.0, float(idx) + 1),
)
]
def _table_to_markdown(
table, doc, image_uri_by_rid: dict[str, str] | None = None
) -> str:
rows: list[list[str]] = []
seen_img_uri: set[str] = set()
for r in table.rows:
vals: list[str] = []
for c in r.cells:
txt = _cell_text_without_revisions(c)
img_uris: list[str] = []
try:
for para in c.paragraphs:
for uri in _extract_image_uris_from_paragraph(
para, doc, image_uri_by_rid
):
if uri in seen_img_uri:
continue
seen_img_uri.add(uri)
img_uris.append(uri)
except Exception:
img_uris = []
if img_uris:
imgs_md = "
".join(f"" for u in img_uris)
vals.append((txt + "
" if txt else "") + imgs_md)
else:
vals.append(txt)
if any(v for v in vals):
rows.append(vals)
if not rows:
return ""
width = max(len(r) for r in rows)
norm = [r + [""] * (width - len(r)) for r in rows]
for i, r in enumerate(norm):
vals = [v for v in r if v]
if not vals:
continue
if vals[0].startswith("备注"):
uniq = list(dict.fromkeys(vals))
if len(uniq) == 1:
norm[i] = [uniq[0]] + [""] * (width - 1)
continue
if len(set(vals)) == 1 and len(vals) >= 2:
norm[i] = [vals[0]] + [""] * (width - 1)
header = norm[0]
lines = [
"| " + " | ".join(header) + " |",
"| " + " | ".join(["---"] * width) + " |",
]
note_blocks: list[str] = []
for r in norm[1:]:
first = (r[0] or "").strip()
if first.startswith("备注") and not any((c or "").strip() for c in r[1:]):
note = re.sub(r"\s+", " ", first)
note = re.sub(r"\s*(\d+)\.", r"\n\1.", note)
note_blocks.append(note.strip())
continue
lines.append("| " + " | ".join(r) + " |")
if note_blocks:
lines.append("")
lines.extend(note_blocks)
return "\n".join(lines)
def _looks_like_form_metadata_table(md: str) -> bool:
flat = " ".join(md.split())
score = 0
for token in [
"文件类别",
"File category",
"文件编号",
"Document No",
"页 数 Page",
"制/修订日期",
"Issued/Revised Date",
]:
if token in flat:
score += 1
return score >= 3
def _table_markdown_to_paragraph_blocks(md: str, start_idx: int) -> list[Block]:
lines = [ln.strip() for ln in md.splitlines() if ln.strip()]
out: list[Block] = []
idx = start_idx
for line in lines:
if not line.startswith("|"):
continue
cells = [c.strip() for c in line.strip("|").split("|")]
cells = [c for c in cells if c and c != "---"]
if not cells:
continue
text = "\n".join(cells)
idx += 1
out.append(
Block(
id=f"docx-{idx}",
page=1,
type="paragraph",
text=text,
bbox=(0.0, float(idx), 100.0, float(idx) + 1),
)
)
return out
def _form_table_to_blocks(table, start_idx: int) -> list[Block]:
out: list[Block] = []
idx = start_idx
metadata_rows: list[list[str]] = []
for row in table.rows:
row_cells: list[list[str]] = []
for cell in row.cells:
parts = _cell_paragraph_texts_without_revisions(cell)
if parts:
row_cells.append(parts)
if not row_cells:
continue
flattened = [p for parts in row_cells for p in parts if p]
if not flattened:
continue
unique_flat = list(dict.fromkeys(flattened))
row_patterns = {tuple(parts) for parts in row_cells}
if len(row_patterns) == 1 and len(row_cells) >= 2:
first = (unique_flat[0] if unique_flat else "").strip()
if "文件修订履历" in first or "Document revision history" in first:
if metadata_rows:
width = max(len(r) for r in metadata_rows)
norm = [r + [""] * (width - len(r)) for r in metadata_rows]
idx += 1
out.append(
Block(
id=f"docx-{idx}",
page=1,
type="table",
text="\n".join(
[
"| " + " | ".join(norm[0]) + " |",
"| " + " | ".join(["---"] * width) + " |",
]
+ ["| " + " | ".join(r) + " |" for r in norm[1:]]
),
bbox=(0.0, float(idx), 100.0, float(idx) + 1),
)
)
metadata_rows = []
for para in unique_flat:
para = para.strip()
if not para:
continue
idx += 1
out.append(
Block(
id=f"docx-{idx}",
page=1,
type="paragraph",
text=para,
bbox=(0.0, float(idx), 100.0, float(idx) + 1),
)
)
continue
if first and not re.search(
r"^(?:[一二三四五六七八九十]+、|\d+\.\d+|[A-Za-z]+、)", first
):
metadata_rows.append(unique_flat)
continue
if metadata_rows:
width = max(len(r) for r in metadata_rows)
norm = [r + [""] * (width - len(r)) for r in metadata_rows]
idx += 1
out.append(
Block(
id=f"docx-{idx}",
page=1,
type="table",
text="\n".join(
[
"| " + " | ".join(norm[0]) + " |",
"| " + " | ".join(["---"] * width) + " |",
]
+ ["| " + " | ".join(r) + " |" for r in norm[1:]]
),
bbox=(0.0, float(idx), 100.0, float(idx) + 1),
)
)
metadata_rows = []
for para in unique_flat:
para = para.strip()
if not para:
continue
idx += 1
out.append(
Block(
id=f"docx-{idx}",
page=1,
type="paragraph",
text=para,
bbox=(0.0, float(idx), 100.0, float(idx) + 1),
)
)
continue
compact = [" / ".join(parts) for parts in row_cells if parts]
text = "\n".join(compact).strip()
if not text:
continue
metadata_rows.append(compact)
if metadata_rows:
width = max(len(r) for r in metadata_rows)
norm = [r + [""] * (width - len(r)) for r in metadata_rows]
idx += 1
out.append(
Block(
id=f"docx-{idx}",
page=1,
type="table",
text="\n".join(
[
"| " + " | ".join(norm[0]) + " |",
"| " + " | ".join(["---"] * width) + " |",
]
+ ["| " + " | ".join(r) + " |" for r in norm[1:]]
),
bbox=(0.0, float(idx), 100.0, float(idx) + 1),
)
)
return out
def _extract_header_lines(doc) -> list[str]:
out: list[str] = []
seen: set[str] = set()
for section in doc.sections:
header = section.header
for p in header.paragraphs:
s = _paragraph_text_without_revisions(p)
if s and s not in seen:
seen.add(s)
out.append(s)
for t in header.tables:
for r in t.rows:
vals = [_cell_text_without_revisions(c) for c in r.cells]
vals = [v for v in vals if v]
if not vals:
continue
s = " ".join(vals)
if s and s not in seen:
seen.add(s)
out.append(s)
return out
def _drop_cover_header_duplicates(blocks: list[Block]) -> list[Block]:
first_table_idx = next(
(i for i, b in enumerate(blocks[:12]) if b.type == "table"), None
)
if first_table_idx is None:
return blocks
table_text = blocks[first_table_idx].text or ""
if "文件类别" not in table_text and "File category" not in table_text:
return blocks
meta_pat = re.compile(
r"文件编号|Document No|文件名称|File name|制定部门|Preparation department|页 数|Page",
re.IGNORECASE,
)
kept: list[Block] = []
for i, block in enumerate(blocks):
if (
i < first_table_idx
and block.type == "paragraph"
and meta_pat.search(block.text or "")
):
continue
kept.append(block)
return kept
def _convert_doc_with_word(path: Path, out_dir: Path) -> Path:
out_dir.mkdir(parents=True, exist_ok=True)
output = out_dir / f"{path.stem}.docx"
return convert_with_word(path.resolve(), output.resolve(), 16)
def _convert_doc_to_docx(path: Path, out_dir: Path) -> Path:
"""
将 .doc 转为 .docx。
Windows 优先 Word COM;Linux/容器走 soffice_util(带 EDKB_SOFFICE_TIMEOUT_SEC 超时)。
"""
out_dir.mkdir(parents=True, exist_ok=True)
output = out_dir / f"{path.stem}.docx"
force_reconvert = str(
os.environ.get("EDKB_FORCE_DOC_RECONVERT", "")
).strip().lower() in {
"1",
"true",
"yes",
}
try:
if not force_reconvert and output.exists() and output.stat().st_size > 0:
return output
except Exception:
pass
errors: list[str] = []
if os.name == "nt":
try:
return _convert_doc_with_word(path, out_dir)
except Exception as exc:
errors.append(f"Word COM conversion failed: {exc}")
# 非 Windows:依次尝试 soffice 候选路径,单次转换受 soffice_util 超时保护
soffice_candidates_list = soffice_candidates()
for soffice in soffice_candidates_list:
if not soffice:
continue
try:
proc = convert_with_soffice(
soffice,
convert_to="docx",
source_path=path,
out_dir=out_dir,
)
except FileNotFoundError:
errors.append(f"soffice not found: {soffice}")
continue
except RuntimeError as exc:
errors.append(str(exc))
continue
if proc.returncode == 0 and output.exists():
return output
stderr = (proc.stderr or "").strip()
errors.append(
f"soffice failed ({soffice}, code={proc.returncode}): {stderr or 'no stderr'}"
)
joined = "; ".join(errors) if errors else "no converter attempted"
raise RuntimeError(
".doc 转 .docx 失败。请安装 LibreOffice(soffice)或本机 Microsoft Word。"
f" details: {joined}"
)
def run(input_data: dict, context: Context) -> list[Block]:
source_path = Path(input_data["file_path"]).resolve()
file_path = source_path
work_dir = Path(input_data["work_dir"]).resolve()
source_ext = source_path.suffix.lower()
if source_ext == ".doc":
file_path = _convert_doc_to_docx(file_path, work_dir)
def _parse_docx(docx_path: Path) -> list[Block]:
from docx import Document
from docx.oxml.table import CT_Tbl
from docx.oxml.text.paragraph import CT_P
from docx.table import Table
from docx.text.paragraph import Paragraph
parsed: list[Block] = []
doc = Document(str(docx_path))
image_uri_by_rid = _build_image_uri_map(doc)
num_to_abs, levels = _load_numbering_schema(docx_path)
list_states: dict[str, dict[int, int]] = {}
context.pages = 1
idx = 0
for line in _extract_header_lines(doc):
idx += 1
parsed.append(
Block(
id=f"docx-{idx}",
page=1,
type="paragraph",
text=line,
bbox=(0.0, float(idx), 100.0, float(idx) + 1),
)
)
for child in doc.element.body.iterchildren():
if isinstance(child, CT_P):
para = Paragraph(child, doc)
text = _paragraph_text_without_revisions(para).strip()
marker = ""
try:
ppr = para._p.pPr
if ppr is not None and ppr.numPr is not None:
ilvl = (
int(ppr.numPr.ilvl.val) if ppr.numPr.ilvl is not None else 0
)
num_id = (
str(ppr.numPr.numId.val)
if ppr.numPr.numId is not None
else ""
)
if num_id:
marker = _next_list_marker(
num_id, ilvl, num_to_abs, levels, list_states
)
except Exception:
marker = ""
if marker and text and not text.startswith(marker):
text = f"{marker} {text}"
image_uris = _extract_image_uris_from_paragraph(
para, doc, image_uri_by_rid
)
if text:
idx += 1
typ = (
"heading"
if para.style and "heading" in para.style.name.lower()
else "paragraph"
)
parsed.append(
Block(
id=f"docx-{idx}",
page=1,
type=typ,
text=text,
bbox=(0.0, float(idx), 100.0, float(idx) + 1),
)
)
for uri in image_uris:
idx += 1
context.images += 1
parsed.append(
Block(
id=f"docx-img-{idx}",
page=1,
type="image",
text="",
bbox=(0.0, float(idx), 100.0, float(idx) + 1),
meta={"data_uri": uri},
)
)
elif isinstance(child, CT_Tbl):
table = Table(child, doc)
md = _table_to_markdown(table, doc, image_uri_by_rid)
if md:
if _looks_like_form_metadata_table(md):
blocks = _form_table_to_blocks(table, idx)
if blocks:
idx += len(blocks)
parsed.extend(blocks)
else:
idx += 1
parsed.append(
Block(
id=f"docx-{idx}",
page=1,
type="table",
text=md,
bbox=(0.0, float(idx), 100.0, float(idx) + 1),
)
)
# 表格内图片已并入表格 markdown 单元格,避免脱离原始位置。
if not any(b.type == "image" for b in parsed):
for uri in _extract_all_image_uris_from_doc(doc, image_uri_by_rid):
idx += 1
context.images += 1
parsed.append(
Block(
id=f"docx-img-{idx}",
page=1,
type="image",
text="",
bbox=(0.0, float(idx), 100.0, float(idx) + 1),
meta={"data_uri": uri},
)
)
if source_ext == ".doc":
try:
word_export_dir = work_dir / "word_export"
word_images = _extract_images_with_word(source_path, word_export_dir)
html_path = word_export_dir / f"{source_path.stem}.word_export.html"
org_side_nodes = _extract_org_side_nodes_from_word_html(html_path)
consumed_uris = _inject_word_workflow_table_images(parsed, html_path)
if consumed_uris:
word_images = _remove_consumed_uris(word_images, consumed_uris)
current_imgs = [b for b in parsed if b.type == "image"]
if len(word_images) > len(current_imgs):
image_slots = [i for i, b in enumerate(parsed) if b.type == "image"]
replaced: list[Block] = []
used = 0
for b in parsed:
if b.type != "image":
replaced.append(b)
continue
if used < len(word_images):
uri = word_images[used]
used += 1
context.images += 1
replaced.append(
Block(
id=f"docx-img-{len(replaced) + 1}",
page=b.page,
type="image",
text="",
bbox=b.bbox,
meta={"data_uri": uri},
)
)
insert_at = image_slots[-1] + 1 if image_slots else len(replaced)
while used < len(word_images):
uri = word_images[used]
used += 1
context.images += 1
replaced.insert(
insert_at,
Block(
id=f"docx-img-{insert_at + 1}",
page=1,
type="image",
text="",
bbox=(
0.0,
float(insert_at + 1),
100.0,
float(insert_at + 2),
),
meta={"data_uri": uri},
),
)
insert_at += 1
parsed = replaced
if org_side_nodes:
idx = _inject_org_side_nodes_after_612(parsed, org_side_nodes, idx)
existing_text = "\n".join(
b.text
for b in parsed
if b.type in {"paragraph", "heading", "table"} and b.text
)
added = _extract_missing_611_blocks_from_word_html(
html_path,
existing_text,
len(parsed),
)
if added:
insert_at = next(
(
i
for i, b in enumerate(parsed)
if b.type in {"paragraph", "heading"}
and (
"参考文件" in (b.text or "")
or "相关表单" in (b.text or "")
)
),
len(parsed),
)
parsed = parsed[:insert_at] + added + parsed[insert_at:]
added_634 = _extract_missing_634_badge_table_from_word_html(
html_path,
"\n".join(
b.text
for b in parsed
if b.type in {"paragraph", "heading", "table"} and b.text
),
len(parsed),
)
if added_634:
anchor_y = None
for b in parsed:
if b.type in {"paragraph", "heading"} and "6.3.4" in (
b.text or ""
):
anchor_y = b.bbox[1]
break
if anchor_y is None:
anchor_y = float(len(parsed))
for n, blk in enumerate(added_634, start=1):
y = float(anchor_y) + 0.9 + 0.05 * n
blk.bbox = (0.0, y, 100.0, y + 0.01)
insert_at_634 = next(
(
i + 1
for i, b in enumerate(parsed)
if b.type in {"paragraph", "heading"}
and "6.3.4" in (b.text or "")
),
next(
(
i
for i, b in enumerate(parsed)
if b.type in {"paragraph", "heading"}
and re.match(r"^\s*[七七]、", (b.text or "").strip())
),
len(parsed),
),
)
parsed = parsed[:insert_at_634] + added_634 + parsed[insert_at_634:]
if word_images:
final_imgs = [b for b in parsed if b.type == "image"]
if len(final_imgs) < len(word_images):
seen = {
hashlib.sha1(
(b.meta or {}).get("data_uri", "").encode("utf-8")
).hexdigest()
for b in final_imgs
if (b.meta or {}).get("data_uri")
}
insert_at = len(parsed)
for uri in word_images:
key = hashlib.sha1(uri.encode("utf-8")).hexdigest()
if key in seen:
continue
seen.add(key)
insert_at += 1
context.images += 1
parsed.append(
Block(
id=f"docx-img-{insert_at}",
page=1,
type="image",
text="",
bbox=(
0.0,
float(insert_at),
100.0,
float(insert_at) + 1,
),
meta={"data_uri": uri},
)
)
except Exception:
pass
parsed = _drop_cover_header_duplicates(parsed)
return parsed
try:
return _parse_docx(file_path)
except Exception as exc:
if file_path.suffix.lower() == ".docx":
try:
repaired = _convert_doc_with_word(file_path, work_dir)
return _parse_docx(repaired)
except Exception as fix_exc:
try:
legacy = work_dir / f"{file_path.stem}.legacy.doc"
shutil.copyfile(file_path, legacy)
repaired = _convert_doc_with_word(legacy, work_dir)
return _parse_docx(repaired)
except Exception as legacy_exc:
context.warnings.append(
"DOCX fallback parser failed: "
f"{exc}; repair failed: {fix_exc}; legacy-doc repair failed: {legacy_exc}"
)
return []
context.warnings.append(f"DOCX fallback parser failed: {exc}")
return []