



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


_lowercase								=						re.compile(r'''\s+''')






def      _A				(UpperCamelCase		:      int )  ->List[str]:



			'''simple docstring'''







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






def      _A				(UpperCamelCase		:      List[str] )  ->Dict:



			'''simple docstring'''







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






def      _A				(UpperCamelCase		:      Dict )  ->str:



			'''simple docstring'''







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






def      _A				(UpperCamelCase		:      Optional[int]      ,			UpperCamelCase		:      List[Any] )  ->Optional[Any]:



			'''simple docstring'''







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






def      _A				(UpperCamelCase		:      Dict      ,			UpperCamelCase		:      Dict=5 )  ->Tuple:



			'''simple docstring'''







			lowerCamelCase__ :      Tuple								=		["""auto-generated""", """autogenerated""", """automatically generated"""]
			lowerCamelCase__ :      Any								=		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				(UpperCamelCase		:      Tuple      ,			UpperCamelCase		:      str=5      ,			UpperCamelCase		:      Union[str, Any]=0.05 )  ->List[str]:



			'''simple docstring'''







			lowerCamelCase__ :      Optional[int]								=		["""unit tests""", """test file""", """configuration file"""]
			lowerCamelCase__ :      Tuple								=		example["""content"""].splitlines()
			lowerCamelCase__ :      List[str]								=		0
			lowerCamelCase__ :      Dict								=		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__ :      Optional[Any]								=		example["""content"""].count("""\n""" )
			lowerCamelCase__ :      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      _A				(UpperCamelCase		:      Any )  ->Optional[Any]:



			'''simple docstring'''







			lowerCamelCase__ :      Any								=		["""def """, """class """, """for """, """while """]
			lowerCamelCase__ :      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      _A				(UpperCamelCase		:      Tuple      ,			UpperCamelCase		:      List[Any]=4 )  ->Tuple:



			'''simple docstring'''







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






def      _A				(UpperCamelCase		:      Optional[Any] )  ->List[Any]:



			'''simple docstring'''







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






def      _A				(UpperCamelCase		:      Union[str, Any] )  ->List[str]:



			'''simple docstring'''







			lowerCamelCase__ :      Tuple								=		{}
			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				(UpperCamelCase		:      Union[str, Any]      ,			UpperCamelCase		:      Tuple      ,			UpperCamelCase		:      List[Any] )  ->int:



			'''simple docstring'''







			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				(UpperCamelCase		:      Any )  ->Union[str, Any]:



			'''simple docstring'''







			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
_lowercase								=						HfArgumentParser(PreprocessingArguments)
_lowercase								=						parser.parse_args()
if args.num_workers is None:
				_lowercase								=						multiprocessing.cpu_count()
_lowercase								=						AutoTokenizer.from_pretrained(args.tokenizer_dir)

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

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

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

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

_lowercase								=						output_dir / '''data'''
data_dir.mkdir(exist_ok=True)

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

import numpy as np

import transformers
from transformers import is_flax_available, is_torch_available
from transformers.testing_utils import is_pt_flax_cross_test, require_flax


if is_flax_available():
				import os

				import jax.numpy as jnp
				from jax import jit

				from transformers import AutoTokenizer, FlaxAutoModelForCausalLM
				from transformers.modeling_flax_pytorch_utils import load_flax_weights_in_pytorch_model

				_lowercase     							=						'''0.12'''  # assumed parallelism: 8


if is_torch_available():
				import torch






def      _A				(UpperCamelCase		:      Dict      ,			UpperCamelCase		:      int      ,			UpperCamelCase		:      Optional[Any]=None )  ->Optional[int]:



			'''simple docstring'''







			if rng is None:
						lowerCamelCase__ :      List[Any]								=		random.Random()

			lowerCamelCase__ :      Tuple								=		1
			for dim in shape:
						total_dims *= dim

			lowerCamelCase__ :      str								=		[]
			for _ in range(UpperCamelCase ):
						values.append(rng.randint(0      ,			vocab_size - 1 ) )

			lowerCamelCase__ :      str								=		np.array(UpperCamelCase      ,			dtype=jnp.intaa ).reshape(UpperCamelCase )

			return output






def      _A				(UpperCamelCase		:      str      ,			UpperCamelCase		:      Dict=None )  ->List[str]:



			'''simple docstring'''







			lowerCamelCase__ :      Any								=		ids_tensor(UpperCamelCase      ,			vocab_size=2      ,			rng=UpperCamelCase )
			# make sure that at least one token is attended to for each batch
			lowerCamelCase__ :      int								=		1
			return attn_mask
