






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



def 							snake_case					(     a_							: List[Any]	)       ->				str:





      """simple docstring"""

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



def 							snake_case					(     a_							: int	)       ->				List[Any]:





      """simple docstring"""

      UpperCamelCase_				:   Optional[int]					    =							[len(a_	) for line in example["""content"""].splitlines()]
      return {"line_mean": np.mean(a_	), "line_max": max(a_	)}



def 							snake_case					(     a_							: List[str]	)       ->				Optional[int]:





      """simple docstring"""

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



def 							snake_case					(     a_							: List[Any]    ,   a_							: str	)       ->				Tuple:





      """simple docstring"""

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



def 							snake_case					(     a_							: Optional[int]    ,   a_							: Tuple=5	)       ->				int:





      """simple docstring"""

      UpperCamelCase_				:   Optional[Any]					    =							["""auto-generated""", """autogenerated""", """automatically generated"""]
      UpperCamelCase_				:   Any					    =							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 							snake_case					(     a_							: Union[str, Any]    ,   a_							: Any=5    ,   a_							: List[str]=0.05	)       ->				Any:





      """simple docstring"""

      UpperCamelCase_				:   List[Any]					    =							["""unit tests""", """test file""", """configuration file"""]
      UpperCamelCase_				:   Union[str, Any]					    =							example["""content"""].splitlines()
      UpperCamelCase_				:   List[str]					    =							0
      UpperCamelCase_				:   Optional[int]					    =							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
      UpperCamelCase_				:   str					    =							example["""content"""].count("""\n"""	)
      UpperCamelCase_				:   List[Any]					    =							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 							snake_case					(     a_							: Dict	)       ->				Optional[int]:





      """simple docstring"""

      UpperCamelCase_				:   Tuple					    =							["""def """, """class """, """for """, """while """]
      UpperCamelCase_				:   Optional[Any]					    =							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 							snake_case					(     a_							: List[str]    ,   a_							: Tuple=4	)       ->				Union[str, Any]:





      """simple docstring"""

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



def 							snake_case					(     a_							: Optional[Any]	)       ->				List[Any]:





      """simple docstring"""

      UpperCamelCase_				:   Any					    =							tokenizer(example["""content"""]    ,   truncation=a_	)["""input_ids"""]
      UpperCamelCase_				:   Any					    =							len(example["""content"""]	) / len(a_	)
      return {"ratio": ratio}



