
'''simple docstring'''







from typing import List, Optional, Union

import numpy as np
import tensorflow as tf

from .utils import logging


__lowerCAmelCase         =    logging.get_logger(__name__)





def 					UpperCAmelCase_		(__a      :    Union[tf.Tensor, np.ndarray] ):






   """simple docstring"""

   if isinstance(__a ,	np.ndarray ):
      return list(tensor.shape )

   _a				:	Optional[int]			=   tf.shape(__a )

   if tensor.shape == tf.TensorShape(__a ):
      return dynamic

   _a				:	Any			=   tensor.shape.as_list()

   return [dynamic[i] if s is None else s for i, s in enumerate(__a )]





def 					UpperCAmelCase_		(__a      :    tf.Tensor ,	__a      :    Optional[int] = None ,	__a      :    Optional[str] = None ):






   """simple docstring"""

   return tf.nn.softmax(logits=logits + 1e-9 ,	axis=__a ,	name=__a )





def 					UpperCAmelCase_		(__a      :    Optional[int] ,	__a      :    Tuple ,	__a      :    Optional[Any] ,	__a      :    Optional[Any]=1e-5 ,	__a      :    Any=-1 ):






   """simple docstring"""

   if weight.shape.rank != 1 or bias.shape.rank != 1 or not isinstance(__a ,	__a ):
      raise NotImplementedError('Only 1D weight and bias tensors are supported for now, with only a single axis.' )

   # Get mean and variance on the axis to be normalized
   _a,  _a				:	Tuple			=   tf.nn.moments(__a ,	axes=[axis] ,	keepdims=__a )

   if axis != -1:
      # Reshape scale and weight to have the same rank as inputs, but with 1 dimensions
      # on every dimension except axis
      _a				:	int			=   [1] * inputs.shape.rank
      _a				:	List[Any]			=   shape_list(__a )[axis]
      _a				:	Dict			=   tf.reshape(__a ,	__a )
      _a				:	str			=   tf.reshape(__a ,	__a )

   # Compute layer normalization using the batch_normalization
   # function.
   _a				:	List[str]			=   tf.nn.batch_normalization(
       __a ,	__a ,	__a ,	offset=__a ,	scale=__a ,	variance_epsilon=__a ,	)
   return outputs





def 					UpperCAmelCase_		(__a      :    Optional[Any] ,	__a      :    List[str]=0 ,	__a      :    Tuple=-1 ):






   """simple docstring"""

   if end_dim < 0:
      end_dim += input.shape.rank
   if start_dim < 0:
      start_dim += input.shape.rank

   if start_dim == end_dim:
      return input

   _a				:	Dict			=   tf.shape(__a )
   _a				:	List[str]			=   tf.math.reduce_prod(in_shape[start_dim : end_dim + 1] )
   _a				:	int			=   tf.concat([in_shape[:start_dim], [flattened_dim], in_shape[end_dim + 1 :]] ,	axis=0 )
   return tf.reshape(__a ,	__a )





def 					UpperCAmelCase_		(__a      :    tf.Tensor ):






   """simple docstring"""

   if not isinstance(__a ,	tf.Tensor ):
      _a				:	str			=   tf.convert_to_tensor(__a )  # Catches stray NumPy inputs
   if encoder_attention_mask.shape.rank == 3:
      _a				:	List[str]			=   encoder_attention_mask[:, None, :, :]
   if encoder_attention_mask.shape.rank == 2:
      _a				:	List[Any]			=   encoder_attention_mask[:, None, None, :]
   # T5 has a mask that can compare sequence ids, we can simulate this here with this transposition
   # Cf. https://github.com/tensorflow/mesh/blob/8d2465e9bc93129b913b5ccc6a59aa97abd96ec6/mesh_tensorflow
   # /transformer/transformer_layers.py#L270
   # encoder_extended_attention_mask = (encoder_extended_attention_mask ==
   # encoder_extended_attention_mask.transpose(-1, -2))
   _a				:	List[Any]			=   (
       tf.cast(1 ,	encoder_attention_mask.dtype ) - encoder_extended_attention_mask
   ) * encoder_extended_attention_mask.dtype.min

   return encoder_extended_attention_mask





def 					UpperCAmelCase_		(__a      :    tf.Tensor ,	__a      :    int ,	__a      :    str = "input_ids" ):






   """simple docstring"""

   tf.debugging.assert_less(
       __a ,	tf.cast(__a ,	dtype=tensor.dtype ) ,	message=(
           f"""The maximum value of {tensor_name} ({tf.math.reduce_max(__a )}) must be smaller than the embedding """
           f"""layer's input dimension ({embed_dim}). The likely cause is some problem at tokenization time."""
       ) ,	)





