Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/docs/extraction/multimodal-extraction.md
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,8 @@ for format details and defaults.

Charts and infographic regions are classified with other page layout elements (tables, text blocks, titles) and processed through layout detection and OCR. `extract_charts` defaults to `True`; `extract_infographics` defaults to `False`. Set `extract_infographics=True` to retain infographic output. Outputs use the same metadata schema as other extracted objects.

When `extract_infographics=False`, detected text and title boxes inside infographic regions are kept in the page text. When `extract_infographics=True`, that text is removed from the page text because infographic OCR reads it instead.

!!! important "Remote Parse v1.2 does not predict chart classes"
Remote [Nemotron Parse v1.2](https://huggingface.co/nvidia/NVIDIA-Nemotron-Parse-v1.2) endpoints remain supported, but the model's semantic classes do not include `Chart` or `Infographic`.
Chart-heavy regions can be labeled `Picture`. The pipeline routes `Picture` elements to the infographic channel when `extract_infographics=True`.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -358,18 +358,24 @@ def _apply_final_score_filter(

def _apply_page_elements_v3_postprocess(
dets: List[Dict[str, Any]],
*,
extract_infographics: bool = True,
) -> List[Dict[str, Any]]:
"""Apply ``postprocess_page_elements_v3`` (box fusion, title matching,
expansion, overlap removal) to a single image's detection list.

Returns the original detections unchanged if the API function is unavailable.
Text inside infographic boxes is kept when ``extract_infographics`` is False, because no
infographic OCR would replace it. Returns the original detections unchanged if the API
function is unavailable.
"""
if postprocess_page_elements_v3 is None or not dets:
return dets
try:
ann_dict = _detections_to_annotation_dict(dets)
labels = YOLOX_PAGE_V3_CLASS_LABELS if YOLOX_PAGE_V3_CLASS_LABELS is not None else list(ann_dict.keys())
result = postprocess_page_elements_v3(ann_dict, labels=labels)
result = postprocess_page_elements_v3(
ann_dict, labels=labels, suppress_text_in_infographics=extract_infographics
)
return _annotation_dict_to_detections(result)
except Exception:
return dets
Expand All @@ -380,6 +386,7 @@ def _remote_response_to_detections(
response_json: Dict[str, Any],
label_names: List[str],
thresholds_per_class: Sequence[float],
extract_infographics: bool = True,
) -> List[Dict[str, Any]]:
# Try direct model-pred style payload first (or common wrappers around it).
candidates: List[Any] = [response_json]
Expand All @@ -405,7 +412,7 @@ def _remote_response_to_detections(
batch_size=1,
label_names=label_names,
)[0]
return _apply_page_elements_v3_postprocess(dets)
return _apply_page_elements_v3_postprocess(dets, extract_infographics=extract_infographics)
except Exception:
pass

Expand All @@ -418,7 +425,7 @@ def _remote_response_to_detections(
if isinstance(bb, dict):
try:
dets = _bounding_boxes_to_detections(bb)
return _apply_page_elements_v3_postprocess(dets)
return _apply_page_elements_v3_postprocess(dets, extract_infographics=extract_infographics)
Comment thread
devin-ai-integration[bot] marked this conversation as resolved.
Resolved
except Exception:
pass

Expand All @@ -430,7 +437,7 @@ def _remote_response_to_detections(
if all(isinstance(v, list) for v in cand.values()):
try:
dets = _annotation_dict_to_detections(cand) # type: ignore[arg-type]
return _apply_page_elements_v3_postprocess(dets)
return _apply_page_elements_v3_postprocess(dets, extract_infographics=extract_infographics)
except Exception:
pass

Expand All @@ -450,6 +457,7 @@ def detect_page_elements_v3(
counts_by_label_column: str = "page_elements_v3_counts_by_label",
remote_retry: RemoteRetryParams | None = None,
nim_client: NIMClient | None = None,
extract_infographics: bool = True,
**kwargs: Any,
) -> Any:
retry = remote_retry or RemoteRetryParams(
Expand Down Expand Up @@ -586,6 +594,7 @@ def detect_page_elements_v3(
response_json=response_items[local_i],
label_names=label_names,
thresholds_per_class=thresholds_per_class,
extract_infographics=extract_infographics,
)
dets = _apply_final_score_filter(dets)
row_payloads[row_i] = {
Expand Down Expand Up @@ -712,7 +721,10 @@ def detect_page_elements_v3(
label_names=label_names,
)
# Apply v3 postprocessing (box fusion via WBF at iou=0.01, title matching, expansion, overlap removal)
per_image_dets = [_apply_page_elements_v3_postprocess(dets) for dets in per_image_dets]
per_image_dets = [
_apply_page_elements_v3_postprocess(dets, extract_infographics=extract_infographics)
for dets in per_image_dets
]
# Apply per-class final score filtering AFTER WBF (matches NIM pipeline ordering)
per_image_dets = [_apply_final_score_filter(dets) for dets in per_image_dets]
for local_i, row_i in enumerate(chunk_idx):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -924,7 +924,7 @@ def build_graph(
parse_kwargs = build_parse_actor_kwargs(extract_params)
graph = graph >> NemotronParseActor(**parse_kwargs)
else:
detect_kwargs: dict[str, Any] = {}
detect_kwargs: dict[str, Any] = {"extract_infographics": bool(extract_params.extract_infographics)}
if extract_params.page_elements_invoke_url:
detect_kwargs["page_elements_invoke_url"] = extract_params.page_elements_invoke_url
if extract_params.api_key:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -865,6 +865,7 @@ def postprocess_page_elements_v3(
annotation_dict: Dict[str, List[List[float]]],
labels: Optional[List[str]] = None,
final_score: Optional[Dict[str, float]] = None,
suppress_text_in_infographics: bool = True,
) -> Dict[str, List[List[float]]]:
"""
Expand bounding boxes of tables/charts/infographics and titles based on the bounding boxes of the other class.
Expand All @@ -873,6 +874,8 @@ def postprocess_page_elements_v3(
"table", "chart", "infographics", "title", "paragraph", "header_footer".
labels: ordered class labels corresponding to the annotation dictionary.
final_score: per-class thresholds used by the final output filter.
suppress_text_in_infographics: remove text, title, and header/footer boxes contained in
infographic boxes. Disable when infographic content is not extracted, so that text is kept.

Returns:
annotation_dict: same as input, with expanded bboxes for page elements.
Expand Down Expand Up @@ -924,10 +927,12 @@ def postprocess_page_elements_v3(
return {label: [] for label in labels}

bboxes, confidences, label_idxs, found_title = match_structured_boxes_with_title(
bboxes, confidences, label_idxs, labels
bboxes, confidences, label_idxs, labels, match_infographics=suppress_text_in_infographics
)
bboxes, label_idxs, confidences = expand_tables_and_charts(bboxes, confidences, label_idxs, labels, found_title)
bboxes, label_idxs, confidences = postprocess_included_texts(bboxes, confidences, label_idxs, labels)
bboxes, label_idxs, confidences = postprocess_included_texts(
bboxes, confidences, label_idxs, labels, suppress_text_in_infographics=suppress_text_in_infographics
)
Comment thread
devin-ai-integration[bot] marked this conversation as resolved.
Resolved

order = np.argsort(bboxes[:, 1] * 10 + bboxes[:, 0])
bboxes, confidences, label_idxs = bboxes[order], confidences[order], label_idxs[order]
Expand Down Expand Up @@ -1578,7 +1583,14 @@ def get_overlaps(boxes, other_boxes, normalize="box_only"):
return overlaps


def postprocess_included(boxes, labels, confs, class_="title", classes=["table", "chart", "title", "infographic"]):
def postprocess_included(
boxes,
labels,
confs,
class_="title",
classes=["table", "chart", "title", "infographic"],
suppress_text_in_infographics=True,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 New flags lack types. The new suppress_text_in_infographics parameter has no type annotation. The same applies to match_infographics in match_structured_boxes_with_title and suppress_text_in_infographics in postprocess_included_texts.

The repository requires type annotations on every public function parameter. Add : bool to these three new parameters; the older untyped parameters are outside this finding.

Rule Used: All public functions, methods, and class attributes must have type annotations. This includes parameter types, return types, and class-level attributes. Private/internal helpers (prefixed with _) are encouraged but not required. (source)

Prompt To Fix With AI
This is a comment left during a code review.
Path: nemo_retriever/src/nemo_retriever/models/nim/primitives/model_interface/yolox.py
Line: 1592

Comment:
**New flags lack types.** The new `suppress_text_in_infographics` parameter has no type annotation. The same applies to `match_infographics` in `match_structured_boxes_with_title` and `suppress_text_in_infographics` in `postprocess_included_texts`.

The repository requires type annotations on every public function parameter. Add `: bool` to these three new parameters; the older untyped parameters are outside this finding.

**Rule Used:** All public functions, methods, and class attributes must have type annotations. This includes parameter types, return types, and class-level attributes. Private/internal helpers (prefixed with _) are encouraged but not required. ([source](https://github.com/nvidia/nemo-retriever/blob/dc3ffe92e7efe27648079031ee5f3b0abc386815/.greptile/config.json))

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

):
"""
Post process title predictions.
- Remove titles that are included in other boxes
Expand All @@ -1588,6 +1600,7 @@ def postprocess_included(boxes, labels, confs, class_="title", classes=["table",
labels (numpy.ndarray [N]): Array of labels.
confs (numpy.ndarray [N]): Array of confidences.
class_ (str, optional): Class to postprocess. Defaults to "title".
suppress_text_in_infographics (bool, optional): Treat infographic boxes as containers. Defaults to True.
classes (list, optional): Classes. Defaults to ["table", "chart", "title", "infographic"].

Returns:
Expand All @@ -1606,7 +1619,7 @@ def postprocess_included(boxes, labels, confs, class_="title", classes=["table",

# other_boxes = boxes[labels != classes.index("title")]

inclusion_classes = ["table", "infographic", "chart"]
inclusion_classes = ["table", "infographic", "chart"] if suppress_text_in_infographics else ["table", "chart"]
if class_ in ["header_footer", "title"]:
inclusion_classes.append("paragraph")

Expand Down Expand Up @@ -1655,7 +1668,7 @@ def remove_overlapping_boxes_using_wbf(boxes, confs, labels):
return boxes, confs, labels


def match_structured_boxes_with_title(boxes, confs, labels, classes):
def match_structured_boxes_with_title(boxes, confs, labels, classes, *, match_infographics=True):
# Reorder by y, x
order = np.argsort(boxes[:, 1] * 10 + boxes[:, 0])
boxes, confs, labels = boxes[order], confs[order], labels[order]
Expand All @@ -1668,7 +1681,7 @@ def match_structured_boxes_with_title(boxes, confs, labels, classes):
confs,
labels,
classes,
to_match_labels=["chart", "table", "infographic"],
to_match_labels=["chart", "table", "infographic"] if match_infographics else ["chart", "table"],
remove_matched_titles=True,
)

Expand Down Expand Up @@ -1718,9 +1731,11 @@ def expand_tables_and_charts(boxes, confs, labels, classes, found_title):
return boxes, labels, confs


def postprocess_included_texts(boxes, confs, labels, classes):
def postprocess_included_texts(boxes, confs, labels, classes, suppress_text_in_infographics=True):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Missing types on new public options

New suppress_text_in_infographics and match_infographics parameters lack type annotations across three public helpers. The repository's Type Safety rules require complete annotations on public interfaces.

Devin left this for you to triage: Real repo-rule gap (new bool params lack annotations), but #2839 is already merged. Recommend a tiny follow-up PR off main adding : bool to the three helpers; no behaviour change.

Learn more

The new options on postprocess_included, match_structured_boxes_with_title, and postprocess_included_texts have boolean defaults but no parameter annotations. The package's Type Safety rules apply to all public interfaces, including these helpers.

Example: match_structured_boxes_with_title(..., match_infographics=True) introduces an unannotated public option, while postprocess_page_elements_v3 annotates its corresponding option as bool.

Recommended fix: Annotate the newly added parameters as suppress_text_in_infographics: bool = True and match_infographics: bool = True in all three helpers.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

for c in ["title", "paragraph", "header_footer"]:
boxes, labels, confs = postprocess_included(boxes, labels, confs, c, classes)
boxes, labels, confs = postprocess_included(
boxes, labels, confs, c, classes, suppress_text_in_infographics=suppress_text_in_infographics
)
return boxes, labels, confs


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -456,7 +456,7 @@ def _run_detection_pipeline(self, batch_df: pd.DataFrame) -> pd.DataFrame:
ocr_version = getattr(extract_params, "ocr_version", "v2")
ocr_lang = getattr(extract_params, "ocr_lang", None)

detect_kwargs: dict[str, Any] = {}
detect_kwargs: dict[str, Any] = {"extract_infographics": bool(extract_params.extract_infographics)}
if extract_params.page_elements_invoke_url:
detect_kwargs["invoke_url"] = extract_params.page_elements_invoke_url
if extract_params.api_key:
Expand Down
90 changes: 90 additions & 0 deletions nemo_retriever/tests/test_page_elements_infographic_text.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
# SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES.
# All rights reserved.
# SPDX-License-Identifier: Apache-2.0

"""Text inside infographic boxes is kept unless infographic content is extracted."""

import pytest

from nemo_retriever.common.modality.page_elements.shared import (
_apply_final_score_filter,
_apply_page_elements_v3_postprocess,
)
from nemo_retriever.models.nim.primitives.model_interface.yolox import postprocess_page_elements_v3

# Raw Page Elements v3 detections (before postprocessing) for a scanned one-page menu whose text
# blocks all lie inside one infographic box.
_MENU_PAGE = [
("text", (0.3761, 0.4244, 0.9642, 0.5818), 0.7944),
("text", (0.3802, 0.6713, 0.8256, 0.7127), 0.7410),
("title", (0.4988, 0.0503, 0.9525, 0.0836), 0.6560),
("text", (0.8184, 0.1410, 0.9117, 0.1596), 0.5705),
("text", (0.0485, 0.1947, 0.3091, 0.3831), 0.5666),
("text", (0.4860, 0.1442, 0.5707, 0.1618), 0.5587),
("text", (0.2840, 0.9223, 0.9376, 0.9690), 0.5521),
("text", (0.0383, 0.7330, 0.1900, 0.7521), 0.4975),
("text", (0.6766, 0.1396, 0.7814, 0.1581), 0.4721),
("text", (0.0428, 0.9203, 0.2446, 0.9700), 0.3514),
("infographic", (0.0232, 0.0000, 1.0000, 1.0000), 0.3491),
("text", (0.6796, 0.1390, 0.9124, 0.1589), 0.2593),
("text", (0.3659, 0.1422, 0.5756, 0.1616), 0.2331),
("title", (0.1100, 0.0428, 0.2808, 0.0997), 0.1624),
("text", (0.3518, 0.9236, 0.6853, 0.9438), 0.0883),
("title", (0.0507, 0.1556, 0.2132, 0.1785), 0.0789),
("text", (0.3650, 0.1420, 0.4239, 0.1591), 0.0483),
("text", (0.2650, 0.9539, 0.9348, 0.9678), 0.0327),
("text", (0.3159, 0.9225, 0.8857, 0.9467), 0.0219),
("text", (0.0480, 0.1986, 0.2085, 0.2467), 0.0167),
("text", (0.0493, 0.2986, 0.3085, 0.3813), 0.0165),
]

_TEXT_LABELS = ("text", "title", "header_footer")


def _detections():
return [{"label_name": label, "bbox_xyxy_norm": list(box), "score": score} for label, box, score in _MENU_PAGE]


def _counts(dets):
counts = {}
for det in dets:
counts[det["label_name"]] = counts.get(det["label_name"], 0) + 1
return counts


@pytest.mark.parametrize("extract_infographics", [False, True])
def test_infographic_contained_text_depends_on_infographic_extraction(extract_infographics):
dets = _apply_page_elements_v3_postprocess(_detections(), extract_infographics=extract_infographics)
counts = _counts(_apply_final_score_filter(dets))
assert counts.get("infographic") == 1
text_boxes = sum(counts.get(label, 0) for label in _TEXT_LABELS)
if extract_infographics:
assert text_boxes == 0
else:
assert text_boxes > 0


@pytest.mark.parametrize("suppress_text_in_infographics", [False, True])
def test_table_contained_paragraph_is_removed_either_way(suppress_text_in_infographics):
labels = ["table", "chart", "title", "infographic", "paragraph", "header_footer"]
annotations = {label: [] for label in labels}
annotations["table"] = [[0.2, 0.2, 0.8, 0.6, 0.87]]
annotations["infographic"] = [[0.1, 0.65, 0.9, 0.95, 0.9]]
annotations["paragraph"] = [[0.3, 0.3, 0.6, 0.4, 0.93], [0.2, 0.7, 0.8, 0.9, 0.95]]
result = postprocess_page_elements_v3(
annotations, labels, suppress_text_in_infographics=suppress_text_in_infographics
)
assert len(result["table"]) == 1
assert len(result["paragraph"]) == (0 if suppress_text_in_infographics else 1)


@pytest.mark.parametrize("extract_infographics", [False, True])
def test_title_only_infographic_preserves_title_when_extraction_is_off(extract_infographics):
detections = [
{"label_name": "infographic", "bbox_xyxy_norm": [0.1, 0.1, 0.9, 0.9], "score": 0.95},
{"label_name": "title", "bbox_xyxy_norm": [0.2, 0.2, 0.5, 0.25], "score": 0.95},
]
result = _apply_page_elements_v3_postprocess(detections, extract_infographics=extract_infographics)
counts = _counts(_apply_final_score_filter(result))
assert counts.get("infographic") == 1
assert counts.get("title", 0) == (0 if extract_infographics else 1)
Loading