



"""simple docstring"""
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						:		Any			= "src/diffusers"

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


UpperCAmelCase						:		List[Any]			= "\n{0} = None\n"

UpperCAmelCase						:		Tuple			= "\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						:		int			= "\ndef {0}(*args, **kwargs):\n    requires_backends({0}, {1})\n"


def 			_SCREAMING_SNAKE_CASE						(__lowerCAmelCase							) ->						Dict:







  '''simple docstring'''


  lowercase_								= _re_backend.findall(snake_case_							)
  if len(snake_case_							) == 0:
    return None

  return "_and_".join(snake_case_							)


def 			_SCREAMING_SNAKE_CASE						() ->						List[Any]:







  '''simple docstring'''


  with open(os.path.join(snake_case_ ,  """__init__.py"""							) ,  """r""" ,  encoding="""utf-8""" ,  newline="""\n"""							) as f:
    lowercase_								= f.readlines()

  # Get to the point we do the actual imports for type checking
  lowercase_								= 0
  lowercase_								= {}
  # Go through the end of the file
  while line_index < len(snake_case_							):
    # If the line contains is_backend_available, we grab all objects associated with the `else` block
    lowercase_								= find_backend(lines[line_index]							)
    if backend is not None:
      while not lines[line_index].startswith("""else:"""							):
        line_index += 1
      line_index += 1
      lowercase_								= []
      # Until we unindent, add backend objects to the list
      while line_index < len(snake_case_							) and len(lines[line_index]							) > 1:
        lowercase_								= lines[line_index]
        lowercase_								= _re_single_line_import.search(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(snake_case_							) > 0:
        lowercase_								= objects
    else:
      line_index += 1

  return backend_specific_objects


def 			_SCREAMING_SNAKE_CASE						(__lowerCAmelCase ,  __lowerCAmelCase							) ->						Dict:







  '''simple docstring'''


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


def 			_SCREAMING_SNAKE_CASE						(__lowerCAmelCase=None							) ->						Any:







  '''simple docstring'''


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

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

  return dummy_files


def 			_SCREAMING_SNAKE_CASE						(__lowerCAmelCase=False							) ->						Dict:







  '''simple docstring'''


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

  # Locate actual dummy modules and read their content.
  lowercase_								= os.path.join(snake_case_ ,  """utils"""							)
  lowercase_								= {
      backend: os.path.join(snake_case_ ,  F'''dummy_{short_names.get(snake_case_ ,  snake_case_							)}_objects.py'''							)
      for backend in dummy_files.keys()
  }

  lowercase_								= {}
  for backend, file_path in dummy_file_paths.items():
    if os.path.isfile(snake_case_							):
      with open(snake_case_ ,  """r""" ,  encoding="""utf-8""" ,  newline="""\n"""							) as f:
        lowercase_								= f.read()
    else:
      lowercase_								= """"""

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


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

       check_dummies(args.fix_and_overwrite)










"""simple docstring"""
import unittest

from transformers import MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING, is_vision_available, pipeline
from transformers.testing_utils import (
    is_pipeline_test,
    nested_simplify,
    require_tf,
    require_torch,
    require_vision,
    slow,
)

from .test_pipelines_common import ANY


if is_vision_available():
       from PIL import Image
else:


       class    SCREAMING_SNAKE_CASE__ :

           @staticmethod
           def 					_UpperCAmelCase	(				*lowerCAmelCase_			:				Tuple ,  **lowerCAmelCase_			:				Tuple):







             """simple docstring"""







             pass


@is_pipeline_test
@require_vision
@require_torch
class    SCREAMING_SNAKE_CASE__ (							unittest.TestCase   ):
    lowercase__      =   MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING

    def 					_UpperCAmelCase	(				self			:				Optional[Any] ,  lowerCAmelCase_			:				int ,  lowerCAmelCase_			:				int ,  lowerCAmelCase_			:				List[Any]):







      """simple docstring"""







      lowercase_								= pipeline(
          """zero-shot-object-detection""" ,  model="""hf-internal-testing/tiny-random-owlvit-object-detection""")

      lowercase_								= [
          {
              """image""": """./tests/fixtures/tests_samples/COCO/000000039769.png""",
              """candidate_labels""": ["""cat""", """remote""", """couch"""],
          }
      ]
      return object_detector, examples

    def 					_UpperCAmelCase	(				self			:				Optional[Any] ,  lowerCAmelCase_			:				int ,  lowerCAmelCase_			:				Optional[Any]):







      """simple docstring"""







      lowercase_								= object_detector(examples[0] ,  threshold=0.0)

      lowercase_								= len(lowerCAmelCase_)
      self.assertGreater(lowerCAmelCase_ ,  0)
      self.assertEqual(
          lowerCAmelCase_ ,  [
              {
                  """score""": ANY(lowerCAmelCase_),
                  """label""": ANY(lowerCAmelCase_),
                  """box""": {"""xmin""": ANY(lowerCAmelCase_), """ymin""": ANY(lowerCAmelCase_), """xmax""": ANY(lowerCAmelCase_), """ymax""": ANY(lowerCAmelCase_)},
              }
              for i in range(lowerCAmelCase_)
          ] ,  )

    @require_tf
    @unittest.skip("""Zero Shot Object Detection not implemented in TF""")
    def 					_UpperCAmelCase	(				self			:				Any):







      """simple docstring"""







      pass

    @require_torch
    def 					_UpperCAmelCase	(				self			:				List[Any]):







      """simple docstring"""







      lowercase_								= pipeline(
          """zero-shot-object-detection""" ,  model="""hf-internal-testing/tiny-random-owlvit-object-detection""")

      lowercase_								= object_detector(
          """./tests/fixtures/tests_samples/COCO/000000039769.png""" ,  candidate_labels=["""cat""", """remote""", """couch"""] ,  threshold=0.64 ,  )

      self.assertEqual(
          nested_simplify(lowerCAmelCase_ ,  decimals=4) ,  [
              {"""score""": 0.7_235, """label""": """cat""", """box""": {"""xmin""": 2_0_4, """ymin""": 1_6_7, """xmax""": 2_3_2, """ymax""": 1_9_0}},
              {"""score""": 0.7_218, """label""": """remote""", """box""": {"""xmin""": 2_0_4, """ymin""": 1_6_7, """xmax""": 2_3_2, """ymax""": 1_9_0}},
              {"""score""": 0.7_184, """label""": """couch""", """box""": {"""xmin""": 2_0_4, """ymin""": 1_6_7, """xmax""": 2_3_2, """ymax""": 1_9_0}},
              {"""score""": 0.6_748, """label""": """remote""", """box""": {"""xmin""": 5_7_1, """ymin""": 8_3, """xmax""": 5_9_8, """ymax""": 1_0_3}},
              {"""score""": 0.6_656, """label""": """cat""", """box""": {"""xmin""": 5_7_1, """ymin""": 8_3, """xmax""": 5_9_8, """ymax""": 1_0_3}},
              {"""score""": 0.6_614, """label""": """couch""", """box""": {"""xmin""": 5_7_1, """ymin""": 8_3, """xmax""": 5_9_8, """ymax""": 1_0_3}},
              {"""score""": 0.6_456, """label""": """remote""", """box""": {"""xmin""": 4_9_4, """ymin""": 1_0_5, """xmax""": 5_2_1, """ymax""": 1_2_7}},
              {"""score""": 0.642, """label""": """remote""", """box""": {"""xmin""": 6_7, """ymin""": 2_7_4, """xmax""": 9_3, """ymax""": 2_9_7}},
              {"""score""": 0.6_419, """label""": """cat""", """box""": {"""xmin""": 4_9_4, """ymin""": 1_0_5, """xmax""": 5_2_1, """ymax""": 1_2_7}},
          ] ,  )

      lowercase_								= object_detector(
          [
              {
                  """image""": """./tests/fixtures/tests_samples/COCO/000000039769.png""",
                  """candidate_labels""": ["""cat""", """remote""", """couch"""],
              }
          ] ,  threshold=0.64 ,  )

      self.assertEqual(
          nested_simplify(lowerCAmelCase_ ,  decimals=4) ,  [
              [
                  {"""score""": 0.7_235, """label""": """cat""", """box""": {"""xmin""": 2_0_4, """ymin""": 1_6_7, """xmax""": 2_3_2, """ymax""": 1_9_0}},
                  {"""score""": 0.7_218, """label""": """remote""", """box""": {"""xmin""": 2_0_4, """ymin""": 1_6_7, """xmax""": 2_3_2, """ymax""": 1_9_0}},
                  {"""score""": 0.7_184, """label""": """couch""", """box""": {"""xmin""": 2_0_4, """ymin""": 1_6_7, """xmax""": 2_3_2, """ymax""": 1_9_0}},
                  {"""score""": 0.6_748, """label""": """remote""", """box""": {"""xmin""": 5_7_1, """ymin""": 8_3, """xmax""": 5_9_8, """ymax""": 1_0_3}},
                  {"""score""": 0.6_656, """label""": """cat""", """box""": {"""xmin""": 5_7_1, """ymin""": 8_3, """xmax""": 5_9_8, """ymax""": 1_0_3}},
                  {"""score""": 0.6_614, """label""": """couch""", """box""": {"""xmin""": 5_7_1, """ymin""": 8_3, """xmax""": 5_9_8, """ymax""": 1_0_3}},
                  {"""score""": 0.6_456, """label""": """remote""", """box""": {"""xmin""": 4_9_4, """ymin""": 1_0_5, """xmax""": 5_2_1, """ymax""": 1_2_7}},
                  {"""score""": 0.642, """label""": """remote""", """box""": {"""xmin""": 6_7, """ymin""": 2_7_4, """xmax""": 9_3, """ymax""": 2_9_7}},
                  {"""score""": 0.6_419, """label""": """cat""", """box""": {"""xmin""": 4_9_4, """ymin""": 1_0_5, """xmax""": 5_2_1, """ymax""": 1_2_7}},
              ]
          ] ,  )

    @require_torch
    @slow
    def 					_UpperCAmelCase	(				self			:				Dict):







      """simple docstring"""







      lowercase_								= pipeline("""zero-shot-object-detection""")

      lowercase_								= object_detector(
          """http://images.cocodataset.org/val2017/000000039769.jpg""" ,  candidate_labels=["""cat""", """remote""", """couch"""] ,  )
      self.assertEqual(
          nested_simplify(lowerCAmelCase_ ,  decimals=4) ,  [
              {"""score""": 0.2_868, """label""": """cat""", """box""": {"""xmin""": 3_2_4, """ymin""": 2_0, """xmax""": 6_4_0, """ymax""": 3_7_3}},
              {"""score""": 0.277, """label""": """remote""", """box""": {"""xmin""": 4_0, """ymin""": 7_2, """xmax""": 1_7_7, """ymax""": 1_1_5}},
              {"""score""": 0.2_537, """label""": """cat""", """box""": {"""xmin""": 1, """ymin""": 5_5, """xmax""": 3_1_5, """ymax""": 4_7_2}},
              {"""score""": 0.1_474, """label""": """remote""", """box""": {"""xmin""": 3_3_5, """ymin""": 7_4, """xmax""": 3_7_1, """ymax""": 1_8_7}},
              {"""score""": 0.1_208, """label""": """couch""", """box""": {"""xmin""": 4, """ymin""": 0, """xmax""": 6_4_2, """ymax""": 4_7_6}},
          ] ,  )

      lowercase_								= object_detector(
          [
              {
                  """image""": """http://images.cocodataset.org/val2017/000000039769.jpg""",
                  """candidate_labels""": ["""cat""", """remote""", """couch"""],
              },
              {
                  """image""": """http://images.cocodataset.org/val2017/000000039769.jpg""",
                  """candidate_labels""": ["""cat""", """remote""", """couch"""],
              },
          ] ,  )
      self.assertEqual(
          nested_simplify(lowerCAmelCase_ ,  decimals=4) ,  [
              [
                  {"""score""": 0.2_868, """label""": """cat""", """box""": {"""xmin""": 3_2_4, """ymin""": 2_0, """xmax""": 6_4_0, """ymax""": 3_7_3}},
                  {"""score""": 0.277, """label""": """remote""", """box""": {"""xmin""": 4_0, """ymin""": 7_2, """xmax""": 1_7_7, """ymax""": 1_1_5}},
                  {"""score""": 0.2_537, """label""": """cat""", """box""": {"""xmin""": 1, """ymin""": 5_5, """xmax""": 3_1_5, """ymax""": 4_7_2}},
                  {"""score""": 0.1_474, """label""": """remote""", """box""": {"""xmin""": 3_3_5, """ymin""": 7_4, """xmax""": 3_7_1, """ymax""": 1_8_7}},
                  {"""score""": 0.1_208, """label""": """couch""", """box""": {"""xmin""": 4, """ymin""": 0, """xmax""": 6_4_2, """ymax""": 4_7_6}},
              ],
              [
                  {"""score""": 0.2_868, """label""": """cat""", """box""": {"""xmin""": 3_2_4, """ymin""": 2_0, """xmax""": 6_4_0, """ymax""": 3_7_3}},
                  {"""score""": 0.277, """label""": """remote""", """box""": {"""xmin""": 4_0, """ymin""": 7_2, """xmax""": 1_7_7, """ymax""": 1_1_5}},
                  {"""score""": 0.2_537, """label""": """cat""", """box""": {"""xmin""": 1, """ymin""": 5_5, """xmax""": 3_1_5, """ymax""": 4_7_2}},
                  {"""score""": 0.1_474, """label""": """remote""", """box""": {"""xmin""": 3_3_5, """ymin""": 7_4, """xmax""": 3_7_1, """ymax""": 1_8_7}},
                  {"""score""": 0.1_208, """label""": """couch""", """box""": {"""xmin""": 4, """ymin""": 0, """xmax""": 6_4_2, """ymax""": 4_7_6}},
              ],
          ] ,  )

    @require_tf
    @unittest.skip("""Zero Shot Object Detection not implemented in TF""")
    def 					_UpperCAmelCase	(				self			:				List[Any]):







      """simple docstring"""







      pass

    @require_torch
    @slow
    def 					_UpperCAmelCase	(				self			:				List[str]):







      """simple docstring"""







      lowercase_								= 0.2
      lowercase_								= pipeline("""zero-shot-object-detection""")

      lowercase_								= object_detector(
          """http://images.cocodataset.org/val2017/000000039769.jpg""" ,  candidate_labels=["""cat""", """remote""", """couch"""] ,  threshold=lowerCAmelCase_ ,  )
      self.assertEqual(
          nested_simplify(lowerCAmelCase_ ,  decimals=4) ,  [
              {"""score""": 0.2_868, """label""": """cat""", """box""": {"""xmin""": 3_2_4, """ymin""": 2_0, """xmax""": 6_4_0, """ymax""": 3_7_3}},
              {"""score""": 0.277, """label""": """remote""", """box""": {"""xmin""": 4_0, """ymin""": 7_2, """xmax""": 1_7_7, """ymax""": 1_1_5}},
              {"""score""": 0.2_537, """label""": """cat""", """box""": {"""xmin""": 1, """ymin""": 5_5, """xmax""": 3_1_5, """ymax""": 4_7_2}},
          ] ,  )




    @require_torch
    @slow
    def 					_UpperCAmelCase	(				self			:				Any):







      """simple docstring"""







      lowercase_								= 2
      lowercase_								= pipeline("""zero-shot-object-detection""")

      lowercase_								= object_detector(
          """http://images.cocodataset.org/val2017/000000039769.jpg""" ,  candidate_labels=["""cat""", """remote""", """couch"""] ,  top_k=lowerCAmelCase_ ,  )
      self.assertEqual(
          nested_simplify(lowerCAmelCase_ ,  decimals=4) ,  [
              {"""score""": 0.2_868, """label""": """cat""", """box""": {"""xmin""": 3_2_4, """ymin""": 2_0, """xmax""": 6_4_0, """ymax""": 3_7_3}},
              {"""score""": 0.277, """label""": """remote""", """box""": {"""xmin""": 4_0, """ymin""": 7_2, """xmax""": 1_7_7, """ymax""": 1_1_5}},
          ] ,  )

