






from ...configuration_utils import PretrainedConfig


UpperCamelCase			    =     {
    '''google/tapas-base-finetuned-sqa''': (
        '''https://huggingface.co/google/tapas-base-finetuned-sqa/resolve/main/config.json'''
    ),
    '''google/tapas-base-finetuned-wtq''': (
        '''https://huggingface.co/google/tapas-base-finetuned-wtq/resolve/main/config.json'''
    ),
    '''google/tapas-base-finetuned-wikisql-supervised''': (
        '''https://huggingface.co/google/tapas-base-finetuned-wikisql-supervised/resolve/main/config.json'''
    ),
    '''google/tapas-base-finetuned-tabfact''': (
        '''https://huggingface.co/google/tapas-base-finetuned-tabfact/resolve/main/config.json'''
    ),
}



class 				__UpperCAmelCase		(_UpperCAmelCase   ):
			__snake_case    :				Union[str, Any]									=							"tapas"







			def __init__(     self:  Optional[Any]				,     UpperCAmelCase_:  int=30_522				,     UpperCAmelCase_:  Any=768				,     UpperCAmelCase_:  int=12				,     UpperCAmelCase_:  Optional[Any]=12				,     UpperCAmelCase_:  Union[str, Any]=3_072				,     UpperCAmelCase_:  Any="gelu"				,     UpperCAmelCase_:  Any=0.1				,     UpperCAmelCase_:  int=0.1				,     UpperCAmelCase_:  Tuple=1_024				,     UpperCAmelCase_:  Union[str, Any]=[3, 256, 256, 2, 256, 256, 10]				,     UpperCAmelCase_:  List[str]=0.02				,     UpperCAmelCase_:  List[str]=1E-12				,     UpperCAmelCase_:  List[Any]=0				,     UpperCAmelCase_:  int=10.0				,     UpperCAmelCase_:  Tuple=0				,     UpperCAmelCase_:  Optional[Any]=1.0				,     UpperCAmelCase_:  List[Any]=None				,     UpperCAmelCase_:  Union[str, Any]=1.0				,     UpperCAmelCase_:  Optional[Any]=False				,     UpperCAmelCase_:  Any=None				,     UpperCAmelCase_:  Optional[int]=1.0				,     UpperCAmelCase_:  Union[str, Any]=1.0				,     UpperCAmelCase_:  List[str]=False				,     UpperCAmelCase_:  Union[str, Any]=False				,     UpperCAmelCase_:  List[str]="ratio"				,     UpperCAmelCase_:  List[Any]=None				,     UpperCAmelCase_:  List[Any]=None				,     UpperCAmelCase_:  Dict=64				,     UpperCAmelCase_:  Union[str, Any]=32				,     UpperCAmelCase_:  Optional[int]=False				,     UpperCAmelCase_:  int=True				,     UpperCAmelCase_:  int=False				,     UpperCAmelCase_:  Union[str, Any]=False				,     UpperCAmelCase_:  List[str]=True				,     UpperCAmelCase_:  Optional[Any]=False				,     UpperCAmelCase_:  Tuple=None				,     UpperCAmelCase_:  int=None				,     **UpperCAmelCase_:  List[Any]				,     ):







									'''simple docstring'''




									super().__init__(pad_token_id=UpperCAmelCase_				,     **UpperCAmelCase_					)

									# BERT hyperparameters (with updated max_position_embeddings and type_vocab_sizes)
									_SCREAMING_SNAKE_CASE     				=  vocab_size
									_SCREAMING_SNAKE_CASE     				=  hidden_size
									_SCREAMING_SNAKE_CASE     				=  num_hidden_layers
									_SCREAMING_SNAKE_CASE     				=  num_attention_heads
									_SCREAMING_SNAKE_CASE     				=  hidden_act
									_SCREAMING_SNAKE_CASE     				=  intermediate_size
									_SCREAMING_SNAKE_CASE     				=  hidden_dropout_prob
									_SCREAMING_SNAKE_CASE     				=  attention_probs_dropout_prob
									_SCREAMING_SNAKE_CASE     				=  max_position_embeddings
									_SCREAMING_SNAKE_CASE     				=  type_vocab_sizes
									_SCREAMING_SNAKE_CASE     				=  initializer_range
									_SCREAMING_SNAKE_CASE     				=  layer_norm_eps

									# Fine-tuning task hyperparameters
									_SCREAMING_SNAKE_CASE     				=  positive_label_weight
									_SCREAMING_SNAKE_CASE     				=  num_aggregation_labels
									_SCREAMING_SNAKE_CASE     				=  aggregation_loss_weight
									_SCREAMING_SNAKE_CASE     				=  use_answer_as_supervision
									_SCREAMING_SNAKE_CASE     				=  answer_loss_importance
									_SCREAMING_SNAKE_CASE     				=  use_normalized_answer_loss
									_SCREAMING_SNAKE_CASE     				=  huber_loss_delta
									_SCREAMING_SNAKE_CASE     				=  temperature
									_SCREAMING_SNAKE_CASE     				=  aggregation_temperature
									_SCREAMING_SNAKE_CASE     				=  use_gumbel_for_cells
									_SCREAMING_SNAKE_CASE     				=  use_gumbel_for_aggregation
									_SCREAMING_SNAKE_CASE     				=  average_approximation_function
									_SCREAMING_SNAKE_CASE     				=  cell_selection_preference
									_SCREAMING_SNAKE_CASE     				=  answer_loss_cutoff
									_SCREAMING_SNAKE_CASE     				=  max_num_rows
									_SCREAMING_SNAKE_CASE     				=  max_num_columns
									_SCREAMING_SNAKE_CASE     				=  average_logits_per_cell
									_SCREAMING_SNAKE_CASE     				=  select_one_column
									_SCREAMING_SNAKE_CASE     				=  allow_empty_column_selection
									_SCREAMING_SNAKE_CASE     				=  init_cell_selection_weights_to_zero
									_SCREAMING_SNAKE_CASE     				=  reset_position_index_per_cell
									_SCREAMING_SNAKE_CASE     				=  disable_per_token_loss

									# Aggregation hyperparameters
									_SCREAMING_SNAKE_CASE     				=  aggregation_labels
									_SCREAMING_SNAKE_CASE     				=  no_aggregation_label_index

									if isinstance(self.aggregation_labels				,     UpperCAmelCase_					):
															_SCREAMING_SNAKE_CASE     				=  {int(UpperCAmelCase_					): v for k, v in aggregation_labels.items()}









