



import json
import os
from functools import lru_cache
from typing import Dict, List, Optional, Tuple, Union

import regex as re

from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...tokenization_utils_base import BatchEncoding, EncodedInput
from ...utils import PaddingStrategy, logging


lowercase_								=     logging.get_logger(__name__)


lowercase_								=     {"""vocab_file""": """vocab.json""", """merges_file""": """merges.txt"""}

# See all LED models at https://huggingface.co/models?filter=LED
lowercase_								=     {
    """vocab_file""": {
        """allenai/led-base-16384""": """https://huggingface.co/allenai/led-base-16384/resolve/main/vocab.json""",
    },
    """merges_file""": {
        """allenai/led-base-16384""": """https://huggingface.co/allenai/led-base-16384/resolve/main/merges.txt""",
    },
    """tokenizer_file""": {
        """allenai/led-base-16384""": """https://huggingface.co/allenai/led-base-16384/resolve/main/tokenizer.json""",
    },
}

lowercase_								=     {
    """allenai/led-base-16384""": 1_6384,
}



@lru_cache()
# Copied from transformers.models.bart.tokenization_bart.bytes_to_unicode
def __lowerCAmelCase (     ):
			lowercase__					  =				(
			    list(range(ord("!"  )						,  ord("~"  ) + 1  )  ) + list(range(ord("¡"  )						,  ord("¬"  ) + 1  )  ) + list(range(ord("®"  )						,  ord("ÿ"  ) + 1  )  )
			)
			lowercase__					  =				bs[:]
			lowercase__					  =				0
			for b in range(2**8  ):
						if b not in bs:
									bs.append(SCREAMING_SNAKE_CASE_  )
									cs.append(2**8 + n  )
									n += 1
			lowercase__					  =				[chr(SCREAMING_SNAKE_CASE_  ) for n in cs]
			return dict(zip(SCREAMING_SNAKE_CASE_						,  SCREAMING_SNAKE_CASE_  )  )



def __lowerCAmelCase (     SCREAMING_SNAKE_CASE_  ):
			lowercase__					  =				set()
			lowercase__					  =				word[0]
			for char in word[1:]:
						pairs.add((prev_char, char)  )
						lowercase__					  =				char
			return pairs




