



'''simple docstring'''



from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_sentencepiece_available,
    is_tokenizers_available,
    is_torch_available,
)


lowerCAmelCase_  :							Optional[int]             =    {
    'configuration_llama': ['LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP', 'LlamaConfig'],
}

try:
							if not is_sentencepiece_available():
														raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
							pass
else:
							lowerCAmelCase_  :							Union[str, Any]             =    ['LlamaTokenizer']

try:
							if not is_tokenizers_available():
														raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
							pass
else:
							lowerCAmelCase_  :							Optional[int]             =    ['LlamaTokenizerFast']

try:
							if not is_torch_available():
														raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
							pass
else:
							lowerCAmelCase_  :							str             =    [
							    'LlamaForCausalLM',
							    'LlamaModel',
							    'LlamaPreTrainedModel',
							    'LlamaForSequenceClassification',
							]


if TYPE_CHECKING:
							from .configuration_llama import LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP, LlamaConfig

							try:
														if not is_sentencepiece_available():
																					raise OptionalDependencyNotAvailable()
							except OptionalDependencyNotAvailable:
														pass
							else:
														from .tokenization_llama import LlamaTokenizer

							try:
														if not is_tokenizers_available():
																					raise OptionalDependencyNotAvailable()
							except OptionalDependencyNotAvailable:
														pass
							else:
														from .tokenization_llama_fast import LlamaTokenizerFast

							try:
														if not is_torch_available():
																					raise OptionalDependencyNotAvailable()
							except OptionalDependencyNotAvailable:
														pass
							else:
														from .modeling_llama import LlamaForCausalLM, LlamaForSequenceClassification, LlamaModel, LlamaPreTrainedModel


else:
							import sys

							lowerCAmelCase_  :							Union[str, Any]             =    _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)







"""simple docstring"""

import io
import json

import fsspec
import pytest

from datasets import Dataset, DatasetDict, Features, NamedSplit, Value
from datasets.io.json import JsonDatasetReader, JsonDatasetWriter

from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases



def       SCREAMING_SNAKE_CASE							( lowercase__					,					lowercase__   )			->						Optional[Any]:
 assert isinstance(lowercase__					,					lowercase__   )
 assert dataset.num_rows == 4
 assert dataset.num_columns == 3
 assert dataset.column_names == ["col_1", "col_2", "col_3"]
 for feature, expected_dtype in expected_features.items():
  assert dataset.features[feature].dtype == expected_dtype



@pytest.mark.parametrize("keep_in_memory"					,					[False, True]   )
def       SCREAMING_SNAKE_CASE							( lowercase__					,					lowercase__					,					lowercase__   )			->						Any:
 lowerCAmelCase__   :				Optional[int] 			=				tmp_path / "cache"
 lowerCAmelCase__   :				Dict 			=				{"col_1": "string", "col_2": "int64", "col_3": "float64"}
 with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase():
  lowerCAmelCase__   :				Tuple 			=				JsonDatasetReader(lowercase__					,					cache_dir=lowercase__					,					keep_in_memory=lowercase__   ).read()
 _check_json_dataset(lowercase__					,					lowercase__   )



@pytest.mark.parametrize(
    "features"					,					[
        None,
        {"col_1": "string", "col_2": "int64", "col_3": "float64"},
        {"col_1": "string", "col_2": "string", "col_3": "string"},
        {"col_1": "int32", "col_2": "int32", "col_3": "int32"},
        {"col_1": "float32", "col_2": "float32", "col_3": "float32"},
    ]					,					)
def       SCREAMING_SNAKE_CASE							( lowercase__					,					lowercase__					,					lowercase__   )			->						Tuple:
 lowerCAmelCase__   :				Union[str, Any] 			=				tmp_path / "cache"
 lowerCAmelCase__   :				Tuple 			=				{"col_1": "string", "col_2": "int64", "col_3": "float64"}
 lowerCAmelCase__   :				List[Any] 			=				features.copy() if features else default_expected_features
 lowerCAmelCase__   :				int 			=				(
     Features({feature: Value(lowercase__   ) for feature, dtype in features.items()}   ) if features is not None else None
 )
 lowerCAmelCase__   :				Tuple 			=				JsonDatasetReader(lowercase__					,					features=lowercase__					,					cache_dir=lowercase__   ).read()
 _check_json_dataset(lowercase__					,					lowercase__   )



