'''simple docstring'''





import asyncio
import os
import re
import sys
import tempfile
import unittest
from contextlib import contextmanager
from copy import deepcopy
from distutils.util import strtobool
from enum import Enum
from importlib.util import find_spec
from pathlib import Path
from unittest.mock import patch

import pyarrow as pa
import pytest
import requests
from packaging import version

from datasets import config


if config.PY_VERSION < version.parse("""3.8"""):
   import importlib_metadata
else:
   import importlib.metadata as importlib_metadata
def 						__A							(     UpperCAmelCase     ,UpperCAmelCase=False					)     ->			Dict:




      '''simple docstring'''


      try:
            _UpperCamelCase			:			str   			=						os.environ[key]
      except KeyError:
            # KEY isn't set, default to `default`.
            _UpperCamelCase			:			List[str]   			=						default
      else:
            # KEY is set, convert it to True or False.
            try:
                  _UpperCamelCase			:			int   			=						strtobool(lowerCamelCase__					)
            except ValueError:
                  # More values are supported, but let's keep the message simple.
                  raise ValueError(f'''If set, {key} must be yes or no.'''					)
      return _value


lowerCAmelCase_	:		Any			=     parse_flag_from_env("""RUN_SLOW""", default=False)
lowerCAmelCase_	:		str			=     parse_flag_from_env("""RUN_REMOTE""", default=False)
lowerCAmelCase_	:		Any			=     parse_flag_from_env("""RUN_LOCAL""", default=True)
lowerCAmelCase_	:		Union[str, Any]			=     parse_flag_from_env("""RUN_PACKAGED""", default=True)

# Compression
lowerCAmelCase_	:		Any			=     pytest.mark.skipif(not config.LZ4_AVAILABLE, reason="""test requires lz4""")
lowerCAmelCase_	:		Union[str, Any]			=     pytest.mark.skipif(not config.PY7ZR_AVAILABLE, reason="""test requires py7zr""")
lowerCAmelCase_	:		List[str]			=     pytest.mark.skipif(not config.ZSTANDARD_AVAILABLE, reason="""test requires zstandard""")

# Audio
lowerCAmelCase_	:		Dict			=     pytest.mark.skipif(
    # On Windows and OS X, soundfile installs sndfile
    find_spec("""soundfile""") is None or version.parse(importlib_metadata.version("""soundfile""")) < version.parse("""0.12.0"""),
    reason="""test requires sndfile>=0.12.1: 'pip install \"soundfile>=0.12.1\"'; """,
)

# Beam
lowerCAmelCase_	:		Tuple			=     pytest.mark.skipif(
    not config.BEAM_AVAILABLE or config.DILL_VERSION >= version.parse("""0.3.2"""),
    reason="""test requires apache-beam and a compatible dill version""",
)

# Dill-cloudpickle compatibility
lowerCAmelCase_	:		int			=     pytest.mark.skipif(
    config.DILL_VERSION <= version.parse("""0.3.2"""),
    reason="""test requires dill>0.3.2 for cloudpickle compatibility""",
)

# Windows
lowerCAmelCase_	:		str			=     pytest.mark.skipif(
    sys.platform == """win32""",
    reason="""test should not be run on Windows""",
)
def 						__A							(     UpperCAmelCase					)     ->			Any:




      '''simple docstring'''


      try:
            import faiss  # noqa
      except ImportError:
            _UpperCamelCase			:			List[str]   			=						unittest.skip("test requires faiss"					)(lowerCamelCase__					)
      return test_case
def 						__A							(     UpperCAmelCase					)     ->			List[Any]:




      '''simple docstring'''


      try:
            import regex  # noqa
      except ImportError:
            _UpperCamelCase			:			Tuple   			=						unittest.skip("test requires regex"					)(lowerCamelCase__					)
      return test_case
def 						__A							(     UpperCAmelCase					)     ->			List[str]:




      '''simple docstring'''


      try:
            import elasticsearch  # noqa
      except ImportError:
            _UpperCamelCase			:			List[str]   			=						unittest.skip("test requires elasticsearch"					)(lowerCamelCase__					)
      return test_case
