


"""simple docstring"""







import argparse
import glob
import importlib.util
import os
import re

import black
from doc_builder.style_doc import style_docstrings_in_code


# All paths are set with the intent you should run this script from the root of the repo with the command
# python utils/check_copies.py
lowerCAmelCase__				    =       '''src/diffusers'''
lowerCAmelCase__				    =       '''.'''


# This is to make sure the diffusers module imported is the one in the repo.
lowerCAmelCase__				    =       importlib.util.spec_from_file_location(
    '''diffusers''',
    os.path.join(DIFFUSERS_PATH, '''__init__.py'''),
    submodule_search_locations=[DIFFUSERS_PATH],
)
lowerCAmelCase__				    =       spec.loader.load_module()
def  a__      (    SCREAMING_SNAKE_CASE   :   int    ,				SCREAMING_SNAKE_CASE   :   int    ):


  '''simple docstring'''







  return line.startswith(SCREAMING_SNAKE_CASE    ) or len(SCREAMING_SNAKE_CASE    ) <= 1 or re.search(r"^\s*\)(\s*->.*:|:)\s*$"    ,				SCREAMING_SNAKE_CASE    ) is not None
def  a__      (    SCREAMING_SNAKE_CASE   :   Tuple    ):


  '''simple docstring'''







  lowerCAmelCase					:					Dict								=							object_name.split("."    )
  lowerCAmelCase					:					Optional[int]								=							0

  # First let's find the module where our object lives.
  lowerCAmelCase					:					Any								=							parts[i]
  while i < len(SCREAMING_SNAKE_CASE    ) and not os.path.isfile(os.path.join(SCREAMING_SNAKE_CASE    ,				f"""{module}.py"""    )    ):
    i += 1
    if i < len(SCREAMING_SNAKE_CASE    ):
      lowerCAmelCase					:					Optional[Any]								=							os.path.join(SCREAMING_SNAKE_CASE    ,				parts[i]    )
  if i >= len(SCREAMING_SNAKE_CASE    ):
    raise ValueError(f"""`object_name` should begin with the name of a module of diffusers but got {object_name}."""    )

  with open(os.path.join(SCREAMING_SNAKE_CASE    ,				f"""{module}.py"""    )    ,				"r"    ,				encoding="utf-8"    ,				newline="\n"    ) as f:
    lowerCAmelCase					:					List[Any]								=							f.readlines()

  # Now let's find the class / func in the code!
  lowerCAmelCase					:					List[str]								=							""
  lowerCAmelCase					:					int								=							0
  for name in parts[i + 1 :]:
    while (
        line_index < len(SCREAMING_SNAKE_CASE    ) and re.search(rf"""^{indent}(class|def)\s+{name}(\(|\:)"""    ,				lines[line_index]    ) is None
    ):
      line_index += 1
    indent += "    "
    line_index += 1

  if line_index >= len(SCREAMING_SNAKE_CASE    ):
    raise ValueError(f""" {object_name} does not match any function or class in {module}."""    )

  # We found the beginning of the class / func, now let's find the end (when the indent diminishes).
  lowerCAmelCase					:					List[str]								=							line_index
  while line_index < len(SCREAMING_SNAKE_CASE    ) and _should_continue(lines[line_index]    ,				SCREAMING_SNAKE_CASE    ):
    line_index += 1
  # Clean up empty lines at the end (if any).
  while len(lines[line_index - 1]    ) <= 1:
    line_index -= 1

  lowerCAmelCase					:					List[Any]								=							lines[start_index:line_index]
  return "".join(SCREAMING_SNAKE_CASE    )


lowerCAmelCase__				    =       re.compile(r'''^(\s*)#\s*Copied from\s+diffusers\.(\S+\.\S+)\s*($|\S.*$)''')
lowerCAmelCase__				    =       re.compile(r'''^\s*(\S+)->(\S+)(\s+.*|$)''')
lowerCAmelCase__				    =       re.compile(r'''<FILL\s+[^>]*>''')
def  a__      (    SCREAMING_SNAKE_CASE   :   str    ):


  '''simple docstring'''







  lowerCAmelCase					:					int								=							code.split("\n"    )
  lowerCAmelCase					:					List[str]								=							0
  while idx < len(SCREAMING_SNAKE_CASE    ) and len(lines[idx]    ) == 0:
    idx += 1
  if idx < len(SCREAMING_SNAKE_CASE    ):
    return re.search(r"^(\s*)\S"    ,				lines[idx]    ).groups()[0]
  return ""
