


import copy
import fnmatch
import json
import os
import pickle as pkl
import shutil
import sys
import tarfile
import tempfile
from collections import OrderedDict
from contextlib import contextmanager
from functools import partial
from hashlib import shaaaa
from io import BytesIO
from pathlib import Path
from urllib.parse import urlparse
from zipfile import ZipFile, is_zipfile

import cva
import numpy as np
import requests
import wget
from filelock import FileLock
from PIL import Image
from tqdm.auto import tqdm
from yaml import Loader, dump, load


try:
 import torch

 __lowerCAmelCase		       =							True
except ImportError:
 __lowerCAmelCase		       =							False


try:
 from torch.hub import _get_torch_home

 __lowerCAmelCase		       =							_get_torch_home()
except ImportError:
 __lowerCAmelCase		       =							os.path.expanduser(
     os.getenv('''TORCH_HOME''', os.path.join(os.getenv('''XDG_CACHE_HOME''', '''~/.cache'''), '''torch'''))
 )

__lowerCAmelCase		       =							os.path.join(torch_cache_home, '''transformers''')

__lowerCAmelCase		       =							'''https://cdn.huggingface.co'''
__lowerCAmelCase		       =							'''https://s3.amazonaws.com/models.huggingface.co/bert'''
__lowerCAmelCase		       =							'''/'''.join(str(Path(__file__).resolve()).split('''/''')[:-1])
__lowerCAmelCase		       =							os.path.join(PATH, '''config.yaml''')
__lowerCAmelCase		       =							os.path.join(PATH, '''attributes.txt''')
__lowerCAmelCase		       =							os.path.join(PATH, '''objects.txt''')
__lowerCAmelCase		       =							os.getenv('''PYTORCH_PRETRAINED_BERT_CACHE''', default_cache_path)
__lowerCAmelCase		       =							os.getenv('''PYTORCH_TRANSFORMERS_CACHE''', PYTORCH_PRETRAINED_BERT_CACHE)
__lowerCAmelCase		       =							os.getenv('''TRANSFORMERS_CACHE''', PYTORCH_TRANSFORMERS_CACHE)
__lowerCAmelCase		       =							'''pytorch_model.bin'''
__lowerCAmelCase		       =							'''config.yaml'''




def    snake_case_     (  snake_case=OBJECTS			,							snake_case=ATTRIBUTES     )  ->				Optional[Any]:
       lowercase__:   Any  			=   []
       with open(snake_case     ) as f:
              for object in f.readlines():
                     vg_classes.append(object.split(','     )[0].lower().strip()     )

       lowercase__:   Dict  			=   []
       with open(snake_case     ) as f:
              for object in f.readlines():
                     vg_attrs.append(object.split(','     )[0].lower().strip()     )
       return vg_classes, vg_attrs




def    snake_case_     (  snake_case     )  ->				Optional[int]:
       lowercase__:   Dict  			=   OrderedDict()
       with open(snake_case			,							'rb'     ) as f:
              lowercase__:   Dict  			=   pkl.load(snake_case     )['model']
       for k in copy.deepcopy(list(ckp.keys()     )     ):
              lowercase__:   str  			=   ckp.pop(snake_case     )
              if isinstance(snake_case			,							np.ndarray     ):
                     lowercase__:   Optional[Any]  			=   torch.tensor(snake_case     )
              else:
                     assert isinstance(snake_case			,							torch.tensor     ), type(snake_case     )
              lowercase__:   Tuple  			=   v
       return r





