





"""simple docstring"""



from typing import List, Optional, Union

import numpy as np
import PIL
import torch
from PIL import Image

from ...models import UNetaDConditionModel, VQModel
from ...pipelines import DiffusionPipeline
from ...pipelines.pipeline_utils import ImagePipelineOutput
from ...schedulers import DDPMScheduler
from ...utils import (
    is_accelerate_available,
    is_accelerate_version,
    logging,
    randn_tensor,
    replace_example_docstring,
)


a_					=     logging.get_logger(__name__)  # pylint: disable=invalid-name

a_					=     """
    Examples:
        ```py
        >>> from diffusers import KandinskyV22Img2ImgPipeline, KandinskyV22PriorPipeline
        >>> from diffusers.utils import load_image
        >>> import torch

        >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained(
        ...     \"kandinsky-community/kandinsky-2-2-prior\", torch_dtype=torch.float16
        ... )
        >>> pipe_prior.to(\"cuda\")

        >>> prompt = \"A red cartoon frog, 4k\"
        >>> image_emb, zero_image_emb = pipe_prior(prompt, return_dict=False)

        >>> pipe = KandinskyV22Img2ImgPipeline.from_pretrained(
        ...     \"kandinsky-community/kandinsky-2-2-decoder\", torch_dtype=torch.float16
        ... )
        >>> pipe.to(\"cuda\")

        >>> init_image = load_image(
        ...     \"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main\"
        ...     \"/kandinsky/frog.png\"
        ... )

        >>> image = pipe(
        ...     image=init_image,
        ...     image_embeds=image_emb,
        ...     negative_image_embeds=zero_image_emb,
        ...     height=768,
        ...     width=768,
        ...     num_inference_steps=100,
        ...     strength=0.2,
        ... ).images

        >>> image[0].save(\"red_frog.png\")
        ```
"""







def 						__lowercase	(  snake_case_    :    Optional[Any]							,snake_case_    :    str							,snake_case_    :    List[str]=8		)  ->Optional[Any]:



    '''simple docstring'''







    __A       :		Any							=	height // scale_factor**2
    if height % scale_factor**2 != 0:
        new_height += 1
    __A       :		str							=	width // scale_factor**2
    if width % scale_factor**2 != 0:
        new_width += 1
    return new_height * scale_factor, new_width * scale_factor







def 						__lowercase	(  snake_case_    :    List[str]							,snake_case_    :    Any=512							,snake_case_    :    Optional[int]=512		)  ->Any:



    '''simple docstring'''







    __A       :		Optional[int]							=	pil_image.resize((w, h)							,resample=Image.BICUBIC							,reducing_gap=1		)
    __A       :		Any							=	np.array(pil_image.convert('''RGB'''		)		)
    __A       :		int							=	arr.astype(np.floataa		) / 127.5 - 1
    __A       :		Union[str, Any]							=	np.transpose(snake_case_							,[2, 0, 1]		)
    __A       :		List[Any]							=	torch.from_numpy(snake_case_		).unsqueeze(0		)
    return image






