





import argparse
import json
import os
import sys
import tempfile
import unittest
from argparse import Namespace
from dataclasses import dataclass, field
from enum import Enum
from pathlib import Path
from typing import List, Literal, Optional

import yaml

from transformers import HfArgumentParser, TrainingArguments
from transformers.hf_argparser import make_choice_type_function, string_to_bool


# Since Python 3.10, we can use the builtin `|` operator for Union types
# See PEP 604: https://peps.python.org/pep-0604
SCREAMING_SNAKE_CASE_   :      List[Any]			=   sys.version_info >= (3, 10)



def  SCREAMING_SNAKE_CASE				(      snake_case=None						,   snake_case=None							)		->    Optional[int]:
		return field(default_factory=lambda: default						,   metadata=snake_case							)

@dataclass
class 		snake_case_   :







	'''simple docstring'''
	__UpperCamelCase   =		42
	__UpperCamelCase   =		42
	__UpperCamelCase   =		42
	__UpperCamelCase   =		42





@dataclass
class 		snake_case_   :







	'''simple docstring'''
	__UpperCamelCase   =		42
	__UpperCamelCase   =		field(default='''toto'''     ,     metadata={'''help''': '''help message'''}						)





@dataclass
class 		snake_case_   :







	'''simple docstring'''
	__UpperCamelCase   =		False
	__UpperCamelCase   =		True
	__UpperCamelCase   =		None





class 		snake_case_   (							UpperCAmelCase_						):







	'''simple docstring'''
	__UpperCamelCase   =		'''titi'''
	__UpperCamelCase   =		'''toto'''





class 		snake_case_   (							UpperCAmelCase_						):







	'''simple docstring'''
	__UpperCamelCase   =		'''titi'''
	__UpperCamelCase   =		'''toto'''
	__UpperCamelCase   =		42





@dataclass
class 		snake_case_   :







	'''simple docstring'''
	__UpperCamelCase   =		"toto"




	def    UpperCAmelCase			(						self							:     List[str]   )       -> Dict:

			'''simple docstring'''




			__lowercase											=     BasicEnum(self.foo   )





@dataclass
class 		snake_case_   :







	'''simple docstring'''
	__UpperCamelCase   =		"toto"




	def    UpperCAmelCase			(						self							:     List[Any]   )       -> Any:

			'''simple docstring'''




			__lowercase											=     MixedTypeEnum(self.foo   )





@dataclass
class 		snake_case_   :







	'''simple docstring'''
	__UpperCamelCase   =		None
	__UpperCamelCase   =		field(default=UpperCAmelCase_     ,     metadata={'''help''': '''help message'''}						)
	__UpperCamelCase   =		None
	__UpperCamelCase   =		list_field(default=[]						)
	__UpperCamelCase   =		list_field(default=[]						)





@dataclass
class 		snake_case_   :







	'''simple docstring'''
	__UpperCamelCase   =		list_field(default=[]						)
	__UpperCamelCase   =		list_field(default=[1, 2, 3]						)
	__UpperCamelCase   =		list_field(default=['''Hallo''', '''Bonjour''', '''Hello''']						)
	__UpperCamelCase   =		list_field(default=[0.1, 0.2, 0.3]						)





@dataclass
class 		snake_case_   :







	'''simple docstring'''
	__UpperCamelCase   =		field()
	__UpperCamelCase   =		field()
	__UpperCamelCase   =		field()




	def    UpperCAmelCase			(						self							:     Optional[Any]   )       -> Dict:

			'''simple docstring'''




			__lowercase											=     BasicEnum(self.required_enum   )





@dataclass
class 		snake_case_   :







	'''simple docstring'''
	__UpperCamelCase   =		42
	__UpperCamelCase   =		field()
	__UpperCamelCase   =		None
	__UpperCamelCase   =		field(default='''toto'''     ,     metadata={'''help''': '''help message'''}						)
	__UpperCamelCase   =		list_field(default=['''Hallo''', '''Bonjour''', '''Hello''']						)


