#                🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
#           This file was automatically generated from src/transformers/models/unlimited_ocr/modular_unlimited_ocr.py.
#               Do NOT edit this file manually as any edits will be overwritten by the generation of
#             the file from the modular. If any change should be done, please apply the change to the
#                          modular_unlimited_ocr.py file directly. One of our CI enforces this.
#                🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
# Copyright 2026 the HuggingFace Team. 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.
import math
import re

from ...image_utils import make_flat_list_of_images
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import TextInput
from ...utils import auto_docstring


@auto_docstring
class UnlimitedOcrProcessor(ProcessorMixin):
    skip_tensor_conversion = ["video_metadata", "text_replacement_offsets", "num_local_patches", "patches_grid"]

    def __init__(
        self,
        image_processor=None,
        tokenizer=None,
        chat_template=None,
        patch_size=16,
        downsample_ratio=4,
        **kwargs,
    ):
        r"""
        patch_size (`int`, *optional*, defaults to `16`):
            The patch size used by the vision encoder (SAM ViT patch embedding size).
        downsample_ratio (`int`, *optional*, defaults to `4`):
            The downsampling ratio applied after the vision encoder.
        """
        self.image_token = "<image>" if not hasattr(tokenizer, "image_token") else tokenizer.image_token
        self.patch_size = patch_size
        self.downsample_ratio = downsample_ratio
        self.image_token_id = tokenizer.convert_tokens_to_ids(self.image_token)
        super().__init__(image_processor, tokenizer, chat_template=chat_template, **kwargs)
        self.detections_pattern = re.compile(
            r"<\|det\|>(\S+) \[(\d+), (\d+), (\d+), (\d+)\]<\|/det\|>(.*?)(?=<\|det\|>|<PAGE>|\Z)",
            flags=re.DOTALL,
        )

    def prepare_inputs_layout(self, images=None, text=None, videos=None, audio=None, **kwargs):
        images, text, videos, audio = super().prepare_inputs_layout(
            images=images, text=text, videos=videos, audio=audio, **kwargs
        )
        if images is not None:
            images = make_flat_list_of_images(images)
        return images, text, videos, audio

    def validate_inputs(self, images=None, text=None, videos=None, audio=None, **kwargs):
        super().validate_inputs(images=images, text=text, videos=videos, audio=audio, **kwargs)
        if text is None:
            raise ValueError("You have to specify text.")

    def replace_image_token(self, image_inputs: dict, image_idx: int, **kwargs) -> TextInput:
        image_size = kwargs.get("size") or self.image_processor.size
        tile_size = kwargs.get("tile_size") or self.image_processor.tile_size
        size = max(image_size["height"], image_size["width"])

        num_queries_global = math.ceil(size // self.patch_size / self.downsample_ratio)
        num_queries_local = math.ceil(tile_size // self.patch_size / self.downsample_ratio)

        num_columns, num_rows = image_inputs["patches_grid"][image_idx]
        num_tokens = num_queries_global * (num_queries_global + 1) + 1
        if image_inputs["num_local_patches"][image_idx] > 0:
            num_tokens += (num_rows * num_queries_local) * (num_columns * num_queries_local + 1)
        return self.image_token * num_tokens

    def batch_decode(self, *args, return_detections: bool = False, **kwargs):
        """
        This method forwards all its arguments to PreTrainedTokenizer's [`~PreTrainedTokenizer.batch_decode`]. Please refer to
        the docstring of this method for more information.

        Args:
            return_detections (`bool`, *optional*, defaults to `False`):
                Whether or not to also return the layout detections parsed from the decoded text.

        Returns:
            `list[str]` or `tuple[list[str], list[list[dict]]]`: The decoded text. If `return_detections` is `True`,
            a tuple of the decoded text and the detections of every sequence, where every detection is a dictionary
            with the keys `region_type`, `box` and `text`. Boxes are in [x1, y1, x2, y2] format with coordinates
            normalized to [0, 999].
        """
        decoded = super().batch_decode(*args, **kwargs)
        if return_detections:
            detections = [self._parse_detections(text) for text in decoded]
            return decoded, detections
        return decoded

    def decode(self, *args, return_detections: bool = False, **kwargs):
        """
        This method forwards all its arguments to PreTrainedTokenizer's [`~PreTrainedTokenizer.decode`]. Please refer to
        the docstring of this method for more information.

        Args:
            return_detections (`bool`, *optional*, defaults to `False`):
                Whether or not to also return the layout detections parsed from the decoded text.

        Returns:
            `str` or `tuple[str, list[dict]]`: The decoded text. If `return_detections` is `True`, a tuple of the
            decoded text and a list of detections, where every detection is a dictionary with the keys `region_type`,
            `box` and `text`. Boxes are in [x1, y1, x2, y2] format with coordinates normalized to [0, 999].
        """
        decoded = super().decode(*args, **kwargs)
        if return_detections:
            detections = self._parse_detections(decoded)
            return decoded, detections
        return decoded

    def _parse_detections(self, decoded: str) -> list[dict]:
        matches = self.detections_pattern.findall(decoded)
        detections = []
        for region_type, x1, y1, x2, y2, text in matches:
            detections.append(
                {
                    "region_type": region_type,
                    "box": [int(x1), int(y1), int(x2), int(y2)],
                    "text": text,
                }
            )
        return detections


__all__ = ["UnlimitedOcrProcessor"]
