





"""simple docstring"""




import argparse
import copy






def       _SCREAMING_SNAKE_CASE		(	_lowercase						:    List[Any]					) ->int:






	'''simple docstring'''






	a      :		int	=				{}

	with open(_lowercase					) as f:
		for line in f:
			if line.split()[0] not in dict_of_neighbours:
				a      :		Union[str, Any]	=				[]
				_list.append([line.split()[1], line.split()[2]]					)
				a      :		Dict	=				_list
			else:
				dict_of_neighbours[line.split()[0]].append(
				    [line.split()[1], line.split()[2]]					)
			if line.split()[1] not in dict_of_neighbours:
				a      :		Optional[int]	=				[]
				_list.append([line.split()[0], line.split()[2]]					)
				a      :		Dict	=				_list
			else:
				dict_of_neighbours[line.split()[1]].append(
				    [line.split()[0], line.split()[2]]					)

	return dict_of_neighbours






def       _SCREAMING_SNAKE_CASE		(	_lowercase						:    Optional[Any]    ,       _lowercase						:    List[str]					) ->Optional[int]:






	'''simple docstring'''






	with open(_lowercase					) as f:
		a      :		Union[str, Any]	=				f.read(1					)
	a      :		Optional[Any]	=				start_node

	a      :		List[str]	=				[]

	a      :		Union[str, Any]	=				start_node

	a      :		int	=				0
	while visiting not in first_solution:
		a      :		Optional[int]	=				1_0000
		for k in dict_of_neighbours[visiting]:
			if int(k[1]					) < int(_lowercase					) and k[0] not in first_solution:
				a      :		List[str]	=				k[1]
				a      :		Optional[int]	=				k[0]

		first_solution.append(_lowercase					)
		a      :		Dict	=				distance_of_first_solution + int(_lowercase					)
		a      :		Tuple	=				best_node

	first_solution.append(_lowercase					)

	a      :		Dict	=				0
	for k in dict_of_neighbours[first_solution[-2]]:
		if k[0] == start_node:
			break
		position += 1

	a      :		Union[str, Any]	=				(
	    distance_of_first_solution
	    + int(dict_of_neighbours[first_solution[-2]][position][1]					)
	    - 1_0000
	)
	return first_solution, distance_of_first_solution






def       _SCREAMING_SNAKE_CASE		(	_lowercase						:    Any    ,       _lowercase						:    List[str]					) ->Dict:






	'''simple docstring'''






	a      :		int	=				[]

	for n in solution[1:-1]:
		a      :		int	=				solution.index(_lowercase					)
		for kn in solution[1:-1]:
			a      :		Optional[Any]	=				solution.index(_lowercase					)
			if n == kn:
				continue

			a      :		str	=				copy.deepcopy(_lowercase					)
			a      :		Any	=				kn
			a      :		Tuple	=				n

			a      :		Optional[int]	=				0

			for k in _tmp[:-1]:
				a      :		int	=				_tmp[_tmp.index(_lowercase					) + 1]
				for i in dict_of_neighbours[k]:
					if i[0] == next_node:
						a      :		Optional[Any]	=				distance + int(i[1]					)
			_tmp.append(_lowercase					)

			if _tmp not in neighborhood_of_solution:
				neighborhood_of_solution.append(_tmp					)

	a      :		List[str]	=				len(neighborhood_of_solution[0]					) - 1

	neighborhood_of_solution.sort(key=lambda _lowercase					: x[index_of_last_item_in_the_list]					)
	return neighborhood_of_solution






