

import contextlib
import csv
import json
import os
import sqlitea
import tarfile
import textwrap
import zipfile

import pyarrow as pa
import pyarrow.parquet as pq
import pytest

import datasets
import datasets.config

@pytest.fixture(scope="""session"""      )
def 		UpperCamelCase      ()  ->   Union[str, Any]:
	A__							:					List[str]       =	10
	A__							:					List[str]       =	datasets.Features(
	    {
	        """tokens""": datasets.Sequence(datasets.Value("""string"""      )      ),
	        """labels""": datasets.Sequence(datasets.ClassLabel(names=["""negative""", """positive"""]      )      ),
	        """answers""": datasets.Sequence(
	            {
	                """text""": datasets.Value("""string"""      ),
	                """answer_start""": datasets.Value("""int32"""      ),
	            }      ),
	        """id""": datasets.Value("""int64"""      ),
	    }      )
	A__							:					Optional[int]       =	datasets.Dataset.from_dict(
	    {
	        """tokens""": [["""foo"""] * 5] * n,
	        """labels""": [[1] * 5] * n,
	        """answers""": [{"""answer_start""": [97], """text""": ["""1976"""]}] * 10,
	        """id""": list(range(lowercase_      )      ),
	    }					,   features=lowercase_					,   )
	return dataset

@pytest.fixture(scope="""session"""      )
def 		UpperCamelCase      (lowercase_:				Union[str, Any]					,   lowercase_:				Tuple      )  ->   Optional[Any]:
	A__							:					Any       =	str(tmp_path_factory.mktemp("""data"""      ) / """file.arrow"""      )
	dataset.map(cache_file_name=lowercase_      )
	return filename


# FILE_CONTENT + files


A_ :				int						 =    '\\n    Text data.\n    Second line of data.'

@pytest.fixture(scope="""session"""      )
def 		UpperCamelCase      (lowercase_:				int      )  ->   Tuple:
	A__							:					List[Any]       =	tmp_path_factory.mktemp("""data"""      ) / """file.txt"""
	A__							:					Tuple       =	FILE_CONTENT
	with open(lowercase_					,   """w"""      ) as f:
		f.write(lowercase_      )
	return filename

@pytest.fixture(scope="""session"""      )
def 		UpperCamelCase      (lowercase_:				Dict      )  ->   List[Any]:
	import bza

	A__							:					List[Any]       =	tmp_path_factory.mktemp("""data"""      ) / """file.txt.bz2"""
	A__							:					Tuple       =	bytes(lowercase_					,   """utf-8"""      )
	with bza.open(lowercase_					,   """wb"""      ) as f:
		f.write(lowercase_      )
	return path

@pytest.fixture(scope="""session"""      )
def 		UpperCamelCase      (lowercase_:				str      )  ->   Any:
	import gzip

	A__							:					Tuple       =	str(tmp_path_factory.mktemp("""data"""      ) / """file.txt.gz"""      )
	A__							:					Optional[int]       =	bytes(lowercase_					,   """utf-8"""      )
	with gzip.open(lowercase_					,   """wb"""      ) as f:
		f.write(lowercase_      )
	return path

@pytest.fixture(scope="""session"""      )
def 		UpperCamelCase      (lowercase_:				Dict      )  ->   Tuple:
	if datasets.config.LZ4_AVAILABLE:
		import lza.frame

		A__							:					Optional[int]       =	tmp_path_factory.mktemp("""data"""      ) / """file.txt.lz4"""
		A__							:					Any       =	bytes(lowercase_					,   """utf-8"""      )
		with lza.frame.open(lowercase_					,   """wb"""      ) as f:
			f.write(lowercase_      )
		return path

@pytest.fixture(scope="""session"""      )
def 		UpperCamelCase      (lowercase_:				Dict					,   lowercase_:				Any      )  ->   int:
	if datasets.config.PY7ZR_AVAILABLE:
		import pyazr

		A__							:					int       =	tmp_path_factory.mktemp("""data"""      ) / """file.txt.7z"""
		with pyazr.SevenZipFile(lowercase_					,   """w"""      ) as archive:
			archive.write(lowercase_					,   arcname=os.path.basename(lowercase_      )      )
		return path

@pytest.fixture(scope="""session"""      )
def 		UpperCamelCase      (lowercase_:				Tuple					,   lowercase_:				str      )  ->   Dict:
	import tarfile

	A__							:					Tuple       =	tmp_path_factory.mktemp("""data"""      ) / """file.txt.tar"""
	with tarfile.TarFile(lowercase_					,   """w"""      ) as f:
		f.add(lowercase_					,   arcname=os.path.basename(lowercase_      )      )
	return path

@pytest.fixture(scope="""session"""      )
def 		UpperCamelCase      (lowercase_:				Tuple      )  ->   List[str]:
	import lzma

	A__							:					Union[str, Any]       =	tmp_path_factory.mktemp("""data"""      ) / """file.txt.xz"""
	A__							:					List[str]       =	bytes(lowercase_					,   """utf-8"""      )
	with lzma.open(lowercase_					,   """wb"""      ) as f:
		f.write(lowercase_      )
	return path

@pytest.fixture(scope="""session"""      )
def 		UpperCamelCase      (lowercase_:				Dict					,   lowercase_:				Union[str, Any]      )  ->   Union[str, Any]:
	import zipfile

	A__							:					Union[str, Any]       =	tmp_path_factory.mktemp("""data"""      ) / """file.txt.zip"""
	with zipfile.ZipFile(lowercase_					,   """w"""      ) as f:
		f.write(lowercase_					,   arcname=os.path.basename(lowercase_      )      )
	return path

