






import os
import unittest

from huggingface_hub.utils import are_progress_bars_disabled

import transformers.models.bart.tokenization_bart
from transformers import logging
from transformers.testing_utils import CaptureLogger, mockenv, mockenv_context
from transformers.utils.logging import disable_progress_bar, enable_progress_bar




class 			snake_case__   (							unittest.TestCase):

       '''simple docstring'''



       def 					__lowercase						(							self    ) ->      Dict:






            '''simple docstring'''





            __snake_case			:Dict          =						logging.get_logger()

            # the current default level is logging.WARNING
            __snake_case			:Tuple          =						logging.get_verbosity()

            logging.set_verbosity_error()
            self.assertEqual(logger.getEffectiveLevel()			,						logging.get_verbosity()    )

            logging.set_verbosity_warning()
            self.assertEqual(logger.getEffectiveLevel()			,						logging.get_verbosity()    )

            logging.set_verbosity_info()
            self.assertEqual(logger.getEffectiveLevel()			,						logging.get_verbosity()    )

            logging.set_verbosity_debug()
            self.assertEqual(logger.getEffectiveLevel()			,						logging.get_verbosity()    )

            # restore to the original level
            logging.set_verbosity(a__    )



       def 					__lowercase						(							self    ) ->      List[str]:






            '''simple docstring'''





            __snake_case			:int          =						logging.get_verbosity()

            __snake_case			:Tuple          =						logging.get_logger("""transformers.models.bart.tokenization_bart"""    )
            __snake_case			:Optional[int]          =						"""Testing 1, 2, 3"""

            # should be able to log warnings (if default settings weren't overridden by `pytest --log-level-all`)
            if level_origin <= logging.WARNING:
                 with CaptureLogger(a__    ) as cl:
                      logger.warning(a__    )
                 self.assertEqual(cl.out			,						msg + """\n"""    )

            # this is setting the level for all of `transformers.*` loggers
            logging.set_verbosity_error()

            # should not be able to log warnings
            with CaptureLogger(a__    ) as cl:
                 logger.warning(a__    )
            self.assertEqual(cl.out			,						""""""    )

            # should be able to log warnings again
            logging.set_verbosity_warning()
            with CaptureLogger(a__    ) as cl:
                 logger.warning(a__    )
            self.assertEqual(cl.out			,						msg + """\n"""    )

            # restore to the original level
            logging.set_verbosity(a__    )



       @mockenv(TRANSFORMERS_VERBOSITY="""error"""    )
       def 					__lowercase						(							self    ) ->      Optional[int]:






            '''simple docstring'''





            transformers.utils.logging._reset_library_root_logger()
            # this action activates the env var
            __snake_case			:List[str]          =						logging.get_logger("""transformers.models.bart.tokenization_bart"""    )

            __snake_case			:Dict          =						os.getenv("""TRANSFORMERS_VERBOSITY"""			,						a__    )
            __snake_case			:Union[str, Any]          =						logging.log_levels[env_level_str]

            __snake_case			:Any          =						logging.get_verbosity()
            self.assertEqual(
                a__			,						a__			,						F'''TRANSFORMERS_VERBOSITY={env_level_str}/{env_level}, but internal verbosity is {current_level}'''			,						)

            # restore to the original level
            __snake_case			:Any          =						""""""
            transformers.utils.logging._reset_library_root_logger()



       @mockenv(TRANSFORMERS_VERBOSITY="""super-error"""    )
       def 					__lowercase						(							self    ) ->      List[Any]:






            '''simple docstring'''





            transformers.utils.logging._reset_library_root_logger()
            __snake_case			:Optional[Any]          =						logging.logging.getLogger()
            with CaptureLogger(a__    ) as cl:
                 # this action activates the env var
                 logging.get_logger("""transformers.models.bart.tokenization_bart"""    )
            self.assertIn("""Unknown option TRANSFORMERS_VERBOSITY=super-error"""			,						cl.out    )

            # no need to restore as nothing was changed



       def 					__lowercase						(							self    ) ->      Any:






            '''simple docstring'''





            transformers.utils.logging._reset_library_root_logger()

            __snake_case			:Union[str, Any]          =						logging.get_logger("""transformers.models.bart.tokenization_bart"""    )
            __snake_case			:List[Any]          =						"""Testing 1, 2, 3"""

            with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS="""1"""    ):
                 # nothing should be logged as env var disables this method
                 with CaptureLogger(a__    ) as cl:
                      logger.warning_advice(a__    )
                 self.assertEqual(cl.out			,						""""""    )

            with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS=""""""    ):
                 # should log normally as TRANSFORMERS_NO_ADVISORY_WARNINGS is unset
                 with CaptureLogger(a__    ) as cl:
                      logger.warning_advice(a__    )
                 self.assertEqual(cl.out			,						msg + """\n"""    )






def   UpperCamelCase  (       ):




     '''simple docstring'''






     disable_progress_bar()
     assert are_progress_bars_disabled()

     enable_progress_bar()
     assert not are_progress_bars_disabled()










# 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 			snake_case__   (							lowercase_):

       '''simple docstring'''
       lowerCamelCase							:				Tuple 				= "dandelin/vilt-b32-finetuned-vqa"
       lowerCamelCase							:				List[str] 				= (
           "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."
       )
       lowerCamelCase							:				Optional[Any] 				= "image_qa"
       lowerCamelCase							:				str 				= AutoProcessor
       lowerCamelCase							:				Union[str, Any] 				= AutoModelForVisualQuestionAnswering

       lowerCamelCase							:				Any 				= ["image", "text"]
       lowerCamelCase							:				Dict 				= ["text"]



       def __init__(							self			,						*a__			,						**a__    ) ->      Any:






            '''simple docstring'''





            requires_backends(self			,						["""vision"""]    )
            super().__init__(*a__			,						**a__    )



       def 					__lowercase						(							self			,						a__			,						a__    ) ->      int:






            '''simple docstring'''





            return self.pre_processor(a__			,						a__			,						return_tensors="""pt"""    )



       def 					__lowercase						(							self			,						a__    ) ->      Union[str, Any]:






            '''simple docstring'''





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



       def 					__lowercase						(							self			,						a__    ) ->      Tuple:






            '''simple docstring'''





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