@require_flax
class 				__A					:
			UpperCamelCase					:List[Any]     =			None
			UpperCamelCase					:Dict     =			()





			def        _snake_case    (self				):
						lowerCamelCase__							,lowerCamelCase__ :      Dict								=		self.model_tester.prepare_config_and_inputs_for_common()

						# cut to half length & take max batch_size 3
						lowerCamelCase__ :      List[Any]								=		2
						lowerCamelCase__ :      Any								=		inputs["""input_ids"""].shape[-1] // 2
						lowerCamelCase__ :      Dict								=		inputs["""input_ids"""][:max_batch_size, :sequence_length]

						lowerCamelCase__ :      List[Any]								=		jnp.ones_like(__magic_name__				)
						lowerCamelCase__ :      Dict								=		attention_mask[:max_batch_size, :sequence_length]

						# generate max 5 tokens
						lowerCamelCase__ :      Tuple								=		input_ids.shape[-1] + 5
						if config.eos_token_id is not None and config.pad_token_id is None:
									# hack to allow generate for models such as GPT2 as is done in `generate()`
									lowerCamelCase__ :      List[Any]								=		config.eos_token_id
						return config, input_ids, attention_mask, max_length





			@is_pt_flax_cross_test
			def        _snake_case    (self				):
						lowerCamelCase__							,lowerCamelCase__							,lowerCamelCase__							,lowerCamelCase__ :      List[Any]								=		self._get_input_ids_and_config()
						lowerCamelCase__ :      Tuple								=		False
						lowerCamelCase__ :      Tuple								=		max_length
						lowerCamelCase__ :      List[Any]								=		0

						for model_class in self.all_generative_model_classes:
									lowerCamelCase__ :      List[Any]								=		model_class(__magic_name__				)

									lowerCamelCase__ :      Tuple								=		model_class.__name__[4:]  # Skip the "Flax" at the beginning
									lowerCamelCase__ :      Union[str, Any]								=		getattr(__magic_name__							,    __magic_name__				)
									lowerCamelCase__ :      Dict								=		pt_model_class(__magic_name__				).eval()
									lowerCamelCase__ :      Union[str, Any]								=		load_flax_weights_in_pytorch_model(__magic_name__							,    flax_model.params				)

									lowerCamelCase__ :      str								=		flax_model.generate(__magic_name__				).sequences
									lowerCamelCase__ :      str								=		pt_model.generate(torch.tensor(__magic_name__							,    dtype=torch.long				)				)

									if flax_generation_outputs.shape[-1] > pt_generation_outputs.shape[-1]:
												lowerCamelCase__ :      Optional[Any]								=		flax_generation_outputs[:, : pt_generation_outputs.shape[-1]]

									self.assertListEqual(pt_generation_outputs.numpy().tolist()							,    flax_generation_outputs.tolist()				)





			def        _snake_case    (self				):
						lowerCamelCase__							,lowerCamelCase__							,lowerCamelCase__							,lowerCamelCase__ :      Tuple								=		self._get_input_ids_and_config()
						lowerCamelCase__ :      Dict								=		False
						lowerCamelCase__ :      str								=		max_length

						for model_class in self.all_generative_model_classes:
									lowerCamelCase__ :      Tuple								=		model_class(__magic_name__				)

									lowerCamelCase__ :      int								=		model.generate(__magic_name__				).sequences
									self.assertEqual(generation_outputs.shape[-1]							,    __magic_name__				)

									lowerCamelCase__ :      int								=		jit(model.generate				)
									lowerCamelCase__ :      List[str]								=		jit_generate(__magic_name__				).sequences

									self.assertListEqual(generation_outputs.tolist()							,    jit_generation_outputs.tolist()				)





			def        _snake_case    (self				):
						lowerCamelCase__							,lowerCamelCase__							,lowerCamelCase__							,lowerCamelCase__ :      Union[str, Any]								=		self._get_input_ids_and_config()
						lowerCamelCase__ :      List[str]								=		True
						lowerCamelCase__ :      Dict								=		max_length

						for model_class in self.all_generative_model_classes:
									lowerCamelCase__ :      str								=		model_class(__magic_name__				)

									lowerCamelCase__ :      Dict								=		model.generate(__magic_name__				).sequences
									self.assertEqual(generation_outputs.shape[-1]							,    __magic_name__				)

									lowerCamelCase__ :      Tuple								=		jit(model.generate				)
									lowerCamelCase__ :      List[str]								=		jit_generate(__magic_name__				).sequences

									self.assertListEqual(generation_outputs.tolist()							,    jit_generation_outputs.tolist()				)





			def        _snake_case    (self				):
						lowerCamelCase__							,lowerCamelCase__							,lowerCamelCase__							,lowerCamelCase__ :      Dict								=		self._get_input_ids_and_config()
						lowerCamelCase__ :      Union[str, Any]								=		False
						lowerCamelCase__ :      Dict								=		max_length
						lowerCamelCase__ :      str								=		2

						for model_class in self.all_generative_model_classes:
									lowerCamelCase__ :      Optional[int]								=		model_class(__magic_name__				)

									lowerCamelCase__ :      Union[str, Any]								=		model.generate(__magic_name__				).sequences
									self.assertEqual(generation_outputs.shape[-1]							,    __magic_name__				)

									lowerCamelCase__ :      Dict								=		jit(model.generate				)
									lowerCamelCase__ :      Optional[int]								=		jit_generate(__magic_name__				).sequences

									self.assertListEqual(generation_outputs.tolist()							,    jit_generation_outputs.tolist()				)





			def        _snake_case    (self				):
						lowerCamelCase__							,lowerCamelCase__							,lowerCamelCase__							,lowerCamelCase__ :      int								=		self._get_input_ids_and_config()
						lowerCamelCase__ :      Dict								=		False
						lowerCamelCase__ :      List[Any]								=		max_length
						lowerCamelCase__ :      List[Any]								=		2
						lowerCamelCase__ :      List[str]								=		2

						for model_class in self.all_generative_model_classes:
									lowerCamelCase__ :      Optional[Any]								=		model_class(__magic_name__				)

									lowerCamelCase__ :      Union[str, Any]								=		model.generate(__magic_name__				).sequences
									self.assertEqual(generation_outputs.shape[0]							,    input_ids.shape[0] * config.num_return_sequences				)





			def        _snake_case    (self				):
						lowerCamelCase__							,lowerCamelCase__							,lowerCamelCase__							,lowerCamelCase__ :      Tuple								=		self._get_input_ids_and_config()
						lowerCamelCase__ :      Optional[int]								=		True
						lowerCamelCase__ :      str								=		max_length
						lowerCamelCase__ :      Optional[int]								=		0.8
						lowerCamelCase__ :      List[Any]								=		10
						lowerCamelCase__ :      int								=		0.3
						lowerCamelCase__ :      Union[str, Any]								=		1
						lowerCamelCase__ :      int								=		8
						lowerCamelCase__ :      Tuple								=		9

						for model_class in self.all_generative_model_classes:
									lowerCamelCase__ :      Optional[Any]								=		model_class(__magic_name__				)

									lowerCamelCase__ :      Any								=		model.generate(__magic_name__				).sequences
									self.assertEqual(generation_outputs.shape[-1]							,    __magic_name__				)

									lowerCamelCase__ :      Optional[int]								=		jit(model.generate				)
									lowerCamelCase__ :      List[Any]								=		jit_generate(__magic_name__				).sequences

									self.assertListEqual(generation_outputs.tolist()							,    jit_generation_outputs.tolist()				)





			def        _snake_case    (self				):
						lowerCamelCase__							,lowerCamelCase__							,lowerCamelCase__							,lowerCamelCase__ :      List[str]								=		self._get_input_ids_and_config()
						lowerCamelCase__ :      str								=		max_length
						lowerCamelCase__ :      List[str]								=		1
						lowerCamelCase__ :      Optional[int]								=		8
						lowerCamelCase__ :      Union[str, Any]								=		9

						for model_class in self.all_generative_model_classes:
									lowerCamelCase__ :      Dict								=		model_class(__magic_name__				)

									lowerCamelCase__ :      Tuple								=		model.generate(__magic_name__				).sequences
									self.assertEqual(generation_outputs.shape[-1]							,    __magic_name__				)

									lowerCamelCase__ :      Optional[int]								=		jit(model.generate				)
									lowerCamelCase__ :      Dict								=		jit_generate(__magic_name__				).sequences

									self.assertListEqual(generation_outputs.tolist()							,    jit_generation_outputs.tolist()				)





			def        _snake_case    (self				):
						lowerCamelCase__							,lowerCamelCase__							,lowerCamelCase__							,lowerCamelCase__ :      int								=		self._get_input_ids_and_config()
						lowerCamelCase__ :      Tuple								=		max_length
						lowerCamelCase__ :      Optional[int]								=		2
						lowerCamelCase__ :      Union[str, Any]								=		1
						lowerCamelCase__ :      Tuple								=		8
						lowerCamelCase__ :      Tuple								=		9

						for model_class in self.all_generative_model_classes:
									lowerCamelCase__ :      Optional[int]								=		model_class(__magic_name__				)

									lowerCamelCase__ :      List[Any]								=		model.generate(__magic_name__				).sequences
									self.assertEqual(generation_outputs.shape[-1]							,    __magic_name__				)

									lowerCamelCase__ :      List[Any]								=		jit(model.generate				)
									lowerCamelCase__ :      Union[str, Any]								=		jit_generate(__magic_name__				).sequences

									self.assertListEqual(generation_outputs.tolist()							,    jit_generation_outputs.tolist()				)





			def        _snake_case    (self				):
						lowerCamelCase__							,lowerCamelCase__							,lowerCamelCase__							,lowerCamelCase__ :      Tuple								=		self._get_input_ids_and_config()

						# pad attention mask on the left
						lowerCamelCase__ :      Any								=		attention_mask.at[(0, 0)].set(0				)

						lowerCamelCase__ :      List[str]								=		False
						lowerCamelCase__ :      str								=		max_length

						for model_class in self.all_generative_model_classes:
									lowerCamelCase__ :      Dict								=		model_class(__magic_name__				)

									lowerCamelCase__ :      List[str]								=		model.generate(__magic_name__							,    attention_mask=__magic_name__				).sequences
									self.assertEqual(generation_outputs.shape[-1]							,    __magic_name__				)

									lowerCamelCase__ :      Tuple								=		jit(model.generate				)
									lowerCamelCase__ :      Any								=		jit_generate(__magic_name__							,    attention_mask=__magic_name__				).sequences

									self.assertListEqual(generation_outputs.tolist()							,    jit_generation_outputs.tolist()				)





			def        _snake_case    (self				):
						lowerCamelCase__							,lowerCamelCase__							,lowerCamelCase__							,lowerCamelCase__ :      Optional[Any]								=		self._get_input_ids_and_config()

						# pad attention mask on the left
						lowerCamelCase__ :      Optional[Any]								=		attention_mask.at[(0, 0)].set(0				)

						lowerCamelCase__ :      int								=		True
						lowerCamelCase__ :      str								=		max_length

						for model_class in self.all_generative_model_classes:
									lowerCamelCase__ :      int								=		model_class(__magic_name__				)

									lowerCamelCase__ :      str								=		model.generate(__magic_name__							,    attention_mask=__magic_name__				).sequences
									self.assertEqual(generation_outputs.shape[-1]							,    __magic_name__				)

									lowerCamelCase__ :      List[Any]								=		jit(model.generate				)
									lowerCamelCase__ :      List[Any]								=		jit_generate(__magic_name__							,    attention_mask=__magic_name__				).sequences

									self.assertListEqual(generation_outputs.tolist()							,    jit_generation_outputs.tolist()				)





			def        _snake_case    (self				):
						lowerCamelCase__							,lowerCamelCase__							,lowerCamelCase__							,lowerCamelCase__ :      Optional[Any]								=		self._get_input_ids_and_config()

						# pad attention mask on the left
						lowerCamelCase__ :      Union[str, Any]								=		attention_mask.at[(0, 0)].set(0				)

						lowerCamelCase__ :      Tuple								=		2
						lowerCamelCase__ :      List[Any]								=		max_length

						for model_class in self.all_generative_model_classes:
									lowerCamelCase__ :      Optional[Any]								=		model_class(__magic_name__				)

									lowerCamelCase__ :      Union[str, Any]								=		model.generate(__magic_name__							,    attention_mask=__magic_name__				).sequences
									self.assertEqual(generation_outputs.shape[-1]							,    __magic_name__				)

									lowerCamelCase__ :      int								=		jit(model.generate				)
									lowerCamelCase__ :      Any								=		jit_generate(__magic_name__							,    attention_mask=__magic_name__				).sequences

									self.assertListEqual(generation_outputs.tolist()							,    jit_generation_outputs.tolist()				)







@require_flax
class 				__A					( unittest.TestCase      ):





			def        _snake_case    (self				):
						lowerCamelCase__ :      Dict								=		AutoTokenizer.from_pretrained("""hf-internal-testing/tiny-bert"""				)
						lowerCamelCase__ :      Tuple								=		FlaxAutoModelForCausalLM.from_pretrained("""hf-internal-testing/tiny-bert-flax-only"""				)

						lowerCamelCase__ :      Dict								=		"""Hello world"""
						lowerCamelCase__ :      Union[str, Any]								=		tokenizer(__magic_name__							,    return_tensors="""np"""				).input_ids

						# typos are quickly detected (the correct argument is `do_sample`)
						with self.assertRaisesRegex(__magic_name__							,    """do_samples"""				):
									model.generate(__magic_name__							,    do_samples=__magic_name__				)

						# arbitrary arguments that will not be used anywhere are also not accepted
						with self.assertRaisesRegex(__magic_name__							,    """foo"""				):
									lowerCamelCase__ :      Tuple								=		{"""foo""": """bar"""}
									model.generate(__magic_name__							,    **__magic_name__				)



