#                🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
#           This file was automatically generated from src/transformers/models/muse_glimmer/modular_muse_glimmer.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_muse_glimmer.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 itertools
import math

import torch
from torchvision.transforms.v2 import functional as tvF

from ...image_processing_utils import BatchFeature
from ...image_utils import PILImageResampling, SizeDict
from ...processing_utils import Unpack, VideosKwargs
from ...utils import TensorType, auto_docstring, logging
from ...utils.constants import IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD
from ...video_processing_utils import BaseVideoProcessor
from ...video_utils import VideoMetadata, group_videos_by_shape, reorder_videos


logger = logging.get_logger(__name__)


class MuseGlimmerVideoProcessorInitKwargs(VideosKwargs, total=False):
    """
    patch_size (`int`, *optional*):
        The spatial patch size of the vision encoder, in pixels.
    temporal_patch_size (`int`, *optional*):
        The temporal patch size of the vision encoder, in frames.
    max_video_frame_tokens (`int`, *optional*):
        Maximum number of vision tokens per video frame; frames are resized to stay under this cap.
    merge_size (`int`, *optional*):
        Factor by which the patch grid is downsampled by pixel shuffling after the vision encoder.
    """

    patch_size: int
    temporal_patch_size: int
    max_video_frame_tokens: int
    merge_size: int


def smart_resize(
    height: int,
    width: int,
    patch_size: int,
    max_tokens: int,
) -> tuple[int, int]:
    """Pick the integer patch grid closest to the input aspect ratio under the token cap.

    Returns the resize target ``(target_height, target_width)`` in pixels.
    """
    ideal_patches_height = height / patch_size
    ideal_patches_width = width / patch_size
    ratio = ideal_patches_width / ideal_patches_height if ideal_patches_height > 0 else 1.0
    if ideal_patches_height * ideal_patches_width > max_tokens:
        ideal_patches_height = (max_tokens / ratio) ** 0.5
        ideal_patches_width = ideal_patches_height * ratio
    candidates = list(
        set(
            itertools.product(
                [math.floor(ideal_patches_height), math.ceil(ideal_patches_height)],
                [math.floor(ideal_patches_width), math.ceil(ideal_patches_width)],
            )
        )
    )
    candidates = [
        (patches_height, patches_width)
        for patches_height, patches_width in candidates
        if patches_height >= 1 and patches_width >= 1 and patches_height * patches_width <= max_tokens
    ]
    if not candidates:
        candidates = [(max(1, round(ideal_patches_height)), max(1, round(ideal_patches_width)))]
    patches_height, patches_width = min(candidates, key=lambda grid: abs(grid[0] / grid[1] - height / width))
    return patches_height * patch_size, patches_width * patch_size


