






import unittest

from transformers import AutoTokenizer, FalconConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
				import torch

				from transformers import (
				    FalconForCausalLM,
				    FalconForQuestionAnswering,
				    FalconForSequenceClassification,
				    FalconForTokenClassification,
				    FalconModel,
				)

class 		__A  :






			def __init__(       self		,					a		,					a=3		,					a=7		,					a=True		,					a=True		,					a=False		,					a=True		,					a=99		,					a=32		,					a=5		,					a=4		,					a=37		,					a="gelu"		,					a=0.1		,					a=0.1		,					a=512		,					a=16		,					a=2		,					a=0.02		,					a=3		,					a=4		,					a=None		,					)      ->       Optional[int]:
						SCREAMING_SNAKE_CASE						= parent
						SCREAMING_SNAKE_CASE						= batch_size
						SCREAMING_SNAKE_CASE						= seq_length
						SCREAMING_SNAKE_CASE						= is_training
						SCREAMING_SNAKE_CASE						= use_input_mask
						SCREAMING_SNAKE_CASE						= use_token_type_ids
						SCREAMING_SNAKE_CASE						= use_labels
						SCREAMING_SNAKE_CASE						= vocab_size
						SCREAMING_SNAKE_CASE						= hidden_size
						SCREAMING_SNAKE_CASE						= num_hidden_layers
						SCREAMING_SNAKE_CASE						= num_attention_heads
						SCREAMING_SNAKE_CASE						= intermediate_size
						SCREAMING_SNAKE_CASE						= hidden_act
						SCREAMING_SNAKE_CASE						= hidden_dropout_prob
						SCREAMING_SNAKE_CASE						= attention_probs_dropout_prob
						SCREAMING_SNAKE_CASE						= max_position_embeddings
						SCREAMING_SNAKE_CASE						= type_vocab_size
						SCREAMING_SNAKE_CASE						= type_sequence_label_size
						SCREAMING_SNAKE_CASE						= initializer_range
						SCREAMING_SNAKE_CASE						= num_labels
						SCREAMING_SNAKE_CASE						= num_choices
						SCREAMING_SNAKE_CASE						= scope






			def    SCREAMING_SNAKE_CASE__    (       self)      ->       Dict:
						SCREAMING_SNAKE_CASE						= ids_tensor([self.batch_size, self.seq_length]		,					self.vocab_size)

						SCREAMING_SNAKE_CASE						= None
						if self.use_input_mask:
									SCREAMING_SNAKE_CASE						= random_attention_mask([self.batch_size, self.seq_length])

						SCREAMING_SNAKE_CASE						= None

						SCREAMING_SNAKE_CASE						= None
						SCREAMING_SNAKE_CASE						= None
						SCREAMING_SNAKE_CASE						= None
						if self.use_labels:
									SCREAMING_SNAKE_CASE						= ids_tensor([self.batch_size]		,					self.type_sequence_label_size)
									SCREAMING_SNAKE_CASE						= ids_tensor([self.batch_size, self.seq_length]		,					self.num_labels)
									SCREAMING_SNAKE_CASE						= ids_tensor([self.batch_size]		,					self.num_choices)

						SCREAMING_SNAKE_CASE						= self.get_config()

						return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels






			def    SCREAMING_SNAKE_CASE__    (       self)      ->       Optional[int]:
						return FalconConfig(
						    vocab_size=self.vocab_size		,					hidden_size=self.hidden_size		,					num_hidden_layers=self.num_hidden_layers		,					num_attention_heads=self.num_attention_heads		,					intermediate_size=self.intermediate_size		,					hidden_act=self.hidden_act		,					hidden_dropout_prob=self.hidden_dropout_prob		,					attention_probs_dropout_prob=self.attention_probs_dropout_prob		,					max_position_embeddings=self.max_position_embeddings		,					type_vocab_size=self.type_vocab_size		,					is_decoder=lowerCAmelCase_		,					initializer_range=self.initializer_range		,					pad_token_id=1		,					new_decoder_architecture=lowerCAmelCase_		,					)






			def    SCREAMING_SNAKE_CASE__    (       self		,					a		,					a		,					a		,					a		,					a		,					a		,					a)      ->       List[Any]:
						SCREAMING_SNAKE_CASE						= FalconModel(config=lowerCAmelCase_)
						model.to(lowerCAmelCase_)
						model.eval()
						SCREAMING_SNAKE_CASE						= model(lowerCAmelCase_		,					attention_mask=lowerCAmelCase_)
						SCREAMING_SNAKE_CASE						= model(lowerCAmelCase_)
						self.parent.assertEqual(result.last_hidden_state.shape		,					(self.batch_size, self.seq_length, self.hidden_size))






			def    SCREAMING_SNAKE_CASE__    (       self		,					a		,					a		,					a		,					a		,					a		,					a		,					a		,					a		,					a		,					)      ->       Any:
						SCREAMING_SNAKE_CASE						= True
						SCREAMING_SNAKE_CASE						= FalconModel(lowerCAmelCase_)
						model.to(lowerCAmelCase_)
						model.eval()
						SCREAMING_SNAKE_CASE						= model(
						    lowerCAmelCase_		,					attention_mask=lowerCAmelCase_		,					encoder_hidden_states=lowerCAmelCase_		,					encoder_attention_mask=lowerCAmelCase_		,					)
						SCREAMING_SNAKE_CASE						= model(
						    lowerCAmelCase_		,					attention_mask=lowerCAmelCase_		,					encoder_hidden_states=lowerCAmelCase_		,					)
						SCREAMING_SNAKE_CASE						= model(lowerCAmelCase_		,					attention_mask=lowerCAmelCase_)
						self.parent.assertEqual(result.last_hidden_state.shape		,					(self.batch_size, self.seq_length, self.hidden_size))






			def    SCREAMING_SNAKE_CASE__    (       self		,					a		,					a		,					a		,					a		,					a		,					a		,					a		,					a		,					a		,					)      ->       str:
						SCREAMING_SNAKE_CASE						= FalconForCausalLM(config=lowerCAmelCase_)
						model.to(lowerCAmelCase_)
						model.eval()
						SCREAMING_SNAKE_CASE						= model(lowerCAmelCase_		,					attention_mask=lowerCAmelCase_		,					labels=lowerCAmelCase_)
						self.parent.assertEqual(result.logits.shape		,					(self.batch_size, self.seq_length, self.vocab_size))






			def    SCREAMING_SNAKE_CASE__    (       self		,					a		,					a		,					a		,					a		,					a		,					a		,					a		,					a		,					a		,					)      ->       Tuple:
						SCREAMING_SNAKE_CASE						= True
						SCREAMING_SNAKE_CASE						= True
						SCREAMING_SNAKE_CASE						= FalconForCausalLM(config=lowerCAmelCase_)
						model.to(lowerCAmelCase_)
						model.eval()

						# first forward pass
						SCREAMING_SNAKE_CASE						= model(
						    lowerCAmelCase_		,					attention_mask=lowerCAmelCase_		,					encoder_hidden_states=lowerCAmelCase_		,					encoder_attention_mask=lowerCAmelCase_		,					use_cache=lowerCAmelCase_		,					)
						SCREAMING_SNAKE_CASE						= outputs.past_key_values

						# create hypothetical multiple next token and extent to next_input_ids
						SCREAMING_SNAKE_CASE						= ids_tensor((self.batch_size, 3)		,					config.vocab_size)
						SCREAMING_SNAKE_CASE						= ids_tensor((self.batch_size, 3)		,					vocab_size=2)

						# append to next input_ids and
						SCREAMING_SNAKE_CASE						= torch.cat([input_ids, next_tokens]		,					dim=-1)
						SCREAMING_SNAKE_CASE						= torch.cat([input_mask, next_mask]		,					dim=-1)

						SCREAMING_SNAKE_CASE						= model(
						    lowerCAmelCase_		,					attention_mask=lowerCAmelCase_		,					encoder_hidden_states=lowerCAmelCase_		,					encoder_attention_mask=lowerCAmelCase_		,					output_hidden_states=lowerCAmelCase_		,					)['hidden_states'][0]
						SCREAMING_SNAKE_CASE						= model(
						    lowerCAmelCase_		,					attention_mask=lowerCAmelCase_		,					encoder_hidden_states=lowerCAmelCase_		,					encoder_attention_mask=lowerCAmelCase_		,					past_key_values=lowerCAmelCase_		,					output_hidden_states=lowerCAmelCase_		,					)['hidden_states'][0]

						# select random slice
						SCREAMING_SNAKE_CASE						= ids_tensor((1,)		,					output_from_past.shape[-1]).item()
						SCREAMING_SNAKE_CASE						= output_from_no_past[:, -3:, random_slice_idx].detach()
						SCREAMING_SNAKE_CASE						= output_from_past[:, :, random_slice_idx].detach()

						self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1])

						# test that outputs are equal for slice
						self.parent.assertTrue(torch.allclose(lowerCAmelCase_		,					lowerCAmelCase_		,					atol=1E-3))







			def    SCREAMING_SNAKE_CASE__    (       self)      ->       Optional[int]:
						SCREAMING_SNAKE_CASE						= self.prepare_config_and_inputs()
						(
						    (
						    SCREAMING_SNAKE_CASE    
						)				,						(
						    SCREAMING_SNAKE_CASE    
						)				,						(
						    SCREAMING_SNAKE_CASE    
						)				,						(
						    SCREAMING_SNAKE_CASE    
						)				,						(
						    SCREAMING_SNAKE_CASE    
						)				,						(
						    SCREAMING_SNAKE_CASE    
						)				,						(
						    SCREAMING_SNAKE_CASE    
						)				,						    
						)						= config_and_inputs
						SCREAMING_SNAKE_CASE						= {'input_ids': input_ids, 'attention_mask': input_mask}
						return config, inputs_dict



