


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


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






def 						lowercase_(    SCREAMING_SNAKE_CASE_      ):


  '''simple docstring'''

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






def 						lowercase_(    SCREAMING_SNAKE_CASE_      ):


  '''simple docstring'''

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






def 						lowercase_(    SCREAMING_SNAKE_CASE_      ):


  '''simple docstring'''

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






def 						lowercase_(    SCREAMING_SNAKE_CASE_ ,		SCREAMING_SNAKE_CASE_      ):


  '''simple docstring'''

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






def 						lowercase_(    SCREAMING_SNAKE_CASE_ ,		SCREAMING_SNAKE_CASE_=5      ):


  '''simple docstring'''

  lowerCamelCase					:   Optional[int]       =							["auto-generated", "autogenerated", "automatically generated"]
  lowerCamelCase					:   int       =							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 						lowercase_(    SCREAMING_SNAKE_CASE_ ,		SCREAMING_SNAKE_CASE_=5 ,		SCREAMING_SNAKE_CASE_=0.05      ):


  '''simple docstring'''

  lowerCamelCase					:   Tuple       =							["unit tests", "test file", "configuration file"]
  lowerCamelCase					:   Any       =							example["content"].splitlines()
  lowerCamelCase					:   str       =							0
  lowerCamelCase					:   int       =							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					:   Optional[int]       =							example["content"].count("\n"      )
  lowerCamelCase					:   List[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 						lowercase_(    SCREAMING_SNAKE_CASE_      ):


  '''simple docstring'''

  lowerCamelCase					:   Optional[Any]       =							["def ", "class ", "for ", "while "]
  lowerCamelCase					:   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 						lowercase_(    SCREAMING_SNAKE_CASE_ ,		SCREAMING_SNAKE_CASE_=4      ):


  '''simple docstring'''

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






def 						lowercase_(    SCREAMING_SNAKE_CASE_      ):


  '''simple docstring'''

  lowerCamelCase					:   Tuple       =							tokenizer(example["content"] ,		truncation=UpperCAmelCase__      )["input_ids"]
  lowerCamelCase					:   Union[str, Any]       =							len(example["content"]      ) / len(UpperCAmelCase__      )
  return {"ratio": ratio}






def 						lowercase_(    SCREAMING_SNAKE_CASE_      ):


  '''simple docstring'''

  lowerCamelCase					:   Union[str, Any]       =							{}
  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 						lowercase_(    SCREAMING_SNAKE_CASE_ ,		SCREAMING_SNAKE_CASE_ ,		SCREAMING_SNAKE_CASE_      ):


  '''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 						lowercase_(    SCREAMING_SNAKE_CASE_      ):


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

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

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

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

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

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

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







from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_flax_available,
    is_tf_available,
    is_tokenizers_available,
    is_torch_available,
)


__lowerCamelCase									=     {
    '''configuration_whisper''': ['''WHISPER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''WhisperConfig''', '''WhisperOnnxConfig'''],
    '''feature_extraction_whisper''': ['''WhisperFeatureExtractor'''],
    '''processing_whisper''': ['''WhisperProcessor'''],
    '''tokenization_whisper''': ['''WhisperTokenizer'''],
}

try:
      if not is_tokenizers_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      pass
else:
      __lowerCamelCase									=     ['''WhisperTokenizerFast''']

try:
      if not is_torch_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      pass
else:
      __lowerCamelCase									=     [
          '''WHISPER_PRETRAINED_MODEL_ARCHIVE_LIST''',
          '''WhisperForConditionalGeneration''',
          '''WhisperModel''',
          '''WhisperPreTrainedModel''',
          '''WhisperForAudioClassification''',
      ]

try:
      if not is_tf_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      pass
else:
      __lowerCamelCase									=     [
          '''TF_WHISPER_PRETRAINED_MODEL_ARCHIVE_LIST''',
          '''TFWhisperForConditionalGeneration''',
          '''TFWhisperModel''',
          '''TFWhisperPreTrainedModel''',
      ]

try:
      if not is_flax_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      pass
else:
      __lowerCamelCase									=     [
          '''FlaxWhisperForConditionalGeneration''',
          '''FlaxWhisperModel''',
          '''FlaxWhisperPreTrainedModel''',
          '''FlaxWhisperForAudioClassification''',
      ]


if TYPE_CHECKING:
      from .configuration_whisper import WHISPER_PRETRAINED_CONFIG_ARCHIVE_MAP, WhisperConfig, WhisperOnnxConfig
      from .feature_extraction_whisper import WhisperFeatureExtractor
      from .processing_whisper import WhisperProcessor
      from .tokenization_whisper import WhisperTokenizer

      try:
            if not is_tokenizers_available():
                  raise OptionalDependencyNotAvailable()
      except OptionalDependencyNotAvailable:
            pass
      else:
            from .tokenization_whisper_fast import WhisperTokenizerFast

      try:
            if not is_torch_available():
                  raise OptionalDependencyNotAvailable()
      except OptionalDependencyNotAvailable:
            pass
      else:
            from .modeling_whisper import (
                WHISPER_PRETRAINED_MODEL_ARCHIVE_LIST,
                WhisperForAudioClassification,
                WhisperForConditionalGeneration,
                WhisperModel,
                WhisperPreTrainedModel,
            )

      try:
            if not is_tf_available():
                  raise OptionalDependencyNotAvailable()
      except OptionalDependencyNotAvailable:
            pass
      else:
            from .modeling_tf_whisper import (
                TF_WHISPER_PRETRAINED_MODEL_ARCHIVE_LIST,
                TFWhisperForConditionalGeneration,
                TFWhisperModel,
                TFWhisperPreTrainedModel,
            )

      try:
            if not is_flax_available():
                  raise OptionalDependencyNotAvailable()
      except OptionalDependencyNotAvailable:
            pass
      else:
            from .modeling_flax_whisper import (
                FlaxWhisperForAudioClassification,
                FlaxWhisperForConditionalGeneration,
                FlaxWhisperModel,
                FlaxWhisperPreTrainedModel,
            )

else:
      import sys

      __lowerCamelCase									=     _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
