Skip to content

Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.

feat: enhance PDF font analysis with Latin and CJK usage detection

myhlolia2e5bc23097a
diff --git a/mineru/utils/pdf_classify.py b/mineru/utils/pdf_classify.py
index 886cf4b8..7a7276d3 100644
--- a/mineru/utils/pdf_classify.py
+++ b/mineru/utils/pdf_classify.py
@@ -21,6 +21,11 @@ TEXT_QUALITY_BAD_THRESHOLD = 0.03
UNICODE_MAP_ERROR_RATIO_THRESHOLD = 0.04
CID_FONT_USAGE_RATIO_THRESHOLD = 0.01
CID_FONT_USAGE_COUNT_THRESHOLD = 30
+LATIN_CJK_FONT_USAGE_RATIO_THRESHOLD = 0.01
+LATIN_CJK_FONT_USAGE_COUNT_THRESHOLD = 30
+LATIN_CJK_FONT_CJK_RATIO_THRESHOLD = 0.8
+LATIN_CHARSET_MIN_LATIN_GLYPHS = 10
+LATIN_CHARSET_MIN_LATIN_RATIO = 0.5
MAX_PAGE_ASPECT_RATIO = 10.0
SUSPICIOUS_CJK_72XX_START = 0x7280
SUSPICIOUS_CJK_72XX_END = 0x72DF
@@ -125,10 +130,13 @@ def classify(pdf_doc: pdfium.PdfDocument, pdf_bytes: bytes) -> str:
)
return "ocr"
- cid_font_signal = get_cid_font_signal_pypdf(pdf_bytes, page_indices)
+ font_resource_signals = _get_font_resource_signals_pypdf(
+ pdf_bytes,
+ page_indices,
+ )
cid_font_usage_signal = _get_cid_font_usage_signal_from_samples(
text_samples,
- cid_font_signal,
+ font_resource_signals["cid_without_to_unicode"],
)
if cid_font_usage_signal["triggered"]:
logger.debug(
@@ -141,6 +149,26 @@ def classify(pdf_doc: pdfium.PdfDocument, pdf_bytes: bytes) -> str:
)
return "ocr"
+ latin_cjk_font_usage_signal = _get_latin_font_cjk_usage_signal_from_samples(
+ text_samples,
+ font_resource_signals["latin_charset_with_to_unicode"],
+ count_threshold=LATIN_CJK_FONT_USAGE_COUNT_THRESHOLD,
+ usage_ratio_threshold=LATIN_CJK_FONT_USAGE_RATIO_THRESHOLD,
+ cjk_ratio_threshold=LATIN_CJK_FONT_CJK_RATIO_THRESHOLD,
+ )
+ if latin_cjk_font_usage_signal["triggered"]:
+ logger.debug(
+ "Classify PDF as OCR due to Latin CharSet font decoding as CJK: "
+ f"page={latin_cjk_font_usage_signal['page_index'] + 1}, "
+ f"fonts={latin_cjk_font_usage_signal['font_names']}, "
+ f"chars={latin_cjk_font_usage_signal['font_char_count']}, "
+ f"cjk={latin_cjk_font_usage_signal['cjk_char_count']}, "
+ f"total={latin_cjk_font_usage_signal['total_chars']}, "
+ f"usage_ratio={latin_cjk_font_usage_signal['font_usage_ratio']:.4f}, "
+ f"cjk_ratio={latin_cjk_font_usage_signal['font_cjk_ratio']:.4f}"
+ )
+ return "ocr"
+
text_quality_signal = _get_text_quality_signal_from_samples(text_samples)
total_chars = text_quality_signal["total_chars"]
abnormal_ratio = text_quality_signal["abnormal_ratio"]
@@ -261,9 +289,16 @@ def _collect_pdfium_text_sample_from_page(page_index: int, page: Any) -> dict[st
private_use_char_count = 0
unicode_map_error_count = 0
font_name_counts = {}
+ non_generated_char_count = 0
+ font_non_generated_char_counts = {}
+ font_non_generated_cjk_char_counts = {}
for char_index in range(char_count):
unicode_code = pdfium_c.FPDFText_GetUnicode(text_page, char_index)
+ is_generated = pdfium_c.FPDFText_IsGenerated(text_page, char_index) == 1
+ if not is_generated:
+ non_generated_char_count += 1
+
if unicode_code == 0:
null_char_count += 1
elif unicode_code == 0xFFFD:
@@ -279,6 +314,14 @@ def _collect_pdfium_text_sample_from_page(page_index: int, page: Any) -> dict[st
font_name = _normalize_pdf_font_name(_get_pdfium_char_font_name(text_page, char_index))
if font_name:
font_name_counts[font_name] = font_name_counts.get(font_name, 0) + 1
+ if not is_generated:
+ font_non_generated_char_counts[font_name] = (
+ font_non_generated_char_counts.get(font_name, 0) + 1
+ )
+ if _is_cjk_unicode_code(unicode_code):
+ font_non_generated_cjk_char_counts[font_name] = (
+ font_non_generated_cjk_char_counts.get(font_name, 0) + 1
+ )
return {
"page_index": page_index,
@@ -291,6 +334,9 @@ def _collect_pdfium_text_sample_from_page(page_index: int, page: Any) -> dict[st
"private_use_char_count": private_use_char_count,
"unicode_map_error_count": unicode_map_error_count,
"font_name_counts": font_name_counts,
+ "non_generated_char_count": non_generated_char_count,
+ "font_non_generated_char_counts": font_non_generated_char_counts,
+ "font_non_generated_cjk_char_counts": font_non_generated_cjk_char_counts,
}
finally:
close_pdfium_child(text_page)
@@ -385,11 +431,94 @@ def _get_unicode_map_error_signal_from_samples(text_samples: list[dict[str, Any]
}
+def _is_cjk_unicode_code(unicode_code: int) -> bool:
+ """判断 Unicode 码点是否属于分类器认可的 CJK 文本范围。"""
+ return any(start <= unicode_code <= end for start, end in CJK_TEXT_RANGES)
+
+
+def _get_cjk_glyph_name_code(glyph_name: str) -> int | None:
+ """解析 uniXXXX/uXXXXX 形式的 CJK glyph name,其他名称返回 None。"""
+ match = re.fullmatch(
+ r"(?:uni([0-9A-Fa-f]{4,6})|u([0-9A-Fa-f]{4,6}))",
+ glyph_name,
+ )
+ if match is None:
+ return None
+ unicode_code = int(match.group(1) or match.group(2), 16)
+ if not _is_cjk_unicode_code(unicode_code):
+ return None
+ return unicode_code
+
+
+def _get_empty_latin_charset_with_to_unicode_signal() -> dict[str, Any]:
+ """构造未触发的 Type1 Latin CharSet 字体候选信号。"""
+ return {
+ "triggered": False,
+ "charset_glyph_count": 0,
+ "latin_glyph_count": 0,
+ "latin_glyph_ratio": 0.0,
+ "cjk_charset_glyph_count": 0,
+ "cjk_charset_glyph_ratio": 0.0,
+ }
+
+
+def _get_latin_charset_with_to_unicode_signal(font: Any) -> dict[str, Any]:
+ """识别带 ToUnicode 且 CharSet 明显为 Latin 的 Type1 字体候选。"""
+ signal = _get_empty_latin_charset_with_to_unicode_signal()
+ if str(font.get("/Subtype")) != "/Type1":
+ return signal
+
+ descriptor = _resolve_pdf_object(font.get("/FontDescriptor"))
+ to_unicode = _resolve_pdf_object(font.get("/ToUnicode"))
+ if descriptor is None or to_unicode is None:
+ return signal
+
+ charset = descriptor.get("/CharSet")
+ if charset is None:
+ return signal
+
+ glyph_names = set(re.findall(r"/([^/\s]+)", str(charset)))
+ charset_glyph_count = len(glyph_names)
+ latin_glyph_count = sum(
+ 1 for glyph_name in glyph_names if re.fullmatch(r"[A-Za-z]", glyph_name)
+ )
+ cjk_charset_glyph_count = sum(
+ 1
+ for glyph_name in glyph_names
+ if _get_cjk_glyph_name_code(glyph_name) is not None
+ )
+ latin_glyph_ratio = (
+ latin_glyph_count / charset_glyph_count if charset_glyph_count else 0.0
+ )
+ cjk_charset_glyph_ratio = (
+ cjk_charset_glyph_count / charset_glyph_count
+ if charset_glyph_count
+ else 0.0
+ )
+
+ signal.update(
+ {
+ "charset_glyph_count": charset_glyph_count,
+ "latin_glyph_count": latin_glyph_count,
+ "latin_glyph_ratio": latin_glyph_ratio,
+ "cjk_charset_glyph_count": cjk_charset_glyph_count,
+ "cjk_charset_glyph_ratio": cjk_charset_glyph_ratio,
+ }
+ )
+ signal["triggered"] = (
+ latin_glyph_count >= LATIN_CHARSET_MIN_LATIN_GLYPHS
+ and latin_glyph_ratio >= LATIN_CHARSET_MIN_LATIN_RATIO
+ and cjk_charset_glyph_count == 0
+ )
+ return signal
+
+
def _normalize_pdf_font_name(font_name: Any) -> str:
"""规范化 PDF 字体名,统一 pypdf 的 NameObject 和 PDFium 返回值格式。"""
if font_name is None:
return ""
- return str(font_name).strip().lstrip("/")
+ normalized_name = str(font_name).strip().lstrip("/")
+ return re.sub(r"^[A-Z]{6}\+", "", normalized_name, count=1)
def _get_pdfium_char_font_name(text_page: Any, char_index: int) -> str:
@@ -475,6 +604,79 @@ def _get_cid_font_usage_signal_from_samples(
return best_signal
+def _get_latin_font_cjk_usage_signal_from_samples(
+ text_samples: list[dict[str, Any]],
+ font_signal: dict[str, Any],
+ count_threshold: int,
+ usage_ratio_threshold: float,
+ cjk_ratio_threshold: float,
+) -> dict[str, Any]:
+ """按单个 Latin 候选字体统计实际使用量及 PDFium 解码后的 CJK 比例。"""
+ best_signal = {
+ "triggered": False,
+ "page_index": None,
+ "font_names": [],
+ "font_char_count": 0,
+ "cjk_char_count": 0,
+ "total_chars": 0,
+ "font_usage_ratio": 0.0,
+ "font_cjk_ratio": 0.0,
+ }
+ if not font_signal or not font_signal.get("triggered"):
+ return best_signal
+
+ page_fonts = font_signal.get("page_fonts") or {}
+ for text_sample in text_samples:
+ page_index = text_sample.get("page_index")
+ total_chars = text_sample.get("non_generated_char_count", 0)
+ if total_chars <= 0:
+ continue
+
+ font_name_counts = text_sample.get("font_non_generated_char_counts") or {}
+ font_cjk_char_counts = text_sample.get("font_non_generated_cjk_char_counts") or {}
+ candidate_font_names = {
+ _normalize_pdf_font_name(font_name)
+ for font_name in page_fonts.get(page_index, set())
+ }
+ candidate_font_names.discard("")
+
+ for font_name in sorted(candidate_font_names):
+ font_char_count = font_name_counts.get(font_name, 0)
+ cjk_char_count = font_cjk_char_counts.get(font_name, 0)
+ font_usage_ratio = font_char_count / total_chars
+ font_cjk_ratio = cjk_char_count / font_char_count if font_char_count else 0.0
+ signal = {
+ "triggered": False,
+ "page_index": page_index,
+ "font_names": [font_name] if font_char_count else [],
+ "font_char_count": font_char_count,
+ "cjk_char_count": cjk_char_count,
+ "total_chars": total_chars,
+ "font_usage_ratio": font_usage_ratio,
+ "font_cjk_ratio": font_cjk_ratio,
+ }
+ if (
+ font_char_count >= count_threshold
+ and font_usage_ratio >= usage_ratio_threshold
+ and font_cjk_ratio >= cjk_ratio_threshold
+ ):
+ signal["triggered"] = True
+ return signal
+
+ if (
+ signal["font_cjk_ratio"],
+ signal["font_usage_ratio"],
+ signal["font_char_count"],
+ ) > (
+ best_signal["font_cjk_ratio"],
+ best_signal["font_usage_ratio"],
+ best_signal["font_char_count"],
+ ):
+ best_signal = signal
+
+ return best_signal
+
+
def _get_u72xx_text_signal_from_samples(text_samples: list[dict[str, Any]]) -> dict[str, Any]:
"""基于已缓存的抽样页文本统计扣除常用字后的 U+7280-U+72DF 字符占比。"""
cjk_chars = 0
@@ -517,8 +719,7 @@ def _get_sample_cleaned_text(text_sample: Any) -> str:
def _is_cjk_text_char(char: str) -> bool:
"""判断字符是否属于中文文档中可接受的 CJK 文字范围。"""
- unicode_code = ord(char)
- return any(start <= unicode_code <= end for start, end in CJK_TEXT_RANGES)
+ return _is_cjk_unicode_code(ord(char))
def _get_cross_script_name(char: str) -> str | None:
@@ -660,10 +861,24 @@ def _get_sampled_ascii_punct_signal_from_samples(text_samples: list[dict[str, An
return best_signal
-def get_cid_font_signal_pypdf(pdf_bytes: bytes, page_indices: list[int]) -> dict[str, Any]:
- """收集抽样页中无 ToUnicode 的 Identity CID 字体资源,供后续按实际字符使用量判定。"""
+def _get_font_resource_cache_key(font_ref: Any, font: Any) -> tuple[Any, ...]:
+ """为 pypdf 字体资源生成页间可复用的分析缓存键。"""
+ idnum = getattr(font_ref, "idnum", None)
+ generation = getattr(font_ref, "generation", None)
+ if idnum is not None:
+ return "indirect", idnum, generation
+ return "direct", id(font)
+
+
+def _get_font_resource_signals_pypdf(
+ pdf_bytes: bytes,
+ page_indices: list[int],
+) -> dict[str, Any]:
+ """一次扫描抽样页字体资源,收集 CID 缺映射和 Type1 Latin 候选字体。"""
reader = PdfReader(BytesIO(pdf_bytes))
- page_fonts = {}
+ cid_page_fonts: dict[int, set[str]] = {}
+ latin_charset_page_fonts: dict[int, set[str]] = {}
+ font_analysis_cache: dict[tuple[Any, ...], dict[str, bool]] = {}
for page_index in page_indices:
page = reader.pages[page_index]
@@ -675,31 +890,66 @@ def get_cid_font_signal_pypdf(pdf_bytes: bytes, page_indices: list[int]) -> dict
if not fonts:
continue
+ # PDFium 只返回规范化字体名;同名不同资源无法可靠归因到具体字体对象。
+ page_latin_font_resources: dict[str, dict[tuple[Any, ...], bool]] = {}
for font_key, font_ref in fonts.items():
font = _resolve_pdf_object(font_ref)
if not font:
continue
- subtype = str(font.get("/Subtype"))
- encoding = str(font.get("/Encoding"))
- has_descendant_fonts = "/DescendantFonts" in font
- has_to_unicode = "/ToUnicode" in font
+ font_name = _normalize_pdf_font_name(font.get("/BaseFont") or font_key)
+ if not font_name:
+ continue
+
+ cache_key = _get_font_resource_cache_key(font_ref, font)
+ analysis = font_analysis_cache.get(cache_key)
+ if analysis is None:
+ subtype = str(font.get("/Subtype"))
+ encoding = str(font.get("/Encoding"))
+ cid_without_to_unicode = (
+ subtype == "/Type0"
+ and encoding in ("/Identity-H", "/Identity-V")
+ and "/DescendantFonts" in font
+ and "/ToUnicode" not in font
+ )
+ latin_charset_signal = _get_latin_charset_with_to_unicode_signal(font)
+ analysis = {
+ "cid_without_to_unicode": cid_without_to_unicode,
+ "latin_charset_with_to_unicode": latin_charset_signal["triggered"],
+ }
+ font_analysis_cache[cache_key] = analysis
- if (
- subtype == "/Type0"
- and encoding in ("/Identity-H", "/Identity-V")
- and has_descendant_fonts
- and not has_to_unicode
- ):
- font_name = font.get("/BaseFont") or font_key
- page_fonts.setdefault(page_index, set()).add(_normalize_pdf_font_name(font_name))
+ if analysis["cid_without_to_unicode"]:
+ cid_page_fonts.setdefault(page_index, set()).add(font_name)
+
+ page_latin_font_resources.setdefault(font_name, {})[cache_key] = analysis[
+ "latin_charset_with_to_unicode"
+ ]
+
+ for font_name, resource_states in page_latin_font_resources.items():
+ if len(resource_states) == 1 and set(resource_states.values()) == {True}:
+ latin_charset_page_fonts.setdefault(page_index, set()).add(font_name)
return {
- "triggered": bool(page_fonts),
- "page_fonts": page_fonts,
+ "cid_without_to_unicode": {
+ "triggered": bool(cid_page_fonts),
+ "page_fonts": cid_page_fonts,
+ },
+ "latin_charset_with_to_unicode": {
+ "triggered": bool(latin_charset_page_fonts),
+ "page_fonts": latin_charset_page_fonts,
+ },
}
+def get_cid_font_signal_pypdf(pdf_bytes: bytes, page_indices: list[int]) -> dict[str, Any]:
+ """兼容旧接口:返回抽样页无 ToUnicode 的 Identity CID 字体资源。"""
+ return _get_font_resource_signals_pypdf(
+ pdf_bytes,
+ page_indices,
+ )["cid_without_to_unicode"]
+
+
def detect_cid_font_signal_pypdf(pdf_bytes: bytes, page_indices: list[int]) -> bool:
"""兼容旧接口:只返回是否存在无 ToUnicode 的 Identity CID 字体资源。"""
return get_cid_font_signal_pypdf(pdf_bytes, page_indices)["triggered"]
diff --git a/mineru/utils/pdf_document.py b/mineru/utils/pdf_document.py
index c453f484..03967db1 100644
--- a/mineru/utils/pdf_document.py
+++ b/mineru/utils/pdf_document.py
@@ -2,6 +2,7 @@
from __future__ import annotations
import asyncio
+import math
import os
from contextlib import contextmanager
from io import BytesIO
@@ -25,7 +26,10 @@ POINTS_PER_INCH: int = 72
DEFAULT_RENDER_DPI: int = 200
DEFAULT_RENDER_SCALE: float = DEFAULT_RENDER_DPI / POINTS_PER_INCH
DEFAULT_RENDER_MAX_EDGE: int = 3500
-NEAR_DUPLICATE_CHAR_BBOX_TOLERANCE = 0.5
+NEAR_IDENTICAL_CHAR_BBOX_TOLERANCE = 1.0
+OFFSET_DUPLICATE_CHAR_BBOX_TOLERANCE = 2.5
+OFFSET_DUPLICATE_TRANSLATION_TOLERANCE = 0.1
+OFFSET_DUPLICATE_MIN_BBOX_OVERLAP_RATIO = 0.45
try:
from pdftext.pdf.chars import PageChars
@@ -339,35 +343,162 @@ def _try_close(obj: object) -> None:
pass
+def _get_visible_char_signature(
+ char: Char,
+) -> tuple[str, tuple[Any, Any, Any, Any], float]:
+ """生成可见字符去重签名,不把 bbox 放入签名以便单独做近重合判断。"""
+ font = char.get("font") or {}
+ font_key = (
+ font.get("name"),
+ font.get("flags"),
+ font.get("size"),
+ font.get("weight"),
+ )
+ rotation_key = round(float(char.get("rotation") or 0.0), 3)
+ return str(char.get("char", "")), font_key, rotation_key
+
+
+def _is_near_identical_bbox(
+ bbox_a: tuple[float, float, float, float],
+ bbox_b: tuple[float, float, float, float],
+) -> bool:
+ """判断两个字符 bbox 是否属于同一视觉位置的一点内抖动。"""
+ return all(
+ abs(coord_a - coord_b) <= NEAR_IDENTICAL_CHAR_BBOX_TOLERANCE
+ for coord_a, coord_b in zip(bbox_a, bbox_b)
+ )
+
+
+def _calculate_bbox_overlap_in_smaller_area(
+ bbox_a: tuple[float, float, float, float],
+ bbox_b: tuple[float, float, float, float],
+) -> float:
+ """计算两个字符框交集占较小字符框面积的比例。"""
+ intersection_width = max(
+ 0.0,
+ min(bbox_a[2], bbox_b[2]) - max(bbox_a[0], bbox_b[0]),
+ )
+ intersection_height = max(
+ 0.0,
+ min(bbox_a[3], bbox_b[3]) - max(bbox_a[1], bbox_b[1]),
+ )
+ bbox_a_area = max(0.0, bbox_a[2] - bbox_a[0]) * max(
+ 0.0,
+ bbox_a[3] - bbox_a[1],
+ )
+ bbox_b_area = max(0.0, bbox_b[2] - bbox_b[0]) * max(
+ 0.0,
+ bbox_b[3] - bbox_b[1],
+ )
+ smaller_area = min(bbox_a_area, bbox_b_area)
+ if smaller_area == 0:
+ return 0.0
+ return intersection_width * intersection_height / smaller_area
+
+
+def _is_adjacent_offset_duplicate_char(
+ previous_char: Char,
+ current_char: Char,
+) -> bool:
+ """识别相邻字符中由对角平移阴影产生的第二个重复字符。"""
+ if _get_visible_char_signature(previous_char) != _get_visible_char_signature(current_char):
+ return False
+
+ previous_bbox = _char_bbox_values(previous_char.get("bbox"))
+ current_bbox = _char_bbox_values(current_char.get("bbox"))
+ if previous_bbox is None or current_bbox is None:
+ return False
+
+ x_start_offset = current_bbox[0] - previous_bbox[0]
+ y_start_offset = current_bbox[1] - previous_bbox[1]
+ x_end_offset = current_bbox[2] - previous_bbox[2]
+ y_end_offset = current_bbox[3] - previous_bbox[3]
+
+ # 阴影层应是同一字符框的刚性平移,避免把大小不同的相邻同字误判为重复。
+ if (
+ abs(x_start_offset - x_end_offset) > OFFSET_DUPLICATE_TRANSLATION_TOLERANCE
+ or abs(y_start_offset - y_end_offset) > OFFSET_DUPLICATE_TRANSLATION_TOLERANCE
+ ):
+ return False
+
+ if not (
+ NEAR_IDENTICAL_CHAR_BBOX_TOLERANCE
+ < abs(x_start_offset)
+ <= OFFSET_DUPLICATE_CHAR_BBOX_TOLERANCE
+ and NEAR_IDENTICAL_CHAR_BBOX_TOLERANCE
+ < abs(y_start_offset)
+ <= OFFSET_DUPLICATE_CHAR_BBOX_TOLERANCE
+ ):
+ return False
+
+ return (
+ _calculate_bbox_overlap_in_smaller_area(previous_bbox, current_bbox)
+ >= OFFSET_DUPLICATE_MIN_BBOX_OVERLAP_RATIO
+ )
+
+
+def _get_near_identical_bbox_bucket_key(
+ bbox_coords: tuple[float, float, float, float],
+) -> tuple[int, int]:
+ """按字符 bbox 左上角生成空间桶 key,缩小近重合判断的候选范围。"""
+ return (
+ math.floor(bbox_coords[0] / NEAR_IDENTICAL_CHAR_BBOX_TOLERANCE),
+ math.floor(bbox_coords[1] / NEAR_IDENTICAL_CHAR_BBOX_TOLERANCE),
+ )
+
+
+def _iter_neighbor_bbox_bucket_keys(
+ bucket_key: tuple[int, int],
+) -> Iterator[tuple[int, int]]:
+ """遍历当前桶及周围 8 个邻近桶,覆盖 bbox 容差范围内的候选字符。"""
+ bucket_x, bucket_y = bucket_key
+ for offset_x in (-1, 0, 1):
+ for offset_y in (-1, 0, 1):
+ yield bucket_x + offset_x, bucket_y + offset_y
+
+
def _deduplicate_near_identical_chars(chars: list[Char]) -> list[Char]:
- """移除坐标近乎重合的重复可见字符,降低 PDF 叠印文本造成的重复抽取。"""
- unique_chars: list[Char] = []
- seen_keys: set[tuple[str, int, int, int, int, str, str]] = set()
+ """清理 PDFium 文本层边界处同字符、同位置及对角阴影重复字符。"""
+ seen_visible_char_bboxes: dict[
+ tuple[str, tuple[Any, Any, Any, Any], float],
+ dict[tuple[int, int], list[tuple[float, float, float, float]]],
+ ] = {}
+ deduplicated_chars: list[Char] = []
+
for char in chars:
text = str(char.get("char", ""))
if not text or text.isspace():
- unique_chars.append(char)
+ deduplicated_chars.append(char)
continue
- bbox_values = _char_bbox_values(char.get("bbox"))
- if bbox_values is None:
- unique_chars.append(char)
+ visible_char_key = _get_visible_char_signature(char)
+ bbox_coords = _char_bbox_values(char.get("bbox"))
+ if bbox_coords is None:
+ deduplicated_chars.append(char)
continue
- rounded_bbox = tuple(
- int(round(float(value) / NEAR_DUPLICATE_CHAR_BBOX_TOLERANCE)) for value in bbox_values
- )
- key = (
- text,
- *rounded_bbox,
- str(char.get("font", "")),
- str(char.get("rotation", "")),
+ if deduplicated_chars and _is_adjacent_offset_duplicate_char(
+ deduplicated_chars[-1],
+ char,
+ ):
+ continue
+
+ bbox_bucket_key = _get_near_identical_bbox_bucket_key(bbox_coords)
+ visible_char_bbox_buckets = seen_visible_char_bboxes.setdefault(
+ visible_char_key,
+ {},
)
- if key in seen_keys:
+ if any(
+ _is_near_identical_bbox(bbox_coords, seen_bbox)
+ for neighbor_bucket_key in _iter_neighbor_bbox_bucket_keys(bbox_bucket_key)
+ for seen_bbox in visible_char_bbox_buckets.get(neighbor_bucket_key, [])
+ ):
continue
- seen_keys.add(key)
- unique_chars.append(char)
- return unique_chars
+
+ visible_char_bbox_buckets.setdefault(bbox_bucket_key, []).append(bbox_coords)
+ deduplicated_chars.append(char)
+
+ return deduplicated_chars
def _is_pdftext_page_chars(chars: Any) -> bool: