

import copy
import fnmatch
import json
import os
import pickle as pkl
import shutil
import sys
import tarfile
import tempfile
from collections import OrderedDict
from contextlib import contextmanager
from functools import partial
from hashlib import shaaaa
from io import BytesIO
from pathlib import Path
from urllib.parse import urlparse
from zipfile import ZipFile, is_zipfile

import cva
import numpy as np
import requests
import wget
from filelock import FileLock
from PIL import Image
from tqdm.auto import tqdm
from yaml import Loader, dump, load


try:
				import torch

				_a:			Any       							=	True
except ImportError:
				_a:			Union[str, Any]       							=	False


try:
				from torch.hub import _get_torch_home

				_a:			Optional[int]       							=	_get_torch_home()
except ImportError:
				_a:			Optional[int]       							=	os.path.expanduser(
				    os.getenv("""TORCH_HOME""", os.path.join(os.getenv("""XDG_CACHE_HOME""", """~/.cache"""), """torch"""))
				)

_a:			List[str]       							=	os.path.join(torch_cache_home, """transformers""")

_a:			List[Any]       							=	"""https://cdn.huggingface.co"""
_a:			Optional[int]       							=	"""https://s3.amazonaws.com/models.huggingface.co/bert"""
_a:			List[str]       							=	"""/""".join(str(Path(__file__).resolve()).split("""/""")[:-1])
_a:			Tuple       							=	os.path.join(PATH, """config.yaml""")
_a:			Optional[int]       							=	os.path.join(PATH, """attributes.txt""")
_a:			Dict       							=	os.path.join(PATH, """objects.txt""")
_a:			Any       							=	os.getenv("""PYTORCH_PRETRAINED_BERT_CACHE""", default_cache_path)
_a:			Any       							=	os.getenv("""PYTORCH_TRANSFORMERS_CACHE""", PYTORCH_PRETRAINED_BERT_CACHE)
_a:			int       							=	os.getenv("""TRANSFORMERS_CACHE""", PYTORCH_TRANSFORMERS_CACHE)
_a:			Dict       							=	"""pytorch_model.bin"""
_a:			Any       							=	"""config.yaml"""



def 					__lowerCAmelCase					(  A=OBJECTS				,   A=ATTRIBUTES			):
	UpperCAmelCase_				 =	[]
	with open(__lowerCamelCase			) as f:
		for object in f.readlines():
			vg_classes.append(object.split(","			)[0].lower().strip()			)

	UpperCAmelCase_				 =	[]
	with open(__lowerCamelCase			) as f:
		for object in f.readlines():
			vg_attrs.append(object.split(","			)[0].lower().strip()			)
	return vg_classes, vg_attrs



def 					__lowerCAmelCase					(  A			):
	UpperCAmelCase_				 =	OrderedDict()
	with open(__lowerCamelCase				,   "rb"			) as f:
		UpperCAmelCase_				 =	pkl.load(__lowerCamelCase			)["model"]
	for k in copy.deepcopy(list(ckp.keys()			)			):
		UpperCAmelCase_				 =	ckp.pop(__lowerCamelCase			)
		if isinstance(__lowerCamelCase				,   np.ndarray			):
			UpperCAmelCase_				 =	torch.tensor(__lowerCamelCase			)
		else:
			assert isinstance(__lowerCamelCase				,   torch.tensor			), type(__lowerCamelCase			)
		UpperCAmelCase_				 =	v
	return r

