
'''simple docstring'''






from typing import Dict

import numpy as np

from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging
from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline, PipelineException


if is_tf_available():
 import tensorflow as tf

 from ..tf_utils import stable_softmax


if is_torch_available():
 import torch


UpperCAmelCase_       :   Any   =       logging.get_logger(__name__)

@add_end_docstrings(
    A						,	r'\n        top_k (`int`, defaults to 5):\n            The number of predictions to return.\n        targets (`str` or `List[str]`, *optional*):\n            When passed, the model will limit the scores to the passed targets instead of looking up in the whole\n            vocab. If the provided targets are not in the model vocab, they will be tokenized and the first resulting\n            token will be used (with a warning, and that might be slower).\n\n    '						,	)
class  UpperCAmelCase__						(       A ):



    def   lowerCamelCase_  (	self      :       Dict,__A      :       GenericTensor     ):
          if self.framework == "tf":
                _lowerCamelCase				:   Any								=   tf.where(input_ids == self.tokenizer.mask_token_id     ).numpy()
          elif self.framework == "pt":
                _lowerCamelCase				:   int								=   torch.nonzero(input_ids == self.tokenizer.mask_token_id,as_tuple=__A     )
          else:
                raise ValueError("Unsupported framework"     )
          return masked_index



    def   lowerCamelCase_  (	self      :       Dict,__A      :       GenericTensor     ):
          _lowerCamelCase				:   List[Any]								=   self.get_masked_index(__A     )
          _lowerCamelCase				:   List[Any]								=   np.prod(masked_index.shape     )
          if numel < 1:
                raise PipelineException(
                    "fill-mask",self.model.base_model_prefix,f'No mask_token ({self.tokenizer.mask_token}) found on the input',)



    def   lowerCamelCase_  (	self      :       Optional[Any],__A      :       GenericTensor     ):
          if isinstance(__A,__A     ):
                for model_input in model_inputs:
                      self._ensure_exactly_one_mask_token(model_input["input_ids"][0]     )
          else:
                for input_ids in model_inputs["input_ids"]:
                      self._ensure_exactly_one_mask_token(__A     )



    def   lowerCamelCase_  (	self      :       List[str],__A      :       Tuple,__A      :       List[Any]=None,**__A      :       str     ):
          if return_tensors is None:
                _lowerCamelCase				:   Optional[int]								=   self.framework
          _lowerCamelCase				:   List[Any]								=   self.tokenizer(__A,return_tensors=__A     )
          self.ensure_exactly_one_mask_token(__A     )
          return model_inputs



    def   lowerCamelCase_  (	self      :       List[Any],__A      :       Union[str, Any]     ):
          _lowerCamelCase				:   Any								=   self.model(**__A     )
          _lowerCamelCase				:   Optional[Any]								=   model_inputs["input_ids"]
          return model_outputs



    def   lowerCamelCase_  (	self      :       List[str],__A      :       int,__A      :       Optional[Any]=5,__A      :       int=None     ):
          # Cap top_k if there are targets
          if target_ids is not None and target_ids.shape[0] < top_k:
                _lowerCamelCase				:   str								=   target_ids.shape[0]
          _lowerCamelCase				:   int								=   model_outputs["input_ids"][0]
          _lowerCamelCase				:   int								=   model_outputs["logits"]

          if self.framework == "tf":
                _lowerCamelCase				:   Any								=   tf.where(input_ids == self.tokenizer.mask_token_id     ).numpy()[:, 0]

                _lowerCamelCase				:   List[Any]								=   outputs.numpy()

                _lowerCamelCase				:   List[str]								=   outputs[0, masked_index, :]
                _lowerCamelCase				:   Dict								=   stable_softmax(__A,axis=-1     )
                if target_ids is not None:
                      _lowerCamelCase				:   Dict								=   tf.gather_nd(tf.squeeze(__A,0     ),target_ids.reshape(-1,1     )     )
                      _lowerCamelCase				:   int								=   tf.expand_dims(__A,0     )

                _lowerCamelCase				:   Tuple								=   tf.math.top_k(__A,k=__A     )
                _lowerCamelCase				:   Union[str, Any]								=   topk.values.numpy(), topk.indices.numpy()
          else:
                _lowerCamelCase				:   List[Any]								=   torch.nonzero(input_ids == self.tokenizer.mask_token_id,as_tuple=__A     ).squeeze(-1     )
                # Fill mask pipeline supports only one ${mask_token} per sample

                _lowerCamelCase				:   List[str]								=   outputs[0, masked_index, :]
                _lowerCamelCase				:   Optional[Any]								=   logits.softmax(dim=-1     )
                if target_ids is not None:
                      _lowerCamelCase				:   List[Any]								=   probs[..., target_ids]

                _lowerCamelCase				:   Optional[int]								=   probs.topk(__A     )

          _lowerCamelCase				:   int								=   []
          _lowerCamelCase				:   Tuple								=   values.shape[0] == 1
          for i, (_values, _predictions) in enumerate(zip(values.tolist(),predictions.tolist()     )     ):
                _lowerCamelCase				:   List[Any]								=   []
                for v, p in zip(_values,_predictions     ):
                      # Copy is important since we're going to modify this array in place
                      _lowerCamelCase				:   Optional[Any]								=   input_ids.numpy().copy()
                      if target_ids is not None:
                            _lowerCamelCase				:   List[str]								=   target_ids[p].tolist()

                      _lowerCamelCase				:   Optional[int]								=   p
                      # Filter padding out:
                      _lowerCamelCase				:   Any								=   tokens[np.where(tokens != self.tokenizer.pad_token_id     )]
                      # Originally we skip special tokens to give readable output.
                      # For multi masks though, the other [MASK] would be removed otherwise
                      # making the output look odd, so we add them back
                      _lowerCamelCase				:   str								=   self.tokenizer.decode(__A,skip_special_tokens=__A     )
                      _lowerCamelCase				:   Any								=   {"score": v, "token": p, "token_str": self.tokenizer.decode([p]     ), "sequence": sequence}
                      row.append(__A     )
                result.append(__A     )
          if single_mask:
                return result[0]
          return result



    def   lowerCamelCase_  (	self      :       Optional[Any],__A      :       Tuple,__A      :       Optional[Any]=None     ):
          if isinstance(__A,__A     ):
                _lowerCamelCase				:   Tuple								=   [targets]
          try:
                _lowerCamelCase				:   Dict								=   self.tokenizer.get_vocab()
          except Exception:
                _lowerCamelCase				:   Optional[int]								=   {}
          _lowerCamelCase				:   List[str]								=   []
          for target in targets:
                _lowerCamelCase				:   Dict								=   vocab.get(__A,__A     )
                if id_ is None:
                      _lowerCamelCase				:   int								=   self.tokenizer(
                          __A,add_special_tokens=__A,return_attention_mask=__A,return_token_type_ids=__A,max_length=1,truncation=__A,)["input_ids"]
                      if len(__A     ) == 0:
                            logger.warning(
                                f'The specified target token `{target}` does not exist in the model vocabulary. '
                                "We cannot replace it with anything meaningful, ignoring it"     )
                            continue
                      _lowerCamelCase				:   List[str]								=   input_ids[0]
                      # XXX: If users encounter this pass
                      # it becomes pretty slow, so let's make sure
                      # The warning enables them to fix the input to
                      # get faster performance.
                      logger.warning(
                          f'The specified target token `{target}` does not exist in the model vocabulary. '
                          f'Replacing with `{self.tokenizer.convert_ids_to_tokens(id_     )}`.'     )
                target_ids.append(id_     )
          _lowerCamelCase				:   Any								=   list(set(__A     )     )
          if len(__A     ) == 0:
                raise ValueError("At least one target must be provided when passed."     )
          _lowerCamelCase				:   List[Any]								=   np.array(__A     )
          return target_ids



    def   lowerCamelCase_  (	self      :       str,__A      :       Any=None,__A      :       int=None     ):
          _lowerCamelCase				:   List[str]								=   {}

          if targets is not None:
                _lowerCamelCase				:   Optional[int]								=   self.get_target_ids(__A,__A     )
                _lowerCamelCase				:   Union[str, Any]								=   target_ids

          if top_k is not None:
                _lowerCamelCase				:   Optional[int]								=   top_k

          if self.tokenizer.mask_token_id is None:
                raise PipelineException(
                    "fill-mask",self.model.base_model_prefix,"The tokenizer does not define a `mask_token`."     )
          return {}, {}, postprocess_params



    def __call__(	self      :       int,__A      :       List[str],*__A      :       Dict,**__A      :       List[str]     ):
          _lowerCamelCase				:   List[str]								=   super().__call__(__A,**__A     )
          if isinstance(__A,__A     ) and len(__A     ) == 1:
                return outputs[0]
          return outputs

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