
import inspect
import tempfile
import unittest

from huggingface_hub import hf_hub_download

from transformers import is_torch_available
from transformers.testing_utils import is_flaky, require_torch, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


a					:	int							=		1E-4

if is_torch_available():
 import torch

 from transformers import AutoformerConfig, AutoformerForPrediction, AutoformerModel
 from transformers.models.autoformer.modeling_autoformer import AutoformerDecoder, AutoformerEncoder




@require_torch
class 		a_						:







    def __init__(			self			:       Dict     ,					__UpperCamelCase			:       List[str]     ,					__UpperCamelCase			:       Optional[int]=16     ,					__UpperCamelCase			:       Union[str, Any]=13     ,					__UpperCamelCase			:       Optional[Any]=7     ,					__UpperCamelCase			:       Dict=14     ,					__UpperCamelCase			:       Tuple=10     ,					__UpperCamelCase			:       Any=19     ,					__UpperCamelCase			:       int=5     ,					__UpperCamelCase			:       str=4     ,					__UpperCamelCase			:       Dict=True     ,					__UpperCamelCase			:       Optional[int]=16     ,					__UpperCamelCase			:       str=2     ,					__UpperCamelCase			:       List[str]=4     ,					__UpperCamelCase			:       int=4     ,					__UpperCamelCase			:       Tuple="gelu"     ,					__UpperCamelCase			:       Dict=0.1     ,					__UpperCamelCase			:       Optional[int]=0.1     ,					__UpperCamelCase			:       Union[str, Any]=[1, 2, 3, 4, 5]     ,					__UpperCamelCase			:       Tuple=25     ,					__UpperCamelCase			:       List[Any]=5     ,					)		->List[Any]:






        '''simple docstring'''






        _UpperCAmelCase          =   d_model
        _UpperCAmelCase          =   parent
        _UpperCAmelCase          =   batch_size
        _UpperCAmelCase          =   prediction_length
        _UpperCAmelCase          =   context_length
        _UpperCAmelCase          =   cardinality
        _UpperCAmelCase          =   num_time_features
        _UpperCAmelCase          =   lags_sequence
        _UpperCAmelCase          =   embedding_dimension
        _UpperCAmelCase          =   is_training
        _UpperCAmelCase          =   hidden_size
        _UpperCAmelCase          =   num_hidden_layers
        _UpperCAmelCase          =   num_attention_heads
        _UpperCAmelCase          =   intermediate_size
        _UpperCAmelCase          =   hidden_act
        _UpperCAmelCase          =   hidden_dropout_prob
        _UpperCAmelCase          =   attention_probs_dropout_prob

        _UpperCAmelCase          =   context_length
        _UpperCAmelCase          =   prediction_length + label_length
        _UpperCAmelCase          =   label_length

        _UpperCAmelCase          =   moving_average
        _UpperCAmelCase          =   autocorrelation_factor







    def      _snake_case					(			self			:       Optional[int]     )		->Optional[Any]:






        '''simple docstring'''






        return AutoformerConfig(
            d_model=self.d_model     ,					encoder_layers=self.num_hidden_layers     ,					decoder_layers=self.num_hidden_layers     ,					encoder_attention_heads=self.num_attention_heads     ,					decoder_attention_heads=self.num_attention_heads     ,					encoder_ffn_dim=self.intermediate_size     ,					decoder_ffn_dim=self.intermediate_size     ,					dropout=self.hidden_dropout_prob     ,					attention_dropout=self.attention_probs_dropout_prob     ,					prediction_length=self.prediction_length     ,					context_length=self.context_length     ,					label_length=self.label_length     ,					lags_sequence=self.lags_sequence     ,					num_time_features=self.num_time_features     ,					num_static_categorical_features=1     ,					cardinality=[self.cardinality]     ,					embedding_dimension=[self.embedding_dimension]     ,					moving_average=self.moving_average     ,					)







    def      _snake_case					(			self			:       Optional[int]     ,					__UpperCamelCase			:       Dict     )		->Tuple:






        '''simple docstring'''






        _UpperCAmelCase          =   config.context_length + max(config.lags_sequence     )

        _UpperCAmelCase          =   ids_tensor([self.batch_size, 1]     ,					config.cardinality[0]     )
        _UpperCAmelCase          =   floats_tensor([self.batch_size, _past_length, config.num_time_features]     )
        _UpperCAmelCase          =   floats_tensor([self.batch_size, _past_length]     )
        _UpperCAmelCase          =   floats_tensor([self.batch_size, _past_length]     ) > 0.5

        # decoder inputs
        _UpperCAmelCase          =   floats_tensor([self.batch_size, config.prediction_length, config.num_time_features]     )
        _UpperCAmelCase          =   floats_tensor([self.batch_size, config.prediction_length]     )

        _UpperCAmelCase          =   {
            """past_values""": past_values,
            """static_categorical_features""": static_categorical_features,
            """past_time_features""": past_time_features,
            """past_observed_mask""": past_observed_mask,
            """future_time_features""": future_time_features,
            """future_values""": future_values,
        }
        return inputs_dict







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






        '''simple docstring'''






        _UpperCAmelCase          =   self.get_config()
        _UpperCAmelCase          =   self.prepare_autoformer_inputs_dict(__UpperCamelCase     )
        return config, inputs_dict







    def      _snake_case					(			self			:       str     )		->List[Any]:






        '''simple docstring'''






        _UpperCAmelCase    ,_UpperCAmelCase          =   self.prepare_config_and_inputs()
        return config, inputs_dict







    def      _snake_case					(			self			:       Optional[Any]     ,					__UpperCamelCase			:       str     ,					__UpperCamelCase			:       Tuple     )		->Optional[Any]:






        '''simple docstring'''






        _UpperCAmelCase          =   AutoformerModel(config=__UpperCamelCase     ).to(__UpperCamelCase     ).eval()
        _UpperCAmelCase          =   model(**__UpperCamelCase     )

        _UpperCAmelCase          =   outputs.encoder_last_hidden_state
        _UpperCAmelCase          =   outputs.last_hidden_state

        with tempfile.TemporaryDirectory() as tmpdirname:
            _UpperCAmelCase          =   model.get_encoder()
            encoder.save_pretrained(__UpperCamelCase     )
            _UpperCAmelCase          =   AutoformerEncoder.from_pretrained(__UpperCamelCase     ).to(__UpperCamelCase     )

        _UpperCAmelCase    ,_UpperCAmelCase    ,_UpperCAmelCase    ,_UpperCAmelCase    ,_UpperCAmelCase          =   model.create_network_inputs(**__UpperCamelCase     )
        _UpperCAmelCase    ,_UpperCAmelCase          =   model.decomposition_layer(transformer_inputs[:, : config.context_length, ...]     )

        _UpperCAmelCase          =   torch.cat(
            (transformer_inputs[:, : config.context_length, ...], feature[:, : config.context_length, ...])     ,					dim=-1     ,					)
        _UpperCAmelCase          =   encoder(inputs_embeds=__UpperCamelCase     )[0]
        self.parent.assertTrue((encoder_last_hidden_state_a - encoder_last_hidden_state).abs().max().item() < 1e-3     )

        _UpperCAmelCase          =   (
            torch.mean(transformer_inputs[:, : config.context_length, ...]     ,					dim=1     )
            .unsqueeze(1     )
            .repeat(1     ,					config.prediction_length     ,					1     )
        )
        _UpperCAmelCase          =   torch.zeros(
            [transformer_inputs.shape[0], config.prediction_length, transformer_inputs.shape[2]]     ,					device=enc_input.device     ,					)

        _UpperCAmelCase          =   torch.cat(
            (
                torch.cat((seasonal_input[:, -config.label_length :, ...], zeros)     ,					dim=1     ),
                feature[:, config.context_length - config.label_length :, ...],
            )     ,					dim=-1     ,					)
        _UpperCAmelCase          =   torch.cat(
            (
                torch.cat((trend_input[:, -config.label_length :, ...], mean)     ,					dim=1     ),
                feature[:, config.context_length - config.label_length :, ...],
            )     ,					dim=-1     ,					)

        with tempfile.TemporaryDirectory() as tmpdirname:
            _UpperCAmelCase          =   model.get_decoder()
            decoder.save_pretrained(__UpperCamelCase     )
            _UpperCAmelCase          =   AutoformerDecoder.from_pretrained(__UpperCamelCase     ).to(__UpperCamelCase     )

        _UpperCAmelCase          =   decoder(
            trend=__UpperCamelCase     ,					inputs_embeds=__UpperCamelCase     ,					encoder_hidden_states=__UpperCamelCase     ,					)[0]

        self.parent.assertTrue((last_hidden_state_a - last_hidden_state).abs().max().item() < 1e-3     )







