
'''simple docstring'''






import json
import os
from typing import Optional

import numpy as np

from ...feature_extraction_utils import BatchFeature
from ...processing_utils import ProcessorMixin
from ...utils import logging
from ...utils.hub import get_file_from_repo
from ..auto import AutoTokenizer


UpperCAmelCase_       :   Dict   =       logging.get_logger(__name__)

class  UpperCAmelCase__						(       A ):
    lowerCAmelCase_				    =		'AutoTokenizer'
    lowerCAmelCase_				    =		['tokenizer']

    lowerCAmelCase_				    =		{
        'semantic_prompt': 1,
        'coarse_prompt': 2,
        'fine_prompt': 2,
    }



    def __init__(	self      :       str,__A      :       int,__A      :       int=None     ):
          super().__init__(__A     )

          _lowerCamelCase				:   Optional[Any]								=   speaker_embeddings



    @classmethod
    def   lowerCamelCase_  (	cls      :       List[Any],__A      :       List[Any],__A      :       Optional[Any]="speaker_embeddings_path.json",**__A      :       Union[str, Any]     ):

          if speaker_embeddings_dict_path is not None:
                _lowerCamelCase				:   int								=   get_file_from_repo(
                    __A,__A,subfolder=kwargs.pop("subfolder",__A     ),cache_dir=kwargs.pop("cache_dir",__A     ),force_download=kwargs.pop("force_download",__A     ),proxies=kwargs.pop("proxies",__A     ),resume_download=kwargs.pop("resume_download",__A     ),local_files_only=kwargs.pop("local_files_only",__A     ),use_auth_token=kwargs.pop("use_auth_token",__A     ),revision=kwargs.pop("revision",__A     ),)
                if speaker_embeddings_path is None:
                      logger.warning(
                          f'`{os.path.join(__A,__A     )}` does not exists\n                    , no preloaded speaker embeddings will be used - Make sure to provide a correct path to the json\n                    dictionnary if wanted, otherwise set `speaker_embeddings_dict_path=None`.'     )
                      _lowerCamelCase				:   Dict								=   None
                else:
                      with open(__A     ) as speaker_embeddings_json:
                            _lowerCamelCase				:   Union[str, Any]								=   json.load(__A     )
          else:
                _lowerCamelCase				:   Optional[int]								=   None

          _lowerCamelCase				:   Any								=   AutoTokenizer.from_pretrained(__A,**__A     )

          return cls(tokenizer=__A,speaker_embeddings=__A     )



    def   lowerCamelCase_  (	self      :       Optional[Any],__A      :       List[str],__A      :       Optional[Any]="speaker_embeddings_path.json",__A      :       int="speaker_embeddings",__A      :       bool = False,**__A      :       Tuple,):
          if self.speaker_embeddings is not None:
                os.makedirs(os.path.join(__A,__A,"v2"     ),exist_ok=__A     )

                _lowerCamelCase				:   Dict								=   {}

                _lowerCamelCase				:   Any								=   save_directory

                for prompt_key in self.speaker_embeddings:
                      if prompt_key != "repo_or_path":
                            _lowerCamelCase				:   Union[str, Any]								=   self._load_voice_preset(__A     )

                            _lowerCamelCase				:   List[str]								=   {}
                            for key in self.speaker_embeddings[prompt_key]:
                                  np.save(
                                      os.path.join(
                                          embeddings_dict["repo_or_path"],__A,f'{prompt_key}_{key}'     ),voice_preset[key],allow_pickle=__A,)
                                  _lowerCamelCase				:   List[str]								=   os.path.join(__A,f'{prompt_key}_{key}.npy'     )

                            _lowerCamelCase				:   Any								=   tmp_dict

                with open(os.path.join(__A,__A     ),"w"     ) as fp:
                      json.dump(__A,__A     )

          super().save_pretrained(__A,__A,**__A     )



    def   lowerCamelCase_  (	self      :       Any,__A      :       str = None,**__A      :       Optional[int]     ):
          _lowerCamelCase				:   Optional[int]								=   self.speaker_embeddings[voice_preset]

          _lowerCamelCase				:   int								=   {}
          for key in ["semantic_prompt", "coarse_prompt", "fine_prompt"]:
                if key not in voice_preset_paths:
                      raise ValueError(
                          f'Voice preset unrecognized, missing {key} as a key in self.speaker_embeddings[{voice_preset}].'     )

                _lowerCamelCase				:   List[str]								=   get_file_from_repo(
                    self.speaker_embeddings.get("repo_or_path","/"     ),voice_preset_paths[key],subfolder=kwargs.pop("subfolder",__A     ),cache_dir=kwargs.pop("cache_dir",__A     ),force_download=kwargs.pop("force_download",__A     ),proxies=kwargs.pop("proxies",__A     ),resume_download=kwargs.pop("resume_download",__A     ),local_files_only=kwargs.pop("local_files_only",__A     ),use_auth_token=kwargs.pop("use_auth_token",__A     ),revision=kwargs.pop("revision",__A     ),)
                if path is None:
                      raise ValueError(
                          f'`{os.path.join(self.speaker_embeddings.get("repo_or_path","/"     ),voice_preset_paths[key]     )}` does not exists\n                    , no preloaded voice preset will be used - Make sure to provide correct paths to the {voice_preset}\n                    embeddings.'     )

                _lowerCamelCase				:   int								=   np.load(__A     )

          return voice_preset_dict



    def   lowerCamelCase_  (	self      :       Any,__A      :       Optional[dict] = None     ):
          for key in ["semantic_prompt", "coarse_prompt", "fine_prompt"]:
                if key not in voice_preset:
                      raise ValueError(f'Voice preset unrecognized, missing {key} as a key.'     )

                if not isinstance(voice_preset[key],np.ndarray     ):
                      raise ValueError(f'{key} voice preset must be a {str(self.preset_shape[key]     )}D ndarray.'     )

                if len(voice_preset[key].shape     ) != self.preset_shape[key]:
                      raise ValueError(f'{key} voice preset must be a {str(self.preset_shape[key]     )}D ndarray.'     )



    def __call__(	self      :       Tuple,__A      :       List[Any]=None,__A      :       Optional[int]=None,__A      :       str="pt",__A      :       Tuple=2_5_6,__A      :       Dict=False,__A      :       List[Any]=True,__A      :       Dict=False,**__A      :       Tuple,):
          if voice_preset is not None and not isinstance(__A,__A     ):
                if (
                    isinstance(__A,__A     )
                    and self.speaker_embeddings is not None
                    and voice_preset in self.speaker_embeddings
                ):
                      _lowerCamelCase				:   Optional[Any]								=   self._load_voice_preset(__A     )

                else:
                      if isinstance(__A,__A     ) and not voice_preset.endswith(".npz"     ):
                            _lowerCamelCase				:   List[str]								=   voice_preset + ".npz"

                      _lowerCamelCase				:   List[Any]								=   np.load(__A     )

          if voice_preset is not None:
                self._validate_voice_preset_dict(__A,**__A     )
                _lowerCamelCase				:   List[str]								=   BatchFeature(data=__A,tensor_type=__A     )

          _lowerCamelCase				:   Dict								=   self.tokenizer(
              __A,return_tensors=__A,padding="max_length",max_length=__A,return_attention_mask=__A,return_token_type_ids=__A,add_special_tokens=__A,**__A,)

          if voice_preset is not None:
                _lowerCamelCase				:   Any								=   voice_preset

          return encoded_text

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


