






"""simple docstring"""
import argparse
import json

import torch

from diffusers import DDPMScheduler, LDMPipeline, UNetaDModel, VQModel

def 							snake_case (  A__      ,A__=1		):
			if n_shave_prefix_segments >= 0:
						return ".".join(path.split("."		)[n_shave_prefix_segments:]		)
			else:
						return ".".join(path.split("."		)[:n_shave_prefix_segments]		)

def 							snake_case (  A__      ,A__=0		):
			UpperCAmelCase_	:					List[Any]     	=   []
			for old_item in old_list:
						UpperCAmelCase_	:					str     	=   old_item.replace("in_layers.0"      ,"norm1"		)
						UpperCAmelCase_	:					Optional[int]     	=   new_item.replace("in_layers.2"      ,"conv1"		)

						UpperCAmelCase_	:					int     	=   new_item.replace("out_layers.0"      ,"norm2"		)
						UpperCAmelCase_	:					Optional[Any]     	=   new_item.replace("out_layers.3"      ,"conv2"		)

						UpperCAmelCase_	:					Dict     	=   new_item.replace("emb_layers.1"      ,"time_emb_proj"		)
						UpperCAmelCase_	:					List[str]     	=   new_item.replace("skip_connection"      ,"conv_shortcut"		)

						UpperCAmelCase_	:					Dict     	=   shave_segments(A__      ,n_shave_prefix_segments=A__		)

						mapping.append({"old": old_item, "new": new_item}		)

			return mapping

def 							snake_case (  A__      ,A__=0		):
			UpperCAmelCase_	:					int     	=   []
			for old_item in old_list:
						UpperCAmelCase_	:					List[str]     	=   old_item

						UpperCAmelCase_	:					Union[str, Any]     	=   new_item.replace("norm.weight"      ,"group_norm.weight"		)
						UpperCAmelCase_	:					Optional[int]     	=   new_item.replace("norm.bias"      ,"group_norm.bias"		)

						UpperCAmelCase_	:					Union[str, Any]     	=   new_item.replace("proj_out.weight"      ,"proj_attn.weight"		)
						UpperCAmelCase_	:					List[Any]     	=   new_item.replace("proj_out.bias"      ,"proj_attn.bias"		)

						UpperCAmelCase_	:					Tuple     	=   shave_segments(A__      ,n_shave_prefix_segments=A__		)

						mapping.append({"old": old_item, "new": new_item}		)

			return mapping

