'''simple docstring'''


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  _lowerCamelCase   (				):



     """simple docstring"""





     UpperCAmelCase_							:       Any       =				10
     UpperCAmelCase_							:       List[Any]       =				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'       ),
         }       )
     UpperCAmelCase_							:       Tuple       =				datasets.Dataset.from_dict(
         {
             'tokens': [['foo'] * 5] * n,
             'labels': [[1] * 5] * n,
             'answers': [{'answer_start': [97], 'text': ['1976']}] * 10,
             'id': list(range(lowerCamelCase_       )       ),
         }     ,					features=lowerCamelCase_     ,					)
     return dataset


@pytest.fixture(scope='session'       )
def  _lowerCamelCase   (				lowerCamelCase_ :							List[str]     ,					lowerCamelCase_ :							Optional[int]       ):



     """simple docstring"""





     UpperCAmelCase_							:       int       =				str(tmp_path_factory.mktemp('data'       ) / 'file.arrow'       )
     dataset.map(cache_file_name=lowerCamelCase_       )
     return filename


# FILE_CONTENT + files


snake_case__					:      List[Any]				      =  '''\
    Text data.
    Second line of data.'''


@pytest.fixture(scope='session'       )
def  _lowerCamelCase   (				lowerCamelCase_ :							Union[str, Any]       ):



     """simple docstring"""





     UpperCAmelCase_							:       List[Any]       =				tmp_path_factory.mktemp('data'       ) / 'file.txt'
     UpperCAmelCase_							:       Any       =				FILE_CONTENT
     with open(lowerCamelCase_     ,					'w'       ) as f:
          f.write(lowerCamelCase_       )
     return filename


@pytest.fixture(scope='session'       )
def  _lowerCamelCase   (				lowerCamelCase_ :							Optional[Any]       ):



     """simple docstring"""





     import bza

     UpperCAmelCase_							:       Optional[Any]       =				tmp_path_factory.mktemp('data'       ) / 'file.txt.bz2'
     UpperCAmelCase_							:       Tuple       =				bytes(lowerCamelCase_     ,					'utf-8'       )
     with bza.open(lowerCamelCase_     ,					'wb'       ) as f:
          f.write(lowerCamelCase_       )
     return path


@pytest.fixture(scope='session'       )
def  _lowerCamelCase   (				lowerCamelCase_ :							Optional[int]       ):



     """simple docstring"""





     import gzip

     UpperCAmelCase_							:       Tuple       =				str(tmp_path_factory.mktemp('data'       ) / 'file.txt.gz'       )
     UpperCAmelCase_							:       Any       =				bytes(lowerCamelCase_     ,					'utf-8'       )
     with gzip.open(lowerCamelCase_     ,					'wb'       ) as f:
          f.write(lowerCamelCase_       )
     return path


@pytest.fixture(scope='session'       )
def  _lowerCamelCase   (				lowerCamelCase_ :							Tuple       ):



     """simple docstring"""





     if datasets.config.LZ4_AVAILABLE:
          import lza.frame

          UpperCAmelCase_							:       Union[str, Any]       =				tmp_path_factory.mktemp('data'       ) / 'file.txt.lz4'
          UpperCAmelCase_							:       str       =				bytes(lowerCamelCase_     ,					'utf-8'       )
          with lza.frame.open(lowerCamelCase_     ,					'wb'       ) as f:
               f.write(lowerCamelCase_       )
          return path


@pytest.fixture(scope='session'       )
def  _lowerCamelCase   (				lowerCamelCase_ :							Tuple     ,					lowerCamelCase_ :							List[str]       ):



     """simple docstring"""





     if datasets.config.PY7ZR_AVAILABLE:
          import pyazr

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


@pytest.fixture(scope='session'       )
def  _lowerCamelCase   (				lowerCamelCase_ :							Dict     ,					lowerCamelCase_ :							Tuple       ):



     """simple docstring"""





     import tarfile

     UpperCAmelCase_							:       Union[str, Any]       =				tmp_path_factory.mktemp('data'       ) / 'file.txt.tar'
     with tarfile.TarFile(lowerCamelCase_     ,					'w'       ) as f:
          f.add(lowerCamelCase_     ,					arcname=os.path.basename(lowerCamelCase_       )       )
     return path


@pytest.fixture(scope='session'       )
def  _lowerCamelCase   (				lowerCamelCase_ :							str       ):



     """simple docstring"""





     import lzma

     UpperCAmelCase_							:       Dict       =				tmp_path_factory.mktemp('data'       ) / 'file.txt.xz'
     UpperCAmelCase_							:       str       =				bytes(lowerCamelCase_     ,					'utf-8'       )
     with lzma.open(lowerCamelCase_     ,					'wb'       ) as f:
          f.write(lowerCamelCase_       )
     return path


