


from collections import Counter
from pathlib import Path
from typing import Optional, Tuple

import yaml
class 		__magic_name__						(yaml.SafeLoader				):





     '''simple docstring'''



     def 	SCREAMING_SNAKE_CASE__						(					self:Union[str, Any]     ,		_a:List[str]   ):
       snake_case__						= [self.constructed_objects[key_node] for key_node, _ in node.value]
       snake_case__						= [tuple(_a   ) if isinstance(_a     ,		_a   ) else key for key in keys]
       snake_case__						= Counter(_a   )
       snake_case__						= [key for key in counter if counter[key] > 1]
       if duplicate_keys:
         raise TypeError(F"""Got duplicate yaml keys: {duplicate_keys}"""   )







     def 	SCREAMING_SNAKE_CASE__						(					self:Dict     ,		_a:Any     ,		_a:Any=False   ):
       snake_case__						= super().construct_mapping(_a     ,		deep=_a   )
       self._check_no_duplicates_on_constructed_node(_a   )
       return mapping







def SCREAMING_SNAKE_CASE	(			__lowerCAmelCase				)    ->				Tuple[Optional[str], str]:
  snake_case__						= list(readme_content.splitlines()				)
  if full_content and full_content[0] == "---" and "---" in full_content[1:]:
    snake_case__						= full_content[1:].index('''---'''				) + 1
    snake_case__						= '''\n'''.join(full_content[1:sep_idx]				)
    return yamlblock, "\n".join(full_content[sep_idx + 1 :]				)

  return None, "\n".join(__lowerCAmelCase				)
class 		__magic_name__						(snake_case_				):





     '''simple docstring'''



     __lowercase				:							Tuple	   =       {'train_eval_index'}  # train-eval-index in the YAML metadata

     @classmethod
     def 	SCREAMING_SNAKE_CASE__						(					cls:Tuple     ,		_a:Path   ):
       with open(_a     ,		encoding='''utf-8'''   ) as readme_file:
         snake_case__				,				snake_case__						= _split_yaml_from_readme(readme_file.read()   )
       if yaml_string is not None:
         return cls.from_yaml_string(_a   )
       else:
         return cls()

     def 	SCREAMING_SNAKE_CASE__						(					self:List[str]     ,		_a:Path   ):
       if path.exists():
         with open(_a     ,		encoding='''utf-8'''   ) as readme_file:
           snake_case__						= readme_file.read()
       else:
         snake_case__						= None
       snake_case__						= self._to_readme(_a   )
       with open(_a     ,		'''w'''     ,		encoding='''utf-8'''   ) as readme_file:
         readme_file.write(_a   )

     def 	SCREAMING_SNAKE_CASE__						(					self:Dict     ,		_a:Optional[str] = None   ):
       if readme_content is not None:
         snake_case__				,				snake_case__						= _split_yaml_from_readme(_a   )
         snake_case__						= '''---\n''' + self.to_yaml_string() + '''---\n''' + content
       else:
         snake_case__						= '''---\n''' + self.to_yaml_string() + '''---\n'''
       return full_content

     @classmethod
     def 	SCREAMING_SNAKE_CASE__						(					cls:str     ,		_a:str   ):
       snake_case__						= yaml.load(_a     ,		Loader=_NoDuplicateSafeLoader   ) or {}

       # Convert the YAML keys to DatasetMetadata fields
       snake_case__						= {
           (key.replace('''-'''     ,		'''_'''   ) if key.replace('''-'''     ,		'''_'''   ) in cls._FIELDS_WITH_DASHES else key): value
           for key, value in metadata_dict.items()
       }
       return cls(**_a   )







     def 	SCREAMING_SNAKE_CASE__						(					self:str   ):
       return yaml.safe_dump(
           {
               (key.replace('''_'''     ,		'''-'''   ) if key in self._FIELDS_WITH_DASHES else key): value
               for key, value in self.items()
           }     ,		sort_keys=_a     ,		allow_unicode=_a     ,		encoding='''utf-8'''     ,		).decode('''utf-8'''   )




