kbzhishiku

This commit is contained in:
runny committed 2026-05-12 08:16:42 +08:00
1 parent 7f542f54a5
commit 08a19ebe96
68 files changed
+16602 -229

No files matched your search

+1
View File
@@ -0,0 +1 @@
"""Atomic skills for enterprise KB pipeline."""
+90
View File
@@ -0,0 +1,90 @@
from __future__ import annotations
import hashlib
import re
from edkb_system.contracts import Chunk, Context
HEAD_RE = re.compile(r"^(#{1,6})\s+(.*)$")
def _chunk_id(source: str, heading: str, index: int, text: str) -> str:
raw = f"{source}|{heading}|{index}|{text}"
return hashlib.sha256(raw.encode("utf-8")).hexdigest()
def run(
input_data: dict,
context: Context,
max_chars: int = 1200,
overlap_chars: int = 150,
add_heading_path_prefix: bool = True,
) -> list[Chunk]:
source = input_data["source"]
md = input_data["text"]
lines = md.splitlines()
stack: list[str] = []
sections: list[tuple[str, str]] = []
buf: list[str] = []
def heading() -> str:
return " > ".join(stack) if stack else "ROOT"
for ln in lines:
m = HEAD_RE.match(ln.strip())
if m:
if buf:
sections.append((heading(), "\n".join(buf).strip()))
buf = []
level = len(m.group(1))
text = m.group(2).strip()
while len(stack) >= level:
stack.pop()
stack.append(text)
else:
buf.append(ln)
if buf:
sections.append((heading(), "\n".join(buf).strip()))
out: list[Chunk] = []
idx = 0
for hp, body in sections:
paras = [p.strip() for p in body.split("\n\n") if p.strip()]
acc = ""
for p in paras:
cand = (acc + "\n\n" + p).strip() if acc else p
if len(cand) <= max_chars:
acc = cand
continue
if acc:
txt = f"# {hp}\n{acc}" if add_heading_path_prefix else acc
out.append(
Chunk(
id=_chunk_id(source, hp, idx, txt),
heading_path=hp,
text=txt,
index=idx,
source=source,
)
)
idx += 1
overlap = txt[-overlap_chars:] if overlap_chars > 0 else ""
acc = (overlap + "\n\n" + p).strip()
else:
acc = p[:max_chars]
if acc:
txt = f"# {hp}\n{acc}" if add_heading_path_prefix else acc
out.append(
Chunk(
id=_chunk_id(source, hp, idx, txt),
heading_path=hp,
text=txt,
index=idx,
source=source,
)
)
idx += 1
return out
File diff suppressed because it is too large. Load diff
+244
View File
@@ -0,0 +1,244 @@
from __future__ import annotations
import hashlib
import json
import re
from dataclasses import asdict
from pathlib import Path
from typing import Any
from edkb_system.contracts import Block
def hash_text(text: str) -> str:
return hashlib.sha256(text.encode("utf-8")).hexdigest()
def hash_file(path: Path) -> str:
h = hashlib.sha256()
with path.open("rb") as f:
while True:
chunk = f.read(1024 * 1024)
if not chunk:
break
h.update(chunk)
return h.hexdigest()
def _page_image_structured_lines(payload: str) -> list[str]:
tokens = [x.strip() for x in payload.split(";") if x.strip()]
if not tokens:
return []
cert_context_hits = 0
cert_context_pat = re.compile(
r"證明書|证明书|CERTIFICATE|材质|材質|TEST CERTIFICATE|ROHS|MSDS|"
r"检测报告|測試報告|材质证明|物性表",
re.IGNORECASE,
)
for tok in tokens:
if cert_context_pat.search(tok):
cert_context_hits += 1
if cert_context_hits < 2:
return []
def _find(pattern: str) -> str:
rx = re.compile(pattern, re.IGNORECASE)
for tok in tokens:
if rx.search(tok):
return tok
return ""
def _find_match(pattern: str) -> str:
rx = re.compile(pattern, re.IGNORECASE)
for tok in tokens:
m = rx.search(tok)
if m:
return m.group(0)
return ""
def _find_after(anchor_pat: str, value_pat: str = r".+") -> str:
anchor_rx = re.compile(anchor_pat, re.IGNORECASE)
value_rx = re.compile(value_pat, re.IGNORECASE)
for idx, tok in enumerate(tokens):
if not anchor_rx.search(tok):
continue
for cand in tokens[idx + 1 : idx + 8]:
if value_rx.search(cand) and not anchor_rx.search(cand):
return cand
return ""
def _uniq(values: list[tuple[str, str]]) -> list[tuple[str, str]]:
out: list[tuple[str, str]] = []
seen: set[str] = set()
for key, value in values:
v = value.strip()
if not v:
continue
marker = f"{key}:{v.lower()}"
if marker in seen:
continue
seen.add(marker)
out.append((key, v))
return out
certificate_no = ""
cert_anchor = re.compile(
r"證明書编号|證明書編號|CERTIFICATE\s*(?:NO|NUMBER)?", re.IGNORECASE
)
cert_value = re.compile(r"(?=.*\d)[A-Z0-9][A-Z0-9/-]{5,}", re.IGNORECASE)
for idx, tok in enumerate(tokens):
if not cert_anchor.search(tok):
continue
for cand in tokens[idx + 1 : idx + 8]:
if re.search(r"fax|tel|date", cand, re.IGNORECASE):
continue
if cert_value.fullmatch(cand):
certificate_no = cand
break
if certificate_no:
break
if not certificate_no:
certificate_no = _find_match(
r"\b(?=[A-Z0-9-]*\d)[A-Z0-9]{4,}-[A-Z0-9-]+\b"
) or _find_match(r"\b\d{6,}[A-Z0-9/-]*\b")
issue_date = _find(
r"(?:JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)[A-Z.]*\s*\d{1,2},?\s*\d{4}"
)
spec = _find(r"JIS\s*G\d+|SGCC|EN\s*\d+")
product = _find_after(r"PRODUCT", r"[A-Z]{2,}[-A-Z0-9 ]{3,}|COIL") or _find(
r"HDG[-A-Z0-9 ]*COIL"
)
customer = _find(r"CORPORATION|COMPANY|STEEL")
order_no = _find_after(r"ORDER|訂單|订单", r"[A-Z0-9/-]{5,}") or _find(
r"[A-Z]{0,3}\d{3,}[A-Z0-9/-]*"
)
weight = ""
for idx, tok in enumerate(tokens):
if tok.lower() == "kg" and idx > 0:
m = re.search(r"\d{1,3}(?:,\d{3})*(?:\.\d+)?", tokens[idx - 1])
weight = (m.group(0) if m else tokens[idx - 1]) + " kg"
break
m = re.search(r"\d{1,3}(?:,\d{3})*(?:\.\d+)?\s*kg", tok, re.IGNORECASE)
if m:
weight = m.group(0)
break
tensile: list[tuple[str, str]] = []
for idx, tok in enumerate(tokens):
if tok in {"降伏", "抗拉", "硬度"}:
for cand in tokens[idx + 1 : idx + 4]:
if re.fullmatch(r"\d+(?:\.\d+)?", cand):
tensile.append((tok, cand))
break
fields = _uniq(
[
("证书编号", certificate_no),
("日期", issue_date),
("客户", customer),
("产品", product),
("规格", spec),
("订单/追踪号", order_no),
("重量", weight),
]
)
if not fields and not tensile:
return []
lines = ["## 识别整理版", ""]
for key, value in fields:
lines.append(f"- {key}:{value}")
if tensile:
if fields:
lines.append("")
lines.append("### 关键数值")
lines.append("")
lines.append("| 项目 | 数值 |")
lines.append("| --- | --- |")
for key, value in _uniq(tensile):
lines.append(f"| {key} | {value} |")
lines.extend(["", "## 原始识别结果", ""])
return lines
def blocks_to_plain_markdown(blocks: list[Block]) -> str:
def _ocr_payload(txt: str) -> str:
payload = txt
if payload.startswith("OCR_TEXT:"):
payload = payload[len("OCR_TEXT:") :].strip()
if not payload or payload == "<empty>":
return ""
payload = re.sub(r"(?m)^\s*-\s*", "", payload)
payload = ";".join(x.strip() for x in payload.splitlines() if x.strip())
return payload
ocr_by_image: dict[str, str] = {}
for b in blocks:
if b.type != "ocr_text" or not b.id.startswith("ocr-"):
continue
payload = _ocr_payload((b.text or "").strip())
if payload:
ocr_by_image[b.id[len("ocr-") :]] = payload
page_text_chars: dict[int, int] = {}
page_body_chars: dict[int, int] = {}
for b in blocks:
if b.type in {"ocr_text", "image"}:
continue
txt = (b.text or "").strip()
if not txt:
continue
page_text_chars[b.page] = page_text_chars.get(b.page, 0) + len(txt)
if b.type != "heading":
page_body_chars[b.page] = page_body_chars.get(b.page, 0) + len(txt)
lines: list[str] = []
image_idx = 0
for b in sorted(
[x for x in blocks if x.type != "ocr_text"],
key=lambda x: (x.page, x.cy(), x.cx()),
):
txt = (b.text or "").strip()
if not txt and b.type != "image":
continue
if b.type == "heading":
lines.append(f"## {txt}")
elif b.type == "image":
data_uri = b.meta.get("data_uri") if b.meta else None
if data_uri:
image_idx += 1
if b.meta and b.meta.get("page_image"):
lines.append(f"![page-image-{b.page}]({data_uri})")
else:
lines.append(f"![image-{image_idx}]({data_uri})")
ocr_text = ocr_by_image.get(b.id)
if ocr_text:
suppress_pptx_ocr = bool(
b.meta and b.meta.get("page_image_source") == "pptx"
) and (
page_body_chars.get(b.page, 0) >= 15
or page_text_chars.get(b.page, 0) >= 40
)
if (
b.meta
and b.meta.get("page_image")
and b.meta.get("page_image_source") != "pptx"
):
lines.extend(_page_image_structured_lines(ocr_text))
if not suppress_pptx_ocr:
lines.append(f"图中文字:{ocr_text}")
else:
lines.append("![image]")
else:
lines.append(txt)
return "\n\n".join(lines).strip() + "\n"
def dump_json(path: Path, data: Any) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
def block_to_dict(block: Block) -> dict[str, Any]:
return asdict(block)
+83
View File
@@ -0,0 +1,83 @@
from __future__ import annotations
import os
import subprocess
from pathlib import Path
from edkb_system.contracts import Context
from edkb_system.skills.word_bridge import convert_with_word
def _find_soffice() -> str | None:
candidates = [
os.environ.get("EDKB_SOFFICE"),
r"C:\Program Files\LibreOffice\program\soffice.exe",
r"C:\Program Files (x86)\LibreOffice\program\soffice.exe",
"soffice",
]
for c in candidates:
if not c:
continue
if c == "soffice":
return c
if Path(c).exists():
return c
return None
def _convert_with_word(path: Path, out_dir: Path) -> Path:
output = out_dir / f"{path.stem}.pdf"
return convert_with_word(path.resolve(), output.resolve(), 17)
def _convert_with_soffice(path: Path, out_dir: Path, soffice: str) -> Path:
output = out_dir / f"{path.stem}.pdf"
cmd = [
soffice,
"--headless",
"--convert-to",
"pdf",
str(path),
"--outdir",
str(out_dir),
]
proc = subprocess.run(cmd, capture_output=True, text=True)
if proc.returncode != 0:
stderr = (proc.stderr or "").strip() or "no stderr"
raise RuntimeError(
f"soffice conversion failed (code={proc.returncode}): {stderr}"
)
if not output.exists():
raise RuntimeError(f"soffice conversion produced no output: {output}")
return output
def run(input_data: dict, context: Context) -> dict:
file_path = Path(input_data["file_path"])
work_dir = Path(input_data["work_dir"])
out_dir = work_dir / "flow_pdf"
out_dir.mkdir(parents=True, exist_ok=True)
errors: list[str] = []
if os.name == "nt":
try:
pdf = _convert_with_word(file_path, out_dir)
return {"pdf_path": str(pdf), "converter": "word"}
except Exception as exc:
errors.append(f"word: {exc}")
soffice = _find_soffice()
if soffice:
try:
pdf = _convert_with_soffice(file_path, out_dir, soffice)
return {"pdf_path": str(pdf), "converter": "soffice"}
except Exception as exc:
errors.append(f"soffice: {exc}")
else:
errors.append("soffice: not found")
context.warnings.append(
"doc->pdf conversion unavailable; fallback to docx text parser"
)
context.warnings.append("doc->pdf details: " + "; ".join(errors))
return {"pdf_path": None, "converter": None}
+567
View File
@@ -0,0 +1,567 @@
from __future__ import annotations
import base64
import hashlib
import io
import json
import os
import re
import shutil
from dataclasses import asdict, replace
from pathlib import Path
from urllib.parse import quote, urlparse
from edkb_system.contracts import Block, Chunk, Context
def _write(path: Path, text: str) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(text, encoding="utf-8")
_EMBEDDED_IMG_RE = re.compile(
r"!\[(?P<alt>[^\]]*)\]\((?P<uri>data:image/(?P<fmt>[a-zA-Z0-9.+-]+);base64,(?P<b64>[^)]+))\)",
re.IGNORECASE | re.DOTALL,
)
_EMBEDDED_IMG_LOOSE_RE = re.compile(
r"!\[(?P<alt>[^\]]*)\]\((?P<uri>data:image/[^)]*)\)",
re.IGNORECASE | re.DOTALL,
)
_EMBEDDED_IMG_ANY_RE = re.compile(
r"!\[[^\]]*\]\(data:image/.*?\)",
re.IGNORECASE | re.DOTALL,
)
_KEEP_IMAGE = "__KEEP_EMBEDDED_IMAGE__"
_DROP_IMAGE = "__DROP_EMBEDDED_IMAGE__"
def _bool_env(name: str, default: bool) -> bool:
raw = os.getenv(name)
if raw is None:
return default
return raw.strip().lower() in {"1", "true", "yes", "on"}
def _sanitize_segment(raw: str) -> str:
s = (raw or "").strip()
if not s:
return "untitled"
s = re.sub(r"\s+", "_", s)
s = s.replace("/", "_").replace("\\", "_")
s = re.sub(r"[:*?\"<>|]", "_", s)
s = re.sub(r"_+", "_", s).strip("._")
return s or "untitled"
def _build_object_prefix(
source_category: str, source_rel_path: str, source_file: str
) -> str:
rel = (source_rel_path or source_file or "document").replace("\\", "/").strip("/")
parts = [p for p in rel.split("/") if p and p not in {".", ".."}]
category = _sanitize_segment(source_category)
if not category:
if len(parts) >= 2:
category = _sanitize_segment(parts[0])
else:
category = "uncategorized"
if parts and _sanitize_segment(parts[0]) == category:
parts = parts[1:]
if parts:
doc_parts = parts[:-1] + [Path(parts[-1]).stem or "document"]
else:
doc_parts = [Path(source_file or "document").stem or "document"]
normalized = [category] + [_sanitize_segment(p) for p in doc_parts]
normalized = [p for p in normalized if p]
return "/".join(normalized)
def _normalize_endpoint(raw_endpoint: str) -> tuple[str, bool]:
endpoint = (raw_endpoint or "").strip()
secure_default = False
if "://" in endpoint:
parsed = urlparse(endpoint)
secure_default = parsed.scheme.lower() == "https"
endpoint = parsed.netloc or parsed.path
endpoint = endpoint.strip().rstrip("/")
return endpoint, secure_default
def _normalize_public_base(raw_base: str, endpoint: str, secure: bool) -> str:
base = (raw_base or "").strip().rstrip("/")
if not base:
scheme = "https" if secure else "http"
return f"{scheme}://{endpoint}".rstrip("/")
if "://" not in base:
scheme = "https" if secure else "http"
return f"{scheme}://{base}".rstrip("/")
return base.rstrip("/")
def _quote_object_name(object_name: str) -> str:
return "/".join(quote(seg, safe="") for seg in object_name.split("/"))
def _ext_from_blob(blob: bytes) -> str | None:
if blob.startswith(b"\x89PNG\r\n\x1a\n"):
return "png"
if blob.startswith(b"\xff\xd8\xff"):
return "jpg"
if blob.startswith((b"GIF87a", b"GIF89a")):
return "gif"
if blob.startswith(b"BM"):
return "bmp"
if len(blob) >= 12 and blob[:4] == b"RIFF" and blob[8:12] == b"WEBP":
return "webp"
return None
def _normalize_ext(fmt: str, blob: bytes) -> str:
f = (fmt or "").lower().strip()
if f in {"jpeg", "jpg"}:
return "jpg"
if f in {"png", "gif", "bmp", "webp"}:
return f
guessed = _ext_from_blob(blob)
return guessed or "png"
def _content_type_for_ext(ext: str) -> str:
if ext == "jpg":
return "image/jpeg"
if ext == "png":
return "image/png"
if ext == "gif":
return "image/gif"
if ext == "bmp":
return "image/bmp"
if ext == "webp":
return "image/webp"
return "application/octet-stream"
def _is_valid_image_blob(blob: bytes) -> bool:
if len(blob) < 8:
return False
if _ext_from_blob(blob):
return True
# Unknown format fallback: keep only if not tiny garbage.
return len(blob) >= 64
class _MinioStorage:
def __init__(
self,
*,
endpoint: str,
bucket_name: str,
access_key: str,
secret_key: str,
secure: bool,
public_base: str,
) -> None:
import importlib
minio_mod = importlib.import_module("minio")
minio_ctor = getattr(minio_mod, "Minio")
self.bucket_name = bucket_name
self.public_base = public_base.rstrip("/")
self.client = minio_ctor(
endpoint,
access_key=access_key,
secret_key=secret_key,
secure=secure,
)
if not self.client.bucket_exists(bucket_name):
self.client.make_bucket(bucket_name)
def put_bytes(self, object_name: str, blob: bytes, content_type: str) -> None:
stream = io.BytesIO(blob)
self.client.put_object(
self.bucket_name,
object_name,
stream,
len(blob),
content_type=content_type,
)
def list_prefix(self, prefix: str) -> list[str]:
return [
obj.object_name
for obj in self.client.list_objects(
self.bucket_name,
prefix=prefix,
recursive=True,
)
]
def remove_object(self, object_name: str) -> None:
self.client.remove_object(self.bucket_name, object_name)
def build_url(self, object_name: str) -> str:
return (
f"{self.public_base}/{self.bucket_name}/{_quote_object_name(object_name)}"
)
class _RemoteImageRewriter:
def __init__(
self,
*,
context: Context,
source_file: str,
source_rel_path: str,
source_category: str,
) -> None:
self.context = context
self.source_file = source_file
self.source_rel_path = source_rel_path
self.source_category = source_category
self.object_prefix = _build_object_prefix(
source_category, source_rel_path, source_file
)
self.allow_embed_fallback = _bool_env("MINIO_ALLOW_EMBED_FALLBACK", False)
self.storage: _MinioStorage | None = None
self._storage_initialized = False
self.uri_cache: dict[str, str] = {}
self.sha_cache: dict[str, tuple[str, str]] = {}
self.referenced_objects: set[str] = set()
self.uploaded_count = 0
self.reused_count = 0
self.invalid_removed_count = 0
self.kept_embedded_count = 0
self.stale_removed_count = 0
self._upload_error_warn_count = 0
self._saw_embedded_image = False
self._next_image_index = 1
def _build_storage(self) -> _MinioStorage | None:
if not _bool_env("MINIO_UPLOAD_ENABLED", True):
if self.allow_embed_fallback:
self.context.warnings.append(
"image-hosting disabled by MINIO_UPLOAD_ENABLED"
)
return None
raise RuntimeError("image-hosting disabled by MINIO_UPLOAD_ENABLED")
endpoint_raw = os.getenv("MINIO_ENDPOINT", "127.0.0.1:9000")
endpoint, secure_default = _normalize_endpoint(endpoint_raw)
secure = _bool_env("MINIO_SECURE", secure_default)
if not endpoint:
if self.allow_embed_fallback:
self.context.warnings.append(
"image-hosting disabled: MINIO_ENDPOINT is empty"
)
return None
raise RuntimeError("image-hosting disabled: MINIO_ENDPOINT is empty")
bucket_name = os.getenv("MINIO_BUCKET", "image-hosting-service")
access_key = os.getenv("MINIO_ACCESS_KEY", "admin")
secret_key = os.getenv("MINIO_SECRET_KEY", "difyai123456")
public_base = _normalize_public_base(
os.getenv("MINIO_PUBLIC_BASE_URL", ""), endpoint, secure
)
try:
return _MinioStorage(
endpoint=endpoint,
bucket_name=bucket_name,
access_key=access_key,
secret_key=secret_key,
secure=secure,
public_base=public_base,
)
except Exception as exc:
if self.allow_embed_fallback:
self.context.warnings.append(
f"image-hosting unavailable, keep embedded image: {exc}"
)
return None
raise RuntimeError(f"image-hosting unavailable: {exc}")
def _warn_upload_error(self, msg: str) -> None:
if self._upload_error_warn_count < 5:
self.context.warnings.append(msg)
self._upload_error_warn_count += 1
def _ensure_storage(self) -> None:
if self._storage_initialized:
return
self.storage = self._build_storage()
self._storage_initialized = True
def _process_embedded_uri(self, uri: str, fmt: str, b64_raw: str) -> str:
cached = self.uri_cache.get(uri)
if cached is not None:
return cached
fmt = (fmt or "png").lower()
b64_clean = re.sub(r"\s+", "", b64_raw)
try:
blob = base64.b64decode(b64_clean, validate=False)
except Exception:
self.invalid_removed_count += 1
self.uri_cache[uri] = _DROP_IMAGE
return _DROP_IMAGE
if not _is_valid_image_blob(blob):
self.invalid_removed_count += 1
self.uri_cache[uri] = _DROP_IMAGE
return _DROP_IMAGE
self._ensure_storage()
if self.storage is None:
if not self.allow_embed_fallback:
raise RuntimeError(
"image-hosting unavailable: embedded fallback is disabled"
)
self.kept_embedded_count += 1
self.uri_cache[uri] = _KEEP_IMAGE
return _KEEP_IMAGE
sha = hashlib.sha256(blob).hexdigest()
cached_sha = self.sha_cache.get(sha)
if cached_sha is not None:
url, object_name = cached_sha
self.referenced_objects.add(object_name)
self.reused_count += 1
self.uri_cache[uri] = url
return url
ext = _normalize_ext(fmt, blob)
content_type = _content_type_for_ext(ext)
file_name = f"img_{self._next_image_index:03d}_{sha[:8]}.{ext}"
self._next_image_index += 1
object_name = (
f"{self.object_prefix}/{file_name}" if self.object_prefix else file_name
)
try:
self.storage.put_bytes(object_name, blob, content_type)
url = self.storage.build_url(object_name)
self.sha_cache[sha] = (url, object_name)
self.referenced_objects.add(object_name)
self.uploaded_count += 1
self.uri_cache[uri] = url
return url
except Exception as exc:
if not self.allow_embed_fallback:
raise RuntimeError(
f"image-hosting upload failed ({self.source_file}): {object_name} ({exc})"
) from exc
self.kept_embedded_count += 1
self.uri_cache[uri] = _KEEP_IMAGE
self._warn_upload_error(
f"image-hosting upload failed ({self.source_file}): {object_name} ({exc})"
)
return _KEEP_IMAGE
def _process_match(self, m: re.Match[str]) -> str:
return self._process_embedded_uri(
m.group("uri"),
m.group("fmt") or "png",
m.group("b64") or "",
)
def _process_loose_uri(self, uri: str) -> str:
cached = self.uri_cache.get(uri)
if cached is not None:
return cached
head, sep, b64_raw = uri.partition(",")
if not sep:
self.invalid_removed_count += 1
self.uri_cache[uri] = _DROP_IMAGE
return _DROP_IMAGE
fmt = "png"
m = re.match(r"^data:image/(?P<fmt>[a-zA-Z0-9.+-]+)", head, re.IGNORECASE)
if m:
fmt = (m.group("fmt") or "png").lower()
return self._process_embedded_uri(uri, fmt, b64_raw)
def replace_text(self, text: str) -> str:
if not text or "data:image/" not in text:
return text
self._saw_embedded_image = True
def repl(m: re.Match[str]) -> str:
alt = m.group("alt") or "image"
decision = self._process_match(m)
if decision == _DROP_IMAGE:
return ""
if decision == _KEEP_IMAGE:
return m.group(0)
return f"![{alt}]({decision})"
out = _EMBEDDED_IMG_RE.sub(repl, text)
if "data:image/" in out:
def loose_repl(m: re.Match[str]) -> str:
alt = m.group("alt") or "image"
decision = self._process_loose_uri(m.group("uri") or "")
if decision == _DROP_IMAGE:
return ""
if decision == _KEEP_IMAGE:
return m.group(0)
return f"![{alt}]({decision})"
out = _EMBEDDED_IMG_LOOSE_RE.sub(loose_repl, out)
if not self.allow_embed_fallback and "data:image/" in out:
dropped_before = self.invalid_removed_count
out = _EMBEDDED_IMG_LOOSE_RE.sub("", out)
out = _EMBEDDED_IMG_ANY_RE.sub("", out)
removed = self.invalid_removed_count - dropped_before
if "data:image/" in out:
self.context.warnings.append(
"image-hosting left non-markdown data:image content; kept as-is"
)
else:
self.context.warnings.append(
"image-hosting removed unsupported embedded images"
+ (f": {removed}" if removed > 0 else "")
)
out = re.sub(r"(?:\s*<br>\s*){2,}", " <br> ", out)
return out
def finalize(self) -> None:
if self._saw_embedded_image and _bool_env("MINIO_CLEANUP_STALE", True):
self._ensure_storage()
if self.storage is not None and _bool_env("MINIO_CLEANUP_STALE", True):
prefix = f"{self.object_prefix}/"
try:
for object_name in self.storage.list_prefix(prefix):
if object_name in self.referenced_objects:
continue
self.storage.remove_object(object_name)
self.stale_removed_count += 1
except Exception as exc:
self.context.warnings.append(
f"image-hosting cleanup failed ({self.source_file}): {exc}"
)
if self.invalid_removed_count > 0:
self.context.warnings.append(
f"image-hosting removed invalid images: {self.invalid_removed_count}"
)
if self.kept_embedded_count > 0 and self.storage is None:
self.context.warnings.append(
"image-hosting unavailable: keep legacy data:image embeds"
)
if (
self.uploaded_count > 0
or self.reused_count > 0
or self.stale_removed_count > 0
):
self.context.warnings.append(
"image-hosting synced "
f"(uploaded={self.uploaded_count}, reused={self.reused_count}, "
f"stale_removed={self.stale_removed_count}, prefix={self.object_prefix})"
)
def run(input_data: dict, context: Context) -> dict:
out_dir = Path(input_data["out_dir"])
out_dir.mkdir(parents=True, exist_ok=True)
source_file = input_data.get("source_file", "")
source_rel_path = input_data.get("source_rel_path", source_file)
source_category = input_data.get("source_category", "")
source_stem = Path(source_file).stem if source_file else out_dir.name
flat_clean_path = Path(
input_data.get("flat_md_path", out_dir.parent / f"{source_stem}.md")
)
view_clean_path = out_dir / "03_clean_view.md"
view_images_dir = out_dir / "images_view"
for p in [
out_dir / "01_raw_layout.json",
out_dir / "02_flow_procedure.md",
out_dir / "03_clean.md",
out_dir / "04_chunks.jsonl",
out_dir / "report.md",
view_clean_path,
flat_clean_path,
]:
if p.exists():
p.unlink()
chunks_dir = out_dir / "chunks"
if chunks_dir.exists():
shutil.rmtree(chunks_dir)
if view_images_dir.exists():
shutil.rmtree(view_images_dir)
clean_md: str = input_data.get("clean_md", "")
chunks: list[Chunk] = input_data.get("chunks", [])
blocks: list[Block] = input_data.get("blocks", [])
flow_markdowns: list[str] = input_data.get("flow_markdowns", [])
rewriter = _RemoteImageRewriter(
context=context,
source_file=source_file,
source_rel_path=source_rel_path,
source_category=source_category,
)
clean_md = rewriter.replace_text(clean_md)
exported_chunks = [replace(c, text=rewriter.replace_text(c.text)) for c in chunks]
rewriter.finalize()
_write(out_dir / "03_clean.md", clean_md)
_write(flat_clean_path, clean_md)
lines = [json.dumps(asdict(c), ensure_ascii=False) for c in exported_chunks]
_write(out_dir / "04_chunks.jsonl", "\n".join(lines) + ("\n" if lines else ""))
chunks_dir.mkdir(parents=True, exist_ok=True)
for c in exported_chunks:
_write(chunks_dir / f"chunk_{c.index:04d}.md", c.text + "\n")
if flow_markdowns:
_write(out_dir / "02_flow_procedure.md", "\n\n".join(flow_markdowns) + "\n")
_write(
out_dir / "01_raw_layout.json",
json.dumps([asdict(b) for b in blocks], ensure_ascii=False, indent=2) + "\n",
)
report_lines = [
f"# Report: {input_data.get('source_file', '')}",
"",
f"- pages: {context.pages}",
f"- images: {context.images}",
f"- ocr_characters: {context.ocr_characters}",
f"- flows_detected: {context.flows_detected}",
f"- confidence: {context.confidence:.2f}",
"",
"## warnings",
]
if context.warnings:
report_lines.extend([f"- {w}" for w in context.warnings])
else:
report_lines.append("- none")
report_lines.extend(
[
"",
"## recommended_dify_settings",
"- Index: High Quality",
"- Retrieval: Hybrid",
"- Chunking: General",
"",
]
)
_write(out_dir / "report.md", "\n".join(report_lines))
return {"out_dir": str(out_dir)}
@@ -0,0 +1,142 @@
from __future__ import annotations
from dataclasses import dataclass
import networkx as nx
from edkb_system.contracts import Block, Context
@dataclass
class Node:
id: str
text: str
page: int
kind: str
bbox: tuple[float, float, float, float]
def _is_decision(text: str) -> bool:
kws = ["判定", "判断", "是否", "if", "check"]
s = text.lower()
return any(k in s for k in kws)
def _dist(a: Node, b: Node) -> float:
ax = (a.bbox[0] + a.bbox[2]) / 2.0
ay = (a.bbox[1] + a.bbox[3]) / 2.0
bx = (b.bbox[0] + b.bbox[2]) / 2.0
by = (b.bbox[1] + b.bbox[3]) / 2.0
return ((ax - bx) ** 2 + (ay - by) ** 2) ** 0.5
def run(input_data: list[Block], context: Context) -> dict:
blocks = [
b
for b in input_data
if b.type in {"textbox", "shape", "diamond", "arrow_label", "paragraph"}
and b.text.strip()
]
by_page: dict[int, list[Block]] = {}
for b in blocks:
by_page.setdefault(b.page, []).append(b)
page_markdowns: list[str] = []
debug: list[dict] = []
for page in sorted(by_page):
cands = by_page[page]
nodes: list[Node] = []
labels: list[Node] = []
for b in cands:
text = b.text.strip()
if b.type == "arrow_label" or text.upper() in {
"NG",
"OK",
"Y",
"N",
"YES",
"NO",
}:
labels.append(Node(b.id, text, b.page, "label", b.bbox))
continue
kind = "decision" if (_is_decision(text) or b.type == "diamond") else "step"
nodes.append(Node(b.id, text, b.page, kind, b.bbox))
nodes = sorted(
nodes,
key=lambda n: (
(n.bbox[1] + n.bbox[3]) / 2.0,
(n.bbox[0] + n.bbox[2]) / 2.0,
),
)
if not nodes:
continue
g = nx.DiGraph()
for n in nodes:
g.add_node(n.id, node=n)
for i, src in enumerate(nodes[:-1]):
dst = nodes[i + 1]
g.add_edge(src.id, dst.id, label=None)
for dec in [n for n in nodes if n.kind == "decision"]:
right_steps = [
n
for n in nodes
if ((n.bbox[0] + n.bbox[2]) / 2.0) > ((dec.bbox[0] + dec.bbox[2]) / 2.0)
]
if right_steps:
target = min(right_steps, key=lambda x: _dist(dec, x))
label_node = None
right_labels = [
l
for l in labels
if ((l.bbox[0] + l.bbox[2]) / 2.0)
> ((dec.bbox[0] + dec.bbox[2]) / 2.0)
]
if right_labels:
label_node = min(right_labels, key=lambda x: _dist(dec, x))
g.add_edge(
dec.id, target.id, label=(label_node.text if label_node else "分支")
)
ordered = nodes
idx_map = {n.id: i + 1 for i, n in enumerate(ordered)}
cycles = list(nx.simple_cycles(g))
cyc_nodes = {nid for cyc in cycles for nid in cyc}
lines = [f"## Page {page} Procedure"]
for n in ordered:
title = n.text
if n.kind == "decision" and not title.startswith("判定"):
title = f"判定:{title}"
lines.append(f"{idx_map[n.id]}. {title}")
if n.kind == "decision":
for _, dst, data in g.out_edges(n.id, data=True):
if data.get("label") is None:
continue
label = data.get("label") or "分支"
if dst in cyc_nodes:
lines.append(f"- {label} -> 返回到步骤{idx_map.get(dst, '?')}")
else:
dst_text = g.nodes[dst]["node"].text
lines.append(f"- {label} -> {dst_text}")
page_markdowns.append("\n".join(lines))
debug.append(
{
"page": page,
"nodes": [
{"id": n.id, "text": n.text, "kind": n.kind, "bbox": list(n.bbox)}
for n in nodes
],
"edges": [
{"src": s, "dst": d, "label": data.get("label")}
for s, d, data in g.edges(data=True)
],
}
)
context.flows_detected = len(page_markdowns)
return {"flow_markdowns": page_markdowns, "debug": debug}
+419
View File
@@ -0,0 +1,419 @@
from __future__ import annotations
import re
import zipfile
from pathlib import Path
from edkb_system.config import RouterConfig
from edkb_system.contracts import Context, DocumentProfile
_DOC_KIND_STRATEGY = {
"flow_procedure": {
"enable": {"edkb-doc-to-pdf", "edkb-flow-reconstruct"},
"disable": set(),
},
"policy_text": {
"enable": set(),
"disable": {"edkb-doc-to-pdf", "edkb-flow-reconstruct"},
},
"tabular_record": {
"enable": set(),
"disable": {"edkb-doc-to-pdf", "edkb-flow-reconstruct"},
},
"mixed": {
"enable": {"edkb-doc-to-pdf", "edkb-flow-reconstruct"},
"disable": set(),
},
}
def _keyword_score(name: str, keywords: dict[str, float]) -> float:
score = 0.0
for k, w in keywords.items():
if k in name:
score += w
return score
def _score_text_keywords(text: str, keywords: dict[str, float]) -> float:
score = 0.0
for k, w in keywords.items():
if k in text:
score += w
return score
def _has_flow_evidence(stem: str, content: dict) -> bool:
name = stem.lower()
strong_name_hit = any(
k in name for k in ["流程", "流程图", "判定", "作业标准", "检验作业"]
)
flow_hits = int(content.get("flow_hits", 0) or 0)
shape_hits = int(content.get("shape_hits", 0) or 0)
if flow_hits >= 6:
return True
if flow_hits >= 3 and shape_hits >= 1:
return True
return strong_name_hit
def _probe_docx_xml(path: Path) -> dict:
signals = {
"has_text": False,
"table_hits": 0,
"flow_hits": 0,
"image_hits": 0,
"shape_hits": 0,
}
try:
with zipfile.ZipFile(path) as zf:
xml_parts = [
n for n in zf.namelist() if n.startswith("word/") and n.endswith(".xml")
]
xml_blob = ""
for n in xml_parts[:12]:
try:
xml_blob += zf.read(n).decode("utf-8", errors="ignore")
except Exception:
continue
except Exception:
return signals
if not xml_blob:
return signals
text = xml_blob.lower()
signals["has_text"] = bool(re.search(r"[a-z\u4e00-\u9fff]{2,}", text))
signals["table_hits"] = text.count("<w:tbl")
signals["image_hits"] = text.count("<a:blip") + text.count("<v:imagedata")
signals["shape_hits"] = (
text.count("<w:drawing") + text.count("<v:shape") + text.count("<wps:wsp")
)
flow_kw = {
"流程": 0.3,
"流程图": 0.4,
"判定": 0.25,
"检验": 0.2,
"作业": 0.15,
}
signals["flow_hits"] = int(_score_text_keywords(text, flow_kw) * 10)
return signals
def _probe_pdf(path: Path) -> dict:
signals = {
"has_text": False,
"table_hits": 0,
"flow_hits": 0,
"image_hits": 0,
"shape_hits": 0,
}
try:
blob = path.read_bytes()[: 2 * 1024 * 1024]
except Exception:
return signals
text = blob.decode("latin-1", errors="ignore")
signals["image_hits"] = text.count("/Subtype /Image") + text.count("/Image")
text_ops = text.count(" BT") + text.count(" ET")
signals["has_text"] = text_ops >= 10
return signals
def _probe_pptx(path: Path) -> dict:
signals = {
"has_text": False,
"table_hits": 0,
"flow_hits": 0,
"image_hits": 0,
"shape_hits": 0,
}
try:
with zipfile.ZipFile(path) as zf:
xml_parts = [
n
for n in zf.namelist()
if n.startswith("ppt/slides/") and n.endswith(".xml")
]
xml_blob = ""
for n in xml_parts[:20]:
try:
xml_blob += zf.read(n).decode("utf-8", errors="ignore")
except Exception:
continue
except Exception:
return signals
if not xml_blob:
return signals
text = xml_blob.lower()
signals["has_text"] = bool(re.search(r"[a-z\u4e00-\u9fff]{2,}", text))
signals["table_hits"] = text.count("<a:tbl")
signals["image_hits"] = text.count("<a:blip")
signals["shape_hits"] = text.count("<p:sp") + text.count("<p:cxnsp")
flow_kw = {"流程": 0.4, "流程图": 0.5, "送样": 0.3, "承认": 0.3, "判定": 0.25}
signals["flow_hits"] = int(_score_text_keywords(text, flow_kw) * 10)
return signals
def _probe_content(file_path: Path, ext: str) -> dict:
if ext == ".docx":
return _probe_docx_xml(file_path)
if ext == ".doc":
cache_docx = file_path.parents[1] / "cache" / f"{file_path.stem}.docx"
if cache_docx.exists():
return _probe_docx_xml(cache_docx)
return {
"has_text": False,
"table_hits": 0,
"flow_hits": 0,
"image_hits": 0,
"shape_hits": 0,
}
if ext == ".pdf":
return _probe_pdf(file_path)
if ext == ".pptx":
return _probe_pptx(file_path)
if ext == ".ppt":
cache_pptx = file_path.parents[1] / "cache" / f"{file_path.stem}.pptx"
if cache_pptx.exists():
return _probe_pptx(cache_pptx)
return {
"has_text": False,
"table_hits": 0,
"flow_hits": 0,
"image_hits": 0,
"shape_hits": 0,
}
if ext in {".xls", ".xlsx", ".csv"}:
return {
"has_text": True,
"table_hits": 8,
"flow_hits": 0,
"image_hits": 0,
"shape_hits": 0,
}
return {
"has_text": False,
"table_hits": 0,
"flow_hits": 0,
"image_hits": 0,
"shape_hits": 0,
}
def _build_pipeline(
ext: str,
doc_kind: str,
scan_likelihood: float,
cfg: RouterConfig,
) -> list[str]:
strategy = _DOC_KIND_STRATEGY.get(doc_kind, _DOC_KIND_STRATEGY["mixed"])
enable = set(strategy["enable"])
disable = set(strategy["disable"])
pipeline: list[str] = []
if ext in {".doc", ".docx"}:
pipeline.append("edkb-loader-docx")
if "edkb-doc-to-pdf" in enable and "edkb-doc-to-pdf" not in disable:
pipeline.append("edkb-doc-to-pdf")
elif ext == ".pdf":
pipeline.append("edkb-loader-pdf")
elif ext in {".ppt", ".pptx"}:
pipeline.append("edkb-loader-pptx")
elif ext in {".xls", ".xlsx"}:
pipeline.extend(["edkb-loader-excel", "edkb-table-linearize"])
elif ext == ".csv":
pipeline.extend(["edkb-loader-csv", "edkb-table-linearize"])
if ext in {".doc", ".docx", ".pdf", ".ppt", ".pptx"}:
if scan_likelihood >= cfg.scan_likelihood_threshold:
pipeline.append("edkb-ocr")
if "edkb-flow-reconstruct" in enable and "edkb-flow-reconstruct" not in disable:
pipeline.append("edkb-flow-reconstruct")
pipeline.extend(
[
"edkb-clean",
"edkb-chunk",
"edkb-quality-gate",
"edkb-export",
"edkb-postcheck",
]
)
return pipeline
def _decide_doc_kind(
stem: str, ext: str, content: dict
) -> tuple[str, float, float, float, list[str]]:
s = stem.lower()
reasons: list[str] = []
flow_pos = {
"流程图": 0.5,
"作业流程": 0.45,
"流程": 0.25,
"检验": 0.25,
"作业标准": 0.35,
"sop": 0.35,
"判定": 0.2,
"oqc": 0.2,
"iqc": 0.2,
}
flow_neg = {
"管理办法": 0.35,
"制度": 0.3,
"守则": 0.3,
"规定": 0.25,
"手册": 0.2,
}
table_pos = {
"台账": 0.45,
"清单": 0.35,
"记录": 0.25,
"表单": 0.4,
"excel": 0.4,
}
flow_raw = 0.35 + _keyword_score(s, flow_pos) - _keyword_score(s, flow_neg)
table_raw = 0.15 + _keyword_score(s, table_pos)
if ext in {".xls", ".xlsx", ".csv"}:
table_raw += 0.55
if ext == ".pdf":
flow_raw += 0.05
if ext in {".ppt", ".pptx"}:
flow_raw += 0.1
flow_raw += min(0.45, 0.04 * content.get("flow_hits", 0))
flow_raw += min(0.25, 0.02 * content.get("shape_hits", 0))
table_raw += min(0.55, 0.08 * content.get("table_hits", 0))
if content.get("image_hits", 0) >= 2 and ext in {
".doc",
".docx",
".pdf",
".ppt",
".pptx",
}:
flow_raw += 0.05
flow_likelihood = max(0.05, min(0.95, flow_raw))
table_likelihood = max(0.05, min(0.95, table_raw))
text_density = 0.55
flow_evidence = _has_flow_evidence(stem, content)
if not flow_evidence:
flow_likelihood = min(flow_likelihood, 0.59)
if content.get("table_hits", 0) >= 1:
table_likelihood = max(table_likelihood, 0.65)
if (
flow_evidence
and flow_likelihood >= 0.65
and (table_likelihood >= 0.5 or content.get("table_hits", 0) >= 1)
):
doc_kind = "mixed"
reasons.append("content indicates mixed flow+table document")
elif table_likelihood >= 0.75 and (flow_likelihood < 0.6 or not flow_evidence):
doc_kind = "tabular_record"
reasons.append("content indicates table-like document")
elif not flow_evidence and (
table_likelihood >= 0.5 or content.get("table_hits", 0) >= 1
):
doc_kind = "tabular_record"
reasons.append("content indicates text+table document without flow")
elif flow_evidence and flow_likelihood >= 0.65:
doc_kind = "flow_procedure"
reasons.append("content indicates flow/procedure document")
elif flow_likelihood <= 0.35 or not flow_evidence:
doc_kind = "policy_text"
reasons.append("content indicates policy/management text")
else:
doc_kind = "mixed"
reasons.append("content indicates mixed document")
return doc_kind, flow_likelihood, table_likelihood, text_density, reasons
def _derive_content_modes(
ext: str,
stem: str,
content: dict,
flow_likelihood: float,
table_likelihood: float,
) -> list[str]:
modes: set[str] = set()
if content.get("has_text") or ext in {
".doc",
".docx",
".pdf",
".ppt",
".pptx",
".xls",
".xlsx",
".csv",
}:
modes.add("text")
if content.get("image_hits", 0) > 0:
modes.add("image")
if table_likelihood >= 0.65 or content.get("table_hits", 0) >= 1:
modes.add("table")
if _has_flow_evidence(stem, content) and flow_likelihood >= 0.6:
modes.add("flow")
return sorted(modes)
def run(input_data: dict, context: Context, cfg: RouterConfig) -> DocumentProfile:
file_path = Path(input_data["file_path"])
ext = file_path.suffix.lower()
file_type = ext.lstrip(".")
size = file_path.stat().st_size if file_path.exists() else 0
has_tables = ext in {".xls", ".xlsx", ".csv"}
content_signals = _probe_content(file_path, ext)
doc_kind, flow_likelihood, table_likelihood, text_density, reasons = (
_decide_doc_kind(file_path.stem, ext, content_signals)
)
content_modes = _derive_content_modes(
ext, file_path.stem, content_signals, flow_likelihood, table_likelihood
)
scan_likelihood = 0.2
if ext == ".pdf" and size > 3 * 1024 * 1024:
scan_likelihood = 0.65
has_images = ext in {".pdf", ".doc", ".docx", ".ppt", ".pptx"}
pipeline = _build_pipeline(ext, doc_kind, scan_likelihood, cfg)
context.file_type = file_type
context.extras["intake"] = {
"doc_kind": doc_kind,
"content_modes": content_modes,
"route_reasons": reasons,
"strategy": {
"enable": sorted(_DOC_KIND_STRATEGY.get(doc_kind, {}).get("enable", set())),
"disable": sorted(
_DOC_KIND_STRATEGY.get(doc_kind, {}).get("disable", set())
),
},
"content_signals": content_signals,
"flow_likelihood": round(flow_likelihood, 3),
"table_likelihood": round(table_likelihood, 3),
"scan_likelihood": round(scan_likelihood, 3),
"pipeline": pipeline,
}
return DocumentProfile(
file_type=file_type,
text_density=text_density,
has_images=has_images,
has_tables=has_tables,
flow_likelihood=flow_likelihood,
scan_likelihood=scan_likelihood,
table_likelihood=table_likelihood,
language_hint="zh",
recommended_pipeline=pipeline,
)
+39
View File
@@ -0,0 +1,39 @@
from __future__ import annotations
import csv
from pathlib import Path
from edkb_system.contracts import Context
def run(input_data: dict, context: Context) -> dict:
file_path = Path(input_data["file_path"])
raw = None
for enc in ("utf-8-sig", "utf-8", "gb18030"):
try:
raw = file_path.read_text(encoding=enc)
break
except UnicodeDecodeError:
continue
if raw is None:
raw = file_path.read_text(errors="ignore")
sample = raw[:4096]
try:
dialect = csv.Sniffer().sniff(sample, delimiters=",;\t")
delim = dialect.delimiter
except Exception:
delim = ","
rows = [
r
for r in csv.reader(raw.splitlines(), delimiter=delim)
if any(c.strip() for c in r)
]
table = {
"sheet": "csv",
"headers": rows[0] if rows else [],
"rows": rows[1:] if len(rows) > 1 else [],
}
context.extras["tables_count"] = 1
return table
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,89 @@
from __future__ import annotations
import os
import subprocess
from pathlib import Path
from openpyxl import load_workbook
from edkb_system.contracts import Context
def _soffice_candidates() -> list[str]:
return [
os.environ.get("EDKB_SOFFICE", "").strip(),
r"C:\Program Files\LibreOffice\program\soffice.exe",
r"C:\Program Files (x86)\LibreOffice\program\soffice.exe",
"soffice",
]
def _convert_xls_to_xlsx(path: Path, out_dir: Path) -> Path:
out_dir.mkdir(parents=True, exist_ok=True)
output = out_dir / f"{path.stem}.xlsx"
errors: list[str] = []
for soffice in _soffice_candidates():
if not soffice:
continue
cmd = [
soffice,
"--headless",
"--convert-to",
"xlsx",
str(path),
"--outdir",
str(out_dir),
]
try:
proc = subprocess.run(cmd, capture_output=True, text=True)
except FileNotFoundError:
errors.append(f"soffice not found: {soffice}")
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(
".xls 转 .xlsx 失败。请安装 LibreOffice(soffice)或设置 EDKB_SOFFICE。"
f" details: {joined}"
)
def _norm(v) -> str:
return "" if v is None else str(v).strip()
def _trim_trailing_empty(vals: list[str]) -> list[str]:
end = len(vals)
while end > 0 and not vals[end - 1]:
end -= 1
return vals[:end]
def run(input_data: dict, context: Context) -> list[dict]:
file_path = Path(input_data["file_path"])
work_dir = Path(input_data["work_dir"])
if file_path.suffix.lower() == ".xls":
file_path = _convert_xls_to_xlsx(file_path, work_dir)
wb = load_workbook(str(file_path), data_only=True)
tables: list[dict] = []
for ws in wb.worksheets:
rows: list[list[str]] = []
for row in ws.iter_rows(values_only=True):
vals = _trim_trailing_empty([_norm(v) for v in row])
if any(vals):
rows.append(vals)
if not rows:
continue
width = max(len(r) for r in rows)
normalized = [r + [""] * (width - len(r)) for r in rows]
tables.append(
{"sheet": ws.title, "headers": normalized[0], "rows": normalized[1:]}
)
context.extras["tables_count"] = len(tables)
return tables
+250
View File
@@ -0,0 +1,250 @@
from __future__ import annotations
import base64
import io
from pathlib import Path
from edkb_system.contracts import Block, Context
def _is_scanned(text_chars: int, pages: int) -> bool:
return text_chars < int(300 * max(pages, 1) / 10)
def _to_data_uri(blob: bytes, content_type: str = "image/png") -> str:
b64 = base64.b64encode(blob).decode("ascii")
return f"data:{content_type};base64,{b64}"
def _normalize_box(
bounds: tuple[float, float, float, float],
) -> tuple[float, float, float, float]:
x0, y0, x1, y1 = bounds
left = min(x0, x1)
right = max(x0, x1)
top = min(y0, y1)
bottom = max(y0, y1)
return (left, top, right, bottom)
def _page_image_stats(
page_width: float,
page_height: float,
image_boxes: list[tuple[float, float, float, float]],
) -> dict[str, float]:
if page_width <= 0 or page_height <= 0 or not image_boxes:
return {
"count": float(len(image_boxes)),
"largest_ratio": 0.0,
"total_ratio": 0.0,
}
page_area = max(page_width * page_height, 1.0)
largest_ratio = 0.0
total_ratio = 0.0
for raw in image_boxes:
x0, y0, x1, y1 = _normalize_box(raw)
width = max(x1 - x0, 0.0)
height = max(y1 - y0, 0.0)
ratio = min((width * height) / page_area, 1.0)
largest_ratio = max(largest_ratio, ratio)
total_ratio += ratio
return {
"count": float(len(image_boxes)),
"largest_ratio": largest_ratio,
"total_ratio": min(total_ratio, 1.5),
}
def _should_use_page_image_mode(
*,
scan_likely: bool,
text_chars: int,
image_count: int,
largest_ratio: float,
total_ratio: float,
) -> bool:
if scan_likely:
if image_count == 0:
return True
if largest_ratio >= 0.55 or total_ratio >= 0.65 or image_count >= 3:
return True
if text_chars <= 120 and (
largest_ratio >= 0.72 or (image_count >= 5 and total_ratio >= 0.45)
):
return True
return False
def _collect_image_boxes(
file_path: Path, page_count: int
) -> dict[int, list[tuple[float, float, float, float]]]:
try:
import pypdfium2 as pdfium
import pypdfium2.raw as pdfium_c
except Exception:
return {}
out: dict[int, list[tuple[float, float, float, float]]] = {}
doc = None
try:
doc = pdfium.PdfDocument(str(file_path))
for page_idx in range(page_count):
page = doc[page_idx]
boxes: list[tuple[float, float, float, float]] = []
try:
for obj in page.get_objects(filter=[pdfium_c.FPDF_PAGEOBJ_IMAGE]):
try:
bounds = obj.get_bounds()
except Exception:
bounds = obj.get_pos()
boxes.append(tuple(float(v) for v in bounds))
except Exception:
boxes = []
out[page_idx + 1] = boxes
except Exception:
return {}
finally:
try:
if doc is not None:
doc.close()
except Exception:
pass
return out
def _render_page_png(
file_path: Path, page_number: int, scale: float = 2.0
) -> bytes | None:
try:
import pypdfium2 as pdfium
except Exception:
return None
doc = None
try:
doc = pdfium.PdfDocument(str(file_path))
page = doc[page_number - 1]
bitmap = page.render(scale=scale)
pil_image = bitmap.to_pil()
buf = io.BytesIO()
pil_image.save(buf, format="PNG")
return buf.getvalue()
except Exception:
return None
finally:
try:
if doc is not None:
doc.close()
except Exception:
pass
def run(input_data: dict, context: Context) -> list[Block]:
file_path = Path(input_data["file_path"])
blocks: list[Block] = []
try:
from pypdf import PdfReader
reader = PdfReader(str(file_path))
context.pages = len(reader.pages)
text_chars = 0
page_payloads: list[dict] = []
for page_idx, p in enumerate(reader.pages, start=1):
text = (p.extract_text() or "").strip()
images: list[dict] = []
if text:
text_chars += len(text)
try:
for img_idx, img in enumerate(getattr(p, "images", []) or [], start=1):
data = getattr(img, "data", None)
if not data:
continue
ext = (getattr(img, "image_format", "") or "").lower()
ct = f"image/{ext}" if ext else "image/png"
images.append({"id": img_idx, "data": data, "content_type": ct})
except Exception:
pass
page_payloads.append({"page": page_idx, "text": text, "images": images})
scan_likely = _is_scanned(text_chars, context.pages)
image_boxes_by_page = _collect_image_boxes(file_path, context.pages)
page_image_mode_pages: list[int] = []
for payload in page_payloads:
page_idx = int(payload["page"])
text = str(payload["text"] or "")
page_images = list(payload["images"])
image_boxes = image_boxes_by_page.get(page_idx, [])
stats = _page_image_stats(1000.0, 1000.0, image_boxes)
use_page_image_mode = _should_use_page_image_mode(
scan_likely=scan_likely,
text_chars=len(text),
image_count=len(page_images) or int(stats["count"]),
largest_ratio=float(stats["largest_ratio"]),
total_ratio=float(stats["total_ratio"]),
)
if text:
blocks.append(
Block(
id=f"pdf-{page_idx}",
page=page_idx,
type="paragraph",
text=text,
bbox=(0.0, 0.0, 1000.0, 1000.0),
)
)
if use_page_image_mode:
rendered = _render_page_png(file_path, page_idx)
if rendered:
blocks.append(
Block(
id=f"pdf-page-{page_idx}",
page=page_idx,
type="image",
text="",
bbox=(0.0, 0.0, 1000.0, 1000.0),
meta={
"data_uri": _to_data_uri(rendered, "image/png"),
"page_image": True,
},
)
)
context.images += 1
page_image_mode_pages.append(page_idx)
continue
for item in page_images:
blocks.append(
Block(
id=f"pdf-{page_idx}-img-{item['id']}",
page=page_idx,
type="image",
text="",
bbox=(0.0, 0.0, 1000.0, 1000.0),
meta={
"data_uri": _to_data_uri(
item["data"], str(item["content_type"])
)
},
)
)
context.images += 1
if scan_likely:
context.warnings.append("pdf likely scanned; OCR recommended")
context.extras["scan_likely"] = True
if page_image_mode_pages:
context.extras["pdf_page_image_mode_pages"] = page_image_mode_pages
context.warnings.append(
"pdf page-image mode pages: "
+ ", ".join(str(x) for x in page_image_mode_pages)
)
except Exception as exc:
context.warnings.append(f"PDF parse failed: {exc}")
return blocks
+478
View File
@@ -0,0 +1,478 @@
from __future__ import annotations
import base64
import hashlib
import io
import re
import subprocess
from pathlib import Path
from edkb_system.contracts import Block, Context
def _to_data_uri(blob: bytes, content_type: str) -> str:
return f"data:{content_type};base64,{base64.b64encode(blob).decode('ascii')}"
def _convert_ppt_to_pptx(path: Path, out_dir: Path) -> Path:
out_dir.mkdir(parents=True, exist_ok=True)
cmd = [
"soffice",
"--headless",
"--convert-to",
"pptx",
str(path),
"--outdir",
str(out_dir),
]
proc = subprocess.run(cmd, capture_output=True, text=True)
if proc.returncode != 0:
raise RuntimeError("Install LibreOffice to convert .ppt to .pptx")
output = out_dir / f"{path.stem}.pptx"
if not output.exists():
raise RuntimeError("Install LibreOffice to convert .ppt to .pptx")
return output
def _convert_presentation_to_pdf(path: Path, out_dir: Path) -> Path | None:
out_dir.mkdir(parents=True, exist_ok=True)
cmd = [
"soffice",
"--headless",
"--convert-to",
"pdf",
str(path),
"--outdir",
str(out_dir),
]
try:
proc = subprocess.run(cmd, capture_output=True, text=True)
except FileNotFoundError:
return None
if proc.returncode != 0:
return None
output = out_dir / f"{path.stem}.pdf"
return output if output.exists() else None
def _export_slide_pngs(path: Path, out_dir: Path) -> dict[int, bytes]:
out_dir.mkdir(parents=True, exist_ok=True)
app = None
pres = None
output: dict[int, bytes] = {}
try:
from win32com.client import DispatchEx
app = DispatchEx("PowerPoint.Application")
pres = app.Presentations.Open(str(path), WithWindow=False)
for idx, slide in enumerate(pres.Slides, start=1):
target = out_dir / f"slide_{idx:03d}.png"
slide.Export(str(target), "PNG")
if target.exists():
output[idx] = target.read_bytes()
except Exception:
return {}
finally:
if pres is not None:
try:
pres.Close()
except Exception:
pass
if app is not None:
try:
app.Quit()
except Exception:
pass
return output
def _norm_text(text: str) -> str:
return "\n".join(x.strip() for x in (text or "").splitlines() if x.strip()).strip()
def _shape_bbox(shape) -> tuple[float, float, float, float]:
left = float(getattr(shape, "left", 0))
top = float(getattr(shape, "top", 0))
width = float(getattr(shape, "width", 0))
height = float(getattr(shape, "height", 0))
return (left, top, left + width, top + height)
def _image_pixel_size(blob: bytes) -> tuple[int, int]:
try:
from PIL import Image
with Image.open(io.BytesIO(blob)) as im:
return int(im.width), int(im.height)
except Exception:
return (0, 0)
def _is_small_decorative_image(
blob: bytes, bbox: tuple[float, float, float, float], slide_area: float
) -> bool:
width_px, height_px = _image_pixel_size(blob)
pixel_area = max(width_px, 0) * max(height_px, 0)
box_area = max(bbox[2] - bbox[0], 0.0) * max(bbox[3] - bbox[1], 0.0)
if (
width_px
and height_px
and (width_px <= 48 or height_px <= 48 or pixel_area <= 6400)
):
return True
if slide_area > 0 and box_area / slide_area <= 0.015 and pixel_area <= 20000:
return True
return False
def _is_dominant_picture(
bbox: tuple[float, float, float, float], slide_area: float
) -> bool:
box_area = max(bbox[2] - bbox[0], 0.0) * max(bbox[3] - bbox[1], 0.0)
if slide_area <= 0:
return False
return box_area / slide_area >= 0.45
def _table_to_markdown(table) -> str:
rows: list[list[str]] = []
for row in table.rows:
vals = [
" ".join(
p.text.strip() for p in cell.text_frame.paragraphs if p.text.strip()
)
for cell in row.cells
]
vals = [v.strip() for v in vals]
if any(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]
header = norm[0]
body = norm[1:]
lines = [
"| " + " | ".join(header) + " |",
"| " + " | ".join(["---"] * width) + " |",
]
lines.extend("| " + " | ".join(r) + " |" for r in body)
return "\n".join(lines)
def _render_pdf_page_png(
pdf_path: Path, page_number: int, scale: float = 2.0
) -> bytes | None:
try:
import pypdfium2 as pdfium
except Exception:
return None
doc = None
try:
doc = pdfium.PdfDocument(str(pdf_path))
page = doc[page_number - 1]
bitmap = page.render(scale=scale)
pil_image = bitmap.to_pil()
buf = io.BytesIO()
pil_image.save(buf, format="PNG")
return buf.getvalue()
except Exception:
return None
finally:
try:
if doc is not None:
doc.close()
except Exception:
pass
def _crop_rendered_region(
rendered: bytes,
*,
crop_bbox: tuple[float, float, float, float],
slide_width: float,
slide_height: float,
padding: float = 0.03,
) -> bytes | None:
try:
from PIL import Image
with Image.open(io.BytesIO(rendered)) as im:
x0, y0, x1, y1 = crop_bbox
pad_x = slide_width * padding
pad_y = slide_height * padding
x0 = max(0.0, x0 - pad_x)
y0 = max(0.0, y0 - pad_y)
x1 = min(slide_width, x1 + pad_x)
y1 = min(slide_height, y1 + pad_y)
if x1 <= x0 or y1 <= y0:
return None
scale_x = im.width / max(slide_width, 1.0)
scale_y = im.height / max(slide_height, 1.0)
box = (
int(x0 * scale_x),
int(y0 * scale_y),
int(x1 * scale_x),
int(y1 * scale_y),
)
cropped = im.crop(box)
buf = io.BytesIO()
cropped.save(buf, format="PNG")
return buf.getvalue()
except Exception:
return None
def _union_bboxes(
boxes: list[tuple[float, float, float, float]],
) -> tuple[float, float, float, float] | None:
if not boxes:
return None
x0 = min(b[0] for b in boxes)
y0 = min(b[1] for b in boxes)
x1 = max(b[2] for b in boxes)
y1 = max(b[3] for b in boxes)
return (x0, y0, x1, y1)
def _bbox_overlap_ratio(
a: tuple[float, float, float, float], b: tuple[float, float, float, float]
) -> float:
ax0, ay0, ax1, ay1 = a
bx0, by0, bx1, by1 = b
ix0 = max(ax0, bx0)
iy0 = max(ay0, by0)
ix1 = min(ax1, bx1)
iy1 = min(ay1, by1)
if ix1 <= ix0 or iy1 <= iy0:
return 0.0
inter = (ix1 - ix0) * (iy1 - iy0)
area = max((ax1 - ax0) * (ay1 - ay0), 1.0)
return inter / area
def _pick_slide_title(flat_shapes) -> str:
candidates: list[tuple[float, float, str]] = []
for shape in flat_shapes:
if not getattr(shape, "has_text_frame", False):
continue
txt = _norm_text(getattr(shape, "text", ""))
if not txt:
continue
top = float(getattr(shape, "top", 0))
left = float(getattr(shape, "left", 0))
candidates.append((top, left, txt))
if not candidates:
return ""
candidates.sort(key=lambda x: (x[0], x[1]))
preferred_pat = re.compile(r"^(?:[一二三四五六七八九十]+、|\d+(?:\.\d+){0,2})")
for top, left, txt in candidates[:6]:
first_line = txt.splitlines()[0].strip()
if preferred_pat.match(first_line) and top <= 1200000:
return first_line
for top, left, txt in candidates[:6]:
first_line = txt.splitlines()[0].strip()
if 2 <= len(first_line) <= 30 and top <= 1800000:
return first_line
return candidates[0][2].splitlines()[0].strip()
def _iter_shapes(shapes):
from pptx.enum.shapes import MSO_SHAPE_TYPE
for shape in shapes:
yield shape
if getattr(shape, "shape_type", None) == MSO_SHAPE_TYPE.GROUP:
for child in _iter_shapes(shape.shapes):
yield child
def run(input_data: dict, context: Context) -> list[Block]:
file_path = Path(input_data["file_path"])
work_dir = Path(input_data["work_dir"])
if file_path.suffix.lower() == ".ppt":
file_path = _convert_ppt_to_pptx(file_path, work_dir)
from pptx import Presentation
from pptx.enum.shapes import MSO_SHAPE_TYPE
prs = Presentation(str(file_path))
slide_pngs = _export_slide_pngs(file_path, work_dir / f"{file_path.stem}_slides")
pdf_path = None if slide_pngs else _convert_presentation_to_pdf(file_path, work_dir)
context.pages = len(prs.slides)
blocks: list[Block] = []
img_idx = 0
blk_idx = 0
slide_area = float(prs.slide_width) * float(prs.slide_height)
for slide_no, slide in enumerate(prs.slides, start=1):
flat_shapes = list(_iter_shapes(slide.shapes))
title_text = _norm_text(
getattr(getattr(slide.shapes, "title", None), "text", "")
)
if not title_text:
title_text = _pick_slide_title(flat_shapes)
heading_text = f"第{slide_no}页"
if title_text:
heading_text = f"第{slide_no}页 {title_text}"
blk_idx += 1
blocks.append(
Block(
id=f"pptx-{slide_no}-heading-{blk_idx}",
page=slide_no,
type="heading",
text=heading_text,
bbox=(0.0, 0.0, 0.0, 0.0),
)
)
seen_image_hashes: set[str] = set()
dominant_pictures = 0
shape_heavy = 0
flow_boxes: list[tuple[float, float, float, float]] = []
suppress_all_images = title_text == "目录"
for shape in flat_shapes:
try:
if shape.shape_type == MSO_SHAPE_TYPE.PICTURE:
image = shape.image
bbox = _shape_bbox(shape)
blob_hash = hashlib.sha1(image.blob).hexdigest()
if blob_hash in seen_image_hashes:
continue
seen_image_hashes.add(blob_hash)
if _is_small_decorative_image(image.blob, bbox, slide_area):
continue
if _is_dominant_picture(bbox, slide_area):
dominant_pictures += 1
elif shape.shape_type in {
MSO_SHAPE_TYPE.AUTO_SHAPE,
MSO_SHAPE_TYPE.LINE,
MSO_SHAPE_TYPE.FREEFORM,
}:
shape_heavy += 1
bbox = _shape_bbox(shape)
mid_x = (bbox[0] + bbox[2]) / 2.0
if (
bbox[2] > bbox[0]
and bbox[3] > bbox[1]
and mid_x >= float(prs.slide_width) * 0.18
):
flow_boxes.append(bbox)
except Exception as exc:
context.warnings.append(f"pptx picture skipped: {exc}")
seen_image_hashes.clear()
render_flow_focus = (
(not suppress_all_images)
and bool(slide_pngs or pdf_path)
and shape_heavy >= 8
and dominant_pictures == 0
)
flow_crop: tuple[float, float, float, float] | None = None
if render_flow_focus:
rendered = slide_pngs.get(slide_no)
if rendered is None and pdf_path is not None:
rendered = _render_pdf_page_png(pdf_path, slide_no)
if rendered:
flow_crop = (0.0, 0.0, float(prs.slide_width), float(prs.slide_height))
img_idx += 1
blocks.append(
Block(
id=f"pptx-flow-{slide_no}-{img_idx}",
page=slide_no,
type="image",
text="",
bbox=flow_crop,
meta={
"data_uri": _to_data_uri(rendered, "image/png"),
"flow_focus": True,
"flow_focus_source": "pptx",
"rendered_slide": True,
},
)
)
for shape in flat_shapes:
try:
if getattr(shape, "has_table", False):
table_md = _table_to_markdown(shape.table)
if table_md:
blk_idx += 1
blocks.append(
Block(
id=f"pptx-{slide_no}-table-{blk_idx}",
page=slide_no,
type="table",
text=table_md,
bbox=_shape_bbox(shape),
)
)
continue
if shape.shape_type == MSO_SHAPE_TYPE.PICTURE:
if render_flow_focus or suppress_all_images:
continue
is_dominant = False
image = shape.image
bbox = _shape_bbox(shape)
blob_hash = hashlib.sha1(image.blob).hexdigest()
if blob_hash in seen_image_hashes:
continue
seen_image_hashes.add(blob_hash)
if _is_small_decorative_image(image.blob, bbox, slide_area):
continue
is_dominant = _is_dominant_picture(bbox, slide_area)
img_idx += 1
ext = (getattr(image, "ext", "png") or "png").lower()
ct = f"image/{'jpeg' if ext == 'jpg' else ext}"
meta: dict[str, object] = {
"data_uri": _to_data_uri(image.blob, ct),
"blob_sha1": blob_hash,
}
if is_dominant:
meta["page_image"] = True
meta["page_image_source"] = "pptx"
blocks.append(
Block(
id=f"pptx-img-{slide_no}-{img_idx}",
page=slide_no,
type="image",
text="",
bbox=bbox,
meta=meta,
)
)
continue
if getattr(shape, "has_text_frame", False):
txt = _norm_text(shape.text)
bbox = _shape_bbox(shape)
if not txt or txt == title_text:
continue
if title_text and txt.startswith(title_text):
txt = txt[len(title_text) :].lstrip("\n ::;;,,")
txt = _norm_text(txt)
if not txt:
continue
if re.fullmatch(r"\d+", txt):
continue
if flow_crop is not None and len(txt) <= 28:
continue
if txt and txt != title_text:
blk_idx += 1
blocks.append(
Block(
id=f"pptx-{slide_no}-text-{blk_idx}",
page=slide_no,
type="paragraph",
text=txt,
bbox=bbox,
)
)
except Exception as exc:
context.warnings.append(f"pptx shape skipped: {exc}")
context.extras["slides_count"] = len(prs.slides)
return blocks
+97
View File
@@ -0,0 +1,97 @@
from __future__ import annotations
import base64
import io
import re
from edkb_system.contracts import Block, Context
def _decode_data_uri_image(data_uri: str):
m = re.match(r"^data:image/[^;]+;base64,(.+)$", data_uri or "", re.DOTALL)
if not m:
return None
try:
raw = base64.b64decode(m.group(1), validate=False)
except Exception:
return None
try:
import numpy as np
from PIL import Image
with Image.open(io.BytesIO(raw)) as im:
return np.array(im.convert("RGB"))
except Exception:
return None
def run(
input_data: list[Block], context: Context, min_confidence: float = 0.3
) -> list[Block]:
blocks = input_data
try:
from rapidocr_onnxruntime import RapidOCR # type: ignore
except Exception:
context.warnings.append("RapidOCR unavailable; skip OCR")
return blocks
engine = RapidOCR()
out: list[Block] = []
for b in blocks:
out.append(b)
if b.type != "image":
continue
context.images += 1
image_obj = b.meta.get("image")
if image_obj is None and b.meta and b.meta.get("data_uri"):
image_obj = _decode_data_uri_image(str(b.meta.get("data_uri")))
if image_obj is None:
out.append(
Block(
id=f"ocr-{b.id}",
page=b.page,
type="ocr_text",
text="OCR_TEXT: <empty>",
bbox=b.bbox,
)
)
continue
try:
result, _ = engine(image_obj)
lines = []
for it in result or []:
if len(it) < 3:
continue
txt = str(it[1]).strip()
conf = float(it[2])
if txt and conf >= min_confidence:
lines.append(txt)
if lines:
text = "OCR_TEXT:\n" + "\n".join(f"- {x}" for x in lines)
context.ocr_characters += sum(len(x) for x in lines)
else:
text = "OCR_TEXT: <empty>"
out.append(
Block(
id=f"ocr-{b.id}",
page=b.page,
type="ocr_text",
text=text,
bbox=b.bbox,
)
)
except Exception as exc:
context.warnings.append(f"OCR failed: {exc}")
out.append(
Block(
id=f"ocr-{b.id}",
page=b.page,
type="ocr_text",
text="OCR_TEXT: <empty>",
bbox=b.bbox,
)
)
return out
+192
View File
@@ -0,0 +1,192 @@
from __future__ import annotations
import json
import re
from pathlib import Path
from edkb_system.contracts import Context
def _has_doc_meta(text: str) -> bool:
flat = " ".join(text.split())
has_header = bool(
re.search(r"制定部门.+制/修订日期.+页码", flat)
or re.search(r"Created Dept\..+Date.+Page", flat)
)
has_meta = bool(
re.search(r"文件编号.+文件级别.+版本", flat)
or re.search(r"Doc\.\s*No\..+File\s*Level.+Rev\.?", flat)
)
return has_header or has_meta
def _expect_doc_meta(text: str) -> bool:
keys = ["文件编号", "文件级别", "制/修订日期", "制定部门", "页码"]
return any(k in text for k in keys)
def _expect_flow_artifacts(text: str) -> bool:
if "作业流程图" not in text:
return False
hints = ["序号", "流程说明", "责任", "相关记录"]
return sum(1 for h in hints if h in text) >= 2
def _expect_related_forms_table(text: str) -> bool:
if "相关表单" not in text:
return False
return ("表单编号" in text) or bool(re.search(r"PB-\d{2,}", text))
def _has_source_images(out_dir: Path) -> bool:
raw = out_dir / "01_raw_layout.json"
if not raw.exists():
return False
try:
data = json.loads(raw.read_text(encoding="utf-8"))
if isinstance(data, list):
for b in data:
if isinstance(b, dict) and b.get("type") == "image":
return True
except Exception:
return False
return False
def _has_markdown_image_reference(text: str) -> bool:
for m in re.finditer(r"!\[[^\]]*\]\(([^)]+)\)", text):
target = (m.group(1) or "").strip()
if target.startswith("data:image/"):
return True
if target.startswith("http://") or target.startswith("https://"):
return True
return False
def _has_remote_image_url(text: str) -> bool:
for m in re.finditer(r"!\[[^\]]*\]\(([^)]+)\)", text):
target = (m.group(1) or "").strip()
if target.startswith("http://") or target.startswith("https://"):
return True
return False
def _expect_revision_table(text: str) -> bool:
if "文件修订履历" in text:
return True
hint = ["日期", "修订章节", "主要修订内容", "版本", "修改人"]
return sum(1 for h in hint if h in text) >= 4
def _collect_issues(text: str) -> list[dict]:
issues: list[dict] = []
lines = text.splitlines()
num_pat = re.compile(r"^\s*\d+(?:\.\d+){1,4}\s+")
non_empty = [(i + 1, ln.strip()) for i, ln in enumerate(lines) if ln.strip()]
if len(non_empty) >= 2:
l1, s1 = non_empty[0]
l2, s2 = non_empty[1]
if "文件编号" in s1 and "文件编号" not in s2 and not s2.startswith("制定部门"):
if not re.match(r"^[一二三四五六七八九十]+、", s2):
issues.append(
{
"code": "title_below_meta",
"line": l1,
"text": f"meta before title: {s1[:80]}",
}
)
for i, ln in enumerate(lines, start=1):
s = ln.strip()
if not s:
continue
if s.startswith("|"):
continue
if re.search(r"\d+\.\d+(?:\.\d+)?\s+.+\s+\d+\.\d+(?:\.\d+)?\s+", s):
issues.append(
{"code": "inline_numbered_sections", "line": i, "text": s[:180]}
)
if re.search(r"[七八]、参考文件\s+[七八]、相关表单", s):
issues.append({"code": "inline_section_titles", "line": i, "text": s[:180]})
for i in range(1, len(lines) - 1):
if lines[i].strip():
continue
prev = lines[i - 1].strip()
nxt = lines[i + 1].strip()
if num_pat.match(prev) and num_pat.match(nxt):
issues.append(
{
"code": "blank_between_numbered_sections",
"line": i + 1,
"text": f"{prev[:70]} / {nxt[:70]}",
}
)
return issues
def run(input_data: dict, context: Context) -> dict:
out_dir = Path(input_data["out_dir"])
clean_md = input_data.get("clean_md", "")
checks = {
"has_doc_meta": _has_doc_meta(clean_md),
"has_revision_table": bool(
(re.search(r"\|\s*(?:日期|文件日期)\b", clean_md) is not None)
and re.search(r"\|\s*.*修订章节", clean_md)
and re.search(r"\|\s*版本\b", clean_md)
),
"has_flow_table": "| 序号 | 流程说明 | 责任部门 | 相关记录 |" in clean_md,
"has_related_forms_table": bool(
re.search(r"\|\s*表单编号\s*\|", clean_md)
and re.search(r"\|\s*[-:]{3,}\s*\|", clean_md)
),
"has_flow_file": (out_dir / "02_flow_procedure.md").exists(),
"has_embedded_images": _has_markdown_image_reference(clean_md),
"has_remote_image_urls": _has_remote_image_url(clean_md),
}
flow_expected = _expect_flow_artifacts(clean_md)
expected = {
"has_doc_meta": _expect_doc_meta(clean_md),
"has_revision_table": _expect_revision_table(clean_md),
"has_flow_table": flow_expected,
"has_related_forms_table": _expect_related_forms_table(clean_md),
"has_flow_file": flow_expected,
"has_embedded_images": _has_source_images(out_dir),
}
failed_required = [k for k, v in expected.items() if v and not checks.get(k, False)]
status = "pass" if not failed_required else "fail"
issues = _collect_issues(clean_md)
if expected["has_embedded_images"] and not checks["has_embedded_images"]:
issues.append(
{
"code": "image_not_embedded",
"line": 0,
"text": "source has image blocks but markdown has no image references",
}
)
if "data:image/" in clean_md:
issues.append(
{
"code": "legacy_base64_image",
"line": 0,
"text": "markdown still contains legacy data:image base64 payload",
}
)
return {
"status": status,
"checks": checks,
"expected": expected,
"failed_required": failed_required,
"issues": issues,
"issue_count": len(issues),
"warnings_count": len(context.warnings),
}
@@ -0,0 +1,23 @@
from __future__ import annotations
from edkb_system.contracts import Chunk, Context
def run(input_data: list[Chunk], context: Context) -> list[Chunk]:
chunks = input_data
if not chunks:
context.warnings.append("quality_gate: no chunks generated")
context.confidence = min(context.confidence, 0.5)
return chunks
short_count = sum(1 for c in chunks if len(c.text.strip()) < 60)
if short_count:
context.warnings.append(f"quality_gate: {short_count} short chunks")
context.confidence = min(context.confidence, 0.8)
unique_texts = len({c.text for c in chunks})
if unique_texts < len(chunks):
context.warnings.append("quality_gate: duplicate chunks detected")
context.confidence = min(context.confidence, 0.75)
return chunks
@@ -0,0 +1,55 @@
from __future__ import annotations
from edkb_system.contracts import Context
COND_KWS = ["条件", "判定", "if", "IF"]
ACT_KWS = ["处理", "动作", "措施", "结果", "输出"]
OWN_KWS = ["责任", "负责人", "部门", "岗位"]
def _find_col(headers: list[str], kws: list[str]) -> int | None:
for i, h in enumerate(headers):
s = (h or "").lower()
if any(k.lower() in s for k in kws):
return i
return None
def _to_table_md(headers: list[str], rows: list[list[str]]) -> str:
hs = [h or "-" for h in headers]
out = ["| " + " | ".join(hs) + " |", "| " + " | ".join(["---"] * len(hs)) + " |"]
for r in rows:
vals = [r[i] if i < len(r) else "" for i in range(len(hs))]
out.append("| " + " | ".join(vals) + " |")
return "\n".join(out)
def run(input_data: list[dict] | dict, context: Context) -> str:
tables = input_data if isinstance(input_data, list) else [input_data]
parts: list[str] = []
for t in tables:
headers = [str(x).strip() for x in t.get("headers", [])]
rows = [[str(c).strip() for c in row] for row in t.get("rows", [])]
parts.append(f"## Sheet: {t.get('sheet', 'Sheet1')}")
cidx = _find_col(headers, COND_KWS)
aidx = _find_col(headers, ACT_KWS)
oidx = _find_col(headers, OWN_KWS)
if cidx is not None and aidx is not None:
for row in rows:
cond = row[cidx] if cidx < len(row) else "满足条件"
act = row[aidx] if aidx < len(row) else "执行处理"
owner = (
row[oidx] if oidx is not None and oidx < len(row) else "相关责任方"
)
parts.append(
f"- 当 {cond or '满足条件'} 时,{owner or '相关责任方'} 执行 {act or '执行处理'}。"
)
else:
parts.append(_to_table_md(headers, rows))
parts.append("")
return "\n".join(parts).strip() + "\n"
+249
View File
@@ -0,0 +1,249 @@
from __future__ import annotations
import os
import subprocess
import sys
import threading
import time
import ctypes
from pathlib import Path
def _list_winword_pids() -> set[int]:
if os.name != "nt":
return set()
try:
proc = subprocess.run(
["tasklist", "/FO", "CSV", "/NH", "/FI", "IMAGENAME eq WINWORD.EXE"],
capture_output=True,
text=True,
check=False,
)
except Exception:
return set()
out: set[int] = set()
for line in (proc.stdout or "").splitlines():
line = line.strip()
if not line or line.startswith("INFO:"):
continue
cols = [part.strip().strip('"') for part in line.split('","')]
if len(cols) < 2:
cols = [part.strip().strip('"') for part in line.split(",")]
if len(cols) < 2:
continue
try:
out.add(int(cols[1]))
except ValueError:
continue
return out
def _kill_winword_pids(pids: set[int]) -> None:
if os.name != "nt":
return
for pid in sorted(pids):
try:
subprocess.run(
["taskkill", "/PID", str(pid), "/F"],
capture_output=True,
text=True,
check=False,
)
except Exception:
continue
def _word_timeout_sec() -> int:
raw = str(os.environ.get("EDKB_WORD_TIMEOUT_SEC", "120")).strip()
try:
value = int(raw)
except ValueError:
value = 120
return max(value, 10)
def _should_accept_word_dialog(
window_title: str, child_texts: list[str], button_texts: list[str]
) -> bool:
text_blob = "\n".join(x.strip().lower() for x in child_texts if x.strip())
if not text_blob:
return False
has_repair_prompt = any(
token in text_blob
for token in [
"出现严重错误",
"是否仍要打开",
"serious error",
"do you still want to open",
]
)
if not has_repair_prompt:
return False
return any(
text.strip().lower().startswith(("是", "yes")) or "&y" in text.lower()
for text in button_texts
)
def _start_word_dialog_watcher() -> tuple[threading.Event, threading.Thread | None]:
stop_event = threading.Event()
if os.name != "nt":
return stop_event, None
def _window_text(user32, hwnd: int) -> str:
length = user32.GetWindowTextLengthW(hwnd)
if length <= 0:
return ""
buf = ctypes.create_unicode_buffer(length + 1)
user32.GetWindowTextW(hwnd, buf, length + 1)
return buf.value
def _class_name(user32, hwnd: int) -> str:
buf = ctypes.create_unicode_buffer(256)
user32.GetClassNameW(hwnd, buf, 255)
return buf.value
def _click_yes_if_needed() -> None:
user32 = ctypes.windll.user32
bm_click = 0x00F5
vk_return = 0x0D
wm_keydown = 0x0100
wm_keyup = 0x0101
while not stop_event.is_set():
windows: list[int] = []
@ctypes.WINFUNCTYPE(ctypes.c_bool, ctypes.c_void_p, ctypes.c_void_p)
def enum_windows(hwnd, lparam):
windows.append(int(hwnd))
return True
user32.EnumWindows(enum_windows, 0)
for hwnd in windows:
title = _window_text(user32, hwnd)
cls = _class_name(user32, hwnd).lower()
if "Microsoft Word" not in title and cls != "#32770":
continue
child_hwnds: list[int] = []
@ctypes.WINFUNCTYPE(ctypes.c_bool, ctypes.c_void_p, ctypes.c_void_p)
def enum_children(child_hwnd, lparam):
child_hwnds.append(int(child_hwnd))
return True
user32.EnumChildWindows(hwnd, enum_children, 0)
child_texts = [_window_text(user32, child) for child in child_hwnds]
button_hwnds = [
child
for child in child_hwnds
if _class_name(user32, child).lower() == "button"
]
button_texts = [_window_text(user32, child) for child in button_hwnds]
if not _should_accept_word_dialog(title, child_texts, button_texts):
continue
user32.SetForegroundWindow(hwnd)
for child, text in zip(button_hwnds, button_texts):
normalized = text.strip().lower()
if normalized.startswith(("是", "yes")) or "&y" in normalized:
user32.SendMessageW(child, bm_click, 0, 0)
break
else:
user32.PostMessageW(hwnd, wm_keydown, vk_return, 0)
user32.PostMessageW(hwnd, wm_keyup, vk_return, 0)
stop_event.wait(0.5)
thread = threading.Thread(target=_click_yes_if_needed, daemon=True)
thread.start()
return stop_event, thread
def convert_with_word(path: Path, output: Path, file_format: int) -> Path:
timeout = _word_timeout_sec()
before_pids = _list_winword_pids()
cmd = [
sys.executable,
"-m",
"edkb_system.skills.word_bridge",
str(path),
str(output),
str(file_format),
]
try:
proc = subprocess.run(
cmd,
capture_output=True,
text=True,
timeout=timeout,
check=False,
)
except subprocess.TimeoutExpired as exc:
after_pids = _list_winword_pids()
_kill_winword_pids(after_pids - before_pids)
raise RuntimeError(
f"Word conversion timed out after {timeout}s: {path.name}"
) from exc
if proc.returncode != 0:
err = (proc.stderr or proc.stdout or "unknown error").strip()
raise RuntimeError(f"Word conversion failed: {err}")
if not output.exists() or output.stat().st_size <= 0:
raise RuntimeError(f"Word conversion produced no output: {output}")
return output
def _child_main(argv: list[str]) -> int:
if len(argv) != 4:
print("usage: word_bridge <input> <output> <file_format>", file=sys.stderr)
return 2
src = Path(argv[1]).resolve()
out = Path(argv[2]).resolve()
file_format = int(argv[3])
out.parent.mkdir(parents=True, exist_ok=True)
stop_event, watcher = _start_word_dialog_watcher()
word = None
doc = None
try:
from win32com.client import DispatchEx
word = DispatchEx("Word.Application")
word.Visible = False
word.DisplayAlerts = 0
try:
word.Options.SaveNormalPrompt = False
except Exception:
pass
doc = word.Documents.Open(
FileName=str(src),
ReadOnly=True,
AddToRecentFiles=False,
ConfirmConversions=False,
NoEncodingDialog=True,
OpenAndRepair=True,
)
doc.SaveAs(str(out), FileFormat=file_format)
finally:
stop_event.set()
if watcher is not None:
watcher.join(timeout=1)
if doc is not None:
try:
doc.Close(False)
except Exception:
pass
if word is not None:
try:
word.Quit()
except Exception:
pass
return 0
if __name__ == "__main__":
raise SystemExit(_child_main(sys.argv))