@pytest.mark.parametrize(
    "features"					,					[
        None,
        {"col_3": "float64", "col_1": "string", "col_2": "int64"},
    ]					,					)
def       SCREAMING_SNAKE_CASE							( lowercase__					,					lowercase__					,					lowercase__   )			->						Optional[Any]:
 lowerCAmelCase__   :				Tuple 			=				tmp_path / "cache"
 lowerCAmelCase__   :				Optional[Any] 			=				{"col_3": "float64", "col_1": "string", "col_2": "int64"}
 lowerCAmelCase__   :				List[str] 			=				features.copy() if features else default_expected_features
 lowerCAmelCase__   :				Dict 			=				(
     Features({feature: Value(lowercase__   ) for feature, dtype in features.items()}   ) if features is not None else None
 )
 lowerCAmelCase__   :				Dict 			=				JsonDatasetReader(lowercase__					,					features=lowercase__					,					cache_dir=lowercase__   ).read()
 assert isinstance(lowercase__					,					lowercase__   )
 assert dataset.num_rows == 2
 assert dataset.num_columns == 3
 assert dataset.column_names == ["col_3", "col_1", "col_2"]
 for feature, expected_dtype in expected_features.items():
  assert dataset.features[feature].dtype == expected_dtype



def       SCREAMING_SNAKE_CASE							( lowercase__					,					lowercase__   )			->						Tuple:
 # jsonl_312_path features are {"col_3": "float64", "col_1": "string", "col_2": "int64"}
 lowerCAmelCase__   :				Any 			=				{"col_2": "int64", "col_3": "float64", "col_1": "string"}
 lowerCAmelCase__   :				Union[str, Any] 			=				features.copy()
 lowerCAmelCase__   :				int 			=				(
     Features({feature: Value(lowercase__   ) for feature, dtype in features.items()}   ) if features is not None else None
 )
 lowerCAmelCase__   :				str 			=				tmp_path / "cache"
 lowerCAmelCase__   :				List[str] 			=				JsonDatasetReader(lowercase__					,					features=lowercase__					,					cache_dir=lowercase__   ).read()
 assert isinstance(lowercase__					,					lowercase__   )
 assert dataset.num_rows == 2
 assert dataset.num_columns == 3
 assert dataset.column_names == ["col_2", "col_3", "col_1"]
 for feature, expected_dtype in expected_features.items():
  assert dataset.features[feature].dtype == expected_dtype



@pytest.mark.parametrize("split"					,					[None, NamedSplit("train"   ), "train", "test"]   )
def       SCREAMING_SNAKE_CASE							( lowercase__					,					lowercase__					,					lowercase__   )			->						Optional[Any]:
 lowerCAmelCase__   :				Optional[int] 			=				tmp_path / "cache"
 lowerCAmelCase__   :				List[Any] 			=				{"col_1": "string", "col_2": "int64", "col_3": "float64"}
 lowerCAmelCase__   :				Dict 			=				JsonDatasetReader(lowercase__					,					cache_dir=lowercase__					,					split=lowercase__   ).read()
 _check_json_dataset(lowercase__					,					lowercase__   )
 assert dataset.split == split if split else "train"



@pytest.mark.parametrize("path_type"					,					[str, list]   )
def       SCREAMING_SNAKE_CASE							( lowercase__					,					lowercase__					,					lowercase__   )			->						Optional[Any]:
 if issubclass(lowercase__					,					lowercase__   ):
  lowerCAmelCase__   :				Dict 			=				jsonl_path
 elif issubclass(lowercase__					,					lowercase__   ):
  lowerCAmelCase__   :				Tuple 			=				[jsonl_path]
 lowerCAmelCase__   :				Any 			=				tmp_path / "cache"
 lowerCAmelCase__   :				List[str] 			=				{"col_1": "string", "col_2": "int64", "col_3": "float64"}
 lowerCAmelCase__   :				int 			=				JsonDatasetReader(lowercase__					,					cache_dir=lowercase__   ).read()
 _check_json_dataset(lowercase__					,					lowercase__   )



def       SCREAMING_SNAKE_CASE							( lowercase__					,					lowercase__					,					lowercase__=("train",)   )			->						List[str]:
 assert isinstance(lowercase__					,					lowercase__   )
 for split in splits:
  lowerCAmelCase__   :				Dict 			=				dataset_dict[split]
  assert dataset.num_rows == 4
  assert dataset.num_columns == 3
  assert dataset.column_names == ["col_1", "col_2", "col_3"]
  for feature, expected_dtype in expected_features.items():
   assert dataset.features[feature].dtype == expected_dtype



