





"""simple docstring"""






import json
import sys
import tempfile
import unittest
from pathlib import Path

import transformers
from transformers import (
    CONFIG_MAPPING,
    IMAGE_PROCESSOR_MAPPING,
    AutoConfig,
    AutoImageProcessor,
    CLIPConfig,
    CLIPImageProcessor,
)
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER


sys.path.append(str(Path(__file__).parent.parent.parent.parent / '''utils'''))

from test_module.custom_configuration import CustomConfig  # noqa E402
from test_module.custom_image_processing import CustomImageProcessor  # noqa E402




class 			__lowercase     (     unittest.TestCase							):







					'''simple docstring'''




					def 	_lowerCamelCase						(  self       ):
									__a	:  List[str]         =					0







					def 	_lowerCamelCase						(  self       ):
									__a	:  List[Any]         =					AutoImageProcessor.from_pretrained('''openai/clip-vit-base-patch32'''       )
									self.assertIsInstance(_UpperCAmelCase		,     _UpperCAmelCase       )







					def 	_lowerCamelCase						(  self       ):
									with tempfile.TemporaryDirectory() as tmpdirname:
													__a	:  int         =					Path(_UpperCAmelCase       ) / '''preprocessor_config.json'''
													__a	:  Any         =					Path(_UpperCAmelCase       ) / '''config.json'''
													json.dump(
													    {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''}		,     open(_UpperCAmelCase		,     '''w'''       )		,     )
													json.dump({'''model_type''': '''clip'''}		,     open(_UpperCAmelCase		,     '''w'''       )       )

													__a	:  Tuple         =					AutoImageProcessor.from_pretrained(_UpperCAmelCase       )
													self.assertIsInstance(_UpperCAmelCase		,     _UpperCAmelCase       )







					def 	_lowerCamelCase						(  self       ):
									# Ensure we can load the image processor from the feature extractor config
									with tempfile.TemporaryDirectory() as tmpdirname:
													__a	:  Dict         =					Path(_UpperCAmelCase       ) / '''preprocessor_config.json'''
													__a	:  Dict         =					Path(_UpperCAmelCase       ) / '''config.json'''
													json.dump(
													    {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''}		,     open(_UpperCAmelCase		,     '''w'''       )		,     )
													json.dump({'''model_type''': '''clip'''}		,     open(_UpperCAmelCase		,     '''w'''       )       )

													__a	:  Dict         =					AutoImageProcessor.from_pretrained(_UpperCAmelCase       )
													self.assertIsInstance(_UpperCAmelCase		,     _UpperCAmelCase       )







					def 	_lowerCamelCase						(  self       ):
									with tempfile.TemporaryDirectory() as tmpdirname:
													__a	:  List[Any]         =					CLIPConfig()

													# Create a dummy config file with image_proceesor_type
													__a	:  Dict         =					Path(_UpperCAmelCase       ) / '''preprocessor_config.json'''
													__a	:  List[str]         =					Path(_UpperCAmelCase       ) / '''config.json'''
													json.dump(
													    {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''}		,     open(_UpperCAmelCase		,     '''w'''       )		,     )
													json.dump({'''model_type''': '''clip'''}		,     open(_UpperCAmelCase		,     '''w'''       )       )

													# remove image_processor_type to make sure config.json alone is enough to load image processor locally
													__a	:  Tuple         =					AutoImageProcessor.from_pretrained(_UpperCAmelCase       ).to_dict()

													config_dict.pop('''image_processor_type'''       )
													__a	:  List[Any]         =					CLIPImageProcessor(**_UpperCAmelCase       )

													# save in new folder
													model_config.save_pretrained(_UpperCAmelCase       )
													config.save_pretrained(_UpperCAmelCase       )

													__a	:  int         =					AutoImageProcessor.from_pretrained(_UpperCAmelCase       )

													# make sure private variable is not incorrectly saved
													__a	:  List[Any]         =					json.loads(config.to_json_string()       )
													self.assertTrue('''_processor_class''' not in dict_as_saved       )

									self.assertIsInstance(_UpperCAmelCase		,     _UpperCAmelCase       )







					def 	_lowerCamelCase						(  self       ):
									with tempfile.TemporaryDirectory() as tmpdirname:
													__a	:  Union[str, Any]         =					Path(_UpperCAmelCase       ) / '''preprocessor_config.json'''
													json.dump(
													    {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''}		,     open(_UpperCAmelCase		,     '''w'''       )		,     )

													__a	:  Any         =					AutoImageProcessor.from_pretrained(_UpperCAmelCase       )
													self.assertIsInstance(_UpperCAmelCase		,     _UpperCAmelCase       )







					def 	_lowerCamelCase						(  self       ):
									with self.assertRaisesRegex(
									    _UpperCAmelCase		,     '''clip-base is not a local folder and is not a valid model identifier'''       ):
													__a	:  Tuple         =					AutoImageProcessor.from_pretrained('''clip-base'''       )







					def 	_lowerCamelCase						(  self       ):
									with self.assertRaisesRegex(
									    _UpperCAmelCase		,     R'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)'''       ):
													__a	:  Dict         =					AutoImageProcessor.from_pretrained(_UpperCAmelCase		,     revision='''aaaaaa'''       )







					def 	_lowerCamelCase						(  self       ):
									with self.assertRaisesRegex(
									    _UpperCAmelCase		,     '''hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.'''		,     ):
													__a	:  Any         =					AutoImageProcessor.from_pretrained('''hf-internal-testing/config-no-model'''       )







					def 	_lowerCamelCase						(  self       ):
									# If remote code is not set, we will time out when asking whether to load the model.
									with self.assertRaises(_UpperCAmelCase       ):
													__a	:  int         =					AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor'''       )
									# If remote code is disabled, we can't load this config.
									with self.assertRaises(_UpperCAmelCase       ):
													__a	:  Tuple         =					AutoImageProcessor.from_pretrained(
													    '''hf-internal-testing/test_dynamic_image_processor'''		,     trust_remote_code=_UpperCAmelCase       )

									__a	:  Union[str, Any]         =					AutoImageProcessor.from_pretrained(
									    '''hf-internal-testing/test_dynamic_image_processor'''		,     trust_remote_code=_UpperCAmelCase       )
									self.assertEqual(image_processor.__class__.__name__		,     '''NewImageProcessor'''       )

									# Test image processor can be reloaded.
									with tempfile.TemporaryDirectory() as tmp_dir:
													image_processor.save_pretrained(_UpperCAmelCase       )
													__a	:  List[str]         =					AutoImageProcessor.from_pretrained(_UpperCAmelCase		,     trust_remote_code=_UpperCAmelCase       )
									self.assertEqual(reloaded_image_processor.__class__.__name__		,     '''NewImageProcessor'''       )







					def 	_lowerCamelCase						(  self       ):
									try:
													AutoConfig.register('''custom'''		,     _UpperCAmelCase       )
													AutoImageProcessor.register(_UpperCAmelCase		,     _UpperCAmelCase       )
													# Trying to register something existing in the Transformers library will raise an error
													with self.assertRaises(_UpperCAmelCase       ):
																	AutoImageProcessor.register(_UpperCAmelCase		,     _UpperCAmelCase       )

													with tempfile.TemporaryDirectory() as tmpdirname:
																	__a	:  Optional[Any]         =					Path(_UpperCAmelCase       ) / '''preprocessor_config.json'''
																	__a	:  int         =					Path(_UpperCAmelCase       ) / '''config.json'''
																	json.dump(
																	    {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''}		,     open(_UpperCAmelCase		,     '''w'''       )		,     )
																	json.dump({'''model_type''': '''clip'''}		,     open(_UpperCAmelCase		,     '''w'''       )       )

																	__a	:  Tuple         =					CustomImageProcessor.from_pretrained(_UpperCAmelCase       )

													# Now that the config is registered, it can be used as any other config with the auto-API
													with tempfile.TemporaryDirectory() as tmp_dir:
																	image_processor.save_pretrained(_UpperCAmelCase       )
																	__a	:  int         =					AutoImageProcessor.from_pretrained(_UpperCAmelCase       )
																	self.assertIsInstance(_UpperCAmelCase		,     _UpperCAmelCase       )

									finally:
													if "custom" in CONFIG_MAPPING._extra_content:
																	del CONFIG_MAPPING._extra_content["custom"]
													if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content:
																	del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]







					def 	_lowerCamelCase						(  self       ):




									class 			__lowercase     (     _UpperCamelCase							):







														'''simple docstring'''




														__lowerCAmelCase					=					True

									try:
													AutoConfig.register('''custom'''		,     _UpperCAmelCase       )
													AutoImageProcessor.register(_UpperCAmelCase		,     _UpperCAmelCase       )
													# If remote code is not set, the default is to use local
													__a	:  Optional[int]         =					AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor'''       )
													self.assertEqual(image_processor.__class__.__name__		,     '''NewImageProcessor'''       )
													self.assertTrue(image_processor.is_local       )

													# If remote code is disabled, we load the local one.
													__a	:  Optional[int]         =					AutoImageProcessor.from_pretrained(
													    '''hf-internal-testing/test_dynamic_image_processor'''		,     trust_remote_code=_UpperCAmelCase       )
													self.assertEqual(image_processor.__class__.__name__		,     '''NewImageProcessor'''       )
													self.assertTrue(image_processor.is_local       )

													# If remote is enabled, we load from the Hub
													__a	:  List[Any]         =					AutoImageProcessor.from_pretrained(
													    '''hf-internal-testing/test_dynamic_image_processor'''		,     trust_remote_code=_UpperCAmelCase       )
													self.assertEqual(image_processor.__class__.__name__		,     '''NewImageProcessor'''       )
													self.assertTrue(not hasattr(_UpperCAmelCase		,     '''is_local'''       )       )

									finally:
													if "custom" in CONFIG_MAPPING._extra_content:
																	del CONFIG_MAPPING._extra_content["custom"]
													if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content:
																	del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]






"""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 			__lowercase     (     _UpperCamelCase							):







					'''simple docstring'''




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

					__lowerCAmelCase					=					['''image''', '''text''']
					__lowerCAmelCase					=					['''image''']







					def __init__(  self		,     *_UpperCAmelCase		,     **_UpperCAmelCase       ):
									requires_backends(self		,     ['''vision''']       )
									super().__init__(*_UpperCAmelCase		,     **_UpperCAmelCase       )







					def 	_lowerCamelCase						(  self		,     _UpperCAmelCase		,     _UpperCAmelCase       ):
									return self.pre_processor(text=[label]		,     images=[image]		,     padding=_UpperCAmelCase		,     return_tensors='''pt'''       )







					def 	_lowerCamelCase						(  self		,     _UpperCAmelCase       ):
									with torch.no_grad():
													__a	:  List[str]         =					self.model(**_UpperCAmelCase       ).logits
									return logits







					def 	_lowerCamelCase						(  self		,     _UpperCAmelCase       ):
									__a	:  str         =					outputs.cpu().detach().numpy()
									__a	:  int         =					0
									__a	:  Optional[int]         =					1
									return Image.fromarray((array * 255).astype(np.uinta       )       )