





from collections import OrderedDict
from typing import TYPE_CHECKING, Any, Mapping, Optional, Union

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig, OnnxSeqaSeqConfigWithPast
from ...utils import logging


if TYPE_CHECKING:
      from ...feature_extraction_utils import FeatureExtractionMixin
      from ...tokenization_utils_base import PreTrainedTokenizerBase
      from ...utils import TensorType

UpperCAmelCase_					:   List[Any] 							=						logging.get_logger(__name__)

UpperCAmelCase_					:   Optional[Any] 							=						{
    """openai/whisper-base""": """https://huggingface.co/openai/whisper-base/resolve/main/config.json""",
}

# fmt: off
UpperCAmelCase_					:   int 							=						[
    1, 2, 7, 8, 9, 10, 14, 25,
    26, 27, 28, 29, 31, 58, 59, 60, 61, 62,
    63, 90, 91, 92, 93, 3_57, 3_66, 4_38, 5_32, 6_85,
    7_05, 7_96, 9_30, 10_58, 12_20, 12_67, 12_79, 13_03, 13_43, 13_77,
    13_91, 16_35, 17_82, 18_75, 21_62, 23_61, 24_88, 34_67, 40_08, 42_11,
    46_00, 48_08, 52_99, 58_55, 63_29, 72_03, 96_09, 99_59, 1_05_63, 1_07_86,
    1_14_20, 1_17_09, 1_19_07, 1_31_63, 1_36_97, 1_37_00, 1_48_08, 1_53_06, 1_64_10, 1_67_91,
    1_79_92, 1_92_03, 1_95_10, 2_07_24, 2_23_05, 2_29_35, 2_70_07, 3_01_09, 3_04_20, 3_34_09,
    3_49_49, 4_02_83, 4_04_93, 4_05_49, 4_72_82, 4_91_46, 5_02_57, 5_03_59, 5_03_60, 5_03_61
]
UpperCAmelCase_					:   Optional[int] 							=						[
    1, 2, 7, 8, 9, 10, 14, 25,
    26, 27, 28, 29, 31, 58, 59, 60, 61, 62,
    63, 90, 91, 92, 93, 3_59, 5_03, 5_22, 5_42, 8_73,
    8_93, 9_02, 9_18, 9_22, 9_31, 13_50, 18_53, 19_82, 24_60, 26_27,
    32_46, 32_53, 32_68, 35_36, 38_46, 39_61, 41_83, 46_67, 65_85, 66_47,
    72_73, 90_61, 93_83, 1_04_28, 1_09_29, 1_19_38, 1_20_33, 1_23_31, 1_25_62, 1_37_93,
    1_41_57, 1_46_35, 1_52_65, 1_56_18, 1_65_53, 1_66_04, 1_83_62, 1_89_56, 2_00_75, 2_16_75,
    2_25_20, 2_61_30, 2_61_61, 2_64_35, 2_82_79, 2_94_64, 3_16_50, 3_23_02, 3_24_70, 3_68_65,
    4_28_63, 4_74_25, 4_98_70, 5_02_54, 5_02_58, 5_03_60, 5_03_61, 5_03_62
]





