


"""simple docstring"""







from __future__ import annotations

from collections import deque






class 						_A  :







    """simple docstring"""




    def __init__(					self				:    str				, __UpperCAmelCase				:    list[str]):
      a						:		list[dict]      							=			[]
      self.adlist.append(
          {"value": "", "next_states": [], "fail_state": 0, "output": []})

      for keyword in keywords:
        self.add_keyword(__UpperCAmelCase)
      self.set_fail_transitions()






    def 	__snake_case							(					self				:    Dict				, __UpperCAmelCase				:    int				, __UpperCAmelCase				:    str):
      for state in self.adlist[current_state]["next_states"]:
        if char == self.adlist[state]["value"]:
          return state
      return None






    def 	__snake_case							(					self				:    str				, __UpperCAmelCase				:    str):
      a						:		Dict      							=			0
      for character in keyword:
        a						:		Any      							=			self.find_next_state(__UpperCAmelCase				, __UpperCAmelCase)
        if next_state is None:
          self.adlist.append(
              {
                  "value": character,
                  "next_states": [],
                  "fail_state": 0,
                  "output": [],
              })
          self.adlist[current_state]["next_states"].append(len(self.adlist) - 1)
          a						:		Tuple      							=			len(self.adlist) - 1
        else:
          a						:		Tuple      							=			next_state
      self.adlist[current_state]["output"].append(__UpperCAmelCase)






    def 	__snake_case							(					self				:    Optional[Any]):
      a						:		deque      							=			deque()
      for node in self.adlist[0]["next_states"]:
        q.append(__UpperCAmelCase)
        a						:		Optional[Any]      							=			0
      while q:
        a						:		Optional[int]      							=			q.popleft()
        for child in self.adlist[r]["next_states"]:
          q.append(__UpperCAmelCase)
          a						:		List[str]      							=			self.adlist[r]["fail_state"]
          while (
              self.find_next_state(__UpperCAmelCase				, self.adlist[child]["value"]) is None
              and state != 0
          ):
            a						:		Optional[int]      							=			self.adlist[state]["fail_state"]
          a						:		Dict      							=			self.find_next_state(
              __UpperCAmelCase				, self.adlist[child]["value"])
          if self.adlist[child]["fail_state"] is None:
            a						:		Optional[int]      							=			0
          a						:		Union[str, Any]      							=			(
              self.adlist[child]["output"]
              + self.adlist[self.adlist[child]["fail_state"]]["output"]
          )






    def 	__snake_case							(					self				:    List[Any]				, __UpperCAmelCase				:    str):
      a						:		dict      							=			{}  # returns a dict with keywords and list of its occurrences
      a						:		Any      							=			0
      for i in range(len(__UpperCAmelCase)):
        while (
            self.find_next_state(__UpperCAmelCase				, string[i]) is None
            and current_state != 0
        ):
          a						:		Any      							=			self.adlist[current_state]["fail_state"]
        a						:		str      							=			self.find_next_state(__UpperCAmelCase				, string[i])
        if next_state is None:
          a						:		Dict      							=			0
        else:
          a						:		Optional[int]      							=			next_state
          for key in self.adlist[current_state]["output"]:
            if key not in result:
              a						:		List[str]      							=			[]
            result[key].append(i - len(__UpperCAmelCase) + 1)
      return result


if __name__ == "__main__":
 import doctest

 doctest.testmod()










"""simple docstring"""







import os
import sys
import unittest


__lowercase    					=      os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
sys.path.append(os.path.join(git_repo_path, """utils"""))

import check_dummies  # noqa: E402
from check_dummies import create_dummy_files, create_dummy_object, find_backend, read_init  # noqa: E402


# Align TRANSFORMERS_PATH in check_dummies with the current path
__lowercase    					=      os.path.join(git_repo_path, """src""", """diffusers""")






