



"""simple docstring"""





import sys
from collections.abc import Mapping
from typing import TYPE_CHECKING

import numpy as np
import pyarrow as pa

from .. import config
from ..utils.py_utils import map_nested
from .formatting import TensorFormatter


if TYPE_CHECKING:
  import torch
class 				lowercase__       (   TensorFormatter[Mapping, '''torch.Tensor''', Mapping]				):







       '''simple docstring'''


       def __init__(							self      :  List[Any]		,    _UpperCAmelCase      :  Optional[Any]=None		,    **_UpperCAmelCase      :  Any   )			->						int:


             '''simple docstring'''




             super().__init__(features=_UpperCAmelCase   )
             UpperCAmelCase_      			=							torch_tensor_kwargs
             import torch  # noqa import torch at initialization



       def 					lowercase__    (							self      :  List[Any]		,    _UpperCAmelCase      :  Tuple   )			->						str:


             '''simple docstring'''




             import torch

             if isinstance(_UpperCAmelCase		,    _UpperCAmelCase   ) and column:
                   if all(
                       isinstance(_UpperCAmelCase		,    torch.Tensor   ) and x.shape == column[0].shape and x.dtype == column[0].dtype
                       for x in column   ):
                         return torch.stack(_UpperCAmelCase   )
             return column



       def 					lowercase__    (							self      :  List[str]		,    _UpperCAmelCase      :  List[str]   )			->						List[str]:


             '''simple docstring'''




             import torch

             if isinstance(_UpperCAmelCase		,    (str, bytes, type(_UpperCAmelCase   ))   ):
                   return value
             elif isinstance(_UpperCAmelCase		,    (np.character, np.ndarray)   ) and np.issubdtype(value.dtype		,    np.character   ):
                   return value.tolist()

             UpperCAmelCase_      			=							{}

             if isinstance(_UpperCAmelCase		,    (np.number, np.ndarray)   ) and np.issubdtype(value.dtype		,    np.integer   ):
                   UpperCAmelCase_      			=							{"dtype": torch.intaa}
             elif isinstance(_UpperCAmelCase		,    (np.number, np.ndarray)   ) and np.issubdtype(value.dtype		,    np.floating   ):
                   UpperCAmelCase_      			=							{"dtype": torch.floataa}
             elif config.PIL_AVAILABLE and "PIL" in sys.modules:
                   import PIL.Image

                   if isinstance(_UpperCAmelCase		,    PIL.Image.Image   ):
                         UpperCAmelCase_      			=							np.asarray(_UpperCAmelCase   )
             return torch.tensor(_UpperCAmelCase		,    **{**default_dtype, **self.torch_tensor_kwargs}   )



       def 					lowercase__    (							self      :  Tuple		,    _UpperCAmelCase      :  List[Any]   )			->						List[str]:


             '''simple docstring'''




             import torch

             # support for torch, tf, jax etc.
             if hasattr(_UpperCAmelCase		,    "__array__"   ) and not isinstance(_UpperCAmelCase		,    torch.Tensor   ):
                   UpperCAmelCase_      			=							data_struct.__array__()
             # support for nested types like struct of list of struct
             if isinstance(_UpperCAmelCase		,    np.ndarray   ):
                   if data_struct.dtype == object:  # torch tensors cannot be instantied from an array of objects
                         return self._consolidate([self.recursive_tensorize(_UpperCAmelCase   ) for substruct in data_struct]   )
             elif isinstance(_UpperCAmelCase		,    (list, tuple)   ):
                   return self._consolidate([self.recursive_tensorize(_UpperCAmelCase   ) for substruct in data_struct]   )
             return self._tensorize(_UpperCAmelCase   )



       def 					lowercase__    (							self      :  Optional[Any]		,    _UpperCAmelCase      :  dict   )			->						Union[str, Any]:


             '''simple docstring'''




             return map_nested(self._recursive_tensorize		,    _UpperCAmelCase		,    map_list=_UpperCAmelCase   )



       def 					lowercase__    (							self      :  Optional[int]		,    _UpperCAmelCase      :  pa.Table   )			->						Mapping:


             '''simple docstring'''




             UpperCAmelCase_      			=							self.numpy_arrow_extractor().extract_row(_UpperCAmelCase   )
             UpperCAmelCase_      			=							self.python_features_decoder.decode_row(_UpperCAmelCase   )
             return self.recursive_tensorize(_UpperCAmelCase   )



       def 					lowercase__    (							self      :  Any		,    _UpperCAmelCase      :  pa.Table   )			->						"torch.Tensor":


             '''simple docstring'''




             UpperCAmelCase_      			=							self.numpy_arrow_extractor().extract_column(_UpperCAmelCase   )
             UpperCAmelCase_      			=							self.python_features_decoder.decode_column(_UpperCAmelCase		,    pa_table.column_names[0]   )
             UpperCAmelCase_      			=							self.recursive_tensorize(_UpperCAmelCase   )
             UpperCAmelCase_      			=							self._consolidate(_UpperCAmelCase   )
             return column







       def 					lowercase__    (							self      :  Optional[int]		,    _UpperCAmelCase      :  pa.Table   )			->						Mapping:


             '''simple docstring'''




             UpperCAmelCase_      			=							self.numpy_arrow_extractor().extract_batch(_UpperCAmelCase   )
             UpperCAmelCase_      			=							self.python_features_decoder.decode_batch(_UpperCAmelCase   )
             UpperCAmelCase_      			=							self.recursive_tensorize(_UpperCAmelCase   )
             for column_name in batch:
                   UpperCAmelCase_      			=							self._consolidate(batch[column_name]   )
             return batch









