

"""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


_a       =							logging.get_logger(__name__)




class 					_lowerCAmelCase  (	lowercase   ):







 """simple docstring"""







 __UpperCAmelCase	:					Tuple   		=	["pixel_values"]


 def __init__(			self							:			Optional[int],					UpperCAmelCase__							:			bool = True,					UpperCAmelCase__							:			Optional[Dict[str, int]] = None,					UpperCAmelCase__							:			PILImageResampling = PILImageResampling.BILINEAR,					UpperCAmelCase__							:			bool = True,					UpperCAmelCase__							:			Dict[str, int] = None,					UpperCAmelCase__							:			bool = True,					UpperCAmelCase__							:			Union[int, float] = 1 / 2_5_5,					UpperCAmelCase__							:			bool = True,					UpperCAmelCase__							:			Optional[Union[float, List[float]]] = None,					UpperCAmelCase__							:			Optional[Union[float, List[float]]] = None,					**UpperCAmelCase__							:			Any,					):
    super().__init__(**UpperCAmelCase__	)
    __lowercase								=						size if size is not None else {"shortest_edge": 2_5_6}
    __lowercase								=						get_size_dict(UpperCAmelCase__,					default_to_square=UpperCAmelCase__	)
    __lowercase								=						crop_size if crop_size is not None else {"height": 2_2_4, "width": 2_2_4}
    __lowercase								=						get_size_dict(UpperCAmelCase__,					param_name="crop_size"	)
    __lowercase								=						do_resize
    __lowercase								=						size
    __lowercase								=						resample
    __lowercase								=						do_center_crop
    __lowercase								=						crop_size
    __lowercase								=						do_rescale
    __lowercase								=						rescale_factor
    __lowercase								=						do_normalize
    __lowercase								=						image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
    __lowercase								=						image_std if image_std is not None else IMAGENET_STANDARD_STD


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


 def 					_lowercase (			self							:			Optional[int],					UpperCAmelCase__							:			np.ndarray,					UpperCAmelCase__							:			Dict[str, int],					UpperCAmelCase__							:			Optional[Union[str, ChannelDimension]] = None,					**UpperCAmelCase__							:			Optional[int],					):
    __lowercase								=						get_size_dict(UpperCAmelCase__	)
    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(UpperCAmelCase__,					size=(size["height"], size["width"]),					data_format=UpperCAmelCase__,					**UpperCAmelCase__	)


 def 					_lowercase (			self							:			str,					UpperCAmelCase__							:			np.ndarray,					UpperCAmelCase__							:			float,					UpperCAmelCase__							:			Optional[Union[str, ChannelDimension]] = None,					**UpperCAmelCase__							:			Union[str, Any]	):
    return rescale(UpperCAmelCase__,					scale=UpperCAmelCase__,					data_format=UpperCAmelCase__,					**UpperCAmelCase__	)


 def 					_lowercase (			self							:			List[str],					UpperCAmelCase__							:			np.ndarray,					UpperCAmelCase__							:			Union[float, List[float]],					UpperCAmelCase__							:			Union[float, List[float]],					UpperCAmelCase__							:			Optional[Union[str, ChannelDimension]] = None,					**UpperCAmelCase__							:			Tuple,					):
    return normalize(UpperCAmelCase__,					mean=UpperCAmelCase__,					std=UpperCAmelCase__,					data_format=UpperCAmelCase__,					**UpperCAmelCase__	)


 def 					_lowercase (			self							:			Dict,					UpperCAmelCase__							:			ImageInput,					UpperCAmelCase__							:			Optional[bool] = None,					UpperCAmelCase__							:			Dict[str, int] = None,					UpperCAmelCase__							:			PILImageResampling = None,					UpperCAmelCase__							:			bool = None,					UpperCAmelCase__							:			Dict[str, int] = None,					UpperCAmelCase__							:			Optional[bool] = None,					UpperCAmelCase__							:			Optional[float] = None,					UpperCAmelCase__							:			Optional[bool] = None,					UpperCAmelCase__							:			Optional[Union[float, List[float]]] = None,					UpperCAmelCase__							:			Optional[Union[float, List[float]]] = None,					UpperCAmelCase__							:			Optional[Union[str, TensorType]] = None,					UpperCAmelCase__							:			Union[str, ChannelDimension] = ChannelDimension.FIRST,					**UpperCAmelCase__							:			Optional[Any],					):
    __lowercase								=						do_resize if do_resize is not None else self.do_resize
    __lowercase								=						size if size is not None else self.size
    __lowercase								=						get_size_dict(UpperCAmelCase__,					default_to_square=UpperCAmelCase__	)
    __lowercase								=						resample if resample is not None else self.resample
    __lowercase								=						do_center_crop if do_center_crop is not None else self.do_center_crop
    __lowercase								=						crop_size if crop_size is not None else self.crop_size
    __lowercase								=						get_size_dict(UpperCAmelCase__,					param_name="crop_size"	)
    __lowercase								=						do_rescale if do_rescale is not None else self.do_rescale
    __lowercase								=						rescale_factor if rescale_factor is not None else self.rescale_factor
    __lowercase								=						do_normalize if do_normalize is not None else self.do_normalize
    __lowercase								=						image_mean if image_mean is not None else self.image_mean
    __lowercase								=						image_std if image_std is not None else self.image_std

    __lowercase								=						make_list_of_images(UpperCAmelCase__	)

    if not valid_images(UpperCAmelCase__	):
       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.
    __lowercase								=						[to_numpy_array(UpperCAmelCase__	) for image in images]

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

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

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

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

    __lowercase								=						[to_channel_dimension_format(UpperCAmelCase__,					UpperCAmelCase__	) for image in images]

    __lowercase								=						{"pixel_values": images}
    return BatchFeature(data=UpperCAmelCase__,					tensor_type=UpperCAmelCase__	)



 def 					_lowercase (			self							:			Optional[Any],					UpperCAmelCase__							:			Tuple,					UpperCAmelCase__							:			List[Tuple] = None	):
    __lowercase								=						outputs.logits

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

       if is_torch_tensor(UpperCAmelCase__	):
          __lowercase								=						target_sizes.numpy()

       __lowercase								=						[]

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

    return semantic_segmentation







"""simple docstring"""





import time
from contextlib import contextmanager
from pathlib import Path

import pytest
import requests
from huggingface_hub.hf_api import HfApi, HfFolder


_a       =							'__DUMMY_TRANSFORMERS_USER__'
_a       =							'Dummy User'
_a       =							'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'

_a       =							'https://hub-ci.huggingface.co'
_a       =							CI_HUB_ENDPOINT + '/datasets/{repo_id}/resolve/{revision}/{path}'
_a       =							CI_HUB_ENDPOINT + '/{repo_id}/resolve/{revision}/{filename}'
_a       =							Path('~/.huggingface/hub_ci_token').expanduser()




@pytest.fixture
def   _A  (  UpperCamelCase_     :       List[Any])	->						Tuple:
   '''simple docstring'''


   monkeypatch.setattr(
       "huggingface_hub.file_download.HUGGINGFACE_CO_URL_TEMPLATE",			UpperCamelCase_)




@pytest.fixture
def   _A  (  UpperCamelCase_     :       int)	->						List[Any]:
   '''simple docstring'''


   monkeypatch.setattr("datasets.config.HF_ENDPOINT",			UpperCamelCase_)
   monkeypatch.setattr("datasets.config.HUB_DATASETS_URL",			UpperCamelCase_)




@pytest.fixture
def   _A  (  UpperCamelCase_     :       str)	->						Dict:
   '''simple docstring'''


   monkeypatch.setattr("huggingface_hub.hf_api.HfFolder.path_token",			UpperCamelCase_)




@pytest.fixture
def   _A  (  UpperCamelCase_     :       Optional[Any],			UpperCamelCase_     :       List[Any])	->						List[str]:
   '''simple docstring'''


   HfFolder.save_token(UpperCamelCase_)
   yield
   HfFolder.delete_token()




@pytest.fixture(scope="session")
def   _A  (  )	->						List[Any]:
   '''simple docstring'''


   return HfApi(endpoint=UpperCamelCase_)




@pytest.fixture(scope="session")
def   _A  (  UpperCamelCase_     :       HfApi)	->						List[Any]:
   '''simple docstring'''


   __lowercase								=						HfFolder.get_token()
   HfFolder.save_token(UpperCamelCase_)
   yield CI_HUB_USER_TOKEN
   if previous_token is not None:
      HfFolder.save_token(UpperCamelCase_)




@pytest.fixture
def   _A  (  UpperCamelCase_     :       Dict)	->						int:
   '''simple docstring'''


   def _cleanup_repo(UpperCamelCase_     :       Optional[int]):
      hf_api.delete_repo(UpperCamelCase_,			token=UpperCamelCase_,			repo_type="dataset")

   return _cleanup_repo




@pytest.fixture
def   _A  (  UpperCamelCase_     :       str)	->						Any:
   '''simple docstring'''


   @contextmanager
   def _temporary_repo(UpperCamelCase_     :       Any):
      try:
         yield repo_id
      finally:
         cleanup_repo(UpperCamelCase_)

   return _temporary_repo




@pytest.fixture(scope="session")
def   _A  (  UpperCamelCase_     :       HfApi,			UpperCamelCase_     :       str,			UpperCamelCase_     :       Optional[int])	->						List[Any]:
   '''simple docstring'''


   __lowercase								=						F"""repo_txt_data-{int(time.time() * 10E3)}"""
   __lowercase								=						F"""{CI_HUB_USER}/{repo_name}"""
   hf_api.create_repo(UpperCamelCase_,			token=UpperCamelCase_,			repo_type="dataset",			private=UpperCamelCase_)
   hf_api.upload_file(
       token=UpperCamelCase_,			path_or_fileobj=str(UpperCamelCase_),			path_in_repo="data/text_data.txt",			repo_id=UpperCamelCase_,			repo_type="dataset",			)
   yield repo_id
   try:
      hf_api.delete_repo(UpperCamelCase_,			token=UpperCamelCase_,			repo_type="dataset")
   except (requests.exceptions.HTTPError, ValueError):  # catch http error and token invalid error
      pass




@pytest.fixture()
def   _A  (  UpperCamelCase_     :       Tuple,			UpperCamelCase_     :       Any,			UpperCamelCase_     :       Dict)	->						Optional[int]:
   '''simple docstring'''


   return hf_private_dataset_repo_txt_data_




@pytest.fixture(scope="session")
def   _A  (  UpperCamelCase_     :       HfApi,			UpperCamelCase_     :       int,			UpperCamelCase_     :       Optional[int])	->						int:
   '''simple docstring'''


   __lowercase								=						F"""repo_zipped_txt_data-{int(time.time() * 10E3)}"""
   __lowercase								=						F"""{CI_HUB_USER}/{repo_name}"""
   hf_api.create_repo(UpperCamelCase_,			token=UpperCamelCase_,			repo_type="dataset",			private=UpperCamelCase_)
   hf_api.upload_file(
       token=UpperCamelCase_,			path_or_fileobj=str(UpperCamelCase_),			path_in_repo="data.zip",			repo_id=UpperCamelCase_,			repo_type="dataset",			)
   yield repo_id
   try:
      hf_api.delete_repo(UpperCamelCase_,			token=UpperCamelCase_,			repo_type="dataset")
   except (requests.exceptions.HTTPError, ValueError):  # catch http error and token invalid error
      pass




@pytest.fixture()
def   _A  (  UpperCamelCase_     :       List[str],			UpperCamelCase_     :       Dict,			UpperCamelCase_     :       Any)	->						int:
   '''simple docstring'''


   return hf_private_dataset_repo_zipped_txt_data_




@pytest.fixture(scope="session")
def   _A  (  UpperCamelCase_     :       HfApi,			UpperCamelCase_     :       List[str],			UpperCamelCase_     :       List[str])	->						List[Any]:
   '''simple docstring'''


   __lowercase								=						F"""repo_zipped_img_data-{int(time.time() * 10E3)}"""
   __lowercase								=						F"""{CI_HUB_USER}/{repo_name}"""
   hf_api.create_repo(UpperCamelCase_,			token=UpperCamelCase_,			repo_type="dataset",			private=UpperCamelCase_)
   hf_api.upload_file(
       token=UpperCamelCase_,			path_or_fileobj=str(UpperCamelCase_),			path_in_repo="data.zip",			repo_id=UpperCamelCase_,			repo_type="dataset",			)
   yield repo_id
   try:
      hf_api.delete_repo(UpperCamelCase_,			token=UpperCamelCase_,			repo_type="dataset")
   except (requests.exceptions.HTTPError, ValueError):  # catch http error and token invalid error
      pass




@pytest.fixture()
def   _A  (  UpperCamelCase_     :       Union[str, Any],			UpperCamelCase_     :       List[str],			UpperCamelCase_     :       List[str])	->						str:
   '''simple docstring'''


   return hf_private_dataset_repo_zipped_img_data_