class 						__snake_case   (						SCREAMING_SNAKE_CASE__	):





 """simple docstring"""


 def __init__(       self   ,		__lowerCamelCase   ,		__lowerCamelCase   ,		__lowerCamelCase   ,		):



     '''simple docstring'''




     super().__init__()

     self.register_modules(
         unet=__lowerCamelCase   ,		scheduler=__lowerCamelCase   ,		movq=__lowerCamelCase   ,		)
     __A       :		Optional[Any]							=	2 ** (len(self.movq.config.block_out_channels    ) - 1)

 def    UpperCamelCase__(       self   ,		__lowerCamelCase   ,		__lowerCamelCase   ,		__lowerCamelCase    ):



     '''simple docstring'''




     __A       :		int							=	min(int(num_inference_steps * strength    )   ,		__lowerCamelCase    )

     __A       :		Optional[int]							=	max(num_inference_steps - init_timestep   ,		0    )
     __A       :		int							=	self.scheduler.timesteps[t_start:]

     return timesteps, num_inference_steps - t_start

 def    UpperCamelCase__(       self   ,		__lowerCamelCase   ,		__lowerCamelCase   ,		__lowerCamelCase   ,		__lowerCamelCase   ,		__lowerCamelCase   ,		__lowerCamelCase   ,		__lowerCamelCase=None    ):



     '''simple docstring'''




     if not isinstance(__lowerCamelCase   ,		(torch.Tensor, PIL.Image.Image, list)    ):
         raise ValueError(
             F"""`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(__lowerCamelCase    )}"""    )

     __A       :		Union[str, Any]							=	image.to(device=__lowerCamelCase   ,		dtype=__lowerCamelCase    )

     __A       :		Tuple							=	batch_size * num_images_per_prompt

     if image.shape[1] == 4:
         __A       :		Optional[Any]							=	image

     else:
         if isinstance(__lowerCamelCase   ,		__lowerCamelCase    ) and len(__lowerCamelCase    ) != batch_size:
             raise ValueError(
                 F"""You have passed a list of generators of length {len(__lowerCamelCase    )}, but requested an effective batch"""
                 F""" size of {batch_size}. Make sure the batch size matches the length of the generators."""    )

         elif isinstance(__lowerCamelCase   ,		__lowerCamelCase    ):
             __A       :		List[str]							=	[
                 self.movq.encode(image[i : i + 1]    ).latent_dist.sample(generator[i]    ) for i in range(__lowerCamelCase    )
             ]
             __A       :		Tuple							=	torch.cat(__lowerCamelCase   ,		dim=0    )
         else:
             __A       :		str							=	self.movq.encode(__lowerCamelCase    ).latent_dist.sample(__lowerCamelCase    )

         __A       :		str							=	self.movq.config.scaling_factor * init_latents

     __A       :		str							=	torch.cat([init_latents]   ,		dim=0    )

     __A       :		int							=	init_latents.shape
     __A       :		List[str]							=	randn_tensor(__lowerCamelCase   ,		generator=__lowerCamelCase   ,		device=__lowerCamelCase   ,		dtype=__lowerCamelCase    )

     # get latents
     __A       :		Union[str, Any]							=	self.scheduler.add_noise(__lowerCamelCase   ,		__lowerCamelCase   ,		__lowerCamelCase    )

     __A       :		int							=	init_latents

     return latents

 def    UpperCamelCase__(       self   ,		__lowerCamelCase=0    ):



     '''simple docstring'''




     if is_accelerate_available():
         from accelerate import cpu_offload
     else:
         raise ImportError('''Please install accelerate via `pip install accelerate`'''    )

     __A       :		Dict							=	torch.device(F"""cuda:{gpu_id}"""    )

     __A       :		Tuple							=	[
         self.unet,
         self.movq,
     ]
     for cpu_offloaded_model in models:
         if cpu_offloaded_model is not None:
             cpu_offload(__lowerCamelCase   ,		__lowerCamelCase    )

 def    UpperCamelCase__(       self   ,		__lowerCamelCase=0    ):



     '''simple docstring'''




     if is_accelerate_available() and is_accelerate_version('''>='''   ,		'''0.17.0.dev0'''    ):
         from accelerate import cpu_offload_with_hook
     else:
         raise ImportError('''`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.'''    )

     __A       :		Union[str, Any]							=	torch.device(F"""cuda:{gpu_id}"""    )

     if self.device.type != "cpu":
         self.to('''cpu'''   ,		silence_dtype_warnings=__lowerCamelCase    )
         torch.cuda.empty_cache()  # otherwise we don't see the memory savings (but they probably exist)

     __A       :		Tuple							=	None
     for cpu_offloaded_model in [self.unet, self.movq]:
         __A					,			__A       :		int							=	cpu_offload_with_hook(__lowerCamelCase   ,		__lowerCamelCase   ,		prev_module_hook=__lowerCamelCase    )

     # We'll offload the last model manually.
     __A       :		Union[str, Any]							=	hook

 @property
 # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     if not hasattr(self.unet   ,		'''_hf_hook'''    ):
         return self.device
     for module in self.unet.modules():
         if (
             hasattr(__lowerCamelCase   ,		'''_hf_hook'''    )
             and hasattr(module._hf_hook   ,		'''execution_device'''    )
             and module._hf_hook.execution_device is not None
         ):
             return torch.device(module._hf_hook.execution_device    )
     return self.device







 @torch.no_grad()
 @replace_example_docstring(__lowerCamelCase    )
 def __call__(       self   ,		__lowerCamelCase   ,		__lowerCamelCase   ,		__lowerCamelCase   ,		__lowerCamelCase = 512   ,		__lowerCamelCase = 512   ,		__lowerCamelCase = 100   ,		__lowerCamelCase = 4.0   ,		__lowerCamelCase = 0.3   ,		__lowerCamelCase = 1   ,		__lowerCamelCase = None   ,		__lowerCamelCase = "pil"   ,		__lowerCamelCase = True   ,		):



     '''simple docstring'''




     __A       :		Optional[int]							=	self._execution_device

     __A       :		Optional[int]							=	guidance_scale > 1.0

     if isinstance(__lowerCamelCase   ,		__lowerCamelCase    ):
         __A       :		str							=	torch.cat(__lowerCamelCase   ,		dim=0    )
     __A       :		List[Any]							=	image_embeds.shape[0]
     if isinstance(__lowerCamelCase   ,		__lowerCamelCase    ):
         __A       :		Optional[Any]							=	torch.cat(__lowerCamelCase   ,		dim=0    )

     if do_classifier_free_guidance:
         __A       :		List[str]							=	image_embeds.repeat_interleave(__lowerCamelCase   ,		dim=0    )
         __A       :		Optional[Any]							=	negative_image_embeds.repeat_interleave(__lowerCamelCase   ,		dim=0    )

     __A       :		int							=	torch.cat([negative_image_embeds, image_embeds]   ,		dim=0    ).to(dtype=self.unet.dtype   ,		device=__lowerCamelCase    )

     if not isinstance(__lowerCamelCase   ,		__lowerCamelCase    ):
         __A       :		int							=	[image]
     if not all(isinstance(__lowerCamelCase   ,		(PIL.Image.Image, torch.Tensor)    ) for i in image    ):
         raise ValueError(
             F"""Input is in incorrect format: {[type(__lowerCamelCase    ) for i in image]}. Currently, we only support  PIL image and pytorch tensor"""    )

     __A       :		List[str]							=	torch.cat([prepare_image(__lowerCamelCase   ,		__lowerCamelCase   ,		__lowerCamelCase    ) for i in image]   ,		dim=0    )
     __A       :		List[str]							=	image.to(dtype=image_embeds.dtype   ,		device=__lowerCamelCase    )

     __A       :		str							=	self.movq.encode(__lowerCamelCase    )['''latents''']
     __A       :		Tuple							=	latents.repeat_interleave(__lowerCamelCase   ,		dim=0    )
     self.scheduler.set_timesteps(__lowerCamelCase   ,		device=__lowerCamelCase    )
     __A					,			__A       :		Optional[int]							=	self.get_timesteps(__lowerCamelCase   ,		__lowerCamelCase   ,		__lowerCamelCase    )
     __A       :		Any							=	timesteps[:1].repeat(batch_size * num_images_per_prompt    )
     __A					,			__A       :		Tuple							=	downscale_height_and_width(__lowerCamelCase   ,		__lowerCamelCase   ,		self.movq_scale_factor    )
     __A       :		int							=	self.prepare_latents(
         __lowerCamelCase   ,		__lowerCamelCase   ,		__lowerCamelCase   ,		__lowerCamelCase   ,		image_embeds.dtype   ,		__lowerCamelCase   ,		__lowerCamelCase    )
     for i, t in enumerate(self.progress_bar(__lowerCamelCase    )    ):
         # expand the latents if we are doing classifier free guidance
         __A       :		List[str]							=	torch.cat([latents] * 2    ) if do_classifier_free_guidance else latents

         __A       :		Any							=	{'''image_embeds''': image_embeds}
         __A       :		List[str]							=	self.unet(
             sample=__lowerCamelCase   ,		timestep=__lowerCamelCase   ,		encoder_hidden_states=__lowerCamelCase   ,		added_cond_kwargs=__lowerCamelCase   ,		return_dict=__lowerCamelCase   ,		)[0]

         if do_classifier_free_guidance:
             __A					,			__A       :		Optional[int]							=	noise_pred.split(latents.shape[1]   ,		dim=1    )
             __A					,			__A       :		Tuple							=	noise_pred.chunk(2    )
             __A					,			__A       :		int							=	variance_pred.chunk(2    )
             __A       :		Optional[Any]							=	noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
             __A       :		Dict							=	torch.cat([noise_pred, variance_pred_text]   ,		dim=1    )

         if not (
             hasattr(self.scheduler.config   ,		'''variance_type'''    )
             and self.scheduler.config.variance_type in ["learned", "learned_range"]
         ):
             __A					,			__A       :		Tuple							=	noise_pred.split(latents.shape[1]   ,		dim=1    )

         # compute the previous noisy sample x_t -> x_t-1
         __A       :		Optional[Any]							=	self.scheduler.step(
             __lowerCamelCase   ,		__lowerCamelCase   ,		__lowerCamelCase   ,		generator=__lowerCamelCase   ,		)[0]

     # post-processing
     __A       :		str							=	self.movq.decode(__lowerCamelCase   ,		force_not_quantize=__lowerCamelCase    )['''sample''']

     if output_type not in ["pt", "np", "pil"]:
         raise ValueError(F"""Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}"""    )

     if output_type in ["np", "pil"]:
         __A       :		Optional[int]							=	image * 0.5 + 0.5
         __A       :		List[str]							=	image.clamp(0   ,		1    )
         __A       :		Tuple							=	image.cpu().permute(0   ,		2   ,		3   ,		1    ).float().numpy()

     if output_type == "pil":
         __A       :		int							=	self.numpy_to_pil(__lowerCamelCase    )

     if not return_dict:
         return (image,)

     return ImagePipelineOutput(images=__lowerCamelCase    )











