





import unittest

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

from .test_pipelines_common import ANY


if is_vision_available():
     from PIL import Image

     from transformers.image_utils import load_image
else:



     class        _SCREAMING_SNAKE_CASE						:







      '''simple docstring'''

      @staticmethod
      def 							SCREAMING_SNAKE_CASE_ (*UpperCAmelCase_    :       Any	,			**UpperCAmelCase_    :       Any)	->Dict:



        '''simple docstring'''



        pass





     def 					lowerCAmelCase_			(	__a		)					->		int:







       """simple docstring"""





       return None


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



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







 '''simple docstring'''
 lowercase_		=      MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING

 @require_pytesseract
 @require_vision
 def 							SCREAMING_SNAKE_CASE_ (self    :       List[Any]	,			UpperCAmelCase_    :       Optional[int]	,			UpperCAmelCase_    :       str	,			UpperCAmelCase_    :       List[Any])	->Optional[Any]:



   '''simple docstring'''



   lowerCamelCase__:				Optional[int]        =pipeline(
       "document-question-answering"	,			model=UpperCAmelCase_	,			tokenizer=UpperCAmelCase_	,			image_processor=UpperCAmelCase_)

   lowerCamelCase__:				List[Any]        =INVOICE_URL
   lowerCamelCase__:				str        =list(zip(*apply_tesseract(load_image(UpperCAmelCase_)	,			UpperCAmelCase_	,			"")))
   lowerCamelCase__:				Optional[int]        ="What is the placebo?"
   lowerCamelCase__:				List[str]        =[
       {
           "image": load_image(UpperCAmelCase_),
           "question": question,
       },
       {
           "image": image,
           "question": question,
       },
       {
           "image": image,
           "question": question,
           "word_boxes": word_boxes,
       },
   ]
   return dqa_pipeline, examples

 def 							SCREAMING_SNAKE_CASE_ (self    :       Tuple	,			UpperCAmelCase_    :       Union[str, Any]	,			UpperCAmelCase_    :       int)	->Dict:



   '''simple docstring'''



   lowerCamelCase__:				Any        =dqa_pipeline(UpperCAmelCase_	,			top_k=2)
   self.assertEqual(
       UpperCAmelCase_	,			[
           [
               {"score": ANY(UpperCAmelCase_), "answer": ANY(UpperCAmelCase_), "start": ANY(UpperCAmelCase_), "end": ANY(UpperCAmelCase_)},
               {"score": ANY(UpperCAmelCase_), "answer": ANY(UpperCAmelCase_), "start": ANY(UpperCAmelCase_), "end": ANY(UpperCAmelCase_)},
           ]
       ]
       * 3	,			)

 @require_torch
 @require_detectrona
 @require_pytesseract
 def 							SCREAMING_SNAKE_CASE_ (self    :       Optional[Any])	->List[Any]:



   '''simple docstring'''



   lowerCamelCase__:				List[Any]        =pipeline("document-question-answering"	,			model="hf-internal-testing/tiny-random-layoutlmv2")
   lowerCamelCase__:				List[Any]        =INVOICE_URL
   lowerCamelCase__:				Any        ="How many cats are there?"

   lowerCamelCase__:				Tuple        =[
       {"score": 0.0001, "answer": "oy 2312/2019", "start": 38, "end": 39},
       {"score": 0.0001, "answer": "oy 2312/2019 DUE", "start": 38, "end": 40},
   ]
   lowerCamelCase__:				Optional[Any]        =dqa_pipeline(image=UpperCAmelCase_	,			question=UpperCAmelCase_	,			top_k=2)
   self.assertEqual(nested_simplify(UpperCAmelCase_	,			decimals=4)	,			UpperCAmelCase_)

   lowerCamelCase__:				Union[str, Any]        =dqa_pipeline({"image": image, "question": question}	,			top_k=2)
   self.assertEqual(nested_simplify(UpperCAmelCase_	,			decimals=4)	,			UpperCAmelCase_)

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

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

 @slow
 @require_torch
 @require_detectrona
 @require_pytesseract
 def 							SCREAMING_SNAKE_CASE_ (self    :       Dict)	->Any:



   '''simple docstring'''



   lowerCamelCase__:				Any        =pipeline(
       "document-question-answering"	,			model="tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa"	,			revision="9977165"	,			)
   lowerCamelCase__:				List[str]        =INVOICE_URL
   lowerCamelCase__:				Tuple        ="What is the invoice number?"

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

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

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

 @slow
 @require_torch
 @require_detectrona
 @require_pytesseract
 def 							SCREAMING_SNAKE_CASE_ (self    :       List[str])	->List[str]:



   '''simple docstring'''



   lowerCamelCase__:				Union[str, Any]        =pipeline(
       "document-question-answering"	,			model="tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa"	,			revision="9977165"	,			max_seq_len=50	,			)
   lowerCamelCase__:				Tuple        =INVOICE_URL
   lowerCamelCase__:				List[Any]        ="What is the invoice number?"

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

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

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

 @slow
 @require_torch
 @require_pytesseract
 @require_vision
 def 							SCREAMING_SNAKE_CASE_ (self    :       List[str])	->Dict:



   '''simple docstring'''



   lowerCamelCase__:				str        =AutoTokenizer.from_pretrained(
       "impira/layoutlm-document-qa"	,			revision="3dc6de3"	,			add_prefix_space=UpperCAmelCase_)
   lowerCamelCase__:				Union[str, Any]        =pipeline(
       "document-question-answering"	,			model="impira/layoutlm-document-qa"	,			tokenizer=UpperCAmelCase_	,			revision="3dc6de3"	,			)
   lowerCamelCase__:				Any        =INVOICE_URL
   lowerCamelCase__:				Optional[int]        ="What is the invoice number?"

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

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

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

   lowerCamelCase__:				Any        =list(zip(*apply_tesseract(load_image(UpperCAmelCase_)	,			UpperCAmelCase_	,			"")))

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

 @slow
 @require_torch
 @require_pytesseract
 @require_vision
 def 							SCREAMING_SNAKE_CASE_ (self    :       int)	->Any:



   '''simple docstring'''



   lowerCamelCase__:				List[Any]        =AutoTokenizer.from_pretrained(
       "impira/layoutlm-document-qa"	,			revision="3dc6de3"	,			add_prefix_space=UpperCAmelCase_)
   lowerCamelCase__:				Optional[Any]        =pipeline(
       "document-question-answering"	,			model="impira/layoutlm-document-qa"	,			tokenizer=UpperCAmelCase_	,			revision="3dc6de3"	,			max_seq_len=50	,			)
   lowerCamelCase__:				Optional[int]        =INVOICE_URL
   lowerCamelCase__:				List[Any]        ="What is the invoice number?"

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

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

   lowerCamelCase__:				Any        =list(zip(*apply_tesseract(load_image(UpperCAmelCase_)	,			UpperCAmelCase_	,			"")))

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

 @slow
 @require_torch
 def 							SCREAMING_SNAKE_CASE_ (self    :       List[str])	->Union[str, Any]:



   '''simple docstring'''



   lowerCamelCase__:				Dict        =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__:				Tuple        =INVOICE_URL
   lowerCamelCase__:				Optional[Any]        ="What is the invoice number?"
   lowerCamelCase__:				Optional[Any]        =dqa_pipeline(image=UpperCAmelCase_	,			question=UpperCAmelCase_	,			top_k=2)
   self.assertEqual(nested_simplify(UpperCAmelCase_	,			decimals=4)	,			[{"answer": "us-001"}])







 @require_tf
 @unittest.skip("Document question answering not implemented in TF")
 def 							SCREAMING_SNAKE_CASE_ (self    :       Tuple)	->List[str]:



   '''simple docstring'''



   pass








