





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


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

def       __A (     a_  :Any)						->						Optional[Any]:
				return {"hash": hashlib.mda(re.sub(a_				,    ''''''				,    example['''content''']).encode('''utf-8''')).hexdigest()}

def       __A (     a_  :Dict)						->						Optional[Any]:
				__a	:  int         =					[len(a_) for line in example['''content'''].splitlines()]
				return {"line_mean": np.mean(a_), "line_max": max(a_)}

def       __A (     a_  :List[Any])						->						Any:
				__a	:  str         =					np.mean([c.isalnum() for c in example['''content''']])
				return {"alpha_frac": alpha_frac}

def       __A (     a_  :Any				,    a_  :List[str])						->						int:
				if example["hash"] in uniques:
								uniques.remove(example['''hash'''])
								return True
				else:
								return False

def       __A (     a_  :Any				,    a_  :Optional[int]=5)						->						List[Any]:
				__a	:  Optional[int]         =					['''auto-generated''', '''autogenerated''', '''automatically generated''']
				__a	:  str         =					example['''content'''].splitlines()
				for _, line in zip(range(a_)				,    a_):
								for keyword in keywords:
												if keyword in line.lower():
																return {"autogenerated": True}
				else:
								return {"autogenerated": False}

def       __A (     a_  :Optional[Any]				,    a_  :List[str]=5				,    a_  :Optional[Any]=0.0_5)						->						Any:
				__a	:  Any         =					['''unit tests''', '''test file''', '''configuration file''']
				__a	:  Any         =					example['''content'''].splitlines()
				__a	:  List[Any]         =					0
				__a	:  Any         =					0
				# first test
				for _, line in zip(range(a_)				,    a_):
								for keyword in keywords:
												if keyword in line.lower():
																return {"config_or_test": True}
    # second test
				__a	:  List[Any]         =					example['''content'''].count('''\n''')
				__a	:  Dict         =					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 (     a_  :str)						->						Optional[Any]:
				__a	:  Optional[int]         =					['''def ''', '''class ''', '''for ''', '''while ''']
				__a	:  Dict         =					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 (     a_  :Optional[int]				,    a_  :Optional[Any]=4)						->						int:
				__a	:  Dict         =					example['''content'''].splitlines()
				__a	:  Union[str, 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 (     a_  :Dict)						->						Optional[Any]:
				__a	:  Any         =					tokenizer(example['''content''']				,    truncation=a_)['''input_ids''']
				__a	:  Any         =					len(example['''content''']) / len(a_)
				return {"ratio": ratio}

def       __A (     a_  :Dict)						->						int:
				__a	:  List[str]         =					{}
				results.update(get_hash(a_))
				results.update(line_stats(a_))
				results.update(alpha_stats(a_))
				results.update(char_token_ratio(a_))
				results.update(is_autogenerated(a_))
				results.update(is_config_or_test(a_))
				results.update(has_no_keywords(a_))
				results.update(has_few_assignments(a_))
				return results

def       __A (     a_  :str				,    a_  :Tuple				,    a_  :Union[str, Any])						->						Dict:
				if not check_uniques(a_				,    a_):
								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 (     a_  :Union[str, Any])						->						Union[str, Any]:
				with open(a_				,    '''rb''') as f_in:
								with gzip.open(str(a_) + '''.gz'''				,    '''wb'''				,    compresslevel=6) as f_out:
												shutil.copyfileobj(a_				,    a_)
				os.unlink(a_)


# 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}')






"""simple docstring"""






# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from ..models.whisper import WhisperForConditionalGeneration, WhisperProcessor
from .base import PipelineTool




class 			__lowercase     (     _UpperCamelCase							):







					'''simple docstring'''




					__lowerCAmelCase					=					'''openai/whisper-base'''
					__lowerCAmelCase					=					(
					    '''This is a tool that transcribes an audio into text. It takes an input named `audio` and returns the '''
					    '''transcribed text.'''
					)
					__lowerCAmelCase					=					'''transcriber'''
					__lowerCAmelCase					=					WhisperProcessor
					__lowerCAmelCase					=					WhisperForConditionalGeneration

					__lowerCAmelCase					=					['''audio''']
					__lowerCAmelCase					=					['''text''']







					def 	_lowerCamelCase						(  self		,     _UpperCAmelCase       ):
									return self.pre_processor(_UpperCAmelCase		,     return_tensors='''pt'''       ).input_features







					def 	_lowerCamelCase						(  self		,     _UpperCAmelCase       ):
									return self.model.generate(inputs=_UpperCAmelCase       )







					def 	_lowerCamelCase						(  self		,     _UpperCAmelCase       ):
									return self.pre_processor.batch_decode(_UpperCAmelCase		,     skip_special_tokens=_UpperCAmelCase       )[0]