
'''simple docstring'''




from typing import Any, Dict, Optional

import torch
import torch.nn.functional as F
from torch import nn

from ..utils import maybe_allow_in_graph
from .activations import get_activation
from .attention_processor import Attention
from .embeddings import CombinedTimestepLabelEmbeddings





@maybe_allow_in_graph
class  A				(							nn.Module						):





     def __init__(							self						,			SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE=0.0						,			SCREAMING_SNAKE_CASE = None						,			SCREAMING_SNAKE_CASE = "geglu"						,			SCREAMING_SNAKE_CASE = None						,			SCREAMING_SNAKE_CASE = False						,			SCREAMING_SNAKE_CASE = False						,			SCREAMING_SNAKE_CASE = False						,			SCREAMING_SNAKE_CASE = False						,			SCREAMING_SNAKE_CASE = True						,			SCREAMING_SNAKE_CASE = "layer_norm"						,			SCREAMING_SNAKE_CASE = False						,			) ->				Any:






         """simple docstring"""






         super().__init__()
         A       :   int					=						only_cross_attention

         A       :   Dict					=						(num_embeds_ada_norm is not None) and norm_type == '''ada_norm_zero'''
         A       :   Dict					=						(num_embeds_ada_norm is not None) and norm_type == '''ada_norm'''

         if norm_type in ("ada_norm", "ada_norm_zero") and num_embeds_ada_norm is None:
             raise ValueError(
                 F'`norm_type` is set to {norm_type}, but `num_embeds_ada_norm` is not defined. Please make sure to'
                 F' define `num_embeds_ada_norm` if setting `norm_type` to {norm_type}.'	)

         # Define 3 blocks. Each block has its own normalization layer.
         # 1. Self-Attn
         if self.use_ada_layer_norm:
             A       :   Any					=						AdaLayerNorm(SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE	)
         elif self.use_ada_layer_norm_zero:
             A       :   List[str]					=						AdaLayerNormZero(SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE	)
         else:
             A       :   List[str]					=						nn.LayerNorm(SCREAMING_SNAKE_CASE						,			elementwise_affine=SCREAMING_SNAKE_CASE	)
         A       :   Optional[Any]					=						Attention(
             query_dim=SCREAMING_SNAKE_CASE						,			heads=SCREAMING_SNAKE_CASE						,			dim_head=SCREAMING_SNAKE_CASE						,			dropout=SCREAMING_SNAKE_CASE						,			bias=SCREAMING_SNAKE_CASE						,			cross_attention_dim=cross_attention_dim if only_cross_attention else None						,			upcast_attention=SCREAMING_SNAKE_CASE						,			)

         # 2. Cross-Attn
         if cross_attention_dim is not None or double_self_attention:
             # We currently only use AdaLayerNormZero for self attention where there will only be one attention block.
             # I.e. the number of returned modulation chunks from AdaLayerZero would not make sense if returned during
             # the second cross attention block.
             A       :   Optional[Any]					=						(
                 AdaLayerNorm(SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE	)
                 if self.use_ada_layer_norm
                 else nn.LayerNorm(SCREAMING_SNAKE_CASE						,			elementwise_affine=SCREAMING_SNAKE_CASE	)
             )
             A       :   Optional[Any]					=						Attention(
                 query_dim=SCREAMING_SNAKE_CASE						,			cross_attention_dim=cross_attention_dim if not double_self_attention else None						,			heads=SCREAMING_SNAKE_CASE						,			dim_head=SCREAMING_SNAKE_CASE						,			dropout=SCREAMING_SNAKE_CASE						,			bias=SCREAMING_SNAKE_CASE						,			upcast_attention=SCREAMING_SNAKE_CASE						,			)  # is self-attn if encoder_hidden_states is none
         else:
             A       :   int					=						None
             A       :   Optional[Any]					=						None

         # 3. Feed-forward
         A       :   Optional[int]					=						nn.LayerNorm(SCREAMING_SNAKE_CASE						,			elementwise_affine=SCREAMING_SNAKE_CASE	)
         A       :   Dict					=						FeedForward(SCREAMING_SNAKE_CASE						,			dropout=SCREAMING_SNAKE_CASE						,			activation_fn=SCREAMING_SNAKE_CASE						,			final_dropout=SCREAMING_SNAKE_CASE	)

         # let chunk size default to None
         A       :   Dict					=						None
         A       :   Optional[int]					=						0





     def 				__lowerCAmelCase							(							self						,			SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE	) ->				int:






         """simple docstring"""






         A       :   Union[str, Any]					=						chunk_size
         A       :   Dict					=						dim





     def 				__lowerCAmelCase							(							self						,			SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE = None						,			SCREAMING_SNAKE_CASE = None						,			SCREAMING_SNAKE_CASE = None						,			SCREAMING_SNAKE_CASE = None						,			SCREAMING_SNAKE_CASE = None						,			SCREAMING_SNAKE_CASE = None						,			) ->				Dict:






         """simple docstring"""






         if self.use_ada_layer_norm:
             A       :   str					=						self.norma(SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE	)
         elif self.use_ada_layer_norm_zero:
             A,  A,  A,  A,  A       :   int					=						self.norma(
                 SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE						,			hidden_dtype=hidden_states.dtype	)
         else:
             A       :   int					=						self.norma(SCREAMING_SNAKE_CASE	)

         A       :   Optional[int]					=						cross_attention_kwargs if cross_attention_kwargs is not None else {}

         A       :   Any					=						self.attna(
             SCREAMING_SNAKE_CASE						,			encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None						,			attention_mask=SCREAMING_SNAKE_CASE						,			**SCREAMING_SNAKE_CASE						,			)
         if self.use_ada_layer_norm_zero:
             A       :   Any					=						gate_msa.unsqueeze(1	) * attn_output
         A       :   List[Any]					=						attn_output + hidden_states

         # 2. Cross-Attention
         if self.attna is not None:
             A       :   Optional[int]					=						(
                 self.norma(SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE	) if self.use_ada_layer_norm else self.norma(SCREAMING_SNAKE_CASE	)
             )

             A       :   Dict					=						self.attna(
                 SCREAMING_SNAKE_CASE						,			encoder_hidden_states=SCREAMING_SNAKE_CASE						,			attention_mask=SCREAMING_SNAKE_CASE						,			**SCREAMING_SNAKE_CASE						,			)
             A       :   List[str]					=						attn_output + hidden_states

         # 3. Feed-forward
         A       :   Union[str, Any]					=						self.norma(SCREAMING_SNAKE_CASE	)

         if self.use_ada_layer_norm_zero:
             A       :   Any					=						norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None]

         if self._chunk_size is not None:
             # "feed_forward_chunk_size" can be used to save memory
             if norm_hidden_states.shape[self._chunk_dim] % self._chunk_size != 0:
                 raise ValueError(
                     F'`hidden_states` dimension to be chunked: {norm_hidden_states.shape[self._chunk_dim]} has to be divisible by chunk size: {self._chunk_size}. Make sure to set an appropriate `chunk_size` when calling `unet.enable_forward_chunking`.'	)

             A       :   Any					=						norm_hidden_states.shape[self._chunk_dim] // self._chunk_size
             A       :   Tuple					=						torch.cat(
                 [self.ff(SCREAMING_SNAKE_CASE	) for hid_slice in norm_hidden_states.chunk(SCREAMING_SNAKE_CASE						,			dim=self._chunk_dim	)]						,			dim=self._chunk_dim						,			)
         else:
             A       :   Optional[int]					=						self.ff(SCREAMING_SNAKE_CASE	)

         if self.use_ada_layer_norm_zero:
             A       :   str					=						gate_mlp.unsqueeze(1	) * ff_output

         A       :   Optional[int]					=						ff_output + hidden_states

         return hidden_states