if is_python_no_less_than_3_10:

		@dataclass
		class 		snake_case_   :







			'''simple docstring'''
			__UpperCamelCase   =		False
			__UpperCamelCase   =		True
			__UpperCamelCase   =		None





		@dataclass
		class 		snake_case_   :







			'''simple docstring'''
			__UpperCamelCase   =		None
			__UpperCamelCase   =		field(default=UpperCAmelCase_     ,     metadata={'''help''': '''help message'''}						)
			__UpperCamelCase   =		None
			__UpperCamelCase   =		list_field(default=[]						)
			__UpperCamelCase   =		list_field(default=[]						)


class 		snake_case_   (							unittest.TestCase						):







	'''simple docstring'''




	def    UpperCAmelCase			(						self							:     Tuple					,      __lowerCamelCase							:     argparse.ArgumentParser					,      __lowerCamelCase							:     argparse.ArgumentParser   )       -> str:

			'''simple docstring'''




			self.assertEqual(len(a._actions   )					,      len(b._actions   )   )
			for x, y in zip(a._actions					,      b._actions   ):
					__lowercase											=     {k: v for k, v in vars(__lowerCamelCase   ).items() if k != 'container'}
					__lowercase											=     {k: v for k, v in vars(__lowerCamelCase   ).items() if k != 'container'}

					# Choices with mixed type have custom function as "type"
					# So we need to compare results directly for equality
					if xx.get('choices'					,      __lowerCamelCase   ) and yy.get('choices'					,      __lowerCamelCase   ):
							for expected_choice in yy["choices"] + xx["choices"]:
									self.assertEqual(xx['type'](__lowerCamelCase   )					,      yy['type'](__lowerCamelCase   )   )
							del xx["type"], yy["type"]

					self.assertEqual(__lowerCamelCase					,      __lowerCamelCase   )




	def    UpperCAmelCase			(						self							:     Any   )       -> Optional[Any]:

			'''simple docstring'''




			__lowercase											=     HfArgumentParser(__lowerCamelCase   )

			__lowercase											=     argparse.ArgumentParser()
			expected.add_argument('--foo'					,      type=__lowerCamelCase					,      required=__lowerCamelCase   )
			expected.add_argument('--bar'					,      type=__lowerCamelCase					,      required=__lowerCamelCase   )
			expected.add_argument('--baz'					,      type=__lowerCamelCase					,      required=__lowerCamelCase   )
			expected.add_argument('--flag'					,      type=__lowerCamelCase					,      default=__lowerCamelCase					,      const=__lowerCamelCase					,      nargs='?'   )
			self.argparsersEqual(__lowerCamelCase					,      __lowerCamelCase   )

			__lowercase											=     ['--foo', '1', '--baz', 'quux', '--bar', '0.5']
			((__lowercase)						,      )											=     parser.parse_args_into_dataclasses(__lowerCamelCase					,      look_for_args_file=__lowerCamelCase   )
			self.assertFalse(example.flag   )




	def    UpperCAmelCase			(						self							:     List[str]   )       -> List[Any]:

			'''simple docstring'''




			__lowercase											=     HfArgumentParser(__lowerCamelCase   )

			__lowercase											=     argparse.ArgumentParser()
			expected.add_argument('--foo'					,      default=42					,      type=__lowerCamelCase   )
			expected.add_argument('--baz'					,      default='toto'					,      type=__lowerCamelCase					,      help='help message'   )
			self.argparsersEqual(__lowerCamelCase					,      __lowerCamelCase   )




	def    UpperCAmelCase			(						self							:     Any   )       -> Dict:

			'''simple docstring'''




			__lowercase											=     argparse.ArgumentParser()
			expected.add_argument('--foo'					,      type=__lowerCamelCase					,      default=__lowerCamelCase					,      const=__lowerCamelCase					,      nargs='?'   )
			expected.add_argument('--baz'					,      type=__lowerCamelCase					,      default=__lowerCamelCase					,      const=__lowerCamelCase					,      nargs='?'   )
			# A boolean no_* argument always has to come after its "default: True" regular counter-part
			# and its default must be set to False
			expected.add_argument('--no_baz'					,      action='store_false'					,      default=__lowerCamelCase					,      dest='baz'   )
			expected.add_argument('--opt'					,      type=__lowerCamelCase					,      default=__lowerCamelCase   )

			__lowercase											=     [WithDefaultBoolExample]
			if is_python_no_less_than_3_10:
					dataclass_types.append(__lowerCamelCase   )

			for dataclass_type in dataclass_types:
					__lowercase											=     HfArgumentParser(__lowerCamelCase   )
					self.argparsersEqual(__lowerCamelCase					,      __lowerCamelCase   )

					__lowercase											=     parser.parse_args([]   )
					self.assertEqual(__lowerCamelCase					,      Namespace(foo=__lowerCamelCase					,      baz=__lowerCamelCase					,      opt=__lowerCamelCase   )   )

					__lowercase											=     parser.parse_args(['--foo', '--no_baz']   )
					self.assertEqual(__lowerCamelCase					,      Namespace(foo=__lowerCamelCase					,      baz=__lowerCamelCase					,      opt=__lowerCamelCase   )   )

					__lowercase											=     parser.parse_args(['--foo', '--baz']   )
					self.assertEqual(__lowerCamelCase					,      Namespace(foo=__lowerCamelCase					,      baz=__lowerCamelCase					,      opt=__lowerCamelCase   )   )

					__lowercase											=     parser.parse_args(['--foo', 'True', '--baz', 'True', '--opt', 'True']   )
					self.assertEqual(__lowerCamelCase					,      Namespace(foo=__lowerCamelCase					,      baz=__lowerCamelCase					,      opt=__lowerCamelCase   )   )

					__lowercase											=     parser.parse_args(['--foo', 'False', '--baz', 'False', '--opt', 'False']   )
					self.assertEqual(__lowerCamelCase					,      Namespace(foo=__lowerCamelCase					,      baz=__lowerCamelCase					,      opt=__lowerCamelCase   )   )




	def    UpperCAmelCase			(						self							:     Optional[Any]   )       -> Dict:

			'''simple docstring'''




			__lowercase											=     HfArgumentParser(__lowerCamelCase   )

			__lowercase											=     argparse.ArgumentParser()
			expected.add_argument(
			    '--foo'					,      default='toto'					,      choices=['titi', 'toto', 42]					,      type=make_choice_type_function(['titi', 'toto', 42]   )					,      )
			self.argparsersEqual(__lowerCamelCase					,      __lowerCamelCase   )

			__lowercase											=     parser.parse_args([]   )
			self.assertEqual(args.foo					,      'toto'   )
			__lowercase											=     parser.parse_args_into_dataclasses([]   )[0]
			self.assertEqual(enum_ex.foo					,      MixedTypeEnum.toto   )

			__lowercase											=     parser.parse_args(['--foo', 'titi']   )
			self.assertEqual(args.foo					,      'titi'   )
			__lowercase											=     parser.parse_args_into_dataclasses(['--foo', 'titi']   )[0]
			self.assertEqual(enum_ex.foo					,      MixedTypeEnum.titi   )

			__lowercase											=     parser.parse_args(['--foo', '42']   )
			self.assertEqual(args.foo					,      42   )
			__lowercase											=     parser.parse_args_into_dataclasses(['--foo', '42']   )[0]
			self.assertEqual(enum_ex.foo					,      MixedTypeEnum.fourtytwo   )




	def    UpperCAmelCase			(						self							:     Dict   )       -> List[str]:

			'''simple docstring'''




			@dataclass
			class 		snake_case_   :







				'''simple docstring'''
				__UpperCamelCase   =		"toto"





			__lowercase											=     HfArgumentParser(__lowerCamelCase   )

			__lowercase											=     argparse.ArgumentParser()
			expected.add_argument(
			    '--foo'					,      default='toto'					,      choices=('titi', 'toto', 42)					,      type=make_choice_type_function(['titi', 'toto', 42]   )					,      )
			self.argparsersEqual(__lowerCamelCase					,      __lowerCamelCase   )

			__lowercase											=     parser.parse_args([]   )
			self.assertEqual(args.foo					,      'toto'   )

			__lowercase											=     parser.parse_args(['--foo', 'titi']   )
			self.assertEqual(args.foo					,      'titi'   )

			__lowercase											=     parser.parse_args(['--foo', '42']   )
			self.assertEqual(args.foo					,      42   )




	def    UpperCAmelCase			(						self							:     List[str]   )       -> Dict:

			'''simple docstring'''




			__lowercase											=     HfArgumentParser(__lowerCamelCase   )

			__lowercase											=     argparse.ArgumentParser()
			expected.add_argument('--foo_int'					,      nargs='+'					,      default=[]					,      type=__lowerCamelCase   )
			expected.add_argument('--bar_int'					,      nargs='+'					,      default=[1, 2, 3]					,      type=__lowerCamelCase   )
			expected.add_argument('--foo_str'					,      nargs='+'					,      default=['Hallo', 'Bonjour', 'Hello']					,      type=__lowerCamelCase   )
			expected.add_argument('--foo_float'					,      nargs='+'					,      default=[0.1, 0.2, 0.3]					,      type=__lowerCamelCase   )

			self.argparsersEqual(__lowerCamelCase					,      __lowerCamelCase   )

			__lowercase											=     parser.parse_args([]   )
			self.assertEqual(
			    __lowerCamelCase					,      Namespace(foo_int=[]					,      bar_int=[1, 2, 3]					,      foo_str=['Hallo', 'Bonjour', 'Hello']					,      foo_float=[0.1, 0.2, 0.3]   )					,      )

			__lowercase											=     parser.parse_args('--foo_int 1 --bar_int 2 3 --foo_str a b c --foo_float 0.1 0.7'.split()   )
			self.assertEqual(__lowerCamelCase					,      Namespace(foo_int=[1]					,      bar_int=[2, 3]					,      foo_str=['a', 'b', 'c']					,      foo_float=[0.1, 0.7]   )   )




	def    UpperCAmelCase			(						self							:     List[str]   )       -> Union[str, Any]:

			'''simple docstring'''




			__lowercase											=     argparse.ArgumentParser()
			expected.add_argument('--foo'					,      default=__lowerCamelCase					,      type=__lowerCamelCase   )
			expected.add_argument('--bar'					,      default=__lowerCamelCase					,      type=__lowerCamelCase					,      help='help message'   )
			expected.add_argument('--baz'					,      default=__lowerCamelCase					,      type=__lowerCamelCase   )
			expected.add_argument('--ces'					,      nargs='+'					,      default=[]					,      type=__lowerCamelCase   )
			expected.add_argument('--des'					,      nargs='+'					,      default=[]					,      type=__lowerCamelCase   )

			__lowercase											=     [OptionalExample]
			if is_python_no_less_than_3_10:
					dataclass_types.append(__lowerCamelCase   )

			for dataclass_type in dataclass_types:
					__lowercase											=     HfArgumentParser(__lowerCamelCase   )

					self.argparsersEqual(__lowerCamelCase					,      __lowerCamelCase   )

					__lowercase											=     parser.parse_args([]   )
					self.assertEqual(__lowerCamelCase					,      Namespace(foo=__lowerCamelCase					,      bar=__lowerCamelCase					,      baz=__lowerCamelCase					,      ces=[]					,      des=[]   )   )

					__lowercase											=     parser.parse_args('--foo 12 --bar 3.14 --baz 42 --ces a b c --des 1 2 3'.split()   )
					self.assertEqual(__lowerCamelCase					,      Namespace(foo=12					,      bar=3.14					,      baz='42'					,      ces=['a', 'b', 'c']					,      des=[1, 2, 3]   )   )




	def    UpperCAmelCase			(						self							:     Dict   )       -> List[str]:

			'''simple docstring'''




			__lowercase											=     HfArgumentParser(__lowerCamelCase   )

			__lowercase											=     argparse.ArgumentParser()
			expected.add_argument('--required_list'					,      nargs='+'					,      type=__lowerCamelCase					,      required=__lowerCamelCase   )
			expected.add_argument('--required_str'					,      type=__lowerCamelCase					,      required=__lowerCamelCase   )
			expected.add_argument(
			    '--required_enum'					,      type=make_choice_type_function(['titi', 'toto']   )					,      choices=['titi', 'toto']					,      required=__lowerCamelCase					,      )
			self.argparsersEqual(__lowerCamelCase					,      __lowerCamelCase   )




	def    UpperCAmelCase			(						self							:     List[Any]   )       -> int:

			'''simple docstring'''




			__lowercase											=     HfArgumentParser(__lowerCamelCase   )

			__lowercase											=     argparse.ArgumentParser()
			expected.add_argument('--foo'					,      type=__lowerCamelCase					,      required=__lowerCamelCase   )
			expected.add_argument(
			    '--required_enum'					,      type=make_choice_type_function(['titi', 'toto']   )					,      choices=['titi', 'toto']					,      required=__lowerCamelCase					,      )
			expected.add_argument('--opt'					,      type=__lowerCamelCase					,      default=__lowerCamelCase   )
			expected.add_argument('--baz'					,      default='toto'					,      type=__lowerCamelCase					,      help='help message'   )
			expected.add_argument('--foo_str'					,      nargs='+'					,      default=['Hallo', 'Bonjour', 'Hello']					,      type=__lowerCamelCase   )
			self.argparsersEqual(__lowerCamelCase					,      __lowerCamelCase   )




	def    UpperCAmelCase			(						self							:     Optional[Any]   )       -> List[str]:

			'''simple docstring'''




			__lowercase											=     HfArgumentParser(__lowerCamelCase   )

			__lowercase											=     {
			    'foo': 12,
			    'bar': 3.14,
			    'baz': '42',
			    'flag': True,
			}

			__lowercase											=     parser.parse_dict(__lowerCamelCase   )[0]
			__lowercase											=     BasicExample(**__lowerCamelCase   )
			self.assertEqual(__lowerCamelCase					,      __lowerCamelCase   )




	def    UpperCAmelCase			(						self							:     Tuple   )       -> Optional[Any]:

			'''simple docstring'''




			__lowercase											=     HfArgumentParser(__lowerCamelCase   )

			__lowercase											=     {
			    'foo': 12,
			    'bar': 3.14,
			    'baz': '42',
			    'flag': True,
			    'extra': 42,
			}

			self.assertRaises(__lowerCamelCase					,      parser.parse_dict					,      __lowerCamelCase					,      allow_extra_keys=__lowerCamelCase   )




	def    UpperCAmelCase			(						self							:     Dict   )       -> Any:

			'''simple docstring'''




			__lowercase											=     HfArgumentParser(__lowerCamelCase   )

			__lowercase											=     {
			    'foo': 12,
			    'bar': 3.14,
			    'baz': '42',
			    'flag': True,
			}
			with tempfile.TemporaryDirectory() as tmp_dir:
					__lowercase											=     os.path.join(__lowerCamelCase					,      'temp_json'   )
					os.mkdir(__lowerCamelCase   )
					with open(temp_local_path + '.json'					,      'w+'   ) as f:
							json.dump(__lowerCamelCase					,      __lowerCamelCase   )
					__lowercase											=     parser.parse_yaml_file(Path(temp_local_path + '.json'   )   )[0]

			__lowercase											=     BasicExample(**__lowerCamelCase   )
			self.assertEqual(__lowerCamelCase					,      __lowerCamelCase   )




	def    UpperCAmelCase			(						self							:     Dict   )       -> List[Any]:

			'''simple docstring'''




			__lowercase											=     HfArgumentParser(__lowerCamelCase   )

			__lowercase											=     {
			    'foo': 12,
			    'bar': 3.14,
			    'baz': '42',
			    'flag': True,
			}
			with tempfile.TemporaryDirectory() as tmp_dir:
					__lowercase											=     os.path.join(__lowerCamelCase					,      'temp_yaml'   )
					os.mkdir(__lowerCamelCase   )
					with open(temp_local_path + '.yaml'					,      'w+'   ) as f:
							yaml.dump(__lowerCamelCase					,      __lowerCamelCase   )
					__lowercase											=     parser.parse_yaml_file(Path(temp_local_path + '.yaml'   )   )[0]
			__lowercase											=     BasicExample(**__lowerCamelCase   )
			self.assertEqual(__lowerCamelCase					,      __lowerCamelCase   )






	def    UpperCAmelCase			(						self							:     str   )       -> Tuple:

			'''simple docstring'''




			__lowercase											=     HfArgumentParser(__lowerCamelCase   )
			self.assertIsNotNone(__lowerCamelCase   )











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

