


'''simple docstring'''
import json
import pathlib
import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision, slow
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():
 from PIL import Image

 from transformers import DetaImageProcessor

class 						_lowerCamelCase					(    unittest.TestCase				):




 '''simple docstring'''


 def __init__(      self      ,      __lowercase      ,      __lowercase=7      ,      __lowercase=3      ,      __lowercase=30      ,      __lowercase=400      ,      __lowercase=True      ,      __lowercase=None      ,      __lowercase=True      ,      __lowercase=[0.5, 0.5, 0.5]      ,      __lowercase=[0.5, 0.5, 0.5]      ,      __lowercase=True      ,      __lowercase=1 / 255      ,      __lowercase=True      ,      ):

  """simple docstring"""







  __A  :		str       =			size if size is not None else {'shortest_edge': 18, 'longest_edge': 1_333}
  __A  :		List[Any]       =			parent
  __A  :		Any       =			batch_size
  __A  :		Dict       =			num_channels
  __A  :		Optional[int]       =			min_resolution
  __A  :		Any       =			max_resolution
  __A  :		str       =			do_resize
  __A  :		Any       =			size
  __A  :		List[str]       =			do_normalize
  __A  :		Dict       =			image_mean
  __A  :		Optional[int]       =			image_std
  __A  :		Tuple       =			do_rescale
  __A  :		str       =			rescale_factor
  __A  :		int       =			do_pad


 def  snake_case__   (      self						):

  """simple docstring"""







  return {
      "do_resize": self.do_resize,
      "size": self.size,
      "do_normalize": self.do_normalize,
      "image_mean": self.image_mean,
      "image_std": self.image_std,
      "do_rescale": self.do_rescale,
      "rescale_factor": self.rescale_factor,
      "do_pad": self.do_pad,
  }







 def  snake_case__   (      self      ,      __lowercase      ,      __lowercase=False						):

  """simple docstring"""







  if not batched:
   __A  :		Tuple       =			image_inputs[0]
   if isinstance(__lowercase      ,      Image.Image						):
    __A     ,__A  :		str       =			image.size
   else:
    __A     ,__A  :		Tuple       =			image.shape[1], image.shape[2]
   if w < h:
    __A  :		int       =			int(self.size['shortest_edge'] * h / w						)
    __A  :		Dict       =			self.size['shortest_edge']
   elif w > h:
    __A  :		List[str]       =			self.size['shortest_edge']
    __A  :		int       =			int(self.size['shortest_edge'] * w / h						)
   else:
    __A  :		Tuple       =			self.size['shortest_edge']
    __A  :		List[str]       =			self.size['shortest_edge']

  else:
   __A  :		List[str]       =			[]
   for image in image_inputs:
    __A     ,__A  :		List[str]       =			self.get_expected_values([image]						)
    expected_values.append((expected_height, expected_width)						)
   __A  :		Optional[int]       =			max(__lowercase      ,      key=lambda __lowercase						: item[0]						)[0]
   __A  :		Union[str, Any]       =			max(__lowercase      ,      key=lambda __lowercase						: item[1]						)[1]

  return expected_height, expected_width


