






"""simple docstring"""



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

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
    center_crop,
    get_resize_output_image_size,
    normalize,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    IMAGENET_STANDARD_MEAN,
    IMAGENET_STANDARD_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_torch_available, is_torch_tensor, logging


if is_torch_available():
 import torch


_lowerCAmelCase	:	int				=      logging.get_logger(__name__)




class 			lowerCAmelCase__			(    __magic_name__   ):
   SCREAMING_SNAKE_CASE_    =['''pixel_values''']
   def __init__(		self      :	List[str]							,			snake_case__      :	bool = True							,			snake_case__      :	Optional[Dict[str, int]] = None							,			snake_case__      :	PILImageResampling = PILImageResampling.BILINEAR							,			snake_case__      :	bool = True							,			snake_case__      :	Dict[str, int] = None							,			snake_case__      :	bool = True							,			snake_case__      :	Union[int, float] = 1 / 2_5_5							,			snake_case__      :	bool = True							,			snake_case__      :	Optional[Union[float, List[float]]] = None							,			snake_case__      :	Optional[Union[float, List[float]]] = None							,			**snake_case__      :	Any							,			):


        '''simple docstring'''
        super().__init__(**snake_case__							)
        UpperCAmelCase__						:    int							=							size if size is not None else {"shortest_edge": 2_5_6}
        UpperCAmelCase__						:    Optional[int]							=							get_size_dict(snake_case__							,			default_to_square=snake_case__							)
        UpperCAmelCase__						:    Any							=							crop_size if crop_size is not None else {"height": 2_2_4, "width": 2_2_4}
        UpperCAmelCase__						:    Any							=							get_size_dict(snake_case__							,			param_name="crop_size"							)
        UpperCAmelCase__						:    Tuple							=							do_resize
        UpperCAmelCase__						:    int							=							size
        UpperCAmelCase__						:    Optional[Any]							=							resample
        UpperCAmelCase__						:    Tuple							=							do_center_crop
        UpperCAmelCase__						:    int							=							crop_size
        UpperCAmelCase__						:    int							=							do_rescale
        UpperCAmelCase__						:    Tuple							=							rescale_factor
        UpperCAmelCase__						:    Tuple							=							do_normalize
        UpperCAmelCase__						:    Union[str, Any]							=							image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
        UpperCAmelCase__						:    Dict							=							image_std if image_std is not None else IMAGENET_STANDARD_STD
   def       __a							(		self      :	Tuple							,			snake_case__      :	np.ndarray							,			snake_case__      :	Dict[str, int]							,			snake_case__      :	PILImageResampling = PILImageResampling.BICUBIC							,			snake_case__      :	Optional[Union[str, ChannelDimension]] = None							,			**snake_case__      :	int							,			):


        '''simple docstring'''
        UpperCAmelCase__						:    Optional[int]							=							get_size_dict(snake_case__							,			default_to_square=snake_case__							)
        if "shortest_edge" not in size:
             raise ValueError(f'The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}'							)
        UpperCAmelCase__						:    Union[str, Any]							=							get_resize_output_image_size(snake_case__							,			size=size["shortest_edge"]							,			default_to_square=snake_case__							)
        return resize(snake_case__							,			size=snake_case__							,			resample=snake_case__							,			data_format=snake_case__							,			**snake_case__							)
   def       __a							(		self      :	str							,			snake_case__      :	np.ndarray							,			snake_case__      :	Dict[str, int]							,			snake_case__      :	Optional[Union[str, ChannelDimension]] = None							,			**snake_case__      :	List[Any]							,			):


        '''simple docstring'''
        UpperCAmelCase__						:    str							=							get_size_dict(snake_case__							)
        if "height" not in size or "width" not in size:
             raise ValueError(f'The `size` parameter must contain the keys `height` and `width`. Got {size.keys()}'							)
        return center_crop(snake_case__							,			size=(size["height"], size["width"])							,			data_format=snake_case__							,			**snake_case__							)
   def       __a							(		self      :	Optional[Any]							,			snake_case__      :	np.ndarray							,			snake_case__      :	float							,			snake_case__      :	Optional[Union[str, ChannelDimension]] = None							,			**snake_case__      :	Tuple							):


        '''simple docstring'''
        return rescale(snake_case__							,			scale=snake_case__							,			data_format=snake_case__							,			**snake_case__							)
   def       __a							(		self      :	str							,			snake_case__      :	np.ndarray							,			snake_case__      :	Union[float, List[float]]							,			snake_case__      :	Union[float, List[float]]							,			snake_case__      :	Optional[Union[str, ChannelDimension]] = None							,			**snake_case__      :	Optional[Any]							,			):


        '''simple docstring'''
        return normalize(snake_case__							,			mean=snake_case__							,			std=snake_case__							,			data_format=snake_case__							,			**snake_case__							)
   def       __a							(		self      :	Dict							,			snake_case__      :	ImageInput							,			snake_case__      :	Optional[bool] = None							,			snake_case__      :	Dict[str, int] = None							,			snake_case__      :	PILImageResampling = None							,			snake_case__      :	bool = None							,			snake_case__      :	Dict[str, int] = None							,			snake_case__      :	Optional[bool] = None							,			snake_case__      :	Optional[float] = None							,			snake_case__      :	Optional[bool] = None							,			snake_case__      :	Optional[Union[float, List[float]]] = None							,			snake_case__      :	Optional[Union[float, List[float]]] = None							,			snake_case__      :	Optional[Union[str, TensorType]] = None							,			snake_case__      :	Union[str, ChannelDimension] = ChannelDimension.FIRST							,			**snake_case__      :	Optional[int]							,			):


        '''simple docstring'''
        UpperCAmelCase__						:    Union[str, Any]							=							do_resize if do_resize is not None else self.do_resize
        UpperCAmelCase__						:    Any							=							size if size is not None else self.size
        UpperCAmelCase__						:    Optional[int]							=							get_size_dict(snake_case__							,			default_to_square=snake_case__							)
        UpperCAmelCase__						:    int							=							resample if resample is not None else self.resample
        UpperCAmelCase__						:    List[str]							=							do_center_crop if do_center_crop is not None else self.do_center_crop
        UpperCAmelCase__						:    str							=							crop_size if crop_size is not None else self.crop_size
        UpperCAmelCase__						:    Dict							=							get_size_dict(snake_case__							,			param_name="crop_size"							)
        UpperCAmelCase__						:    Optional[Any]							=							do_rescale if do_rescale is not None else self.do_rescale
        UpperCAmelCase__						:    List[Any]							=							rescale_factor if rescale_factor is not None else self.rescale_factor
        UpperCAmelCase__						:    int							=							do_normalize if do_normalize is not None else self.do_normalize
        UpperCAmelCase__						:    int							=							image_mean if image_mean is not None else self.image_mean
        UpperCAmelCase__						:    Tuple							=							image_std if image_std is not None else self.image_std

        UpperCAmelCase__						:    Optional[int]							=							make_list_of_images(snake_case__							)

        if not valid_images(snake_case__							):
             raise ValueError(
                 "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
                 "torch.Tensor, tf.Tensor or jax.ndarray."							)

        if do_resize and size is None:
             raise ValueError("Size must be specified if do_resize is True."							)

        if do_center_crop and crop_size is None:
             raise ValueError("Crop size must be specified if do_center_crop is True."							)

        if do_rescale and rescale_factor is None:
             raise ValueError("Rescale factor must be specified if do_rescale is True."							)

        if do_normalize and (image_mean is None or image_std is None):
             raise ValueError("Image mean and std must be specified if do_normalize is True."							)

        # All transformations expect numpy arrays.
        UpperCAmelCase__						:    List[str]							=							[to_numpy_array(snake_case__							) for image in images]

        if do_resize:
             UpperCAmelCase__						:    Any							=							[self.resize(image=snake_case__							,			size=snake_case__							,			resample=snake_case__							) for image in images]

        if do_center_crop:
             UpperCAmelCase__						:    Optional[int]							=							[self.center_crop(image=snake_case__							,			size=snake_case__							) for image in images]

        if do_rescale:
             UpperCAmelCase__						:    Dict							=							[self.rescale(image=snake_case__							,			scale=snake_case__							) for image in images]

        if do_normalize:
             UpperCAmelCase__						:    Any							=							[self.normalize(image=snake_case__							,			mean=snake_case__							,			std=snake_case__							) for image in images]

        UpperCAmelCase__						:    int							=							[to_channel_dimension_format(snake_case__							,			snake_case__							) for image in images]

        UpperCAmelCase__						:    List[Any]							=							{"pixel_values": images}
        return BatchFeature(data=snake_case__							,			tensor_type=snake_case__							)




   def       __a							(		self      :	List[Any]							,			snake_case__      :	List[Any]							,			snake_case__      :	List[Tuple] = None							):


        '''simple docstring'''
        UpperCAmelCase__						:    Dict							=							outputs.logits

        # Resize logits and compute semantic segmentation maps
        if target_sizes is not None:
             if len(snake_case__							) != len(snake_case__							):
                  raise ValueError(
                      "Make sure that you pass in as many target sizes as the batch dimension of the logits"							)

             if is_torch_tensor(snake_case__							):
                  UpperCAmelCase__						:    Optional[int]							=							target_sizes.numpy()

             UpperCAmelCase__						:    Union[str, Any]							=							[]

             for idx in range(len(snake_case__							)							):
                  UpperCAmelCase__						:    Dict							=							torch.nn.functional.interpolate(
                      logits[idx].unsqueeze(dim=0							)							,			size=target_sizes[idx]							,			mode="bilinear"							,			align_corners=snake_case__							)
                  UpperCAmelCase__						:    List[Any]							=							resized_logits[0].argmax(dim=0							)
                  semantic_segmentation.append(snake_case__							)
        else:
             UpperCAmelCase__						:    Any							=							logits.argmax(dim=1							)
             UpperCAmelCase__						:    List[Any]							=							[semantic_segmentation[i] for i in range(semantic_segmentation.shape[0]							)]

        return semantic_segmentation










