#                🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
#           This file was automatically generated from src/transformers/models/glm_image/modular_glm_image.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_glm_image.py file directly. One of our CI enforces this.
#                🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
# Copyright 2025 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 torch

from ...feature_extraction_utils import BatchFeature
from ...image_utils import ImageInput
from ...processing_utils import ImagesKwargs, ProcessingKwargs, ProcessorMixin, Unpack
from ...tokenization_utils_base import PreTokenizedInput, TextInput
from ...utils.import_utils import requires


class GlmImageImagesKwargs(ImagesKwargs, total=False):
    """
    target_h (`int`):
        Height of the target image to be generated.
    target_w (`int`):
        Width of the target image to be generated.
    """

    target_h: int
    target_w: int


class GlmImageProcessorKwargs(ProcessingKwargs, total=False):
    _defaults = {
        "text_kwargs": {
            "padding": False,
            "return_mm_token_type_ids": False,
        },
        "images_kwargs": {
            "target_h": 1152,
            "target_w": 768,
        },
    }
    images_kwargs: GlmImageImagesKwargs


@requires(backends=("torch",))
class GlmImageProcessor(ProcessorMixin):
    r"""
    Constructs a GLM-Image processor which wraps a GLM-Image image processor and a GLM-Image tokenizer into a single processor.
    [`~GlmImageProcessor.__call__`] and [`~GlmImageProcessor.decode`] for more information.
    Args:
        image_processor ([`GlmImageProcessor`], *optional*):
            The image processor is a required input.
        tokenizer ([`PreTrainedTokenizerFast`], *optional*):
            The tokenizer is a required input.
        chat_template (`str`, *optional*): A Jinja template which will be used to convert lists of messages
            in a chat into a tokenizable string.
    """

    valid_processor_kwargs = GlmImageProcessorKwargs
    model_input_names = ["input_ids", "attention_mask", "pixel_values", "image_grid_thw", "images_per_sample"]

    def __init__(self, image_processor=None, tokenizer=None, chat_template=None, **kwargs):
        self.image_token = tokenizer.image_token
        self.grid_bos_token = tokenizer.grid_bos_token
        self.grid_eos_token = tokenizer.grid_eos_token
        self.bos_token = tokenizer.bos_token
        self.image_token_id = tokenizer.convert_tokens_to_ids(self.image_token)
        super().__init__(image_processor, tokenizer, chat_template=chat_template)

    def __call__(
        self,
        images: ImageInput | None = None,
        text: TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] = None,
        **kwargs: Unpack[GlmImageProcessorKwargs],
    ) -> BatchFeature:
        """
        Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text`
        and `kwargs` arguments to PreTrainedTokenizerFast's [`~PreTrainedTokenizerFast.__call__`] if `text` is not `None` to encode
        the text.

        Args:
            images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `List[PIL.Image.Image]`, `List[np.ndarray]`, `List[torch.Tensor]`):
                The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
                tensor. Both channels-first and channels-last formats are supported.
            text (`str`, `List[str]`, `List[List[str]]`):
                The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
                (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
                `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
            return_tensors (`str` or [`~utils.TensorType`], *optional*):
                If set, will return tensors of a particular framework. Acceptable values are:
                - `'pt'`: Return PyTorch `torch.Tensor` objects.
                - `'np'`: Return NumPy `np.ndarray` objects.

        Returns:
            [`BatchFeature`]: A [`BatchFeature`] with the following fields:

            - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
            - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
              `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
              `None`).
            - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
            - **image_grid_thw** -- List of image 3D grid in LLM. Returned when `images` is not `None`.
        """
        output_kwargs = self._merge_kwargs(
            GlmImageProcessorKwargs,
            tokenizer_init_kwargs=self.tokenizer.init_kwargs,
            **kwargs,
        )

        model_inputs = super().__call__(images=images, text=text, **output_kwargs)
        if text is None:  # early exit if cond only on text
            return model_inputs

        target_h = output_kwargs["images_kwargs"].get("target_h")
        target_w = output_kwargs["images_kwargs"].get("target_w")
        return_tensors = output_kwargs["text_kwargs"].get("return_tensors")
        is_text_to_image = images is None

        # Count images per sample by counting image tokens in each text
        batch_size = len(text) if not isinstance(text, str) else 1
        images_per_sample = []
        for i in range(batch_size):
            images_per_sample.append(text[i].count(self.image_token))

        # Build prompt with target shape and combine grids in a single loop
        # Format: [sample0_source_grids..., sample0_target_grids, sample1_source_grids..., sample1_target_grids, ...]
        # Note: In image2image mode, batches are homogeneous (same number of source images per sample)
        num_source_images = images_per_sample[0] if images_per_sample else 0

        all_grids = []
        for i in range(batch_size):
            token_h, token_w, prev_h, prev_w = self._get_target_shape(height=target_h, width=target_w)
            # Add source grids for this sample (i2i mode only)
            if not is_text_to_image and num_source_images > 0:
                start_idx = i * num_source_images
                all_grids.append(model_inputs["image_grid_thw"][start_idx : start_idx + num_source_images])
            # Add target grid for this sample
            all_grids.append(
                self._build_target_image_grid_thw(
                    token_h=token_h,
                    token_w=token_w,
                    prev_token_h=prev_h,
                    prev_token_w=prev_w,
                    is_text_to_image=is_text_to_image,
                )
            )
        model_inputs["image_grid_thw"] = torch.cat(all_grids, dim=0)

        # Store images_per_sample for later use (add target images count)
        # Each sample will have: source_images + target_images (typically 2 for t2i, 1 for i2i)
        num_target_grids = 2 if is_text_to_image else 1
        model_inputs["images_per_sample"] = torch.tensor(
            [num_source_images + num_target_grids] * batch_size, dtype=torch.long
        )
        return BatchFeature(data=model_inputs, tensor_type=return_tensors)

    def prepare_inputs_layout(
        self,
        images: ImageInput | None = None,
        text: TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] | None = None,
        **kwargs: Unpack[GlmImageImagesKwargs],
    ):
        images, text, *_ = super().prepare_inputs_layout(images=images, text=text, **kwargs)

        processed_text = text
        if text is not None:
            processed_text = []
            target_h = kwargs["images_kwargs"].get("target_h", None)
            target_w = kwargs["images_kwargs"].get("target_w", None)

            for sample in text:
                token_h, token_w, prev_token_h, prev_token_w = self._get_target_shape(height=target_h, width=target_w)
                if images is None:
                    sample = f"{sample}{self.grid_bos_token}{token_h} {token_w}{self.grid_eos_token}{self.grid_bos_token}{prev_token_h} {prev_token_w}{self.grid_eos_token}{self.bos_token}"
                else:
                    sample = f"{sample}{self.grid_bos_token}{token_h} {token_w}{self.grid_eos_token}{self.bos_token}"
                processed_text.append(sample)

        return images, processed_text, None, None

    def validate_inputs(
        self,
        images: ImageInput | None = None,
        text: TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] | None = None,
        **kwargs: Unpack[GlmImageImagesKwargs],
    ):
        super().validate_inputs(images=images, text=text)
        if text is None and images is None:
            raise ValueError("You must provide at least one of `text` or `images`.")

        # Validate homogeneity for i2i mode
        images_per_sample = []
        for i in range(len(text)):
            images_per_sample.append(text[i].count(self.image_token))

        if images is not None and images_per_sample and len(set(images_per_sample)) != 1:
            raise ValueError(
                f"In image-to-image mode, all samples must have the same number of source images. "
                f"Got different counts: {images_per_sample}"
            )

    def _process_images(self, images: ImageInput, **kwargs):
        # Kwargs used only in processor, if we pass them down to image processor it raises an error
        kwargs.pop("target_h", None)
        kwargs.pop("target_w", None)
        return super()._process_images(images, **kwargs)

    def replace_image_token(self, image_inputs: dict, image_idx: int, **kwargs) -> str:
        merge_length = self.image_processor.merge_size**2
        num_image_tokens = image_inputs["image_grid_thw"][image_idx].prod() // merge_length
        return self.image_token * num_image_tokens

    def _get_target_shape(
        self,
        height: int,
        width: int,
    ) -> tuple[str, int, int, int, int]:
        factor = 32
        height = (height // factor) * factor
        width = (width // factor) * factor
        token_h = height // factor
        token_w = width // factor
        ratio = token_h / token_w
        prev_token_h = int(math.sqrt(ratio) * (factor // 2))
        prev_token_w = int(math.sqrt(1 / ratio) * (factor // 2))
        return token_h, token_w, prev_token_h, prev_token_w

    @staticmethod
    def _build_target_image_grid_thw(
        token_h: int,
        token_w: int,
        prev_token_h: int,
        prev_token_w: int,
        is_text_to_image: bool = True,
    ):
        if is_text_to_image:
            # Text-to-image: 2 target grids (large + small preview)
            return torch.tensor(
                [
                    [1, token_h, token_w],
                    [1, prev_token_h, prev_token_w],
                ],
            )
        else:
            # Image-to-image: 1 target grid only
            return torch.tensor(
                [
                    [1, token_h, token_w],
                ],
            )


__all__ = ["GlmImageProcessor"]
