






'''simple docstring'''





import json
import os
import pickle
import subprocess
from hashlib import mda
from pathlib import Path
from tempfile import gettempdir
from textwrap import dedent
from types import CodeType, FunctionType
from unittest import TestCase
from unittest.mock import patch

import pytest
from multiprocess import Pool
from packaging import version

import datasets
from datasets.fingerprint import Hasher, fingerprint_transform
from datasets.table import InMemoryTable

from .utils import (
    require_regex,
    require_spacy,
    require_spacy_model,
    require_tiktoken,
    require_torch,
    require_transformers,
)





class 		SCREAMING_SNAKE_CASE__   :



		def __init__(    self:    Any				,   a:    List[Any])  ->Optional[Any]:






								'''simple docstring'''


								a_				     =   foo




		def __call__(    self:    Optional[Any])  ->str:






								'''simple docstring'''


								return self.foo





class 		SCREAMING_SNAKE_CASE__   (     datasets.Dataset    ):



		@fingerprint_transform(inplace=a)
		def _lowerCAmelCase     (    self:    List[str]				,   a:    Tuple				,   *a:    Optional[Any]				,   **a:    Optional[Any])  ->Union[str, Any]:






								'''simple docstring'''


								return DatasetChild(self.data				,   fingerprint=a)




		@fingerprint_transform(inplace=a)
		def _lowerCAmelCase     (    self:    Optional[Any]				,   a:    Tuple				,   *a:    Union[str, Any]				,   **a:    Optional[int])  ->Optional[Any]:






								'''simple docstring'''


								return DatasetChild(self.data				,   fingerprint=a)





class 		SCREAMING_SNAKE_CASE__   :



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






								'''simple docstring'''


								a_				     =   callable



		def __call__(    self:    List[str]				,   *a:    Union[str, Any]				,   **a:    Tuple)  ->int:






								'''simple docstring'''


								if self.callable is not None:
														return self.callable(*a				,   **a)




		def __getstate__(    self:    str)  ->str:






								'''simple docstring'''


								raise pickle.PicklingError()





class 		SCREAMING_SNAKE_CASE__   (     lowercase_    ):



		@require_transformers
		@pytest.mark.integration
		def _lowerCAmelCase     (    self:    List[str])  ->Tuple:






								'''simple docstring'''


								from transformers import AutoTokenizer

								def encode(a:    Union[str, Any]):
														return tokenizer(a)

								# TODO: add hash consistency tests across sessions
								a_				     =   AutoTokenizer.from_pretrained("bert-base-uncased")
								a_				     =   mda(datasets.utils.py_utils.dumps(a)).hexdigest()
								a_				     =   mda(datasets.utils.py_utils.dumps(lambda a: tokenizer(a))).hexdigest()
								a_				     =   mda(datasets.utils.py_utils.dumps(a)).hexdigest()
								a_				     =   AutoTokenizer.from_pretrained("bert-base-cased")
								a_				     =   mda(datasets.utils.py_utils.dumps(a)).hexdigest()
								a_				     =   mda(datasets.utils.py_utils.dumps(lambda a: tokenizer(a))).hexdigest()
								a_				     =   mda(datasets.utils.py_utils.dumps(a)).hexdigest()
								a_				     =   AutoTokenizer.from_pretrained("bert-base-uncased")
								a_				     =   mda(datasets.utils.py_utils.dumps(a)).hexdigest()
								a_				     =   mda(datasets.utils.py_utils.dumps(lambda a: tokenizer(a))).hexdigest()
								a_				     =   mda(datasets.utils.py_utils.dumps(a)).hexdigest()
								self.assertEqual(a				,   a)
								self.assertNotEqual(a				,   a)
								self.assertEqual(a				,   a)
								self.assertNotEqual(a				,   a)
								self.assertEqual(a				,   a)
								self.assertNotEqual(a				,   a)



		@require_transformers
		@pytest.mark.integration
		def _lowerCAmelCase     (    self:    str)  ->Dict:






								'''simple docstring'''


								from transformers import AutoTokenizer

								a_				     =   AutoTokenizer.from_pretrained("gpt2")
								a_				     =   mda(datasets.utils.py_utils.dumps(a)).hexdigest()
								tokenizer("Hello world !")  # call once to change the tokenizer's cache
								a_				     =   mda(datasets.utils.py_utils.dumps(a)).hexdigest()
								self.assertEqual(a				,   a)




		@require_regex
		def _lowerCAmelCase     (    self:    int)  ->Tuple:






								'''simple docstring'''


								import regex

								a_				     =   regex.Regex("foo")
								a_				     =   mda(datasets.utils.py_utils.dumps(a)).hexdigest()
								a_				     =   regex.Regex("bar")
								a_				     =   mda(datasets.utils.py_utils.dumps(a)).hexdigest()
								a_				     =   regex.Regex("foo")
								a_				     =   mda(datasets.utils.py_utils.dumps(a)).hexdigest()
								self.assertEqual(a				,   a)
								self.assertNotEqual(a				,   a)





