perf(kb):1.优化 PDF只对可疑页做 image box 分析避免整本重复扫描/重复 reopen;2.doc/.docx 不再因为“有图片”就强制 OCR;3.只在 intake 路由 明确要求 OCR 时才跑
This commit is contained in:
1 parent
a3123cd602
commit
c58ed37cc1
11 files changed
+717
-122
No files matched your search
@@ -17,6 +17,9 @@ 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"
|
||||
@@ -25,18 +28,64 @@ def _to_data_uri(blob: bytes, content_type: str | None = None) -> str:
|
||||
|
||||
|
||||
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:
|
||||
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)
|
||||
return _to_data_uri(out.getvalue(), "image/jpeg")
|
||||
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:
|
||||
return _to_data_uri(blob, content_type)
|
||||
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]:
|
||||
@@ -209,14 +258,24 @@ def _split_tall_image(blob: bytes, ext: str) -> list[bytes]:
|
||||
return [blob]
|
||||
|
||||
|
||||
def _extract_image_uris_from_paragraph(para, doc) -> list[str]:
|
||||
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)
|
||||
@@ -226,42 +285,34 @@ def _extract_image_uris_from_paragraph(para, doc) -> list[str]:
|
||||
return uris
|
||||
|
||||
|
||||
def _extract_all_image_uris_from_doc(doc) -> list[str]:
|
||||
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()
|
||||
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 _, 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)
|
||||
uri = _to_preferred_image_data_uri(blob, content_type)
|
||||
key = hashlib.sha1(blob).hexdigest()
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
uris.append(uri)
|
||||
except Exception:
|
||||
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) -> list[str]:
|
||||
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):
|
||||
for uri in _extract_image_uris_from_paragraph(
|
||||
para, doc, image_uri_by_rid
|
||||
):
|
||||
if uri in seen:
|
||||
continue
|
||||
seen.add(uri)
|
||||
@@ -1298,7 +1349,9 @@ def _extract_missing_634_badge_table_from_word_html(
|
||||
]
|
||||
|
||||
|
||||
def _table_to_markdown(table, doc) -> str:
|
||||
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:
|
||||
@@ -1308,7 +1361,9 @@ def _table_to_markdown(table, doc) -> str:
|
||||
img_uris: list[str] = []
|
||||
try:
|
||||
for para in c.paragraphs:
|
||||
for uri in _extract_image_uris_from_paragraph(para, doc):
|
||||
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)
|
||||
@@ -1664,6 +1719,7 @@ def run(input_data: dict, context: Context) -> list[Block]:
|
||||
|
||||
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
|
||||
@@ -1706,7 +1762,9 @@ def run(input_data: dict, context: Context) -> list[Block]:
|
||||
|
||||
if marker and text and not text.startswith(marker):
|
||||
text = f"{marker} {text}"
|
||||
image_uris = _extract_image_uris_from_paragraph(para, doc)
|
||||
image_uris = _extract_image_uris_from_paragraph(
|
||||
para, doc, image_uri_by_rid
|
||||
)
|
||||
if text:
|
||||
idx += 1
|
||||
typ = (
|
||||
@@ -1738,7 +1796,7 @@ def run(input_data: dict, context: Context) -> list[Block]:
|
||||
)
|
||||
elif isinstance(child, CT_Tbl):
|
||||
table = Table(child, doc)
|
||||
md = _table_to_markdown(table, 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)
|
||||
@@ -1760,7 +1818,7 @@ def run(input_data: dict, context: Context) -> list[Block]:
|
||||
# 表格内图片已并入表格 markdown 单元格,避免脱离原始位置。
|
||||
|
||||
if not any(b.type == "image" for b in parsed):
|
||||
for uri in _extract_all_image_uris_from_doc(doc):
|
||||
for uri in _extract_all_image_uris_from_doc(doc, image_uri_by_rid):
|
||||
idx += 1
|
||||
context.images += 1
|
||||
parsed.append(
|
||||
|
||||
Reference in new issue
Block a user