
"""simple docstring"""
import functools
import logging
import os
import sys
import threading
from logging import (
    CRITICAL,  # NOQA
    DEBUG,  # NOQA
    ERROR,  # NOQA
    FATAL,  # NOQA
    INFO,  # NOQA
    NOTSET,  # NOQA
    WARN,  # NOQA
    WARNING,  # NOQA
)
from typing import Optional

import huggingface_hub.utils as hf_hub_utils
from tqdm import auto as tqdm_lib


lowercase_       :						Tuple     					=	threading.Lock()
lowercase_       :						Optional[logging.Handler]     					=	None

lowercase_       :						Any     					=	{
    '''debug''': logging.DEBUG,
    '''info''': logging.INFO,
    '''warning''': logging.WARNING,
    '''error''': logging.ERROR,
    '''critical''': logging.CRITICAL,
}

lowercase_       :						str     					=	logging.WARNING

lowercase_       :						int     					=	True





def    _lowerCAmelCase    (     )  ->    List[str]:
  _SCREAMING_SNAKE_CASE   :				Union[str, Any]							    = os.getenv("TRANSFORMERS_VERBOSITY",						lowerCamelCase__				)
  if env_level_str:
    if env_level_str in log_levels:
      return log_levels[env_level_str]
    else:
      logging.getLogger().warning(
          f'''Unknown option TRANSFORMERS_VERBOSITY={env_level_str}, '''
          f'''has to be one of: { ", ".join(log_levels.keys()				) }'''				)
  return _default_log_level





def    _lowerCAmelCase    (     )  ->    str:
  return __name__.split("."				)[0]





def    _lowerCAmelCase    (     )  ->    logging.Logger:
  return logging.getLogger(_get_library_name()				)





def    _lowerCAmelCase    (     )  ->    None:
  global _default_handler

  with _lock:
    if _default_handler:
      # This library has already configured the library root logger.
      return
    _SCREAMING_SNAKE_CASE   :				Tuple							    = logging.StreamHandler()  # Set sys.stderr as stream.
    _SCREAMING_SNAKE_CASE   :				str							    = sys.stderr.flush

    # Apply our default configuration to the library root logger.
    _SCREAMING_SNAKE_CASE   :				Dict							    = _get_library_root_logger()
    library_root_logger.addHandler(_default_handler				)
    library_root_logger.setLevel(_get_default_logging_level()				)
    _SCREAMING_SNAKE_CASE   :				Any							    = False





def    _lowerCAmelCase    (     )  ->    None:
  global _default_handler

  with _lock:
    if not _default_handler:
      return

    _SCREAMING_SNAKE_CASE   :				int							    = _get_library_root_logger()
    library_root_logger.removeHandler(_default_handler				)
    library_root_logger.setLevel(logging.NOTSET				)
    _SCREAMING_SNAKE_CASE   :				Union[str, Any]							    = None





def    _lowerCAmelCase    (     )  ->    Any:
  return log_levels





def    _lowerCAmelCase    (     lowerCamelCase__							:							Optional[str] = None				)  ->    logging.Logger:

  if name is None:
    _SCREAMING_SNAKE_CASE   :				Optional[int]							    = _get_library_name()

  _configure_library_root_logger()
  return logging.getLogger(lowerCamelCase__				)





def    _lowerCAmelCase    (     )  ->    int:
  _configure_library_root_logger()
  return _get_library_root_logger().getEffectiveLevel()





def    _lowerCAmelCase    (     lowerCamelCase__							:							int				)  ->    None:
  _configure_library_root_logger()
  _get_library_root_logger().setLevel(lowerCamelCase__				)





def    _lowerCAmelCase    (     )  ->    Any:
  return set_verbosity(lowerCamelCase__				)





def    _lowerCAmelCase    (     )  ->    Optional[Any]:
  return set_verbosity(lowerCamelCase__				)





def    _lowerCAmelCase    (     )  ->    str:
  return set_verbosity(lowerCamelCase__				)





def    _lowerCAmelCase    (     )  ->    Optional[Any]:
  return set_verbosity(lowerCamelCase__				)





def    _lowerCAmelCase    (     )  ->    None:
  _configure_library_root_logger()

  assert _default_handler is not None
  _get_library_root_logger().removeHandler(_default_handler				)





