Skip to content

armgit / OXR

Public Imported from GitHub
0

An open-source document parsing model with SOTA accuracy and speed, using an RSI loop during post-training.

80.8 KB
Raw Blame
# Copyright (c) 2024 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Vendored function closure from the XY-Cut++ authors' implementation.

Paper authors: Shuai Liu, Youmeng Li, Jizeng Wei
Paper: https://arxiv.org/abs/2504.10258
Source repository: https://github.com/liushuai35/PaddleXrc
Source commit: 7873ab38662e3277091520f4259f090bc197fee4
Source path: paddlex/inference/pipelines/layout_parsing/utils.py
Source SHA-256: 9681d0b80b7738a2e6febc163bb91cbc1c12275a0c3aa2621be6c91b37033189

Only the transitive function closure needed by get_layout_ordering is vendored.

OXR extension: get_layout_ordering accepts remove_overlaps=False so the
order-only adapter can preserve every input block. The default retains the
upstream overlap-removal behavior.
"""

from __future__ import annotations

from typing import Any, Dict, List, Optional, Tuple, Union

import numpy as np

UPSTREAM_COMMIT = "7873ab38662e3277091520f4259f090bc197fee4"
UPSTREAM_SOURCE_SHA256 = "9681d0b80b7738a2e6febc163bb91cbc1c12275a0c3aa2621be6c91b37033189"


def _calculate_overlap_area_div_minbox_area_ratio(
    bbox1: Union[list, tuple],
    bbox2: Union[list, tuple],
) -> float:
    """
    Calculate the ratio of the overlap area between bbox1 and bbox2
    to the area of the smaller bounding box.

    Args:
        bbox1 (list or tuple): Coordinates of the first bounding box [x_min, y_min, x_max, y_max].
        bbox2 (list or tuple): Coordinates of the second bounding box [x_min, y_min, x_max, y_max].

    Returns:
        float: The ratio of the overlap area to the area of the smaller bounding box.
    """
    bbox1 = list(map(int, bbox1))
    bbox2 = list(map(int, bbox2))

    x_left = max(bbox1[0], bbox2[0])
    y_top = max(bbox1[1], bbox2[1])
    x_right = min(bbox1[2], bbox2[2])
    y_bottom = min(bbox1[3], bbox2[3])

    if x_right <= x_left or y_bottom <= y_top:
        return 0.0

    intersection_area = (x_right - x_left) * (y_bottom - y_top)
    area_bbox1 = (bbox1[2] - bbox1[0]) * (bbox1[3] - bbox1[1])
    area_bbox2 = (bbox2[2] - bbox2[0]) * (bbox2[3] - bbox2[1])
    min_box_area = min(area_bbox1, area_bbox2)

    if min_box_area <= 0:
        return 0.0

    return intersection_area / min_box_area


def _projection_by_bboxes(boxes: np.ndarray, axis: int) -> np.ndarray:
    """
    Generate a 1D projection histogram from bounding boxes along a specified axis.

    Args:
        boxes: A (N, 4) array of bounding boxes defined by [x_min, y_min, x_max, y_max].
        axis: Axis for projection; 0 for horizontal (x-axis), 1 for vertical (y-axis).

    Returns:
        A 1D numpy array representing the projection histogram based on bounding box intervals.
    """
    assert axis in [0, 1]
    max_length = np.max(boxes[:, axis::2])
    projection = np.zeros(max_length, dtype=int)

    # Increment projection histogram over the interval defined by each bounding box
    for start, end in boxes[:, axis::2]:
        projection[start:end] += 1

    return projection


def _split_projection_profile(arr_values: np.ndarray, min_value: float, min_gap: float):
    """
    Split the projection profile into segments based on specified thresholds.

    Args:
        arr_values: 1D array representing the projection profile.
        min_value: Minimum value threshold to consider a profile segment significant.
        min_gap: Minimum gap width to consider a separation between segments.

    Returns:
        A tuple of start and end indices for each segment that meets the criteria.
    """
    # Identify indices where the projection exceeds the minimum value
    significant_indices = np.where(arr_values > min_value)[0]
    if not len(significant_indices):
        return

    # Calculate gaps between significant indices
    index_diffs = significant_indices[1:] - significant_indices[:-1]
    gap_indices = np.where(index_diffs > min_gap)[0]

    # Determine start and end indices of segments
    segment_starts = np.insert(
        significant_indices[gap_indices + 1],
        0,
        significant_indices[0],
    )
    segment_ends = np.append(
        significant_indices[gap_indices],
        significant_indices[-1] + 1,
    )

    return segment_starts, segment_ends


def _recursive_yx_cut(
    boxes: np.ndarray,
    indices: List[int],
    res: List[int],
    segment_ids: List[int],
    current_id: int,
    min_gap: int = 1,
):
    """
    Recursively project and segment bounding boxes, starting with Y-axis and followed by X-axis.

    Args:
        boxes: A (N, 4) array representing bounding boxes.
        indices: List of indices indicating the original position of boxes.
        res: List to store indices of the final segmented bounding boxes.
        min_gap (int): Minimum gap width to consider a separation between segments on the X-axis. Defaults to 1.

    Returns:
        None: This function modifies the `res` list in place.
    """
    assert len(boxes) == len(
        indices
    ), "The length of boxes and indices must be the same."

    # Sort by y_min for Y-axis projection
    y_sorted_indices = boxes[:, 1].argsort()
    y_sorted_boxes = boxes[y_sorted_indices]
    y_sorted_indices = np.array(indices)[y_sorted_indices]

    # Perform Y-axis projection
    y_projection = _projection_by_bboxes(boxes=y_sorted_boxes, axis=1)
    y_intervals = _split_projection_profile(y_projection, 0, 1)

    if not y_intervals:
        for idx in indices:
            segment_ids.append(current_id)
        # current_id += 1
        res.extend(indices)
        return

    # Process each segment defined by Y-axis projection
    for y_start, y_end in zip(*y_intervals):
        # Select boxes within the current y interval
        y_interval_indices = (y_start <= y_sorted_boxes[:, 1]) & (
            y_sorted_boxes[:, 1] < y_end
        )
        y_boxes_chunk = y_sorted_boxes[y_interval_indices]
        y_indices_chunk = y_sorted_indices[y_interval_indices]

        # Sort by x_min for X-axis projection
        x_sorted_indices = y_boxes_chunk[:, 0].argsort()
        x_sorted_boxes_chunk = y_boxes_chunk[x_sorted_indices]
        x_sorted_indices_chunk = y_indices_chunk[x_sorted_indices]

        # Perform X-axis projection
        x_projection = _projection_by_bboxes(boxes=x_sorted_boxes_chunk, axis=0)
        x_intervals = _split_projection_profile(x_projection, 0, min_gap)

        if not x_intervals:
            for idx in x_sorted_indices_chunk:
                segment_ids.append(current_id)
            current_id += 1
            res.extend(x_sorted_indices_chunk)
            continue

        # If X-axis cannot be further segmented, add current indices to results
        if len(x_intervals[0]) == 1:
            for idx in x_sorted_indices_chunk:
                segment_ids.append(current_id)
            current_id += 1
            res.extend(x_sorted_indices_chunk)
            continue

        # Recursively process each segment defined by X-axis projection
        for x_start, x_end in zip(*x_intervals):
            x_interval_indices = (x_start <= x_sorted_boxes_chunk[:, 0]) & (
                x_sorted_boxes_chunk[:, 0] < x_end
            )
            _recursive_yx_cut(
                x_sorted_boxes_chunk[x_interval_indices],
                x_sorted_indices_chunk[x_interval_indices],
                res,
                segment_ids,
                current_id,
            )
            current_id += 1


def _recursive_xy_cut(
    boxes: np.ndarray,
    indices: List[int],
    res: List[int],
    segment_ids: List[int],
    current_id: int,
    min_gap: int = 1,
):
    """
    Recursively performs X-axis projection followed by Y-axis projection to segment bounding boxes.

    Args:
        boxes: A (N, 4) array representing bounding boxes with [x_min, y_min, x_max, y_max].
        indices: A list of indices representing the position of boxes in the original data.
        res: A list to store indices of bounding boxes that meet the criteria.
        min_gap (int): Minimum gap width to consider a separation between segments on the X-axis. Defaults to 1.

    Returns:
        None: This function modifies the `res` list in place.
    """
    # Ensure boxes and indices have the same length
    assert len(boxes) == len(
        indices
    ), "The length of boxes and indices must be the same."

    # Sort by x_min to prepare for X-axis projection
    x_sorted_indices = boxes[:, 0].argsort()
    x_sorted_boxes = boxes[x_sorted_indices]
    x_sorted_indices = np.array(indices)[x_sorted_indices]

    # Perform X-axis projection
    x_projection = _projection_by_bboxes(boxes=x_sorted_boxes, axis=0)
    x_intervals = _split_projection_profile(x_projection, 0, 1)

    if not x_intervals:
        for idx in indices:
            segment_ids.append(current_id)
        res.extend(indices)
        return

    # Process each segment defined by X-axis projection
    for x_start, x_end in zip(*x_intervals):
        # Select boxes within the current x interval
        x_interval_indices = (x_start <= x_sorted_boxes[:, 0]) & (
            x_sorted_boxes[:, 0] < x_end
        )
        x_boxes_chunk = x_sorted_boxes[x_interval_indices]
        x_indices_chunk = x_sorted_indices[x_interval_indices]

        # Sort selected boxes by y_min to prepare for Y-axis projection
        y_sorted_indices = x_boxes_chunk[:, 1].argsort()
        y_sorted_boxes_chunk = x_boxes_chunk[y_sorted_indices]
        y_sorted_indices_chunk = x_indices_chunk[y_sorted_indices]

        # Perform Y-axis projection
        y_projection = _projection_by_bboxes(boxes=y_sorted_boxes_chunk, axis=1)
        y_intervals = _split_projection_profile(y_projection, 0, min_gap)

        if not y_intervals:
            for idx in y_sorted_indices_chunk:
                segment_ids.append(current_id)
            current_id += 1
            res.extend(y_sorted_indices_chunk)
            continue

        # If Y-axis cannot be further segmented, add current indices to results
        if len(y_intervals[0]) == 1:
            for idx in y_sorted_indices_chunk:
                segment_ids.append(current_id)
            current_id += 1
            res.extend(y_sorted_indices_chunk)
            continue

        # Recursively process each segment defined by Y-axis projection
        for y_start, y_end in zip(*y_intervals):
            y_interval_indices = (y_start <= y_sorted_boxes_chunk[:, 1]) & (
                y_sorted_boxes_chunk[:, 1] < y_end
            )
            _recursive_xy_cut(
                y_sorted_boxes_chunk[y_interval_indices],
                y_sorted_indices_chunk[y_interval_indices],
                res,
                segment_ids,
                current_id,
            )
            current_id += 1


def sort_by_xycut(
    block_bboxes: Union[np.ndarray, List[List[int]]],
    direction: int = 0,
    min_gap: int = 1,
) -> List[int]:
    """
    Sort bounding boxes using recursive XY cut method based on the specified direction.

    Args:
        block_bboxes (Union[np.ndarray, List[List[int]]]): An array or list of bounding boxes,
                                                           where each box is represented as
                                                           [x_min, y_min, x_max, y_max].
        direction (int): Direction for the initial cut. Use 1 for Y-axis first and 0 for X-axis first.
                         Defaults to 0.
        min_gap (int): Minimum gap width to consider a separation between segments. Defaults to 1.

    Returns:
        List[int]: A list of indices representing the order of sorted bounding boxes.
    """
    block_bboxes = np.asarray(block_bboxes).astype(int)
    res = []
    segment_ids = []
    current_id = 0
    if direction == 1:
        _recursive_yx_cut(
            block_bboxes,
            np.arange(len(block_bboxes)).tolist(),
            res,
            segment_ids,
            current_id,
            min_gap,
        )
    else:
        _recursive_xy_cut(
            block_bboxes,
            np.arange(len(block_bboxes)).tolist(),
            res,
            segment_ids,
            current_id,
            min_gap,
        )
    return res, segment_ids


def _get_minbox_if_overlap_by_ratio(
    bbox1: Union[List[int], Tuple[int, int, int, int]],
    bbox2: Union[List[int], Tuple[int, int, int, int]],
    ratio: float,
    smaller: bool = True,
) -> Optional[Union[List[int], Tuple[int, int, int, int]]]:
    """
    Determine if the overlap area between two bounding boxes exceeds a given ratio
    and return the smaller (or larger) bounding box based on the `smaller` flag.

    Args:
        bbox1 (Union[List[int], Tuple[int, int, int, int]]): Coordinates of the first bounding box [x_min, y_min, x_max, y_max].
        bbox2 (Union[List[int], Tuple[int, int, int, int]]): Coordinates of the second bounding box [x_min, y_min, x_max, y_max].
        ratio (float): The overlap ratio threshold.
        smaller (bool): If True, return the smaller bounding box; otherwise, return the larger one.

    Returns:
        Optional[Union[List[int], Tuple[int, int, int, int]]]:
            The selected bounding box or None if the overlap ratio is not exceeded.
    """
    # Calculate the areas of both bounding boxes
    area1 = (bbox1[2] - bbox1[0]) * (bbox1[3] - bbox1[1])
    area2 = (bbox2[2] - bbox2[0]) * (bbox2[3] - bbox2[1])
    # Calculate the overlap ratio using a helper function
    overlap_ratio = _calculate_overlap_area_div_minbox_area_ratio(bbox1, bbox2)
    # Check if the overlap ratio exceeds the threshold
    if overlap_ratio > ratio:
        if (area1 <= area2 and smaller) or (area1 >= area2 and not smaller):
            return 1
        else:
            return 2
    return None


def _remove_overlap_blocks(
    blocks: List[Dict[str, List[int]]],
    threshold: float = 0.65,
    smaller: bool = True,
) -> Tuple[List[Dict[str, List[int]]], List[Dict[str, List[int]]]]:
    """
    Remove overlapping blocks based on a specified overlap ratio threshold.

    Args:
        blocks (List[Dict[str, List[int]]]): List of block dictionaries, each containing a 'block_bbox' key.
        threshold (float): Ratio threshold to determine significant overlap.
        smaller (bool): If True, the smaller block in overlap is removed.

    Returns:
        Tuple[List[Dict[str, List[int]]], List[Dict[str, List[int]]]]:
            A tuple containing the updated list of blocks and a list of dropped blocks.
    """
    dropped_blocks = []
    dropped_indexes = set()

    # Iterate over each pair of blocks to find overlaps
    for i, block1 in enumerate(blocks):
        for j in range(i + 1, len(blocks)):
            block2 = blocks[j]
            # Skip blocks that are already marked for removal
            if i in dropped_indexes or j in dropped_indexes:
                continue
            # Check for overlap and determine which block to remove
            overlap_box_index = _get_minbox_if_overlap_by_ratio(
                block1["block_bbox"],
                block2["block_bbox"],
                threshold,
                smaller=smaller,
            )
            if overlap_box_index is not None:
                # Determine which block to remove based on overlap_box_index
                if overlap_box_index == 1:
                    drop_index = i
                else:
                    drop_index = j
                dropped_indexes.add(drop_index)

    # Remove marked blocks from the original list
    for index in sorted(dropped_indexes, reverse=True):
        dropped_blocks.append(blocks[index])
        del blocks[index]

    return blocks, dropped_blocks


def _get_text_median_width(
    blocks: List[Dict[str, any]], is_horizontal=True
) -> Tuple[float, int, float]:
    """
    Calculate the median width of blocks labeled as "text".

    Args:
        blocks (List[Dict[str, any]]): List of block dictionaries, each containing a 'block_bbox' and 'label'.

    Returns:
        float: The median width of text blocks, or infinity if no text blocks are found.
        int: The count of text blocks within 10% of the median width.
        float: The page length of text blocks.
    """
    if is_horizontal:
        widths = [
            block["block_bbox"][2] - block["block_bbox"][0]
            for block in blocks
            if block.get("block_label") == "text"
        ]
        page_max = max([block["block_bbox"][2] for block in blocks] + [0])
        page_min = min([block["block_bbox"][0] for block in blocks] + [0])
    else:
        widths = [
            block["block_bbox"][3] - block["block_bbox"][1]
            for block in blocks
            if block.get("block_label")
            in ["text", "formula", "algorithm", "reference", "content", "abstract"]
        ]
        page_max = max([block["block_bbox"][3] for block in blocks] + [0])
        page_min = min([block["block_bbox"][1] for block in blocks] + [0])

    if len(widths) == 0:
        return float("inf"), 0, 0

    page_length = page_max - page_min
    k = np.median(widths)
    differences = np.abs(widths - k)
    k_01 = k * 0.4
    count = np.sum(differences < k_01)
    return k if widths else float("inf"), count, page_length


def _get_layout_property(
    blocks: List[Dict[str, any]],
    median_width: float,
    no_mask_labels: List[str],
    threshold: float = 0.8,
    # other_layout_threshold: float = 0.4,
) -> Tuple[List[Dict[str, any]], bool]:
    """
    Determine the layout (single or double column) of text blocks.

    Args:
        blocks (List[Dict[str, any]]): List of block dictionaries containing 'label' and 'block_bbox'.
        median_width (float): Median width of text blocks.
        no_mask_labels (List[str]): Labels of blocks to be considered for layout analysis.
        threshold (float): Threshold for determining layout overlap.

    Returns:
        Tuple[List[Dict[str, any]], bool]: Updated list of blocks with layout information and a boolean
        indicating if the double layout area is greater than the single layout area.
    """
    blocks.sort(
        key=lambda x: (
            x["block_bbox"][0],
            (x["block_bbox"][2] - x["block_bbox"][0]),
        ),
    )
    check_single_layout = {}
    page_min_x, page_max_x = float("inf"), 0
    double_label_area = 0
    single_label_area = 0

    for i, block in enumerate(blocks):
        page_min_x = min(page_min_x, block["block_bbox"][0])
        page_max_x = max(page_max_x, block["block_bbox"][2])
    page_width = page_max_x - page_min_x

    for i, block in enumerate(blocks):
        if block["block_label"] not in no_mask_labels:
            continue

        x_min_i, _, x_max_i, _ = block["block_bbox"]
        layout_length = x_max_i - x_min_i
        (
            cover_count,
            cover_with_threshold_count,
            other_layout_threshold_count,
        ) = (0, 0, 0)
        match_block_with_threshold_indexes = []

        has_left_text = False
        has_right_text = False
        x1, y1, x2, y2 = block["block_bbox"]
        for j, block2 in enumerate(blocks):
            if i == j or block2["block_label"] != "text":
                continue
            bbox2 = block2["block_bbox"]
            x1_2, y1_2, x2_2, y2_2 = bbox2
            if x2_2 <= x1 and not (y2_2 <= y1 or y1_2 >= y2):
                has_left_text = True
            if x1_2 >= x2 and not (y2_2 <= y1 or y1_2 >= y2):
                has_right_text = True
            if has_left_text or has_right_text:
                break
        no_text_on_sides = not (has_left_text or has_right_text)
        no_text_on_sides = True

        for j, other_block in enumerate(blocks):
            if i == j or other_block["block_label"] not in no_mask_labels:
                continue

            x_min_j, _, x_max_j, _ = other_block["block_bbox"]
            x_match_min, x_match_max = max(
                x_min_i,
                x_min_j,
            ), min(x_max_i, x_max_j)
            match_block_iou = (x_match_max - x_match_min) / (x_max_j - x_min_j)
            # max_iou = _get_projection_iou(block["block_bbox"],other_block["block_bbox"])

            if match_block_iou > 0:
                cover_count += 1
                if match_block_iou > threshold:
                    cover_with_threshold_count += 1
                    match_block_with_threshold_indexes.append(
                        (j, match_block_iou),
                    )
                # elif max_iou > other_layout_threshold: # centered text
                #     other_layout_threshold_count += 1

                x_min_i = x_match_max
                if x_min_i >= x_max_i:
                    break

        if ((layout_length > median_width * 1.3) and cover_count >= 2) or (
            layout_length > 0.6 * page_width
        ):
            # ) or (layout_length > 0.6 * page_width and no_text_on_sides):
            # if (
            #     layout_length > median_width * 1.3 and cover_count >= 2
            # ):
            # if layout_length > median_width * 1.3 and (cover_with_threshold_count >= 2):
            block["layout"] = "double"
            double_label_area += (block["block_bbox"][2] - block["block_bbox"][0]) * (
                block["block_bbox"][3] - block["block_bbox"][1]
            )
        # elif layout_length < median_width* 0.5 and cover_count >= 2:
        # # elif other_layout_threshold_count >= 2:
        #     block["layout"] = "other"
        else:
            block["layout"] = "single"
            check_single_layout[i] = match_block_with_threshold_indexes

    # Check single-layout block
    for i, single_layout in check_single_layout.items():
        if single_layout:
            index, match_iou = single_layout[-1]
            if match_iou > 0.9 and blocks[index]["layout"] == "double":
                blocks[i]["layout"] = "double"
                double_label_area += (
                    blocks[i]["block_bbox"][2] - blocks[i]["block_bbox"][0]
                ) * (blocks[i]["block_bbox"][3] - blocks[i]["block_bbox"][1])
            else:
                single_label_area += (
                    blocks[i]["block_bbox"][2] - blocks[i]["block_bbox"][0]
                ) * (blocks[i]["block_bbox"][3] - blocks[i]["block_bbox"][1])

    return blocks, (double_label_area > single_label_area)


def _get_bbox_direction(input_bbox: List[float], ratio: float = 1.0) -> bool:
    """
    Determine if a bounding box is horizontal or vertical.

    Args:
        input_bbox (List[float]): Bounding box [x_min, y_min, x_max, y_max].
        ratio (float): Ratio for determining orientation. Default is 1.0.

    Returns:
        bool: True if the bounding box is considered horizontal, False if vertical.
    """
    width = input_bbox[2] - input_bbox[0]
    height = input_bbox[3] - input_bbox[1]
    return width * ratio >= height


def _get_projection_iou(
    input_bbox: List[float],
    match_bbox: List[float],
    is_horizontal: bool = True,
) -> float:
    """
    Calculate the IoU of lines between two bounding boxes.

    Args:
        input_bbox (List[float]): First bounding box [x_min, y_min, x_max, y_max].
        match_bbox (List[float]): Second bounding box [x_min, y_min, x_max, y_max].
        is_horizontal (bool): Whether to compare horizontally or vertically.

    Returns:
        float: Line IoU. Returns 0 if there is no overlap.
    """
    if is_horizontal:
        x_match_min = max(input_bbox[0], match_bbox[0])
        x_match_max = min(input_bbox[2], match_bbox[2])
        overlap = max(0, x_match_max - x_match_min)
        input_width = min(input_bbox[2] - input_bbox[0], match_bbox[2] - match_bbox[0])
    else:
        y_match_min = max(input_bbox[1], match_bbox[1])
        y_match_max = min(input_bbox[3], match_bbox[3])
        overlap = max(0, y_match_max - y_match_min)
        input_width = min(input_bbox[3] - input_bbox[1], match_bbox[3] - match_bbox[1])

    return overlap / input_width if input_width > 0 else 0.0


def _get_pre_cut(
    boxes: np.ndarray, indices: List[int], direction=0, min_gap=1.0
):  # direction 0 x;1 y
    sorted_indices = boxes[:, direction].argsort()
    sorted_boxes = boxes[sorted_indices]
    sorted_indices = np.array(indices)[sorted_indices]

    # Perform X-axis projection
    projection = _projection_by_bboxes(boxes=sorted_boxes, axis=direction)
    intervals = _split_projection_profile(projection, 0, 1)

    if not intervals:
        return []

    # Process each segment defined by axis projection
    last_end = -1
    res = []
    interval_list = []
    for start, end in zip(*intervals):
        if last_end != -1 and start - last_end >= min_gap:
            res.append((last_end + start) // 2)
            interval_list.append(start - last_end)
        last_end = end
    return res, np.median(interval_list) if len(interval_list) else 0.0


def _get_sub_category(
    blocks: List[Dict[str, Any]],
    title_labels: List[str],
    min_gap_x=10,
    min_gap_y=10,
    is_only_x=False,
) -> Tuple[List[Dict[str, Any]], List[float]]:
    """
    Determine the layout of title and text blocks and collect pre_cuts.

    Args:
        blocks (List[Dict[str, Any]]): List of block dictionaries.
        title_labels (List[str]): List of labels considered as titles.

    Returns:
        List[Dict[str, Any]]: Updated list of blocks with title-text layout information.
        Dict[float]: Dict of pre_cuts coordinates.
    """
    if len(blocks) == 0:
        return blocks, {}

    sub_title_labels = ["paragraph_title"]
    vision_labels = ["image", "table", "chart", "figure"]
    vision_title_labels = ["figure_title", "chart_title", "table_title"]
    all_labels = title_labels + sub_title_labels + vision_labels + vision_title_labels
    special_pre_cut_labels = sub_title_labels

    # single doc title is irregular,pre cut not applicable
    num_doc_title = 0
    for block in blocks:
        if block["block_label"] == "doc_title":
            num_doc_title += 1
            if num_doc_title == 2:
                special_pre_cut_labels = title_labels + sub_title_labels
                break

    min_x = min(block["block_bbox"][0] for block in blocks)
    min_y = min(block["block_bbox"][1] for block in blocks)
    max_x = max(block["block_bbox"][2] for block in blocks)
    max_y = max(block["block_bbox"][3] for block in blocks)
    region_bbox = (min_x, min_y, max_x, max_y)
    region_x_center = (region_bbox[0] + region_bbox[2]) / 2
    region_y_center = (region_bbox[1] + region_bbox[3]) / 2
    region_width = region_bbox[2] - region_bbox[0]
    region_height = region_bbox[3] - region_bbox[1]

    bboxes = np.array([list(map(int, block["block_bbox"])) for block in blocks])
    pre_cuts = {"tran": False}

    x_pre_cuts, interval_len_x = _get_pre_cut(
        boxes=bboxes, indices=list(range(len(blocks))), direction=0, min_gap=min_gap_x
    )
    y_pre_cuts, interval_len_y = _get_pre_cut(
        boxes=bboxes, indices=list(range(len(blocks))), direction=1, min_gap=70
    )

    if is_only_x == False:
        if interval_len_x * 2 < interval_len_y:
            pre_cuts["tran"] = True
            pre_cuts["y"] = y_pre_cuts

    # if y_pre_cuts != [] and is_only_x==False:
    #     pre_cuts["y"] = y_pre_cuts

    if x_pre_cuts != [] and len(blocks) > min_gap_y:
        pre_cuts["x"] = x_pre_cuts

    for i, block1 in enumerate(blocks):
        block1.setdefault("title_text", [])
        block1.setdefault("sub_title", [])
        block1.setdefault("vision_footnote", [])
        block1.setdefault("sub_label", block1["block_label"])

        if block1["block_label"] not in all_labels:
            continue

        bbox1 = block1["block_bbox"]
        x1, y1, x2, y2 = bbox1
        is_horizontal_1 = _get_bbox_direction(block1["block_bbox"])
        left_up_title_text_distance = float("inf")
        left_up_title_text_index = -1
        left_up_title_text_direction = None
        right_down_title_text_distance = float("inf")
        right_down_title_text_index = -1
        right_down_title_text_direction = None

        # pre-cuts
        # Condition 1: Length is greater than half of the layout region
        if is_horizontal_1:
            block_length = x2 - x1
            required_length = region_width / 2
        else:
            block_length = y2 - y1
            required_length = region_height / 2
        if block1["block_label"] in special_pre_cut_labels:
            length_condition = True
        else:
            length_condition = block_length > required_length

        # Condition 2: Centered check (must be within ±20 in both horizontal and vertical directions)
        block_x_center = (x1 + x2) / 2
        block_y_center = (y1 + y2) / 2
        tolerance_len = block_length // 5
        if block1["block_label"] in special_pre_cut_labels:
            tolerance_len = block_length // 10
        if is_horizontal_1:
            is_centered = abs(block_x_center - region_x_center) <= tolerance_len
        else:
            is_centered = abs(block_y_center - region_y_center) <= tolerance_len
        # Condition 3: Check for surrounding text
        has_left_text = False
        has_right_text = False
        has_above_text = False
        has_below_text = False
        for block2 in blocks:
            if (
                block2["block_label"]
                not in ["text", "formula", "content", "abstract", "reference"]
                + title_labels
                + sub_title_labels
                + vision_title_labels
            ):
                continue
            bbox2 = block2["block_bbox"]
            x1_2, y1_2, x2_2, y2_2 = bbox2
            if is_horizontal_1:
                if x2_2 <= x1 and not (y2_2 <= y1 or y1_2 >= y2):
                    has_left_text = True
                if x1_2 >= x2 and not (y2_2 <= y1 or y1_2 >= y2):
                    has_right_text = True
            else:
                if y2_2 <= y1 and not (x2_2 <= x1 or x1_2 >= x2):
                    has_above_text = True
                if y1_2 >= y2 and not (x2_2 <= x1 or x1_2 >= x2):
                    has_below_text = True

            if (is_horizontal_1 and has_left_text and has_right_text) or (
                not is_horizontal_1 and has_above_text and has_below_text
            ):
                break

        no_text_on_sides = (
            not (has_left_text or has_right_text)
            if is_horizontal_1
            else not (has_above_text or has_below_text)
        )

        # Add coordinates if all conditions are met
        if is_centered and length_condition and no_text_on_sides:
            if is_horizontal_1:
                pre_cuts.setdefault("y", []).append(y1)
            else:
                pre_cuts.setdefault("x", []).append(x1)

        block_iou_threshold = 0.1
        if block1["block_label"] in sub_title_labels:
            block_iou_threshold = 0.5
        match_iou_flag_left_up = False
        match_iou_flag_right_down = False

        for j, block2 in enumerate(blocks):
            if i == j:
                continue

            bbox2 = block2["block_bbox"]
            x1_prime, y1_prime, x2_prime, y2_prime = bbox2
            is_horizontal_2 = _get_bbox_direction(bbox2)
            match_block_iou = _get_projection_iou(
                bbox2,
                bbox1,
                is_horizontal_1,
            )

            def distance_(is_horizontal, is_left_up):
                if match_block_iou > 0:
                    if is_horizontal:
                        if is_left_up:
                            return (y1 - y2_prime + 2) // 5 + x1_prime / 5000
                        else:
                            return (y1_prime - y2 + 2) // 5 + x1_prime / 5000

                    else:
                        if is_left_up:
                            return (x1 - x2_prime + 2) // 5 + y1_prime / 5000
                        else:
                            return (x1_prime - x2 + 2) // 5 + y1_prime / 5000
                else:
                    return float("inf")

            if is_horizontal_1:
                # if match_block_iou >= block_iou_threshold:
                left_up_distance = distance_(True, True)
                right_down_distance = distance_(True, False)
                if y2_prime <= y1 and left_up_distance <= left_up_title_text_distance:
                    left_up_title_text_index = j
                    left_up_title_text_distance = left_up_distance
                    left_up_title_text_direction = is_horizontal_2
                    if match_block_iou < block_iou_threshold:
                        match_iou_flag_left_up = False
                    else:
                        match_iou_flag_left_up = True
                elif (
                    y1_prime > y2
                    and right_down_distance < right_down_title_text_distance
                ):
                    right_down_title_text_distance = right_down_distance
                    right_down_title_text_index = j
                    right_down_title_text_direction = is_horizontal_2
                    if match_block_iou < block_iou_threshold:
                        match_iou_flag_right_down = False
                    else:
                        match_iou_flag_right_down = True

            else:
                # if match_block_iou >= block_iou_threshold:
                left_up_distance = distance_(False, True)
                right_down_distance = distance_(False, False)
                if x2_prime <= x1 and left_up_distance <= left_up_title_text_distance:
                    left_up_title_text_distance = left_up_distance
                    left_up_title_text_index = j
                    left_up_title_text_direction = is_horizontal_2
                    if match_block_iou < block_iou_threshold:
                        match_iou_flag_left_up = False
                    else:
                        match_iou_flag_left_up = True
                elif (
                    x1_prime > x2
                    and right_down_distance < right_down_title_text_distance
                ):
                    right_down_title_text_distance = right_down_distance
                    right_down_title_text_index = j
                    right_down_title_text_direction = is_horizontal_2
                    if match_block_iou < block_iou_threshold:
                        match_iou_flag_right_down = False
                    else:
                        match_iou_flag_right_down = True

        height = bbox1[3] - bbox1[1]
        width = bbox1[2] - bbox1[0]
        title_text_weight = [0.8, 0.8]

        title_text, sub_title, vision_footnote = [], [], []

        def get_sub_category_(
            title_text_direction,
            title_text_index,
            label,
            is_left_up=True,
        ):
            direction_ = [1, 3] if is_left_up else [2, 4]
            if (
                title_text_direction == is_horizontal_1
                and title_text_index != -1
                and (label == "text" or label == "paragraph_title")
            ):
                bbox2 = blocks[title_text_index]["block_bbox"]
                if is_horizontal_1:
                    height1 = bbox2[3] - bbox2[1]
                    width1 = bbox2[2] - bbox2[0]
                    if label == "text":
                        if (
                            _nearest_edge_distance(bbox1, bbox2)[0] <= 15
                            and block1["block_label"] in vision_labels
                            and width1 < width
                            and height1 < 0.5 * height
                        ):
                            blocks[title_text_index]["sub_label"] = "vision_footnote"
                            vision_footnote.append(bbox2)
                        elif (
                            height1 < height * title_text_weight[0]
                            and (width1 < width or width1 > 1.5 * width)
                            and block1["block_label"] in title_labels
                        ):
                            blocks[title_text_index]["sub_label"] = "title_text"
                            title_text.append((direction_[0], bbox2))
                    elif (
                        label == "paragraph_title"
                        and block1["block_label"] in sub_title_labels
                    ):
                        sub_title.append(bbox2)
                else:
                    height1 = bbox2[3] - bbox2[1]
                    width1 = bbox2[2] - bbox2[0]
                    if label == "text":
                        if (
                            _nearest_edge_distance(bbox1, bbox2)[0] <= 15
                            and block1["block_label"] in vision_labels
                            and height1 < height
                            and width1 < 0.5 * width
                        ):
                            blocks[title_text_index]["sub_label"] = "vision_footnote"
                            vision_footnote.append(bbox2)
                        elif (
                            width1 < width * title_text_weight[1]
                            and block1["block_label"] in title_labels
                        ):
                            blocks[title_text_index]["sub_label"] = "title_text"
                            title_text.append((direction_[1], bbox2))
                    elif (
                        label == "paragraph_title"
                        and block1["block_label"] in sub_title_labels
                    ):
                        sub_title.append(bbox2)

        if match_iou_flag_right_down == False:
            right_down_title_text_index = -1
        if match_iou_flag_left_up == False:
            left_up_title_text_index = -1

        if (
            is_horizontal_1
            and abs(left_up_title_text_distance - right_down_title_text_distance) * 5
            > height
        ) or (
            not is_horizontal_1
            and abs(left_up_title_text_distance - right_down_title_text_distance) * 5
            > width
        ):
            if left_up_title_text_distance < right_down_title_text_distance:
                get_sub_category_(
                    left_up_title_text_direction,
                    left_up_title_text_index,
                    blocks[left_up_title_text_index]["block_label"],
                    True,
                )
            else:
                get_sub_category_(
                    right_down_title_text_direction,
                    right_down_title_text_index,
                    blocks[right_down_title_text_index]["block_label"],
                    False,
                )
        else:
            get_sub_category_(
                left_up_title_text_direction,
                left_up_title_text_index,
                blocks[left_up_title_text_index]["block_label"],
                True,
            )
            get_sub_category_(
                right_down_title_text_direction,
                right_down_title_text_index,
                blocks[right_down_title_text_index]["block_label"],
                False,
            )

        if block1["block_label"] in title_labels:
            if blocks[i].get("title_text") == []:
                blocks[i]["title_text"] = title_text

        if block1["block_label"] in sub_title_labels:
            if blocks[i].get("sub_title") == []:
                blocks[i]["sub_title"] = sub_title

        if block1["block_label"] in vision_labels:
            if blocks[i].get("vision_footnote") == []:
                blocks[i]["vision_footnote"] = vision_footnote

    return blocks, pre_cuts


def _projection_index_xy(blocks):
    blocks.sort(key=lambda x: (x["index"], x["block_bbox"][1], x["block_bbox"][0]))

    sorted_blocks = []
    i = 0
    while i < len(blocks):
        block1 = blocks[i]
        mid_blocks = [block1]
        for j in range(i + 1, len(blocks)):
            block2 = blocks[j]
            if block1["index"] != block2["index"]:
                break
            iou = _get_projection_iou(
                block1["block_bbox"], block2["block_bbox"], is_horizontal=False
            )
            if iou > 0.5:
                mid_blocks.append(block2)
            else:
                break
        mid_blocks.sort(key=lambda x: x["block_bbox"][0])
        sorted_blocks.extend(mid_blocks)
        i += len(mid_blocks)
    return sorted_blocks


def _projection_xy(bboxes, segment_ids, is_horizontal=False):
    """
    Sort and group bounding boxes based on their projection along the x or y axis.

    :param bboxes: List of bounding boxes, each represented as [x1, y1, x2, y2].
    :param is_horizontal: Boolean indicating whether to project horizontally (True) or vertically (False).
    :return: Sorted and grouped bounding boxes.
    """
    # Determine the axis for sorting
    axis = 1 if is_horizontal else 0

    # Initial sort based on the chosen axis
    # sorted_bboxes = sorted(bboxes, key=lambda x: (x[(axis + 1)%2], x[axis]))
    bboxes_with_ids = list(zip(bboxes, segment_ids))
    bboxes_with_ids.sort(key=lambda x: (x[1], x[0][1], x[0][0]))

    # Initialize the final list of sorted and grouped bounding boxes
    final_sorted_bboxes = []

    # Initialize the visited array
    visited = [False] * len(bboxes_with_ids)

    # Group by segment_id
    for i in range(len(bboxes_with_ids)):
        if visited[i]:
            continue

        current_id = bboxes_with_ids[i][1]
        mid_bboxes_with_ids = [bboxes_with_ids[i]]
        visited[i] = True

        # Collect all bboxes with the same segment_id and IoU > 0.4
        for j in range(i + 1, len(bboxes_with_ids)):
            if visited[j] or bboxes_with_ids[j][1] != current_id:
                continue

            bbox1 = mid_bboxes_with_ids[-1][0]
            bbox2 = bboxes_with_ids[j][0]
            iou = _get_projection_iou(bbox1, bbox2, is_horizontal=is_horizontal)
            if iou > 0.5:
                mid_bboxes_with_ids.append(bboxes_with_ids[j])
                visited[j] = True

        # Sort the collected bboxes within the same segment_id based on the projection axis
        mid_bboxes_with_ids.sort(key=lambda x: (x[0][axis], x[0][(axis + 1) % 2]))

        # Add the sorted bboxes to the final list
        final_sorted_bboxes.extend([x[0] for x in mid_bboxes_with_ids])

    return final_sorted_bboxes


def get_layout_ordering(
    parsing_res_list: List[Dict[str, Any]],
    no_mask_labels: List[str] = [],
    is_only_xycut=False,
    is_add_mgs=True,
    is_add_cmm=True,
    is_use_adaptive_scheme=True,
    is_add_pre_cut=True,
    is_single_stage=False,
    min_gap_x=-1,
    min_gap_y=-1,
    is_only_x=False,
    remove_overlaps=True,
) -> List[Dict[str, Any]]:
    """
    Process layout parsing results to remove overlapping bounding boxes
    and assign an ordering index based on their positions.

    Modifies:
        The 'parsing_res_list' list by adding an 'index' to each block.

    Args:
        parsing_res_list (List[Dict[str, Any]]): List of block dictionaries with 'block_bbox' and 'block_label'.
        no_mask_labels (List[str]): Labels for which overlapping removal is not performed.
        remove_overlaps (bool): Whether to apply the upstream overlap-removal
            heuristic before ordering. Defaults to True.
    """
    title_text_labels = ["doc_title"]
    title_labels = ["doc_title", "paragraph_title"]
    vision_labels = ["image", "table", "seal", "chart", "figure"]
    vision_title_labels = ["table_title", "chart_title", "figure_title"]

    if remove_overlaps:
        parsing_res_list, _ = _remove_overlap_blocks(
            parsing_res_list,
            threshold=0.5,
            smaller=True,
        )
    parsing_res_list, pre_cuts = _get_sub_category(
        parsing_res_list,
        title_text_labels,
        min_gap_x=min_gap_x,
        min_gap_y=min_gap_y,
        is_only_x=is_only_x,
    )

    if is_only_xycut == True:
        doc_flag = False

    projection_direction_page = False
    median_height, small_height_num, page_height = _get_text_median_width(
        parsing_res_list, is_horizontal=False
    )
    if median_height < 0.05 * page_height and small_height_num > 45:
        pre_cuts = {"x": []}
        projection_direction_page = True

    if is_only_xycut or is_add_mgs == False or is_add_pre_cut == False:
        parsing_res_by_pre_cuts_list = [parsing_res_list]
    else:
        parsing_res_by_pre_cuts_list = [parsing_res_list]
        if len(pre_cuts) > 1:
            block_bboxes = [block["block_bbox"] for block in parsing_res_list]
            if pre_cuts["tran"]:
                axes_order = ["y", "x"]
            else:
                axes_order = ["x", "y"]
            # print(pre_cuts)
            # print(axes_order)
            for axis in axes_order:
                if axis in pre_cuts:
                    axis_index = 1 if axis == "y" else 0

                    max_val = max(bbox[axis_index + 2] for bbox in block_bboxes)

                    intervals = []
                    prev = 0
                    for cut in sorted(pre_cuts[axis]):
                        intervals.append((prev, cut))
                        prev = cut
                    intervals.append((prev, max_val))

                    new_parsing_res_by_pre_cuts_list = []

                    for parsing_res_group in parsing_res_by_pre_cuts_list:
                        for start, end in intervals:
                            parsing_res_by_current_interval = []
                            parsing_res_group_bboxes = [
                                block["block_bbox"] for block in parsing_res_group
                            ]
                            for idx, bbox in enumerate(parsing_res_group_bboxes):
                                if (bbox[axis_index] >= start) and (
                                    bbox[axis_index] < end
                                ):
                                    parsing_res_by_current_interval.append(
                                        parsing_res_group[idx]
                                    )
                            new_parsing_res_by_pre_cuts_list.append(
                                parsing_res_by_current_interval
                            )

                    parsing_res_by_pre_cuts_list = new_parsing_res_by_pre_cuts_list

    final_parsing_res_list = []
    num_index = 0
    num_sub_index = 0
    page_first_doc_title = False
    for sub_page_idx, parsing_res_by_pre_cuts in enumerate(
        parsing_res_by_pre_cuts_list
    ):
        # print("input", [block["block_bbox"] for block in parsing_res_by_pre_cuts])
        # use mask
        if is_only_xycut == False:
            doc_flag = False
            median_width, _, _ = _get_text_median_width(parsing_res_by_pre_cuts)
            parsing_res_by_pre_cuts, projection_direction = _get_layout_property(
                parsing_res_by_pre_cuts,
                median_width,
                no_mask_labels=no_mask_labels,
                threshold=0.3,
            )
            projection_direction = projection_direction or projection_direction_page

            for block in parsing_res_by_pre_cuts:
                block["block_bbox"] = list(map(int, block["block_bbox"]))
                if block["block_label"] == "doc_title":
                    page_first_doc_title = True

            # Convert bounding boxes to float and remove overlaps
            (
                double_text_blocks,
                other_text_blocks,
                title_text_blocks,
                title_blocks,
                vision_blocks,
                vision_title_blocks,
                vision_footnote_blocks,
                other_blocks,
            ) = ([], [], [], [], [], [], [], [])

            drop_indexes = []

            parsing_res_by_pre_cuts.sort(key=lambda x: int(x["block_bbox"][1]))
            first_label_flag = True

            for index, block in enumerate(parsing_res_by_pre_cuts):
                label = block["sub_label"]
                block["block_bbox"] = list(map(int, block["block_bbox"]))

                # use mask and add mgs
                if is_add_mgs:

                    # if page_first_doc_title == False and (first_label_flag and label == "paragraph_title"):
                    #     block["sub_label"] = "doc_title"

                    if label == "doc_title":
                        doc_flag = True

                    if label in no_mask_labels:
                        if block["layout"] == "double":
                            double_text_blocks.append(block)
                            drop_indexes.append(index)
                        # elif block["layout"] == "other":
                        #     other_text_blocks.append(block)
                        #     drop_indexes.append(index)
                        first_label_flag = False
                    elif label == "title_text":
                        title_text_blocks.append(block)
                        drop_indexes.append(index)
                        first_label_flag = False
                    elif label == "vision_footnote":
                        vision_footnote_blocks.append(block)
                        drop_indexes.append(index)
                        first_label_flag = False
                    elif label in vision_title_labels:
                        vision_title_blocks.append(block)
                        drop_indexes.append(index)
                        first_label_flag = False
                    elif label in title_labels:
                        title_blocks.append(block)
                        drop_indexes.append(index)
                        first_label_flag = False
                    elif label in vision_labels:
                        vision_blocks.append(block)
                        drop_indexes.append(index)
                        first_label_flag = False
                    else:
                        other_blocks.append(block)
                        drop_indexes.append(index)
                # use mask and no mgs
                else:
                    if label not in no_mask_labels:
                        other_blocks.append(block)
                        drop_indexes.append(index)

            # keep single_layout text
            for index in sorted(drop_indexes, reverse=True):
                del parsing_res_by_pre_cuts[index]

            # use mask and use mgs
            if is_add_mgs:
                if len(parsing_res_by_pre_cuts) > 0:
                    # single text label
                    if is_use_adaptive_scheme and (
                        len(double_text_blocks) > len(parsing_res_by_pre_cuts)
                        or projection_direction
                    ):
                        parsing_res_by_pre_cuts.extend(
                            title_blocks + double_text_blocks
                        )
                        title_blocks = []
                        double_text_blocks = []
                        block_bboxes = [
                            block["block_bbox"] for block in parsing_res_by_pre_cuts
                        ]
                        # block_bboxes.sort(
                        #     key=lambda x: (
                        #         x[0] // max(20, median_width),
                        #         x[1],
                        #     ),
                        # )
                        block_bboxes = np.array(block_bboxes)
                        # print("sort by yx")
                        sorted_indices, segment_ids = sort_by_xycut(
                            block_bboxes, direction=1, min_gap=1
                        )
                    else:
                        block_bboxes = [
                            block["block_bbox"] for block in parsing_res_by_pre_cuts
                        ]
                        # block_bboxes.sort(key=lambda x: (x[0] // 20, x[1]))
                        block_bboxes = np.array(block_bboxes)
                        # print("sort by xy")
                        sorted_indices, segment_ids = sort_by_xycut(
                            block_bboxes, direction=0, min_gap=1
                        )
                    # get index
                    sorted_boxes = block_bboxes[sorted_indices].tolist()
                    # print("sorte bboxes", sorted_boxes, segment_ids)

                    # projection ordering
                    sorted_boxes = _projection_xy(sorted_boxes, segment_ids)

                    # print(sorted_boxes)
                    for block in parsing_res_by_pre_cuts:
                        block["index"] = (
                            num_index + sorted_boxes.index(block["block_bbox"]) + 1
                        )
                        block["sub_index"] = (
                            num_sub_index + sorted_boxes.index(block["block_bbox"]) + 1
                        )

            # use mask and no mgs
            else:
                block_bboxes = [
                    block["block_bbox"] for block in parsing_res_by_pre_cuts
                ]
                block_bboxes.sort(
                    key=lambda x: (
                        x[0] // max(20, median_width),
                        x[1],
                    ),
                )
                block_bboxes = np.array(block_bboxes)
                sorted_indices, segment_ids = sort_by_xycut(
                    block_bboxes, direction=1, min_gap=1
                )
                # get index
                sorted_boxes = block_bboxes[sorted_indices].tolist()
                for block in parsing_res_by_pre_cuts:
                    block["index"] = (
                        num_index + sorted_boxes.index(block["block_bbox"]) + 1
                    )
                    block["sub_index"] = (
                        num_sub_index + sorted_boxes.index(block["block_bbox"]) + 1
                    )

            def nearest_match_(
                input_blocks, distance_type="manhattan", is_add_index=True
            ):
                for block in input_blocks:
                    bbox = block["block_bbox"]
                    min_distance = float("inf")
                    min_distance_config = [
                        [float("inf"), float("inf")],
                        float("inf"),
                        float("inf"),
                    ]  # for double text
                    nearest_gt_index = 0
                    for match_block in parsing_res_by_pre_cuts:
                        match_bbox = match_block["block_bbox"]
                        if distance_type == "nearest_iou_edge_distance":
                            distance, min_distance_config = _nearest_iou_edge_distance(
                                bbox,
                                match_bbox,
                                block["sub_label"],
                                vision_labels=vision_labels,
                                no_mask_labels=no_mask_labels,
                                median_width=median_width,
                                title_labels=title_labels,
                                title_text=block["title_text"],
                                sub_title=block["sub_title"],
                                min_distance_config=min_distance_config,
                                tolerance_len=10,
                            )
                        elif distance_type == "title_text":
                            if (
                                match_block["block_label"]
                                in title_labels + ["abstract"]
                                and match_block["title_text"] != []
                            ):
                                iou_left_up = (
                                    _calculate_overlap_area_div_minbox_area_ratio(
                                        bbox,
                                        match_block["title_text"][0][1],
                                    )
                                )
                                iou_right_down = (
                                    _calculate_overlap_area_div_minbox_area_ratio(
                                        bbox,
                                        match_block["title_text"][-1][1],
                                    )
                                )
                                iou = 1 - max(iou_left_up, iou_right_down)
                                distance = _manhattan_distance(bbox, match_bbox) * iou
                            else:
                                distance = float("inf")
                        elif distance_type == "manhattan":
                            distance = _manhattan_distance(bbox, match_bbox)
                        elif distance_type == "vision_footnote":
                            if (
                                match_block["block_label"] in vision_labels
                                and match_block["vision_footnote"] != []
                            ):
                                iou_left_up = (
                                    _calculate_overlap_area_div_minbox_area_ratio(
                                        bbox,
                                        match_block["vision_footnote"][0],
                                    )
                                )
                                iou_right_down = (
                                    _calculate_overlap_area_div_minbox_area_ratio(
                                        bbox,
                                        match_block["vision_footnote"][-1],
                                    )
                                )
                                iou = 1 - max(iou_left_up, iou_right_down)
                                distance = _manhattan_distance(bbox, match_bbox) * iou
                            else:
                                distance = float("inf")
                        elif distance_type == "vision_body":
                            if (
                                match_block["block_label"] in vision_title_labels
                                and block["vision_footnote"] != []
                            ):
                                iou_left_up = (
                                    _calculate_overlap_area_div_minbox_area_ratio(
                                        match_bbox,
                                        block["vision_footnote"][0],
                                    )
                                )
                                iou_right_down = (
                                    _calculate_overlap_area_div_minbox_area_ratio(
                                        match_bbox,
                                        block["vision_footnote"][-1],
                                    )
                                )
                                iou = 1 - max(iou_left_up, iou_right_down)
                                distance = _manhattan_distance(bbox, match_bbox) * iou
                            else:
                                distance = float("inf")
                        else:
                            raise NotImplementedError

                        if distance < min_distance:
                            min_distance = distance
                            if is_add_index:
                                nearest_gt_index = match_block.get("index", 999)
                            else:
                                nearest_gt_index = match_block.get("sub_index", 999)

                    if is_add_index:
                        block["index"] = nearest_gt_index
                    else:
                        block["sub_index"] = nearest_gt_index

                    parsing_res_by_pre_cuts.append(block)

            if is_add_cmm and is_single_stage == False:
                # label:double layout text
                double_text_blocks.sort(
                    key=lambda x: (
                        x["block_bbox"][1] // 10,
                        x["block_bbox"][0] // median_width,
                        x["block_bbox"][1] ** 2 + x["block_bbox"][0] ** 2,
                    ),
                )
                nearest_match_(
                    double_text_blocks,
                    distance_type="nearest_iou_edge_distance",
                )
                # parsing_res_by_pre_cuts.sort(
                #     key=lambda x: (
                #         x["index"],
                #         x["block_bbox"][1],
                #         x["block_bbox"][0],
                #     ),
                # )
                parsing_res_by_pre_cuts = _projection_index_xy(parsing_res_by_pre_cuts)

                for idx, block in enumerate(parsing_res_by_pre_cuts):
                    block["index"] = num_index + idx + 1
                    block["sub_index"] = num_sub_index + idx + 1

                # label:doc_title , paragraph_title
                title_blocks.sort(
                    key=lambda x: (
                        x["block_bbox"][1],
                        x["block_bbox"][0] // median_width,
                        x["block_bbox"][1] ** 2 + x["block_bbox"][0] ** 2,
                    ),
                )

                nearest_match_(title_blocks, distance_type="nearest_iou_edge_distance")

                if doc_flag:
                    text_sort_labels = ["doc_title"]
                    text_label_priority = {
                        label: priority
                        for priority, label in enumerate(text_sort_labels)
                    }
                    doc_titles = []
                    for i, block in enumerate(parsing_res_by_pre_cuts):
                        if block["block_label"] == "doc_title":
                            doc_titles.append(
                                (
                                    i,
                                    block["block_bbox"][1],
                                    block["block_bbox"][0],
                                ),
                            )
                    doc_titles.sort(key=lambda x: (x[1], x[2]))
                    first_doc_title_index = doc_titles[0][0]
                    parsing_res_by_pre_cuts[first_doc_title_index]["index"] = 1
                    parsing_res_by_pre_cuts.sort(
                        key=lambda x: (
                            x["index"],
                            text_label_priority.get(x["block_label"], 9999),
                            x["block_bbox"][1],
                            x["block_bbox"][0],
                        ),
                    )
                    # parsing_res_by_pre_cuts = _projection_index_xy(
                    #     parsing_res_by_pre_cuts
                    # )
                else:
                    parsing_res_by_pre_cuts = _projection_index_xy(
                        parsing_res_by_pre_cuts
                    )

                for idx, block in enumerate(parsing_res_by_pre_cuts):
                    block["index"] = num_index + idx + 1
                    block["sub_index"] = num_sub_index + idx + 1

                # label:other layout text
                # other_text_blocks.sort(
                #     key=lambda x: (
                #         x["block_bbox"][1] // 10,
                #         x["block_bbox"][0] // median_width,
                #         x["block_bbox"][1] ** 2 + x["block_bbox"][0] ** 2,
                #     ),
                # )
                # nearest_match_(
                #     other_text_blocks,
                #     distance_type="nearest_iou_edge_distance",
                # )
                # # parsing_res_by_pre_cuts.sort(
                # #     key=lambda x: (
                # #         x["index"],
                # #         x["block_bbox"][1],
                # #         x["block_bbox"][0],
                # #     ),
                # # )
                # parsing_res_by_pre_cuts = custom_sort_key(parsing_res_by_pre_cuts)

                # for idx, block in enumerate(parsing_res_by_pre_cuts):
                #     block["index"] = num_index + idx + 1
                #     block["sub_index"] = num_sub_index + idx + 1

                # label:title-text
                nearest_match_(title_text_blocks, distance_type="title_text")

                def hor_tb_and_ver_lr(x, label):
                    input_bbox = x["block_bbox"]
                    is_horizontal = _get_bbox_direction(input_bbox)

                    if is_horizontal:
                        return input_bbox[1]
                    else:
                        return -1 if label == "doc_title" else input_bbox[0]

                parsing_res_by_pre_cuts.sort(
                    key=lambda x: (
                        x["index"],
                        hor_tb_and_ver_lr(x, x["block_label"]),
                    ),
                )

                for idx, block in enumerate(parsing_res_by_pre_cuts):
                    block["index"] = num_index + idx + 1
                    block["sub_index"] = num_sub_index + idx + 1

                # label:image,figure,chart,seal
                nearest_match_(
                    vision_blocks,
                    distance_type="nearest_iou_edge_distance",
                    is_add_index=False,
                )
                parsing_res_by_pre_cuts.sort(
                    key=lambda x: (
                        x["sub_index"],
                        x["block_bbox"][1],
                        x["block_bbox"][0],
                    ),
                )

                for idx, block in enumerate(parsing_res_by_pre_cuts):
                    block["sub_index"] = num_sub_index + idx + 1

                # label:image,figure,chart,seal title
                nearest_match_(
                    vision_title_blocks,
                    distance_type="nearest_iou_edge_distance",
                    is_add_index=False,
                )
                parsing_res_by_pre_cuts.sort(
                    key=lambda x: (
                        x["sub_index"],
                        x["block_bbox"][1],
                        x["block_bbox"][0],
                    ),
                )

                for idx, block in enumerate(parsing_res_by_pre_cuts):
                    block["sub_index"] = num_sub_index + idx + 1

                # label:vision footnote
                nearest_match_(
                    vision_footnote_blocks,
                    distance_type="vision_footnote",
                    is_add_index=False,
                )
                text_label_priority = {"vision_footnote": 9999}
                parsing_res_by_pre_cuts.sort(
                    key=lambda x: (
                        x["sub_index"],
                        text_label_priority.get(x["sub_label"], 0),
                        x["block_bbox"][1],
                        x["block_bbox"][0],
                    ),
                )

                for idx, block in enumerate(parsing_res_by_pre_cuts):
                    block["sub_index"] = num_sub_index + idx + 1

                # label:header、footnote、header_image...
                nearest_match_(
                    other_blocks, distance_type="manhattan", is_add_index=False
                )

            # use mask and (mgs) and (no cmm or is_single_stage=True)
            else:
                if is_add_mgs:
                    all_blocks = double_text_blocks + title_text_blocks + title_blocks
                else:
                    all_blocks = other_blocks

                if is_add_cmm and is_single_stage:
                    nearest_match_(
                        all_blocks,
                        distance_type="nearest_iou_edge_distance",
                        is_add_index=True,
                    )
                else:
                    nearest_match_(
                        all_blocks,
                        distance_type="manhattan",
                        is_add_index=True,
                    )

                parsing_res_by_pre_cuts.sort(
                    key=lambda x: (
                        x["index"],
                        x["block_bbox"][1],
                        x["block_bbox"][0],
                    ),
                )

                for idx, block in enumerate(parsing_res_by_pre_cuts):
                    block["index"] = num_index + idx + 1
                    block["sub_index"] = num_sub_index + idx + 1

        # only xycut:baseline
        else:
            if len(parsing_res_by_pre_cuts) > 0:
                block_bboxes = [
                    block["block_bbox"] for block in parsing_res_by_pre_cuts
                ]
                block_bboxes = np.array(block_bboxes)
                sorted_indices, segment_ids = sort_by_xycut(
                    block_bboxes, direction=1, min_gap=1
                )

                sorted_boxes = block_bboxes[sorted_indices].tolist()

                for block in parsing_res_by_pre_cuts:
                    block["index"] = (
                        num_index + sorted_boxes.index(block["block_bbox"]) + 1
                    )
                    block["sub_index"] = (
                        num_sub_index + sorted_boxes.index(block["block_bbox"]) + 1
                    )

        if page_first_doc_title == False and doc_flag:
            page_first_doc_title = True
            if pre_cuts.get("x") != None and sub_page_idx != 0:
                init_idx = 0
                parsing_res_by_pre_cuts.sort(key=lambda x: x.get("index", 999))
                for i in range(
                    min(len(parsing_res_by_pre_cuts), 3)
                ):  # doc title,title_text,title_text
                    if parsing_res_by_pre_cuts[i]["sub_label"] in [
                        "doc_title",
                        "title_text",
                    ]:
                        parsing_res_by_pre_cuts[i]["index"] = init_idx
                        parsing_res_by_pre_cuts[i]["sub_index"] = init_idx
                        init_idx += 0.01

        # add all parsing result
        final_parsing_res_list.extend(parsing_res_by_pre_cuts)

        # update num index
        num_sub_index += len(parsing_res_by_pre_cuts)
        for parsing_res in parsing_res_by_pre_cuts:
            if parsing_res.get("index"):
                num_index += 1

    final_parsing_res_list.sort(key=lambda x: (x["sub_index"]))
    index = 1
    for idx, block in enumerate(final_parsing_res_list):
        if block.get("index"):
            block["index"] = index
            index += 1
        block["sub_index"] = idx + 1

    parsing_res_list = [
        {
            "block_label": parsing_res["block_label"],
            "block_content": parsing_res["block_content"],
            "block_bbox": parsing_res["block_bbox"],
            "block_image": parsing_res.get("block_image", None),
            "seg_start_flag": parsing_res["seg_start_flag"],
            "seg_end_flag": parsing_res["seg_end_flag"],
            "sub_label": parsing_res["sub_label"],
            "sub_index": parsing_res["sub_index"],
            "index": parsing_res.get("index", None),
        }
        for parsing_res in final_parsing_res_list
    ]

    return parsing_res_list


def _manhattan_distance(
    point1: Tuple[float, float],
    point2: Tuple[float, float],
    weight_x: float = 1.0,
    weight_y: float = 1.0,
) -> float:
    """
    Calculate the weighted Manhattan distance between two points.

    Args:
        point1 (Tuple[float, float]): The first point as (x, y).
        point2 (Tuple[float, float]): The second point as (x, y).
        weight_x (float): The weight for the x-axis distance. Default is 1.0.
        weight_y (float): The weight for the y-axis distance. Default is 1.0.

    Returns:
        float: The weighted Manhattan distance between the two points.
    """
    return weight_x * abs(point1[0] - point2[0]) + weight_y * abs(point1[1] - point2[1])


def _nearest_edge_distance(
    input_bbox: List[int],
    match_bbox: List[int],
    weight: List[float] = [1.0, 1.0, 1.0, 1.0],
    label: str = "text",
    no_mask_labels: List[str] = [],
    min_edge_distance_config: List[float] = [],
    tolerance_len: float = 10.0,
) -> Tuple[float, List[float]]:
    """
    Calculate the nearest edge distance between two bounding boxes, considering directional weights.

    Args:
        input_bbox (list): The bounding box coordinates [x1, y1, x2, y2] of the input object.
        match_bbox (list): The bounding box coordinates [x1', y1', x2', y2'] of the object to match against.
        weight (list, optional): Directional weights for the edge distances [left, right, up, down]. Defaults to [1, 1, 1, 1].
        label (str, optional): The label/type of the object in the bounding box (e.g., 'text'). Defaults to 'text'.
        no_mask_labels (list, optional): Labels for which no masking is applied when calculating edge distances. Defaults to an empty list.
        min_edge_distance_config (list, optional): Configuration for minimum edge distances [min_edge_distance_x, min_edge_distance_y].
        Defaults to [float('inf'), float('inf')].
        tolerance_len (float, optional): The tolerance length for adjusting edge distances. Defaults to 10.

    Returns:
        Tuple[float, List[float]]: A tuple containing:
            - The calculated minimum edge distance between the bounding boxes.
            - A list with the minimum edge distances in the x and y directions.
    """
    match_bbox_iou = _calculate_overlap_area_div_minbox_area_ratio(
        input_bbox,
        match_bbox,
    )
    if match_bbox_iou > 0 and label not in no_mask_labels:
        return 0, [0, 0]

    if not min_edge_distance_config:
        min_edge_distance_config = [float("inf"), float("inf")]
    min_edge_distance_x, min_edge_distance_y = min_edge_distance_config

    x1, y1, x2, y2 = input_bbox
    x1_prime, y1_prime, x2_prime, y2_prime = match_bbox

    direction_num = 0
    distance_x = float("inf")
    distance_y = float("inf")
    distance = [float("inf")] * 4

    # input_bbox is to the left of match_bbox
    if x2 <= x1_prime:
        direction_num += 1
        distance[0] = x1_prime - x2
        if abs(distance[0] - min_edge_distance_x) <= tolerance_len:
            distance_x = min_edge_distance_x * weight[0]
        else:
            distance_x = distance[0] * weight[0]
    # input_bbox is to the right of match_bbox
    elif x1 >= x2_prime:
        direction_num += 1
        distance[1] = x1 - x2_prime
        if abs(distance[1] - min_edge_distance_x) <= tolerance_len:
            distance_x = min_edge_distance_x * weight[1]
        else:
            distance_x = distance[1] * weight[1]
    elif match_bbox_iou > 0:
        distance[0] = 0
        distance_x = 0

    # input_bbox is above match_bbox
    if y2 <= y1_prime:
        direction_num += 1
        distance[2] = y1_prime - y2
        if abs(distance[2] - min_edge_distance_y) <= tolerance_len:
            distance_y = min_edge_distance_y * weight[2]
        else:
            distance_y = distance[2] * weight[2]
        if label in no_mask_labels:
            distance_y = max(0.1, distance_y) * 10  # for abstract
    # input_bbox is below match_bbox
    elif y1 >= y2_prime:
        direction_num += 1
        distance[3] = y1 - y2_prime
        if abs(distance[3] - min_edge_distance_y) <= tolerance_len:
            distance_y = min_edge_distance_y * weight[3]
        else:
            distance_y = distance[3] * weight[3]
    elif match_bbox_iou > 0:
        distance[2] = 0
        distance_y = 0

    if direction_num == 2:
        return (distance_x + distance_y), [
            min(distance[0], distance[1]),
            min(distance[2], distance[3]),
        ]
    else:
        return min(distance_x, distance_y), [
            min(distance[0], distance[1]),
            min(distance[2], distance[3]),
        ]


def _get_weights(label, horizontal):
    """Define weights based on the label and orientation."""
    if label == "doc_title":
        return (
            [1, 0.1, 0.1, 1] if horizontal else [0.2, 0.1, 1, 1]
        )  # left-down ,  right-left
    elif label in [
        "paragraph_title",
        "table_title",
        "abstract",
        "image",
        "seal",
        "chart",
        "figure",
    ]:
        return [1, 1, 0.1, 1]  # down
    else:
        return [1, 1, 1, 0.1]


def _nearest_iou_edge_distance(
    input_bbox: List[int],
    match_bbox: List[int],
    label: str,
    vision_labels: List[str],
    no_mask_labels: List[str],
    median_width: int = -1,
    title_labels: List[str] = [],
    title_text: List[Tuple[int, List[int]]] = [],
    sub_title: List[List[int]] = [],
    min_distance_config: List[float] = [],
    tolerance_len: float = 10.0,
) -> Tuple[float, List[float]]:
    """
    Calculate the nearest IOU edge distance between two bounding boxes, considering label types, title adjustments, and minimum distance configurations.
    This function computes the edge distance between two bounding boxes while considering their overlap (IOU) and various adjustments based on label types,
    title text, and subtitle information. It also applies minimum distance configurations and tolerance adjustments.

    Args:
        input_bbox (List[int]): The bounding box coordinates [x1, y1, x2, y2] of the input object.
        match_bbox (List[int]): The bounding box coordinates [x1', y1', x2', y2'] of the object to match against.
        label (str): The label/type of the object in the bounding box (e.g., 'image', 'text', etc.).
        vision_labels (List[str]): List of labels for vision-related objects (e.g., images, icons).
        no_mask_labels (List[str]): Labels for which no masking is applied when calculating edge distances.
        median_width (int, optional): The median width for title dispersion calculation. Defaults to -1.
        title_labels (List[str], optional): Labels that indicate the object is a title. Defaults to an empty list.
        title_text (List[Tuple[int, List[int]]], optional): Text content associated with title labels, in the format [(position_indicator, [x1, y1, x2, y2]), ...].
        sub_title (List[List[int]], optional): List of subtitle bounding boxes to adjust the input_bbox. Defaults to an empty list.
        min_distance_config (List[float], optional): Configuration for minimum distances [min_edge_distance_config, up_edge_distances_config, total_distance].
        tolerance_len (float, optional): The tolerance length for adjusting edge distances. Defaults to 10.0.

    Returns:
        Tuple[float, List[float]]: A tuple containing:
            - The calculated distance considering IOU and adjustments.
            - The updated minimum distance configuration.
    """

    x1, y1, x2, y2 = input_bbox
    x1_prime, y1_prime, x2_prime, y2_prime = match_bbox

    min_edge_distance_config, up_edge_distances_config, total_distance = (
        min_distance_config
    )

    iou_distance = 0

    if label in vision_labels:
        horizontal1 = horizontal2 = True
    else:
        horizontal1 = _get_bbox_direction(input_bbox)
        horizontal2 = _get_bbox_direction(match_bbox, 3)

    if (
        horizontal1 != horizontal2
        or _get_projection_iou(input_bbox, match_bbox, horizontal1) < 0.01
    ):
        iou_distance = 1

    if label == "doc_title":
        # Calculate distance for titles
        disperse = max(1, median_width)
        tolerance_len = max(tolerance_len, disperse)

    # Adjust input_bbox based on sub_title
    if sub_title:
        for sub in sub_title:
            x1_, y1_, x2_, y2_ = sub
            x1, y1, x2, y2 = (
                min(x1, x1_),
                min(y1, y1_),
                min(x2, x2_),
                max(y2, y2_),
            )
        input_bbox = [x1, y1, x2, y2]

    if title_text:
        for sub in title_text:
            x1_, y1_, x2_, y2_ = sub[1]
            if horizontal1:
                x1, y1, x2, y2 = (
                    min(x1, x1_),
                    min(y1, y1_),
                    min(x2, x2_),
                    max(y2, y2_),
                )
            else:
                x1, y1, x2, y2 = (
                    min(x1, x1_),
                    min(y1, y1_),
                    max(x2, x2_),
                    min(y2, y2_),
                )
        input_bbox = [x1, y1, x2, y2]

    # Calculate edge distance
    weight = _get_weights(label, horizontal1)
    # static weight
    # weight = [1.,1.,1.,1.]
    if label == "abstract":
        tolerance_len *= 2

    edge_distance, edge_distance_config = _nearest_edge_distance(
        input_bbox,
        match_bbox,
        weight,
        label=label,
        no_mask_labels=no_mask_labels,
        min_edge_distance_config=min_edge_distance_config,
        tolerance_len=tolerance_len,
    )

    # Weights for combining distances
    iou_edge_weight = [10**8, 10**4, 1, 0.0001]
    # static weight
    # iou_edge_weight = [1**6,1**3,1.,1**-3]

    # Calculate up and left edge distances
    up_edge_distance = y1_prime
    left_edge_distance = x1_prime
    if (
        label in no_mask_labels or label in title_labels or label in vision_labels
    ) and y1 > y2_prime:
        up_edge_distance = -y2_prime
        left_edge_distance = -x2_prime

    min_up_edge_distance = up_edge_distances_config
    if abs(min_up_edge_distance - up_edge_distance) <= tolerance_len:
        up_edge_distance = min_up_edge_distance

    # Calculate total distance
    distance = (
        iou_distance * iou_edge_weight[0]
        + edge_distance * iou_edge_weight[1]
        + up_edge_distance * iou_edge_weight[2]
        + left_edge_distance * iou_edge_weight[3]
    )
    # distance = iou_distance
    # distance = edge_distance
    # distance =  up_edge_distance
    # distance =  left_edge_distance

    # Update minimum distance configuration if a smaller distance is found
    if total_distance > distance:
        edge_distance_config = [
            edge_distance_config[0],
            edge_distance_config[1],
        ]
        min_distance_config = [
            edge_distance_config,
            up_edge_distance,
            distance,
        ]

    return distance, min_distance_config