



'''simple docstring'''






import json
import os
from pathlib import Path

import pytest

from datasets.download.download_config import DownloadConfig
from datasets.download.download_manager import DownloadManager
from datasets.utils.file_utils import hash_url_to_filename


UpperCamelCase__:   Union[str, Any]								=			"http://www.mocksite.com/file1.txt"
UpperCamelCase__:   Tuple								=			"\"text\": [\"foo\", \"foo\"]"
UpperCamelCase__:   Dict								=			"6d8ce9aa78a471c7477201efbeabd3bb01ac2e7d100a6dc024ba1608361f90a8"

class 				SCREAMING_SNAKE_CASE:







	"""simple docstring"""






	lowerCamelCase__			 =       200
	lowerCamelCase__			 =       {"""Content-Length""": """100"""}
	lowerCamelCase__			 =       {}







	def      A	(						self			:     Tuple		,			**__snake_case			:     Dict		)			->		List[Any]:
								return [bytes(__snake_case		,			'''utf-8'''		)]


def  snake_case_     (					*_lowerCAmelCase  :						Optional[Any]   ,      **_lowerCAmelCase  :						str  )      ->   List[str]:
							return MockResponse()


@pytest.mark.parametrize('''urls_type'''   ,      [str, list, dict]  )
def  snake_case_     (					_lowerCAmelCase  :						str   ,      _lowerCAmelCase  :						Any   ,      _lowerCAmelCase  :						Dict  )      ->   str:
							import requests

							monkeypatch.setattr(_lowerCAmelCase   ,      '''request'''   ,      _lowerCAmelCase  )

							UpperCAmelCase :       Optional[Any] 							=		URL
							if issubclass(_lowerCAmelCase   ,      _lowerCAmelCase  ):
														UpperCAmelCase :       List[Any] 							=		url
							elif issubclass(_lowerCAmelCase   ,      _lowerCAmelCase  ):
														UpperCAmelCase :       int 							=		[url]
							elif issubclass(_lowerCAmelCase   ,      _lowerCAmelCase  ):
														UpperCAmelCase :       str 							=		{'''train''': url}
							UpperCAmelCase :       Dict 							=		'''dummy'''
							UpperCAmelCase :       Optional[int] 							=		'''downloads'''
							UpperCAmelCase :       List[str] 							=		tmp_path
							UpperCAmelCase :       Optional[Any] 							=		DownloadConfig(
							    cache_dir=os.path.join(_lowerCAmelCase   ,      _lowerCAmelCase  )   ,      use_etag=_lowerCAmelCase   ,      )
							UpperCAmelCase :       Tuple 							=		DownloadManager(dataset_name=_lowerCAmelCase   ,      download_config=_lowerCAmelCase  )
							UpperCAmelCase :       Any 							=		dl_manager.download(_lowerCAmelCase  )
							UpperCAmelCase :       Any 							=		urls
							for downloaded_paths in [downloaded_paths]:
														if isinstance(_lowerCAmelCase   ,      _lowerCAmelCase  ):
																					UpperCAmelCase :       Optional[Any] 							=		[downloaded_paths]
																					UpperCAmelCase :       Any 							=		[urls]
														elif isinstance(_lowerCAmelCase   ,      _lowerCAmelCase  ):
																					assert "train" in downloaded_paths.keys()
																					UpperCAmelCase :       Any 							=		downloaded_paths.values()
																					UpperCAmelCase :       Tuple 							=		urls.values()
														assert downloaded_paths
														for downloaded_path, input_url in zip(_lowerCAmelCase   ,      _lowerCAmelCase  ):
																					assert downloaded_path == dl_manager.downloaded_paths[input_url]
																					UpperCAmelCase :       List[str] 							=		Path(_lowerCAmelCase  )
																					UpperCAmelCase :       List[Any] 							=		downloaded_path.parts
																					assert parts[-1] == HASH
																					assert parts[-2] == cache_subdir
																					assert downloaded_path.exists()
																					UpperCAmelCase :       List[Any] 							=		downloaded_path.read_text()
																					assert content == CONTENT
																					UpperCAmelCase :       Union[str, Any] 							=		downloaded_path.with_suffix('''.json'''  )
																					assert metadata_downloaded_path.exists()
																					UpperCAmelCase :       Any 							=		json.loads(metadata_downloaded_path.read_text()  )
																					assert metadata_content == {"url": URL, "etag": None}