def    _lowerCAmelCase    (     )  ->    None:
  _configure_library_root_logger()

  assert _default_handler is not None
  _get_library_root_logger().addHandler(_default_handler				)





def    _lowerCAmelCase    (     lowerCamelCase__							:							logging.Handler				)  ->    None:
  _configure_library_root_logger()

  assert handler is not None
  _get_library_root_logger().addHandler(lowerCamelCase__				)





def    _lowerCAmelCase    (     lowerCamelCase__							:							logging.Handler				)  ->    None:
  _configure_library_root_logger()

  assert handler is not None and handler not in _get_library_root_logger().handlers
  _get_library_root_logger().removeHandler(lowerCamelCase__				)





def    _lowerCAmelCase    (     )  ->    None:
  _configure_library_root_logger()
  _SCREAMING_SNAKE_CASE   :				int							    = False





def    _lowerCAmelCase    (     )  ->    None:
  _configure_library_root_logger()
  _SCREAMING_SNAKE_CASE   :				Dict							    = True





def    _lowerCAmelCase    (     )  ->    None:
  _SCREAMING_SNAKE_CASE   :				Optional[int]							    = _get_library_root_logger().handlers

  for handler in handlers:
    _SCREAMING_SNAKE_CASE   :				List[str]							    = logging.Formatter("[%(levelname)s|%(filename)s:%(lineno)s] %(asctime)s >> %(message)s"				)
    handler.setFormatter(lowerCamelCase__				)





def    _lowerCAmelCase    (     )  ->    None:
  _SCREAMING_SNAKE_CASE   :				Union[str, Any]							    = _get_library_root_logger().handlers

  for handler in handlers:
    handler.setFormatter(lowerCamelCase__				)





def    _lowerCAmelCase    (     self							:							Any,						*lowerCamelCase__							:							List[Any],						**lowerCamelCase__							:							Optional[Any]				)  ->    Dict:
  _SCREAMING_SNAKE_CASE   :				List[Any]							    = os.getenv("TRANSFORMERS_NO_ADVISORY_WARNINGS",						lowerCamelCase__				)
  if no_advisory_warnings:
    return
  self.warning(*lowerCamelCase__,						**lowerCamelCase__				)


lowercase_       :						Union[str, Any]     					=	warning_advice





@functools.lru_cache(lowerCamelCase__				)
def    _lowerCAmelCase    (     self							:							List[str],						*lowerCamelCase__							:							Optional[Any],						**lowerCamelCase__							:							str				)  ->    List[str]:
  self.warning(*lowerCamelCase__,						**lowerCamelCase__				)


lowercase_       :						Any     					=	warning_once
class 			UpperCamelCase      :
   def __init__(     self  ,     *snake_case__  ,     **snake_case__				):  # pylint: disable=unused-argument




     """simple docstring"""


     _SCREAMING_SNAKE_CASE   :				Any							    = args[0] if args else None
   def __iter__(     self				):




     """simple docstring"""


     return iter(self._iterator				)
   def __getattr__(     self  ,     snake_case__				):




     """simple docstring"""


     def empty_fn(*snake_case__  ,     **snake_case__				):  # pylint: disable=unused-argument
       return

     return empty_fn
   def __enter__(     self				):




     """simple docstring"""


     return self




   def __exit__(     self  ,     snake_case__  ,     snake_case__  ,     snake_case__				):




     """simple docstring"""


     return
class 			UpperCamelCase      :
   def __call__(     self  ,     *snake_case__  ,     **snake_case__				):




     """simple docstring"""


     if _tqdm_active:
       return tqdm_lib.tqdm(*snake_case__  ,     **snake_case__				)
     else:
       return EmptyTqdm(*snake_case__  ,     **snake_case__				)
   def 				__SCREAMING_SNAKE_CASE							(     self  ,     *snake_case__  ,     **snake_case__				):




     """simple docstring"""


     _SCREAMING_SNAKE_CASE   :				Union[str, Any]							    = None
     if _tqdm_active:
       return tqdm_lib.tqdm.set_lock(*snake_case__  ,     **snake_case__				)




   def 				__SCREAMING_SNAKE_CASE							(     self				):




     """simple docstring"""


     if _tqdm_active:
       return tqdm_lib.tqdm.get_lock()
lowercase_       :						List[Any]     					=	_tqdm_cls()





