



"""simple docstring"""


import json
import os
import re
import unicodedata
from typing import Optional, Tuple

from ...tokenization_utils import PreTrainedTokenizer, _is_control, _is_punctuation, _is_whitespace
from ...utils import logging


snake_case_								=			logging.get_logger(__name__)

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

snake_case_								=			{
    """vocab_file""": {"""openai-gpt""": """https://huggingface.co/openai-gpt/resolve/main/vocab.json"""},
    """merges_file""": {"""openai-gpt""": """https://huggingface.co/openai-gpt/resolve/main/merges.txt"""},
}

snake_case_								=			{
    """openai-gpt""": 512,
}

def 					_lowerCAmelCase (  lowercase_		):
						UpperCAmelCase			 =					text.strip()
						if not text:
												return []
						UpperCAmelCase			 =					text.split()
						return tokens







class  A_     (	SCREAMING_SNAKE_CASE_							):



						"""simple docstring"""






						def __init__(   self					:Union[str, Any]  ,    lowercase_					:Any=True  ,    lowercase_					:Tuple=None  ,    lowercase_					:Optional[Any]=True  ,    lowercase_					:Union[str, Any]=None  ,    lowercase_					:Optional[int]=True  ,    )							->     List[str]:
												if never_split is None:
																		UpperCAmelCase			 =					[]
												UpperCAmelCase			 =					do_lower_case
												UpperCAmelCase			 =					set(lowercase_   )
												UpperCAmelCase			 =					tokenize_chinese_chars
												UpperCAmelCase			 =					strip_accents
												UpperCAmelCase			 =					do_split_on_punc






						def       UpperCAmelCase__	(   self					:Tuple  ,    lowercase_					:Tuple  ,    lowercase_					:List[Any]=None   )							->     List[str]:
												UpperCAmelCase			 =					self.never_split.union(set(lowercase_   )   ) if never_split else self.never_split
												UpperCAmelCase			 =					self._clean_text(lowercase_   )

												# This was added on November 1st, 2018 for the multilingual and Chinese
												# models. This is also applied to the English models now, but it doesn't
												# matter since the English models were not trained on any Chinese data
												# and generally don't have any Chinese data in them (there are Chinese
												# characters in the vocabulary because Wikipedia does have some Chinese
												# words in the English Wikipedia.).
												if self.tokenize_chinese_chars:
																		UpperCAmelCase			 =					self._tokenize_chinese_chars(lowercase_   )
												# prevents treating the same character with different unicode codepoints as different characters
												UpperCAmelCase			 =					unicodedata.normalize('NFC'  ,    lowercase_   )
												UpperCAmelCase			 =					whitespace_tokenize(lowercase_   )
												UpperCAmelCase			 =					[]
												for token in orig_tokens:
																		if token not in never_split:
																								if self.do_lower_case:
																														UpperCAmelCase			 =					token.lower()
																														if self.strip_accents is not False:
																																				UpperCAmelCase			 =					self._run_strip_accents(lowercase_   )
																								elif self.strip_accents:
																														UpperCAmelCase			 =					self._run_strip_accents(lowercase_   )
																		split_tokens.extend(self._run_split_on_punc(lowercase_  ,    lowercase_   )   )

												UpperCAmelCase			 =					whitespace_tokenize(' '.join(lowercase_   )   )
												return output_tokens






						def       UpperCAmelCase__	(   self					:Optional[int]  ,    lowercase_					:List[Any]   )							->     Any:
												UpperCAmelCase			 =					unicodedata.normalize('NFD'  ,    lowercase_   )
												UpperCAmelCase			 =					[]
												for char in text:
																		UpperCAmelCase			 =					unicodedata.category(lowercase_   )
																		if cat == "Mn":
																								continue
																		output.append(lowercase_   )
												return "".join(lowercase_   )






						def       UpperCAmelCase__	(   self					:Optional[Any]  ,    lowercase_					:Union[str, Any]  ,    lowercase_					:Any=None   )							->     Tuple:
												if not self.do_split_on_punc or (never_split is not None and text in never_split):
																		return [text]
												UpperCAmelCase			 =					list(lowercase_   )
												UpperCAmelCase			 =					0
												UpperCAmelCase			 =					True
												UpperCAmelCase			 =					[]
												while i < len(lowercase_   ):
																		UpperCAmelCase			 =					chars[i]
																		if _is_punctuation(lowercase_   ):
																								output.append([char]   )
																								UpperCAmelCase			 =					True
																		else:
																								if start_new_word:
																														output.append([]   )
																								UpperCAmelCase			 =					False
																								output[-1].append(lowercase_   )
																		i += 1

												return ["".join(lowercase_   ) for x in output]






						def       UpperCAmelCase__	(   self					:List[Any]  ,    lowercase_					:Optional[Any]   )							->     List[str]:
												UpperCAmelCase			 =					[]
												for char in text:
																		UpperCAmelCase			 =					ord(lowercase_   )
																		if self._is_chinese_char(lowercase_   ):
																								output.append(' '   )
																								output.append(lowercase_   )
																								output.append(' '   )
																		else:
																								output.append(lowercase_   )
												return "".join(lowercase_   )






						def       UpperCAmelCase__	(   self					:Tuple  ,    lowercase_					:Dict   )							->     Any:
												# This defines a "chinese character" as anything in the CJK Unicode block:
												#   https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
												#
												# Note that the CJK Unicode block is NOT all Japanese and Korean characters,
												# despite its name. The modern Korean Hangul alphabet is a different block,
												# as is Japanese Hiragana and Katakana. Those alphabets are used to write
												# space-separated words, so they are not treated specially and handled
												# like the all of the other languages.
												if (
												    (cp >= 0x4E00 and cp <= 0x9FFF)
												    or (cp >= 0x3400 and cp <= 0x4DBF)  #
												    or (cp >= 0x20000 and cp <= 0x2A6DF)  #
												    or (cp >= 0x2A700 and cp <= 0x2B73F)  #
												    or (cp >= 0x2B740 and cp <= 0x2B81F)  #
												    or (cp >= 0x2B820 and cp <= 0x2CEAF)  #
												    or (cp >= 0xF900 and cp <= 0xFAFF)
												    or (cp >= 0x2F800 and cp <= 0x2FA1F)  #
												):  #
																		return True

												return False






						def       UpperCAmelCase__	(   self					:Union[str, Any]  ,    lowercase_					:Any   )							->     Optional[Any]:
												UpperCAmelCase			 =					[]
												for char in text:
																		UpperCAmelCase			 =					ord(lowercase_   )
																		if cp == 0 or cp == 0xFFFD or _is_control(lowercase_   ):
																								continue
																		if _is_whitespace(lowercase_   ):
																								output.append(' '   )
																		else:
																								output.append(lowercase_   )
												return "".join(lowercase_   )


