


'''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


UpperCAmelCase_			:  int										=   get_tests_dir('fixtures/dummy-config.json')

class     _lowerCamelCase       (     unittest.TestCase					):




 '''simple docstring'''


 def 			snake_case__ (   self    ):

  """simple docstring"""







  __A	:		str	  =      0


 def 			snake_case__ (   self    ):

  """simple docstring"""







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


 def 			snake_case__ (   self    ):

  """simple docstring"""







  __A	:		Union[str, Any]	  =      AutoConfig.from_pretrained('bert-base-uncased'    )
  self.assertIsInstance(__lowercase   ,   __lowercase    )


 def 			snake_case__ (   self    ):

  """simple docstring"""







  __A	:		Optional[Any]	  =      AutoConfig.from_pretrained(__lowercase    )
  self.assertIsInstance(__lowercase   ,   __lowercase    )


 def 			snake_case__ (   self    ):

  """simple docstring"""







  __A	:		Optional[int]	  =      AutoConfig.from_pretrained(__lowercase    )
  self.assertIsInstance(__lowercase   ,   __lowercase    )


 def 			snake_case__ (   self    ):

  """simple docstring"""







  __A	:		List[Any]	  =      AutoConfig.for_model('roberta'    )
  self.assertIsInstance(__lowercase   ,   __lowercase    )


 def 			snake_case__ (   self    ):

  """simple docstring"""







  with tempfile.TemporaryDirectory() as tmp_dir:
   # This model name contains bert and roberta, but roberta ends up being picked.
   __A	:		Dict	  =      os.path.join(__lowercase   ,   'fake-roberta'    )
   os.makedirs(__lowercase   ,   exist_ok=__lowercase    )
   with open(os.path.join(__lowercase   ,   'config.json'    )   ,   'w'    ) as f:
    f.write(json.dumps({}    )    )
   __A	:		Dict	  =      AutoConfig.from_pretrained(__lowercase    )
   self.assertEqual(type(__lowercase    )   ,   __lowercase    )


 def 			snake_case__ (   self    ):

  """simple docstring"""







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

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

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


 def 			snake_case__ (   self    ):

  """simple docstring"""







  with self.assertRaisesRegex(
      __lowercase   ,   'bert-base is not a local folder and is not a valid model identifier'    ):
   __A	:		List[Any]	  =      AutoConfig.from_pretrained('bert-base'    )


 def 			snake_case__ (   self    ):

  """simple docstring"""







  with self.assertRaisesRegex(
      __lowercase   ,   R'aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)'    ):
   __A	:		Optional[Any]	  =      AutoConfig.from_pretrained(__lowercase   ,   revision='aaaaaa'    )


 def 			snake_case__ (   self    ):

  """simple docstring"""







  with self.assertRaisesRegex(
      __lowercase   ,   'hf-internal-testing/no-config-test-repo does not appear to have a file named config.json.'   ,   ):
   __A	:		Any	  =      AutoConfig.from_pretrained('hf-internal-testing/no-config-test-repo'    )


 def 			snake_case__ (   self    ):

  """simple docstring"""







  with self.assertRaises(__lowercase    ):
   __A	:		List[str]	  =      AutoConfig.from_pretrained('hf-internal-testing/test_dynamic_model'    )
  # If remote code is disabled, we can't load this config.
  with self.assertRaises(__lowercase    ):
   __A	:		Union[str, Any]	  =      AutoConfig.from_pretrained('hf-internal-testing/test_dynamic_model'   ,   trust_remote_code=__lowercase    )

  __A	:		Optional[int]	  =      AutoConfig.from_pretrained('hf-internal-testing/test_dynamic_model'   ,   trust_remote_code=__lowercase    )
  self.assertEqual(config.__class__.__name__   ,   'NewModelConfig'    )

  # Test config can be reloaded.
  with tempfile.TemporaryDirectory() as tmp_dir:
   config.save_pretrained(__lowercase    )
   __A	:		str	  =      AutoConfig.from_pretrained(__lowercase   ,   trust_remote_code=__lowercase    )
  self.assertEqual(reloaded_config.__class__.__name__   ,   'NewModelConfig'    )







 def 			snake_case__ (   self    ):

  """simple docstring"""







  class     _lowerCamelCase       (     snake_case_					):




   '''simple docstring'''
   __lowercase					:		Optional[int]     				=    '''new-model'''

  try:
   AutoConfig.register('new-model'   ,   __lowercase    )
   # If remote code is not set, the default is to use local
   __A	:		Union[str, 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.
   __A	:		Tuple	  =      AutoConfig.from_pretrained('hf-internal-testing/test_dynamic_model'   ,   trust_remote_code=__lowercase    )
   self.assertEqual(config.__class__.__name__   ,   'NewModelConfigLocal'    )

   # If remote is enabled, we load from the Hub
   __A	:		str	  =      AutoConfig.from_pretrained('hf-internal-testing/test_dynamic_model'   ,   trust_remote_code=__lowercase    )
   self.assertEqual(config.__class__.__name__   ,   'NewModelConfig'    )

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










'''simple docstring'''
# 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 typing import TYPE_CHECKING

import torch

from ..models.auto import AutoModelForVisualQuestionAnswering, AutoProcessor
from ..utils import requires_backends
from .base import PipelineTool


if TYPE_CHECKING:
 from PIL import Image

class     _lowerCamelCase       (     snake_case_					):




 '''simple docstring'''
 __lowercase					:		int     				=    '''dandelin/vilt-b32-finetuned-vqa'''
 __lowercase					:		int     				=    (
     '''This is a tool that answers a question about an image. It takes an input named `image` which should be the '''
     '''image containing the information, as well as a `question` which should be the question in English. It '''
     '''returns a text that is the answer to the question.'''
 )
 __lowercase					:		Union[str, Any]     				=    '''image_qa'''
 __lowercase					:		Optional[Any]     				=    AutoProcessor
 __lowercase					:		Tuple     				=    AutoModelForVisualQuestionAnswering

 __lowercase					:		Tuple     				=    ['''image''', '''text''']
 __lowercase					:		List[str]     				=    ['''text''']


 def __init__(   self   ,   *__lowercase   ,   **__lowercase    ):

  """simple docstring"""







  requires_backends(self   ,   ['vision']    )
  super().__init__(*__lowercase   ,   **__lowercase    )


 def 			snake_case__ (   self   ,   __lowercase   ,   __lowercase    ):

  """simple docstring"""







  return self.pre_processor(__lowercase   ,   __lowercase   ,   return_tensors='pt'    )


 def 			snake_case__ (   self   ,   __lowercase    ):

  """simple docstring"""







  with torch.no_grad():
   return self.model(**__lowercase    ).logits







 def 			snake_case__ (   self   ,   __lowercase    ):

  """simple docstring"""







  __A	:		List[str]	  =      outputs.argmax(-1    ).item()
  return self.model.config.idalabel[idx]






