


'''simple docstring'''







import json
import os
import sys
import tempfile
import unittest
from pathlib import Path
from shutil import copyfile

from huggingface_hub import HfFolder, Repository, create_repo, delete_repo
from requests.exceptions import HTTPError

import transformers
from transformers import (
    CONFIG_MAPPING,
    FEATURE_EXTRACTOR_MAPPING,
    PROCESSOR_MAPPING,
    TOKENIZER_MAPPING,
    AutoConfig,
    AutoFeatureExtractor,
    AutoProcessor,
    AutoTokenizer,
    BertTokenizer,
    ProcessorMixin,
    WavaVecaConfig,
    WavaVecaFeatureExtractor,
    WavaVecaProcessor,
)
from transformers.testing_utils import TOKEN, USER, get_tests_dir, is_staging_test
from transformers.tokenization_utils import TOKENIZER_CONFIG_FILE
from transformers.utils import FEATURE_EXTRACTOR_NAME, is_tokenizers_available


sys.path.append(str(Path(__file__).parent.parent.parent.parent / """utils"""))

from test_module.custom_configuration import CustomConfig  # noqa E402
from test_module.custom_feature_extraction import CustomFeatureExtractor  # noqa E402
from test_module.custom_processing import CustomProcessor  # noqa E402
from test_module.custom_tokenization import CustomTokenizer  # noqa E402


