





import shutil
import tempfile
import unittest

import numpy as np

from transformers.testing_utils import (
    is_pt_tf_cross_test,
    require_tf,
    require_torch,
    require_torchvision,
    require_vision,
)
from transformers.utils import is_tf_available, is_torch_available, is_vision_available


if is_vision_available():
    from PIL import Image

    from transformers import AutoProcessor, SamImageProcessor, SamProcessor

if is_torch_available():
    import torch

if is_tf_available():
    import tensorflow as tf

@require_vision
@require_torchvision
class   lowerCAmelCase				(   unittest.TestCase     ):
 def 	A_      ( self    : List[str]      )     ->      Dict:
     lowerCamelCase__       : Dict   					=						tempfile.mkdtemp()
     lowerCamelCase__       : str   					=						SamImageProcessor()
     lowerCamelCase__       : Dict   					=						SamProcessor(UpperCAmelCase      )
     processor.save_pretrained(self.tmpdirname      )
 def 	A_      ( self    : Optional[Any]     ,	**UpperCAmelCase    : Any      )     ->      List[str]:
     return AutoProcessor.from_pretrained(self.tmpdirname     ,	**UpperCAmelCase      ).image_processor
 def 	A_      ( self    : Optional[int]      )     ->      int:
     shutil.rmtree(self.tmpdirname      )
 def 	A_      ( self    : List[Any]      )     ->      int:
     lowerCamelCase__       : List[str]   					=						[np.random.randint(255     ,	size=(3, 30, 400)     ,	dtype=np.uinta      )]

     lowerCamelCase__       : Any   					=						[Image.fromarray(np.moveaxis(UpperCAmelCase     ,	0     ,	-1      )      ) for x in image_inputs]

     return image_inputs
 def 	A_      ( self    : List[Any]      )     ->      str:
     lowerCamelCase__       : Any   					=						SamProcessor(image_processor=self.get_image_processor()      )
     processor.save_pretrained(self.tmpdirname      )

     lowerCamelCase__       : Dict   					=						self.get_image_processor(do_normalize=UpperCAmelCase     ,	padding_value=1.0      )

     lowerCamelCase__       : int   					=						SamProcessor.from_pretrained(self.tmpdirname     ,	do_normalize=UpperCAmelCase     ,	padding_value=1.0      )

     self.assertEqual(processor.image_processor.to_json_string()     ,	image_processor_add_kwargs.to_json_string()      )
     self.assertIsInstance(processor.image_processor     ,	UpperCAmelCase      )
 def 	A_      ( self    : Tuple      )     ->      str:
     lowerCamelCase__       : List[Any]   					=						self.get_image_processor()

     lowerCamelCase__       : int   					=						SamProcessor(image_processor=UpperCAmelCase      )

     lowerCamelCase__       : List[Any]   					=						self.prepare_image_inputs()

     lowerCamelCase__       : List[Any]   					=						image_processor(UpperCAmelCase     ,	return_tensors='np'      )
     lowerCamelCase__       : Dict   					=						processor(images=UpperCAmelCase     ,	return_tensors='np'      )

     input_feat_extract.pop('original_sizes'      )  # pop original_sizes as it is popped in the processor
     input_feat_extract.pop('reshaped_input_sizes'      )  # pop original_sizes as it is popped in the processor

     for key in input_feat_extract.keys():
         self.assertAlmostEqual(input_feat_extract[key].sum()     ,	input_processor[key].sum()     ,	delta=1e-2      )







 @require_torch
 def 	A_      ( self    : Optional[Any]      )     ->      Dict:
     lowerCamelCase__       : Optional[int]   					=						self.get_image_processor()

     lowerCamelCase__       : Tuple   					=						SamProcessor(image_processor=UpperCAmelCase      )
     lowerCamelCase__       : List[Any]   					=						[torch.ones((1, 3, 5, 5)      )]

     lowerCamelCase__       : int   					=						[[1764, 2646]]

     lowerCamelCase__       : Any   					=						[[683, 1024]]
     lowerCamelCase__       : int   					=						processor.post_process_masks(UpperCAmelCase     ,	UpperCAmelCase     ,	UpperCAmelCase      )
     self.assertEqual(masks[0].shape     ,	(1, 3, 1764, 2646)      )

     lowerCamelCase__       : List[str]   					=						processor.post_process_masks(
         UpperCAmelCase     ,	torch.tensor(UpperCAmelCase      )     ,	torch.tensor(UpperCAmelCase      )      )
     self.assertEqual(masks[0].shape     ,	(1, 3, 1764, 2646)      )

     # should also work with np
     lowerCamelCase__       : str   					=						[np.ones((1, 3, 5, 5)      )]
     lowerCamelCase__       : Optional[Any]   					=						processor.post_process_masks(UpperCAmelCase     ,	np.array(UpperCAmelCase      )     ,	np.array(UpperCAmelCase      )      )

     self.assertEqual(masks[0].shape     ,	(1, 3, 1764, 2646)      )

     lowerCamelCase__       : List[str]   					=						[[1, 0], [0, 1]]
     with self.assertRaises(UpperCAmelCase      ):
         lowerCamelCase__       : str   					=						processor.post_process_masks(UpperCAmelCase     ,	np.array(UpperCAmelCase      )     ,	np.array(UpperCAmelCase      )      )


