
import random
import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
					import torch

if is_vision_available():
					import PIL

					from transformers import FlavaImageProcessor
					from transformers.image_utils import PILImageResampling
					from transformers.models.flava.image_processing_flava import (
					    FLAVA_CODEBOOK_MEAN,
					    FLAVA_CODEBOOK_STD,
					    FLAVA_IMAGE_MEAN,
					    FLAVA_IMAGE_STD,
					)
else:
					lowerCamelCase__        =						None







class 	A__				(	unittest.TestCase      ):






				def __init__(		self   : Optional[Any]       ,	a   : Tuple       ,	a   : List[str]=7       ,	a   : Union[str, Any]=3       ,	a   : Union[str, Any]=30       ,	a   : Any=400       ,	a   : Union[str, Any]=True       ,	a   : int=None       ,	a   : Any=True       ,	a   : Any=None       ,	a   : List[str]=None       ,	a   : Dict=True       ,	a   : Dict=1 / 255       ,	a   : Optional[Any]=True       ,	a   : List[str]=FLAVA_IMAGE_MEAN       ,	a   : List[Any]=FLAVA_IMAGE_STD       ,	a   : int=14       ,	a   : int=75       ,	a   : str=None       ,	a   : Tuple=16       ,	a   : List[Any]=0.3       ,	a   : Optional[Any]=None       ,	a   : Tuple=True       ,	a   : Dict=None       ,	a   : List[str]=None       ,	a   : Any=True       ,	a   : List[Any]=None       ,	a   : Optional[int]=True       ,	a   : List[Any]=True       ,	a   : Optional[Any]=FLAVA_CODEBOOK_MEAN       ,	a   : Dict=FLAVA_CODEBOOK_STD       ,	):






							'''simple docstring'''







							lowerCAmelCase__ : Tuple   =						size if size is not None else {'height': 224, 'width': 224}
							lowerCAmelCase__ : int   =						crop_size if crop_size is not None else {'height': 224, 'width': 224}
							lowerCAmelCase__ : Optional[Any]   =						codebook_size if codebook_size is not None else {'height': 112, 'width': 112}
							lowerCAmelCase__ : List[str]   =						codebook_crop_size if codebook_crop_size is not None else {'height': 112, 'width': 112}

							lowerCAmelCase__ : Optional[Any]   =						parent
							lowerCAmelCase__ : Optional[Any]   =						batch_size
							lowerCAmelCase__ : Any   =						num_channels
							lowerCAmelCase__ : int   =						do_resize
							lowerCAmelCase__ : Optional[Any]   =						do_rescale
							lowerCAmelCase__ : Optional[int]   =						rescale_factor
							lowerCAmelCase__ : Optional[int]   =						min_resolution
							lowerCAmelCase__ : Any   =						max_resolution
							lowerCAmelCase__ : Union[str, Any]   =						size
							lowerCAmelCase__ : List[Any]   =						resample if resample is not None else PILImageResampling.BICUBIC
							lowerCAmelCase__ : Optional[int]   =						do_normalize
							lowerCAmelCase__ : Any   =						image_mean
							lowerCAmelCase__ : Any   =						image_std
							lowerCAmelCase__ : List[str]   =						do_center_crop
							lowerCAmelCase__ : List[str]   =						crop_size

							lowerCAmelCase__ : List[Any]   =						input_size_patches
							lowerCAmelCase__ : List[Any]   =						total_mask_patches
							lowerCAmelCase__ : List[Any]   =						mask_group_max_patches
							lowerCAmelCase__ : Union[str, Any]   =						mask_group_min_patches
							lowerCAmelCase__ : Optional[Any]   =						mask_group_min_aspect_ratio
							lowerCAmelCase__ : str   =						mask_group_max_aspect_ratio

							lowerCAmelCase__ : Dict   =						codebook_do_resize
							lowerCAmelCase__ : Tuple   =						codebook_size
							lowerCAmelCase__ : Tuple   =						codebook_resample if codebook_resample is not None else PILImageResampling.LANCZOS
							lowerCAmelCase__ : Optional[int]   =						codebook_do_center_crop
							lowerCAmelCase__ : Tuple   =						codebook_crop_size
							lowerCAmelCase__ : int   =						codebook_do_map_pixels
							lowerCAmelCase__ : List[str]   =						codebook_do_normalize
							lowerCAmelCase__ : Union[str, Any]   =						codebook_image_mean
							lowerCAmelCase__ : Dict   =						codebook_image_std






				def 				_lowerCamelCase						(		self   : Any  ):






							'''simple docstring'''







							return {
							    "image_mean": self.image_mean,
							    "image_std": self.image_std,
							    "do_normalize": self.do_normalize,
							    "do_resize": self.do_resize,
							    "size": self.size,
							    "resample": self.resample,
							    "do_rescale": self.do_rescale,
							    "rescale_factor": self.rescale_factor,
							    "do_center_crop": self.do_center_crop,
							    "crop_size": self.crop_size,
							    "input_size_patches": self.input_size_patches,
							    "total_mask_patches": self.total_mask_patches,
							    "mask_group_max_patches": self.mask_group_max_patches,
							    "mask_group_min_patches": self.mask_group_min_patches,
							    "mask_group_min_aspect_ratio": self.mask_group_min_aspect_ratio,
							    "mask_group_max_aspect_ratio": self.mask_group_min_aspect_ratio,
							    "codebook_do_resize": self.codebook_do_resize,
							    "codebook_size": self.codebook_size,
							    "codebook_resample": self.codebook_resample,
							    "codebook_do_center_crop": self.codebook_do_center_crop,
							    "codebook_crop_size": self.codebook_crop_size,
							    "codebook_do_map_pixels": self.codebook_do_map_pixels,
							    "codebook_do_normalize": self.codebook_do_normalize,
							    "codebook_image_mean": self.codebook_image_mean,
							    "codebook_image_std": self.codebook_image_std,
							}






				def 				_lowerCamelCase						(		self   : Optional[Any]  ):






							'''simple docstring'''







							return (self.size["height"], self.size["width"])






				def 				_lowerCamelCase						(		self   : Optional[Any]  ):






							'''simple docstring'''







							return (
							    (self.input_size_patches, self.input_size_patches)
							    if not isinstance(self.input_size_patches       ,	a  )
							    else self.input_size_patches
							)






				def 				_lowerCamelCase						(		self   : Optional[int]  ):






							'''simple docstring'''







							return (self.codebook_size["height"], self.codebook_size["width"])