lowerCAmelCase     :  List[Any]											=    get_tests_dir("""fixtures/dummy_feature_extractor_config.json""")
lowerCAmelCase     :  str											=    get_tests_dir("""fixtures/vocab.json""")
lowerCAmelCase     :  int											=    get_tests_dir("""fixtures""")
class 						UpperCamelCase__       (			unittest.TestCase						):



     """simple docstring"""






     __magic_name__           =     ['[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'bla', 'blou']







     def a						(			self ):

            '''simple docstring'''

            _lowerCAmelCase     :				Any       =							0







     def a						(			self ):

            '''simple docstring'''

            _lowerCAmelCase     :				Tuple       =							AutoProcessor.from_pretrained('facebook/wav2vec2-base-960h' )
            self.assertIsInstance(_lowerCamelCase   ,						_lowerCamelCase )







     def a						(			self ):

            '''simple docstring'''

            with tempfile.TemporaryDirectory() as tmpdirname:
                   _lowerCAmelCase     :				Any       =							WavaVecaConfig()
                   _lowerCAmelCase     :				Optional[Any]       =							AutoProcessor.from_pretrained('facebook/wav2vec2-base-960h' )

                   # save in new folder
                   model_config.save_pretrained(_lowerCamelCase )
                   processor.save_pretrained(_lowerCamelCase )

                   _lowerCAmelCase     :				Any       =							AutoProcessor.from_pretrained(_lowerCamelCase )

            self.assertIsInstance(_lowerCamelCase   ,						_lowerCamelCase )







     def a						(			self ):

            '''simple docstring'''

            with tempfile.TemporaryDirectory() as tmpdirname:
                   # copy relevant files
                   copyfile(_lowerCamelCase   ,						os.path.join(_lowerCamelCase   ,						_lowerCamelCase ) )
                   copyfile(_lowerCamelCase   ,						os.path.join(_lowerCamelCase   ,						'vocab.json' ) )

                   _lowerCAmelCase     :				Any       =							AutoProcessor.from_pretrained(_lowerCamelCase )

            self.assertIsInstance(_lowerCamelCase   ,						_lowerCamelCase )







     def a						(			self ):

            '''simple docstring'''

            with tempfile.TemporaryDirectory() as tmpdirname:
                   _lowerCAmelCase     :				Union[str, Any]       =							WavaVecaFeatureExtractor()
                   _lowerCAmelCase     :				Any       =							AutoTokenizer.from_pretrained('facebook/wav2vec2-base-960h' )

                   _lowerCAmelCase     :				Tuple       =							WavaVecaProcessor(_lowerCamelCase   ,						_lowerCamelCase )

                   # save in new folder
                   processor.save_pretrained(_lowerCamelCase )

                   # drop `processor_class` in tokenizer
                   with open(os.path.join(_lowerCamelCase   ,						_lowerCamelCase )   ,						'r' ) as f:
                          _lowerCAmelCase     :				Dict       =							json.load(_lowerCamelCase )
                          config_dict.pop('processor_class' )

                   with open(os.path.join(_lowerCamelCase   ,						_lowerCamelCase )   ,						'w' ) as f:
                          f.write(json.dumps(_lowerCamelCase ) )

                   _lowerCAmelCase     :				Union[str, Any]       =							AutoProcessor.from_pretrained(_lowerCamelCase )

            self.assertIsInstance(_lowerCamelCase   ,						_lowerCamelCase )







     def a						(			self ):

            '''simple docstring'''

            with tempfile.TemporaryDirectory() as tmpdirname:
                   _lowerCAmelCase     :				Union[str, Any]       =							WavaVecaFeatureExtractor()
                   _lowerCAmelCase     :				str       =							AutoTokenizer.from_pretrained('facebook/wav2vec2-base-960h' )

                   _lowerCAmelCase     :				Optional[int]       =							WavaVecaProcessor(_lowerCamelCase   ,						_lowerCamelCase )

                   # save in new folder
                   processor.save_pretrained(_lowerCamelCase )

                   # drop `processor_class` in feature extractor
                   with open(os.path.join(_lowerCamelCase   ,						_lowerCamelCase )   ,						'r' ) as f:
                          _lowerCAmelCase     :				int       =							json.load(_lowerCamelCase )
                          config_dict.pop('processor_class' )

                   with open(os.path.join(_lowerCamelCase   ,						_lowerCamelCase )   ,						'w' ) as f:
                          f.write(json.dumps(_lowerCamelCase ) )

                   _lowerCAmelCase     :				Union[str, Any]       =							AutoProcessor.from_pretrained(_lowerCamelCase )

            self.assertIsInstance(_lowerCamelCase   ,						_lowerCamelCase )







     def a						(			self ):

            '''simple docstring'''

            with tempfile.TemporaryDirectory() as tmpdirname:
                   _lowerCAmelCase     :				Dict       =							WavaVecaConfig(processor_class='Wav2Vec2Processor' )
                   model_config.save_pretrained(_lowerCamelCase )
                   # copy relevant files
                   copyfile(_lowerCamelCase   ,						os.path.join(_lowerCamelCase   ,						'vocab.json' ) )
                   # create emtpy sample processor
                   with open(os.path.join(_lowerCamelCase   ,						_lowerCamelCase )   ,						'w' ) as f:
                          f.write('{}' )

                   _lowerCAmelCase     :				List[Any]       =							AutoProcessor.from_pretrained(_lowerCamelCase )

            self.assertIsInstance(_lowerCamelCase   ,						_lowerCamelCase )







     def a						(			self ):

            '''simple docstring'''

            with self.assertRaises(_lowerCamelCase ):
                   _lowerCAmelCase     :				Optional[int]       =							AutoProcessor.from_pretrained('hf-internal-testing/test_dynamic_processor' )
            # If remote code is disabled, we can't load this config.
            with self.assertRaises(_lowerCamelCase ):
                   _lowerCAmelCase     :				int       =							AutoProcessor.from_pretrained(
                       'hf-internal-testing/test_dynamic_processor'   ,						trust_remote_code=_lowerCamelCase )

            _lowerCAmelCase     :				Tuple       =							AutoProcessor.from_pretrained('hf-internal-testing/test_dynamic_processor'   ,						trust_remote_code=_lowerCamelCase )
            self.assertTrue(processor.special_attribute_present )
            self.assertEqual(processor.__class__.__name__   ,						'NewProcessor' )

            _lowerCAmelCase     :				List[str]       =							processor.feature_extractor
            self.assertTrue(feature_extractor.special_attribute_present )
            self.assertEqual(feature_extractor.__class__.__name__   ,						'NewFeatureExtractor' )

            _lowerCAmelCase     :				Optional[int]       =							processor.tokenizer
            self.assertTrue(tokenizer.special_attribute_present )
            if is_tokenizers_available():
                   self.assertEqual(tokenizer.__class__.__name__   ,						'NewTokenizerFast' )

                   # Test we can also load the slow version
                   _lowerCAmelCase     :				Tuple       =							AutoProcessor.from_pretrained(
                       'hf-internal-testing/test_dynamic_processor'   ,						trust_remote_code=_lowerCamelCase   ,						use_fast=_lowerCamelCase )
                   _lowerCAmelCase     :				Tuple       =							new_processor.tokenizer
                   self.assertTrue(new_tokenizer.special_attribute_present )
                   self.assertEqual(new_tokenizer.__class__.__name__   ,						'NewTokenizer' )
            else:
                   self.assertEqual(tokenizer.__class__.__name__   ,						'NewTokenizer' )







     def a						(			self ):

            '''simple docstring'''

            try:
                   AutoConfig.register('custom'   ,						_lowerCamelCase )
                   AutoFeatureExtractor.register(_lowerCamelCase   ,						_lowerCamelCase )
                   AutoTokenizer.register(_lowerCamelCase   ,						slow_tokenizer_class=_lowerCamelCase )
                   AutoProcessor.register(_lowerCamelCase   ,						_lowerCamelCase )
                   # Trying to register something existing in the Transformers library will raise an error
                   with self.assertRaises(_lowerCamelCase ):
                          AutoProcessor.register(_lowerCamelCase   ,						_lowerCamelCase )

                   # Now that the config is registered, it can be used as any other config with the auto-API
                   _lowerCAmelCase     :				List[str]       =							CustomFeatureExtractor.from_pretrained(_lowerCamelCase )

                   with tempfile.TemporaryDirectory() as tmp_dir:
                          _lowerCAmelCase     :				Optional[Any]       =							os.path.join(_lowerCamelCase   ,						'vocab.txt' )
                          with open(_lowerCamelCase   ,						'w'   ,						encoding='utf-8' ) as vocab_writer:
                                 vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens] ) )
                          _lowerCAmelCase     :				Dict       =							CustomTokenizer(_lowerCamelCase )

                   _lowerCAmelCase     :				List[Any]       =							CustomProcessor(_lowerCamelCase   ,						_lowerCamelCase )

                   with tempfile.TemporaryDirectory() as tmp_dir:
                          processor.save_pretrained(_lowerCamelCase )
                          _lowerCAmelCase     :				Dict       =							AutoProcessor.from_pretrained(_lowerCamelCase )
                          self.assertIsInstance(_lowerCamelCase   ,						_lowerCamelCase )

            finally:
                   if "custom" in CONFIG_MAPPING._extra_content:
                          del CONFIG_MAPPING._extra_content["custom"]
                   if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content:
                          del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig]
                   if CustomConfig in TOKENIZER_MAPPING._extra_content:
                          del TOKENIZER_MAPPING._extra_content[CustomConfig]
                   if CustomConfig in PROCESSOR_MAPPING._extra_content:
                          del PROCESSOR_MAPPING._extra_content[CustomConfig]







     def a						(			self ):

            '''simple docstring'''

            class 						UpperCamelCase__       (			__a						):



                 """simple docstring"""






                 __magic_name__           =     False
            class 						UpperCamelCase__       (			__a						):



                 """simple docstring"""






                 __magic_name__           =     False
            class 						UpperCamelCase__       (			__a						):



                 """simple docstring"""






                 __magic_name__           =     'AutoFeatureExtractor'
                 __magic_name__           =     'AutoTokenizer'
                 __magic_name__           =     False

            try:
                   AutoConfig.register('custom'   ,						_lowerCamelCase )
                   AutoFeatureExtractor.register(_lowerCamelCase   ,						_lowerCamelCase )
                   AutoTokenizer.register(_lowerCamelCase   ,						slow_tokenizer_class=_lowerCamelCase )
                   AutoProcessor.register(_lowerCamelCase   ,						_lowerCamelCase )
                   # If remote code is not set, the default is to use local classes.
                   _lowerCAmelCase     :				Any       =							AutoProcessor.from_pretrained('hf-internal-testing/test_dynamic_processor' )
                   self.assertEqual(processor.__class__.__name__   ,						'NewProcessor' )
                   self.assertFalse(processor.special_attribute_present )
                   self.assertFalse(processor.feature_extractor.special_attribute_present )
                   self.assertFalse(processor.tokenizer.special_attribute_present )

                   # If remote code is disabled, we load the local ones.
                   _lowerCAmelCase     :				str       =							AutoProcessor.from_pretrained(
                       'hf-internal-testing/test_dynamic_processor'   ,						trust_remote_code=_lowerCamelCase )
                   self.assertEqual(processor.__class__.__name__   ,						'NewProcessor' )
                   self.assertFalse(processor.special_attribute_present )
                   self.assertFalse(processor.feature_extractor.special_attribute_present )
                   self.assertFalse(processor.tokenizer.special_attribute_present )

                   # If remote is enabled, we load from the Hub.
                   _lowerCAmelCase     :				List[str]       =							AutoProcessor.from_pretrained(
                       'hf-internal-testing/test_dynamic_processor'   ,						trust_remote_code=_lowerCamelCase )
                   self.assertEqual(processor.__class__.__name__   ,						'NewProcessor' )
                   self.assertTrue(processor.special_attribute_present )
                   self.assertTrue(processor.feature_extractor.special_attribute_present )
                   self.assertTrue(processor.tokenizer.special_attribute_present )

            finally:
                   if "custom" in CONFIG_MAPPING._extra_content:
                          del CONFIG_MAPPING._extra_content["custom"]
                   if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content:
                          del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig]
                   if CustomConfig in TOKENIZER_MAPPING._extra_content:
                          del TOKENIZER_MAPPING._extra_content[CustomConfig]
                   if CustomConfig in PROCESSOR_MAPPING._extra_content:
                          del PROCESSOR_MAPPING._extra_content[CustomConfig]







     def a						(			self ):

            '''simple docstring'''

            _lowerCAmelCase     :				Dict       =							AutoProcessor.from_pretrained('hf-internal-testing/tiny-random-bert' )
            self.assertEqual(processor.__class__.__name__   ,						'BertTokenizerFast' )







     def a						(			self ):

            '''simple docstring'''

            _lowerCAmelCase     :				int       =							AutoProcessor.from_pretrained('hf-internal-testing/tiny-random-convnext' )
            self.assertEqual(processor.__class__.__name__   ,						'ConvNextImageProcessor' )
