






"""simple docstring"""

import logging
import os
from dataclasses import dataclass, field
from typing import Dict, Optional

import datasets
import numpy as np
import tensorflow as tf

from transformers import (
    AutoConfig,
    AutoTokenizer,
    EvalPrediction,
    HfArgumentParser,
    PreTrainedTokenizer,
    TFAutoModelForSequenceClassification,
    TFTrainer,
    TFTrainingArguments,
)
from transformers.utils import logging as hf_logging


hf_logging.set_verbosity_info()
hf_logging.enable_default_handler()
hf_logging.enable_explicit_format()




def __lowercase    (							_a	,    _a	,    _a	,    _a	,    _a	,    _a = None	,    ):
    snake_case_				:  List[str]       =			{}

    if train_file is not None:
        snake_case_				:  List[str]       =			[train_file]
    if eval_file is not None:
        snake_case_				:  Any       =			[eval_file]
    if test_file is not None:
        snake_case_				:  List[Any]       =			[test_file]

    snake_case_				:  List[Any]       =			datasets.load_dataset('''csv'''	,    data_files=snake_case__					)
    snake_case_				:  List[str]       =			list(ds[list(files.keys()					)[0]].features.keys()					)
    snake_case_				:  Optional[Any]       =			features_name.pop(snake_case__					)
    snake_case_				:  Optional[int]       =			list(set(ds[list(files.keys()					)[0]][label_name]					)					)
    snake_case_				:  Union[str, Any]       =			{label: i for i, label in enumerate(snake_case__					)}
    snake_case_				:  Dict       =			tokenizer.model_input_names
    snake_case_				:  List[str]       =			{}

    if len(snake_case__					) == 1:
        for k in files.keys():
            snake_case_				:  Optional[int]       =			ds[k].map(
                lambda _a					: tokenizer.batch_encode_plus(
                    example[features_name[0]]	,    truncation=snake_case__	,    max_length=snake_case__	,    padding='''max_length'''					)	,    batched=snake_case__	,    )
    elif len(snake_case__					) == 2:
        for k in files.keys():
            snake_case_				:  Any       =			ds[k].map(
                lambda _a					: tokenizer.batch_encode_plus(
                    (example[features_name[0]], example[features_name[1]])	,    truncation=snake_case__	,    max_length=snake_case__	,    padding='''max_length'''	,    )	,    batched=snake_case__	,    )

    def gen_train():
        for ex in transformed_ds[datasets.Split.TRAIN]:
            snake_case_				:  List[Any]       =			{k: v for k, v in ex.items() if k in input_names}
            snake_case_				:  int       =			labelaid[ex[label_name]]
            yield (d, label)

    def gen_val():
        for ex in transformed_ds[datasets.Split.VALIDATION]:
            snake_case_				:  Union[str, Any]       =			{k: v for k, v in ex.items() if k in input_names}
            snake_case_				:  Dict       =			labelaid[ex[label_name]]
            yield (d, label)

    def gen_test():
        for ex in transformed_ds[datasets.Split.TEST]:
            snake_case_				:  Dict       =			{k: v for k, v in ex.items() if k in input_names}
            snake_case_				:  List[str]       =			labelaid[ex[label_name]]
            yield (d, label)

    snake_case_				:  Any       =			(
        tf.data.Dataset.from_generator(
            snake_case__	,    ({k: tf.intaa for k in input_names}, tf.intaa)	,    ({k: tf.TensorShape([None]					) for k in input_names}, tf.TensorShape([]					))	,    )
        if datasets.Split.TRAIN in transformed_ds
        else None
    )

    if train_ds is not None:
        snake_case_				:  int       =			train_ds.apply(tf.data.experimental.assert_cardinality(len(ds[datasets.Split.TRAIN]					)					)					)

    snake_case_				:  Tuple       =			(
        tf.data.Dataset.from_generator(
            snake_case__	,    ({k: tf.intaa for k in input_names}, tf.intaa)	,    ({k: tf.TensorShape([None]					) for k in input_names}, tf.TensorShape([]					))	,    )
        if datasets.Split.VALIDATION in transformed_ds
        else None
    )

    if val_ds is not None:
        snake_case_				:  Optional[int]       =			val_ds.apply(tf.data.experimental.assert_cardinality(len(ds[datasets.Split.VALIDATION]					)					)					)

    snake_case_				:  str       =			(
        tf.data.Dataset.from_generator(
            snake_case__	,    ({k: tf.intaa for k in input_names}, tf.intaa)	,    ({k: tf.TensorShape([None]					) for k in input_names}, tf.TensorShape([]					))	,    )
        if datasets.Split.TEST in transformed_ds
        else None
    )

    if test_ds is not None:
        snake_case_				:  Any       =			test_ds.apply(tf.data.experimental.assert_cardinality(len(ds[datasets.Split.TEST]					)					)					)

    return train_ds, val_ds, test_ds, labelaid