"""simple docstring"""



import json
import os
import sys
import tempfile
import unittest
from pathlib import Path
from shutil import copyfile

from huggingface_hub import HfFolder, Repository, create_repo, delete_repo
from requests.exceptions import HTTPError

import transformers
from transformers import (
    CONFIG_MAPPING,
    FEATURE_EXTRACTOR_MAPPING,
    PROCESSOR_MAPPING,
    TOKENIZER_MAPPING,
    AutoConfig,
    AutoFeatureExtractor,
    AutoProcessor,
    AutoTokenizer,
    BertTokenizer,
    ProcessorMixin,
    WavaVecaConfig,
    WavaVecaFeatureExtractor,
    WavaVecaProcessor,
)
from transformers.testing_utils import TOKEN, USER, get_tests_dir, is_staging_test
from transformers.tokenization_utils import TOKENIZER_CONFIG_FILE
from transformers.utils import FEATURE_EXTRACTOR_NAME, is_tokenizers_available


sys.path.append(str(Path(__file__).parent.parent.parent.parent / """utils"""))

from test_module.custom_configuration import CustomConfig  # noqa E402
from test_module.custom_feature_extraction import CustomFeatureExtractor  # noqa E402
from test_module.custom_processing import CustomProcessor  # noqa E402
from test_module.custom_tokenization import CustomTokenizer  # noqa E402