def 						__A							(     UpperCAmelCase					)     ->			Optional[Any]:




      '''simple docstring'''


      try:
            import sqlalchemy  # noqa
      except ImportError:
            _UpperCamelCase			:			Any   			=						unittest.skip("test requires sqlalchemy"					)(lowerCamelCase__					)
      return test_case
def 						__A							(     UpperCAmelCase					)     ->			int:




      '''simple docstring'''


      if not config.TORCH_AVAILABLE:
            _UpperCamelCase			:			int   			=						unittest.skip("test requires PyTorch"					)(lowerCamelCase__					)
      return test_case
def 						__A							(     UpperCAmelCase					)     ->			Dict:




      '''simple docstring'''


      if not config.TF_AVAILABLE:
            _UpperCamelCase			:			List[str]   			=						unittest.skip("test requires TensorFlow"					)(lowerCamelCase__					)
      return test_case
def 						__A							(     UpperCAmelCase					)     ->			int:




      '''simple docstring'''


      if not config.JAX_AVAILABLE:
            _UpperCamelCase			:			str   			=						unittest.skip("test requires JAX"					)(lowerCamelCase__					)
      return test_case
def 						__A							(     UpperCAmelCase					)     ->			List[Any]:




      '''simple docstring'''


      if not config.PIL_AVAILABLE:
            _UpperCamelCase			:			Union[str, Any]   			=						unittest.skip("test requires Pillow"					)(lowerCamelCase__					)
      return test_case
def 						__A							(     UpperCAmelCase					)     ->			Tuple:




      '''simple docstring'''


      try:
            import transformers  # noqa F401
      except ImportError:
            return unittest.skip("test requires transformers"					)(lowerCamelCase__					)
      else:
            return test_case
def 						__A							(     UpperCAmelCase					)     ->			int:




      '''simple docstring'''


      try:
            import tiktoken  # noqa F401
      except ImportError:
            return unittest.skip("test requires tiktoken"					)(lowerCamelCase__					)
      else:
            return test_case
def 						__A							(     UpperCAmelCase					)     ->			Union[str, Any]:




      '''simple docstring'''


      try:
            import spacy  # noqa F401
      except ImportError:
            return unittest.skip("test requires spacy"					)(lowerCamelCase__					)
      else:
            return test_case
def 						__A							(     UpperCAmelCase					)     ->			Any:




      '''simple docstring'''


      def _require_spacy_model(UpperCAmelCase					):
            try:
                  import spacy  # noqa F401

                  spacy.load(lowerCamelCase__					)
            except ImportError:
                  return unittest.skip("test requires spacy"					)(lowerCamelCase__					)
            except OSError:
                  return unittest.skip("test requires spacy model '{}'".format(lowerCamelCase__					)					)(lowerCamelCase__					)
            else:
                  return test_case

      return _require_spacy_model
def 						__A							(     UpperCAmelCase					)     ->			Optional[Any]:




      '''simple docstring'''


      try:
            import pyspark  # noqa F401
      except ImportError:
            return unittest.skip("test requires pyspark"					)(lowerCamelCase__					)
      else:
            return test_case
def 						__A							(     UpperCAmelCase					)     ->			Optional[Any]:




      '''simple docstring'''


      try:
            import joblibspark  # noqa F401
      except ImportError:
            return unittest.skip("test requires joblibspark"					)(lowerCamelCase__					)
      else:
            return test_case
def 						__A							(     UpperCAmelCase					)     ->			Tuple:




      '''simple docstring'''


      if not _run_slow_tests or _run_slow_tests == 0:
            _UpperCamelCase			:			int   			=						unittest.skip("test is slow"					)(lowerCamelCase__					)
      return test_case
def 						__A							(     UpperCAmelCase					)     ->			str:




      '''simple docstring'''


      if not _run_local_tests or _run_local_tests == 0:
            _UpperCamelCase			:			List[str]   			=						unittest.skip("test is local"					)(lowerCamelCase__					)
      return test_case
def 						__A							(     UpperCAmelCase					)     ->			Dict:




      '''simple docstring'''


      if not _run_packaged_tests or _run_packaged_tests == 0:
            _UpperCamelCase			:			Tuple   			=						unittest.skip("test is packaged"					)(lowerCamelCase__					)
      return test_case