def    _lowerCAmelCase    (     )  ->    bool:
  global _tqdm_active
  return bool(_tqdm_active				)





def    _lowerCAmelCase    (     )  ->    int:
  global _tqdm_active
  _SCREAMING_SNAKE_CASE   :				Optional[Any]							    = True
  hf_hub_utils.enable_progress_bars()





def    _lowerCAmelCase    (     )  ->    Any:
  global _tqdm_active
  _SCREAMING_SNAKE_CASE   :				Optional[Any]							    = False
  hf_hub_utils.disable_progress_bars()





"""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.
import re

from ..models.auto import AutoProcessor
from ..models.vision_encoder_decoder import VisionEncoderDecoderModel
from ..utils import is_vision_available
from .base import PipelineTool


if is_vision_available():
      from PIL import Image
class 			UpperCamelCase      (							__SCREAMING_SNAKE_CASE  ):
     A__      =			"""naver-clova-ix/donut-base-finetuned-docvqa"""
     A__      =			(
         """This is a tool that answers a question about an document (pdf). It takes an input named `document` which """
         """should be the document containing the information, as well as a `question` that is the question about the """
         """document. It returns a text that contains the answer to the question."""
     )
     A__      =			"""document_qa"""
     A__      =			AutoProcessor
     A__      =			VisionEncoderDecoderModel

     A__      =			["""image""", """text"""]
     A__      =			["""text"""]
     def __init__(     self  ,     *snake_case__  ,     **snake_case__				):




       """simple docstring"""


       if not is_vision_available():
         raise ValueError("Pillow must be installed to use the DocumentQuestionAnsweringTool."				)

       super().__init__(*snake_case__  ,     **snake_case__				)
     def 				__SCREAMING_SNAKE_CASE							(     self  ,     snake_case__  ,     snake_case__				):




       """simple docstring"""


       _SCREAMING_SNAKE_CASE   :				List[str]							    = "<s_docvqa><s_question>{user_input}</s_question><s_answer>"
       _SCREAMING_SNAKE_CASE   :				Optional[int]							    = task_prompt.replace("{user_input}"  ,     snake_case__				)
       _SCREAMING_SNAKE_CASE   :				Tuple							    = self.pre_processor.tokenizer(
           snake_case__  ,     add_special_tokens=snake_case__  ,     return_tensors="pt"				).input_ids
       _SCREAMING_SNAKE_CASE   :				Union[str, Any]							    = self.pre_processor(snake_case__  ,     return_tensors="pt"				).pixel_values

       return {"decoder_input_ids": decoder_input_ids, "pixel_values": pixel_values}
     def 				__SCREAMING_SNAKE_CASE							(     self  ,     snake_case__				):




       """simple docstring"""


       return self.model.generate(
           inputs["pixel_values"].to(self.device				)  ,     decoder_input_ids=inputs["decoder_input_ids"].to(self.device				)  ,     max_length=self.model.decoder.config.max_position_embeddings  ,     early_stopping=snake_case__  ,     pad_token_id=self.pre_processor.tokenizer.pad_token_id  ,     eos_token_id=self.pre_processor.tokenizer.eos_token_id  ,     use_cache=snake_case__  ,     num_beams=1  ,     bad_words_ids=[[self.pre_processor.tokenizer.unk_token_id]]  ,     return_dict_in_generate=snake_case__  ,     ).sequences




     def 				__SCREAMING_SNAKE_CASE							(     self  ,     snake_case__				):




       """simple docstring"""


       _SCREAMING_SNAKE_CASE   :				int							    = self.pre_processor.batch_decode(snake_case__				)[0]
       _SCREAMING_SNAKE_CASE   :				Optional[Any]							    = sequence.replace(self.pre_processor.tokenizer.eos_token  ,     ""				)
       _SCREAMING_SNAKE_CASE   :				Optional[Any]							    = sequence.replace(self.pre_processor.tokenizer.pad_token  ,     ""				)
       _SCREAMING_SNAKE_CASE   :				Dict							    = re.sub(r"<.*?>"  ,     ""  ,     snake_case__  ,     count=1				).strip()  # remove first task start token
       _SCREAMING_SNAKE_CASE   :				Dict							    = self.pre_processor.tokenajson(snake_case__				)

       return sequence["answer"]