class   __UpperCamelCase			:
	SCREAMING_SNAKE_CASE__			 =   {}




	def __init__(						self		:  List[Any]						,		lowerCAmelCase		:  Any						,		lowerCAmelCase		:  Tuple = "root"						,		lowerCAmelCase		:  Optional[int]=0							):


		'''simple docstring'''







		UpperCAmelCase_				 =	name
		UpperCAmelCase_				 =	level
		UpperCAmelCase_				 =	{}
		for k, v in dictionary.items():
			if v is None:
				raise ValueError()
			UpperCAmelCase_				 =	copy.deepcopy(__lowerCamelCase							)
			UpperCAmelCase_				 =	copy.deepcopy(__lowerCamelCase							)
			if isinstance(__lowerCamelCase						,		__lowerCamelCase							):
				UpperCAmelCase_				 =	Config(__lowerCamelCase						,		name=__lowerCamelCase						,		level=level + 1							)
			UpperCAmelCase_				 =	v
			setattr(self						,		__lowerCamelCase						,		__lowerCamelCase							)

		UpperCAmelCase_				 =	d




	def __repr__(						self		:  Any							):


		'''simple docstring'''







		return str(list((self._pointer.keys())							)							)




	def __setattr__(						self		:  List[Any]						,		lowerCAmelCase		:  Union[str, Any]						,		lowerCAmelCase		:  str							):


		'''simple docstring'''







		UpperCAmelCase_				 =	val
		UpperCAmelCase_				 =	val
		UpperCAmelCase_				 =	key.split("."							)
		UpperCAmelCase_				 =	len(__lowerCamelCase							) - 1
		UpperCAmelCase_				 =	self._pointer
		if len(__lowerCamelCase							) > 1:
			for i, l in enumerate(__lowerCamelCase							):
				if hasattr(self						,		__lowerCamelCase							) and isinstance(getattr(self						,		__lowerCamelCase							)						,		__lowerCamelCase							):
					setattr(getattr(self						,		__lowerCamelCase							)						,		".".join(levels[i:]							)						,		__lowerCamelCase							)
				if l == last_level:
					UpperCAmelCase_				 =	val
				else:
					UpperCAmelCase_				 =	pointer[l]




	def 					__A    (						self		:  List[str]							):


		'''simple docstring'''







		return self._pointer




	def 					__A    (						self		:  int						,		lowerCAmelCase		:  int						,		lowerCAmelCase		:  Tuple							):


		'''simple docstring'''







		with open(F"{file_name}"						,		"w"							) as stream:
			dump(__lowerCamelCase						,		__lowerCamelCase							)




	def 					__A    (						self		:  Tuple						,		lowerCAmelCase		:  Optional[Any]						,		lowerCAmelCase		:  Optional[Any]							):


		'''simple docstring'''







		with open(F"{file_name}"						,		"w"							) as stream:
			json.dump(__lowerCamelCase						,		__lowerCamelCase							)




	@staticmethod
	def 					__A    (						lowerCAmelCase		:  List[Any]							):


		'''simple docstring'''







		with open(__lowerCamelCase							) as stream:
			UpperCAmelCase_				 =	load(__lowerCamelCase						,		Loader=__lowerCamelCase							)
		return data




	def __str__(						self		:  int							):


		'''simple docstring'''







		UpperCAmelCase_				 =	"    "
		if self._name != "root":
			UpperCAmelCase_				 =	F"{t * (self._level-1)}{self._name}:\n"
		else:
			UpperCAmelCase_				 =	""
		UpperCAmelCase_				 =	self._level
		for i, (k, v) in enumerate(self._pointer.items()							):
			if isinstance(__lowerCamelCase						,		__lowerCamelCase							):
				r += F"{t * (self._level)}{v}\n"
				self._level += 1
			else:
				r += F"{t * (self._level)}{k}: {v} ({type(__lowerCamelCase							).__name__})\n"
			UpperCAmelCase_				 =	level
		return r[:-1]




	@classmethod
	def 					__A    (						cls		:  int						,		lowerCAmelCase		:  str						,		**lowerCAmelCase		:  Optional[int]							):


		'''simple docstring'''







		UpperCAmelCase_				 =	cls.get_config_dict(__lowerCamelCase						,		**__lowerCamelCase							)
		return cls(__lowerCamelCase							)




	@classmethod
	def 					__A    (						cls		:  List[str]						,		lowerCAmelCase		:  Optional[Any]						,		**lowerCAmelCase		:  Union[str, Any]							):


		'''simple docstring'''







		UpperCAmelCase_				 =	kwargs.pop("cache_dir"						,		__lowerCamelCase							)
		UpperCAmelCase_				 =	kwargs.pop("force_download"						,		__lowerCamelCase							)
		UpperCAmelCase_				 =	kwargs.pop("resume_download"						,		__lowerCamelCase							)
		UpperCAmelCase_				 =	kwargs.pop("proxies"						,		__lowerCamelCase							)
		UpperCAmelCase_				 =	kwargs.pop("local_files_only"						,		__lowerCamelCase							)

		if os.path.isdir(__lowerCamelCase							):
			UpperCAmelCase_				 =	os.path.join(__lowerCamelCase						,		__lowerCamelCase							)
		elif os.path.isfile(__lowerCamelCase							) or is_remote_url(__lowerCamelCase							):
			UpperCAmelCase_				 =	pretrained_model_name_or_path
		else:
			UpperCAmelCase_				 =	hf_bucket_url(__lowerCamelCase						,		filename=__lowerCamelCase						,		use_cdn=__lowerCamelCase							)

		try:
			# Load from URL or cache if already cached
			UpperCAmelCase_				 =	cached_path(
			    __lowerCamelCase						,		cache_dir=__lowerCamelCase						,		force_download=__lowerCamelCase						,		proxies=__lowerCamelCase						,		resume_download=__lowerCamelCase						,		local_files_only=__lowerCamelCase						,		)
			# Load config dict
			if resolved_config_file is None:
				raise EnvironmentError

			UpperCAmelCase_				 =	Config.load_yaml(__lowerCamelCase							)

		except EnvironmentError:
			UpperCAmelCase_				 =	"Can't load config for"
			raise EnvironmentError(__lowerCamelCase							)

		if resolved_config_file == config_file:
			print("loading configuration file from path"							)
		else:
			print("loading configuration file cache"							)

		return Config.load_yaml(__lowerCamelCase							), kwargs