class      lowercase__    (							__A  ):
  __UpperCamelCase	     =  """whisper"""
  __UpperCamelCase	     =  ["""past_key_values"""]
  __UpperCamelCase	     =  {"""num_attention_heads""": """encoder_attention_heads""", """hidden_size""": """d_model"""}







  def __init__(	self    ,						_lowercase=51_865    ,						_lowercase=80    ,						_lowercase=6    ,						_lowercase=4    ,						_lowercase=6    ,						_lowercase=4    ,						_lowercase=1_536    ,						_lowercase=1_536    ,						_lowercase=0.0    ,						_lowercase=0.0    ,						_lowercase=50_257    ,						_lowercase=True    ,						_lowercase=True    ,						_lowercase="gelu"    ,						_lowercase=256    ,						_lowercase=0.0    ,						_lowercase=0.0    ,						_lowercase=0.0    ,						_lowercase=0.02    ,						_lowercase=False    ,						_lowercase=1_500    ,						_lowercase=448    ,						_lowercase=50_256    ,						_lowercase=50_256    ,						_lowercase=50_256    ,						_lowercase=None    ,						_lowercase=[220, 50_256]    ,						_lowercase=False    ,						_lowercase=256    ,						_lowercase=False    ,						_lowercase=0.05    ,						_lowercase=10    ,						_lowercase=2    ,						_lowercase=0.0    ,						_lowercase=10    ,						_lowercase=0    ,						_lowercase=7    ,						**_lowercase    ,						):
       lowerCAmelCase_					:       str    =		vocab_size
       lowerCAmelCase_					:       int    =		num_mel_bins
       lowerCAmelCase_					:       int    =		d_model
       lowerCAmelCase_					:       str    =		encoder_layers
       lowerCAmelCase_					:       Tuple    =		encoder_attention_heads
       lowerCAmelCase_					:       Union[str, Any]    =		decoder_layers
       lowerCAmelCase_					:       Optional[Any]    =		decoder_attention_heads
       lowerCAmelCase_					:       int    =		decoder_ffn_dim
       lowerCAmelCase_					:       Union[str, Any]    =		encoder_ffn_dim
       lowerCAmelCase_					:       Dict    =		dropout
       lowerCAmelCase_					:       str    =		attention_dropout
       lowerCAmelCase_					:       Optional[int]    =		activation_dropout
       lowerCAmelCase_					:       Union[str, Any]    =		activation_function
       lowerCAmelCase_					:       Any    =		init_std
       lowerCAmelCase_					:       int    =		encoder_layerdrop
       lowerCAmelCase_					:       str    =		decoder_layerdrop
       lowerCAmelCase_					:       Optional[int]    =		use_cache
       lowerCAmelCase_					:       List[str]    =		encoder_layers
       lowerCAmelCase_					:       Optional[Any]    =		scale_embedding  # scale factor will be sqrt(d_model) if True
       lowerCAmelCase_					:       List[str]    =		max_source_positions
       lowerCAmelCase_					:       str    =		max_target_positions

       # Audio Classification-specific parameters. Feel free to ignore for other classes.
       lowerCAmelCase_					:       List[Any]    =		classifier_proj_size
       lowerCAmelCase_					:       Union[str, Any]    =		use_weighted_layer_sum

       # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779
       lowerCAmelCase_					:       Dict    =		apply_spec_augment
       lowerCAmelCase_					:       Dict    =		mask_time_prob
       lowerCAmelCase_					:       List[str]    =		mask_time_length
       lowerCAmelCase_					:       Optional[Any]    =		mask_time_min_masks
       lowerCAmelCase_					:       Optional[int]    =		mask_feature_prob
       lowerCAmelCase_					:       Optional[int]    =		mask_feature_length
       lowerCAmelCase_					:       List[str]    =		mask_feature_min_masks

       lowerCAmelCase_					:       Any    =		median_filter_width

       super().__init__(
           pad_token_id=_lowercase    ,						bos_token_id=_lowercase    ,						eos_token_id=_lowercase    ,						is_encoder_decoder=_lowercase    ,						decoder_start_token_id=_lowercase    ,						suppress_tokens=_lowercase    ,						begin_suppress_tokens=_lowercase    ,						**_lowercase    ,						)





