






"""simple docstring"""




import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin


if is_torch_available():
  import torch

if is_vision_available():
  from PIL import Image

  from transformers import SwinaSRImageProcessor
  from transformers.image_transforms import get_image_size


class  __lowercase (		unittest.TestCase					):







     '''simple docstring'''




     def __init__(			self    :     Union[str, Any]	,		UpperCamelCase_    :     int	,		UpperCamelCase_    :     Optional[Any]=7	,		UpperCamelCase_    :     int=3	,		UpperCamelCase_    :     int=18	,		UpperCamelCase_    :     int=30	,		UpperCamelCase_    :     Any=400	,		UpperCamelCase_    :     Any=True	,		UpperCamelCase_    :     Optional[Any]=1 / 255	,		UpperCamelCase_    :     List[str]=True	,		UpperCamelCase_    :     Any=8	,		):


         """simple docstring"""



         __A             =		parent
         __A             =		batch_size
         __A             =		num_channels
         __A             =		image_size
         __A             =		min_resolution
         __A             =		max_resolution
         __A             =		do_rescale
         __A             =		rescale_factor
         __A             =		do_pad
         __A             =		pad_size




     def 						lowerCAmelCase_       (			self    :     List[str]			):


         """simple docstring"""



         return {
             "do_rescale": self.do_rescale,
             "rescale_factor": self.rescale_factor,
             "do_pad": self.do_pad,
             "pad_size": self.pad_size,
         }





     def 						lowerCAmelCase_       (			self    :     str	,		UpperCamelCase_    :     Optional[Any]=False	,		UpperCamelCase_    :     Tuple=False	,		UpperCamelCase_    :     List[Any]=False			):


         """simple docstring"""



         assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

         if equal_resolution:
             __A             =		[]
             for i in range(self.batch_size			):
                 image_inputs.append(
                     np.random.randint(
                         255	,		size=(self.num_channels, self.max_resolution, self.max_resolution)	,		dtype=np.uinta			)			)
         else:
             __A             =		[]
             for i in range(self.batch_size			):
                 __A      ,		__A             =		np.random.choice(np.arange(self.min_resolution	,		self.max_resolution			)	,		2			)
                 image_inputs.append(np.random.randint(255	,		size=(self.num_channels, width, height)	,		dtype=np.uinta			)			)

         if not numpify and not torchify:
             # PIL expects the channel dimension as last dimension
             __A             =		[Image.fromarray(np.moveaxis(UpperCamelCase_	,		0	,		-1			)			) for x in image_inputs]

         if torchify:
             __A             =		[torch.from_numpy(UpperCamelCase_			) for x in image_inputs]

         return image_inputs