class 		SCREAMING_SNAKE_CASE__   (     lowercase_    ):



		def _lowerCAmelCase     (    self:    Optional[int])  ->int:






								'''simple docstring'''


								def func():
														return foo

								a_				     =   [0]
								a_				     =   mda(datasets.utils.py_utils.dumps(a)).hexdigest()
								a_				     =   [1]
								a_				     =   mda(datasets.utils.py_utils.dumps(a)).hexdigest()
								a_				     =   [0]
								a_				     =   mda(datasets.utils.py_utils.dumps(a)).hexdigest()
								self.assertEqual(a				,   a)
								self.assertNotEqual(a				,   a)



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






								'''simple docstring'''


								def func():
														pass

								a_				     =   mda(datasets.utils.py_utils.dumps(a)).hexdigest()

								def func():
														pass

								a_				     =   mda(datasets.utils.py_utils.dumps(a)).hexdigest()
								self.assertEqual(a				,   a)



		def _lowerCAmelCase     (    self:    Optional[int])  ->str:






								'''simple docstring'''


								a_				     =   mda(datasets.utils.py_utils.dumps(Foo([0]))).hexdigest()
								a_				     =   mda(datasets.utils.py_utils.dumps(Foo([1]))).hexdigest()
								a_				     =   mda(datasets.utils.py_utils.dumps(Foo([0]))).hexdigest()
								self.assertEqual(a				,   a)
								self.assertNotEqual(a				,   a)



		def _lowerCAmelCase     (    self:    str)  ->Union[str, Any]:






								'''simple docstring'''


								a_				     =   mda(datasets.utils.py_utils.dumps(Foo([0]).__call__)).hexdigest()
								a_				     =   mda(datasets.utils.py_utils.dumps(Foo([1]).__call__)).hexdigest()
								a_				     =   mda(datasets.utils.py_utils.dumps(Foo([0]).__call__)).hexdigest()
								self.assertEqual(a				,   a)
								self.assertNotEqual(a				,   a)



		def _lowerCAmelCase     (    self:    Optional[int])  ->Union[str, Any]:






								'''simple docstring'''


								a_				     =   (
								    "co_argcount",
								    "co_kwonlyargcount",
								    "co_nlocals",
								    "co_stacksize",
								    "co_flags",
								    "co_code",
								    "co_consts",
								    "co_names",
								    "co_varnames",
								    "co_filename",
								    "co_name",
								    "co_firstlineno",
								    "co_lnotab",
								    "co_freevars",
								    "co_cellvars",
								)

								def _create_code_pyaa(*a:    str):
														if hasattr(args[-3]				,   "encode"):
																				a_				     =   list(a)
																				a_				     =   args[-3].encode()  # co_lnotab
																				a_				     =   args[-10].encode()  # co_code
														if hasattr(a				,   "co_posonlyargcount"):
																				if len(a) == 16:
																										return CodeType(*a)
																				elif len(a) == 15:
																										return CodeType(args[0]				,   0				,   *args[1:])
																				return CodeType(args[0]				,   0				,   0				,   *args[1:])
														elif hasattr(a				,   "co_kwonlyargcount"):
																				if len(a) == 16:
																										return CodeType(args[0]				,   *args[2:])
																				elif len(a) == 15:
																										return CodeType(*a)
																				return CodeType(args[0]				,   0				,   *args[1:])
														if len(a) == 16:
																				return CodeType(args[0]				,   *args[3:])
														elif len(a) == 15:
																				return CodeType(args[0]				,   *args[2:])
														return CodeType(*a)

								def create_ipython_func(a:    List[Any]				,   a:    str):
														def func():
																				return returned_obj

														a_				     =   func.__code__
														# Use _create_code from dill in order to make it work for different python versions
														if datasets.config.PY_VERSION < version.parse("3.8"):
																				a_				     =   _create_code_pyaa(
																				    *[getattr(a				,   a) if k != "co_filename" else co_filename for k in code_args_pyaa])
														else:
																				a_				     =   code.replace(co_filename=a)
														return FunctionType(a				,   func.__globals__				,   func.__name__				,   func.__defaults__				,   func.__closure__)

								a_     ,       a_				     =   "<ipython-input-2-e0383a102aae>", [0]
								a_				     =   mda(datasets.utils.py_utils.dumps(create_ipython_func(a				,   a))).hexdigest()
								a_     ,       a_				     =   "<ipython-input-2-e0383a102aae>", [1]
								a_				     =   mda(datasets.utils.py_utils.dumps(create_ipython_func(a				,   a))).hexdigest()
								a_     ,       a_				     =   "<ipython-input-5-713f6613acf3>", [0]
								a_				     =   mda(datasets.utils.py_utils.dumps(create_ipython_func(a				,   a))).hexdigest()
								self.assertEqual(a				,   a)
								self.assertNotEqual(a				,   a)

								a_     ,       a_				     =   os.path.join(gettempdir()				,   "ipykernel_12345"				,   "321456789.py"), [0]
								a_				     =   mda(datasets.utils.py_utils.dumps(create_ipython_func(a				,   a))).hexdigest()
								a_     ,       a_				     =   os.path.join(gettempdir()				,   "ipykernel_12345"				,   "321456789.py"), [1]
								a_				     =   mda(datasets.utils.py_utils.dumps(create_ipython_func(a				,   a))).hexdigest()
								a_     ,       a_				     =   os.path.join(gettempdir()				,   "ipykernel_12345"				,   "654123987.py"), [0]
								a_				     =   mda(datasets.utils.py_utils.dumps(create_ipython_func(a				,   a))).hexdigest()
								self.assertEqual(a				,   a)
								self.assertNotEqual(a				,   a)




		def _lowerCAmelCase     (    self:    str)  ->Optional[Any]:






								'''simple docstring'''


								a_     ,       a_				     =   [0], [1]

								def func():
														return foo, bar

								a_				     =   "__main__"

								def globalvars_mocka_side_effect(a:    str				,   *a:    str				,   **a:    Optional[int]):
														return {"foo": foo, "bar": bar}

								def globalvars_mocka_side_effect(a:    Optional[Any]				,   *a:    Optional[int]				,   **a:    Optional[Any]):
														return {"bar": bar, "foo": foo}

								with patch("dill.detect.globalvars"				,   side_effect=a) as globalvars_mocka:
														a_				     =   mda(datasets.utils.py_utils.dumps(a)).hexdigest()
														self.assertGreater(globalvars_mocka.call_count				,   0)
								with patch("dill.detect.globalvars"				,   side_effect=a) as globalvars_mocka:
														a_				     =   mda(datasets.utils.py_utils.dumps(a)).hexdigest()
														self.assertGreater(globalvars_mocka.call_count				,   0)
								self.assertEqual(a				,   a)





