
import os
import time
from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, List, Optional, Union

import torch
from filelock import FileLock
from torch.utils.data import Dataset

from ...models.auto.modeling_auto import MODEL_FOR_QUESTION_ANSWERING_MAPPING
from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging
from ..processors.squad import SquadFeatures, SquadVaProcessor, SquadVaProcessor, squad_convert_examples_to_features


UpperCAmelCase	      = logging.get_logger(__name__)

UpperCAmelCase	      = list(MODEL_FOR_QUESTION_ANSWERING_MAPPING.keys())
UpperCAmelCase	      = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)







@dataclass
class        A_   :




	'''simple docstring'''


	_UpperCamelCase     :     str							 =       field(
	    default=__lowerCamelCase      ,	metadata={"""help""": """Model type selected in the list: """ + """, """.join(__lowerCamelCase   )}   )
	_UpperCamelCase     :     str							 =       field(
	    default=__lowerCamelCase      ,	metadata={"""help""": """The input data dir. Should contain the .json files for the SQuAD task."""}   )
	_UpperCamelCase     :     int							 =       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."""
	        )
	    }      ,	)
	_UpperCamelCase     :     int							 =       field(
	    default=128      ,	metadata={"""help""": """When splitting up a long document into chunks, how much stride to take between chunks."""}      ,	)
	_UpperCamelCase     :     int							 =       field(
	    default=64      ,	metadata={
	        """help""": (
	            """The maximum number of tokens for the question. Questions longer than this will """
	            """be truncated to this length."""
	        )
	    }      ,	)
	_UpperCamelCase     :     int							 =       field(
	    default=30      ,	metadata={
	        """help""": (
	            """The maximum length of an answer that can be generated. This is needed because the start """
	            """and end predictions are not conditioned on one another."""
	        )
	    }      ,	)
	_UpperCamelCase     :     bool							 =       field(
	    default=__lowerCamelCase      ,	metadata={"""help""": """Overwrite the cached training and evaluation sets"""}   )
	_UpperCamelCase     :     bool							 =       field(
	    default=__lowerCamelCase      ,	metadata={"""help""": """If true, the SQuAD examples contain some that do not have an answer."""}   )
	_UpperCamelCase     :     float							 =       field(
	    default=0.0      ,	metadata={"""help""": """If null_score - best_non_null is greater than the threshold predict null."""}   )
	_UpperCamelCase     :     int							 =       field(
	    default=20      ,	metadata={"""help""": """If null_score - best_non_null is greater than the threshold predict null."""}   )
	_UpperCamelCase     :     int							 =       field(
	    default=0      ,	metadata={
	        """help""": (
	            """language id of input for language-specific xlm models (see"""
	            """ tokenization_xlm.PRETRAINED_INIT_CONFIGURATION)"""
	        )
	    }      ,	)
	_UpperCamelCase     :     int							 =       field(default=1      ,	metadata={"""help""": """multiple threads for converting example to features"""}   )







class        A_   (			__lowerCamelCase   ):




	'''simple docstring'''


	_UpperCamelCase     :     List[Any]							 =       """train"""
	_UpperCamelCase     :     Tuple							 =       """dev"""







class        A_   (			__lowerCamelCase   ):




	'''simple docstring'''


	_UpperCamelCase     :     SquadDataTrainingArguments
	_UpperCamelCase     :     List[SquadFeatures]
	_UpperCamelCase     :     Split
	_UpperCamelCase     :     bool





	def __init__(       self		,    snake_case		,    snake_case		,    snake_case = None		,    snake_case = Split.train		,    snake_case = False		,    snake_case = None		,    snake_case = "pt"		,    ):
		lowercase       =    args
		lowercase       =    is_language_sensitive
		lowercase       =    SquadVaProcessor() if args.version_2_with_negative else SquadVaProcessor()
		if isinstance(snake_case		,    snake_case       ):
			try:
				lowercase       =    Split[mode]
			except KeyError:
				raise KeyError('mode is not a valid split name'       )
		lowercase       =    mode
		# Load data features from cache or dataset file
		lowercase       =    'v2' if args.version_2_with_negative else 'v1'
		lowercase       =    os.path.join(
		    cache_dir if cache_dir is not None else args.data_dir		,    F'''cached_{mode.value}_{tokenizer.__class__.__name__}_{args.max_seq_length}_{version_tag}'''		,    )

		# Make sure only the first process in distributed training processes the dataset,
		# and the others will use the cache.
		lowercase       =    cached_features_file + '.lock'
		with FileLock(snake_case       ):
			if os.path.exists(snake_case       ) and not args.overwrite_cache:
				lowercase       =    time.time()
				lowercase       =    torch.load(snake_case       )

				# Legacy cache files have only features, while new cache files
				# will have dataset and examples also.
				lowercase       =    self.old_features['features']
				lowercase       =    self.old_features.get('dataset'		,    snake_case       )
				lowercase       =    self.old_features.get('examples'		,    snake_case       )
				logger.info(
				    F'''Loading features from cached file {cached_features_file} [took %.3f s]'''		,    time.time() - start       )

				if self.dataset is None or self.examples is None:
					logger.warning(
					    F'''Deleting cached file {cached_features_file} will allow dataset and examples to be cached in'''
					    ' future run'       )
			else:
				if mode == Split.dev:
					lowercase       =    self.processor.get_dev_examples(args.data_dir       )
				else:
					lowercase       =    self.processor.get_train_examples(args.data_dir       )

				lowercase  ,					lowercase       =    squad_convert_examples_to_features(
				    examples=self.examples		,    tokenizer=snake_case		,    max_seq_length=args.max_seq_length		,    doc_stride=args.doc_stride		,    max_query_length=args.max_query_length		,    is_training=mode == Split.train		,    threads=args.threads		,    return_dataset=snake_case		,    )

				lowercase       =    time.time()
				torch.save(
				    {'features': self.features, 'dataset': self.dataset, 'examples': self.examples}		,    snake_case		,    )
				# ^ This seems to take a lot of time so I want to investigate why and how we can improve.
				logger.info(
				    F'''Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]'''       )





	def __len__(       self       ):
		return len(self.features       )





	def __getitem__(       self		,    snake_case       ):
		# Convert to Tensors and build dataset
		lowercase       =    self.features[i]

		lowercase       =    torch.tensor(feature.input_ids		,    dtype=torch.long       )
		lowercase       =    torch.tensor(feature.attention_mask		,    dtype=torch.long       )
		lowercase       =    torch.tensor(feature.token_type_ids		,    dtype=torch.long       )
		lowercase       =    torch.tensor(feature.cls_index		,    dtype=torch.long       )
		lowercase       =    torch.tensor(feature.p_mask		,    dtype=torch.float       )
		lowercase       =    torch.tensor(feature.is_impossible		,    dtype=torch.float       )

		lowercase       =    {
		    'input_ids': input_ids,
		    'attention_mask': attention_mask,
		    'token_type_ids': token_type_ids,
		}

		if self.args.model_type in ["xlm", "roberta", "distilbert", "camembert"]:
			del inputs["token_type_ids"]

		if self.args.model_type in ["xlnet", "xlm"]:
			inputs.update({'cls_index': cls_index, 'p_mask': p_mask}       )
			if self.args.version_2_with_negative:
				inputs.update({'is_impossible': is_impossible}       )
			if self.is_language_sensitive:
				inputs.update({'langs': (torch.ones(input_ids.shape		,    dtype=torch.intaa       ) * self.args.lang_id)}       )

		if self.mode == Split.train:
			lowercase       =    torch.tensor(feature.start_position		,    dtype=torch.long       )
			lowercase       =    torch.tensor(feature.end_position		,    dtype=torch.long       )
			inputs.update({'start_positions': start_positions, 'end_positions': end_positions}       )

		return inputs



import os
from datetime import datetime as dt

from github import Github


UpperCAmelCase	      = [
    '''good first issue''',
    '''good second issue''',
    '''good difficult issue''',
    '''enhancement''',
    '''new pipeline/model''',
    '''new scheduler''',
    '''wip''',
]






def 							UpperCAmelCase_		(							):
	lowercase       =    Github(os.environ['GITHUB_TOKEN']							)
	lowercase       =    g.get_repo('huggingface/diffusers'							)
	lowercase       =    repo.get_issues(state='open'							)

	for issue in open_issues:
		lowercase       =    sorted(issue.get_comments() ,							key=lambda __SCREAMING_SNAKE_CASE							: i.created_at ,							reverse=__SCREAMING_SNAKE_CASE							)
		lowercase       =    comments[0] if len(__SCREAMING_SNAKE_CASE							) > 0 else None
		if (
		    last_comment is not None
		    and last_comment.user.login == "github-actions[bot]"
		    and (dt.utcnow() - issue.updated_at).days > 7
		    and (dt.utcnow() - issue.created_at).days >= 30
		    and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels()							)
		):
			# Closes the issue after 7 days of inactivity since the Stalebot notification.
			issue.edit(state='closed'							)
		elif (
		    "stale" in issue.get_labels()
		    and last_comment is not None
		    and last_comment.user.login != "github-actions[bot]"
		):
			# Opens the issue if someone other than Stalebot commented.
			issue.edit(state='open'							)
			issue.remove_from_labels('stale'							)
		elif (
		    (dt.utcnow() - issue.updated_at).days > 23
		    and (dt.utcnow() - issue.created_at).days >= 30
		    and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels()							)
		):
			# Post a Stalebot notification after 23 days of inactivity.
			issue.create_comment(
			    'This issue has been automatically marked as stale because it has not had '
			    'recent activity. If you think this still needs to be addressed '
			    'please comment on this thread.\n\nPlease note that issues that do not follow the '
			    '[contributing guidelines](https://github.com/huggingface/diffusers/blob/main/CONTRIBUTING.md) '
			    'are likely to be ignored.'							)
			issue.add_to_labels('stale'							)


if __name__ == "__main__":
	main()

