
'''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__      :		Optional[Any]       							=  re.compile(R"\s+")
def    lowerCAmelCase_	(				SCREAMING_SNAKE_CASE_						)     ->     int:




   """simple docstring"""
   return {"hash": hashlib.mda(re.sub(SCREAMING_SNAKE_CASE_    ,      """"""    ,      example["""content"""]						).encode("""utf-8"""						)						).hexdigest()}
def    lowerCAmelCase_	(				SCREAMING_SNAKE_CASE_						)     ->     Union[str, Any]:




   """simple docstring"""
   _SCREAMING_SNAKE_CASE      =				[len(SCREAMING_SNAKE_CASE_						) for line in example["""content"""].splitlines()]
   return {"line_mean": np.mean(SCREAMING_SNAKE_CASE_						), "line_max": max(SCREAMING_SNAKE_CASE_						)}
def    lowerCAmelCase_	(				SCREAMING_SNAKE_CASE_						)     ->     Optional[Any]:




   """simple docstring"""
   _SCREAMING_SNAKE_CASE      =				np.mean([c.isalnum() for c in example["""content"""]]						)
   return {"alpha_frac": alpha_frac}
def    lowerCAmelCase_	(				SCREAMING_SNAKE_CASE_    ,      SCREAMING_SNAKE_CASE_						)     ->     Union[str, Any]:




   """simple docstring"""
   if example["hash"] in uniques:
      uniques.remove(example["""hash"""]						)
      return True
   else:
      return False
def    lowerCAmelCase_	(				SCREAMING_SNAKE_CASE_    ,      SCREAMING_SNAKE_CASE_=5						)     ->     Any:




   """simple docstring"""
   _SCREAMING_SNAKE_CASE      =				["""auto-generated""", """autogenerated""", """automatically generated"""]
   _SCREAMING_SNAKE_CASE      =				example["""content"""].splitlines()
   for _, line in zip(range(SCREAMING_SNAKE_CASE_						)    ,      SCREAMING_SNAKE_CASE_						):
      for keyword in keywords:
         if keyword in line.lower():
            return {"autogenerated": True}
   else:
      return {"autogenerated": False}
def    lowerCAmelCase_	(				SCREAMING_SNAKE_CASE_    ,      SCREAMING_SNAKE_CASE_=5    ,      SCREAMING_SNAKE_CASE_=0.05						)     ->     Union[str, Any]:




   """simple docstring"""
   _SCREAMING_SNAKE_CASE      =				["""unit tests""", """test file""", """configuration file"""]
   _SCREAMING_SNAKE_CASE      =				example["""content"""].splitlines()
   _SCREAMING_SNAKE_CASE      =				0
   _SCREAMING_SNAKE_CASE      =				0
   # first test
   for _, line in zip(range(SCREAMING_SNAKE_CASE_						)    ,      SCREAMING_SNAKE_CASE_						):
      for keyword in keywords:
         if keyword in line.lower():
            return {"config_or_test": True}
    # second test
   _SCREAMING_SNAKE_CASE      =				example["""content"""].count("""\n"""						)
   _SCREAMING_SNAKE_CASE      =				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_	(				SCREAMING_SNAKE_CASE_						)     ->     Union[str, Any]:




   """simple docstring"""
   _SCREAMING_SNAKE_CASE      =				["""def """, """class """, """for """, """while """]
   _SCREAMING_SNAKE_CASE      =				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_	(				SCREAMING_SNAKE_CASE_    ,      SCREAMING_SNAKE_CASE_=4						)     ->     str:




   """simple docstring"""
   _SCREAMING_SNAKE_CASE      =				example["""content"""].splitlines()
   _SCREAMING_SNAKE_CASE      =				0
   for line in lines:
      counter += line.lower().count("""="""						)
      if counter > minimum:
         return {"has_few_assignments": False}
   return {"has_few_assignments": True}
def    lowerCAmelCase_	(				SCREAMING_SNAKE_CASE_						)     ->     Tuple:




   """simple docstring"""
   _SCREAMING_SNAKE_CASE      =				tokenizer(example["""content"""]    ,      truncation=SCREAMING_SNAKE_CASE_						)["""input_ids"""]
   _SCREAMING_SNAKE_CASE      =				len(example["""content"""]						) / len(SCREAMING_SNAKE_CASE_						)
   return {"ratio": ratio}
def    lowerCAmelCase_	(				SCREAMING_SNAKE_CASE_						)     ->     Tuple:




   """simple docstring"""
   _SCREAMING_SNAKE_CASE      =				{}
   results.update(get_hash(SCREAMING_SNAKE_CASE_						)						)
   results.update(line_stats(SCREAMING_SNAKE_CASE_						)						)
   results.update(alpha_stats(SCREAMING_SNAKE_CASE_						)						)
   results.update(char_token_ratio(SCREAMING_SNAKE_CASE_						)						)
   results.update(is_autogenerated(SCREAMING_SNAKE_CASE_						)						)
   results.update(is_config_or_test(SCREAMING_SNAKE_CASE_						)						)
   results.update(has_no_keywords(SCREAMING_SNAKE_CASE_						)						)
   results.update(has_few_assignments(SCREAMING_SNAKE_CASE_						)						)
   return results
def    lowerCAmelCase_	(				SCREAMING_SNAKE_CASE_    ,      SCREAMING_SNAKE_CASE_    ,      SCREAMING_SNAKE_CASE_						)     ->     int:




   """simple docstring"""
   if not check_uniques(SCREAMING_SNAKE_CASE_    ,      SCREAMING_SNAKE_CASE_						):
      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_	(				SCREAMING_SNAKE_CASE_						)     ->     int:




   """simple docstring"""
   with open(SCREAMING_SNAKE_CASE_    ,      """rb"""						) as f_in:
      with gzip.open(str(SCREAMING_SNAKE_CASE_						) + """.gz"""    ,      """wb"""    ,      compresslevel=6						) as f_out:
         shutil.copyfileobj(SCREAMING_SNAKE_CASE_    ,      SCREAMING_SNAKE_CASE_						)
   os.unlink(SCREAMING_SNAKE_CASE_						)


# Settings
UpperCamelCase__      :		List[str]       							=  HfArgumentParser(PreprocessingArguments)
UpperCamelCase__      :		List[Any]       							=  parser.parse_args()
if args.num_workers is None:
     UpperCamelCase__      :		Optional[int]       							=  multiprocessing.cpu_count()
UpperCamelCase__      :		List[Any]       							=  AutoTokenizer.from_pretrained(args.tokenizer_dir)

# Load dataset
UpperCamelCase__      :		Union[str, Any]       							=  time.time()
UpperCamelCase__      :		Optional[Any]       							=  load_dataset(args.dataset_name, split="train")
print(f"""Time to load dataset: {time.time()-t_start:.2f}""")

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

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

# Deduplicate data and apply heuristics
UpperCamelCase__      :		Optional[Any]       							=  time.time()
UpperCamelCase__      :		Tuple       							=  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__      :		Optional[int]       							=  time.time()
     UpperCamelCase__							,      UpperCamelCase__      :		List[Any]       							=  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__      :		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__      :		Tuple       							=  output_dir / "data"
data_dir.mkdir(exist_ok=True)

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








'''simple docstring'''



import numpy as np
import torch
from torch.utils.data import Dataset

from utils import logger

class    _a				(_lowerCamelCase):





       """simple docstring"""




       def __init__(							self       ,							A__       ,							A__      )    ->			Any:
          _SCREAMING_SNAKE_CASE      =				params

          _SCREAMING_SNAKE_CASE      =				np.array(A__      )
          _SCREAMING_SNAKE_CASE      =				np.array([len(A__      ) for t in data]      )

          self.check()
          self.remove_long_sequences()
          self.remove_empty_sequences()
          self.remove_unknown_sequences()
          self.check()
          self.print_statistics()






       def __getitem__(							self       ,							A__      )    ->			Dict:
          return (self.token_ids[index], self.lengths[index])






       def __len__(							self      )    ->			Tuple:
          return len(self.lengths      )






       def        UpperCamelCase				(							self      )    ->			Dict:
          assert len(self.token_ids      ) == len(self.lengths      )
          assert all(self.lengths[i] == len(self.token_ids[i]      ) for i in range(len(self.lengths      )      )      )






       def        UpperCamelCase				(							self      )    ->			List[str]:
          _SCREAMING_SNAKE_CASE      =				self.params.max_model_input_size
          _SCREAMING_SNAKE_CASE      =				self.lengths > max_len
          logger.info(F"Splitting {sum(A__      )} too long sequences."      )

          def divide_chunks(A__       ,							A__      ):
             return [l[i : i + n] for i in range(0       ,							len(A__      )       ,							A__      )]

          _SCREAMING_SNAKE_CASE      =				[]
          _SCREAMING_SNAKE_CASE      =				[]
          if self.params.mlm:
             _SCREAMING_SNAKE_CASE ,							_SCREAMING_SNAKE_CASE      =				self.params.special_tok_ids["""cls_token"""], self.params.special_tok_ids["""sep_token"""]
          else:
             _SCREAMING_SNAKE_CASE ,							_SCREAMING_SNAKE_CASE      =				self.params.special_tok_ids["""bos_token"""], self.params.special_tok_ids["""eos_token"""]

          for seq_, len_ in zip(self.token_ids       ,							self.lengths      ):
             assert (seq_[0] == cls_id) and (seq_[-1] == sep_id), seq_
             if len_ <= max_len:
                new_tok_ids.append(seq_      )
                new_lengths.append(len_      )
             else:
                _SCREAMING_SNAKE_CASE      =				[]
                for sub_s in divide_chunks(seq_       ,							max_len - 2      ):
                   if sub_s[0] != cls_id:
                      _SCREAMING_SNAKE_CASE      =				np.insert(A__       ,							0       ,							A__      )
                   if sub_s[-1] != sep_id:
                      _SCREAMING_SNAKE_CASE      =				np.insert(A__       ,							len(A__      )       ,							A__      )
                   assert len(A__      ) <= max_len
                   assert (sub_s[0] == cls_id) and (sub_s[-1] == sep_id), sub_s
                   sub_seqs.append(A__      )

                new_tok_ids.extend(A__      )
                new_lengths.extend([len(A__      ) for l in sub_seqs]      )

          _SCREAMING_SNAKE_CASE      =				np.array(A__      )
          _SCREAMING_SNAKE_CASE      =				np.array(A__      )






       def        UpperCamelCase				(							self      )    ->			List[str]:
          _SCREAMING_SNAKE_CASE      =				len(self      )
          _SCREAMING_SNAKE_CASE      =				self.lengths > 11
          _SCREAMING_SNAKE_CASE      =				self.token_ids[indices]
          _SCREAMING_SNAKE_CASE      =				self.lengths[indices]
          _SCREAMING_SNAKE_CASE      =				len(self      )
          logger.info(F"Remove {init_size - new_size} too short (<=11 tokens) sequences."      )






       def        UpperCamelCase				(							self      )    ->			int:
          if "unk_token" not in self.params.special_tok_ids:
             return
          else:
             _SCREAMING_SNAKE_CASE      =				self.params.special_tok_ids["""unk_token"""]
          _SCREAMING_SNAKE_CASE      =				len(self      )
          _SCREAMING_SNAKE_CASE      =				np.array([np.count_nonzero(a == unk_token_id      ) for a in self.token_ids]      )
          _SCREAMING_SNAKE_CASE      =				(unk_occs / self.lengths) < 0.5
          _SCREAMING_SNAKE_CASE      =				self.token_ids[indices]
          _SCREAMING_SNAKE_CASE      =				self.lengths[indices]
          _SCREAMING_SNAKE_CASE      =				len(self      )
          logger.info(F"Remove {init_size - new_size} sequences with a high level of unknown tokens (50%)."      )






       def        UpperCamelCase				(							self      )    ->			Optional[Any]:
          if not self.params.is_master:
             return
          logger.info(F"{len(self      )} sequences"      )
          # data_len = sum(self.lengths)
          # nb_unique_tokens = len(Counter(list(chain(*self.token_ids))))
          # logger.info(f'{data_len} tokens ({nb_unique_tokens} unique)')

          # unk_idx = self.params.special_tok_ids['unk_token']
          # nb_unknown = sum([(t==unk_idx).sum() for t in self.token_ids])
          # logger.info(f'{nb_unknown} unknown tokens (covering {100*nb_unknown/data_len:.2f}% of the data)')






       def        UpperCamelCase				(							self       ,							A__      )    ->			Any:
          _SCREAMING_SNAKE_CASE      =				[t[0] for t in batch]
          _SCREAMING_SNAKE_CASE      =				[t[1] for t in batch]
          assert len(A__      ) == len(A__      )

          # Max for paddings
          _SCREAMING_SNAKE_CASE      =				max(A__      )

          # Pad token ids
          if self.params.mlm:
             _SCREAMING_SNAKE_CASE      =				self.params.special_tok_ids["""pad_token"""]
          else:
             _SCREAMING_SNAKE_CASE      =				self.params.special_tok_ids["""unk_token"""]
          _SCREAMING_SNAKE_CASE      =				[list(t.astype(A__      )      ) + [pad_idx] * (max_seq_len_ - len(A__      )) for t in token_ids]
          assert len(tk_      ) == len(A__      )
          assert all(len(A__      ) == max_seq_len_ for t in tk_      )

          _SCREAMING_SNAKE_CASE      =				torch.tensor(tk_      )  # (bs, max_seq_len_)
          _SCREAMING_SNAKE_CASE      =				torch.tensor(A__      )  # (bs)
          return tk_t, lg_t