class 				_snake_case			(					lowercase__):
				UpperCamelCase__				:					Any     		=VOCAB_FILES_NAMES
				UpperCamelCase__				:					Any     		=PRETRAINED_VOCAB_FILES_MAP
				UpperCamelCase__				:					List[str]     		=PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
				UpperCamelCase__				:					int     		=["""input_ids""", """attention_mask"""]




				def __init__(						self					:						int,					__lowercase					:						List[str],					__lowercase					:						Union[str, Any],					__lowercase					:						str="replace",					__lowercase					:						int="<s>",					__lowercase					:						Dict="</s>",					__lowercase					:						List[str]="</s>",					__lowercase					:						int="<s>",					__lowercase					:						List[Any]="<unk>",					__lowercase					:						Dict="<pad>",					__lowercase					:						Union[str, Any]="<mask>",					__lowercase					:						int=False,					**__lowercase					:						int,					):
							lowercase__					  =				AddedToken(__lowercase,					lstrip=__lowercase,					rstrip=__lowercase						) if isinstance(__lowercase,					__lowercase						) else bos_token
							lowercase__					  =				AddedToken(__lowercase,					lstrip=__lowercase,					rstrip=__lowercase						) if isinstance(__lowercase,					__lowercase						) else eos_token
							lowercase__					  =				AddedToken(__lowercase,					lstrip=__lowercase,					rstrip=__lowercase						) if isinstance(__lowercase,					__lowercase						) else sep_token
							lowercase__					  =				AddedToken(__lowercase,					lstrip=__lowercase,					rstrip=__lowercase						) if isinstance(__lowercase,					__lowercase						) else cls_token
							lowercase__					  =				AddedToken(__lowercase,					lstrip=__lowercase,					rstrip=__lowercase						) if isinstance(__lowercase,					__lowercase						) else unk_token
							lowercase__					  =				AddedToken(__lowercase,					lstrip=__lowercase,					rstrip=__lowercase						) if isinstance(__lowercase,					__lowercase						) else pad_token

							# Mask token behave like a normal word, i.e. include the space before it
							lowercase__					  =				AddedToken(__lowercase,					lstrip=__lowercase,					rstrip=__lowercase						) if isinstance(__lowercase,					__lowercase						) else mask_token

							super().__init__(
							    errors=__lowercase,					bos_token=__lowercase,					eos_token=__lowercase,					unk_token=__lowercase,					sep_token=__lowercase,					cls_token=__lowercase,					pad_token=__lowercase,					mask_token=__lowercase,					add_prefix_space=__lowercase,					**__lowercase,					)

							with open(__lowercase,					encoding="utf-8"						) as vocab_handle:
										lowercase__					  =				json.load(__lowercase						)
							lowercase__					  =				{v: k for k, v in self.encoder.items()}
							lowercase__					  =				errors  # how to handle errors in decoding
							lowercase__					  =				bytes_to_unicode()
							lowercase__					  =				{v: k for k, v in self.byte_encoder.items()}
							with open(__lowercase,					encoding="utf-8"						) as merges_handle:
										lowercase__					  =				merges_handle.read().split("\n"						)[1:-1]
							lowercase__					  =				[tuple(merge.split()						) for merge in bpe_merges]
							lowercase__					  =				dict(zip(__lowercase,					range(len(__lowercase						)						)						)						)
							lowercase__					  =				{}
							lowercase__					  =				add_prefix_space

							# Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions
							lowercase__					  =				re.compile(R"'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+"						)




				@property
				# Copied from transformers.models.bart.tokenization_bart.BartTokenizer.vocab_size
				def 							A__      (						self					:						Tuple						):
							return len(self.encoder						)




				def 							A__      (						self					:						str						):
							return dict(self.encoder,					**self.added_tokens_encoder						)




				def 							A__      (						self					:						Optional[int],					__lowercase					:						Optional[int]						):
							if token in self.cache:
										return self.cache[token]
							lowercase__					  =				tuple(__lowercase						)
							lowercase__					  =				get_pairs(__lowercase						)

							if not pairs:
										return token

							while True:
										lowercase__					  =				min(__lowercase,					key=lambda __lowercase						: self.bpe_ranks.get(__lowercase,					float("inf"						)						)						)
										if bigram not in self.bpe_ranks:
													break
										lowercase__  ,       lowercase__					  =				bigram
										lowercase__					  =				[]
										lowercase__					  =				0
										while i < len(__lowercase						):
													try:
																lowercase__					  =				word.index(__lowercase,					__lowercase						)
													except ValueError:
																new_word.extend(word[i:]						)
																break
													else:
																new_word.extend(word[i:j]						)
																lowercase__					  =				j

													if word[i] == first and i < len(__lowercase						) - 1 and word[i + 1] == second:
																new_word.append(first + second						)
																i += 2
													else:
																new_word.append(word[i]						)
																i += 1
										lowercase__					  =				tuple(__lowercase						)
										lowercase__					  =				new_word
										if len(__lowercase						) == 1:
													break
										else:
													lowercase__					  =				get_pairs(__lowercase						)
							lowercase__					  =				" ".join(__lowercase						)
							lowercase__					  =				word
							return word




				def 							A__      (						self					:						Union[str, Any],					__lowercase					:						Union[str, Any]						):
							lowercase__					  =				[]
							for token in re.findall(self.pat,					__lowercase						):
										lowercase__					  =				"".join(
										    self.byte_encoder[b] for b in token.encode("utf-8"						)						)  # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
										bpe_tokens.extend(bpe_token for bpe_token in self.bpe(__lowercase						).split(" "						)						)
							return bpe_tokens




				def 							A__      (						self					:						List[Any],					__lowercase					:						int						):
							return self.encoder.get(__lowercase,					self.encoder.get(self.unk_token						)						)




				def 							A__      (						self					:						Tuple,					__lowercase					:						Optional[int]						):
							return self.decoder.get(__lowercase						)




				def 							A__      (						self					:						List[str],					__lowercase					:						str						):
							lowercase__					  =				"".join(__lowercase						)
							lowercase__					  =				bytearray([self.byte_decoder[c] for c in text]						).decode("utf-8",					errors=self.errors						)
							return text




				def 							A__      (						self					:						Tuple,					__lowercase					:						str,					__lowercase					:						Optional[str] = None						):
							if not os.path.isdir(__lowercase						):
										logger.error(F'''Vocabulary path ({save_directory}) should be a directory'''						)
										return
							lowercase__					  =				os.path.join(
							    __lowercase,					(filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]						)
							lowercase__					  =				os.path.join(
							    __lowercase,					(filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]						)

							with open(__lowercase,					"w",					encoding="utf-8"						) as f:
										f.write(json.dumps(self.encoder,					indent=2,					sort_keys=__lowercase,					ensure_ascii=__lowercase						) + "\n"						)

							lowercase__					  =				0
							with open(__lowercase,					"w",					encoding="utf-8"						) as writer:
										writer.write("#version: 0.2\n"						)
										for bpe_tokens, token_index in sorted(self.bpe_ranks.items(),					key=lambda __lowercase						: kv[1]						):
													if index != token_index:
																logger.warning(
																    F'''Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.'''
																    " Please check that the tokenizer is not corrupted!"						)
																lowercase__					  =				token_index
													writer.write(" ".join(__lowercase						) + "\n"						)
													index += 1

							return vocab_file, merge_file




				def 							A__      (						self					:						str,					__lowercase					:						List[int],					__lowercase					:						Optional[List[int]] = None						):
							if token_ids_a is None:
										return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
							lowercase__					  =				[self.cls_token_id]
							lowercase__					  =				[self.sep_token_id]
							return cls + token_ids_a + sep + sep + token_ids_a + sep




				def 							A__      (						self					:						List[Any],					__lowercase					:						List[int],					__lowercase					:						Optional[List[int]] = None,					__lowercase					:						bool = False						):
							if already_has_special_tokens:
										return super().get_special_tokens_mask(
										    token_ids_a=__lowercase,					token_ids_a=__lowercase,					already_has_special_tokens=__lowercase						)

							if token_ids_a is None:
										return [1] + ([0] * len(__lowercase						)) + [1]
							return [1] + ([0] * len(__lowercase						)) + [1, 1] + ([0] * len(__lowercase						)) + [1]




				def 							A__      (						self					:						int,					__lowercase					:						List[int],					__lowercase					:						Optional[List[int]] = None						):
							lowercase__					  =				[self.sep_token_id]
							lowercase__					  =				[self.cls_token_id]

							if token_ids_a is None:
										return len(cls + token_ids_a + sep						) * [0]
							return len(cls + token_ids_a + sep + sep + token_ids_a + sep						) * [0]




				def 							A__      (						self					:						Optional[Any],					__lowercase					:						str,					__lowercase					:						int=False,					**__lowercase					:						Optional[int]						):
							lowercase__					  =				kwargs.pop("add_prefix_space",					self.add_prefix_space						)
							if (is_split_into_words or add_prefix_space) and (len(__lowercase						) > 0 and not text[0].isspace()):
										lowercase__					  =				" " + text
							return (text, kwargs)




				def 							A__      (						self					:						str,					__lowercase					:						Union[Dict[str, EncodedInput], BatchEncoding],					__lowercase					:						Optional[int] = None,					__lowercase					:						PaddingStrategy = PaddingStrategy.DO_NOT_PAD,					__lowercase					:						Optional[int] = None,					__lowercase					:						Optional[bool] = None,					):
							lowercase__					  =				super()._pad(
							    encoded_inputs=__lowercase,					max_length=__lowercase,					padding_strategy=__lowercase,					pad_to_multiple_of=__lowercase,					return_attention_mask=__lowercase,					)

							# Load from model defaults
							if return_attention_mask is None:
										lowercase__					  =				"attention_mask" in self.model_input_names

							if return_attention_mask and "global_attention_mask" in encoded_inputs:
										lowercase__					  =				encoded_inputs[self.model_input_names[0]]
										# `global_attention_mask` need to have the same length as other (sequential) inputs.
										lowercase__					  =				len(encoded_inputs["global_attention_mask"]						) != len(__lowercase						)

										if needs_to_be_padded:
													lowercase__					  =				len(__lowercase						) - len(encoded_inputs["global_attention_mask"]						)

													if self.padding_side == "right":
																# Use `-1` since `0` in `global_attention_mask` means `local attention` instead of `not to attend`
																lowercase__					  =				(
																    encoded_inputs["global_attention_mask"] + [-1] * difference
																)
													elif self.padding_side == "left":
																lowercase__					  =				[-1] * difference + encoded_inputs[
																    "global_attention_mask"
																]
													else:
																raise ValueError("Invalid padding strategy:" + str(self.padding_side						)						)

							return encoded_inputs