class 						_A  (  unittest.TestCase  ):







    """simple docstring"""




    def 	__snake_case							(					self				:    Any):
      a						:		List[Any]      							=			find_backend("    if not is_torch_available():")
      self.assertEqual(__UpperCAmelCase				, "torch")

      # backend_with_underscore = find_backend("    if not is_tensorflow_text_available():")
      # self.assertEqual(backend_with_underscore, "tensorflow_text")

      a						:		Dict      							=			find_backend("    if not (is_torch_available() and is_transformers_available()):")
      self.assertEqual(__UpperCAmelCase				, "torch_and_transformers")

      # double_backend_with_underscore = find_backend(
      #    "    if not (is_sentencepiece_available() and is_tensorflow_text_available()):"
      # )
      # self.assertEqual(double_backend_with_underscore, "sentencepiece_and_tensorflow_text")

      a						:		int      							=			find_backend(
          "    if not (is_torch_available() and is_transformers_available() and is_onnx_available()):")
      self.assertEqual(__UpperCAmelCase				, "torch_and_transformers_and_onnx")






    def 	__snake_case							(					self				:    Union[str, Any]):
      a						:		Dict      							=			read_init()
      # We don't assert on the exact list of keys to allow for smooth grow of backend-specific objects
      self.assertIn("torch"				, __UpperCAmelCase)
      self.assertIn("torch_and_transformers"				, __UpperCAmelCase)
      self.assertIn("flax_and_transformers"				, __UpperCAmelCase)
      self.assertIn("torch_and_transformers_and_onnx"				, __UpperCAmelCase)

      # Likewise, we can't assert on the exact content of a key
      self.assertIn("UNet2DModel"				, objects["torch"])
      self.assertIn("FlaxUNet2DConditionModel"				, objects["flax"])
      self.assertIn("StableDiffusionPipeline"				, objects["torch_and_transformers"])
      self.assertIn("FlaxStableDiffusionPipeline"				, objects["flax_and_transformers"])
      self.assertIn("LMSDiscreteScheduler"				, objects["torch_and_scipy"])
      self.assertIn("OnnxStableDiffusionPipeline"				, objects["torch_and_transformers_and_onnx"])






    def 	__snake_case							(					self				:    Tuple):
      a						:		Optional[int]      							=			create_dummy_object("CONSTANT"				, "'torch'")
      self.assertEqual(__UpperCAmelCase				, "\nCONSTANT = None\n")

      a						:		Dict      							=			create_dummy_object("function"				, "'torch'")
      self.assertEqual(
          __UpperCAmelCase				, "\ndef function(*args, **kwargs):\n    requires_backends(function, 'torch')\n")

      a						:		Optional[Any]      							=			"\nclass FakeClass(metaclass=DummyObject):\n    _backends = 'torch'\n\n    def __init__(self, *args, **kwargs):\n        requires_backends(self, 'torch')\n\n    @classmethod\n    def from_config(cls, *args, **kwargs):\n        requires_backends(cls, 'torch')\n\n    @classmethod\n    def from_pretrained(cls, *args, **kwargs):\n        requires_backends(cls, 'torch')\n"
      a						:		int      							=			create_dummy_object("FakeClass"				, "'torch'")
      self.assertEqual(__UpperCAmelCase				, __UpperCAmelCase)






    def 	__snake_case							(					self				:    List[str]):
      a						:		List[str]      							=			"# This file is autogenerated by the command `make fix-copies`, do not edit.\nfrom ..utils import DummyObject, requires_backends\n\n\nCONSTANT = None\n\n\ndef function(*args, **kwargs):\n    requires_backends(function, [\"torch\"])\n\n\nclass FakeClass(metaclass=DummyObject):\n    _backends = [\"torch\"]\n\n    def __init__(self, *args, **kwargs):\n        requires_backends(self, [\"torch\"])\n\n    @classmethod\n    def from_config(cls, *args, **kwargs):\n        requires_backends(cls, [\"torch\"])\n\n    @classmethod\n    def from_pretrained(cls, *args, **kwargs):\n        requires_backends(cls, [\"torch\"])\n"
      a						:		Tuple      							=			create_dummy_files({"torch": ["CONSTANT", "function", "FakeClass"]})
      self.assertEqual(dummy_files["torch"]				, __UpperCAmelCase)






