





'''simple docstring'''




import gc
import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer

from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEPipeline
from diffusers.pipelines.shap_e import ShapERenderer
from diffusers.utils import load_numpy, slow
from diffusers.utils.testing_utils import require_torch_gpu, torch_device

from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference


class 					SCREAMING_SNAKE_CASE       (_lowerCAmelCase   ,						unittest.TestCase				):
     lowerCAmelCase						     =			ShapEPipeline
     lowerCAmelCase						     =			['''prompt''']
     lowerCAmelCase						     =			['''prompt''']
     lowerCAmelCase						     =			[
         '''num_images_per_prompt''',
         '''num_inference_steps''',
         '''generator''',
         '''latents''',
         '''guidance_scale''',
         '''frame_size''',
         '''output_type''',
         '''return_dict''',
     ]
     lowerCAmelCase						     =			False


     @property
     def 				SCREAMING_SNAKE_CASE    (		self):

          '''simple docstring'''






          return 32


     @property
     def 				SCREAMING_SNAKE_CASE    (		self):

          '''simple docstring'''






          return 32


     @property
     def 				SCREAMING_SNAKE_CASE    (		self):

          '''simple docstring'''






          return self.time_input_dim * 4


     @property
     def 				SCREAMING_SNAKE_CASE    (		self):

          '''simple docstring'''






          return 8


     @property
     def 				SCREAMING_SNAKE_CASE    (		self):

          '''simple docstring'''






          __A		:					Optional[Any]						=			CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip')
          return tokenizer


     @property
     def 				SCREAMING_SNAKE_CASE    (		self):

          '''simple docstring'''






          torch.manual_seed(0)
          __A		:					Dict						=			CLIPTextConfig(
              bos_token_id=0		,      eos_token_id=2		,      hidden_size=self.text_embedder_hidden_size		,      projection_dim=self.text_embedder_hidden_size		,      intermediate_size=37		,      layer_norm_eps=1e-0_5		,      num_attention_heads=4		,      num_hidden_layers=5		,      pad_token_id=1		,      vocab_size=1000		,      )
          return CLIPTextModelWithProjection(_UpperCAmelCase)


     @property
     def 				SCREAMING_SNAKE_CASE    (		self):

          '''simple docstring'''






          torch.manual_seed(0)

          __A		:					str						=			{
              'num_attention_heads': 2,
              'attention_head_dim': 16,
              'embedding_dim': self.time_input_dim,
              'num_embeddings': 32,
              'embedding_proj_dim': self.text_embedder_hidden_size,
              'time_embed_dim': self.time_embed_dim,
              'num_layers': 1,
              'clip_embed_dim': self.time_input_dim * 2,
              'additional_embeddings': 0,
              'time_embed_act_fn': 'gelu',
              'norm_in_type': 'layer',
              'encoder_hid_proj_type': None,
              'added_emb_type': None,
          }

          __A		:					str						=			PriorTransformer(**_UpperCAmelCase)
          return model


     @property
     def 				SCREAMING_SNAKE_CASE    (		self):

          '''simple docstring'''






          torch.manual_seed(0)

          __A		:					int						=			{
              'param_shapes': (
                  (self.renderer_dim, 93),
                  (self.renderer_dim, 8),
                  (self.renderer_dim, 8),
                  (self.renderer_dim, 8),
              ),
              'd_latent': self.time_input_dim,
              'd_hidden': self.renderer_dim,
              'n_output': 12,
              'background': (
                  0.1,
                  0.1,
                  0.1,
              ),
          }
          __A		:					List[str]						=			ShapERenderer(**_UpperCAmelCase)
          return model


     def 				SCREAMING_SNAKE_CASE    (		self):

          '''simple docstring'''






          __A		:					str						=			self.dummy_prior
          __A		:					Optional[Any]						=			self.dummy_text_encoder
          __A		:					Dict						=			self.dummy_tokenizer
          __A		:					Optional[int]						=			self.dummy_renderer

          __A		:					Union[str, Any]						=			HeunDiscreteScheduler(
              beta_schedule='exp'		,      num_train_timesteps=1024		,      prediction_type='sample'		,      use_karras_sigmas=_UpperCAmelCase		,      clip_sample=_UpperCAmelCase		,      clip_sample_range=1.0		,      )
          __A		:					Optional[int]						=			{
              'prior': prior,
              'text_encoder': text_encoder,
              'tokenizer': tokenizer,
              'renderer': renderer,
              'scheduler': scheduler,
          }

          return components


     def 				SCREAMING_SNAKE_CASE    (		self		,      _UpperCAmelCase		,      _UpperCAmelCase=0):

          '''simple docstring'''






          if str(_UpperCAmelCase).startswith('mps'):
               __A		:					Optional[Any]						=			torch.manual_seed(_UpperCAmelCase)
          else:
               __A		:					Union[str, Any]						=			torch.Generator(device=_UpperCAmelCase).manual_seed(_UpperCAmelCase)
          __A		:					str						=			{
              'prompt': 'horse',
              'generator': generator,
              'num_inference_steps': 1,
              'frame_size': 32,
              'output_type': 'np',
          }
          return inputs


     def 				SCREAMING_SNAKE_CASE    (		self):

          '''simple docstring'''






          __A		:					List[Any]						=			'cpu'

          __A		:					Optional[int]						=			self.get_dummy_components()

          __A		:					Optional[Any]						=			self.pipeline_class(**_UpperCAmelCase)
          __A		:					Dict						=			pipe.to(_UpperCAmelCase)

          pipe.set_progress_bar_config(disable=_UpperCAmelCase)

          __A		:					List[str]						=			pipe(**self.get_dummy_inputs(_UpperCAmelCase))
          __A		:					Optional[int]						=			output.images[0]
          __A		:					Dict						=			image[0, -3:, -3:, -1]

          assert image.shape == (20, 32, 32, 3)

          __A		:					Tuple						=			np.array(
              [
                  0.00039216,
                  0.00039216,
                  0.00039216,
                  0.00039216,
                  0.00039216,
                  0.00039216,
                  0.00039216,
                  0.00039216,
                  0.00039216,
              ])

          assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2


     def 				SCREAMING_SNAKE_CASE    (		self):

          '''simple docstring'''






          self._test_inference_batch_consistent(batch_sizes=[1, 2])


     def 				SCREAMING_SNAKE_CASE    (		self):

          '''simple docstring'''






          __A		:					Optional[Any]						=			torch_device == 'cpu'
          __A		:					Union[str, Any]						=			True

          self._test_inference_batch_single_identical(
              batch_size=2		,      test_max_difference=_UpperCAmelCase		,      relax_max_difference=_UpperCAmelCase		,      )


     def 				SCREAMING_SNAKE_CASE    (		self):

          '''simple docstring'''






          __A		:					List[str]						=			self.get_dummy_components()
          __A		:					Union[str, Any]						=			self.pipeline_class(**_UpperCAmelCase)
          __A		:					Union[str, Any]						=			pipe.to(_UpperCAmelCase)
          pipe.set_progress_bar_config(disable=_UpperCAmelCase)

          __A		:					Optional[Any]						=			1
          __A		:					int						=			2

          __A		:					Union[str, Any]						=			self.get_dummy_inputs(_UpperCAmelCase)

          for key in inputs.keys():
               if key in self.batch_params:
                    __A		:					List[Any]						=			batch_size * [inputs[key]]

          __A		:					Dict						=			pipe(**_UpperCAmelCase		,      num_images_per_prompt=_UpperCAmelCase)[0]

          assert images.shape[0] == batch_size * num_images_per_prompt