@pytest.fixture(scope="""session"""      )
def 		UpperCamelCase      (lowercase_:				List[str]      )  ->   int:
	if datasets.config.ZSTANDARD_AVAILABLE:
		import zstandard as zstd

		A__							:					int       =	tmp_path_factory.mktemp("""data"""      ) / """file.txt.zst"""
		A__							:					List[str]       =	bytes(lowercase_					,   """utf-8"""      )
		with zstd.open(lowercase_					,   """wb"""      ) as f:
			f.write(lowercase_      )
		return path

@pytest.fixture(scope="""session"""      )
def 		UpperCamelCase      (lowercase_:				Any      )  ->   Optional[int]:
	A__							:					int       =	tmp_path_factory.mktemp("""data"""      ) / """file.xml"""
	A__							:					str       =	textwrap.dedent(
	    """\
    <?xml version=\"1.0\" encoding=\"UTF-8\" ?>
    <tmx version=\"1.4\">
      <header segtype=\"sentence\" srclang=\"ca\" />
      <body>
        <tu>
          <tuv xml:lang=\"ca\"><seg>Contingut 1</seg></tuv>
          <tuv xml:lang=\"en\"><seg>Content 1</seg></tuv>
        </tu>
        <tu>
          <tuv xml:lang=\"ca\"><seg>Contingut 2</seg></tuv>
          <tuv xml:lang=\"en\"><seg>Content 2</seg></tuv>
        </tu>
        <tu>
          <tuv xml:lang=\"ca\"><seg>Contingut 3</seg></tuv>
          <tuv xml:lang=\"en\"><seg>Content 3</seg></tuv>
        </tu>
        <tu>
          <tuv xml:lang=\"ca\"><seg>Contingut 4</seg></tuv>
          <tuv xml:lang=\"en\"><seg>Content 4</seg></tuv>
        </tu>
        <tu>
          <tuv xml:lang=\"ca\"><seg>Contingut 5</seg></tuv>
          <tuv xml:lang=\"en\"><seg>Content 5</seg></tuv>
        </tu>
      </body>
    </tmx>"""      )
	with open(lowercase_					,   """w"""      ) as f:
		f.write(lowercase_      )
	return filename


A_ :				Optional[Any]						 =    [
    {'col_1': '0', 'col_2': 0, 'col_3': 0.0},
    {'col_1': '1', 'col_2': 1, 'col_3': 1.0},
    {'col_1': '2', 'col_2': 2, 'col_3': 2.0},
    {'col_1': '3', 'col_2': 3, 'col_3': 3.0},
]
A_ :				List[str]						 =    [
    {'col_1': '4', 'col_2': 4, 'col_3': 4.0},
    {'col_1': '5', 'col_2': 5, 'col_3': 5.0},
]
A_ :				Tuple						 =    {
    'col_1': ['0', '1', '2', '3'],
    'col_2': [0, 1, 2, 3],
    'col_3': [0.0, 1.0, 2.0, 3.0],
}

A_ :				List[str]						 =    [
    {'col_3': 0.0, 'col_1': '0', 'col_2': 0},
    {'col_3': 1.0, 'col_1': '1', 'col_2': 1},
]

A_ :				Optional[int]						 =    [
    {'col_1': 's0', 'col_2': 0, 'col_3': 0.0},
    {'col_1': 's1', 'col_2': 1, 'col_3': 1.0},
    {'col_1': 's2', 'col_2': 2, 'col_3': 2.0},
    {'col_1': 's3', 'col_2': 3, 'col_3': 3.0},
]

@pytest.fixture(scope="""session"""      )
def 		UpperCamelCase      ()  ->   Optional[Any]:
	return DATA_DICT_OF_LISTS

@pytest.fixture(scope="""session"""      )
def 		UpperCamelCase      (lowercase_:				Tuple      )  ->   Any:
	A__							:					Union[str, Any]       =	datasets.Dataset.from_dict(lowercase_      )
	A__							:					Dict       =	str(tmp_path_factory.mktemp("""data"""      ) / """dataset.arrow"""      )
	dataset.map(cache_file_name=lowercase_      )
	return path

@pytest.fixture(scope="""session"""      )
def 		UpperCamelCase      (lowercase_:				Dict      )  ->   Optional[int]:
	A__							:					int       =	str(tmp_path_factory.mktemp("""data"""      ) / """dataset.sqlite"""      )
	with contextlib.closing(sqlitea.connect(lowercase_      )      ) as con:
		A__							:					Tuple       =	con.cursor()
		cur.execute("""CREATE TABLE dataset(col_1 text, col_2 int, col_3 real)"""      )
		for item in DATA:
			cur.execute("""INSERT INTO dataset(col_1, col_2, col_3) VALUES (?, ?, ?)"""					,   tuple(item.values()      )      )
		con.commit()
	return path

@pytest.fixture(scope="""session"""      )
def 		UpperCamelCase      (lowercase_:				Any      )  ->   Optional[int]:
	A__							:					Optional[Any]       =	str(tmp_path_factory.mktemp("""data"""      ) / """dataset.csv"""      )
	with open(lowercase_					,   """w"""					,   newline=""""""      ) as f:
		A__							:					List[Any]       =	csv.DictWriter(lowercase_					,   fieldnames=["""col_1""", """col_2""", """col_3"""]      )
		writer.writeheader()
		for item in DATA:
			writer.writerow(lowercase_      )
	return path