@pytest.mark.parametrize("keep_in_memory"					,					[False, True]   )
def       SCREAMING_SNAKE_CASE							( lowercase__					,					lowercase__					,					lowercase__   )			->						List[str]:
 lowerCAmelCase__   :				int 			=				tmp_path / "cache"
 lowerCAmelCase__   :				str 			=				{"col_1": "string", "col_2": "int64", "col_3": "float64"}
 with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase():
  lowerCAmelCase__   :				Dict 			=				JsonDatasetReader({"train": jsonl_path}					,					cache_dir=lowercase__					,					keep_in_memory=lowercase__   ).read()
 _check_json_datasetdict(lowercase__					,					lowercase__   )



@pytest.mark.parametrize(
    "features"					,					[
        None,
        {"col_1": "string", "col_2": "int64", "col_3": "float64"},
        {"col_1": "string", "col_2": "string", "col_3": "string"},
        {"col_1": "int32", "col_2": "int32", "col_3": "int32"},
        {"col_1": "float32", "col_2": "float32", "col_3": "float32"},
    ]					,					)
def       SCREAMING_SNAKE_CASE							( lowercase__					,					lowercase__					,					lowercase__   )			->						List[str]:
 lowerCAmelCase__   :				str 			=				tmp_path / "cache"
 lowerCAmelCase__   :				Union[str, Any] 			=				{"col_1": "string", "col_2": "int64", "col_3": "float64"}
 lowerCAmelCase__   :				str 			=				features.copy() if features else default_expected_features
 lowerCAmelCase__   :				Dict 			=				(
     Features({feature: Value(lowercase__   ) for feature, dtype in features.items()}   ) if features is not None else None
 )
 lowerCAmelCase__   :				List[Any] 			=				JsonDatasetReader({"train": jsonl_path}					,					features=lowercase__					,					cache_dir=lowercase__   ).read()
 _check_json_datasetdict(lowercase__					,					lowercase__   )



@pytest.mark.parametrize("split"					,					[None, NamedSplit("train"   ), "train", "test"]   )
def       SCREAMING_SNAKE_CASE							( lowercase__					,					lowercase__					,					lowercase__   )			->						Dict:
 if split:
  lowerCAmelCase__   :				int 			=				{split: jsonl_path}
 else:
  lowerCAmelCase__   :				str 			=				"train"
  lowerCAmelCase__   :				Tuple 			=				{"train": jsonl_path, "test": jsonl_path}
 lowerCAmelCase__   :				Any 			=				tmp_path / "cache"
 lowerCAmelCase__   :				Dict 			=				{"col_1": "string", "col_2": "int64", "col_3": "float64"}
 lowerCAmelCase__   :				int 			=				JsonDatasetReader(lowercase__					,					cache_dir=lowercase__   ).read()
 _check_json_datasetdict(lowercase__					,					lowercase__					,					splits=list(path.keys()   )   )
 assert all(dataset[split].split == split for split in path.keys()   )



def       SCREAMING_SNAKE_CASE							( lowercase__   )			->						List[Any]:
 return json.load(lowercase__   )



def       SCREAMING_SNAKE_CASE							( lowercase__   )			->						Optional[int]:
 return [json.loads(lowercase__   ) for line in buffer]






