






'''simple docstring'''







from abc import ABC, abstractmethod
from typing import List, Optional




class 		UpperCamelCase__     (a      ):




		'''simple docstring'''





		def __init__(   self							):
								# test for the above condition
								self.test()






		def       UpperCamelCase_       (   self							):
								lowerCamelCase__								=	0
								lowerCamelCase__								=	False
								while not completed:
														if counter == 1:
																				self.reset()
														lowerCamelCase__								=	self.advance()
														if not self.does_advance(_lowerCAmelCase							):
																				raise Exception(
																				    """Custom Constraint is not defined correctly. self.does_advance(self.advance()) must be true."""							)

														lowerCamelCase__							,      lowerCamelCase__							,      lowerCamelCase__								=	self.update(_lowerCAmelCase							)
														counter += 1

														if counter > 1_00_00:
																				raise Exception("""update() does not fulfill the constraint."""							)

								if self.remaining() != 0:
														raise Exception("""Custom Constraint is not defined correctly."""							)






		@abstractmethod
		def       UpperCamelCase_       (   self							):
								raise NotImplementedError(
								    F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.'''							)






		@abstractmethod
		def       UpperCamelCase_       (   self ,_lowerCAmelCase							):
								raise NotImplementedError(
								    F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.'''							)






		@abstractmethod
		def       UpperCamelCase_       (   self ,_lowerCAmelCase							):
								raise NotImplementedError(
								    F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.'''							)






		@abstractmethod
		def       UpperCamelCase_       (   self							):
								raise NotImplementedError(
								    F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.'''							)






		@abstractmethod
		def       UpperCamelCase_       (   self							):
								raise NotImplementedError(
								    F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.'''							)






		@abstractmethod
		def       UpperCamelCase_       (   self ,_lowerCAmelCase=False							):
								raise NotImplementedError(
								    F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.'''							)




class 		UpperCamelCase__     (a      ):




		'''simple docstring'''





		def __init__(   self ,_lowerCAmelCase							):
								super(_lowerCAmelCase ,self							).__init__()

								if not isinstance(_lowerCAmelCase ,_lowerCAmelCase							) or len(_lowerCAmelCase							) == 0:
														raise ValueError(F'''`token_ids` has to be a non-empty list, but is {token_ids}.'''							)
								if any((not isinstance(_lowerCAmelCase ,_lowerCAmelCase							) or token_id < 0) for token_id in token_ids							):
														raise ValueError(F'''Each list in `token_ids` has to be a list of positive integers, but is {token_ids}.'''							)

								lowerCamelCase__								=	token_ids

								lowerCamelCase__								=	len(self.token_ids							)
								lowerCamelCase__								=	-1  # the index of the currently fulfilled step
								lowerCamelCase__								=	False






		def       UpperCamelCase_       (   self							):
								if self.completed:
														return None
								return self.token_ids[self.fulfilled_idx + 1]






		def       UpperCamelCase_       (   self ,_lowerCAmelCase							):
								if not isinstance(_lowerCAmelCase ,_lowerCAmelCase							):
														raise ValueError(F'''`token_id` has to be an `int`, but is {token_id} of type {type(_lowerCAmelCase							)}'''							)

								if self.completed:
														return False

								return token_id == self.token_ids[self.fulfilled_idx + 1]






		def       UpperCamelCase_       (   self ,_lowerCAmelCase							):
								if not isinstance(_lowerCAmelCase ,_lowerCAmelCase							):
														raise ValueError(F'''`token_id` has to be an `int`, but is {token_id} of type {type(_lowerCAmelCase							)}'''							)

								lowerCamelCase__								=	False
								lowerCamelCase__								=	False
								lowerCamelCase__								=	False

								if self.does_advance(_lowerCAmelCase							):
														self.fulfilled_idx += 1
														lowerCamelCase__								=	True
														if self.fulfilled_idx == (self.seqlen - 1):
																				lowerCamelCase__								=	True
														lowerCamelCase__								=	completed
								else:
														# failed to make progress.
														lowerCamelCase__								=	True
														self.reset()
								return stepped, completed, reset






		def       UpperCamelCase_       (   self							):
								lowerCamelCase__								=	False
								lowerCamelCase__								=	0






		def       UpperCamelCase_       (   self							):
								return self.seqlen - (self.fulfilled_idx + 1)






		def       UpperCamelCase_       (   self ,_lowerCAmelCase=False							):
								lowerCamelCase__								=	PhrasalConstraint(self.token_ids							)

								if stateful:
														lowerCamelCase__								=	self.seqlen
														lowerCamelCase__								=	self.fulfilled_idx
														lowerCamelCase__								=	self.completed

								return new_constraint




