


"""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,
    flip_channel_order,
    get_resize_output_image_size,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_torch_available, is_torch_tensor, is_vision_available, logging


if is_vision_available():
  import PIL

if is_torch_available():
  import torch


__snake_case   			=    logging.get_logger(__name__)







class _lowerCAmelCase				(      snake_case_	):
   __UpperCAmelCase :       Tuple							  =  ['''pixel_values''']







   def __init__(	self						,	UpperCamelCase__ = True						,	UpperCamelCase__ = None						,	UpperCamelCase__ = PILImageResampling.BILINEAR						,	UpperCamelCase__ = True						,	UpperCamelCase__ = 1 / 255						,	UpperCamelCase__ = True						,	UpperCamelCase__ = None						,	UpperCamelCase__ = True						,	**UpperCamelCase__						,	)	->		None:

       '''simple docstring'''




       super().__init__(**UpperCamelCase__						)
       snake_case    :      int      					=    size if size is not None else {"shortest_edge": 224}
       snake_case    :      Dict      					=    get_size_dict(UpperCamelCase__						,	default_to_square=UpperCamelCase__						)
       snake_case    :      Tuple      					=    crop_size if crop_size is not None else {"height": 256, "width": 256}
       snake_case    :      Dict      					=    get_size_dict(UpperCamelCase__						,	param_name="crop_size"						)

       snake_case    :      List[Any]      					=    do_resize
       snake_case    :      Any      					=    size
       snake_case    :      Dict      					=    resample
       snake_case    :      str      					=    do_rescale
       snake_case    :      List[str]      					=    rescale_factor
       snake_case    :      Dict      					=    do_center_crop
       snake_case    :      List[Any]      					=    crop_size
       snake_case    :      Union[str, Any]      					=    do_flip_channel_order







   def  lowerCamelCase		(	self						,	UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__ = PIL.Image.BILINEAR						,	UpperCamelCase__ = None						,	**UpperCamelCase__						,	)	->		np.ndarray:

       '''simple docstring'''




       snake_case    :      str      					=    get_size_dict(UpperCamelCase__						,	default_to_square=UpperCamelCase__						)
       if "shortest_edge" not in size:
           raise ValueError(F'The `size` dictionary must contain the key `shortest_edge`. Got {size.keys()}'						)
       snake_case    :      List[str]      					=    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  lowerCamelCase		(	self						,	UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__ = None						,	**UpperCamelCase__						,	)	->		np.ndarray:

       '''simple docstring'''




       snake_case    :      str      					=    get_size_dict(UpperCamelCase__						)
       if "height" not in size or "width" not in size:
           raise ValueError(F'The `size` dictionary must contain the keys `height` and `width`. Got {size.keys()}'						)
       return center_crop(UpperCamelCase__						,	size=(size["height"], size["width"])						,	data_format=UpperCamelCase__						,	**UpperCamelCase__						)







   def  lowerCamelCase		(	self						,	UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__ = None						,	**UpperCamelCase__						,	)	->		Union[str, Any]:

       '''simple docstring'''




       return rescale(UpperCamelCase__						,	scale=UpperCamelCase__						,	data_format=UpperCamelCase__						,	**UpperCamelCase__						)







   def  lowerCamelCase		(	self						,	UpperCamelCase__						,	UpperCamelCase__ = None						)	->		np.ndarray:

       '''simple docstring'''




       return flip_channel_order(UpperCamelCase__						,	data_format=UpperCamelCase__						)







   def  lowerCamelCase		(	self						,	UpperCamelCase__						,	UpperCamelCase__ = None						,	UpperCamelCase__ = None						,	UpperCamelCase__ = None						,	UpperCamelCase__ = None						,	UpperCamelCase__ = None						,	UpperCamelCase__ = None						,	UpperCamelCase__ = None						,	UpperCamelCase__ = None						,	UpperCamelCase__ = None						,	UpperCamelCase__ = ChannelDimension.FIRST						,	**UpperCamelCase__						,	)	->		PIL.Image.Image:

       '''simple docstring'''




       snake_case    :      Tuple      					=    do_resize if do_resize is not None else self.do_resize
       snake_case    :      Union[str, Any]      					=    resample if resample is not None else self.resample
       snake_case    :      List[Any]      					=    do_rescale if do_rescale is not None else self.do_rescale
       snake_case    :      Dict      					=    rescale_factor if rescale_factor is not None else self.rescale_factor
       snake_case    :      Any      					=    do_center_crop if do_center_crop is not None else self.do_center_crop
       snake_case    :      List[Any]      					=    (
           do_flip_channel_order if do_flip_channel_order is not None else self.do_flip_channel_order
       )

       snake_case    :      Any      					=    size if size is not None else self.size
       snake_case    :      Dict      					=    get_size_dict(UpperCamelCase__						,	default_to_square=UpperCamelCase__						)
       snake_case    :      Union[str, Any]      					=    crop_size if crop_size is not None else self.crop_size
       snake_case    :      int      					=    get_size_dict(UpperCamelCase__						,	param_name="crop_size"						)

       snake_case    :      Tuple      					=    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_rescale and rescale_factor is None:
           raise ValueError("Rescale factor must be specified if do_rescale is True."						)

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

       # All transformations expect numpy arrays.
       snake_case    :      List[Any]      					=    [to_numpy_array(UpperCamelCase__						) for image in images]

       if do_resize:
           snake_case    :      int      					=    [self.resize(image=UpperCamelCase__						,	size=UpperCamelCase__						,	resample=UpperCamelCase__						) for image in images]

       if do_center_crop:
           snake_case    :      int      					=    [self.center_crop(image=UpperCamelCase__						,	size=UpperCamelCase__						) for image in images]

       if do_rescale:
           snake_case    :      List[str]      					=    [self.rescale(image=UpperCamelCase__						,	scale=UpperCamelCase__						) for image in images]

       # the pretrained checkpoints assume images are BGR, not RGB
       if do_flip_channel_order:
           snake_case    :      List[str]      					=    [self.flip_channel_order(image=UpperCamelCase__						) for image in images]

       snake_case    :      Tuple      					=    [to_channel_dimension_format(UpperCamelCase__						,	UpperCamelCase__						) for image in images]

       snake_case    :      Union[str, Any]      					=    {"pixel_values": images}
       return BatchFeature(data=UpperCamelCase__						,	tensor_type=UpperCamelCase__						)







   def  lowerCamelCase		(	self						,	UpperCamelCase__						,	UpperCamelCase__ = None						)	->		Tuple:

       '''simple docstring'''




       snake_case    :      str      					=    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__						):
               snake_case    :      Optional[int]      					=    target_sizes.numpy()

           snake_case    :      List[Any]      					=    []

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

       return semantic_segmentation









"""simple docstring"""



import json
import os
import tempfile
import unittest
import unittest.mock as mock
from pathlib import Path

from requests.exceptions import HTTPError

from transformers.utils import (
    CONFIG_NAME,
    FLAX_WEIGHTS_NAME,
    TF2_WEIGHTS_NAME,
    TRANSFORMERS_CACHE,
    WEIGHTS_NAME,
    cached_file,
    get_file_from_repo,
    has_file,
)


__snake_case   			=    """hf-internal-testing/tiny-random-bert"""
__snake_case   			=    os.path.join(TRANSFORMERS_CACHE, """models--hf-internal-testing--tiny-random-bert""")
__snake_case   			=    """9b8c223d42b2188cb49d29af482996f9d0f3e5a6"""







class _lowerCAmelCase				(      unittest.TestCase	):







   def  lowerCamelCase		(	self						)	->		str:

       '''simple docstring'''




       snake_case    :      int      					=    cached_file(UpperCamelCase__						,	UpperCamelCase__						)
       # Should have downloaded the file in here
       self.assertTrue(os.path.isdir(UpperCamelCase__						)						)
       # Cache should contain at least those three subfolders:
       for subfolder in ["blobs", "refs", "snapshots"]:
           self.assertTrue(os.path.isdir(os.path.join(UpperCamelCase__						,	UpperCamelCase__						)						)						)
       with open(os.path.join(UpperCamelCase__						,	"refs"						,	"main"						)						) as f:
           snake_case    :      Dict      					=    f.read()
       self.assertEqual(UpperCamelCase__						,	os.path.join(UpperCamelCase__						,	"snapshots"						,	UpperCamelCase__						,	UpperCamelCase__						)						)
       self.assertTrue(os.path.isfile(UpperCamelCase__						)						)

       # File is cached at the same place the second time.
       snake_case    :      List[str]      					=    cached_file(UpperCamelCase__						,	UpperCamelCase__						)
       self.assertEqual(UpperCamelCase__						,	UpperCamelCase__						)

       # Using a specific revision to test the full commit hash.
       snake_case    :      Any      					=    cached_file(UpperCamelCase__						,	UpperCamelCase__						,	revision="9b8c223"						)
       self.assertEqual(UpperCamelCase__						,	os.path.join(UpperCamelCase__						,	"snapshots"						,	UpperCamelCase__						,	UpperCamelCase__						)						)







   def  lowerCamelCase		(	self						)	->		Any:

       '''simple docstring'''




       with self.assertRaisesRegex(UpperCamelCase__						,	"is not a valid model identifier"						):
           snake_case    :      Optional[Any]      					=    cached_file("tiny-random-bert"						,	UpperCamelCase__						)

       with self.assertRaisesRegex(UpperCamelCase__						,	"is not a valid git identifier"						):
           snake_case    :      Optional[Any]      					=    cached_file(UpperCamelCase__						,	UpperCamelCase__						,	revision="aaaa"						)

       with self.assertRaisesRegex(UpperCamelCase__						,	"does not appear to have a file named"						):
           snake_case    :      List[Any]      					=    cached_file(UpperCamelCase__						,	"conf"						)







   def  lowerCamelCase		(	self						)	->		Tuple:

       '''simple docstring'''




       with self.assertRaisesRegex(UpperCamelCase__						,	"does not appear to have a file named"						):
           snake_case    :      Tuple      					=    cached_file(UpperCamelCase__						,	"conf"						)

       with open(os.path.join(UpperCamelCase__						,	"refs"						,	"main"						)						) as f:
           snake_case    :      Any      					=    f.read()
       self.assertTrue(os.path.isfile(os.path.join(UpperCamelCase__						,	".no_exist"						,	UpperCamelCase__						,	"conf"						)						)						)

       snake_case    :      Optional[Any]      					=    cached_file(UpperCamelCase__						,	"conf"						,	_raise_exceptions_for_missing_entries=UpperCamelCase__						)
       self.assertIsNone(UpperCamelCase__						)

       snake_case    :      Any      					=    cached_file(UpperCamelCase__						,	"conf"						,	local_files_only=UpperCamelCase__						,	_raise_exceptions_for_missing_entries=UpperCamelCase__						)
       self.assertIsNone(UpperCamelCase__						)

       snake_case    :      Any      					=    mock.Mock()
       snake_case    :      List[Any]      					=    500
       snake_case    :      int      					=    {}
       snake_case    :      Optional[int]      					=    HTTPError
       snake_case    :      Tuple      					=    {}

       # Under the mock environment we get a 500 error when trying to reach the tokenizer.
       with mock.patch("requests.Session.request"						,	return_value=UpperCamelCase__						) as mock_head:
           snake_case    :      Tuple      					=    cached_file(UpperCamelCase__						,	"conf"						,	_raise_exceptions_for_connection_errors=UpperCamelCase__						)
           self.assertIsNone(UpperCamelCase__						)
           # This check we did call the fake head request
           mock_head.assert_called()







   def  lowerCamelCase		(	self						)	->		Any:

       '''simple docstring'''




       self.assertTrue(has_file("hf-internal-testing/tiny-bert-pt-only"						,	UpperCamelCase__						)						)
       self.assertFalse(has_file("hf-internal-testing/tiny-bert-pt-only"						,	UpperCamelCase__						)						)
       self.assertFalse(has_file("hf-internal-testing/tiny-bert-pt-only"						,	UpperCamelCase__						)						)







   def  lowerCamelCase		(	self						)	->		str:

       '''simple docstring'''




       self.assertIsNone(get_file_from_repo("bert-base-cased"						,	"ahah.txt"						)						)

       # The function raises if the repository does not exist.
       with self.assertRaisesRegex(UpperCamelCase__						,	"is not a valid model identifier"						):
           get_file_from_repo("bert-base-case"						,	UpperCamelCase__						)

       # The function raises if the revision does not exist.
       with self.assertRaisesRegex(UpperCamelCase__						,	"is not a valid git identifier"						):
           get_file_from_repo("bert-base-cased"						,	UpperCamelCase__						,	revision="ahaha"						)

       snake_case    :      int      					=    get_file_from_repo("bert-base-cased"						,	UpperCamelCase__						)
       # The name is the cached name which is not very easy to test, so instead we load the content.
       snake_case    :      str      					=    json.loads(open(UpperCamelCase__						,	"r"						).read()						)
       self.assertEqual(config["hidden_size"]						,	768						)







   def  lowerCamelCase		(	self						)	->		Optional[Any]:

       '''simple docstring'''




       with tempfile.TemporaryDirectory() as tmp_dir:
           snake_case    :      int      					=    Path(UpperCamelCase__						) / "a.txt"
           filename.touch()
           self.assertEqual(get_file_from_repo(UpperCamelCase__						,	"a.txt"						)						,	str(UpperCamelCase__						)						)

           self.assertIsNone(get_file_from_repo(UpperCamelCase__						,	"b.txt"						)						)





