
"""simple docstring"""







import gc
import random
import unittest

import numpy as np
import torch
from transformers import (
    CLIPImageProcessor,
    CLIPTextConfig,
    CLIPTextModelWithProjection,
    CLIPTokenizer,
    CLIPVisionConfig,
    CLIPVisionModelWithProjection,
)

from diffusers import (
    DiffusionPipeline,
    UnCLIPImageVariationPipeline,
    UnCLIPScheduler,
    UNetaDConditionModel,
    UNetaDModel,
)
from diffusers.pipelines.unclip.text_proj import UnCLIPTextProjModel
from diffusers.utils import floats_tensor, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, load_image, require_torch_gpu, skip_mps

from ..pipeline_params import IMAGE_VARIATION_BATCH_PARAMS, IMAGE_VARIATION_PARAMS
from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference


enable_full_determinism()




class  A__       (	_lowerCamelCase       ,     unittest.TestCase):
		A_						:       Optional[int]				   =	UnCLIPImageVariationPipeline
		A_						:       Optional[int]				   =	IMAGE_VARIATION_PARAMS - {'height', 'width', 'guidance_scale'}
		A_						:       Dict				   =	IMAGE_VARIATION_BATCH_PARAMS

		A_						:       Dict				   =	[
		    'generator',
		    'return_dict',
		    'decoder_num_inference_steps',
		    'super_res_num_inference_steps',
		]
		A_						:       Dict				   =	False

		@property
		def 							__lowerCamelCase							(      self ):
			return 32

		@property
		def 							__lowerCamelCase							(      self ):
			return 32

		@property
		def 							__lowerCamelCase							(      self ):
			return self.time_input_dim

		@property
		def 							__lowerCamelCase							(      self ):
			return self.time_input_dim * 4

		@property
		def 							__lowerCamelCase							(      self ):
			return 1_00

		@property
		def 							__lowerCamelCase							(      self ):
			__lowerCAmelCase			:						int									=      CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' )
			return tokenizer

		@property
		def 							__lowerCamelCase							(      self ):
			torch.manual_seed(0 )
			__lowerCAmelCase			:						int									=      CLIPTextConfig(
			    bos_token_id=0       ,		eos_token_id=2       ,		hidden_size=self.text_embedder_hidden_size       ,		projection_dim=self.text_embedder_hidden_size       ,		intermediate_size=37       ,		layer_norm_eps=1E-05       ,		num_attention_heads=4       ,		num_hidden_layers=5       ,		pad_token_id=1       ,		vocab_size=10_00       ,		)
			return CLIPTextModelWithProjection(_SCREAMING_SNAKE_CASE )

		@property
		def 							__lowerCamelCase							(      self ):
			torch.manual_seed(0 )
			__lowerCAmelCase			:						Tuple									=      CLIPVisionConfig(
			    hidden_size=self.text_embedder_hidden_size       ,		projection_dim=self.text_embedder_hidden_size       ,		num_hidden_layers=5       ,		num_attention_heads=4       ,		image_size=32       ,		intermediate_size=37       ,		patch_size=1       ,		)
			return CLIPVisionModelWithProjection(_SCREAMING_SNAKE_CASE )

		@property
		def 							__lowerCamelCase							(      self ):
			torch.manual_seed(0 )

			__lowerCAmelCase			:						List[str]									=      {
			    'clip_embeddings_dim': self.text_embedder_hidden_size,
			    'time_embed_dim': self.time_embed_dim,
			    'cross_attention_dim': self.cross_attention_dim,
			}

			__lowerCAmelCase			:						Tuple									=      UnCLIPTextProjModel(**_SCREAMING_SNAKE_CASE )
			return model

		@property
		def 							__lowerCamelCase							(      self ):
			torch.manual_seed(0 )

			__lowerCAmelCase			:						Optional[int]									=      {
			    'sample_size': 32,
			    # RGB in channels
			    'in_channels': 3,
			    # Out channels is double in channels because predicts mean and variance
			    'out_channels': 6,
			    'down_block_types': ('ResnetDownsampleBlock2D', 'SimpleCrossAttnDownBlock2D'),
			    'up_block_types': ('SimpleCrossAttnUpBlock2D', 'ResnetUpsampleBlock2D'),
			    'mid_block_type': 'UNetMidBlock2DSimpleCrossAttn',
			    'block_out_channels': (self.block_out_channels_a, self.block_out_channels_a * 2),
			    'layers_per_block': 1,
			    'cross_attention_dim': self.cross_attention_dim,
			    'attention_head_dim': 4,
			    'resnet_time_scale_shift': 'scale_shift',
			    'class_embed_type': 'identity',
			}

			__lowerCAmelCase			:						Optional[Any]									=      UNetaDConditionModel(**_SCREAMING_SNAKE_CASE )
			return model

		@property
		def 							__lowerCamelCase							(      self ):
			return {
			    "sample_size": 64,
			    "layers_per_block": 1,
			    "down_block_types": ("ResnetDownsampleBlock2D", "ResnetDownsampleBlock2D"),
			    "up_block_types": ("ResnetUpsampleBlock2D", "ResnetUpsampleBlock2D"),
			    "block_out_channels": (self.block_out_channels_a, self.block_out_channels_a * 2),
			    "in_channels": 6,
			    "out_channels": 3,
			}

		@property
		def 							__lowerCamelCase							(      self ):
			torch.manual_seed(0 )

			__lowerCAmelCase			:						List[Any]									=      UNetaDModel(**self.dummy_super_res_kwargs )
			return model

		@property
		def 							__lowerCamelCase							(      self ):
			# seeded differently to get different unet than `self.dummy_super_res_first`
			torch.manual_seed(1 )

			__lowerCAmelCase			:						Dict									=      UNetaDModel(**self.dummy_super_res_kwargs )
			return model

		def 							__lowerCamelCase							(      self ):
			__lowerCAmelCase			:						str									=      self.dummy_decoder
			__lowerCAmelCase			:						int									=      self.dummy_text_proj
			__lowerCAmelCase			:						int									=      self.dummy_text_encoder
			__lowerCAmelCase			:						Any									=      self.dummy_tokenizer
			__lowerCAmelCase			:						List[Any]									=      self.dummy_super_res_first
			__lowerCAmelCase			:						List[str]									=      self.dummy_super_res_last

			__lowerCAmelCase			:						Dict									=      UnCLIPScheduler(
			    variance_type='learned_range'       ,		prediction_type='epsilon'       ,		num_train_timesteps=10_00       ,		)

			__lowerCAmelCase			:						Optional[Any]									=      UnCLIPScheduler(
			    variance_type='fixed_small_log'       ,		prediction_type='epsilon'       ,		num_train_timesteps=10_00       ,		)

			__lowerCAmelCase			:						Dict									=      CLIPImageProcessor(crop_size=32       ,		size=32 )

			__lowerCAmelCase			:						Any									=      self.dummy_image_encoder

			return {
			    "decoder": decoder,
			    "text_encoder": text_encoder,
			    "tokenizer": tokenizer,
			    "text_proj": text_proj,
			    "feature_extractor": feature_extractor,
			    "image_encoder": image_encoder,
			    "super_res_first": super_res_first,
			    "super_res_last": super_res_last,
			    "decoder_scheduler": decoder_scheduler,
			    "super_res_scheduler": super_res_scheduler,
			}

		def 							__lowerCamelCase							(      self       ,		_SCREAMING_SNAKE_CASE       ,		_SCREAMING_SNAKE_CASE=0       ,		_SCREAMING_SNAKE_CASE=True ):
			__lowerCAmelCase			:						Tuple									=      floats_tensor((1, 3, 32, 32)       ,		rng=random.Random(_SCREAMING_SNAKE_CASE ) ).to(_SCREAMING_SNAKE_CASE )
			if str(_SCREAMING_SNAKE_CASE ).startswith('mps' ):
				__lowerCAmelCase			:						int									=      torch.manual_seed(_SCREAMING_SNAKE_CASE )
			else:
				__lowerCAmelCase			:						List[Any]									=      torch.Generator(device=_SCREAMING_SNAKE_CASE ).manual_seed(_SCREAMING_SNAKE_CASE )

			if pil_image:
				__lowerCAmelCase			:						List[str]									=      input_image * 0.5 + 0.5
				__lowerCAmelCase			:						Optional[int]									=      input_image.clamp(0       ,		1 )
				__lowerCAmelCase			:						Optional[int]									=      input_image.cpu().permute(0       ,		2       ,		3       ,		1 ).float().numpy()
				__lowerCAmelCase			:						Any									=      DiffusionPipeline.numpy_to_pil(_SCREAMING_SNAKE_CASE )[0]

			return {
			    "image": input_image,
			    "generator": generator,
			    "decoder_num_inference_steps": 2,
			    "super_res_num_inference_steps": 2,
			    "output_type": "np",
			}

		def 							__lowerCamelCase							(      self ):
			__lowerCAmelCase			:						str									=      'cpu'

			__lowerCAmelCase			:						Optional[int]									=      self.get_dummy_components()

			__lowerCAmelCase			:						Tuple									=      self.pipeline_class(**_SCREAMING_SNAKE_CASE )
			__lowerCAmelCase			:						int									=      pipe.to(_SCREAMING_SNAKE_CASE )

			pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE )

			__lowerCAmelCase			:						str									=      self.get_dummy_inputs(_SCREAMING_SNAKE_CASE       ,		pil_image=_SCREAMING_SNAKE_CASE )

			__lowerCAmelCase			:						Optional[Any]									=      pipe(**_SCREAMING_SNAKE_CASE )
			__lowerCAmelCase			:						Dict									=      output.images

			__lowerCAmelCase			:						Optional[Any]									=      self.get_dummy_inputs(_SCREAMING_SNAKE_CASE       ,		pil_image=_SCREAMING_SNAKE_CASE )

			__lowerCAmelCase			:						Optional[int]									=      pipe(
			    **_SCREAMING_SNAKE_CASE       ,		return_dict=_SCREAMING_SNAKE_CASE       ,		)[0]

			__lowerCAmelCase			:						Any									=      image[0, -3:, -3:, -1]
			__lowerCAmelCase			:						Dict									=      image_from_tuple[0, -3:, -3:, -1]

			assert image.shape == (1, 64, 64, 3)

			__lowerCAmelCase			:						Any									=      np.array(
			    [
			        0.9997,
			        0.0002,
			        0.9997,
			        0.9997,
			        0.9969,
			        0.0023,
			        0.9997,
			        0.9969,
			        0.9970,
			    ] )

			assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
			assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2

		def 							__lowerCamelCase							(      self ):
			__lowerCAmelCase			:						Tuple									=      'cpu'

			__lowerCAmelCase			:						Any									=      self.get_dummy_components()

			__lowerCAmelCase			:						Tuple									=      self.pipeline_class(**_SCREAMING_SNAKE_CASE )
			__lowerCAmelCase			:						str									=      pipe.to(_SCREAMING_SNAKE_CASE )

			pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE )

			__lowerCAmelCase			:						str									=      self.get_dummy_inputs(_SCREAMING_SNAKE_CASE       ,		pil_image=_SCREAMING_SNAKE_CASE )

			__lowerCAmelCase			:						str									=      pipe(**_SCREAMING_SNAKE_CASE )
			__lowerCAmelCase			:						Union[str, Any]									=      output.images

			__lowerCAmelCase			:						Any									=      self.get_dummy_inputs(_SCREAMING_SNAKE_CASE       ,		pil_image=_SCREAMING_SNAKE_CASE )

			__lowerCAmelCase			:						Optional[Any]									=      pipe(
			    **_SCREAMING_SNAKE_CASE       ,		return_dict=_SCREAMING_SNAKE_CASE       ,		)[0]

			__lowerCAmelCase			:						Optional[Any]									=      image[0, -3:, -3:, -1]
			__lowerCAmelCase			:						List[Any]									=      image_from_tuple[0, -3:, -3:, -1]

			assert image.shape == (1, 64, 64, 3)

			__lowerCAmelCase			:						Union[str, Any]									=      np.array([0.9997, 0.0003, 0.9997, 0.9997, 0.9970, 0.0024, 0.9997, 0.9971, 0.9971] )

			assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
			assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2

		def 							__lowerCamelCase							(      self ):
			__lowerCAmelCase			:						Optional[Any]									=      'cpu'

			__lowerCAmelCase			:						Optional[int]									=      self.get_dummy_components()

			__lowerCAmelCase			:						Optional[int]									=      self.pipeline_class(**_SCREAMING_SNAKE_CASE )
			__lowerCAmelCase			:						int									=      pipe.to(_SCREAMING_SNAKE_CASE )

			pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE )

			__lowerCAmelCase			:						Tuple									=      self.get_dummy_inputs(_SCREAMING_SNAKE_CASE       ,		pil_image=_SCREAMING_SNAKE_CASE )
			__lowerCAmelCase			:						Optional[int]									=      [
			    pipeline_inputs['image'],
			    pipeline_inputs['image'],
			]

			__lowerCAmelCase			:						Dict									=      pipe(**_SCREAMING_SNAKE_CASE )
			__lowerCAmelCase			:						Optional[int]									=      output.images

			__lowerCAmelCase			:						List[Any]									=      self.get_dummy_inputs(_SCREAMING_SNAKE_CASE       ,		pil_image=_SCREAMING_SNAKE_CASE )
			__lowerCAmelCase			:						Dict									=      [
			    tuple_pipeline_inputs['image'],
			    tuple_pipeline_inputs['image'],
			]

			__lowerCAmelCase			:						List[Any]									=      pipe(
			    **_SCREAMING_SNAKE_CASE       ,		return_dict=_SCREAMING_SNAKE_CASE       ,		)[0]

			__lowerCAmelCase			:						Any									=      image[0, -3:, -3:, -1]
			__lowerCAmelCase			:						Dict									=      image_from_tuple[0, -3:, -3:, -1]

			assert image.shape == (2, 64, 64, 3)

			__lowerCAmelCase			:						Union[str, Any]									=      np.array(
			    [
			        0.9997,
			        0.9989,
			        0.0008,
			        0.0021,
			        0.9960,
			        0.0018,
			        0.0014,
			        0.0002,
			        0.9933,
			    ] )

			assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
			assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2

		def 							__lowerCamelCase							(      self ):
			__lowerCAmelCase			:						Union[str, Any]									=      torch.device('cpu' )




			class  A__       :
					A_						:       Any				   =	1



			__lowerCAmelCase			:						Any									=      self.get_dummy_components()

			__lowerCAmelCase			:						Optional[int]									=      self.pipeline_class(**_SCREAMING_SNAKE_CASE )
			__lowerCAmelCase			:						List[Any]									=      pipe.to(_SCREAMING_SNAKE_CASE )

			pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE )

			__lowerCAmelCase			:						Optional[int]									=      torch.Generator(device=_SCREAMING_SNAKE_CASE ).manual_seed(0 )
			__lowerCAmelCase			:						Any									=      pipe.decoder.dtype
			__lowerCAmelCase			:						Union[str, Any]									=      1

			__lowerCAmelCase			:						Dict									=      (
			    batch_size,
			    pipe.decoder.config.in_channels,
			    pipe.decoder.config.sample_size,
			    pipe.decoder.config.sample_size,
			)
			__lowerCAmelCase			:						List[Any]									=      pipe.prepare_latents(
			    _SCREAMING_SNAKE_CASE       ,		dtype=_SCREAMING_SNAKE_CASE       ,		device=_SCREAMING_SNAKE_CASE       ,		generator=_SCREAMING_SNAKE_CASE       ,		latents=_SCREAMING_SNAKE_CASE       ,		scheduler=DummyScheduler() )

			__lowerCAmelCase			:						Union[str, Any]									=      (
			    batch_size,
			    pipe.super_res_first.config.in_channels // 2,
			    pipe.super_res_first.config.sample_size,
			    pipe.super_res_first.config.sample_size,
			)
			__lowerCAmelCase			:						int									=      pipe.prepare_latents(
			    _SCREAMING_SNAKE_CASE       ,		dtype=_SCREAMING_SNAKE_CASE       ,		device=_SCREAMING_SNAKE_CASE       ,		generator=_SCREAMING_SNAKE_CASE       ,		latents=_SCREAMING_SNAKE_CASE       ,		scheduler=DummyScheduler() )

			__lowerCAmelCase			:						Tuple									=      self.get_dummy_inputs(_SCREAMING_SNAKE_CASE       ,		pil_image=_SCREAMING_SNAKE_CASE )

			__lowerCAmelCase			:						Any									=      pipe(
			    **_SCREAMING_SNAKE_CASE       ,		decoder_latents=_SCREAMING_SNAKE_CASE       ,		super_res_latents=_SCREAMING_SNAKE_CASE ).images

			__lowerCAmelCase			:						Tuple									=      self.get_dummy_inputs(_SCREAMING_SNAKE_CASE       ,		pil_image=_SCREAMING_SNAKE_CASE )
			# Don't pass image, instead pass embedding
			__lowerCAmelCase			:						List[str]									=      pipeline_inputs.pop('image' )
			__lowerCAmelCase			:						Optional[Any]									=      pipe.image_encoder(_SCREAMING_SNAKE_CASE ).image_embeds

			__lowerCAmelCase			:						Union[str, Any]									=      pipe(
			    **_SCREAMING_SNAKE_CASE       ,		decoder_latents=_SCREAMING_SNAKE_CASE       ,		super_res_latents=_SCREAMING_SNAKE_CASE       ,		image_embeddings=_SCREAMING_SNAKE_CASE       ,		).images

			# make sure passing text embeddings manually is identical
			assert np.abs(img_out_a - img_out_a ).max() < 1E-4

		@skip_mps
		def 							__lowerCamelCase							(      self ):
			__lowerCAmelCase			:						int									=      torch_device == 'cpu'

			# Check is relaxed because there is not a torch 2.0 sliced attention added kv processor
			__lowerCAmelCase			:						int									=      1E-2

			self._test_attention_slicing_forward_pass(
			    test_max_difference=_SCREAMING_SNAKE_CASE       ,		expected_max_diff=_SCREAMING_SNAKE_CASE )

		@skip_mps
		def 							__lowerCamelCase							(      self ):
			__lowerCAmelCase			:						Union[str, Any]									=      torch_device == 'cpu'
			__lowerCAmelCase			:						List[Any]									=      True
			__lowerCAmelCase			:						Optional[Any]									=      [
			    'decoder_num_inference_steps',
			    'super_res_num_inference_steps',
			]

			self._test_inference_batch_single_identical(
			    test_max_difference=_SCREAMING_SNAKE_CASE       ,		relax_max_difference=_SCREAMING_SNAKE_CASE       ,		additional_params_copy_to_batched_inputs=_SCREAMING_SNAKE_CASE       ,		)

		def 							__lowerCamelCase							(      self ):
			__lowerCAmelCase			:						List[Any]									=      [
			    'decoder_num_inference_steps',
			    'super_res_num_inference_steps',
			]

			if torch_device == "mps":
				# TODO: MPS errors with larger batch sizes
				__lowerCAmelCase			:						str									=      [2, 3]
				self._test_inference_batch_consistent(
				    batch_sizes=_SCREAMING_SNAKE_CASE       ,		additional_params_copy_to_batched_inputs=_SCREAMING_SNAKE_CASE       ,		)
			else:
				self._test_inference_batch_consistent(
				    additional_params_copy_to_batched_inputs=_SCREAMING_SNAKE_CASE )

		@skip_mps
		def 							__lowerCamelCase							(      self ):
			return super().test_dict_tuple_outputs_equivalent()

		@skip_mps
		def 							__lowerCamelCase							(      self ):
			return super().test_save_load_local()







		@skip_mps
		def 							__lowerCamelCase							(      self ):
			return super().test_save_load_optional_components()