@require_torch
@require_vision
class  __lowercase (		lowercase_     , unittest.TestCase					):







     '''simple docstring'''
     SCREAMING_SNAKE_CASE				  =			SwinaSRImageProcessor if is_vision_available() else None




     def 						lowerCAmelCase_       (			self    :     str			):


         """simple docstring"""



         __A             =		SwinaSRImageProcessingTester(self			)




     @property
     def 						lowerCAmelCase_       (			self    :     Tuple			):


         """simple docstring"""



         return self.image_processor_tester.prepare_image_processor_dict()




     def 						lowerCAmelCase_       (			self    :     int			):


         """simple docstring"""



         __A             =		self.image_processing_class(**self.image_processor_dict			)
         self.assertTrue(hasattr(UpperCamelCase_	,		"""do_rescale"""			)			)
         self.assertTrue(hasattr(UpperCamelCase_	,		"""rescale_factor"""			)			)
         self.assertTrue(hasattr(UpperCamelCase_	,		"""do_pad"""			)			)
         self.assertTrue(hasattr(UpperCamelCase_	,		"""pad_size"""			)			)




     def 						lowerCAmelCase_       (			self    :     List[str]			):


         """simple docstring"""



         pass




     def 						lowerCAmelCase_       (			self    :     Tuple	,		UpperCamelCase_    :     List[Any]			):


         """simple docstring"""



         __A      ,		__A             =		get_image_size(UpperCamelCase_			)
         __A             =		self.image_processor_tester.pad_size

         __A             =		(old_height // size + 1) * size - old_height
         __A             =		(old_width // size + 1) * size - old_width
         return old_height + pad_height, old_width + pad_width




     def 						lowerCAmelCase_       (			self    :     Optional[int]			):


         """simple docstring"""



         __A             =		self.image_processing_class(**self.image_processor_dict			)
         # create random PIL images
         __A             =		self.image_processor_tester.prepare_inputs(equal_resolution=UpperCamelCase_			)
         for image in image_inputs:
             self.assertIsInstance(UpperCamelCase_	,		Image.Image			)

         # Test not batched input
         __A             =		image_processor(image_inputs[0]	,		return_tensors="""pt"""			).pixel_values
         __A      ,		__A             =		self.calculate_expected_size(np.array(image_inputs[0]			)			)
         self.assertEqual(
             encoded_images.shape	,		(
                 1,
                 self.image_processor_tester.num_channels,
                 expected_height,
                 expected_width,
             )	,		)




     def 						lowerCAmelCase_       (			self    :     Any			):


         """simple docstring"""



         __A             =		self.image_processing_class(**self.image_processor_dict			)
         # create random numpy tensors
         __A             =		self.image_processor_tester.prepare_inputs(equal_resolution=UpperCamelCase_	,		numpify=UpperCamelCase_			)
         for image in image_inputs:
             self.assertIsInstance(UpperCamelCase_	,		np.ndarray			)

         # Test not batched input
         __A             =		image_processor(image_inputs[0]	,		return_tensors="""pt"""			).pixel_values
         __A      ,		__A             =		self.calculate_expected_size(image_inputs[0]			)
         self.assertEqual(
             encoded_images.shape	,		(
                 1,
                 self.image_processor_tester.num_channels,
                 expected_height,
                 expected_width,
             )	,		)





     def 						lowerCAmelCase_       (			self    :     Any			):


         """simple docstring"""



         __A             =		self.image_processing_class(**self.image_processor_dict			)
         # create random PyTorch tensors
         __A             =		self.image_processor_tester.prepare_inputs(equal_resolution=UpperCamelCase_	,		torchify=UpperCamelCase_			)
         for image in image_inputs:
             self.assertIsInstance(UpperCamelCase_	,		torch.Tensor			)

         # Test not batched input
         __A             =		image_processor(image_inputs[0]	,		return_tensors="""pt"""			).pixel_values
         __A      ,		__A             =		self.calculate_expected_size(image_inputs[0]			)
         self.assertEqual(
             encoded_images.shape	,		(
                 1,
                 self.image_processor_tester.num_channels,
                 expected_height,
                 expected_width,
             )	,		)












# Copyright 2022 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 os
from typing import List



def      _SCREAMING_SNAKE_CASE  (	__lowercase				:     List[str]     ,			__lowercase				:     str      )  -> Optional[int]:





    """simple docstring"""

    if name != "training_function" and name != "main":
        raise ValueError(f"Incorrect function name passed: {name}, choose either 'main' or 'training_function'"      )
    __A      ,		__A             =		[], False
    for line in lines:
        if not found_start and f"def {name}" in line:
            __A             =		True
            good_lines.append(__lowercase      )
            continue
        if found_start:
            if name == "training_function" and "def main" in line:
                return good_lines
            if name == "main" and "if __name__" in line:
                return good_lines
            good_lines.append(__lowercase      )



def      _SCREAMING_SNAKE_CASE  (	__lowercase				:     List[str]      )  -> Optional[int]:





    """simple docstring"""

    return [line for line in lines if not line.lstrip().startswith("""#"""      ) and line != "\n"]






def      _SCREAMING_SNAKE_CASE  (	__lowercase				:     str     ,			__lowercase				:     str     ,			__lowercase				:     bool     ,			__lowercase				:     str = None      )  -> List[Any]:





    """simple docstring"""

    with open(__lowercase     ,			"""r"""      ) as f:
        __A             =		f.readlines()
    with open(os.path.abspath(os.path.join("""examples"""     ,			"""nlp_example.py"""      )      )     ,			"""r"""      ) as f:
        __A             =		f.readlines()
    with open(__lowercase     ,			"""r"""      ) as f:
        __A             =		f.readlines()
    if secondary_filename is not None:
        with open(__lowercase     ,			"""r"""      ) as f:
            __A             =		f.readlines()

    # This is our base, we remove all the code from here in our `full_filename` and `feature_filename` to find the new content
    if parser_only:
        __A             =		clean_lines(get_function_contents_by_name(__lowercase     ,			"""main"""      )      )
        __A             =		clean_lines(get_function_contents_by_name(__lowercase     ,			"""main"""      )      )
        __A             =		clean_lines(get_function_contents_by_name(__lowercase     ,			"""main"""      )      )
        if secondary_filename is not None:
            __A             =		clean_lines(get_function_contents_by_name(__lowercase     ,			"""main"""      )      )
    else:
        __A             =		clean_lines(get_function_contents_by_name(__lowercase     ,			"""training_function"""      )      )
        __A             =		clean_lines(get_function_contents_by_name(__lowercase     ,			"""training_function"""      )      )
        __A             =		clean_lines(get_function_contents_by_name(__lowercase     ,			"""training_function"""      )      )
        if secondary_filename is not None:
            __A             =		clean_lines(
                get_function_contents_by_name(__lowercase     ,			"""training_function"""      )      )

    __A             =		"""train_dataloader, eval_dataloader = get_dataloaders(accelerator, batch_size)\n"""

    # Specific code in our script that differs from the full version, aka what is new
    __A             =		[]
    __A             =		[]  # We keep track of the idxs just in case it's a repeated statement
    __A             =		iter(__lowercase      )
    for i in range(len(__lowercase      ) - 1      ):
        if i not in passed_idxs:
            __A             =		next(__lowercase      )
            if (line not in full_file_func) and (line.lstrip() != _dl_line):
                if "TESTING_MOCKED_DATALOADERS" not in line:
                    new_feature_code.append(__lowercase      )
                    passed_idxs.append(__lowercase      )
                else:
                    # Skip over the `config['num_epochs'] = 2` statement
                    __A             =		next(__lowercase      )

    # Extract out just the new parts from the full_file_training_func
    __A             =		[]
    __A             =		[]  # We keep track of the idxs just in case it's a repeated statement
    for i, line in enumerate(__lowercase      ):
        if i not in passed_idxs:
            if (line not in full_file_func) and (line.lstrip() != _dl_line):
                if "TESTING_MOCKED_DATALOADERS" not in line:
                    new_full_example_parts.append(__lowercase      )
                    passed_idxs.append(__lowercase      )

    # Finally, get the overall diff
    __A             =		[line for line in new_feature_code if line not in new_full_example_parts]
    if secondary_filename is not None:
        __A             =		[line for line in full_file_contents if line not in secondary_file_func]
        __A             =		[line for line in diff_from_example if line not in diff_from_two]

    return diff_from_example