lowercase__					:						List[str]												=			logging.getLogger(__name__)




@dataclass
class  _UpperCAmelCase :
 _lowerCAmelCase     :    int	      =	field(metadata={"""help""": """Which column contains the label"""})
 _lowerCAmelCase     :    str	      =	field(default=_lowercase					,  metadata={"""help""": """The path of the training file"""})
 _lowerCAmelCase     :    Optional[str]	      =	field(default=_lowercase					,  metadata={"""help""": """The path of the development file"""})
 _lowerCAmelCase     :    Optional[str]	      =	field(default=_lowercase					,  metadata={"""help""": """The path of the test file"""})
 _lowerCAmelCase     :    int	      =	field(
     default=1_2_8					,  metadata={
         """help""": (
             """The maximum total input sequence length after tokenization. Sequences longer """
             """than this will be truncated, sequences shorter will be padded."""
         )
     }					,  )
 _lowerCAmelCase     :    bool	      =	field(
     default=_lowercase					,  metadata={"""help""": """Overwrite the cached training and evaluation sets"""})





@dataclass
class  _UpperCAmelCase :
 _lowerCAmelCase     :    str	      =	field(
     metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""})
 _lowerCAmelCase     :    Optional[str]	      =	field(
     default=_lowercase					,  metadata={"""help""": """Pretrained config name or path if not the same as model_name"""})
 _lowerCAmelCase     :    Optional[str]	      =	field(
     default=_lowercase					,  metadata={"""help""": """Pretrained tokenizer name or path if not the same as model_name"""})
 _lowerCAmelCase     :    bool	      =	field(default=_lowercase					,  metadata={"""help""": """Set this flag to use fast tokenization."""})
 # If you want to tweak more attributes on your tokenizer, you should do it in a distinct script,
 # or just modify its tokenizer_config.json.
 _lowerCAmelCase     :    Optional[str]	      =	field(
     default=_lowercase					,  metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""}					,  )





