

'''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__     (   UpperCAmelCase__					)      ->      str:
       return {"hash": hashlib.mda(re.sub(UpperCAmelCase__,							"""""",							example["""content"""]					).encode("""utf-8"""					)					).hexdigest()}
def    UpperCAmelCase__     (   UpperCAmelCase__					)      ->      Union[str, Any]:
       A_						       =   [len(UpperCAmelCase__					) for line in example["""content"""].splitlines()]
       return {"line_mean": np.mean(UpperCAmelCase__					), "line_max": max(UpperCAmelCase__					)}
def    UpperCAmelCase__     (   UpperCAmelCase__					)      ->      Any:
       A_						       =   np.mean([c.isalnum() for c in example["""content"""]]					)
       return {"alpha_frac": alpha_frac}
def    UpperCAmelCase__     (   UpperCAmelCase__,							UpperCAmelCase__					)      ->      Dict:
       if example["hash"] in uniques:
              uniques.remove(example["""hash"""]					)
              return True
       else:
              return False
def    UpperCAmelCase__     (   UpperCAmelCase__,							UpperCAmelCase__=5					)      ->      Optional[int]:
       A_						       =   ["""auto-generated""", """autogenerated""", """automatically generated"""]
       A_						       =   example["""content"""].splitlines()
       for _, line in zip(range(UpperCAmelCase__					),							UpperCAmelCase__					):
              for keyword in keywords:
                     if keyword in line.lower():
                            return {"autogenerated": True}
       else:
              return {"autogenerated": False}
def    UpperCAmelCase__     (   UpperCAmelCase__,							UpperCAmelCase__=5,							UpperCAmelCase__=0.05					)      ->      List[str]:
       A_						       =   ["""unit tests""", """test file""", """configuration file"""]
       A_						       =   example["""content"""].splitlines()
       A_						       =   0
       A_						       =   0
       # first test
       for _, line in zip(range(UpperCAmelCase__					),							UpperCAmelCase__					):
              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    UpperCAmelCase__     (   UpperCAmelCase__					)      ->      Tuple:
       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    UpperCAmelCase__     (   UpperCAmelCase__,							UpperCAmelCase__=4					)      ->      Any:
       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    UpperCAmelCase__     (   UpperCAmelCase__					)      ->      List[str]:
       A_						       =   tokenizer(example["""content"""],							truncation=UpperCAmelCase__					)["""input_ids"""]
       A_						       =   len(example["""content"""]					) / len(UpperCAmelCase__					)
       return {"ratio": ratio}
def    UpperCAmelCase__     (   UpperCAmelCase__					)      ->      Optional[Any]:
       A_						       =   {}
       results.update(get_hash(UpperCAmelCase__					)					)
       results.update(line_stats(UpperCAmelCase__					)					)
       results.update(alpha_stats(UpperCAmelCase__					)					)
       results.update(char_token_ratio(UpperCAmelCase__					)					)
       results.update(is_autogenerated(UpperCAmelCase__					)					)
       results.update(is_config_or_test(UpperCAmelCase__					)					)
       results.update(has_no_keywords(UpperCAmelCase__					)					)
       results.update(has_few_assignments(UpperCAmelCase__					)					)
       return results
def    UpperCAmelCase__     (   UpperCAmelCase__,							UpperCAmelCase__,							UpperCAmelCase__					)      ->      Tuple:
       if not check_uniques(UpperCAmelCase__,							UpperCAmelCase__					):
              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__     (   UpperCAmelCase__					)      ->      str:
       with open(UpperCAmelCase__,							"""rb"""					) as f_in:
              with gzip.open(str(UpperCAmelCase__					) + """.gz""",							"""wb""",							compresslevel=6					) as f_out:
                     shutil.copyfileobj(UpperCAmelCase__,							UpperCAmelCase__					)
       os.unlink(UpperCAmelCase__					)


# 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}""")



'''simple docstring'''







from math import pow
def    UpperCAmelCase__     (   UpperCAmelCase__,							UpperCAmelCase__,							UpperCAmelCase__,							UpperCAmelCase__,							UpperCAmelCase__,							)      ->      tuple[int, int]:
       if current_sum == needed_sum:
              # If the sum of the powers is equal to needed_sum, then we have a solution.
              solutions_count += 1
              return current_sum, solutions_count

       A_						       =   int(pow(UpperCAmelCase__,							UpperCAmelCase__					)					)
       if current_sum + i_to_n <= needed_sum:
              # If the sum of the powers is less than needed_sum, then continue adding powers.
              current_sum += i_to_n
              A_       ,      A_						       =   backtrack(
                  UpperCAmelCase__,							UpperCAmelCase__,							current_number + 1,							UpperCAmelCase__,							UpperCAmelCase__					)
              current_sum -= i_to_n
       if i_to_n < needed_sum:
              # If the power of i is less than needed_sum, then try with the next power.
              A_       ,      A_						       =   backtrack(
                  UpperCAmelCase__,							UpperCAmelCase__,							current_number + 1,							UpperCAmelCase__,							UpperCAmelCase__					)
       return current_sum, solutions_count
def    UpperCAmelCase__     (   UpperCAmelCase__,							UpperCAmelCase__					)      ->      int:
       if not (1 <= needed_sum <= 10_00 and 2 <= power <= 10):
              raise ValueError(
                  """Invalid input\n"""
                  """needed_sum must be between 1 and 1000, power between 2 and 10."""					)

       return backtrack(UpperCAmelCase__,							UpperCAmelCase__,							1,							0,							0					)[1]  # Return the solutions_count


if __name__ == "__main__":
      import doctest

      doctest.testmod()