def 					__lowerCAmelCase					(  A			):
	UpperCAmelCase_				 =	torch.load("dump.pt"				,   map_location=in_tensor.device			)
	UpperCAmelCase_				 =	in_tensor.numpy()
	UpperCAmelCase_				 =	out_tensor.numpy()[0]
	print(na.shape				,   na[0, 0, :5]			)
	print(na.shape				,   na[0, 0, :5]			)
	assert np.allclose(__lowerCamelCase				,   __lowerCamelCase				,   rtol=0.01				,   atol=0.1			), (
	    F"{sum([1 for x in np.isclose(__lowerCamelCase				,   __lowerCamelCase				,   rtol=0.01				,   atol=0.1			).flatten() if x is False]			)/len(na.flatten()			)*100:.4f} %"
	    " element-wise mismatch"
	)
	raise Exception("tensors are all good"			)

	# Hugging face functions below



def 					__lowerCAmelCase					(  A			):
	UpperCAmelCase_				 =	urlparse(__lowerCamelCase			)
	return parsed.scheme in ("http", "https")



def 					__lowerCAmelCase					(  A				,   A				,   A=True			):
	UpperCAmelCase_				 =	CLOUDFRONT_DISTRIB_PREFIX if use_cdn else S3_BUCKET_PREFIX
	UpperCAmelCase_				 =	"/" not in model_id
	if legacy_format:
		return F"{endpoint}/{model_id}-{filename}"
	else:
		return F"{endpoint}/{model_id}/{filename}"



def 					__lowerCAmelCase					(  A				,   A				,   A=None				,   A=0				,   A=None				,   ):
	UpperCAmelCase_				 =	"python/{}".format(sys.version.split()[0]			)
	if _torch_available:
		ua += "; torch/{}".format(torch.__version__			)
	if isinstance(__lowerCamelCase				,   __lowerCamelCase			):
		ua += "; " + "; ".join("{}/{}".format(__lowerCamelCase				,   __lowerCamelCase			) for k, v in user_agent.items()			)
	elif isinstance(__lowerCamelCase				,   __lowerCamelCase			):
		ua += "; " + user_agent
	UpperCAmelCase_				 =	{"user-agent": ua}
	if resume_size > 0:
		UpperCAmelCase_				 =	"bytes=%d-" % (resume_size,)
	UpperCAmelCase_				 =	requests.get(__lowerCamelCase				,   stream=__lowerCamelCase				,   proxies=__lowerCamelCase				,   headers=__lowerCamelCase			)
	if response.status_code == 416:  # Range not satisfiable
		return
	UpperCAmelCase_				 =	response.headers.get("Content-Length"			)
	UpperCAmelCase_				 =	resume_size + int(__lowerCamelCase			) if content_length is not None else None
	UpperCAmelCase_				 =	tqdm(
	    unit="B"				,   unit_scale=__lowerCamelCase				,   total=__lowerCamelCase				,   initial=__lowerCamelCase				,   desc="Downloading"				,   )
	for chunk in response.iter_content(chunk_size=1024			):
		if chunk:  # filter out keep-alive new chunks
			progress.update(len(__lowerCamelCase			)			)
			temp_file.write(__lowerCamelCase			)
	progress.close()



