






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


SCREAMING_SNAKE_CASE__   :      Union[str, Any]				=		re.compile(r"""\s+""")

def   __lowercase       (			snake_case			):







				"""simple docstring"""






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

def   __lowercase       (			snake_case			):







				"""simple docstring"""






				__magic_name__		:List[Any]   =   [len(snake_case			) for line in example['''content'''].splitlines()]
				return {"line_mean": np.mean(snake_case			), "line_max": max(snake_case			)}

def   __lowercase       (			snake_case			):







				"""simple docstring"""






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

def   __lowercase       (			snake_case,	snake_case			):







				"""simple docstring"""






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

def   __lowercase       (			snake_case,	snake_case=5			):







				"""simple docstring"""






				__magic_name__		:int   =   ['''auto-generated''', '''autogenerated''', '''automatically generated''']
				__magic_name__		:Dict   =   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   __lowercase       (			snake_case,	snake_case=5,	snake_case=0.05			):







				"""simple docstring"""






				__magic_name__		:str   =   ['''unit tests''', '''test file''', '''configuration file''']
				__magic_name__		:Optional[Any]   =   example['''content'''].splitlines()
				__magic_name__		:Any   =   0
				__magic_name__		:List[Any]   =   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
				__magic_name__		:List[str]   =   example['''content'''].count('''\n'''			)
				__magic_name__		:Optional[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   __lowercase       (			snake_case			):







				"""simple docstring"""






				__magic_name__		:Optional[int]   =   ['''def ''', '''class ''', '''for ''', '''while ''']
				__magic_name__		:int   =   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   __lowercase       (			snake_case,	snake_case=4			):







				"""simple docstring"""






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

def   __lowercase       (			snake_case			):







				"""simple docstring"""






				__magic_name__		:List[Any]   =   tokenizer(example['''content'''],	truncation=snake_case			)['''input_ids''']
				__magic_name__		:Optional[Any]   =   len(example['''content''']			) / len(snake_case			)
				return {"ratio": ratio}

def   __lowercase       (			snake_case			):







				"""simple docstring"""






				__magic_name__		:Union[str, Any]   =   {}
				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   __lowercase       (			snake_case,	snake_case,	snake_case			):







				"""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   __lowercase       (			snake_case			):







				"""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
SCREAMING_SNAKE_CASE__   :      int				=		HfArgumentParser(PreprocessingArguments)
SCREAMING_SNAKE_CASE__   :      Union[str, Any]				=		parser.parse_args()
if args.num_workers is None:
					SCREAMING_SNAKE_CASE__   :      Tuple				=		multiprocessing.cpu_count()
SCREAMING_SNAKE_CASE__   :      List[Any]				=		AutoTokenizer.from_pretrained(args.tokenizer_dir)

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

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

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

# Deduplicate data and apply heuristics
SCREAMING_SNAKE_CASE__   :      int				=		time.time()
SCREAMING_SNAKE_CASE__   :      List[Any]				=		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:
					SCREAMING_SNAKE_CASE__   :      List[Any]				=		time.time()
					SCREAMING_SNAKE_CASE__				,       SCREAMING_SNAKE_CASE__   :      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
SCREAMING_SNAKE_CASE__   :      Any				=		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)

SCREAMING_SNAKE_CASE__   :      Optional[Any]				=		output_dir / """data"""
data_dir.mkdir(exist_ok=True)

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














import numpy as np
import torch
from torch.utils.data import Dataset

