






# 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 _lowercase			(       __lowerCAmelCase	):
							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:       Union[str, Any]    ,							*UpperCamelCase__:       Optional[Any]    ,							**UpperCamelCase__:       int  ):


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

														super().__init__(*_UpperCamelCase    ,							**_UpperCamelCase  )




							def 	lowerCamelCase_       (							self:       List[str]    ,							UpperCamelCase__:       "Image"    ,							UpperCamelCase__:       str  ):
														lowerCamelCase__      :			List[str] 						= """<s_docvqa><s_question>{user_input}</s_question><s_answer>"""
														lowerCamelCase__      :			Optional[int] 						= task_prompt.replace("""{user_input}"""    ,							_UpperCamelCase  )
														lowerCamelCase__      :			Union[str, Any] 						= self.pre_processor.tokenizer(
														    _UpperCamelCase    ,							add_special_tokens=_UpperCamelCase    ,							return_tensors="""pt"""  ).input_ids
														lowerCamelCase__      :			Dict 						= self.pre_processor(_UpperCamelCase    ,							return_tensors="""pt"""  ).pixel_values

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




							def 	lowerCamelCase_       (							self:       int    ,							UpperCamelCase__:       Optional[Any]  ):
														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:       Optional[int]    ,							UpperCamelCase__:       List[Any]  ):
														lowerCamelCase__      :			Optional[int] 						= self.pre_processor.batch_decode(_UpperCamelCase  )[0]
														lowerCamelCase__      :			Dict 						= sequence.replace(self.pre_processor.tokenizer.eos_token    ,							""""""  )
														lowerCamelCase__      :			Optional[int] 						= sequence.replace(self.pre_processor.tokenizer.pad_token    ,							""""""  )
														lowerCamelCase__      :			Optional[int] 						= re.sub(R"""<.*?>"""    ,							""""""    ,							_UpperCamelCase    ,							count=1  ).strip()  # remove first task start token
														lowerCamelCase__      :			List[str] 						= self.pre_processor.tokenajson(_UpperCamelCase  )

														return sequence["answer"]









'''simple docstring'''







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


_A			:    str					  =logging.get_logger(__name__)

_A			:    int					  ={
    '''weiweishi/roc-bert-base-zh''': '''https://huggingface.co/weiweishi/roc-bert-base-zh/resolve/main/config.json''',
}

class _lowercase			(       _lowercase	):
							a          = """roc_bert"""




							def __init__(							self:       Optional[Any]    ,							UpperCamelCase__:       Any=30_522    ,							UpperCamelCase__:       Optional[Any]=768    ,							UpperCamelCase__:       Union[str, Any]=12    ,							UpperCamelCase__:       Tuple=12    ,							UpperCamelCase__:       Tuple=3_072    ,							UpperCamelCase__:       str="gelu"    ,							UpperCamelCase__:       List[Any]=0.1    ,							UpperCamelCase__:       List[str]=0.1    ,							UpperCamelCase__:       Dict=512    ,							UpperCamelCase__:       str=2    ,							UpperCamelCase__:       str=0.02    ,							UpperCamelCase__:       Tuple=1e-12    ,							UpperCamelCase__:       Any=True    ,							UpperCamelCase__:       Union[str, Any]=0    ,							UpperCamelCase__:       List[Any]="absolute"    ,							UpperCamelCase__:       Any=None    ,							UpperCamelCase__:       Any=True    ,							UpperCamelCase__:       Optional[int]=True    ,							UpperCamelCase__:       Union[str, Any]=768    ,							UpperCamelCase__:       int=910    ,							UpperCamelCase__:       Tuple=512    ,							UpperCamelCase__:       int=24_858    ,							UpperCamelCase__:       Optional[Any]=True    ,							**UpperCamelCase__:       Optional[Any]    ,							):
														lowerCamelCase__      :			Optional[Any] 						= vocab_size
														lowerCamelCase__      :			Tuple 						= max_position_embeddings
														lowerCamelCase__      :			List[Any] 						= hidden_size
														lowerCamelCase__      :			int 						= num_hidden_layers
														lowerCamelCase__      :			Tuple 						= num_attention_heads
														lowerCamelCase__      :			Any 						= intermediate_size
														lowerCamelCase__      :			List[str] 						= hidden_act
														lowerCamelCase__      :			str 						= hidden_dropout_prob
														lowerCamelCase__      :			Dict 						= attention_probs_dropout_prob
														lowerCamelCase__      :			Union[str, Any] 						= initializer_range
														lowerCamelCase__      :			Tuple 						= type_vocab_size
														lowerCamelCase__      :			Optional[Any] 						= layer_norm_eps
														lowerCamelCase__      :			List[Any] 						= use_cache
														lowerCamelCase__      :			Tuple 						= enable_pronunciation
														lowerCamelCase__      :			Union[str, Any] 						= enable_shape
														lowerCamelCase__      :			Union[str, Any] 						= pronunciation_embed_dim
														lowerCamelCase__      :			Any 						= pronunciation_vocab_size
														lowerCamelCase__      :			int 						= shape_embed_dim
														lowerCamelCase__      :			Tuple 						= shape_vocab_size
														lowerCamelCase__      :			Optional[Any] 						= concat_input
														lowerCamelCase__      :			str 						= position_embedding_type
														lowerCamelCase__      :			Dict 						= classifier_dropout
														super().__init__(pad_token_id=UpperCamelCase__    ,							**UpperCamelCase__  )