@auto_docstring
class MuseGlimmerVideoProcessor(BaseVideoProcessor):
    resample = PILImageResampling.LANCZOS
    image_mean = IMAGENET_STANDARD_MEAN
    image_std = IMAGENET_STANDARD_STD
    default_to_square = True
    do_convert_rgb = True
    do_resize = True
    do_rescale = True
    do_normalize = True
    patch_size = 14
    temporal_patch_size = 2
    merge_size = 2
    max_video_frame_tokens = 144
    num_frames = 96
    fps = 2.0
    do_sample_frames = True

    valid_kwargs = MuseGlimmerVideoProcessorInitKwargs
    model_input_names = ["pixel_values_videos", "video_grid_thw"]

    def __init__(self, **kwargs: Unpack[MuseGlimmerVideoProcessorInitKwargs]):
        super().__init__(**kwargs)

    def _validate_preprocess_kwargs(self, **kwargs):
        # MuseGlimmer uses aspect_ratio_preserving_resize driven by patch_size,
        # not the standard `size` parameter. Temporarily disable do_resize so
        # the base validation doesn't raise an error
        kwargs["do_resize"] = False
        super()._validate_preprocess_kwargs(**kwargs)

    def resize(
        self,
        videos: torch.Tensor,
        resample: PILImageResampling | tvF.InterpolationMode | int | None,
        patch_size: int,
        merge_size: int,
        max_tokens: int,
        **kwargs,
    ) -> torch.Tensor:
        """Resize dynamically based on input video aspect ratio."""
        height, width = videos.shape[-2:]
        resized_height, resized_width = smart_resize(
            height=height,
            width=width,
            patch_size=patch_size * merge_size,
            max_tokens=max_tokens,
        )

        return super().resize(
            videos,
            size=SizeDict(height=resized_height, width=resized_width),
            resample=resample,
            antialias=True,
        )

    def patchify(
        self,
        videos: torch.Tensor,
        patch_size: int,
        temporal_patch_size: int,
    ) -> tuple[torch.Tensor, int, int]:
        "Patchifies each video into flat layout of shape (`seq_len`, `patch_dim`) so we can concat dynamically shaped pixels."
        batch_size, num_frames, channel, resized_height, resized_width = videos.shape

        # Check that videos have `num_frames` divisible by `temporal_patch_size`
        if pad := -num_frames % temporal_patch_size:
            repeats = videos[:, -1:].expand(-1, pad, -1, -1, -1)
            videos = torch.cat((videos, repeats), dim=1)
            num_frames += pad

        grid_t = num_frames // temporal_patch_size
        grid_h, grid_w = resized_height // patch_size, resized_width // patch_size

        patches = videos.view(
            batch_size,
            grid_t,
            temporal_patch_size,
            channel,
            grid_h,
            patch_size,
            grid_w,
            patch_size,
        )
        # Unlike Glm4v, each flattened patch is laid out (temporal, channel), not (channel, temporal).
        patches = patches.permute(0, 1, 4, 6, 2, 3, 5, 7)
        flatten_patches = patches.reshape(
            batch_size,
            grid_t * grid_h * grid_w,
            temporal_patch_size * channel * patch_size * patch_size,
        )

        return flatten_patches, grid_t, grid_h, grid_w

    def sample_frames(
        self,
        metadata: VideoMetadata,
        temporal_patch_size: int | None = None,
        num_frames: int | None = None,
        fps: int | float | None = None,
        **kwargs,
    ):
        """
        Default sampling function which uniformly samples the desired number of frames between 0 and total number of frames.
        If `fps` is passed along with metadata, `fps` frames per second are sampled uniformty. Arguments `num_frames`
        and `fps` are mutually exclusive.

        Args:
            metadata (`VideoMetadata`):
                Metadata of the video containing information about total duration, fps and total number of frames.
            temporal_patch_size (`int`, *optional*):
                The temporal patch size of the vision encoder. Number of sampled frames will be rounded to be divisible by frame factor.
            num_frames (`int`, *optional*):
                Maximum number of frames to sample. Defaults to `self.num_frames`.
            fps (`int` or `float`, *optional*):
                Target frames to sample per second. Defaults to `self.fps`.

        Returns:
            np.ndarray:
                Indices to sample video frames.
        """
        if metadata.fps is None:
            logger.warning_once(
                "The `fps` of the input video could not be inferred. Defaulting to `fps=24`. "
                "Provide `video_metadata` for more accurate frame sampling."
            )
            metadata.fps = 24

        total_num_frames = metadata.total_num_frames
        num_frames = min(int(total_num_frames * fps / metadata.fps), num_frames, total_num_frames)
        num_frames = max(temporal_patch_size, (num_frames // temporal_patch_size) * temporal_patch_size)
        num_frames = min(num_frames, total_num_frames)
        indices = torch.linspace(0, total_num_frames - 1, num_frames).long()
        return indices

    def _preprocess(
        self,
        videos: list[torch.Tensor],
        do_resize: bool,
        do_convert_rgb: bool,
        resample: PILImageResampling | tvF.InterpolationMode | int | None,
        do_rescale: bool,
        rescale_factor: float,
        do_normalize: bool,
        image_mean: float | list[float] | None,
        image_std: float | list[float] | None,
        return_tensors: str | TensorType | None,
        patch_size: int,
        temporal_patch_size: int,
        max_video_frame_tokens: int,
        merge_size: int,
        disable_grouping: bool = False,
        **kwargs,
    ) -> BatchFeature:
        # Group videos by size for batched resizing
        grouped_videos, grouped_videos_index = group_videos_by_shape(videos)
        resized_videos_grouped = {}
        for shape, stacked_videos in grouped_videos.items():
            if do_convert_rgb:
                stacked_videos = self.convert_to_rgb(stacked_videos)
            if do_resize:
                stacked_videos = self.resize(
                    stacked_videos,
                    patch_size=patch_size,
                    merge_size=merge_size,
                    max_tokens=max_video_frame_tokens,
                    resample=resample,
                )
            resized_videos_grouped[shape] = stacked_videos
        resized_videos = reorder_videos(resized_videos_grouped, grouped_videos_index)

        # Group videos by size for further processing
        # Needed in case do_resize is False, or resize returns videos with different sizes
        grouped_videos, grouped_videos_index = group_videos_by_shape(resized_videos)
        processed_videos_grouped = {}
        processed_grids = {}
        for shape, stacked_videos in grouped_videos.items():
            # Fused rescale and normalize
            stacked_videos = self.rescale_and_normalize(
                stacked_videos, do_rescale, rescale_factor, do_normalize, image_mean, image_std
            )
            patches, grid_t, grid_h, grid_w = self.patchify(
                stacked_videos,
                patch_size=patch_size,
                temporal_patch_size=temporal_patch_size,
            )

            processed_videos_grouped[shape] = patches
            processed_grids[shape] = [[grid_t, grid_h, grid_w]] * len(stacked_videos)

        processed_videos = reorder_videos(processed_videos_grouped, grouped_videos_index)
        processed_grids = reorder_videos(processed_grids, grouped_videos_index)
        pixel_values_videos = torch.cat(processed_videos, dim=0)
        video_grid_thw = torch.tensor(processed_grids)

        return BatchFeature(
            data={"pixel_values_videos": pixel_values_videos, "video_grid_thw": video_grid_thw},
            tensor_type=return_tensors,
        )


__all__ = ["MuseGlimmerVideoProcessor"]