class   __a			:
 __lowercase :							Dict        = {}
 def __init__(   self				, lowerCAmelCase__				, lowerCAmelCase__ = "root"				, lowerCAmelCase__=0 )					->				Union[str, Any]:




        '''simple docstring'''
        lowercase__:   Dict  			=   name
        lowercase__:   Optional[Any]  			=   level
        lowercase__:   int  			=   {}
        for k, v in dictionary.items():
               if v is None:
                      raise ValueError()
               lowercase__:   Union[str, Any]  			=   copy.deepcopy(lowerCAmelCase__ )
               lowercase__:   Dict  			=   copy.deepcopy(lowerCAmelCase__ )
               if isinstance(lowerCAmelCase__				, lowerCAmelCase__ ):
                      lowercase__:   str  			=   Config(lowerCAmelCase__				, name=lowerCAmelCase__				, level=level + 1 )
               lowercase__:   Optional[Any]  			=   v
               setattr(self				, lowerCAmelCase__				, lowerCAmelCase__ )

        lowercase__:   int  			=   d
 def __repr__(   self )					->				Any:




        '''simple docstring'''
        return str(list((self._pointer.keys()) ) )
 def __setattr__(   self				, lowerCAmelCase__				, lowerCAmelCase__ )					->				Optional[int]:




        '''simple docstring'''
        lowercase__:   Optional[int]  			=   val
        lowercase__:   Optional[Any]  			=   val
        lowercase__:   Union[str, Any]  			=   key.split('.' )
        lowercase__:   Union[str, Any]  			=   len(lowerCAmelCase__ ) - 1
        lowercase__:   int  			=   self._pointer
        if len(lowerCAmelCase__ ) > 1:
               for i, l in enumerate(lowerCAmelCase__ ):
                      if hasattr(self				, lowerCAmelCase__ ) and isinstance(getattr(self				, lowerCAmelCase__ )				, lowerCAmelCase__ ):
                             setattr(getattr(self				, lowerCAmelCase__ )				, '.'.join(levels[i:] )				, lowerCAmelCase__ )
                      if l == last_level:
                             lowercase__:   List[Any]  			=   val
                      else:
                             lowercase__:   Dict  			=   pointer[l]
 def 		SCREAMING_SNAKE_CASE__   (   self )					->				Optional[Any]:




        '''simple docstring'''
        return self._pointer
 def 		SCREAMING_SNAKE_CASE__   (   self				, lowerCAmelCase__				, lowerCAmelCase__ )					->				Union[str, Any]:




        '''simple docstring'''
        with open(F'{file_name}'				, 'w' ) as stream:
               dump(lowerCAmelCase__				, lowerCAmelCase__ )
 def 		SCREAMING_SNAKE_CASE__   (   self				, lowerCAmelCase__				, lowerCAmelCase__ )					->				Tuple:




        '''simple docstring'''
        with open(F'{file_name}'				, 'w' ) as stream:
               json.dump(lowerCAmelCase__				, lowerCAmelCase__ )
 @staticmethod
 def 		SCREAMING_SNAKE_CASE__   (   lowerCAmelCase__ )					->				Union[str, Any]:




        '''simple docstring'''
        with open(lowerCAmelCase__ ) as stream:
               lowercase__:   Optional[int]  			=   load(lowerCAmelCase__				, Loader=lowerCAmelCase__ )
        return data
 def __str__(   self )					->				Optional[Any]:




        '''simple docstring'''
        lowercase__:   Dict  			=   '    '
        if self._name != "root":
               lowercase__:   Any  			=   F'{t * (self._level-1)}{self._name}:\n'
        else:
               lowercase__:   Dict  			=   ''
        lowercase__:   int  			=   self._level
        for i, (k, v) in enumerate(self._pointer.items() ):
               if isinstance(lowerCAmelCase__				, lowerCAmelCase__ ):
                      r += F'{t * (self._level)}{v}\n'
                      self._level += 1
               else:
                      r += F'{t * (self._level)}{k}: {v} ({type(lowerCAmelCase__ ).__name__})\n'
               lowercase__:   str  			=   level
        return r[:-1]
 @classmethod
 def 		SCREAMING_SNAKE_CASE__   (   cls				, lowerCAmelCase__				, **lowerCAmelCase__ )					->				Tuple:




        '''simple docstring'''
        lowercase__			,						lowercase__:   List[str]  			=   cls.get_config_dict(lowerCAmelCase__				, **lowerCAmelCase__ )
        return cls(lowerCAmelCase__ )
 @classmethod
 def 		SCREAMING_SNAKE_CASE__   (   cls				, lowerCAmelCase__				, **lowerCAmelCase__ )					->				Optional[Any]:




        '''simple docstring'''
        lowercase__:   Optional[int]  			=   kwargs.pop('cache_dir'				, lowerCAmelCase__ )
        lowercase__:   Union[str, Any]  			=   kwargs.pop('force_download'				, lowerCAmelCase__ )
        lowercase__:   List[str]  			=   kwargs.pop('resume_download'				, lowerCAmelCase__ )
        lowercase__:   Optional[int]  			=   kwargs.pop('proxies'				, lowerCAmelCase__ )
        lowercase__:   Dict  			=   kwargs.pop('local_files_only'				, lowerCAmelCase__ )

        if os.path.isdir(lowerCAmelCase__ ):
               lowercase__:   Any  			=   os.path.join(lowerCAmelCase__				, lowerCAmelCase__ )
        elif os.path.isfile(lowerCAmelCase__ ) or is_remote_url(lowerCAmelCase__ ):
               lowercase__:   Optional[Any]  			=   pretrained_model_name_or_path
        else:
               lowercase__:   str  			=   hf_bucket_url(lowerCAmelCase__				, filename=lowerCAmelCase__				, use_cdn=lowerCAmelCase__ )

        try:
               # Load from URL or cache if already cached
               lowercase__:   Any  			=   cached_path(
                   lowerCAmelCase__				, cache_dir=lowerCAmelCase__				, force_download=lowerCAmelCase__				, proxies=lowerCAmelCase__				, resume_download=lowerCAmelCase__				, local_files_only=lowerCAmelCase__				, )
               # Load config dict
               if resolved_config_file is None:
                      raise EnvironmentError

               lowercase__:   List[str]  			=   Config.load_yaml(lowerCAmelCase__ )

        except EnvironmentError:
               lowercase__:   Dict  			=   'Can\'t load config for'
               raise EnvironmentError(lowerCAmelCase__ )

        if resolved_config_file == config_file:
               print('loading configuration file from path' )
        else:
               print('loading configuration file cache' )

        return Config.load_yaml(lowerCAmelCase__ ), kwargs





