






'''simple docstring'''




import functools
import operator

from ...configuration_utils import PretrainedConfig
from ...utils import logging


__lowerCamelCase   :					Any   							=					logging.get_logger(__name__)

__lowerCamelCase   :					Optional[Any]   							=					{
    '''facebook/wav2vec2-base-960h''': '''https://huggingface.co/facebook/wav2vec2-base-960h/resolve/main/config.json''',
    # See all Wav2Vec2 models at https://huggingface.co/models?filter=wav2vec2
}







class    A_	(a_							):
							"""simple docstring"""




							a__   		=	'''wav2vec2'''

							def __init__(		self			:int       ,							lowerCAmelCase__			:Optional[Any]=32       ,							lowerCAmelCase__			:Any=768       ,							lowerCAmelCase__			:Union[str, Any]=12       ,							lowerCAmelCase__			:Dict=12       ,							lowerCAmelCase__			:Dict=3_072       ,							lowerCAmelCase__			:int="gelu"       ,							lowerCAmelCase__			:Dict=0.1       ,							lowerCAmelCase__			:str=0.1       ,							lowerCAmelCase__			:Dict=0.1       ,							lowerCAmelCase__			:Tuple=0.0       ,							lowerCAmelCase__			:List[Any]=0.0       ,							lowerCAmelCase__			:Tuple=0.1       ,							lowerCAmelCase__			:Union[str, Any]=0.1       ,							lowerCAmelCase__			:List[str]=0.0_2       ,							lowerCAmelCase__			:Union[str, Any]=1E-5       ,							lowerCAmelCase__			:List[str]="group"       ,							lowerCAmelCase__			:Tuple="gelu"       ,							lowerCAmelCase__			:str=(512, 512, 512, 512, 512, 512, 512)       ,							lowerCAmelCase__			:List[Any]=(5, 2, 2, 2, 2, 2, 2)       ,							lowerCAmelCase__			:List[Any]=(10, 3, 3, 3, 3, 2, 2)       ,							lowerCAmelCase__			:List[Any]=False       ,							lowerCAmelCase__			:Dict=128       ,							lowerCAmelCase__			:List[str]=16       ,							lowerCAmelCase__			:List[str]=False       ,							lowerCAmelCase__			:Optional[Any]=True       ,							lowerCAmelCase__			:Dict=0.0_5       ,							lowerCAmelCase__			:Tuple=10       ,							lowerCAmelCase__			:str=2       ,							lowerCAmelCase__			:List[str]=0.0       ,							lowerCAmelCase__			:Dict=10       ,							lowerCAmelCase__			:List[Any]=0       ,							lowerCAmelCase__			:Union[str, Any]=320       ,							lowerCAmelCase__			:Dict=2       ,							lowerCAmelCase__			:Optional[Any]=0.1       ,							lowerCAmelCase__			:Optional[Any]=100       ,							lowerCAmelCase__			:List[Any]=256       ,							lowerCAmelCase__			:int=256       ,							lowerCAmelCase__			:Tuple=0.1       ,							lowerCAmelCase__			:Any="sum"       ,							lowerCAmelCase__			:str=False       ,							lowerCAmelCase__			:List[str]=False       ,							lowerCAmelCase__			:int=256       ,							lowerCAmelCase__			:Dict=(512, 512, 512, 512, 1_500)       ,							lowerCAmelCase__			:List[str]=(5, 3, 3, 1, 1)       ,							lowerCAmelCase__			:Tuple=(1, 2, 3, 1, 1)       ,							lowerCAmelCase__			:str=512       ,							lowerCAmelCase__			:Any=0       ,							lowerCAmelCase__			:List[Any]=1       ,							lowerCAmelCase__			:Dict=2       ,							lowerCAmelCase__			:Dict=False       ,							lowerCAmelCase__			:str=3       ,							lowerCAmelCase__			:Any=2       ,							lowerCAmelCase__			:Union[str, Any]=3       ,							lowerCAmelCase__			:str=None       ,							lowerCAmelCase__			:Any=None       ,							**lowerCAmelCase__			:Optional[Any]       ,							)				->  Dict:


										'''simple docstring'''




										super().__init__(**lowerCAmelCase__       ,							pad_token_id=lowerCAmelCase__       ,							bos_token_id=lowerCAmelCase__       ,							eos_token_id=lowerCAmelCase__				)
										snake_case_				:					int   =       hidden_size
										snake_case_				:					List[str]   =       feat_extract_norm
										snake_case_				:					List[Any]   =       feat_extract_activation
										snake_case_				:					str   =       list(lowerCAmelCase__				)
										snake_case_				:					Union[str, Any]   =       list(lowerCAmelCase__				)
										snake_case_				:					Tuple   =       list(lowerCAmelCase__				)
										snake_case_				:					List[Any]   =       conv_bias
										snake_case_				:					List[Any]   =       num_conv_pos_embeddings
										snake_case_				:					List[Any]   =       num_conv_pos_embedding_groups
										snake_case_				:					Tuple   =       len(self.conv_dim				)
										snake_case_				:					Optional[Any]   =       num_hidden_layers
										snake_case_				:					int   =       intermediate_size
										snake_case_				:					str   =       hidden_act
										snake_case_				:					Any   =       num_attention_heads
										snake_case_				:					int   =       hidden_dropout
										snake_case_				:					List[str]   =       attention_dropout
										snake_case_				:					List[Any]   =       activation_dropout
										snake_case_				:					int   =       feat_proj_dropout
										snake_case_				:					Tuple   =       final_dropout
										snake_case_				:					int   =       layerdrop
										snake_case_				:					List[Any]   =       layer_norm_eps
										snake_case_				:					Any   =       initializer_range
										snake_case_				:					Optional[Any]   =       vocab_size
										snake_case_				:					Any   =       do_stable_layer_norm
										snake_case_				:					Dict   =       use_weighted_layer_sum

										if (
										    (len(self.conv_stride				) != self.num_feat_extract_layers)
										    or (len(self.conv_kernel				) != self.num_feat_extract_layers)
										    or (len(self.conv_dim				) != self.num_feat_extract_layers)
										):
													raise ValueError(
													    "Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` =="
													    " `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) ="
													    F''' {len(self.conv_dim				)}`, `len(config.conv_stride) = {len(self.conv_stride				)}`,'''
													    F''' `len(config.conv_kernel) = {len(self.conv_kernel				)}`.'''				)

										# fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779
										snake_case_				:					Optional[Any]   =       apply_spec_augment
										snake_case_				:					str   =       mask_time_prob
										snake_case_				:					Any   =       mask_time_length
										snake_case_				:					Dict   =       mask_time_min_masks
										snake_case_				:					Optional[int]   =       mask_feature_prob
										snake_case_				:					List[str]   =       mask_feature_length
										snake_case_				:					Union[str, Any]   =       mask_feature_min_masks

										# parameters for pretraining with codevector quantized representations
										snake_case_				:					Optional[int]   =       num_codevectors_per_group
										snake_case_				:					Union[str, Any]   =       num_codevector_groups
										snake_case_				:					Optional[int]   =       contrastive_logits_temperature
										snake_case_				:					int   =       feat_quantizer_dropout
										snake_case_				:					List[Any]   =       num_negatives
										snake_case_				:					List[Any]   =       codevector_dim
										snake_case_				:					str   =       proj_codevector_dim
										snake_case_				:					Dict   =       diversity_loss_weight

										# ctc loss
										snake_case_				:					str   =       ctc_loss_reduction
										snake_case_				:					Union[str, Any]   =       ctc_zero_infinity

										# adapter
										snake_case_				:					List[str]   =       add_adapter
										snake_case_				:					Optional[Any]   =       adapter_kernel_size
										snake_case_				:					int   =       adapter_stride
										snake_case_				:					List[str]   =       num_adapter_layers
										snake_case_				:					List[str]   =       output_hidden_size or hidden_size
										snake_case_				:					str   =       adapter_attn_dim

										# SequenceClassification-specific parameter. Feel free to ignore for other classes.
										snake_case_				:					List[Any]   =       classifier_proj_size

										# XVector-specific parameters. Feel free to ignore for other classes.
										snake_case_				:					int   =       list(lowerCAmelCase__				)
										snake_case_				:					Dict   =       list(lowerCAmelCase__				)
										snake_case_				:					Optional[int]   =       list(lowerCAmelCase__				)
										snake_case_				:					Union[str, Any]   =       xvector_output_dim






							@property
							def 							_A	(		self			:str				)				->  Dict:


										'''simple docstring'''




										return functools.reduce(operator.mul       ,							self.conv_stride       ,							1				)