@require_torch
class 		a_						( _UpperCAmelCase     ,						_UpperCAmelCase     ,						unittest.TestCase	):
    a      :				List[str]     =				(AutoformerModel, AutoformerForPrediction) if is_torch_available() else ()
    a      :				Any     =				(AutoformerForPrediction,) if is_torch_available() else ()
    a      :				Optional[Any]     =				{'feature-extraction': AutoformerModel} if is_torch_available() else {}
    a      :				Optional[int]     =				False
    a      :				List[str]     =				False
    a      :				Optional[int]     =				False
    a      :				Optional[int]     =				False
    a      :				List[Any]     =				False
    a      :				Optional[int]     =				False







    def      _snake_case					(			self			:       List[str]     )		->Optional[Any]:






        '''simple docstring'''






        _UpperCAmelCase          =   AutoformerModelTester(self     )
        _UpperCAmelCase          =   ConfigTester(self     ,					config_class=__UpperCamelCase     ,					has_text_modality=__UpperCamelCase     )







    def      _snake_case					(			self			:       str     )		->int:






        '''simple docstring'''






        self.config_tester.run_common_tests()







    def      _snake_case					(			self			:       Any     )		->int:






        '''simple docstring'''






        _UpperCAmelCase    ,_UpperCAmelCase          =   self.model_tester.prepare_config_and_inputs()
        for model_class in self.all_model_classes:
            _UpperCAmelCase          =   model_class(__UpperCamelCase     )

            with tempfile.TemporaryDirectory() as tmpdirname:
                model.save_pretrained(__UpperCamelCase     )
                _UpperCAmelCase    ,_UpperCAmelCase          =   model_class.from_pretrained(__UpperCamelCase     ,					output_loading_info=__UpperCamelCase     )
            self.assertEqual(info["""missing_keys"""]     ,					[]     )







    def      _snake_case					(			self			:       str     )		->List[Any]:






        '''simple docstring'''






        _UpperCAmelCase          =   self.model_tester.prepare_config_and_inputs_for_common()
        self.model_tester.check_encoder_decoder_model_standalone(*__UpperCamelCase     )







    @unittest.skip(reason="""Model has no tokens embeddings"""     )
    def      _snake_case					(			self			:       Union[str, Any]     )		->int:






        '''simple docstring'''






        pass







    def      _snake_case					(			self			:       Tuple     )		->Any:






        '''simple docstring'''






        _UpperCAmelCase          =   inspect.signature(getattr(__UpperCamelCase     ,					"""forward"""     )     )
        # The main input is the name of the argument after `self`
        _UpperCAmelCase          =   list(model_signature.parameters.keys()     )[1]
        self.assertEqual(AutoformerModel.main_input_name     ,					__UpperCamelCase     )







    def      _snake_case					(			self			:       Any     )		->str:






        '''simple docstring'''






        _UpperCAmelCase    ,_UpperCAmelCase          =   self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
            _UpperCAmelCase          =   model_class(__UpperCamelCase     )
            _UpperCAmelCase          =   inspect.signature(model.forward     )
            # signature.parameters is an OrderedDict => so arg_names order is deterministic
            _UpperCAmelCase          =   [*signature.parameters.keys()]

            _UpperCAmelCase          =   [
                """past_values""",
                """past_time_features""",
                """past_observed_mask""",
                """static_categorical_features""",
                """static_real_features""",
                """future_values""",
                """future_time_features""",
            ]

            if model.__class__.__name__ in ["AutoformerForPrediction"]:
                expected_arg_names.append("""future_observed_mask"""     )

            expected_arg_names.extend(
                [
                    """decoder_attention_mask""",
                    """head_mask""",
                    """decoder_head_mask""",
                    """cross_attn_head_mask""",
                    """encoder_outputs""",
                    """past_key_values""",
                    """output_hidden_states""",
                    """output_attentions""",
                    """use_cache""",
                    """return_dict""",
                ]     )

            self.assertListEqual(arg_names[: len(__UpperCamelCase     )]     ,					__UpperCamelCase     )







    def      _snake_case					(			self			:       int     )		->Any:






        '''simple docstring'''






        _UpperCAmelCase    ,_UpperCAmelCase          =   self.model_tester.prepare_config_and_inputs_for_common()
        _UpperCAmelCase          =   True

        _UpperCAmelCase          =   getattr(self.model_tester     ,					"""seq_length"""     ,					__UpperCamelCase     )
        _UpperCAmelCase          =   getattr(self.model_tester     ,					"""decoder_seq_length"""     ,					__UpperCamelCase     )
        _UpperCAmelCase          =   getattr(self.model_tester     ,					"""encoder_seq_length"""     ,					__UpperCamelCase     )
        _UpperCAmelCase          =   getattr(self.model_tester     ,					"""d_model"""     ,					__UpperCamelCase     )
        _UpperCAmelCase          =   getattr(self.model_tester     ,					"""num_attention_heads"""     ,					__UpperCamelCase     )
        _UpperCAmelCase          =   d_model // num_attention_heads

        for model_class in self.all_model_classes:
            _UpperCAmelCase          =   True
            _UpperCAmelCase          =   False
            _UpperCAmelCase          =   True
            _UpperCAmelCase          =   model_class(__UpperCamelCase     )
            model.to(__UpperCamelCase     )
            model.eval()
            with torch.no_grad():
                _UpperCAmelCase          =   model(**self._prepare_for_class(__UpperCamelCase     ,					__UpperCamelCase     )     )
            _UpperCAmelCase          =   outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions
            self.assertEqual(len(__UpperCamelCase     )     ,					self.model_tester.num_hidden_layers     )

            # check that output_attentions also work using config
            del inputs_dict["output_attentions"]
            _UpperCAmelCase          =   True
            _UpperCAmelCase          =   model_class(__UpperCamelCase     )
            model.to(__UpperCamelCase     )
            model.eval()
            with torch.no_grad():
                _UpperCAmelCase          =   model(**self._prepare_for_class(__UpperCamelCase     ,					__UpperCamelCase     )     )
            _UpperCAmelCase          =   outputs.encoder_attentions
            self.assertEqual(len(__UpperCamelCase     )     ,					self.model_tester.num_hidden_layers     )

            self.assertListEqual(
                list(attentions[0].shape[-3:]     )     ,					[self.model_tester.num_attention_heads, encoder_seq_length, dim]     ,					)
            _UpperCAmelCase          =   len(__UpperCamelCase     )

            _UpperCAmelCase          =   7

            if "last_hidden_state" in outputs:
                correct_outlen += 1

            if "trend" in outputs:
                correct_outlen += 1

            if "past_key_values" in outputs:
                correct_outlen += 1  # past_key_values have been returned

            if "loss" in outputs:
                correct_outlen += 1

            if "params" in outputs:
                correct_outlen += 1

            self.assertEqual(__UpperCamelCase     ,					__UpperCamelCase     )

            # decoder attentions
            _UpperCAmelCase          =   outputs.decoder_attentions
            self.assertIsInstance(__UpperCamelCase     ,					(list, tuple)     )
            self.assertEqual(len(__UpperCamelCase     )     ,					self.model_tester.num_hidden_layers     )
            self.assertListEqual(
                list(decoder_attentions[0].shape[-3:]     )     ,					[self.model_tester.num_attention_heads, decoder_seq_length, dim]     ,					)

            # cross attentions
            _UpperCAmelCase          =   outputs.cross_attentions
            self.assertIsInstance(__UpperCamelCase     ,					(list, tuple)     )
            self.assertEqual(len(__UpperCamelCase     )     ,					self.model_tester.num_hidden_layers     )
            self.assertListEqual(
                list(cross_attentions[0].shape[-3:]     )     ,					[self.model_tester.num_attention_heads, decoder_seq_length, dim]     ,					)

        # Check attention is always last and order is fine
        _UpperCAmelCase          =   True
        _UpperCAmelCase          =   True
        _UpperCAmelCase          =   model_class(__UpperCamelCase     )
        model.to(__UpperCamelCase     )
        model.eval()
        with torch.no_grad():
            _UpperCAmelCase          =   model(**self._prepare_for_class(__UpperCamelCase     ,					__UpperCamelCase     )     )

        self.assertEqual(out_len + 2     ,					len(__UpperCamelCase     )     )

        _UpperCAmelCase          =   outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions

        self.assertEqual(len(__UpperCamelCase     )     ,					self.model_tester.num_hidden_layers     )
        self.assertListEqual(
            list(self_attentions[0].shape[-3:]     )     ,					[self.model_tester.num_attention_heads, encoder_seq_length, dim]     ,					)







    @is_flaky()
    def      _snake_case					(			self			:       Union[str, Any]     )		->Tuple:






        '''simple docstring'''






        super().test_retain_grad_hidden_states_attentions()