@slow
@require_torch_gpu
class  A__       (	unittest.TestCase):

		def 							__lowerCamelCase							(      self ):
			# clean up the VRAM after each test
			super().tearDown()
			gc.collect()
			torch.cuda.empty_cache()







		def 							__lowerCamelCase							(      self ):
			__lowerCAmelCase			:						Optional[int]									=      load_image(
			    'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/unclip/cat.png' )
			__lowerCAmelCase			:						str									=      load_numpy(
			    'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
			    '/unclip/karlo_v1_alpha_cat_variation_fp16.npy' )

			__lowerCAmelCase			:						int									=      UnCLIPImageVariationPipeline.from_pretrained(
			    'kakaobrain/karlo-v1-alpha-image-variations'       ,		torch_dtype=torch.floataa )
			__lowerCAmelCase			:						List[str]									=      pipeline.to(_SCREAMING_SNAKE_CASE )
			pipeline.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE )

			__lowerCAmelCase			:						List[str]									=      torch.Generator(device='cpu' ).manual_seed(0 )
			__lowerCAmelCase			:						List[str]									=      pipeline(
			    _SCREAMING_SNAKE_CASE       ,		generator=_SCREAMING_SNAKE_CASE       ,		output_type='np'       ,		)

			__lowerCAmelCase			:						int									=      output.images[0]

			assert image.shape == (2_56, 2_56, 3)

			assert_mean_pixel_difference(_SCREAMING_SNAKE_CASE       ,		_SCREAMING_SNAKE_CASE       ,		15 )







