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

			_SCREAMING_SNAKE_CASE:    str     						=							True
except ImportError:
			_SCREAMING_SNAKE_CASE:    Optional[int]     						=							False


try:
			from torch.hub import _get_torch_home

			_SCREAMING_SNAKE_CASE:    str     						=							_get_torch_home()
except ImportError:
			_SCREAMING_SNAKE_CASE:    Union[str, Any]     						=							os.path.expanduser(
			    os.getenv('''TORCH_HOME''', os.path.join(os.getenv('''XDG_CACHE_HOME''', '''~/.cache'''), '''torch'''))
			)

_SCREAMING_SNAKE_CASE:    Dict     						=							os.path.join(torch_cache_home, '''transformers''')

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






def  UpperCAmelCase__(    lowerCamelCase_=OBJECTS				,						lowerCamelCase_=ATTRIBUTES	):



			"""simple docstring"""





			_snake_case														=   []
			with open(lowerCamelCase_	) as f:
						for object in f.readlines():
									vg_classes.append(object.split(","	)[0].lower().strip()	)

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






def  UpperCAmelCase__(    lowerCamelCase_	):



			"""simple docstring"""





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

class 						_SCREAMING_SNAKE_CASE				:






		"""simple docstring"""







		A_    			=   {}



		def __init__(      self     :					Optional[Any]	,       __SCREAMING_SNAKE_CASE     :					dict	,       __SCREAMING_SNAKE_CASE     :					str = "root"	,       __SCREAMING_SNAKE_CASE     :					Optional[int]=0 ):






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

					_snake_case														=   d



		def __repr__(      self     :					Dict ):






					"""simple docstring"""
					return str(list((self._pointer.keys()) ) )



		def __setattr__(      self     :					Any	,       __SCREAMING_SNAKE_CASE     :					Optional[Any]	,       __SCREAMING_SNAKE_CASE     :					Any ):






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



		def 					_a					(      self     :					int ):






					"""simple docstring"""
					return self._pointer



		def 					_a					(      self     :					List[str]	,       __SCREAMING_SNAKE_CASE     :					List[str]	,       __SCREAMING_SNAKE_CASE     :					Any ):






					"""simple docstring"""
					with open(F'{file_name}'	,       "w" ) as stream:
								dump(__SCREAMING_SNAKE_CASE	,       __SCREAMING_SNAKE_CASE )



		def 					_a					(      self     :					Optional[int]	,       __SCREAMING_SNAKE_CASE     :					Optional[Any]	,       __SCREAMING_SNAKE_CASE     :					List[str] ):






					"""simple docstring"""
					with open(F'{file_name}'	,       "w" ) as stream:
								json.dump(__SCREAMING_SNAKE_CASE	,       __SCREAMING_SNAKE_CASE )



		@staticmethod
		def 					_a					(      __SCREAMING_SNAKE_CASE     :					Tuple ):






					"""simple docstring"""
					with open(__SCREAMING_SNAKE_CASE ) as stream:
								_snake_case														=   load(__SCREAMING_SNAKE_CASE	,       Loader=__SCREAMING_SNAKE_CASE )
					return data



		def __str__(      self     :					List[str] ):






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



		@classmethod
		def 					_a					(      cls     :					List[str]	,       __SCREAMING_SNAKE_CASE     :					str	,       **__SCREAMING_SNAKE_CASE     :					Any ):






					"""simple docstring"""
					_snake_case							,			_snake_case														=   cls.get_config_dict(__SCREAMING_SNAKE_CASE	,       **__SCREAMING_SNAKE_CASE )
					return cls(__SCREAMING_SNAKE_CASE )







		@classmethod
		def 					_a					(      cls     :					str	,       __SCREAMING_SNAKE_CASE     :					str	,       **__SCREAMING_SNAKE_CASE     :					Union[str, Any] ):






					"""simple docstring"""
					_snake_case														=   kwargs.pop("cache_dir"	,       __SCREAMING_SNAKE_CASE )
					_snake_case														=   kwargs.pop("force_download"	,       __SCREAMING_SNAKE_CASE )
					_snake_case														=   kwargs.pop("resume_download"	,       __SCREAMING_SNAKE_CASE )
					_snake_case														=   kwargs.pop("proxies"	,       __SCREAMING_SNAKE_CASE )
					_snake_case														=   kwargs.pop("local_files_only"	,       __SCREAMING_SNAKE_CASE )

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

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

								_snake_case														=   Config.load_yaml(__SCREAMING_SNAKE_CASE )

					except EnvironmentError:
								_snake_case														=   "Can't load config for"
								raise EnvironmentError(__SCREAMING_SNAKE_CASE )

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

					return Config.load_yaml(__SCREAMING_SNAKE_CASE ), kwargs






