
"""simple docstring"""







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

		A_						:       int				   =	['image', 'text']
		A_						:       Union[str, Any]				   =	['text']

		def __init__(      self       ,		*_SCREAMING_SNAKE_CASE       ,		**_SCREAMING_SNAKE_CASE ):
			if not is_vision_available():
				raise ValueError('Pillow must be installed to use the DocumentQuestionAnsweringTool.' )

			super().__init__(*_SCREAMING_SNAKE_CASE       ,		**_SCREAMING_SNAKE_CASE )

		def 							__lowerCamelCase							(      self       ,		_SCREAMING_SNAKE_CASE       ,		_SCREAMING_SNAKE_CASE ):
			__lowerCAmelCase			:						List[Any]									=      '<s_docvqa><s_question>{user_input}</s_question><s_answer>'
			__lowerCAmelCase			:						Dict									=      task_prompt.replace('{user_input}'       ,		_SCREAMING_SNAKE_CASE )
			__lowerCAmelCase			:						Optional[Any]									=      self.pre_processor.tokenizer(
			    _SCREAMING_SNAKE_CASE       ,		add_special_tokens=_SCREAMING_SNAKE_CASE       ,		return_tensors='pt' ).input_ids
			__lowerCAmelCase			:						List[Any]									=      self.pre_processor(_SCREAMING_SNAKE_CASE       ,		return_tensors='pt' ).pixel_values

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

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







		def 							__lowerCamelCase							(      self       ,		_SCREAMING_SNAKE_CASE ):
			__lowerCAmelCase			:						Optional[Any]									=      self.pre_processor.batch_decode(_SCREAMING_SNAKE_CASE )[0]
			__lowerCAmelCase			:						Any									=      sequence.replace(self.pre_processor.tokenizer.eos_token       ,		'' )
			__lowerCAmelCase			:						List[str]									=      sequence.replace(self.pre_processor.tokenizer.pad_token       ,		'' )
			__lowerCAmelCase			:						Optional[Any]									=      re.sub(R'<.*?>'       ,		''       ,		_SCREAMING_SNAKE_CASE       ,		count=1 ).strip()  # remove first task start token
			__lowerCAmelCase			:						List[str]									=      self.pre_processor.tokenajson(_SCREAMING_SNAKE_CASE )

			return sequence["answer"]







import unittest

from transformers import CamembertTokenizer, CamembertTokenizerFast
from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow
from transformers.utils import is_torch_available

from ...test_tokenization_common import TokenizerTesterMixin


lowerCamelCase       :       Any        =				get_tests_dir('''fixtures/test_sentencepiece.model''')
lowerCamelCase       :       Any        =				get_tests_dir('''fixtures/test_sentencepiece_bpe.model''')

lowerCamelCase       :       Optional[int]        =				'''pt''' if is_torch_available() else '''tf'''