@require_torch
@require_vision
class 	A__				(	lowercase__		,  unittest.TestCase      ):
				lowercase            =    FlavaImageProcessor if is_vision_available() else None
				lowercase            =    None






				def 				_lowerCamelCase						(		self   : Union[str, Any]  ):






							'''simple docstring'''







							lowerCAmelCase__ : List[Any]   =						FlavaImageProcessingTester(self  )






				@property
				def 				_lowerCamelCase						(		self   : str  ):






							'''simple docstring'''







							return self.image_processor_tester.prepare_image_processor_dict()






				def 				_lowerCamelCase						(		self   : int  ):






							'''simple docstring'''







							lowerCAmelCase__ : List[str]   =						self.image_processing_class(**self.image_processor_dict  )
							self.assertTrue(hasattr(a       ,	'image_mean'  )  )
							self.assertTrue(hasattr(a       ,	'image_std'  )  )
							self.assertTrue(hasattr(a       ,	'do_normalize'  )  )
							self.assertTrue(hasattr(a       ,	'do_resize'  )  )
							self.assertTrue(hasattr(a       ,	'resample'  )  )
							self.assertTrue(hasattr(a       ,	'crop_size'  )  )
							self.assertTrue(hasattr(a       ,	'do_center_crop'  )  )
							self.assertTrue(hasattr(a       ,	'do_rescale'  )  )
							self.assertTrue(hasattr(a       ,	'rescale_factor'  )  )
							self.assertTrue(hasattr(a       ,	'masking_generator'  )  )
							self.assertTrue(hasattr(a       ,	'codebook_do_resize'  )  )
							self.assertTrue(hasattr(a       ,	'codebook_size'  )  )
							self.assertTrue(hasattr(a       ,	'codebook_resample'  )  )
							self.assertTrue(hasattr(a       ,	'codebook_do_center_crop'  )  )
							self.assertTrue(hasattr(a       ,	'codebook_crop_size'  )  )
							self.assertTrue(hasattr(a       ,	'codebook_do_map_pixels'  )  )
							self.assertTrue(hasattr(a       ,	'codebook_do_normalize'  )  )
							self.assertTrue(hasattr(a       ,	'codebook_image_mean'  )  )
							self.assertTrue(hasattr(a       ,	'codebook_image_std'  )  )






				def 				_lowerCamelCase						(		self   : Union[str, Any]  ):






							'''simple docstring'''







							lowerCAmelCase__ : Dict   =						self.image_processing_class.from_dict(self.image_processor_dict  )
							self.assertEqual(image_processor.size       ,	{'height': 224, 'width': 224}  )
							self.assertEqual(image_processor.crop_size       ,	{'height': 224, 'width': 224}  )
							self.assertEqual(image_processor.codebook_size       ,	{'height': 112, 'width': 112}  )
							self.assertEqual(image_processor.codebook_crop_size       ,	{'height': 112, 'width': 112}  )

							lowerCAmelCase__ : List[Any]   =						self.image_processing_class.from_dict(
							    self.image_processor_dict       ,	size=42       ,	crop_size=84       ,	codebook_size=33       ,	codebook_crop_size=66  )
							self.assertEqual(image_processor.size       ,	{'height': 42, 'width': 42}  )
							self.assertEqual(image_processor.crop_size       ,	{'height': 84, 'width': 84}  )
							self.assertEqual(image_processor.codebook_size       ,	{'height': 33, 'width': 33}  )
							self.assertEqual(image_processor.codebook_crop_size       ,	{'height': 66, 'width': 66}  )






				def 				_lowerCamelCase						(		self   : str  ):






							'''simple docstring'''







							pass






				def 				_lowerCamelCase						(		self   : List[str]  ):






							'''simple docstring'''







							lowerCAmelCase__ : Optional[int]   =						self.image_processing_class(**self.image_processor_dict  )
							# create random PIL images
							lowerCAmelCase__ : List[Any]   =						prepare_image_inputs(self.image_processor_tester       ,	equal_resolution=a  )
							for image in image_inputs:
										self.assertIsInstance(a       ,	PIL.Image.Image  )

							# Test not batched input
							lowerCAmelCase__ : List[str]   =						image_processing(image_inputs[0]       ,	return_tensors='pt'  )

							# Test no bool masked pos
							self.assertFalse('bool_masked_pos' in encoded_images  )

							lowerCAmelCase__ ,							lowerCAmelCase__ : Dict   =						self.image_processor_tester.get_expected_image_size()

							self.assertEqual(
							    encoded_images.pixel_values.shape       ,	(1, self.image_processor_tester.num_channels, expected_height, expected_width)       ,	)

							# Test batched
							lowerCAmelCase__ : int   =						image_processing(a       ,	return_tensors='pt'  )
							lowerCAmelCase__ ,							lowerCAmelCase__ : Dict   =						self.image_processor_tester.get_expected_image_size()

							# Test no bool masked pos
							self.assertFalse('bool_masked_pos' in encoded_images  )

							self.assertEqual(
							    encoded_images.pixel_values.shape       ,	(
							        self.image_processor_tester.batch_size,
							        self.image_processor_tester.num_channels,
							        expected_height,
							        expected_width,
							    )       ,	)






				def 				_lowerCamelCase						(		self   : Dict       ,	a   : Union[str, Any]       ,	a   : Optional[int]  ):






							'''simple docstring'''







							lowerCAmelCase__ : Any   =						self.image_processing_class(**self.image_processor_dict  )
							# create random tensors
							lowerCAmelCase__ : Union[str, Any]   =						prepare_image_inputs(self.image_processor_tester       ,	equal_resolution=a       ,	**a  )
							for image in image_inputs:
										self.assertIsInstance(a       ,	a  )

							# Test not batched input
							lowerCAmelCase__ : Union[str, Any]   =						image_processing(image_inputs[0]       ,	return_tensors='pt'  )

							lowerCAmelCase__ ,							lowerCAmelCase__ : Optional[int]   =						self.image_processor_tester.get_expected_image_size()
							self.assertEqual(
							    encoded_images.pixel_values.shape       ,	(1, self.image_processor_tester.num_channels, expected_height, expected_width)       ,	)

							lowerCAmelCase__ : Union[str, Any]   =						image_processing(a       ,	return_image_mask=a       ,	return_tensors='pt'  )

							lowerCAmelCase__ ,							lowerCAmelCase__ : Optional[int]   =						self.image_processor_tester.get_expected_image_size()
							self.assertEqual(
							    encoded_images.pixel_values.shape       ,	(
							        self.image_processor_tester.batch_size,
							        self.image_processor_tester.num_channels,
							        expected_height,
							        expected_width,
							    )       ,	)

							lowerCAmelCase__ ,							lowerCAmelCase__ : str   =						self.image_processor_tester.get_expected_mask_size()
							self.assertEqual(
							    encoded_images.bool_masked_pos.shape       ,	(
							        self.image_processor_tester.batch_size,
							        expected_height,
							        expected_width,
							    )       ,	)

							# Test batched
							lowerCAmelCase__ : Any   =						image_processing(a       ,	return_tensors='pt'  ).pixel_values

							lowerCAmelCase__ ,							lowerCAmelCase__ : List[Any]   =						self.image_processor_tester.get_expected_image_size()
							self.assertEqual(
							    encoded_images.shape       ,	(
							        self.image_processor_tester.batch_size,
							        self.image_processor_tester.num_channels,
							        expected_height,
							        expected_width,
							    )       ,	)

							# Test masking
							lowerCAmelCase__ : int   =						image_processing(a       ,	return_image_mask=a       ,	return_tensors='pt'  )

							lowerCAmelCase__ ,							lowerCAmelCase__ : Any   =						self.image_processor_tester.get_expected_image_size()
							self.assertEqual(
							    encoded_images.pixel_values.shape       ,	(
							        self.image_processor_tester.batch_size,
							        self.image_processor_tester.num_channels,
							        expected_height,
							        expected_width,
							    )       ,	)

							lowerCAmelCase__ ,							lowerCAmelCase__ : Union[str, Any]   =						self.image_processor_tester.get_expected_mask_size()
							self.assertEqual(
							    encoded_images.bool_masked_pos.shape       ,	(
							        self.image_processor_tester.batch_size,
							        expected_height,
							        expected_width,
							    )       ,	)






				def 				_lowerCamelCase						(		self   : Any  ):






							'''simple docstring'''







							self._test_call_framework(np.ndarray       ,	prepare_kwargs={'numpify': True}  )






				def 				_lowerCamelCase						(		self   : Optional[Any]  ):






							'''simple docstring'''







							self._test_call_framework(torch.Tensor       ,	prepare_kwargs={'torchify': True}  )






				def 				_lowerCamelCase						(		self   : Any  ):






							'''simple docstring'''







							random.seed(1_234  )
							lowerCAmelCase__ : Union[str, Any]   =						self.image_processing_class(**self.image_processor_dict  )
							lowerCAmelCase__ : Any   =						prepare_image_inputs(self.image_processor_tester       ,	equal_resolution=a       ,	torchify=a  )

							# Test not batched input
							lowerCAmelCase__ : int   =						image_processing(image_inputs[0]       ,	return_image_mask=a       ,	return_tensors='pt'  )
							self.assertEqual(encoded_images.bool_masked_pos.sum().item()       ,	75  )






				def 				_lowerCamelCase						(		self   : Any  ):






							'''simple docstring'''







							lowerCAmelCase__ : Tuple   =						self.image_processing_class(**self.image_processor_dict  )
							# create random PIL images
							lowerCAmelCase__ : str   =						prepare_image_inputs(self.image_processor_tester       ,	equal_resolution=a  )
							for image in image_inputs:
										self.assertIsInstance(a       ,	PIL.Image.Image  )

							# Test not batched input
							lowerCAmelCase__ : str   =						image_processing(image_inputs[0]       ,	return_codebook_pixels=a       ,	return_tensors='pt'  )
							lowerCAmelCase__ ,							lowerCAmelCase__ : Optional[Any]   =						self.image_processor_tester.get_expected_codebook_image_size()
							self.assertEqual(
							    encoded_images.codebook_pixel_values.shape       ,	(1, self.image_processor_tester.num_channels, expected_height, expected_width)       ,	)

							# Test batched
							lowerCAmelCase__ : int   =						image_processing(a       ,	return_codebook_pixels=a       ,	return_tensors='pt'  )
							lowerCAmelCase__ ,							lowerCAmelCase__ : int   =						self.image_processor_tester.get_expected_codebook_image_size()
							self.assertEqual(
							    encoded_images.codebook_pixel_values.shape       ,	(
							        self.image_processor_tester.batch_size,
							        self.image_processor_tester.num_channels,
							        expected_height,
							        expected_width,
							    )       ,	)





