




'''simple docstring'''







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

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

from ...tokenization_utils_base import PreTrainedTokenizerBase
from ...utils import logging
from ..processors.glue import glue_convert_examples_to_features, glue_output_modes, glue_processors
from ..processors.utils import InputFeatures


A									=logging.get_logger(__name__)


@dataclass
class     _a						:
       __a       :  List[str]            =      field(metadata={"""help""": """The name of the task to train on: """ + """, """.join(glue_processors.keys()				)}				)
       __a       :  int            =      field(
           metadata={"""help""": """The input data dir. Should contain the .tsv files (or other data files) for the task."""}				)
       __a       :  Any            =      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."""
               )
           }							,							)
       __a       :  Any            =      field(
           default=_A							,							metadata={"""help""": """Overwrite the cached training and evaluation sets"""}				)
       def 					A   (			self		:			Optional[Any]       ):



           '''simple docstring'''

           UpperCAmelCase     =	self.task_name.lower()






class     _a						(			_A				):
       __a       :  str            =      """train"""
       __a       :  Dict            =      """dev"""
       __a       :  Tuple            =      """test"""






class     _a						(			_A				):
       __a       :  Optional[Any]            =      42
       __a       :  List[str]            =      42
       __a       :  str            =      42
       def __init__(			self		:			Tuple     ,       lowercase		:			GlueDataTrainingArguments     ,       lowercase		:			PreTrainedTokenizerBase     ,       lowercase		:			Optional[int] = None     ,       lowercase		:			Union[str, Split] = Split.train     ,       lowercase		:			Optional[str] = None     ,       ):



           '''simple docstring'''

           warnings.warn(
               '''This dataset will be removed from the library soon, preprocessing should be handled with the 🤗 Datasets '''
               '''library. You can have a look at this example script for pointers: '''
               '''https://github.com/huggingface/transformers/blob/main/examples/pytorch/text-classification/run_glue.py'''     ,       UpperCamelCase__     ,       )
           UpperCAmelCase     =	args
           UpperCAmelCase     =	glue_processors[args.task_name]()
           UpperCAmelCase     =	glue_output_modes[args.task_name]
           if isinstance(UpperCamelCase__     ,       UpperCamelCase__       ):
               try:
                   UpperCAmelCase     =	Split[mode]
               except KeyError:
                   raise KeyError('''mode is not a valid split name'''       )
                   # Load data features from cache or dataset file
           UpperCAmelCase     =	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}_{args.task_name}"     ,       )
           UpperCAmelCase     =	self.processor.get_labels()
           if args.task_name in ["mnli", "mnli-mm"] and tokenizer.__class__.__name__ in (
               "RobertaTokenizer",
               "RobertaTokenizerFast",
               "XLMRobertaTokenizer",
               "BartTokenizer",
               "BartTokenizerFast",
           ):
               # HACK(label indices are swapped in RoBERTa pretrained model)
               UpperCAmelCase ,  UpperCAmelCase     =	label_list[2], label_list[1]
           UpperCAmelCase     =	label_list

           # Make sure only the first process in distributed training processes the dataset,
           # and the others will use the cache.
           UpperCAmelCase     =	cached_features_file + '''.lock'''
           with FileLock(UpperCamelCase__       ):
               if os.path.exists(UpperCamelCase__       ) and not args.overwrite_cache:
                   UpperCAmelCase     =	time.time()
                   UpperCAmelCase     =	torch.load(UpperCamelCase__       )
                   logger.info(
                       f"Loading features from cached file {cached_features_file} [took %.3f s]"     ,       time.time() - start       )
               else:
                   logger.info(f"Creating features from dataset file at {args.data_dir}"       )

                   if mode == Split.dev:
                       UpperCAmelCase     =	self.processor.get_dev_examples(args.data_dir       )
                   elif mode == Split.test:
                       UpperCAmelCase     =	self.processor.get_test_examples(args.data_dir       )
                   else:
                       UpperCAmelCase     =	self.processor.get_train_examples(args.data_dir       )
                   if limit_length is not None:
                       UpperCAmelCase     =	examples[:limit_length]
                   UpperCAmelCase     =	glue_convert_examples_to_features(
                       UpperCamelCase__     ,       UpperCamelCase__     ,       max_length=args.max_seq_length     ,       label_list=UpperCamelCase__     ,       output_mode=self.output_mode     ,       )
                   UpperCAmelCase     =	time.time()
                   torch.save(self.features     ,       UpperCamelCase__       )
                   # ^ 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		:			Optional[int]       ):



           '''simple docstring'''

           return len(self.features       )
       def __getitem__(			self		:			List[Any]     ,       lowercase		:			List[str]       ):



           '''simple docstring'''

           return self.features[i]







       def 					A   (			self		:			Union[str, Any]       ):



           '''simple docstring'''

           return self.label_list






'''simple docstring'''







from typing import Union

from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_vision_available():
   from PIL import Image

   from ..image_utils import load_image

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

A									=logging.get_logger(__name__)


@add_end_docstrings(__a				)
class     _a						(			__a				):
       def __init__(			self		:			Optional[int]     ,       *lowercase		:			Any     ,       **lowercase		:			Optional[int]       ):



           '''simple docstring'''

           super().__init__(*lowercase     ,       **lowercase       )
           self.check_model_type(lowercase       )
       def 					A   (			self		:			List[str]     ,       lowercase		:			str=None     ,       lowercase		:			List[str]=None     ,       lowercase		:			List[str]=None     ,       **lowercase		:			List[str]       ):



           '''simple docstring'''

           UpperCAmelCase ,  UpperCAmelCase     =	{}, {}
           if padding is not None:
               UpperCAmelCase     =	padding
           if truncation is not None:
               UpperCAmelCase     =	truncation
           if top_k is not None:
               UpperCAmelCase     =	top_k
           return preprocess_params, {}, postprocess_params
       def __call__(			self		:			Optional[Any]     ,       lowercase		:			Union["Image.Image", str]     ,       lowercase		:			str = None     ,       **lowercase		:			Optional[int]       ):



           '''simple docstring'''

           if isinstance(lowercase     ,       (Image.Image, str)       ) and isinstance(lowercase     ,       lowercase       ):
               UpperCAmelCase     =	{'''image''': image, '''question''': question}
           else:
               UpperCAmelCase     =	image
           UpperCAmelCase     =	super().__call__(lowercase     ,       **lowercase       )
           return results
       def 					A   (			self		:			List[Any]     ,       lowercase		:			List[str]     ,       lowercase		:			Any=False     ,       lowercase		:			Any=False       ):



           '''simple docstring'''

           UpperCAmelCase     =	load_image(inputs['''image''']       )
           UpperCAmelCase     =	self.tokenizer(
               inputs['''question''']     ,       return_tensors=self.framework     ,       padding=lowercase     ,       truncation=lowercase       )
           UpperCAmelCase     =	self.image_processor(images=lowercase     ,       return_tensors=self.framework       )
           model_inputs.update(lowercase       )
           return model_inputs
       def 					A   (			self		:			Dict     ,       lowercase		:			Optional[Any]       ):



           '''simple docstring'''

           UpperCAmelCase     =	self.model(**lowercase       )
           return model_outputs







       def 					A   (			self		:			Union[str, Any]     ,       lowercase		:			int     ,       lowercase		:			Optional[Any]=5       ):



           '''simple docstring'''

           if top_k > self.model.config.num_labels:
               UpperCAmelCase     =	self.model.config.num_labels

           if self.framework == "pt":
               UpperCAmelCase     =	model_outputs.logits.sigmoid()[0]
               UpperCAmelCase ,  UpperCAmelCase     =	probs.topk(lowercase       )
           else:
               raise ValueError(f"Unsupported framework: {self.framework}"       )

           UpperCAmelCase     =	scores.tolist()
           UpperCAmelCase     =	ids.tolist()
           return [{"score": score, "answer": self.model.config.idalabel[_id]} for score, _id in zip(lowercase     ,       lowercase       )]