def __lowercase    (							):
    # See all possible arguments in src/transformers/training_args.py
    # or by passing the --help flag to this script.
    # We now keep distinct sets of args, for a cleaner separation of concerns.
    snake_case_				:  Optional[Any]       =			HfArgumentParser((ModelArguments, DataTrainingArguments, TFTrainingArguments)					)
    snake_case_,			snake_case_,			snake_case_				:  Optional[int]       =			parser.parse_args_into_dataclasses()

    if (
        os.path.exists(training_args.output_dir					)
        and os.listdir(training_args.output_dir					)
        and training_args.do_train
        and not training_args.overwrite_output_dir
    ):
        raise ValueError(
            f"Output directory ({training_args.output_dir}) already exists and is not empty. Use"
            ''' --overwrite_output_dir to overcome.'''					)

    # Setup logging
    logging.basicConfig(
        format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s'''	,    datefmt='''%m/%d/%Y %H:%M:%S'''	,    level=logging.INFO	,    )
    logger.info(
        f"n_replicas: {training_args.n_replicas}, distributed training: {bool(training_args.n_replicas > 1					)}, "
        f"16-bits training: {training_args.fpaa}"					)
    logger.info(f"Training/evaluation parameters {training_args}"					)

    # Load pretrained model and tokenizer
    #
    # Distributed training:
    # The .from_pretrained methods guarantee that only one local process can concurrently
    # download model & vocab.

    snake_case_				:  Optional[Any]       =			AutoTokenizer.from_pretrained(
        model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path	,    cache_dir=model_args.cache_dir	,    )

    snake_case_,			snake_case_,			snake_case_,			snake_case_				:  Optional[int]       =			get_tfds(
        train_file=data_args.train_file	,    eval_file=data_args.dev_file	,    test_file=data_args.test_file	,    tokenizer=snake_case__	,    label_column_id=data_args.label_column_id	,    max_seq_length=data_args.max_seq_length	,    )

    snake_case_				:  Union[str, Any]       =			AutoConfig.from_pretrained(
        model_args.config_name if model_args.config_name else model_args.model_name_or_path	,    num_labels=len(snake_case__					)	,    labelaid=snake_case__	,    idalabel={id: label for label, id in labelaid.items()}	,    finetuning_task='''text-classification'''	,    cache_dir=model_args.cache_dir	,    )

    with training_args.strategy.scope():
        snake_case_				:  int       =			TFAutoModelForSequenceClassification.from_pretrained(
            model_args.model_name_or_path	,    from_pt=bool('''.bin''' in model_args.model_name_or_path					)	,    config=snake_case__	,    cache_dir=model_args.cache_dir	,    )

    def compute_metrics(_a					) -> Dict:
        snake_case_				:  List[str]       =			np.argmax(p.predictions	,    axis=1					)

        return {"acc": (preds == p.label_ids).mean()}

    # Initialize our Trainer
    snake_case_				:  Tuple       =			TFTrainer(
        model=snake_case__	,    args=snake_case__	,    train_dataset=snake_case__	,    eval_dataset=snake_case__	,    compute_metrics=snake_case__	,    )

    # Training
    if training_args.do_train:
        trainer.train()
        trainer.save_model()
        tokenizer.save_pretrained(training_args.output_dir					)

    # Evaluation
    snake_case_				:  Dict       =			{}
    if training_args.do_eval:
        logger.info('''*** Evaluate ***'''					)
        snake_case_				:  str       =			trainer.evaluate()
        snake_case_				:  Optional[Any]       =			os.path.join(training_args.output_dir	,    '''eval_results.txt'''					)

        with open(snake_case__	,    '''w'''					) as writer:
            logger.info('''***** Eval results *****'''					)

            for key, value in result.items():
                logger.info(f"  {key} = {value}"					)
                writer.write(f"{key} = {value}\n"					)

            results.update(snake_case__					)

    return results


if __name__ == "__main__":
     main()










"""simple docstring"""

import sys
import tempfile
import unittest
import unittest.mock as mock
from pathlib import Path

from huggingface_hub import HfFolder, delete_repo
from requests.exceptions import HTTPError

from transformers import AutoFeatureExtractor, WavaVecaFeatureExtractor
from transformers.testing_utils import TOKEN, USER, get_tests_dir, is_staging_test


sys.path.append(str(Path(__file__).parent.parent / '''utils'''))

from test_module.custom_feature_extraction import CustomFeatureExtractor  # noqa E402


lowercase__					:						Any												=			get_tests_dir('''fixtures''')




class  _UpperCAmelCase (    unittest.TestCase):

 def 		_snake_case      (  self	: Tuple       ):
     # A mock response for an HTTP head request to emulate server down
     snake_case_				:  str       =			mock.Mock()
     snake_case_				:  Optional[Any]       =			500
     snake_case_				:  str       =			{}
     snake_case_				:  Optional[int]       =			HTTPError
     snake_case_				:  Tuple       =			{}

     # Download this model to make sure it's in the cache.
     snake_case_				:  List[str]       =			WavaVecaFeatureExtractor.from_pretrained('''hf-internal-testing/tiny-random-wav2vec2'''       )
     # Under the mock environment we get a 500 error when trying to reach the model.
     with mock.patch('''requests.Session.request'''						,  return_value=lowercase_       ) as mock_head:
         snake_case_				:  int       =			WavaVecaFeatureExtractor.from_pretrained('''hf-internal-testing/tiny-random-wav2vec2'''       )
         # This check we did call the fake head request
         mock_head.assert_called()






 def 		_snake_case      (  self	: Union[str, Any]       ):
     # This test is for deprecated behavior and can be removed in v5
     snake_case_				:  str       =			WavaVecaFeatureExtractor.from_pretrained(
         '''https://huggingface.co/hf-internal-testing/tiny-random-wav2vec2/resolve/main/preprocessor_config.json'''       )





@is_staging_test
class  _UpperCAmelCase (    unittest.TestCase):

 @classmethod
 def 		_snake_case      (  cls	: int       ):
     snake_case_				:  Dict       =			TOKEN
     HfFolder.save_token(lowercase_       )

 @classmethod
 def 		_snake_case      (  cls	: str       ):
     try:
         delete_repo(token=cls._token						,  repo_id='''test-feature-extractor'''       )
     except HTTPError:
         pass

     try:
         delete_repo(token=cls._token						,  repo_id='''valid_org/test-feature-extractor-org'''       )
     except HTTPError:
         pass

     try:
         delete_repo(token=cls._token						,  repo_id='''test-dynamic-feature-extractor'''       )
     except HTTPError:
         pass

 def 		_snake_case      (  self	: Any       ):
     snake_case_				:  int       =			WavaVecaFeatureExtractor.from_pretrained(lowercase_       )
     feature_extractor.push_to_hub('''test-feature-extractor'''						,  use_auth_token=self._token       )

     snake_case_				:  Optional[Any]       =			WavaVecaFeatureExtractor.from_pretrained(f"{USER}/test-feature-extractor"       )
     for k, v in feature_extractor.__dict__.items():
         self.assertEqual(lowercase_						,  getattr(lowercase_						,  lowercase_       )       )

     # Reset repo
     delete_repo(token=self._token						,  repo_id='''test-feature-extractor'''       )

     # Push to hub via save_pretrained
     with tempfile.TemporaryDirectory() as tmp_dir:
         feature_extractor.save_pretrained(
             lowercase_						,  repo_id='''test-feature-extractor'''						,  push_to_hub=lowercase_						,  use_auth_token=self._token       )

     snake_case_				:  Optional[int]       =			WavaVecaFeatureExtractor.from_pretrained(f"{USER}/test-feature-extractor"       )
     for k, v in feature_extractor.__dict__.items():
         self.assertEqual(lowercase_						,  getattr(lowercase_						,  lowercase_       )       )

 def 		_snake_case      (  self	: Dict       ):
     snake_case_				:  Union[str, Any]       =			WavaVecaFeatureExtractor.from_pretrained(lowercase_       )
     feature_extractor.push_to_hub('''valid_org/test-feature-extractor'''						,  use_auth_token=self._token       )

     snake_case_				:  Optional[int]       =			WavaVecaFeatureExtractor.from_pretrained('''valid_org/test-feature-extractor'''       )
     for k, v in feature_extractor.__dict__.items():
         self.assertEqual(lowercase_						,  getattr(lowercase_						,  lowercase_       )       )

     # Reset repo
     delete_repo(token=self._token						,  repo_id='''valid_org/test-feature-extractor'''       )

     # Push to hub via save_pretrained
     with tempfile.TemporaryDirectory() as tmp_dir:
         feature_extractor.save_pretrained(
             lowercase_						,  repo_id='''valid_org/test-feature-extractor-org'''						,  push_to_hub=lowercase_						,  use_auth_token=self._token       )

     snake_case_				:  int       =			WavaVecaFeatureExtractor.from_pretrained('''valid_org/test-feature-extractor-org'''       )
     for k, v in feature_extractor.__dict__.items():
         self.assertEqual(lowercase_						,  getattr(lowercase_						,  lowercase_       )       )






 def 		_snake_case      (  self	: str       ):
     CustomFeatureExtractor.register_for_auto_class()
     snake_case_				:  Optional[Any]       =			CustomFeatureExtractor.from_pretrained(lowercase_       )

     feature_extractor.push_to_hub('''test-dynamic-feature-extractor'''						,  use_auth_token=self._token       )

     # This has added the proper auto_map field to the config
     self.assertDictEqual(
         feature_extractor.auto_map						,  {'''AutoFeatureExtractor''': '''custom_feature_extraction.CustomFeatureExtractor'''}						,  )

     snake_case_				:  Any       =			AutoFeatureExtractor.from_pretrained(
         f"{USER}/test-dynamic-feature-extractor"						,  trust_remote_code=lowercase_       )
     # Can't make an isinstance check because the new_feature_extractor is from the CustomFeatureExtractor class of a dynamic module
     self.assertEqual(new_feature_extractor.__class__.__name__						,  '''CustomFeatureExtractor'''       )





