


from jiwer import compute_measures

import datasets


snake_case__				:	Union[str, Any]					       =					'\\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'

snake_case__				:	Any					       =					'\\nWord error rate (WER) is a common metric of the performance of an automatic speech recognition system.\n\nThe general difficulty of measuring performance lies in the fact that the recognized word sequence can have a different length from the reference word sequence (supposedly the correct one). The WER is derived from the Levenshtein distance, working at the word level instead of the phoneme level. The WER is a valuable tool for comparing different systems as well as for evaluating improvements within one system. This kind of measurement, however, provides no details on the nature of translation errors and further work is therefore required to identify the main source(s) of error and to focus any research effort.\n\nThis problem is solved by first aligning the recognized word sequence with the reference (spoken) word sequence using dynamic string alignment. Examination of this issue is seen through a theory called the power law that states the correlation between perplexity and word error rate.\n\nWord error rate can then be computed as:\n\nWER = (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 words,\nN is the number of words in the reference (N=S+D+C).\n\nThis value indicates the average number of errors per reference word. The lower the value, the better the\nperformance of the ASR system with a WER of 0 being a perfect score.\n'

snake_case__				:	Optional[int]					       =					'\nCompute WER score of transcribed segments against references.\n\nArgs:\n    references: List of references for each speech input.\n    predictions: List of transcriptions to score.\n    concatenate_texts (bool, default=False): Whether to concatenate all input texts or compute WER iteratively.\n\nReturns:\n    (float): the word 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    >>> wer = datasets.load_metric("wer")\n    >>> wer_score = wer.compute(predictions=predictions, references=references)\n    >>> print(wer_score)\n    0.5\n'





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




       '''simple docstring'''



       def 				_lowerCAmelCase							(						self				:				Optional[Any]							)					->List[str]:
          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""",
              ]		,				)




       def 				_lowerCAmelCase							(						self				:				int		,				__a				:				Any=None		,				__a				:				Optional[int]=None		,				__a				:				Dict=False							)					->List[str]:
          if concatenate_texts:
             return compute_measures(__a		,				__a							)["wer"]
          else:
             lowerCamelCase_						:   Optional[Any]		= 0
             lowerCamelCase_						:   Tuple		= 0
             for prediction, reference in zip(__a		,				__a							):
                lowerCamelCase_						:   Union[str, Any]		= compute_measures(__a		,				__a							)
                incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"]
                total += measures["substitutions"] + measures["deletions"] + measures["hits"]
             return incorrect / total









import argparse
import logging
import os

import datasets
import tensorflow as tf

from transformers import AutoTokenizer


snake_case__				:	Dict					       =					logging.getLogger(__name__)


def    __lowerCamelCase   (      )     ->    Any:
   lowerCamelCase_						:   str		= argparse.ArgumentParser(
       description="""Prepare TFRecord shards from pre-tokenized samples of the wikitext dataset."""					)
   parser.add_argument(
       """--dataset_name"""						,						type=A__						,						default="""wikitext"""						,						help="""Name of the training. Explore datasets at: hf.co/datasets."""						,						)
   parser.add_argument(
       """--dataset_config"""						,						type=A__						,						default="""wikitext-103-raw-v1"""						,						help="""Configuration name of the dataset."""					)
   parser.add_argument(
       """--tokenizer_name_or_path"""						,						type=A__						,						default="""sayakpaul/unigram-tokenizer-wikitext"""						,						help="""Tokenizer identifier. Can be a local filepath or a Hub identifier."""						,						)
   parser.add_argument(
       """--shard_size"""						,						type=A__						,						default=1000						,						help="""Number of entries to go in a single shard."""						,						)
   parser.add_argument("""--split"""						,						type=A__						,						default="""train"""						,						choices=["""train""", """test""", """validation"""]					)
   parser.add_argument(
       """--limit"""						,						default=A__						,						type=A__						,						help="""Limit the number of shards (used for debugging)."""						,						)
   parser.add_argument(
       """--max_length"""						,						type=A__						,						default=512						,						help="""Maximum sequence length. For training on TPUs, it helps to have a maximum"""
       """ sequence length that is a multiple of 8."""						,						)
   parser.add_argument(
       """--output_dir"""						,						default="""tf-tpu"""						,						type=A__						,						help="""Output directory where the TFRecord shards will be saved. If the"""
       """ path is appended with `gs://` ('gs://tf-tpu', for example) then the TFRecord"""
       """ shards will be directly saved to a Google Cloud Storage bucket."""						,						)

   lowerCamelCase_						:   Optional[int]		= parser.parse_args()
   return args


def    __lowerCamelCase   (      A__						: Tuple					)     ->    str:
   def fn(A__						: Dict					):
      return tokenizer(examples["""text"""]					)

   return fn


def    __lowerCamelCase   (      A__						: Union[str, Any]					)     ->    Union[str, Any]:
   lowerCamelCase_						:   Dict		= []
   for i in range(len(tokenized_data["""input_ids"""]					)					):
      lowerCamelCase_						:   List[str]		= {
          """input_ids""": tf.train.Feature(intaa_list=tf.train.IntaaList(value=tokenized_data["""input_ids"""][i]					)					),
          """attention_mask""": tf.train.Feature(
              intaa_list=tf.train.IntaaList(value=tokenized_data["""attention_mask"""][i]					)					),
      }
      lowerCamelCase_						:   Optional[int]		= tf.train.Features(feature=A__					)
      lowerCamelCase_						:   Tuple		= tf.train.Example(features=A__					)
      lowerCamelCase_						:   Optional[Any]		= example.SerializeToString()
      records.append(A__					)
   return records


def    __lowerCamelCase   (      A__						: Tuple					)     ->    Union[str, Any]:
   lowerCamelCase_						:   int		= datasets.load_dataset(args.dataset_name						,						args.dataset_config						,						split=args.split					)

   if args.limit is not None:
      lowerCamelCase_						:   str		= min(len(A__					)						,						args.limit					)
      lowerCamelCase_						:   Dict		= dataset.select(range(A__					)					)
      print(f'''Limiting the dataset to {args.limit} entries.'''					)

   lowerCamelCase_						:   str		= AutoTokenizer.from_pretrained(args.tokenizer_name_or_path					)

   # Handle output directory creation.
   # For serializing into a Google Cloud Storage Bucket, one needs to first
   # create a bucket.
   if "gs" not in args.output_dir:
      if not os.path.exists(args.output_dir					):
         os.makedirs(args.output_dir					)
      lowerCamelCase_						:   Optional[int]		= os.path.join(args.output_dir						,						args.split					)
      if not os.path.exists(A__					):
         os.makedirs(A__					)
   else:
      lowerCamelCase_						:   Any		= os.path.join(args.output_dir						,						args.split					)

   # Tokenize the whole dataset at once.
   lowerCamelCase_						:   List[str]		= tokenize_function(A__					)
   lowerCamelCase_						:   List[Any]		= dataset.map(A__						,						batched=A__						,						num_proc=4						,						remove_columns=["""text"""]					)

   # We need to concatenate all our texts together, and then split the result
   # into chunks of a fixed size, which we will call block_size. To do this, we
   # will use the map method again, with the option batched=True. When we use batched=True,
   # the function we pass to map() will be passed multiple inputs at once, allowing us
   # to group them into more or fewer examples than we had in the input.
   # This allows us to create our new fixed-length samples. The advantage of this
   # method is that we don't lose a whole lot of content from the dataset compared to the
   # case where we simply tokenize with a pre-defined max_length.

   def group_texts(A__						: Union[str, Any]					):
      # Concatenate all texts.
      lowerCamelCase_						:   Optional[int]		= {k: sum(examples[k]						,						[]					) for k in examples.keys()}
      lowerCamelCase_						:   Union[str, Any]		= len(concatenated_examples[list(examples.keys()					)[0]]					)
      # We drop the small remainder, though you could add padding instead if the model supports it
      # In this, as in all things, we advise you to follow your heart 🫀
      lowerCamelCase_						:   Union[str, Any]		= (total_length // args.max_length) * args.max_length
      # Split by chunks of max_len.
      lowerCamelCase_						:   List[str]		= {
          k: [t[i : i + args.max_length] for i in range(0						,						A__						,						args.max_length					)]
          for k, t in concatenated_examples.items()
      }
      return result

   lowerCamelCase_						:   Optional[int]		= dataset_tokenized.map(A__						,						batched=A__						,						batch_size=1000						,						num_proc=4					)

   lowerCamelCase_						:   List[str]		= 0
   lowerCamelCase_						:   Tuple		= 0
   for shard in range(0						,						len(A__					)						,						args.shard_size					):
      lowerCamelCase_						:   Union[str, Any]		= grouped_dataset[shard : shard + args.shard_size]
      lowerCamelCase_						:   Optional[int]		= len(dataset_snapshot["""input_ids"""]					)
      lowerCamelCase_						:   List[str]		= os.path.join(A__						,						f'''dataset-{shard_count}-{records_containing}.tfrecord'''					)
      lowerCamelCase_						:   Optional[int]		= get_serialized_examples(A__					)

      with tf.io.TFRecordWriter(A__					) as out_file:
         for i in range(len(A__					)					):
            lowerCamelCase_						:   Dict		= serialized_examples[i]
            out_file.write(A__					)
         print("""Wrote file {} containing {} records""".format(A__						,						A__					)					)

      shard_count += 1
      total_records += records_containing

   with open(f'''split-{args.split}-records-count.txt'''						,						"""w"""					) as f:
      print(f'''Total {args.split} records: {total_records}'''						,						file=A__					)


if __name__ == "__main__":
      snake_case__				:	str					       =					parse_args()
      main(args)