SCREAMING_SNAKE_CASE_   :      Union[str, Any]			=   logging.get_logger(__name__)

@add_end_docstrings(UpperCAmelCase_						)
class 		snake_case_   (							UpperCAmelCase_						):







	'''simple docstring'''




	def __init__(						self							:     Optional[int]					,      *__lowerCamelCase							:     Optional[int]					,      **__lowerCamelCase							:     List[Any]   )       -> Optional[Any]:

			'''simple docstring'''




			super().__init__(*__lowerCamelCase					,      **__lowerCamelCase   )
			self.check_model_type(__lowerCamelCase   )




	def    UpperCAmelCase			(						self							:     Optional[int]					,      __lowerCamelCase							:     int=None					,      __lowerCamelCase							:     List[Any]=None					,      __lowerCamelCase							:     Any=None					,      **__lowerCamelCase							:     Optional[int]   )       -> Any:

			'''simple docstring'''




			__lowercase						,      __lowercase											=     {}, {}
			if padding is not None:
					__lowercase											=     padding
			if truncation is not None:
					__lowercase											=     truncation
			if top_k is not None:
					__lowercase											=     top_k
			return preprocess_params, {}, postprocess_params




	def __call__(						self							:     str					,      __lowerCamelCase							:     Union["Image.Image", str]					,      __lowerCamelCase							:     str = None					,      **__lowerCamelCase							:     Dict   )       -> Tuple:

			'''simple docstring'''




			if isinstance(__lowerCamelCase					,      (Image.Image, str)   ) and isinstance(__lowerCamelCase					,      __lowerCamelCase   ):
					__lowercase											=     {'image': image, 'question': question}
			else:
					__lowercase											=     image
			__lowercase											=     super().__call__(__lowerCamelCase					,      **__lowerCamelCase   )
			return results




	def    UpperCAmelCase			(						self							:     List[Any]					,      __lowerCamelCase							:     List[str]					,      __lowerCamelCase							:     Optional[Any]=False					,      __lowerCamelCase							:     Optional[Any]=False   )       -> Optional[int]:

			'''simple docstring'''




			__lowercase											=     load_image(inputs['image']   )
			__lowercase											=     self.tokenizer(
			    inputs['question']					,      return_tensors=self.framework					,      padding=__lowerCamelCase					,      truncation=__lowerCamelCase   )
			__lowercase											=     self.image_processor(images=__lowerCamelCase					,      return_tensors=self.framework   )
			model_inputs.update(__lowerCamelCase   )
			return model_inputs




	def    UpperCAmelCase			(						self							:     str					,      __lowerCamelCase							:     Tuple   )       -> Any:

			'''simple docstring'''




			__lowercase											=     self.model(**__lowerCamelCase   )
			return model_outputs






	def    UpperCAmelCase			(						self							:     int					,      __lowerCamelCase							:     Any					,      __lowerCamelCase							:     int=5   )       -> Tuple:

			'''simple docstring'''




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

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

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