def       _SCREAMING_SNAKE_CASE		(	_lowercase						:    Any    ,       _lowercase						:    Optional[Any]    ,       _lowercase						:    Union[str, Any]    ,       _lowercase						:    str    ,       _lowercase						:    str					) ->List[str]:






	'''simple docstring'''






	a      :		Optional[int]	=				1
	a      :		int	=				first_solution
	a      :		str	=				[]
	a      :		Any	=				distance_of_first_solution
	a      :		List[str]	=				solution

	while count <= iters:
		a      :		List[Any]	=				find_neighborhood(_lowercase    ,       _lowercase					)
		a      :		Union[str, Any]	=				0
		a      :		List[Any]	=				neighborhood[index_of_best_solution]
		a      :		Dict	=				len(_lowercase					) - 1

		a      :		Optional[Any]	=				False
		while not found:
			a      :		str	=				0
			while i < len(_lowercase					):
				if best_solution[i] != solution[i]:
					a      :		str	=				best_solution[i]
					a      :		int	=				solution[i]
					break
				a      :		Union[str, Any]	=				i + 1

			if [first_exchange_node, second_exchange_node] not in tabu_list and [
			    second_exchange_node,
			    first_exchange_node,
			] not in tabu_list:
				tabu_list.append([first_exchange_node, second_exchange_node]					)
				a      :		Optional[Any]	=				True
				a      :		Optional[Any]	=				best_solution[:-1]
				a      :		Union[str, Any]	=				neighborhood[index_of_best_solution][best_cost_index]
				if cost < best_cost:
					a      :		Any	=				cost
					a      :		List[str]	=				solution
			else:
				a      :		int	=				index_of_best_solution + 1
				a      :		Any	=				neighborhood[index_of_best_solution]

		if len(_lowercase					) >= size:
			tabu_list.pop(0					)

		a      :		Any	=				count + 1

	return best_solution_ever, best_cost






def       _SCREAMING_SNAKE_CASE		(	_lowercase						:    Tuple=None					) ->Union[str, Any]:






	'''simple docstring'''






	a      :		List[Any]	=				generate_neighbours(args.File					)

	a,       a      :		Union[str, Any]	=				generate_first_solution(
	    args.File    ,       _lowercase					)

	a,       a      :		Optional[Any]	=				tabu_search(
	    _lowercase    ,       _lowercase    ,       _lowercase    ,       args.Iterations    ,       args.Size    ,       )

	print(F"""Best solution: {best_sol}, with total distance: {best_cost}."""					)


if __name__ == "__main__":
		a						: Optional[int]     	=			argparse.ArgumentParser(description='''Tabu Search''')
		parser.add_argument(
		    '''-f''',
		    '''--File''',
		    type=str,
		    help='''Path to the file containing the data''',
		    required=True,
		)
		parser.add_argument(
		    '''-i''',
		    '''--Iterations''',
		    type=int,
		    help='''How many iterations the algorithm should perform''',
		    required=True,
		)
		parser.add_argument(
		    '''-s''', '''--Size''', type=int, help='''Size of the tabu list''', required=True
		)

		# Pass the arguments to main method
		main(parser.parse_args())