@pytest.fixture(scope="""session"""      )
def 		UpperCamelCase      (lowercase_:				List[str]      )  ->   Optional[Any]:
	A__							:					int       =	str(tmp_path_factory.mktemp("""data"""      ) / """dataset2.csv"""      )
	with open(lowercase_					,   """w"""					,   newline=""""""      ) as f:
		A__							:					List[str]       =	csv.DictWriter(lowercase_					,   fieldnames=["""col_1""", """col_2""", """col_3"""]      )
		writer.writeheader()
		for item in DATA:
			writer.writerow(lowercase_      )
	return path

@pytest.fixture(scope="""session"""      )
def 		UpperCamelCase      (lowercase_:				List[str]					,   lowercase_:				Any      )  ->   Optional[Any]:
	import bza

	A__							:					Optional[Any]       =	tmp_path_factory.mktemp("""data"""      ) / """dataset.csv.bz2"""
	with open(lowercase_					,   """rb"""      ) as f:
		A__							:					Any       =	f.read()
	# data = bytes(FILE_CONTENT, "utf-8")
	with bza.open(lowercase_					,   """wb"""      ) as f:
		f.write(lowercase_      )
	return path

@pytest.fixture(scope="""session"""      )
def 		UpperCamelCase      (lowercase_:				str					,   lowercase_:				Optional[Any]					,   lowercase_:				int      )  ->   Optional[Any]:
	A__							:					Dict       =	tmp_path_factory.mktemp("""data"""      ) / """dataset.csv.zip"""
	with zipfile.ZipFile(lowercase_					,   """w"""      ) as f:
		f.write(lowercase_					,   arcname=os.path.basename(lowercase_      )      )
		f.write(lowercase_					,   arcname=os.path.basename(lowercase_      )      )
	return path

@pytest.fixture(scope="""session"""      )
def 		UpperCamelCase      (lowercase_:				Tuple					,   lowercase_:				Optional[int]					,   lowercase_:				Tuple      )  ->   List[str]:
	A__							:					Optional[int]       =	tmp_path_factory.mktemp("""data"""      ) / """dataset.csv.zip"""
	with zipfile.ZipFile(lowercase_					,   """w"""      ) as f:
		f.write(lowercase_					,   arcname=os.path.basename(csv_path.replace(""".csv"""					,   """.CSV"""      )      )      )
		f.write(lowercase_					,   arcname=os.path.basename(csva_path.replace(""".csv"""					,   """.CSV"""      )      )      )
	return path

@pytest.fixture(scope="""session"""      )
def 		UpperCamelCase      (lowercase_:				Tuple					,   lowercase_:				Dict					,   lowercase_:				int      )  ->   str:
	A__							:					Union[str, Any]       =	tmp_path_factory.mktemp("""data"""      ) / """dataset_with_dir.csv.zip"""
	with zipfile.ZipFile(lowercase_					,   """w"""      ) as f:
		f.write(lowercase_					,   arcname=os.path.join("""main_dir"""					,   os.path.basename(lowercase_      )      )      )
		f.write(lowercase_					,   arcname=os.path.join("""main_dir"""					,   os.path.basename(lowercase_      )      )      )
	return path

@pytest.fixture(scope="""session"""      )
def 		UpperCamelCase      (lowercase_:				int      )  ->   str:
	A__							:					int       =	str(tmp_path_factory.mktemp("""data"""      ) / """dataset.parquet"""      )
	A__							:					Union[str, Any]       =	pa.schema(
	    {
	        """col_1""": pa.string(),
	        """col_2""": pa.intaa(),
	        """col_3""": pa.floataa(),
	    }      )
	with open(lowercase_					,   """wb"""      ) as f:
		A__							:					List[str]       =	pq.ParquetWriter(lowercase_					,   schema=lowercase_      )
		A__							:					str       =	pa.Table.from_pydict({k: [DATA[i][k] for i in range(len(lowercase_      )      )] for k in DATA[0]}					,   schema=lowercase_      )
		writer.write_table(lowercase_      )
		writer.close()
	return path

@pytest.fixture(scope="""session"""      )
def 		UpperCamelCase      (lowercase_:				Tuple      )  ->   Optional[Any]:
	A__							:					Union[str, Any]       =	str(tmp_path_factory.mktemp("""data"""      ) / """dataset.json"""      )
	A__							:					Union[str, Any]       =	{"""data""": DATA}
	with open(lowercase_					,   """w"""      ) as f:
		json.dump(lowercase_					,   lowercase_      )
	return path

@pytest.fixture(scope="""session"""      )
def 		UpperCamelCase      (lowercase_:				List[str]      )  ->   str:
	A__							:					str       =	str(tmp_path_factory.mktemp("""data"""      ) / """dataset.json"""      )
	A__							:					Dict       =	{"""data""": DATA_DICT_OF_LISTS}
	with open(lowercase_					,   """w"""      ) as f:
		json.dump(lowercase_					,   lowercase_      )
	return path

