


# Copyright 2022 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
from typing import List



def 			_lowerCAmelCase						(							lowerCAmelCase_							:List[str]		,						lowerCAmelCase_							:str							)->List[str]:
   '''simple docstring'''






   if name != "training_function" and name != "main":
      raise ValueError(F'''Incorrect function name passed: {name}, choose either \'main\' or \'training_function\''''							)
   snake_case_    ,    snake_case_					    =					[], False
   for line in lines:
      if not found_start and F'''def {name}''' in line:
         snake_case_					    =					True
         good_lines.append(lowerCAmelCase_							)
         continue
      if found_start:
         if name == "training_function" and "def main" in line:
            return good_lines
         if name == "main" and "if __name__" in line:
            return good_lines
         good_lines.append(lowerCAmelCase_							)



def 			_lowerCAmelCase						(							lowerCAmelCase_							:List[str]							)->Tuple:
   '''simple docstring'''






   return [line for line in lines if not line.lstrip().startswith("#"							) and line != "\n"]



def 			_lowerCAmelCase						(							lowerCAmelCase_							:str		,						lowerCAmelCase_							:str		,						lowerCAmelCase_							:bool		,						lowerCAmelCase_							:str = None							)->Optional[int]:
   '''simple docstring'''






   with open(lowerCAmelCase_		,						"r"							) as f:
      snake_case_					    =					f.readlines()
   with open(os.path.abspath(os.path.join("examples"		,						"nlp_example.py"							)							)		,						"r"							) as f:
      snake_case_					    =					f.readlines()
   with open(lowerCAmelCase_		,						"r"							) as f:
      snake_case_					    =					f.readlines()
   if secondary_filename is not None:
      with open(lowerCAmelCase_		,						"r"							) as f:
         snake_case_					    =					f.readlines()

    # This is our base, we remove all the code from here in our `full_filename` and `feature_filename` to find the new content
   if parser_only:
      snake_case_					    =					clean_lines(get_function_contents_by_name(lowerCAmelCase_		,						"main"							)							)
      snake_case_					    =					clean_lines(get_function_contents_by_name(lowerCAmelCase_		,						"main"							)							)
      snake_case_					    =					clean_lines(get_function_contents_by_name(lowerCAmelCase_		,						"main"							)							)
      if secondary_filename is not None:
         snake_case_					    =					clean_lines(get_function_contents_by_name(lowerCAmelCase_		,						"main"							)							)
   else:
      snake_case_					    =					clean_lines(get_function_contents_by_name(lowerCAmelCase_		,						"training_function"							)							)
      snake_case_					    =					clean_lines(get_function_contents_by_name(lowerCAmelCase_		,						"training_function"							)							)
      snake_case_					    =					clean_lines(get_function_contents_by_name(lowerCAmelCase_		,						"training_function"							)							)
      if secondary_filename is not None:
         snake_case_					    =					clean_lines(
             get_function_contents_by_name(lowerCAmelCase_		,						"training_function"							)							)

   snake_case_					    =					"train_dataloader, eval_dataloader = get_dataloaders(accelerator, batch_size)\n"

   # Specific code in our script that differs from the full version, aka what is new
   snake_case_					    =					[]
   snake_case_					    =					[]  # We keep track of the idxs just in case it's a repeated statement
   snake_case_					    =					iter(lowerCAmelCase_							)
   for i in range(len(lowerCAmelCase_							) - 1							):
      if i not in passed_idxs:
         snake_case_					    =					next(lowerCAmelCase_							)
         if (line not in full_file_func) and (line.lstrip() != _dl_line):
            if "TESTING_MOCKED_DATALOADERS" not in line:
               new_feature_code.append(lowerCAmelCase_							)
               passed_idxs.append(lowerCAmelCase_							)
            else:
               # Skip over the `config['num_epochs'] = 2` statement
               snake_case_					    =					next(lowerCAmelCase_							)

    # Extract out just the new parts from the full_file_training_func
   snake_case_					    =					[]
   snake_case_					    =					[]  # We keep track of the idxs just in case it's a repeated statement
   for i, line in enumerate(lowerCAmelCase_							):
      if i not in passed_idxs:
         if (line not in full_file_func) and (line.lstrip() != _dl_line):
            if "TESTING_MOCKED_DATALOADERS" not in line:
               new_full_example_parts.append(lowerCAmelCase_							)
               passed_idxs.append(lowerCAmelCase_							)

    # Finally, get the overall diff
   snake_case_					    =					[line for line in new_feature_code if line not in new_full_example_parts]
   if secondary_filename is not None:
      snake_case_					    =					[line for line in full_file_contents if line not in secondary_file_func]
      snake_case_					    =					[line for line in diff_from_example if line not in diff_from_two]

   return diff_from_example