def 					__lowerCAmelCase					(  A				,   A=None				,   A=False				,   A=None				,   A=10				,   A=False				,   A=None				,   A=False				,   ):
	if cache_dir is None:
		UpperCAmelCase_				 =	TRANSFORMERS_CACHE
	if isinstance(__lowerCamelCase				,   __lowerCamelCase			):
		UpperCAmelCase_				 =	str(__lowerCamelCase			)

	os.makedirs(__lowerCamelCase				,   exist_ok=__lowerCamelCase			)

	UpperCAmelCase_				 =	None
	if not local_files_only:
		try:
			UpperCAmelCase_				 =	requests.head(__lowerCamelCase				,   allow_redirects=__lowerCamelCase				,   proxies=__lowerCamelCase				,   timeout=__lowerCamelCase			)
			if response.status_code == 200:
				UpperCAmelCase_				 =	response.headers.get("ETag"			)
		except (EnvironmentError, requests.exceptions.Timeout):
			# etag is already None
			pass

	UpperCAmelCase_				 =	url_to_filename(__lowerCamelCase				,   __lowerCamelCase			)

	# get cache path to put the file
	UpperCAmelCase_				 =	os.path.join(__lowerCamelCase				,   __lowerCamelCase			)

	# etag is None = we don't have a connection, or url doesn't exist, or is otherwise inaccessible.
	# try to get the last downloaded one
	if etag is None:
		if os.path.exists(__lowerCamelCase			):
			return cache_path
		else:
			UpperCAmelCase_				 =	[
			    file
			    for file in fnmatch.filter(os.listdir(__lowerCamelCase			)				,   filename + ".*"			)
			    if not file.endswith(".json"			) and not file.endswith(".lock"			)
			]
			if len(__lowerCamelCase			) > 0:
				return os.path.join(__lowerCamelCase				,   matching_files[-1]			)
			else:
				# If files cannot be found and local_files_only=True,
				# the models might've been found if local_files_only=False
				# Notify the user about that
				if local_files_only:
					raise ValueError(
					    "Cannot find the requested files in the cached path and outgoing traffic has been"
					    " disabled. To enable model look-ups and downloads online, set 'local_files_only'"
					    " to False."			)
				return None

    # From now on, etag is not None.
	if os.path.exists(__lowerCamelCase			) and not force_download:
		return cache_path

	# Prevent parallel downloads of the same file with a lock.
	UpperCAmelCase_				 =	cache_path + ".lock"
	with FileLock(__lowerCamelCase			):
		# If the download just completed while the lock was activated.
		if os.path.exists(__lowerCamelCase			) and not force_download:
			# Even if returning early like here, the lock will be released.
			return cache_path

		if resume_download:
			UpperCAmelCase_				 =	cache_path + ".incomplete"

			@contextmanager
			def _resumable_file_manager():
				with open(__lowerCamelCase				,   "a+b"			) as f:
					yield f

			UpperCAmelCase_				 =	_resumable_file_manager
			if os.path.exists(__lowerCamelCase			):
				UpperCAmelCase_				 =	os.stat(__lowerCamelCase			).st_size
			else:
				UpperCAmelCase_				 =	0
		else:
			UpperCAmelCase_				 =	partial(tempfile.NamedTemporaryFile				,   dir=__lowerCamelCase				,   delete=__lowerCamelCase			)
			UpperCAmelCase_				 =	0

		# Download to temporary file, then copy to cache dir once finished.
		# Otherwise you get corrupt cache entries if the download gets interrupted.
		with temp_file_manager() as temp_file:
			print(
			    "%s not found in cache or force_download set to True, downloading to %s"				,   __lowerCamelCase				,   temp_file.name				,   )

			http_get(
			    __lowerCamelCase				,   __lowerCamelCase				,   proxies=__lowerCamelCase				,   resume_size=__lowerCamelCase				,   user_agent=__lowerCamelCase				,   )

		os.replace(temp_file.name				,   __lowerCamelCase			)

		UpperCAmelCase_				 =	{"url": url, "etag": etag}
		UpperCAmelCase_				 =	cache_path + ".json"
		with open(__lowerCamelCase				,   "w"			) as meta_file:
			json.dump(__lowerCamelCase				,   __lowerCamelCase			)

	return cache_path



def 					__lowerCAmelCase					(  A				,   A=None			):
	UpperCAmelCase_				 =	url.encode("utf-8"			)
	UpperCAmelCase_				 =	shaaaa(__lowerCamelCase			)
	UpperCAmelCase_				 =	url_hash.hexdigest()

	if etag:
		UpperCAmelCase_				 =	etag.encode("utf-8"			)
		UpperCAmelCase_				 =	shaaaa(__lowerCamelCase			)
		filename += "." + etag_hash.hexdigest()

	if url.endswith(".h5"			):
		filename += ".h5"

	return filename