class 		SCREAMING_SNAKE_CASE__   (     lowercase_    ):



		def _lowerCAmelCase     (    self:    List[str])  ->Optional[int]:






								'''simple docstring'''


								a_				     =   Hasher.hash("hello")
								a_				     =   Hasher.hash("hello")
								a_				     =   Hasher.hash("there")
								self.assertEqual(a				,   a)
								self.assertNotEqual(a				,   a)



		def _lowerCAmelCase     (    self:    List[Any])  ->List[str]:






								'''simple docstring'''


								a_				     =   Hasher.hash(Foo("hello"))
								a_				     =   Hasher.hash(Foo("hello"))
								a_				     =   Hasher.hash(Foo("there"))
								self.assertEqual(a				,   a)
								self.assertNotEqual(a				,   a)



		def _lowerCAmelCase     (    self:    Optional[int])  ->List[str]:






								'''simple docstring'''


								a_				     =   Hasher()
								for x in ["hello", Foo("hello")]:
														hasher.update(a)
								a_				     =   hasher.hexdigest()
								a_				     =   Hasher()
								for x in ["hello", Foo("hello")]:
														hasher.update(a)
								a_				     =   hasher.hexdigest()
								a_				     =   Hasher()
								for x in ["there", Foo("there")]:
														hasher.update(a)
								a_				     =   hasher.hexdigest()
								self.assertEqual(a				,   a)
								self.assertNotEqual(a				,   a)



		def _lowerCAmelCase     (    self:    int)  ->Any:






								'''simple docstring'''


								with self.assertRaises(pickle.PicklingError):
														Hasher.hash(UnpicklableCallable(Foo("hello")))



		def _lowerCAmelCase     (    self:    int)  ->Optional[int]:






								'''simple docstring'''


								a_				     =   "abc"
								a_				     =   [string, string]  # two strings have the same ids
								a_				     =   [string, string]
								a_				     =   json.loads(f"""[\"{string}\", \"{string}\"]""")  # two strings have different ids
								self.assertIs(obja[0]				,   a)
								self.assertIs(obja[0]				,   obja[1])
								self.assertIs(obja[0]				,   a)
								self.assertIs(obja[0]				,   obja[1])
								self.assertIsNot(obja[0]				,   a)
								self.assertIsNot(obja[0]				,   obja[1])
								a_				     =   Hasher.hash(a)
								a_				     =   Hasher.hash(a)
								a_				     =   Hasher.hash(a)
								self.assertEqual(a				,   a)
								self.assertEqual(a				,   a)



		@require_tiktoken
		def _lowerCAmelCase     (    self:    Optional[int])  ->List[Any]:






								'''simple docstring'''


								import tiktoken

								a_				     =   tiktoken.get_encoding("gpt2")
								a_				     =   mda(datasets.utils.py_utils.dumps(a)).hexdigest()
								a_				     =   tiktoken.get_encoding("r50k_base")
								a_				     =   mda(datasets.utils.py_utils.dumps(a)).hexdigest()
								a_				     =   tiktoken.get_encoding("gpt2")
								a_				     =   mda(datasets.utils.py_utils.dumps(a)).hexdigest()
								self.assertEqual(a				,   a)
								self.assertNotEqual(a				,   a)



		@require_torch
		def _lowerCAmelCase     (    self:    str)  ->str:






								'''simple docstring'''


								import torch

								a_				     =   torch.tensor([1.0])
								a_				     =   mda(datasets.utils.py_utils.dumps(a)).hexdigest()
								a_				     =   torch.tensor([2.0])
								a_				     =   mda(datasets.utils.py_utils.dumps(a)).hexdigest()
								a_				     =   torch.tensor([1.0])
								a_				     =   mda(datasets.utils.py_utils.dumps(a)).hexdigest()
								self.assertEqual(a				,   a)
								self.assertNotEqual(a				,   a)




		@require_spacy
		@require_spacy_model("en_core_web_sm")
		@require_spacy_model("fr_core_news_sm")
		@pytest.mark.integration
		def _lowerCAmelCase     (    self:    int)  ->List[str]:






								'''simple docstring'''


								import spacy

								a_				     =   spacy.load("en_core_web_sm")
								a_				     =   mda(datasets.utils.py_utils.dumps(a)).hexdigest()
								a_				     =   spacy.load("fr_core_news_sm")
								a_				     =   mda(datasets.utils.py_utils.dumps(a)).hexdigest()
								a_				     =   spacy.load("en_core_web_sm")
								a_				     =   mda(datasets.utils.py_utils.dumps(a)).hexdigest()
								self.assertEqual(a				,   a)
								self.assertNotEqual(a				,   a)





