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


lowerCAmelCase_     =	re.compile(R'''\s+''')



def      lowerCamelCase_(__SCREAMING_SNAKE_CASE  )->    Union[str, Any]:
							return {"hash": hashlib.mda(re.sub(__SCREAMING_SNAKE_CASE     ,	""""""     ,	example["""content"""]  ).encode("""utf-8"""  )  ).hexdigest()}



def      lowerCamelCase_(__SCREAMING_SNAKE_CASE  )->    Tuple:
							_SCREAMING_SNAKE_CASE		:						Optional[Any]			  =    [len(__SCREAMING_SNAKE_CASE  ) for line in example["""content"""].splitlines()]
							return {"line_mean": np.mean(__SCREAMING_SNAKE_CASE  ), "line_max": max(__SCREAMING_SNAKE_CASE  )}



def      lowerCamelCase_(__SCREAMING_SNAKE_CASE  )->    Dict:
							_SCREAMING_SNAKE_CASE		:						List[Any]			  =    np.mean([c.isalnum() for c in example["""content"""]]  )
							return {"alpha_frac": alpha_frac}



def      lowerCamelCase_(__SCREAMING_SNAKE_CASE     ,	__SCREAMING_SNAKE_CASE  )->    List[str]:
							if example["hash"] in uniques:
														uniques.remove(example["""hash"""]  )
														return True
							else:
														return False



def      lowerCamelCase_(__SCREAMING_SNAKE_CASE     ,	__SCREAMING_SNAKE_CASE=5  )->    Any:
							_SCREAMING_SNAKE_CASE		:						Any			  =    ["""auto-generated""", """autogenerated""", """automatically generated"""]
							_SCREAMING_SNAKE_CASE		:						Union[str, Any]			  =    example["""content"""].splitlines()
							for _, line in zip(range(__SCREAMING_SNAKE_CASE  )     ,	__SCREAMING_SNAKE_CASE  ):
														for keyword in keywords:
																					if keyword in line.lower():
																												return {"autogenerated": True}
							else:
														return {"autogenerated": False}



def      lowerCamelCase_(__SCREAMING_SNAKE_CASE     ,	__SCREAMING_SNAKE_CASE=5     ,	__SCREAMING_SNAKE_CASE=0.05  )->    Optional[int]:
							_SCREAMING_SNAKE_CASE		:						List[Any]			  =    ["""unit tests""", """test file""", """configuration file"""]
							_SCREAMING_SNAKE_CASE		:						Optional[int]			  =    example["""content"""].splitlines()
							_SCREAMING_SNAKE_CASE		:						Dict			  =    0
							_SCREAMING_SNAKE_CASE		:						Union[str, Any]			  =    0
							# first test
							for _, line in zip(range(__SCREAMING_SNAKE_CASE  )     ,	__SCREAMING_SNAKE_CASE  ):
														for keyword in keywords:
																					if keyword in line.lower():
																												return {"config_or_test": True}
    # second test
							_SCREAMING_SNAKE_CASE		:						List[Any]			  =    example["""content"""].count("""\n"""  )
							_SCREAMING_SNAKE_CASE		:						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      lowerCamelCase_(__SCREAMING_SNAKE_CASE  )->    Optional[int]:
							_SCREAMING_SNAKE_CASE		:						Any			  =    ["""def """, """class """, """for """, """while """]
							_SCREAMING_SNAKE_CASE		:						List[str]			  =    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_(__SCREAMING_SNAKE_CASE     ,	__SCREAMING_SNAKE_CASE=4  )->    Dict:
							_SCREAMING_SNAKE_CASE		:						Any			  =    example["""content"""].splitlines()
							_SCREAMING_SNAKE_CASE		:						Tuple			  =    0
							for line in lines:
														counter += line.lower().count("""="""  )
														if counter > minimum:
																					return {"has_few_assignments": False}
							return {"has_few_assignments": True}



def      lowerCamelCase_(__SCREAMING_SNAKE_CASE  )->    List[Any]:
							_SCREAMING_SNAKE_CASE		:						int			  =    tokenizer(example["""content"""]     ,	truncation=__SCREAMING_SNAKE_CASE  )["""input_ids"""]
							_SCREAMING_SNAKE_CASE		:						int			  =    len(example["""content"""]  ) / len(__SCREAMING_SNAKE_CASE  )
							return {"ratio": ratio}



