




# 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 __snake_case			(			a		):
   UpperCAmelCase__  :    Union[str, Any]          =  '''naver-clova-ix/donut-base-finetuned-docvqa'''
   UpperCAmelCase__  :    List[Any]          =  (
       '''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.'''
   )
   UpperCAmelCase__  :    str          =  '''document_qa'''
   UpperCAmelCase__  :    Dict          =  AutoProcessor
   UpperCAmelCase__  :    List[str]          =  VisionEncoderDecoderModel

   UpperCAmelCase__  :    str          =  ['''image''', '''text''']
   UpperCAmelCase__  :    Union[str, Any]          =  ['''text''']







   def __init__(      self		:						List[Any]					,						*_snake_case		:						Union[str, Any]					,						**_snake_case		:						List[str]):

        """simple docstring"""


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

        super().__init__(*_snake_case					,						**_snake_case)







   def lowerCamelCase						(      self		:						Optional[Any]					,						_snake_case		:						"Image"					,						_snake_case		:						str):

        """simple docstring"""


        UpperCAmelCase_          =							'''<s_docvqa><s_question>{user_input}</s_question><s_answer>'''
        UpperCAmelCase_          =							task_prompt.replace('''{user_input}'''					,						_snake_case)
        UpperCAmelCase_          =							self.pre_processor.tokenizer(
            _snake_case					,						add_special_tokens=_snake_case					,						return_tensors='''pt''').input_ids
        UpperCAmelCase_          =							self.pre_processor(_snake_case					,						return_tensors='''pt''').pixel_values

        return {"decoder_input_ids": decoder_input_ids, "pixel_values": pixel_values}







   def lowerCamelCase						(      self		:						Optional[int]					,						_snake_case		:						List[str]):

        """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 lowerCamelCase						(      self		:						Optional[Any]					,						_snake_case		:						Any):

        """simple docstring"""


        UpperCAmelCase_          =							self.pre_processor.batch_decode(_snake_case)[0]
        UpperCAmelCase_          =							sequence.replace(self.pre_processor.tokenizer.eos_token					,						'''''')
        UpperCAmelCase_          =							sequence.replace(self.pre_processor.tokenizer.pad_token					,						'''''')
        UpperCAmelCase_          =							re.sub(r'''<.*?>'''					,						''''''					,						_snake_case					,						count=1).strip()  # remove first task start token
        UpperCAmelCase_          =							self.pre_processor.tokenajson(_snake_case)

        return sequence["answer"]













from typing import List, Optional, Union

from ...configuration_utils import PretrainedConfig
from ...utils import logging


UpperCAmelCase_     							= logging.get_logger(__name__)

UpperCAmelCase_     							= {
    'huggingface/informer-tourism-monthly': (
        'https://huggingface.co/huggingface/informer-tourism-monthly/resolve/main/config.json'
    ),
    # See all Informer models at https://huggingface.co/models?filter=informer
}






class     lowercase__       (	__lowerCamelCase				):

   '''simple docstring'''


   a						:							Optional[int]   		=		"informer"
   a						:							Tuple   		=		{
       "hidden_size": "d_model",
       "num_attention_heads": "encoder_attention_heads",
       "num_hidden_layers": "encoder_layers",
   }




   def __init__(    self,		__magic_name__ = None,		__magic_name__ = None,		__magic_name__ = "student_t",		__magic_name__ = "nll",		__magic_name__ = 1,		__magic_name__ = None,		__magic_name__ = "mean",		__magic_name__ = 0,		__magic_name__ = 0,		__magic_name__ = 0,		__magic_name__ = 0,		__magic_name__ = None,		__magic_name__ = None,		__magic_name__ = 64,		__magic_name__ = 32,		__magic_name__ = 32,		__magic_name__ = 2,		__magic_name__ = 2,		__magic_name__ = 2,		__magic_name__ = 2,		__magic_name__ = True,		__magic_name__ = "gelu",		__magic_name__ = 0.05,		__magic_name__ = 0.1,		__magic_name__ = 0.1,		__magic_name__ = 0.1,		__magic_name__ = 0.1,		__magic_name__ = 100,		__magic_name__ = 0.02,		__magic_name__=True,		__magic_name__ = "prob",		__magic_name__ = 5,		__magic_name__ = True,		**__magic_name__,		) ->      Optional[int]:






       """simple docstring"""
       # time series specific configuration
       UpperCamelCase__							:				List[Any]          =      prediction_length
       UpperCamelCase__							:				Any          =      context_length or prediction_length
       UpperCamelCase__							:				Optional[int]          =      distribution_output
       UpperCamelCase__							:				Union[str, Any]          =      loss
       UpperCamelCase__							:				Optional[Any]          =      input_size
       UpperCamelCase__							:				Dict          =      num_time_features
       UpperCamelCase__							:				Dict          =      lags_sequence if lags_sequence is not None else [1, 2, 3, 4, 5, 6, 7]
       UpperCamelCase__							:				Optional[int]          =      scaling
       UpperCamelCase__							:				Any          =      num_dynamic_real_features
       UpperCamelCase__							:				Optional[int]          =      num_static_real_features
       UpperCamelCase__							:				Optional[Any]          =      num_static_categorical_features

       # set cardinality
       if cardinality and num_static_categorical_features > 0:
           if len(__magic_name__							) != num_static_categorical_features:
               raise ValueError(
                   '''The cardinality should be a list of the same length as `num_static_categorical_features`'''							)
           UpperCamelCase__							:				str          =      cardinality
       else:
           UpperCamelCase__							:				int          =      [0]

       # set embedding_dimension
       if embedding_dimension and num_static_categorical_features > 0:
           if len(__magic_name__							) != num_static_categorical_features:
               raise ValueError(
                   '''The embedding dimension should be a list of the same length as `num_static_categorical_features`'''							)
           UpperCamelCase__							:				Any          =      embedding_dimension
       else:
           UpperCamelCase__							:				Union[str, Any]          =      [min(50,		(cat + 1) // 2							) for cat in self.cardinality]

       UpperCamelCase__							:				Optional[Any]          =      num_parallel_samples

       # Transformer architecture configuration
       UpperCamelCase__							:				Union[str, Any]          =      input_size * len(self.lags_sequence							) + self._number_of_features
       UpperCamelCase__							:				Optional[Any]          =      d_model
       UpperCamelCase__							:				Tuple          =      encoder_attention_heads
       UpperCamelCase__							:				Any          =      decoder_attention_heads
       UpperCamelCase__							:				Dict          =      encoder_ffn_dim
       UpperCamelCase__							:				Optional[Any]          =      decoder_ffn_dim
       UpperCamelCase__							:				str          =      encoder_layers
       UpperCamelCase__							:				Optional[int]          =      decoder_layers

       UpperCamelCase__							:				Optional[Any]          =      dropout
       UpperCamelCase__							:				List[Any]          =      attention_dropout
       UpperCamelCase__							:				Any          =      activation_dropout
       UpperCamelCase__							:				Optional[int]          =      encoder_layerdrop
       UpperCamelCase__							:				Union[str, Any]          =      decoder_layerdrop

       UpperCamelCase__							:				Tuple          =      activation_function
       UpperCamelCase__							:				List[str]          =      init_std

       UpperCamelCase__							:				int          =      use_cache

       # Informer
       UpperCamelCase__							:				Optional[int]          =      attention_type
       UpperCamelCase__							:				Optional[int]          =      sampling_factor
       UpperCamelCase__							:				Dict          =      distil

       super().__init__(is_encoder_decoder=__magic_name__,		**__magic_name__							)




   @property
   def       UpperCamelCase__  (    self							) ->      int:






       """simple docstring"""
       return (
           sum(self.embedding_dimension							)
           + self.num_dynamic_real_features
           + self.num_time_features
           + self.num_static_real_features
           + self.input_size * 2  # the log1p(abs(loc)) and log(scale) features
       )

