



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


lowercase_									=    re.compile(R"\s+")




def lowerCAmelCase    (__A):



     """simple docstring"""



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




def lowerCAmelCase    (__A):



     """simple docstring"""



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




def lowerCAmelCase    (__A):



     """simple docstring"""



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




def lowerCAmelCase    (__A    ,      __A):



     """simple docstring"""



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




def lowerCAmelCase    (__A    ,      __A=5):



     """simple docstring"""



     _a           =    ['''auto-generated''', '''autogenerated''', '''automatically generated''']
     _a           =    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 lowerCAmelCase    (__A    ,      __A=5    ,      __A=0.05):



     """simple docstring"""



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



     """simple docstring"""



     _a           =    ['''def ''', '''class ''', '''for ''', '''while ''']
     _a           =    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 lowerCAmelCase    (__A    ,      __A=4):



     """simple docstring"""



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




def lowerCAmelCase    (__A):



     """simple docstring"""



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




def lowerCAmelCase    (__A):



     """simple docstring"""



     _a           =    {}
     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 lowerCAmelCase    (__A    ,      __A    ,      __A):



     """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 lowerCAmelCase    (__A):



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

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

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

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

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

lowercase_									=    output_dir / "data"
data_dir.mkdir(exist_ok=True)

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





import json
import os
import unittest

from transformers.models.ctrl.tokenization_ctrl import VOCAB_FILES_NAMES, CTRLTokenizer

from ...test_tokenization_common import TokenizerTesterMixin






class __A     (    A  ,  unittest.TestCase		):



 '''simple docstring'''







 __lowerCamelCase       :			Union[str, Any]		=			CTRLTokenizer
 __lowerCamelCase       :			Union[str, Any]		=			False
 __lowerCamelCase       :			Any		=			False



 def    a__    (self			)       ->	Optional[int]:


      """simple docstring"""



      super().setUp()

      # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt
      _a           =    ['''adapt''', '''re@@''', '''a@@''', '''apt''', '''c@@''', '''t''', '''<unk>''']
      _a           =    dict(zip(A					,  range(len(A			)			)			)			)
      _a           =    ['''#version: 0.2''', '''a p''', '''ap t</w>''', '''r e''', '''a d''', '''ad apt</w>''', '''''']
      _a           =    {'''unk_token''': '''<unk>'''}

      _a           =    os.path.join(self.tmpdirname					,  VOCAB_FILES_NAMES['''vocab_file''']			)
      _a           =    os.path.join(self.tmpdirname					,  VOCAB_FILES_NAMES['''merges_file''']			)
      with open(self.vocab_file					,  '''w'''					,  encoding='''utf-8'''			) as fp:
           fp.write(json.dumps(A			) + '''\n'''			)
      with open(self.merges_file					,  '''w'''					,  encoding='''utf-8'''			) as fp:
           fp.write('''\n'''.join(A			)			)



 def    a__    (self					,  **A			)       ->	int:


      """simple docstring"""



      kwargs.update(self.special_tokens_map			)
      return CTRLTokenizer.from_pretrained(self.tmpdirname					,  **A			)



 def    a__    (self					,  A			)       ->	Tuple:


      """simple docstring"""



      _a           =    '''adapt react readapt apt'''
      _a           =    '''adapt react readapt apt'''
      return input_text, output_text



 def    a__    (self			)       ->	List[Any]:


      """simple docstring"""



      _a           =    CTRLTokenizer(self.vocab_file					,  self.merges_file					,  **self.special_tokens_map			)
      _a           =    '''adapt react readapt apt'''
      _a           =    '''adapt re@@ a@@ c@@ t re@@ adapt apt'''.split()
      _a           =    tokenizer.tokenize(A			)
      self.assertListEqual(A					,  A			)

      _a           =    tokens + [tokenizer.unk_token]

      _a           =    [0, 1, 2, 4, 5, 1, 0, 3, 6]
      self.assertListEqual(tokenizer.convert_tokens_to_ids(A			)					,  A			)