@pytest.fixture(scope="""session"""      )
def 		UpperCamelCase      (lowercase_:				List[Any]      )  ->   Optional[Any]:
	A__							:					Union[str, Any]       =	str(tmp_path_factory.mktemp("""data"""      ) / """dataset.jsonl"""      )
	with open(lowercase_					,   """w"""      ) as f:
		for item in DATA:
			f.write(json.dumps(lowercase_      ) + """\n"""      )
	return path

@pytest.fixture(scope="""session"""      )
def 		UpperCamelCase      (lowercase_:				List[str]      )  ->   Dict:
	A__							:					Tuple       =	str(tmp_path_factory.mktemp("""data"""      ) / """dataset2.jsonl"""      )
	with open(lowercase_					,   """w"""      ) as f:
		for item in DATA:
			f.write(json.dumps(lowercase_      ) + """\n"""      )
	return path

@pytest.fixture(scope="""session"""      )
def 		UpperCamelCase      (lowercase_:				List[Any]      )  ->   Optional[Any]:
	A__							:					Union[str, Any]       =	str(tmp_path_factory.mktemp("""data"""      ) / """dataset_312.jsonl"""      )
	with open(lowercase_					,   """w"""      ) as f:
		for item in DATA_312:
			f.write(json.dumps(lowercase_      ) + """\n"""      )
	return path

@pytest.fixture(scope="""session"""      )
def 		UpperCamelCase      (lowercase_:				Union[str, Any]      )  ->   str:
	A__							:					Tuple       =	str(tmp_path_factory.mktemp("""data"""      ) / """dataset-str.jsonl"""      )
	with open(lowercase_					,   """w"""      ) as f:
		for item in DATA_STR:
			f.write(json.dumps(lowercase_      ) + """\n"""      )
	return path

@pytest.fixture(scope="""session"""      )
def 		UpperCamelCase      (lowercase_:				Tuple					,   lowercase_:				int      )  ->   Optional[Any]:
	import gzip

	A__							:					Tuple       =	str(tmp_path_factory.mktemp("""data"""      ) / """dataset.txt.gz"""      )
	with open(lowercase_					,   """rb"""      ) as orig_file:
		with gzip.open(lowercase_					,   """wb"""      ) as zipped_file:
			zipped_file.writelines(lowercase_      )
	return path

@pytest.fixture(scope="""session"""      )
def 		UpperCamelCase      (lowercase_:				int					,   lowercase_:				Optional[int]      )  ->   List[str]:
	import gzip

	A__							:					List[Any]       =	str(tmp_path_factory.mktemp("""data"""      ) / """dataset.jsonl.gz"""      )
	with open(lowercase_					,   """rb"""      ) as orig_file:
		with gzip.open(lowercase_					,   """wb"""      ) as zipped_file:
			zipped_file.writelines(lowercase_      )
	return path

@pytest.fixture(scope="""session"""      )
def 		UpperCamelCase      (lowercase_:				List[str]					,   lowercase_:				List[str]					,   lowercase_:				Union[str, Any]      )  ->   Optional[Any]:
	A__							:					Any       =	tmp_path_factory.mktemp("""data"""      ) / """dataset.jsonl.zip"""
	with zipfile.ZipFile(lowercase_					,   """w"""      ) as f:
		f.write(lowercase_					,   arcname=os.path.basename(lowercase_      )      )
		f.write(lowercase_					,   arcname=os.path.basename(lowercase_      )      )
	return path

@pytest.fixture(scope="""session"""      )
def 		UpperCamelCase      (lowercase_:				List[str]					,   lowercase_:				List[str]					,   lowercase_:				Union[str, Any]					,   lowercase_:				str      )  ->   Optional[int]:
	A__							:					Union[str, Any]       =	tmp_path_factory.mktemp("""data"""      ) / """dataset_nested.jsonl.zip"""
	with zipfile.ZipFile(lowercase_					,   """w"""      ) as f:
		f.write(lowercase_					,   arcname=os.path.join("""nested"""					,   os.path.basename(lowercase_      )      )      )
	return path

@pytest.fixture(scope="""session"""      )
def 		UpperCamelCase      (lowercase_:				Optional[Any]					,   lowercase_:				Any					,   lowercase_:				Any      )  ->   Tuple:
	A__							:					List[Any]       =	tmp_path_factory.mktemp("""data"""      ) / """dataset_with_dir.jsonl.zip"""
	with zipfile.ZipFile(lowercase_					,   """w"""      ) as f:
		f.write(lowercase_					,   arcname=os.path.join("""main_dir"""					,   os.path.basename(lowercase_      )      )      )
		f.write(lowercase_					,   arcname=os.path.join("""main_dir"""					,   os.path.basename(lowercase_      )      )      )
	return path

@pytest.fixture(scope="""session"""      )
def 		UpperCamelCase      (lowercase_:				str					,   lowercase_:				List[Any]					,   lowercase_:				Tuple      )  ->   Any:
	A__							:					Dict       =	tmp_path_factory.mktemp("""data"""      ) / """dataset.jsonl.tar"""
	with tarfile.TarFile(lowercase_					,   """w"""      ) as f:
		f.add(lowercase_					,   arcname=os.path.basename(lowercase_      )      )
		f.add(lowercase_					,   arcname=os.path.basename(lowercase_      )      )
	return path