import csv
import os

import pytest

from datasets import Dataset, DatasetDict, Features, NamedSplit, Value
from datasets.io.csv import CsvDatasetReader, CsvDatasetWriter

from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases



def 			_lowerCAmelCase						(							lowerCAmelCase_							:Optional[Any]		,						lowerCAmelCase_							:List[str]							)->Dict:
   '''simple docstring'''






   assert isinstance(lowerCAmelCase_		,						lowerCAmelCase_							)
   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 			_lowerCAmelCase						(							lowerCAmelCase_							:Dict		,						lowerCAmelCase_							:List[Any]		,						lowerCAmelCase_							:List[str]							)->int:
   '''simple docstring'''






   snake_case_					    =					tmp_path / "cache"
   snake_case_					    =					{"col_1": "int64", "col_2": "int64", "col_3": "float64"}
   with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase():
      snake_case_					    =					CsvDatasetReader(lowerCAmelCase_		,						cache_dir=lowerCAmelCase_		,						keep_in_memory=lowerCAmelCase_							).read()
   _check_csv_dataset(lowerCAmelCase_		,						lowerCAmelCase_							)



@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 			_lowerCAmelCase						(							lowerCAmelCase_							:List[str]		,						lowerCAmelCase_							:Optional[Any]		,						lowerCAmelCase_							:Optional[Any]							)->Optional[int]:
   '''simple docstring'''






   snake_case_					    =					tmp_path / "cache"
   # CSV file loses col_1 string dtype information: default now is "int64" instead of "string"
   snake_case_					    =					{"col_1": "int64", "col_2": "int64", "col_3": "float64"}
   snake_case_					    =					features.copy() if features else default_expected_features
   snake_case_					    =					(
       Features({feature: Value(lowerCAmelCase_							) for feature, dtype in features.items()}							) if features is not None else None
   )
   snake_case_					    =					CsvDatasetReader(lowerCAmelCase_		,						features=lowerCAmelCase_		,						cache_dir=lowerCAmelCase_							).read()
   _check_csv_dataset(lowerCAmelCase_		,						lowerCAmelCase_							)



@pytest.mark.parametrize("split"		,						[None, NamedSplit("train"							), "train", "test"]							)
def 			_lowerCAmelCase						(							lowerCAmelCase_							:Optional[int]		,						lowerCAmelCase_							:Tuple		,						lowerCAmelCase_							:List[Any]							)->Optional[int]:
   '''simple docstring'''






   snake_case_					    =					tmp_path / "cache"
   snake_case_					    =					{"col_1": "int64", "col_2": "int64", "col_3": "float64"}
   snake_case_					    =					CsvDatasetReader(lowerCAmelCase_		,						cache_dir=lowerCAmelCase_		,						split=lowerCAmelCase_							).read()
   _check_csv_dataset(lowerCAmelCase_		,						lowerCAmelCase_							)
   assert dataset.split == split if split else "train"



@pytest.mark.parametrize("path_type"		,						[str, list]							)
def 			_lowerCAmelCase						(							lowerCAmelCase_							:Any		,						lowerCAmelCase_							:Dict		,						lowerCAmelCase_							:List[Any]							)->List[Any]:
   '''simple docstring'''






   if issubclass(lowerCAmelCase_		,						lowerCAmelCase_							):
      snake_case_					    =					csv_path
   elif issubclass(lowerCAmelCase_		,						lowerCAmelCase_							):
      snake_case_					    =					[csv_path]
   snake_case_					    =					tmp_path / "cache"
   snake_case_					    =					{"col_1": "int64", "col_2": "int64", "col_3": "float64"}
   snake_case_					    =					CsvDatasetReader(lowerCAmelCase_		,						cache_dir=lowerCAmelCase_							).read()
   _check_csv_dataset(lowerCAmelCase_		,						lowerCAmelCase_							)



def 			_lowerCAmelCase						(							lowerCAmelCase_							:List[str]		,						lowerCAmelCase_							:Dict		,						lowerCAmelCase_							:List[str]=("train",)							)->Optional[Any]:
   '''simple docstring'''






   assert isinstance(lowerCAmelCase_		,						lowerCAmelCase_							)
   for split in splits:
      snake_case_					    =					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 			_lowerCAmelCase						(							lowerCAmelCase_							:Union[str, Any]		,						lowerCAmelCase_							:Dict		,						lowerCAmelCase_							:List[Any]							)->Any:
   '''simple docstring'''






   snake_case_					    =					tmp_path / "cache"
   snake_case_					    =					{"col_1": "int64", "col_2": "int64", "col_3": "float64"}
   with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase():
      snake_case_					    =					CsvDatasetReader({"train": csv_path}		,						cache_dir=lowerCAmelCase_		,						keep_in_memory=lowerCAmelCase_							).read()
   _check_csv_datasetdict(lowerCAmelCase_		,						lowerCAmelCase_							)