@pytest.fixture(scope='session'       )
def  _lowerCamelCase   (				lowerCamelCase_ :							str     ,					lowerCamelCase_ :							Optional[int]       ):



     """simple docstring"""





     import zipfile

     UpperCAmelCase_							:       str       =				tmp_path_factory.mktemp('data'       ) / 'file.txt.zip'
     with zipfile.ZipFile(lowerCamelCase_     ,					'w'       ) as f:
          f.write(lowerCamelCase_     ,					arcname=os.path.basename(lowerCamelCase_       )       )
     return path


@pytest.fixture(scope='session'       )
def  _lowerCamelCase   (				lowerCamelCase_ :							str       ):



     """simple docstring"""





     if datasets.config.ZSTANDARD_AVAILABLE:
          import zstandard as zstd

          UpperCAmelCase_							:       Dict       =				tmp_path_factory.mktemp('data'       ) / 'file.txt.zst'
          UpperCAmelCase_							:       Any       =				bytes(lowerCamelCase_     ,					'utf-8'       )
          with zstd.open(lowerCamelCase_     ,					'wb'       ) as f:
               f.write(lowerCamelCase_       )
          return path


@pytest.fixture(scope='session'       )
def  _lowerCamelCase   (				lowerCamelCase_ :							Union[str, Any]       ):



     """simple docstring"""





     UpperCAmelCase_							:       List[str]       =				tmp_path_factory.mktemp('data'       ) / 'file.xml'
     UpperCAmelCase_							:       Optional[Any]       =				textwrap.dedent(
         '\\n    <?xml version="1.0" encoding="UTF-8" ?>\n    <tmx version="1.4">\n      <header segtype="sentence" srclang="ca" />\n      <body>\n        <tu>\n          <tuv xml:lang="ca"><seg>Contingut 1</seg></tuv>\n          <tuv xml:lang="en"><seg>Content 1</seg></tuv>\n        </tu>\n        <tu>\n          <tuv xml:lang="ca"><seg>Contingut 2</seg></tuv>\n          <tuv xml:lang="en"><seg>Content 2</seg></tuv>\n        </tu>\n        <tu>\n          <tuv xml:lang="ca"><seg>Contingut 3</seg></tuv>\n          <tuv xml:lang="en"><seg>Content 3</seg></tuv>\n        </tu>\n        <tu>\n          <tuv xml:lang="ca"><seg>Contingut 4</seg></tuv>\n          <tuv xml:lang="en"><seg>Content 4</seg></tuv>\n        </tu>\n        <tu>\n          <tuv xml:lang="ca"><seg>Contingut 5</seg></tuv>\n          <tuv xml:lang="en"><seg>Content 5</seg></tuv>\n        </tu>\n      </body>\n    </tmx>'       )
     with open(lowerCamelCase_     ,					'w'       ) as f:
          f.write(lowerCamelCase_       )
     return filename