UpperCAmelCase_       :   Any   =       re.compile(R'\s+')







def 		A_       (	_lowerCAmelCase   :    List[str]							):



      """simple docstring"""




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







def 		A_       (	_lowerCAmelCase   :    Union[str, Any]							):



      """simple docstring"""




      _lowerCamelCase				:   Union[str, Any]								=   [len(_lowerCAmelCase							) for line in example["content"].splitlines()]
      return {"line_mean": np.mean(_lowerCAmelCase							), "line_max": max(_lowerCAmelCase							)}







def 		A_       (	_lowerCAmelCase   :    int							):



      """simple docstring"""




      _lowerCamelCase				:   Union[str, Any]								=   np.mean([c.isalnum() for c in example["content"]]							)
      return {"alpha_frac": alpha_frac}







def 		A_       (	_lowerCAmelCase   :    str				,	_lowerCAmelCase   :    Tuple							):



      """simple docstring"""




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







def 		A_       (	_lowerCAmelCase   :    Optional[int]				,	_lowerCAmelCase   :    Dict=5							):



      """simple docstring"""




      _lowerCamelCase				:   Optional[int]								=   ["auto-generated", "autogenerated", "automatically generated"]
      _lowerCamelCase				:   Dict								=   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 		A_       (	_lowerCAmelCase   :    List[str]				,	_lowerCAmelCase   :    Optional[Any]=5				,	_lowerCAmelCase   :    List[Any]=0.0_5							):



      """simple docstring"""




      _lowerCamelCase				:   Union[str, Any]								=   ["unit tests", "test file", "configuration file"]
      _lowerCamelCase				:   int								=   example["content"].splitlines()
      _lowerCamelCase				:   int								=   0
      _lowerCamelCase				:   Optional[Any]								=   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
      _lowerCamelCase				:   Union[str, Any]								=   example["content"].count("\n"							)
      _lowerCamelCase				:   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 		A_       (	_lowerCAmelCase   :    int							):



      """simple docstring"""




      _lowerCamelCase				:   str								=   ["def ", "class ", "for ", "while "]
      _lowerCamelCase				:   List[str]								=   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_       (	_lowerCAmelCase   :    Dict				,	_lowerCAmelCase   :    int=4							):



      """simple docstring"""




      _lowerCamelCase				:   List[Any]								=   example["content"].splitlines()
      _lowerCamelCase				:   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_       (	_lowerCAmelCase   :    List[str]							):



      """simple docstring"""




      _lowerCamelCase				:   List[Any]								=   tokenizer(example["content"]				,	truncation=_lowerCAmelCase							)["input_ids"]
      _lowerCamelCase				:   str								=   len(example["content"]							) / len(_lowerCAmelCase							)
      return {"ratio": ratio}