def  UpperCAmelCase__(    lowerCamelCase_	):



			"""simple docstring"""





			_snake_case														=   torch.load("dump.pt"				,						map_location=in_tensor.device	)
			_snake_case														=   in_tensor.numpy()
			_snake_case														=   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.0_1				,						atol=0.1	), (
			    f'{sum([1 for x in np.isclose(lowerCamelCase_				,						lowerCamelCase_				,						rtol=0.0_1				,						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  UpperCAmelCase__(    lowerCamelCase_	):



			"""simple docstring"""





			_snake_case														=   urlparse(lowerCamelCase_	)
			return parsed.scheme in ("http", "https")






def  UpperCAmelCase__(    lowerCamelCase_				,						lowerCamelCase_				,						lowerCamelCase_=True	):



			"""simple docstring"""





			_snake_case														=   CLOUDFRONT_DISTRIB_PREFIX if use_cdn else S3_BUCKET_PREFIX
			_snake_case														=   "/" not in model_id
			if legacy_format:
						return f'{endpoint}/{model_id}-{filename}'
			else:
						return f'{endpoint}/{model_id}/{filename}'






def  UpperCAmelCase__(    lowerCamelCase_				,						lowerCamelCase_				,						lowerCamelCase_=None				,						lowerCamelCase_=0				,						lowerCamelCase_=None				,						):



			"""simple docstring"""





			_snake_case														=   "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
			_snake_case														=   {"user-agent": ua}
			if resume_size > 0:
						_snake_case														=   "bytes=%d-" % (resume_size,)
			_snake_case														=   requests.get(lowerCamelCase_				,						stream=lowerCamelCase_				,						proxies=lowerCamelCase_				,						headers=lowerCamelCase_	)
			if response.status_code == 416:  # Range not satisfiable
						return
			_snake_case														=   response.headers.get("Content-Length"	)
			_snake_case														=   resume_size + int(lowerCamelCase_	) if content_length is not None else None
			_snake_case														=   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  UpperCAmelCase__(    lowerCamelCase_				,						lowerCamelCase_=None				,						lowerCamelCase_=False				,						lowerCamelCase_=None				,						lowerCamelCase_=10				,						lowerCamelCase_=False				,						lowerCamelCase_=None				,						lowerCamelCase_=False				,						):



			"""simple docstring"""





			if cache_dir is None:
						_snake_case														=   TRANSFORMERS_CACHE
			if isinstance(lowerCamelCase_				,						lowerCamelCase_	):
						_snake_case														=   str(lowerCamelCase_	)

			os.makedirs(lowerCamelCase_				,						exist_ok=lowerCamelCase_	)

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

			_snake_case														=   url_to_filename(lowerCamelCase_				,						lowerCamelCase_	)

			# get cache path to put the file
			_snake_case														=   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:
									_snake_case														=   [
									    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.
			_snake_case														=   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:
									_snake_case														=   cache_path + ".incomplete"

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

									_snake_case														=   _resumable_file_manager
									if os.path.exists(lowerCamelCase_	):
												_snake_case														=   os.stat(lowerCamelCase_	).st_size
									else:
												_snake_case														=   0
						else:
									_snake_case														=   partial(tempfile.NamedTemporaryFile				,						dir=lowerCamelCase_				,						delete=lowerCamelCase_	)
									_snake_case														=   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_	)

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

			return cache_path






def  UpperCAmelCase__(    lowerCamelCase_				,						lowerCamelCase_=None	):



			"""simple docstring"""





			_snake_case														=   url.encode("utf-8"	)
			_snake_case														=   shaaaa(lowerCamelCase_	)
			_snake_case														=   url_hash.hexdigest()

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

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

			return filename






def  UpperCAmelCase__(    lowerCamelCase_				,						lowerCamelCase_=None				,						lowerCamelCase_=False				,						lowerCamelCase_=None				,						lowerCamelCase_=False				,						lowerCamelCase_=None				,						lowerCamelCase_=False				,						lowerCamelCase_=False				,						lowerCamelCase_=False				,						):



			"""simple docstring"""





			if cache_dir is None:
						_snake_case														=   TRANSFORMERS_CACHE
			if isinstance(lowerCamelCase_				,						lowerCamelCase_	):
						_snake_case														=   str(lowerCamelCase_	)
			if isinstance(lowerCamelCase_				,						lowerCamelCase_	):
						_snake_case														=   str(lowerCamelCase_	)

			if is_remote_url(lowerCamelCase_	):
						# URL, so get it from the cache (downloading if necessary)
						_snake_case														=   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.
						_snake_case														=   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/"
						_snake_case							,			_snake_case														=   os.path.split(lowerCamelCase_	)
						_snake_case														=   output_file.replace("."				,						"-"	) + "-extracted"
						_snake_case														=   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
						_snake_case														=   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_	):
												_snake_case														=   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  UpperCAmelCase__(    lowerCamelCase_				,						lowerCamelCase_=","	):



			"""simple docstring"""





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