class      lowercase__    (							__A  ):







  @property
  def 	UpperCAmelCase__		(	self						):
       lowerCAmelCase_					:       Tuple    =		OrderedDict(
           [
               ("""input_features""", {0: """batch""", 1: """feature_size""", 2: """encoder_sequence"""}),
           ]						)
       if self.use_past:
            lowerCAmelCase_					:       Union[str, Any]    =		{0: """batch"""}
       else:
            lowerCAmelCase_					:       Dict    =		{0: """batch""", 1: """decoder_sequence"""}

       if self.use_past:
            self.fill_with_past_key_values_(_lowercase    ,						direction="""inputs"""						)

       return common_inputs







  def 	UpperCAmelCase__		(	self    ,						_lowercase    ,						_lowercase = -1    ,						_lowercase = -1    ,						_lowercase = False    ,						_lowercase = None    ,						_lowercase = 22_050    ,						_lowercase = 5.0    ,						_lowercase = 220    ,						):
       lowerCAmelCase_					:       List[str]    =		OrderedDict()
       lowerCAmelCase_					:       Dict    =		OnnxConfig.generate_dummy_inputs(
           self    ,						preprocessor=preprocessor.feature_extractor    ,						batch_size=_lowercase    ,						framework=_lowercase    ,						sampling_rate=_lowercase    ,						time_duration=_lowercase    ,						frequency=_lowercase    ,						)
       lowerCAmelCase_					:       Optional[int]    =		encoder_inputs["""input_features"""].shape[2]
       lowerCAmelCase_					:       Optional[int]    =		encoder_sequence_length // 2 if self.use_past else seq_length

       lowerCAmelCase_					:       str    =		super().generate_dummy_inputs(
           preprocessor.tokenizer    ,						_lowercase    ,						_lowercase    ,						_lowercase    ,						_lowercase						)

       lowerCAmelCase_					:       Optional[int]    =		encoder_inputs.pop("""input_features"""						)
       lowerCAmelCase_					:       str    =		decoder_inputs.pop("""decoder_input_ids"""						)

       if "past_key_values" in decoder_inputs:
            lowerCAmelCase_					:       Dict    =		decoder_inputs.pop("""past_key_values"""						)

       return dummy_inputs







  @property
  def 	UpperCAmelCase__		(	self						):
       return 1e-3







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
UpperCAmelCase_					:   Tuple 							=						"""src/diffusers"""
UpperCAmelCase_					:   str 							=						"""."""


# This is to make sure the diffusers module imported is the one in the repo.
UpperCAmelCase_					:   Any 							=						importlib.util.spec_from_file_location(
    """diffusers""",
    os.path.join(DIFFUSERS_PATH, """__init__.py"""),
    submodule_search_locations=[DIFFUSERS_PATH],
)
UpperCAmelCase_					:   Union[str, Any] 							=						spec.loader.load_module()






def 							_lowerCAmelCase (  _a   :					Optional[int]					,   _a   :					Optional[int]			)	->			Tuple:
     return line.startswith(_a			) or len(_a			) <= 1 or re.search(R"""^\s*\)(\s*->.*:|:)\s*$"""					,   _a			) is not None