def  _UpperCamelCase	(						_A="train-batch.pt"      )    ->  Optional[int]:





    """simple docstring"""

    _UpperCAmelCase          =   hf_hub_download(repo_id="""hf-internal-testing/tourism-monthly-batch"""					,      filename=_A					,      repo_type="""dataset"""      )
    _UpperCAmelCase          =   torch.load(_A					,      map_location=_A      )
    return batch







@require_torch
@slow
class 		a_						( unittest.TestCase	):







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






        '''simple docstring'''






        _UpperCAmelCase          =   AutoformerModel.from_pretrained("""huggingface/autoformer-tourism-monthly"""     ).to(__UpperCamelCase     )
        _UpperCAmelCase          =   prepare_batch()

        with torch.no_grad():
            _UpperCAmelCase          =   model(
                past_values=batch["""past_values"""]     ,					past_time_features=batch["""past_time_features"""]     ,					past_observed_mask=batch["""past_observed_mask"""]     ,					static_categorical_features=batch["""static_categorical_features"""]     ,					future_values=batch["""future_values"""]     ,					future_time_features=batch["""future_time_features"""]     ,					)[0]

        _UpperCAmelCase          =   torch.Size(
            (64, model.config.prediction_length + model.config.label_length, model.config.feature_size)     )
        self.assertEqual(output.shape     ,					__UpperCamelCase     )

        _UpperCAmelCase          =   torch.tensor(
            [[0.3_5_9_3, -1.3_3_9_8, 0.6_3_3_0], [0.2_2_7_9, 1.5_3_9_6, -0.1_7_9_2], [0.0_4_5_0, 1.3_2_2_5, -0.2_3_3_5]]     ,					device=__UpperCamelCase     )
        self.assertTrue(torch.allclose(output[0, :3, :3]     ,					__UpperCamelCase     ,					atol=__UpperCamelCase     )     )







    def      _snake_case					(			self			:       int     )		->List[str]:






        '''simple docstring'''






        _UpperCAmelCase          =   AutoformerForPrediction.from_pretrained("""huggingface/autoformer-tourism-monthly"""     ).to(__UpperCamelCase     )
        _UpperCAmelCase          =   prepare_batch("""val-batch.pt"""     )
        with torch.no_grad():
            _UpperCAmelCase          =   model(
                past_values=batch["""past_values"""]     ,					past_time_features=batch["""past_time_features"""]     ,					past_observed_mask=batch["""past_observed_mask"""]     ,					static_categorical_features=batch["""static_categorical_features"""]     ,					).encoder_last_hidden_state
        _UpperCAmelCase          =   torch.Size((64, model.config.context_length, model.config.d_model)     )
        self.assertEqual(output.shape     ,					__UpperCamelCase     )

        _UpperCAmelCase          =   torch.tensor(
            [[-0.0_7_3_4, -0.9_0_3_6, 0.8_3_5_8], [4.7_1_8_6, 2.4_1_1_3, 1.9_5_8_1], [1.7_9_5_3, 2.3_5_5_8, 1.2_9_7_0]]     ,					device=__UpperCamelCase     )
        self.assertTrue(torch.allclose(output[0, :3, :3]     ,					__UpperCamelCase     ,					atol=__UpperCamelCase     )     )







    def      _snake_case					(			self			:       Dict     )		->int:






        '''simple docstring'''






        _UpperCAmelCase          =   AutoformerForPrediction.from_pretrained("""huggingface/autoformer-tourism-monthly"""     ).to(__UpperCamelCase     )
        _UpperCAmelCase          =   prepare_batch("""val-batch.pt"""     )
        with torch.no_grad():
            _UpperCAmelCase          =   model.generate(
                static_categorical_features=batch["""static_categorical_features"""]     ,					past_time_features=batch["""past_time_features"""]     ,					past_values=batch["""past_values"""]     ,					future_time_features=batch["""future_time_features"""]     ,					past_observed_mask=batch["""past_observed_mask"""]     ,					)
        _UpperCAmelCase          =   torch.Size((64, model.config.num_parallel_samples, model.config.prediction_length)     )
        self.assertEqual(outputs.sequences.shape     ,					__UpperCamelCase     )

        _UpperCAmelCase          =   torch.tensor([31_30.67_63, 40_56.52_93, 70_53.07_86]     ,					device=__UpperCamelCase     )
        _UpperCAmelCase          =   outputs.sequences.mean(dim=1     )
        self.assertTrue(torch.allclose(mean_prediction[0, -3:]     ,					__UpperCamelCase     ,					rtol=1e-1     )     )