from __future__ import annotations





def 					lowerCAmelCase_			(	__a     ,   __a		)					->		List[Any]:







  """simple docstring"""





  print(F"""Vertex\tShortest Distance from vertex {src}"""		)
  for i, d in enumerate(__a		):
    print(F"""{i}\t\t{d}"""		)





def 					lowerCAmelCase_			(	__a     ,   __a     ,   __a		)					->		Tuple:







  """simple docstring"""





  for j in range(__a		):
    lowerCamelCase__  , lowerCamelCase__  , lowerCamelCase__:				str        =(graph[j][k] for k in ["src", "dst", "weight"])
    if distance[u] != float("inf"		) and distance[u] + w < distance[v]:
      return True
  return False





def 					lowerCAmelCase_			(	__a     ,   __a     ,   __a     ,   __a		)					->		list[float]:







  """simple docstring"""





  lowerCamelCase__:				List[str]        =[float("inf"		)] * vertex_count
  lowerCamelCase__:				List[str]        =0.0

  for _ in range(vertex_count - 1		):
    for j in range(__a		):
      lowerCamelCase__  , lowerCamelCase__  , lowerCamelCase__:				Union[str, Any]        =(graph[j][k] for k in ["src", "dst", "weight"])

      if distance[u] != float("inf"		) and distance[u] + w < distance[v]:
        lowerCamelCase__:				int        =distance[u] + w

  lowerCamelCase__:				Tuple        =check_negative_cycle(__a     ,   __a     ,   __a		)
  if negative_cycle_exists:
    raise Exception("Negative cycle found"		)

  return distance


if __name__ == "__main__":
     import doctest

     doctest.testmod()

     __A     =    int(input("Enter number of vertices: ").strip())
     __A     =    int(input("Enter number of edges: ").strip())

     __A     =    [{} for _ in range(E)]

     for i in range(E):
          print("Edge ", i + 1)
          __A ,     __A ,     __A     =    (
              int(x)
              for x in input("Enter source, destination, weight: ").strip().split(" ")
          )
          __A     =    {"src": src, "dst": dest, "weight": weight}

     __A     =    int(input("\nEnter shortest path source:").strip())
     __A     =    bellman_ford(graph, V, E, source)
     print_distance(shortest_distance, 0)