@require_torch
class 		__A  (  __UpperCAmelCase   ,    __UpperCAmelCase   ,    __UpperCAmelCase   ,    unittest.TestCase					):
			_lowercase		:    Any			     =							(
			    (
			        FalconModel,
			        FalconForCausalLM,
			        FalconForSequenceClassification,
			        FalconForTokenClassification,
			        FalconForQuestionAnswering,
			    )
			    if is_torch_available()
			    else ()
			)
			_lowercase		:    Union[str, Any]			     =							(FalconForCausalLM,) if is_torch_available() else ()
			_lowercase		:    Tuple			     =							(
			    {
			        '''feature-extraction''': FalconModel,
			        '''text-classification''': FalconForSequenceClassification,
			        '''text-generation''': FalconForCausalLM,
			        '''question-answering''': FalconForQuestionAnswering,
			        '''token-classification''': FalconForTokenClassification,
			        '''zero-shot''': FalconForSequenceClassification,
			    }
			    if is_torch_available()
			    else {}
			)
			_lowercase		:    Optional[Any]			     =							False
			_lowercase		:    Union[str, Any]			     =							False






			def    SCREAMING_SNAKE_CASE__    (       self)      ->       Optional[Any]:
						SCREAMING_SNAKE_CASE						= FalconModelTester(self)
						SCREAMING_SNAKE_CASE						= ConfigTester(self		,					config_class=lowerCAmelCase_		,					hidden_size=37)






			def    SCREAMING_SNAKE_CASE__    (       self)      ->       List[Any]:
						self.config_tester.run_common_tests()






			def    SCREAMING_SNAKE_CASE__    (       self)      ->       Any:
						SCREAMING_SNAKE_CASE						= self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(*lowerCAmelCase_)






			def    SCREAMING_SNAKE_CASE__    (       self)      ->       str:
						SCREAMING_SNAKE_CASE				,						*SCREAMING_SNAKE_CASE						= self.model_tester.prepare_config_and_inputs()
						for alibi in [True, False]:
									SCREAMING_SNAKE_CASE						= alibi
									self.model_tester.create_and_check_model(lowerCAmelCase_		,					*lowerCAmelCase_)






			def    SCREAMING_SNAKE_CASE__    (       self)      ->       Dict:
						SCREAMING_SNAKE_CASE				,						SCREAMING_SNAKE_CASE						= self.model_tester.prepare_config_and_inputs_for_common()
						SCREAMING_SNAKE_CASE						= 3
						SCREAMING_SNAKE_CASE						= input_dict['input_ids']
						SCREAMING_SNAKE_CASE						= input_ids.ne(1).to(lowerCAmelCase_)
						SCREAMING_SNAKE_CASE						= ids_tensor([self.model_tester.batch_size]		,					self.model_tester.type_sequence_label_size)
						SCREAMING_SNAKE_CASE						= FalconForSequenceClassification(lowerCAmelCase_)
						model.to(lowerCAmelCase_)
						model.eval()
						SCREAMING_SNAKE_CASE						= model(lowerCAmelCase_		,					attention_mask=lowerCAmelCase_		,					labels=lowerCAmelCase_)
						self.assertEqual(result.logits.shape		,					(self.model_tester.batch_size, self.model_tester.num_labels))






			def    SCREAMING_SNAKE_CASE__    (       self)      ->       Optional[int]:
						SCREAMING_SNAKE_CASE				,						SCREAMING_SNAKE_CASE						= self.model_tester.prepare_config_and_inputs_for_common()
						SCREAMING_SNAKE_CASE						= 3
						SCREAMING_SNAKE_CASE						= 'single_label_classification'
						SCREAMING_SNAKE_CASE						= input_dict['input_ids']
						SCREAMING_SNAKE_CASE						= input_ids.ne(1).to(lowerCAmelCase_)
						SCREAMING_SNAKE_CASE						= ids_tensor([self.model_tester.batch_size]		,					self.model_tester.type_sequence_label_size)
						SCREAMING_SNAKE_CASE						= FalconForSequenceClassification(lowerCAmelCase_)
						model.to(lowerCAmelCase_)
						model.eval()
						SCREAMING_SNAKE_CASE						= model(lowerCAmelCase_		,					attention_mask=lowerCAmelCase_		,					labels=lowerCAmelCase_)
						self.assertEqual(result.logits.shape		,					(self.model_tester.batch_size, self.model_tester.num_labels))






			def    SCREAMING_SNAKE_CASE__    (       self)      ->       Union[str, Any]:
						SCREAMING_SNAKE_CASE				,						SCREAMING_SNAKE_CASE						= self.model_tester.prepare_config_and_inputs_for_common()
						SCREAMING_SNAKE_CASE						= input_dict['input_ids']
						SCREAMING_SNAKE_CASE						= FalconForCausalLM(lowerCAmelCase_)
						model.to(lowerCAmelCase_)
						model.eval()
						SCREAMING_SNAKE_CASE						= model(lowerCAmelCase_		,					use_cache=lowerCAmelCase_)
						SCREAMING_SNAKE_CASE						= input_ids.shape[0]
						SCREAMING_SNAKE_CASE						= model._convert_to_rw_cache(result.past_key_values)
						SCREAMING_SNAKE_CASE						= model._convert_cache_to_standard_format(lowerCAmelCase_		,					lowerCAmelCase_)
						for layer in range(len(lowerCAmelCase_)):
									for tensor_idx in range(2):
												self.assertTrue(rw_cache[layer][tensor_idx].ndim == 3)
												self.assertTrue(result.past_key_values[layer][tensor_idx].ndim == 4)
												self.assertTrue(
												    torch.all(result.past_key_values[layer][tensor_idx] == standard_cache[layer][tensor_idx]))






			def    SCREAMING_SNAKE_CASE__    (       self)      ->       Any:
						SCREAMING_SNAKE_CASE				,						SCREAMING_SNAKE_CASE						= self.model_tester.prepare_config_and_inputs_for_common()
						SCREAMING_SNAKE_CASE						= 3
						SCREAMING_SNAKE_CASE						= 'multi_label_classification'
						SCREAMING_SNAKE_CASE						= input_dict['input_ids']
						SCREAMING_SNAKE_CASE						= input_ids.ne(1).to(lowerCAmelCase_)
						SCREAMING_SNAKE_CASE						= ids_tensor(
						    [self.model_tester.batch_size, config.num_labels]		,					self.model_tester.type_sequence_label_size).to(torch.float)
						SCREAMING_SNAKE_CASE						= FalconForSequenceClassification(lowerCAmelCase_)
						model.to(lowerCAmelCase_)
						model.eval()
						SCREAMING_SNAKE_CASE						= model(lowerCAmelCase_		,					attention_mask=lowerCAmelCase_		,					labels=lowerCAmelCase_)
						self.assertEqual(result.logits.shape		,					(self.model_tester.batch_size, self.model_tester.num_labels))







			def    SCREAMING_SNAKE_CASE__    (       self)      ->       int:







						for model_class in self.all_generative_model_classes:
									SCREAMING_SNAKE_CASE				,						SCREAMING_SNAKE_CASE						= self.model_tester.prepare_config_and_inputs_for_common()

									# If it doesn't support cache, pass the test
									if not hasattr(lowerCAmelCase_		,					'use_cache'):
												return

									SCREAMING_SNAKE_CASE						= model_class(lowerCAmelCase_).to(lowerCAmelCase_)
									if "use_cache" not in inputs:
												SCREAMING_SNAKE_CASE						= True
									SCREAMING_SNAKE_CASE						= model(**lowerCAmelCase_)

									# If "past_key_values" is not returned, pass the test (e.g. RWKV uses a different cache name and format)
									if "past_key_values" not in outputs:
												return

									SCREAMING_SNAKE_CASE						= (
									    getattr(lowerCAmelCase_		,					'decoder_layers'		,					lowerCAmelCase_)
									    or getattr(lowerCAmelCase_		,					'num_decoder_layers'		,					lowerCAmelCase_)
									    or config.num_hidden_layers
									)
									SCREAMING_SNAKE_CASE						= getattr(lowerCAmelCase_		,					'num_kv_heads'		,					config.num_attention_heads)
									SCREAMING_SNAKE_CASE						= getattr(lowerCAmelCase_		,					'd_model'		,					config.hidden_size)
									SCREAMING_SNAKE_CASE						= embed_dim // num_attention_heads

									SCREAMING_SNAKE_CASE						= outputs['past_key_values']
									self.assertEqual(len(lowerCAmelCase_)		,					lowerCAmelCase_)

									SCREAMING_SNAKE_CASE				,						SCREAMING_SNAKE_CASE						= inputs['input_ids'].shape
									for i in range(lowerCAmelCase_):
												if config.new_decoder_architecture:
															SCREAMING_SNAKE_CASE						= config.num_attention_heads
												elif config.multi_query:
															SCREAMING_SNAKE_CASE						= 1
												self.assertEqual(len(past_kv[0])		,					2)  # K V for the decoder = 2
												self.assertEqual(
												    past_kv[i][0].shape		,					(batch_size, num_attention_heads, seq_length, per_head_embed_dim))
												self.assertEqual(
												    past_kv[i][1].shape		,					(batch_size, num_attention_heads, seq_length, per_head_embed_dim))