def 		A_       (	_lowerCAmelCase   :    Optional[Any]							):



      """simple docstring"""




      _lowerCamelCase				:   Optional[Any]								=   {}
      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 		A_       (	_lowerCAmelCase   :    Union[str, Any]				,	_lowerCAmelCase   :    Optional[Any]				,	_lowerCAmelCase   :    str							):



      """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 		A_       (	_lowerCAmelCase   :    int							):



      """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
UpperCAmelCase_       :   Any   =       HfArgumentParser(PreprocessingArguments)
UpperCAmelCase_       :   Optional[int]   =       parser.parse_args()
if args.num_workers is None:
 UpperCAmelCase_       :   str   =       multiprocessing.cpu_count()
UpperCAmelCase_       :   Tuple   =       AutoTokenizer.from_pretrained(args.tokenizer_dir)

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

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

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

# Deduplicate data and apply heuristics
UpperCAmelCase_       :   Optional[int]   =       time.time()
UpperCAmelCase_       :   int   =       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:
 UpperCAmelCase_       :   Tuple   =       time.time()
 UpperCAmelCase_,   UpperCAmelCase_       :   List[str]   =       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
UpperCAmelCase_       :   List[str]   =       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)

UpperCAmelCase_       :   List[Any]   =       output_dir / 'data'
data_dir.mkdir(exist_ok=True)

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