def    snake_case_     (  snake_case     )  ->				Optional[int]:
       lowercase__:   Optional[Any]  			=   torch.load('dump.pt'			,							map_location=in_tensor.device     )
       lowercase__:   Any  			=   in_tensor.numpy()
       lowercase__:   List[str]  			=   out_tensor.numpy()[0]
       print(na.shape			,							na[0, 0, :5]     )
       print(na.shape			,							na[0, 0, :5]     )
       assert np.allclose(snake_case			,							snake_case			,							rtol=0.0_1			,							atol=0.1     ), (
           f'{sum([1 for x in np.isclose(snake_case			,							snake_case			,							rtol=0.0_1			,							atol=0.1     ).flatten() if x is False]     )/len(na.flatten()     )*1_00:.4f} %'
           " element-wise mismatch"
       )
       raise Exception('tensors are all good'     )

       # Hugging face functions below




def    snake_case_     (  snake_case     )  ->				Any:
       lowercase__:   List[str]  			=   urlparse(snake_case     )
       return parsed.scheme in ("http", "https")




def    snake_case_     (  snake_case			,							snake_case			,							snake_case=True     )  ->				str:
       lowercase__:   Tuple  			=   CLOUDFRONT_DISTRIB_PREFIX if use_cdn else S3_BUCKET_PREFIX
       lowercase__:   List[str]  			=   '/' not in model_id
       if legacy_format:
              return f'{endpoint}/{model_id}-{filename}'
       else:
              return f'{endpoint}/{model_id}/{filename}'




def    snake_case_     (  snake_case			,							snake_case			,							snake_case=None			,							snake_case=0			,							snake_case=None			,							)  ->				Optional[int]:
       lowercase__:   Optional[Any]  			=   'python/{}'.format(sys.version.split()[0]     )
       if _torch_available:
              ua += "; torch/{}".format(torch.__version__     )
       if isinstance(snake_case			,							snake_case     ):
              ua += "; " + "; ".join('{}/{}'.format(snake_case			,							snake_case     ) for k, v in user_agent.items()     )
       elif isinstance(snake_case			,							snake_case     ):
              ua += "; " + user_agent
       lowercase__:   int  			=   {'user-agent': ua}
       if resume_size > 0:
              lowercase__:   Dict  			=   'bytes=%d-' % (resume_size,)
       lowercase__:   str  			=   requests.get(snake_case			,							stream=snake_case			,							proxies=snake_case			,							headers=snake_case     )
       if response.status_code == 4_16:  # Range not satisfiable
              return
       lowercase__:   List[Any]  			=   response.headers.get('Content-Length'     )
       lowercase__:   Tuple  			=   resume_size + int(snake_case     ) if content_length is not None else None
       lowercase__:   List[str]  			=   tqdm(
           unit='B'			,							unit_scale=snake_case			,							total=snake_case			,							initial=snake_case			,							desc='Downloading'			,							)
       for chunk in response.iter_content(chunk_size=10_24     ):
              if chunk:  # filter out keep-alive new chunks
                     progress.update(len(snake_case     )     )
                     temp_file.write(snake_case     )
       progress.close()