@require_vision
@require_tf
class   lowerCAmelCase				(   unittest.TestCase     ):
 def 	A_      ( self    : Optional[Any]      )     ->      Optional[Any]:
     lowerCamelCase__       : Dict   					=						tempfile.mkdtemp()
     lowerCamelCase__       : Optional[int]   					=						SamImageProcessor()
     lowerCamelCase__       : List[str]   					=						SamProcessor(UpperCAmelCase      )
     processor.save_pretrained(self.tmpdirname      )
 def 	A_      ( self    : str     ,	**UpperCAmelCase    : Union[str, Any]      )     ->      str:
     return AutoProcessor.from_pretrained(self.tmpdirname     ,	**UpperCAmelCase      ).image_processor
 def 	A_      ( self    : Any      )     ->      Optional[Any]:
     shutil.rmtree(self.tmpdirname      )
 def 	A_      ( self    : List[str]      )     ->      Optional[Any]:
     lowerCamelCase__       : Union[str, Any]   					=						[np.random.randint(255     ,	size=(3, 30, 400)     ,	dtype=np.uinta      )]

     lowerCamelCase__       : Union[str, Any]   					=						[Image.fromarray(np.moveaxis(UpperCAmelCase     ,	0     ,	-1      )      ) for x in image_inputs]

     return image_inputs
 def 	A_      ( self    : int      )     ->      Union[str, Any]:
     lowerCamelCase__       : Optional[int]   					=						SamProcessor(image_processor=self.get_image_processor()      )
     processor.save_pretrained(self.tmpdirname      )

     lowerCamelCase__       : Any   					=						self.get_image_processor(do_normalize=UpperCAmelCase     ,	padding_value=1.0      )

     lowerCamelCase__       : List[Any]   					=						SamProcessor.from_pretrained(self.tmpdirname     ,	do_normalize=UpperCAmelCase     ,	padding_value=1.0      )

     self.assertEqual(processor.image_processor.to_json_string()     ,	image_processor_add_kwargs.to_json_string()      )
     self.assertIsInstance(processor.image_processor     ,	UpperCAmelCase      )
 def 	A_      ( self    : int      )     ->      Optional[Any]:
     lowerCamelCase__       : Optional[int]   					=						self.get_image_processor()

     lowerCamelCase__       : Tuple   					=						SamProcessor(image_processor=UpperCAmelCase      )

     lowerCamelCase__       : Any   					=						self.prepare_image_inputs()

     lowerCamelCase__       : Optional[Any]   					=						image_processor(UpperCAmelCase     ,	return_tensors='np'      )
     lowerCamelCase__       : List[Any]   					=						processor(images=UpperCAmelCase     ,	return_tensors='np'      )

     input_feat_extract.pop('original_sizes'      )  # pop original_sizes as it is popped in the processor
     input_feat_extract.pop('reshaped_input_sizes'      )  # pop reshaped_input_sizes as it is popped in the processor

     for key in input_feat_extract.keys():
         self.assertAlmostEqual(input_feat_extract[key].sum()     ,	input_processor[key].sum()     ,	delta=1e-2      )







 @require_tf
 def 	A_      ( self    : Tuple      )     ->      int:
     lowerCamelCase__       : Union[str, Any]   					=						self.get_image_processor()

     lowerCamelCase__       : int   					=						SamProcessor(image_processor=UpperCAmelCase      )
     lowerCamelCase__       : List[str]   					=						[tf.ones((1, 3, 5, 5)      )]

     lowerCamelCase__       : Optional[int]   					=						[[1764, 2646]]

     lowerCamelCase__       : str   					=						[[683, 1024]]
     lowerCamelCase__       : List[Any]   					=						processor.post_process_masks(UpperCAmelCase     ,	UpperCAmelCase     ,	UpperCAmelCase     ,	return_tensors='tf'      )
     self.assertEqual(masks[0].shape     ,	(1, 3, 1764, 2646)      )

     lowerCamelCase__       : Tuple   					=						processor.post_process_masks(
         UpperCAmelCase     ,	tf.convert_to_tensor(UpperCAmelCase      )     ,	tf.convert_to_tensor(UpperCAmelCase      )     ,	return_tensors='tf'     ,	)
     self.assertEqual(masks[0].shape     ,	(1, 3, 1764, 2646)      )

     # should also work with np
     lowerCamelCase__       : int   					=						[np.ones((1, 3, 5, 5)      )]
     lowerCamelCase__       : List[Any]   					=						processor.post_process_masks(
         UpperCAmelCase     ,	np.array(UpperCAmelCase      )     ,	np.array(UpperCAmelCase      )     ,	return_tensors='tf'      )

     self.assertEqual(masks[0].shape     ,	(1, 3, 1764, 2646)      )

     lowerCamelCase__       : int   					=						[[1, 0], [0, 1]]
     with self.assertRaises(tf.errors.InvalidArgumentError      ):
         lowerCamelCase__       : Optional[int]   					=						processor.post_process_masks(
             UpperCAmelCase     ,	np.array(UpperCAmelCase      )     ,	np.array(UpperCAmelCase      )     ,	return_tensors='tf'      )