class 		UpperCamelCase__     :




		'''simple docstring'''





		def __init__(   self ,_lowerCAmelCase ,_lowerCAmelCase=True							):
								lowerCamelCase__								=	max([len(_lowerCAmelCase							) for one in nested_token_ids]							)

								lowerCamelCase__								=	{}
								for token_ids in nested_token_ids:
														lowerCamelCase__								=	root
														for tidx, token_id in enumerate(_lowerCAmelCase							):
																				if token_id not in level:
																										lowerCamelCase__								=	{}

																				lowerCamelCase__								=	level[token_id]

								if no_subsets and self.has_subsets(_lowerCAmelCase ,_lowerCAmelCase							):
														raise ValueError(
														    """Each list in `nested_token_ids` can't be a complete subset of another list, but is"""
														    F''' {nested_token_ids}.'''							)

								lowerCamelCase__								=	root






		def       UpperCamelCase_       (   self ,_lowerCAmelCase							):
								lowerCamelCase__								=	self.trie

								for current_token in current_seq:
														lowerCamelCase__								=	start[current_token]

								lowerCamelCase__								=	list(start.keys()							)

								return next_tokens






		def       UpperCamelCase_       (   self ,_lowerCAmelCase							):
								lowerCamelCase__								=	self.next_tokens(_lowerCAmelCase							)

								return len(_lowerCAmelCase							) == 0






		def       UpperCamelCase_       (   self ,_lowerCAmelCase							):
								lowerCamelCase__								=	list(root.values()							)
								if len(_lowerCAmelCase							) == 0:
														return 1
								else:
														return sum([self.count_leaves(_lowerCAmelCase							) for nn in next_nodes]							)






		def       UpperCamelCase_       (   self ,_lowerCAmelCase ,_lowerCAmelCase							):
								lowerCamelCase__								=	self.count_leaves(_lowerCAmelCase							)
								return len(_lowerCAmelCase							) != leaf_count




class 		UpperCamelCase__     (a      ):




		'''simple docstring'''





		def __init__(   self ,_lowerCAmelCase							):
								super(_lowerCAmelCase ,self							).__init__()

								if not isinstance(_lowerCAmelCase ,_lowerCAmelCase							) or len(_lowerCAmelCase							) == 0:
														raise ValueError(F'''`nested_token_ids` has to be a non-empty list, but is {nested_token_ids}.'''							)
								if any(not isinstance(_lowerCAmelCase ,_lowerCAmelCase							) for token_ids in nested_token_ids							):
														raise ValueError(F'''`nested_token_ids` has to be a list of lists, but is {nested_token_ids}.'''							)
								if any(
								    any((not isinstance(_lowerCAmelCase ,_lowerCAmelCase							) or token_id < 0) for token_id in token_ids							)
								    for token_ids in nested_token_ids							):
														raise ValueError(
														    F'''Each list in `nested_token_ids` has to be a list of positive integers, but is {nested_token_ids}.'''							)

								lowerCamelCase__								=	DisjunctiveTrie(_lowerCAmelCase							)
								lowerCamelCase__								=	nested_token_ids

								lowerCamelCase__								=	self.trie.max_height
								lowerCamelCase__								=	[]
								lowerCamelCase__								=	False






		def       UpperCamelCase_       (   self							):
								lowerCamelCase__								=	self.trie.next_tokens(self.current_seq							)

								if len(_lowerCAmelCase							) == 0:
														return None
								else:
														return token_list






		def       UpperCamelCase_       (   self ,_lowerCAmelCase							):
								if not isinstance(_lowerCAmelCase ,_lowerCAmelCase							):
														raise ValueError(F'''`token_id` is supposed to be type `int`, but is {token_id} of type {type(_lowerCAmelCase							)}'''							)

								lowerCamelCase__								=	self.trie.next_tokens(self.current_seq							)

								return token_id in next_tokens






		def       UpperCamelCase_       (   self ,_lowerCAmelCase							):
								if not isinstance(_lowerCAmelCase ,_lowerCAmelCase							):
														raise ValueError(F'''`token_id` is supposed to be type `int`, but is {token_id} of type {type(_lowerCAmelCase							)}'''							)

								lowerCamelCase__								=	False
								lowerCamelCase__								=	False
								lowerCamelCase__								=	False

								if self.does_advance(_lowerCAmelCase							):
														self.current_seq.append(_lowerCAmelCase							)
														lowerCamelCase__								=	True
								else:
														lowerCamelCase__								=	True
														self.reset()

								lowerCamelCase__								=	self.trie.reached_leaf(self.current_seq							)
								lowerCamelCase__								=	completed

								return stepped, completed, reset






		def       UpperCamelCase_       (   self							):
								lowerCamelCase__								=	False
								lowerCamelCase__								=	[]






		def       UpperCamelCase_       (   self							):
								if self.completed:
														# since this can be completed without reaching max height
														return 0
								else:
														return self.seqlen - len(self.current_seq							)






		def       UpperCamelCase_       (   self ,_lowerCAmelCase=False							):
								lowerCamelCase__								=	DisjunctiveConstraint(self.token_ids							)

								if stateful:
														lowerCamelCase__								=	self.seqlen
														lowerCamelCase__								=	self.current_seq
														lowerCamelCase__								=	self.completed

								return new_constraint




