






import logging
import os
from dataclasses import dataclass, field
from importlib import import_module
from typing import Dict, List, Optional, Tuple

import numpy as np
from seqeval.metrics import classification_report, fa_score, precision_score, recall_score
from utils_ner import Split, TFTokenClassificationDataset, TokenClassificationTask

from transformers import (
    AutoConfig,
    AutoTokenizer,
    EvalPrediction,
    HfArgumentParser,
    TFAutoModelForTokenClassification,
    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()


A__     :      Optional[int]             =			logging.getLogger(__name__)
@dataclass
class 				_UpperCAmelCase :

				"""simple docstring"""




				lowercase__    							=	field(
				    metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""}     )
				lowercase__    							=	field(
				    default=A__		,metadata={"""help""": """Pretrained config name or path if not the same as model_name"""}     )
				lowercase__    							=	field(
				    default="""NER"""		,metadata={"""help""": """Task type to fine tune in training (e.g. NER, POS, etc)"""}     )
				lowercase__    							=	field(
				    default=A__		,metadata={"""help""": """Pretrained tokenizer name or path if not the same as model_name"""}     )
				lowercase__    							=	field(default=A__		,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.
				lowercase__    							=	field(
				    default=A__		,metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""}		,)



@dataclass
class 				_UpperCAmelCase :

				"""simple docstring"""




				lowercase__    							=	field(
				    metadata={"""help""": """The input data dir. Should contain the .txt files for a CoNLL-2003-formatted task."""}     )
				lowercase__    							=	field(
				    metadata={"""help""": """Path to a file containing all labels. If not specified, CoNLL-2003 labels are used."""}     )
				lowercase__    							=	field(
				    default=128		,metadata={
				        """help""": (
				            """The maximum total input sequence length after tokenization. Sequences longer """
				            """than this will be truncated, sequences shorter will be padded."""
				        )
				    }		,)
				lowercase__    							=	field(
				    default=A__		,metadata={"""help""": """Overwrite the cached training and evaluation sets"""}     )