"""simple docstring"""



import argparse
import os
import re

import packaging.version


__A		:       List[str]  				=		'''examples/'''
__A		:       int  				=		{
    '''examples''': (re.compile(R'''^check_min_version\("[^"]+"\)\s*$''', re.MULTILINE), '''check_min_version("VERSION")\n'''),
    '''init''': (re.compile(R'''^__version__\s+=\s+"([^"]+)"\s*$''', re.MULTILINE), '''__version__ = "VERSION"\n'''),
    '''setup''': (re.compile(R'''^(\s*)version\s*=\s*"[^"]+",''', re.MULTILINE), R'''\1version="VERSION",'''),
    '''doc''': (re.compile(R'''^(\s*)release\s*=\s*"[^"]+"$''', re.MULTILINE), '''release = "VERSION"\n'''),
}
__A		:       Dict  				=		{
    '''init''': '''src/transformers/__init__.py''',
    '''setup''': '''setup.py''',
}
__A		:       Optional[int]  				=		'''README.md'''



def 						lowercase    (				__snake_case				: int		,					__snake_case				: Any		,					__snake_case				: int	):
		with open(__snake_case		,					'''r'''		,					encoding='''utf-8'''		,					newline='''\n'''	) as f:
				lowercase_ : int							       =   f.read()
		lowercase_       ,					lowercase_ : List[str]							       =   REPLACE_PATTERNS[pattern]
		lowercase_ : Union[str, Any]							       =   replace.replace('''VERSION'''		,					__snake_case	)
		lowercase_ : Optional[Any]							       =   re_pattern.sub(__snake_case		,					__snake_case	)
		with open(__snake_case		,					'''w'''		,					encoding='''utf-8'''		,					newline='''\n'''	) as f:
				f.write(__snake_case	)



