


import argparse
import os
import re


# All paths are set with the intent you should run this script from the root of the repo with the command
# python utils/check_dummies.py
__UpperCamelCase       :       Optional[Any]						       =				"src/diffusers"

# Matches is_xxx_available()
__UpperCamelCase       :       Union[str, Any]						       =				re.compile(r"is\_([a-z_]*)_available\(\)")
# Matches from xxx import bla
__UpperCamelCase       :       Optional[Any]						       =				re.compile(r"\s+from\s+\S*\s+import\s+([^\(\s].*)\n")


__UpperCamelCase       :       str						       =				"\n{0} = None\n"

__UpperCamelCase       :       int						       =				"\nclass {0}(metaclass=DummyObject):\n    _backends = {1}\n\n    def __init__(self, *args, **kwargs):\n        requires_backends(self, {1})\n\n    @classmethod\n    def from_config(cls, *args, **kwargs):\n        requires_backends(cls, {1})\n\n    @classmethod\n    def from_pretrained(cls, *args, **kwargs):\n        requires_backends(cls, {1})\n"


__UpperCamelCase       :       List[str]						       =				"\ndef {0}(*args, **kwargs):\n    requires_backends({0}, {1})\n"

def 			_a  (				SCREAMING_SNAKE_CASE	:				str     ):







 """simple docstring"""



 UpperCamelCase__					:    Optional[Any]          =   _re_backend.findall(SCREAMING_SNAKE_CASE     )
 if len(SCREAMING_SNAKE_CASE     ) == 0:
  return None

 return "_and_".join(SCREAMING_SNAKE_CASE     )

def 			_a  (				):







 """simple docstring"""



 with open(os.path.join(SCREAMING_SNAKE_CASE    , '''__init__.py'''     )    , '''r'''    , encoding='''utf-8'''    , newline='''\n'''     ) as f:
  UpperCamelCase__					:    Tuple          =   f.readlines()

 # Get to the point we do the actual imports for type checking
 UpperCamelCase__					:    Any          =   0
 UpperCamelCase__					:    Any          =   {}
 # Go through the end of the file
 while line_index < len(SCREAMING_SNAKE_CASE     ):
  # If the line contains is_backend_available, we grab all objects associated with the `else` block
  UpperCamelCase__					:    Any          =   find_backend(lines[line_index]     )
  if backend is not None:
   while not lines[line_index].startswith('''else:'''     ):
    line_index += 1
   line_index += 1
   UpperCamelCase__					:    Union[str, Any]          =   []
   # Until we unindent, add backend objects to the list
   while line_index < len(SCREAMING_SNAKE_CASE     ) and len(lines[line_index]     ) > 1:
    UpperCamelCase__					:    Union[str, Any]          =   lines[line_index]
    UpperCamelCase__					:    Tuple          =   _re_single_line_import.search(SCREAMING_SNAKE_CASE     )
    if single_line_import_search is not None:
     objects.extend(single_line_import_search.groups()[0].split(''', '''     )     )
    elif line.startswith(''' ''' * 8     ):
     objects.append(line[8:-2]     )
    line_index += 1

   if len(SCREAMING_SNAKE_CASE     ) > 0:
    UpperCamelCase__					:    str          =   objects
  else:
   line_index += 1

 return backend_specific_objects

def 			_a  (				SCREAMING_SNAKE_CASE	:				Any    , SCREAMING_SNAKE_CASE	:				str     ):







 """simple docstring"""



 if name.isupper():
  return DUMMY_CONSTANT.format(SCREAMING_SNAKE_CASE     )
 elif name.islower():
  return DUMMY_FUNCTION.format(SCREAMING_SNAKE_CASE    , SCREAMING_SNAKE_CASE     )
 else:
  return DUMMY_CLASS.format(SCREAMING_SNAKE_CASE    , SCREAMING_SNAKE_CASE     )