def 					__lowerCAmelCase					(  A				,   A=None				,   A=False				,   A=None				,   A=False				,   A=None				,   A=False				,   A=False				,   A=False				,   ):
	if cache_dir is None:
		UpperCAmelCase_				 =	TRANSFORMERS_CACHE
	if isinstance(__lowerCamelCase				,   __lowerCamelCase			):
		UpperCAmelCase_				 =	str(__lowerCamelCase			)
	if isinstance(__lowerCamelCase				,   __lowerCamelCase			):
		UpperCAmelCase_				 =	str(__lowerCamelCase			)

	if is_remote_url(__lowerCamelCase			):
		# URL, so get it from the cache (downloading if necessary)
		UpperCAmelCase_				 =	get_from_cache(
		    __lowerCamelCase				,   cache_dir=__lowerCamelCase				,   force_download=__lowerCamelCase				,   proxies=__lowerCamelCase				,   resume_download=__lowerCamelCase				,   user_agent=__lowerCamelCase				,   local_files_only=__lowerCamelCase				,   )
	elif os.path.exists(__lowerCamelCase			):
		# File, and it exists.
		UpperCAmelCase_				 =	url_or_filename
	elif urlparse(__lowerCamelCase			).scheme == "":
		# File, but it doesn't exist.
		raise EnvironmentError("file {} not found".format(__lowerCamelCase			)			)
	else:
		# Something unknown
		raise ValueError("unable to parse {} as a URL or as a local path".format(__lowerCamelCase			)			)

	if extract_compressed_file:
		if not is_zipfile(__lowerCamelCase			) and not tarfile.is_tarfile(__lowerCamelCase			):
			return output_path

		# Path where we extract compressed archives
		# We avoid '.' in dir name and add "-extracted" at the end: "./model.zip" => "./model-zip-extracted/"
		UpperCAmelCase_				 =	os.path.split(__lowerCamelCase			)
		UpperCAmelCase_				 =	output_file.replace("."				,   "-"			) + "-extracted"
		UpperCAmelCase_				 =	os.path.join(__lowerCamelCase				,   __lowerCamelCase			)

		if os.path.isdir(__lowerCamelCase			) and os.listdir(__lowerCamelCase			) and not force_extract:
			return output_path_extracted

		# Prevent parallel extractions
		UpperCAmelCase_				 =	output_path + ".lock"
		with FileLock(__lowerCamelCase			):
			shutil.rmtree(__lowerCamelCase				,   ignore_errors=__lowerCamelCase			)
			os.makedirs(__lowerCamelCase			)
			if is_zipfile(__lowerCamelCase			):
				with ZipFile(__lowerCamelCase				,   "r"			) as zip_file:
					zip_file.extractall(__lowerCamelCase			)
					zip_file.close()
			elif tarfile.is_tarfile(__lowerCamelCase			):
				UpperCAmelCase_				 =	tarfile.open(__lowerCamelCase			)
				tar_file.extractall(__lowerCamelCase			)
				tar_file.close()
			else:
				raise EnvironmentError("Archive format of {} could not be identified".format(__lowerCamelCase			)			)

		return output_path_extracted

	return output_path



def 					__lowerCAmelCase					(  A				,   A=","			):
	assert isinstance(__lowerCamelCase				,   __lowerCamelCase			)
	if os.path.isfile(__lowerCamelCase			):
		with open(__lowerCamelCase			) as f:
			UpperCAmelCase_				 =	eval(f.read()			)
	else:
		UpperCAmelCase_				 =	requests.get(__lowerCamelCase			)
		try:
			UpperCAmelCase_				 =	requests.json()
		except Exception:
			UpperCAmelCase_				 =	req.content.decode()
			assert data is not None, "could not connect"
			try:
				UpperCAmelCase_				 =	eval(__lowerCamelCase			)
			except Exception:
				UpperCAmelCase_				 =	data.split("\n"			)
		req.close()
	return data



def 					__lowerCAmelCase					(  A			):
	UpperCAmelCase_				 =	requests.get(__lowerCamelCase			)
	UpperCAmelCase_				 =	np.array(Image.open(BytesIO(response.content			)			)			)
	return img



def 					__lowerCAmelCase					(  A			):
	UpperCAmelCase_				 =	url.split("/"			)[-1]
	if fn not in os.listdir(os.getcwd()			):
		wget.download(__lowerCamelCase			)
	with open(__lowerCamelCase				,   "rb"			) as stream:
		UpperCAmelCase_				 =	pkl.load(__lowerCamelCase			)
	UpperCAmelCase_				 =	weights.pop("model"			)
	UpperCAmelCase_				 =	{}
	for k, v in model.items():
		UpperCAmelCase_				 =	torch.from_numpy(__lowerCamelCase			)
		if "running_var" in k:
			UpperCAmelCase_				 =	torch.tensor([0]			)
			UpperCAmelCase_				 =	k.replace("running_var"				,   "num_batches_tracked"			)
			UpperCAmelCase_				 =	zero
	return new



def 					__lowerCAmelCase					(  ):
	print(F"{os.path.abspath(os.path.join(__lowerCamelCase				,   os.pardir			)			)}/demo.ipynb"			)