# 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		(_UpperCAmelCase   ):
			__snake_case    :				Dict									=							"naver-clova-ix/donut-base-finetuned-docvqa"
			__snake_case    :				Dict									=							(
			    "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."
			)
			__snake_case    :				Dict									=							"document_qa"
			__snake_case    :				Any									=							AutoProcessor
			__snake_case    :				int									=							VisionEncoderDecoderModel

			__snake_case    :				Union[str, Any]									=							["image", "text"]
			__snake_case    :				Optional[int]									=							["text"]







			def __init__(     self:  List[Any]				,     *UpperCAmelCase_:  Optional[int]				,     **UpperCAmelCase_:  List[str]					):







									'''simple docstring'''




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

									super().__init__(*UpperCAmelCase_				,     **UpperCAmelCase_					)







			def 							UpperCamelCase				(     self:  Optional[int]				,     UpperCAmelCase_:  "Image"				,     UpperCAmelCase_:  str					):







									'''simple docstring'''




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

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







			def 							UpperCamelCase				(     self:  Dict				,     UpperCAmelCase_:  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=UpperCAmelCase_				,     pad_token_id=self.pre_processor.tokenizer.pad_token_id				,     eos_token_id=self.pre_processor.tokenizer.eos_token_id				,     use_cache=UpperCAmelCase_				,     num_beams=1				,     bad_words_ids=[[self.pre_processor.tokenizer.unk_token_id]]				,     return_dict_in_generate=UpperCAmelCase_				,     ).sequences







			def 							UpperCamelCase				(     self:  Dict				,     UpperCAmelCase_:  Tuple					):







									'''simple docstring'''




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

									return sequence["answer"]