class  A				(							nn.Module						):





     def __init__(							self						,			SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE = None						,			SCREAMING_SNAKE_CASE = 4						,			SCREAMING_SNAKE_CASE = 0.0						,			SCREAMING_SNAKE_CASE = "geglu"						,			SCREAMING_SNAKE_CASE = False						,			) ->				int:






         """simple docstring"""






         super().__init__()
         A       :   int					=						int(dim * mult	)
         A       :   Tuple					=						dim_out if dim_out is not None else dim

         if activation_fn == "gelu":
             A       :   Any					=						GELU(SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE	)
         if activation_fn == "gelu-approximate":
             A       :   int					=						GELU(SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE						,			approximate='''tanh'''	)
         elif activation_fn == "geglu":
             A       :   List[str]					=						GEGLU(SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE	)
         elif activation_fn == "geglu-approximate":
             A       :   Union[str, Any]					=						ApproximateGELU(SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE	)

         A       :   Optional[Any]					=						nn.ModuleList([]	)
         # project in
         self.net.append(SCREAMING_SNAKE_CASE	)
         # project dropout
         self.net.append(nn.Dropout(SCREAMING_SNAKE_CASE	)	)
         # project out
         self.net.append(nn.Linear(SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE	)	)
         # FF as used in Vision Transformer, MLP-Mixer, etc. have a final dropout
         if final_dropout:
             self.net.append(nn.Dropout(SCREAMING_SNAKE_CASE	)	)





     def 				__lowerCAmelCase							(							self						,			SCREAMING_SNAKE_CASE	) ->				Tuple:






         """simple docstring"""






         for module in self.net:
             A       :   List[Any]					=						module(SCREAMING_SNAKE_CASE	)
         return hidden_states





