

'''simple docstring'''





import unittest

from transformers import MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING, AutoTokenizer, is_vision_available
from transformers.pipelines import pipeline
from transformers.pipelines.document_question_answering import apply_tesseract
from transformers.testing_utils import (
    is_pipeline_test,
    nested_simplify,
    require_detectrona,
    require_pytesseract,
    require_tf,
    require_torch,
    require_vision,
    slow,
)

from .test_pipelines_common import ANY


if is_vision_available():
							from PIL import Image

							from transformers.image_utils import load_image
else:





							class 		__SCREAMING_SNAKE_CASE							:







											@staticmethod
											def  lowerCamelCase_	(       *UpperCAmelCase__     :		List[Any]		,					**UpperCAmelCase__     :		Optional[int]   ):
																	'''simple docstring'''
																	pass






							def 				_lowerCAmelCase			(   __magic_name__						:     str						)				->  List[str]:
													return None


# This is a pinned image from a specific revision of a document question answering space, hosted by HuggingFace,
# so we can expect it to be available.
UpperCamelCase_    						=       (
    """https://huggingface.co/spaces/impira/docquery/resolve/2f6c96314dc84dfda62d40de9da55f2f5165d403/invoice.png"""
)





@is_pipeline_test
@require_torch
@require_vision
class 		__SCREAMING_SNAKE_CASE							(			unittest.TestCase      ):
				lowerCamelCase_		       =    MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING







				@require_pytesseract
				@require_vision
				def  lowerCamelCase_	(       self     :		str		,					UpperCAmelCase__     :		List[Any]		,					UpperCAmelCase__     :		List[Any]		,					UpperCAmelCase__     :		str   ):
										'''simple docstring'''
										lowercase :							List[Any]    		=pipeline(
										    '''document-question-answering'''		,					model=UpperCAmelCase__		,					tokenizer=UpperCAmelCase__		,					image_processor=UpperCAmelCase__   )

										lowercase :							str    		=INVOICE_URL
										lowercase :							Dict    		=list(zip(*apply_tesseract(load_image(UpperCAmelCase__   )		,					UpperCAmelCase__		,					''''''   )   )   )
										lowercase :							Optional[int]    		='''What is the placebo?'''
										lowercase :							Optional[int]    		=[
										    {
										        '''image''': load_image(UpperCAmelCase__   ),
										        '''question''': question,
										    },
										    {
										        '''image''': image,
										        '''question''': question,
										    },
										    {
										        '''image''': image,
										        '''question''': question,
										        '''word_boxes''': word_boxes,
										    },
										]
										return dqa_pipeline, examples







				def  lowerCamelCase_	(       self     :		Optional[Any]		,					UpperCAmelCase__     :		Union[str, Any]		,					UpperCAmelCase__     :		Optional[int]   ):
										'''simple docstring'''
										lowercase :							Dict    		=dqa_pipeline(UpperCAmelCase__		,					top_k=2   )
										self.assertEqual(
										    UpperCAmelCase__		,					[
										        [
										            {'''score''': ANY(UpperCAmelCase__   ), '''answer''': ANY(UpperCAmelCase__   ), '''start''': ANY(UpperCAmelCase__   ), '''end''': ANY(UpperCAmelCase__   )},
										            {'''score''': ANY(UpperCAmelCase__   ), '''answer''': ANY(UpperCAmelCase__   ), '''start''': ANY(UpperCAmelCase__   ), '''end''': ANY(UpperCAmelCase__   )},
										        ]
										    ]
										    * 3		,					)







				@require_torch
				@require_detectrona
				@require_pytesseract
				def  lowerCamelCase_	(       self     :		List[str]   ):
										'''simple docstring'''
										lowercase :							str    		=pipeline('''document-question-answering'''		,					model='''hf-internal-testing/tiny-random-layoutlmv2'''   )
										lowercase :							List[str]    		=INVOICE_URL
										lowercase :							Tuple    		='''How many cats are there?'''

										lowercase :							str    		=[
										    {'''score''': 0.00_01, '''answer''': '''oy 2312/2019''', '''start''': 38, '''end''': 39},
										    {'''score''': 0.00_01, '''answer''': '''oy 2312/2019 DUE''', '''start''': 38, '''end''': 40},
										]
										lowercase :							Union[str, Any]    		=dqa_pipeline(image=UpperCAmelCase__		,					question=UpperCAmelCase__		,					top_k=2   )
										self.assertEqual(nested_simplify(UpperCAmelCase__		,					decimals=4   )		,					UpperCAmelCase__   )

										lowercase :							Union[str, Any]    		=dqa_pipeline({'''image''': image, '''question''': question}		,					top_k=2   )
										self.assertEqual(nested_simplify(UpperCAmelCase__		,					decimals=4   )		,					UpperCAmelCase__   )

										# This image does not detect ANY text in it, meaning layoutlmv2 should fail.
										# Empty answer probably
										lowercase :							Optional[Any]    		='''./tests/fixtures/tests_samples/COCO/000000039769.png'''
										lowercase :							Any    		=dqa_pipeline(image=UpperCAmelCase__		,					question=UpperCAmelCase__		,					top_k=2   )
										self.assertEqual(UpperCAmelCase__		,					[]   )

										# We can optionnally pass directly the words and bounding boxes
										lowercase :							Optional[Any]    		='''./tests/fixtures/tests_samples/COCO/000000039769.png'''
										lowercase :							Dict    		=[]
										lowercase :							List[Any]    		=[]
										lowercase :							Dict    		=dqa_pipeline(image=UpperCAmelCase__		,					question=UpperCAmelCase__		,					words=UpperCAmelCase__		,					boxes=UpperCAmelCase__		,					top_k=2   )
										self.assertEqual(UpperCAmelCase__		,					[]   )







				@slow
				@require_torch
				@require_detectrona
				@require_pytesseract
				def  lowerCamelCase_	(       self     :		Any   ):
										'''simple docstring'''
										lowercase :							List[Any]    		=pipeline(
										    '''document-question-answering'''		,					model='''tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa'''		,					revision='''9977165'''		,					)
										lowercase :							Union[str, Any]    		=INVOICE_URL
										lowercase :							Any    		='''What is the invoice number?'''

										lowercase :							Dict    		=dqa_pipeline(image=UpperCAmelCase__		,					question=UpperCAmelCase__		,					top_k=2   )
										self.assertEqual(
										    nested_simplify(UpperCAmelCase__		,					decimals=4   )		,					[
										        {'''score''': 0.99_44, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
										        {'''score''': 0.00_09, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
										    ]		,					)

										lowercase :							Any    		=dqa_pipeline({'''image''': image, '''question''': question}		,					top_k=2   )
										self.assertEqual(
										    nested_simplify(UpperCAmelCase__		,					decimals=4   )		,					[
										        {'''score''': 0.99_44, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
										        {'''score''': 0.00_09, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
										    ]		,					)

										lowercase :							Any    		=dqa_pipeline(
										    [{'''image''': image, '''question''': question}, {'''image''': image, '''question''': question}]		,					top_k=2   )
										self.assertEqual(
										    nested_simplify(UpperCAmelCase__		,					decimals=4   )		,					[
										        [
										            {'''score''': 0.99_44, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
										            {'''score''': 0.00_09, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
										        ],
										    ]
										    * 2		,					)







				@slow
				@require_torch
				@require_detectrona
				@require_pytesseract
				def  lowerCamelCase_	(       self     :		str   ):
										'''simple docstring'''
										lowercase :							Any    		=pipeline(
										    '''document-question-answering'''		,					model='''tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa'''		,					revision='''9977165'''		,					max_seq_len=50		,					)
										lowercase :							Optional[int]    		=INVOICE_URL
										lowercase :							Dict    		='''What is the invoice number?'''

										lowercase :							Optional[Any]    		=dqa_pipeline(image=UpperCAmelCase__		,					question=UpperCAmelCase__		,					top_k=2   )
										self.assertEqual(
										    nested_simplify(UpperCAmelCase__		,					decimals=4   )		,					[
										        {'''score''': 0.99_74, '''answer''': '''1110212019''', '''start''': 23, '''end''': 23},
										        {'''score''': 0.99_48, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
										    ]		,					)

										lowercase :							Optional[Any]    		=dqa_pipeline({'''image''': image, '''question''': question}		,					top_k=2   )
										self.assertEqual(
										    nested_simplify(UpperCAmelCase__		,					decimals=4   )		,					[
										        {'''score''': 0.99_74, '''answer''': '''1110212019''', '''start''': 23, '''end''': 23},
										        {'''score''': 0.99_48, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
										    ]		,					)

										lowercase :							Optional[Any]    		=dqa_pipeline(
										    [{'''image''': image, '''question''': question}, {'''image''': image, '''question''': question}]		,					top_k=2   )
										self.assertEqual(
										    nested_simplify(UpperCAmelCase__		,					decimals=4   )		,					[
										        [
										            {'''score''': 0.99_74, '''answer''': '''1110212019''', '''start''': 23, '''end''': 23},
										            {'''score''': 0.99_48, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
										        ]
										    ]
										    * 2		,					)







				@slow
				@require_torch
				@require_pytesseract
				@require_vision
				def  lowerCamelCase_	(       self     :		str   ):
										'''simple docstring'''
										lowercase :							Optional[int]    		=AutoTokenizer.from_pretrained(
										    '''impira/layoutlm-document-qa'''		,					revision='''3dc6de3'''		,					add_prefix_space=UpperCAmelCase__   )
										lowercase :							Optional[Any]    		=pipeline(
										    '''document-question-answering'''		,					model='''impira/layoutlm-document-qa'''		,					tokenizer=UpperCAmelCase__		,					revision='''3dc6de3'''		,					)
										lowercase :							Dict    		=INVOICE_URL
										lowercase :							Union[str, Any]    		='''What is the invoice number?'''

										lowercase :							Union[str, Any]    		=dqa_pipeline(image=UpperCAmelCase__		,					question=UpperCAmelCase__		,					top_k=2   )
										self.assertEqual(
										    nested_simplify(UpperCAmelCase__		,					decimals=4   )		,					[
										        {'''score''': 0.42_51, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
										        {'''score''': 0.08_19, '''answer''': '''1110212019''', '''start''': 23, '''end''': 23},
										    ]		,					)

										lowercase :							List[Any]    		=dqa_pipeline({'''image''': image, '''question''': question}		,					top_k=2   )
										self.assertEqual(
										    nested_simplify(UpperCAmelCase__		,					decimals=4   )		,					[
										        {'''score''': 0.42_51, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
										        {'''score''': 0.08_19, '''answer''': '''1110212019''', '''start''': 23, '''end''': 23},
										    ]		,					)

										lowercase :							Dict    		=dqa_pipeline(
										    [{'''image''': image, '''question''': question}, {'''image''': image, '''question''': question}]		,					top_k=2   )
										self.assertEqual(
										    nested_simplify(UpperCAmelCase__		,					decimals=4   )		,					[
										        [
										            {'''score''': 0.42_51, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
										            {'''score''': 0.08_19, '''answer''': '''1110212019''', '''start''': 23, '''end''': 23},
										        ]
										    ]
										    * 2		,					)

										lowercase :							Dict    		=list(zip(*apply_tesseract(load_image(UpperCAmelCase__   )		,					UpperCAmelCase__		,					''''''   )   )   )

										# This model should also work if `image` is set to None
										lowercase :							int    		=dqa_pipeline({'''image''': None, '''word_boxes''': word_boxes, '''question''': question}		,					top_k=2   )
										self.assertEqual(
										    nested_simplify(UpperCAmelCase__		,					decimals=4   )		,					[
										        {'''score''': 0.42_51, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
										        {'''score''': 0.08_19, '''answer''': '''1110212019''', '''start''': 23, '''end''': 23},
										    ]		,					)







				@slow
				@require_torch
				@require_pytesseract
				@require_vision
				def  lowerCamelCase_	(       self     :		Any   ):
										'''simple docstring'''
										lowercase :							List[str]    		=AutoTokenizer.from_pretrained(
										    '''impira/layoutlm-document-qa'''		,					revision='''3dc6de3'''		,					add_prefix_space=UpperCAmelCase__   )
										lowercase :							Any    		=pipeline(
										    '''document-question-answering'''		,					model='''impira/layoutlm-document-qa'''		,					tokenizer=UpperCAmelCase__		,					revision='''3dc6de3'''		,					max_seq_len=50		,					)
										lowercase :							Union[str, Any]    		=INVOICE_URL
										lowercase :							List[str]    		='''What is the invoice number?'''

										lowercase :							Dict    		=dqa_pipeline(image=UpperCAmelCase__		,					question=UpperCAmelCase__		,					top_k=2   )
										self.assertEqual(
										    nested_simplify(UpperCAmelCase__		,					decimals=4   )		,					[
										        {'''score''': 0.99_99, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
										        {'''score''': 0.99_98, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
										    ]		,					)

										lowercase :							Tuple    		=dqa_pipeline(
										    [{'''image''': image, '''question''': question}, {'''image''': image, '''question''': question}]		,					top_k=2   )
										self.assertEqual(
										    nested_simplify(UpperCAmelCase__		,					decimals=4   )		,					[
										        [
										            {'''score''': 0.99_99, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
										            {'''score''': 0.99_98, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
										        ]
										    ]
										    * 2		,					)

										lowercase :							List[Any]    		=list(zip(*apply_tesseract(load_image(UpperCAmelCase__   )		,					UpperCAmelCase__		,					''''''   )   )   )

										# This model should also work if `image` is set to None
										lowercase :							str    		=dqa_pipeline({'''image''': None, '''word_boxes''': word_boxes, '''question''': question}		,					top_k=2   )
										self.assertEqual(
										    nested_simplify(UpperCAmelCase__		,					decimals=4   )		,					[
										        {'''score''': 0.99_99, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
										        {'''score''': 0.99_98, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
										    ]		,					)







				@slow
				@require_torch
				def  lowerCamelCase_	(       self     :		Any   ):
										'''simple docstring'''
										lowercase :							Tuple    		=pipeline(
										    '''document-question-answering'''		,					model='''naver-clova-ix/donut-base-finetuned-docvqa'''		,					tokenizer=AutoTokenizer.from_pretrained('''naver-clova-ix/donut-base-finetuned-docvqa'''   )		,					feature_extractor='''naver-clova-ix/donut-base-finetuned-docvqa'''		,					)

										lowercase :							Tuple    		=INVOICE_URL
										lowercase :							str    		='''What is the invoice number?'''
										lowercase :							str    		=dqa_pipeline(image=UpperCAmelCase__		,					question=UpperCAmelCase__		,					top_k=2   )
										self.assertEqual(nested_simplify(UpperCAmelCase__		,					decimals=4   )		,					[{'''answer''': '''us-001'''}]   )







				@require_tf
				@unittest.skip('''Document question answering not implemented in TF'''   )
				def  lowerCamelCase_	(       self     :		Any   ):
										'''simple docstring'''
										pass









from timeit import timeit

lowerCamelCase		   =			{
    'MALAYALAM': True,
    'String': False,
    'rotor': True,
    'level': True,
    'A': True,
    'BB': True,
    'ABC': False,
    'amanaplanacanalpanama': True,  # "a man a plan a canal panama"
}
# Ensure our test data is valid
assert all((key == key[::-1]) is value for key, value in test_data.items())




def       a_ (       SCREAMING_SNAKE_CASE__   : str	):
       '''simple docstring'''





       _lowerCamelCase			:						Optional[int]            =0
       _lowerCamelCase			:						Union[str, Any]            =len(SCREAMING_SNAKE_CASE__	) - 1
       while start_i < end_i:
              if s[start_i] == s[end_i]:
                     start_i += 1
                     end_i -= 1
              else:
                     return False
       return True




def       a_ (       SCREAMING_SNAKE_CASE__   : str	):
       '''simple docstring'''





       _lowerCamelCase			:						List[str]            =len(SCREAMING_SNAKE_CASE__	) // 2
       _lowerCamelCase			:						Optional[Any]            =len(SCREAMING_SNAKE_CASE__	)

       # We need to traverse till half of the length of string
       # as we can get access of the i'th last element from
       # i'th index.
       # eg: [0,1,2,3,4,5] => 4th index can be accessed
       # with the help of 1st index (i==n-i-1)
       # where n is length of string
       return all(s[i] == s[n - i - 1] for i in range(SCREAMING_SNAKE_CASE__	)	)




def       a_ (       SCREAMING_SNAKE_CASE__   : str	):
       '''simple docstring'''





       if len(SCREAMING_SNAKE_CASE__	) <= 2:
              return True
       if s[0] == s[len(SCREAMING_SNAKE_CASE__	) - 1]:
              return is_palindrome_recursive(s[1:-1]	)
       else:
              return False




def       a_ (       SCREAMING_SNAKE_CASE__   : str	):
       '''simple docstring'''





       return s == s[::-1]




def       a_ (       SCREAMING_SNAKE_CASE__   : str	):
       '''simple docstring'''





       _lowerCamelCase			:						Optional[int]            =F'''all({name}(key) is value for key, value in test_data.items())'''
       _lowerCamelCase			:						List[Any]            =F'''from __main__ import test_data, {name}'''
       _lowerCamelCase			:						Any            =500_000
       _lowerCamelCase			:						Dict            =timeit(stmt=SCREAMING_SNAKE_CASE__						,     setup=SCREAMING_SNAKE_CASE__						,     number=SCREAMING_SNAKE_CASE__	)
       print(F'''{name:<35} finished {number:,} runs in {result:.5f} seconds'''	)


if __name__ == "__main__":
 for key, value in test_data.items():
  assert is_palindrome(key) is is_palindrome_recursive(key)
  assert is_palindrome(key) is is_palindrome_slice(key)
  print(F"""{key:21} {value}""")
 print('a man a plan a canal panama')

 # finished 500,000 runs in 0.46793 seconds
 benchmark_function('is_palindrome_slice')
 # finished 500,000 runs in 0.85234 seconds
 benchmark_function('is_palindrome')
 # finished 500,000 runs in 1.32028 seconds
 benchmark_function('is_palindrome_recursive')
 # finished 500,000 runs in 2.08679 seconds
 benchmark_function('is_palindrome_traversal')


