

# Lint as: python3
import os
import re
import urllib.parse
from pathlib import Path
from typing import Callable, List, Optional, Union
from zipfile import ZipFile

from ..utils.file_utils import cached_path, hf_github_url
from ..utils.logging import get_logger
from ..utils.version import Version


_a:    Optional[int] 							=			get_logger(__name__)

class 						__UpperCamelCase    :
	SCREAMING_SNAKE_CASE__    				=     'dummy_data'
	SCREAMING_SNAKE_CASE__    				=     'datasets'
	SCREAMING_SNAKE_CASE__    				=     False




	def __init__(		self	:						Any		,	lowerCAmelCase	:						str		,	lowerCAmelCase	:						str		,	lowerCAmelCase	:						Union[Version, str]		,	lowerCAmelCase	:						Optional[str] = None		,	lowerCAmelCase	:						bool = False		,	lowerCAmelCase	:						bool = True		,	lowerCAmelCase	:						Optional[List[Callable]] = None		,	):


		'''simple docstring'''







		UpperCAmelCase_       				=			0
		UpperCAmelCase_       				=			dataset_name
		UpperCAmelCase_       				=			cache_dir
		UpperCAmelCase_       				=			use_local_dummy_data
		UpperCAmelCase_       				=			config
		# download_callbacks take a single url as input
		UpperCAmelCase_       				=			download_callbacks or []
		# if False, it doesn't load existing files and it returns the paths of the dummy files relative
		# to the dummy_data zip file root
		UpperCAmelCase_       				=			load_existing_dummy_data

		# TODO(PVP, QL) might need to make this more general
		UpperCAmelCase_       				=			str(lowerCAmelCase							)
		# to be downloaded
		UpperCAmelCase_       				=			None
		UpperCAmelCase_       				=			None




	@property
	def       __A					(		self	:						Dict							):


		'''simple docstring'''







		if self._dummy_file is None:
			UpperCAmelCase_       				=			self.download_dummy_data()
		return self._dummy_file




	@property
	def       __A					(		self	:						Optional[int]							):


		'''simple docstring'''







		if self.config is not None:
			# structure is dummy / config_name / version_name
			return os.path.join("dummy"		,	self.config.name		,	self.version_name							)
		# structure is dummy / version_name
		return os.path.join("dummy"		,	self.version_name							)




	@property
	def       __A					(		self	:						Tuple							):


		'''simple docstring'''







		return os.path.join(self.dummy_data_folder		,	"dummy_data.zip"							)




	def       __A					(		self	:						Dict							):


		'''simple docstring'''







		UpperCAmelCase_       				=			(
		    self.local_path_to_dummy_data if self.use_local_dummy_data is True else self.github_path_to_dummy_data
		)

		UpperCAmelCase_       				=			cached_path(
		    lowerCAmelCase		,	cache_dir=self.cache_dir		,	extract_compressed_file=lowerCAmelCase		,	force_extract=lowerCAmelCase							)

		return os.path.join(lowerCAmelCase		,	self.dummy_file_name							)




	@property
	def       __A					(		self	:						Tuple							):


		'''simple docstring'''







		return os.path.join(self.datasets_scripts_dir		,	self.dataset_name		,	self.dummy_zip_file							)




	@property
	def       __A					(		self	:						Union[str, Any]							):


		'''simple docstring'''







		if self._bucket_url is None:
			UpperCAmelCase_       				=			hf_github_url(self.dataset_name		,	self.dummy_zip_file.replace(os.sep		,	"/"							)							)
		return self._bucket_url




	@property
	def       __A					(		self	:						Tuple							):


		'''simple docstring'''







		if os.path.isdir(self.dummy_file							):
			return self.dummy_file
		# else cut off path to file -> example `xsum`.
		return "/".join(self.dummy_file.replace(os.sep		,	"/"							).split("/"							)[:-1]							)




	def       __A					(		self	:						List[str]		,	lowerCAmelCase	:						int		,	*lowerCAmelCase	:						int							):


		'''simple docstring'''







		if self.load_existing_dummy_data:
			# dummy data is downloaded and tested
			UpperCAmelCase_       				=			self.dummy_file
		else:
			# dummy data cannot be downloaded and only the path to dummy file is returned
			UpperCAmelCase_       				=			self.dummy_file_name

		# special case when data_url is a dict
		if isinstance(lowerCAmelCase		,	lowerCAmelCase							):
			return self.create_dummy_data_dict(lowerCAmelCase		,	lowerCAmelCase							)
		elif isinstance(lowerCAmelCase		,	(list, tuple)							):
			return self.create_dummy_data_list(lowerCAmelCase		,	lowerCAmelCase							)
		else:
			return self.create_dummy_data_single(lowerCAmelCase		,	lowerCAmelCase							)




	def       __A					(		self	:						Optional[int]		,	lowerCAmelCase	:						Tuple		,	*lowerCAmelCase	:						Optional[int]							):


		'''simple docstring'''







		return self.download_and_extract(lowerCAmelCase							)




	def       __A					(		self	:						Dict		,	lowerCAmelCase	:						str		,	lowerCAmelCase	:						Dict							):


		'''simple docstring'''







		return self.download_and_extract(lowerCAmelCase							)




	def       __A					(		self	:						Any		,	lowerCAmelCase	:						List[str]		,	*lowerCAmelCase	:						List[str]		,	**lowerCAmelCase	:						List[Any]							):


		'''simple docstring'''







		return path




	def       __A					(		self	:						str							):


		'''simple docstring'''







		return {}




	def       __A					(		self	:						Tuple		,	lowerCAmelCase	:						Optional[int]		,	lowerCAmelCase	:						Tuple							):


		'''simple docstring'''







		UpperCAmelCase_       				=			{}
		for key, single_urls in data_url.items():
			for download_callback in self.download_callbacks:
				if isinstance(lowerCAmelCase		,	lowerCAmelCase							):
					for single_url in single_urls:
						download_callback(lowerCAmelCase							)
				else:
					UpperCAmelCase_       				=			single_urls
					download_callback(lowerCAmelCase							)
            # we force the name of each key to be the last file / folder name of the url path
            # if the url has arguments, we need to encode them with urllib.parse.quote_plus
			if isinstance(lowerCAmelCase		,	lowerCAmelCase							):
				UpperCAmelCase_       				=			[os.path.join(lowerCAmelCase		,	urllib.parse.quote_plus(Path(lowerCAmelCase							).name							)							) for x in single_urls]
			else:
				UpperCAmelCase_       				=			single_urls
				UpperCAmelCase_       				=			os.path.join(lowerCAmelCase		,	urllib.parse.quote_plus(Path(lowerCAmelCase							).name							)							)
			UpperCAmelCase_       				=			value

		# make sure that values are unique
		if all(isinstance(lowerCAmelCase		,	lowerCAmelCase							) for i in dummy_data_dict.values()							) and len(set(dummy_data_dict.values()							)							) < len(
		    dummy_data_dict.values()							):
			# append key to value to make its name unique
			UpperCAmelCase_       				=			{key: value + key for key, value in dummy_data_dict.items()}

		return dummy_data_dict




	def       __A					(		self	:						Optional[Any]		,	lowerCAmelCase	:						int		,	lowerCAmelCase	:						Tuple							):


		'''simple docstring'''







		UpperCAmelCase_       				=			[]
		# trick: if there are many shards named like `data.txt-000001-of-00300`, only use the first one
		UpperCAmelCase_       				=			all(bool(re.findall("[0-9]{3,}-of-[0-9]{3,}"		,	lowerCAmelCase							)							) for url in data_url							)
		UpperCAmelCase_       				=			all(
		    url.startswith("https://ftp.ncbi.nlm.nih.gov/pubmed/baseline/pubmed"							) for url in data_url							)
		if data_url and (is_tf_records or is_pubmed_records):
			UpperCAmelCase_       				=			[data_url[0]] * len(lowerCAmelCase							)
		for single_url in data_url:
			for download_callback in self.download_callbacks:
				download_callback(lowerCAmelCase							)
			# we force the name of each key to be the last file / folder name of the url path
			# if the url has arguments, we need to encode them with urllib.parse.quote_plus
			UpperCAmelCase_       				=			os.path.join(lowerCAmelCase		,	urllib.parse.quote_plus(single_url.split("/"							)[-1]							)							)
			dummy_data_list.append(lowerCAmelCase							)
		return dummy_data_list




	def       __A					(		self	:						Union[str, Any]		,	lowerCAmelCase	:						Tuple		,	lowerCAmelCase	:						List[Any]							):


		'''simple docstring'''







		for download_callback in self.download_callbacks:
			download_callback(lowerCAmelCase							)
		# we force the name of each key to be the last file / folder name of the url path
		# if the url has arguments, we need to encode them with urllib.parse.quote_plus
		UpperCAmelCase_       				=			os.path.join(lowerCAmelCase		,	urllib.parse.quote_plus(data_url.split("/"							)[-1]							)							)
		if os.path.exists(lowerCAmelCase							) or not self.load_existing_dummy_data:
			return value
		else:
			# Backward compatibility, maybe deprecate at one point.
			# For many datasets with single url calls to dl_manager.download_and_extract,
			# the dummy_data.zip file is actually the zipped downloaded file
			# while now we expected the dummy_data.zip file to be a directory containing
			# the downloaded file.
			return path_to_dummy_data




	def       __A					(		self	:						Any							):


		'''simple docstring'''







		pass




	def       __A					(		self	:						List[Any]							):


		'''simple docstring'''







		pass




	def       __A					(		self	:						str		,	lowerCAmelCase	:						Optional[int]							):


		'''simple docstring'''







		def _iter_archive_members(lowerCAmelCase	:						str							):
			# this preserves the order of the members inside the ZIP archive
			UpperCAmelCase_       				=			Path(self.dummy_file							).parent
			UpperCAmelCase_       				=			path.relative_to(lowerCAmelCase							)
			with ZipFile(self.local_path_to_dummy_data							) as zip_file:
				UpperCAmelCase_       				=			zip_file.namelist()
			for member in members:
				if member.startswith(relative_path.as_posix()							):
					yield dummy_parent_path.joinpath(lowerCAmelCase							)

		UpperCAmelCase_       				=			Path(lowerCAmelCase							)
		UpperCAmelCase_       				=			_iter_archive_members(lowerCAmelCase							) if self.use_local_dummy_data else path.rglob("*"							)
		for file_path in file_paths:
			if file_path.is_file() and not file_path.name.startswith((".", "__")							):
				yield file_path.relative_to(lowerCAmelCase							).as_posix(), file_path.open("rb"							)




	def       __A					(		self	:						Dict		,	lowerCAmelCase	:						List[Any]							):


		'''simple docstring'''







		if not isinstance(lowerCAmelCase		,	lowerCAmelCase							):
			UpperCAmelCase_       				=			[paths]
		for path in paths:
			if os.path.isfile(lowerCAmelCase							):
				if os.path.basename(lowerCAmelCase							).startswith((".", "__")							):
					return
				yield path
			else:
				for dirpath, dirnames, filenames in os.walk(lowerCAmelCase							):
					if os.path.basename(lowerCAmelCase							).startswith((".", "__")							):
						continue
					dirnames.sort()
					for filename in sorted(lowerCAmelCase							):
						if filename.startswith((".", "__")							):
							continue
						yield os.path.join(lowerCAmelCase		,	lowerCAmelCase							)


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