class  A				(							nn.Module						):





     def __init__(							self						,			SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE = "none"	) ->				Tuple:






         """simple docstring"""






         super().__init__()
         A       :   int					=						nn.Linear(SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE	)
         A       :   Dict					=						approximate





     def 				__lowerCAmelCase							(							self						,			SCREAMING_SNAKE_CASE	) ->				List[str]:






         """simple docstring"""






         if gate.device.type != "mps":
             return F.gelu(SCREAMING_SNAKE_CASE						,			approximate=self.approximate	)
         # mps: gelu is not implemented for float16
         return F.gelu(gate.to(dtype=torch.floataa	)						,			approximate=self.approximate	).to(dtype=gate.dtype	)





     def 				__lowerCAmelCase							(							self						,			SCREAMING_SNAKE_CASE	) ->				Optional[int]:






         """simple docstring"""






         A       :   str					=						self.proj(SCREAMING_SNAKE_CASE	)
         A       :   Tuple					=						self.gelu(SCREAMING_SNAKE_CASE	)
         return hidden_states





class  A				(							nn.Module						):





     def __init__(							self						,			SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE	) ->				Dict:






         """simple docstring"""






         super().__init__()
         A       :   str					=						nn.Linear(SCREAMING_SNAKE_CASE						,			dim_out * 2	)





     def 				__lowerCAmelCase							(							self						,			SCREAMING_SNAKE_CASE	) ->				Optional[Any]:






         """simple docstring"""






         if gate.device.type != "mps":
             return F.gelu(SCREAMING_SNAKE_CASE	)
         # mps: gelu is not implemented for float16
         return F.gelu(gate.to(dtype=torch.floataa	)	).to(dtype=gate.dtype	)





     def 				__lowerCAmelCase							(							self						,			SCREAMING_SNAKE_CASE	) ->				str:






         """simple docstring"""






         A,  A       :   Optional[int]					=						self.proj(SCREAMING_SNAKE_CASE	).chunk(2						,			dim=-1	)
         return hidden_states * self.gelu(SCREAMING_SNAKE_CASE	)





class  A				(							nn.Module						):





     def __init__(							self						,			SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE	) ->				List[Any]:






         """simple docstring"""






         super().__init__()
         A       :   Optional[int]					=						nn.Linear(SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE	)





     def 				__lowerCAmelCase							(							self						,			SCREAMING_SNAKE_CASE	) ->				int:






         """simple docstring"""






         A       :   Union[str, Any]					=						self.proj(SCREAMING_SNAKE_CASE	)
         return x * torch.sigmoid(1.702 * x	)