"""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     __a   (   *lowerCAmelCase__      ,					**lowerCAmelCase__      )	-> str:
										pass






		def       _SCREAMING_SNAKE_CASE		(	_lowercase						:    Tuple					) ->Dict:






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


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






							@require_pytesseract
							@require_vision
							def     __a   (   self      ,					lowerCAmelCase__      ,					lowerCAmelCase__      ,					lowerCAmelCase__      )	-> Tuple:
								a      :		Tuple	=				pipeline(
								    "document-question-answering"      ,					model=lowerCAmelCase__      ,					tokenizer=lowerCAmelCase__      ,					image_processor=lowerCAmelCase__      )

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






							def     __a   (   self      ,					lowerCAmelCase__      ,					lowerCAmelCase__      )	-> Dict:
								a      :		Tuple	=				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     __a   (   self      )	-> List[Any]:
								a      :		List[Any]	=				pipeline("document-question-answering"      ,					model="hf-internal-testing/tiny-random-layoutlmv2"      )
								a      :		Dict	=				INVOICE_URL
								a      :		List[str]	=				"How many cats are there?"

								a      :		Tuple	=				[
								    {"score": 0.0_001, "answer": "oy 2312/2019", "start": 38, "end": 39},
								    {"score": 0.0_001, "answer": "oy 2312/2019 DUE", "start": 38, "end": 40},
								]
								a      :		Optional[int]	=				dqa_pipeline(image=lowerCAmelCase__      ,					question=lowerCAmelCase__      ,					top_k=2      )
								self.assertEqual(nested_simplify(lowerCAmelCase__      ,					decimals=4      )      ,					lowerCAmelCase__      )

								a      :		Optional[int]	=				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
								a      :		List[Any]	=				"./tests/fixtures/tests_samples/COCO/000000039769.png"
								a      :		Any	=				dqa_pipeline(image=lowerCAmelCase__      ,					question=lowerCAmelCase__      ,					top_k=2      )
								self.assertEqual(lowerCAmelCase__      ,					[]      )

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






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

								a      :		int	=				dqa_pipeline(image=lowerCAmelCase__      ,					question=lowerCAmelCase__      ,					top_k=2      )
								self.assertEqual(
								    nested_simplify(lowerCAmelCase__      ,					decimals=4      )      ,					[
								        {"score": 0.9_944, "answer": "us-001", "start": 16, "end": 16},
								        {"score": 0.0_009, "answer": "us-001", "start": 16, "end": 16},
								    ]      ,					)

								a      :		str	=				dqa_pipeline({"image": image, "question": question}      ,					top_k=2      )
								self.assertEqual(
								    nested_simplify(lowerCAmelCase__      ,					decimals=4      )      ,					[
								        {"score": 0.9_944, "answer": "us-001", "start": 16, "end": 16},
								        {"score": 0.0_009, "answer": "us-001", "start": 16, "end": 16},
								    ]      ,					)

								a      :		Any	=				dqa_pipeline(
								    [{"image": image, "question": question}, {"image": image, "question": question}]      ,					top_k=2      )
								self.assertEqual(
								    nested_simplify(lowerCAmelCase__      ,					decimals=4      )      ,					[
								        [
								            {"score": 0.9_944, "answer": "us-001", "start": 16, "end": 16},
								            {"score": 0.0_009, "answer": "us-001", "start": 16, "end": 16},
								        ],
								    ]
								    * 2      ,					)






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

								a      :		List[Any]	=				dqa_pipeline(image=lowerCAmelCase__      ,					question=lowerCAmelCase__      ,					top_k=2      )
								self.assertEqual(
								    nested_simplify(lowerCAmelCase__      ,					decimals=4      )      ,					[
								        {"score": 0.9_974, "answer": "1110212019", "start": 23, "end": 23},
								        {"score": 0.9_948, "answer": "us-001", "start": 16, "end": 16},
								    ]      ,					)

								a      :		str	=				dqa_pipeline({"image": image, "question": question}      ,					top_k=2      )
								self.assertEqual(
								    nested_simplify(lowerCAmelCase__      ,					decimals=4      )      ,					[
								        {"score": 0.9_974, "answer": "1110212019", "start": 23, "end": 23},
								        {"score": 0.9_948, "answer": "us-001", "start": 16, "end": 16},
								    ]      ,					)

								a      :		Tuple	=				dqa_pipeline(
								    [{"image": image, "question": question}, {"image": image, "question": question}]      ,					top_k=2      )
								self.assertEqual(
								    nested_simplify(lowerCAmelCase__      ,					decimals=4      )      ,					[
								        [
								            {"score": 0.9_974, "answer": "1110212019", "start": 23, "end": 23},
								            {"score": 0.9_948, "answer": "us-001", "start": 16, "end": 16},
								        ]
								    ]
								    * 2      ,					)






							@slow
							@require_torch
							@require_pytesseract
							@require_vision
							def     __a   (   self      )	-> str:
								a      :		Optional[int]	=				AutoTokenizer.from_pretrained(
								    "impira/layoutlm-document-qa"      ,					revision="3dc6de3"      ,					add_prefix_space=lowerCAmelCase__      )
								a      :		int	=				pipeline(
								    "document-question-answering"      ,					model="impira/layoutlm-document-qa"      ,					tokenizer=lowerCAmelCase__      ,					revision="3dc6de3"      ,					)
								a      :		List[Any]	=				INVOICE_URL
								a      :		Tuple	=				"What is the invoice number?"

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

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

								a      :		List[Any]	=				dqa_pipeline(
								    [{"image": image, "question": question}, {"image": image, "question": question}]      ,					top_k=2      )
								self.assertEqual(
								    nested_simplify(lowerCAmelCase__      ,					decimals=4      )      ,					[
								        [
								            {"score": 0.4_251, "answer": "us-001", "start": 16, "end": 16},
								            {"score": 0.0_819, "answer": "1110212019", "start": 23, "end": 23},
								        ]
								    ]
								    * 2      ,					)

								a      :		Dict	=				list(zip(*apply_tesseract(load_image(lowerCAmelCase__      )      ,					lowerCAmelCase__      ,					""      )      )      )

								# This model should also work if `image` is set to None
								a      :		Optional[Any]	=				dqa_pipeline({"image": None, "word_boxes": word_boxes, "question": question}      ,					top_k=2      )
								self.assertEqual(
								    nested_simplify(lowerCAmelCase__      ,					decimals=4      )      ,					[
								        {"score": 0.4_251, "answer": "us-001", "start": 16, "end": 16},
								        {"score": 0.0_819, "answer": "1110212019", "start": 23, "end": 23},
								    ]      ,					)






							@slow
							@require_torch
							@require_pytesseract
							@require_vision
							def     __a   (   self      )	-> Tuple:
								a      :		int	=				AutoTokenizer.from_pretrained(
								    "impira/layoutlm-document-qa"      ,					revision="3dc6de3"      ,					add_prefix_space=lowerCAmelCase__      )
								a      :		Tuple	=				pipeline(
								    "document-question-answering"      ,					model="impira/layoutlm-document-qa"      ,					tokenizer=lowerCAmelCase__      ,					revision="3dc6de3"      ,					max_seq_len=50      ,					)
								a      :		List[str]	=				INVOICE_URL
								a      :		Union[str, Any]	=				"What is the invoice number?"

								a      :		List[Any]	=				dqa_pipeline(image=lowerCAmelCase__      ,					question=lowerCAmelCase__      ,					top_k=2      )
								self.assertEqual(
								    nested_simplify(lowerCAmelCase__      ,					decimals=4      )      ,					[
								        {"score": 0.9_999, "answer": "us-001", "start": 16, "end": 16},
								        {"score": 0.9_998, "answer": "us-001", "start": 16, "end": 16},
								    ]      ,					)

								a      :		List[str]	=				dqa_pipeline(
								    [{"image": image, "question": question}, {"image": image, "question": question}]      ,					top_k=2      )
								self.assertEqual(
								    nested_simplify(lowerCAmelCase__      ,					decimals=4      )      ,					[
								        [
								            {"score": 0.9_999, "answer": "us-001", "start": 16, "end": 16},
								            {"score": 0.9_998, "answer": "us-001", "start": 16, "end": 16},
								        ]
								    ]
								    * 2      ,					)

								a      :		List[Any]	=				list(zip(*apply_tesseract(load_image(lowerCAmelCase__      )      ,					lowerCAmelCase__      ,					""      )      )      )

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






							@slow
							@require_torch
							def     __a   (   self      )	-> int:
								a      :		Tuple	=				pipeline(
								    "document-question-answering"      ,					model="naver-clova-ix/donut-base-finetuned-docvqa"      ,					tokenizer=AutoTokenizer.from_pretrained("naver-clova-ix/donut-base-finetuned-docvqa"      )      ,					feature_extractor="naver-clova-ix/donut-base-finetuned-docvqa"      ,					)

								a      :		Optional[Any]	=				INVOICE_URL
								a      :		Tuple	=				"What is the invoice number?"
								a      :		List[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     __a   (   self      )	-> int:
								pass