def    snake_case_     (  snake_case			,							snake_case=None			,							snake_case=False			,							snake_case=None			,							snake_case=10			,							snake_case=False			,							snake_case=None			,							snake_case=False			,							)  ->				str:
       if cache_dir is None:
              lowercase__:   List[Any]  			=   TRANSFORMERS_CACHE
       if isinstance(snake_case			,							snake_case     ):
              lowercase__:   str  			=   str(snake_case     )

       os.makedirs(snake_case			,							exist_ok=snake_case     )

       lowercase__:   Union[str, Any]  			=   None
       if not local_files_only:
              try:
                     lowercase__:   int  			=   requests.head(snake_case			,							allow_redirects=snake_case			,							proxies=snake_case			,							timeout=snake_case     )
                     if response.status_code == 2_00:
                            lowercase__:   Any  			=   response.headers.get('ETag'     )
              except (EnvironmentError, requests.exceptions.Timeout):
                     # etag is already None
                     pass

       lowercase__:   List[str]  			=   url_to_filename(snake_case			,							snake_case     )

       # get cache path to put the file
       lowercase__:   Any  			=   os.path.join(snake_case			,							snake_case     )

       # etag is None = we don't have a connection, or url doesn't exist, or is otherwise inaccessible.
       # try to get the last downloaded one
       if etag is None:
              if os.path.exists(snake_case     ):
                     return cache_path
              else:
                     lowercase__:   Dict  			=   [
                         file
                         for file in fnmatch.filter(os.listdir(snake_case     )			,							filename + '.*'     )
                         if not file.endswith('.json'     ) and not file.endswith('.lock'     )
                     ]
                     if len(snake_case     ) > 0:
                            return os.path.join(snake_case			,							matching_files[-1]     )
                     else:
                            # If files cannot be found and local_files_only=True,
                            # the models might've been found if local_files_only=False
                            # Notify the user about that
                            if local_files_only:
                                   raise ValueError(
                                       'Cannot find the requested files in the cached path and outgoing traffic has been'
                                       ' disabled. To enable model look-ups and downloads online, set \'local_files_only\''
                                       ' to False.'     )
                            return None

    # From now on, etag is not None.
       if os.path.exists(snake_case     ) and not force_download:
              return cache_path

       # Prevent parallel downloads of the same file with a lock.
       lowercase__:   Union[str, Any]  			=   cache_path + '.lock'
       with FileLock(snake_case     ):
              # If the download just completed while the lock was activated.
              if os.path.exists(snake_case     ) and not force_download:
                     # Even if returning early like here, the lock will be released.
                     return cache_path

              if resume_download:
                     lowercase__:   Tuple  			=   cache_path + '.incomplete'

                     @contextmanager
                     def _resumable_file_manager():
                            with open(snake_case			,							'a+b'     ) as f:
                                   yield f

                     lowercase__:   str  			=   _resumable_file_manager
                     if os.path.exists(snake_case     ):
                            lowercase__:   Any  			=   os.stat(snake_case     ).st_size
                     else:
                            lowercase__:   Tuple  			=   0
              else:
                     lowercase__:   Optional[Any]  			=   partial(tempfile.NamedTemporaryFile			,							dir=snake_case			,							delete=snake_case     )
                     lowercase__:   Any  			=   0

              # Download to temporary file, then copy to cache dir once finished.
              # Otherwise you get corrupt cache entries if the download gets interrupted.
              with temp_file_manager() as temp_file:
                     print(
                         '%s not found in cache or force_download set to True, downloading to %s'			,							snake_case			,							temp_file.name			,							)

                     http_get(
                         snake_case			,							snake_case			,							proxies=snake_case			,							resume_size=snake_case			,							user_agent=snake_case			,							)

              os.replace(temp_file.name			,							snake_case     )

              lowercase__:   int  			=   {'url': url, 'etag': etag}
              lowercase__:   Dict  			=   cache_path + '.json'
              with open(snake_case			,							'w'     ) as meta_file:
                     json.dump(snake_case			,							snake_case     )

       return cache_path




def    snake_case_     (  snake_case			,							snake_case=None     )  ->				Dict:
       lowercase__:   str  			=   url.encode('utf-8'     )
       lowercase__:   Any  			=   shaaaa(snake_case     )
       lowercase__:   str  			=   url_hash.hexdigest()

       if etag:
              lowercase__:   int  			=   etag.encode('utf-8'     )
              lowercase__:   List[Any]  			=   shaaaa(snake_case     )
              filename += "." + etag_hash.hexdigest()

       if url.endswith('.h5'     ):
              filename += ".h5"

       return filename