@slow
@require_torch_gpu
class 					SCREAMING_SNAKE_CASE       (unittest.TestCase				):


     def 				SCREAMING_SNAKE_CASE    (		self):

          '''simple docstring'''






          super().tearDown()
          gc.collect()
          torch.cuda.empty_cache()


     def 				SCREAMING_SNAKE_CASE    (		self):

          '''simple docstring'''






          __A		:					Union[str, Any]						=			load_numpy(
              'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
              '/shap_e/test_shap_e_np_out.npy')
          __A		:					Union[str, Any]						=			ShapEPipeline.from_pretrained('openai/shap-e')
          __A		:					Any						=			pipe.to(_UpperCAmelCase)
          pipe.set_progress_bar_config(disable=_UpperCAmelCase)

          __A		:					Any						=			torch.Generator(device=_UpperCAmelCase).manual_seed(0)

          __A		:					List[str]						=			pipe(
              'a shark'		,      generator=_UpperCAmelCase		,      guidance_scale=15.0		,      num_inference_steps=64		,      frame_size=64		,      output_type='np'		,      ).images[0]

          assert images.shape == (20, 64, 64, 3)

          assert_mean_pixel_difference(_UpperCAmelCase		,      _UpperCAmelCase)







'''simple docstring'''



import sacrebleu as scb
from packaging import version
from sacrebleu import CHRF