lowerCamelCase__							:						List[str]							     =   {
    """image-classification""": [],
    """translation""": [],
    """image-segmentation""": [],
    """fill-mask""": [],
    """automatic-speech-recognition""": [],
    """token-classification""": [],
    """sentence-similarity""": [],
    """audio-classification""": [],
    """question-answering""": [],
    """summarization""": [],
    """zero-shot-classification""": [],
    """table-to-text""": [],
    """feature-extraction""": [],
    """other""": [],
    """multiple-choice""": [],
    """text-classification""": [],
    """text-to-image""": [],
    """text2text-generation""": [],
    """zero-shot-image-classification""": [],
    """tabular-classification""": [],
    """tabular-regression""": [],
    """image-to-image""": [],
    """tabular-to-text""": [],
    """unconditional-image-generation""": [],
    """text-retrieval""": [],
    """text-to-speech""": [],
    """object-detection""": [],
    """audio-to-audio""": [],
    """text-generation""": [],
    """conversational""": [],
    """table-question-answering""": [],
    """visual-question-answering""": [],
    """image-to-text""": [],
    """reinforcement-learning""": [],
    """voice-activity-detection""": [],
    """time-series-forecasting""": [],
    """document-question-answering""": [],
}


if __name__ == "__main__":
   from argparse import ArgumentParser

   lowerCamelCase__							:						str							     =   ArgumentParser(usage="""Validate the yaml metadata block of a README.md file.""")
   ap.add_argument("""readme_filepath""")
   lowerCamelCase__							:						Optional[Any]							     =   ap.parse_args()

   lowerCamelCase__							:						List[Any]							     =   Path(args.readme_filepath)
   lowerCamelCase__							:						Optional[Any]							     =   DatasetMetadata.from_readme(readme_filepath)
   print(dataset_metadata)
   dataset_metadata.to_readme(readme_filepath)





import random
import unittest

import torch

from diffusers import IFImgaImgSuperResolutionPipeline
from diffusers.utils import floats_tensor
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import skip_mps, torch_device

from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS
from ..test_pipelines_common import PipelineTesterMixin
from . import IFPipelineTesterMixin
@skip_mps
class 		__magic_name__						(snake_case_   ,snake_case_   ,unittest.TestCase				):





     '''simple docstring'''



     __lowercase				:							str	   =       IFImgaImgSuperResolutionPipeline
     __lowercase				:							Optional[Any]	   =       TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'width', 'height'}
     __lowercase				:							int	   =       TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({'original_image'}				)
     __lowercase				:							List[str]	   =       PipelineTesterMixin.required_optional_params - {'latents'}

     def 	SCREAMING_SNAKE_CASE__						(					self:Dict   ):
       return self._get_superresolution_dummy_components()

     def 	SCREAMING_SNAKE_CASE__						(					self:Dict     ,		_a:int     ,		_a:Optional[Any]=0   ):
       if str(_a   ).startswith('''mps'''   ):
         snake_case__						= torch.manual_seed(_a   )
       else:
         snake_case__						= torch.Generator(device=_a   ).manual_seed(_a   )

       snake_case__						= floats_tensor((1, 3, 32, 32)     ,		rng=random.Random(_a   )   ).to(_a   )
       snake_case__						= floats_tensor((1, 3, 16, 16)     ,		rng=random.Random(_a   )   ).to(_a   )

       snake_case__						= {
           '''prompt''': '''A painting of a squirrel eating a burger''',
           '''image''': image,
           '''original_image''': original_image,
           '''generator''': generator,
           '''num_inference_steps''': 2,
           '''output_type''': '''numpy''',
       }

       return inputs

     @unittest.skipIf(
         torch_device != '''cuda''' or not is_xformers_available()     ,		reason='''XFormers attention is only available with CUDA and `xformers` installed'''     ,		)
     def 	SCREAMING_SNAKE_CASE__						(					self:Union[str, Any]   ):
       self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3   )

     def 	SCREAMING_SNAKE_CASE__						(					self:Tuple   ):
       self._test_save_load_optional_components()

     @unittest.skipIf(torch_device != '''cuda'''     ,		reason='''float16 requires CUDA'''   )
     def 	SCREAMING_SNAKE_CASE__						(					self:Dict   ):
       # Due to non-determinism in save load of the hf-internal-testing/tiny-random-t5 text encoder
       super().test_save_load_floataa(expected_max_diff=1e-1   )

     def 	SCREAMING_SNAKE_CASE__						(					self:Optional[int]   ):
       self._test_attention_slicing_forward_pass(expected_max_diff=1e-2   )

     def 	SCREAMING_SNAKE_CASE__						(					self:str   ):
       self._test_save_load_local()







     def 	SCREAMING_SNAKE_CASE__						(					self:Union[str, Any]   ):
       self._test_inference_batch_single_identical(
           expected_max_diff=1e-2     ,		)