@pytest.mark.parametrize('''paths_type'''   ,      [str, list, dict]  )
def  snake_case_     (					_lowerCAmelCase  :						List[str]   ,      _lowerCAmelCase  :						Union[str, Any]   ,      _lowerCAmelCase  :						List[Any]  )      ->   int:
							UpperCAmelCase :       Optional[int] 							=		str(_lowerCAmelCase  )
							if issubclass(_lowerCAmelCase   ,      _lowerCAmelCase  ):
														UpperCAmelCase :       Union[str, Any] 							=		filename
							elif issubclass(_lowerCAmelCase   ,      _lowerCAmelCase  ):
														UpperCAmelCase :       int 							=		[filename]
							elif issubclass(_lowerCAmelCase   ,      _lowerCAmelCase  ):
														UpperCAmelCase :       Union[str, Any] 							=		{'''train''': filename}
							UpperCAmelCase :       Optional[int] 							=		'''dummy'''
							UpperCAmelCase :       Union[str, Any] 							=		xz_file.parent
							UpperCAmelCase :       Tuple 							=		'''extracted'''
							UpperCAmelCase :       List[Any] 							=		DownloadConfig(
							    cache_dir=_lowerCAmelCase   ,      use_etag=_lowerCAmelCase   ,      )
							UpperCAmelCase :       Optional[Any] 							=		DownloadManager(dataset_name=_lowerCAmelCase   ,      download_config=_lowerCAmelCase  )
							UpperCAmelCase :       List[Any] 							=		dl_manager.extract(_lowerCAmelCase  )
							UpperCAmelCase :       Union[str, Any] 							=		paths
							for extracted_paths in [extracted_paths]:
														if isinstance(_lowerCAmelCase   ,      _lowerCAmelCase  ):
																					UpperCAmelCase :       int 							=		[extracted_paths]
																					UpperCAmelCase :       int 							=		[paths]
														elif isinstance(_lowerCAmelCase   ,      _lowerCAmelCase  ):
																					assert "train" in extracted_paths.keys()
																					UpperCAmelCase :       Any 							=		extracted_paths.values()
																					UpperCAmelCase :       Tuple 							=		paths.values()
														assert extracted_paths
														for extracted_path, input_path in zip(_lowerCAmelCase   ,      _lowerCAmelCase  ):
																					assert extracted_path == dl_manager.extracted_paths[input_path]
																					UpperCAmelCase :       Union[str, Any] 							=		Path(_lowerCAmelCase  )
																					UpperCAmelCase :       List[Any] 							=		extracted_path.parts
																					assert parts[-1] == hash_url_to_filename(_lowerCAmelCase   ,      etag=_lowerCAmelCase  )
																					assert parts[-2] == extracted_subdir
																					assert extracted_path.exists()
																					UpperCAmelCase :       Union[str, Any] 							=		extracted_path.read_text()
																					UpperCAmelCase :       List[str] 							=		text_file.read_text()
																					assert extracted_file_content == expected_file_content


def  snake_case_     (					_lowerCAmelCase  :						Union[str, Any]   ,      _lowerCAmelCase  :						List[Any]  )      ->   str:
							assert path.endswith('''.jsonl'''  )
							for num_items, line in enumerate(_lowerCAmelCase   ,      start=1  ):
														UpperCAmelCase :       str 							=		json.loads(line.decode('''utf-8'''  )  )
														assert item.keys() == {"col_1", "col_2", "col_3"}
							assert num_items == 4


@pytest.mark.parametrize('''archive_jsonl'''   ,      ['''tar_jsonl_path''', '''zip_jsonl_path''']  )
def  snake_case_     (					_lowerCAmelCase  :						Union[str, Any]   ,      _lowerCAmelCase  :						str  )      ->   Optional[int]:
							UpperCAmelCase :       Optional[Any] 							=		request.getfixturevalue(_lowerCAmelCase  )
							UpperCAmelCase :       Any 							=		DownloadManager()
							for num_jsonl, (path, file) in enumerate(dl_manager.iter_archive(_lowerCAmelCase  )   ,      start=1  ):
														_test_jsonl(_lowerCAmelCase   ,      _lowerCAmelCase  )
							assert num_jsonl == 2


@pytest.mark.parametrize('''archive_nested_jsonl'''   ,      ['''tar_nested_jsonl_path''', '''zip_nested_jsonl_path''']  )
def  snake_case_     (					_lowerCAmelCase  :						Any   ,      _lowerCAmelCase  :						Union[str, Any]  )      ->   Tuple:
							UpperCAmelCase :       int 							=		request.getfixturevalue(_lowerCAmelCase  )
							UpperCAmelCase :       str 							=		DownloadManager()
							for num_tar, (path, file) in enumerate(dl_manager.iter_archive(_lowerCAmelCase  )   ,      start=1  ):
														for num_jsonl, (subpath, subfile) in enumerate(dl_manager.iter_archive(_lowerCAmelCase  )   ,      start=1  ):
																					_test_jsonl(_lowerCAmelCase   ,      _lowerCAmelCase  )
							assert num_tar == 1
							assert num_jsonl == 2




