




# 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       __lowercase      (	lowercase_  ):







     '''simple docstring'''
     SCREAMING_SNAKE_CASE   						=				(
         "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."
     )
     SCREAMING_SNAKE_CASE   						=				"CIDAS/clipseg-rd64-refined"
     SCREAMING_SNAKE_CASE   						=				"image_segmenter"
     SCREAMING_SNAKE_CASE   						=				CLIPSegForImageSegmentation

     SCREAMING_SNAKE_CASE   						=				["image", "text"]
     SCREAMING_SNAKE_CASE   						=				["image"]




     def __init__(				self       :			Any ,	*UpperCamelCase_       :			List[str] ,	**UpperCamelCase_       :			List[Any]				):


         """simple docstring"""



         requires_backends(self ,	["""vision"""]				)
         super().__init__(*UpperCamelCase_ ,	**UpperCamelCase_				)




     def 		lowerCAmelCase_     (				self       :			Union[str, Any] ,	UpperCamelCase_       :			"Image" ,	UpperCamelCase_       :			str				):


         """simple docstring"""



         return self.pre_processor(text=[label] ,	images=[image] ,	padding=UpperCamelCase_ ,	return_tensors="""pt"""				)




     def 		lowerCAmelCase_     (				self       :			Union[str, Any] ,	UpperCamelCase_       :			Dict				):


         """simple docstring"""



         with torch.no_grad():
             __A         =	self.model(**UpperCamelCase_				).logits
         return logits





     def 		lowerCAmelCase_     (				self       :			Dict ,	UpperCamelCase_       :			Dict				):


         """simple docstring"""



         __A         =	outputs.cpu().detach().numpy()
         __A         =	0
         __A         =	1
         return Image.fromarray((array * 255).astype(np.uinta				)				)












from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding


class       __lowercase      (	lowercase_  ):







     '''simple docstring'''
     SCREAMING_SNAKE_CASE   						=				["image_processor", "tokenizer"]
     SCREAMING_SNAKE_CASE   						=				"AutoImageProcessor"
     SCREAMING_SNAKE_CASE   						=				"AutoTokenizer"




     def __init__(				self       :			str ,	UpperCamelCase_       :			Any ,	UpperCamelCase_       :			str				):


         """simple docstring"""



         super().__init__(UpperCamelCase_ ,	UpperCamelCase_				)
         __A         =	self.image_processor




     def __call__(				self       :			Optional[Any] ,	UpperCamelCase_       :			Optional[Any]=None ,	UpperCamelCase_       :			Any=None ,	UpperCamelCase_       :			List[Any]=None ,	**UpperCamelCase_       :			int				):


         """simple docstring"""



         if text is None and images is None:
             raise ValueError("""You have to specify either text or images. Both cannot be none."""				)

         if text is not None:
             __A         =	self.tokenizer(UpperCamelCase_ ,	return_tensors=UpperCamelCase_ ,	**UpperCamelCase_				)

         if images is not None:
             __A         =	self.image_processor(UpperCamelCase_ ,	return_tensors=UpperCamelCase_ ,	**UpperCamelCase_				)

         if text is not None and images is not None:
             __A         =	image_features.pixel_values
             return encoding
         elif text is not None:
             return encoding
         else:
             return BatchEncoding(data=dict(**UpperCamelCase_				) ,	tensor_type=UpperCamelCase_				)




     def 		lowerCAmelCase_     (				self       :			List[str] ,	*UpperCamelCase_       :			Tuple ,	**UpperCamelCase_       :			List[str]				):


         """simple docstring"""



         return self.tokenizer.batch_decode(*UpperCamelCase_ ,	**UpperCamelCase_				)




     def 		lowerCAmelCase_     (				self       :			Any ,	*UpperCamelCase_       :			int ,	**UpperCamelCase_       :			Tuple				):


         """simple docstring"""



         return self.tokenizer.decode(*UpperCamelCase_ ,	**UpperCamelCase_				)





     @property
     def 		lowerCAmelCase_     (				self       :			Optional[Any]				):


         """simple docstring"""



         return ["input_ids", "attention_mask", "pixel_values"]




