






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       __lowercase      :







       '''simple docstring'''




       @staticmethod
       def 		lowerCAmelCase_     (				*UpperCamelCase_       :			Optional[Any] ,	**UpperCamelCase_       :			List[str]				):


           """simple docstring"""



           pass



  def 			_SCREAMING_SNAKE_CASE						( __lowercase   :			Union[str, Any]    )						->      str:





      """simple docstring"""

      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.
__a				  =   (
    "https://huggingface.co/spaces/impira/docquery/resolve/2f6c96314dc84dfda62d40de9da55f2f5165d403/invoice.png"
)


@is_pipeline_test
@require_torch
@require_vision
class       __lowercase      (	unittest.TestCase  ):







     '''simple docstring'''
     SCREAMING_SNAKE_CASE   						=				MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING




     @require_pytesseract
     @require_vision
     def 		lowerCAmelCase_     (				self       :			Optional[Any] ,	UpperCamelCase_       :			Optional[int] ,	UpperCamelCase_       :			List[str] ,	UpperCamelCase_       :			List[str]				):


         """simple docstring"""



         __A         =	pipeline(
             """document-question-answering""" ,	model=UpperCamelCase_ ,	tokenizer=UpperCamelCase_ ,	image_processor=UpperCamelCase_				)

         __A         =	INVOICE_URL
         __A         =	list(zip(*apply_tesseract(load_image(UpperCamelCase_				) ,	UpperCamelCase_ ,	""""""				)				)				)
         __A         =	'What is the placebo?'
         __A         =	[
             {
                 '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[int] ,	UpperCamelCase_       :			Dict ,	UpperCamelCase_       :			Union[str, Any]				):


         """simple docstring"""



         __A         =	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"""



         __A         =	pipeline("""document-question-answering""" ,	model="""hf-internal-testing/tiny-random-layoutlmv2"""				)
         __A         =	INVOICE_URL
         __A         =	'How many cats are there?'

         __A         =	[
             {'score': 0.0001, 'answer': 'oy 2312/2019', 'start': 38, 'end': 39},
             {'score': 0.0001, 'answer': 'oy 2312/2019 DUE', 'start': 38, 'end': 40},
         ]
         __A         =	dqa_pipeline(image=UpperCamelCase_ ,	question=UpperCamelCase_ ,	top_k=2				)
         self.assertEqual(nested_simplify(UpperCamelCase_ ,	decimals=4				) ,	UpperCamelCase_				)

         __A         =	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
         __A         =	'./tests/fixtures/tests_samples/COCO/000000039769.png'
         __A         =	dqa_pipeline(image=UpperCamelCase_ ,	question=UpperCamelCase_ ,	top_k=2				)
         self.assertEqual(UpperCamelCase_ ,	[]				)

         # We can optionnally pass directly the words and bounding boxes
         __A         =	'./tests/fixtures/tests_samples/COCO/000000039769.png'
         __A         =	[]
         __A         =	[]
         __A         =	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       :			Optional[int]				):


         """simple docstring"""



         __A         =	pipeline(
             """document-question-answering""" ,	model="""tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa""" ,	revision="""9977165""" ,	)
         __A         =	INVOICE_URL
         __A         =	'What is the invoice number?'

         __A         =	dqa_pipeline(image=UpperCamelCase_ ,	question=UpperCamelCase_ ,	top_k=2				)
         self.assertEqual(
             nested_simplify(UpperCamelCase_ ,	decimals=4				) ,	[
                 {"""score""": 0.9944, """answer""": """us-001""", """start""": 16, """end""": 16},
                 {"""score""": 0.0009, """answer""": """us-001""", """start""": 16, """end""": 16},
             ] ,	)

         __A         =	dqa_pipeline({"""image""": image, """question""": question} ,	top_k=2				)
         self.assertEqual(
             nested_simplify(UpperCamelCase_ ,	decimals=4				) ,	[
                 {"""score""": 0.9944, """answer""": """us-001""", """start""": 16, """end""": 16},
                 {"""score""": 0.0009, """answer""": """us-001""", """start""": 16, """end""": 16},
             ] ,	)

         __A         =	dqa_pipeline(
             [{"""image""": image, """question""": question}, {"""image""": image, """question""": question}] ,	top_k=2				)
         self.assertEqual(
             nested_simplify(UpperCamelCase_ ,	decimals=4				) ,	[
                 [
                     {"""score""": 0.9944, """answer""": """us-001""", """start""": 16, """end""": 16},
                     {"""score""": 0.0009, """answer""": """us-001""", """start""": 16, """end""": 16},
                 ],
             ]
             * 2 ,	)




     @slow
     @require_torch
     @require_detectrona
     @require_pytesseract
     def 		lowerCAmelCase_     (				self       :			str				):


         """simple docstring"""



         __A         =	pipeline(
             """document-question-answering""" ,	model="""tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa""" ,	revision="""9977165""" ,	max_seq_len=50 ,	)
         __A         =	INVOICE_URL
         __A         =	'What is the invoice number?'

         __A         =	dqa_pipeline(image=UpperCamelCase_ ,	question=UpperCamelCase_ ,	top_k=2				)
         self.assertEqual(
             nested_simplify(UpperCamelCase_ ,	decimals=4				) ,	[
                 {"""score""": 0.9974, """answer""": """1110212019""", """start""": 23, """end""": 23},
                 {"""score""": 0.9948, """answer""": """us-001""", """start""": 16, """end""": 16},
             ] ,	)

         __A         =	dqa_pipeline({"""image""": image, """question""": question} ,	top_k=2				)
         self.assertEqual(
             nested_simplify(UpperCamelCase_ ,	decimals=4				) ,	[
                 {"""score""": 0.9974, """answer""": """1110212019""", """start""": 23, """end""": 23},
                 {"""score""": 0.9948, """answer""": """us-001""", """start""": 16, """end""": 16},
             ] ,	)

         __A         =	dqa_pipeline(
             [{"""image""": image, """question""": question}, {"""image""": image, """question""": question}] ,	top_k=2				)
         self.assertEqual(
             nested_simplify(UpperCamelCase_ ,	decimals=4				) ,	[
                 [
                     {"""score""": 0.9974, """answer""": """1110212019""", """start""": 23, """end""": 23},
                     {"""score""": 0.9948, """answer""": """us-001""", """start""": 16, """end""": 16},
                 ]
             ]
             * 2 ,	)




     @slow
     @require_torch
     @require_pytesseract
     @require_vision
     def 		lowerCAmelCase_     (				self       :			str				):


         """simple docstring"""



         __A         =	AutoTokenizer.from_pretrained(
             """impira/layoutlm-document-qa""" ,	revision="""3dc6de3""" ,	add_prefix_space=UpperCamelCase_				)
         __A         =	pipeline(
             """document-question-answering""" ,	model="""impira/layoutlm-document-qa""" ,	tokenizer=UpperCamelCase_ ,	revision="""3dc6de3""" ,	)
         __A         =	INVOICE_URL
         __A         =	'What is the invoice number?'

         __A         =	dqa_pipeline(image=UpperCamelCase_ ,	question=UpperCamelCase_ ,	top_k=2				)
         self.assertEqual(
             nested_simplify(UpperCamelCase_ ,	decimals=4				) ,	[
                 {"""score""": 0.4251, """answer""": """us-001""", """start""": 16, """end""": 16},
                 {"""score""": 0.0819, """answer""": """1110212019""", """start""": 23, """end""": 23},
             ] ,	)

         __A         =	dqa_pipeline({"""image""": image, """question""": question} ,	top_k=2				)
         self.assertEqual(
             nested_simplify(UpperCamelCase_ ,	decimals=4				) ,	[
                 {"""score""": 0.4251, """answer""": """us-001""", """start""": 16, """end""": 16},
                 {"""score""": 0.0819, """answer""": """1110212019""", """start""": 23, """end""": 23},
             ] ,	)

         __A         =	dqa_pipeline(
             [{"""image""": image, """question""": question}, {"""image""": image, """question""": question}] ,	top_k=2				)
         self.assertEqual(
             nested_simplify(UpperCamelCase_ ,	decimals=4				) ,	[
                 [
                     {"""score""": 0.4251, """answer""": """us-001""", """start""": 16, """end""": 16},
                     {"""score""": 0.0819, """answer""": """1110212019""", """start""": 23, """end""": 23},
                 ]
             ]
             * 2 ,	)

         __A         =	list(zip(*apply_tesseract(load_image(UpperCamelCase_				) ,	UpperCamelCase_ ,	""""""				)				)				)

         # This model should also work if `image` is set to None
         __A         =	dqa_pipeline({"""image""": None, """word_boxes""": word_boxes, """question""": question} ,	top_k=2				)
         self.assertEqual(
             nested_simplify(UpperCamelCase_ ,	decimals=4				) ,	[
                 {"""score""": 0.4251, """answer""": """us-001""", """start""": 16, """end""": 16},
                 {"""score""": 0.0819, """answer""": """1110212019""", """start""": 23, """end""": 23},
             ] ,	)




     @slow
     @require_torch
     @require_pytesseract
     @require_vision
     def 		lowerCAmelCase_     (				self       :			List[Any]				):


         """simple docstring"""



         __A         =	AutoTokenizer.from_pretrained(
             """impira/layoutlm-document-qa""" ,	revision="""3dc6de3""" ,	add_prefix_space=UpperCamelCase_				)
         __A         =	pipeline(
             """document-question-answering""" ,	model="""impira/layoutlm-document-qa""" ,	tokenizer=UpperCamelCase_ ,	revision="""3dc6de3""" ,	max_seq_len=50 ,	)
         __A         =	INVOICE_URL
         __A         =	'What is the invoice number?'

         __A         =	dqa_pipeline(image=UpperCamelCase_ ,	question=UpperCamelCase_ ,	top_k=2				)
         self.assertEqual(
             nested_simplify(UpperCamelCase_ ,	decimals=4				) ,	[
                 {"""score""": 0.9999, """answer""": """us-001""", """start""": 16, """end""": 16},
                 {"""score""": 0.9998, """answer""": """us-001""", """start""": 16, """end""": 16},
             ] ,	)

         __A         =	dqa_pipeline(
             [{"""image""": image, """question""": question}, {"""image""": image, """question""": question}] ,	top_k=2				)
         self.assertEqual(
             nested_simplify(UpperCamelCase_ ,	decimals=4				) ,	[
                 [
                     {"""score""": 0.9999, """answer""": """us-001""", """start""": 16, """end""": 16},
                     {"""score""": 0.9998, """answer""": """us-001""", """start""": 16, """end""": 16},
                 ]
             ]
             * 2 ,	)

         __A         =	list(zip(*apply_tesseract(load_image(UpperCamelCase_				) ,	UpperCamelCase_ ,	""""""				)				)				)

         # This model should also work if `image` is set to None
         __A         =	dqa_pipeline({"""image""": None, """word_boxes""": word_boxes, """question""": question} ,	top_k=2				)
         self.assertEqual(
             nested_simplify(UpperCamelCase_ ,	decimals=4				) ,	[
                 {"""score""": 0.9999, """answer""": """us-001""", """start""": 16, """end""": 16},
                 {"""score""": 0.9998, """answer""": """us-001""", """start""": 16, """end""": 16},
             ] ,	)




     @slow
     @require_torch
     def 		lowerCAmelCase_     (				self       :			Union[str, Any]				):


         """simple docstring"""



         __A         =	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""" ,	)

         __A         =	INVOICE_URL
         __A         =	'What is the invoice number?'
         __A         =	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       :			Tuple				):


         """simple docstring"""



         pass