def 							snake_case (  A__      ,A__      ,A__      ,A__=None      ,A__=None      ,A__=None		):
			assert isinstance(A__      ,A__		), "Paths should be a list of dicts containing 'old' and 'new' keys."

			# Splits the attention layers into three variables.
			if attention_paths_to_split is not None:
						for path, path_map in attention_paths_to_split.items():
									UpperCAmelCase_	:					Union[str, Any]     	=   old_checkpoint[path]
									UpperCAmelCase_	:					Tuple     	=   old_tensor.shape[0] // 3

									UpperCAmelCase_	:					Optional[int]     	=   (-1, channels) if len(old_tensor.shape		) == 3 else (-1)

									UpperCAmelCase_	:					Union[str, Any]     	=   old_tensor.shape[0] // config["num_head_channels"] // 3

									UpperCAmelCase_	:					Optional[Any]     	=   old_tensor.reshape((num_heads, 3 * channels // num_heads) + old_tensor.shape[1:]		)
									UpperCAmelCase_	,      UpperCAmelCase_	,      UpperCAmelCase_	:					Any     	=   old_tensor.split(channels // num_heads      ,dim=1		)

									UpperCAmelCase_	:					List[Any]     	=   query.reshape(A__		)
									UpperCAmelCase_	:					int     	=   key.reshape(A__		)
									UpperCAmelCase_	:					Union[str, Any]     	=   value.reshape(A__		)

			for path in paths:
						UpperCAmelCase_	:					Any     	=   path["new"]

						# These have already been assigned
						if attention_paths_to_split is not None and new_path in attention_paths_to_split:
									continue

						# Global renaming happens here
						UpperCAmelCase_	:					int     	=   new_path.replace("middle_block.0"      ,"mid_block.resnets.0"		)
						UpperCAmelCase_	:					Tuple     	=   new_path.replace("middle_block.1"      ,"mid_block.attentions.0"		)
						UpperCAmelCase_	:					Tuple     	=   new_path.replace("middle_block.2"      ,"mid_block.resnets.1"		)

						if additional_replacements is not None:
									for replacement in additional_replacements:
												UpperCAmelCase_	:					List[str]     	=   new_path.replace(replacement["old"]      ,replacement["new"]		)

        # proj_attn.weight has to be converted from conv 1D to linear
						if "proj_attn.weight" in new_path:
									UpperCAmelCase_	:					Tuple     	=   old_checkpoint[path["old"]][:, :, 0]
						else:
									UpperCAmelCase_	:					Union[str, Any]     	=   old_checkpoint[path["old"]]

def 							snake_case (  A__      ,A__		):
			UpperCAmelCase_	:					str     	=   {}

			UpperCAmelCase_	:					List[Any]     	=   checkpoint["time_embed.0.weight"]
			UpperCAmelCase_	:					Optional[Any]     	=   checkpoint["time_embed.0.bias"]
			UpperCAmelCase_	:					Optional[int]     	=   checkpoint["time_embed.2.weight"]
			UpperCAmelCase_	:					Optional[int]     	=   checkpoint["time_embed.2.bias"]

			UpperCAmelCase_	:					List[str]     	=   checkpoint["input_blocks.0.0.weight"]
			UpperCAmelCase_	:					Dict     	=   checkpoint["input_blocks.0.0.bias"]

			UpperCAmelCase_	:					List[Any]     	=   checkpoint["out.0.weight"]
			UpperCAmelCase_	:					List[Any]     	=   checkpoint["out.0.bias"]
			UpperCAmelCase_	:					List[Any]     	=   checkpoint["out.2.weight"]
			UpperCAmelCase_	:					Optional[Any]     	=   checkpoint["out.2.bias"]

			# Retrieves the keys for the input blocks only
			UpperCAmelCase_	:					Dict     	=   len({".".join(layer.split("."		)[:2]		) for layer in checkpoint if "input_blocks" in layer}		)
			UpperCAmelCase_	:					List[str]     	=   {
			    layer_id: [key for key in checkpoint if F"""input_blocks.{layer_id}""" in key]
			    for layer_id in range(A__		)
			}

			# Retrieves the keys for the middle blocks only
			UpperCAmelCase_	:					str     	=   len({".".join(layer.split("."		)[:2]		) for layer in checkpoint if "middle_block" in layer}		)
			UpperCAmelCase_	:					Dict     	=   {
			    layer_id: [key for key in checkpoint if F"""middle_block.{layer_id}""" in key]
			    for layer_id in range(A__		)
			}

			# Retrieves the keys for the output blocks only
			UpperCAmelCase_	:					List[str]     	=   len({".".join(layer.split("."		)[:2]		) for layer in checkpoint if "output_blocks" in layer}		)
			UpperCAmelCase_	:					Optional[Any]     	=   {
			    layer_id: [key for key in checkpoint if F"""output_blocks.{layer_id}""" in key]
			    for layer_id in range(A__		)
			}

			for i in range(1      ,A__		):
						UpperCAmelCase_	:					Union[str, Any]     	=   (i - 1) // (config["num_res_blocks"] + 1)
						UpperCAmelCase_	:					Dict     	=   (i - 1) % (config["num_res_blocks"] + 1)

						UpperCAmelCase_	:					Union[str, Any]     	=   [key for key in input_blocks[i] if F"""input_blocks.{i}.0""" in key]
						UpperCAmelCase_	:					Optional[int]     	=   [key for key in input_blocks[i] if F"""input_blocks.{i}.1""" in key]

						if F"""input_blocks.{i}.0.op.weight""" in checkpoint:
									UpperCAmelCase_	:					List[str]     	=   checkpoint[
									    F"""input_blocks.{i}.0.op.weight"""
									]
									UpperCAmelCase_	:					List[Any]     	=   checkpoint[
									    F"""input_blocks.{i}.0.op.bias"""
									]
									continue

						UpperCAmelCase_	:					Any     	=   renew_resnet_paths(A__		)
						UpperCAmelCase_	:					Tuple     	=   {"old": F"""input_blocks.{i}.0""", "new": F"""down_blocks.{block_id}.resnets.{layer_in_block_id}"""}
						UpperCAmelCase_	:					Tuple     	=   {"old": "resnets.2.op", "new": "downsamplers.0.op"}
						assign_to_checkpoint(
						    A__      ,A__      ,A__      ,additional_replacements=[meta_path, resnet_op]      ,config=A__		)

						if len(A__		):
									UpperCAmelCase_	:					Union[str, Any]     	=   renew_attention_paths(A__		)
									UpperCAmelCase_	:					List[Any]     	=   {
									    "old": F"""input_blocks.{i}.1""",
									    "new": F"""down_blocks.{block_id}.attentions.{layer_in_block_id}""",
									}
									UpperCAmelCase_	:					Union[str, Any]     	=   {
									    F"""input_blocks.{i}.1.qkv.bias""": {
									        "key": F"""down_blocks.{block_id}.attentions.{layer_in_block_id}.key.bias""",
									        "query": F"""down_blocks.{block_id}.attentions.{layer_in_block_id}.query.bias""",
									        "value": F"""down_blocks.{block_id}.attentions.{layer_in_block_id}.value.bias""",
									    },
									    F"""input_blocks.{i}.1.qkv.weight""": {
									        "key": F"""down_blocks.{block_id}.attentions.{layer_in_block_id}.key.weight""",
									        "query": F"""down_blocks.{block_id}.attentions.{layer_in_block_id}.query.weight""",
									        "value": F"""down_blocks.{block_id}.attentions.{layer_in_block_id}.value.weight""",
									    },
									}
									assign_to_checkpoint(
									    A__      ,A__      ,A__      ,additional_replacements=[meta_path]      ,attention_paths_to_split=A__      ,config=A__      ,)

			UpperCAmelCase_	:					Dict     	=   middle_blocks[0]
			UpperCAmelCase_	:					List[str]     	=   middle_blocks[1]
			UpperCAmelCase_	:					List[Any]     	=   middle_blocks[2]

			UpperCAmelCase_	:					Dict     	=   renew_resnet_paths(A__		)
			assign_to_checkpoint(A__      ,A__      ,A__      ,config=A__		)

			UpperCAmelCase_	:					List[str]     	=   renew_resnet_paths(A__		)
			assign_to_checkpoint(A__      ,A__      ,A__      ,config=A__		)

			UpperCAmelCase_	:					Union[str, Any]     	=   renew_attention_paths(A__		)
			UpperCAmelCase_	:					Optional[int]     	=   {
			    "middle_block.1.qkv.bias": {
			        "key": "mid_block.attentions.0.key.bias",
			        "query": "mid_block.attentions.0.query.bias",
			        "value": "mid_block.attentions.0.value.bias",
			    },
			    "middle_block.1.qkv.weight": {
			        "key": "mid_block.attentions.0.key.weight",
			        "query": "mid_block.attentions.0.query.weight",
			        "value": "mid_block.attentions.0.value.weight",
			    },
			}
			assign_to_checkpoint(
			    A__      ,A__      ,A__      ,attention_paths_to_split=A__      ,config=A__		)

			for i in range(A__		):
						UpperCAmelCase_	:					Optional[Any]     	=   i // (config["num_res_blocks"] + 1)
						UpperCAmelCase_	:					Optional[Any]     	=   i % (config["num_res_blocks"] + 1)
						UpperCAmelCase_	:					Optional[int]     	=   [shave_segments(A__      ,2		) for name in output_blocks[i]]
						UpperCAmelCase_	:					Union[str, Any]     	=   {}

						for layer in output_block_layers:
									UpperCAmelCase_	,      UpperCAmelCase_	:					int     	=   layer.split("."		)[0], shave_segments(A__      ,1		)
									if layer_id in output_block_list:
												output_block_list[layer_id].append(A__		)
									else:
												UpperCAmelCase_	:					Dict     	=   [layer_name]

						if len(A__		) > 1:
									UpperCAmelCase_	:					Optional[Any]     	=   [key for key in output_blocks[i] if F"""output_blocks.{i}.0""" in key]
									UpperCAmelCase_	:					str     	=   [key for key in output_blocks[i] if F"""output_blocks.{i}.1""" in key]

									UpperCAmelCase_	:					List[Any]     	=   renew_resnet_paths(A__		)
									UpperCAmelCase_	:					List[Any]     	=   renew_resnet_paths(A__		)

									UpperCAmelCase_	:					List[str]     	=   {"old": F"""output_blocks.{i}.0""", "new": F"""up_blocks.{block_id}.resnets.{layer_in_block_id}"""}
									assign_to_checkpoint(A__      ,A__      ,A__      ,additional_replacements=[meta_path]      ,config=A__		)

									if ["conv.weight", "conv.bias"] in output_block_list.values():
												UpperCAmelCase_	:					Union[str, Any]     	=   list(output_block_list.values()		).index(["conv.weight", "conv.bias"]		)
												UpperCAmelCase_	:					str     	=   checkpoint[
												    F"""output_blocks.{i}.{index}.conv.weight"""
												]
												UpperCAmelCase_	:					List[str]     	=   checkpoint[
												    F"""output_blocks.{i}.{index}.conv.bias"""
												]

												# Clear attentions as they have been attributed above.
												if len(A__		) == 2:
															UpperCAmelCase_	:					Dict     	=   []

									if len(A__		):
												UpperCAmelCase_	:					Any     	=   renew_attention_paths(A__		)
												UpperCAmelCase_	:					str     	=   {
												    "old": F"""output_blocks.{i}.1""",
												    "new": F"""up_blocks.{block_id}.attentions.{layer_in_block_id}""",
												}
												UpperCAmelCase_	:					str     	=   {
												    F"""output_blocks.{i}.1.qkv.bias""": {
												        "key": F"""up_blocks.{block_id}.attentions.{layer_in_block_id}.key.bias""",
												        "query": F"""up_blocks.{block_id}.attentions.{layer_in_block_id}.query.bias""",
												        "value": F"""up_blocks.{block_id}.attentions.{layer_in_block_id}.value.bias""",
												    },
												    F"""output_blocks.{i}.1.qkv.weight""": {
												        "key": F"""up_blocks.{block_id}.attentions.{layer_in_block_id}.key.weight""",
												        "query": F"""up_blocks.{block_id}.attentions.{layer_in_block_id}.query.weight""",
												        "value": F"""up_blocks.{block_id}.attentions.{layer_in_block_id}.value.weight""",
												    },
												}
												assign_to_checkpoint(
												    A__      ,A__      ,A__      ,additional_replacements=[meta_path]      ,attention_paths_to_split=to_split if any("qkv" in key for key in attentions		) else None      ,config=A__      ,)
						else:
									UpperCAmelCase_	:					Optional[Any]     	=   renew_resnet_paths(A__      ,n_shave_prefix_segments=1		)
									for path in resnet_0_paths:
												UpperCAmelCase_	:					Any     	=   ".".join(["output_blocks", str(A__		), path["old"]]		)
												UpperCAmelCase_	:					Union[str, Any]     	=   ".".join(["up_blocks", str(A__		), "resnets", str(A__		), path["new"]]		)

												UpperCAmelCase_	:					Optional[int]     	=   checkpoint[old_path]

			return new_checkpoint


if __name__ == "__main__":
			lowerCamelCase_							      = argparse.ArgumentParser()

			parser.add_argument(
			    '''--checkpoint_path''', default=None, type=str, required=True, help='''Path to the checkpoint to convert.'''
			)

			parser.add_argument(
			    '''--config_file''',
			    default=None,
			    type=str,
			    required=True,
			    help='''The config json file corresponding to the architecture.''',
			)

			parser.add_argument('''--dump_path''', default=None, type=str, required=True, help='''Path to the output model.''')

			lowerCamelCase_							      = parser.parse_args()

			lowerCamelCase_							      = torch.load(args.checkpoint_path)

			with open(args.config_file) as f:
						lowerCamelCase_							      = json.loads(f.read())

			lowerCamelCase_							      = convert_ldm_checkpoint(checkpoint, config)

			if "ldm" in config:
						del config["ldm"]

			lowerCamelCase_							      = UNetaDModel(**config)
			model.load_state_dict(converted_checkpoint)

			try:
						lowerCamelCase_							      = DDPMScheduler.from_config('''/'''.join(args.checkpoint_path.split('''/''')[:-1]))
						lowerCamelCase_							      = VQModel.from_pretrained('''/'''.join(args.checkpoint_path.split('''/''')[:-1]))

						lowerCamelCase_							      = LDMPipeline(unet=model, scheduler=scheduler, vae=vqvae)
						pipe.save_pretrained(args.dump_path)
			except:  # noqa: E722
						model.save_pretrained(args.dump_path)






"""simple docstring"""

import argparse
import json
import os
import sys
import tempfile
import unittest
from argparse import Namespace
from dataclasses import dataclass, field
from enum import Enum
from pathlib import Path
from typing import List, Literal, Optional

import yaml

from transformers import HfArgumentParser, TrainingArguments
from transformers.hf_argparser import make_choice_type_function, string_to_bool


# Since Python 3.10, we can use the builtin `|` operator for Union types
# See PEP 604: https://peps.python.org/pep-0604
_UpperCamelCase		     =    sys.version_info >= (3, 1_0)



def       SCREAMING_SNAKE_CASE							( lowercase__=None					,					lowercase__=None   )			->						List[Any]:
 return field(default_factory=lambda: default					,					metadata=lowercase__   )






@dataclass
class 			__a					:





       """simple docstring"""


       __UpperCamelCase					:      int
       __UpperCamelCase					:      float
       __UpperCamelCase					:      str
       __UpperCamelCase					:      bool






@dataclass
class 			__a					:





       """simple docstring"""


       __UpperCamelCase					:      int    =						42
       __UpperCamelCase					:      str    =						field(default='toto'       ,	metadata={'help': 'help message'}       )






@dataclass
class 			__a					:





       """simple docstring"""


       __UpperCamelCase					:      bool    =						False
       __UpperCamelCase					:      bool    =						True
       __UpperCamelCase					:      Optional[bool]    =						None






class 			__a					(						__magic_name__       ):





       """simple docstring"""


       __UpperCamelCase					:      List[str]    =						'titi'
       __UpperCamelCase					:      Tuple    =						'toto'






class 			__a					(						__magic_name__       ):





       """simple docstring"""


       __UpperCamelCase					:      Tuple    =						'titi'
       __UpperCamelCase					:      List[Any]    =						'toto'
       __UpperCamelCase					:      List[str]    =						42






@dataclass
class 			__a					:





       """simple docstring"""


       __UpperCamelCase					:      BasicEnum    =						"toto"






       def 			SCREAMING_SNAKE_CASE_	(   self   ):





        """simple docstring"""

        lowerCAmelCase__   :				Optional[int] 			=				BasicEnum(self.foo   )






@dataclass
class 			__a					:





       """simple docstring"""


       __UpperCamelCase					:      MixedTypeEnum    =						"toto"






       def 			SCREAMING_SNAKE_CASE_	(   self   ):





        """simple docstring"""

        lowerCAmelCase__   :				List[str] 			=				MixedTypeEnum(self.foo   )






@dataclass
class 			__a					:





       """simple docstring"""


       __UpperCamelCase					:      Optional[int]    =						None
       __UpperCamelCase					:      Optional[float]    =						field(default=__magic_name__       ,	metadata={'help': 'help message'}       )
       __UpperCamelCase					:      Optional[str]    =						None
       __UpperCamelCase					:      Optional[List[str]]    =						list_field(default=[]       )
       __UpperCamelCase					:      Optional[List[int]]    =						list_field(default=[]       )






@dataclass
class 			__a					:





       """simple docstring"""


       __UpperCamelCase					:      List[int]    =						list_field(default=[]       )
       __UpperCamelCase					:      List[int]    =						list_field(default=[1, 2, 3]       )
       __UpperCamelCase					:      List[str]    =						list_field(default=['Hallo', 'Bonjour', 'Hello']       )
       __UpperCamelCase					:      List[float]    =						list_field(default=[0.1, 0.2, 0.3]       )






@dataclass
class 			__a					:





       """simple docstring"""


       __UpperCamelCase					:      List[int]    =						field()
       __UpperCamelCase					:      str    =						field()
       __UpperCamelCase					:      BasicEnum    =						field()






       def 			SCREAMING_SNAKE_CASE_	(   self   ):





        """simple docstring"""

        lowerCAmelCase__   :				Optional[Any] 			=				BasicEnum(self.required_enum   )






@dataclass
class 			__a					:





       """simple docstring"""


       __UpperCamelCase					:      int
       __UpperCamelCase					:      "BasicEnum"    =						field()
       __UpperCamelCase					:      "Optional[bool]"    =						None
       __UpperCamelCase					:      "str"    =						field(default='toto'       ,	metadata={'help': 'help message'}       )
       __UpperCamelCase					:      "List[str]"    =						list_field(default=['Hallo', 'Bonjour', 'Hello']       )


if is_python_no_less_than_3_10:






    @dataclass
    class 			__a					:





           """simple docstring"""


           __UpperCamelCase					:      bool    =						False
           __UpperCamelCase					:      bool    =						True
           __UpperCamelCase					:      bool | None    =						None






    @dataclass
    class 			__a					:





           """simple docstring"""


           __UpperCamelCase					:      int | None    =						None
           __UpperCamelCase					:      float | None    =						field(default=__magic_name__       ,	metadata={'help': 'help message'}       )
           __UpperCamelCase					:      str | None    =						None
           __UpperCamelCase					:      list[str] | None    =						list_field(default=[]       )
           __UpperCamelCase					:      list[int] | None    =						list_field(default=[]       )






class 			__a					(						unittest.TestCase       ):





       """simple docstring"""


       def 			SCREAMING_SNAKE_CASE_	(   self			,					snake_case			,					snake_case   ):





        """simple docstring"""

        self.assertEqual(len(a._actions   )			,					len(b._actions   )   )
        for x, y in zip(a._actions			,					b._actions   ):
         lowerCAmelCase__   :				Union[str, Any] 			=				{k: v for k, v in vars(snake_case   ).items() if k != "container"}
         lowerCAmelCase__   :				Union[str, Any] 			=				{k: v for k, v in vars(snake_case   ).items() if k != "container"}

         # Choices with mixed type have custom function as "type"
         # So we need to compare results directly for equality
         if xx.get("choices"			,					snake_case   ) and yy.get("choices"			,					snake_case   ):
          for expected_choice in yy["choices"] + xx["choices"]:
           self.assertEqual(xx["type"](snake_case   )			,					yy["type"](snake_case   )   )
          del xx["type"], yy["type"]

         self.assertEqual(snake_case			,					snake_case   )






       def 			SCREAMING_SNAKE_CASE_	(   self   ):





        """simple docstring"""

        lowerCAmelCase__   :				Union[str, Any] 			=				HfArgumentParser(snake_case   )

        lowerCAmelCase__   :				Optional[int] 			=				argparse.ArgumentParser()
        expected.add_argument("--foo"			,					type=snake_case			,					required=snake_case   )
        expected.add_argument("--bar"			,					type=snake_case			,					required=snake_case   )
        expected.add_argument("--baz"			,					type=snake_case			,					required=snake_case   )
        expected.add_argument("--flag"			,					type=snake_case			,					default=snake_case			,					const=snake_case			,					nargs="?"   )
        self.argparsersEqual(snake_case			,					snake_case   )

        lowerCAmelCase__   :				List[Any] 			=				["--foo", "1", "--baz", "quux", "--bar", "0.5"]
        ((lowerCAmelCase__)			,						)   :				Dict 			=				parser.parse_args_into_dataclasses(snake_case			,					look_for_args_file=snake_case   )
        self.assertFalse(example.flag   )






       def 			SCREAMING_SNAKE_CASE_	(   self   ):





        """simple docstring"""

        lowerCAmelCase__   :				Tuple 			=				HfArgumentParser(snake_case   )

        lowerCAmelCase__   :				Optional[int] 			=				argparse.ArgumentParser()
        expected.add_argument("--foo"			,					default=42			,					type=snake_case   )
        expected.add_argument("--baz"			,					default="toto"			,					type=snake_case			,					help="help message"   )
        self.argparsersEqual(snake_case			,					snake_case   )






       def 			SCREAMING_SNAKE_CASE_	(   self   ):





        """simple docstring"""

        lowerCAmelCase__   :				Optional[Any] 			=				argparse.ArgumentParser()
        expected.add_argument("--foo"			,					type=snake_case			,					default=snake_case			,					const=snake_case			,					nargs="?"   )
        expected.add_argument("--baz"			,					type=snake_case			,					default=snake_case			,					const=snake_case			,					nargs="?"   )
        # A boolean no_* argument always has to come after its "default: True" regular counter-part
        # and its default must be set to False
        expected.add_argument("--no_baz"			,					action="store_false"			,					default=snake_case			,					dest="baz"   )
        expected.add_argument("--opt"			,					type=snake_case			,					default=snake_case   )

        lowerCAmelCase__   :				Optional[Any] 			=				[WithDefaultBoolExample]
        if is_python_no_less_than_3_10:
         dataclass_types.append(snake_case   )

        for dataclass_type in dataclass_types:
         lowerCAmelCase__   :				Optional[Any] 			=				HfArgumentParser(snake_case   )
         self.argparsersEqual(snake_case			,					snake_case   )

         lowerCAmelCase__   :				Union[str, Any] 			=				parser.parse_args([]   )
         self.assertEqual(snake_case			,					Namespace(foo=snake_case			,					baz=snake_case			,					opt=snake_case   )   )

         lowerCAmelCase__   :				List[str] 			=				parser.parse_args(["--foo", "--no_baz"]   )
         self.assertEqual(snake_case			,					Namespace(foo=snake_case			,					baz=snake_case			,					opt=snake_case   )   )

         lowerCAmelCase__   :				Optional[Any] 			=				parser.parse_args(["--foo", "--baz"]   )
         self.assertEqual(snake_case			,					Namespace(foo=snake_case			,					baz=snake_case			,					opt=snake_case   )   )

         lowerCAmelCase__   :				List[Any] 			=				parser.parse_args(["--foo", "True", "--baz", "True", "--opt", "True"]   )
         self.assertEqual(snake_case			,					Namespace(foo=snake_case			,					baz=snake_case			,					opt=snake_case   )   )

         lowerCAmelCase__   :				Optional[int] 			=				parser.parse_args(["--foo", "False", "--baz", "False", "--opt", "False"]   )
         self.assertEqual(snake_case			,					Namespace(foo=snake_case			,					baz=snake_case			,					opt=snake_case   )   )






       def 			SCREAMING_SNAKE_CASE_	(   self   ):





        """simple docstring"""

        lowerCAmelCase__   :				Tuple 			=				HfArgumentParser(snake_case   )

        lowerCAmelCase__   :				Optional[Any] 			=				argparse.ArgumentParser()
        expected.add_argument(
            "--foo"			,					default="toto"			,					choices=["titi", "toto", 42]			,					type=make_choice_type_function(["titi", "toto", 42]   )			,					)
        self.argparsersEqual(snake_case			,					snake_case   )

        lowerCAmelCase__   :				Union[str, Any] 			=				parser.parse_args([]   )
        self.assertEqual(args.foo			,					"toto"   )
        lowerCAmelCase__   :				List[str] 			=				parser.parse_args_into_dataclasses([]   )[0]
        self.assertEqual(enum_ex.foo			,					MixedTypeEnum.toto   )

        lowerCAmelCase__   :				List[Any] 			=				parser.parse_args(["--foo", "titi"]   )
        self.assertEqual(args.foo			,					"titi"   )
        lowerCAmelCase__   :				Any 			=				parser.parse_args_into_dataclasses(["--foo", "titi"]   )[0]
        self.assertEqual(enum_ex.foo			,					MixedTypeEnum.titi   )

        lowerCAmelCase__   :				Tuple 			=				parser.parse_args(["--foo", "42"]   )
        self.assertEqual(args.foo			,					42   )
        lowerCAmelCase__   :				Tuple 			=				parser.parse_args_into_dataclasses(["--foo", "42"]   )[0]
        self.assertEqual(enum_ex.foo			,					MixedTypeEnum.fourtytwo   )






       def 			SCREAMING_SNAKE_CASE_	(   self   ):





        """simple docstring"""

        @dataclass
        class 			__a					:





               """simple docstring"""


               __UpperCamelCase					:      Literal["titi", "toto", 42]    =						"toto"




        lowerCAmelCase__   :				Dict 			=				HfArgumentParser(snake_case   )

        lowerCAmelCase__   :				Dict 			=				argparse.ArgumentParser()
        expected.add_argument(
            "--foo"			,					default="toto"			,					choices=("titi", "toto", 42)			,					type=make_choice_type_function(["titi", "toto", 42]   )			,					)
        self.argparsersEqual(snake_case			,					snake_case   )

        lowerCAmelCase__   :				int 			=				parser.parse_args([]   )
        self.assertEqual(args.foo			,					"toto"   )

        lowerCAmelCase__   :				Optional[int] 			=				parser.parse_args(["--foo", "titi"]   )
        self.assertEqual(args.foo			,					"titi"   )

        lowerCAmelCase__   :				int 			=				parser.parse_args(["--foo", "42"]   )
        self.assertEqual(args.foo			,					42   )






       def 			SCREAMING_SNAKE_CASE_	(   self   ):





        """simple docstring"""

        lowerCAmelCase__   :				str 			=				HfArgumentParser(snake_case   )

        lowerCAmelCase__   :				Union[str, Any] 			=				argparse.ArgumentParser()
        expected.add_argument("--foo_int"			,					nargs="+"			,					default=[]			,					type=snake_case   )
        expected.add_argument("--bar_int"			,					nargs="+"			,					default=[1, 2, 3]			,					type=snake_case   )
        expected.add_argument("--foo_str"			,					nargs="+"			,					default=["Hallo", "Bonjour", "Hello"]			,					type=snake_case   )
        expected.add_argument("--foo_float"			,					nargs="+"			,					default=[0.1, 0.2, 0.3]			,					type=snake_case   )

        self.argparsersEqual(snake_case			,					snake_case   )

        lowerCAmelCase__   :				Tuple 			=				parser.parse_args([]   )
        self.assertEqual(
            snake_case			,					Namespace(foo_int=[]			,					bar_int=[1, 2, 3]			,					foo_str=["Hallo", "Bonjour", "Hello"]			,					foo_float=[0.1, 0.2, 0.3]   )			,					)

        lowerCAmelCase__   :				List[Any] 			=				parser.parse_args("--foo_int 1 --bar_int 2 3 --foo_str a b c --foo_float 0.1 0.7".split()   )
        self.assertEqual(snake_case			,					Namespace(foo_int=[1]			,					bar_int=[2, 3]			,					foo_str=["a", "b", "c"]			,					foo_float=[0.1, 0.7]   )   )






       def 			SCREAMING_SNAKE_CASE_	(   self   ):





        """simple docstring"""

        lowerCAmelCase__   :				Dict 			=				argparse.ArgumentParser()
        expected.add_argument("--foo"			,					default=snake_case			,					type=snake_case   )
        expected.add_argument("--bar"			,					default=snake_case			,					type=snake_case			,					help="help message"   )
        expected.add_argument("--baz"			,					default=snake_case			,					type=snake_case   )
        expected.add_argument("--ces"			,					nargs="+"			,					default=[]			,					type=snake_case   )
        expected.add_argument("--des"			,					nargs="+"			,					default=[]			,					type=snake_case   )

        lowerCAmelCase__   :				Optional[Any] 			=				[OptionalExample]
        if is_python_no_less_than_3_10:
         dataclass_types.append(snake_case   )

        for dataclass_type in dataclass_types:
         lowerCAmelCase__   :				Tuple 			=				HfArgumentParser(snake_case   )

         self.argparsersEqual(snake_case			,					snake_case   )

         lowerCAmelCase__   :				Any 			=				parser.parse_args([]   )
         self.assertEqual(snake_case			,					Namespace(foo=snake_case			,					bar=snake_case			,					baz=snake_case			,					ces=[]			,					des=[]   )   )

         lowerCAmelCase__   :				List[str] 			=				parser.parse_args("--foo 12 --bar 3.14 --baz 42 --ces a b c --des 1 2 3".split()   )
         self.assertEqual(snake_case			,					Namespace(foo=12			,					bar=3.14			,					baz="42"			,					ces=["a", "b", "c"]			,					des=[1, 2, 3]   )   )






       def 			SCREAMING_SNAKE_CASE_	(   self   ):





        """simple docstring"""

        lowerCAmelCase__   :				Optional[Any] 			=				HfArgumentParser(snake_case   )

        lowerCAmelCase__   :				List[Any] 			=				argparse.ArgumentParser()
        expected.add_argument("--required_list"			,					nargs="+"			,					type=snake_case			,					required=snake_case   )
        expected.add_argument("--required_str"			,					type=snake_case			,					required=snake_case   )
        expected.add_argument(
            "--required_enum"			,					type=make_choice_type_function(["titi", "toto"]   )			,					choices=["titi", "toto"]			,					required=snake_case			,					)
        self.argparsersEqual(snake_case			,					snake_case   )






       def 			SCREAMING_SNAKE_CASE_	(   self   ):





        """simple docstring"""

        lowerCAmelCase__   :				Dict 			=				HfArgumentParser(snake_case   )

        lowerCAmelCase__   :				Optional[Any] 			=				argparse.ArgumentParser()
        expected.add_argument("--foo"			,					type=snake_case			,					required=snake_case   )
        expected.add_argument(
            "--required_enum"			,					type=make_choice_type_function(["titi", "toto"]   )			,					choices=["titi", "toto"]			,					required=snake_case			,					)
        expected.add_argument("--opt"			,					type=snake_case			,					default=snake_case   )
        expected.add_argument("--baz"			,					default="toto"			,					type=snake_case			,					help="help message"   )
        expected.add_argument("--foo_str"			,					nargs="+"			,					default=["Hallo", "Bonjour", "Hello"]			,					type=snake_case   )
        self.argparsersEqual(snake_case			,					snake_case   )






       def 			SCREAMING_SNAKE_CASE_	(   self   ):





        """simple docstring"""

        lowerCAmelCase__   :				Any 			=				HfArgumentParser(snake_case   )

        lowerCAmelCase__   :				List[Any] 			=				{
            "foo": 12,
            "bar": 3.14,
            "baz": "42",
            "flag": True,
        }

        lowerCAmelCase__   :				Tuple 			=				parser.parse_dict(snake_case   )[0]
        lowerCAmelCase__   :				Any 			=				BasicExample(**snake_case   )
        self.assertEqual(snake_case			,					snake_case   )






       def 			SCREAMING_SNAKE_CASE_	(   self   ):





        """simple docstring"""

        lowerCAmelCase__   :				Union[str, Any] 			=				HfArgumentParser(snake_case   )

        lowerCAmelCase__   :				List[Any] 			=				{
            "foo": 12,
            "bar": 3.14,
            "baz": "42",
            "flag": True,
            "extra": 42,
        }

        self.assertRaises(snake_case			,					parser.parse_dict			,					snake_case			,					allow_extra_keys=snake_case   )






       def 			SCREAMING_SNAKE_CASE_	(   self   ):





        """simple docstring"""

        lowerCAmelCase__   :				Union[str, Any] 			=				HfArgumentParser(snake_case   )

        lowerCAmelCase__   :				Optional[Any] 			=				{
            "foo": 12,
            "bar": 3.14,
            "baz": "42",
            "flag": True,
        }
        with tempfile.TemporaryDirectory() as tmp_dir:
         lowerCAmelCase__   :				int 			=				os.path.join(snake_case			,					"temp_json"   )
         os.mkdir(snake_case   )
         with open(temp_local_path + ".json"			,					"w+"   ) as f:
          json.dump(snake_case			,					snake_case   )
         lowerCAmelCase__   :				Any 			=				parser.parse_yaml_file(Path(temp_local_path + ".json"   )   )[0]

        lowerCAmelCase__   :				str 			=				BasicExample(**snake_case   )
        self.assertEqual(snake_case			,					snake_case   )






       def 			SCREAMING_SNAKE_CASE_	(   self   ):





        """simple docstring"""

        lowerCAmelCase__   :				str 			=				HfArgumentParser(snake_case   )

        lowerCAmelCase__   :				int 			=				{
            "foo": 12,
            "bar": 3.14,
            "baz": "42",
            "flag": True,
        }
        with tempfile.TemporaryDirectory() as tmp_dir:
         lowerCAmelCase__   :				Optional[Any] 			=				os.path.join(snake_case			,					"temp_yaml"   )
         os.mkdir(snake_case   )
         with open(temp_local_path + ".yaml"			,					"w+"   ) as f:
          yaml.dump(snake_case			,					snake_case   )
         lowerCAmelCase__   :				Dict 			=				parser.parse_yaml_file(Path(temp_local_path + ".yaml"   )   )[0]
        lowerCAmelCase__   :				int 			=				BasicExample(**snake_case   )
        self.assertEqual(snake_case			,					snake_case   )






       def 			SCREAMING_SNAKE_CASE_	(   self   ):





        """simple docstring"""

        lowerCAmelCase__   :				Union[str, Any] 			=				HfArgumentParser(snake_case   )
        self.assertIsNotNone(snake_case   )






