






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
a     :   Union[str, Any]    =       'src/transformers'

# Matches is_xxx_available()
a     :   int    =       re.compile(r'is\_([a-z_]*)_available()')
# Matches from xxx import bla
a     :   str    =       re.compile(r'\s+from\s+\S*\s+import\s+([^\(\s].*)\n')
a     :   int    =       re.compile(r'^\s+if\s+not\s+\(?is\_[a-z_]*\_available\(\)')


a     :   Any    =       '\n{0} = None\n'

a     :   Tuple    =       '\nclass {0}(metaclass=DummyObject):\n    _backends = {1}\n\n    def __init__(self, *args, **kwargs):\n        requires_backends(self, {1})\n'


a     :   str    =       '\ndef {0}(*args, **kwargs):\n    requires_backends({0}, {1})\n'
def       a__						(  A					):
   if _re_test_backend.search(A					) is None:
      return None
   lowercase__						:	Any         = [b[0] for b in _re_backend.findall(A					)]
   backends.sort()
   return "_and_".join(A					)
def       a__						(  ):
   with open(os.path.join(A		,				"""__init__.py"""					)		,				"""r"""		,				encoding="""utf-8"""		,				newline="""\n"""					) as f:
      lowercase__						:	List[str]         = f.readlines()

   # Get to the point we do the actual imports for type checking
   lowercase__						:	Optional[Any]         = 0
   while not lines[line_index].startswith("""if TYPE_CHECKING"""					):
      line_index += 1

   lowercase__						:	Optional[int]         = {}
   # Go through the end of the file
   while line_index < len(A					):
      # If the line is an if is_backend_available, we grab all objects associated.
      lowercase__						:	int         = find_backend(lines[line_index]					)
      if backend is not None:
         while not lines[line_index].startswith("""    else:"""					):
            line_index += 1
         line_index += 1

         lowercase__						:	List[str]         = []
         # Until we unindent, add backend objects to the list
         while len(lines[line_index]					) <= 1 or lines[line_index].startswith(""" """ * 8					):
            lowercase__						:	Optional[Any]         = lines[line_index]
            lowercase__						:	List[Any]         = _re_single_line_import.search(A					)
            if single_line_import_search is not None:
               objects.extend(single_line_import_search.groups()[0].split(""", """					)					)
            elif line.startswith(""" """ * 12					):
               objects.append(line[12:-2]					)
            line_index += 1

         lowercase__						:	List[str]         = objects
      else:
         line_index += 1

   return backend_specific_objects
def       a__						(  A		,				A					):
   if name.isupper():
      return DUMMY_CONSTANT.format(A					)
   elif name.islower():
      return DUMMY_FUNCTION.format(A		,				A					)
   else:
      return DUMMY_CLASS.format(A		,				A					)
def       a__						(  A=None					):
   if backend_specific_objects is None:
      lowercase__						:	List[Any]         = read_init()
   # For special correspondence backend to module name as used in the function requires_modulename
   lowercase__						:	Optional[int]         = {}

   for backend, objects in backend_specific_objects.items():
      lowercase__						:	List[str]         = """[""" + """, """.join(F'''"{b}"''' for b in backend.split("""_and_"""					)					) + """]"""
      lowercase__						:	Dict         = """# 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(A		,				A					) for o in objects]					)
      lowercase__						:	str         = dummy_file

   return dummy_files
def       a__						(  A=False					):
   lowercase__						:	Dict         = create_dummy_files()
   # For special correspondence backend to shortcut as used in utils/dummy_xxx_objects.py
   lowercase__						:	Optional[int]         = {"""torch""": """pt"""}

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

   lowercase__						:	Dict         = {}
   for backend, file_path in dummy_file_paths.items():
      if os.path.isfile(A					):
         with open(A		,				"""r"""		,				encoding="""utf-8"""		,				newline="""\n"""					) as f:
            lowercase__						:	List[str]         = f.read()
      else:
         lowercase__						:	int         = """"""

   for backend in dummy_files.keys():
      if dummy_files[backend] != actual_dummies[backend]:
         if overwrite:
            print(
                F'''Updating transformers.utils.dummy_{short_names.get(A		,				A					)}_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'''transformers.utils.dummy_{short_names.get(A		,				A					)}_objects.py. Run `make fix-copies` '''
                """to fix this."""					)


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

 check_dummies(args.fix_and_overwrite)










from typing import SupportsIndex

import numpy as np
from scipy.ndimage import convolve
def       a__						(  A		,				A		,				A					):
   lowercase__						:	Dict         = np.stack((horizontal_flow, vertical_flow)		,				2					)

   # Create a grid of all pixel coordinates and subtract the flow to get the
   # target pixels coordinates
   lowercase__						:	Tuple         = np.stack(
       np.meshgrid(np.arange(0		,				image.shape[1]					)		,				np.arange(0		,				image.shape[0]					)					)		,				2					)
   lowercase__						:	Union[str, Any]         = np.round(grid - flow					).astype(np.intaa					)

   # Find the locations outside of the original image
   lowercase__						:	Optional[Any]         = (grid < 0) | (grid >= np.array([image.shape[1], image.shape[0]]					))
   lowercase__						:	int         = 0

   lowercase__						:	Tuple         = image[grid[:, :, 1], grid[:, :, 0]]

   # Set pixels at invalid locations to 0
   lowercase__						:	str         = 0

   return warped
def       a__						(  A		,				A		,				A		,				A = None		,				):
   if alpha is None:
      lowercase__						:	Tuple         = 0.1

   # Initialize flow
   lowercase__						:	Optional[int]         = np.zeros_like(A					)
   lowercase__						:	Tuple         = np.zeros_like(A					)

   # Prepare kernels for the calculation of the derivatives and the average velocity
   lowercase__						:	Tuple         = np.array([[-1, 1], [-1, 1]]					) * 0.2_5
   lowercase__						:	int         = np.array([[-1, -1], [1, 1]]					) * 0.2_5
   lowercase__						:	Optional[int]         = np.array([[1, 1], [1, 1]]					) * 0.2_5
   lowercase__						:	Optional[Any]         = np.array(
       [[1 / 12, 1 / 6, 1 / 12], [1 / 6, 0, 1 / 6], [1 / 12, 1 / 6, 1 / 12]]					)

   # Iteratively refine the flow
   for _ in range(A					):
      lowercase__						:	Optional[int]         = warp(A		,				A		,				A					)
      lowercase__						:	Union[str, Any]         = convolve(A		,				A					) + convolve(A		,				A					)
      lowercase__						:	Union[str, Any]         = convolve(A		,				A					) + convolve(A		,				A					)
      lowercase__						:	str         = convolve(A		,				A					) + convolve(A		,				-kernel_t					)

      lowercase__						:	str         = convolve(A		,				A					)
      lowercase__						:	Tuple         = convolve(A		,				A					)

      # This updates the flow as proposed in the paper (Step 12)
      lowercase__						:	List[Any]         = (
          derivative_x * avg_horizontal_velocity
          + derivative_y * avg_vertical_velocity
          + derivative_t
      )
      lowercase__						:	Union[str, Any]         = update / (alpha**2 + derivative_x**2 + derivative_y**2)

      lowercase__						:	Optional[int]         = avg_horizontal_velocity - derivative_x * update
      lowercase__						:	int         = avg_vertical_velocity - derivative_y * update

   return horizontal_flow, vertical_flow


if __name__ == "__main__":
 import doctest

 doctest.testmod()