@pytest.mark.integration
def 			__UpperCAmelCase				(lowercase__				)		->				Any:

						'''simple docstring'''


						a_				     =   tmp_path / "dir1"
						a_				     =   tmp_path / "dir2"
						dira.mkdir()
						dira.mkdir()
						a_				     =   "script.py"
						a_				     =   dedent(
						    "\n    from datasets.fingerprint import Hasher\n    def foo():\n        pass\n    print(Hasher.hash(foo))\n    "				)
						a_				     =   dira / script_filename
						a_				     =   dira / script_filename
						with script_patha.open("w"				) as f:
												f.write(lowercase__				)
						with script_patha.open("w"				) as f:
												f.write(lowercase__				)
						a_				     =   subprocess.check_output(["python", str(lowercase__				)]				)
						a_				     =   subprocess.check_output(["python", str(lowercase__				)]				)
						assert fingerprinta == fingerprinta



def 			__UpperCAmelCase				()		->				List[str]:

						'''simple docstring'''


						a_				     =   {"a": [0, 1, 2]}
						a_				     =   DatasetChild(InMemoryTable.from_pydict(lowercase__				)				)
						a_				     =   dataset.funca()._fingerprint
						assert expected_fingerprint == dataset.funca()._fingerprint
						assert expected_fingerprint != dataset.funca()._fingerprint

						with Pool(2				) as p:
												assert expected_fingerprint == p.apply_async(dataset.funca				).get()._fingerprint
												assert expected_fingerprint != p.apply_async(dataset.funca				).get()._fingerprint