def 							_lowerCAmelCase (  _a   :					List[Any]			)	->			int:
     lowerCAmelCase_					:       List[str]    =		object_name.split("""."""			)
     lowerCAmelCase_					:       List[Any]    =		0

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

     with open(os.path.join(_a					,   F'{module}.py'			)					,   """r"""					,   encoding="""utf-8"""					,   newline="""\n"""			) as f:
          lowerCAmelCase_					:       Union[str, Any]    =		f.readlines()

     # Now let's find the class / func in the code!
     lowerCAmelCase_					:       List[Any]    =		""""""
     lowerCAmelCase_					:       Optional[int]    =		0
     for name in parts[i + 1 :]:
          while (
              line_index < len(_a			) 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(_a			):
          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_					:       str    =		line_index
     while line_index < len(_a			) and _should_continue(lines[line_index]					,   _a			):
          line_index += 1
     # Clean up empty lines at the end (if any).
     while len(lines[line_index - 1]			) <= 1:
          line_index -= 1

     lowerCAmelCase_					:       int    =		lines[start_index:line_index]
     return "".join(_a			)


UpperCAmelCase_					:   str 							=						re.compile(r"""^(\s*)#\s*Copied from\s+diffusers\.(\S+\.\S+)\s*($|\S.*$)""")
UpperCAmelCase_					:   int 							=						re.compile(r"""^\s*(\S+)->(\S+)(\s+.*|$)""")
UpperCAmelCase_					:   List[str] 							=						re.compile(r"""<FILL\s+[^>]*>""")






def 							_lowerCAmelCase (  _a   :					Dict			)	->			List[Any]:
     lowerCAmelCase_					:       int    =		code.split("""\n"""			)
     lowerCAmelCase_					:       Any    =		0
     while idx < len(_a			) and len(lines[idx]			) == 0:
          idx += 1
     if idx < len(_a			):
          return re.search(R"""^(\s*)\S"""					,   lines[idx]			).groups()[0]
     return ""






def 							_lowerCAmelCase (  _a   :					Optional[int]			)	->			Union[str, Any]:
     lowerCAmelCase_					:       Tuple    =		len(get_indent(_a			)			) > 0
     if has_indent:
          lowerCAmelCase_					:       Union[str, Any]    =		F'class Bla:\n{code}'
     lowerCAmelCase_					:       Tuple    =		black.Mode(target_versions={black.TargetVersion.PYaa}					,   line_length=1_19					,   preview=_a			)
     lowerCAmelCase_					:       str    =		black.format_str(_a					,   mode=_a			)
     lowerCAmelCase_   ,  lowerCAmelCase_					:       List[str]    =		style_docstrings_in_code(_a			)
     return result[len("""class Bla:\n"""			) :] if has_indent else result






def 							_lowerCAmelCase (  _a   :					Tuple					,   _a   :					str=False			)	->			Tuple:
     with open(_a					,   """r"""					,   encoding="""utf-8"""					,   newline="""\n"""			) as f:
          lowerCAmelCase_					:       List[str]    =		f.readlines()
     lowerCAmelCase_					:       Union[str, Any]    =		[]
     lowerCAmelCase_					:       Dict    =		0
     # Not a for loop cause `lines` is going to change (if `overwrite=True`).
     while line_index < len(_a			):
          lowerCAmelCase_					:       str    =		_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_					:       str    =		search.groups()
          lowerCAmelCase_					:       List[Any]    =		find_code_in_diffusers(_a			)
          lowerCAmelCase_					:       Tuple    =		get_indent(_a			)

          lowerCAmelCase_					:       Union[str, Any]    =		line_index + 1 if indent == theoretical_indent else line_index + 2
          lowerCAmelCase_					:       str    =		theoretical_indent
          lowerCAmelCase_					:       Tuple    =		start_index

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

          lowerCAmelCase_					:       str    =		lines[start_index:line_index]
          lowerCAmelCase_					:       Optional[Any]    =		"""""".join(_a			)

          # Remove any nested `Copied from` comments to avoid circular copies
          lowerCAmelCase_					:       Optional[int]    =		[line for line in theoretical_code.split("""\n"""			) if _re_copy_warning.search(_a			) is None]
          lowerCAmelCase_					:       str    =		"""\n""".join(_a			)

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

            # Blackify after replacement. To be able to do that, we need the header (class or function definition)
            # from the previous line
               lowerCAmelCase_					:       str    =		blackify(lines[start_index - 1] + theoretical_code			)
               lowerCAmelCase_					:       Optional[Any]    =		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_					:       Any    =		lines[:start_index] + [theoretical_code] + lines[line_index:]
                    lowerCAmelCase_					:       Dict    =		start_index + 1

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






def 							_lowerCAmelCase (  _a   :					bool = False			)	->			List[Any]:
     lowerCAmelCase_					:       Optional[Any]    =		glob.glob(os.path.join(_a					,   """**/*.py"""			)					,   recursive=_a			)
     lowerCAmelCase_					:       Union[str, Any]    =		[]
     for filename in all_files:
          lowerCAmelCase_					:       Union[str, Any]    =		is_copy_consistent(_a					,   _a			)
          diffs += [F'- {filename}: copy does not match {d[0]} at line {d[1]}' for d in new_diffs]
     if not overwrite and len(_a			) > 0:
          lowerCAmelCase_					:       List[Any]    =		"""\n""".join(_a			)
          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__":
      UpperCAmelCase_					:   Optional[int] 							=						argparse.ArgumentParser()
      parser.add_argument("""--fix_and_overwrite""", action="""store_true""", help="""Whether to fix inconsistencies.""")
      UpperCAmelCase_					:   List[str] 							=						parser.parse_args()

      check_copies(args.fix_and_overwrite)