@pytest.fixture(scope="""session"""      )
def 		UpperCamelCase      (lowercase_:				List[Any]					,   lowercase_:				Tuple					,   lowercase_:				Union[str, Any]					,   lowercase_:				int      )  ->   int:
	A__							:					Tuple       =	tmp_path_factory.mktemp("""data"""      ) / """dataset_nested.jsonl.tar"""
	with tarfile.TarFile(lowercase_					,   """w"""      ) as f:
		f.add(lowercase_					,   arcname=os.path.join("""nested"""					,   os.path.basename(lowercase_      )      )      )
	return path

@pytest.fixture(scope="""session"""      )
def 		UpperCamelCase      (lowercase_:				Any      )  ->   Union[str, Any]:
	A__							:					Union[str, Any]       =	["""0""", """1""", """2""", """3"""]
	A__							:					str       =	str(tmp_path_factory.mktemp("""data"""      ) / """dataset.txt"""      )
	with open(lowercase_					,   """w"""      ) as f:
		for item in data:
			f.write(item + """\n"""      )
	return path

@pytest.fixture(scope="""session"""      )
def 		UpperCamelCase      (lowercase_:				Optional[int]      )  ->   int:
	A__							:					int       =	["""0""", """1""", """2""", """3"""]
	A__							:					Optional[Any]       =	str(tmp_path_factory.mktemp("""data"""      ) / """dataset2.txt"""      )
	with open(lowercase_					,   """w"""      ) as f:
		for item in data:
			f.write(item + """\n"""      )
	return path

@pytest.fixture(scope="""session"""      )
def 		UpperCamelCase      (lowercase_:				Union[str, Any]      )  ->   int:
	A__							:					Optional[int]       =	["""0""", """1""", """2""", """3"""]
	A__							:					str       =	tmp_path_factory.mktemp("""data"""      ) / """dataset.abc"""
	with open(lowercase_					,   """w"""      ) as f:
		for item in data:
			f.write(item + """\n"""      )
	return path

@pytest.fixture(scope="""session"""      )
def 		UpperCamelCase      (lowercase_:				int					,   lowercase_:				Tuple					,   lowercase_:				Union[str, Any]      )  ->   List[Any]:
	A__							:					Optional[int]       =	tmp_path_factory.mktemp("""data"""      ) / """dataset.text.zip"""
	with zipfile.ZipFile(lowercase_					,   """w"""      ) as f:
		f.write(lowercase_					,   arcname=os.path.basename(lowercase_      )      )
		f.write(lowercase_					,   arcname=os.path.basename(lowercase_      )      )
	return path

@pytest.fixture(scope="""session"""      )
def 		UpperCamelCase      (lowercase_:				int					,   lowercase_:				Any					,   lowercase_:				Optional[Any]      )  ->   int:
	A__							:					Tuple       =	tmp_path_factory.mktemp("""data"""      ) / """dataset_with_dir.text.zip"""
	with zipfile.ZipFile(lowercase_					,   """w"""      ) as f:
		f.write(lowercase_					,   arcname=os.path.join("""main_dir"""					,   os.path.basename(lowercase_      )      )      )
		f.write(lowercase_					,   arcname=os.path.join("""main_dir"""					,   os.path.basename(lowercase_      )      )      )
	return path

@pytest.fixture(scope="""session"""      )
def 		UpperCamelCase      (lowercase_:				Dict					,   lowercase_:				int					,   lowercase_:				Any      )  ->   Optional[int]:
	A__							:					int       =	tmp_path_factory.mktemp("""data"""      ) / """dataset.ext.zip"""
	with zipfile.ZipFile(lowercase_					,   """w"""      ) as f:
		f.write(lowercase_					,   arcname=os.path.basename("""unsupported.ext"""      )      )
		f.write(lowercase_					,   arcname=os.path.basename("""unsupported_2.ext"""      )      )
	return path

@pytest.fixture(scope="""session"""      )
def 		UpperCamelCase      (lowercase_:				Any      )  ->   Optional[Any]:
	A__							:					int       =	"""\n""".join(["""First""", """Second\u2029with Unicode new line""", """Third"""]      )
	A__							:					Dict       =	str(tmp_path_factory.mktemp("""data"""      ) / """dataset_with_unicode_new_lines.txt"""      )
	with open(lowercase_					,   """w"""					,   encoding="""utf-8"""      ) as f:
		f.write(lowercase_      )
	return path

@pytest.fixture(scope="""session"""      )
def 		UpperCamelCase      ()  ->   Union[str, Any]:
	return os.path.join("""tests"""					,   """features"""					,   """data"""					,   """test_image_rgb.jpg"""      )

@pytest.fixture(scope="""session"""      )
def 		UpperCamelCase      ()  ->   int:
	return os.path.join("""tests"""					,   """features"""					,   """data"""					,   """test_audio_44100.wav"""      )

@pytest.fixture(scope="""session"""      )
def 		UpperCamelCase      (lowercase_:				Union[str, Any]					,   lowercase_:				Optional[Any]      )  ->   int:
	A__							:					Union[str, Any]       =	tmp_path_factory.mktemp("""data"""      ) / """dataset.img.zip"""
	with zipfile.ZipFile(lowercase_					,   """w"""      ) as f:
		f.write(lowercase_					,   arcname=os.path.basename(lowercase_      )      )
		f.write(lowercase_					,   arcname=os.path.basename(lowercase_      ).replace(""".jpg"""					,   """2.jpg"""      )      )
	return path