class 		UpperCamelCase__     :




		'''simple docstring'''





		def __init__(   self ,_lowerCAmelCase							):
								lowerCamelCase__								=	constraints

								# max # of steps required to fulfill a given constraint
								lowerCamelCase__								=	max([c.seqlen for c in constraints]							)
								lowerCamelCase__								=	len(_lowerCAmelCase							)
								lowerCamelCase__								=	False

								self.init_state()






		def       UpperCamelCase_       (   self							):
								lowerCamelCase__								=	[]
								lowerCamelCase__								=	None
								lowerCamelCase__								=	[constraint.copy(stateful=_lowerCAmelCase							) for constraint in self.constraints]






		def       UpperCamelCase_       (   self							):
								lowerCamelCase__								=	0
								if self.inprogress_constraint:
														# extra points for having a constraint mid-fulfilled
														add += self.max_seqlen - self.inprogress_constraint.remaining()

								return (len(self.complete_constraints							) * self.max_seqlen) + add






		def       UpperCamelCase_       (   self							):
								lowerCamelCase__								=	[]
								if self.inprogress_constraint is None:
														for constraint in self.pending_constraints:  # "pending" == "unfulfilled yet"
																				lowerCamelCase__								=	constraint.advance()
																				if isinstance(_lowerCAmelCase ,_lowerCAmelCase							):
																										token_list.append(_lowerCAmelCase							)
																				elif isinstance(_lowerCAmelCase ,_lowerCAmelCase							):
																										token_list.extend(_lowerCAmelCase							)
								else:
														lowerCamelCase__								=	self.inprogress_constraint.advance()
														if isinstance(_lowerCAmelCase ,_lowerCAmelCase							):
																				token_list.append(_lowerCAmelCase							)
														elif isinstance(_lowerCAmelCase ,_lowerCAmelCase							):
																				token_list.extend(_lowerCAmelCase							)

								if len(_lowerCAmelCase							) == 0:
														return None
								else:
														return token_list






		def       UpperCamelCase_       (   self ,_lowerCAmelCase							):
								self.init_state()

								if token_ids is not None:
														for token in token_ids:
																				# completes or steps **one** constraint
																				lowerCamelCase__							,      lowerCamelCase__								=	self.add(_lowerCAmelCase							)

																				# the entire list of constraints are fulfilled
																				if self.completed:
																										break






		def       UpperCamelCase_       (   self ,_lowerCAmelCase							):
								if not isinstance(_lowerCAmelCase ,_lowerCAmelCase							):
														raise ValueError(F'''`token_id` should be an `int`, but is `{token_id}`.'''							)

								lowerCamelCase__							,      lowerCamelCase__								=	False, False

								if self.completed:
														lowerCamelCase__								=	True
														lowerCamelCase__								=	False
														return complete, stepped

								if self.inprogress_constraint is not None:
														# In the middle of fulfilling a constraint. If the `token_id` *does* makes an incremental progress to current
														# job, simply update the state

														lowerCamelCase__							,      lowerCamelCase__							,      lowerCamelCase__								=	self.inprogress_constraint.update(_lowerCAmelCase							)
														if reset:
																				# 1. If the next token breaks the progress, then we must restart.
																				#     e.g. constraint = "I love pies" and sequence so far is "I love" but `token_id` == "books".

																				#     But that doesn't mean we self.init_state(), since we only reset the state for this particular
																				#     constraint, not the full list of constraints.

																				self.pending_constraints.append(self.inprogress_constraint.copy(stateful=_lowerCAmelCase							)							)
																				lowerCamelCase__								=	None

														if complete:
																				# 2. If the next token completes the constraint, move it to completed list, set
																				#     inprogress to None. If there are no pending constraints either, then this full list of constraints
																				#     is complete.

																				self.complete_constraints.append(self.inprogress_constraint							)
																				lowerCamelCase__								=	None

																				if len(self.pending_constraints							) == 0:
																										# we're done!
																										lowerCamelCase__								=	True

								else:
														# Not in the middle of fulfilling a constraint. So does this `token_id` helps us step towards any of our list
														# of constraints?

														for cidx, pending_constraint in enumerate(self.pending_constraints							):
																				if pending_constraint.does_advance(_lowerCAmelCase							):
																										lowerCamelCase__							,      lowerCamelCase__							,      lowerCamelCase__								=	pending_constraint.update(_lowerCAmelCase							)

																										if not stepped:
																																raise Exception(
																																    """`constraint.update(token_id)` is not yielding incremental progress, """
																																    """even though `constraint.does_advance(token_id)` is true."""							)

																										if complete:
																																self.complete_constraints.append(_lowerCAmelCase							)
																																lowerCamelCase__								=	None

																										if not complete and stepped:
																																lowerCamelCase__								=	pending_constraint

																										if complete or stepped:
																																# If we made any progress at all, then it's at least not a "pending constraint".

																																lowerCamelCase__								=	(
																																    self.pending_constraints[:cidx] + self.pending_constraints[cidx + 1 :]
																																)

																																if len(self.pending_constraints							) == 0 and self.inprogress_constraint is None:
																																						# If there's no longer any pending after this and no inprogress either, then we must be
																																						# complete.

																																						lowerCamelCase__								=	True

																																break  # prevent accidentally stepping through multiple constraints with just one token.

								return complete, stepped






		def       UpperCamelCase_       (   self ,_lowerCAmelCase=True							):
								lowerCamelCase__								=	ConstraintListState(self.constraints							)  # we actually never though self.constraints objects
								# throughout this process. So it's at initialization state.

								if stateful:
														lowerCamelCase__								=	[
														    constraint.copy(stateful=_lowerCAmelCase							) for constraint in self.complete_constraints
														]
														if self.inprogress_constraint is not None:
																				lowerCamelCase__								=	self.inprogress_constraint.copy(stateful=_lowerCAmelCase							)
														lowerCamelCase__								=	[constraint.copy() for constraint in self.pending_constraints]

								return new_state




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 						lowerCamelCase__      ( __A    :int		):


       """simple docstring"""




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