def  snake_case_     (					_lowerCAmelCase  :						List[Any]  )      ->   Union[str, Any]:
							UpperCAmelCase :       Optional[Any] 							=		DownloadManager()
							for num_file, file in enumerate(dl_manager.iter_files(_lowerCAmelCase  )   ,      start=1  ):
														assert os.path.basename(_lowerCAmelCase  ) == ("test.txt" if num_file == 1 else "train.txt")
							assert num_file == 2













"""simple docstring"""



# Lint as: python3
import sys
from collections.abc import Mapping
from typing import TYPE_CHECKING

import numpy as np
import pyarrow as pa

from .. import config
from ..utils.py_utils import map_nested
from .formatting import TensorFormatter


if TYPE_CHECKING:
						import torch





class 					_UpperCAmelCase       ( TensorFormatter[Mapping, "torch.Tensor", Mapping]							):




					def __init__(				self     :						Any    ,						A     :						int=None    ,						**A     :						str   )  ->  Union[str, Any]:
							super().__init__(features=A   )
							lowercase_ : Union[str, Any]							       =   torch_tensor_kwargs
							import torch  # noqa import torch at initialization




					def   A  (				self     :						Dict    ,						A     :						int   )  ->  List[Any]:
							import torch

							if isinstance(A    ,						A   ) and column:
									if all(
									    isinstance(A    ,						torch.Tensor   ) and x.shape == column[0].shape and x.dtype == column[0].dtype
									    for x in column   ):
											return torch.stack(A   )
							return column




					def   A  (				self     :						int    ,						A     :						Any   )  ->  Optional[Any]:
							import torch

							if isinstance(A    ,						(str, bytes, type(A   ))   ):
									return value
							elif isinstance(A    ,						(np.character, np.ndarray)   ) and np.issubdtype(value.dtype    ,						np.character   ):
									return value.tolist()

							lowercase_ : Any							       =   {}

							if isinstance(A    ,						(np.number, np.ndarray)   ) and np.issubdtype(value.dtype    ,						np.integer   ):
									lowercase_ : Any							       =   {'''dtype''': torch.intaa}
							elif isinstance(A    ,						(np.number, np.ndarray)   ) and np.issubdtype(value.dtype    ,						np.floating   ):
									lowercase_ : Dict							       =   {'''dtype''': torch.floataa}
							elif config.PIL_AVAILABLE and "PIL" in sys.modules:
									import PIL.Image

									if isinstance(A    ,						PIL.Image.Image   ):
											lowercase_ : Dict							       =   np.asarray(A   )
							return torch.tensor(A    ,						**{**default_dtype, **self.torch_tensor_kwargs}   )




					def   A  (				self     :						Union[str, Any]    ,						A     :						Optional[int]   )  ->  str:
							import torch

							# support for torch, tf, jax etc.
							if hasattr(A    ,						'''__array__'''   ) and not isinstance(A    ,						torch.Tensor   ):
									lowercase_ : Optional[int]							       =   data_struct.__array__()
							# support for nested types like struct of list of struct
							if isinstance(A    ,						np.ndarray   ):
									if data_struct.dtype == object:  # torch tensors cannot be instantied from an array of objects
											return self._consolidate([self.recursive_tensorize(A   ) for substruct in data_struct]   )
							elif isinstance(A    ,						(list, tuple)   ):
									return self._consolidate([self.recursive_tensorize(A   ) for substruct in data_struct]   )
							return self._tensorize(A   )




					def   A  (				self     :						Dict    ,						A     :						dict   )  ->  Tuple:
							return map_nested(self._recursive_tensorize    ,						A    ,						map_list=A   )




					def   A  (				self     :						str    ,						A     :						pa.Table   )  ->  Mapping:
							lowercase_ : Optional[Any]							       =   self.numpy_arrow_extractor().extract_row(A   )
							lowercase_ : str							       =   self.python_features_decoder.decode_row(A   )
							return self.recursive_tensorize(A   )




					def   A  (				self     :						List[Any]    ,						A     :						pa.Table   )  ->  "torch.Tensor":
							lowercase_ : List[str]							       =   self.numpy_arrow_extractor().extract_column(A   )
							lowercase_ : str							       =   self.python_features_decoder.decode_column(A    ,						pa_table.column_names[0]   )
							lowercase_ : Optional[int]							       =   self.recursive_tensorize(A   )
							lowercase_ : Any							       =   self._consolidate(A   )
							return column






					def   A  (				self     :						List[str]    ,						A     :						pa.Table   )  ->  Mapping:
							lowercase_ : Optional[int]							       =   self.numpy_arrow_extractor().extract_batch(A   )
							lowercase_ : int							       =   self.python_features_decoder.decode_batch(A   )
							lowercase_ : Dict							       =   self.recursive_tensorize(A   )
							for column_name in batch:
									lowercase_ : Optional[Any]							       =   self._consolidate(batch[column_name]   )
							return batch