def      lowerCamelCase_(__SCREAMING_SNAKE_CASE  )->    str:
							_SCREAMING_SNAKE_CASE		:						List[str]			  =    {}
							results.update(get_hash(__SCREAMING_SNAKE_CASE  )  )
							results.update(line_stats(__SCREAMING_SNAKE_CASE  )  )
							results.update(alpha_stats(__SCREAMING_SNAKE_CASE  )  )
							results.update(char_token_ratio(__SCREAMING_SNAKE_CASE  )  )
							results.update(is_autogenerated(__SCREAMING_SNAKE_CASE  )  )
							results.update(is_config_or_test(__SCREAMING_SNAKE_CASE  )  )
							results.update(has_no_keywords(__SCREAMING_SNAKE_CASE  )  )
							results.update(has_few_assignments(__SCREAMING_SNAKE_CASE  )  )
							return results



def      lowerCamelCase_(__SCREAMING_SNAKE_CASE     ,	__SCREAMING_SNAKE_CASE     ,	__SCREAMING_SNAKE_CASE  )->    Optional[int]:
							if not check_uniques(__SCREAMING_SNAKE_CASE     ,	__SCREAMING_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_(__SCREAMING_SNAKE_CASE  )->    Optional[int]:
							with open(__SCREAMING_SNAKE_CASE     ,	"""rb"""  ) as f_in:
														with gzip.open(str(__SCREAMING_SNAKE_CASE  ) + """.gz"""     ,	"""wb"""     ,	compresslevel=6  ) as f_out:
																					shutil.copyfileobj(__SCREAMING_SNAKE_CASE     ,	__SCREAMING_SNAKE_CASE  )
							os.unlink(__SCREAMING_SNAKE_CASE  )


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

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

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

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

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

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

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





import unittest
from queue import Empty
from threading import Thread

from transformers import AutoTokenizer, TextIteratorStreamer, TextStreamer, is_torch_available
from transformers.testing_utils import CaptureStdout, require_torch, torch_device

from ..test_modeling_common import ids_tensor


if is_torch_available():
			import torch

			from transformers import AutoModelForCausalLM




@require_torch
class  _snake_case		(    unittest.TestCase ):







				"""simple docstring"""






				def 		_lowerCAmelCase		(      self							:							List[Any]):



											"""simple docstring"""







											_SCREAMING_SNAKE_CASE		:						Optional[Any]			  =    AutoTokenizer.from_pretrained("""hf-internal-testing/tiny-random-gpt2""")
											_SCREAMING_SNAKE_CASE		:						Optional[int]			  =    AutoModelForCausalLM.from_pretrained("""hf-internal-testing/tiny-random-gpt2""").to(_A)
											_SCREAMING_SNAKE_CASE		:						Any			  =    -1

											_SCREAMING_SNAKE_CASE		:						List[str]			  =    ids_tensor((1, 5)      ,    vocab_size=model.config.vocab_size).to(_A)
											_SCREAMING_SNAKE_CASE		:						Dict			  =    model.generate(_A      ,    max_new_tokens=1_0      ,    do_sample=_A)
											_SCREAMING_SNAKE_CASE		:						Dict			  =    tokenizer.decode(greedy_ids[0])

											with CaptureStdout() as cs:
																		_SCREAMING_SNAKE_CASE		:						Any			  =    TextStreamer(_A)
																		model.generate(_A      ,    max_new_tokens=1_0      ,    do_sample=_A      ,    streamer=_A)
											# The greedy text should be printed to stdout, except for the final "\n" in the streamer
											_SCREAMING_SNAKE_CASE		:						str			  =    cs.out[:-1]

											self.assertEqual(_A      ,    _A)





				def 		_lowerCAmelCase		(      self							:							Any):



											"""simple docstring"""







											_SCREAMING_SNAKE_CASE		:						Optional[Any]			  =    AutoTokenizer.from_pretrained("""hf-internal-testing/tiny-random-gpt2""")
											_SCREAMING_SNAKE_CASE		:						Any			  =    AutoModelForCausalLM.from_pretrained("""hf-internal-testing/tiny-random-gpt2""").to(_A)
											_SCREAMING_SNAKE_CASE		:						List[Any]			  =    -1

											_SCREAMING_SNAKE_CASE		:						str			  =    ids_tensor((1, 5)      ,    vocab_size=model.config.vocab_size).to(_A)
											_SCREAMING_SNAKE_CASE		:						Optional[Any]			  =    model.generate(_A      ,    max_new_tokens=1_0      ,    do_sample=_A)
											_SCREAMING_SNAKE_CASE		:						Any			  =    tokenizer.decode(greedy_ids[0])

											_SCREAMING_SNAKE_CASE		:						List[Any]			  =    TextIteratorStreamer(_A)
											_SCREAMING_SNAKE_CASE		:						Any			  =    {"""input_ids""": input_ids, """max_new_tokens""": 1_0, """do_sample""": False, """streamer""": streamer}
											_SCREAMING_SNAKE_CASE		:						List[Any]			  =    Thread(target=model.generate      ,    kwargs=_A)
											thread.start()
											_SCREAMING_SNAKE_CASE		:						Any			  =    """"""
											for new_text in streamer:
																		streamer_text += new_text

											self.assertEqual(_A      ,    _A)





				def 		_lowerCAmelCase		(      self							:							List[Any]):



											"""simple docstring"""







											_SCREAMING_SNAKE_CASE		:						Optional[int]			  =    AutoTokenizer.from_pretrained("""hf-internal-testing/tiny-random-gpt2""")
											_SCREAMING_SNAKE_CASE		:						Dict			  =    AutoModelForCausalLM.from_pretrained("""hf-internal-testing/tiny-random-gpt2""").to(_A)
											_SCREAMING_SNAKE_CASE		:						Any			  =    -1

											_SCREAMING_SNAKE_CASE		:						Any			  =    ids_tensor((1, 5)      ,    vocab_size=model.config.vocab_size).to(_A)
											_SCREAMING_SNAKE_CASE		:						Optional[Any]			  =    model.generate(_A      ,    max_new_tokens=1_0      ,    do_sample=_A)
											_SCREAMING_SNAKE_CASE		:						str			  =    greedy_ids[:, input_ids.shape[1] :]
											_SCREAMING_SNAKE_CASE		:						Dict			  =    tokenizer.decode(new_greedy_ids[0])

											with CaptureStdout() as cs:
																		_SCREAMING_SNAKE_CASE		:						Any			  =    TextStreamer(_A      ,    skip_prompt=_A)
																		model.generate(_A      ,    max_new_tokens=1_0      ,    do_sample=_A      ,    streamer=_A)
											# The greedy text should be printed to stdout, except for the final "\n" in the streamer
											_SCREAMING_SNAKE_CASE		:						Optional[int]			  =    cs.out[:-1]

											self.assertEqual(_A      ,    _A)





				def 		_lowerCAmelCase		(      self							:							Dict):



											"""simple docstring"""







											_SCREAMING_SNAKE_CASE		:						int			  =    AutoTokenizer.from_pretrained("""distilgpt2""")
											_SCREAMING_SNAKE_CASE		:						Optional[Any]			  =    AutoModelForCausalLM.from_pretrained("""distilgpt2""").to(_A)
											_SCREAMING_SNAKE_CASE		:						int			  =    -1

											_SCREAMING_SNAKE_CASE		:						List[str]			  =    torch.ones((1, 5)      ,    device=_A).long() * model.config.bos_token_id
											with CaptureStdout() as cs:
																		_SCREAMING_SNAKE_CASE		:						Optional[int]			  =    TextStreamer(_A      ,    skip_special_tokens=_A)
																		model.generate(_A      ,    max_new_tokens=1      ,    do_sample=_A      ,    streamer=_A)

											# The prompt contains a special token, so the streamer should not print it. As such, the output text, when
											# re-tokenized, must only contain one token
											_SCREAMING_SNAKE_CASE		:						Optional[Any]			  =    cs.out[:-1]  # Remove the final "\n"
											_SCREAMING_SNAKE_CASE		:						Tuple			  =    tokenizer(_A      ,    return_tensors="""pt""")
											self.assertEqual(streamer_text_tokenized.input_ids.shape      ,    (1, 1))





				def 		_lowerCAmelCase		(      self							:							str):



											"""simple docstring"""







											_SCREAMING_SNAKE_CASE		:						Optional[Any]			  =    AutoTokenizer.from_pretrained("""hf-internal-testing/tiny-random-gpt2""")
											_SCREAMING_SNAKE_CASE		:						List[Any]			  =    AutoModelForCausalLM.from_pretrained("""hf-internal-testing/tiny-random-gpt2""").to(_A)
											_SCREAMING_SNAKE_CASE		:						Tuple			  =    -1

											_SCREAMING_SNAKE_CASE		:						Dict			  =    ids_tensor((1, 5)      ,    vocab_size=model.config.vocab_size).to(_A)
											_SCREAMING_SNAKE_CASE		:						int			  =    TextIteratorStreamer(_A      ,    timeout=0.001)
											_SCREAMING_SNAKE_CASE		:						List[Any]			  =    {"""input_ids""": input_ids, """max_new_tokens""": 1_0, """do_sample""": False, """streamer""": streamer}
											_SCREAMING_SNAKE_CASE		:						List[str]			  =    Thread(target=model.generate      ,    kwargs=_A)
											thread.start()

											# The streamer will timeout after 0.001 seconds, so an exception will be raised
											with self.assertRaises(_A):
																		_SCREAMING_SNAKE_CASE		:						str			  =    """"""
																		for new_text in streamer:
																									streamer_text += new_text


