





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


_a						=   re.compile(R"\s+")





def lowerCAmelCase__(__snake_case							)       ->   List[str]:







	'''simple docstring'''







	return {"hash": hashlib.mda(re.sub(__snake_case ,'''''' ,example['''content''']							).encode('''utf-8'''							)							).hexdigest()}





def lowerCAmelCase__(__snake_case							)       ->   Dict:







	'''simple docstring'''







	lowerCamelCase__              =	[len(__snake_case							) for line in example["""content"""].splitlines()]
	return {"line_mean": np.mean(__snake_case							), "line_max": max(__snake_case							)}





def lowerCAmelCase__(__snake_case							)       ->   str:







	'''simple docstring'''







	lowerCamelCase__              =	np.mean([c.isalnum() for c in example['''content''']]							)
	return {"alpha_frac": alpha_frac}





def lowerCAmelCase__(__snake_case ,__snake_case							)       ->   Optional[Any]:







	'''simple docstring'''







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





def lowerCAmelCase__(__snake_case ,__snake_case=5							)       ->   Tuple:







	'''simple docstring'''







	lowerCamelCase__              =	["""auto-generated""", """autogenerated""", """automatically generated"""]
	lowerCamelCase__              =	example["""content"""].splitlines()
	for _, line in zip(range(__snake_case							) ,__snake_case							):
		for keyword in keywords:
			if keyword in line.lower():
				return {"autogenerated": True}
	else:
		return {"autogenerated": False}





def lowerCAmelCase__(__snake_case ,__snake_case=5 ,__snake_case=0.0_5							)       ->   List[str]:







	'''simple docstring'''







	lowerCamelCase__              =	["""unit tests""", """test file""", """configuration file"""]
	lowerCamelCase__              =	example["""content"""].splitlines()
	lowerCamelCase__              =	0
	lowerCamelCase__              =	0
	# first test
	for _, line in zip(range(__snake_case							) ,__snake_case							):
		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 lowerCAmelCase__(__snake_case							)       ->   Optional[Any]:







	'''simple docstring'''







	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 lowerCAmelCase__(__snake_case ,__snake_case=4							)       ->   Tuple:







	'''simple docstring'''







	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 lowerCAmelCase__(__snake_case							)       ->   List[Any]:







	'''simple docstring'''







	lowerCamelCase__              =	tokenizer(example['''content'''] ,truncation=__snake_case							)["""input_ids"""]
	lowerCamelCase__              =	len(example['''content''']							) / len(__snake_case							)
	return {"ratio": ratio}





def lowerCAmelCase__(__snake_case							)       ->   List[str]:







	'''simple docstring'''







	lowerCamelCase__              =	{}
	results.update(get_hash(__snake_case							)							)
	results.update(line_stats(__snake_case							)							)
	results.update(alpha_stats(__snake_case							)							)
	results.update(char_token_ratio(__snake_case							)							)
	results.update(is_autogenerated(__snake_case							)							)
	results.update(is_config_or_test(__snake_case							)							)
	results.update(has_no_keywords(__snake_case							)							)
	results.update(has_few_assignments(__snake_case							)							)
	return results





def lowerCAmelCase__(__snake_case ,__snake_case ,__snake_case							)       ->   int:







	'''simple docstring'''







	if not check_uniques(__snake_case ,__snake_case							):
		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 lowerCAmelCase__(__snake_case							)       ->   Union[str, Any]:







	'''simple docstring'''







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


# Settings
_a						=   HfArgumentParser(PreprocessingArguments)
_a						=   parser.parse_args()
if args.num_workers is None:
			_a						=   multiprocessing.cpu_count()
_a						=   AutoTokenizer.from_pretrained(args.tokenizer_dir)

# Load dataset
_a						=   time.time()
_a						=   load_dataset(args.dataset_name, split="train")
print(f"""Time to load dataset: {time.time()-t_start:.2f}""")

# Run preprocessing
_a						=   time.time()
_a						=   ds.map(preprocess, num_proc=args.num_workers)
print(f"""Time to preprocess dataset: {time.time()-t_start:.2f}""")

# Deduplicate hashes
_a						=   set(ds.unique("hash"))
_a						=   len(uniques) / len(ds)
print(f"""Fraction of duplicates: {1-frac:.2%}""")

# Deduplicate data and apply heuristics
_a						=   time.time()
_a						=   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:
			_a						=   time.time()
			_a		,	_a						=   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
_a						=   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)

_a						=   output_dir / "data"
data_dir.mkdir(exist_ok=True)

_a						=   time.time()
for file_number, index in enumerate(range(0, len(ds_filter), args.samples_per_file)):
			_a						=   str(data_dir / f"""file-{file_number+1:012}.json""")
			_a						=   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}""")










from __future__ import annotations





def lowerCAmelCase__(__snake_case ,__snake_case = None ,__snake_case = None							)       ->   None:







	'''simple docstring'''







	if start is None:
		lowerCamelCase__              =	0

	if end is None:
		lowerCamelCase__              =	len(__snake_case							) - 1

	if start >= end:
		return

	lowerCamelCase__              =	(start + end) // 2

	slowsort(__snake_case ,__snake_case ,__snake_case							)
	slowsort(__snake_case ,mid + 1 ,__snake_case							)

	if sequence[end] < sequence[mid]:
		lowerCamelCase__       ,			lowerCamelCase__              =	sequence[mid], sequence[end]

	slowsort(__snake_case ,__snake_case ,end - 1							)


if __name__ == "__main__":
			from doctest import testmod

			testmod()