@require_torch
@require_vision
class 						_lowerCamelCase					(    snake_case_    ,		unittest.TestCase				):




 '''simple docstring'''
 __lowercase				:		Union[str, Any]    							=						DetaImageProcessor if is_vision_available() else None


 def  snake_case__   (      self						):

  """simple docstring"""







  __A  :		Optional[int]       =			DetaImageProcessingTester(self						)


 @property
 def  snake_case__   (      self						):

  """simple docstring"""







  return self.image_processor_tester.prepare_image_processor_dict()


 def  snake_case__   (      self						):

  """simple docstring"""







  __A  :		Any       =			self.image_processing_class(**self.image_processor_dict						)
  self.assertTrue(hasattr(__lowercase      ,      'image_mean'						)						)
  self.assertTrue(hasattr(__lowercase      ,      'image_std'						)						)
  self.assertTrue(hasattr(__lowercase      ,      'do_normalize'						)						)
  self.assertTrue(hasattr(__lowercase      ,      'do_resize'						)						)
  self.assertTrue(hasattr(__lowercase      ,      'do_rescale'						)						)
  self.assertTrue(hasattr(__lowercase      ,      'do_pad'						)						)
  self.assertTrue(hasattr(__lowercase      ,      'size'						)						)


 def  snake_case__   (      self						):

  """simple docstring"""







  __A  :		str       =			self.image_processing_class.from_dict(self.image_processor_dict						)
  self.assertEqual(image_processor.size      ,      {'shortest_edge': 18, 'longest_edge': 1_333}						)
  self.assertEqual(image_processor.do_pad      ,      __lowercase						)


 def  snake_case__   (      self						):

  """simple docstring"""







  pass


 def  snake_case__   (      self						):

  """simple docstring"""







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

  # Test not batched input
  __A  :		Optional[Any]       =			image_processing(image_inputs[0]      ,      return_tensors='pt'						).pixel_values

  __A     ,__A  :		Any       =			self.image_processor_tester.get_expected_values(__lowercase						)

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

  # Test batched
  __A     ,__A  :		Union[str, Any]       =			self.image_processor_tester.get_expected_values(__lowercase      ,      batched=__lowercase						)

  __A  :		Optional[int]       =			image_processing(__lowercase      ,      return_tensors='pt'						).pixel_values
  self.assertEqual(
      encoded_images.shape      ,      (
          self.image_processor_tester.batch_size,
          self.image_processor_tester.num_channels,
          expected_height,
          expected_width,
      )      ,      )


 def  snake_case__   (      self						):

  """simple docstring"""







  __A  :		Any       =			self.image_processing_class(**self.image_processor_dict						)
  # create random numpy tensors
  __A  :		int       =			prepare_image_inputs(self.image_processor_tester      ,      equal_resolution=__lowercase      ,      numpify=__lowercase						)
  for image in image_inputs:
   self.assertIsInstance(__lowercase      ,      np.ndarray						)

  # Test not batched input
  __A  :		int       =			image_processing(image_inputs[0]      ,      return_tensors='pt'						).pixel_values

  __A     ,__A  :		Tuple       =			self.image_processor_tester.get_expected_values(__lowercase						)

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

  # Test batched
  __A  :		Any       =			image_processing(__lowercase      ,      return_tensors='pt'						).pixel_values

  __A     ,__A  :		Optional[int]       =			self.image_processor_tester.get_expected_values(__lowercase      ,      batched=__lowercase						)

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


 def  snake_case__   (      self						):

  """simple docstring"""







  __A  :		List[Any]       =			self.image_processing_class(**self.image_processor_dict						)
  # create random PyTorch tensors
  __A  :		Any       =			prepare_image_inputs(self.image_processor_tester      ,      equal_resolution=__lowercase      ,      torchify=__lowercase						)
  for image in image_inputs:
   self.assertIsInstance(__lowercase      ,      torch.Tensor						)

  # Test not batched input
  __A  :		Dict       =			image_processing(image_inputs[0]      ,      return_tensors='pt'						).pixel_values

  __A     ,__A  :		List[str]       =			self.image_processor_tester.get_expected_values(__lowercase						)

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

  # Test batched
  __A  :		List[str]       =			image_processing(__lowercase      ,      return_tensors='pt'						).pixel_values

  __A     ,__A  :		Any       =			self.image_processor_tester.get_expected_values(__lowercase      ,      batched=__lowercase						)

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


 @slow
 def  snake_case__   (      self						):

  """simple docstring"""







  __A  :		List[Any]       =			Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'						)
  with open('./tests/fixtures/tests_samples/COCO/coco_annotations.txt'      ,      'r'						) as f:
   __A  :		List[Any]       =			json.loads(f.read()						)

  __A  :		int       =			{'image_id': 39_769, 'annotations': target}

  # encode them
  __A  :		Optional[int]       =			DetaImageProcessor()
  __A  :		Union[str, Any]       =			image_processing(images=__lowercase      ,      annotations=__lowercase      ,      return_tensors='pt'						)

  # verify pixel values
  __A  :		Union[str, Any]       =			torch.Size([1, 3, 800, 1_066]						)
  self.assertEqual(encoding['pixel_values'].shape      ,      __lowercase						)

  __A  :		Tuple       =			torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1]						)
  self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3]      ,      __lowercase      ,      atol=1E-4						)						)

  # verify area
  __A  :		int       =			torch.tensor([5_8_8_7.9_6_0_0, 1_1_2_5_0.2_0_6_1, 4_8_9_3_5_3.8_4_3_8, 8_3_7_1_2_2.7_5_0_0, 1_4_7_9_6_7.5_1_5_6, 1_6_5_7_3_2.3_4_3_8]						)
  self.assertTrue(torch.allclose(encoding['labels'][0]['area']      ,      __lowercase						)						)
  # verify boxes
  __A  :		Union[str, Any]       =			torch.Size([6, 4]						)
  self.assertEqual(encoding['labels'][0]['boxes'].shape      ,      __lowercase						)
  __A  :		Tuple       =			torch.tensor([0.5_5_0_3, 0.2_7_6_5, 0.0_6_0_4, 0.2_2_1_5]						)
  self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0]      ,      __lowercase      ,      atol=1E-3						)						)
  # verify image_id
  __A  :		Union[str, Any]       =			torch.tensor([39_769]						)
  self.assertTrue(torch.allclose(encoding['labels'][0]['image_id']      ,      __lowercase						)						)
  # verify is_crowd
  __A  :		List[Any]       =			torch.tensor([0, 0, 0, 0, 0, 0]						)
  self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd']      ,      __lowercase						)						)
  # verify class_labels
  __A  :		List[str]       =			torch.tensor([75, 75, 63, 65, 17, 17]						)
  self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels']      ,      __lowercase						)						)
  # verify orig_size
  __A  :		Optional[Any]       =			torch.tensor([480, 640]						)
  self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size']      ,      __lowercase						)						)
  # verify size
  __A  :		List[str]       =			torch.tensor([800, 1_066]						)
  self.assertTrue(torch.allclose(encoding['labels'][0]['size']      ,      __lowercase						)						)







 @slow
 def  snake_case__   (      self						):

  """simple docstring"""







  __A  :		Tuple       =			Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'						)
  with open('./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt'      ,      'r'						) as f:
   __A  :		List[Any]       =			json.loads(f.read()						)

  __A  :		Dict       =			{'file_name': '000000039769.png', 'image_id': 39_769, 'segments_info': target}

  __A  :		str       =			pathlib.Path('./tests/fixtures/tests_samples/COCO/coco_panoptic'						)

  # encode them
  __A  :		int       =			DetaImageProcessor(format='coco_panoptic'						)
  __A  :		List[Any]       =			image_processing(images=__lowercase      ,      annotations=__lowercase      ,      masks_path=__lowercase      ,      return_tensors='pt'						)

  # verify pixel values
  __A  :		Tuple       =			torch.Size([1, 3, 800, 1_066]						)
  self.assertEqual(encoding['pixel_values'].shape      ,      __lowercase						)

  __A  :		str       =			torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1]						)
  self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3]      ,      __lowercase      ,      atol=1E-4						)						)

  # verify area
  __A  :		List[str]       =			torch.tensor([1_4_7_9_7_9.6_8_7_5, 1_6_5_5_2_7.0_4_6_9, 4_8_4_6_3_8.5_9_3_8, 1_1_2_9_2.9_3_7_5, 5_8_7_9.6_5_6_2, 7_6_3_4.1_1_4_7]						)
  self.assertTrue(torch.allclose(encoding['labels'][0]['area']      ,      __lowercase						)						)
  # verify boxes
  __A  :		List[Any]       =			torch.Size([6, 4]						)
  self.assertEqual(encoding['labels'][0]['boxes'].shape      ,      __lowercase						)
  __A  :		Union[str, Any]       =			torch.tensor([0.2_6_2_5, 0.5_4_3_7, 0.4_6_8_8, 0.8_6_2_5]						)
  self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0]      ,      __lowercase      ,      atol=1E-3						)						)
  # verify image_id
  __A  :		List[str]       =			torch.tensor([39_769]						)
  self.assertTrue(torch.allclose(encoding['labels'][0]['image_id']      ,      __lowercase						)						)
  # verify is_crowd
  __A  :		Union[str, Any]       =			torch.tensor([0, 0, 0, 0, 0, 0]						)
  self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd']      ,      __lowercase						)						)
  # verify class_labels
  __A  :		Optional[Any]       =			torch.tensor([17, 17, 63, 75, 75, 93]						)
  self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels']      ,      __lowercase						)						)
  # verify masks
  __A  :		Dict       =			822_873
  self.assertEqual(encoding['labels'][0]['masks'].sum().item()      ,      __lowercase						)
  # verify orig_size
  __A  :		Union[str, Any]       =			torch.tensor([480, 640]						)
  self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size']      ,      __lowercase						)						)
  # verify size
  __A  :		Any       =			torch.tensor([800, 1_066]						)
  self.assertTrue(torch.allclose(encoding['labels'][0]['size']      ,      __lowercase						)						)