def 						lowercase    (				__snake_case				: int	):
		for folder, directories, fnames in os.walk(__snake_case	):
				# Removing some of the folders with non-actively maintained examples from the walk
				if "research_projects" in directories:
						directories.remove('''research_projects'''	)
				if "legacy" in directories:
						directories.remove('''legacy'''	)
				for fname in fnames:
						if fname.endswith('''.py'''	):
								update_version_in_file(os.path.join(__snake_case		,					__snake_case	)		,					__snake_case		,					pattern='''examples'''	)



def 						lowercase    (				__snake_case				: Optional[Any]		,					__snake_case				: Optional[Any]=False	):
		for pattern, fname in REPLACE_FILES.items():
				update_version_in_file(__snake_case		,					__snake_case		,					__snake_case	)
		if not patch:
				update_version_in_examples(__snake_case	)



def 						lowercase    (				):
		lowercase_ : Union[str, Any]							       =   '''🤗 Transformers currently provides the following architectures'''
		lowercase_ : Union[str, Any]							       =   '''1. Want to contribute a new model?'''
		with open(__snake_case		,					'''r'''		,					encoding='''utf-8'''		,					newline='''\n'''	) as f:
				lowercase_ : List[str]							       =   f.readlines()

		# Find the start of the list.
		lowercase_ : Optional[Any]							       =   0
		while not lines[start_index].startswith(_start_prompt	):
				start_index += 1
		start_index += 1

		lowercase_ : str							       =   start_index
		# Update the lines in the model list.
		while not lines[index].startswith(_end_prompt	):
				if lines[index].startswith('''1.'''	):
						lowercase_ : str							       =   lines[index].replace(
						    '''https://huggingface.co/docs/transformers/main/model_doc'''		,					'''https://huggingface.co/docs/transformers/model_doc'''		,					)
				index += 1

		with open(__snake_case		,					'''w'''		,					encoding='''utf-8'''		,					newline='''\n'''	) as f:
				f.writelines(__snake_case	)