'''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   :					List[str]   							=					re.compile(R'''\s+''')

def 	__UpperCAmelCase       ( __magic_name__						)->    Union[str, Any]:



			"""simple docstring"""



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

def 	__UpperCAmelCase       ( __magic_name__						)->    str:



			"""simple docstring"""



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

def 	__UpperCAmelCase       ( __magic_name__						)->    int:



			"""simple docstring"""



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

def 	__UpperCAmelCase       ( __magic_name__     ,__magic_name__						)->    Tuple:



			"""simple docstring"""



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

def 	__UpperCAmelCase       ( __magic_name__     ,__magic_name__=5						)->    Tuple:



			"""simple docstring"""



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

def 	__UpperCAmelCase       ( __magic_name__     ,__magic_name__=5     ,__magic_name__=0.05						)->    Optional[Any]:



			"""simple docstring"""



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



			"""simple docstring"""



			snake_case_				:					List[Any]   =       ["def ", "class ", "for ", "while "]
			snake_case_				:					Optional[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 	__UpperCAmelCase       ( __magic_name__     ,__magic_name__=4						)->    Optional[int]:



			"""simple docstring"""



			snake_case_				:					Tuple   =       example["content"].splitlines()
			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 	__UpperCAmelCase       ( __magic_name__						)->    List[Any]:



			"""simple docstring"""



			snake_case_				:					Tuple   =       tokenizer(example["content"]     ,truncation=__magic_name__						)["input_ids"]
			snake_case_				:					int   =       len(example["content"]						) / len(__magic_name__						)
			return {"ratio": ratio}

def 	__UpperCAmelCase       ( __magic_name__						)->    Optional[Any]:



			"""simple docstring"""



			snake_case_				:					Union[str, Any]   =       {}
			results.update(get_hash(__magic_name__						)						)
			results.update(line_stats(__magic_name__						)						)
			results.update(alpha_stats(__magic_name__						)						)
			results.update(char_token_ratio(__magic_name__						)						)
			results.update(is_autogenerated(__magic_name__						)						)
			results.update(is_config_or_test(__magic_name__						)						)
			results.update(has_no_keywords(__magic_name__						)						)
			results.update(has_few_assignments(__magic_name__						)						)
			return results

def 	__UpperCAmelCase       ( __magic_name__     ,__magic_name__     ,__magic_name__						)->    Tuple:



			"""simple docstring"""



			if not check_uniques(__magic_name__     ,__magic_name__						):
						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       ( __magic_name__						)->    Dict:



			"""simple docstring"""



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


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

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

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

# Deduplicate hashes
__lowerCamelCase   :					Any   							=					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   :					List[str]   							=					time.time()
__lowerCamelCase   :					Tuple   							=					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   :					List[str]   							=					time.time()
		__lowerCamelCase							,      __lowerCamelCase   :					Tuple   							=					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   :					List[Any]   							=					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[str]   							=					output_dir / '''data'''
data_dir.mkdir(exist_ok=True)

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




