



# 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   _A   ( _lowercase	):


						'''simple docstring'''





						_snake_case			:     Union[str, Any]      							=      """naver-clova-ix/donut-base-finetuned-docvqa"""
						_snake_case			:     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."""
						)
						_snake_case			:     Tuple      							=      """document_qa"""
						_snake_case			:     Tuple      							=      AutoProcessor
						_snake_case			:     int      							=      VisionEncoderDecoderModel

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



						def __init__(	self	:							Tuple							,      *lowerCamelCase	:							int							,      **lowerCamelCase	:							Union[str, Any]	):






							'''simple docstring'''



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

							super().__init__(*lowerCamelCase							,      **lowerCamelCase	)



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






							'''simple docstring'''



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

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



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






							'''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=lowerCamelCase							,      pad_token_id=self.pre_processor.tokenizer.pad_token_id							,      eos_token_id=self.pre_processor.tokenizer.eos_token_id							,      use_cache=lowerCamelCase							,      num_beams=1							,      bad_words_ids=[[self.pre_processor.tokenizer.unk_token_id]]							,      return_dict_in_generate=lowerCamelCase							,      ).sequences



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






							'''simple docstring'''



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

							return sequence["answer"]








from collections import OrderedDict
from typing import Mapping

from packaging import version

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


snake_case__					:     List[Any]    		=   logging.get_logger(__name__)

snake_case__					:     List[str]    		=   {
    """hustvl/yolos-small""": """https://huggingface.co/hustvl/yolos-small/resolve/main/config.json""",
    # See all YOLOS models at https://huggingface.co/models?filter=yolos
}

class   _A   ( _lowercase	):


						'''simple docstring'''





						_snake_case			:     List[Any]      							=      """yolos"""



						def __init__(	self	:							Union[str, Any]							,      lowerCamelCase	:							Union[str, Any]=768							,      lowerCamelCase	:							int=12							,      lowerCamelCase	:							Union[str, Any]=12							,      lowerCamelCase	:							Optional[Any]=3_072							,      lowerCamelCase	:							Optional[int]="gelu"							,      lowerCamelCase	:							Dict=0.0							,      lowerCamelCase	:							Optional[Any]=0.0							,      lowerCamelCase	:							Any=0.02							,      lowerCamelCase	:							Optional[Any]=1e-12							,      lowerCamelCase	:							Optional[Any]=[512, 864]							,      lowerCamelCase	:							str=16							,      lowerCamelCase	:							Dict=3							,      lowerCamelCase	:							str=True							,      lowerCamelCase	:							List[Any]=100							,      lowerCamelCase	:							Dict=True							,      lowerCamelCase	:							Dict=False							,      lowerCamelCase	:							List[str]=1							,      lowerCamelCase	:							str=5							,      lowerCamelCase	:							Any=2							,      lowerCamelCase	:							str=5							,      lowerCamelCase	:							Optional[int]=2							,      lowerCamelCase	:							List[Any]=0.1							,      **lowerCamelCase	:							List[Any]							,      ):






							'''simple docstring'''



							super().__init__(**lowerCamelCase	)

							__lowercase		       =			hidden_size
							__lowercase		       =			num_hidden_layers
							__lowercase		       =			num_attention_heads
							__lowercase		       =			intermediate_size
							__lowercase		       =			hidden_act
							__lowercase		       =			hidden_dropout_prob
							__lowercase		       =			attention_probs_dropout_prob
							__lowercase		       =			initializer_range
							__lowercase		       =			layer_norm_eps
							__lowercase		       =			image_size
							__lowercase		       =			patch_size
							__lowercase		       =			num_channels
							__lowercase		       =			qkv_bias
							__lowercase		       =			num_detection_tokens
							__lowercase		       =			use_mid_position_embeddings
							__lowercase		       =			auxiliary_loss
							# Hungarian matcher
							__lowercase		       =			class_cost
							__lowercase		       =			bbox_cost
							__lowercase		       =			giou_cost
							# Loss coefficients
							__lowercase		       =			bbox_loss_coefficient
							__lowercase		       =			giou_loss_coefficient
							__lowercase		       =			eos_coefficient

class   _A   ( _lowercase	):


						'''simple docstring'''





						_snake_case			:     Dict      							=      version.parse("""1.11"""	)



						@property
						def     _snake_case	(	self	:							Union[str, Any]	):






							'''simple docstring'''



							return OrderedDict(
							    [
							        ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}),
							    ]	)



						@property
						def     _snake_case	(	self	:							str	):






							'''simple docstring'''



							return 1e-4



						@property
						def     _snake_case	(	self	:							Tuple	):






							'''simple docstring'''



							return 12