def  a__      (    SCREAMING_SNAKE_CASE   :   Optional[int]    ):


  '''simple docstring'''







  lowerCAmelCase					:					List[Any]								=							len(get_indent(SCREAMING_SNAKE_CASE    )    ) > 0
  if has_indent:
    lowerCAmelCase					:					Tuple								=							f"""class Bla:\n{code}"""
  lowerCAmelCase					:					Optional[Any]								=							black.Mode(target_versions={black.TargetVersion.PYaa}    ,				line_length=1_1_9    ,				preview=SCREAMING_SNAKE_CASE    )
  lowerCAmelCase					:					Dict								=							black.format_str(SCREAMING_SNAKE_CASE    ,				mode=SCREAMING_SNAKE_CASE    )
  lowerCAmelCase						,  lowerCAmelCase					:					List[Any]								=							style_docstrings_in_code(SCREAMING_SNAKE_CASE    )
  return result[len("class Bla:\n"    ) :] if has_indent else result
def  a__      (    SCREAMING_SNAKE_CASE   :   Optional[Any]    ,				SCREAMING_SNAKE_CASE   :   int=False    ):


  '''simple docstring'''







  with open(SCREAMING_SNAKE_CASE    ,				"r"    ,				encoding="utf-8"    ,				newline="\n"    ) as f:
    lowerCAmelCase					:					int								=							f.readlines()
  lowerCAmelCase					:					List[str]								=							[]
  lowerCAmelCase					:					str								=							0
  # Not a for loop cause `lines` is going to change (if `overwrite=True`).
  while line_index < len(SCREAMING_SNAKE_CASE    ):
    lowerCAmelCase					:					List[Any]								=							_re_copy_warning.search(lines[line_index]    )
    if search is None:
      line_index += 1
      continue

    # There is some copied code here, let's retrieve the original.
    lowerCAmelCase						,  lowerCAmelCase						,  lowerCAmelCase					:					List[Any]								=							search.groups()
    lowerCAmelCase					:					List[str]								=							find_code_in_diffusers(SCREAMING_SNAKE_CASE    )
    lowerCAmelCase					:					Optional[Any]								=							get_indent(SCREAMING_SNAKE_CASE    )

    lowerCAmelCase					:					Dict								=							line_index + 1 if indent == theoretical_indent else line_index + 2
    lowerCAmelCase					:					Optional[int]								=							theoretical_indent
    lowerCAmelCase					:					List[str]								=							start_index

    # Loop to check the observed code, stop when indentation diminishes or if we see a End copy comment.
    lowerCAmelCase					:					str								=							True
    while line_index < len(SCREAMING_SNAKE_CASE    ) and should_continue:
      line_index += 1
      if line_index >= len(SCREAMING_SNAKE_CASE    ):
        break
      lowerCAmelCase					:					Tuple								=							lines[line_index]
      lowerCAmelCase					:					str								=							_should_continue(SCREAMING_SNAKE_CASE    ,				SCREAMING_SNAKE_CASE    ) and re.search(f"""^{indent}# End copy"""    ,				SCREAMING_SNAKE_CASE    ) is None
    # Clean up empty lines at the end (if any).
    while len(lines[line_index - 1]    ) <= 1:
      line_index -= 1

    lowerCAmelCase					:					Tuple								=							lines[start_index:line_index]
    lowerCAmelCase					:					List[str]								=							"".join(SCREAMING_SNAKE_CASE    )

    # Remove any nested `Copied from` comments to avoid circular copies
    lowerCAmelCase					:					List[str]								=							[line for line in theoretical_code.split("\n"    ) if _re_copy_warning.search(SCREAMING_SNAKE_CASE    ) is None]
    lowerCAmelCase					:					Union[str, Any]								=							"\n".join(SCREAMING_SNAKE_CASE    )

    # Before comparing, use the `replace_pattern` on the original code.
    if len(SCREAMING_SNAKE_CASE    ) > 0:
      lowerCAmelCase					:					str								=							replace_pattern.replace("with"    ,				""    ).split(","    )
      lowerCAmelCase					:					List[str]								=							[_re_replace_pattern.search(SCREAMING_SNAKE_CASE    ) for p in patterns]
      for pattern in patterns:
        if pattern is None:
          continue
        lowerCAmelCase						,  lowerCAmelCase						,  lowerCAmelCase					:					List[str]								=							pattern.groups()
        lowerCAmelCase					:					List[Any]								=							re.sub(SCREAMING_SNAKE_CASE    ,				SCREAMING_SNAKE_CASE    ,				SCREAMING_SNAKE_CASE    )
        if option.strip() == "all-casing":
          lowerCAmelCase					:					Optional[Any]								=							re.sub(obja.lower()    ,				obja.lower()    ,				SCREAMING_SNAKE_CASE    )
          lowerCAmelCase					:					Dict								=							re.sub(obja.upper()    ,				obja.upper()    ,				SCREAMING_SNAKE_CASE    )

            # Blackify after replacement. To be able to do that, we need the header (class or function definition)
            # from the previous line
      lowerCAmelCase					:					Union[str, Any]								=							blackify(lines[start_index - 1] + theoretical_code    )
      lowerCAmelCase					:					List[str]								=							theoretical_code[len(lines[start_index - 1]    ) :]

    # Test for a diff and act accordingly.
    if observed_code != theoretical_code:
      diffs.append([object_name, start_index]    )
      if overwrite:
        lowerCAmelCase					:					Tuple								=							lines[:start_index] + [theoretical_code] + lines[line_index:]
        lowerCAmelCase					:					int								=							start_index + 1

  if overwrite and len(SCREAMING_SNAKE_CASE    ) > 0:
    # Warn the user a file has been modified.
    print(f"""Detected changes, rewriting {filename}."""    )
    with open(SCREAMING_SNAKE_CASE    ,				"w"    ,				encoding="utf-8"    ,				newline="\n"    ) as f:
      f.writelines(SCREAMING_SNAKE_CASE    )
  return diffs