a_					=     get_tests_dir("""fixtures/dummy_feature_extractor_config.json""")
a_					=     get_tests_dir("""fixtures/vocab.json""")
a_					=     get_tests_dir("""fixtures""")






class 						__snake_case   (						unittest.TestCase	):





 """simple docstring"""


 _lowerCamelCase								=	["""[UNK]""", """[CLS]""", """[SEP]""", """[PAD]""", """[MASK]""", """bla""", """blou"""]

 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     __A       :		Optional[Any]							=	0

 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     __A       :		str							=	AutoProcessor.from_pretrained('''facebook/wav2vec2-base-960h'''    )
     self.assertIsInstance(__lowerCamelCase   ,		__lowerCamelCase    )

 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     with tempfile.TemporaryDirectory() as tmpdirname:
         __A       :		str							=	WavaVecaConfig()
         __A       :		Dict							=	AutoProcessor.from_pretrained('''facebook/wav2vec2-base-960h'''    )

         # save in new folder
         model_config.save_pretrained(__lowerCamelCase    )
         processor.save_pretrained(__lowerCamelCase    )

         __A       :		List[str]							=	AutoProcessor.from_pretrained(__lowerCamelCase    )

     self.assertIsInstance(__lowerCamelCase   ,		__lowerCamelCase    )

 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     with tempfile.TemporaryDirectory() as tmpdirname:
         # copy relevant files
         copyfile(__lowerCamelCase   ,		os.path.join(__lowerCamelCase   ,		__lowerCamelCase    )    )
         copyfile(__lowerCamelCase   ,		os.path.join(__lowerCamelCase   ,		'''vocab.json'''    )    )

         __A       :		Union[str, Any]							=	AutoProcessor.from_pretrained(__lowerCamelCase    )

     self.assertIsInstance(__lowerCamelCase   ,		__lowerCamelCase    )

 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     with tempfile.TemporaryDirectory() as tmpdirname:
         __A       :		Union[str, Any]							=	WavaVecaFeatureExtractor()
         __A       :		Optional[Any]							=	AutoTokenizer.from_pretrained('''facebook/wav2vec2-base-960h'''    )

         __A       :		Union[str, Any]							=	WavaVecaProcessor(__lowerCamelCase   ,		__lowerCamelCase    )

         # save in new folder
         processor.save_pretrained(__lowerCamelCase    )

         # drop `processor_class` in tokenizer
         with open(os.path.join(__lowerCamelCase   ,		__lowerCamelCase    )   ,		'''r'''    ) as f:
             __A       :		Optional[int]							=	json.load(__lowerCamelCase    )
             config_dict.pop('''processor_class'''    )

         with open(os.path.join(__lowerCamelCase   ,		__lowerCamelCase    )   ,		'''w'''    ) as f:
             f.write(json.dumps(__lowerCamelCase    )    )

         __A       :		Tuple							=	AutoProcessor.from_pretrained(__lowerCamelCase    )

     self.assertIsInstance(__lowerCamelCase   ,		__lowerCamelCase    )

 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     with tempfile.TemporaryDirectory() as tmpdirname:
         __A       :		Optional[int]							=	WavaVecaFeatureExtractor()
         __A       :		List[str]							=	AutoTokenizer.from_pretrained('''facebook/wav2vec2-base-960h'''    )

         __A       :		List[Any]							=	WavaVecaProcessor(__lowerCamelCase   ,		__lowerCamelCase    )

         # save in new folder
         processor.save_pretrained(__lowerCamelCase    )

         # drop `processor_class` in feature extractor
         with open(os.path.join(__lowerCamelCase   ,		__lowerCamelCase    )   ,		'''r'''    ) as f:
             __A       :		int							=	json.load(__lowerCamelCase    )
             config_dict.pop('''processor_class'''    )

         with open(os.path.join(__lowerCamelCase   ,		__lowerCamelCase    )   ,		'''w'''    ) as f:
             f.write(json.dumps(__lowerCamelCase    )    )

         __A       :		Optional[int]							=	AutoProcessor.from_pretrained(__lowerCamelCase    )

     self.assertIsInstance(__lowerCamelCase   ,		__lowerCamelCase    )

 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     with tempfile.TemporaryDirectory() as tmpdirname:
         __A       :		Optional[Any]							=	WavaVecaConfig(processor_class='''Wav2Vec2Processor'''    )
         model_config.save_pretrained(__lowerCamelCase    )
         # copy relevant files
         copyfile(__lowerCamelCase   ,		os.path.join(__lowerCamelCase   ,		'''vocab.json'''    )    )
         # create emtpy sample processor
         with open(os.path.join(__lowerCamelCase   ,		__lowerCamelCase    )   ,		'''w'''    ) as f:
             f.write('''{}'''    )

         __A       :		Union[str, Any]							=	AutoProcessor.from_pretrained(__lowerCamelCase    )

     self.assertIsInstance(__lowerCamelCase   ,		__lowerCamelCase    )

 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     with self.assertRaises(__lowerCamelCase    ):
         __A       :		Union[str, Any]							=	AutoProcessor.from_pretrained('''hf-internal-testing/test_dynamic_processor'''    )
     # If remote code is disabled, we can't load this config.
     with self.assertRaises(__lowerCamelCase    ):
         __A       :		Dict							=	AutoProcessor.from_pretrained(
             '''hf-internal-testing/test_dynamic_processor'''   ,		trust_remote_code=__lowerCamelCase    )

     __A       :		List[Any]							=	AutoProcessor.from_pretrained('''hf-internal-testing/test_dynamic_processor'''   ,		trust_remote_code=__lowerCamelCase    )
     self.assertTrue(processor.special_attribute_present    )
     self.assertEqual(processor.__class__.__name__   ,		'''NewProcessor'''    )

     __A       :		Union[str, Any]							=	processor.feature_extractor
     self.assertTrue(feature_extractor.special_attribute_present    )
     self.assertEqual(feature_extractor.__class__.__name__   ,		'''NewFeatureExtractor'''    )

     __A       :		Optional[int]							=	processor.tokenizer
     self.assertTrue(tokenizer.special_attribute_present    )
     if is_tokenizers_available():
         self.assertEqual(tokenizer.__class__.__name__   ,		'''NewTokenizerFast'''    )

         # Test we can also load the slow version
         __A       :		int							=	AutoProcessor.from_pretrained(
             '''hf-internal-testing/test_dynamic_processor'''   ,		trust_remote_code=__lowerCamelCase   ,		use_fast=__lowerCamelCase    )
         __A       :		Optional[int]							=	new_processor.tokenizer
         self.assertTrue(new_tokenizer.special_attribute_present    )
         self.assertEqual(new_tokenizer.__class__.__name__   ,		'''NewTokenizer'''    )
     else:
         self.assertEqual(tokenizer.__class__.__name__   ,		'''NewTokenizer'''    )

 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     try:
         AutoConfig.register('''custom'''   ,		__lowerCamelCase    )
         AutoFeatureExtractor.register(__lowerCamelCase   ,		__lowerCamelCase    )
         AutoTokenizer.register(__lowerCamelCase   ,		slow_tokenizer_class=__lowerCamelCase    )
         AutoProcessor.register(__lowerCamelCase   ,		__lowerCamelCase    )
         # Trying to register something existing in the Transformers library will raise an error
         with self.assertRaises(__lowerCamelCase    ):
             AutoProcessor.register(__lowerCamelCase   ,		__lowerCamelCase    )

         # Now that the config is registered, it can be used as any other config with the auto-API
         __A       :		str							=	CustomFeatureExtractor.from_pretrained(__lowerCamelCase    )

         with tempfile.TemporaryDirectory() as tmp_dir:
             __A       :		Optional[Any]							=	os.path.join(__lowerCamelCase   ,		'''vocab.txt'''    )
             with open(__lowerCamelCase   ,		'''w'''   ,		encoding='''utf-8'''    ) as vocab_writer:
                 vocab_writer.write(''''''.join([x + '''\n''' for x in self.vocab_tokens]    )    )
             __A       :		Dict							=	CustomTokenizer(__lowerCamelCase    )

         __A       :		Optional[Any]							=	CustomProcessor(__lowerCamelCase   ,		__lowerCamelCase    )

         with tempfile.TemporaryDirectory() as tmp_dir:
             processor.save_pretrained(__lowerCamelCase    )
             __A       :		List[str]							=	AutoProcessor.from_pretrained(__lowerCamelCase    )
             self.assertIsInstance(__lowerCamelCase   ,		__lowerCamelCase    )

     finally:
         if "custom" in CONFIG_MAPPING._extra_content:
             del CONFIG_MAPPING._extra_content["custom"]
         if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content:
             del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig]
         if CustomConfig in TOKENIZER_MAPPING._extra_content:
             del TOKENIZER_MAPPING._extra_content[CustomConfig]
         if CustomConfig in PROCESSOR_MAPPING._extra_content:
             del PROCESSOR_MAPPING._extra_content[CustomConfig]

 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     class 						__snake_case   (						SCREAMING_SNAKE_CASE__	):





      """simple docstring"""


      _lowerCamelCase								=	False






     class 						__snake_case   (						SCREAMING_SNAKE_CASE__	):





      """simple docstring"""


      _lowerCamelCase								=	False






     class 						__snake_case   (						SCREAMING_SNAKE_CASE__	):





      """simple docstring"""


      _lowerCamelCase								=	"""AutoFeatureExtractor"""
      _lowerCamelCase								=	"""AutoTokenizer"""
      _lowerCamelCase								=	False

     try:
         AutoConfig.register('''custom'''   ,		__lowerCamelCase    )
         AutoFeatureExtractor.register(__lowerCamelCase   ,		__lowerCamelCase    )
         AutoTokenizer.register(__lowerCamelCase   ,		slow_tokenizer_class=__lowerCamelCase    )
         AutoProcessor.register(__lowerCamelCase   ,		__lowerCamelCase    )
         # If remote code is not set, the default is to use local classes.
         __A       :		Union[str, Any]							=	AutoProcessor.from_pretrained('''hf-internal-testing/test_dynamic_processor'''    )
         self.assertEqual(processor.__class__.__name__   ,		'''NewProcessor'''    )
         self.assertFalse(processor.special_attribute_present    )
         self.assertFalse(processor.feature_extractor.special_attribute_present    )
         self.assertFalse(processor.tokenizer.special_attribute_present    )

         # If remote code is disabled, we load the local ones.
         __A       :		int							=	AutoProcessor.from_pretrained(
             '''hf-internal-testing/test_dynamic_processor'''   ,		trust_remote_code=__lowerCamelCase    )
         self.assertEqual(processor.__class__.__name__   ,		'''NewProcessor'''    )
         self.assertFalse(processor.special_attribute_present    )
         self.assertFalse(processor.feature_extractor.special_attribute_present    )
         self.assertFalse(processor.tokenizer.special_attribute_present    )

         # If remote is enabled, we load from the Hub.
         __A       :		str							=	AutoProcessor.from_pretrained(
             '''hf-internal-testing/test_dynamic_processor'''   ,		trust_remote_code=__lowerCamelCase    )
         self.assertEqual(processor.__class__.__name__   ,		'''NewProcessor'''    )
         self.assertTrue(processor.special_attribute_present    )
         self.assertTrue(processor.feature_extractor.special_attribute_present    )
         self.assertTrue(processor.tokenizer.special_attribute_present    )

     finally:
         if "custom" in CONFIG_MAPPING._extra_content:
             del CONFIG_MAPPING._extra_content["custom"]
         if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content:
             del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig]
         if CustomConfig in TOKENIZER_MAPPING._extra_content:
             del TOKENIZER_MAPPING._extra_content[CustomConfig]
         if CustomConfig in PROCESSOR_MAPPING._extra_content:
             del PROCESSOR_MAPPING._extra_content[CustomConfig]

 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     __A       :		int							=	AutoProcessor.from_pretrained('''hf-internal-testing/tiny-random-bert'''    )
     self.assertEqual(processor.__class__.__name__   ,		'''BertTokenizerFast'''    )







 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     __A       :		int							=	AutoProcessor.from_pretrained('''hf-internal-testing/tiny-random-convnext'''    )
     self.assertEqual(processor.__class__.__name__   ,		'''ConvNextImageProcessor'''    )