def    snake_case_     (  snake_case			,							snake_case=None			,							snake_case=False			,							snake_case=None			,							snake_case=False			,							snake_case=None			,							snake_case=False			,							snake_case=False			,							snake_case=False			,							)  ->				int:
       if cache_dir is None:
              lowercase__:   Dict  			=   TRANSFORMERS_CACHE
       if isinstance(snake_case			,							snake_case     ):
              lowercase__:   List[str]  			=   str(snake_case     )
       if isinstance(snake_case			,							snake_case     ):
              lowercase__:   Optional[Any]  			=   str(snake_case     )

       if is_remote_url(snake_case     ):
              # URL, so get it from the cache (downloading if necessary)
              lowercase__:   Tuple  			=   get_from_cache(
                  snake_case			,							cache_dir=snake_case			,							force_download=snake_case			,							proxies=snake_case			,							resume_download=snake_case			,							user_agent=snake_case			,							local_files_only=snake_case			,							)
       elif os.path.exists(snake_case     ):
              # File, and it exists.
              lowercase__:   Optional[Any]  			=   url_or_filename
       elif urlparse(snake_case     ).scheme == "":
              # File, but it doesn't exist.
              raise EnvironmentError('file {} not found'.format(snake_case     )     )
       else:
              # Something unknown
              raise ValueError('unable to parse {} as a URL or as a local path'.format(snake_case     )     )

       if extract_compressed_file:
              if not is_zipfile(snake_case     ) and not tarfile.is_tarfile(snake_case     ):
                     return output_path

              # Path where we extract compressed archives
              # We avoid '.' in dir name and add "-extracted" at the end: "./model.zip" => "./model-zip-extracted/"
              lowercase__			,						lowercase__:   Any  			=   os.path.split(snake_case     )
              lowercase__:   str  			=   output_file.replace('.'			,							'-'     ) + '-extracted'
              lowercase__:   List[Any]  			=   os.path.join(snake_case			,							snake_case     )

              if os.path.isdir(snake_case     ) and os.listdir(snake_case     ) and not force_extract:
                     return output_path_extracted

              # Prevent parallel extractions
              lowercase__:   Tuple  			=   output_path + '.lock'
              with FileLock(snake_case     ):
                     shutil.rmtree(snake_case			,							ignore_errors=snake_case     )
                     os.makedirs(snake_case     )
                     if is_zipfile(snake_case     ):
                            with ZipFile(snake_case			,							'r'     ) as zip_file:
                                   zip_file.extractall(snake_case     )
                                   zip_file.close()
                     elif tarfile.is_tarfile(snake_case     ):
                            lowercase__:   str  			=   tarfile.open(snake_case     )
                            tar_file.extractall(snake_case     )
                            tar_file.close()
                     else:
                            raise EnvironmentError('Archive format of {} could not be identified'.format(snake_case     )     )

              return output_path_extracted

       return output_path




def    snake_case_     (  snake_case			,							snake_case=","     )  ->				Union[str, Any]:
       assert isinstance(snake_case			,							snake_case     )
       if os.path.isfile(snake_case     ):
              with open(snake_case     ) as f:
                     lowercase__:   List[str]  			=   eval(f.read()     )
       else:
              lowercase__:   Tuple  			=   requests.get(snake_case     )
              try:
                     lowercase__:   Optional[Any]  			=   requests.json()
              except Exception:
                     lowercase__:   int  			=   req.content.decode()
                     assert data is not None, "could not connect"
                     try:
                            lowercase__:   Any  			=   eval(snake_case     )
                     except Exception:
                            lowercase__:   int  			=   data.split('\n'     )
              req.close()
       return data




def    snake_case_     (  snake_case     )  ->				int:
       lowercase__:   Optional[int]  			=   requests.get(snake_case     )
       lowercase__:   Tuple  			=   np.array(Image.open(BytesIO(response.content     )     )     )
       return img




def    snake_case_     (  snake_case     )  ->				Tuple:
       lowercase__:   int  			=   url.split('/'     )[-1]
       if fn not in os.listdir(os.getcwd()     ):
              wget.download(snake_case     )
       with open(snake_case			,							'rb'     ) as stream:
              lowercase__:   int  			=   pkl.load(snake_case     )
       lowercase__:   Optional[Any]  			=   weights.pop('model'     )
       lowercase__:   List[str]  			=   {}
       for k, v in model.items():
              lowercase__:   List[Any]  			=   torch.from_numpy(snake_case     )
              if "running_var" in k:
                     lowercase__:   Optional[Any]  			=   torch.tensor([0]     )
                     lowercase__:   str  			=   k.replace('running_var'			,							'num_batches_tracked'     )
                     lowercase__:   List[Any]  			=   zero
       return new