def 			_SCREAMING_SNAKE_CASE						( __lowercase   :			str = "The quick brown fox jumps over the lazy dog"			,				)						->      bool:





    """simple docstring"""

    __A         =	set()

    # Replace all the whitespace in our sentence
    __A         =	input_str.replace(""" """			,				""""""    )
    for alpha in input_str:
        if "a" <= alpha.lower() <= "z":
            frequency.add(alpha.lower()    )
    return len(__lowercase    ) == 2_6



def 			_SCREAMING_SNAKE_CASE						( __lowercase   :			str = "The quick brown fox jumps over the lazy dog"			,				)						->      bool:





    """simple docstring"""

    __A         =	[False] * 2_6
    for char in input_str:
        if char.islower():
            __A         =	True
        elif char.isupper():
            __A         =	True
    return all(__lowercase    )



def 			_SCREAMING_SNAKE_CASE						( __lowercase   :			str = "The quick brown fox jumps over the lazy dog"			,				)						->      bool:





    """simple docstring"""

    return len({char for char in input_str.lower() if char.isalpha()}    ) == 2_6



def 			_SCREAMING_SNAKE_CASE						( )						->      None:





    """simple docstring"""

    from timeit import timeit

    __A         =	"""from __main__ import is_pangram, is_pangram_faster, is_pangram_fastest"""
    print(timeit("""is_pangram()"""			,				setup=__lowercase    )    )
    print(timeit("""is_pangram_faster()"""			,				setup=__lowercase    )    )
    print(timeit("""is_pangram_fastest()"""			,				setup=__lowercase    )    )
    # 5.348480500048026, 2.6477354579837993, 1.8470395830227062
    # 5.036091582966037, 2.644472333951853,  1.8869528750656173


if __name__ == "__main__":
  import doctest

  doctest.testmod()
  benchmark()