@is_staging_test
class 						__snake_case   (						unittest.TestCase	):





 """simple docstring"""


 _lowerCamelCase								=	["""[UNK]""", """[CLS]""", """[SEP]""", """[PAD]""", """[MASK]""", """bla""", """blou"""]

 @classmethod
 def    UpperCamelCase__(       cls    ):



     '''simple docstring'''




     __A       :		Optional[int]							=	TOKEN
     HfFolder.save_token(__lowerCamelCase    )

 @classmethod
 def    UpperCamelCase__(       cls    ):



     '''simple docstring'''




     try:
         delete_repo(token=cls._token   ,		repo_id='''test-processor'''    )
     except HTTPError:
         pass

     try:
         delete_repo(token=cls._token   ,		repo_id='''valid_org/test-processor-org'''    )
     except HTTPError:
         pass

     try:
         delete_repo(token=cls._token   ,		repo_id='''test-dynamic-processor'''    )
     except HTTPError:
         pass

 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     __A       :		Tuple							=	WavaVecaProcessor.from_pretrained(__lowerCamelCase    )
     with tempfile.TemporaryDirectory() as tmp_dir:
         processor.save_pretrained(
             os.path.join(__lowerCamelCase   ,		'''test-processor'''    )   ,		push_to_hub=__lowerCamelCase   ,		use_auth_token=self._token    )

         __A       :		Tuple							=	WavaVecaProcessor.from_pretrained(F"""{USER}/test-processor"""    )
         for k, v in processor.feature_extractor.__dict__.items():
             self.assertEqual(__lowerCamelCase   ,		getattr(new_processor.feature_extractor   ,		__lowerCamelCase    )    )
         self.assertDictEqual(new_processor.tokenizer.get_vocab()   ,		processor.tokenizer.get_vocab()    )

 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     __A       :		Optional[int]							=	WavaVecaProcessor.from_pretrained(__lowerCamelCase    )

     with tempfile.TemporaryDirectory() as tmp_dir:
         processor.save_pretrained(
             os.path.join(__lowerCamelCase   ,		'''test-processor-org'''    )   ,		push_to_hub=__lowerCamelCase   ,		use_auth_token=self._token   ,		organization='''valid_org'''   ,		)

         __A       :		int							=	WavaVecaProcessor.from_pretrained('''valid_org/test-processor-org'''    )
         for k, v in processor.feature_extractor.__dict__.items():
             self.assertEqual(__lowerCamelCase   ,		getattr(new_processor.feature_extractor   ,		__lowerCamelCase    )    )
         self.assertDictEqual(new_processor.tokenizer.get_vocab()   ,		processor.tokenizer.get_vocab()    )







 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     CustomFeatureExtractor.register_for_auto_class()
     CustomTokenizer.register_for_auto_class()
     CustomProcessor.register_for_auto_class()

     __A       :		Any							=	CustomFeatureExtractor.from_pretrained(__lowerCamelCase    )

     with tempfile.TemporaryDirectory() as tmp_dir:
         __A       :		List[Any]							=	os.path.join(__lowerCamelCase   ,		'''vocab.txt'''    )
         with open(__lowerCamelCase   ,		'''w'''   ,		encoding='''utf-8'''    ) as vocab_writer:
             vocab_writer.write(''''''.join([x + '''\n''' for x in self.vocab_tokens]    )    )
         __A       :		Optional[int]							=	CustomTokenizer(__lowerCamelCase    )

     __A       :		Any							=	CustomProcessor(__lowerCamelCase   ,		__lowerCamelCase    )

     with tempfile.TemporaryDirectory() as tmp_dir:
         create_repo(F"""{USER}/test-dynamic-processor"""   ,		token=self._token    )
         __A       :		Tuple							=	Repository(__lowerCamelCase   ,		clone_from=F"""{USER}/test-dynamic-processor"""   ,		token=self._token    )
         processor.save_pretrained(__lowerCamelCase    )

         # This has added the proper auto_map field to the feature extractor config
         self.assertDictEqual(
             processor.feature_extractor.auto_map   ,		{
                 '''AutoFeatureExtractor''': '''custom_feature_extraction.CustomFeatureExtractor''',
                 '''AutoProcessor''': '''custom_processing.CustomProcessor''',
             }   ,		)

         # This has added the proper auto_map field to the tokenizer config
         with open(os.path.join(__lowerCamelCase   ,		'''tokenizer_config.json'''    )    ) as f:
             __A       :		Tuple							=	json.load(__lowerCamelCase    )
         self.assertDictEqual(
             tokenizer_config['''auto_map''']   ,		{
                 '''AutoTokenizer''': ['''custom_tokenization.CustomTokenizer''', None],
                 '''AutoProcessor''': '''custom_processing.CustomProcessor''',
             }   ,		)

         # The code has been copied from fixtures
         self.assertTrue(os.path.isfile(os.path.join(__lowerCamelCase   ,		'''custom_feature_extraction.py'''    )    )    )
         self.assertTrue(os.path.isfile(os.path.join(__lowerCamelCase   ,		'''custom_tokenization.py'''    )    )    )
         self.assertTrue(os.path.isfile(os.path.join(__lowerCamelCase   ,		'''custom_processing.py'''    )    )    )

         repo.push_to_hub()

     __A       :		Any							=	AutoProcessor.from_pretrained(F"""{USER}/test-dynamic-processor"""   ,		trust_remote_code=__lowerCamelCase    )
     # Can't make an isinstance check because the new_processor is from the CustomProcessor class of a dynamic module
     self.assertEqual(new_processor.__class__.__name__   ,		'''CustomProcessor'''    )