"""simple docstring"""





import warnings

from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding
class 				lowercase__       (   SCREAMING_SNAKE_CASE				):







       '''simple docstring'''


       UpperCamelCase						=					['''image_processor''', '''tokenizer''']
       UpperCamelCase						=					'''ViTImageProcessor'''
       UpperCamelCase						=					('''CLIPTokenizer''', '''CLIPTokenizerFast''')



       def __init__(							self      :  List[Any]		,    _UpperCAmelCase      :  str=None		,    _UpperCAmelCase      :  Optional[int]=None		,    **_UpperCAmelCase      :  List[str]   )			->						Any:


             '''simple docstring'''




             UpperCAmelCase_      			=							None
             if "feature_extractor" in kwargs:
                   warnings.warn(
                       "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"
                       " instead."		,    _UpperCAmelCase		,    )
                   UpperCAmelCase_      			=							kwargs.pop("feature_extractor"   )

             UpperCAmelCase_      			=							image_processor if image_processor is not None else feature_extractor
             if image_processor is None:
                   raise ValueError("You need to specify an `image_processor`."   )
             if tokenizer is None:
                   raise ValueError("You need to specify a `tokenizer`."   )

             super().__init__(_UpperCAmelCase		,    _UpperCAmelCase   )



       def __call__(							self      :  Optional[Any]		,    _UpperCAmelCase      :  Any=None		,    _UpperCAmelCase      :  Optional[int]=None		,    _UpperCAmelCase      :  str=None		,    _UpperCAmelCase      :  List[Any]=None		,    **_UpperCAmelCase      :  str   )			->						Optional[int]:


             '''simple docstring'''




             if text is None and visual_prompt is None and images is None:
                   raise ValueError("You have to specify either text, visual prompt or images."   )

             if text is not None and visual_prompt is not None:
                   raise ValueError("You have to specify exactly one type of prompt. Either text or visual prompt."   )

             if text is not None:
                   UpperCAmelCase_      			=							self.tokenizer(_UpperCAmelCase		,    return_tensors=_UpperCAmelCase		,    **_UpperCAmelCase   )

             if visual_prompt is not None:
                   UpperCAmelCase_      			=							self.image_processor(_UpperCAmelCase		,    return_tensors=_UpperCAmelCase		,    **_UpperCAmelCase   )

             if images is not None:
                   UpperCAmelCase_      			=							self.image_processor(_UpperCAmelCase		,    return_tensors=_UpperCAmelCase		,    **_UpperCAmelCase   )

             if visual_prompt is not None and images is not None:
                   UpperCAmelCase_      			=							{
                       "pixel_values": image_features.pixel_values,
                       "conditional_pixel_values": prompt_features.pixel_values,
                   }
                   return encoding
             elif text is not None and images is not None:
                   UpperCAmelCase_      			=							image_features.pixel_values
                   return encoding
             elif text is not None:
                   return encoding
             elif visual_prompt is not None:
                   UpperCAmelCase_      			=							{
                       "conditional_pixel_values": prompt_features.pixel_values,
                   }
                   return encoding
             else:
                   return BatchEncoding(data=dict(**_UpperCAmelCase   )		,    tensor_type=_UpperCAmelCase   )



       def 					lowercase__    (							self      :  List[Any]		,    *_UpperCAmelCase      :  List[str]		,    **_UpperCAmelCase      :  List[Any]   )			->						Any:


             '''simple docstring'''




             return self.tokenizer.batch_decode(*_UpperCAmelCase		,    **_UpperCAmelCase   )



       def 					lowercase__    (							self      :  Dict		,    *_UpperCAmelCase      :  Tuple		,    **_UpperCAmelCase      :  List[Any]   )			->						Union[str, Any]:


             '''simple docstring'''




             return self.tokenizer.decode(*_UpperCAmelCase		,    **_UpperCAmelCase   )



       @property
       def 					lowercase__    (							self      :  int   )			->						Optional[int]:


             '''simple docstring'''




             warnings.warn(
                 "`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead."		,    _UpperCAmelCase		,    )
             return self.image_processor_class







       @property
       def 					lowercase__    (							self      :  str   )			->						List[Any]:


             '''simple docstring'''




             warnings.warn(
                 "`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead."		,    _UpperCAmelCase		,    )
             return self.image_processor




