

'''simple docstring'''
import importlib
import json
import os
import sys
import tempfile
import unittest
from pathlib import Path

import transformers
import transformers.models.auto
from transformers.models.auto.configuration_auto import CONFIG_MAPPING, AutoConfig
from transformers.models.bert.configuration_bert import BertConfig
from transformers.models.roberta.configuration_roberta import RobertaConfig
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, get_tests_dir


sys.path.append(str(Path(__file__).parent.parent.parent.parent / 'utils'))

from test_module.custom_configuration import CustomConfig  # noqa E402


_snake_case         =  get_tests_dir('fixtures/dummy-config.json')


class        a__  (							unittest.TestCase  ):


   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      _lowercase      :				List[Any]      					=       0


   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      self.assertIsNotNone(transformers.models.auto.__spec__  )
      self.assertIsNotNone(importlib.util.find_spec("transformers.models.auto"  )  )


   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      _lowercase      :				int      					=       AutoConfig.from_pretrained("bert-base-uncased"  )
      self.assertIsInstance(_UpperCamelCase      ,    _UpperCamelCase  )


   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      _lowercase      :				Optional[Any]      					=       AutoConfig.from_pretrained(_UpperCamelCase  )
      self.assertIsInstance(_UpperCamelCase      ,    _UpperCamelCase  )


   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      _lowercase      :				Union[str, Any]      					=       AutoConfig.from_pretrained(_UpperCamelCase  )
      self.assertIsInstance(_UpperCamelCase      ,    _UpperCamelCase  )


   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      _lowercase      :				str      					=       AutoConfig.for_model("roberta"  )
      self.assertIsInstance(_UpperCamelCase      ,    _UpperCamelCase  )


   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      with tempfile.TemporaryDirectory() as tmp_dir:
         # This model name contains bert and roberta, but roberta ends up being picked.
         _lowercase      :				List[Any]      					=       os.path.join(_UpperCamelCase      ,    "fake-roberta"  )
         os.makedirs(_UpperCamelCase      ,    exist_ok=_UpperCamelCase  )
         with open(os.path.join(_UpperCamelCase      ,    "config.json"  )      ,    "w"  ) as f:
            f.write(json.dumps({}  )  )
         _lowercase      :				Union[str, Any]      					=       AutoConfig.from_pretrained(_UpperCamelCase  )
         self.assertEqual(type(_UpperCamelCase  )      ,    _UpperCamelCase  )


   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      try:
         AutoConfig.register("custom"      ,    _UpperCamelCase  )
         # Wrong model type will raise an error
         with self.assertRaises(_UpperCamelCase  ):
            AutoConfig.register("model"      ,    _UpperCamelCase  )
         # Trying to register something existing in the Transformers library will raise an error
         with self.assertRaises(_UpperCamelCase  ):
            AutoConfig.register("bert"      ,    _UpperCamelCase  )

         # Now that the config is registered, it can be used as any other config with the auto-API
         _lowercase      :				List[str]      					=       CustomConfig()
         with tempfile.TemporaryDirectory() as tmp_dir:
            config.save_pretrained(_UpperCamelCase  )
            _lowercase      :				Union[str, Any]      					=       AutoConfig.from_pretrained(_UpperCamelCase  )
            self.assertIsInstance(_UpperCamelCase      ,    _UpperCamelCase  )

      finally:
         if "custom" in CONFIG_MAPPING._extra_content:
            del CONFIG_MAPPING._extra_content["custom"]


   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      with self.assertRaisesRegex(
          _UpperCamelCase      ,    "bert-base is not a local folder and is not a valid model identifier"  ):
         _lowercase      :				Dict      					=       AutoConfig.from_pretrained("bert-base"  )


   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      with self.assertRaisesRegex(
          _UpperCamelCase      ,    R"aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)"  ):
         _lowercase      :				List[Any]      					=       AutoConfig.from_pretrained(_UpperCamelCase      ,    revision="aaaaaa"  )


   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      with self.assertRaisesRegex(
          _UpperCamelCase      ,    "hf-internal-testing/no-config-test-repo does not appear to have a file named config.json."      ,    ):
         _lowercase      :				List[str]      					=       AutoConfig.from_pretrained("hf-internal-testing/no-config-test-repo"  )


   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      with self.assertRaises(_UpperCamelCase  ):
         _lowercase      :				Tuple      					=       AutoConfig.from_pretrained("hf-internal-testing/test_dynamic_model"  )
      # If remote code is disabled, we can't load this config.
      with self.assertRaises(_UpperCamelCase  ):
         _lowercase      :				Optional[int]      					=       AutoConfig.from_pretrained("hf-internal-testing/test_dynamic_model"      ,    trust_remote_code=_UpperCamelCase  )

      _lowercase      :				Union[str, Any]      					=       AutoConfig.from_pretrained("hf-internal-testing/test_dynamic_model"      ,    trust_remote_code=_UpperCamelCase  )
      self.assertEqual(config.__class__.__name__      ,    "NewModelConfig"  )

      # Test config can be reloaded.
      with tempfile.TemporaryDirectory() as tmp_dir:
         config.save_pretrained(_UpperCamelCase  )
         _lowercase      :				Any      					=       AutoConfig.from_pretrained(_UpperCamelCase      ,    trust_remote_code=_UpperCamelCase  )
      self.assertEqual(reloaded_config.__class__.__name__      ,    "NewModelConfig"  )






   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      class        a__  (							lowerCamelCase_  ):
         _SCREAMING_SNAKE_CASE   :					Dict     	=							'new-model'

      try:
         AutoConfig.register("new-model"      ,    _UpperCamelCase  )
         # If remote code is not set, the default is to use local
         _lowercase      :				Any      					=       AutoConfig.from_pretrained("hf-internal-testing/test_dynamic_model"  )
         self.assertEqual(config.__class__.__name__      ,    "NewModelConfigLocal"  )

         # If remote code is disabled, we load the local one.
         _lowercase      :				str      					=       AutoConfig.from_pretrained("hf-internal-testing/test_dynamic_model"      ,    trust_remote_code=_UpperCamelCase  )
         self.assertEqual(config.__class__.__name__      ,    "NewModelConfigLocal"  )

         # If remote is enabled, we load from the Hub
         _lowercase      :				Union[str, Any]      					=       AutoConfig.from_pretrained("hf-internal-testing/test_dynamic_model"      ,    trust_remote_code=_UpperCamelCase  )
         self.assertEqual(config.__class__.__name__      ,    "NewModelConfig"  )

      finally:
         if "new-model" in CONFIG_MAPPING._extra_content:
            del CONFIG_MAPPING._extra_content["new-model"]









