


"""simple docstring"""




import gzip
import hashlib
import json
import multiprocessing
import os
import re
import shutil
import time
from pathlib import Path

import numpy as np
from arguments import PreprocessingArguments
from datasets import load_dataset
from minhash_deduplication import deduplicate_dataset

from transformers import AutoTokenizer, HfArgumentParser


__magic_name__						: Tuple    =				re.compile(R'\s+')





def       a_ (	lowercase__ :int     ):
			return {"hash": hashlib.mda(re.sub(_UpperCamelCase,			"""""",			example["""content"""]     ).encode("""utf-8"""     )     ).hexdigest()}





def       a_ (	lowercase__ :Optional[Any]     ):
			__lowerCamelCase          =      [len(_UpperCamelCase     ) for line in example["""content"""].splitlines()]
			return {"line_mean": np.mean(_UpperCamelCase     ), "line_max": max(_UpperCamelCase     )}





def       a_ (	lowercase__ :Union[str, Any]     ):
			__lowerCamelCase          =      np.mean([c.isalnum() for c in example["""content"""]]     )
			return {"alpha_frac": alpha_frac}





def       a_ (	lowercase__ :Tuple,			lowercase__ :Any     ):







			if example["hash"] in uniques:
						uniques.remove(example["""hash"""]     )
						return True
			else:
						return False





def       a_ (	lowercase__ :Dict,			lowercase__ :Dict=5     ):
			__lowerCamelCase          =      ["""auto-generated""", """autogenerated""", """automatically generated"""]
			__lowerCamelCase          =      example["""content"""].splitlines()
			for _, line in zip(range(_UpperCamelCase     ),			_UpperCamelCase     ):
						for keyword in keywords:
									if keyword in line.lower():
												return {"autogenerated": True}
			else:
						return {"autogenerated": False}





def       a_ (	lowercase__ :int,			lowercase__ :str=5,			lowercase__ :Union[str, Any]=0.05     ):
			__lowerCamelCase          =      ["""unit tests""", """test file""", """configuration file"""]
			__lowerCamelCase          =      example["""content"""].splitlines()
			__lowerCamelCase          =      0
			__lowerCamelCase          =      0
			# first test
			for _, line in zip(range(_UpperCamelCase     ),			_UpperCamelCase     ):
						for keyword in keywords:
									if keyword in line.lower():
												return {"config_or_test": True}
    # second test
			__lowerCamelCase          =      example["""content"""].count("""\n"""     )
			__lowerCamelCase          =      int(coeff * nlines     )
			for line in lines:
						count_config += line.lower().count("""config"""     )
						count_test += line.lower().count("""test"""     )
						if count_config > threshold or count_test > threshold:
									return {"config_or_test": True}
			return {"config_or_test": False}





def       a_ (	lowercase__ :Optional[int]     ):
			__lowerCamelCase          =      ["""def """, """class """, """for """, """while """]
			__lowerCamelCase          =      example["""content"""].splitlines()
			for line in lines:
						for keyword in keywords:
									if keyword in line.lower():
												return {"has_no_keywords": False}
			return {"has_no_keywords": True}





def       a_ (	lowercase__ :Optional[Any],			lowercase__ :Optional[int]=4     ):
			__lowerCamelCase          =      example["""content"""].splitlines()
			__lowerCamelCase          =      0
			for line in lines:
						counter += line.lower().count("""="""     )
						if counter > minimum:
									return {"has_few_assignments": False}
			return {"has_few_assignments": True}





def       a_ (	lowercase__ :List[str]     ):
			__lowerCamelCase          =      tokenizer(example["""content"""],			truncation=_UpperCamelCase     )["""input_ids"""]
			__lowerCamelCase          =      len(example["""content"""]     ) / len(_UpperCamelCase     )
			return {"ratio": ratio}





def       a_ (	lowercase__ :Optional[int]     ):
			__lowerCamelCase          =      {}
			results.update(get_hash(_UpperCamelCase     )     )
			results.update(line_stats(_UpperCamelCase     )     )
			results.update(alpha_stats(_UpperCamelCase     )     )
			results.update(char_token_ratio(_UpperCamelCase     )     )
			results.update(is_autogenerated(_UpperCamelCase     )     )
			results.update(is_config_or_test(_UpperCamelCase     )     )
			results.update(has_no_keywords(_UpperCamelCase     )     )
			results.update(has_few_assignments(_UpperCamelCase     )     )
			return results





def       a_ (	lowercase__ :str,			lowercase__ :Tuple,			lowercase__ :Tuple     ):







			if not check_uniques(_UpperCamelCase,			_UpperCamelCase     ):
						return False
			elif example["autogenerated"]:
						return False
			elif example["line_max"] > args.line_max:
						return False
			elif example["line_mean"] > args.line_mean:
						return False
			elif example["alpha_frac"] < args.alpha_frac:
						return False
			elif example["ratio"] < args.min_token_ratio:
						return False
			elif example["config_or_test"] and np.random.rand() <= args.filter_proba:
						return False
			elif example["has_no_keywords"] and np.random.rand() <= args.filter_proba:
						return False
			elif example["has_few_assignments"]:
						return False
			else:
						return True





def       a_ (	lowercase__ :Dict     ):







			with open(_UpperCamelCase,			"""rb"""     ) as f_in:
						with gzip.open(str(_UpperCamelCase     ) + """.gz""",			"""wb""",			compresslevel=6     ) as f_out:
									shutil.copyfileobj(_UpperCamelCase,			_UpperCamelCase     )
			os.unlink(_UpperCamelCase     )