def  UpperCAmelCase__(    lowerCamelCase_	):



			"""simple docstring"""





			_snake_case														=   requests.get(lowerCamelCase_	)
			_snake_case														=   np.array(Image.open(BytesIO(response.content	)	)	)
			return img






def  UpperCAmelCase__(    lowerCamelCase_	):



			"""simple docstring"""





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






def  UpperCAmelCase__(    ):



			"""simple docstring"""





			print(f'{os.path.abspath(os.path.join(lowerCamelCase_				,						os.pardir	)	)}/demo.ipynb'	)






def  UpperCAmelCase__(    lowerCamelCase_				,						lowerCamelCase_="RGB"	):



			"""simple docstring"""





			assert isinstance(lowerCamelCase_				,						lowerCamelCase_	)
			if os.path.isfile(lowerCamelCase_	):
						_snake_case														=   cva.imread(lowerCamelCase_	)
			else:
						_snake_case														=   get_image_from_url(lowerCamelCase_	)
						assert img is not None, f'could not connect to: {im}'
			_snake_case														=   cva.cvtColor(lowerCamelCase_				,						cva.COLOR_BGR2RGB	)
			if input_format == "RGB":
						_snake_case														=   img[:, :, ::-1]
			return img







def  UpperCAmelCase__(    lowerCamelCase_				,						lowerCamelCase_=1	):



			"""simple docstring"""





			return (images[i : i + batch] for i in range(0				,						len(lowerCamelCase_	)				,						lowerCamelCase_	))


import collections
import types

import numpy as np

from ..utils import (
    add_end_docstrings,
    is_tensorflow_probability_available,
    is_tf_available,
    is_torch_available,
    requires_backends,
)
from .base import PIPELINE_INIT_ARGS, ArgumentHandler, Dataset, Pipeline, PipelineException


if is_torch_available():
			import torch

			from ..models.auto.modeling_auto import (
			    MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING,
			    MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING,
			)

if is_tf_available() and is_tensorflow_probability_available():
			import tensorflow as tf
			import tensorflow_probability as tfp

			from ..models.auto.modeling_tf_auto import (
			    TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING,
			    TF_MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING,
			)