import numpy as np
from utils_multiple_choice import MultipleChoiceDataset, Split, processors

import transformers
from transformers import (
    AutoConfig,
    AutoModelForMultipleChoice,
    AutoTokenizer,
    DataCollatorWithPadding,
    EvalPrediction,
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    set_seed,
)
from transformers.trainer_utils import is_main_process


_a:    int 							=			logging.getLogger(__name__)



def       __lowerCAmelCase      (						A       ,     A    ):
	return (preds == labels).mean()

@dataclass
class 						__UpperCamelCase    :
	SCREAMING_SNAKE_CASE__    				=     field(
	    metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'}						)
	SCREAMING_SNAKE_CASE__    				=     field(
	    default=lowercase     ,     metadata={'help': 'Pretrained config name or path if not the same as model_name'}						)
	SCREAMING_SNAKE_CASE__    				=     field(
	    default=lowercase     ,     metadata={'help': 'Pretrained tokenizer name or path if not the same as model_name'}						)
	SCREAMING_SNAKE_CASE__    				=     field(
	    default=lowercase     ,     metadata={'help': 'Where do you want to store the pretrained models downloaded from huggingface.co'}     ,     )


@dataclass
class 						__UpperCamelCase    :
	SCREAMING_SNAKE_CASE__    				=     field(metadata={'help': 'The name of the task to train on: ' + ', '.join(processors.keys()						)}						)
	SCREAMING_SNAKE_CASE__    				=     field(metadata={'help': 'Should contain the data files for the task.'}						)
	SCREAMING_SNAKE_CASE__    				=     field(
	    default=1_28     ,     metadata={
	        'help': (
	            'The maximum total input sequence length after tokenization. Sequences longer '
	            'than this will be truncated, sequences shorter will be padded.'
	        )
	    }     ,     )
	SCREAMING_SNAKE_CASE__    				=     field(
	    default=lowercase     ,     metadata={'help': 'Overwrite the cached training and evaluation sets'}						)



def       __lowerCAmelCase      (						):
	# 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.

	UpperCAmelCase_       				=			HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)    )
	UpperCAmelCase_				,   UpperCAmelCase_				,   UpperCAmelCase_       				=			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 if training_args.local_rank in [-1, 0] else logging.WARN       ,     )
	logger.warning(
	    "Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s"       ,     training_args.local_rank       ,     training_args.device       ,     training_args.n_gpu       ,     bool(training_args.local_rank != -1    )       ,     training_args.fpaa       ,     )
	# Set the verbosity to info of the Transformers logger (on main process only):
	if is_main_process(training_args.local_rank    ):
		transformers.utils.logging.set_verbosity_info()
		transformers.utils.logging.enable_default_handler()
		transformers.utils.logging.enable_explicit_format()
	logger.info("Training/evaluation parameters %s"       ,     A    )

	# Set seed
	set_seed(training_args.seed    )

	try:
		UpperCAmelCase_       				=			processors[data_args.task_name]()
		UpperCAmelCase_       				=			processor.get_labels()
		UpperCAmelCase_       				=			len(A    )
	except KeyError:
		raise ValueError("Task not found: %s" % (data_args.task_name)    )

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

	UpperCAmelCase_       				=			AutoConfig.from_pretrained(
	    model_args.config_name if model_args.config_name else model_args.model_name_or_path       ,     num_labels=A       ,     finetuning_task=data_args.task_name       ,     cache_dir=model_args.cache_dir       ,     )
	UpperCAmelCase_       				=			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       ,     )
	UpperCAmelCase_       				=			AutoModelForMultipleChoice.from_pretrained(
	    model_args.model_name_or_path       ,     from_tf=bool(".ckpt" in model_args.model_name_or_path    )       ,     config=A       ,     cache_dir=model_args.cache_dir       ,     )

	# Get datasets
	UpperCAmelCase_       				=			(
	    MultipleChoiceDataset(
	        data_dir=data_args.data_dir       ,     tokenizer=A       ,     task=data_args.task_name       ,     max_seq_length=data_args.max_seq_length       ,     overwrite_cache=data_args.overwrite_cache       ,     mode=Split.train       ,     )
	    if training_args.do_train
	    else None
	)
	UpperCAmelCase_       				=			(
	    MultipleChoiceDataset(
	        data_dir=data_args.data_dir       ,     tokenizer=A       ,     task=data_args.task_name       ,     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 compute_metrics(A    ) -> Dict:
		UpperCAmelCase_       				=			np.argmax(p.predictions       ,     axis=1    )
		return {"acc": simple_accuracy(A       ,     p.label_ids    )}

	# Data collator
	UpperCAmelCase_       				=			DataCollatorWithPadding(A       ,     pad_to_multiple_of=8    ) if training_args.fpaa else None

	# Initialize our Trainer
	UpperCAmelCase_       				=			Trainer(
	    model=A       ,     args=A       ,     train_dataset=A       ,     eval_dataset=A       ,     compute_metrics=A       ,     data_collator=A       ,     )

	# Training
	if training_args.do_train:
		trainer.train(
		    model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path    ) else None    )
		trainer.save_model()
		# For convenience, we also re-save the tokenizer to the same directory,
		# so that you can share your model easily on huggingface.co/models =)
		if trainer.is_world_master():
			tokenizer.save_pretrained(training_args.output_dir    )

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

		UpperCAmelCase_       				=			trainer.evaluate()

		UpperCAmelCase_       				=			os.path.join(training_args.output_dir       ,     "eval_results.txt"    )
		if trainer.is_world_master():
			with open(A       ,     "w"    ) as writer:
				logger.info("***** Eval results *****"    )
				for key, value in result.items():
					logger.info("  %s = %s"       ,     A       ,     A    )
					writer.write("%s = %s\n" % (key, value)    )

				results.update(A    )

	return results



def       __lowerCAmelCase      (						A    ):
	# For xla_spawn (TPUs)
	main()


if __name__ == "__main__":
				main()