






'''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


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



def 							snake_case					(     a_							: List[Any]	)       ->				str:





						"""simple docstring"""

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



def 							snake_case					(     a_							: int	)       ->				List[Any]:





						"""simple docstring"""

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



def 							snake_case					(     a_							: List[str]	)       ->				Optional[int]:





						"""simple docstring"""

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



def 							snake_case					(     a_							: List[Any]    ,   a_							: str	)       ->				Tuple:





						"""simple docstring"""

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



def 							snake_case					(     a_							: Optional[int]    ,   a_							: Tuple=5	)       ->				int:





						"""simple docstring"""

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



def 							snake_case					(     a_							: Union[str, Any]    ,   a_							: Any=5    ,   a_							: List[str]=0.05	)       ->				Any:





						"""simple docstring"""

						UpperCamelCase_				:   List[Any]					    =							["""unit tests""", """test file""", """configuration file"""]
						UpperCamelCase_				:   Union[str, Any]					    =							example["""content"""].splitlines()
						UpperCamelCase_				:   List[str]					    =							0
						UpperCamelCase_				:   Optional[int]					    =							0
						# first test
						for _, line in zip(range(a_	)    ,   a_	):
												for keyword in keywords:
																		if keyword in line.lower():
																								return {"config_or_test": True}
    # second test
						UpperCamelCase_				:   str					    =							example["""content"""].count("""\n"""	)
						UpperCamelCase_				:   List[Any]					    =							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 							snake_case					(     a_							: Dict	)       ->				Optional[int]:





						"""simple docstring"""

						UpperCamelCase_				:   Tuple					    =							["""def """, """class """, """for """, """while """]
						UpperCamelCase_				:   Optional[Any]					    =							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 							snake_case					(     a_							: List[str]    ,   a_							: Tuple=4	)       ->				Union[str, Any]:





						"""simple docstring"""

						UpperCamelCase_				:   Optional[Any]					    =							example["""content"""].splitlines()
						UpperCamelCase_				:   Any					    =							0
						for line in lines:
												counter += line.lower().count("""="""	)
												if counter > minimum:
																		return {"has_few_assignments": False}
						return {"has_few_assignments": True}



def 							snake_case					(     a_							: Optional[Any]	)       ->				List[Any]:





						"""simple docstring"""

						UpperCamelCase_				:   Any					    =							tokenizer(example["""content"""]    ,   truncation=a_	)["""input_ids"""]
						UpperCamelCase_				:   Any					    =							len(example["""content"""]	) / len(a_	)
						return {"ratio": ratio}



def 							snake_case					(     a_							: Optional[int]	)       ->				Any:





						"""simple docstring"""

						UpperCamelCase_				:   Union[str, Any]					    =							{}
						results.update(get_hash(a_	)	)
						results.update(line_stats(a_	)	)
						results.update(alpha_stats(a_	)	)
						results.update(char_token_ratio(a_	)	)
						results.update(is_autogenerated(a_	)	)
						results.update(is_config_or_test(a_	)	)
						results.update(has_no_keywords(a_	)	)
						results.update(has_few_assignments(a_	)	)
						return results



def 							snake_case					(     a_							: Optional[Any]    ,   a_							: Union[str, Any]    ,   a_							: int	)       ->				int:





						"""simple docstring"""

						if not check_uniques(a_    ,   a_	):
												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 							snake_case					(     a_							: Optional[int]	)       ->				int:





						"""simple docstring"""

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


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

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

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

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

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

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

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














'''simple docstring'''

def 							snake_case					(     a_							: int	)       ->				int:





      """simple docstring"""

      assert (
          isinstance(a_    ,   a_	) and number_of_steps > 0
      ), f"number_of_steps needs to be positive integer, your input {number_of_steps}"
      if number_of_steps == 1:
            return 1
      UpperCamelCase_    ,			UpperCamelCase_				:   str					    =							1, 1
      for _ in range(number_of_steps - 1	):
            UpperCamelCase_    ,			UpperCamelCase_				:   Tuple					    =							current + previous, current
      return current


if __name__ == "__main__":
      import doctest

      doctest.testmod()






