

import argparse
import json

import torch

from diffusers import AutoencoderKL, DDPMPipeline, DDPMScheduler, UNetaDModel, VQModel



def  snake_case_(_UpperCamelCase					,			_UpperCamelCase=1	)				->      List[Any]:



  """simple docstring"""






  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_(_UpperCamelCase					,			_UpperCamelCase=0	)				->      Dict:



  """simple docstring"""






  _snake_case		=				[]
  for old_item in old_list:
    _snake_case		=				old_item
    _snake_case		=				new_item.replace('''block.'''					,			'''resnets.'''	)
    _snake_case		=				new_item.replace('''conv_shorcut'''					,			'''conv1'''	)
    _snake_case		=				new_item.replace('''in_shortcut'''					,			'''conv_shortcut'''	)
    _snake_case		=				new_item.replace('''temb_proj'''					,			'''time_emb_proj'''	)

    _snake_case		=				shave_segments(_UpperCamelCase					,			n_shave_prefix_segments=_UpperCamelCase	)

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

  return mapping



def  snake_case_(_UpperCamelCase					,			_UpperCamelCase=0					,			_UpperCamelCase=False	)				->      Tuple:



  """simple docstring"""






  _snake_case		=				[]
  for old_item in old_list:
    _snake_case		=				old_item

    # In `model.mid`, the layer is called `attn`.
    if not in_mid:
      _snake_case		=				new_item.replace('''attn'''					,			'''attentions'''	)
    _snake_case		=				new_item.replace('''.k.'''					,			'''.key.'''	)
    _snake_case		=				new_item.replace('''.v.'''					,			'''.value.'''	)
    _snake_case		=				new_item.replace('''.q.'''					,			'''.query.'''	)

    _snake_case		=				new_item.replace('''proj_out'''					,			'''proj_attn'''	)
    _snake_case		=				new_item.replace('''norm'''					,			'''group_norm'''	)

    _snake_case		=				shave_segments(_UpperCamelCase					,			n_shave_prefix_segments=_UpperCamelCase	)
    mapping.append({'''old''': old_item, '''new''': new_item}	)

  return mapping



def  snake_case_(_UpperCamelCase					,			_UpperCamelCase					,			_UpperCamelCase					,			_UpperCamelCase=None					,			_UpperCamelCase=None					,			_UpperCamelCase=None	)				->      Dict:



  """simple docstring"""






  assert isinstance(_UpperCamelCase					,			_UpperCamelCase	), "Paths should be a list of dicts containing 'old' and 'new' keys."

  if attention_paths_to_split is not None:
    if config is None:
      raise ValueError('''Please specify the config if setting \'attention_paths_to_split\' to \'True\'.'''	)

    for path, path_map in attention_paths_to_split.items():
      _snake_case		=				old_checkpoint[path]
      _snake_case		=				old_tensor.shape[0] // 3

      _snake_case		=				(-1, channels) if len(old_tensor.shape	) == 3 else (-1)

      _snake_case		=				old_tensor.shape[0] // config.get('''num_head_channels'''					,			1	) // 3

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

      _snake_case		=				query.reshape(_UpperCamelCase	).squeeze()
      _snake_case		=				key.reshape(_UpperCamelCase	).squeeze()
      _snake_case		=				value.reshape(_UpperCamelCase	).squeeze()

  for path in paths:
    _snake_case		=				path['''new''']

    if attention_paths_to_split is not None and new_path in attention_paths_to_split:
      continue

    _snake_case		=				new_path.replace('''down.'''					,			'''down_blocks.'''	)
    _snake_case		=				new_path.replace('''up.'''					,			'''up_blocks.'''	)

    if additional_replacements is not None:
      for replacement in additional_replacements:
        _snake_case		=				new_path.replace(replacement['''old''']					,			replacement['''new''']	)

    if "attentions" in new_path:
      _snake_case		=				old_checkpoint[path['''old''']].squeeze()
    else:
      _snake_case		=				old_checkpoint[path['''old''']]



