



import os
from dataclasses import dataclass, field
from io import BytesIO
from typing import TYPE_CHECKING, Any, ClassVar, Dict, Optional, Union

import numpy as np
import pyarrow as pa

from .. import config
from ..download.streaming_download_manager import xopen, xsplitext
from ..table import array_cast
from ..utils.py_utils import no_op_if_value_is_null, string_to_dict


if TYPE_CHECKING:
	from .features import FeatureType


UpperCAmelCase ,       UpperCAmelCase ,       UpperCAmelCase							 =					False, False, False

@dataclass
class  __snake_case      :







							'''simple docstring'''






							UpperCamelCase__				:      Optional[int]         =					None
							UpperCamelCase__				:      bool         =					True
							UpperCamelCase__				:      bool         =					True
							UpperCamelCase__				:      Optional[str]         =					None
							# Automatically constructed
							UpperCamelCase__				:      ClassVar[str]         =					"dict"
							UpperCamelCase__				:      ClassVar[Any]         =					pa.struct({"""bytes""": pa.binary(), """path""": pa.string()})
							UpperCamelCase__				:      str         =					field(default="""Audio"""			,init=SCREAMING_SNAKE_CASE			,repr=SCREAMING_SNAKE_CASE)


							def __call__(							self		):
											return self.pa_type


							def _a      (							self  ,  a_		):
											try:
															import soundfile as sf  # soundfile is a dependency of librosa, needed to decode audio files.
											except ImportError as err:
															raise ImportError("""To support encoding audio data, please install 'soundfile'."""		) from err
											if isinstance(a_  ,  a_		):
															return {"bytes": None, "path": value}
											elif isinstance(a_  ,  a_		):
															return {"bytes": value, "path": None}
											elif "array" in value:
															# convert the audio array to wav bytes
															a__				      =		BytesIO()
															sf.write(a_  ,  value["""array"""]  ,  value["""sampling_rate"""]  ,  format="""wav"""		)
															return {"bytes": buffer.getvalue(), "path": None}
											elif value.get("""path"""		) is not None and os.path.isfile(value["""path"""]		):
															# we set "bytes": None to not duplicate the data if they're already available locally
															if value["path"].endswith("""pcm"""		):
																			# "PCM" only has raw audio bytes
																			if value.get("""sampling_rate"""		) is None:
																							# At least, If you want to convert "PCM-byte" to "WAV-byte", you have to know sampling rate
																							raise KeyError("""To use PCM files, please specify a 'sampling_rate' in Audio object"""		)
																			if value.get("""bytes"""		):
																							# If we already had PCM-byte, we don`t have to make "read file, make bytes" (just use it!)
																							a__				      =		np.frombuffer(value["""bytes"""]  ,  dtype=np.intaa		).astype(np.floataa		) / 32_767
																			else:
																							a__				      =		np.memmap(value["""path"""]  ,  dtype="""h"""  ,  mode="""r"""		).astype(np.floataa		) / 32_767

																			a__				      =		BytesIO(bytes()		)
																			sf.write(a_  ,  a_  ,  value["""sampling_rate"""]  ,  format="""wav"""		)
																			return {"bytes": buffer.getvalue(), "path": None}
															else:
																			return {"bytes": None, "path": value.get("""path"""		)}
											elif value.get("""bytes"""		) is not None or value.get("""path"""		) is not None:
															# store the audio bytes, and path is used to infer the audio format using the file extension
															return {"bytes": value.get("""bytes"""		), "path": value.get("""path"""		)}
											else:
															raise ValueError(
															    F'''An audio sample should have one of \'path\' or \'bytes\' but they are missing or None in {value}.'''		)


							def _a      (							self  ,  a_  ,  a_ = None		):
											if not self.decode:
															raise RuntimeError("""Decoding is disabled for this feature. Please use Audio(decode=True) instead."""		)

											a__      ,			a__				      =		(value["""path"""], BytesIO(value["""bytes"""]		)) if value["""bytes"""] is not None else (value["""path"""], None)
											if path is None and file is None:
															raise ValueError(F'''An audio sample should have one of \'path\' or \'bytes\' but both are None in {value}.'''		)

											try:
															import librosa
															import soundfile as sf
											except ImportError as err:
															raise ImportError("""To support decoding audio files, please install 'librosa' and 'soundfile'."""		) from err

											a__				      =		xsplitext(a_		)[1][1:].lower() if path is not None else None
											if not config.IS_OPUS_SUPPORTED and audio_format == "opus":
															raise RuntimeError(
															    """Decoding 'opus' files requires system library 'libsndfile'>=1.0.31, """
															    """You can try to update `soundfile` python library: `pip install \"soundfile>=0.12.1\"`. """		)
											elif not config.IS_MP3_SUPPORTED and audio_format == "mp3":
															raise RuntimeError(
															    """Decoding 'mp3' files requires system library 'libsndfile'>=1.1.0, """
															    """You can try to update `soundfile` python library: `pip install \"soundfile>=0.12.1\"`. """		)

											if file is None:
															a__				      =		token_per_repo_id or {}
															a__				      =		path.split("""::"""		)[-1]
															try:
																			a__				      =		string_to_dict(a_  ,  config.HUB_DATASETS_URL		)["""repo_id"""]
																			a__				      =		token_per_repo_id[repo_id]
															except (ValueError, KeyError):
																			a__				      =		None

															with xopen(a_  ,  """rb"""  ,  use_auth_token=a_		) as f:
																			a__      ,			a__				      =		sf.read(a_		)

											else:
															a__      ,			a__				      =		sf.read(a_		)

											a__				      =		array.T
											if self.mono:
															a__				      =		librosa.to_mono(a_		)
											if self.sampling_rate and self.sampling_rate != sampling_rate:
															a__				      =		librosa.resample(a_  ,  orig_sr=a_  ,  target_sr=self.sampling_rate		)
															a__				      =		self.sampling_rate

											return {"path": path, "array": array, "sampling_rate": sampling_rate}


							def _a      (							self		):
											from .features import Value

											if self.decode:
															raise ValueError("""Cannot flatten a decoded Audio feature."""		)
											return {
											    "bytes": Value("""binary"""		),
											    "path": Value("""string"""		),
											}


							def _a      (							self  ,  a_		):
											if pa.types.is_string(storage.type		):
															a__				      =		pa.array([None] * len(a_		)  ,  type=pa.binary()		)
															a__				      =		pa.StructArray.from_arrays([bytes_array, storage]  ,  ["""bytes""", """path"""]  ,  mask=storage.is_null()		)
											elif pa.types.is_binary(storage.type		):
															a__				      =		pa.array([None] * len(a_		)  ,  type=pa.string()		)
															a__				      =		pa.StructArray.from_arrays([storage, path_array]  ,  ["""bytes""", """path"""]  ,  mask=storage.is_null()		)
											elif pa.types.is_struct(storage.type		) and storage.type.get_all_field_indices("""array"""		):
															a__				      =		pa.array([Audio().encode_example(a_		) if x is not None else None for x in storage.to_pylist()]		)
											elif pa.types.is_struct(storage.type		):
															if storage.type.get_field_index("""bytes"""		) >= 0:
																			a__				      =		storage.field("""bytes"""		)
															else:
																			a__				      =		pa.array([None] * len(a_		)  ,  type=pa.binary()		)
															if storage.type.get_field_index("""path"""		) >= 0:
																			a__				      =		storage.field("""path"""		)
															else:
																			a__				      =		pa.array([None] * len(a_		)  ,  type=pa.string()		)
															a__				      =		pa.StructArray.from_arrays([bytes_array, path_array]  ,  ["""bytes""", """path"""]  ,  mask=storage.is_null()		)
											return array_cast(a_  ,  self.pa_type		)







							def _a      (							self  ,  a_		):

											@no_op_if_value_is_null
											def path_to_bytes(a_		):
															with xopen(a_  ,  """rb"""		) as f:
																			a__				      =		f.read()
															return bytes_

											a__				      =		pa.array(
											    [
											        (path_to_bytes(x["""path"""]		) if x["""bytes"""] is None else x["""bytes"""]) if x is not None else None
											        for x in storage.to_pylist()
											    ]  ,  type=pa.binary()  ,  )
											a__				      =		pa.array(
											    [os.path.basename(a_		) if path is not None else None for path in storage.field("""path"""		).to_pylist()]  ,  type=pa.string()  ,  )
											a__				      =		pa.StructArray.from_arrays([bytes_array, path_array]  ,  ["""bytes""", """path"""]  ,  mask=bytes_array.is_null()		)
											return array_cast(a_  ,  self.pa_type		)






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  __snake_case      (   unittest.TestCase):







							'''simple docstring'''






							def _a      (							self		):
											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_145_466, 0.4_578_275, 0.40_821_073],
											    """image_std""": [0.26_862_954, 0.26_130_258, 0.27_577_711],
											}
											a__				      =		os.path.join(self.tmpdirname  ,  a_		)
											with open(self.image_processor_file  ,  """w"""  ,  encoding="""utf-8"""		) as fp:
															json.dump(a_  ,  a_		)


							def _a      (							self  ,  **a_		):
											return CLIPTokenizer.from_pretrained(self.tmpdirname  ,  pad_token="""!"""  ,  **a_		)


							def _a      (							self  ,  **a_		):
											return CLIPTokenizerFast.from_pretrained(self.tmpdirname  ,  pad_token="""!"""  ,  **a_		)


							def _a      (							self  ,  **a_		):
											return OwlViTImageProcessor.from_pretrained(self.tmpdirname  ,  **a_		)


							def _a      (							self		):
											shutil.rmtree(self.tmpdirname		)


							def _a      (							self		):
											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 _a      (							self		):
											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 _a      (							self		):
											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 _a      (							self		):
											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 _a      (							self		):
											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 _a      (							self		):
											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 _a      (							self		):
											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 _a      (							self		):
											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 _a      (							self		):
											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__				      =		[
											    [49_406, 2_368, 49_407, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
											    [49_406, 6_841, 11_301, 49_407, 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 _a      (							self		):
											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 _a      (							self		):
											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_		)