@pytest.fixture(scope="""session"""      )
def 		UpperCamelCase      (lowercase_:				Tuple      )  ->   List[str]:
	A__							:					str       =	tmp_path_factory.mktemp("""data_dir"""      )

	(data_dir / "subdir").mkdir()
	with open(data_dir / """subdir""" / """train.txt"""					,   """w"""      ) as f:
		f.write("""foo\n""" * 10      )
	with open(data_dir / """subdir""" / """test.txt"""					,   """w"""      ) as f:
		f.write("""bar\n""" * 10      )
	# hidden file
	with open(data_dir / """subdir""" / """.test.txt"""					,   """w"""      ) as f:
		f.write("""bar\n""" * 10      )

	# hidden directory
	(data_dir / ".subdir").mkdir()
	with open(data_dir / """.subdir""" / """train.txt"""					,   """w"""      ) as f:
		f.write("""foo\n""" * 10      )
	with open(data_dir / """.subdir""" / """test.txt"""					,   """w"""      ) as f:
		f.write("""bar\n""" * 10      )

	return data_dir






import inspect
import logging
import os
import random
import shutil
import tempfile
import unittest

import pytest
import torch
from torch import nn
from torch.utils.data import DataLoader, TensorDataset

from accelerate import Accelerator
from accelerate.test_utils import execute_subprocess_async, require_cuda
from accelerate.utils import ProjectConfiguration, set_seed


A_ :				Any						 =    logging.getLogger(__name__)

def 		UpperCamelCase      (lowercase_:				Optional[Any]=2					,   lowercase_:				Union[str, Any]=3					,   lowercase_:				int=16					,   lowercase_:				int = 10					,   lowercase_:				int = 2      )  ->   int:

	def get_dataset(lowercase_:				Optional[int]      ):
		A__							:					Optional[Any]       =	torch.randn(batch_size * n_batches					,   1      )
		return TensorDataset(lowercase_					,   a * x + b + 0.1 * torch.randn(batch_size * n_batches					,   1      )      )

	A__							:					Dict       =	get_dataset(lowercase_      )
	A__							:					Any       =	get_dataset(lowercase_      )
	A__							:					Dict       =	DataLoader(lowercase_					,   shuffle=lowercase_					,   batch_size=lowercase_					,   num_workers=4      )
	A__							:					Optional[Any]       =	DataLoader(lowercase_					,   shuffle=lowercase_					,   batch_size=lowercase_					,   num_workers=4      )
	return (train_dataloader, valid_dataloader)

def 		UpperCamelCase      (lowercase_:				Optional[Any]					,   lowercase_:				List[str]					,   lowercase_:				int					,   lowercase_:				int					,   lowercase_:				List[str]					,   lowercase_:				Dict=None      )  ->   List[Any]:
	A__							:					List[Any]       =	[]
	for epoch in range(lowercase_      ):
		# Train quickly
		model.train()
		for batch in dataloader:
			A__     ,     A__							:					Any       =	batch
			A__							:					Any       =	model(lowercase_      )
			A__							:					Any       =	torch.nn.functional.mse_loss(lowercase_					,   lowercase_      )
			accelerator.backward(lowercase_      )
			optimizer.step()
			optimizer.zero_grad()
		rands.append(random.random()      )  # Introduce some randomness
		if scheduler is not None:
			scheduler.step()
	return rands



class 					_a		(nn.Module       ):


					'''simple docstring'''






					def __init__(				self    ):
						super().__init__()
						A__							:					str       =	nn.Parameter(torch.randn(1    )    )
						A__							:					Any       =	nn.Parameter(torch.randn(1    )    )






					def 						__A    (				self					, A__    ):
						return x * self.a + self.b