def 			_a  (				SCREAMING_SNAKE_CASE	:				Union[str, Any]=None     ):







 """simple docstring"""



 if backend_specific_objects is None:
  UpperCamelCase__					:    int          =   read_init()
 # For special correspondence backend to module name as used in the function requires_modulename
 UpperCamelCase__					:    Any          =   {}

 for backend, objects in backend_specific_objects.items():
  UpperCamelCase__					:    Union[str, Any]          =   '''[''' + ''', '''.join(F"\"{b}\"" for b in backend.split('''_and_'''     )     ) + ''']'''
  UpperCamelCase__					:    Optional[int]          =   '''# This file is autogenerated by the command `make fix-copies`, do not edit.\n'''
  dummy_file += "from ..utils import DummyObject, requires_backends\n\n"
  dummy_file += "\n".join([create_dummy_object(SCREAMING_SNAKE_CASE    , SCREAMING_SNAKE_CASE     ) for o in objects]     )
  UpperCamelCase__					:    str          =   dummy_file

 return dummy_files

def 			_a  (				SCREAMING_SNAKE_CASE	:				List[Any]=False     ):







 """simple docstring"""



 UpperCamelCase__					:    Any          =   create_dummy_files()
 # For special correspondence backend to shortcut as used in utils/dummy_xxx_objects.py
 UpperCamelCase__					:    Dict          =   {'''torch''': '''pt'''}

 # Locate actual dummy modules and read their content.
 UpperCamelCase__					:    str          =   os.path.join(SCREAMING_SNAKE_CASE    , '''utils'''     )
 UpperCamelCase__					:    Optional[Any]          =   {
     backend: os.path.join(SCREAMING_SNAKE_CASE    , F"dummy_{short_names.get(SCREAMING_SNAKE_CASE    , SCREAMING_SNAKE_CASE     )}_objects.py"     )
     for backend in dummy_files.keys()
 }

 UpperCamelCase__					:    Dict          =   {}
 for backend, file_path in dummy_file_paths.items():
  if os.path.isfile(SCREAMING_SNAKE_CASE     ):
   with open(SCREAMING_SNAKE_CASE    , '''r'''    , encoding='''utf-8'''    , newline='''\n'''     ) as f:
    UpperCamelCase__					:    Tuple          =   f.read()
  else:
   UpperCamelCase__					:    List[Any]          =   ''''''

 for backend in dummy_files.keys():
  if dummy_files[backend] != actual_dummies[backend]:
   if overwrite:
    print(
        F"Updating diffusers.utils.dummy_{short_names.get(SCREAMING_SNAKE_CASE    , SCREAMING_SNAKE_CASE     )}_objects.py as the main "
        '''__init__ has new objects.'''     )
    with open(dummy_file_paths[backend]    , '''w'''    , encoding='''utf-8'''    , newline='''\n'''     ) as f:
     f.write(dummy_files[backend]     )
   else:
    raise ValueError(
        '''The main __init__ has objects that are not present in '''
        F"diffusers.utils.dummy_{short_names.get(SCREAMING_SNAKE_CASE    , SCREAMING_SNAKE_CASE     )}_objects.py. Run `make fix-copies` "
        '''to fix this.'''     )


if __name__ == "__main__":
       __UpperCamelCase       :       Optional[int]						       =				argparse.ArgumentParser()
       parser.add_argument("--fix_and_overwrite", action="store_true", help="Whether to fix inconsistencies.")
       __UpperCamelCase       :       Union[str, Any]						       =				parser.parse_args()

       check_dummies(args.fix_and_overwrite)






import os
import time
from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, List, Optional, Union

import torch
from filelock import FileLock
from torch.utils.data import Dataset

from ...models.auto.modeling_auto import MODEL_FOR_QUESTION_ANSWERING_MAPPING
from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging
from ..processors.squad import SquadFeatures, SquadVaProcessor, SquadVaProcessor, squad_convert_examples_to_features


__UpperCamelCase       :       List[str]						       =				logging.get_logger(__name__)

__UpperCamelCase       :       Union[str, Any]						       =				list(MODEL_FOR_QUESTION_ANSWERING_MAPPING.keys())
__UpperCamelCase       :       Dict						       =				tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)