import datasets


__UpperCamelCase   :							List[str]         =   """\
@inproceedings{popovic-2015-chrf,
    title = \"chr{F}: character n-gram {F}-score for automatic {MT} evaluation\",
    author = \"Popovi{\'c}, Maja\",
    booktitle = \"Proceedings of the Tenth Workshop on Statistical Machine Translation\",
    month = sep,
    year = \"2015\",
    address = \"Lisbon, Portugal\",
    publisher = \"Association for Computational Linguistics\",
    url = \"https://aclanthology.org/W15-3049\",
    doi = \"10.18653/v1/W15-3049\",
    pages = \"392--395\",
}
@inproceedings{popovic-2017-chrf,
    title = \"chr{F}++: words helping character n-grams\",
    author = \"Popovi{\'c}, Maja\",
    booktitle = \"Proceedings of the Second Conference on Machine Translation\",
    month = sep,
    year = \"2017\",
    address = \"Copenhagen, Denmark\",
    publisher = \"Association for Computational Linguistics\",
    url = \"https://aclanthology.org/W17-4770\",
    doi = \"10.18653/v1/W17-4770\",
    pages = \"612--618\",
}
@inproceedings{post-2018-call,
    title = \"A Call for Clarity in Reporting {BLEU} Scores\",
    author = \"Post, Matt\",
    booktitle = \"Proceedings of the Third Conference on Machine Translation: Research Papers\",
    month = oct,
    year = \"2018\",
    address = \"Belgium, Brussels\",
    publisher = \"Association for Computational Linguistics\",
    url = \"https://www.aclweb.org/anthology/W18-6319\",
    pages = \"186--191\",
}
"""

__UpperCamelCase   :							Union[str, Any]         =   """\
ChrF and ChrF++ are two MT evaluation metrics. They both use the F-score statistic for character n-gram matches,
and ChrF++ adds word n-grams as well which correlates more strongly with direct assessment. We use the implementation
that is already present in sacrebleu.

The implementation here is slightly different from sacrebleu in terms of the required input format. The length of
the references and hypotheses lists need to be the same, so you may need to transpose your references compared to
sacrebleu's required input format. See https://github.com/huggingface/datasets/issues/3154#issuecomment-950746534

See the README.md file at https://github.com/mjpost/sacreBLEU#chrf--chrf for more information.
"""