@require_torch
class 		__A  (  unittest.TestCase					):






			@slow
			def    SCREAMING_SNAKE_CASE__    (       self)      ->       List[Any]:
						SCREAMING_SNAKE_CASE						= AutoTokenizer.from_pretrained('Rocketknight1/falcon-rw-1b')
						SCREAMING_SNAKE_CASE						= FalconForCausalLM.from_pretrained('Rocketknight1/falcon-rw-1b')
						model.eval()
						model.to(lowerCAmelCase_)
						SCREAMING_SNAKE_CASE						= tokenizer('My favorite food is'		,					return_tensors='pt').to(lowerCAmelCase_)

						SCREAMING_SNAKE_CASE						= (
						    'My favorite food is pizza. I love it so much that I have a pizza party every year for my birthday.'
						)

						SCREAMING_SNAKE_CASE						= model.generate(**lowerCAmelCase_		,					do_sample=lowerCAmelCase_		,					max_new_tokens=19)
						SCREAMING_SNAKE_CASE						= tokenizer.batch_decode(lowerCAmelCase_)[0]

						self.assertEqual(lowerCAmelCase_		,					lowerCAmelCase_)






			@slow
			def    SCREAMING_SNAKE_CASE__    (       self)      ->       str:







						for repo in ["Rocketknight1/tiny-random-falcon-7b", "Rocketknight1/tiny-random-falcon-40b"]:
									SCREAMING_SNAKE_CASE						= AutoTokenizer.from_pretrained(lowerCAmelCase_)
									SCREAMING_SNAKE_CASE						= FalconForCausalLM.from_pretrained(lowerCAmelCase_)
									model.eval()
									model.to(lowerCAmelCase_)
									SCREAMING_SNAKE_CASE						= tokenizer('My favorite food is'		,					return_tensors='pt').to(lowerCAmelCase_)

									# We just test that these run without errors - the models are randomly initialized
									# and so the actual text outputs will be garbage
									model.generate(**lowerCAmelCase_		,					do_sample=lowerCAmelCase_		,					max_new_tokens=4)
									model.generate(**lowerCAmelCase_		,					do_sample=lowerCAmelCase_		,					max_new_tokens=4)
									model.generate(**lowerCAmelCase_		,					num_beams=2		,					max_new_tokens=4)







			@slow
			def    SCREAMING_SNAKE_CASE__    (       self)      ->       List[Any]:







						with torch.no_grad():
									for repo in [
									    "Rocketknight1/falcon-rw-1b",
									    "Rocketknight1/tiny-random-falcon-7b",
									    "Rocketknight1/tiny-random-falcon-40b",
									]:
												SCREAMING_SNAKE_CASE						= AutoTokenizer.from_pretrained(lowerCAmelCase_)
												SCREAMING_SNAKE_CASE						= FalconForCausalLM.from_pretrained(lowerCAmelCase_)
												model.eval()
												model.to(device=lowerCAmelCase_)
												SCREAMING_SNAKE_CASE						= tokenizer('My favorite food is'		,					return_tensors='pt').to(lowerCAmelCase_)

												# Test results are the same with and without cache
												SCREAMING_SNAKE_CASE						= model.generate(**lowerCAmelCase_		,					do_sample=lowerCAmelCase_		,					max_new_tokens=20		,					use_cache=lowerCAmelCase_)
												SCREAMING_SNAKE_CASE						= model.generate(**lowerCAmelCase_		,					do_sample=lowerCAmelCase_		,					max_new_tokens=20		,					use_cache=lowerCAmelCase_)
												self.assertTrue((outputs_cache - outputs_no_cache).sum().item() == 0)