def 			__UpperCAmelCase				()		->				Dict:

						'''simple docstring'''


						a_				     =   {"a": [0, 1, 2]}





						class 		SCREAMING_SNAKE_CASE__   (     datasets.Dataset    ):



								@fingerprint_transform(inplace=a)
								def _lowerCAmelCase     (    self:    Optional[Any]				,   a:    Dict)  ->List[Any]:






														'''simple docstring'''


														return DummyDatasetChild(self.data				,   fingerprint=a)





						a_				     =   DummyDatasetChild(InMemoryTable.from_pydict(lowercase__				)				).func()





						class 		SCREAMING_SNAKE_CASE__   (     datasets.Dataset    ):



								@fingerprint_transform(inplace=a				,   version="1.0.0")
								def _lowerCAmelCase     (    self:    str				,   a:    Optional[int])  ->List[str]:






														'''simple docstring'''


														return DummyDatasetChild(self.data				,   fingerprint=a)





						a_				     =   DummyDatasetChild(InMemoryTable.from_pydict(lowercase__				)				).func()





						class 		SCREAMING_SNAKE_CASE__   (     datasets.Dataset    ):



								@fingerprint_transform(inplace=a				,   version="2.0.0")
								def _lowerCAmelCase     (    self:    Dict				,   a:    Dict)  ->Dict:






														'''simple docstring'''


														return DummyDatasetChild(self.data				,   fingerprint=a)





						a_				     =   DummyDatasetChild(InMemoryTable.from_pydict(lowercase__				)				).func()

						assert len({fingeprint_no_version, fingeprint_a, fingeprint_a}				) == 3



def 			__UpperCAmelCase				()		->				List[str]:

						'''simple docstring'''


						a_				     =   Hasher()
						hasher.update(lambda lowercase__				: x				)











'''simple docstring'''





from collections import OrderedDict
from typing import Mapping

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


a_      = logging.get_logger(__name__)

a_      = {
    'google/mobilebert-uncased': 'https://huggingface.co/google/mobilebert-uncased/resolve/main/config.json'
}





class 		SCREAMING_SNAKE_CASE__   (     lowercase_    ):
		_UpperCAmelCase         =MOBILEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP
		_UpperCAmelCase         ='''mobilebert'''



		def __init__(    self:    Union[str, Any]				,   a:    str=3_05_22				,   a:    List[str]=5_12				,   a:    List[str]=24				,   a:    Dict=4				,   a:    List[str]=5_12				,   a:    Optional[int]="relu"				,   a:    Dict=0.0				,   a:    Union[str, Any]=0.1				,   a:    int=5_12				,   a:    Optional[Any]=2				,   a:    List[Any]=0.02				,   a:    Optional[Any]=1e-12				,   a:    List[Any]=0				,   a:    Optional[int]=1_28				,   a:    Union[str, Any]=True				,   a:    Dict=True				,   a:    List[Any]=1_28				,   a:    Any=False				,   a:    Any=True				,   a:    Dict=4				,   a:    List[Any]="no_norm"				,   a:    Any=True				,   a:    Tuple=None				,   **a:    Any				,   )  ->Any:






								'''simple docstring'''


								super().__init__(pad_token_id=a				,   **a)

								a_				     =   vocab_size
								a_				     =   hidden_size
								a_				     =   num_hidden_layers
								a_				     =   num_attention_heads
								a_				     =   hidden_act
								a_				     =   intermediate_size
								a_				     =   hidden_dropout_prob
								a_				     =   attention_probs_dropout_prob
								a_				     =   max_position_embeddings
								a_				     =   type_vocab_size
								a_				     =   initializer_range
								a_				     =   layer_norm_eps
								a_				     =   embedding_size
								a_				     =   trigram_input
								a_				     =   use_bottleneck
								a_				     =   intra_bottleneck_size
								a_				     =   use_bottleneck_attention
								a_				     =   key_query_shared_bottleneck
								a_				     =   num_feedforward_networks
								a_				     =   normalization_type
								a_				     =   classifier_activation

								if self.use_bottleneck:
														a_				     =   intra_bottleneck_size
								else:
														a_				     =   hidden_size

								a_				     =   classifier_dropout





class 		SCREAMING_SNAKE_CASE__   (     lowercase_    ):



		@property
		def _lowerCAmelCase     (    self:    Optional[int])  ->Mapping[str, Mapping[int, str]]:






								'''simple docstring'''


								if self.task == "multiple-choice":
														a_				     =   {0: "batch", 1: "choice", 2: "sequence"}
								else:
														a_				     =   {0: "batch", 1: "sequence"}
								return OrderedDict(
								    [
								        ("input_ids", dynamic_axis),
								        ("attention_mask", dynamic_axis),
								        ("token_type_ids", dynamic_axis),
								    ])