import unittest

import numpy as np

from transformers.testing_utils import is_flaky, require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
							import torch

if is_vision_available():
							from PIL import Image

							from transformers import DonutImageProcessor
class 				_snake_case			(					unittest.TestCase):




				def __init__(						self					:						Dict,					__lowercase					:						int,					__lowercase					:						Union[str, Any]=7,					__lowercase					:						Union[str, Any]=3,					__lowercase					:						Any=18,					__lowercase					:						Union[str, Any]=30,					__lowercase					:						Any=400,					__lowercase					:						List[str]=True,					__lowercase					:						Dict=None,					__lowercase					:						List[str]=True,					__lowercase					:						int=False,					__lowercase					:						Union[str, Any]=True,					__lowercase					:						str=True,					__lowercase					:						Optional[int]=[0.5, 0.5, 0.5],					__lowercase					:						List[Any]=[0.5, 0.5, 0.5],					):
							lowercase__					  =				parent
							lowercase__					  =				batch_size
							lowercase__					  =				num_channels
							lowercase__					  =				image_size
							lowercase__					  =				min_resolution
							lowercase__					  =				max_resolution
							lowercase__					  =				do_resize
							lowercase__					  =				size if size is not None else {"height": 18, "width": 20}
							lowercase__					  =				do_thumbnail
							lowercase__					  =				do_align_axis
							lowercase__					  =				do_pad
							lowercase__					  =				do_normalize
							lowercase__					  =				image_mean
							lowercase__					  =				image_std




				def 							A__      (						self					:						Optional[Any]						):
							return {
							    "do_resize": self.do_resize,
							    "size": self.size,
							    "do_thumbnail": self.do_thumbnail,
							    "do_align_long_axis": self.do_align_axis,
							    "do_pad": self.do_pad,
							    "do_normalize": self.do_normalize,
							    "image_mean": self.image_mean,
							    "image_std": self.image_std,
							}