'''simple docstring'''
import warnings
from typing import List

import numpy as np

from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding
from ...utils import is_flax_available, is_tf_available, is_torch_available


class        a__  (							lowerCamelCase_  ):
   _SCREAMING_SNAKE_CASE   :					List[Any]     	=							['image_processor', 'tokenizer']
   _SCREAMING_SNAKE_CASE   :					str     	=							'OwlViTImageProcessor'
   _SCREAMING_SNAKE_CASE   :					List[str]     	=							('CLIPTokenizer', 'CLIPTokenizerFast')


   def __init__(			self      ,    _UpperCamelCase=None      ,    _UpperCamelCase=None      ,    **_UpperCamelCase  ):





      """simple docstring"""





      _lowercase      :				Dict      					=       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      ,    )
         _lowercase      :				Optional[int]      					=       kwargs.pop("feature_extractor"  )

      _lowercase      :				str      					=       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      ,    _UpperCamelCase=None      ,    _UpperCamelCase=None      ,    _UpperCamelCase=None      ,    _UpperCamelCase="max_length"      ,    _UpperCamelCase="np"      ,    **_UpperCamelCase  ):





      """simple docstring"""





      if text is None and query_images is None and images is None:
         raise ValueError(
             "You have to specify at least one text or query image or image. All three cannot be none."  )

      if text is not None:
         if isinstance(_UpperCamelCase      ,    _UpperCamelCase  ) or (isinstance(_UpperCamelCase      ,    _UpperCamelCase  ) and not isinstance(text[0]      ,    _UpperCamelCase  )):
            _lowercase      :				int      					=       [self.tokenizer(_UpperCamelCase      ,    padding=_UpperCamelCase      ,    return_tensors=_UpperCamelCase      ,    **_UpperCamelCase  )]

         elif isinstance(_UpperCamelCase      ,    _UpperCamelCase  ) and isinstance(text[0]      ,    _UpperCamelCase  ):
            _lowercase      :				str      					=       []

            # Maximum number of queries across batch
            _lowercase      :				str      					=       max([len(_UpperCamelCase  ) for t in text]  )

            # Pad all batch samples to max number of text queries
            for t in text:
               if len(_UpperCamelCase  ) != max_num_queries:
                  _lowercase      :				List[Any]      					=       t + [" "] * (max_num_queries - len(_UpperCamelCase  ))

               _lowercase      :				Tuple      					=       self.tokenizer(_UpperCamelCase      ,    padding=_UpperCamelCase      ,    return_tensors=_UpperCamelCase      ,    **_UpperCamelCase  )
               encodings.append(_UpperCamelCase  )
         else:
            raise TypeError("Input text should be a string, a list of strings or a nested list of strings"  )

         if return_tensors == "np":
            _lowercase      :				List[Any]      					=       np.concatenate([encoding["input_ids"] for encoding in encodings]      ,    axis=0  )
            _lowercase      :				Optional[Any]      					=       np.concatenate([encoding["attention_mask"] for encoding in encodings]      ,    axis=0  )

         elif return_tensors == "jax" and is_flax_available():
            import jax.numpy as jnp

            _lowercase      :				Union[str, Any]      					=       jnp.concatenate([encoding["input_ids"] for encoding in encodings]      ,    axis=0  )
            _lowercase      :				int      					=       jnp.concatenate([encoding["attention_mask"] for encoding in encodings]      ,    axis=0  )

         elif return_tensors == "pt" and is_torch_available():
            import torch

            _lowercase      :				int      					=       torch.cat([encoding["input_ids"] for encoding in encodings]      ,    dim=0  )
            _lowercase      :				Dict      					=       torch.cat([encoding["attention_mask"] for encoding in encodings]      ,    dim=0  )

         elif return_tensors == "tf" and is_tf_available():
            import tensorflow as tf

            _lowercase      :				Optional[int]      					=       tf.stack([encoding["input_ids"] for encoding in encodings]      ,    axis=0  )
            _lowercase      :				List[str]      					=       tf.stack([encoding["attention_mask"] for encoding in encodings]      ,    axis=0  )

         else:
            raise ValueError("Target return tensor type could not be returned"  )

         _lowercase      :				Optional[int]      					=       BatchEncoding()
         _lowercase      :				List[Any]      					=       input_ids
         _lowercase      :				Dict      					=       attention_mask

      if query_images is not None:
         _lowercase      :				int      					=       BatchEncoding()
         _lowercase      :				Any      					=       self.image_processor(
             _UpperCamelCase      ,    return_tensors=_UpperCamelCase      ,    **_UpperCamelCase  ).pixel_values
         _lowercase      :				Any      					=       query_pixel_values

      if images is not None:
         _lowercase      :				str      					=       self.image_processor(_UpperCamelCase      ,    return_tensors=_UpperCamelCase      ,    **_UpperCamelCase  )

      if text is not None and images is not None:
         _lowercase      :				List[Any]      					=       image_features.pixel_values
         return encoding
      elif query_images is not None and images is not None:
         _lowercase      :				Optional[Any]      					=       image_features.pixel_values
         return encoding
      elif text is not None or query_images is not None:
         return encoding
      else:
         return BatchEncoding(data=dict(**_UpperCamelCase  )      ,    tensor_type=_UpperCamelCase  )


   def 						_lowerCamelCase       (			self      ,    *_UpperCamelCase      ,    **_UpperCamelCase  ):





      """simple docstring"""





      return self.image_processor.post_process(*_UpperCamelCase      ,    **_UpperCamelCase  )


   def 						_lowerCamelCase       (			self      ,    *_UpperCamelCase      ,    **_UpperCamelCase  ):





      """simple docstring"""





      return self.image_processor.post_process_object_detection(*_UpperCamelCase      ,    **_UpperCamelCase  )


   def 						_lowerCamelCase       (			self      ,    *_UpperCamelCase      ,    **_UpperCamelCase  ):





      """simple docstring"""





      return self.image_processor.post_process_image_guided_detection(*_UpperCamelCase      ,    **_UpperCamelCase  )


   def 						_lowerCamelCase       (			self      ,    *_UpperCamelCase      ,    **_UpperCamelCase  ):





      """simple docstring"""





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


   def 						_lowerCamelCase       (			self      ,    *_UpperCamelCase      ,    **_UpperCamelCase  ):





      """simple docstring"""





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


   @property
   def 						_lowerCamelCase       (			self  ):





      """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 						_lowerCamelCase       (			self  ):





      """simple docstring"""





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