def   a      (						):






				'''simple docstring'''
				# 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.
				lowercase__       			=      HfArgumentParser((ModelArguments, DataTrainingArguments, TFTrainingArguments)    )
				lowercase__			,						lowercase__			,						lowercase__       			=      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.'''    )

				lowercase__       			=      import_module('''tasks'''    )

				try:
								lowercase__       			=      getattr(lowerCamelCase_		,       model_args.task_type    )
								lowercase__       			=      token_classification_task_clazz()
				except AttributeError:
								raise ValueError(
								    F"""Task {model_args.task_type} needs to be defined as a TokenClassificationTask subclass in {module}. """
								    F"""Available tasks classes are: {TokenClassificationTask.__subclasses__()}"""    )

				# 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(
				    '''n_replicas: %s, distributed training: %s, 16-bits training: %s'''		,       training_args.n_replicas		,       bool(training_args.n_replicas > 1    )		,       training_args.fpaa		,       )
				logger.info('''Training/evaluation parameters %s'''		,       lowerCamelCase_    )

				# Prepare Token Classification task
				lowercase__       			=      token_classification_task.get_labels(data_args.labels    )
				lowercase__       			=      dict(enumerate(lowerCamelCase_    )    )
				lowercase__       			=      len(lowerCamelCase_    )

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

				lowercase__       			=      AutoConfig.from_pretrained(
				    model_args.config_name if model_args.config_name else model_args.model_name_or_path		,       num_labels=lowerCamelCase_		,       idalabel=lowerCamelCase_		,       labelaid={label: i for i, label in enumerate(lowerCamelCase_    )}		,       cache_dir=model_args.cache_dir		,       )
				lowercase__       			=      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		,       use_fast=model_args.use_fast		,       )

				with training_args.strategy.scope():
								lowercase__       			=      TFAutoModelForTokenClassification.from_pretrained(
								    model_args.model_name_or_path		,       from_pt=bool('''.bin''' in model_args.model_name_or_path    )		,       config=lowerCamelCase_		,       cache_dir=model_args.cache_dir		,       )

				# Get datasets
				lowercase__       			=      (
				    TFTokenClassificationDataset(
				        token_classification_task=lowerCamelCase_		,       data_dir=data_args.data_dir		,       tokenizer=lowerCamelCase_		,       labels=lowerCamelCase_		,       model_type=config.model_type		,       max_seq_length=data_args.max_seq_length		,       overwrite_cache=data_args.overwrite_cache		,       mode=Split.train		,       )
				    if training_args.do_train
				    else None
				)
				lowercase__       			=      (
				    TFTokenClassificationDataset(
				        token_classification_task=lowerCamelCase_		,       data_dir=data_args.data_dir		,       tokenizer=lowerCamelCase_		,       labels=lowerCamelCase_		,       model_type=config.model_type		,       max_seq_length=data_args.max_seq_length		,       overwrite_cache=data_args.overwrite_cache		,       mode=Split.dev		,       )
				    if training_args.do_eval
				    else None
				)

				def align_predictions(lowerCamelCase_		,       lowerCamelCase_    ) -> Tuple[List[int], List[int]]:
								lowercase__       			=      np.argmax(lowerCamelCase_		,       axis=2    )
								lowercase__			,						lowercase__       			=      preds.shape
								lowercase__       			=      [[] for _ in range(lowerCamelCase_    )]
								lowercase__       			=      [[] for _ in range(lowerCamelCase_    )]

								for i in range(lowerCamelCase_    ):
												for j in range(lowerCamelCase_    ):
																if label_ids[i, j] != -100:
																				out_label_list[i].append(label_map[label_ids[i][j]]    )
																				preds_list[i].append(label_map[preds[i][j]]    )

								return preds_list, out_label_list

				def compute_metrics(lowerCamelCase_    ) -> Dict:
								lowercase__			,						lowercase__       			=      align_predictions(p.predictions		,       p.label_ids    )

								return {
								    "precision": precision_score(lowerCamelCase_		,       lowerCamelCase_    ),
								    "recall": recall_score(lowerCamelCase_		,       lowerCamelCase_    ),
								    "f1": fa_score(lowerCamelCase_		,       lowerCamelCase_    ),
								}

				# Initialize our Trainer
				lowercase__       			=      TFTrainer(
				    model=lowerCamelCase_		,       args=lowerCamelCase_		,       train_dataset=train_dataset.get_dataset() if train_dataset else None		,       eval_dataset=eval_dataset.get_dataset() if eval_dataset else None		,       compute_metrics=lowerCamelCase_		,       )

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

				# Evaluation
				lowercase__       			=      {}
				if training_args.do_eval:
								logger.info('''*** Evaluate ***'''    )

								lowercase__       			=      trainer.evaluate()
								lowercase__       			=      os.path.join(training_args.output_dir		,       '''eval_results.txt'''    )

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

												for key, value in result.items():
																logger.info('''  %s = %s'''		,       lowerCamelCase_		,       lowerCamelCase_    )
																writer.write('''%s = %s\n''' % (key, value)    )

												results.update(lowerCamelCase_    )

    # Predict
				if training_args.do_predict:
								lowercase__       			=      TFTokenClassificationDataset(
								    token_classification_task=lowerCamelCase_		,       data_dir=data_args.data_dir		,       tokenizer=lowerCamelCase_		,       labels=lowerCamelCase_		,       model_type=config.model_type		,       max_seq_length=data_args.max_seq_length		,       overwrite_cache=data_args.overwrite_cache		,       mode=Split.test		,       )

								lowercase__			,						lowercase__			,						lowercase__       			=      trainer.predict(test_dataset.get_dataset()    )
								lowercase__			,						lowercase__       			=      align_predictions(lowerCamelCase_		,       lowerCamelCase_    )
								lowercase__       			=      classification_report(lowerCamelCase_		,       lowerCamelCase_    )

								logger.info('''\n%s'''		,       lowerCamelCase_    )

								lowercase__       			=      os.path.join(training_args.output_dir		,       '''test_results.txt'''    )

								with open(lowerCamelCase_		,       '''w'''    ) as writer:
												writer.write('''%s\n''' % report    )

								# Save predictions
								lowercase__       			=      os.path.join(training_args.output_dir		,       '''test_predictions.txt'''    )

								with open(lowerCamelCase_		,       '''w'''    ) as writer:
												with open(os.path.join(data_args.data_dir		,       '''test.txt'''    )		,       '''r'''    ) as f:
																lowercase__       			=      0

																for line in f:
																				if line.startswith('''-DOCSTART-'''    ) or line == "" or line == "\n":
																								writer.write(lowerCamelCase_    )

																								if not preds_list[example_id]:
																												example_id += 1
																				elif preds_list[example_id]:
																								lowercase__       			=      line.split()[0] + ''' ''' + preds_list[example_id].pop(0    ) + '''\n'''

																								writer.write(lowerCamelCase_    )
																				else:
																								logger.warning('''Maximum sequence length exceeded: No prediction for \'%s\'.'''		,       line.split()[0]    )

				return results