"""simple docstring"""



import unittest

from transformers import is_flax_available
from transformers.testing_utils import require_flax, require_sentencepiece, require_tokenizers, require_torch, slow


if is_flax_available():
 import optax
 from flax.training.common_utils import onehot

 from transformers import AutoTokenizer, FlaxMTaForConditionalGeneration
 from transformers.models.ta.modeling_flax_ta import shift_tokens_right




@require_torch
@require_sentencepiece
@require_tokenizers
@require_flax
class 			lowerCAmelCase__			(    unittest.TestCase   ):
   @slow
   def       __a							(		self      :	List[str]							):


        '''simple docstring'''
        UpperCAmelCase__						:    Union[str, Any]							=							FlaxMTaForConditionalGeneration.from_pretrained("google/mt5-small"							)
        UpperCAmelCase__						:    str							=							AutoTokenizer.from_pretrained("google/mt5-small"							)

        UpperCAmelCase__						:    str							=							tokenizer("Hello there"							,			return_tensors="np"							).input_ids
        UpperCAmelCase__						:    Optional[Any]							=							tokenizer("Hi I am"							,			return_tensors="np"							).input_ids

        UpperCAmelCase__						:    Any							=							shift_tokens_right(snake_case__							,			model.config.pad_token_id							,			model.config.decoder_start_token_id							)

        UpperCAmelCase__						:    Any							=							model(snake_case__							,			decoder_input_ids=snake_case__							).logits
        UpperCAmelCase__						:    Any							=							optax.softmax_cross_entropy(snake_case__							,			onehot(snake_case__							,			logits.shape[-1]							)							).mean()

        UpperCAmelCase__						:    List[str]							=							-(labels.shape[-1] * loss.item())

        UpperCAmelCase__						:    Dict							=							-84.9127
        self.assertTrue(abs(mtf_score - EXPECTED_SCORE							) < 1e-4							)