# 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 typing import TYPE_CHECKING

from ..utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_torch_available,
)


SCREAMING_SNAKE_CASE_    :       int       =							{
    '''agents''': ['''Agent''', '''AzureOpenAiAgent''', '''HfAgent''', '''LocalAgent''', '''OpenAiAgent'''],
    '''base''': ['''PipelineTool''', '''RemoteTool''', '''Tool''', '''launch_gradio_demo''', '''load_tool'''],
}

try:
 if not is_torch_available():
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 pass
else:
 SCREAMING_SNAKE_CASE_    :       int       =							['''DocumentQuestionAnsweringTool''']
 SCREAMING_SNAKE_CASE_    :       List[Any]       =							['''ImageCaptioningTool''']
 SCREAMING_SNAKE_CASE_    :       Union[str, Any]       =							['''ImageQuestionAnsweringTool''']
 SCREAMING_SNAKE_CASE_    :       str       =							['''ImageSegmentationTool''']
 SCREAMING_SNAKE_CASE_    :       Any       =							['''SpeechToTextTool''']
 SCREAMING_SNAKE_CASE_    :       Union[str, Any]       =							['''TextClassificationTool''']
 SCREAMING_SNAKE_CASE_    :       List[Any]       =							['''TextQuestionAnsweringTool''']
 SCREAMING_SNAKE_CASE_    :       Dict       =							['''TextSummarizationTool''']
 SCREAMING_SNAKE_CASE_    :       Optional[int]       =							['''TextToSpeechTool''']
 SCREAMING_SNAKE_CASE_    :       Dict       =							['''TranslationTool''']

if TYPE_CHECKING:
 from .agents import Agent, AzureOpenAiAgent, HfAgent, LocalAgent, OpenAiAgent
 from .base import PipelineTool, RemoteTool, Tool, launch_gradio_demo, load_tool

 try:
  if not is_torch_available():
   raise OptionalDependencyNotAvailable()
 except OptionalDependencyNotAvailable:
  pass
 else:
  from .document_question_answering import DocumentQuestionAnsweringTool
  from .image_captioning import ImageCaptioningTool
  from .image_question_answering import ImageQuestionAnsweringTool
  from .image_segmentation import ImageSegmentationTool
  from .speech_to_text import SpeechToTextTool
  from .text_classification import TextClassificationTool
  from .text_question_answering import TextQuestionAnsweringTool
  from .text_summarization import TextSummarizationTool
  from .text_to_speech import TextToSpeechTool
  from .translation import TranslationTool
else:
 import sys

 SCREAMING_SNAKE_CASE_    :       Optional[Any]       =							_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)






