





'''simple docstring'''




import argparse
import io

import requests
import torch
from omegaconf import OmegaConf

from diffusers import AutoencoderKL
from diffusers.pipelines.stable_diffusion.convert_from_ckpt import (
    assign_to_checkpoint,
    conv_attn_to_linear,
    create_vae_diffusers_config,
    renew_vae_attention_paths,
    renew_vae_resnet_paths,
)






def        _lowerCAmelCase			(  __snake_case  : Optional[Any] ,							__snake_case  : str			)     ->     Optional[int]:
     __A						: List[Any]      =       checkpoint

     __A						: Union[str, Any]      =       {}

     __A						: Any      =       vae_state_dict['encoder.conv_in.weight']
     __A						: Optional[Any]      =       vae_state_dict['encoder.conv_in.bias']
     __A						: Dict      =       vae_state_dict['encoder.conv_out.weight']
     __A						: int      =       vae_state_dict['encoder.conv_out.bias']
     __A						: str      =       vae_state_dict['encoder.norm_out.weight']
     __A						: Dict      =       vae_state_dict['encoder.norm_out.bias']

     __A						: int      =       vae_state_dict['decoder.conv_in.weight']
     __A						: List[Any]      =       vae_state_dict['decoder.conv_in.bias']
     __A						: List[str]      =       vae_state_dict['decoder.conv_out.weight']
     __A						: int      =       vae_state_dict['decoder.conv_out.bias']
     __A						: str      =       vae_state_dict['decoder.norm_out.weight']
     __A						: Union[str, Any]      =       vae_state_dict['decoder.norm_out.bias']

     __A						: Dict      =       vae_state_dict['quant_conv.weight']
     __A						: Optional[int]      =       vae_state_dict['quant_conv.bias']
     __A						: int      =       vae_state_dict['post_quant_conv.weight']
     __A						: List[str]      =       vae_state_dict['post_quant_conv.bias']

     # Retrieves the keys for the encoder down blocks only
     __A						: Any      =       len({'.'.join(layer.split('.'			)[:3]			) for layer in vae_state_dict if 'encoder.down' in layer}			)
     __A						: List[Any]      =       {
         layer_id: [key for key in vae_state_dict if f'down.{layer_id}' in key] for layer_id in range(__snake_case			)
     }

     # Retrieves the keys for the decoder up blocks only
     __A						: Union[str, Any]      =       len({'.'.join(layer.split('.'			)[:3]			) for layer in vae_state_dict if 'decoder.up' in layer}			)
     __A						: Tuple      =       {
         layer_id: [key for key in vae_state_dict if f'up.{layer_id}' in key] for layer_id in range(__snake_case			)
     }

     for i in range(__snake_case			):
          __A						: Tuple      =       [key for key in down_blocks[i] if f'down.{i}' in key and f'down.{i}.downsample' not in key]

          if f'encoder.down.{i}.downsample.conv.weight' in vae_state_dict:
               __A						: Tuple      =       vae_state_dict.pop(
                   f'encoder.down.{i}.downsample.conv.weight'			)
               __A						: List[str]      =       vae_state_dict.pop(
                   f'encoder.down.{i}.downsample.conv.bias'			)

          __A						: Union[str, Any]      =       renew_vae_resnet_paths(__snake_case			)
          __A						: int      =       {'old': f'down.{i}.block', 'new': f'down_blocks.{i}.resnets'}
          assign_to_checkpoint(__snake_case ,							__snake_case ,							__snake_case ,							additional_replacements=[meta_path] ,							config=__snake_case			)

     __A						: Any      =       [key for key in vae_state_dict if 'encoder.mid.block' in key]
     __A						: Union[str, Any]      =       2
     for i in range(1 ,							num_mid_res_blocks + 1			):
          __A						: Any      =       [key for key in mid_resnets if f'encoder.mid.block_{i}' in key]

          __A						: str      =       renew_vae_resnet_paths(__snake_case			)
          __A						: Union[str, Any]      =       {'old': f'mid.block_{i}', 'new': f'mid_block.resnets.{i - 1}'}
          assign_to_checkpoint(__snake_case ,							__snake_case ,							__snake_case ,							additional_replacements=[meta_path] ,							config=__snake_case			)

     __A						: Any      =       [key for key in vae_state_dict if 'encoder.mid.attn' in key]
     __A						: List[Any]      =       renew_vae_attention_paths(__snake_case			)
     __A						: Tuple      =       {'old': 'mid.attn_1', 'new': 'mid_block.attentions.0'}
     assign_to_checkpoint(__snake_case ,							__snake_case ,							__snake_case ,							additional_replacements=[meta_path] ,							config=__snake_case			)
     conv_attn_to_linear(__snake_case			)

     for i in range(__snake_case			):
          __A						: Any      =       num_up_blocks - 1 - i
          __A						: Tuple      =       [
              key for key in up_blocks[block_id] if f'up.{block_id}' in key and f'up.{block_id}.upsample' not in key
          ]

          if f'decoder.up.{block_id}.upsample.conv.weight' in vae_state_dict:
               __A						: str      =       vae_state_dict[
                   f'decoder.up.{block_id}.upsample.conv.weight'
               ]
               __A						: Tuple      =       vae_state_dict[
                   f'decoder.up.{block_id}.upsample.conv.bias'
               ]

          __A						: int      =       renew_vae_resnet_paths(__snake_case			)
          __A						: int      =       {'old': f'up.{block_id}.block', 'new': f'up_blocks.{i}.resnets'}
          assign_to_checkpoint(__snake_case ,							__snake_case ,							__snake_case ,							additional_replacements=[meta_path] ,							config=__snake_case			)

     __A						: List[str]      =       [key for key in vae_state_dict if 'decoder.mid.block' in key]
     __A						: str      =       2
     for i in range(1 ,							num_mid_res_blocks + 1			):
          __A						: List[Any]      =       [key for key in mid_resnets if f'decoder.mid.block_{i}' in key]

          __A						: Any      =       renew_vae_resnet_paths(__snake_case			)
          __A						: Optional[int]      =       {'old': f'mid.block_{i}', 'new': f'mid_block.resnets.{i - 1}'}
          assign_to_checkpoint(__snake_case ,							__snake_case ,							__snake_case ,							additional_replacements=[meta_path] ,							config=__snake_case			)

     __A						: Union[str, Any]      =       [key for key in vae_state_dict if 'decoder.mid.attn' in key]
     __A						: Optional[Any]      =       renew_vae_attention_paths(__snake_case			)
     __A						: Union[str, Any]      =       {'old': 'mid.attn_1', 'new': 'mid_block.attentions.0'}
     assign_to_checkpoint(__snake_case ,							__snake_case ,							__snake_case ,							additional_replacements=[meta_path] ,							config=__snake_case			)
     conv_attn_to_linear(__snake_case			)
     return new_checkpoint