if __name__ == "__main__":
							main()












import importlib
import os
import platform
from pathlib import Path

from packaging import version

from .utils.logging import get_logger


A__     :      List[Any]             =			get_logger(__name__)

# Datasets
A__     :      Union[str, Any]             =			'https://s3.amazonaws.com/datasets.huggingface.co/datasets/datasets'
A__     :      Dict             =			'https://cdn-datasets.huggingface.co/datasets/datasets'
A__     :      str             =			'https://raw.githubusercontent.com/huggingface/datasets/{revision}/datasets/{path}/{name}'

# Metrics
A__     :      Optional[int]             =			'https://s3.amazonaws.com/datasets.huggingface.co/datasets/metrics'
A__     :      Optional[Any]             =			'https://cdn-datasets.huggingface.co/datasets/metric'
A__     :      Tuple             =			'https://raw.githubusercontent.com/huggingface/datasets/{revision}/metrics/{path}/{name}'

# Hub
A__     :      int             =			os.environ.get('HF_ENDPOINT', 'https://huggingface.co')
A__     :      str             =			HF_ENDPOINT + '/datasets/{repo_id}/resolve/{revision}/{path}'
A__     :      Any             =			'main'

A__     :      Tuple             =			version.parse(platform.python_version())

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

# General environment variables accepted values for booleans
A__     :      List[str]             =			{'1', 'ON', 'YES', 'TRUE'}
A__     :      List[Any]             =			ENV_VARS_TRUE_VALUES.union({'AUTO'})


# Imports
A__     :      List[str]             =			version.parse(importlib_metadata.version('dill'))
A__     :      int             =			version.parse(importlib_metadata.version('pandas'))
A__     :      Optional[Any]             =			version.parse(importlib_metadata.version('pyarrow'))

A__     :      Union[str, Any]             =			os.environ.get('USE_TF', 'AUTO').upper()
A__     :      List[Any]             =			os.environ.get('USE_TORCH', 'AUTO').upper()
A__     :      Optional[Any]             =			os.environ.get('USE_JAX', 'AUTO').upper()

A__     :      List[Any]             =			'N/A'
A__     :      int             =			False

if USE_TORCH in ENV_VARS_TRUE_AND_AUTO_VALUES and USE_TF not in ENV_VARS_TRUE_VALUES:
							A__     :      List[str]             =			importlib.util.find_spec('torch') is not None
							if TORCH_AVAILABLE:
														try:
																					A__     :      Union[str, Any]             =			version.parse(importlib_metadata.version('torch'))
																					logger.info(F"PyTorch version {TORCH_VERSION} available.")
														except importlib_metadata.PackageNotFoundError:
																					pass
