




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


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







def 			lowerCamelCase_		(       UpperCamelCase__				:      Optional[int]      )     ->       Any:





				"""simple docstring"""


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







def 			lowerCamelCase_		(       UpperCamelCase__				:      List[Any]      )     ->       Union[str, Any]:





				"""simple docstring"""


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







def 			lowerCamelCase_		(       UpperCamelCase__				:      Optional[Any]      )     ->       List[Any]:





				"""simple docstring"""


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







def 			lowerCamelCase_		(       UpperCamelCase__				:      List[str] ,     UpperCamelCase__				:      Tuple      )     ->       Optional[Any]:





				"""simple docstring"""


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







def 			lowerCamelCase_		(       UpperCamelCase__				:      Tuple ,     UpperCamelCase__				:      Dict=5      )     ->       List[str]:





				"""simple docstring"""


				__lowerCamelCase		       =    ['auto-generated', 'autogenerated', 'automatically generated']
				__lowerCamelCase		       =    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 			lowerCamelCase_		(       UpperCamelCase__				:      str ,     UpperCamelCase__				:      Any=5 ,     UpperCamelCase__				:      List[str]=0.05      )     ->       List[Any]:





				"""simple docstring"""


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





				"""simple docstring"""


				__lowerCamelCase		       =    ['def ', 'class ', 'for ', 'while ']
				__lowerCamelCase		       =    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_		(       UpperCamelCase__				:      Optional[Any] ,     UpperCamelCase__				:      List[Any]=4      )     ->       str:





				"""simple docstring"""


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







def 			lowerCamelCase_		(       UpperCamelCase__				:      Optional[int]      )     ->       Dict:





				"""simple docstring"""


				__lowerCamelCase		       =    tokenizer(example['content'] ,     truncation=UpperCamelCase__      )['input_ids']
				__lowerCamelCase		       =    len(example['content']      ) / len(UpperCamelCase__      )
				return {"ratio": ratio}







def 			lowerCamelCase_		(       UpperCamelCase__				:      Dict      )     ->       Tuple:





				"""simple docstring"""


				__lowerCamelCase		       =    {}
				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 			lowerCamelCase_		(       UpperCamelCase__				:      List[str] ,     UpperCamelCase__				:      str ,     UpperCamelCase__				:      Optional[Any]      )     ->       Optional[Any]:





				"""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 			lowerCamelCase_		(       UpperCamelCase__				:      int      )     ->       int:





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

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

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

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

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

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

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

import torch

from transformers import TransfoXLConfig, TransfoXLLMHeadModel, load_tf_weights_in_transfo_xl
from transformers.models.transfo_xl import tokenization_transfo_xl as data_utils
from transformers.models.transfo_xl.tokenization_transfo_xl import CORPUS_NAME, VOCAB_FILES_NAMES
from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging


logging.set_verbosity_info()

# We do this to be able to load python 2 datasets pickles
# See e.g. https://stackoverflow.com/questions/2121874/python-pickling-after-changing-a-modules-directory/2121918#2121918
__A        =    data_utils.TransfoXLTokenizer
__A        =    data_utils.TransfoXLCorpus
__A        =    data_utils
__A        =    data_utils







def 			lowerCamelCase_		(       UpperCamelCase__				:      List[str] ,     UpperCamelCase__				:      Optional[int] ,     UpperCamelCase__				:      Union[str, Any] ,     UpperCamelCase__				:      Optional[Any]      )     ->       Union[str, Any]:





				"""simple docstring"""


				if transfo_xl_dataset_file:
								# Convert a pre-processed corpus (see original TensorFlow repo)
								with open(UpperCamelCase__ ,     'rb'      ) as fp:
												__lowerCamelCase		       =    pickle.load(UpperCamelCase__ ,     encoding='latin1'      )
								# Save vocabulary and dataset cache as Dictionaries (should be better than pickles for the long-term)
								__lowerCamelCase		       =    pytorch_dump_folder_path + '/' + VOCAB_FILES_NAMES['pretrained_vocab_file']
								print(F"""Save vocabulary to {pytorch_vocab_dump_path}"""      )
								__lowerCamelCase		       =    corpus.vocab.__dict__
								torch.save(UpperCamelCase__ ,     UpperCamelCase__      )

								__lowerCamelCase		       =    corpus.__dict__
								corpus_dict_no_vocab.pop('vocab' ,     UpperCamelCase__      )
								__lowerCamelCase		       =    pytorch_dump_folder_path + '/' + CORPUS_NAME
								print(F"""Save dataset to {pytorch_dataset_dump_path}"""      )
								torch.save(UpperCamelCase__ ,     UpperCamelCase__      )

				if tf_checkpoint_path:
								# Convert a pre-trained TensorFlow model
								__lowerCamelCase		       =    os.path.abspath(UpperCamelCase__      )
								__lowerCamelCase		       =    os.path.abspath(UpperCamelCase__      )

								print(F"""Converting Transformer XL checkpoint from {tf_path} with config at {config_path}."""      )
								# Initialise PyTorch model
								if transfo_xl_config_file == "":
												__lowerCamelCase		       =    TransfoXLConfig()
								else:
												__lowerCamelCase		       =    TransfoXLConfig.from_json_file(UpperCamelCase__      )
								print(F"""Building PyTorch model from configuration: {config}"""      )
								__lowerCamelCase		       =    TransfoXLLMHeadModel(UpperCamelCase__      )

								__lowerCamelCase		       =    load_tf_weights_in_transfo_xl(UpperCamelCase__ ,     UpperCamelCase__ ,     UpperCamelCase__      )
								# Save pytorch-model
								__lowerCamelCase		       =    os.path.join(UpperCamelCase__ ,     UpperCamelCase__      )
								__lowerCamelCase		       =    os.path.join(UpperCamelCase__ ,     UpperCamelCase__      )
								print(F"""Save PyTorch model to {os.path.abspath(UpperCamelCase__      )}"""      )
								torch.save(model.state_dict() ,     UpperCamelCase__      )
								print(F"""Save configuration file to {os.path.abspath(UpperCamelCase__      )}"""      )
								with open(UpperCamelCase__ ,     'w' ,     encoding='utf-8'      ) as f:
												f.write(config.to_json_string()      )


if __name__ == "__main__":
					__A        =    argparse.ArgumentParser()
					parser.add_argument(
					    "--pytorch_dump_folder_path",
					    default=None,
					    type=str,
					    required=True,
					    help="Path to the folder to store the PyTorch model or dataset/vocab.",
					)
					parser.add_argument(
					    "--tf_checkpoint_path",
					    default="",
					    type=str,
					    help="An optional path to a TensorFlow checkpoint path to be converted.",
					)
					parser.add_argument(
					    "--transfo_xl_config_file",
					    default="",
					    type=str,
					    help=(
					        "An optional config json file corresponding to the pre-trained BERT model. \n"
					        "This specifies the model architecture."
					    ),
					)
					parser.add_argument(
					    "--transfo_xl_dataset_file",
					    default="",
					    type=str,
					    help="An optional dataset file to be converted in a vocabulary.",
					)
					__A        =    parser.parse_args()
					convert_transfo_xl_checkpoint_to_pytorch(
					    args.tf_checkpoint_path,
					    args.transfo_xl_config_file,
					    args.pytorch_dump_folder_path,
					    args.transfo_xl_dataset_file,
					)