def 					UpperCAmelCase_		(__a      :    Tuple ,	__a      :    Union[str, Any] ,	__a      :    List[Any] ):






   """simple docstring"""

   _a				:	Tuple			=   6_4_5_1_2
   # Check that no item in `data` is larger than `HDF5_OBJECT_HEADER_LIMIT`
   # because in that case even chunking the array would not make the saving
   # possible.
   _a				:	Union[str, Any]			=   [x for x in data if len(__a ) > HDF5_OBJECT_HEADER_LIMIT]

   # Expecting this to never be true.
   if bad_attributes:
      raise RuntimeError(
          'The following attributes cannot be saved to HDF5 file because '
          f"""they are larger than {HDF5_OBJECT_HEADER_LIMIT} """
          f"""bytes: {bad_attributes}""" )

   _a				:	List[str]			=   np.asarray(__a )

   _a				:	List[Any]			=   1
   _a				:	Union[str, Any]			=   np.array_split(__a ,	__a )

   # This will never loop forever thanks to the test above.
   while any(x.nbytes > HDF5_OBJECT_HEADER_LIMIT for x in chunked_data ):
      num_chunks += 1
      _a				:	Optional[int]			=   np.array_split(__a ,	__a )

   if num_chunks > 1:
      for chunk_id, chunk_data in enumerate(__a ):
         _a				:	str			=   chunk_data
   else:
      _a				:	Optional[int]			=   data





def 					UpperCAmelCase_		(__a      :    str ,	__a      :    int ):






   """simple docstring"""

   if name in group.attrs:
      _a				:	str			=   [n.decode('utf8' ) if hasattr(__a ,	'decode' ) else n for n in group.attrs[name]]
   else:
      _a				:	Any			=   []
      _a				:	str			=   0
      while "%s%d" % (name, chunk_id) in group.attrs:
         data.extend(
             [n.decode('utf8' ) if hasattr(__a ,	'decode' ) else n for n in group.attrs['%s%d' % (name, chunk_id)]] )
         chunk_id += 1
   return data





def 					UpperCAmelCase_		(__a      :    List[Any] ):






   """simple docstring"""

   def _expand_single_ad_tensor(__a      :    Tuple ):
      if isinstance(__a ,	tf.Tensor ) and t.shape.rank == 1:
         return tf.expand_dims(__a ,	axis=-1 )
      return t

   return tf.nest.map_structure(_expand_single_ad_tensor ,	__a )





'''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         =    re.compile(r"""\s+""")





def 					UpperCAmelCase_		(__a      :    Any ):






   """simple docstring"""

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





def 					UpperCAmelCase_		(__a      :    str ):






   """simple docstring"""

   _a				:	List[str]			=   [len(__a ) for line in example['content'].splitlines()]
   return {"line_mean": np.mean(__a ), "line_max": max(__a )}





def 					UpperCAmelCase_		(__a      :    str ):






   """simple docstring"""

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





def 					UpperCAmelCase_		(__a      :    Optional[int] ,	__a      :    Any ):






   """simple docstring"""

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





def 					UpperCAmelCase_		(__a      :    int ,	__a      :    Union[str, Any]=5 ):






   """simple docstring"""

   _a				:	Optional[int]			=   ['auto-generated', 'autogenerated', 'automatically generated']
   _a				:	List[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 					UpperCAmelCase_		(__a      :    List[str] ,	__a      :    Dict=5 ,	__a      :    Tuple=0.05 ):






   """simple docstring"""

   _a				:	Optional[int]			=   ['unit tests', 'test file', 'configuration file']
   _a				:	int			=   example['content'].splitlines()
   _a				:	int			=   0
   _a				:	Dict			=   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				:	int			=   example['content'].count('\n' )
   _a				:	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_		(__a      :    Optional[int] ):






   """simple docstring"""

   _a				:	List[str]			=   ['def ', 'class ', 'for ', 'while ']
   _a				:	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 					UpperCAmelCase_		(__a      :    int ,	__a      :    Any=4 ):






   """simple docstring"""

   _a				:	List[str]			=   example['content'].splitlines()
   _a				:	Dict			=   0
   for line in lines:
      counter += line.lower().count('=' )
      if counter > minimum:
         return {"has_few_assignments": False}
   return {"has_few_assignments": True}





def 					UpperCAmelCase_		(__a      :    str ):






   """simple docstring"""

   _a				:	Optional[Any]			=   tokenizer(example['content'] ,	truncation=__a )['input_ids']
   _a				:	Optional[int]			=   len(example['content'] ) / len(__a )
   return {"ratio": ratio}





def 					UpperCAmelCase_		(__a      :    str ):






   """simple docstring"""

   _a				:	Dict			=   {}
   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 					UpperCAmelCase_		(__a      :    Any ,	__a      :    Any ,	__a      :    str ):






   """simple docstring"""

   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 					UpperCAmelCase_		(__a      :    Union[str, Any] ):






   """simple docstring"""

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

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

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

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

# Deduplicate data and apply heuristics
__lowerCAmelCase         =    time.time()
__lowerCAmelCase         =    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         =    time.time()
  __lowerCAmelCase   ,				__lowerCAmelCase         =    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         =    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         =    output_dir / """data"""
data_dir.mkdir(exist_ok=True)

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