'''simple docstring'''
import unittest

from datasets import load_dataset

from transformers.pipelines import pipeline
from transformers.testing_utils import is_pipeline_test, nested_simplify, require_torch, slow

@is_pipeline_test
@require_torch
class 						_lowerCamelCase					(    unittest.TestCase				):




 '''simple docstring'''


 @require_torch
 def  snake_case__   (      self						):

  """simple docstring"""







  __A  :		Optional[int]       =			pipeline(
      task='zero-shot-audio-classification'      ,      model='hf-internal-testing/tiny-clap-htsat-unfused'						)
  __A  :		str       =			load_dataset('ashraq/esc50'						)
  __A  :		Union[str, Any]       =			dataset['train']['audio'][-1]['array']
  __A  :		List[str]       =			audio_classifier(__lowercase      ,      candidate_labels=['Sound of a dog', 'Sound of vaccum cleaner']						)
  self.assertEqual(
      nested_simplify(__lowercase						)      ,      [{'score': 0.5_0_1, 'label': 'Sound of a dog'}, {'score': 0.4_9_9, 'label': 'Sound of vaccum cleaner'}]      ,      )


 @unittest.skip('No models are available in TF'						)
 def  snake_case__   (      self						):

  """simple docstring"""







  pass


 @slow
 @require_torch
 def  snake_case__   (      self						):

  """simple docstring"""







  __A  :		Dict       =			pipeline(
      task='zero-shot-audio-classification'      ,      model='laion/clap-htsat-unfused'      ,      )
  # This is an audio of a dog
  __A  :		Optional[Any]       =			load_dataset('ashraq/esc50'						)
  __A  :		List[str]       =			dataset['train']['audio'][-1]['array']
  __A  :		Union[str, Any]       =			audio_classifier(__lowercase      ,      candidate_labels=['Sound of a dog', 'Sound of vaccum cleaner']						)

  self.assertEqual(
      nested_simplify(__lowercase						)      ,      [
          {'score': 0.9_9_9, 'label': 'Sound of a dog'},
          {'score': 0.0_0_1, 'label': 'Sound of vaccum cleaner'},
      ]      ,      )

  __A  :		Any       =			audio_classifier([audio] * 5      ,      candidate_labels=['Sound of a dog', 'Sound of vaccum cleaner']						)
  self.assertEqual(
      nested_simplify(__lowercase						)      ,      [
          [
              {'score': 0.9_9_9, 'label': 'Sound of a dog'},
              {'score': 0.0_0_1, 'label': 'Sound of vaccum cleaner'},
          ],
      ]
      * 5      ,      )
  __A  :		str       =			audio_classifier(
      [audio] * 5      ,      candidate_labels=['Sound of a dog', 'Sound of vaccum cleaner']      ,      batch_size=5						)
  self.assertEqual(
      nested_simplify(__lowercase						)      ,      [
          [
              {'score': 0.9_9_9, 'label': 'Sound of a dog'},
              {'score': 0.0_0_1, 'label': 'Sound of vaccum cleaner'},
          ],
      ]
      * 5      ,      )







 @unittest.skip('No models are available in TF'						)
 def  snake_case__   (      self						):

  """simple docstring"""







  pass