class 						_SCREAMING_SNAKE_CASE				(  _lowercase				):






		"""simple docstring"""







		def __call__(      self     :					Union[str, Any]	,       __SCREAMING_SNAKE_CASE     :					int=None	,       __SCREAMING_SNAKE_CASE     :					str=None	,       **__SCREAMING_SNAKE_CASE     :					Union[str, Any] ):






					"""simple docstring"""
					# Returns tqa_pipeline_inputs of shape:
					# [
					#   {"table": pd.DataFrame, "query": List[str]},
					#   ...,
					#   {"table": pd.DataFrame, "query" : List[str]}
					# ]
					requires_backends(self	,       "pandas" )
					import pandas as pd

					if table is None:
								raise ValueError("Keyword argument `table` cannot be None." )
					elif query is None:
								if isinstance(__SCREAMING_SNAKE_CASE	,       __SCREAMING_SNAKE_CASE ) and table.get("query" ) is not None and table.get("table" ) is not None:
											_snake_case														=   [table]
								elif isinstance(__SCREAMING_SNAKE_CASE	,       __SCREAMING_SNAKE_CASE ) and len(__SCREAMING_SNAKE_CASE ) > 0:
											if not all(isinstance(__SCREAMING_SNAKE_CASE	,       __SCREAMING_SNAKE_CASE ) for d in table ):
														raise ValueError(
														    F'Keyword argument `table` should be a list of dict, but is {(type(__SCREAMING_SNAKE_CASE ) for d in table)}' )

											if table[0].get("query" ) is not None and table[0].get("table" ) is not None:
														_snake_case														=   table
											else:
														raise ValueError(
														    "If keyword argument `table` is a list of dictionaries, each dictionary should have a `table`"
														    F' and `query` key, but only dictionary has keys {table[0].keys()} `table` and `query` keys.' )
								elif Dataset is not None and isinstance(__SCREAMING_SNAKE_CASE	,       __SCREAMING_SNAKE_CASE ) or isinstance(__SCREAMING_SNAKE_CASE	,       types.GeneratorType ):
											return table
								else:
											raise ValueError(
											    "Invalid input. Keyword argument `table` should be either of type `dict` or `list`, but "
											    F'is {type(__SCREAMING_SNAKE_CASE )})' )
					else:
								_snake_case														=   [{"table": table, "query": query}]

					for tqa_pipeline_input in tqa_pipeline_inputs:
								if not isinstance(tqa_pipeline_input["table"]	,       pd.DataFrame ):
											if tqa_pipeline_input["table"] is None:
														raise ValueError("Table cannot be None." )

											_snake_case														=   pd.DataFrame(tqa_pipeline_input["table"] )

					return tqa_pipeline_inputs

