


import warnings
from typing import List, Optional, Union

import numpy as np
import PIL
import torch
from PIL import Image

from .configuration_utils import ConfigMixin, register_to_config
from .utils import CONFIG_NAME, PIL_INTERPOLATION, deprecate



class     snake_case__  (      _A  ):
				__lowerCAmelCase		=      CONFIG_NAME
				@register_to_config
				def __init__(  self     ,      _UpperCAmelCase = True     ,      _UpperCAmelCase = 8     ,      _UpperCAmelCase = "lanczos"     ,      _UpperCAmelCase = True     ,      _UpperCAmelCase = False     ,      ):




										"""simple docstring"""




										super().__init__()
				@staticmethod
				def  UpperCamelCase_						(  _UpperCAmelCase      ):




										"""simple docstring"""




										if images.ndim == 3:
																__magic_name__				:							Optional[int]				=      images[None, ...]
										__magic_name__				:							Dict				=      (images * 255).round().astype('uint8'      )
										if images.shape[-1] == 1:
																# special case for grayscale (single channel) images
																__magic_name__				:							Tuple				=      [Image.fromarray(image.squeeze()     ,      mode='L'      ) for image in images]
										else:
																__magic_name__				:							List[str]				=      [Image.fromarray(_UpperCAmelCase      ) for image in images]

										return pil_images
				@staticmethod
				def  UpperCamelCase_						(  _UpperCAmelCase      ):




										"""simple docstring"""




										if not isinstance(_UpperCAmelCase     ,      _UpperCAmelCase      ):
																__magic_name__				:							Union[str, Any]				=      [images]
										__magic_name__				:							Union[str, Any]				=      [np.array(_UpperCAmelCase      ).astype(np.floataa      ) / 255.0 for image in images]
										__magic_name__				:							Any				=      np.stack(_UpperCAmelCase     ,      axis=0      )

										return images
				@staticmethod
				def  UpperCamelCase_						(  _UpperCAmelCase      ):




										"""simple docstring"""




										if images.ndim == 3:
																__magic_name__				:							Optional[Any]				=      images[..., None]

										__magic_name__				:							Tuple				=      torch.from_numpy(images.transpose(0     ,      3     ,      1     ,      2      )      )
										return images
				@staticmethod
				def  UpperCamelCase_						(  _UpperCAmelCase      ):




										"""simple docstring"""




										__magic_name__				:							List[str]				=      images.cpu().permute(0     ,      2     ,      3     ,      1      ).float().numpy()
										return images
				@staticmethod
				def  UpperCamelCase_						(  _UpperCAmelCase      ):




										"""simple docstring"""




										return 2.0 * images - 1.0
				@staticmethod
				def  UpperCamelCase_						(  _UpperCAmelCase      ):




										"""simple docstring"""




										return (images / 2 + 0.5).clamp(0     ,      1      )
				@staticmethod
				def  UpperCamelCase_						(  _UpperCAmelCase      ):




										"""simple docstring"""




										__magic_name__				:							Tuple				=      image.convert('RGB'      )
										return image
				def  UpperCamelCase_						(  self     ,      _UpperCAmelCase     ,      _UpperCAmelCase = None     ,      _UpperCAmelCase = None     ,      ):




										"""simple docstring"""




										if height is None:
																__magic_name__				:							List[str]				=      image.height
										if width is None:
																__magic_name__				:							Tuple				=      image.width

										__magic_name__		, __magic_name__				:							Tuple				=      (
										    x - x % self.config.vae_scale_factor for x in (width, height)
										)  # resize to integer multiple of vae_scale_factor
										__magic_name__				:							Tuple				=      image.resize((width, height)     ,      resample=PIL_INTERPOLATION[self.config.resample]      )
										return image
				def  UpperCamelCase_						(  self     ,      _UpperCAmelCase     ,      _UpperCAmelCase = None     ,      _UpperCAmelCase = None     ,      ):




										"""simple docstring"""




										__magic_name__				:							Dict				=      (PIL.Image.Image, np.ndarray, torch.Tensor)
										if isinstance(_UpperCAmelCase     ,      _UpperCAmelCase      ):
																__magic_name__				:							List[str]				=      [image]
										elif not (isinstance(_UpperCAmelCase     ,      _UpperCAmelCase      ) and all(isinstance(_UpperCAmelCase     ,      _UpperCAmelCase      ) for i in image      )):
																raise ValueError(
																    F"Input is in incorrect format: {[type(_UpperCAmelCase      ) for i in image]}. Currently, we only support {', '.join(_UpperCAmelCase      )}"      )

										if isinstance(image[0]     ,      PIL.Image.Image      ):
																if self.config.do_convert_rgb:
																						__magic_name__				:							Optional[Any]				=      [self.convert_to_rgb(_UpperCAmelCase      ) for i in image]
																if self.config.do_resize:
																						__magic_name__				:							Optional[Any]				=      [self.resize(_UpperCAmelCase     ,      _UpperCAmelCase     ,      _UpperCAmelCase      ) for i in image]
																__magic_name__				:							Dict				=      self.pil_to_numpy(_UpperCAmelCase      )  # to np
																__magic_name__				:							Optional[Any]				=      self.numpy_to_pt(_UpperCAmelCase      )  # to pt

										elif isinstance(image[0]     ,      np.ndarray      ):
																__magic_name__				:							str				=      np.concatenate(_UpperCAmelCase     ,      axis=0      ) if image[0].ndim == 4 else np.stack(_UpperCAmelCase     ,      axis=0      )
																__magic_name__				:							int				=      self.numpy_to_pt(_UpperCAmelCase      )
																__magic_name__		, __magic_name__		, __magic_name__		, __magic_name__				:							List[str]				=      image.shape
																if self.config.do_resize and (
																    height % self.config.vae_scale_factor != 0 or width % self.config.vae_scale_factor != 0
																):
																						raise ValueError(
																						    F"Currently we only support resizing for PIL image - please resize your numpy array to be divisible by {self.config.vae_scale_factor}"
																						    F"currently the sizes are {height} and {width}. You can also pass a PIL image instead to use resize option in VAEImageProcessor"      )

										elif isinstance(image[0]     ,      torch.Tensor      ):
																__magic_name__				:							Optional[Any]				=      torch.cat(_UpperCAmelCase     ,      axis=0      ) if image[0].ndim == 4 else torch.stack(_UpperCAmelCase     ,      axis=0      )
																__magic_name__		, __magic_name__		, __magic_name__		, __magic_name__				:							List[str]				=      image.shape

																# don't need any preprocess if the image is latents
																if channel == 4:
																						return image

																if self.config.do_resize and (
																    height % self.config.vae_scale_factor != 0 or width % self.config.vae_scale_factor != 0
																):
																						raise ValueError(
																						    F"Currently we only support resizing for PIL image - please resize your pytorch tensor to be divisible by {self.config.vae_scale_factor}"
																						    F"currently the sizes are {height} and {width}. You can also pass a PIL image instead to use resize option in VAEImageProcessor"      )

        # expected range [0,1], normalize to [-1,1]
										__magic_name__				:							Optional[Any]				=      self.config.do_normalize
										if image.min() < 0:
																warnings.warn(
																    'Passing `image` as torch tensor with value range in [-1,1] is deprecated. The expected value range for image tensor is [0,1] '
																    F"when passing as pytorch tensor or numpy Array. You passed `image` with value range [{image.min()},{image.max()}]"     ,      _UpperCAmelCase     ,      )
																__magic_name__				:							Tuple				=      False

										if do_normalize:
																__magic_name__				:							Any				=      self.normalize(_UpperCAmelCase      )

										return image





				def  UpperCamelCase_						(  self     ,      _UpperCAmelCase     ,      _UpperCAmelCase = "pil"     ,      _UpperCAmelCase = None     ,      ):




										"""simple docstring"""




										if not isinstance(_UpperCAmelCase     ,      torch.Tensor      ):
																raise ValueError(
																    F"Input for postprocessing is in incorrect format: {type(_UpperCAmelCase      )}. We only support pytorch tensor"      )
										if output_type not in ["latent", "pt", "np", "pil"]:
																__magic_name__				:							Optional[int]				=      (
																    F"the output_type {output_type} is outdated and has been set to `np`. Please make sure to set it to one of these instead: "
																    '`pil`, `np`, `pt`, `latent`'
																)
																deprecate('Unsupported output_type'     ,      '1.0.0'     ,      _UpperCAmelCase     ,      standard_warn=_UpperCAmelCase      )
																__magic_name__				:							Union[str, Any]				=      'np'

										if output_type == "latent":
																return image

										if do_denormalize is None:
																__magic_name__				:							int				=      [self.config.do_normalize] * image.shape[0]

										__magic_name__				:							List[str]				=      torch.stack(
										    [self.denormalize(image[i]      ) if do_denormalize[i] else image[i] for i in range(image.shape[0]      )]      )

										if output_type == "pt":
																return image

										__magic_name__				:							Union[str, Any]				=      self.pt_to_numpy(_UpperCAmelCase      )

										if output_type == "np":
																return image

										if output_type == "pil":
																return self.numpy_to_pil(_UpperCAmelCase      )