def  a__      (    SCREAMING_SNAKE_CASE   :   bool = False    ):


  '''simple docstring'''







  lowerCAmelCase					:					List[Any]								=							glob.glob(os.path.join(SCREAMING_SNAKE_CASE    ,				"**/*.py"    )    ,				recursive=SCREAMING_SNAKE_CASE    )
  lowerCAmelCase					:					str								=							[]
  for filename in all_files:
    lowerCAmelCase					:					List[Any]								=							is_copy_consistent(SCREAMING_SNAKE_CASE    ,				SCREAMING_SNAKE_CASE    )
    diffs += [f"""- {filename}: copy does not match {d[0]} at line {d[1]}""" for d in new_diffs]
  if not overwrite and len(SCREAMING_SNAKE_CASE    ) > 0:
    lowerCAmelCase					:					List[Any]								=							"\n".join(SCREAMING_SNAKE_CASE    )
    raise Exception(
        "Found the following copy inconsistencies:\n"
        + diff
        + "\nRun `make fix-copies` or `python utils/check_copies.py --fix_and_overwrite` to fix them."    )


if __name__ == "__main__":
     lowerCAmelCase__				    =       argparse.ArgumentParser()
     parser.add_argument('''--fix_and_overwrite''', action='''store_true''', help='''Whether to fix inconsistencies.''')
     lowerCAmelCase__				    =       parser.parse_args()

     check_copies(args.fix_and_overwrite)









"""simple docstring"""







from typing import List, Optional

from ...configuration_utils import PretrainedConfig
from ...utils import logging


lowerCAmelCase__				    =       logging.get_logger(__name__)

lowerCAmelCase__				    =       {
    '''huggingface/autoformer-tourism-monthly''': '''https://huggingface.co/huggingface/autoformer-tourism-monthly/resolve/main/config.json''',
}