snake_case__					:      int				      =  [
    {'''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},
]
snake_case__					:      Tuple				      =  [
    {'''col_1''': '''4''', '''col_2''': 4, '''col_3''': 4.0},
    {'''col_1''': '''5''', '''col_2''': 5, '''col_3''': 5.0},
]
snake_case__					:      Optional[int]				      =  {
    '''col_1''': ['''0''', '''1''', '''2''', '''3'''],
    '''col_2''': [0, 1, 2, 3],
    '''col_3''': [0.0, 1.0, 2.0, 3.0],
}

snake_case__					:      Optional[Any]				      =  [
    {'''col_3''': 0.0, '''col_1''': '''0''', '''col_2''': 0},
    {'''col_3''': 1.0, '''col_1''': '''1''', '''col_2''': 1},
]

snake_case__					:      List[str]				      =  [
    {'''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  _lowerCamelCase   (				):



     """simple docstring"""





     return DATA_DICT_OF_LISTS


@pytest.fixture(scope='session'       )
def  _lowerCamelCase   (				lowerCamelCase_ :							Union[str, Any]       ):



     """simple docstring"""





     UpperCAmelCase_							:       Optional[int]       =				datasets.Dataset.from_dict(lowerCamelCase_       )
     UpperCAmelCase_							:       Tuple       =				str(tmp_path_factory.mktemp('data'       ) / 'dataset.arrow'       )
     dataset.map(cache_file_name=lowerCamelCase_       )
     return path


@pytest.fixture(scope='session'       )
def  _lowerCamelCase   (				lowerCamelCase_ :							str       ):



     """simple docstring"""





     UpperCAmelCase_							:       Tuple       =				str(tmp_path_factory.mktemp('data'       ) / 'dataset.sqlite'       )
     with contextlib.closing(sqlitea.connect(lowerCamelCase_       )       ) as con:
          UpperCAmelCase_							:       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  _lowerCamelCase   (				lowerCamelCase_ :							str       ):



     """simple docstring"""





     UpperCAmelCase_							:       str       =				str(tmp_path_factory.mktemp('data'       ) / 'dataset.csv'       )
     with open(lowerCamelCase_     ,					'w'     ,					newline=''       ) as f:
          UpperCAmelCase_							:       List[Any]       =				csv.DictWriter(lowerCamelCase_     ,					fieldnames=['col_1', 'col_2', 'col_3']       )
          writer.writeheader()
          for item in DATA:
               writer.writerow(lowerCamelCase_       )
     return path


@pytest.fixture(scope='session'       )
def  _lowerCamelCase   (				lowerCamelCase_ :							Union[str, Any]       ):



     """simple docstring"""





     UpperCAmelCase_							:       Any       =				str(tmp_path_factory.mktemp('data'       ) / 'dataset2.csv'       )
     with open(lowerCamelCase_     ,					'w'     ,					newline=''       ) as f:
          UpperCAmelCase_							:       List[str]       =				csv.DictWriter(lowerCamelCase_     ,					fieldnames=['col_1', 'col_2', 'col_3']       )
          writer.writeheader()
          for item in DATA:
               writer.writerow(lowerCamelCase_       )
     return path


@pytest.fixture(scope='session'       )
def  _lowerCamelCase   (				lowerCamelCase_ :							Tuple     ,					lowerCamelCase_ :							Tuple       ):



     """simple docstring"""





     import bza

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


@pytest.fixture(scope='session'       )
def  _lowerCamelCase   (				lowerCamelCase_ :							Union[str, Any]     ,					lowerCamelCase_ :							Tuple     ,					lowerCamelCase_ :							Dict       ):



     """simple docstring"""





     UpperCAmelCase_							:       Optional[Any]       =				tmp_path_factory.mktemp('data'       ) / 'dataset.csv.zip'
     with zipfile.ZipFile(lowerCamelCase_     ,					'w'       ) as f:
          f.write(lowerCamelCase_     ,					arcname=os.path.basename(lowerCamelCase_       )       )
          f.write(lowerCamelCase_     ,					arcname=os.path.basename(lowerCamelCase_       )       )
     return path


@pytest.fixture(scope='session'       )
def  _lowerCamelCase   (				lowerCamelCase_ :							str     ,					lowerCamelCase_ :							Optional[Any]     ,					lowerCamelCase_ :							Dict       ):



     """simple docstring"""





     UpperCAmelCase_							:       Optional[Any]       =				tmp_path_factory.mktemp('data'       ) / 'dataset.csv.zip'
     with zipfile.ZipFile(lowerCamelCase_     ,					'w'       ) as f:
          f.write(lowerCamelCase_     ,					arcname=os.path.basename(csv_path.replace('.csv'     ,					'.CSV'       )       )       )
          f.write(lowerCamelCase_     ,					arcname=os.path.basename(csva_path.replace('.csv'     ,					'.CSV'       )       )       )
     return path


@pytest.fixture(scope='session'       )
def  _lowerCamelCase   (				lowerCamelCase_ :							str     ,					lowerCamelCase_ :							Optional[Any]     ,					lowerCamelCase_ :							Dict       ):



     """simple docstring"""





     UpperCAmelCase_							:       List[str]       =				tmp_path_factory.mktemp('data'       ) / 'dataset_with_dir.csv.zip'
     with zipfile.ZipFile(lowerCamelCase_     ,					'w'       ) as f:
          f.write(lowerCamelCase_     ,					arcname=os.path.join('main_dir'     ,					os.path.basename(lowerCamelCase_       )       )       )
          f.write(lowerCamelCase_     ,					arcname=os.path.join('main_dir'     ,					os.path.basename(lowerCamelCase_       )       )       )
     return path


@pytest.fixture(scope='session'       )
def  _lowerCamelCase   (				lowerCamelCase_ :							List[Any]       ):



     """simple docstring"""





     UpperCAmelCase_							:       Optional[int]       =				str(tmp_path_factory.mktemp('data'       ) / 'dataset.parquet'       )
     UpperCAmelCase_							:       Any       =				pa.schema(
         {
             'col_1': pa.string(),
             'col_2': pa.intaa(),
             'col_3': pa.floataa(),
         }       )
     with open(lowerCamelCase_     ,					'wb'       ) as f:
          UpperCAmelCase_							:       Optional[int]       =				pq.ParquetWriter(lowerCamelCase_     ,					schema=lowerCamelCase_       )
          UpperCAmelCase_							:       List[str]       =				pa.Table.from_pydict({k: [DATA[i][k] for i in range(len(lowerCamelCase_       )       )] for k in DATA[0]}     ,					schema=lowerCamelCase_       )
          writer.write_table(lowerCamelCase_       )
          writer.close()
     return path


@pytest.fixture(scope='session'       )
def  _lowerCamelCase   (				lowerCamelCase_ :							Tuple       ):



     """simple docstring"""





     UpperCAmelCase_							:       List[str]       =				str(tmp_path_factory.mktemp('data'       ) / 'dataset.json'       )
     UpperCAmelCase_							:       Tuple       =				{'data': DATA}
     with open(lowerCamelCase_     ,					'w'       ) as f:
          json.dump(lowerCamelCase_     ,					lowerCamelCase_       )
     return path


@pytest.fixture(scope='session'       )
def  _lowerCamelCase   (				lowerCamelCase_ :							Any       ):



     """simple docstring"""





     UpperCAmelCase_							:       Tuple       =				str(tmp_path_factory.mktemp('data'       ) / 'dataset.json'       )
     UpperCAmelCase_							:       Optional[int]       =				{'data': DATA_DICT_OF_LISTS}
     with open(lowerCamelCase_     ,					'w'       ) as f:
          json.dump(lowerCamelCase_     ,					lowerCamelCase_       )
     return path


@pytest.fixture(scope='session'       )
def  _lowerCamelCase   (				lowerCamelCase_ :							Tuple       ):



     """simple docstring"""





     UpperCAmelCase_							:       int       =				str(tmp_path_factory.mktemp('data'       ) / 'dataset.jsonl'       )
     with open(lowerCamelCase_     ,					'w'       ) as f:
          for item in DATA:
               f.write(json.dumps(lowerCamelCase_       ) + '\n'       )
     return path


@pytest.fixture(scope='session'       )
def  _lowerCamelCase   (				lowerCamelCase_ :							List[str]       ):



     """simple docstring"""





     UpperCAmelCase_							:       Optional[int]       =				str(tmp_path_factory.mktemp('data'       ) / 'dataset2.jsonl'       )
     with open(lowerCamelCase_     ,					'w'       ) as f:
          for item in DATA:
               f.write(json.dumps(lowerCamelCase_       ) + '\n'       )
     return path


@pytest.fixture(scope='session'       )
def  _lowerCamelCase   (				lowerCamelCase_ :							Optional[Any]       ):



     """simple docstring"""





     UpperCAmelCase_							:       List[Any]       =				str(tmp_path_factory.mktemp('data'       ) / 'dataset_312.jsonl'       )
     with open(lowerCamelCase_     ,					'w'       ) as f:
          for item in DATA_312:
               f.write(json.dumps(lowerCamelCase_       ) + '\n'       )
     return path


@pytest.fixture(scope='session'       )
def  _lowerCamelCase   (				lowerCamelCase_ :							List[Any]       ):



     """simple docstring"""





     UpperCAmelCase_							:       Optional[int]       =				str(tmp_path_factory.mktemp('data'       ) / 'dataset-str.jsonl'       )
     with open(lowerCamelCase_     ,					'w'       ) as f:
          for item in DATA_STR:
               f.write(json.dumps(lowerCamelCase_       ) + '\n'       )
     return path


@pytest.fixture(scope='session'       )
def  _lowerCamelCase   (				lowerCamelCase_ :							Union[str, Any]     ,					lowerCamelCase_ :							List[str]       ):



     """simple docstring"""





     import gzip

     UpperCAmelCase_							:       int       =				str(tmp_path_factory.mktemp('data'       ) / 'dataset.txt.gz'       )
     with open(lowerCamelCase_     ,					'rb'       ) as orig_file:
          with gzip.open(lowerCamelCase_     ,					'wb'       ) as zipped_file:
               zipped_file.writelines(lowerCamelCase_       )
     return path


@pytest.fixture(scope='session'       )
def  _lowerCamelCase   (				lowerCamelCase_ :							Union[str, Any]     ,					lowerCamelCase_ :							Union[str, Any]       ):



     """simple docstring"""





     import gzip

     UpperCAmelCase_							:       Union[str, Any]       =				str(tmp_path_factory.mktemp('data'       ) / 'dataset.jsonl.gz'       )
     with open(lowerCamelCase_     ,					'rb'       ) as orig_file:
          with gzip.open(lowerCamelCase_     ,					'wb'       ) as zipped_file:
               zipped_file.writelines(lowerCamelCase_       )
     return path


@pytest.fixture(scope='session'       )
def  _lowerCamelCase   (				lowerCamelCase_ :							Optional[Any]     ,					lowerCamelCase_ :							Union[str, Any]     ,					lowerCamelCase_ :							Union[str, Any]       ):



     """simple docstring"""





     UpperCAmelCase_							:       Optional[int]       =				tmp_path_factory.mktemp('data'       ) / 'dataset.jsonl.zip'
     with zipfile.ZipFile(lowerCamelCase_     ,					'w'       ) as f:
          f.write(lowerCamelCase_     ,					arcname=os.path.basename(lowerCamelCase_       )       )
          f.write(lowerCamelCase_     ,					arcname=os.path.basename(lowerCamelCase_       )       )
     return path


@pytest.fixture(scope='session'       )
def  _lowerCamelCase   (				lowerCamelCase_ :							Tuple     ,					lowerCamelCase_ :							Optional[int]     ,					lowerCamelCase_ :							List[str]     ,					lowerCamelCase_ :							str       ):



     """simple docstring"""





     UpperCAmelCase_							:       Union[str, Any]       =				tmp_path_factory.mktemp('data'       ) / 'dataset_nested.jsonl.zip'
     with zipfile.ZipFile(lowerCamelCase_     ,					'w'       ) as f:
          f.write(lowerCamelCase_     ,					arcname=os.path.join('nested'     ,					os.path.basename(lowerCamelCase_       )       )       )
     return path


@pytest.fixture(scope='session'       )
def  _lowerCamelCase   (				lowerCamelCase_ :							Optional[Any]     ,					lowerCamelCase_ :							List[Any]     ,					lowerCamelCase_ :							List[Any]       ):



     """simple docstring"""





     UpperCAmelCase_							:       Tuple       =				tmp_path_factory.mktemp('data'       ) / 'dataset_with_dir.jsonl.zip'
     with zipfile.ZipFile(lowerCamelCase_     ,					'w'       ) as f:
          f.write(lowerCamelCase_     ,					arcname=os.path.join('main_dir'     ,					os.path.basename(lowerCamelCase_       )       )       )
          f.write(lowerCamelCase_     ,					arcname=os.path.join('main_dir'     ,					os.path.basename(lowerCamelCase_       )       )       )
     return path


@pytest.fixture(scope='session'       )
def  _lowerCamelCase   (				lowerCamelCase_ :							Optional[int]     ,					lowerCamelCase_ :							str     ,					lowerCamelCase_ :							Optional[int]       ):



     """simple docstring"""





     UpperCAmelCase_							:       Tuple       =				tmp_path_factory.mktemp('data'       ) / 'dataset.jsonl.tar'
     with tarfile.TarFile(lowerCamelCase_     ,					'w'       ) as f:
          f.add(lowerCamelCase_     ,					arcname=os.path.basename(lowerCamelCase_       )       )
          f.add(lowerCamelCase_     ,					arcname=os.path.basename(lowerCamelCase_       )       )
     return path


@pytest.fixture(scope='session'       )
def  _lowerCamelCase   (				lowerCamelCase_ :							str     ,					lowerCamelCase_ :							Any     ,					lowerCamelCase_ :							List[Any]     ,					lowerCamelCase_ :							int       ):



     """simple docstring"""





     UpperCAmelCase_							:       Tuple       =				tmp_path_factory.mktemp('data'       ) / 'dataset_nested.jsonl.tar'
     with tarfile.TarFile(lowerCamelCase_     ,					'w'       ) as f:
          f.add(lowerCamelCase_     ,					arcname=os.path.join('nested'     ,					os.path.basename(lowerCamelCase_       )       )       )
     return path


@pytest.fixture(scope='session'       )
def  _lowerCamelCase   (				lowerCamelCase_ :							Tuple       ):



     """simple docstring"""





     UpperCAmelCase_							:       List[Any]       =				['0', '1', '2', '3']
     UpperCAmelCase_							:       Optional[int]       =				str(tmp_path_factory.mktemp('data'       ) / 'dataset.txt'       )
     with open(lowerCamelCase_     ,					'w'       ) as f:
          for item in data:
               f.write(item + '\n'       )
     return path


@pytest.fixture(scope='session'       )
def  _lowerCamelCase   (				lowerCamelCase_ :							List[str]       ):



     """simple docstring"""





     UpperCAmelCase_							:       Tuple       =				['0', '1', '2', '3']
     UpperCAmelCase_							:       List[Any]       =				str(tmp_path_factory.mktemp('data'       ) / 'dataset2.txt'       )
     with open(lowerCamelCase_     ,					'w'       ) as f:
          for item in data:
               f.write(item + '\n'       )
     return path


@pytest.fixture(scope='session'       )
def  _lowerCamelCase   (				lowerCamelCase_ :							Dict       ):



     """simple docstring"""





     UpperCAmelCase_							:       int       =				['0', '1', '2', '3']
     UpperCAmelCase_							:       List[str]       =				tmp_path_factory.mktemp('data'       ) / 'dataset.abc'
     with open(lowerCamelCase_     ,					'w'       ) as f:
          for item in data:
               f.write(item + '\n'       )
     return path


@pytest.fixture(scope='session'       )
def  _lowerCamelCase   (				lowerCamelCase_ :							str     ,					lowerCamelCase_ :							List[Any]     ,					lowerCamelCase_ :							int       ):



     """simple docstring"""





     UpperCAmelCase_							:       Tuple       =				tmp_path_factory.mktemp('data'       ) / 'dataset.text.zip'
     with zipfile.ZipFile(lowerCamelCase_     ,					'w'       ) as f:
          f.write(lowerCamelCase_     ,					arcname=os.path.basename(lowerCamelCase_       )       )
          f.write(lowerCamelCase_     ,					arcname=os.path.basename(lowerCamelCase_       )       )
     return path


@pytest.fixture(scope='session'       )
def  _lowerCamelCase   (				lowerCamelCase_ :							Optional[Any]     ,					lowerCamelCase_ :							str     ,					lowerCamelCase_ :							Tuple       ):



     """simple docstring"""





     UpperCAmelCase_							:       List[str]       =				tmp_path_factory.mktemp('data'       ) / 'dataset_with_dir.text.zip'
     with zipfile.ZipFile(lowerCamelCase_     ,					'w'       ) as f:
          f.write(lowerCamelCase_     ,					arcname=os.path.join('main_dir'     ,					os.path.basename(lowerCamelCase_       )       )       )
          f.write(lowerCamelCase_     ,					arcname=os.path.join('main_dir'     ,					os.path.basename(lowerCamelCase_       )       )       )
     return path


@pytest.fixture(scope='session'       )
def  _lowerCamelCase   (				lowerCamelCase_ :							List[str]     ,					lowerCamelCase_ :							List[Any]     ,					lowerCamelCase_ :							Union[str, Any]       ):



     """simple docstring"""





     UpperCAmelCase_							:       Dict       =				tmp_path_factory.mktemp('data'       ) / 'dataset.ext.zip'
     with zipfile.ZipFile(lowerCamelCase_     ,					'w'       ) as f:
          f.write(lowerCamelCase_     ,					arcname=os.path.basename('unsupported.ext'       )       )
          f.write(lowerCamelCase_     ,					arcname=os.path.basename('unsupported_2.ext'       )       )
     return path


@pytest.fixture(scope='session'       )
def  _lowerCamelCase   (				lowerCamelCase_ :							Optional[Any]       ):



     """simple docstring"""





     UpperCAmelCase_							:       List[Any]       =				'\n'.join(['First', 'Second\u2029with Unicode new line', 'Third']       )
     UpperCAmelCase_							:       List[Any]       =				str(tmp_path_factory.mktemp('data'       ) / 'dataset_with_unicode_new_lines.txt'       )
     with open(lowerCamelCase_     ,					'w'     ,					encoding='utf-8'       ) as f:
          f.write(lowerCamelCase_       )
     return path


@pytest.fixture(scope='session'       )
def  _lowerCamelCase   (				):



     """simple docstring"""





     return os.path.join('tests'     ,					'features'     ,					'data'     ,					'test_image_rgb.jpg'       )


@pytest.fixture(scope='session'       )
def  _lowerCamelCase   (				):



     """simple docstring"""





     return os.path.join('tests'     ,					'features'     ,					'data'     ,					'test_audio_44100.wav'       )


@pytest.fixture(scope='session'       )
def  _lowerCamelCase   (				lowerCamelCase_ :							Any     ,					lowerCamelCase_ :							Tuple       ):



     """simple docstring"""





     UpperCAmelCase_							:       List[Any]       =				tmp_path_factory.mktemp('data'       ) / 'dataset.img.zip'
     with zipfile.ZipFile(lowerCamelCase_     ,					'w'       ) as f:
          f.write(lowerCamelCase_     ,					arcname=os.path.basename(lowerCamelCase_       )       )
          f.write(lowerCamelCase_     ,					arcname=os.path.basename(lowerCamelCase_       ).replace('.jpg'     ,					'2.jpg'       )       )
     return path





@pytest.fixture(scope='session'       )
def  _lowerCamelCase   (				lowerCamelCase_ :							List[Any]       ):



     """simple docstring"""





     UpperCAmelCase_							:       List[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







'''simple docstring'''


import numpy as np
import torch
from torch.nn import CrossEntropyLoss
from transformers import AutoModelForCausalLM, AutoTokenizer

import datasets
from datasets import logging


snake_case__					:      str				      =  '''\

'''

snake_case__					:      Union[str, Any]				      =  '''
Perplexity (PPL) is one of the most common metrics for evaluating language models.
It is defined as the exponentiated average negative log-likelihood of a sequence.

For more information, see https://huggingface.co/docs/transformers/perplexity
'''

snake_case__					:      str				      =  '''
Args:
    model_id (str): model used for calculating Perplexity
            NOTE: Perplexity can only be calculated for causal language models.
                    This includes models such as gpt2, causal variations of bert,
                    causal versions of t5, and more (the full list can be found
                    in the AutoModelForCausalLM documentation here:
                    https://huggingface.co/docs/transformers/master/en/model_doc/auto#transformers.AutoModelForCausalLM )

    input_texts (list of str): input text, each separate text snippet
        is one list entry.
    batch_size (int): the batch size to run texts through the model. Defaults to 16.
    add_start_token (bool): whether to add the start token to the texts,
        so the perplexity can include the probability of the first word. Defaults to True.
    device (str): device to run on, defaults to \'cuda\' when available
Returns:
    perplexity: dictionary containing the perplexity scores for the texts
        in the input list, as well as the mean perplexity. If one of the input texts is
        longer than the max input length of the model, then it is truncated to the
        max length for the perplexity computation.
Examples:
    Example 1:
        >>> perplexity = datasets.load_metric("perplexity")
        >>> input_texts = ["lorem ipsum", "Happy Birthday!", "Bienvenue"]
        >>> results = perplexity.compute(model_id=\'gpt2\',
        ...                              add_start_token=False,
        ...                              input_texts=input_texts) # doctest:+ELLIPSIS
        >>> print(list(results.keys()))
        [\'perplexities\', \'mean_perplexity\']
        >>> print(round(results["mean_perplexity"], 2))
        78.22
        >>> print(round(results["perplexities"][0], 2))
        11.11

    Example 2:
        >>> perplexity = datasets.load_metric("perplexity")
        >>> input_texts = datasets.load_dataset("wikitext",
        ...                                     "wikitext-2-raw-v1",
        ...                                     split="test")["text"][:50] # doctest:+ELLIPSIS
        [...]
        >>> input_texts = [s for s in input_texts if s!=\'\']
        >>> results = perplexity.compute(model_id=\'gpt2\',
        ...                              input_texts=input_texts) # doctest:+ELLIPSIS
        >>> print(list(results.keys()))
        [\'perplexities\', \'mean_perplexity\']
        >>> print(round(results["mean_perplexity"], 2))
        60.35
        >>> print(round(results["perplexities"][0], 2))
        81.12
'''






@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION						,     _KWARGS_DESCRIPTION	)
class 					__SCREAMING_SNAKE_CASE						(	datasets.Metric	):







  '''simple docstring'''






  def _UpperCamelCase					(			self						):




       '''simple docstring'''

       return datasets.MetricInfo(
           description=_DESCRIPTION				,		citation=_CITATION				,		inputs_description=_KWARGS_DESCRIPTION				,		features=datasets.Features(
               {
                   'input_texts': datasets.Value('string'						),
               }						)				,		reference_urls=['https://huggingface.co/docs/transformers/perplexity']				,		)






  def _UpperCamelCase					(			self				,		snake_case_				,		snake_case_				,		snake_case_ = 1_6				,		snake_case_ = True				,		snake_case_=None						):




       '''simple docstring'''

       if device is not None:
            assert device in ["gpu", "cpu", "cuda"], "device should be either gpu or cpu."
            if device == "gpu":
                 UpperCAmelCase_							:       int       =				'cuda'
       else:
            UpperCAmelCase_							:       Union[str, Any]       =				'cuda' if torch.cuda.is_available() else 'cpu'

       UpperCAmelCase_							:       Tuple       =				AutoModelForCausalLM.from_pretrained(snake_case_						)
       UpperCAmelCase_							:       Dict       =				model.to(snake_case_						)

       UpperCAmelCase_							:       Dict       =				AutoTokenizer.from_pretrained(snake_case_						)

       # if batch_size > 1 (which generally leads to padding being required), and
       # if there is not an already assigned pad_token, assign an existing
       # special token to also be the padding token
       if tokenizer.pad_token is None and batch_size > 1:
            UpperCAmelCase_							:       Any       =				list(tokenizer.special_tokens_map_extended.values()						)
            # check that the model already has at least one special token defined
            assert (
                len(snake_case_						) > 0
            ), "If batch_size > 1, model must have at least one special token to use for padding. Please use a different model or set batch_size=1."
            # assign one of the special tokens to also be the pad token
            tokenizer.add_special_tokens({'pad_token': existing_special_tokens[0]}						)

       if add_start_token:
            # leave room for <BOS> token to be added:
            assert (
                tokenizer.bos_token is not None
            ), "Input model must already have a BOS token if using add_start_token=True. Please use a different model, or set add_start_token=False"
            UpperCAmelCase_							:       Union[str, Any]       =				model.config.max_length - 1
       else:
            UpperCAmelCase_							:       int       =				model.config.max_length

       UpperCAmelCase_							:       List[str]       =				tokenizer(
           snake_case_				,		add_special_tokens=snake_case_				,		padding=snake_case_				,		truncation=snake_case_				,		max_length=snake_case_				,		return_tensors='pt'				,		return_attention_mask=snake_case_				,		).to(snake_case_						)

       UpperCAmelCase_							:       Tuple       =				encodings['input_ids']
       UpperCAmelCase_							:       Optional[int]       =				encodings['attention_mask']

       # check that each input is long enough:
       if add_start_token:
            assert torch.all(torch.ge(attn_masks.sum(1						)				,		1						)						), "Each input text must be at least one token long."
       else:
            assert torch.all(
                torch.ge(attn_masks.sum(1						)				,		2						)						), "When add_start_token=False, each input text must be at least two tokens long. Run with add_start_token=True if inputting strings of only one token, and remove all empty input strings."

       UpperCAmelCase_							:       Union[str, Any]       =				[]
       UpperCAmelCase_							:       Optional[int]       =				CrossEntropyLoss(reduction='none'						)

       for start_index in logging.tqdm(range(0				,		len(snake_case_						)				,		snake_case_						)						):
            UpperCAmelCase_							:       Union[str, Any]       =				min(start_index + batch_size				,		len(snake_case_						)						)
            UpperCAmelCase_							:       List[Any]       =				encoded_texts[start_index:end_index]
            UpperCAmelCase_							:       Tuple       =				attn_masks[start_index:end_index]

            if add_start_token:
                 UpperCAmelCase_							:       List[str]       =				torch.tensor([[tokenizer.bos_token_id]] * encoded_batch.size(dim=0						)						).to(snake_case_						)
                 UpperCAmelCase_							:       Any       =				torch.cat([bos_tokens_tensor, encoded_batch]				,		dim=1						)
                 UpperCAmelCase_							:       List[Any]       =				torch.cat(
                     [torch.ones(bos_tokens_tensor.size()				,		dtype=torch.intaa						).to(snake_case_						), attn_mask]				,		dim=1						)

            UpperCAmelCase_							:       List[Any]       =				encoded_batch

            with torch.no_grad():
                 UpperCAmelCase_							:       int       =				model(snake_case_				,		attention_mask=snake_case_						).logits

            UpperCAmelCase_							:       Any       =				out_logits[..., :-1, :].contiguous()
            UpperCAmelCase_							:       Dict       =				labels[..., 1:].contiguous()
            UpperCAmelCase_							:       Union[str, Any]       =				attn_mask[..., 1:].contiguous()

            UpperCAmelCase_							:       List[Any]       =				torch.expa(
                (loss_fct(shift_logits.transpose(1				,		2						)				,		snake_case_						) * shift_attention_mask_batch).sum(1						)
                / shift_attention_mask_batch.sum(1						)						)

            ppls += perplexity_batch.tolist()

       return {"perplexities": ppls, "mean_perplexity": np.mean(snake_case_						)}