class     snake_case__  (      _A  ):
				__lowerCAmelCase		=      CONFIG_NAME
				@register_to_config
				def __init__(  self     ,      _UpperCAmelCase = True     ,      _UpperCAmelCase = 8     ,      _UpperCAmelCase = "lanczos"     ,      _UpperCAmelCase = True     ,      ):




										"""simple docstring"""




										super().__init__()
				@staticmethod
				def  UpperCamelCase_						(  _UpperCAmelCase      ):




										"""simple docstring"""




										if images.ndim == 3:
																__magic_name__				:							Tuple				=      images[None, ...]
										__magic_name__				:							Optional[Any]				=      (images * 255).round().astype('uint8'      )
										if images.shape[-1] == 1:
																# special case for grayscale (single channel) images
																__magic_name__				:							Union[str, Any]				=      [Image.fromarray(image.squeeze()     ,      mode='L'      ) for image in images]
										else:
																__magic_name__				:							Union[str, Any]				=      [Image.fromarray(image[:, :, :3]      ) for image in images]

										return pil_images
				@staticmethod
				def  UpperCamelCase_						(  _UpperCAmelCase      ):




										"""simple docstring"""




										return image[:, :, 1] * 2**8 + image[:, :, 2]
				def  UpperCamelCase_						(  self     ,      _UpperCAmelCase      ):




										"""simple docstring"""




										if images.ndim == 3:
																__magic_name__				:							Tuple				=      images[None, ...]
										__magic_name__				:							int				=      images[:, :, :, 3:]
										if images.shape[-1] == 6:
																__magic_name__				:							int				=      (images_depth * 255).round().astype('uint8'      )
																__magic_name__				:							List[str]				=      [
																    Image.fromarray(self.rgblike_to_depthmap(_UpperCAmelCase      )     ,      mode='I;16'      ) for image_depth in images_depth
																]
										elif images.shape[-1] == 4:
																__magic_name__				:							int				=      (images_depth * 65535.0).astype(np.uintaa      )
																__magic_name__				:							Optional[Any]				=      [Image.fromarray(_UpperCAmelCase     ,      mode='I;16'      ) for image_depth in images_depth]
										else:
																raise Exception('Not supported'      )

										return pil_images





				def  UpperCamelCase_						(  self     ,      _UpperCAmelCase     ,      _UpperCAmelCase = "pil"     ,      _UpperCAmelCase = None     ,      ):




										"""simple docstring"""




										if not isinstance(_UpperCAmelCase     ,      torch.Tensor      ):
																raise ValueError(
																    F"Input for postprocessing is in incorrect format: {type(_UpperCAmelCase      )}. We only support pytorch tensor"      )
										if output_type not in ["latent", "pt", "np", "pil"]:
																__magic_name__				:							Tuple				=      (
																    F"the output_type {output_type} is outdated and has been set to `np`. Please make sure to set it to one of these instead: "
																    '`pil`, `np`, `pt`, `latent`'
																)
																deprecate('Unsupported output_type'     ,      '1.0.0'     ,      _UpperCAmelCase     ,      standard_warn=_UpperCAmelCase      )
																__magic_name__				:							List[str]				=      'np'

										if do_denormalize is None:
																__magic_name__				:							List[str]				=      [self.config.do_normalize] * image.shape[0]

										__magic_name__				:							Dict				=      torch.stack(
										    [self.denormalize(image[i]      ) if do_denormalize[i] else image[i] for i in range(image.shape[0]      )]      )

										__magic_name__				:							Any				=      self.pt_to_numpy(_UpperCAmelCase      )

										if output_type == "np":
																if image.shape[-1] == 6:
																						__magic_name__				:							Any				=      np.stack([self.rgblike_to_depthmap(im[:, :, 3:]      ) for im in image]     ,      axis=0      )
																else:
																						__magic_name__				:							str				=      image[:, :, :, 3:]
																return image[:, :, :, :3], image_depth

										if output_type == "pil":
																return self.numpy_to_pil(_UpperCAmelCase      ), self.numpy_to_depth(_UpperCAmelCase      )
										else:
																raise Exception(F"This type {output_type} is not supported"      )