def        _lowerCAmelCase			(  __snake_case  : str ,							__snake_case  : str ,							)     ->     int:
     # Only support V1
     __A						: List[str]      =       requests.get(
         ' https://raw.githubusercontent.com/CompVis/stable-diffusion/main/configs/stable-diffusion/v1-inference.yaml'			)
     __A						: Dict      =       io.BytesIO(r.content			)

     __A						: int      =       OmegaConf.load(__snake_case			)
     __A						: Union[str, Any]      =       5_12
     __A						: Optional[Any]      =       'cuda' if torch.cuda.is_available() else 'cpu'
     if checkpoint_path.endswith('safetensors'			):
          from safetensors import safe_open

          __A						: Optional[Any]      =       {}
          with safe_open(__snake_case ,							framework='pt' ,							device='cpu'			) as f:
               for key in f.keys():
                    __A						: Any      =       f.get_tensor(__snake_case			)
     else:
          __A						: str      =       torch.load(__snake_case ,							map_location=__snake_case			)['state_dict']

     # Convert the VAE model.
     __A						: Optional[Any]      =       create_vae_diffusers_config(__snake_case ,							image_size=__snake_case			)
     __A						: Union[str, Any]      =       custom_convert_ldm_vae_checkpoint(__snake_case ,							__snake_case			)

     __A						: Optional[Any]      =       AutoencoderKL(**__snake_case			)
     vae.load_state_dict(__snake_case			)
     vae.save_pretrained(__snake_case			)