from utils import logger
class     lowerCamelCase_					(   lowerCamelCase			):







				def __init__(    self							,       __lowerCAmelCase							,       __lowerCAmelCase  ):
								"""simple docstring"""
								__magic_name__		:Optional[int]   =   params

								__magic_name__		:Any   =   np.array(__lowerCAmelCase  )
								__magic_name__		:Optional[Any]   =   np.array([len(__lowerCAmelCase  ) for t in data]  )

								self.check()
								self.remove_long_sequences()
								self.remove_empty_sequences()
								self.remove_unknown_sequences()
								self.check()
								self.print_statistics()







				def __getitem__(    self							,       __lowerCAmelCase  ):
								"""simple docstring"""
								return (self.token_ids[index], self.lengths[index])







				def __len__(    self  ):
								"""simple docstring"""
								return len(self.lengths  )







				def       A						(    self  ):
								"""simple docstring"""
								assert len(self.token_ids  ) == len(self.lengths  )
								assert all(self.lengths[i] == len(self.token_ids[i]  ) for i in range(len(self.lengths  )  )  )







				def       A						(    self  ):
								"""simple docstring"""
								__magic_name__		:Any   =   self.params.max_model_input_size
								__magic_name__		:int   =   self.lengths > max_len
								logger.info(F'''Splitting {sum(__lowerCAmelCase  )} too long sequences.'''  )

								def divide_chunks(__lowerCAmelCase							,       __lowerCAmelCase  ):
												return [l[i : i + n] for i in range(0							,       len(__lowerCAmelCase  )							,       __lowerCAmelCase  )]

								__magic_name__		:Optional[int]   =   []
								__magic_name__		:List[Any]   =   []
								if self.params.mlm:
												__magic_name__  ,					__magic_name__		:Optional[Any]   =   self.params.special_tok_ids['''cls_token'''], self.params.special_tok_ids['''sep_token''']
								else:
												__magic_name__  ,					__magic_name__		:Tuple   =   self.params.special_tok_ids['''bos_token'''], self.params.special_tok_ids['''eos_token''']

								for seq_, len_ in zip(self.token_ids							,       self.lengths  ):
												assert (seq_[0] == cls_id) and (seq_[-1] == sep_id), seq_
												if len_ <= max_len:
																new_tok_ids.append(seq_  )
																new_lengths.append(len_  )
												else:
																__magic_name__		:int   =   []
																for sub_s in divide_chunks(seq_							,       max_len - 2  ):
																				if sub_s[0] != cls_id:
																								__magic_name__		:List[Any]   =   np.insert(__lowerCAmelCase							,       0							,       __lowerCAmelCase  )
																				if sub_s[-1] != sep_id:
																								__magic_name__		:Union[str, Any]   =   np.insert(__lowerCAmelCase							,       len(__lowerCAmelCase  )							,       __lowerCAmelCase  )
																				assert len(__lowerCAmelCase  ) <= max_len
																				assert (sub_s[0] == cls_id) and (sub_s[-1] == sep_id), sub_s
																				sub_seqs.append(__lowerCAmelCase  )

																new_tok_ids.extend(__lowerCAmelCase  )
																new_lengths.extend([len(__lowerCAmelCase  ) for l in sub_seqs]  )

								__magic_name__		:Tuple   =   np.array(__lowerCAmelCase  )
								__magic_name__		:Optional[int]   =   np.array(__lowerCAmelCase  )







				def       A						(    self  ):
								"""simple docstring"""
								__magic_name__		:Optional[Any]   =   len(self  )
								__magic_name__		:int   =   self.lengths > 1_1
								__magic_name__		:List[str]   =   self.token_ids[indices]
								__magic_name__		:Union[str, Any]   =   self.lengths[indices]
								__magic_name__		:List[str]   =   len(self  )
								logger.info(F'''Remove {init_size - new_size} too short (<=11 tokens) sequences.'''  )







				def       A						(    self  ):
								"""simple docstring"""
								if "unk_token" not in self.params.special_tok_ids:
												return
								else:
												__magic_name__		:Tuple   =   self.params.special_tok_ids['''unk_token''']
								__magic_name__		:Dict   =   len(self  )
								__magic_name__		:Tuple   =   np.array([np.count_nonzero(a == unk_token_id  ) for a in self.token_ids]  )
								__magic_name__		:int   =   (unk_occs / self.lengths) < 0.5
								__magic_name__		:str   =   self.token_ids[indices]
								__magic_name__		:str   =   self.lengths[indices]
								__magic_name__		:Any   =   len(self  )
								logger.info(F'''Remove {init_size - new_size} sequences with a high level of unknown tokens (50%).'''  )







				def       A						(    self  ):
								"""simple docstring"""
								if not self.params.is_master:
												return
								logger.info(F'''{len(self  )} sequences'''  )
								# data_len = sum(self.lengths)
								# nb_unique_tokens = len(Counter(list(chain(*self.token_ids))))
								# logger.info(f'{data_len} tokens ({nb_unique_tokens} unique)')

								# unk_idx = self.params.special_tok_ids['unk_token']
								# nb_unknown = sum([(t==unk_idx).sum() for t in self.token_ids])
								# logger.info(f'{nb_unknown} unknown tokens (covering {100*nb_unknown/data_len:.2f}% of the data)')







				def       A						(    self							,       __lowerCAmelCase  ):
								"""simple docstring"""
								__magic_name__		:Optional[Any]   =   [t[0] for t in batch]
								__magic_name__		:List[Any]   =   [t[1] for t in batch]
								assert len(__lowerCAmelCase  ) == len(__lowerCAmelCase  )

								# Max for paddings
								__magic_name__		:Tuple   =   max(__lowerCAmelCase  )

								# Pad token ids
								if self.params.mlm:
												__magic_name__		:Any   =   self.params.special_tok_ids['''pad_token''']
								else:
												__magic_name__		:str   =   self.params.special_tok_ids['''unk_token''']
								__magic_name__		:Any   =   [list(t.astype(__lowerCAmelCase  )  ) + [pad_idx] * (max_seq_len_ - len(__lowerCAmelCase  )) for t in token_ids]
								assert len(tk_  ) == len(__lowerCAmelCase  )
								assert all(len(__lowerCAmelCase  ) == max_seq_len_ for t in tk_  )

								__magic_name__		:Optional[int]   =   torch.tensor(tk_  )  # (bs, max_seq_len_)
								__magic_name__		:Optional[int]   =   torch.tensor(__lowerCAmelCase  )  # (bs)
								return tk_t, lg_t