import functools
from contextlib import contextmanager

import bert_score
from packaging import version

import datasets
@contextmanager
def  __SCREAMING_SNAKE_CASE       (				)       ->  Tuple:
						def filter_log(lowercase__  :List[Any]				):
												return False if "This IS expected if you are initializing" in record.msg else True

						__magic_name__				:							Any				=      datasets.utils.logging.get_logger('transformers.modeling_utils'				)
						logger.addFilter(lowercase__				)
						try:
												yield
						finally:
												logger.removeFilter(lowercase__				)


snake_case__     							= '\\n@inproceedings{bert-score,\n  title={BERTScore: Evaluating Text Generation with BERT},\n  author={Tianyi Zhang* and Varsha Kishore* and Felix Wu* and Kilian Q. Weinberger and Yoav Artzi},\n  booktitle={International Conference on Learning Representations},\n  year={2020},\n  url={https://openreview.net/forum?id=SkeHuCVFDr}\n}\n'

snake_case__     							= '\\nBERTScore leverages the pre-trained contextual embeddings from BERT and matches words in candidate and reference\nsentences by cosine similarity.\nIt has been shown to correlate with human judgment on sentence-level and system-level evaluation.\nMoreover, BERTScore computes precision, recall, and F1 measure, which can be useful for evaluating different language\ngeneration tasks.\n\nSee the project\'s README at https://github.com/Tiiiger/bert_score#readme for more information.\n'