def 						__A							(     UpperCAmelCase					)     ->			Any:




      '''simple docstring'''


      if not _run_remote_tests or _run_remote_tests == 0:
            _UpperCamelCase			:			Any   			=						unittest.skip("test requires remote"					)(lowerCamelCase__					)
      return test_case
def 						__A							(     *UpperCAmelCase					)     ->			Tuple:




      '''simple docstring'''


      def decorate(cls					):
            for name, fn in cls.__dict__.items():
                  if callable(lowerCamelCase__					) and name.startswith("test"					):
                        for decorator in decorators:
                              _UpperCamelCase			:			Tuple   			=						decorator(lowerCamelCase__					)
                        setattr(cls     ,lowerCamelCase__     ,lowerCamelCase__					)
            return cls

      return decorate




class 		SCREAMING_SNAKE_CASE     (					SCREAMING_SNAKE_CASE	):







    '''simple docstring'''
    pass





class 		SCREAMING_SNAKE_CASE     (					SCREAMING_SNAKE_CASE	):







    '''simple docstring'''
    UpperCAmelCase__							=							0
    UpperCAmelCase__							=							1
    UpperCAmelCase__							=							2





@contextmanager
def 						__A							(     UpperCAmelCase=OfflineSimulationMode.CONNECTION_FAILS     ,UpperCAmelCase=1E-16					)     ->			int:




      '''simple docstring'''
      _UpperCamelCase			:			Optional[Any]   			=						requests.Session().request

      def timeout_request(UpperCAmelCase     ,UpperCAmelCase     ,UpperCAmelCase     ,**UpperCAmelCase					):
            # Change the url to an invalid url so that the connection hangs
            _UpperCamelCase			:			List[Any]   			=						"https://10.255.255.1"
            if kwargs.get("timeout"					) is None:
                  raise RequestWouldHangIndefinitelyError(
                      f'''Tried a call to {url} in offline mode with no timeout set. Please set a timeout.'''					)
            _UpperCamelCase			:			str   			=						timeout
            try:
                  return online_request(lowerCamelCase__     ,lowerCamelCase__     ,**lowerCamelCase__					)
            except Exception as e:
                  # The following changes in the error are just here to make the offline timeout error prettier
                  _UpperCamelCase			:			Any   			=						url
                  _UpperCamelCase			:			Any   			=						e.args[0]
                  _UpperCamelCase			:			Optional[Any]   			=						(max_retry_error.args[0].replace("10.255.255.1"     ,f'''OfflineMock[{url}]'''					),)
                  _UpperCamelCase			:			str   			=						(max_retry_error,)
                  raise

      def raise_connection_error(UpperCAmelCase     ,UpperCAmelCase     ,**UpperCAmelCase					):
            raise requests.ConnectionError("Offline mode is enabled."     ,request=lowerCamelCase__					)

      if mode is OfflineSimulationMode.CONNECTION_FAILS:
            with patch("requests.Session.send"     ,lowerCamelCase__					):
                  yield
      elif mode is OfflineSimulationMode.CONNECTION_TIMES_OUT:
            # inspired from https://stackoverflow.com/a/904609
            with patch("requests.Session.request"     ,lowerCamelCase__					):
                  yield
      elif mode is OfflineSimulationMode.HF_DATASETS_OFFLINE_SET_TO_1:
            with patch("datasets.config.HF_DATASETS_OFFLINE"     ,lowerCamelCase__					):
                  yield
      else:
            raise ValueError("Please use a value from the OfflineSimulationMode enum."					)
@contextmanager
def 						__A							(     *UpperCAmelCase     ,**UpperCAmelCase					)     ->			str:




      '''simple docstring'''
      _UpperCamelCase			:			int   			=						str(Path().resolve()					)
      with tempfile.TemporaryDirectory(*lowerCamelCase__     ,**lowerCamelCase__					) as tmp_dir:
            try:
                  os.chdir(lowerCamelCase__					)
                  yield
            finally:
                  os.chdir(lowerCamelCase__					)