def 					_lowerCAmelCase (  lowercase_		):
						UpperCAmelCase			 =					set()
						UpperCAmelCase			 =					word[0]
						for char in word[1:]:
												pairs.add((prev_char, char)		)
												UpperCAmelCase			 =					char
						return pairs

def 					_lowerCAmelCase (  lowercase_		):
						UpperCAmelCase			 =					text.replace('—'						,      '-'		)
						UpperCAmelCase			 =					text.replace('–'						,      '-'		)
						UpperCAmelCase			 =					text.replace('―'						,      '-'		)
						UpperCAmelCase			 =					text.replace('…'						,      '...'		)
						UpperCAmelCase			 =					text.replace('´'						,      '\''		)
						UpperCAmelCase			 =					re.sub(R'(-+|~+|!+|"+|;+|\?+|\++|,+|\)+|\(+|\\+|\/+|\*+|\[+|\]+|}+|{+|\|+|_+)'						,      R' \1 '						,      lowercase_		)
						UpperCAmelCase			 =					re.sub(R'\s*\n\s*'						,      ' \n '						,      lowercase_		)
						UpperCAmelCase			 =					re.sub(R'[^\S\n]+'						,      ' '						,      lowercase_		)
						return text.strip()







class  A_     (	SCREAMING_SNAKE_CASE_							):



						"""simple docstring"""
						__UpperCamelCase													=				VOCAB_FILES_NAMES
						__UpperCamelCase													=				PRETRAINED_VOCAB_FILES_MAP
						__UpperCamelCase													=				PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
						__UpperCamelCase													=				["""input_ids""", """attention_mask"""]






						def __init__(   self					:Optional[Any]  ,    lowercase_					:Dict  ,    lowercase_					:Any  ,    lowercase_					:int="<unk>"  ,    **lowercase_					:int   )							->     List[Any]:
												super().__init__(unk_token=lowercase_  ,    **lowercase_   )

												try:
																		import ftfy
																		from spacy.lang.en import English

																		UpperCAmelCase			 =					English()
																		UpperCAmelCase			 =					_nlp.tokenizer
																		UpperCAmelCase			 =					ftfy.fix_text
												except ImportError:
																		logger.warning('ftfy or spacy is not installed using BERT BasicTokenizer instead of SpaCy & ftfy.'   )
																		UpperCAmelCase			 =					BasicTokenizer(do_lower_case=lowercase_   )
																		UpperCAmelCase			 =					None

												with open(lowercase_  ,    encoding='utf-8'   ) as vocab_handle:
																		UpperCAmelCase			 =					json.load(lowercase_   )
												UpperCAmelCase			 =					{v: k for k, v in self.encoder.items()}
												with open(lowercase_  ,    encoding='utf-8'   ) as merges_handle:
																		UpperCAmelCase			 =					merges_handle.read().split('\n'   )[1:-1]
												UpperCAmelCase			 =					[tuple(merge.split()   ) for merge in merges]
												UpperCAmelCase			 =					dict(zip(lowercase_  ,    range(len(lowercase_   )   )   )   )
												UpperCAmelCase			 =					{}






						@property
						def       UpperCAmelCase__	(   self					:Union[str, Any]   )							->     Optional[Any]:
												return True






						@property
						def       UpperCAmelCase__	(   self					:Tuple   )							->     int:
												return len(self.encoder   )






						def       UpperCAmelCase__	(   self					:List[str]   )							->     Optional[Any]:
												return dict(self.encoder  ,    **self.added_tokens_encoder   )






						def       UpperCAmelCase__	(   self					:str  ,    lowercase_					:str   )							->     List[Any]:
												UpperCAmelCase			 =					tuple(token[:-1]   ) + (token[-1] + '</w>',)
												if token in self.cache:
																		return self.cache[token]
												UpperCAmelCase			 =					get_pairs(lowercase_   )

												if not pairs:
																		return token + "</w>"

												while True:
																		UpperCAmelCase			 =					min(lowercase_  ,    key=lambda lowercase_   : self.bpe_ranks.get(lowercase_  ,    float('inf'   )   )   )
																		if bigram not in self.bpe_ranks:
																								break
																		UpperCAmelCase ,       UpperCAmelCase			 =					bigram
																		UpperCAmelCase			 =					[]
																		UpperCAmelCase			 =					0
																		while i < len(lowercase_   ):
																								try:
																														UpperCAmelCase			 =					word.index(lowercase_  ,    lowercase_   )
																								except ValueError:
																														new_word.extend(word[i:]   )
																														break
																								else:
																														new_word.extend(word[i:j]   )
																														UpperCAmelCase			 =					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
																		UpperCAmelCase			 =					tuple(lowercase_   )
																		UpperCAmelCase			 =					new_word
																		if len(lowercase_   ) == 1:
																								break
																		else:
																								UpperCAmelCase			 =					get_pairs(lowercase_   )
												UpperCAmelCase			 =					' '.join(lowercase_   )
												if word == "\n  </w>":
																		UpperCAmelCase			 =					'\n</w>'
												UpperCAmelCase			 =					word
												return word






						def       UpperCAmelCase__	(   self					:List[str]  ,    lowercase_					:Optional[int]   )							->     Any:
												UpperCAmelCase			 =					[]
												if self.fix_text is None:
																		# Using BERT's BasicTokenizer
																		UpperCAmelCase			 =					self.nlp.tokenize(lowercase_   )
																		for token in text:
																								split_tokens.extend(list(self.bpe(lowercase_   ).split(' '   )   )   )
												else:
																		# Using SpaCy & ftfy (original tokenization process of OpenAI GPT)
																		UpperCAmelCase			 =					self.nlp(text_standardize(self.fix_text(lowercase_   )   )   )
																		for token in text:
																								split_tokens.extend(list(self.bpe(token.text.lower()   ).split(' '   )   )   )
												return split_tokens






						def       UpperCAmelCase__	(   self					:List[Any]  ,    lowercase_					:List[Any]   )							->     int:
												return self.encoder.get(lowercase_  ,    self.encoder.get(self.unk_token   )   )






						def       UpperCAmelCase__	(   self					:Any  ,    lowercase_					:List[Any]   )							->     Union[str, Any]:
												return self.decoder.get(lowercase_  ,    self.unk_token   )






						def       UpperCAmelCase__	(   self					:Optional[Any]  ,    lowercase_					:str   )							->     List[Any]:
												UpperCAmelCase			 =					''.join(lowercase_   ).replace('</w>'  ,    ' '   ).strip()
												return out_string






						def       UpperCAmelCase__	(   self					:Any  ,    lowercase_					:str  ,    lowercase_					:Optional[str] = None   )							->     Tuple[str]:
												if not os.path.isdir(lowercase_   ):
																		logger.error(f"""Vocabulary path ({save_directory}) should be a directory"""   )
																		return
												UpperCAmelCase			 =					os.path.join(
												    lowercase_  ,    (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']   )
												UpperCAmelCase			 =					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'   )

												UpperCAmelCase			 =					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!'   )
																														UpperCAmelCase			 =					token_index
																								writer.write(' '.join(lowercase_   ) + '\n'   )
																								index += 1

												return vocab_file, merge_file






'''simple docstring'''

import sys
from typing import Tuple

import numpy as np
import torch
from PIL import Image
from torch import nn

from transformers.image_utils import PILImageResampling
from utils import img_tensorize




class 		SCREAMING_SNAKE_CASE_					:



			"""simple docstring"""






			def __init__(							self				,			snake_case_				,			snake_case_=sys.maxsize					):
									snake_case :       Any				=    "bilinear"
									snake_case :       Dict				=    max_size
									snake_case :       Dict				=    short_edge_length






			def __call__(							self				,			snake_case_					):
									snake_case :       Optional[Any]				=    []
									for img in imgs:
															snake_case				,					snake_case :       Dict				=    img.shape[:2]
															# later: provide list and randomly choose index for resize
															snake_case :       Dict				=    np.random.randint(self.short_edge_length[0]				,			self.short_edge_length[1] + 1					)
															if size == 0:
																					return img
															snake_case :       Any				=    size * 1.0 / min(snake_case_				,			snake_case_					)
															if h < w:
																					snake_case				,					snake_case :       Optional[int]				=    size, scale * w
															else:
																					snake_case				,					snake_case :       Tuple				=    scale * h, size
															if max(snake_case_				,			snake_case_					) > self.max_size:
																					snake_case :       Optional[int]				=    self.max_size * 1.0 / max(snake_case_				,			snake_case_					)
																					snake_case :       Dict				=    newh * scale
																					snake_case :       List[Any]				=    neww * scale
															snake_case :       int				=    int(neww + 0.5					)
															snake_case :       List[Any]				=    int(newh + 0.5					)

															if img.dtype == np.uinta:
																					snake_case :       List[Any]				=    Image.fromarray(snake_case_					)
																					snake_case :       str				=    pil_image.resize((neww, newh)				,			PILImageResampling.BILINEAR					)
																					snake_case :       List[str]				=    np.asarray(snake_case_					)
															else:
																					snake_case :       List[Any]				=    img.permute(2				,			0				,			1					).unsqueeze(0					)  # 3, 0, 1)  # hw(c) -> nchw
																					snake_case :       Tuple				=    nn.functional.interpolate(
																					    snake_case_				,			(newh, neww)				,			mode=self.interp_method				,			align_corners=snake_case_					).squeeze(0					)
															img_augs.append(snake_case_					)

									return img_augs







class 		SCREAMING_SNAKE_CASE_					:



			"""simple docstring"""






			def __init__(							self				,			snake_case_					):
									snake_case :       Union[str, Any]				=    ResizeShortestEdge([cfg.INPUT.MIN_SIZE_TEST, cfg.INPUT.MIN_SIZE_TEST]				,			cfg.INPUT.MAX_SIZE_TEST					)
									snake_case :       Any				=    cfg.INPUT.FORMAT
									snake_case :       Optional[int]				=    cfg.SIZE_DIVISIBILITY
									snake_case :       Optional[int]				=    cfg.PAD_VALUE
									snake_case :       int				=    cfg.INPUT.MAX_SIZE_TEST
									snake_case :       Optional[int]				=    cfg.MODEL.DEVICE
									snake_case :       int				=    torch.tensor(cfg.MODEL.PIXEL_STD					).to(self.device					).view(len(cfg.MODEL.PIXEL_STD					)				,			1				,			1					)
									snake_case :       List[Any]				=    torch.tensor(cfg.MODEL.PIXEL_MEAN					).to(self.device					).view(len(cfg.MODEL.PIXEL_STD					)				,			1				,			1					)
									snake_case :       Dict				=    lambda snake_case_					: (x - self.pixel_mean) / self.pixel_std



			def   lowerCamelCase (							self				,			snake_case_					):
									snake_case :       List[Any]				=    tuple(max(snake_case_					) for s in zip(*[img.shape for img in images]					)					)
									snake_case :       int				=    [im.shape[-2:] for im in images]
									snake_case :       List[Any]				=    [
									    nn.functional.pad(
									        snake_case_				,			[0, max_size[-1] - size[1], 0, max_size[-2] - size[0]]				,			value=self.pad_value				,			)
									    for size, im in zip(snake_case_				,			snake_case_					)
									]

									return torch.stack(snake_case_					), torch.tensor(snake_case_					)






			def __call__(							self				,			snake_case_				,			snake_case_=False					):
									with torch.no_grad():
															if not isinstance(snake_case_				,			snake_case_					):
																					snake_case :       int				=    [images]
															if single_image:
																					assert len(snake_case_					) == 1
															for i in range(len(snake_case_					)					):
																					if isinstance(images[i]				,			torch.Tensor					):
																											images.insert(snake_case_				,			images.pop(snake_case_					).to(self.device					).float()					)
																					elif not isinstance(images[i]				,			torch.Tensor					):
																											images.insert(
																											    snake_case_				,			torch.as_tensor(img_tensorize(images.pop(snake_case_					)				,			input_format=self.input_format					)					)
																											    .to(self.device					)
																											    .float()				,			)
            # resize smallest edge
															snake_case :       List[Any]				=    torch.tensor([im.shape[:2] for im in images]					)
															snake_case :       Any				=    self.aug(snake_case_					)
															# transpose images and convert to torch tensors
															# images = [torch.as_tensor(i.astype("float32")).permute(2, 0, 1).to(self.device) for i in images]
															# now normalize before pad to avoid useless arithmetic
															snake_case :       str				=    [self.normalizer(snake_case_					) for x in images]
															# now pad them to do the following operations
															snake_case				,					snake_case :       int				=    self.pad(snake_case_					)
															# Normalize

															if self.size_divisibility > 0:
																					raise NotImplementedError()
															# pad
															snake_case :       Union[str, Any]				=    torch.true_divide(snake_case_				,			snake_case_					)
															if single_image:
																					return images[0], sizes[0], scales_yx[0]
															else:
																					return images, sizes, scales_yx







def        UpperCAmelCase__   (				_lowerCAmelCase    :			Any,      _lowerCAmelCase    :			Optional[int])    ->		int:



						"""simple docstring"""

						boxes[:, 0::2] *= scale_yx[:, 1]
						boxes[:, 1::2] *= scale_yx[:, 0]
						return boxes



def        UpperCAmelCase__   (				_lowerCAmelCase    :			Union[str, Any],      _lowerCAmelCase    :			Tuple[int, int])    ->		List[str]:



						"""simple docstring"""

						assert torch.isfinite(_lowerCAmelCase).all(), "Box tensor contains infinite or NaN!"
						snake_case				,					snake_case :       Union[str, Any]				=    box_size
						tensor[:, 0].clamp_(min=0,      max=_lowerCAmelCase)
						tensor[:, 1].clamp_(min=0,      max=_lowerCAmelCase)
						tensor[:, 2].clamp_(min=0,      max=_lowerCAmelCase)
						tensor[:, 3].clamp_(min=0,      max=_lowerCAmelCase)





