


"""simple docstring"""
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       (snake_case__):





							'''simple docstring'''

							__lowercase:						List[Any]							 =      """naver-clova-ix/donut-base-finetuned-docvqa"""
							__lowercase:						List[str]							 =      (
							    """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."""
							)
							__lowercase:						List[str]							 =      """document_qa"""
							__lowercase:						Optional[Any]							 =      AutoProcessor
							__lowercase:						str							 =      VisionEncoderDecoderModel

							__lowercase:						int							 =      ["""image""", """text"""]
							__lowercase:						List[Any]							 =      ["""text"""]



							def __init__(			self							: Tuple						,    *UpperCAmelCase_							: Any						,    **UpperCAmelCase_							: Union[str, Any]    )   ->List[Any]:



														"""simple docstring"""



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

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



							def 						lowerCAmelCase    (			self							: Tuple						,    UpperCAmelCase_							: "Image"						,    UpperCAmelCase_							: str    )   ->Union[str, Any]:



														"""simple docstring"""



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

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



							def 						lowerCAmelCase    (			self							: Tuple						,    UpperCAmelCase_							: List[str]    )   ->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=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 						lowerCAmelCase    (			self							: List[str]						,    UpperCAmelCase_							: int    )   ->Tuple:



														"""simple docstring"""



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

														return sequence["answer"]







"""simple docstring"""
from ...configuration_utils import PretrainedConfig
from ...utils import logging


__SCREAMING_SNAKE_CASE							:      Union[str, Any]						=      logging.get_logger(__name__)

__SCREAMING_SNAKE_CASE							:      int						=      {
    'google/canine-s': 'https://huggingface.co/google/canine-s/resolve/main/config.json',
    # See all CANINE models at https://huggingface.co/models?filter=canine
}





class        __A       (snake_case__):





							'''simple docstring'''

							__lowercase:						List[str]							 =      """canine"""



							def __init__(			self							: Union[str, Any]						,    UpperCAmelCase_							: str=768						,    UpperCAmelCase_							: Union[str, Any]=12						,    UpperCAmelCase_							: Optional[Any]=12						,    UpperCAmelCase_							: Optional[Any]=3_072						,    UpperCAmelCase_							: List[Any]="gelu"						,    UpperCAmelCase_							: int=0.1						,    UpperCAmelCase_							: Any=0.1						,    UpperCAmelCase_							: List[str]=16_384						,    UpperCAmelCase_							: Tuple=16						,    UpperCAmelCase_							: int=0.02						,    UpperCAmelCase_							: Tuple=1E-12						,    UpperCAmelCase_							: str=0						,    UpperCAmelCase_							: int=0XE000						,    UpperCAmelCase_							: Optional[int]=0XE001						,    UpperCAmelCase_							: Dict=4						,    UpperCAmelCase_							: List[Any]=4						,    UpperCAmelCase_							: List[Any]=8						,    UpperCAmelCase_							: Dict=16_384						,    UpperCAmelCase_							: Optional[int]=128						,    **UpperCAmelCase_							: Any						,    )   ->int:



														"""simple docstring"""



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

														snake_case_          =						max_position_embeddings
														snake_case_          =						hidden_size
														snake_case_          =						num_hidden_layers
														snake_case_          =						num_attention_heads
														snake_case_          =						intermediate_size
														snake_case_          =						hidden_act
														snake_case_          =						hidden_dropout_prob
														snake_case_          =						attention_probs_dropout_prob
														snake_case_          =						initializer_range
														snake_case_          =						type_vocab_size
														snake_case_          =						layer_norm_eps

														# Character config:
														snake_case_          =						downsampling_rate
														snake_case_          =						upsampling_kernel_size
														snake_case_          =						num_hash_functions
														snake_case_          =						num_hash_buckets
														snake_case_          =						local_transformer_stride