@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 			_lowerCAmelCase						(							lowerCAmelCase_							:List[Any]		,						lowerCAmelCase_							:Optional[Any]		,						lowerCAmelCase_							:Any							)->str:
   '''simple docstring'''






   snake_case_					    =					tmp_path / "cache"
   # CSV file loses col_1 string dtype information: default now is "int64" instead of "string"
   snake_case_					    =					{"col_1": "int64", "col_2": "int64", "col_3": "float64"}
   snake_case_					    =					features.copy() if features else default_expected_features
   snake_case_					    =					(
       Features({feature: Value(lowerCAmelCase_							) for feature, dtype in features.items()}							) if features is not None else None
   )
   snake_case_					    =					CsvDatasetReader({"train": csv_path}		,						features=lowerCAmelCase_		,						cache_dir=lowerCAmelCase_							).read()
   _check_csv_datasetdict(lowerCAmelCase_		,						lowerCAmelCase_							)



@pytest.mark.parametrize("split"		,						[None, NamedSplit("train"							), "train", "test"]							)
def 			_lowerCAmelCase						(							lowerCAmelCase_							:str		,						lowerCAmelCase_							:Tuple		,						lowerCAmelCase_							:Any							)->str:
   '''simple docstring'''






   if split:
      snake_case_					    =					{split: csv_path}
   else:
      snake_case_					    =					{"train": csv_path, "test": csv_path}
   snake_case_					    =					tmp_path / "cache"
   snake_case_					    =					{"col_1": "int64", "col_2": "int64", "col_3": "float64"}
   snake_case_					    =					CsvDatasetReader(lowerCAmelCase_		,						cache_dir=lowerCAmelCase_							).read()
   _check_csv_datasetdict(lowerCAmelCase_		,						lowerCAmelCase_		,						splits=list(path.keys()							)							)
   assert all(dataset[split].split == split for split in path.keys()							)



def 			_lowerCAmelCase						(							lowerCAmelCase_							:Tuple							)->str:
   '''simple docstring'''






   with open(lowerCAmelCase_		,						encoding="utf-8"							) as csvfile:
      yield from csv.reader(lowerCAmelCase_							)



def 			_lowerCAmelCase						(							lowerCAmelCase_							:Tuple		,						lowerCAmelCase_							:Dict							)->Any:
   '''simple docstring'''






   snake_case_					    =					tmp_path / "cache"
   snake_case_					    =					os.path.join(lowerCAmelCase_		,						"tmp.csv"							)
   snake_case_					    =					CsvDatasetReader({"train": csv_path}		,						cache_dir=lowerCAmelCase_							).read()
   CsvDatasetWriter(dataset["train"]		,						lowerCAmelCase_		,						num_proc=1							).write()

   snake_case_					    =					iter_csv_file(lowerCAmelCase_							)
   snake_case_					    =					iter_csv_file(lowerCAmelCase_							)

   for rowa, rowa in zip(lowerCAmelCase_		,						lowerCAmelCase_							):
      assert rowa == rowa



def 			_lowerCAmelCase						(							lowerCAmelCase_							:str		,						lowerCAmelCase_							:Any							)->Union[str, Any]:
   '''simple docstring'''






   snake_case_					    =					tmp_path / "cache"
   snake_case_					    =					os.path.join(lowerCAmelCase_		,						"tmp.csv"							)
   snake_case_					    =					CsvDatasetReader({"train": csv_path}		,						cache_dir=lowerCAmelCase_							).read()
   CsvDatasetWriter(dataset["train"]		,						lowerCAmelCase_		,						num_proc=2							).write()

   snake_case_					    =					iter_csv_file(lowerCAmelCase_							)
   snake_case_					    =					iter_csv_file(lowerCAmelCase_							)

   for rowa, rowa in zip(lowerCAmelCase_		,						lowerCAmelCase_							):
      assert rowa == rowa



def 			_lowerCAmelCase						(							lowerCAmelCase_							:Any		,						lowerCAmelCase_							:Optional[int]							)->int:
   '''simple docstring'''






   snake_case_					    =					tmp_path / "cache"
   snake_case_					    =					os.path.join(lowerCAmelCase_		,						"tmp.csv"							)
   snake_case_					    =					CsvDatasetReader({"train": csv_path}		,						cache_dir=lowerCAmelCase_							).read()
   with pytest.raises(lowerCAmelCase_							):
      CsvDatasetWriter(dataset["train"]		,						lowerCAmelCase_		,						num_proc=0							)