class 					_a		(unittest.TestCase       ):


					'''simple docstring'''






					def 						__A    (				self    ):
						with tempfile.TemporaryDirectory() as tmpdir:
							set_seed(42    )
							A__							:					Optional[Any]       =	DummyModel()
							A__							:					Optional[Any]       =	torch.optim.Adam(params=model.parameters()					, lr=1e-3    )
							A__     ,     A__							:					str       =	dummy_dataloaders()
							A__							:					Dict       =	ProjectConfiguration(total_limit=1					, project_dir=A__					, automatic_checkpoint_naming=A__    )
							# Train baseline
							A__							:					List[str]       =	Accelerator(project_config=A__    )
							A__     ,     A__     ,     A__     ,     A__							:					Any       =	accelerator.prepare(
							    A__					, A__					, A__					, A__    )
							# Save initial
							accelerator.save_state()

							# Save second state
							accelerator.save_state()
							self.assertEqual(len(os.listdir(accelerator.project_dir    )    )					, 1    )






					def 						__A    (				self    ):
						with tempfile.TemporaryDirectory() as tmpdir:
							set_seed(42    )
							A__							:					str       =	DummyModel()
							A__							:					Optional[int]       =	torch.optim.Adam(params=model.parameters()					, lr=1e-3    )
							A__     ,     A__							:					int       =	dummy_dataloaders()
							# Train baseline
							A__							:					str       =	Accelerator()
							A__     ,     A__     ,     A__     ,     A__							:					List[str]       =	accelerator.prepare(
							    A__					, A__					, A__					, A__    )
							# Save initial
							A__							:					List[Any]       =	os.path.join(A__					, """initial"""    )
							accelerator.save_state(A__    )
							((A__)     ,     (A__))							:					str       =	model.a.item(), model.b.item()
							A__							:					Dict       =	optimizer.state_dict()
							A__							:					List[str]       =	train(3					, A__					, A__					, A__					, A__    )
							((A__)     ,     (A__))							:					str       =	model.a.item(), model.b.item()
							A__							:					Any       =	optimizer.state_dict()

							# Train partially
							set_seed(42    )
							A__							:					Optional[int]       =	DummyModel()
							A__							:					Dict       =	torch.optim.Adam(params=model.parameters()					, lr=1e-3    )
							A__     ,     A__							:					Dict       =	dummy_dataloaders()
							A__							:					List[str]       =	Accelerator()
							A__     ,     A__     ,     A__     ,     A__							:					Optional[Any]       =	accelerator.prepare(
							    A__					, A__					, A__					, A__    )
							accelerator.load_state(A__    )
							((A__)     ,     (A__))							:					Tuple       =	model.a.item(), model.b.item()
							A__							:					Union[str, Any]       =	optimizer.state_dict()
							self.assertEqual(A__					, A__    )
							self.assertEqual(A__					, A__    )
							self.assertEqual(A__					, A__    )

							A__							:					List[str]       =	train(2					, A__					, A__					, A__					, A__    )
							# Save everything
							A__							:					Optional[int]       =	os.path.join(A__					, """checkpoint"""    )
							accelerator.save_state(A__    )

							# Load everything back in and make sure all states work
							accelerator.load_state(A__    )
							test_rands += train(1					, A__					, A__					, A__					, A__    )
							((A__)     ,     (A__))							:					Union[str, Any]       =	model.a.item(), model.b.item()
							A__							:					Optional[int]       =	optimizer.state_dict()
							self.assertEqual(A__					, A__    )
							self.assertEqual(A__					, A__    )
							self.assertEqual(A__					, A__    )
							self.assertEqual(A__					, A__    )






					def 						__A    (				self    ):
						with tempfile.TemporaryDirectory() as tmpdir:
							set_seed(42    )
							A__							:					int       =	DummyModel()
							A__							:					Optional[int]       =	torch.optim.Adam(params=model.parameters()					, lr=1e-3    )
							A__     ,     A__							:					List[str]       =	dummy_dataloaders()
							A__							:					str       =	ProjectConfiguration(automatic_checkpoint_naming=A__    )

							# Train baseline
							A__							:					Any       =	Accelerator(project_dir=A__					, project_config=A__    )
							A__     ,     A__     ,     A__     ,     A__							:					str       =	accelerator.prepare(
							    A__					, A__					, A__					, A__    )
							# Save initial
							accelerator.save_state()
							((A__)     ,     (A__))							:					Tuple       =	model.a.item(), model.b.item()
							A__							:					int       =	optimizer.state_dict()
							A__							:					int       =	train(3					, A__					, A__					, A__					, A__    )
							((A__)     ,     (A__))							:					Optional[Any]       =	model.a.item(), model.b.item()
							A__							:					Any       =	optimizer.state_dict()

							# Train partially
							set_seed(42    )
							A__							:					Dict       =	DummyModel()
							A__							:					List[Any]       =	torch.optim.Adam(params=model.parameters()					, lr=1e-3    )
							A__     ,     A__							:					Union[str, Any]       =	dummy_dataloaders()
							A__							:					List[Any]       =	ProjectConfiguration(iteration=1					, automatic_checkpoint_naming=A__    )
							A__							:					Dict       =	Accelerator(project_dir=A__					, project_config=A__    )
							A__     ,     A__     ,     A__     ,     A__							:					Union[str, Any]       =	accelerator.prepare(
							    A__					, A__					, A__					, A__    )
							accelerator.load_state(os.path.join(A__					, """checkpoints"""					, """checkpoint_0"""    )    )
							((A__)     ,     (A__))							:					Optional[int]       =	model.a.item(), model.b.item()
							A__							:					Tuple       =	optimizer.state_dict()
							self.assertEqual(A__					, A__    )
							self.assertEqual(A__					, A__    )
							self.assertEqual(A__					, A__    )

							A__							:					str       =	train(2					, A__					, A__					, A__					, A__    )
							# Save everything
							accelerator.save_state()

							# Load everything back in and make sure all states work
							accelerator.load_state(os.path.join(A__					, """checkpoints"""					, """checkpoint_1"""    )    )
							test_rands += train(1					, A__					, A__					, A__					, A__    )
							((A__)     ,     (A__))							:					Optional[int]       =	model.a.item(), model.b.item()
							A__							:					List[Any]       =	optimizer.state_dict()
							self.assertEqual(A__					, A__    )
							self.assertEqual(A__					, A__    )
							self.assertEqual(A__					, A__    )
							self.assertEqual(A__					, A__    )






					def 						__A    (				self    ):
						A__							:					Union[str, Any]       =	torch.tensor([1, 2, 3]    )
						A__							:					int       =	torch.tensor([2, 3, 4]    )
						A__							:					List[Any]       =	DummyModel()
						A__							:					List[Any]       =	torch.optim.Adam(net.parameters()    )
						A__							:					Tuple       =	Accelerator()
						with self.assertRaises(A__    ) as ve:
							accelerator.register_for_checkpointing(A__					, A__					, A__					, A__    )
						A__							:					Any       =	str(ve.exception    )
						self.assertTrue("""Item at index 0""" in message    )
						self.assertTrue("""Item at index 1""" in message    )
						self.assertFalse("""Item at index 2""" in message    )
						self.assertFalse("""Item at index 3""" in message    )






					def 						__A    (				self    ):
						with tempfile.TemporaryDirectory() as tmpdir:
							set_seed(42    )
							A__							:					Any       =	DummyModel()
							A__							:					Union[str, Any]       =	torch.optim.Adam(params=model.parameters()					, lr=1e-3    )
							A__							:					Dict       =	torch.optim.lr_scheduler.StepLR(A__					, step_size=1					, gamma=0.9_9    )
							A__     ,     A__							:					List[Any]       =	dummy_dataloaders()
							A__							:					Tuple       =	ProjectConfiguration(automatic_checkpoint_naming=A__    )
							# Train baseline
							A__							:					Optional[Any]       =	Accelerator(project_dir=A__					, project_config=A__    )
							A__     ,     A__     ,     A__     ,     A__     ,     A__							:					Union[str, Any]       =	accelerator.prepare(
							    A__					, A__					, A__					, A__					, A__    )
							# Save initial
							accelerator.save_state()
							A__							:					Tuple       =	scheduler.state_dict()
							train(3					, A__					, A__					, A__					, A__					, A__    )
							self.assertNotEqual(A__					, scheduler.state_dict()    )

							# Load everything back in and make sure all states work
							accelerator.load_state(os.path.join(A__					, """checkpoints"""					, """checkpoint_0"""    )    )
							self.assertEqual(A__					, scheduler.state_dict()    )






					def 						__A    (				self    ):
						with tempfile.TemporaryDirectory() as tmpdir:
							set_seed(42    )
							A__							:					Optional[Any]       =	DummyModel()
							A__							:					int       =	ProjectConfiguration(automatic_checkpoint_naming=A__					, total_limit=2    )
							# Train baseline
							A__							:					List[str]       =	Accelerator(project_dir=A__					, project_config=A__    )
							A__							:					Union[str, Any]       =	accelerator.prepare(A__    )
							# Save 3 states:
							for _ in range(11    ):
								accelerator.save_state()
							self.assertTrue(not os.path.exists(os.path.join(A__					, """checkpoints"""					, """checkpoint_0"""    )    )    )
							self.assertTrue(os.path.exists(os.path.join(A__					, """checkpoints"""					, """checkpoint_9"""    )    )    )
							self.assertTrue(os.path.exists(os.path.join(A__					, """checkpoints"""					, """checkpoint_10"""    )    )    )






					@require_cuda
					def 						__A    (				self    ):
						A__							:					Dict       =	["""torchrun""", F"""--nproc_per_node={torch.cuda.device_count()}""", inspect.getfile(self.__class__    )]
						execute_subprocess_async(A__					, env=os.environ.copy()    )