def  snake_case_(_UpperCamelCase					,			_UpperCamelCase	)				->      Tuple:



  """simple docstring"""






  _snake_case		=				{}

  _snake_case		=				checkpoint['''temb.dense.0.weight''']
  _snake_case		=				checkpoint['''temb.dense.0.bias''']
  _snake_case		=				checkpoint['''temb.dense.1.weight''']
  _snake_case		=				checkpoint['''temb.dense.1.bias''']

  _snake_case		=				checkpoint['''norm_out.weight''']
  _snake_case		=				checkpoint['''norm_out.bias''']

  _snake_case		=				checkpoint['''conv_in.weight''']
  _snake_case		=				checkpoint['''conv_in.bias''']
  _snake_case		=				checkpoint['''conv_out.weight''']
  _snake_case		=				checkpoint['''conv_out.bias''']

  _snake_case		=				len({'''.'''.join(layer.split('''.'''	)[:2]	) for layer in checkpoint if '''down''' in layer}	)
  _snake_case		=				{
      layer_id: [key for key in checkpoint if F"""down.{layer_id}""" in key] for layer_id in range(_UpperCamelCase	)
  }

  _snake_case		=				len({'''.'''.join(layer.split('''.'''	)[:2]	) for layer in checkpoint if '''up''' in layer}	)
  _snake_case		=				{layer_id: [key for key in checkpoint if F"""up.{layer_id}""" in key] for layer_id in range(_UpperCamelCase	)}

  for i in range(_UpperCamelCase	):
    _snake_case		=				(i - 1) // (config['''layers_per_block'''] + 1)

    if any('''downsample''' in layer for layer in down_blocks[i]	):
      _snake_case		=				checkpoint[
          F"""down.{i}.downsample.op.weight"""
      ]
      _snake_case		=				checkpoint[F"""down.{i}.downsample.op.bias"""]
    #            new_checkpoint[f'down_blocks.{i}.downsamplers.0.op.weight'] = checkpoint[f'down.{i}.downsample.conv.weight']
    #            new_checkpoint[f'down_blocks.{i}.downsamplers.0.op.bias'] = checkpoint[f'down.{i}.downsample.conv.bias']

    if any('''block''' in layer for layer in down_blocks[i]	):
      _snake_case		=				len(
          {'''.'''.join(shave_segments(_UpperCamelCase					,			2	).split('''.'''	)[:2]	) for layer in down_blocks[i] if '''block''' in layer}	)
      _snake_case		=				{
          layer_id: [key for key in down_blocks[i] if F"""block.{layer_id}""" in key]
          for layer_id in range(_UpperCamelCase	)
      }

      if num_blocks > 0:
        for j in range(config['''layers_per_block''']	):
          _snake_case		=				renew_resnet_paths(blocks[j]	)
          assign_to_checkpoint(_UpperCamelCase					,			_UpperCamelCase					,			_UpperCamelCase	)

    if any('''attn''' in layer for layer in down_blocks[i]	):
      _snake_case		=				len(
          {'''.'''.join(shave_segments(_UpperCamelCase					,			2	).split('''.'''	)[:2]	) for layer in down_blocks[i] if '''attn''' in layer}	)
      _snake_case		=				{
          layer_id: [key for key in down_blocks[i] if F"""attn.{layer_id}""" in key]
          for layer_id in range(_UpperCamelCase	)
      }

      if num_attn > 0:
        for j in range(config['''layers_per_block''']	):
          _snake_case		=				renew_attention_paths(attns[j]	)
          assign_to_checkpoint(_UpperCamelCase					,			_UpperCamelCase					,			_UpperCamelCase					,			config=_UpperCamelCase	)

  _snake_case		=				[key for key in checkpoint if '''mid.block_1''' in key]
  _snake_case		=				[key for key in checkpoint if '''mid.block_2''' in key]
  _snake_case		=				[key for key in checkpoint if '''mid.attn_1''' in key]

  # Mid new 2
  _snake_case		=				renew_resnet_paths(_UpperCamelCase	)
  assign_to_checkpoint(
      _UpperCamelCase					,			_UpperCamelCase					,			_UpperCamelCase					,			additional_replacements=[{'''old''': '''mid.''', '''new''': '''mid_new_2.'''}, {'''old''': '''block_1''', '''new''': '''resnets.0'''}]					,			)

  _snake_case		=				renew_resnet_paths(_UpperCamelCase	)
  assign_to_checkpoint(
      _UpperCamelCase					,			_UpperCamelCase					,			_UpperCamelCase					,			additional_replacements=[{'''old''': '''mid.''', '''new''': '''mid_new_2.'''}, {'''old''': '''block_2''', '''new''': '''resnets.1'''}]					,			)

  _snake_case		=				renew_attention_paths(_UpperCamelCase					,			in_mid=_UpperCamelCase	)
  assign_to_checkpoint(
      _UpperCamelCase					,			_UpperCamelCase					,			_UpperCamelCase					,			additional_replacements=[{'''old''': '''mid.''', '''new''': '''mid_new_2.'''}, {'''old''': '''attn_1''', '''new''': '''attentions.0'''}]					,			)

  for i in range(_UpperCamelCase	):
    _snake_case		=				num_up_blocks - 1 - i

    if any('''upsample''' in layer for layer in up_blocks[i]	):
      _snake_case		=				checkpoint[
          F"""up.{i}.upsample.conv.weight"""
      ]
      _snake_case		=				checkpoint[F"""up.{i}.upsample.conv.bias"""]

    if any('''block''' in layer for layer in up_blocks[i]	):
      _snake_case		=				len(
          {'''.'''.join(shave_segments(_UpperCamelCase					,			2	).split('''.'''	)[:2]	) for layer in up_blocks[i] if '''block''' in layer}	)
      _snake_case		=				{
          layer_id: [key for key in up_blocks[i] if F"""block.{layer_id}""" in key] for layer_id in range(_UpperCamelCase	)
      }

      if num_blocks > 0:
        for j in range(config['''layers_per_block'''] + 1	):
          _snake_case		=				{'''old''': F"""up_blocks.{i}""", '''new''': F"""up_blocks.{block_id}"""}
          _snake_case		=				renew_resnet_paths(blocks[j]	)
          assign_to_checkpoint(_UpperCamelCase					,			_UpperCamelCase					,			_UpperCamelCase					,			additional_replacements=[replace_indices]	)

    if any('''attn''' in layer for layer in up_blocks[i]	):
      _snake_case		=				len(
          {'''.'''.join(shave_segments(_UpperCamelCase					,			2	).split('''.'''	)[:2]	) for layer in up_blocks[i] if '''attn''' in layer}	)
      _snake_case		=				{
          layer_id: [key for key in up_blocks[i] if F"""attn.{layer_id}""" in key] for layer_id in range(_UpperCamelCase	)
      }

      if num_attn > 0:
        for j in range(config['''layers_per_block'''] + 1	):
          _snake_case		=				{'''old''': F"""up_blocks.{i}""", '''new''': F"""up_blocks.{block_id}"""}
          _snake_case		=				renew_attention_paths(attns[j]	)
          assign_to_checkpoint(_UpperCamelCase					,			_UpperCamelCase					,			_UpperCamelCase					,			additional_replacements=[replace_indices]	)

  _snake_case		=				{k.replace('''mid_new_2'''					,			'''mid_block'''	): v for k, v in new_checkpoint.items()}
  return new_checkpoint