def 						lowercase    (				):
		with open(REPLACE_FILES['''init''']		,					'''r'''	) as f:
				lowercase_ : List[Any]							       =   f.read()
		lowercase_ : List[str]							       =   REPLACE_PATTERNS['''init'''][0].search(__snake_case	).groups()[0]
		return packaging.version.parse(__snake_case	)



def 						lowercase    (				__snake_case				: Optional[Any]=False	):
		lowercase_ : str							       =   get_version()
		if patch and default_version.is_devrelease:
				raise ValueError('''Can\'t create a patch version from the dev branch, checkout a released version!'''	)
		if default_version.is_devrelease:
				lowercase_ : Optional[Any]							       =   default_version.base_version
		elif patch:
				lowercase_ : Optional[int]							       =   F'''{default_version.major}.{default_version.minor}.{default_version.micro + 1}'''
		else:
				lowercase_ : Optional[int]							       =   F'''{default_version.major}.{default_version.minor + 1}.0'''

		# Now let's ask nicely if that's the right one.
		lowercase_ : int							       =   input(F'''Which version are you releasing? [{default_version}]'''	)
		if len(__snake_case	) == 0:
				lowercase_ : Dict							       =   default_version

		print(F'''Updating version to {version}.'''	)
		global_version_update(__snake_case		,					patch=__snake_case	)
		if not patch:
				print('''Cleaning main README, don\'t forget to run `make fix-copies`.'''	)
				clean_main_ref_in_model_list()



def 						lowercase    (				):
		lowercase_ : List[Any]							       =   get_version()
		lowercase_ : List[str]							       =   F'''{current_version.major}.{current_version.minor + 1}.0.dev0'''
		lowercase_ : Any							       =   current_version.base_version

		# Check with the user we got that right.
		lowercase_ : Tuple							       =   input(F'''Which version are we developing now? [{dev_version}]'''	)
		if len(__snake_case	) == 0:
				lowercase_ : str							       =   dev_version

		print(F'''Updating version to {version}.'''	)
		global_version_update(__snake_case	)
		print('''Cleaning main README, don\'t forget to run `make fix-copies`.'''	)
		clean_main_ref_in_model_list()


if __name__ == "__main__":
						__A		:       int  				=		argparse.ArgumentParser()
						parser.add_argument('''--post_release''', action='''store_true''', help='''Whether this is pre or post release.''')
						parser.add_argument('''--patch''', action='''store_true''', help='''Whether or not this is a patch release.''')
						__A		:       Any  				=		parser.parse_args()
						if not args.post_release:
												pre_release_work(patch=args.patch)
						elif args.patch:
												print('''Nothing to do after a patch :-)''')
						else:
												post_release_work()