class 				SCREAMING_SNAKE_CASE__    (		lowercase    ):
       """simple docstring"""


       a  :    Dict       ="autoformer"
       a  :    Dict       ={
           "hidden_size": "d_model",
           "num_attention_heads": "encoder_attention_heads",
           "num_hidden_layers": "encoder_layers",
       }

       def __init__(						self		,					snake_case__ = None		,					snake_case__ = None		,					snake_case__ = "student_t"		,					snake_case__ = "nll"		,					snake_case__ = 1		,					snake_case__ = [1, 2, 3, 4, 5, 6, 7]		,					snake_case__ = True		,					snake_case__ = 0		,					snake_case__ = 0		,					snake_case__ = 0		,					snake_case__ = 0		,					snake_case__ = None		,					snake_case__ = None		,					snake_case__ = 64		,					snake_case__ = 2		,					snake_case__ = 2		,					snake_case__ = 2		,					snake_case__ = 2		,					snake_case__ = 32		,					snake_case__ = 32		,					snake_case__ = "gelu"		,					snake_case__ = 0.1		,					snake_case__ = 0.1		,					snake_case__ = 0.1		,					snake_case__ = 0.1		,					snake_case__ = 0.1		,					snake_case__ = 100		,					snake_case__ = 0.02		,					snake_case__ = True		,					snake_case__=True		,					snake_case__ = 10		,					snake_case__ = 25		,					snake_case__ = 3		,					**snake_case__		,					):






         """simple docstring"""





         lowerCAmelCase					:					Any								=							prediction_length
         lowerCAmelCase					:					Dict								=							context_length if context_length is not None else prediction_length
         lowerCAmelCase					:					Tuple								=							distribution_output
         lowerCAmelCase					:					List[Any]								=							loss
         lowerCAmelCase					:					int								=							input_size
         lowerCAmelCase					:					str								=							num_time_features
         lowerCAmelCase					:					str								=							lags_sequence
         lowerCAmelCase					:					List[str]								=							scaling
         lowerCAmelCase					:					List[Any]								=							num_dynamic_real_features
         lowerCAmelCase					:					Tuple								=							num_static_real_features
         lowerCAmelCase					:					Dict								=							num_static_categorical_features
         if cardinality is not None and num_static_categorical_features > 0:
           if len(snake_case__						) != num_static_categorical_features:
             raise ValueError(
                 "The cardinality should be a list of the same length as `num_static_categorical_features`"						)
           lowerCAmelCase					:					Any								=							cardinality
         else:
           lowerCAmelCase					:					Union[str, Any]								=							[0]
         if embedding_dimension is not None and num_static_categorical_features > 0:
           if len(snake_case__						) != num_static_categorical_features:
             raise ValueError(
                 "The embedding dimension should be a list of the same length as `num_static_categorical_features`"						)
           lowerCAmelCase					:					Tuple								=							embedding_dimension
         else:
           lowerCAmelCase					:					Any								=							[min(50		,					(cat + 1) // 2						) for cat in self.cardinality]
         lowerCAmelCase					:					Any								=							num_parallel_samples

         # Transformer architecture configuration
         lowerCAmelCase					:					str								=							input_size * len(self.lags_sequence						) + self._number_of_features
         lowerCAmelCase					:					Any								=							d_model
         lowerCAmelCase					:					List[str]								=							encoder_attention_heads
         lowerCAmelCase					:					Union[str, Any]								=							decoder_attention_heads
         lowerCAmelCase					:					Optional[int]								=							encoder_ffn_dim
         lowerCAmelCase					:					Optional[Any]								=							decoder_ffn_dim
         lowerCAmelCase					:					int								=							encoder_layers
         lowerCAmelCase					:					int								=							decoder_layers

         lowerCAmelCase					:					List[Any]								=							dropout
         lowerCAmelCase					:					Optional[int]								=							attention_dropout
         lowerCAmelCase					:					Union[str, Any]								=							activation_dropout
         lowerCAmelCase					:					Optional[int]								=							encoder_layerdrop
         lowerCAmelCase					:					Dict								=							decoder_layerdrop

         lowerCAmelCase					:					Tuple								=							activation_function
         lowerCAmelCase					:					Optional[Any]								=							init_std

         lowerCAmelCase					:					List[Any]								=							use_cache

         # Autoformer
         lowerCAmelCase					:					Any								=							label_length
         lowerCAmelCase					:					Any								=							moving_average
         lowerCAmelCase					:					Optional[Any]								=							autocorrelation_factor

         super().__init__(is_encoder_decoder=snake_case__		,					**snake_case__						)







       @property
       def 	lowercase__							(						self						):






         """simple docstring"""





         return (
             sum(self.embedding_dimension						)
             + self.num_dynamic_real_features
             + self.num_time_features
             + self.num_static_real_features
             + self.input_size * 2  # the log1p(abs(loc)) and log(scale) features
         )





