




'''simple docstring'''







import os
import unittest

from transformers.models.cpmant.tokenization_cpmant import VOCAB_FILES_NAMES, CpmAntTokenizer
from transformers.testing_utils import require_jieba, tooslow

from ...test_tokenization_common import TokenizerTesterMixin


@require_jieba
class     _a						(			__a							,							unittest.TestCase				):
       __a       :  List[Any]            =      CpmAntTokenizer
       __a       :  int            =      False
       def 					A   (			self		:			Optional[Any]       ):



           '''simple docstring'''

           super().setUp()

           UpperCAmelCase     =	[
               '''<d>''',
               '''</d>''',
               '''<s>''',
               '''</s>''',
               '''</_>''',
               '''<unk>''',
               '''<pad>''',
               '''</n>''',
               '''我''',
               '''是''',
               '''C''',
               '''P''',
               '''M''',
               '''A''',
               '''n''',
               '''t''',
           ]
           UpperCAmelCase     =	os.path.join(self.tmpdirname     ,       VOCAB_FILES_NAMES['''vocab_file''']       )
           with open(self.vocab_file     ,       '''w'''     ,       encoding='''utf-8'''       ) as vocab_writer:
               vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens]       )       )







       @tooslow
       def 					A   (			self		:			Optional[int]       ):



           '''simple docstring'''

           UpperCAmelCase     =	CpmAntTokenizer.from_pretrained('''openbmb/cpm-ant-10b'''       )
           UpperCAmelCase     =	'''今天天气真好！'''
           UpperCAmelCase     =	['''今天''', '''天气''', '''真''', '''好''', '''！''']
           UpperCAmelCase     =	tokenizer.tokenize(lowercase       )
           self.assertListEqual(lowercase     ,       lowercase       )
           UpperCAmelCase     =	'''今天天气真好！'''
           UpperCAmelCase     =	[tokenizer.bos_token] + tokens

           UpperCAmelCase     =	[6, 9_802, 14_962, 2_082, 831, 244]
           self.assertListEqual(tokenizer.convert_tokens_to_ids(lowercase       )     ,       lowercase       )

           UpperCAmelCase     =	tokenizer.decode(lowercase       )
           self.assertEqual(lowercase     ,       lowercase       )






'''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       )]




