



'''simple docstring'''


import argparse
import os
import re

import packaging.version


_lowerCamelCase	:       int      	=	"examples/"
_lowerCamelCase	:       Dict      	=	{
    "examples": (re.compile(R"^check_min_version\(\"[^\"]+\"\)\s*$", re.MULTILINE), "check_min_version(\"VERSION\")\n"),
    "init": (re.compile(R"^__version__\s+=\s+\"([^\"]+)\"\s*$", re.MULTILINE), "__version__ = \"VERSION\"\n"),
    "setup": (re.compile(R"^(\s*)version\s*=\s*\"[^\"]+\",", re.MULTILINE), R"\1version=\"VERSION\","),
    "doc": (re.compile(R"^(\s*)release\s*=\s*\"[^\"]+\"$", re.MULTILINE), "release = \"VERSION\"\n"),
}
_lowerCamelCase	:       List[str]      	=	{
    "init": "src/transformers/__init__.py",
    "setup": "setup.py",
}
_lowerCamelCase	:       Union[str, Any]      	=	"README.md"







def 				__lowerCamelCase				(   A__    ,						A__    ,						A__    )       ->	Optional[Any]:






   """simple docstring"""
   with open(A__    ,						'r'    ,						encoding='utf-8'    ,						newline='\n'    ) as f:
      UpperCamelCase					=  f.read()
   UpperCamelCase				,      UpperCamelCase					=  REPLACE_PATTERNS[pattern]
   UpperCamelCase					=  replace.replace('VERSION'    ,						A__    )
   UpperCamelCase					=  re_pattern.sub(A__    ,						A__    )
   with open(A__    ,						'w'    ,						encoding='utf-8'    ,						newline='\n'    ) as f:
      f.write(A__    )







def 				__lowerCamelCase				(   A__    )       ->	Optional[int]:






   """simple docstring"""
   for folder, directories, fnames in os.walk(A__    ):
      # Removing some of the folders with non-actively maintained examples from the walk
      if "research_projects" in directories:
         directories.remove('research_projects'    )
      if "legacy" in directories:
         directories.remove('legacy'    )
      for fname in fnames:
         if fname.endswith('.py'    ):
            update_version_in_file(os.path.join(A__    ,						A__    )    ,						A__    ,						pattern='examples'    )







def 				__lowerCamelCase				(   A__    ,						A__=False    )       ->	List[str]:






   """simple docstring"""
   for pattern, fname in REPLACE_FILES.items():
      update_version_in_file(A__    ,						A__    ,						A__    )
   if not patch:
      update_version_in_examples(A__    )







def 				__lowerCamelCase				(   )       ->	Optional[Any]:






   """simple docstring"""
   UpperCamelCase					=  '🤗 Transformers currently provides the following architectures'
   UpperCamelCase					=  '1. Want to contribute a new model?'
   with open(A__    ,						'r'    ,						encoding='utf-8'    ,						newline='\n'    ) as f:
      UpperCamelCase					=  f.readlines()

   # Find the start of the list.
   UpperCamelCase					=  0
   while not lines[start_index].startswith(_start_prompt    ):
      start_index += 1
   start_index += 1

   UpperCamelCase					=  start_index
   # Update the lines in the model list.
   while not lines[index].startswith(_end_prompt    ):
      if lines[index].startswith('1.'    ):
         UpperCamelCase					=  lines[index].replace(
             'https://huggingface.co/docs/transformers/main/model_doc'    ,						'https://huggingface.co/docs/transformers/model_doc'    ,						)
      index += 1

   with open(A__    ,						'w'    ,						encoding='utf-8'    ,						newline='\n'    ) as f:
      f.writelines(A__    )







def 				__lowerCamelCase				(   )       ->	Optional[Any]:






   """simple docstring"""
   with open(REPLACE_FILES['init']    ,						'r'    ) as f:
      UpperCamelCase					=  f.read()
   UpperCamelCase					=  REPLACE_PATTERNS['init'][0].search(A__    ).groups()[0]
   return packaging.version.parse(A__    )







def 				__lowerCamelCase				(   A__=False    )       ->	Union[str, Any]:






   """simple docstring"""
   UpperCamelCase					=  get_version()
   if patch and default_version.is_devrelease:
      raise ValueError('Can\'t create a patch version from the dev branch, checkout a released version!'    )
   if default_version.is_devrelease:
      UpperCamelCase					=  default_version.base_version
   elif patch:
      UpperCamelCase					=  F"""{default_version.major}.{default_version.minor}.{default_version.micro + 1}"""
   else:
      UpperCamelCase					=  F"""{default_version.major}.{default_version.minor + 1}.0"""

   # Now let's ask nicely if that's the right one.
   UpperCamelCase					=  input(F"""Which version are you releasing? [{default_version}]"""    )
   if len(A__    ) == 0:
      UpperCamelCase					=  default_version

   print(F"""Updating version to {version}."""    )
   global_version_update(A__    ,						patch=A__    )
   if not patch:
      print('Cleaning main README, don\'t forget to run `make fix-copies`.'    )
      clean_main_ref_in_model_list()







def 				__lowerCamelCase				(   )       ->	int:






   """simple docstring"""
   UpperCamelCase					=  get_version()
   UpperCamelCase					=  F"""{current_version.major}.{current_version.minor + 1}.0.dev0"""
   UpperCamelCase					=  current_version.base_version

   # Check with the user we got that right.
   UpperCamelCase					=  input(F"""Which version are we developing now? [{dev_version}]"""    )
   if len(A__    ) == 0:
      UpperCamelCase					=  dev_version

   print(F"""Updating version to {version}."""    )
   global_version_update(A__    )
   print('Cleaning main README, don\'t forget to run `make fix-copies`.'    )
   clean_main_ref_in_model_list()


if __name__ == "__main__":
   _lowerCamelCase	:       Optional[Any]      	=	argparse.ArgumentParser()
   parser.add_argument("--post_release", action="store_true", help="Whether this is pre or post release.")
   parser.add_argument("--patch", action="store_true", help="Whether or not this is a patch release.")
   _lowerCamelCase	:       Dict      	=	parser.parse_args()
   if not args.post_release:
      pre_release_work(patch=args.patch)
   elif args.patch:
      print("Nothing to do after a patch :-)")
   else:
      post_release_work()



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