@require_vision
@require_torchvision
class   lowerCAmelCase				(   unittest.TestCase     ):
 def 	A_      ( self    : str      )     ->      Optional[int]:
     lowerCamelCase__       : Optional[int]   					=						tempfile.mkdtemp()
     lowerCamelCase__       : Optional[Any]   					=						SamImageProcessor()
     lowerCamelCase__       : List[Any]   					=						SamProcessor(UpperCAmelCase      )
     processor.save_pretrained(self.tmpdirname      )
 def 	A_      ( self    : Union[str, Any]     ,	**UpperCAmelCase    : Optional[Any]      )     ->      List[str]:
     return AutoProcessor.from_pretrained(self.tmpdirname     ,	**UpperCAmelCase      ).image_processor
 def 	A_      ( self    : List[Any]      )     ->      Any:
     shutil.rmtree(self.tmpdirname      )
 def 	A_      ( self    : List[Any]      )     ->      int:
     lowerCamelCase__       : Any   					=						[np.random.randint(255     ,	size=(3, 30, 400)     ,	dtype=np.uinta      )]

     lowerCamelCase__       : Tuple   					=						[Image.fromarray(np.moveaxis(UpperCAmelCase     ,	0     ,	-1      )      ) for x in image_inputs]

     return image_inputs
 @is_pt_tf_cross_test
 def 	A_      ( self    : Union[str, Any]      )     ->      Union[str, Any]:
     lowerCamelCase__       : Dict   					=						self.get_image_processor()

     lowerCamelCase__       : Optional[Any]   					=						SamProcessor(image_processor=UpperCAmelCase      )
     lowerCamelCase__       : str   					=						np.random.randint(0     ,	2     ,	size=(1, 3, 5, 5)      ).astype(np.floataa      )
     lowerCamelCase__       : Union[str, Any]   					=						[tf.convert_to_tensor(UpperCAmelCase      )]
     lowerCamelCase__       : int   					=						[torch.tensor(UpperCAmelCase      )]

     lowerCamelCase__       : Any   					=						[[1764, 2646]]

     lowerCamelCase__       : str   					=						[[683, 1024]]
     lowerCamelCase__       : Optional[Any]   					=						processor.post_process_masks(
         UpperCAmelCase     ,	UpperCAmelCase     ,	UpperCAmelCase     ,	return_tensors='tf'      )
     lowerCamelCase__       : Any   					=						processor.post_process_masks(
         UpperCAmelCase     ,	UpperCAmelCase     ,	UpperCAmelCase     ,	return_tensors='pt'      )

     self.assertTrue(np.all(tf_masks[0].numpy() == pt_masks[0].numpy()      )      )







 @is_pt_tf_cross_test
 def 	A_      ( self    : Optional[int]      )     ->      str:
     lowerCamelCase__       : Optional[int]   					=						self.get_image_processor()

     lowerCamelCase__       : Tuple   					=						SamProcessor(image_processor=UpperCAmelCase      )

     lowerCamelCase__       : List[Any]   					=						self.prepare_image_inputs()

     lowerCamelCase__       : Any   					=						image_processor(UpperCAmelCase     ,	return_tensors='pt'      )['pixel_values'].numpy()
     lowerCamelCase__       : List[Any]   					=						processor(images=UpperCAmelCase     ,	return_tensors='pt'      )['pixel_values'].numpy()

     lowerCamelCase__       : Tuple   					=						image_processor(UpperCAmelCase     ,	return_tensors='tf'      )['pixel_values'].numpy()
     lowerCamelCase__       : int   					=						processor(images=UpperCAmelCase     ,	return_tensors='tf'      )['pixel_values'].numpy()

     self.assertTrue(np.allclose(UpperCAmelCase     ,	UpperCAmelCase      )      )
     self.assertTrue(np.allclose(UpperCAmelCase     ,	UpperCAmelCase      )      )
     self.assertTrue(np.allclose(UpperCAmelCase     ,	UpperCAmelCase      )      )