if __name__ == "__main__":
	A_ :				List[str]						 =    '/tmp/accelerate/state_checkpointing'
	A_ :				Optional[Any]						 =    DummyModel()
	A_ :				Union[str, Any]						 =    torch.optim.Adam(params=model.parameters(), lr=1E-3)
	A_ :				str						 =    torch.optim.lr_scheduler.StepLR(optimizer, step_size=1, gamma=0.99)
	A_ ,    A_ :				List[Any]						 =    dummy_dataloaders()
	A_ :				int						 =    ProjectConfiguration(automatic_checkpoint_naming=True)
	# Train baseline
	A_ :				List[str]						 =    Accelerator(project_dir=savedir, project_config=project_config, mixed_precision='no')
	if accelerator.process_index == 0:
		if os.path.exists(savedir):
			shutil.rmtree(savedir)
		os.makedirs(savedir)
	A_ ,    A_ ,    A_ ,    A_ ,    A_ :				List[Any]						 =    accelerator.prepare(
	    model, optimizer, train_dataloader, valid_dataloader, scheduler
	)
	A_ ,    A_ :				Dict						 =    accelerator.prepare(model, optimizer)
	train(3, model, train_dataloader, optimizer, accelerator, scheduler)
	# Check that the intial optimizer is loaded on the GPU
	for group in optimizer.param_groups:
		A_ :				str						 =    group['params'][0].device
		break
	assert param_device.type == accelerator.device.type
	A_ :				Optional[Any]						 =    model.cpu()
	accelerator.wait_for_everyone()
	accelerator.save_state()
	accelerator.wait_for_everyone()

	# Check CPU state
	accelerator.load_state(os.path.join(savedir, 'checkpoints', 'checkpoint_0'), map_location='cpu')
	for group in optimizer.param_groups:
		A_ :				str						 =    group['params'][0].device
		break
	assert (
	    param_device.type == torch.device('cpu').type
	), f"Loaded optimizer states did not match, expected to be loaded on the CPU but got {param_device}"

	# Check device state
	model.to(accelerator.device)
	accelerator.load_state(os.path.join(savedir, 'checkpoints', 'checkpoint_0'), map_location='on_device')
	for group in optimizer.param_groups:
		A_ :				Tuple						 =    group['params'][0].device
		break
	assert (
	    param_device.type == accelerator.device.type
	), f"Loaded optimizer states did not match, expected to be loaded on {accelerator.device} but got {param_device}"

	# Check error
	with pytest.raises(TypeError, match='Unsupported optimizer map location passed'):
		accelerator.load_state(os.path.join(savedir, 'checkpoints', 'checkpoint_0'), map_location='invalid')
	accelerator.wait_for_everyone()
	if accelerator.process_index == 0:
		shutil.rmtree(savedir)
	accelerator.wait_for_everyone()