@dataclass
class       __magic_name__	:
     A:		str			=      field(
         default=__lowerCAmelCase					,				metadata={"help": "Model type selected in the list: " + ", ".join(__lowerCAmelCase)})
     A:		str			=      field(
         default=__lowerCAmelCase					,				metadata={"help": "The input data dir. Should contain the .json files for the SQuAD task."})
     A:		int			=      field(
         default=1_2_8					,				metadata={
             "help": (
                 "The maximum total input sequence length after tokenization. Sequences longer "
                 "than this will be truncated, sequences shorter will be padded."
             )
         }					,				)
     A:		int			=      field(
         default=1_2_8					,				metadata={"help": "When splitting up a long document into chunks, how much stride to take between chunks."}					,				)
     A:		int			=      field(
         default=6_4					,				metadata={
             "help": (
                 "The maximum number of tokens for the question. Questions longer than this will "
                 "be truncated to this length."
             )
         }					,				)
     A:		int			=      field(
         default=3_0					,				metadata={
             "help": (
                 "The maximum length of an answer that can be generated. This is needed because the start "
                 "and end predictions are not conditioned on one another."
             )
         }					,				)
     A:		bool			=      field(
         default=__lowerCAmelCase					,				metadata={"help": "Overwrite the cached training and evaluation sets"})
     A:		bool			=      field(
         default=__lowerCAmelCase					,				metadata={"help": "If true, the SQuAD examples contain some that do not have an answer."})
     A:		float			=      field(
         default=0.0					,				metadata={"help": "If null_score - best_non_null is greater than the threshold predict null."})
     A:		int			=      field(
         default=2_0					,				metadata={"help": "If null_score - best_non_null is greater than the threshold predict null."})
     A:		int			=      field(
         default=0					,				metadata={
             "help": (
                 "language id of input for language-specific xlm models (see"
                 " tokenization_xlm.PRETRAINED_INIT_CONFIGURATION)"
             )
         }					,				)
     A:		int			=      field(default=1					,				metadata={"help": "multiple threads for converting example to features"})



class       __magic_name__	(     __lowerCAmelCase):
     A:		Union[str, Any]			=      "train"
     A:		List[str]			=      "dev"