@require_sentencepiece
@require_tokenizers
class 						lowerCAmelCase   (       __a					,				unittest.TestCase	):

					'''simple docstring'''

					_A  :	Dict     =					CamembertTokenizer
					_A  :	Union[str, Any]     =					CamembertTokenizerFast
					_A  :	Union[str, Any]     =					True
					_A  :	Tuple     =					True



					def 					lowerCAmelCase (     self :		Optional[int]							)	->     Optional[int]:


												"""simple docstring"""

												super().setUp()

												# We have a SentencePiece fixture for testing
												__lowercase					:							Union[str, Any]			=   CamembertTokenizer(__a							)
												tokenizer.save_pretrained(self.tmpdirname							)



					def 					lowerCAmelCase (     self :		Optional[int]							)	->     Optional[Any]:


												"""simple docstring"""

												__lowercase					:							Dict			=   """<pad>"""
												__lowercase					:							Dict			=   1

												self.assertEqual(self.get_tokenizer()._convert_token_to_id(__a							)						,   __a							)
												self.assertEqual(self.get_tokenizer()._convert_id_to_token(__a							)						,   __a							)



					def 					lowerCAmelCase (     self :		Optional[Any]							)	->     Tuple:


												"""simple docstring"""

												__lowercase					:							int			=   list(self.get_tokenizer().get_vocab().keys()							)

												self.assertEqual(vocab_keys[0]						,   """<s>NOTUSED"""							)
												self.assertEqual(vocab_keys[1]						,   """<pad>"""							)
												self.assertEqual(vocab_keys[-1]						,   """<mask>"""							)
												self.assertEqual(len(__a							)						,   1004							)



					def 					lowerCAmelCase (     self :		str							)	->     List[Any]:


												"""simple docstring"""

												self.assertEqual(self.get_tokenizer().vocab_size						,   1005							)



					def 					lowerCAmelCase (     self :		Any							)	->     Optional[Any]:


												"""simple docstring"""

												__lowercase					:							Tuple			=   CamembertTokenizer(__a							)
												tokenizer.save_pretrained(self.tmpdirname							)
												__lowercase					:							Tuple			=   CamembertTokenizerFast.from_pretrained(self.tmpdirname							)

												__lowercase					:							List[str]			=   """I was born in 92000, and this is falsé."""

												__lowercase					:							Optional[Any]			=   tokenizer.encode(__a							)
												__lowercase					:							List[Any]			=   rust_tokenizer.encode(__a							)
												self.assertListEqual(__a						,   __a							)

												__lowercase					:							Tuple			=   tokenizer.encode(__a						,   add_special_tokens=__a							)
												__lowercase					:							Union[str, Any]			=   rust_tokenizer.encode(__a						,   add_special_tokens=__a							)
												self.assertListEqual(__a						,   __a							)

												# <unk> tokens are not the same for `rust` than for `slow`.
												# Because spm gives back raw token instead of `unk` in EncodeAsPieces
												# tokens = tokenizer.tokenize(sequence)
												__lowercase					:							Dict			=   tokenizer.convert_ids_to_tokens(__a							)
												__lowercase					:							Any			=   rust_tokenizer.tokenize(__a							)
												self.assertListEqual(__a						,   __a							)



					def 					lowerCAmelCase (     self :		Any							)	->     Dict:


												"""simple docstring"""

												if not self.test_rust_tokenizer:
																			return

												__lowercase					:							List[str]			=   self.get_tokenizer()
												__lowercase					:							Any			=   self.get_rust_tokenizer()

												__lowercase					:							Any			=   """I was born in 92000, and this is falsé."""

												__lowercase					:							Tuple			=   tokenizer.tokenize(__a							)
												__lowercase					:							Optional[Any]			=   rust_tokenizer.tokenize(__a							)
												self.assertListEqual(__a						,   __a							)

												__lowercase					:							Dict			=   tokenizer.encode(__a						,   add_special_tokens=__a							)
												__lowercase					:							Dict			=   rust_tokenizer.encode(__a						,   add_special_tokens=__a							)
												self.assertListEqual(__a						,   __a							)

												__lowercase					:							Any			=   self.get_rust_tokenizer()
												__lowercase					:							str			=   tokenizer.encode(__a							)
												__lowercase					:							Union[str, Any]			=   rust_tokenizer.encode(__a							)
												self.assertListEqual(__a						,   __a							)



					@slow
					def 					lowerCAmelCase (     self :		Optional[int]							)	->     List[Any]:


												"""simple docstring"""

												__lowercase					:							str			=   {"""input_ids""": [[5, 54, 7196, 297, 30, 23, 776, 18, 11, 3215, 3705, 8252, 22, 3164, 1181, 2116, 29, 16, 813, 25, 791, 3314, 20, 3446, 38, 27575, 120, 6, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [5, 468, 17, 11, 9088, 20, 1517, 8, 22804, 18818, 10, 38, 629, 607, 607, 142, 19, 7196, 867, 56, 10326, 24, 2267, 20, 416, 5072, 15612, 233, 734, 7, 2399, 27, 16, 3015, 1649, 7, 24, 20, 4338, 2399, 27, 13, 3400, 14, 13, 6189, 8, 930, 9, 6]], """attention_mask""": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]}  # noqa: E501
												# fmt: on

												# camembert is a french model. So we also use french texts.
												__lowercase					:							List[str]			=   [
												    """Le transformeur est un modèle d'apprentissage profond introduit en 2017, """
												    """utilisé principalement dans le domaine du traitement automatique des langues (TAL).""",
												    """À l'instar des réseaux de neurones récurrents (RNN), les transformeurs sont conçus """
												    """pour gérer des données séquentielles, telles que le langage naturel, pour des tâches """
												    """telles que la traduction et la synthèse de texte.""",
												]

												self.tokenizer_integration_test_util(
												    expected_encoding=__a						,   model_name="""camembert-base"""						,   revision="""3a0641d9a1aeb7e848a74299e7e4c4bca216b4cf"""						,   sequences=__a						,   )