def 						lowerCamelCase__      ( __A    :Any		):


       """simple docstring"""




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







def 						lowerCamelCase__      ( __A    :Any		):


       """simple docstring"""




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







def 						lowerCamelCase__      ( __A    :str	,__A    :int		):


       """simple docstring"""




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







def 						lowerCamelCase__      ( __A    :Optional[int]	,__A    :int=5		):


       """simple docstring"""




       __snake_case       	=							["""auto-generated""", """autogenerated""", """automatically generated"""]
       __snake_case       	=							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 						lowerCamelCase__      ( __A    :int	,__A    :int=5	,__A    :str=0.05		):


       """simple docstring"""




       __snake_case       	=							["""unit tests""", """test file""", """configuration file"""]
       __snake_case       	=							example["""content"""].splitlines()
       __snake_case       	=							0
       __snake_case       	=							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
       __snake_case       	=							example["""content"""].count("""\n"""		)
       __snake_case       	=							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__      ( __A    :Dict		):


       """simple docstring"""




       __snake_case       	=							["""def """, """class """, """for """, """while """]
       __snake_case       	=							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__      ( __A    :Dict	,__A    :List[str]=4		):


       """simple docstring"""




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







def 						lowerCamelCase__      ( __A    :str		):


       """simple docstring"""




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







def 						lowerCamelCase__      ( __A    :Optional[Any]		):


       """simple docstring"""




       __snake_case       	=							{}
       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 						lowerCamelCase__      ( __A    :int	,__A    :str	,__A    :Dict		):


       """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 						lowerCamelCase__      ( __A    :str		):


       """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}')

