
"""simple docstring"""





import os
import sys
import unittest


_a														=		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
_a														=		os.path.join(git_repo_path, """src""", """diffusers""")






class    _UpperCAmelCase(   unittest.TestCase     ):



		def 						UpperCAmelCase							( self)	->	List[str]:






							'''simple docstring'''
							_UpperCamelCase										=  find_backend('''    if not is_torch_available():''')
							self.assertEqual(__a    ,		'''torch''')

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

							_UpperCamelCase										=  find_backend('''    if not (is_torch_available() and is_transformers_available()):''')
							self.assertEqual(__a    ,		'''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")

							_UpperCamelCase										=  find_backend(
							    '''    if not (is_torch_available() and is_transformers_available() and is_onnx_available()):''')
							self.assertEqual(__a    ,		'''torch_and_transformers_and_onnx''')



		def 						UpperCAmelCase							( self)	->	str:






							'''simple docstring'''
							_UpperCamelCase										=  read_init()
							# We don't assert on the exact list of keys to allow for smooth grow of backend-specific objects
							self.assertIn('''torch'''    ,		__a)
							self.assertIn('''torch_and_transformers'''    ,		__a)
							self.assertIn('''flax_and_transformers'''    ,		__a)
							self.assertIn('''torch_and_transformers_and_onnx'''    ,		__a)

							# 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 						UpperCAmelCase							( self)	->	Union[str, Any]:






							'''simple docstring'''
							_UpperCamelCase										=  create_dummy_object('''CONSTANT'''    ,		'''\'torch\'''')
							self.assertEqual(__a    ,		'''\nCONSTANT = None\n''')

							_UpperCamelCase										=  create_dummy_object('''function'''    ,		'''\'torch\'''')
							self.assertEqual(
							    __a    ,		'''\ndef function(*args, **kwargs):\n    requires_backends(function, \'torch\')\n''')

							_UpperCamelCase										=  '''
class FakeClass(metaclass=DummyObject):
    _backends = \'torch\'

    def __init__(self, *args, **kwargs):
        requires_backends(self, \'torch\')

    @classmethod
    def from_config(cls, *args, **kwargs):
        requires_backends(cls, \'torch\')

    @classmethod
    def from_pretrained(cls, *args, **kwargs):
        requires_backends(cls, \'torch\')
'''
							_UpperCamelCase										=  create_dummy_object('''FakeClass'''    ,		'''\'torch\'''')
							self.assertEqual(__a    ,		__a)




		def 						UpperCAmelCase							( self)	->	List[str]:






							'''simple docstring'''
							_UpperCamelCase										=  '''# This file is autogenerated by the command `make fix-copies`, do not edit.
from ..utils import DummyObject, requires_backends


CONSTANT = None


def function(*args, **kwargs):
    requires_backends(function, ["torch"])


class FakeClass(metaclass=DummyObject):
    _backends = ["torch"]

    def __init__(self, *args, **kwargs):
        requires_backends(self, ["torch"])

    @classmethod
    def from_config(cls, *args, **kwargs):
        requires_backends(cls, ["torch"])

    @classmethod
    def from_pretrained(cls, *args, **kwargs):
        requires_backends(cls, ["torch"])
'''
							_UpperCamelCase										=  create_dummy_files({'''torch''': ['''CONSTANT''', '''function''', '''FakeClass''']})
							self.assertEqual(dummy_files['''torch''']    ,		__a)








"""simple docstring"""





# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import numpy as np
import torch

from ..models.clipseg import CLIPSegForImageSegmentation
from ..utils import is_vision_available, requires_backends
from .base import PipelineTool


if is_vision_available():
				from PIL import Image






class    _UpperCAmelCase(   lowerCamelCase     ):
		lowercase__      =				(
		    'This is a tool that creates a segmentation mask of an image according to a label. It cannot create an image.'
		    'It takes two arguments named `image` which should be the original image, and `label` which should be a text '
		    'describing the elements what should be identified in the segmentation mask. The tool returns the mask.'
		)
		lowercase__      =				'CIDAS/clipseg-rd64-refined'
		lowercase__      =				'image_segmenter'
		lowercase__      =				CLIPSegForImageSegmentation

		lowercase__      =				['image', 'text']
		lowercase__      =				['image']



		def __init__( self    ,		*__a    ,		**__a)	->	Any:






							'''simple docstring'''
							requires_backends(self    ,		['''vision'''])
							super().__init__(*__a    ,		**__a)



		def 						UpperCAmelCase							( self    ,		__a    ,		__a)	->	Dict:






							'''simple docstring'''
							return self.pre_processor(text=[label]    ,		images=[image]    ,		padding=__a    ,		return_tensors='''pt''')



		def 						UpperCAmelCase							( self    ,		__a)	->	Tuple:






							'''simple docstring'''
							with torch.no_grad():
												_UpperCamelCase										=  self.model(**__a).logits
							return logits




		def 						UpperCAmelCase							( self    ,		__a)	->	Any:






							'''simple docstring'''
							_UpperCamelCase										=  outputs.cpu().detach().numpy()
							_UpperCamelCase										=  0
							_UpperCamelCase										=  1
							return Image.fromarray((array * 2_55).astype(np.uinta))