@is_staging_test
class 						UpperCamelCase__       (			unittest.TestCase						):



     """simple docstring"""






     __magic_name__           =     ['[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'bla', 'blou']







     @classmethod
     def a						(			cls ):

            '''simple docstring'''

            _lowerCAmelCase     :				Tuple       =							TOKEN
            HfFolder.save_token(_lowerCamelCase )







     @classmethod
     def a						(			cls ):

            '''simple docstring'''

            try:
                   delete_repo(token=cls._token   ,						repo_id='test-processor' )
            except HTTPError:
                   pass

            try:
                   delete_repo(token=cls._token   ,						repo_id='valid_org/test-processor-org' )
            except HTTPError:
                   pass

            try:
                   delete_repo(token=cls._token   ,						repo_id='test-dynamic-processor' )
            except HTTPError:
                   pass







     def a						(			self ):

            '''simple docstring'''

            _lowerCAmelCase     :				Optional[int]       =							WavaVecaProcessor.from_pretrained(_lowerCamelCase )
            with tempfile.TemporaryDirectory() as tmp_dir:
                   processor.save_pretrained(
                       os.path.join(_lowerCamelCase   ,						'test-processor' )   ,						push_to_hub=_lowerCamelCase   ,						use_auth_token=self._token )

                   _lowerCAmelCase     :				Union[str, Any]       =							WavaVecaProcessor.from_pretrained(F'{USER}/test-processor' )
                   for k, v in processor.feature_extractor.__dict__.items():
                          self.assertEqual(_lowerCamelCase   ,						getattr(new_processor.feature_extractor   ,						_lowerCamelCase ) )
                   self.assertDictEqual(new_processor.tokenizer.get_vocab()   ,						processor.tokenizer.get_vocab() )







     def a						(			self ):

            '''simple docstring'''

            _lowerCAmelCase     :				int       =							WavaVecaProcessor.from_pretrained(_lowerCamelCase )

            with tempfile.TemporaryDirectory() as tmp_dir:
                   processor.save_pretrained(
                       os.path.join(_lowerCamelCase   ,						'test-processor-org' )   ,						push_to_hub=_lowerCamelCase   ,						use_auth_token=self._token   ,						organization='valid_org'   ,						)

                   _lowerCAmelCase     :				Dict       =							WavaVecaProcessor.from_pretrained('valid_org/test-processor-org' )
                   for k, v in processor.feature_extractor.__dict__.items():
                          self.assertEqual(_lowerCamelCase   ,						getattr(new_processor.feature_extractor   ,						_lowerCamelCase ) )
                   self.assertDictEqual(new_processor.tokenizer.get_vocab()   ,						processor.tokenizer.get_vocab() )







     def a						(			self ):

            '''simple docstring'''

            CustomFeatureExtractor.register_for_auto_class()
            CustomTokenizer.register_for_auto_class()
            CustomProcessor.register_for_auto_class()

            _lowerCAmelCase     :				List[str]       =							CustomFeatureExtractor.from_pretrained(_lowerCamelCase )

            with tempfile.TemporaryDirectory() as tmp_dir:
                   _lowerCAmelCase     :				Optional[int]       =							os.path.join(_lowerCamelCase   ,						'vocab.txt' )
                   with open(_lowerCamelCase   ,						'w'   ,						encoding='utf-8' ) as vocab_writer:
                          vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens] ) )
                   _lowerCAmelCase     :				Dict       =							CustomTokenizer(_lowerCamelCase )

            _lowerCAmelCase     :				Any       =							CustomProcessor(_lowerCamelCase   ,						_lowerCamelCase )

            with tempfile.TemporaryDirectory() as tmp_dir:
                   create_repo(F'{USER}/test-dynamic-processor'   ,						token=self._token )
                   _lowerCAmelCase     :				Union[str, Any]       =							Repository(_lowerCamelCase   ,						clone_from=F'{USER}/test-dynamic-processor'   ,						token=self._token )
                   processor.save_pretrained(_lowerCamelCase )

                   # This has added the proper auto_map field to the feature extractor config
                   self.assertDictEqual(
                       processor.feature_extractor.auto_map   ,						{
                           'AutoFeatureExtractor': 'custom_feature_extraction.CustomFeatureExtractor',
                           'AutoProcessor': 'custom_processing.CustomProcessor',
                       }   ,						)

                   # This has added the proper auto_map field to the tokenizer config
                   with open(os.path.join(_lowerCamelCase   ,						'tokenizer_config.json' ) ) as f:
                          _lowerCAmelCase     :				int       =							json.load(_lowerCamelCase )
                   self.assertDictEqual(
                       tokenizer_config['auto_map']   ,						{
                           'AutoTokenizer': ['custom_tokenization.CustomTokenizer', None],
                           'AutoProcessor': 'custom_processing.CustomProcessor',
                       }   ,						)

                   # The code has been copied from fixtures
                   self.assertTrue(os.path.isfile(os.path.join(_lowerCamelCase   ,						'custom_feature_extraction.py' ) ) )
                   self.assertTrue(os.path.isfile(os.path.join(_lowerCamelCase   ,						'custom_tokenization.py' ) ) )
                   self.assertTrue(os.path.isfile(os.path.join(_lowerCamelCase   ,						'custom_processing.py' ) ) )

                   repo.push_to_hub()

            _lowerCAmelCase     :				Union[str, Any]       =							AutoProcessor.from_pretrained(F'{USER}/test-dynamic-processor'   ,						trust_remote_code=_lowerCamelCase )
            # Can't make an isinstance check because the new_processor is from the CustomProcessor class of a dynamic module
            self.assertEqual(new_processor.__class__.__name__   ,						'CustomProcessor' )