def  snake_case_(_UpperCamelCase					,			_UpperCamelCase	)				->      Tuple:



  """simple docstring"""






  _snake_case		=				{}

  _snake_case		=				checkpoint['''encoder.norm_out.weight''']
  _snake_case		=				checkpoint['''encoder.norm_out.bias''']

  _snake_case		=				checkpoint['''encoder.conv_in.weight''']
  _snake_case		=				checkpoint['''encoder.conv_in.bias''']
  _snake_case		=				checkpoint['''encoder.conv_out.weight''']
  _snake_case		=				checkpoint['''encoder.conv_out.bias''']

  _snake_case		=				checkpoint['''decoder.norm_out.weight''']
  _snake_case		=				checkpoint['''decoder.norm_out.bias''']

  _snake_case		=				checkpoint['''decoder.conv_in.weight''']
  _snake_case		=				checkpoint['''decoder.conv_in.bias''']
  _snake_case		=				checkpoint['''decoder.conv_out.weight''']
  _snake_case		=				checkpoint['''decoder.conv_out.bias''']

  _snake_case		=				len({'''.'''.join(layer.split('''.'''	)[:3]	) for layer in checkpoint if '''down''' in layer}	)
  _snake_case		=				{
      layer_id: [key for key in checkpoint if F"""down.{layer_id}""" in key] for layer_id in range(_UpperCamelCase	)
  }

  _snake_case		=				len({'''.'''.join(layer.split('''.'''	)[:3]	) for layer in checkpoint if '''up''' in layer}	)
  _snake_case		=				{layer_id: [key for key in checkpoint if F"""up.{layer_id}""" in key] for layer_id in range(_UpperCamelCase	)}

  for i in range(_UpperCamelCase	):
    _snake_case		=				(i - 1) // (config['''layers_per_block'''] + 1)

    if any('''downsample''' in layer for layer in down_blocks[i]	):
      _snake_case		=				checkpoint[
          F"""encoder.down.{i}.downsample.conv.weight"""
      ]
      _snake_case		=				checkpoint[
          F"""encoder.down.{i}.downsample.conv.bias"""
      ]

    if any('''block''' in layer for layer in down_blocks[i]	):
      _snake_case		=				len(
          {'''.'''.join(shave_segments(_UpperCamelCase					,			3	).split('''.'''	)[:3]	) for layer in down_blocks[i] if '''block''' in layer}	)
      _snake_case		=				{
          layer_id: [key for key in down_blocks[i] if F"""block.{layer_id}""" in key]
          for layer_id in range(_UpperCamelCase	)
      }

      if num_blocks > 0:
        for j in range(config['''layers_per_block''']	):
          _snake_case		=				renew_resnet_paths(blocks[j]	)
          assign_to_checkpoint(_UpperCamelCase					,			_UpperCamelCase					,			_UpperCamelCase	)

    if any('''attn''' in layer for layer in down_blocks[i]	):
      _snake_case		=				len(
          {'''.'''.join(shave_segments(_UpperCamelCase					,			3	).split('''.'''	)[:3]	) for layer in down_blocks[i] if '''attn''' in layer}	)
      _snake_case		=				{
          layer_id: [key for key in down_blocks[i] if F"""attn.{layer_id}""" in key]
          for layer_id in range(_UpperCamelCase	)
      }

      if num_attn > 0:
        for j in range(config['''layers_per_block''']	):
          _snake_case		=				renew_attention_paths(attns[j]	)
          assign_to_checkpoint(_UpperCamelCase					,			_UpperCamelCase					,			_UpperCamelCase					,			config=_UpperCamelCase	)

  _snake_case		=				[key for key in checkpoint if '''mid.block_1''' in key]
  _snake_case		=				[key for key in checkpoint if '''mid.block_2''' in key]
  _snake_case		=				[key for key in checkpoint if '''mid.attn_1''' in key]

  # Mid new 2
  _snake_case		=				renew_resnet_paths(_UpperCamelCase	)
  assign_to_checkpoint(
      _UpperCamelCase					,			_UpperCamelCase					,			_UpperCamelCase					,			additional_replacements=[{'''old''': '''mid.''', '''new''': '''mid_new_2.'''}, {'''old''': '''block_1''', '''new''': '''resnets.0'''}]					,			)

  _snake_case		=				renew_resnet_paths(_UpperCamelCase	)
  assign_to_checkpoint(
      _UpperCamelCase					,			_UpperCamelCase					,			_UpperCamelCase					,			additional_replacements=[{'''old''': '''mid.''', '''new''': '''mid_new_2.'''}, {'''old''': '''block_2''', '''new''': '''resnets.1'''}]					,			)

  _snake_case		=				renew_attention_paths(_UpperCamelCase					,			in_mid=_UpperCamelCase	)
  assign_to_checkpoint(
      _UpperCamelCase					,			_UpperCamelCase					,			_UpperCamelCase					,			additional_replacements=[{'''old''': '''mid.''', '''new''': '''mid_new_2.'''}, {'''old''': '''attn_1''', '''new''': '''attentions.0'''}]					,			)

  for i in range(_UpperCamelCase	):
    _snake_case		=				num_up_blocks - 1 - i

    if any('''upsample''' in layer for layer in up_blocks[i]	):
      _snake_case		=				checkpoint[
          F"""decoder.up.{i}.upsample.conv.weight"""
      ]
      _snake_case		=				checkpoint[
          F"""decoder.up.{i}.upsample.conv.bias"""
      ]

    if any('''block''' in layer for layer in up_blocks[i]	):
      _snake_case		=				len(
          {'''.'''.join(shave_segments(_UpperCamelCase					,			3	).split('''.'''	)[:3]	) for layer in up_blocks[i] if '''block''' in layer}	)
      _snake_case		=				{
          layer_id: [key for key in up_blocks[i] if F"""block.{layer_id}""" in key] for layer_id in range(_UpperCamelCase	)
      }

      if num_blocks > 0:
        for j in range(config['''layers_per_block'''] + 1	):
          _snake_case		=				{'''old''': F"""up_blocks.{i}""", '''new''': F"""up_blocks.{block_id}"""}
          _snake_case		=				renew_resnet_paths(blocks[j]	)
          assign_to_checkpoint(_UpperCamelCase					,			_UpperCamelCase					,			_UpperCamelCase					,			additional_replacements=[replace_indices]	)

    if any('''attn''' in layer for layer in up_blocks[i]	):
      _snake_case		=				len(
          {'''.'''.join(shave_segments(_UpperCamelCase					,			3	).split('''.'''	)[:3]	) for layer in up_blocks[i] if '''attn''' in layer}	)
      _snake_case		=				{
          layer_id: [key for key in up_blocks[i] if F"""attn.{layer_id}""" in key] for layer_id in range(_UpperCamelCase	)
      }

      if num_attn > 0:
        for j in range(config['''layers_per_block'''] + 1	):
          _snake_case		=				{'''old''': F"""up_blocks.{i}""", '''new''': F"""up_blocks.{block_id}"""}
          _snake_case		=				renew_attention_paths(attns[j]	)
          assign_to_checkpoint(_UpperCamelCase					,			_UpperCamelCase					,			_UpperCamelCase					,			additional_replacements=[replace_indices]	)

  _snake_case		=				{k.replace('''mid_new_2'''					,			'''mid_block'''	): v for k, v in new_checkpoint.items()}
  _snake_case		=				checkpoint['''quant_conv.weight''']
  _snake_case		=				checkpoint['''quant_conv.bias''']
  if "quantize.embedding.weight" in checkpoint:
    _snake_case		=				checkpoint['''quantize.embedding.weight''']
  _snake_case		=				checkpoint['''post_quant_conv.weight''']
  _snake_case		=				checkpoint['''post_quant_conv.bias''']

  return new_checkpoint