@add_end_docstrings(_lowercase				)
class 						_SCREAMING_SNAKE_CASE				(  _lowercase				):






		"""simple docstring"""







		A_    			=   '''table,query'''



		def __init__(      self     :					Optional[Any]	,       __SCREAMING_SNAKE_CASE     :					Tuple=TableQuestionAnsweringArgumentHandler()	,       *__SCREAMING_SNAKE_CASE     :					Optional[int]	,       **__SCREAMING_SNAKE_CASE     :					List[Any] ):






					"""simple docstring"""
					super().__init__(*__SCREAMING_SNAKE_CASE	,       **__SCREAMING_SNAKE_CASE )
					_snake_case														=   args_parser

					self.check_model_type(
					    dict(
					        TF_MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING.items()
					        + TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING.items() )
					    if self.framework == "tf"
					    else dict(
					        MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING.items() + MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING.items() ) )

					_snake_case														=   bool(getattr(self.model.config	,       "aggregation_labels"	,       __SCREAMING_SNAKE_CASE ) ) and bool(
					    getattr(self.model.config	,       "num_aggregation_labels"	,       __SCREAMING_SNAKE_CASE ) )
					_snake_case														=   "tapas" if hasattr(self.model.config	,       "aggregation_labels" ) else None



		def 					_a					(      self     :					List[Any]	,       **__SCREAMING_SNAKE_CASE     :					str ):






					"""simple docstring"""
					return self.model(**__SCREAMING_SNAKE_CASE )



		def 					_a					(      self     :					Tuple	,       **__SCREAMING_SNAKE_CASE     :					List[Any] ):






					"""simple docstring"""
					if self.framework == "pt":
								_snake_case														=   []
								_snake_case														=   []
								_snake_case														=   None
								_snake_case														=   inputs["input_ids"].shape[0]

								_snake_case														=   inputs["input_ids"].to(self.device )
								_snake_case														=   inputs["attention_mask"].to(self.device )
								_snake_case														=   inputs["token_type_ids"].to(self.device )
								_snake_case														=   None

								for index in range(__SCREAMING_SNAKE_CASE ):
											# If sequences have already been processed, the token type IDs will be created according to the previous
											# answer.
											if prev_answers is not None:
														_snake_case														=   token_type_ids_example[:, 3]  # shape (seq_len,)
														_snake_case														=   np.zeros_like(prev_labels_example.cpu().numpy() )  # shape (seq_len,)

														_snake_case														=   token_type_ids[index]  # shape (seq_len, 7)
														for i in range(model_labels.shape[0] ):
																	_snake_case														=   token_type_ids_example[:, 0].tolist()[i]
																	_snake_case														=   token_type_ids_example[:, 1].tolist()[i] - 1
																	_snake_case														=   token_type_ids_example[:, 2].tolist()[i] - 1

																	if row_id >= 0 and col_id >= 0 and segment_id == 1:
																				_snake_case														=   int(prev_answers[(col_id, row_id)] )

														_snake_case														=   torch.from_numpy(__SCREAMING_SNAKE_CASE ).type(torch.long ).to(self.device )

											_snake_case														=   input_ids[index]
											_snake_case														=   attention_mask[index]  # shape (seq_len,)
											_snake_case														=   token_type_ids[index]  # shape (seq_len, 7)
											_snake_case														=   self.model(
											    input_ids=input_ids_example.unsqueeze(0 )	,       attention_mask=attention_mask_example.unsqueeze(0 )	,       token_type_ids=token_type_ids_example.unsqueeze(0 )	,       )
											_snake_case														=   outputs.logits

											if self.aggregate:
														all_aggregations.append(outputs.logits_aggregation )

											all_logits.append(__SCREAMING_SNAKE_CASE )

											_snake_case														=   torch.distributions.Bernoulli(logits=__SCREAMING_SNAKE_CASE )
											_snake_case														=   dist_per_token.probs * attention_mask_example.type(torch.floataa ).to(
											    dist_per_token.probs.device )

											_snake_case														=   collections.defaultdict(__SCREAMING_SNAKE_CASE )
											for i, p in enumerate(probabilities.squeeze().tolist() ):
														_snake_case														=   token_type_ids_example[:, 0].tolist()[i]
														_snake_case														=   token_type_ids_example[:, 1].tolist()[i] - 1
														_snake_case														=   token_type_ids_example[:, 2].tolist()[i] - 1
														if col >= 0 and row >= 0 and segment_id == 1:
																	coords_to_probs[(col, row)].append(__SCREAMING_SNAKE_CASE )

											_snake_case														=   {key: np.array(coords_to_probs[key] ).mean() > 0.5 for key in coords_to_probs}

								_snake_case														=   torch.cat(tuple(__SCREAMING_SNAKE_CASE )	,       0 )

								return (logits_batch,) if not self.aggregate else (logits_batch, torch.cat(tuple(__SCREAMING_SNAKE_CASE )	,       0 ))
					else:
								_snake_case														=   []
								_snake_case														=   []
								_snake_case														=   None
								_snake_case														=   inputs["input_ids"].shape[0]

								_snake_case														=   inputs["input_ids"]
								_snake_case														=   inputs["attention_mask"]
								_snake_case														=   inputs["token_type_ids"].numpy()
								_snake_case														=   None

								for index in range(__SCREAMING_SNAKE_CASE ):
											# If sequences have already been processed, the token type IDs will be created according to the previous
											# answer.
											if prev_answers is not None:
														_snake_case														=   token_type_ids_example[:, 3]  # shape (seq_len,)
														_snake_case														=   np.zeros_like(__SCREAMING_SNAKE_CASE	,       dtype=np.intaa )  # shape (seq_len,)

														_snake_case														=   token_type_ids[index]  # shape (seq_len, 7)
														for i in range(model_labels.shape[0] ):
																	_snake_case														=   token_type_ids_example[:, 0].tolist()[i]
																	_snake_case														=   token_type_ids_example[:, 1].tolist()[i] - 1
																	_snake_case														=   token_type_ids_example[:, 2].tolist()[i] - 1

																	if row_id >= 0 and col_id >= 0 and segment_id == 1:
																				_snake_case														=   int(prev_answers[(col_id, row_id)] )

														_snake_case														=   model_labels

											_snake_case														=   input_ids[index]
											_snake_case														=   attention_mask[index]  # shape (seq_len,)
											_snake_case														=   token_type_ids[index]  # shape (seq_len, 7)
											_snake_case														=   self.model(
											    input_ids=np.expand_dims(__SCREAMING_SNAKE_CASE	,       axis=0 )	,       attention_mask=np.expand_dims(__SCREAMING_SNAKE_CASE	,       axis=0 )	,       token_type_ids=np.expand_dims(__SCREAMING_SNAKE_CASE	,       axis=0 )	,       )
											_snake_case														=   outputs.logits

											if self.aggregate:
														all_aggregations.append(outputs.logits_aggregation )

											all_logits.append(__SCREAMING_SNAKE_CASE )

											_snake_case														=   tfp.distributions.Bernoulli(logits=__SCREAMING_SNAKE_CASE )
											_snake_case														=   dist_per_token.probs_parameter() * tf.cast(__SCREAMING_SNAKE_CASE	,       tf.floataa )

											_snake_case														=   collections.defaultdict(__SCREAMING_SNAKE_CASE )
											_snake_case														=   token_type_ids_example
											for i, p in enumerate(tf.squeeze(__SCREAMING_SNAKE_CASE ).numpy().tolist() ):
														_snake_case														=   token_type_ids_example[:, 0].tolist()[i]
														_snake_case														=   token_type_ids_example[:, 1].tolist()[i] - 1
														_snake_case														=   token_type_ids_example[:, 2].tolist()[i] - 1
														if col >= 0 and row >= 0 and segment_id == 1:
																	coords_to_probs[(col, row)].append(__SCREAMING_SNAKE_CASE )

											_snake_case														=   {key: np.array(coords_to_probs[key] ).mean() > 0.5 for key in coords_to_probs}

								_snake_case														=   tf.concat(tuple(__SCREAMING_SNAKE_CASE )	,       0 )

								return (logits_batch,) if not self.aggregate else (logits_batch, tf.concat(tuple(__SCREAMING_SNAKE_CASE )	,       0 ))



		def __call__(      self     :					str	,       *__SCREAMING_SNAKE_CASE     :					Optional[int]	,       **__SCREAMING_SNAKE_CASE     :					List[Any] ):






					"""simple docstring"""
					_snake_case														=   self._args_parser(*__SCREAMING_SNAKE_CASE	,       **__SCREAMING_SNAKE_CASE )

					_snake_case														=   super().__call__(__SCREAMING_SNAKE_CASE	,       **__SCREAMING_SNAKE_CASE )
					if len(__SCREAMING_SNAKE_CASE ) == 1:
								return results[0]
					return results



		def 					_a					(      self     :					Optional[int]	,       __SCREAMING_SNAKE_CASE     :					Optional[int]=None	,       __SCREAMING_SNAKE_CASE     :					Union[str, Any]=None	,       __SCREAMING_SNAKE_CASE     :					str=None	,       **__SCREAMING_SNAKE_CASE     :					Optional[int] ):






					"""simple docstring"""
					_snake_case														=   {}
					if padding is not None:
								_snake_case														=   padding
					if truncation is not None:
								_snake_case														=   truncation

					_snake_case														=   {}
					if sequential is not None:
								_snake_case														=   sequential
					return preprocess_params, forward_params, {}



		def 					_a					(      self     :					Any	,       __SCREAMING_SNAKE_CASE     :					Tuple	,       __SCREAMING_SNAKE_CASE     :					Optional[Any]=None	,       __SCREAMING_SNAKE_CASE     :					Union[str, Any]=True	,       __SCREAMING_SNAKE_CASE     :					str=None ):






					"""simple docstring"""
					if truncation is None:
								if self.type == "tapas":
											_snake_case														=   "drop_rows_to_fit"
								else:
											_snake_case														=   "do_not_truncate"

					_snake_case							,			_snake_case														=   pipeline_input["table"], pipeline_input["query"]
					if table.empty:
								raise ValueError("table is empty" )
					if query is None or query == "":
								raise ValueError("query is empty" )
					_snake_case														=   self.tokenizer(__SCREAMING_SNAKE_CASE	,       __SCREAMING_SNAKE_CASE	,       return_tensors=self.framework	,       truncation=__SCREAMING_SNAKE_CASE	,       padding=__SCREAMING_SNAKE_CASE )
					_snake_case														=   table
					return inputs



		def 					_a					(      self     :					Optional[int]	,       __SCREAMING_SNAKE_CASE     :					str	,       __SCREAMING_SNAKE_CASE     :					List[Any]=False ):






					"""simple docstring"""
					_snake_case														=   model_inputs.pop("table" )

					if self.type == "tapas":
								if sequential:
											_snake_case														=   self.sequential_inference(**__SCREAMING_SNAKE_CASE )
								else:
											_snake_case														=   self.batch_inference(**__SCREAMING_SNAKE_CASE )
					else:
								_snake_case														=   self.model.generate(**__SCREAMING_SNAKE_CASE )
					_snake_case														=   {"model_inputs": model_inputs, "table": table, "outputs": outputs}
					return model_outputs







		def 					_a					(      self     :					Dict	,       __SCREAMING_SNAKE_CASE     :					Optional[int] ):






					"""simple docstring"""
					_snake_case														=   model_outputs["model_inputs"]
					_snake_case														=   model_outputs["table"]
					_snake_case														=   model_outputs["outputs"]
					if self.type == "tapas":
								if self.aggregate:
											_snake_case							,			_snake_case														=   outputs[:2]
											_snake_case														=   self.tokenizer.convert_logits_to_predictions(__SCREAMING_SNAKE_CASE	,       __SCREAMING_SNAKE_CASE	,       __SCREAMING_SNAKE_CASE )
											_snake_case							,			_snake_case														=   predictions
											_snake_case														=   {i: self.model.config.aggregation_labels[pred] for i, pred in enumerate(__SCREAMING_SNAKE_CASE )}

											_snake_case														=   self.model.config.no_aggregation_label_index
											_snake_case														=   {
											    i: aggregators[i] + " > " for i, pred in enumerate(__SCREAMING_SNAKE_CASE ) if pred != no_agg_label_index
											}
								else:
											_snake_case														=   outputs[0]
											_snake_case														=   self.tokenizer.convert_logits_to_predictions(__SCREAMING_SNAKE_CASE	,       __SCREAMING_SNAKE_CASE )
											_snake_case														=   predictions[0]
											_snake_case														=   {}
											_snake_case														=   {}
								_snake_case														=   []
								for index, coordinates in enumerate(__SCREAMING_SNAKE_CASE ):
											_snake_case														=   [table.iat[coordinate] for coordinate in coordinates]
											_snake_case														=   aggregators.get(__SCREAMING_SNAKE_CASE	,       "" )
											_snake_case														=   aggregators_prefix.get(__SCREAMING_SNAKE_CASE	,       "" )
											_snake_case														=   {
											    "answer": aggregator_prefix + ", ".join(__SCREAMING_SNAKE_CASE ),
											    "coordinates": coordinates,
											    "cells": [table.iat[coordinate] for coordinate in coordinates],
											}
											if aggregator:
														_snake_case														=   aggregator

											answers.append(__SCREAMING_SNAKE_CASE )
								if len(__SCREAMING_SNAKE_CASE ) == 0:
											raise PipelineException("Empty answer" )
					else:
								_snake_case														=   [{"answer": answer} for answer in self.tokenizer.batch_decode(__SCREAMING_SNAKE_CASE	,       skip_special_tokens=__SCREAMING_SNAKE_CASE )]

					return answers if len(__SCREAMING_SNAKE_CASE ) > 1 else answers[0]