else:
							logger.info('Disabling PyTorch because USE_TF is set')

A__     :      int             =			'N/A'
A__     :      Optional[int]             =			False

if USE_TF in ENV_VARS_TRUE_AND_AUTO_VALUES and USE_TORCH not in ENV_VARS_TRUE_VALUES:
							A__     :      Optional[int]             =			importlib.util.find_spec('tensorflow') is not None
							if TF_AVAILABLE:
														# For the metadata, we have to look for both tensorflow and tensorflow-cpu
														for package in [
														    "tensorflow",
														    "tensorflow-cpu",
														    "tensorflow-gpu",
														    "tf-nightly",
														    "tf-nightly-cpu",
														    "tf-nightly-gpu",
														    "intel-tensorflow",
														    "tensorflow-rocm",
														    "tensorflow-macos",
														]:
																					try:
																												A__     :      Any             =			version.parse(importlib_metadata.version(package))
																					except importlib_metadata.PackageNotFoundError:
																												continue
																					else:
																												break
														else:
																					A__     :      Tuple             =			False
							if TF_AVAILABLE:
														if TF_VERSION.major < 2:
																					logger.info(F"TensorFlow found but with version {TF_VERSION}. `datasets` requires version 2 minimum.")
																					A__     :      Any             =			False
														else:
																					logger.info(F"TensorFlow version {TF_VERSION} available.")
else:
							logger.info('Disabling Tensorflow because USE_TORCH is set')


A__     :      Union[str, Any]             =			'N/A'
A__     :      str             =			False

if USE_JAX in ENV_VARS_TRUE_AND_AUTO_VALUES:
							A__     :      Union[str, Any]             =			importlib.util.find_spec('jax') is not None and importlib.util.find_spec('jaxlib') is not None
							if JAX_AVAILABLE:
														try:
																					A__     :      str             =			version.parse(importlib_metadata.version('jax'))
																					logger.info(F"JAX version {JAX_VERSION} available.")
														except importlib_metadata.PackageNotFoundError:
																					pass
else:
							logger.info('Disabling JAX because USE_JAX is set to False')


A__     :      str             =			os.environ.get('USE_BEAM', 'AUTO').upper()
A__     :      List[Any]             =			'N/A'
A__     :      Tuple             =			False
if USE_BEAM in ENV_VARS_TRUE_AND_AUTO_VALUES:
							try:
														A__     :      str             =			version.parse(importlib_metadata.version('apache_beam'))
														A__     :      Any             =			True
														logger.info(F"Apache Beam version {BEAM_VERSION} available.")
							except importlib_metadata.PackageNotFoundError:
														pass
else:
							logger.info('Disabling Apache Beam because USE_BEAM is set to False')


# Optional tools for data loading
A__     :      Optional[int]             =			importlib.util.find_spec('sqlalchemy') is not None

# Optional tools for feature decoding
A__     :      List[str]             =			importlib.util.find_spec('PIL') is not None
A__     :      Optional[Any]             =			importlib.util.find_spec('soundfile') is not None and version.parse(
    importlib.import_module('soundfile').__libsndfile_version__
) >= version.parse('1.0.31')
A__     :      Tuple             =			importlib.util.find_spec('soundfile') is not None and version.parse(
    importlib.import_module('soundfile').__libsndfile_version__
) >= version.parse('1.1.0')

# Optional compression tools
A__     :      List[Any]             =			importlib.util.find_spec('rarfile') is not None
A__     :      Union[str, Any]             =			importlib.util.find_spec('zstandard') is not None
A__     :      Any             =			importlib.util.find_spec('lz4') is not None
A__     :      int             =			importlib.util.find_spec('py7zr') is not None


# Cache location
A__     :      Tuple             =			'~/.cache'
A__     :      Dict             =			os.getenv('XDG_CACHE_HOME', DEFAULT_XDG_CACHE_HOME)
A__     :      Dict             =			os.path.join(XDG_CACHE_HOME, 'huggingface')
A__     :      Tuple             =			os.path.expanduser(os.getenv('HF_HOME', DEFAULT_HF_CACHE_HOME))