# Settings
__magic_name__						: Tuple    =				HfArgumentParser(PreprocessingArguments)
__magic_name__						: Optional[int]    =				parser.parse_args()
if args.num_workers is None:
					__magic_name__						: str    =				multiprocessing.cpu_count()
__magic_name__						: List[str]    =				AutoTokenizer.from_pretrained(args.tokenizer_dir)

# Load dataset
__magic_name__						: Tuple    =				time.time()
__magic_name__						: Union[str, Any]    =				load_dataset(args.dataset_name, split='train')
print(f"""Time to load dataset: {time.time()-t_start:.2f}""")

# Run preprocessing
__magic_name__						: int    =				time.time()
__magic_name__						: Optional[Any]    =				ds.map(preprocess, num_proc=args.num_workers)
print(f"""Time to preprocess dataset: {time.time()-t_start:.2f}""")

# Deduplicate hashes
__magic_name__						: Optional[Any]    =				set(ds.unique('hash'))
__magic_name__						: Dict    =				len(uniques) / len(ds)
print(f"""Fraction of duplicates: {1-frac:.2%}""")

# Deduplicate data and apply heuristics
__magic_name__						: Union[str, Any]    =				time.time()
__magic_name__						: int    =				ds.filter(filter, fn_kwargs={'uniques': uniques, 'args': args})
print(f"""Time to filter dataset: {time.time()-t_start:.2f}""")
print(f"""Size of filtered dataset: {len(ds_filter)}""")

# Deduplicate with minhash and jaccard similarity
if args.near_deduplication:
					__magic_name__						: Dict    =				time.time()
					__magic_name__						: Dict    =				deduplicate_dataset(ds_filter, args.jaccard_threshold)
					print(f"""Time to deduplicate dataset: {time.time()-t_start:.2f}""")
					print(f"""Size of deduplicate dataset: {len(ds_filter)}""")

# Save data in batches of samples_per_file
__magic_name__						: Dict    =				Path(args.output_dir)
output_dir.mkdir(exist_ok=True)

# save duplicate_clusters in the output_dir as artifacts
# not sure it is the right place the save it
if args.near_deduplication:
					with open(output_dir / 'duplicate_clusters.json', 'w') as f:
										json.dump(duplicate_clusters, f)

__magic_name__						: List[str]    =				output_dir / '''data'''
data_dir.mkdir(exist_ok=True)

__magic_name__						: str    =				time.time()
for file_number, index in enumerate(range(0, len(ds_filter), args.samples_per_file)):
					__magic_name__						: List[Any]    =				str(data_dir / f"""file-{file_number+1:012}.json""")
					__magic_name__						: Union[str, Any]    =				min(len(ds_filter), index + args.samples_per_file)
					ds_filter.select(list(range(index, end_index))).to_json(file_path)
					compress_file(file_path)


print(f"""Time to save dataset: {time.time()-t_start:.2f}""")








# Lint as: python3
# pylint: enable=line-too-long
# pylint: disable=g-import-not-at-top,g-bad-import-order,wrong-import-position

a			:			Dict												=					'''2.13.1'''

import platform

import pyarrow
from packaging import version


if version.parse(platform.python_version()) < version.parse('''3.7'''):
	raise ImportWarning(
	    '''To use `datasets`, Python>=3.7 is required, and the current version of Python doesn\'t match this condition.'''
	)

if version.parse(pyarrow.__version__).major < 8:
	raise ImportWarning(
	    '''To use `datasets`, the module `pyarrow>=8.0.0` is required, and the current version of `pyarrow` doesn\'t match this condition.\n'''
	    '''If you are running this in a Google Colab, you should probably just restart the runtime to use the right version of `pyarrow`.'''
	)

del platform
del pyarrow
del version

from .arrow_dataset import Dataset
from .arrow_reader import ReadInstruction
from .builder import ArrowBasedBuilder, BeamBasedBuilder, BuilderConfig, DatasetBuilder, GeneratorBasedBuilder
from .combine import concatenate_datasets, interleave_datasets
from .dataset_dict import DatasetDict, IterableDatasetDict
from .download import *
from .features import *
from .fingerprint import disable_caching, enable_caching, is_caching_enabled, set_caching_enabled
from .info import DatasetInfo, MetricInfo
from .inspect import (
    get_dataset_config_info,
    get_dataset_config_names,
    get_dataset_infos,
    get_dataset_split_names,
    inspect_dataset,
    inspect_metric,
    list_datasets,
    list_metrics,
)
from .iterable_dataset import IterableDataset
from .load import load_dataset, load_dataset_builder, load_from_disk, load_metric
from .metric import Metric
from .splits import (
    NamedSplit,
    NamedSplitAll,
    Split,
    SplitBase,
    SplitDict,
    SplitGenerator,
    SplitInfo,
    SubSplitInfo,
    percent,
)
from .tasks import *
from .utils import *
from .utils import logging


# deprecated modules
from datasets import arrow_dataset as _arrow_dataset  # isort:skip
from datasets import utils as _utils  # isort:skip
from datasets.utils import download_manager as _deprecated_download_manager  # isort:skip

a			:			Optional[int]												=					concatenate_datasets
a			:			List[Any]												=					DownloadConfig
a			:			List[Any]												=					DownloadManager
a			:			str												=					DownloadMode
a			:			int												=					DownloadConfig
a			:			List[str]												=					DownloadMode
a			:			Optional[int]												=					DownloadManager

del _arrow_dataset, _utils, _deprecated_download_manager