from typing import Any, Dict, List, Union

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


if is_vision_available():
				from ..image_utils import load_image


if is_torch_available():
				import torch

				from ..models.auto.modeling_auto import MODEL_FOR_OBJECT_DETECTION_MAPPING, MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING

a_		:						str             =    logging.get_logger(__name__)


a_		:						List[Any]             =    Dict[str, Any]
a_		:						Optional[int]             =    List[Prediction]

@add_end_docstrings(A__					)
class 		_snake_case  (  A__					):






			def __init__(       self		,					*a		,					**a)      ->       int:
						super().__init__(*a		,					**a)

						if self.framework == "tf":
									raise ValueError(f'''The {self.__class__} is only available in PyTorch.''')

						requires_backends(self		,					'vision')
						self.check_model_type(
						    dict(MODEL_FOR_OBJECT_DETECTION_MAPPING.items() + MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING.items()))






			def    SCREAMING_SNAKE_CASE__    (       self		,					**a)      ->       int:
						SCREAMING_SNAKE_CASE						= {}
						if "threshold" in kwargs:
									SCREAMING_SNAKE_CASE						= kwargs['threshold']
						return {}, {}, postprocess_kwargs






			def __call__(       self		,					*a		,					**a)      ->       Union[Predictions, List[Prediction]]:
						return super().__call__(*a		,					**a)






			def    SCREAMING_SNAKE_CASE__    (       self		,					a)      ->       List[str]:
						SCREAMING_SNAKE_CASE						= load_image(a)
						SCREAMING_SNAKE_CASE						= torch.IntTensor([[image.height, image.width]])
						SCREAMING_SNAKE_CASE						= self.image_processor(images=[image]		,					return_tensors='pt')
						if self.tokenizer is not None:
									SCREAMING_SNAKE_CASE						= self.tokenizer(text=inputs['words']		,					boxes=inputs['boxes']		,					return_tensors='pt')
						SCREAMING_SNAKE_CASE						= target_size
						return inputs






			def    SCREAMING_SNAKE_CASE__    (       self		,					a)      ->       int:
						SCREAMING_SNAKE_CASE						= model_inputs.pop('target_size')
						SCREAMING_SNAKE_CASE						= self.model(**a)
						SCREAMING_SNAKE_CASE						= outputs.__class__({'target_size': target_size, **outputs})
						if self.tokenizer is not None:
									SCREAMING_SNAKE_CASE						= model_inputs['bbox']
						return model_outputs






			def    SCREAMING_SNAKE_CASE__    (       self		,					a		,					a=0.9)      ->       Dict:
						SCREAMING_SNAKE_CASE						= model_outputs['target_size']
						if self.tokenizer is not None:
									# This is a LayoutLMForTokenClassification variant.
									# The OCR got the boxes and the model classified the words.
									SCREAMING_SNAKE_CASE				,						SCREAMING_SNAKE_CASE						= target_size[0].tolist()

									def unnormalize(a):
												return self._get_bounding_box(
												    torch.Tensor(
												        [
												            (width * bbox[0] / 1000),
												            (height * bbox[1] / 1000),
												            (width * bbox[2] / 1000),
												            (height * bbox[3] / 1000),
												        ]))

									SCREAMING_SNAKE_CASE				,						SCREAMING_SNAKE_CASE						= model_outputs['logits'].squeeze(0).softmax(dim=-1).max(dim=-1)
									SCREAMING_SNAKE_CASE						= [self.model.config.idalabel[prediction] for prediction in classes.tolist()]
									SCREAMING_SNAKE_CASE						= [unnormalize(a) for bbox in model_outputs['bbox'].squeeze(0)]
									SCREAMING_SNAKE_CASE						= ['score', 'label', 'box']
									SCREAMING_SNAKE_CASE						= [dict(zip(a		,					a)) for vals in zip(scores.tolist()		,					a		,					a) if vals[0] > threshold]
						else:
									# This is a regular ForObjectDetectionModel
									SCREAMING_SNAKE_CASE						= self.image_processor.post_process_object_detection(a		,					a		,					a)
									SCREAMING_SNAKE_CASE						= raw_annotations[0]
									SCREAMING_SNAKE_CASE						= raw_annotation['scores']
									SCREAMING_SNAKE_CASE						= raw_annotation['labels']
									SCREAMING_SNAKE_CASE						= raw_annotation['boxes']

									SCREAMING_SNAKE_CASE						= scores.tolist()
									SCREAMING_SNAKE_CASE						= [self.model.config.idalabel[label.item()] for label in labels]
									SCREAMING_SNAKE_CASE						= [self._get_bounding_box(a) for box in boxes]

									# {"scores": [...], ...} --> [{"score":x, ...}, ...]
									SCREAMING_SNAKE_CASE						= ['score', 'label', 'box']
									SCREAMING_SNAKE_CASE						= [
									    dict(zip(a		,					a))
									    for vals in zip(raw_annotation['scores']		,					raw_annotation['labels']		,					raw_annotation['boxes'])
									]

						return annotation







			def    SCREAMING_SNAKE_CASE__    (       self		,					a)      ->       Dict[str, int]:
						if self.framework != "pt":
									raise ValueError('The ObjectDetectionPipeline is only available in PyTorch.')
						SCREAMING_SNAKE_CASE				,						SCREAMING_SNAKE_CASE				,						SCREAMING_SNAKE_CASE				,						SCREAMING_SNAKE_CASE						= box.int().tolist()
						SCREAMING_SNAKE_CASE						= {
						    'xmin': xmin,
						    'ymin': ymin,
						    'xmax': xmax,
						    'ymax': ymax,
						}
						return bbox




