
"""simple docstring"""


import json
import os
import shutil
import tempfile
import unittest

import numpy as np
import pytest

from transformers import CLIPTokenizer, CLIPTokenizerFast
from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES
from transformers.testing_utils import require_vision
from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available


if is_vision_available():
		from PIL import Image

		from transformers import OwlViTImageProcessor, OwlViTProcessor







@require_vision
class  lowerCAmelCase_ (					unittest.TestCase			):



						'''simple docstring'''


						def   _SCREAMING_SNAKE_CASE					(       self   :					List[str]					)   ->      Optional[Any]:
							A        =      tempfile.mkdtemp()

							# fmt: off
							A        =      ["", "l", "o", "w", "e", "r", "s", "t", "i", "d", "n", "lo", "l</w>", "w</w>", "r</w>", "t</w>", "low</w>", "er</w>", "lowest</w>", "newer</w>", "wider", "<unk>", "<|startoftext|>", "<|endoftext|>"]
							# fmt: on
							A        =      dict(zip(__A     ,range(len(__A					)					)					)					)
							A        =      ["#version: 0.2", "l o", "lo w</w>", "e r</w>", ""]
							A        =      {"unk_token": "<unk>"}

							A        =      os.path.join(self.tmpdirname     ,VOCAB_FILES_NAMES['vocab_file']					)
							A        =      os.path.join(self.tmpdirname     ,VOCAB_FILES_NAMES['merges_file']					)
							with open(self.vocab_file     ,'w'     ,encoding='utf-8'					) as fp:
								fp.write(json.dumps(__A					) + '\n'					)
							with open(self.merges_file     ,'w'     ,encoding='utf-8'					) as fp:
								fp.write('\n'.join(__A					)					)

							A        =      {
							    "do_resize": True,
							    "size": 20,
							    "do_center_crop": True,
							    "crop_size": 18,
							    "do_normalize": True,
							    "image_mean": [0.48_14_54_66, 0.4_57_82_75, 0.40_82_10_73],
							    "image_std": [0.26_86_29_54, 0.26_13_02_58, 0.27_57_77_11],
							}
							A        =      os.path.join(self.tmpdirname     ,__A					)
							with open(self.image_processor_file     ,'w'     ,encoding='utf-8'					) as fp:
								json.dump(__A     ,__A					)


						def   _SCREAMING_SNAKE_CASE					(       self   :					Optional[Any]     ,**A_   :					List[Any]					)   ->      List[str]:
							return CLIPTokenizer.from_pretrained(self.tmpdirname     ,pad_token='!'     ,**__A					)


						def   _SCREAMING_SNAKE_CASE					(       self   :					Dict     ,**A_   :					List[str]					)   ->      List[str]:
							return CLIPTokenizerFast.from_pretrained(self.tmpdirname     ,pad_token='!'     ,**__A					)


						def   _SCREAMING_SNAKE_CASE					(       self   :					Any     ,**A_   :					str					)   ->      List[str]:
							return OwlViTImageProcessor.from_pretrained(self.tmpdirname     ,**__A					)


						def   _SCREAMING_SNAKE_CASE					(       self   :					List[str]					)   ->      List[str]:
							shutil.rmtree(self.tmpdirname					)


						def   _SCREAMING_SNAKE_CASE					(       self   :					Any					)   ->      List[Any]:
							A        =      [np.random.randint(255     ,size=(3, 30, 400)     ,dtype=np.uinta					)]

							A        =      [Image.fromarray(np.moveaxis(__A     ,0     ,-1					)					) for x in image_inputs]

							return image_inputs


						def   _SCREAMING_SNAKE_CASE					(       self   :					Optional[Any]					)   ->      Tuple:
							A        =      self.get_tokenizer()
							A        =      self.get_rust_tokenizer()
							A        =      self.get_image_processor()

							A        =      OwlViTProcessor(tokenizer=__A     ,image_processor=__A					)
							processor_slow.save_pretrained(self.tmpdirname					)
							A        =      OwlViTProcessor.from_pretrained(self.tmpdirname     ,use_fast=__A					)

							A        =      OwlViTProcessor(tokenizer=__A     ,image_processor=__A					)
							processor_fast.save_pretrained(self.tmpdirname					)
							A        =      OwlViTProcessor.from_pretrained(self.tmpdirname					)

							self.assertEqual(processor_slow.tokenizer.get_vocab()     ,tokenizer_slow.get_vocab()					)
							self.assertEqual(processor_fast.tokenizer.get_vocab()     ,tokenizer_fast.get_vocab()					)
							self.assertEqual(tokenizer_slow.get_vocab()     ,tokenizer_fast.get_vocab()					)
							self.assertIsInstance(processor_slow.tokenizer     ,__A					)
							self.assertIsInstance(processor_fast.tokenizer     ,__A					)

							self.assertEqual(processor_slow.image_processor.to_json_string()     ,image_processor.to_json_string()					)
							self.assertEqual(processor_fast.image_processor.to_json_string()     ,image_processor.to_json_string()					)
							self.assertIsInstance(processor_slow.image_processor     ,__A					)
							self.assertIsInstance(processor_fast.image_processor     ,__A					)


						def   _SCREAMING_SNAKE_CASE					(       self   :					Union[str, Any]					)   ->      List[str]:
							A        =      OwlViTProcessor(tokenizer=self.get_tokenizer()     ,image_processor=self.get_image_processor()					)
							processor.save_pretrained(self.tmpdirname					)

							A        =      self.get_tokenizer(bos_token='(BOS)'     ,eos_token='(EOS)'					)
							A        =      self.get_image_processor(do_normalize=__A					)

							A        =      OwlViTProcessor.from_pretrained(
							    self.tmpdirname     ,bos_token='(BOS)'     ,eos_token='(EOS)'     ,do_normalize=__A					)

							self.assertEqual(processor.tokenizer.get_vocab()     ,tokenizer_add_kwargs.get_vocab()					)
							self.assertIsInstance(processor.tokenizer     ,__A					)

							self.assertEqual(processor.image_processor.to_json_string()     ,image_processor_add_kwargs.to_json_string()					)
							self.assertIsInstance(processor.image_processor     ,__A					)


						def   _SCREAMING_SNAKE_CASE					(       self   :					Optional[Any]					)   ->      int:
							A        =      self.get_image_processor()
							A        =      self.get_tokenizer()

							A        =      OwlViTProcessor(tokenizer=__A     ,image_processor=__A					)

							A        =      self.prepare_image_inputs()

							A        =      image_processor(__A     ,return_tensors='np'					)
							A        =      processor(images=__A     ,return_tensors='np'					)

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


						def   _SCREAMING_SNAKE_CASE					(       self   :					Optional[int]					)   ->      Optional[Any]:
							A        =      self.get_image_processor()
							A        =      self.get_tokenizer()

							A        =      OwlViTProcessor(tokenizer=__A     ,image_processor=__A					)

							A        =      "lower newer"

							A        =      processor(text=__A     ,return_tensors='np'					)

							A        =      tokenizer(__A     ,return_tensors='np'					)

							for key in encoded_tok.keys():
								self.assertListEqual(encoded_tok[key][0].tolist()     ,encoded_processor[key][0].tolist()					)


						def   _SCREAMING_SNAKE_CASE					(       self   :					List[Any]					)   ->      str:
							A        =      self.get_image_processor()
							A        =      self.get_tokenizer()

							A        =      OwlViTProcessor(tokenizer=__A     ,image_processor=__A					)

							A        =      "lower newer"
							A        =      self.prepare_image_inputs()

							A        =      processor(text=__A     ,images=__A					)

							self.assertListEqual(list(inputs.keys()					)     ,['input_ids', 'attention_mask', 'pixel_values']					)

							# test if it raises when no input is passed
							with pytest.raises(__A					):
								processor()


						def   _SCREAMING_SNAKE_CASE					(       self   :					Dict					)   ->      Union[str, Any]:
							A        =      "google/owlvit-base-patch32"
							A        =      OwlViTProcessor.from_pretrained(__A					)

							A        =      ["cat", "nasa badge"]
							A        =      processor(text=__A					)

							A        =      16
							self.assertListEqual(list(inputs.keys()					)     ,['input_ids', 'attention_mask']					)
							self.assertEqual(inputs['input_ids'].shape     ,(2, seq_length)					)

							# test if it raises when no input is passed
							with pytest.raises(__A					):
								processor()


						def   _SCREAMING_SNAKE_CASE					(       self   :					Optional[int]					)   ->      List[Any]:
							A        =      "google/owlvit-base-patch32"
							A        =      OwlViTProcessor.from_pretrained(__A					)

							A        =      [["cat", "nasa badge"], ["person"]]
							A        =      processor(text=__A					)

							A        =      16
							A        =      len(__A					)
							A        =      max([len(__A					) for texts in input_texts]					)

							self.assertListEqual(list(inputs.keys()					)     ,['input_ids', 'attention_mask']					)
							self.assertEqual(inputs['input_ids'].shape     ,(batch_size * num_max_text_queries, seq_length)					)

							# test if it raises when no input is passed
							with pytest.raises(__A					):
								processor()


						def   _SCREAMING_SNAKE_CASE					(       self   :					Dict					)   ->      Union[str, Any]:
							A        =      "google/owlvit-base-patch32"
							A        =      OwlViTProcessor.from_pretrained(__A					)

							A        =      ["cat", "nasa badge"]
							A        =      processor(text=__A					)

							A        =      16
							A        =      inputs["input_ids"]
							A        =      [
							    [4_9406, 2368, 4_9407, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
							    [4_9406, 6841, 1_1301, 4_9407, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
							]

							self.assertListEqual(list(inputs.keys()					)     ,['input_ids', 'attention_mask']					)
							self.assertEqual(inputs['input_ids'].shape     ,(2, seq_length)					)
							self.assertListEqual(list(input_ids[0]					)     ,predicted_ids[0]					)
							self.assertListEqual(list(input_ids[1]					)     ,predicted_ids[1]					)


						def   _SCREAMING_SNAKE_CASE					(       self   :					Dict					)   ->      Any:
							A        =      self.get_image_processor()
							A        =      self.get_tokenizer()

							A        =      OwlViTProcessor(tokenizer=__A     ,image_processor=__A					)

							A        =      self.prepare_image_inputs()
							A        =      self.prepare_image_inputs()

							A        =      processor(images=__A     ,query_images=__A					)

							self.assertListEqual(list(inputs.keys()					)     ,['query_pixel_values', 'pixel_values']					)

							# test if it raises when no input is passed
							with pytest.raises(__A					):
								processor()




						def   _SCREAMING_SNAKE_CASE					(       self   :					int					)   ->      Any:
							A        =      self.get_image_processor()
							A        =      self.get_tokenizer()

							A        =      OwlViTProcessor(tokenizer=__A     ,image_processor=__A					)

							A        =      [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]

							A        =      processor.batch_decode(__A					)
							A        =      tokenizer.batch_decode(__A					)

							self.assertListEqual(__A     ,__A					)



# 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.whisper import WhisperForConditionalGeneration, WhisperProcessor
from .base import PipelineTool
class 	UpperCAmelCase_					(					UpperCamelCase    ):

   '''simple docstring'''




   __A :      Dict     		=		"openai/whisper-base"
   __A :      str     		=		(
       "This is a tool that transcribes an audio into text. It takes an input named `audio` and returns the "
       "transcribed text."
   )
   __A :      Any     		=		"transcriber"
   __A :      Any     		=		WhisperProcessor
   __A :      int     		=		WhisperForConditionalGeneration

   __A :      Any     		=		["audio"]
   __A :      List[str]     		=		["text"]






   def _snake_case    (		self						,				__A ):






     """simple docstring"""





     return self.pre_processor(__A						,				return_tensors="pt" ).input_features






   def _snake_case    (		self						,				__A ):






     """simple docstring"""





     return self.model.generate(inputs=__A )






   def _snake_case    (		self						,				__A ):






     """simple docstring"""





     return self.pre_processor.batch_decode(__A						,				skip_special_tokens=__A )[0]