@contextmanager
def 						__A							(     )     ->			Any:




      '''simple docstring'''
      import gc

      gc.collect()
      _UpperCamelCase			:			Optional[Any]   			=						pa.total_allocated_bytes()
      yield
      assert pa.total_allocated_bytes() - previous_allocated_memory > 0, "Arrow memory didn't increase."
@contextmanager
def 						__A							(     )     ->			List[Any]:




      '''simple docstring'''
      import gc

      gc.collect()
      _UpperCamelCase			:			Optional[Any]   			=						pa.total_allocated_bytes()
      yield
      assert pa.total_allocated_bytes() - previous_allocated_memory <= 0, "Arrow memory wasn't expected to increase."
def 						__A							(     UpperCAmelCase     ,UpperCAmelCase					)     ->			str:




      '''simple docstring'''
      return deepcopy(lowerCamelCase__					).integers(0     ,1_0_0     ,1_0					).tolist() == deepcopy(lowerCamelCase__					).integers(0     ,1_0_0     ,1_0					).tolist()
def 						__A							(     UpperCAmelCase					)     ->			int:




      '''simple docstring'''
      import decorator
      from requests.exceptions import HTTPError

      def _wrapper(UpperCAmelCase     ,*UpperCAmelCase     ,**UpperCAmelCase					):
            try:
                  return func(*lowerCamelCase__     ,**lowerCamelCase__					)
            except HTTPError as err:
                  if str(lowerCamelCase__					).startswith("500"					) or str(lowerCamelCase__					).startswith("502"					):
                        pytest.xfail(str(lowerCamelCase__					)					)
                  raise err

      return decorator.decorator(_wrapper     ,lowerCamelCase__					)




class 		SCREAMING_SNAKE_CASE     :







    '''simple docstring'''





    def __init__(						self					:						List[Any]       ,		lowercase__					:						str       ,		lowercase__					:						int       ,		lowercase__					:						Optional[Any]					)							->Any:


          '''simple docstring'''




          _UpperCamelCase			:			Optional[Any]   			=						returncode
          _UpperCamelCase			:			Optional[int]   			=						stdout
          _UpperCamelCase			:			int   			=						stderr





async def 						__A							(     UpperCAmelCase     ,UpperCAmelCase					)     ->			Union[str, Any]:




      '''simple docstring'''


      while True:
            _UpperCamelCase			:			Any   			=						await stream.readline()
            if line:
                  callback(lowerCamelCase__					)
            else:
                  break
async def 						__A							(     UpperCAmelCase     ,UpperCAmelCase=None     ,UpperCAmelCase=None     ,UpperCAmelCase=None     ,UpperCAmelCase=False     ,UpperCAmelCase=False					)     ->			_RunOutput:




      '''simple docstring'''


      if echo:
            print("\nRunning: "     ," ".join(lowerCamelCase__					)					)

      _UpperCamelCase			:			Optional[Any]   			=						await asyncio.create_subprocess_exec(
          cmd[0]     ,*cmd[1:]     ,stdin=lowerCamelCase__     ,stdout=asyncio.subprocess.PIPE     ,stderr=asyncio.subprocess.PIPE     ,env=lowerCamelCase__     ,)

      # note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe
      # https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait
      #
      # If it starts hanging, will need to switch to the following code. The problem is that no data
      # will be seen until it's done and if it hangs for example there will be no debug info.
      # out, err = await p.communicate()
      # return _RunOutput(p.returncode, out, err)

      _UpperCamelCase			:			Union[str, Any]   			=						[]
      _UpperCamelCase			:			Tuple   			=						[]

      def tee(UpperCAmelCase     ,UpperCAmelCase     ,UpperCAmelCase     ,UpperCAmelCase=""					):
            _UpperCamelCase			:			List[Any]   			=						line.decode("utf-8"					).rstrip()
            sink.append(lowerCamelCase__					)
            if not quiet:
                  print(lowerCamelCase__     ,lowerCamelCase__     ,file=lowerCamelCase__					)

    # XXX: the timeout doesn't seem to make any difference here
      await asyncio.wait(
          [
              _read_stream(p.stdout     ,lambda UpperCAmelCase					: tee(lowerCamelCase__     ,lowerCamelCase__     ,sys.stdout     ,label="stdout:"					)					),
              _read_stream(p.stderr     ,lambda UpperCAmelCase					: tee(lowerCamelCase__     ,lowerCamelCase__     ,sys.stderr     ,label="stderr:"					)					),
          ]     ,timeout=lowerCamelCase__     ,)
      return _RunOutput(await p.wait()     ,lowerCamelCase__     ,lowerCamelCase__					)