class  A				(							nn.Module						):





     def __init__(							self						,			SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE	) ->				List[str]:






         """simple docstring"""






         super().__init__()
         A       :   Any					=						nn.Embedding(SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE	)
         A       :   Dict					=						nn.SiLU()
         A       :   Union[str, Any]					=						nn.Linear(SCREAMING_SNAKE_CASE						,			embedding_dim * 2	)
         A       :   Union[str, Any]					=						nn.LayerNorm(SCREAMING_SNAKE_CASE						,			elementwise_affine=SCREAMING_SNAKE_CASE	)





     def 				__lowerCAmelCase							(							self						,			SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE	) ->				List[Any]:






         """simple docstring"""






         A       :   List[Any]					=						self.linear(self.silu(self.emb(SCREAMING_SNAKE_CASE	)	)	)
         A,  A       :   str					=						torch.chunk(SCREAMING_SNAKE_CASE						,			2	)
         A       :   List[str]					=						self.norm(SCREAMING_SNAKE_CASE	) * (1 + scale) + shift
         return x





class  A				(							nn.Module						):





     def __init__(							self						,			SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE	) ->				int:






         """simple docstring"""






         super().__init__()

         A       :   List[Any]					=						CombinedTimestepLabelEmbeddings(SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE	)

         A       :   List[str]					=						nn.SiLU()
         A       :   Optional[int]					=						nn.Linear(SCREAMING_SNAKE_CASE						,			6 * embedding_dim						,			bias=SCREAMING_SNAKE_CASE	)
         A       :   Any					=						nn.LayerNorm(SCREAMING_SNAKE_CASE						,			elementwise_affine=SCREAMING_SNAKE_CASE						,			eps=1e-6	)





     def 				__lowerCAmelCase							(							self						,			SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE=None	) ->				Any:






         """simple docstring"""






         A       :   Tuple					=						self.linear(self.silu(self.emb(SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE						,			hidden_dtype=SCREAMING_SNAKE_CASE	)	)	)
         A,  A,  A,  A,  A,  A       :   str					=						emb.chunk(6						,			dim=1	)
         A       :   Union[str, Any]					=						self.norm(SCREAMING_SNAKE_CASE	) * (1 + scale_msa[:, None]) + shift_msa[:, None]
         return x, gate_msa, shift_mlp, scale_mlp, gate_mlp





class  A				(							nn.Module						):





     def __init__(							self						,			SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE = None						,			SCREAMING_SNAKE_CASE = 1e-5	) ->				Optional[int]:






         """simple docstring"""






         super().__init__()
         A       :   str					=						num_groups
         A       :   Union[str, Any]					=						eps

         if act_fn is None:
             A       :   Optional[int]					=						None
         else:
             A       :   Dict					=						get_activation(SCREAMING_SNAKE_CASE	)

         A       :   Tuple					=						nn.Linear(SCREAMING_SNAKE_CASE						,			out_dim * 2	)





     def 				__lowerCAmelCase							(							self						,			SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE	) ->				Union[str, Any]:






         """simple docstring"""






         if self.act:
             A       :   Dict					=						self.act(SCREAMING_SNAKE_CASE	)
         A       :   Union[str, Any]					=						self.linear(SCREAMING_SNAKE_CASE	)
         A       :   Optional[int]					=						emb[:, :, None, None]
         A,  A       :   Dict					=						emb.chunk(2						,			dim=1	)

         A       :   Dict					=						F.group_norm(SCREAMING_SNAKE_CASE						,			self.num_groups						,			eps=self.eps	)
         A       :   Optional[int]					=						x * (1 + scale) + shift
         return x