def 							snake_case					(     a_							: Optional[int]	)       ->				Any:





      """simple docstring"""

      UpperCamelCase_				:   Union[str, Any]					    =							{}
      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 							snake_case					(     a_							: Optional[Any]    ,   a_							: Union[str, Any]    ,   a_							: int	)       ->				int:





      """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 							snake_case					(     a_							: Optional[int]	)       ->				int:





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

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

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

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

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

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

import jiwer
import jiwer.transforms as tr
from packaging import version

import datasets
from datasets.config import PY_VERSION


if PY_VERSION < version.parse("3.8"):
      import importlib_metadata
else:
      import importlib.metadata as importlib_metadata


UpperCamelCase							=""


if version.parse(importlib_metadata.version("jiwer")) < version.parse("2.3.0"):




      class     A    (      tr.AbstractTransform						):






       """simple docstring"""





       def __init__(							self			,     __lowerCAmelCase = " " ):
             UpperCamelCase_				:   str					    =							sentence_delimiter
       def   _UpperCAmelCase       (							self			,     __lowerCAmelCase ):
             return list(__lowerCAmelCase )





       def   _UpperCAmelCase       (							self			,     __lowerCAmelCase ):
             UpperCamelCase_				:   List[Any]					    =							[]
             for sent_idx, sentence in enumerate(__lowerCAmelCase ):
                   chars.extend(self.process_string(__lowerCAmelCase ) )
                   if self.sentence_delimiter is not None and self.sentence_delimiter != "" and sent_idx < len(__lowerCAmelCase ) - 1:
                         chars.append(self.sentence_delimiter )
             return chars






      UpperCamelCase							=tr.Compose(
          [tr.RemoveMultipleSpaces(), tr.Strip(), SentencesToListOfCharacters(SENTENCE_DELIMITER)]
      )
else:
      UpperCamelCase							=tr.Compose(
          [
              tr.RemoveMultipleSpaces(),
              tr.Strip(),
              tr.ReduceToSingleSentence(SENTENCE_DELIMITER),
              tr.ReduceToListOfListOfChars(),
          ]
      )


UpperCamelCase							="\\n@inproceedings{inproceedings,\n    author = {Morris, Andrew and Maier, Viktoria and Green, Phil},\n    year = {2004},\n    month = {01},\n    pages = {},\n    title = {From WER and RIL to MER and WIL: improved evaluation measures for connected speech recognition.}\n}\n"

UpperCamelCase							="\\nCharacter error rate (CER) is a common metric of the performance of an automatic speech recognition system.\n\nCER is similar to Word Error Rate (WER), but operates on character instead of word. Please refer to docs of WER for further information.\n\nCharacter error rate can be computed as:\n\nCER = (S + D + I) / N = (S + D + I) / (S + D + C)\n\nwhere\n\nS is the number of substitutions,\nD is the number of deletions,\nI is the number of insertions,\nC is the number of correct characters,\nN is the number of characters in the reference (N=S+D+C).\n\nCER's output is not always a number between 0 and 1, in particular when there is a high number of insertions. This value is often associated to the percentage of characters that were incorrectly predicted. The lower the value, the better the\nperformance of the ASR system with a CER of 0 being a perfect score.\n"

UpperCamelCase							="\nComputes CER score of transcribed segments against references.\nArgs:\n    references: list of references for each speech input.\n    predictions: list of transcribtions to score.\n    concatenate_texts: Whether or not to concatenate sentences before evaluation, set to True for more accurate result.\nReturns:\n    (float): the character error rate\n\nExamples:\n\n    >>> predictions = [\"this is the prediction\", \"there is an other sample\"]\n    >>> references = [\"this is the reference\", \"there is another one\"]\n    >>> cer = datasets.load_metric(\"cer\")\n    >>> cer_score = cer.compute(predictions=predictions, references=references)\n    >>> print(cer_score)\n    0.34146341463414637\n"




@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION,   _KWARGS_DESCRIPTION						)
class     A    (      datasets.Metric						):






 """simple docstring"""





 def   _UpperCAmelCase       (							self ):
       return datasets.MetricInfo(
           description=_DESCRIPTION			,     citation=_CITATION			,     inputs_description=_KWARGS_DESCRIPTION			,     features=datasets.Features(
               {
                   """predictions""": datasets.Value("""string"""			,     id="""sequence""" ),
                   """references""": datasets.Value("""string"""			,     id="""sequence""" ),
               } )			,     codebase_urls=["""https://github.com/jitsi/jiwer/"""]			,     reference_urls=[
               """https://en.wikipedia.org/wiki/Word_error_rate""",
               """https://sites.google.com/site/textdigitisation/qualitymeasures/computingerrorrates""",
           ]			,     )





 def   _UpperCAmelCase       (							self			,     __lowerCAmelCase			,     __lowerCAmelCase			,     __lowerCAmelCase=False ):
       if concatenate_texts:
             return jiwer.compute_measures(
                 __lowerCAmelCase			,     __lowerCAmelCase			,     truth_transform=__lowerCAmelCase			,     hypothesis_transform=__lowerCAmelCase			,     )["wer"]

       UpperCamelCase_				:   Optional[Any]					    =							0
       UpperCamelCase_				:   str					    =							0
       for prediction, reference in zip(__lowerCAmelCase			,     __lowerCAmelCase ):
             UpperCamelCase_				:   Optional[int]					    =							jiwer.compute_measures(
                 __lowerCAmelCase			,     __lowerCAmelCase			,     truth_transform=__lowerCAmelCase			,     hypothesis_transform=__lowerCAmelCase			,     )
             incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"]
             total += measures["substitutions"] + measures["deletions"] + measures["hits"]

       return incorrect / total