def 						__A							(     UpperCAmelCase     ,UpperCAmelCase=None     ,UpperCAmelCase=None     ,UpperCAmelCase=1_8_0     ,UpperCAmelCase=False     ,UpperCAmelCase=True					)     ->			_RunOutput:




      '''simple docstring'''
      _UpperCamelCase			:			Dict   			=						asyncio.get_event_loop()
      _UpperCamelCase			:			int   			=						loop.run_until_complete(
          _stream_subprocess(lowerCamelCase__     ,env=lowerCamelCase__     ,stdin=lowerCamelCase__     ,timeout=lowerCamelCase__     ,quiet=lowerCamelCase__     ,echo=lowerCamelCase__					)					)

      _UpperCamelCase			:			List[Any]   			=						" ".join(lowerCamelCase__					)
      if result.returncode > 0:
            _UpperCamelCase			:			Dict   			=						"\n".join(result.stderr					)
            raise RuntimeError(
                f'''\'{cmd_str}\' failed with returncode {result.returncode}\n\n'''
                f'''The combined stderr from workers follows:\n{stderr}'''					)

      # check that the subprocess actually did run and produced some output, should the test rely on
      # the remote side to do the testing
      if not result.stdout and not result.stderr:
            raise RuntimeError(f'''\'{cmd_str}\' produced no output.'''					)

      return result
def 						__A							(     )     ->			str:




      '''simple docstring'''
      _UpperCamelCase			:			Tuple   			=						os.environ.get("PYTEST_XDIST_WORKER"     ,"gw0"					)
      _UpperCamelCase			:			Tuple   			=						re.sub(R"^gw"     ,""     ,lowerCamelCase__     ,0     ,re.M					)
      return int(lowerCamelCase__					)






def 						__A							(     )     ->			Optional[Any]:




      '''simple docstring'''
      _UpperCamelCase			:			Dict   			=						2_9_5_0_0
      _UpperCamelCase			:			Any   			=						pytest_xdist_worker_id()
      return port + uniq_delta



'''simple docstring'''





from typing import List, Optional, Union

from ...configuration_utils import PretrainedConfig
from ...utils import logging


lowerCAmelCase_	:		Optional[int]			=     logging.get_logger(__name__)

lowerCAmelCase_	:		Tuple			=     {
    """huggingface/time-series-transformer-tourism-monthly""": (
        """https://huggingface.co/huggingface/time-series-transformer-tourism-monthly/resolve/main/config.json"""
    ),
    # See all TimeSeriesTransformer models at https://huggingface.co/models?filter=time_series_transformer
}