'''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


lowercase			:				str    		=			get_tests_dir('fixtures/dummy_feature_extractor_config.json')
lowercase			:				str    		=			get_tests_dir('fixtures/vocab.json')
lowercase			:				int    		=			get_tests_dir('fixtures')





class  A				(							unittest.TestCase						):
     __magic_name__						=		['''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''bla''', '''blou''']





     def 				__lowerCAmelCase							(							self	) ->				List[str]:






         """simple docstring"""






         A       :   Tuple					=						0





     def 				__lowerCAmelCase							(							self	) ->				Optional[int]:






         """simple docstring"""






         A       :   List[Any]					=						AutoProcessor.from_pretrained('''facebook/wav2vec2-base-960h'''	)
         self.assertIsInstance(SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE	)





     def 				__lowerCAmelCase							(							self	) ->				List[str]:






         """simple docstring"""






         with tempfile.TemporaryDirectory() as tmpdirname:
             A       :   Union[str, Any]					=						WavaVecaConfig()
             A       :   List[str]					=						AutoProcessor.from_pretrained('''facebook/wav2vec2-base-960h'''	)

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

             A       :   List[str]					=						AutoProcessor.from_pretrained(SCREAMING_SNAKE_CASE	)

         self.assertIsInstance(SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE	)





     def 				__lowerCAmelCase							(							self	) ->				int:






         """simple docstring"""






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

             A       :   Optional[Any]					=						AutoProcessor.from_pretrained(SCREAMING_SNAKE_CASE	)

         self.assertIsInstance(SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE	)





     def 				__lowerCAmelCase							(							self	) ->				Union[str, Any]:






         """simple docstring"""






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

             A       :   str					=						WavaVecaProcessor(SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE	)

             # save in new folder
             processor.save_pretrained(SCREAMING_SNAKE_CASE	)

             # drop `processor_class` in tokenizer
             with open(os.path.join(SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE	)						,			'''r'''	) as f:
                 A       :   Dict					=						json.load(SCREAMING_SNAKE_CASE	)
                 config_dict.pop('''processor_class'''	)

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

             A       :   Optional[Any]					=						AutoProcessor.from_pretrained(SCREAMING_SNAKE_CASE	)

         self.assertIsInstance(SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE	)





     def 				__lowerCAmelCase							(							self	) ->				int:






         """simple docstring"""






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

             A       :   str					=						WavaVecaProcessor(SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE	)

             # save in new folder
             processor.save_pretrained(SCREAMING_SNAKE_CASE	)

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

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

             A       :   str					=						AutoProcessor.from_pretrained(SCREAMING_SNAKE_CASE	)

         self.assertIsInstance(SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE	)





     def 				__lowerCAmelCase							(							self	) ->				Optional[Any]:






         """simple docstring"""






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

             A       :   List[str]					=						AutoProcessor.from_pretrained(SCREAMING_SNAKE_CASE	)

         self.assertIsInstance(SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE	)





     def 				__lowerCAmelCase							(							self	) ->				Any:






         """simple docstring"""






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

         A       :   Union[str, Any]					=						AutoProcessor.from_pretrained('''hf-internal-testing/test_dynamic_processor'''						,			trust_remote_code=SCREAMING_SNAKE_CASE	)
         self.assertTrue(processor.special_attribute_present	)
         self.assertEqual(processor.__class__.__name__						,			'''NewProcessor'''	)

         A       :   List[str]					=						processor.feature_extractor
         self.assertTrue(feature_extractor.special_attribute_present	)
         self.assertEqual(feature_extractor.__class__.__name__						,			'''NewFeatureExtractor'''	)

         A       :   Tuple					=						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       :   List[str]					=						AutoProcessor.from_pretrained(
                 '''hf-internal-testing/test_dynamic_processor'''						,			trust_remote_code=SCREAMING_SNAKE_CASE						,			use_fast=SCREAMING_SNAKE_CASE	)
             A       :   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 				__lowerCAmelCase							(							self	) ->				Optional[Any]:






         """simple docstring"""






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

             # Now that the config is registered, it can be used as any other config with the auto-API
             A       :   List[Any]					=						CustomFeatureExtractor.from_pretrained(SCREAMING_SNAKE_CASE	)

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

             A       :   Any					=						CustomProcessor(SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE	)

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

         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 				__lowerCAmelCase							(							self	) ->				Optional[int]:






         """simple docstring"""






         class  A				(							__snake_case						):
              __magic_name__						=		False





         class  A				(							__snake_case						):
              __magic_name__						=		False





         class  A				(							__snake_case						):
              __magic_name__						=		'''AutoFeatureExtractor'''
              __magic_name__						=		'''AutoTokenizer'''
              __magic_name__						=		False

         try:
             AutoConfig.register('''custom'''						,			SCREAMING_SNAKE_CASE	)
             AutoFeatureExtractor.register(SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE	)
             AutoTokenizer.register(SCREAMING_SNAKE_CASE						,			slow_tokenizer_class=SCREAMING_SNAKE_CASE	)
             AutoProcessor.register(SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE	)
             # 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       :   Optional[int]					=						AutoProcessor.from_pretrained(
                 '''hf-internal-testing/test_dynamic_processor'''						,			trust_remote_code=SCREAMING_SNAKE_CASE	)
             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       :   Tuple					=						AutoProcessor.from_pretrained(
                 '''hf-internal-testing/test_dynamic_processor'''						,			trust_remote_code=SCREAMING_SNAKE_CASE	)
             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 				__lowerCAmelCase							(							self	) ->				str:






         """simple docstring"""






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





     def 				__lowerCAmelCase							(							self	) ->				str:






         """simple docstring"""






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





@is_staging_test
class  A				(							unittest.TestCase						):
     __magic_name__						=		['''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''bla''', '''blou''']





     @classmethod
     def 				__lowerCAmelCase							(							cls	) ->				Dict:






         """simple docstring"""






         A       :   Optional[int]					=						TOKEN
         HfFolder.save_token(SCREAMING_SNAKE_CASE	)





     @classmethod
     def 				__lowerCAmelCase							(							cls	) ->				Any:






         """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 				__lowerCAmelCase							(							self	) ->				Dict:






         """simple docstring"""






         A       :   Union[str, Any]					=						WavaVecaProcessor.from_pretrained(SCREAMING_SNAKE_CASE	)
         with tempfile.TemporaryDirectory() as tmp_dir:
             processor.save_pretrained(
                 os.path.join(SCREAMING_SNAKE_CASE						,			'''test-processor'''	)						,			push_to_hub=SCREAMING_SNAKE_CASE						,			use_auth_token=self._token	)

             A       :   int					=						WavaVecaProcessor.from_pretrained(F'{USER}/test-processor'	)
             for k, v in processor.feature_extractor.__dict__.items():
                 self.assertEqual(SCREAMING_SNAKE_CASE						,			getattr(new_processor.feature_extractor						,			SCREAMING_SNAKE_CASE	)	)
             self.assertDictEqual(new_processor.tokenizer.get_vocab()						,			processor.tokenizer.get_vocab()	)





     def 				__lowerCAmelCase							(							self	) ->				Optional[int]:






         """simple docstring"""






         A       :   Tuple					=						WavaVecaProcessor.from_pretrained(SCREAMING_SNAKE_CASE	)

         with tempfile.TemporaryDirectory() as tmp_dir:
             processor.save_pretrained(
                 os.path.join(SCREAMING_SNAKE_CASE						,			'''test-processor-org'''	)						,			push_to_hub=SCREAMING_SNAKE_CASE						,			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(SCREAMING_SNAKE_CASE						,			getattr(new_processor.feature_extractor						,			SCREAMING_SNAKE_CASE	)	)
             self.assertDictEqual(new_processor.tokenizer.get_vocab()						,			processor.tokenizer.get_vocab()	)





     def 				__lowerCAmelCase							(							self	) ->				str:






         """simple docstring"""






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

         A       :   Any					=						CustomFeatureExtractor.from_pretrained(SCREAMING_SNAKE_CASE	)

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

         A       :   Union[str, Any]					=						CustomProcessor(SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE	)

         with tempfile.TemporaryDirectory() as tmp_dir:
             create_repo(F'{USER}/test-dynamic-processor'						,			token=self._token	)
             A       :   List[str]					=						Repository(SCREAMING_SNAKE_CASE						,			clone_from=F'{USER}/test-dynamic-processor'						,			token=self._token	)
             processor.save_pretrained(SCREAMING_SNAKE_CASE	)

             # 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(SCREAMING_SNAKE_CASE						,			'''tokenizer_config.json'''	)	) as f:
                 A       :   Dict					=						json.load(SCREAMING_SNAKE_CASE	)
             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(SCREAMING_SNAKE_CASE						,			'''custom_feature_extraction.py'''	)	)	)
             self.assertTrue(os.path.isfile(os.path.join(SCREAMING_SNAKE_CASE						,			'''custom_tokenization.py'''	)	)	)
             self.assertTrue(os.path.isfile(os.path.join(SCREAMING_SNAKE_CASE						,			'''custom_processing.py'''	)	)	)

             repo.push_to_hub()

         A       :   Optional[int]					=						AutoProcessor.from_pretrained(F'{USER}/test-dynamic-processor'						,			trust_remote_code=SCREAMING_SNAKE_CASE	)
         # 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'''	)