if __name__ == "__main__":
  lowercase__    :      List[str]						=    argparse.ArgumentParser()

  parser.add_argument('''--vae_pt_path''', default=None, type=str, required=True, help='''Path to the VAE.pt to convert.''')
  parser.add_argument('''--dump_path''', default=None, type=str, required=True, help='''Path to the VAE.pt to convert.''')

  lowercase__    :      Optional[Any]						=    parser.parse_args()

  vae_pt_to_vae_diffuser(args.vae_pt_path, args.dump_path)






'''simple docstring'''




import unittest

from transformers import (
    MODEL_FOR_OBJECT_DETECTION_MAPPING,
    AutoFeatureExtractor,
    AutoModelForObjectDetection,
    ObjectDetectionPipeline,
    is_vision_available,
    pipeline,
)
from transformers.testing_utils import (
    is_pipeline_test,
    nested_simplify,
    require_pytesseract,
    require_tf,
    require_timm,
    require_torch,
    require_vision,
    slow,
)

from .test_pipelines_common import ANY


if is_vision_available():
  from PIL import Image
else:


  class  SCREAMING_SNAKE_CASE    :


       @staticmethod
       def 							SCREAMING_SNAKE_CASE  (						*_UpperCAmelCase						,	**_UpperCAmelCase):

            '''simple docstring'''






            pass


