




from typing import Dict, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import convert_to_rgb, normalize, rescale, resize, to_channel_dimension_format
from ...image_utils import (
    OPENAI_CLIP_MEAN,
    OPENAI_CLIP_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


if is_vision_available():
      import PIL


__magic_name__  :  Union[str, Any]					=       logging.get_logger(__name__)





class     SCREAMING_SNAKE_CASE__		(lowerCAmelCase__			):
     lowercase_ :      List[Any]				= ['''pixel_values''']
     def __init__(						self	:		Optional[int]       ,						__lowerCamelCase	:		int = True       ,						__lowerCamelCase	:		Optional[Any] = None       ,						__lowerCamelCase	:		List[Any] = PILImageResampling.BICUBIC       ,						__lowerCamelCase	:		Optional[int] = True       ,						__lowerCamelCase	:		Tuple = 1 / 2_55       ,						__lowerCamelCase	:		List[Any] = True       ,						__lowerCamelCase	:		Dict = None       ,						__lowerCamelCase	:		List[str] = None       ,						__lowerCamelCase	:		Any = True       ,						**__lowerCamelCase	:		List[str]       ,						):



       """simple docstring"""
       super().__init__(**__lowerCAmelCase						)
       lowerCAmelCase__										=      size if size is not None else {'''height''': 3_84, '''width''': 3_84}
       lowerCAmelCase__										=      get_size_dict(__lowerCAmelCase       ,						default_to_square=__lowerCAmelCase						)

       lowerCAmelCase__										=      do_resize
       lowerCAmelCase__										=      size
       lowerCAmelCase__										=      resample
       lowerCAmelCase__										=      do_rescale
       lowerCAmelCase__										=      rescale_factor
       lowerCAmelCase__										=      do_normalize
       lowerCAmelCase__										=      image_mean if image_mean is not None else OPENAI_CLIP_MEAN
       lowerCAmelCase__										=      image_std if image_std is not None else OPENAI_CLIP_STD
       lowerCAmelCase__										=      do_convert_rgb
     def        A__      (						self	:		str       ,						__lowerCamelCase	:		List[Any]       ,						__lowerCamelCase	:		Dict       ,						__lowerCamelCase	:		str = PILImageResampling.BICUBIC       ,						__lowerCamelCase	:		Union[str, Any] = None       ,						**__lowerCamelCase	:		Optional[Any]       ,						):



       """simple docstring"""
       lowerCAmelCase__										=      get_size_dict(__lowerCAmelCase       ,						default_to_square=__lowerCAmelCase						)
       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()}"""						)
       lowerCAmelCase__										=      (size['''height'''], size['''width'''])
       return resize(__lowerCAmelCase       ,						size=__lowerCAmelCase       ,						resample=__lowerCAmelCase       ,						data_format=__lowerCAmelCase       ,						**__lowerCAmelCase						)
     def        A__      (						self	:		List[Any]       ,						__lowerCamelCase	:		List[Any]       ,						__lowerCamelCase	:		Dict       ,						__lowerCamelCase	:		Optional[int] = None       ,						**__lowerCamelCase	:		Tuple       ,						):



       """simple docstring"""
       return rescale(__lowerCAmelCase       ,						scale=__lowerCAmelCase       ,						data_format=__lowerCAmelCase       ,						**__lowerCAmelCase						)
     def        A__      (						self	:		Any       ,						__lowerCamelCase	:		List[Any]       ,						__lowerCamelCase	:		List[str]       ,						__lowerCamelCase	:		List[str]       ,						__lowerCamelCase	:		Optional[Any] = None       ,						**__lowerCamelCase	:		List[Any]       ,						):



       """simple docstring"""
       return normalize(__lowerCAmelCase       ,						mean=__lowerCAmelCase       ,						std=__lowerCAmelCase       ,						data_format=__lowerCAmelCase       ,						**__lowerCAmelCase						)



     def        A__      (						self	:		Optional[int]       ,						__lowerCamelCase	:		List[Any]       ,						__lowerCamelCase	:		Dict = None       ,						__lowerCamelCase	:		Any = None       ,						__lowerCamelCase	:		Optional[int] = None       ,						__lowerCamelCase	:		Optional[int] = None       ,						__lowerCamelCase	:		List[str] = None       ,						__lowerCamelCase	:		int = None       ,						__lowerCamelCase	:		Any = None       ,						__lowerCamelCase	:		Optional[int] = None       ,						__lowerCamelCase	:		Dict = None       ,						__lowerCamelCase	:		List[str] = None       ,						__lowerCamelCase	:		Any = ChannelDimension.FIRST       ,						**__lowerCamelCase	:		Any       ,						):



       """simple docstring"""
       lowerCAmelCase__										=      do_resize if do_resize is not None else self.do_resize
       lowerCAmelCase__										=      resample if resample is not None else self.resample
       lowerCAmelCase__										=      do_rescale if do_rescale is not None else self.do_rescale
       lowerCAmelCase__										=      rescale_factor if rescale_factor is not None else self.rescale_factor
       lowerCAmelCase__										=      do_normalize if do_normalize is not None else self.do_normalize
       lowerCAmelCase__										=      image_mean if image_mean is not None else self.image_mean
       lowerCAmelCase__										=      image_std if image_std is not None else self.image_std
       lowerCAmelCase__										=      do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb

       lowerCAmelCase__										=      size if size is not None else self.size
       lowerCAmelCase__										=      get_size_dict(__lowerCAmelCase       ,						default_to_square=__lowerCAmelCase						)

       lowerCAmelCase__										=      make_list_of_images(__lowerCAmelCase						)

       if not valid_images(__lowerCAmelCase						):
         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 or resample is None:
         raise ValueError('''Size and resample 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_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.'''						)

       # PIL RGBA images are converted to RGB
       if do_convert_rgb:
         lowerCAmelCase__										=      [convert_to_rgb(__lowerCAmelCase						) for image in images]

       # All transformations expect numpy arrays.
       lowerCAmelCase__										=      [to_numpy_array(__lowerCAmelCase						) for image in images]

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

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

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

       lowerCAmelCase__										=      [to_channel_dimension_format(__lowerCAmelCase       ,						__lowerCAmelCase						) for image in images]

       lowerCAmelCase__										=      BatchFeature(data={'''pixel_values''': images}       ,						tensor_type=__lowerCAmelCase						)

       return encoded_outputs


'''simple docstring'''




import math
import time

from transformers import Trainer, is_torch_tpu_available
from transformers.trainer_utils import PredictionOutput, speed_metrics


if is_torch_tpu_available(check_device=False):
						import torch_xla.core.xla_model as xm
						import torch_xla.debug.metrics as met






class 							a__(   lowerCAmelCase__      ):


			'''simple docstring'''






			def __init__(  self			,       *__lowerCAmelCase			,       __lowerCAmelCase=None			,       __lowerCAmelCase=None			,       **__lowerCAmelCase):




					"""simple docstring"""


					super().__init__(*__lowerCAmelCase			,       **__lowerCAmelCase)
					lowerCAmelCase     =    eval_examples
					lowerCAmelCase     =    post_process_function



			def 				a_			(  self			,       __lowerCAmelCase=None			,       __lowerCAmelCase=None			,       __lowerCAmelCase=None			,       __lowerCAmelCase = "eval"):




					"""simple docstring"""


					lowerCAmelCase     =    self.eval_dataset if eval_dataset is None else eval_dataset
					lowerCAmelCase     =    self.get_eval_dataloader(__lowerCAmelCase)
					lowerCAmelCase     =    self.eval_examples if eval_examples is None else eval_examples

					# Temporarily disable metric computation, we will do it in the loop here.
					lowerCAmelCase     =    self.compute_metrics
					lowerCAmelCase     =    None
					lowerCAmelCase     =    self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
					lowerCAmelCase     =    time.time()
					try:
							lowerCAmelCase     =    eval_loop(
							    __lowerCAmelCase			,       description="""Evaluation"""			,       prediction_loss_only=True if compute_metrics is None else None			,       ignore_keys=__lowerCAmelCase			,       metric_key_prefix=__lowerCAmelCase			,       )
					finally:
							lowerCAmelCase     =    compute_metrics
					lowerCAmelCase     =    self.args.eval_batch_size * self.args.world_size
					if f"{metric_key_prefix}_jit_compilation_time" in output.metrics:
							start_time += output.metrics[f"{metric_key_prefix}_jit_compilation_time"]
					output.metrics.update(
					    speed_metrics(
					        __lowerCAmelCase			,       __lowerCAmelCase			,       num_samples=output.num_samples			,       num_steps=math.ceil(output.num_samples / total_batch_size)			,       ))
					if self.post_process_function is not None and self.compute_metrics is not None and self.args.should_save:
							# Only the main node write the results by default
							lowerCAmelCase     =    self.post_process_function(__lowerCAmelCase			,       __lowerCAmelCase			,       output.predictions)
							lowerCAmelCase     =    self.compute_metrics(__lowerCAmelCase)

							# Prefix all keys with metric_key_prefix + '_'
							for key in list(metrics.keys()):
									if not key.startswith(f"{metric_key_prefix}_"):
											lowerCAmelCase     =    metrics.pop(__lowerCAmelCase)
							metrics.update(output.metrics)
					else:
							lowerCAmelCase     =    output.metrics

					if self.args.should_log:
							# Only the main node log the results by default
							self.log(__lowerCAmelCase)

					if self.args.tpu_metrics_debug or self.args.debug:
							# tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.)
							xm.master_print(met.metrics_report())

					lowerCAmelCase     =    self.callback_handler.on_evaluate(self.args			,       self.state			,       self.control			,       __lowerCAmelCase)
					return metrics







			def 				a_			(  self			,       __lowerCAmelCase			,       __lowerCAmelCase			,       __lowerCAmelCase=None			,       __lowerCAmelCase = "test"):




					"""simple docstring"""


					lowerCAmelCase     =    self.get_test_dataloader(__lowerCAmelCase)

					# Temporarily disable metric computation, we will do it in the loop here.
					lowerCAmelCase     =    self.compute_metrics
					lowerCAmelCase     =    None
					lowerCAmelCase     =    self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
					lowerCAmelCase     =    time.time()
					try:
							lowerCAmelCase     =    eval_loop(
							    __lowerCAmelCase			,       description="""Prediction"""			,       prediction_loss_only=True if compute_metrics is None else None			,       ignore_keys=__lowerCAmelCase			,       metric_key_prefix=__lowerCAmelCase			,       )
					finally:
							lowerCAmelCase     =    compute_metrics
					lowerCAmelCase     =    self.args.eval_batch_size * self.args.world_size
					if f"{metric_key_prefix}_jit_compilation_time" in output.metrics:
							start_time += output.metrics[f"{metric_key_prefix}_jit_compilation_time"]
					output.metrics.update(
					    speed_metrics(
					        __lowerCAmelCase			,       __lowerCAmelCase			,       num_samples=output.num_samples			,       num_steps=math.ceil(output.num_samples / total_batch_size)			,       ))

					if self.post_process_function is None or self.compute_metrics is None:
							return output

					lowerCAmelCase     =    self.post_process_function(__lowerCAmelCase			,       __lowerCAmelCase			,       output.predictions			,       """predict""")
					lowerCAmelCase     =    self.compute_metrics(__lowerCAmelCase)

					# Prefix all keys with metric_key_prefix + '_'
					for key in list(metrics.keys()):
							if not key.startswith(f"{metric_key_prefix}_"):
									lowerCAmelCase     =    metrics.pop(__lowerCAmelCase)
					metrics.update(output.metrics)
					return PredictionOutput(predictions=predictions.predictions			,       label_ids=predictions.label_ids			,       metrics=__lowerCAmelCase)