class       __magic_name__	(     __lowerCAmelCase):
     A:		SquadDataTrainingArguments
     A:		List[SquadFeatures]
     A:		Split
     A:		bool


     def __init__(      self							:     Tuple							,	lowerCamelCase__							:     SquadDataTrainingArguments							,	lowerCamelCase__							:     PreTrainedTokenizer							,	lowerCamelCase__							:     Optional[int] = None							,	lowerCamelCase__							:     Union[str, Split] = Split.train							,	lowerCamelCase__							:     Optional[bool] = False							,	lowerCamelCase__							:     Optional[str] = None							,	lowerCamelCase__							:     Optional[str] = "pt"							,	)  ->      int:





      '''simple docstring'''






      UpperCamelCase__					:    Dict          =   args
      UpperCamelCase__					:    Union[str, Any]          =   is_language_sensitive
      UpperCamelCase__					:    List[Any]          =   SquadVaProcessor() if args.version_2_with_negative else SquadVaProcessor()
      if isinstance(lowerCamelCase__							,	lowerCamelCase__			):
       try:
        UpperCamelCase__					:    Union[str, Any]          =   Split[mode]
       except KeyError:
        raise KeyError('''mode is not a valid split name'''			)
      UpperCamelCase__					:    List[str]          =   mode
      # Load data features from cache or dataset file
      UpperCamelCase__					:    List[str]          =   '''v2''' if args.version_2_with_negative else '''v1'''
      UpperCamelCase__					:    str          =   os.path.join(
          cache_dir if cache_dir is not None else args.data_dir							,	F"cached_{mode.value}_{tokenizer.__class__.__name__}_{args.max_seq_length}_{version_tag}"							,	)

      # Make sure only the first process in distributed training processes the dataset,
      # and the others will use the cache.
      UpperCamelCase__					:    Tuple          =   cached_features_file + '''.lock'''
      with FileLock(lowerCamelCase__			):
       if os.path.exists(lowerCamelCase__			) and not args.overwrite_cache:
        UpperCamelCase__					:    int          =   time.time()
        UpperCamelCase__					:    List[str]          =   torch.load(lowerCamelCase__			)

        # Legacy cache files have only features, while new cache files
        # will have dataset and examples also.
        UpperCamelCase__					:    Any          =   self.old_features['''features''']
        UpperCamelCase__					:    Union[str, Any]          =   self.old_features.get('''dataset'''							,	lowerCamelCase__			)
        UpperCamelCase__					:    List[str]          =   self.old_features.get('''examples'''							,	lowerCamelCase__			)
        logger.info(
            F"Loading features from cached file {cached_features_file} [took %.3f s]"							,	time.time() - start			)

        if self.dataset is None or self.examples is None:
         logger.warning(
             F"Deleting cached file {cached_features_file} will allow dataset and examples to be cached in"
             ''' future run'''			)
       else:
        if mode == Split.dev:
         UpperCamelCase__					:    List[str]          =   self.processor.get_dev_examples(args.data_dir			)
        else:
         UpperCamelCase__					:    Any          =   self.processor.get_train_examples(args.data_dir			)

        UpperCamelCase__       ,				UpperCamelCase__					:    Union[str, Any]          =   squad_convert_examples_to_features(
            examples=self.examples							,	tokenizer=lowerCamelCase__							,	max_seq_length=args.max_seq_length							,	doc_stride=args.doc_stride							,	max_query_length=args.max_query_length							,	is_training=mode == Split.train							,	threads=args.threads							,	return_dataset=lowerCamelCase__							,	)

        UpperCamelCase__					:    Tuple          =   time.time()
        torch.save(
            {'''features''': self.features, '''dataset''': self.dataset, '''examples''': self.examples}							,	lowerCamelCase__							,	)
        # ^ This seems to take a lot of time so I want to investigate why and how we can improve.
        logger.info(
            F"Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]"			)


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





      '''simple docstring'''






      return len(self.features			)


     def __getitem__(      self							:     Dict							,	lowerCamelCase__							:     Any			)  ->      Dict[str, torch.Tensor]:





      '''simple docstring'''






      UpperCamelCase__					:    List[Any]          =   self.features[i]

      UpperCamelCase__					:    Optional[Any]          =   torch.tensor(feature.input_ids							,	dtype=torch.long			)
      UpperCamelCase__					:    Tuple          =   torch.tensor(feature.attention_mask							,	dtype=torch.long			)
      UpperCamelCase__					:    Optional[int]          =   torch.tensor(feature.token_type_ids							,	dtype=torch.long			)
      UpperCamelCase__					:    int          =   torch.tensor(feature.cls_index							,	dtype=torch.long			)
      UpperCamelCase__					:    List[Any]          =   torch.tensor(feature.p_mask							,	dtype=torch.float			)
      UpperCamelCase__					:    Any          =   torch.tensor(feature.is_impossible							,	dtype=torch.float			)

      UpperCamelCase__					:    Dict          =   {
          '''input_ids''': input_ids,
          '''attention_mask''': attention_mask,
          '''token_type_ids''': token_type_ids,
      }

      if self.args.model_type in ["xlm", "roberta", "distilbert", "camembert"]:
       del inputs["token_type_ids"]

      if self.args.model_type in ["xlnet", "xlm"]:
       inputs.update({'''cls_index''': cls_index, '''p_mask''': p_mask}			)
       if self.args.version_2_with_negative:
        inputs.update({'''is_impossible''': is_impossible}			)
       if self.is_language_sensitive:
        inputs.update({'''langs''': (torch.ones(input_ids.shape							,	dtype=torch.intaa			) * self.args.lang_id)}			)

      if self.mode == Split.train:
       UpperCamelCase__					:    Optional[Any]          =   torch.tensor(feature.start_position							,	dtype=torch.long			)
       UpperCamelCase__					:    Optional[int]          =   torch.tensor(feature.end_position							,	dtype=torch.long			)
       inputs.update({'''start_positions''': start_positions, '''end_positions''': end_positions}			)

      return inputs


