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






          @staticmethod
          def    __A  (		*a__    ,					**a__  ):
            pass







     def 							SCREAMING_SNAKE_CASE					(      _lowerCamelCase						:	Optional[Any]     )	->				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.
_a				:		Dict	   =       (
    'https://huggingface.co/spaces/impira/docquery/resolve/2f6c96314dc84dfda62d40de9da55f2f5165d403/invoice.png'
)
@is_pipeline_test
@require_torch
@require_vision
class 						__A							(			unittest.TestCase		):
     _UpperCamelCase							:      str		 =		MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING






     @require_pytesseract
     @require_vision
     def    __A  (		self    ,					a__    ,					a__    ,					a__  ):
       _lowerCAmelCase						:	Optional[int]        =					pipeline(
           """document-question-answering"""    ,					model=a__    ,					tokenizer=a__    ,					image_processor=a__  )

       _lowerCAmelCase						:	Tuple        =					INVOICE_URL
       _lowerCAmelCase						:	List[str]        =					list(zip(*apply_tesseract(load_image(a__  )    ,					a__    ,					""""""  )  )  )
       _lowerCAmelCase						:	Union[str, Any]        =					"""What is the placebo?"""
       _lowerCAmelCase						:	str        =					[
           {
               """image""": load_image(a__  ),
               """question""": question,
           },
           {
               """image""": image,
               """question""": question,
           },
           {
               """image""": image,
               """question""": question,
               """word_boxes""": word_boxes,
           },
       ]
       return dqa_pipeline, examples






     def    __A  (		self    ,					a__    ,					a__  ):
       _lowerCAmelCase						:	List[str]        =					dqa_pipeline(a__    ,					top_k=2  )
       self.assertEqual(
           a__    ,					[
               [
                   {"""score""": ANY(a__  ), """answer""": ANY(a__  ), """start""": ANY(a__  ), """end""": ANY(a__  )},
                   {"""score""": ANY(a__  ), """answer""": ANY(a__  ), """start""": ANY(a__  ), """end""": ANY(a__  )},
               ]
           ]
           * 3    ,					)






     @require_torch
     @require_detectrona
     @require_pytesseract
     def    __A  (		self  ):
       _lowerCAmelCase						:	Tuple        =					pipeline("""document-question-answering"""    ,					model="""hf-internal-testing/tiny-random-layoutlmv2"""  )
       _lowerCAmelCase						:	List[Any]        =					INVOICE_URL
       _lowerCAmelCase						:	Optional[Any]        =					"""How many cats are there?"""

       _lowerCAmelCase						:	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},
       ]
       _lowerCAmelCase						:	Dict        =					dqa_pipeline(image=a__    ,					question=a__    ,					top_k=2  )
       self.assertEqual(nested_simplify(a__    ,					decimals=4  )    ,					a__  )

       _lowerCAmelCase						:	List[str]        =					dqa_pipeline({"""image""": image, """question""": question}    ,					top_k=2  )
       self.assertEqual(nested_simplify(a__    ,					decimals=4  )    ,					a__  )

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

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






     @slow
     @require_torch
     @require_detectrona
     @require_pytesseract
     def    __A  (		self  ):
       _lowerCAmelCase						:	List[str]        =					pipeline(
           """document-question-answering"""    ,					model="""tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa"""    ,					revision="""9977165"""    ,					)
       _lowerCAmelCase						:	int        =					INVOICE_URL
       _lowerCAmelCase						:	Optional[Any]        =					"""What is the invoice number?"""

       _lowerCAmelCase						:	str        =					dqa_pipeline(image=a__    ,					question=a__    ,					top_k=2  )
       self.assertEqual(
           nested_simplify(a__    ,					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},
           ]    ,					)

       _lowerCAmelCase						:	Optional[int]        =					dqa_pipeline({"""image""": image, """question""": question}    ,					top_k=2  )
       self.assertEqual(
           nested_simplify(a__    ,					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},
           ]    ,					)

       _lowerCAmelCase						:	Tuple        =					dqa_pipeline(
           [{"""image""": image, """question""": question}, {"""image""": image, """question""": question}]    ,					top_k=2  )
       self.assertEqual(
           nested_simplify(a__    ,					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    __A  (		self  ):
       _lowerCAmelCase						:	Optional[Any]        =					pipeline(
           """document-question-answering"""    ,					model="""tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa"""    ,					revision="""9977165"""    ,					max_seq_len=50    ,					)
       _lowerCAmelCase						:	Dict        =					INVOICE_URL
       _lowerCAmelCase						:	Union[str, Any]        =					"""What is the invoice number?"""

       _lowerCAmelCase						:	int        =					dqa_pipeline(image=a__    ,					question=a__    ,					top_k=2  )
       self.assertEqual(
           nested_simplify(a__    ,					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},
           ]    ,					)

       _lowerCAmelCase						:	List[str]        =					dqa_pipeline({"""image""": image, """question""": question}    ,					top_k=2  )
       self.assertEqual(
           nested_simplify(a__    ,					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},
           ]    ,					)

       _lowerCAmelCase						:	Dict        =					dqa_pipeline(
           [{"""image""": image, """question""": question}, {"""image""": image, """question""": question}]    ,					top_k=2  )
       self.assertEqual(
           nested_simplify(a__    ,					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    __A  (		self  ):
       _lowerCAmelCase						:	str        =					AutoTokenizer.from_pretrained(
           """impira/layoutlm-document-qa"""    ,					revision="""3dc6de3"""    ,					add_prefix_space=a__  )
       _lowerCAmelCase						:	Tuple        =					pipeline(
           """document-question-answering"""    ,					model="""impira/layoutlm-document-qa"""    ,					tokenizer=a__    ,					revision="""3dc6de3"""    ,					)
       _lowerCAmelCase						:	Optional[int]        =					INVOICE_URL
       _lowerCAmelCase						:	List[Any]        =					"""What is the invoice number?"""

       _lowerCAmelCase						:	int        =					dqa_pipeline(image=a__    ,					question=a__    ,					top_k=2  )
       self.assertEqual(
           nested_simplify(a__    ,					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},
           ]    ,					)

       _lowerCAmelCase						:	int        =					dqa_pipeline({"""image""": image, """question""": question}    ,					top_k=2  )
       self.assertEqual(
           nested_simplify(a__    ,					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},
           ]    ,					)

       _lowerCAmelCase						:	Optional[int]        =					dqa_pipeline(
           [{"""image""": image, """question""": question}, {"""image""": image, """question""": question}]    ,					top_k=2  )
       self.assertEqual(
           nested_simplify(a__    ,					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    ,					)

       _lowerCAmelCase						:	str        =					list(zip(*apply_tesseract(load_image(a__  )    ,					a__    ,					""""""  )  )  )

       # This model should also work if `image` is set to None
       _lowerCAmelCase						:	Optional[Any]        =					dqa_pipeline({"""image""": None, """word_boxes""": word_boxes, """question""": question}    ,					top_k=2  )
       self.assertEqual(
           nested_simplify(a__    ,					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    __A  (		self  ):
       _lowerCAmelCase						:	Optional[int]        =					AutoTokenizer.from_pretrained(
           """impira/layoutlm-document-qa"""    ,					revision="""3dc6de3"""    ,					add_prefix_space=a__  )
       _lowerCAmelCase						:	List[Any]        =					pipeline(
           """document-question-answering"""    ,					model="""impira/layoutlm-document-qa"""    ,					tokenizer=a__    ,					revision="""3dc6de3"""    ,					max_seq_len=50    ,					)
       _lowerCAmelCase						:	Optional[Any]        =					INVOICE_URL
       _lowerCAmelCase						:	Union[str, Any]        =					"""What is the invoice number?"""

       _lowerCAmelCase						:	List[str]        =					dqa_pipeline(image=a__    ,					question=a__    ,					top_k=2  )
       self.assertEqual(
           nested_simplify(a__    ,					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},
           ]    ,					)

       _lowerCAmelCase						:	Union[str, Any]        =					dqa_pipeline(
           [{"""image""": image, """question""": question}, {"""image""": image, """question""": question}]    ,					top_k=2  )
       self.assertEqual(
           nested_simplify(a__    ,					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    ,					)

       _lowerCAmelCase						:	Union[str, Any]        =					list(zip(*apply_tesseract(load_image(a__  )    ,					a__    ,					""""""  )  )  )

       # This model should also work if `image` is set to None
       _lowerCAmelCase						:	int        =					dqa_pipeline({"""image""": None, """word_boxes""": word_boxes, """question""": question}    ,					top_k=2  )
       self.assertEqual(
           nested_simplify(a__    ,					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    __A  (		self  ):
       _lowerCAmelCase						:	str        =					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						:	List[str]        =					INVOICE_URL
       _lowerCAmelCase						:	int        =					"""What is the invoice number?"""
       _lowerCAmelCase						:	List[str]        =					dqa_pipeline(image=a__    ,					question=a__    ,					top_k=2  )
       self.assertEqual(nested_simplify(a__    ,					decimals=4  )    ,					[{"""answer""": """us-001"""}]  )






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





"""simple docstring"""




import contextlib
from multiprocessing import Pool, RLock

from tqdm.auto import tqdm

from ..utils import experimental, logging


_a				:		List[Any]	   =       logging.get_logger(__name__)
class 						__A							:
     _UpperCamelCase							:      str		 =		None







@experimental
def 							SCREAMING_SNAKE_CASE					(      _lowerCamelCase						:	Optional[int]      ,_lowerCamelCase						:	Any      ,_lowerCamelCase						:	Optional[int]      ,_lowerCamelCase						:	List[str]      ,_lowerCamelCase						:	List[Any]      ,_lowerCamelCase						:	Tuple      ,_lowerCamelCase						:	Optional[int]     )	->				List[Any]:
  if ParallelBackendConfig.backend_name is None:
    return _map_with_multiprocessing_pool(
        _lowerCamelCase      ,_lowerCamelCase      ,_lowerCamelCase      ,_lowerCamelCase      ,_lowerCamelCase      ,_lowerCamelCase      ,_lowerCamelCase     )

  return _map_with_joblib(_lowerCamelCase      ,_lowerCamelCase      ,_lowerCamelCase      ,_lowerCamelCase      ,_lowerCamelCase      ,_lowerCamelCase      ,_lowerCamelCase     )





def 							SCREAMING_SNAKE_CASE					(      _lowerCamelCase						:	List[str]      ,_lowerCamelCase						:	Optional[Any]      ,_lowerCamelCase						:	str      ,_lowerCamelCase						:	Tuple      ,_lowerCamelCase						:	Any      ,_lowerCamelCase						:	Optional[int]      ,_lowerCamelCase						:	Tuple     )	->				Union[str, Any]:
  _lowerCAmelCase						:	int        =					num_proc if num_proc <= len(_lowerCamelCase     ) else len(_lowerCamelCase     )
  _lowerCAmelCase						:	Union[str, Any]        =					[]  # We organize the splits ourselve (contiguous splits)
  for index in range(_lowerCamelCase     ):
    _lowerCAmelCase						:	List[str]        =					len(_lowerCamelCase     ) // num_proc
    _lowerCAmelCase						:	str        =					len(_lowerCamelCase     ) % num_proc
    _lowerCAmelCase						:	Tuple        =					div * index + min(_lowerCamelCase      ,_lowerCamelCase     )
    _lowerCAmelCase						:	int        =					start + div + (1 if index < mod else 0)
    split_kwds.append((function, iterable[start:end], types, index, disable_tqdm, desc)     )

  if len(_lowerCamelCase     ) != sum(len(i[1]     ) for i in split_kwds     ):
    raise ValueError(
        f"Error dividing inputs iterable among processes. "
        f"Total number of objects {len(_lowerCamelCase     )}, "
        f"length: {sum(len(i[1]     ) for i in split_kwds     )}"     )

  logger.info(
      f"Spawning {num_proc} processes for {len(_lowerCamelCase     )} objects in slices of {[len(i[1]     ) for i in split_kwds]}"     )
  _lowerCAmelCase      ,     _lowerCAmelCase						:	List[str]        =					None, None
  if not disable_tqdm:
    _lowerCAmelCase      ,     _lowerCAmelCase						:	Optional[Any]        =					(RLock(),), tqdm.set_lock
  with Pool(_lowerCamelCase      ,initargs=_lowerCamelCase      ,initializer=_lowerCamelCase     ) as pool:
    _lowerCAmelCase						:	str        =					pool.map(_lowerCamelCase      ,_lowerCamelCase     )
  logger.info(f"Finished {num_proc} processes"     )
  _lowerCAmelCase						:	int        =					[obj for proc_res in mapped for obj in proc_res]
  logger.info(f"Unpacked {len(_lowerCamelCase     )} objects"     )

  return mapped





def 							SCREAMING_SNAKE_CASE					(      _lowerCamelCase						:	List[str]      ,_lowerCamelCase						:	Union[str, Any]      ,_lowerCamelCase						:	int      ,_lowerCamelCase						:	Dict      ,_lowerCamelCase						:	Tuple      ,_lowerCamelCase						:	Any      ,_lowerCamelCase						:	str     )	->				Optional[Any]:
  # progress bar is not yet supported for _map_with_joblib, because tqdm couldn't accurately be applied to joblib,
  # and it requires monkey-patching joblib internal classes which is subject to change
  import joblib

  with joblib.parallel_backend(ParallelBackendConfig.backend_name      ,n_jobs=_lowerCamelCase     ):
    return joblib.Parallel()(
        joblib.delayed(_lowerCamelCase     )((function, obj, types, None, True, None)     ) for obj in iterable     )






@experimental
@contextlib.contextmanager
def 							SCREAMING_SNAKE_CASE					(      _lowerCamelCase						:	str     )	->				Any:
  _lowerCAmelCase						:	List[Any]        =					backend_name

  if backend_name == "spark":
    from joblibspark import register_spark

    register_spark()

    # TODO: call create_cache_and_write_probe if "download" in steps
    # TODO: raise NotImplementedError when Dataset.map etc is called

  try:
    yield
  finally:
    _lowerCAmelCase						:	Optional[Any]        =					None