"""simple docstring"""



import argparse
import os
import re

import packaging.version


a					:	str							=		'''examples/'''
a					:	List[str]							=		{
    '''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					:	Tuple							=		{
    '''init''': '''src/diffusers/__init__.py''',
    '''setup''': '''setup.py''',
}
a					:	List[str]							=		'''README.md'''


def  _UpperCamelCase	(						_A					,      _A					,      _A      )    ->  Dict:





    """simple docstring"""

    with open(_A					,      """r"""					,      encoding="""utf-8"""					,      newline="""\n"""      ) as f:
        _UpperCAmelCase          =   f.read()
    _UpperCAmelCase    ,_UpperCAmelCase          =   REPLACE_PATTERNS[pattern]
    _UpperCAmelCase          =   replace.replace("""VERSION"""					,      _A      )
    _UpperCAmelCase          =   re_pattern.sub(_A					,      _A      )
    with open(_A					,      """w"""					,      encoding="""utf-8"""					,      newline="""\n"""      ) as f:
        f.write(_A      )


def  _UpperCamelCase	(						_A      )    ->  Union[str, Any]:





    """simple docstring"""

    for folder, directories, fnames in os.walk(_A      ):
        # 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(_A					,      _A      )					,      _A					,      pattern="""examples"""      )


def  _UpperCamelCase	(						_A					,      _A=False      )    ->  int:





    """simple docstring"""

    for pattern, fname in REPLACE_FILES.items():
        update_version_in_file(_A					,      _A					,      _A      )
    if not patch:
        update_version_in_examples(_A      )


def  _UpperCamelCase	(						)    ->  Any:





    """simple docstring"""

    _UpperCAmelCase          =   """🤗 Transformers currently provides the following architectures"""
    _UpperCAmelCase          =   """1. Want to contribute a new model?"""
    with open(_A					,      """r"""					,      encoding="""utf-8"""					,      newline="""\n"""      ) as f:
        _UpperCAmelCase          =   f.readlines()

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

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

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


def  _UpperCamelCase	(						)    ->  Optional[int]:





    """simple docstring"""

    with open(REPLACE_FILES["""init"""]					,      """r"""      ) as f:
        _UpperCAmelCase          =   f.read()
    _UpperCAmelCase          =   REPLACE_PATTERNS["""init"""][0].search(_A      ).groups()[0]
    return packaging.version.parse(_A      )


def  _UpperCamelCase	(						_A=False      )    ->  List[Any]:





    """simple docstring"""

    _UpperCAmelCase          =   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:
        _UpperCAmelCase          =   default_version.base_version
    elif patch:
        _UpperCAmelCase          =   F"""{default_version.major}.{default_version.minor}.{default_version.micro + 1}"""
    else:
        _UpperCAmelCase          =   F"""{default_version.major}.{default_version.minor + 1}.0"""

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

    print(F"""Updating version to {version}."""      )
    global_version_update(_A					,      patch=_A      )


def  _UpperCamelCase	(						)    ->  List[Any]:





    """simple docstring"""

    _UpperCAmelCase          =   get_version()
    _UpperCAmelCase          =   F"""{current_version.major}.{current_version.minor + 1}.0.dev0"""
    _UpperCAmelCase          =   current_version.base_version

    # Check with the user we got that right.
    _UpperCAmelCase          =   input(F"""Which version are we developing now? [{dev_version}]"""      )
    if len(_A      ) == 0:
        _UpperCAmelCase          =   dev_version

    print(F"""Updating version to {version}."""      )
    global_version_update(_A      )


#    print("Cleaning main README, don't forget to run `make fix-copies`.")
#    clean_main_ref_in_model_list()


if __name__ == "__main__":
 a					:	Dict							=		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					:	Tuple							=		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()