snake_case__     							= '\nBERTScore Metrics with the hashcode from a source against one or more references.\n\nArgs:\n    predictions (list of str): Prediction/candidate sentences.\n    references (list of str or list of list of str): Reference sentences.\n    lang (str): Language of the sentences; required (e.g. \'en\').\n    model_type (str): Bert specification, default using the suggested\n        model for the target language; has to specify at least one of\n        `model_type` or `lang`.\n    num_layers (int): The layer of representation to use,\n        default using the number of layers tuned on WMT16 correlation data.\n    verbose (bool): Turn on intermediate status update.\n    idf (bool or dict): Use idf weighting; can also be a precomputed idf_dict.\n    device (str): On which the contextual embedding model will be allocated on.\n        If this argument is None, the model lives on cuda:0 if cuda is available.\n    nthreads (int): Number of threads.\n    batch_size (int): Bert score processing batch size,\n        at least one of `model_type` or `lang`. `lang` needs to be\n        specified when `rescale_with_baseline` is True.\n    rescale_with_baseline (bool): Rescale bertscore with pre-computed baseline.\n    baseline_path (str): Customized baseline file.\n    use_fast_tokenizer (bool): `use_fast` parameter passed to HF tokenizer. New in version 0.3.10.\n\nReturns:\n    precision: Precision.\n    recall: Recall.\n    f1: F1 score.\n    hashcode: Hashcode of the library.\n\nExamples:\n\n    >>> predictions = ["hello there", "general kenobi"]\n    >>> references = ["hello there", "general kenobi"]\n    >>> bertscore = datasets.load_metric("bertscore")\n    >>> results = bertscore.compute(predictions=predictions, references=references, lang="en")\n    >>> print([round(v, 2) for v in results["f1"]])\n    [1.0, 1.0]\n'