__UpperCamelCase   :							str         =   """
Produces ChrF(++) scores for hypotheses given reference translations.

Args:
    predictions (list of str): The predicted sentences.
    references (list of list of str): The references. There should be one reference sub-list for each prediction sentence.
    char_order (int): Character n-gram order. Defaults to `6`.
    word_order (int): Word n-gram order. If equals to `2`, the metric is referred to as chrF++. Defaults to `0`.
    beta (int): Determine the importance of recall w.r.t precision. Defaults to `2`.
    lowercase (bool): if `True`, enables case-insensitivity. Defaults to `False`.
    whitespace (bool): If `True`, include whitespaces when extracting character n-grams.
    eps_smoothing (bool): If `True`, applies epsilon smoothing similar
    to reference chrF++.py, NLTK and Moses implementations. If `False`,
    it takes into account effective match order similar to sacreBLEU < 2.0.0. Defaults to `False`.

Returns:
    'score' (float): The chrF (chrF++) score,
    'char_order' (int): The character n-gram order,
    'word_order' (int): The word n-gram order. If equals to 2, the metric is referred to as chrF++,
    'beta' (int): Determine the importance of recall w.r.t precision

Examples:
    Example 1--a simple example of calculating chrF:
        >>> prediction = [\"The relationship between cats and dogs is not exactly friendly.\", \"a good bookshop is just a genteel black hole that knows how to read.\"]
        >>> reference = [[\"The relationship between dogs and cats is not exactly friendly.\"], [\"A good bookshop is just a genteel Black Hole that knows how to read.\"]]
        >>> chrf = datasets.load_metric(\"chrf\")
        >>> results = chrf.compute(predictions=prediction, references=reference)
        >>> print(results)
        {'score': 84.64214891738334, 'char_order': 6, 'word_order': 0, 'beta': 2}

    Example 2--the same example, but with the argument word_order=2, to calculate chrF++ instead of chrF:
        >>> prediction = [\"The relationship between cats and dogs is not exactly friendly.\", \"a good bookshop is just a genteel black hole that knows how to read.\"]
        >>> reference = [[\"The relationship between dogs and cats is not exactly friendly.\"], [\"A good bookshop is just a genteel Black Hole that knows how to read.\"]]
        >>> chrf = datasets.load_metric(\"chrf\")
        >>> results = chrf.compute(predictions=prediction,
        ...                         references=reference,
        ...                         word_order=2)
        >>> print(results)
        {'score': 82.87263732906315, 'char_order': 6, 'word_order': 2, 'beta': 2}

    Example 3--the same chrF++ example as above, but with `lowercase=True` to normalize all case:
        >>> prediction = [\"The relationship between cats and dogs is not exactly friendly.\", \"a good bookshop is just a genteel black hole that knows how to read.\"]
        >>> reference = [[\"The relationship between dogs and cats is not exactly friendly.\"], [\"A good bookshop is just a genteel Black Hole that knows how to read.\"]]
        >>> chrf = datasets.load_metric(\"chrf\")
        >>> results = chrf.compute(predictions=prediction,
        ...                         references=reference,
        ...                         word_order=2,
        ...                         lowercase=True)
        >>> print(results)
        {'score': 92.12853119829202, 'char_order': 6, 'word_order': 2, 'beta': 2}
"""
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION   ,   _KWARGS_DESCRIPTION  )
class 				__SCREAMING_SNAKE_CASE							(				datasets.Metric  ):




      def 			__UpperCamelCase				(	self   )				->Union[str, Any]:



         '''simple docstring'''
         if version.parse(scb.__version__   ) < version.parse('1.4.12'   ):
            raise ImportWarning(
                'To use `sacrebleu`, the module `sacrebleu>=1.4.12` is required, and the current version of `sacrebleu` doesn\'t match this condition.\n'
                'You can install it with `pip install "sacrebleu>=1.4.12"`.'   )
         return datasets.MetricInfo(
             description=_DESCRIPTION			, citation=_CITATION			, homepage='https://github.com/mjpost/sacreBLEU#chrf--chrf'			, 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/mjpost/sacreBLEU#chrf--chrf']			, reference_urls=[
                 'https://github.com/m-popovic/chrF',
             ]			, )






      def 			__UpperCamelCase				(	self			, lowerCamelCase			, lowerCamelCase			, lowerCamelCase = CHRF.CHAR_ORDER			, lowerCamelCase = CHRF.WORD_ORDER			, lowerCamelCase = CHRF.BETA			, lowerCamelCase = False			, lowerCamelCase = False			, lowerCamelCase = False			, )				->Union[str, Any]:



         '''simple docstring'''
         __a					  =     len(references[0]   )
         if any(len(lowerCamelCase   ) != references_per_prediction for refs in references   ):
            raise ValueError('Sacrebleu requires the same number of references for each prediction'   )
         __a					  =     [[refs[i] for refs in references] for i in range(lowerCamelCase   )]

         __a					  =     CHRF(lowerCamelCase			, lowerCamelCase			, lowerCamelCase			, lowerCamelCase			, lowerCamelCase			, lowerCamelCase   )
         __a					  =     sb_chrf.corpus_score(lowerCamelCase			, lowerCamelCase   )

         return {
             "score": output.score,
             "char_order": output.char_order,
             "word_order": output.word_order,
             "beta": output.beta,
         }