





'''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 : Optional[Any]											=			re.compile(r"\s+")







def 							UpperCAmelCase_    (	lowerCAmelCase_							):

				"""simple docstring"""






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







def 							UpperCAmelCase_    (	lowerCAmelCase_							):

				"""simple docstring"""






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







def 							UpperCAmelCase_    (	lowerCAmelCase_							):

				"""simple docstring"""






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







def 							UpperCAmelCase_    (	lowerCAmelCase_		,							lowerCAmelCase_							):

				"""simple docstring"""






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







def 							UpperCAmelCase_    (	lowerCAmelCase_		,							lowerCAmelCase_=5							):

				"""simple docstring"""






				lowercase         = ["auto-generated", "autogenerated", "automatically generated"]
				lowercase         = example["content"].splitlines()
				for _, line in zip(range(lowerCAmelCase_							)		,							lowerCAmelCase_							):
								for keyword in keywords:
												if keyword in line.lower():
																return {"autogenerated": True}
				else:
								return {"autogenerated": False}







def 							UpperCAmelCase_    (	lowerCAmelCase_		,							lowerCAmelCase_=5		,							lowerCAmelCase_=0.05							):

				"""simple docstring"""






				lowercase         = ["unit tests", "test file", "configuration file"]
				lowercase         = example["content"].splitlines()
				lowercase         = 0
				lowercase         = 0
				# first test
				for _, line in zip(range(lowerCAmelCase_							)		,							lowerCAmelCase_							):
								for keyword in keywords:
												if keyword in line.lower():
																return {"config_or_test": True}
    # second test
				lowercase         = example["content"].count("\n"							)
				lowercase         = 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 							UpperCAmelCase_    (	lowerCAmelCase_							):

				"""simple docstring"""






				lowercase         = ["def ", "class ", "for ", "while "]
				lowercase         = 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 							UpperCAmelCase_    (	lowerCAmelCase_		,							lowerCAmelCase_=4							):

				"""simple docstring"""






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







def 							UpperCAmelCase_    (	lowerCAmelCase_							):

				"""simple docstring"""






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







def 							UpperCAmelCase_    (	lowerCAmelCase_							):

				"""simple docstring"""






				lowercase         = {}
				results.update(get_hash(lowerCAmelCase_							)							)
				results.update(line_stats(lowerCAmelCase_							)							)
				results.update(alpha_stats(lowerCAmelCase_							)							)
				results.update(char_token_ratio(lowerCAmelCase_							)							)
				results.update(is_autogenerated(lowerCAmelCase_							)							)
				results.update(is_config_or_test(lowerCAmelCase_							)							)
				results.update(has_no_keywords(lowerCAmelCase_							)							)
				results.update(has_few_assignments(lowerCAmelCase_							)							)
				return results







def 							UpperCAmelCase_    (	lowerCAmelCase_		,							lowerCAmelCase_		,							lowerCAmelCase_							):

				"""simple docstring"""






				if not check_uniques(lowerCAmelCase_		,							lowerCAmelCase_							):
								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 							UpperCAmelCase_    (	lowerCAmelCase_							):

				"""simple docstring"""






				with open(lowerCAmelCase_		,							"rb"							) as f_in:
								with gzip.open(str(lowerCAmelCase_							) + ".gz"		,							"wb"		,							compresslevel=6							) as f_out:
												shutil.copyfileobj(lowerCAmelCase_		,							lowerCAmelCase_							)
				os.unlink(lowerCAmelCase_							)


# Settings
__lowerCamelCase : Tuple											=			HfArgumentParser(PreprocessingArguments)
__lowerCamelCase : str											=			parser.parse_args()
if args.num_workers is None:
			__lowerCamelCase : int											=			multiprocessing.cpu_count()
__lowerCamelCase : List[str]											=			AutoTokenizer.from_pretrained(args.tokenizer_dir)

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

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

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

# Deduplicate data and apply heuristics
__lowerCamelCase : str											=			time.time()
__lowerCamelCase : List[str]											=			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 : str											=			time.time()
			__lowerCamelCase				,    __lowerCamelCase : Optional[Any]											=			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 : Dict											=			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 : List[Any]											=			output_dir / "data"
data_dir.mkdir(exist_ok=True)

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

from .evaluate import evaluate


__lowerCamelCase : Optional[Any]											=			"\\n@inproceedings{Rajpurkar2016SQuAD10,\n  title={SQuAD: 100, 000+ Questions for Machine Comprehension of Text},\n  author={Pranav Rajpurkar and Jian Zhang and Konstantin Lopyrev and Percy Liang},\n  booktitle={EMNLP},\n  year={2016}\n}\n"

__lowerCamelCase : Any											=			"\nThis metric wrap the official scoring script for version 1 of the Stanford Question Answering Dataset (SQuAD).\n\nStanford Question Answering Dataset (SQuAD) is a reading comprehension dataset, consisting of questions posed by\ncrowdworkers on a set of Wikipedia articles, where the answer to every question is a segment of text, or span,\nfrom the corresponding reading passage, or the question might be unanswerable.\n"

__lowerCamelCase : Union[str, Any]											=			"\nComputes SQuAD scores (F1 and EM).\nArgs:\n    predictions: List of question-answers dictionaries with the following key-values:\n        - 'id': id of the question-answer pair as given in the references (see below)\n        - 'prediction_text': the text of the answer\n    references: List of question-answers dictionaries with the following key-values:\n        - 'id': id of the question-answer pair (see above),\n        - 'answers': a Dict in the SQuAD dataset format\n            {\n                'text': list of possible texts for the answer, as a list of strings\n                'answer_start': list of start positions for the answer, as a list of ints\n            }\n            Note that answer_start values are not taken into account to compute the metric.\nReturns:\n    'exact_match': Exact match (the normalized answer exactly match the gold answer)\n    'f1': The F-score of predicted tokens versus the gold answer\nExamples:\n\n    >>> predictions = [{'prediction_text': '1976', 'id': '56e10a3be3433e1400422b22'}]\n    >>> references = [{'answers': {'answer_start': [97], 'text': ['1976']}, 'id': '56e10a3be3433e1400422b22'}]\n    >>> squad_metric = datasets.load_metric(\"squad\")\n    >>> results = squad_metric.compute(predictions=predictions, references=references)\n    >>> print(results)\n    {'exact_match': 100.0, 'f1': 100.0}\n"

@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION			,       _KWARGS_DESCRIPTION  )
class       UpperCAmelCase (						datasets.Metric  ):




		def 				UpperCAmelCase__   (self      :	Union[str, Any]				)					-> Union[str, Any]:
						return datasets.MetricInfo(
						    description=_DESCRIPTION							,			citation=_CITATION							,			inputs_description=_KWARGS_DESCRIPTION							,			features=datasets.Features(
						        {
						            "predictions": {"id": datasets.Value("string"				), "prediction_text": datasets.Value("string"				)},
						            "references": {
						                "id": datasets.Value("string"				),
						                "answers": datasets.features.Sequence(
						                    {
						                        "text": datasets.Value("string"				),
						                        "answer_start": datasets.Value("int32"				),
						                    }				),
						            },
						        }				)							,			codebase_urls=["https://rajpurkar.github.io/SQuAD-explorer/"]							,			reference_urls=["https://rajpurkar.github.io/SQuAD-explorer/"]							,			)





		def 				UpperCAmelCase__   (self      :	List[str]							,			A__      :	List[Any]							,			A__      :	List[str]				)					-> str:
						lowercase         = {prediction["id"]: prediction["prediction_text"] for prediction in predictions}
						lowercase         = [
						    {
						        "paragraphs": [
						            {
						                "qas": [
						                    {
						                        "answers": [{"text": answer_text} for answer_text in ref["answers"]["text"]],
						                        "id": ref["id"],
						                    }
						                    for ref in references
						                ]
						            }
						        ]
						    }
						]
						lowercase         = evaluate(dataset=A__							,			predictions=A__				)
						return score