def 					__lowerCAmelCase					(  A				,   A="RGB"			):
	assert isinstance(__lowerCamelCase				,   __lowerCamelCase			)
	if os.path.isfile(__lowerCamelCase			):
		UpperCAmelCase_				 =	cva.imread(__lowerCamelCase			)
	else:
		UpperCAmelCase_				 =	get_image_from_url(__lowerCamelCase			)
		assert img is not None, F"could not connect to: {im}"
	UpperCAmelCase_				 =	cva.cvtColor(__lowerCamelCase				,   cva.COLOR_BGR2RGB			)
	if input_format == "RGB":
		UpperCAmelCase_				 =	img[:, :, ::-1]
	return img




def 					__lowerCAmelCase					(  A				,   A=1			):
	return (images[i : i + batch] for i in range(0				,   len(__lowerCamelCase			)				,   __lowerCamelCase			))






import json
import os
import random
import shutil
import tempfile
import unittest

import numpy as np
import pytest

from transformers import BertTokenizer, BertTokenizerFast
from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES
from transformers.testing_utils import require_vision
from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available


if is_vision_available():
       from PIL import Image

       from transformers import FlavaImageProcessor, FlavaProcessor
       from transformers.models.flava.image_processing_flava import (
           FLAVA_CODEBOOK_MEAN,
           FLAVA_CODEBOOK_STD,
           FLAVA_IMAGE_MEAN,
           FLAVA_IMAGE_STD,
       )





