




import argparse
import logging
import os

import datasets
import tensorflow as tf

from transformers import AutoTokenizer


__lowerCamelCase   :						int				=			logging.getLogger(__name__)







def 		lowercase__   (		):





					'''simple docstring'''






					__magic_name__							:	Tuple    							=							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=1_0_0_0							,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=5_1_2							,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.'''							,)

					__magic_name__							:	Union[str, Any]    							=							parser.parse_args()
					return args







def 		lowercase__   (		__A:	int				):





					'''simple docstring'''






					def fn(__A:	Optional[int]				):
										return tokenizer(examples['''text''']				)

					return fn







def 		lowercase__   (		__A:	Union[str, Any]				):





					'''simple docstring'''






					__magic_name__							:	Any    							=							[]
					for i in range(len(tokenized_data['''input_ids''']				)				):
										__magic_name__							:	Any    							=							{
										    '''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]				)				),
										}
										__magic_name__							:	Dict    							=							tf.train.Features(feature=__A				)
										__magic_name__							:	str    							=							tf.train.Example(features=__A				)
										__magic_name__							:	Optional[Any]    							=							example.SerializeToString()
										records.append(__A				)
					return records







def 		lowercase__   (		__A:	List[str]				):





					'''simple docstring'''






					__magic_name__							:	Union[str, Any]    							=							datasets.load_dataset(args.dataset_name							,args.dataset_config							,split=args.split				)

					if args.limit is not None:
										__magic_name__							:	Union[str, Any]    							=							min(len(__A				)							,args.limit				)
										__magic_name__							:	Optional[Any]    							=							dataset.select(range(__A				)				)
										print(F'''Limiting the dataset to {args.limit} entries.'''				)

					__magic_name__							:	Optional[int]    							=							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				)
										__magic_name__							:	Union[str, Any]    							=							os.path.join(args.output_dir							,args.split				)
										if not os.path.exists(__A				):
															os.makedirs(__A				)
					else:
										__magic_name__							:	int    							=							os.path.join(args.output_dir							,args.split				)

					# Tokenize the whole dataset at once.
					__magic_name__							:	int    							=							tokenize_function(__A				)
					__magic_name__							:	Optional[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:	Dict				):
										# Concatenate all texts.
										__magic_name__							:	Optional[Any]    							=							{k: sum(examples[k]							,[]				) for k in examples.keys()}
										__magic_name__							:	int    							=							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 🫀
										__magic_name__							:	str    							=							(total_length // args.max_length) * args.max_length
										# Split by chunks of max_len.
										__magic_name__							:	Dict    							=							{
										    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

					__magic_name__							:	Tuple    							=							dataset_tokenized.map(__A							,batched=__A							,batch_size=1_0_0_0							,num_proc=4				)

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

										with tf.io.TFRecordWriter(__A				) as out_file:
															for i in range(len(__A				)				):
																				__magic_name__							:	str    							=							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__":
	__lowerCamelCase   :						Optional[int]				=			parse_args()
	main(args)









import warnings
from typing import Dict

import numpy as np

from ..utils import ExplicitEnum, add_end_docstrings, is_tf_available, is_torch_available
from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline


if is_tf_available():
	from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING

if is_torch_available():
	from ..models.auto.modeling_auto import MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING







def 		lowercase__   (		__A:	str				):





					'''simple docstring'''






					return 1.0 / (1.0 + np.exp(-_outputs				))







def 		lowercase__   (		__A:	str				):





					'''simple docstring'''






					__magic_name__							:	List[str]    							=							np.max(_outputs							,axis=-1							,keepdims=__A				)
					__magic_name__							:	int    							=							np.exp(_outputs - maxes				)
					return shifted_exp / shifted_exp.sum(axis=-1							,keepdims=__A				)


class    lowerCamelCase    (		_lowerCamelCase						):






			'''simple docstring'''





			UpperCamelCase__								='''sigmoid'''
			UpperCamelCase__								='''softmax'''
			UpperCamelCase__								='''none'''






@add_end_docstrings(
    _lowerCamelCase				,R'''
        return_all_scores (`bool`, *optional*, defaults to `False`):
            Whether to return all prediction scores or just the one of the predicted class.
        function_to_apply (`str`, *optional*, defaults to `"default"`):
            The function to apply to the model outputs in order to retrieve the scores. Accepts four different values:

            - `"default"`: if the model has a single label, will apply the sigmoid function on the output. If the model
              has several labels, will apply the softmax function on the output.
            - `"sigmoid"`: Applies the sigmoid function on the output.
            - `"softmax"`: Applies the softmax function on the output.
            - `"none"`: Does not apply any function on the output.
    '''				,)
class    lowerCamelCase    (		_lowerCamelCase						):






			'''simple docstring'''





			UpperCamelCase__								=False
			UpperCamelCase__								=ClassificationFunction.NONE

			def __init__( self			:   Tuple       ,						**lowerCamelCase_			:   Tuple  )						->   List[Any]:
								super().__init__(**lowerCamelCase_  )

								self.check_model_type(
								    TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
								    if self.framework == '''tf'''
								    else MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING  )

			def 							UpperCAmelCase__       ( self			:   Optional[int]       ,						lowerCamelCase_			:   Tuple=None       ,						lowerCamelCase_			:   Dict=None       ,						lowerCamelCase_			:   Optional[int]=""       ,						**lowerCamelCase_			:   int  )						->   str:
								# Using "" as default argument because we're going to use `top_k=None` in user code to declare
								# "No top_k"
								__magic_name__							:	Dict    							=							tokenizer_kwargs

								__magic_name__							:	Dict    							=							{}
								if hasattr(self.model.config       ,						'''return_all_scores'''  ) and return_all_scores is None:
													__magic_name__							:	List[str]    							=							self.model.config.return_all_scores

								if isinstance(lowerCamelCase_       ,						lowerCamelCase_  ) or top_k is None:
													__magic_name__							:	Dict    							=							top_k
													__magic_name__							:	List[Any]    							=							False
								elif return_all_scores is not None:
													warnings.warn(
													    '''`return_all_scores` is now deprecated,  if want a similar functionality use `top_k=None` instead of'''
													    ''' `return_all_scores=True` or `top_k=1` instead of `return_all_scores=False`.'''       ,						lowerCamelCase_       ,						)
													if return_all_scores:
																		__magic_name__							:	str    							=							None
													else:
																		__magic_name__							:	int    							=							1

								if isinstance(lowerCamelCase_       ,						lowerCamelCase_  ):
													__magic_name__							:	str    							=							ClassificationFunction[function_to_apply.upper()]

								if function_to_apply is not None:
													__magic_name__							:	List[str]    							=							function_to_apply
								return preprocess_params, {}, postprocess_params

			def __call__( self			:   Optional[Any]       ,						*lowerCamelCase_			:   Union[str, Any]       ,						**lowerCamelCase_			:   Union[str, Any]  )						->   Optional[int]:
								__magic_name__							:	Optional[int]    							=							super().__call__(*lowerCamelCase_       ,						**lowerCamelCase_  )
								# TODO try and retrieve it in a nicer way from _sanitize_parameters.
								__magic_name__							:	int    							=							'''top_k''' not in kwargs
								if isinstance(args[0]       ,						lowerCamelCase_  ) and _legacy:
													# This pipeline is odd, and return a list when single item is run
													return [result]
								else:
													return result

			def 							UpperCAmelCase__       ( self			:   Optional[Any]       ,						lowerCamelCase_			:   Any       ,						**lowerCamelCase_			:   int  )						->   Dict[str, GenericTensor]:
								__magic_name__							:	Union[str, Any]    							=							self.framework
								if isinstance(lowerCamelCase_       ,						lowerCamelCase_  ):
													return self.tokenizer(**lowerCamelCase_       ,						return_tensors=lowerCamelCase_       ,						**lowerCamelCase_  )
								elif isinstance(lowerCamelCase_       ,						lowerCamelCase_  ) and len(lowerCamelCase_  ) == 1 and isinstance(inputs[0]       ,						lowerCamelCase_  ) and len(inputs[0]  ) == 2:
													# It used to be valid to use a list of list of list for text pairs, keeping this path for BC
													return self.tokenizer(
													    text=inputs[0][0]       ,						text_pair=inputs[0][1]       ,						return_tensors=lowerCamelCase_       ,						**lowerCamelCase_  )
								elif isinstance(lowerCamelCase_       ,						lowerCamelCase_  ):
													# This is likely an invalid usage of the pipeline attempting to pass text pairs.
													raise ValueError(
													    '''The pipeline received invalid inputs, if you are trying to send text pairs, you can try to send a'''
													    ''' dictionary `{"text": "My text", "text_pair": "My pair"}` in order to send a text pair.'''  )
								return self.tokenizer(lowerCamelCase_       ,						return_tensors=lowerCamelCase_       ,						**lowerCamelCase_  )

			def 							UpperCAmelCase__       ( self			:   str       ,						lowerCamelCase_			:   Dict  )						->   Union[str, Any]:
								return self.model(**lowerCamelCase_  )


			def 							UpperCAmelCase__       ( self			:   Dict       ,						lowerCamelCase_			:   Dict       ,						lowerCamelCase_			:   Dict=None       ,						lowerCamelCase_			:   List[str]=1       ,						lowerCamelCase_			:   Any=True  )						->   int:
								# `_legacy` is used to determine if we're running the naked pipeline and in backward
								# compatibility mode, or if running the pipeline with `pipeline(..., top_k=1)` we're running
								# the more natural result containing the list.
								# Default value before `set_parameters`
								if function_to_apply is None:
													if self.model.config.problem_type == "multi_label_classification" or self.model.config.num_labels == 1:
																		__magic_name__							:	Union[str, Any]    							=							ClassificationFunction.SIGMOID
													elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1:
																		__magic_name__							:	str    							=							ClassificationFunction.SOFTMAX
													elif hasattr(self.model.config       ,						'''function_to_apply'''  ) and function_to_apply is None:
																		__magic_name__							:	Dict    							=							self.model.config.function_to_apply
													else:
																		__magic_name__							:	Optional[Any]    							=							ClassificationFunction.NONE

								__magic_name__							:	Any    							=							model_outputs['''logits'''][0]
								__magic_name__							:	Optional[int]    							=							outputs.numpy()

								if function_to_apply == ClassificationFunction.SIGMOID:
													__magic_name__							:	List[str]    							=							sigmoid(lowerCamelCase_  )
								elif function_to_apply == ClassificationFunction.SOFTMAX:
													__magic_name__							:	Optional[int]    							=							softmax(lowerCamelCase_  )
								elif function_to_apply == ClassificationFunction.NONE:
													__magic_name__							:	Optional[int]    							=							outputs
								else:
													raise ValueError(F'''Unrecognized `function_to_apply` argument: {function_to_apply}'''  )

								if top_k == 1 and _legacy:
													return {"label": self.model.config.idalabel[scores.argmax().item()], "score": scores.max().item()}

								__magic_name__							:	Union[str, Any]    							=							[
								    {'''label''': self.model.config.idalabel[i], '''score''': score.item()} for i, score in enumerate(lowerCamelCase_  )
								]
								if not _legacy:
													dict_scores.sort(key=lambda lowerCamelCase_  : x["score"]       ,						reverse=lowerCamelCase_  )
													if top_k is not None:
																		__magic_name__							:	Dict    							=							dict_scores[:top_k]
								return dict_scores