class 			__a					:





       """simple docstring"""


       @pytest.mark.parametrize("lines, load_json_function"			,					[(True, load_json_lines), (False, load_json)]   )
       def 			SCREAMING_SNAKE_CASE_	(   self			,					snake_case			,					snake_case			,					snake_case   ):





        """simple docstring"""

        with io.BytesIO() as buffer:
         JsonDatasetWriter(snake_case			,					snake_case			,					lines=snake_case   ).write()
         buffer.seek(0   )
         lowerCAmelCase__   :				int 			=				load_json_function(snake_case   )
        assert isinstance(snake_case			,					snake_case   )
        assert isinstance(exported_content[0]			,					snake_case   )
        assert len(snake_case   ) == 10






       @pytest.mark.parametrize(
           "orient, container, keys, len_at"			,					[
               ("records", list, {"tokens", "labels", "answers", "id"}, None),
               ("split", dict, {"columns", "data"}, "data"),
               ("index", dict, set("0123456789"   ), None),
               ("columns", dict, {"tokens", "labels", "answers", "id"}, "tokens"),
               ("values", list, None, None),
               ("table", dict, {"schema", "data"}, "data"),
           ]			,					)
       def 			SCREAMING_SNAKE_CASE_	(   self			,					snake_case			,					snake_case			,					snake_case			,					snake_case			,					snake_case   ):





        """simple docstring"""

        with io.BytesIO() as buffer:
         JsonDatasetWriter(snake_case			,					snake_case			,					lines=snake_case			,					orient=snake_case   ).write()
         buffer.seek(0   )
         lowerCAmelCase__   :				Optional[Any] 			=				load_json(snake_case   )
        assert isinstance(snake_case			,					snake_case   )
        if keys:
         if container is dict:
          assert exported_content.keys() == keys
         else:
          assert exported_content[0].keys() == keys
        else:
         assert not hasattr(snake_case			,					"keys"   ) and not hasattr(exported_content[0]			,					"keys"   )
        if len_at:
         assert len(exported_content[len_at]   ) == 10
        else:
         assert len(snake_case   ) == 10






       @pytest.mark.parametrize("lines, load_json_function"			,					[(True, load_json_lines), (False, load_json)]   )
       def 			SCREAMING_SNAKE_CASE_	(   self			,					snake_case			,					snake_case			,					snake_case   ):





        """simple docstring"""

        with io.BytesIO() as buffer:
         JsonDatasetWriter(snake_case			,					snake_case			,					lines=snake_case			,					num_proc=2   ).write()
         buffer.seek(0   )
         lowerCAmelCase__   :				int 			=				load_json_function(snake_case   )
        assert isinstance(snake_case			,					snake_case   )
        assert isinstance(exported_content[0]			,					snake_case   )
        assert len(snake_case   ) == 10






       @pytest.mark.parametrize(
           "orient, container, keys, len_at"			,					[
               ("records", list, {"tokens", "labels", "answers", "id"}, None),
               ("split", dict, {"columns", "data"}, "data"),
               ("index", dict, set("0123456789"   ), None),
               ("columns", dict, {"tokens", "labels", "answers", "id"}, "tokens"),
               ("values", list, None, None),
               ("table", dict, {"schema", "data"}, "data"),
           ]			,					)
       def 			SCREAMING_SNAKE_CASE_	(   self			,					snake_case			,					snake_case			,					snake_case			,					snake_case			,					snake_case   ):





        """simple docstring"""

        with io.BytesIO() as buffer:
         JsonDatasetWriter(snake_case			,					snake_case			,					lines=snake_case			,					orient=snake_case			,					num_proc=2   ).write()
         buffer.seek(0   )
         lowerCAmelCase__   :				Tuple 			=				load_json(snake_case   )
        assert isinstance(snake_case			,					snake_case   )
        if keys:
         if container is dict:
          assert exported_content.keys() == keys
         else:
          assert exported_content[0].keys() == keys
        else:
         assert not hasattr(snake_case			,					"keys"   ) and not hasattr(exported_content[0]			,					"keys"   )
        if len_at:
         assert len(exported_content[len_at]   ) == 10
        else:
         assert len(snake_case   ) == 10






       def 			SCREAMING_SNAKE_CASE_	(   self			,					snake_case   ):





        """simple docstring"""

        with pytest.raises(snake_case   ):
         with io.BytesIO() as buffer:
          JsonDatasetWriter(snake_case			,					snake_case			,					num_proc=0   )






       @pytest.mark.parametrize("compression, extension"			,					[("gzip", "gz"), ("bz2", "bz2"), ("xz", "xz")]   )
       def 			SCREAMING_SNAKE_CASE_	(   self			,					snake_case			,					snake_case			,					snake_case			,					snake_case			,					snake_case   ):





        """simple docstring"""

        lowerCAmelCase__   :				Any 			=				tmp_path_factory.mktemp("data"   ) / F"""test.json.{extension}"""
        lowerCAmelCase__   :				str 			=				str(shared_datadir / F"""test_file.json.{extension}"""   )
        JsonDatasetWriter(snake_case			,					snake_case			,					compression=snake_case   ).write()

        with fsspec.open(snake_case			,					"rb"			,					compression="infer"   ) as f:
         lowerCAmelCase__   :				Optional[int] 			=				f.read()
        with fsspec.open(snake_case			,					"rb"			,					compression="infer"   ) as f:
         lowerCAmelCase__   :				Optional[int] 			=				f.read()
        assert exported_content == original_content