@require_torch
@require_vision
class 				_snake_case			(					lowercase__    ,	unittest.TestCase):
				UpperCamelCase__				:					Optional[int]     		=DonutImageProcessor if is_vision_available() else None




				def 							A__      (						self					:						str						):
							lowercase__					  =				DonutImageProcessingTester(self						)




				@property
				def 							A__      (						self					:						List[str]						):
							return self.image_processor_tester.prepare_image_processor_dict()




				def 							A__      (						self					:						Optional[Any]						):
							lowercase__					  =				self.image_processing_class(**self.image_processor_dict						)
							self.assertTrue(hasattr(__lowercase,					"do_resize"						)						)
							self.assertTrue(hasattr(__lowercase,					"size"						)						)
							self.assertTrue(hasattr(__lowercase,					"do_thumbnail"						)						)
							self.assertTrue(hasattr(__lowercase,					"do_align_long_axis"						)						)
							self.assertTrue(hasattr(__lowercase,					"do_pad"						)						)
							self.assertTrue(hasattr(__lowercase,					"do_normalize"						)						)
							self.assertTrue(hasattr(__lowercase,					"image_mean"						)						)
							self.assertTrue(hasattr(__lowercase,					"image_std"						)						)




				def 							A__      (						self					:						str						):
							lowercase__					  =				self.image_processing_class.from_dict(self.image_processor_dict						)
							self.assertEqual(image_processor.size,					{"height": 18, "width": 20}						)

							lowercase__					  =				self.image_processing_class.from_dict(self.image_processor_dict,					size=42						)
							self.assertEqual(image_processor.size,					{"height": 42, "width": 42}						)

							# Previous config had dimensions in (width, height) order
							lowercase__					  =				self.image_processing_class.from_dict(self.image_processor_dict,					size=(42, 84)						)
							self.assertEqual(image_processor.size,					{"height": 84, "width": 42}						)




				def 							A__      (						self					:						List[str]						):
							pass




				@is_flaky()
				def 							A__      (						self					:						Dict						):
							# Initialize image_processing
							lowercase__					  =				self.image_processing_class(**self.image_processor_dict						)
							# create random PIL images
							lowercase__					  =				prepare_image_inputs(self.image_processor_tester,					equal_resolution=__lowercase						)
							for image in image_inputs:
										self.assertIsInstance(__lowercase,					Image.Image						)

							# Test not batched input
							lowercase__					  =				image_processing(image_inputs[0],					return_tensors="pt"						).pixel_values
							self.assertEqual(
							    encoded_images.shape,					(
							        1,
							        self.image_processor_tester.num_channels,
							        self.image_processor_tester.size["height"],
							        self.image_processor_tester.size["width"],
							    ),					)

							# Test batched
							lowercase__					  =				image_processing(__lowercase,					return_tensors="pt"						).pixel_values
							self.assertEqual(
							    encoded_images.shape,					(
							        self.image_processor_tester.batch_size,
							        self.image_processor_tester.num_channels,
							        self.image_processor_tester.size["height"],
							        self.image_processor_tester.size["width"],
							    ),					)




				@is_flaky()
				def 							A__      (						self					:						Optional[Any]						):
							# Initialize image_processing
							lowercase__					  =				self.image_processing_class(**self.image_processor_dict						)
							# create random numpy tensors
							lowercase__					  =				prepare_image_inputs(self.image_processor_tester,					equal_resolution=__lowercase,					numpify=__lowercase						)
							for image in image_inputs:
										self.assertIsInstance(__lowercase,					np.ndarray						)

							# Test not batched input
							lowercase__					  =				image_processing(image_inputs[0],					return_tensors="pt"						).pixel_values
							self.assertEqual(
							    encoded_images.shape,					(
							        1,
							        self.image_processor_tester.num_channels,
							        self.image_processor_tester.size["height"],
							        self.image_processor_tester.size["width"],
							    ),					)

							# Test batched
							lowercase__					  =				image_processing(__lowercase,					return_tensors="pt"						).pixel_values
							self.assertEqual(
							    encoded_images.shape,					(
							        self.image_processor_tester.batch_size,
							        self.image_processor_tester.num_channels,
							        self.image_processor_tester.size["height"],
							        self.image_processor_tester.size["width"],
							    ),					)




				@is_flaky()
				def 							A__      (						self					:						Tuple						):
							# Initialize image_processing
							lowercase__					  =				self.image_processing_class(**self.image_processor_dict						)
							# create random PyTorch tensors
							lowercase__					  =				prepare_image_inputs(self.image_processor_tester,					equal_resolution=__lowercase,					torchify=__lowercase						)
							for image in image_inputs:
										self.assertIsInstance(__lowercase,					torch.Tensor						)

							# Test not batched input
							lowercase__					  =				image_processing(image_inputs[0],					return_tensors="pt"						).pixel_values
							self.assertEqual(
							    encoded_images.shape,					(
							        1,
							        self.image_processor_tester.num_channels,
							        self.image_processor_tester.size["height"],
							        self.image_processor_tester.size["width"],
							    ),					)

							# Test batched
							lowercase__					  =				image_processing(__lowercase,					return_tensors="pt"						).pixel_values
							self.assertEqual(
							    encoded_images.shape,					(
							        self.image_processor_tester.batch_size,
							        self.image_processor_tester.num_channels,
							        self.image_processor_tester.size["height"],
							        self.image_processor_tester.size["width"],
							    ),					)