class 		SCREAMING_SNAKE_CASE     (					SCREAMING_SNAKE_CASE	):







				'''simple docstring'''
				UpperCAmelCase__							=							'''time_series_transformer'''
				UpperCAmelCase__							=							{
				    '''hidden_size''': '''d_model''',
				    '''num_attention_heads''': '''encoder_attention_heads''',
				    '''num_hidden_layers''': '''encoder_layers''',
				}





				def __init__(						self					:						int       ,		lowercase__					:						Optional[int] = None       ,		lowercase__					:						Optional[int] = None       ,		lowercase__					:						str = "student_t"       ,		lowercase__					:						str = "nll"       ,		lowercase__					:						int = 1       ,		lowercase__					:						List[int] = [1, 2, 3, 4, 5, 6, 7]       ,		lowercase__					:						Optional[Union[str, bool]] = "mean"       ,		lowercase__					:						int = 0       ,		lowercase__					:						int = 0       ,		lowercase__					:						int = 0       ,		lowercase__					:						int = 0       ,		lowercase__					:						Optional[List[int]] = None       ,		lowercase__					:						Optional[List[int]] = None       ,		lowercase__					:						int = 32       ,		lowercase__					:						int = 32       ,		lowercase__					:						int = 2       ,		lowercase__					:						int = 2       ,		lowercase__					:						int = 2       ,		lowercase__					:						int = 2       ,		lowercase__					:						bool = True       ,		lowercase__					:						str = "gelu"       ,		lowercase__					:						int = 64       ,		lowercase__					:						float = 0.1       ,		lowercase__					:						float = 0.1       ,		lowercase__					:						float = 0.1       ,		lowercase__					:						float = 0.1       ,		lowercase__					:						float = 0.1       ,		lowercase__					:						int = 100       ,		lowercase__					:						float = 0.0_2       ,		lowercase__					:						Optional[int]=True       ,		**lowercase__					:						Optional[Any]       ,		)							->Optional[Any]:


										'''simple docstring'''




										_UpperCamelCase			:			int   			=						prediction_length
										_UpperCamelCase			:			Optional[Any]   			=						context_length or prediction_length
										_UpperCamelCase			:			List[str]   			=						distribution_output
										_UpperCamelCase			:			Optional[Any]   			=						loss
										_UpperCamelCase			:			Tuple   			=						input_size
										_UpperCamelCase			:			Optional[int]   			=						num_time_features
										_UpperCamelCase			:			Union[str, Any]   			=						lags_sequence
										_UpperCamelCase			:			int   			=						scaling
										_UpperCamelCase			:			Dict   			=						num_dynamic_real_features
										_UpperCamelCase			:			str   			=						num_static_real_features
										_UpperCamelCase			:			Any   			=						num_static_categorical_features
										if cardinality and num_static_categorical_features > 0:
																if len(lowercase__					) != num_static_categorical_features:
																						raise ValueError(
																						    "The cardinality should be a list of the same length as `num_static_categorical_features`"					)
																_UpperCamelCase			:			Dict   			=						cardinality
										else:
																_UpperCamelCase			:			str   			=						[0]
										if embedding_dimension and num_static_categorical_features > 0:
																if len(lowercase__					) != num_static_categorical_features:
																						raise ValueError(
																						    "The embedding dimension should be a list of the same length as `num_static_categorical_features`"					)
																_UpperCamelCase			:			int   			=						embedding_dimension
										else:
																_UpperCamelCase			:			Optional[Any]   			=						[min(50       ,		(cat + 1) // 2					) for cat in self.cardinality]
										_UpperCamelCase			:			Union[str, Any]   			=						num_parallel_samples

										# Transformer architecture configuration
										_UpperCamelCase			:			int   			=						input_size * len(lowercase__					) + self._number_of_features
										_UpperCamelCase			:			Optional[Any]   			=						d_model
										_UpperCamelCase			:			str   			=						encoder_attention_heads
										_UpperCamelCase			:			List[Any]   			=						decoder_attention_heads
										_UpperCamelCase			:			str   			=						encoder_ffn_dim
										_UpperCamelCase			:			List[str]   			=						decoder_ffn_dim
										_UpperCamelCase			:			Union[str, Any]   			=						encoder_layers
										_UpperCamelCase			:			Optional[int]   			=						decoder_layers

										_UpperCamelCase			:			int   			=						dropout
										_UpperCamelCase			:			Optional[int]   			=						attention_dropout
										_UpperCamelCase			:			int   			=						activation_dropout
										_UpperCamelCase			:			List[Any]   			=						encoder_layerdrop
										_UpperCamelCase			:			int   			=						decoder_layerdrop

										_UpperCamelCase			:			List[Any]   			=						activation_function
										_UpperCamelCase			:			Any   			=						init_std

										_UpperCamelCase			:			Optional[Any]   			=						use_cache

										super().__init__(is_encoder_decoder=lowercase__       ,		**lowercase__					)







				@property
				def  snake_case__				(						self					:						Union[str, Any]					)							->int:


										'''simple docstring'''




										return (
										    sum(self.embedding_dimension					)
										    + self.num_dynamic_real_features
										    + self.num_time_features
										    + self.num_static_real_features
										    + self.input_size * 2  # the log1p(abs(loc)) and log(scale) features
										)