A__     :      str             =			os.path.join(HF_CACHE_HOME, 'datasets')
A__     :      List[Any]             =			Path(os.getenv('HF_DATASETS_CACHE', DEFAULT_HF_DATASETS_CACHE))

A__     :      Optional[int]             =			os.path.join(HF_CACHE_HOME, 'metrics')
A__     :      Optional[int]             =			Path(os.getenv('HF_METRICS_CACHE', DEFAULT_HF_METRICS_CACHE))

A__     :      List[str]             =			os.path.join(HF_CACHE_HOME, 'modules')
A__     :      List[Any]             =			Path(os.getenv('HF_MODULES_CACHE', DEFAULT_HF_MODULES_CACHE))

A__     :      Optional[int]             =			'downloads'
A__     :      Optional[int]             =			os.path.join(HF_DATASETS_CACHE, DOWNLOADED_DATASETS_DIR)
A__     :      int             =			Path(os.getenv('HF_DATASETS_DOWNLOADED_DATASETS_PATH', DEFAULT_DOWNLOADED_DATASETS_PATH))

A__     :      Optional[int]             =			'extracted'
A__     :      Union[str, Any]             =			os.path.join(DEFAULT_DOWNLOADED_DATASETS_PATH, EXTRACTED_DATASETS_DIR)
A__     :      Tuple             =			Path(os.getenv('HF_DATASETS_EXTRACTED_DATASETS_PATH', DEFAULT_EXTRACTED_DATASETS_PATH))

# Download count for the website
A__     :      List[str]             =			(
    os.environ.get('HF_UPDATE_DOWNLOAD_COUNTS', 'AUTO').upper() in ENV_VARS_TRUE_AND_AUTO_VALUES
)

# Batch size constants. For more info, see:
# https://github.com/apache/arrow/blob/master/docs/source/cpp/arrays.rst#size-limitations-and-recommendations)
A__     :      List[Any]             =			10_00

# Size of the preloaded record batch in `Dataset.__iter__`
A__     :      int             =			10

# Pickling tables works only for small tables (<4GiB)
# For big tables, we write them on disk instead
A__     :      str             =			4 << 30

# Max shard size in bytes (e.g. to shard parquet datasets in push_to_hub or download_and_prepare)
A__     :      Dict             =			'500MB'

# Parquet configuration
A__     :      Optional[Any]             =			1_00
A__     :      List[Any]             =			1_00
A__     :      Tuple             =			1_00

# Offline mode
A__     :      Optional[Any]             =			os.environ.get('HF_DATASETS_OFFLINE', 'AUTO').upper() in ENV_VARS_TRUE_VALUES

# In-memory
A__     :      Union[str, Any]             =			0  # Disabled
A__     :      Tuple             =			float(os.environ.get('HF_DATASETS_IN_MEMORY_MAX_SIZE', DEFAULT_IN_MEMORY_MAX_SIZE))

# File names
A__     :      str             =			'dataset.arrow'
A__     :      List[str]             =			'indices.arrow'
A__     :      List[Any]             =			'state.json'
A__     :      int             =			'dataset_info.json'
A__     :      Tuple             =			'dataset_infos.json'
A__     :      int             =			'LICENSE'
A__     :      Union[str, Any]             =			'metric_info.json'
A__     :      List[Any]             =			'dataset_dict.json'

A__     :      Optional[Any]             =			'datasets_modules'

A__     :      Dict             =			2_55

# Streaming
A__     :      Optional[Any]             =			20
A__     :      str             =			5

# Datasets without script
A__     :      Optional[int]             =			2_00
A__     :      Optional[Any]             =			10
A__     :      Any             =			2_00

# Progress bars
A__     :      Any             =			0.05  # 20 progress updates per sec