def    snake_case_     (  )  ->				Optional[int]:
       print(f'{os.path.abspath(os.path.join(snake_case			,							os.pardir     )     )}/demo.ipynb'     )




def    snake_case_     (  snake_case			,							snake_case="RGB"     )  ->				Optional[Any]:
       assert isinstance(snake_case			,							snake_case     )
       if os.path.isfile(snake_case     ):
              lowercase__:   Any  			=   cva.imread(snake_case     )
       else:
              lowercase__:   int  			=   get_image_from_url(snake_case     )
              assert img is not None, f'could not connect to: {im}'
       lowercase__:   int  			=   cva.cvtColor(snake_case			,							cva.COLOR_BGR2RGB     )
       if input_format == "RGB":
              lowercase__:   int  			=   img[:, :, ::-1]
       return img




def    snake_case_     (  snake_case			,							snake_case=1     )  ->				Tuple:
       return (images[i : i + batch] for i in range(0			,							len(snake_case     )			,							snake_case     ))






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   __a			:
  @staticmethod
  def 		SCREAMING_SNAKE_CASE__   (   *lowerCAmelCase__				, **lowerCAmelCase__ )					->				List[str]:




         '''simple docstring'''
         pass





 def    snake_case_     (  snake_case     )  ->				Optional[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.
__lowerCAmelCase		       =							(
    '''https://huggingface.co/spaces/impira/docquery/resolve/2f6c96314dc84dfda62d40de9da55f2f5165d403/invoice.png'''
)





@is_pipeline_test
@require_torch
@require_vision
class   __a			(    unittest.TestCase      ):
 __lowercase :							Dict        = MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING
 @require_pytesseract
 @require_vision
 def 		SCREAMING_SNAKE_CASE__   (   self				, lowerCAmelCase__				, lowerCAmelCase__				, lowerCAmelCase__ )					->				int:




        '''simple docstring'''
        lowercase__:   Optional[Any]  			=   pipeline(
            'document-question-answering'				, model=lowerCAmelCase__				, tokenizer=lowerCAmelCase__				, image_processor=lowerCAmelCase__ )

        lowercase__:   int  			=   INVOICE_URL
        lowercase__:   Dict  			=   list(zip(*apply_tesseract(load_image(lowerCAmelCase__ )				, lowerCAmelCase__				, '' ) ) )
        lowercase__:   str  			=   'What is the placebo?'
        lowercase__:   Any  			=   [
            {
                'image': load_image(lowerCAmelCase__ ),
                'question': question,
            },
            {
                'image': image,
                'question': question,
            },
            {
                'image': image,
                'question': question,
                'word_boxes': word_boxes,
            },
        ]
        return dqa_pipeline, examples
 def 		SCREAMING_SNAKE_CASE__   (   self				, lowerCAmelCase__				, lowerCAmelCase__ )					->				int:




        '''simple docstring'''
        lowercase__:   str  			=   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 		SCREAMING_SNAKE_CASE__   (   self )					->				Dict:




        '''simple docstring'''
        lowercase__:   Union[str, Any]  			=   pipeline('document-question-answering'				, model='hf-internal-testing/tiny-random-layoutlmv2' )
        lowercase__:   Optional[Any]  			=   INVOICE_URL
        lowercase__:   int  			=   'How many cats are there?'

        lowercase__:   List[str]  			=   [
            {'score': 0.0_0_0_1, 'answer': 'oy 2312/2019', 'start': 38, 'end': 39},
            {'score': 0.0_0_0_1, 'answer': 'oy 2312/2019 DUE', 'start': 38, 'end': 40},
        ]
        lowercase__:   Dict  			=   dqa_pipeline(image=lowerCAmelCase__				, question=lowerCAmelCase__				, top_k=2 )
        self.assertEqual(nested_simplify(lowerCAmelCase__				, decimals=4 )				, lowerCAmelCase__ )

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

        # We can optionnally pass directly the words and bounding boxes
        lowercase__:   int  			=   './tests/fixtures/tests_samples/COCO/000000039769.png'
        lowercase__:   List[Any]  			=   []
        lowercase__:   Optional[int]  			=   []
        lowercase__:   Any  			=   dqa_pipeline(image=lowerCAmelCase__				, question=lowerCAmelCase__				, words=lowerCAmelCase__				, boxes=lowerCAmelCase__				, top_k=2 )
        self.assertEqual(lowerCAmelCase__				, [] )
 @slow
 @require_torch
 @require_detectrona
 @require_pytesseract
 def 		SCREAMING_SNAKE_CASE__   (   self )					->				Any:




        '''simple docstring'''
        lowercase__:   List[str]  			=   pipeline(
            'document-question-answering'				, model='tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa'				, revision='9977165'				, )
        lowercase__:   int  			=   INVOICE_URL
        lowercase__:   str  			=   'What is the invoice number?'

        lowercase__:   Union[str, Any]  			=   dqa_pipeline(image=lowerCAmelCase__				, question=lowerCAmelCase__				, top_k=2 )
        self.assertEqual(
            nested_simplify(lowerCAmelCase__				, decimals=4 )				, [
                {'score': 0.9_9_4_4, 'answer': 'us-001', 'start': 16, 'end': 16},
                {'score': 0.0_0_0_9, 'answer': 'us-001', 'start': 16, 'end': 16},
            ]				, )

        lowercase__:   Any  			=   dqa_pipeline({'image': image, 'question': question}				, top_k=2 )
        self.assertEqual(
            nested_simplify(lowerCAmelCase__				, decimals=4 )				, [
                {'score': 0.9_9_4_4, 'answer': 'us-001', 'start': 16, 'end': 16},
                {'score': 0.0_0_0_9, 'answer': 'us-001', 'start': 16, 'end': 16},
            ]				, )

        lowercase__:   Optional[int]  			=   dqa_pipeline(
            [{'image': image, 'question': question}, {'image': image, 'question': question}]				, top_k=2 )
        self.assertEqual(
            nested_simplify(lowerCAmelCase__				, decimals=4 )				, [
                [
                    {'score': 0.9_9_4_4, 'answer': 'us-001', 'start': 16, 'end': 16},
                    {'score': 0.0_0_0_9, 'answer': 'us-001', 'start': 16, 'end': 16},
                ],
            ]
            * 2				, )
 @slow
 @require_torch
 @require_detectrona
 @require_pytesseract
 def 		SCREAMING_SNAKE_CASE__   (   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__:   Union[str, Any]  			=   'What is the invoice number?'

        lowercase__:   Optional[Any]  			=   dqa_pipeline(image=lowerCAmelCase__				, question=lowerCAmelCase__				, top_k=2 )
        self.assertEqual(
            nested_simplify(lowerCAmelCase__				, decimals=4 )				, [
                {'score': 0.9_9_7_4, 'answer': '1110212019', 'start': 23, 'end': 23},
                {'score': 0.9_9_4_8, 'answer': 'us-001', 'start': 16, 'end': 16},
            ]				, )

        lowercase__:   Tuple  			=   dqa_pipeline({'image': image, 'question': question}				, top_k=2 )
        self.assertEqual(
            nested_simplify(lowerCAmelCase__				, decimals=4 )				, [
                {'score': 0.9_9_7_4, 'answer': '1110212019', 'start': 23, 'end': 23},
                {'score': 0.9_9_4_8, 'answer': 'us-001', 'start': 16, 'end': 16},
            ]				, )

        lowercase__:   Dict  			=   dqa_pipeline(
            [{'image': image, 'question': question}, {'image': image, 'question': question}]				, top_k=2 )
        self.assertEqual(
            nested_simplify(lowerCAmelCase__				, decimals=4 )				, [
                [
                    {'score': 0.9_9_7_4, 'answer': '1110212019', 'start': 23, 'end': 23},
                    {'score': 0.9_9_4_8, 'answer': 'us-001', 'start': 16, 'end': 16},
                ]
            ]
            * 2				, )
 @slow
 @require_torch
 @require_pytesseract
 @require_vision
 def 		SCREAMING_SNAKE_CASE__   (   self )					->				str:




        '''simple docstring'''
        lowercase__:   Optional[Any]  			=   AutoTokenizer.from_pretrained(
            'impira/layoutlm-document-qa'				, revision='3dc6de3'				, add_prefix_space=lowerCAmelCase__ )
        lowercase__:   Optional[Any]  			=   pipeline(
            'document-question-answering'				, model='impira/layoutlm-document-qa'				, tokenizer=lowerCAmelCase__				, revision='3dc6de3'				, )
        lowercase__:   List[str]  			=   INVOICE_URL
        lowercase__:   Union[str, Any]  			=   'What is the invoice number?'

        lowercase__:   Dict  			=   dqa_pipeline(image=lowerCAmelCase__				, question=lowerCAmelCase__				, top_k=2 )
        self.assertEqual(
            nested_simplify(lowerCAmelCase__				, decimals=4 )				, [
                {'score': 0.4_2_5_1, 'answer': 'us-001', 'start': 16, 'end': 16},
                {'score': 0.0_8_1_9, 'answer': '1110212019', 'start': 23, 'end': 23},
            ]				, )

        lowercase__:   List[str]  			=   dqa_pipeline({'image': image, 'question': question}				, top_k=2 )
        self.assertEqual(
            nested_simplify(lowerCAmelCase__				, decimals=4 )				, [
                {'score': 0.4_2_5_1, 'answer': 'us-001', 'start': 16, 'end': 16},
                {'score': 0.0_8_1_9, 'answer': '1110212019', 'start': 23, 'end': 23},
            ]				, )

        lowercase__:   int  			=   dqa_pipeline(
            [{'image': image, 'question': question}, {'image': image, 'question': question}]				, top_k=2 )
        self.assertEqual(
            nested_simplify(lowerCAmelCase__				, decimals=4 )				, [
                [
                    {'score': 0.4_2_5_1, 'answer': 'us-001', 'start': 16, 'end': 16},
                    {'score': 0.0_8_1_9, 'answer': '1110212019', 'start': 23, 'end': 23},
                ]
            ]
            * 2				, )

        lowercase__:   Any  			=   list(zip(*apply_tesseract(load_image(lowerCAmelCase__ )				, lowerCAmelCase__				, '' ) ) )

        # This model should also work if `image` is set to None
        lowercase__:   List[Any]  			=   dqa_pipeline({'image': None, 'word_boxes': word_boxes, 'question': question}				, top_k=2 )
        self.assertEqual(
            nested_simplify(lowerCAmelCase__				, decimals=4 )				, [
                {'score': 0.4_2_5_1, 'answer': 'us-001', 'start': 16, 'end': 16},
                {'score': 0.0_8_1_9, 'answer': '1110212019', 'start': 23, 'end': 23},
            ]				, )
 @slow
 @require_torch
 @require_pytesseract
 @require_vision
 def 		SCREAMING_SNAKE_CASE__   (   self )					->				Dict:




        '''simple docstring'''
        lowercase__:   Any  			=   AutoTokenizer.from_pretrained(
            'impira/layoutlm-document-qa'				, revision='3dc6de3'				, add_prefix_space=lowerCAmelCase__ )
        lowercase__:   str  			=   pipeline(
            'document-question-answering'				, model='impira/layoutlm-document-qa'				, tokenizer=lowerCAmelCase__				, revision='3dc6de3'				, max_seq_len=50				, )
        lowercase__:   Optional[Any]  			=   INVOICE_URL
        lowercase__:   Optional[Any]  			=   'What is the invoice number?'

        lowercase__:   Optional[int]  			=   dqa_pipeline(image=lowerCAmelCase__				, question=lowerCAmelCase__				, top_k=2 )
        self.assertEqual(
            nested_simplify(lowerCAmelCase__				, decimals=4 )				, [
                {'score': 0.9_9_9_9, 'answer': 'us-001', 'start': 16, 'end': 16},
                {'score': 0.9_9_9_8, '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(lowerCAmelCase__				, decimals=4 )				, [
                [
                    {'score': 0.9_9_9_9, 'answer': 'us-001', 'start': 16, 'end': 16},
                    {'score': 0.9_9_9_8, 'answer': 'us-001', 'start': 16, 'end': 16},
                ]
            ]
            * 2				, )

        lowercase__:   Optional[int]  			=   list(zip(*apply_tesseract(load_image(lowerCAmelCase__ )				, lowerCAmelCase__				, '' ) ) )

        # This model should also work if `image` is set to None
        lowercase__:   Tuple  			=   dqa_pipeline({'image': None, 'word_boxes': word_boxes, 'question': question}				, top_k=2 )
        self.assertEqual(
            nested_simplify(lowerCAmelCase__				, decimals=4 )				, [
                {'score': 0.9_9_9_9, 'answer': 'us-001', 'start': 16, 'end': 16},
                {'score': 0.9_9_9_8, 'answer': 'us-001', 'start': 16, 'end': 16},
            ]				, )
 @slow
 @require_torch
 def 		SCREAMING_SNAKE_CASE__   (   self )					->				Optional[Any]:




        '''simple docstring'''
        lowercase__:   List[Any]  			=   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__:   int  			=   INVOICE_URL
        lowercase__:   int  			=   'What is the invoice number?'
        lowercase__:   Union[str, Any]  			=   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 		SCREAMING_SNAKE_CASE__   (   self )					->				List[str]:




        '''simple docstring'''
        pass