@require_vision
class 	lowerCAmelCase__(       unittest.TestCase			):






       '''simple docstring'''


       def 			UpperCamelCase_	(					self							)	->   str:
            _SCREAMING_SNAKE_CASE				:		str  			=							tempfile.mkdtemp()

            # fmt: off
            _SCREAMING_SNAKE_CASE				:		Optional[Any]  			=							["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "want", "##want", "##ed", "wa", "un", "runn", "##ing", ",", "low", "lowest"]
            # fmt: on
            _SCREAMING_SNAKE_CASE				:		int  			=							os.path.join(self.tmpdirname			,  VOCAB_FILES_NAMES["vocab_file"]							)

            with open(self.vocab_file			,  "w"			,  encoding="utf-8"							) as fp:
                 fp.write("".join([x + "\n" for x in vocab_tokens]							)							)

            _SCREAMING_SNAKE_CASE				:		Any  			=							{
                "image_mean": FLAVA_IMAGE_MEAN,
                "image_std": FLAVA_IMAGE_STD,
                "do_normalize": True,
                "do_resize": True,
                "size": 2_2_4,
                "do_center_crop": True,
                "crop_size": 2_2_4,
                "input_size_patches": 1_4,
                "total_mask_patches": 7_5,
                "mask_group_max_patches": None,
                "mask_group_min_patches": 1_6,
                "mask_group_min_aspect_ratio": 0.3,
                "mask_group_max_aspect_ratio": None,
                "codebook_do_resize": True,
                "codebook_size": 1_1_2,
                "codebook_do_center_crop": True,
                "codebook_crop_size": 1_1_2,
                "codebook_do_map_pixels": True,
                "codebook_do_normalize": True,
                "codebook_image_mean": FLAVA_CODEBOOK_MEAN,
                "codebook_image_std": FLAVA_CODEBOOK_STD,
            }

            _SCREAMING_SNAKE_CASE				:		Union[str, Any]  			=							os.path.join(self.tmpdirname			,  __lowerCamelCase							)
            with open(self.image_processor_file			,  "w"			,  encoding="utf-8"							) as fp:
                 json.dump(__lowerCamelCase			,  __lowerCamelCase							)




       def 			UpperCamelCase_	(					self			,  **__lowerCamelCase							)	->   List[str]:
            return BertTokenizer.from_pretrained(self.tmpdirname			,  **__lowerCamelCase							)




       def 			UpperCamelCase_	(					self			,  **__lowerCamelCase							)	->   Optional[Any]:
            return BertTokenizerFast.from_pretrained(self.tmpdirname			,  **__lowerCamelCase							)




       def 			UpperCamelCase_	(					self			,  **__lowerCamelCase							)	->   Tuple:
            return FlavaImageProcessor.from_pretrained(self.tmpdirname			,  **__lowerCamelCase							)




       def 			UpperCamelCase_	(					self							)	->   int:
            shutil.rmtree(self.tmpdirname							)




       def 			UpperCamelCase_	(					self							)	->   Optional[int]:
            _SCREAMING_SNAKE_CASE				:		Optional[int]  			=							[np.random.randint(2_5_5			,  size=(3, 3_0, 4_0_0)			,  dtype=np.uinta							)]

            _SCREAMING_SNAKE_CASE				:		Union[str, Any]  			=							[Image.fromarray(np.moveaxis(__lowerCamelCase			,  0			,  -1							)							) for x in image_inputs]

            return image_inputs




       def 			UpperCamelCase_	(					self							)	->   Any:
            _SCREAMING_SNAKE_CASE				:		Dict  			=							self.get_tokenizer()
            _SCREAMING_SNAKE_CASE				:		Any  			=							self.get_rust_tokenizer()
            _SCREAMING_SNAKE_CASE				:		Dict  			=							self.get_image_processor()

            _SCREAMING_SNAKE_CASE				:		List[Any]  			=							FlavaProcessor(tokenizer=__lowerCamelCase			,  image_processor=__lowerCamelCase							)
            processor_slow.save_pretrained(self.tmpdirname							)
            _SCREAMING_SNAKE_CASE				:		Tuple  			=							FlavaProcessor.from_pretrained(self.tmpdirname			,  use_fast=__lowerCamelCase							)

            _SCREAMING_SNAKE_CASE				:		Optional[Any]  			=							FlavaProcessor(tokenizer=__lowerCamelCase			,  image_processor=__lowerCamelCase							)
            processor_fast.save_pretrained(self.tmpdirname							)
            _SCREAMING_SNAKE_CASE				:		int  			=							FlavaProcessor.from_pretrained(self.tmpdirname							)

            self.assertEqual(processor_slow.tokenizer.get_vocab()			,  tokenizer_slow.get_vocab()							)
            self.assertEqual(processor_fast.tokenizer.get_vocab()			,  tokenizer_fast.get_vocab()							)
            self.assertEqual(tokenizer_slow.get_vocab()			,  tokenizer_fast.get_vocab()							)
            self.assertIsInstance(processor_slow.tokenizer			,  __lowerCamelCase							)
            self.assertIsInstance(processor_fast.tokenizer			,  __lowerCamelCase							)

            self.assertEqual(processor_slow.image_processor.to_json_string()			,  image_processor.to_json_string()							)
            self.assertEqual(processor_fast.image_processor.to_json_string()			,  image_processor.to_json_string()							)
            self.assertIsInstance(processor_slow.image_processor			,  __lowerCamelCase							)
            self.assertIsInstance(processor_fast.image_processor			,  __lowerCamelCase							)




       def 			UpperCamelCase_	(					self							)	->   Optional[int]:
            _SCREAMING_SNAKE_CASE				:		Dict  			=							FlavaProcessor(tokenizer=self.get_tokenizer()			,  image_processor=self.get_image_processor()							)
            processor.save_pretrained(self.tmpdirname							)

            _SCREAMING_SNAKE_CASE				:		str  			=							self.get_tokenizer(bos_token="(BOS)"			,  eos_token="(EOS)"							)
            _SCREAMING_SNAKE_CASE				:		List[str]  			=							self.get_image_processor(do_normalize=__lowerCamelCase			,  padding_value=1.0							)

            _SCREAMING_SNAKE_CASE				:		Dict  			=							FlavaProcessor.from_pretrained(
                self.tmpdirname			,  bos_token="(BOS)"			,  eos_token="(EOS)"			,  do_normalize=__lowerCamelCase			,  padding_value=1.0							)

            self.assertEqual(processor.tokenizer.get_vocab()			,  tokenizer_add_kwargs.get_vocab()							)
            self.assertIsInstance(processor.tokenizer			,  __lowerCamelCase							)

            self.assertEqual(processor.image_processor.to_json_string()			,  image_processor_add_kwargs.to_json_string()							)
            self.assertIsInstance(processor.image_processor			,  __lowerCamelCase							)




       def 			UpperCamelCase_	(					self							)	->   Any:
            _SCREAMING_SNAKE_CASE				:		str  			=							self.get_image_processor()
            _SCREAMING_SNAKE_CASE				:		Union[str, Any]  			=							self.get_tokenizer()

            _SCREAMING_SNAKE_CASE				:		Any  			=							FlavaProcessor(tokenizer=__lowerCamelCase			,  image_processor=__lowerCamelCase							)

            _SCREAMING_SNAKE_CASE				:		int  			=							self.prepare_image_inputs()

            _SCREAMING_SNAKE_CASE				:		List[str]  			=							image_processor(__lowerCamelCase			,  return_tensors="np"							)
            _SCREAMING_SNAKE_CASE				:		str  			=							processor(images=__lowerCamelCase			,  return_tensors="np"							)

            for key in input_feat_extract.keys():
                 self.assertAlmostEqual(input_feat_extract[key].sum()			,  input_processor[key].sum()			,  delta=1E-2							)

            # With rest of the args
            random.seed(1_2_3_4							)
            _SCREAMING_SNAKE_CASE				:		List[Any]  			=							image_processor(
                __lowerCamelCase			,  return_image_mask=__lowerCamelCase			,  return_codebook_pixels=__lowerCamelCase			,  return_tensors="np"							)
            random.seed(1_2_3_4							)
            _SCREAMING_SNAKE_CASE				:		Optional[Any]  			=							processor(
                images=__lowerCamelCase			,  return_image_mask=__lowerCamelCase			,  return_codebook_pixels=__lowerCamelCase			,  return_tensors="np"							)

            for key in input_feat_extract.keys():
                 self.assertAlmostEqual(input_feat_extract[key].sum()			,  input_processor[key].sum()			,  delta=1E-2							)




       def 			UpperCamelCase_	(					self							)	->   int:
            _SCREAMING_SNAKE_CASE				:		Any  			=							self.get_image_processor()
            _SCREAMING_SNAKE_CASE				:		Union[str, Any]  			=							self.get_tokenizer()

            _SCREAMING_SNAKE_CASE				:		int  			=							FlavaProcessor(tokenizer=__lowerCamelCase			,  image_processor=__lowerCamelCase							)

            _SCREAMING_SNAKE_CASE				:		Optional[Any]  			=							"lower newer"

            _SCREAMING_SNAKE_CASE				:		Union[str, Any]  			=							processor(text=__lowerCamelCase							)

            _SCREAMING_SNAKE_CASE				:		List[str]  			=							tokenizer(__lowerCamelCase							)

            for key in encoded_tok.keys():
                 self.assertListEqual(encoded_tok[key]			,  encoded_processor[key]							)




       def 			UpperCamelCase_	(					self							)	->   Tuple:
            _SCREAMING_SNAKE_CASE				:		Union[str, Any]  			=							self.get_image_processor()
            _SCREAMING_SNAKE_CASE				:		Optional[Any]  			=							self.get_tokenizer()

            _SCREAMING_SNAKE_CASE				:		List[Any]  			=							FlavaProcessor(tokenizer=__lowerCamelCase			,  image_processor=__lowerCamelCase							)

            _SCREAMING_SNAKE_CASE				:		Any  			=							"lower newer"
            _SCREAMING_SNAKE_CASE				:		Dict  			=							self.prepare_image_inputs()

            _SCREAMING_SNAKE_CASE				:		List[Any]  			=							processor(text=__lowerCamelCase			,  images=__lowerCamelCase							)

            self.assertListEqual(list(inputs.keys()							)			,  ["input_ids", "token_type_ids", "attention_mask", "pixel_values"]							)

            # add extra args
            _SCREAMING_SNAKE_CASE				:		Tuple  			=							processor(text=__lowerCamelCase			,  images=__lowerCamelCase			,  return_codebook_pixels=__lowerCamelCase			,  return_image_mask=__lowerCamelCase							)

            self.assertListEqual(
                list(inputs.keys()							)			,  [
                    "input_ids",
                    "token_type_ids",
                    "attention_mask",
                    "pixel_values",
                    "codebook_pixel_values",
                    "bool_masked_pos",
                ]			,  )

            # test if it raises when no input is passed
            with pytest.raises(__lowerCamelCase							):
                 processor()




       def 			UpperCamelCase_	(					self							)	->   Dict:
            _SCREAMING_SNAKE_CASE				:		Optional[int]  			=							self.get_image_processor()
            _SCREAMING_SNAKE_CASE				:		str  			=							self.get_tokenizer()

            _SCREAMING_SNAKE_CASE				:		int  			=							FlavaProcessor(tokenizer=__lowerCamelCase			,  image_processor=__lowerCamelCase							)

            _SCREAMING_SNAKE_CASE				:		Optional[int]  			=							[[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]

            _SCREAMING_SNAKE_CASE				:		Dict  			=							processor.batch_decode(__lowerCamelCase							)
            _SCREAMING_SNAKE_CASE				:		Any  			=							tokenizer.batch_decode(__lowerCamelCase							)

            self.assertListEqual(__lowerCamelCase			,  __lowerCamelCase							)







       def 			UpperCamelCase_	(					self							)	->   Any:
            _SCREAMING_SNAKE_CASE				:		int  			=							self.get_image_processor()
            _SCREAMING_SNAKE_CASE				:		Union[str, Any]  			=							self.get_tokenizer()

            _SCREAMING_SNAKE_CASE				:		Dict  			=							FlavaProcessor(tokenizer=__lowerCamelCase			,  image_processor=__lowerCamelCase							)

            _SCREAMING_SNAKE_CASE				:		Optional[Any]  			=							"lower newer"
            _SCREAMING_SNAKE_CASE				:		Optional[int]  			=							self.prepare_image_inputs()

            _SCREAMING_SNAKE_CASE				:		List[Any]  			=							processor(text=__lowerCamelCase			,  images=__lowerCamelCase							)

            self.assertListEqual(list(inputs.keys()							)			,  processor.model_input_names							)