@is_pipeline_test
@require_vision
@require_timm
@require_torch
class  SCREAMING_SNAKE_CASE    (unittest.TestCase							):
     lowerCAmelCase					=       MODEL_FOR_OBJECT_DETECTION_MAPPING


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

          '''simple docstring'''






          __A						: Dict      =       ObjectDetectionPipeline(model=_UpperCAmelCase						,	image_processor=_UpperCAmelCase)
          return object_detector, ["./tests/fixtures/tests_samples/COCO/000000039769.png"]


     def 							SCREAMING_SNAKE_CASE  (						self						,	_UpperCAmelCase						,	_UpperCAmelCase):

          '''simple docstring'''






          __A						: str      =       object_detector('./tests/fixtures/tests_samples/COCO/000000039769.png'						,	threshold=0.0)

          self.assertGreater(len(_UpperCAmelCase)						,	0)
          for detected_object in outputs:
               self.assertEqual(
                   _UpperCAmelCase						,	{
                       'score': ANY(_UpperCAmelCase),
                       'label': ANY(_UpperCAmelCase),
                       'box': {'xmin': ANY(_UpperCAmelCase), 'ymin': ANY(_UpperCAmelCase), 'xmax': ANY(_UpperCAmelCase), 'ymax': ANY(_UpperCAmelCase)},
                   }						,	)

          import datasets

          __A						: Tuple      =       datasets.load_dataset('hf-internal-testing/fixtures_image_utils'						,	'image'						,	split='test')

          __A						: List[str]      =       [
              Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'),
              'http://images.cocodataset.org/val2017/000000039769.jpg',
              # RGBA
              dataset[0]['file'],
              # LA
              dataset[1]['file'],
              # L
              dataset[2]['file'],
          ]
          __A						: Union[str, Any]      =       object_detector(_UpperCAmelCase						,	threshold=0.0)

          self.assertEqual(len(_UpperCAmelCase)						,	len(_UpperCAmelCase))
          for outputs in batch_outputs:
               self.assertGreater(len(_UpperCAmelCase)						,	0)
               for detected_object in outputs:
                    self.assertEqual(
                        _UpperCAmelCase						,	{
                            'score': ANY(_UpperCAmelCase),
                            'label': ANY(_UpperCAmelCase),
                            'box': {'xmin': ANY(_UpperCAmelCase), 'ymin': ANY(_UpperCAmelCase), 'xmax': ANY(_UpperCAmelCase), 'ymax': ANY(_UpperCAmelCase)},
                        }						,	)


     @require_tf
     @unittest.skip('Object detection not implemented in TF')
     def 							SCREAMING_SNAKE_CASE  (						self):

          '''simple docstring'''






          pass


     @require_torch
     def 							SCREAMING_SNAKE_CASE  (						self):

          '''simple docstring'''






          __A						: List[str]      =       'hf-internal-testing/tiny-detr-mobilenetsv3'

          __A						: Any      =       AutoModelForObjectDetection.from_pretrained(_UpperCAmelCase)
          __A						: int      =       AutoFeatureExtractor.from_pretrained(_UpperCAmelCase)
          __A						: Any      =       ObjectDetectionPipeline(model=_UpperCAmelCase						,	feature_extractor=_UpperCAmelCase)

          __A						: Dict      =       object_detector('http://images.cocodataset.org/val2017/000000039769.jpg'						,	threshold=0.0)

          self.assertEqual(
              nested_simplify(_UpperCAmelCase						,	decimals=4)						,	[
                  {'score': 0.3376, 'label': 'LABEL_0', 'box': {'xmin': 159, 'ymin': 120, 'xmax': 480, 'ymax': 359}},
                  {'score': 0.3376, 'label': 'LABEL_0', 'box': {'xmin': 159, 'ymin': 120, 'xmax': 480, 'ymax': 359}},
              ]						,	)

          __A						: Optional[Any]      =       object_detector(
              [
                  'http://images.cocodataset.org/val2017/000000039769.jpg',
                  'http://images.cocodataset.org/val2017/000000039769.jpg',
              ]						,	threshold=0.0						,	)

          self.assertEqual(
              nested_simplify(_UpperCAmelCase						,	decimals=4)						,	[
                  [
                      {'score': 0.3376, 'label': 'LABEL_0', 'box': {'xmin': 159, 'ymin': 120, 'xmax': 480, 'ymax': 359}},
                      {'score': 0.3376, 'label': 'LABEL_0', 'box': {'xmin': 159, 'ymin': 120, 'xmax': 480, 'ymax': 359}},
                  ],
                  [
                      {'score': 0.3376, 'label': 'LABEL_0', 'box': {'xmin': 159, 'ymin': 120, 'xmax': 480, 'ymax': 359}},
                      {'score': 0.3376, 'label': 'LABEL_0', 'box': {'xmin': 159, 'ymin': 120, 'xmax': 480, 'ymax': 359}},
                  ],
              ]						,	)


     @require_torch
     @slow
     def 							SCREAMING_SNAKE_CASE  (						self):

          '''simple docstring'''






          __A						: Optional[Any]      =       'facebook/detr-resnet-50'

          __A						: Union[str, Any]      =       AutoModelForObjectDetection.from_pretrained(_UpperCAmelCase)
          __A						: Tuple      =       AutoFeatureExtractor.from_pretrained(_UpperCAmelCase)
          __A						: List[Any]      =       ObjectDetectionPipeline(model=_UpperCAmelCase						,	feature_extractor=_UpperCAmelCase)

          __A						: Union[str, Any]      =       object_detector('http://images.cocodataset.org/val2017/000000039769.jpg')
          self.assertEqual(
              nested_simplify(_UpperCAmelCase						,	decimals=4)						,	[
                  {'score': 0.9982, 'label': 'remote', 'box': {'xmin': 40, 'ymin': 70, 'xmax': 175, 'ymax': 117}},
                  {'score': 0.9960, 'label': 'remote', 'box': {'xmin': 333, 'ymin': 72, 'xmax': 368, 'ymax': 187}},
                  {'score': 0.9955, 'label': 'couch', 'box': {'xmin': 0, 'ymin': 1, 'xmax': 639, 'ymax': 473}},
                  {'score': 0.9988, 'label': 'cat', 'box': {'xmin': 13, 'ymin': 52, 'xmax': 314, 'ymax': 470}},
                  {'score': 0.9987, 'label': 'cat', 'box': {'xmin': 345, 'ymin': 23, 'xmax': 640, 'ymax': 368}},
              ]						,	)

          __A						: Tuple      =       object_detector(
              [
                  'http://images.cocodataset.org/val2017/000000039769.jpg',
                  'http://images.cocodataset.org/val2017/000000039769.jpg',
              ])
          self.assertEqual(
              nested_simplify(_UpperCAmelCase						,	decimals=4)						,	[
                  [
                      {'score': 0.9982, 'label': 'remote', 'box': {'xmin': 40, 'ymin': 70, 'xmax': 175, 'ymax': 117}},
                      {'score': 0.9960, 'label': 'remote', 'box': {'xmin': 333, 'ymin': 72, 'xmax': 368, 'ymax': 187}},
                      {'score': 0.9955, 'label': 'couch', 'box': {'xmin': 0, 'ymin': 1, 'xmax': 639, 'ymax': 473}},
                      {'score': 0.9988, 'label': 'cat', 'box': {'xmin': 13, 'ymin': 52, 'xmax': 314, 'ymax': 470}},
                      {'score': 0.9987, 'label': 'cat', 'box': {'xmin': 345, 'ymin': 23, 'xmax': 640, 'ymax': 368}},
                  ],
                  [
                      {'score': 0.9982, 'label': 'remote', 'box': {'xmin': 40, 'ymin': 70, 'xmax': 175, 'ymax': 117}},
                      {'score': 0.9960, 'label': 'remote', 'box': {'xmin': 333, 'ymin': 72, 'xmax': 368, 'ymax': 187}},
                      {'score': 0.9955, 'label': 'couch', 'box': {'xmin': 0, 'ymin': 1, 'xmax': 639, 'ymax': 473}},
                      {'score': 0.9988, 'label': 'cat', 'box': {'xmin': 13, 'ymin': 52, 'xmax': 314, 'ymax': 470}},
                      {'score': 0.9987, 'label': 'cat', 'box': {'xmin': 345, 'ymin': 23, 'xmax': 640, 'ymax': 368}},
                  ],
              ]						,	)


     @require_torch
     @slow
     def 							SCREAMING_SNAKE_CASE  (						self):

          '''simple docstring'''






          __A						: List[Any]      =       'facebook/detr-resnet-50'

          __A						: str      =       pipeline('object-detection'						,	model=_UpperCAmelCase)

          __A						: Any      =       object_detector('http://images.cocodataset.org/val2017/000000039769.jpg')
          self.assertEqual(
              nested_simplify(_UpperCAmelCase						,	decimals=4)						,	[
                  {'score': 0.9982, 'label': 'remote', 'box': {'xmin': 40, 'ymin': 70, 'xmax': 175, 'ymax': 117}},
                  {'score': 0.9960, 'label': 'remote', 'box': {'xmin': 333, 'ymin': 72, 'xmax': 368, 'ymax': 187}},
                  {'score': 0.9955, 'label': 'couch', 'box': {'xmin': 0, 'ymin': 1, 'xmax': 639, 'ymax': 473}},
                  {'score': 0.9988, 'label': 'cat', 'box': {'xmin': 13, 'ymin': 52, 'xmax': 314, 'ymax': 470}},
                  {'score': 0.9987, 'label': 'cat', 'box': {'xmin': 345, 'ymin': 23, 'xmax': 640, 'ymax': 368}},
              ]						,	)

          __A						: str      =       object_detector(
              [
                  'http://images.cocodataset.org/val2017/000000039769.jpg',
                  'http://images.cocodataset.org/val2017/000000039769.jpg',
              ])
          self.assertEqual(
              nested_simplify(_UpperCAmelCase						,	decimals=4)						,	[
                  [
                      {'score': 0.9982, 'label': 'remote', 'box': {'xmin': 40, 'ymin': 70, 'xmax': 175, 'ymax': 117}},
                      {'score': 0.9960, 'label': 'remote', 'box': {'xmin': 333, 'ymin': 72, 'xmax': 368, 'ymax': 187}},
                      {'score': 0.9955, 'label': 'couch', 'box': {'xmin': 0, 'ymin': 1, 'xmax': 639, 'ymax': 473}},
                      {'score': 0.9988, 'label': 'cat', 'box': {'xmin': 13, 'ymin': 52, 'xmax': 314, 'ymax': 470}},
                      {'score': 0.9987, 'label': 'cat', 'box': {'xmin': 345, 'ymin': 23, 'xmax': 640, 'ymax': 368}},
                  ],
                  [
                      {'score': 0.9982, 'label': 'remote', 'box': {'xmin': 40, 'ymin': 70, 'xmax': 175, 'ymax': 117}},
                      {'score': 0.9960, 'label': 'remote', 'box': {'xmin': 333, 'ymin': 72, 'xmax': 368, 'ymax': 187}},
                      {'score': 0.9955, 'label': 'couch', 'box': {'xmin': 0, 'ymin': 1, 'xmax': 639, 'ymax': 473}},
                      {'score': 0.9988, 'label': 'cat', 'box': {'xmin': 13, 'ymin': 52, 'xmax': 314, 'ymax': 470}},
                      {'score': 0.9987, 'label': 'cat', 'box': {'xmin': 345, 'ymin': 23, 'xmax': 640, 'ymax': 368}},
                  ],
              ]						,	)


     @require_torch
     @slow
     def 							SCREAMING_SNAKE_CASE  (						self):

          '''simple docstring'''






          __A						: List[Any]      =       0.9985
          __A						: List[Any]      =       'facebook/detr-resnet-50'

          __A						: List[str]      =       pipeline('object-detection'						,	model=_UpperCAmelCase)

          __A						: List[Any]      =       object_detector('http://images.cocodataset.org/val2017/000000039769.jpg'						,	threshold=_UpperCAmelCase)
          self.assertEqual(
              nested_simplify(_UpperCAmelCase						,	decimals=4)						,	[
                  {'score': 0.9988, 'label': 'cat', 'box': {'xmin': 13, 'ymin': 52, 'xmax': 314, 'ymax': 470}},
                  {'score': 0.9987, 'label': 'cat', 'box': {'xmin': 345, 'ymin': 23, 'xmax': 640, 'ymax': 368}},
              ]						,	)


     @require_torch
     @require_pytesseract
     @slow
     def 							SCREAMING_SNAKE_CASE  (						self):

          '''simple docstring'''






          __A						: Optional[int]      =       'Narsil/layoutlmv3-finetuned-funsd'
          __A						: Tuple      =       0.9993

          __A						: str      =       pipeline('object-detection'						,	model=_UpperCAmelCase						,	threshold=_UpperCAmelCase)

          __A						: Optional[int]      =       object_detector(
              'https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png')
          self.assertEqual(
              nested_simplify(_UpperCAmelCase						,	decimals=4)						,	[
                  {'score': 0.9993, 'label': 'I-ANSWER', 'box': {'xmin': 294, 'ymin': 254, 'xmax': 343, 'ymax': 264}},
                  {'score': 0.9993, 'label': 'I-ANSWER', 'box': {'xmin': 294, 'ymin': 254, 'xmax': 343, 'ymax': 264}},
              ]						,	)