if __name__ == "__main__":
 __A     						=      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.''')

 __A     						=      parser.parse_args()
 __A     						=      torch.load(args.checkpoint_path)

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

 # unet case
 __A     						=      {key.split('''.''')[0] for key in checkpoint.keys()}
 if "encoder" in key_prefix_set and "decoder" in key_prefix_set:
  __A     						=      convert_vq_autoenc_checkpoint(checkpoint, config)
 else:
  __A     						=      convert_ddpm_checkpoint(checkpoint, config)

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

 if config["_class_name"] == "VQModel":
  __A     						=      VQModel(**config)
  model.load_state_dict(converted_checkpoint)
  model.save_pretrained(args.dump_path)
 elif config["_class_name"] == "AutoencoderKL":
  __A     						=      AutoencoderKL(**config)
  model.load_state_dict(converted_checkpoint)
  model.save_pretrained(args.dump_path)
 else:
  __A     						=      UNetaDModel(**config)
  model.load_state_dict(converted_checkpoint)

  __A     						=      DDPMScheduler.from_config('''/'''.join(args.checkpoint_path.split('''/''')[:-1]))

  __A     						=      DDPMPipeline(unet=model, scheduler=scheduler)
  pipe.save_pretrained(args.dump_path)




from __future__ import annotations

from collections import Counter



def  snake_case_(_UpperCamelCase	)				->      list[int]:



  """simple docstring"""






  _snake_case		=				[True] * n
  _snake_case		=				False
  _snake_case		=				False
  _snake_case		=				True

  for i in range(3					,			int(n**0.5 + 1	)					,			2	):
    _snake_case		=				i * 2
    while index < n:
      _snake_case		=				False
      _snake_case		=				index + i

  _snake_case		=				[2]

  for i in range(3					,			_UpperCamelCase					,			2	):
    if is_prime[i]:
      primes.append(_UpperCamelCase	)

  return primes



def  snake_case_(_UpperCamelCase	)				->      list[list[int]]:



  """simple docstring"""






  _snake_case		=				str(_UpperCamelCase	)
  _snake_case		=				[]
  _snake_case		=				['''0''', '''1''', '''2''', '''3''', '''4''', '''5''', '''6''', '''7''', '''8''', '''9''']

  for duplicate in Counter(_UpperCamelCase	) - Counter(set(_UpperCamelCase	)	):
    _snake_case		=				[int(number_str.replace(_UpperCamelCase					,			_UpperCamelCase	)	) for digit in digits]
    replacements.append(_UpperCamelCase	)

  return replacements



def  snake_case_(_UpperCamelCase = 8	)				->      int:



  """simple docstring"""






  _snake_case		=				set()

  # Filter primes with less than 3 replaceable digits
  _snake_case		=				{
      x for x in set(prime_sieve(1_000_000	)	) if len(str(_UpperCamelCase	)	) - len(set(str(_UpperCamelCase	)	)	) >= 3
  }

  for prime in primes:
    if prime in numbers_checked:
      continue

    _snake_case		=				digit_replacements(_UpperCamelCase	)

    for family in replacements:
      numbers_checked.update(_UpperCamelCase	)
      _snake_case		=				primes.intersection(_UpperCamelCase	)

      if len(_UpperCamelCase	) != family_length:
        continue

      return min(_UpperCamelCase	)

  return -1


if __name__ == "__main__":
 print(solution())