@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION						,       _KWARGS_DESCRIPTION  )
class     snake_case__  (      datasets.Metric  ):
				def  UpperCamelCase_						(  self      ):




										"""simple docstring"""




										return datasets.MetricInfo(
										    description=_DESCRIPTION     ,      citation=_CITATION     ,      homepage='https://github.com/Tiiiger/bert_score'     ,      inputs_description=_KWARGS_DESCRIPTION     ,      features=datasets.Features(
										        {
										            'predictions': datasets.Value('string'     ,      id='sequence'      ),
										            'references': datasets.Sequence(datasets.Value('string'     ,      id='sequence'      )     ,      id='references'      ),
										        }      )     ,      codebase_urls=['https://github.com/Tiiiger/bert_score']     ,      reference_urls=[
										        'https://github.com/Tiiiger/bert_score',
										        'https://arxiv.org/abs/1904.09675',
										    ]     ,      )
				def  UpperCamelCase_						(  self     ,      _UpperCAmelCase     ,      _UpperCAmelCase     ,      _UpperCAmelCase=None     ,      _UpperCAmelCase=None     ,      _UpperCAmelCase=None     ,      _UpperCAmelCase=False     ,      _UpperCAmelCase=False     ,      _UpperCAmelCase=None     ,      _UpperCAmelCase=64     ,      _UpperCAmelCase=4     ,      _UpperCAmelCase=False     ,      _UpperCAmelCase=False     ,      _UpperCAmelCase=None     ,      _UpperCAmelCase=False     ,      ):




										"""simple docstring"""




										__magic_name__				:							List[str]				=      bert_score.utils.get_hash
										__magic_name__				:							Dict				=      bert_score.BERTScorer

										if version.parse(bert_score.__version__      ) >= version.parse('0.3.10'      ):
																__magic_name__				:							Any				=      functools.partial(_UpperCAmelCase     ,      use_fast_tokenizer=_UpperCAmelCase      )
																__magic_name__				:							Tuple				=      functools.partial(_UpperCAmelCase     ,      use_fast_tokenizer=_UpperCAmelCase      )
										elif use_fast_tokenizer:
																raise ImportWarning(
																    'To use a fast tokenizer, the module `bert-score>=0.3.10` is required, and the current version of `bert-score` doesn\'t match this condition.\n'
																    'You can install it with `pip install "bert-score>=0.3.10"`.'      )

										if model_type is None:
																assert lang is not None, "either lang or model_type should be specified"
																__magic_name__				:							List[Any]				=      bert_score.utils.langamodel[lang.lower()]

										if num_layers is None:
																__magic_name__				:							Optional[Any]				=      bert_score.utils.modelalayers[model_type]

										__magic_name__				:							List[str]				=      get_hash(
										    model=_UpperCAmelCase     ,      num_layers=_UpperCAmelCase     ,      idf=_UpperCAmelCase     ,      rescale_with_baseline=_UpperCAmelCase     ,      use_custom_baseline=baseline_path is not None     ,      )

										with filter_logging_context():
																if not hasattr(self     ,      'cached_bertscorer'      ) or self.cached_bertscorer.hash != hashcode:
																						__magic_name__				:							Optional[int]				=      scorer(
																						    model_type=_UpperCAmelCase     ,      num_layers=_UpperCAmelCase     ,      batch_size=_UpperCAmelCase     ,      nthreads=_UpperCAmelCase     ,      all_layers=_UpperCAmelCase     ,      idf=_UpperCAmelCase     ,      device=_UpperCAmelCase     ,      lang=_UpperCAmelCase     ,      rescale_with_baseline=_UpperCAmelCase     ,      baseline_path=_UpperCAmelCase     ,      )

										((__magic_name__)		, (__magic_name__)		, (__magic_name__))				:							List[Any]				=      self.cached_bertscorer.score(
										    cands=_UpperCAmelCase     ,      refs=_UpperCAmelCase     ,      verbose=_UpperCAmelCase     ,      batch_size=_UpperCAmelCase     ,      )
										__magic_name__				:							int				=      {
										    'precision': P.tolist(),
										    'recall': R.tolist(),
										    'f1': F.tolist(),
										    'hashcode': hashcode,
										}
										return output_dict
				def  UpperCamelCase_						(  self     ,      _UpperCAmelCase=None     ,      _UpperCAmelCase=None     ,      **_UpperCAmelCase      ):




										"""simple docstring"""




										if references is not None:
																__magic_name__				:							List[str]				=      [[ref] if isinstance(_UpperCAmelCase     ,      _UpperCAmelCase      ) else ref for ref in references]
										super().add_batch(predictions=_UpperCAmelCase     ,      references=_UpperCAmelCase     ,      **_UpperCAmelCase      )





				def  UpperCamelCase_						(  self     ,      _UpperCAmelCase=None     ,      _UpperCAmelCase=None     ,      **_UpperCAmelCase      ):




										"""simple docstring"""




										if isinstance(_UpperCAmelCase     ,      _UpperCAmelCase      ):
																__magic_name__				:							List[Any]				=      [reference]
										super().add(prediction=_UpperCAmelCase     ,      reference=_UpperCAmelCase     ,      **_UpperCAmelCase      )