# 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.
from ..models.auto import AutoModelForSeqaSeqLM, AutoTokenizer
from .base import PipelineTool

class   lowerCAmelCase				(   __UpperCamelCase     ):
 UpperCAmelCase__						=						"""philschmid/bart-large-cnn-samsum"""
 UpperCAmelCase__						=						(
     """This is a tool that summarizes an English text. It takes an input `text` containing the text to summarize, """
     """and returns a summary of the text."""
 )
 UpperCAmelCase__						=						"""summarizer"""
 UpperCAmelCase__						=						AutoTokenizer
 UpperCAmelCase__						=						AutoModelForSeqaSeqLM

 UpperCAmelCase__						=						["""text"""]
 UpperCAmelCase__						=						["""text"""]
 def 	A_      ( self    : Tuple     ,	UpperCAmelCase    : List[Any]      )     ->      List[str]:
     return self.pre_processor(UpperCAmelCase     ,	return_tensors='pt'     ,	truncation=UpperCAmelCase      )
 def 	A_      ( self    : Optional[int]     ,	UpperCAmelCase    : Dict      )     ->      str:
     return self.model.generate(**UpperCAmelCase      )[0]







 def 	A_      ( self    : Tuple     ,	UpperCAmelCase    : List[Any]      )     ->      Union[str, Any]:
     return self.pre_processor.decode(UpperCAmelCase     ,	skip_special_tokens=UpperCAmelCase     ,	clean_up_tokenization_spaces=UpperCAmelCase      )