'''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     __UpperCAmelCase       :





   @staticmethod
   def 						UpperCAmelCase_	(	*_lowerCamelCase    ,     **_lowerCamelCase ):
      pass






 def snake_case_      (					__snake_case  :							int)			->					Union[str, Any]:
    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_     :						Any    							=(
    '''https://huggingface.co/spaces/impira/docquery/resolve/2f6c96314dc84dfda62d40de9da55f2f5165d403/invoice.png'''
)


@is_pipeline_test
@require_torch
@require_vision
class     __UpperCAmelCase       ( unittest.TestCase		):
  __A :				Union[str, Any]											= MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING





  @require_pytesseract
  @require_vision
  def 						UpperCAmelCase_	(	self    ,     _lowerCamelCase    ,     _lowerCamelCase    ,     _lowerCamelCase ):
     lowerCAmelCase_			=      pipeline(
         '''document-question-answering'''    ,     model=_lowerCamelCase    ,     tokenizer=_lowerCamelCase    ,     image_processor=_lowerCamelCase )

     lowerCAmelCase_			=      INVOICE_URL
     lowerCAmelCase_			=      list(zip(*apply_tesseract(load_image(_lowerCamelCase )    ,     _lowerCamelCase    ,     '''''' ) ) )
     lowerCAmelCase_			=      '''What is the placebo?'''
     lowerCAmelCase_			=      [
         {
             '''image''': load_image(_lowerCamelCase ),
             '''question''': question,
         },
         {
             '''image''': image,
             '''question''': question,
         },
         {
             '''image''': image,
             '''question''': question,
             '''word_boxes''': word_boxes,
         },
     ]
     return dqa_pipeline, examples





  def 						UpperCAmelCase_	(	self    ,     _lowerCamelCase    ,     _lowerCamelCase ):
     lowerCAmelCase_			=      dqa_pipeline(_lowerCamelCase    ,     top_k=2 )
     self.assertEqual(
         _lowerCamelCase    ,     [
             [
                 {'''score''': ANY(_lowerCamelCase ), '''answer''': ANY(_lowerCamelCase ), '''start''': ANY(_lowerCamelCase ), '''end''': ANY(_lowerCamelCase )},
                 {'''score''': ANY(_lowerCamelCase ), '''answer''': ANY(_lowerCamelCase ), '''start''': ANY(_lowerCamelCase ), '''end''': ANY(_lowerCamelCase )},
             ]
         ]
         * 3    ,     )





  @require_torch
  @require_detectrona
  @require_pytesseract
  def 						UpperCAmelCase_	(	self ):
     lowerCAmelCase_			=      pipeline('''document-question-answering'''    ,     model='''hf-internal-testing/tiny-random-layoutlmv2''' )
     lowerCAmelCase_			=      INVOICE_URL
     lowerCAmelCase_			=      '''How many cats are there?'''

     lowerCAmelCase_			=      [
         {'''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},
     ]
     lowerCAmelCase_			=      dqa_pipeline(image=_lowerCamelCase    ,     question=_lowerCamelCase    ,     top_k=2 )
     self.assertEqual(nested_simplify(_lowerCamelCase    ,     decimals=4 )    ,     _lowerCamelCase )

     lowerCAmelCase_			=      dqa_pipeline({'''image''': image, '''question''': question}    ,     top_k=2 )
     self.assertEqual(nested_simplify(_lowerCamelCase    ,     decimals=4 )    ,     _lowerCamelCase )

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

     # We can optionnally pass directly the words and bounding boxes
     lowerCAmelCase_			=      '''./tests/fixtures/tests_samples/COCO/000000039769.png'''
     lowerCAmelCase_			=      []
     lowerCAmelCase_			=      []
     lowerCAmelCase_			=      dqa_pipeline(image=_lowerCamelCase    ,     question=_lowerCamelCase    ,     words=_lowerCamelCase    ,     boxes=_lowerCamelCase    ,     top_k=2 )
     self.assertEqual(_lowerCamelCase    ,     [] )





  @slow
  @require_torch
  @require_detectrona
  @require_pytesseract
  def 						UpperCAmelCase_	(	self ):
     lowerCAmelCase_			=      pipeline(
         '''document-question-answering'''    ,     model='''tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa'''    ,     revision='''9977165'''    ,     )
     lowerCAmelCase_			=      INVOICE_URL
     lowerCAmelCase_			=      '''What is the invoice number?'''

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

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

     lowerCAmelCase_			=      dqa_pipeline(
         [{'''image''': image, '''question''': question}, {'''image''': image, '''question''': question}]    ,     top_k=2 )
     self.assertEqual(
         nested_simplify(_lowerCamelCase    ,     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 						UpperCAmelCase_	(	self ):
     lowerCAmelCase_			=      pipeline(
         '''document-question-answering'''    ,     model='''tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa'''    ,     revision='''9977165'''    ,     max_seq_len=50    ,     )
     lowerCAmelCase_			=      INVOICE_URL
     lowerCAmelCase_			=      '''What is the invoice number?'''

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

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

     lowerCAmelCase_			=      dqa_pipeline(
         [{'''image''': image, '''question''': question}, {'''image''': image, '''question''': question}]    ,     top_k=2 )
     self.assertEqual(
         nested_simplify(_lowerCamelCase    ,     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 						UpperCAmelCase_	(	self ):
     lowerCAmelCase_			=      AutoTokenizer.from_pretrained(
         '''impira/layoutlm-document-qa'''    ,     revision='''3dc6de3'''    ,     add_prefix_space=_lowerCamelCase )
     lowerCAmelCase_			=      pipeline(
         '''document-question-answering'''    ,     model='''impira/layoutlm-document-qa'''    ,     tokenizer=_lowerCamelCase    ,     revision='''3dc6de3'''    ,     )
     lowerCAmelCase_			=      INVOICE_URL
     lowerCAmelCase_			=      '''What is the invoice number?'''

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

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

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

     lowerCAmelCase_			=      list(zip(*apply_tesseract(load_image(_lowerCamelCase )    ,     _lowerCamelCase    ,     '''''' ) ) )

     # This model should also work if `image` is set to None
     lowerCAmelCase_			=      dqa_pipeline({'''image''': None, '''word_boxes''': word_boxes, '''question''': question}    ,     top_k=2 )
     self.assertEqual(
         nested_simplify(_lowerCamelCase    ,     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 						UpperCAmelCase_	(	self ):
     lowerCAmelCase_			=      AutoTokenizer.from_pretrained(
         '''impira/layoutlm-document-qa'''    ,     revision='''3dc6de3'''    ,     add_prefix_space=_lowerCamelCase )
     lowerCAmelCase_			=      pipeline(
         '''document-question-answering'''    ,     model='''impira/layoutlm-document-qa'''    ,     tokenizer=_lowerCamelCase    ,     revision='''3dc6de3'''    ,     max_seq_len=50    ,     )
     lowerCAmelCase_			=      INVOICE_URL
     lowerCAmelCase_			=      '''What is the invoice number?'''

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

     lowerCAmelCase_			=      dqa_pipeline(
         [{'''image''': image, '''question''': question}, {'''image''': image, '''question''': question}]    ,     top_k=2 )
     self.assertEqual(
         nested_simplify(_lowerCamelCase    ,     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    ,     )

     lowerCAmelCase_			=      list(zip(*apply_tesseract(load_image(_lowerCamelCase )    ,     _lowerCamelCase    ,     '''''' ) ) )

     # This model should also work if `image` is set to None
     lowerCAmelCase_			=      dqa_pipeline({'''image''': None, '''word_boxes''': word_boxes, '''question''': question}    ,     top_k=2 )
     self.assertEqual(
         nested_simplify(_lowerCamelCase    ,     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 						UpperCAmelCase_	(	self ):
     lowerCAmelCase_			=      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'''    ,     )

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







  @require_tf
  @unittest.skip('''Document question answering not implemented in TF''' )
  def 						UpperCAmelCase_	(	self ):
     pass





