

import unittest

from transformers import (
    MODEL_FOR_OBJECT_DETECTION_MAPPING,
    AutoFeatureExtractor,
    AutoModelForObjectDetection,
    ObjectDetectionPipeline,
    is_vision_available,
    pipeline,
)
from transformers.testing_utils import (
    is_pipeline_test,
    nested_simplify,
    require_pytesseract,
    require_tf,
    require_timm,
    require_torch,
    require_vision,
    slow,
)

from .test_pipelines_common import ANY


if is_vision_available():
					from PIL import Image
else:

					class 				a  :


											@staticmethod
											def        _UpperCAmelCase				(       *A_						,					**A_	):







															'''simple docstring'''


															pass

@is_pipeline_test
@require_vision
@require_timm
@require_torch
class 				a  (	unittest.TestCase				):
						_lowercase    						=			MODEL_FOR_OBJECT_DETECTION_MAPPING


						def        _UpperCAmelCase				(       self						,					A_						,					A_						,					A_	):







										'''simple docstring'''


										_UpperCAmelCase       :		Optional[Any] 		=    ObjectDetectionPipeline(model=A_						,					image_processor=A_	)
										return object_detector, ["./tests/fixtures/tests_samples/COCO/000000039769.png"]


						def        _UpperCAmelCase				(       self						,					A_						,					A_	):







										'''simple docstring'''


										_UpperCAmelCase       :		Any 		=    object_detector("./tests/fixtures/tests_samples/COCO/000000039769.png"						,					threshold=0.0	)

										self.assertGreater(len(A_	)						,					0	)
										for detected_object in outputs:
														self.assertEqual(
														    A_						,					{
														        "score": ANY(A_	),
														        "label": ANY(A_	),
														        "box": {"xmin": ANY(A_	), "ymin": ANY(A_	), "xmax": ANY(A_	), "ymax": ANY(A_	)},
														    }						,					)

										import datasets

										_UpperCAmelCase       :		Union[str, Any] 		=    datasets.load_dataset("hf-internal-testing/fixtures_image_utils"						,					"image"						,					split="test"	)

										_UpperCAmelCase       :		List[str] 		=    [
										    Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"	),
										    "http://images.cocodataset.org/val2017/000000039769.jpg",
										    # RGBA
										    dataset[0]["file"],
										    # LA
										    dataset[1]["file"],
										    # L
										    dataset[2]["file"],
										]
										_UpperCAmelCase       :		List[str] 		=    object_detector(A_						,					threshold=0.0	)

										self.assertEqual(len(A_	)						,					len(A_	)	)
										for outputs in batch_outputs:
														self.assertGreater(len(A_	)						,					0	)
														for detected_object in outputs:
																		self.assertEqual(
																		    A_						,					{
																		        "score": ANY(A_	),
																		        "label": ANY(A_	),
																		        "box": {"xmin": ANY(A_	), "ymin": ANY(A_	), "xmax": ANY(A_	), "ymax": ANY(A_	)},
																		    }						,					)


						@require_tf
						@unittest.skip("Object detection not implemented in TF"	)
						def        _UpperCAmelCase				(       self	):







										'''simple docstring'''


										pass


						@require_torch
						def        _UpperCAmelCase				(       self	):







										'''simple docstring'''


										_UpperCAmelCase       :		Union[str, Any] 		=    "hf-internal-testing/tiny-detr-mobilenetsv3"

										_UpperCAmelCase       :		Any 		=    AutoModelForObjectDetection.from_pretrained(A_	)
										_UpperCAmelCase       :		Union[str, Any] 		=    AutoFeatureExtractor.from_pretrained(A_	)
										_UpperCAmelCase       :		List[str] 		=    ObjectDetectionPipeline(model=A_						,					feature_extractor=A_	)

										_UpperCAmelCase       :		Union[str, Any] 		=    object_detector("http://images.cocodataset.org/val2017/000000039769.jpg"						,					threshold=0.0	)

										self.assertEqual(
										    nested_simplify(A_						,					decimals=4	)						,					[
										        {"score": 0.33_76, "label": "LABEL_0", "box": {"xmin": 159, "ymin": 120, "xmax": 480, "ymax": 359}},
										        {"score": 0.33_76, "label": "LABEL_0", "box": {"xmin": 159, "ymin": 120, "xmax": 480, "ymax": 359}},
										    ]						,					)

										_UpperCAmelCase       :		Union[str, Any] 		=    object_detector(
										    [
										        "http://images.cocodataset.org/val2017/000000039769.jpg",
										        "http://images.cocodataset.org/val2017/000000039769.jpg",
										    ]						,					threshold=0.0						,					)

										self.assertEqual(
										    nested_simplify(A_						,					decimals=4	)						,					[
										        [
										            {"score": 0.33_76, "label": "LABEL_0", "box": {"xmin": 159, "ymin": 120, "xmax": 480, "ymax": 359}},
										            {"score": 0.33_76, "label": "LABEL_0", "box": {"xmin": 159, "ymin": 120, "xmax": 480, "ymax": 359}},
										        ],
										        [
										            {"score": 0.33_76, "label": "LABEL_0", "box": {"xmin": 159, "ymin": 120, "xmax": 480, "ymax": 359}},
										            {"score": 0.33_76, "label": "LABEL_0", "box": {"xmin": 159, "ymin": 120, "xmax": 480, "ymax": 359}},
										        ],
										    ]						,					)


						@require_torch
						@slow
						def        _UpperCAmelCase				(       self	):







										'''simple docstring'''


										_UpperCAmelCase       :		Tuple 		=    "facebook/detr-resnet-50"

										_UpperCAmelCase       :		Tuple 		=    AutoModelForObjectDetection.from_pretrained(A_	)
										_UpperCAmelCase       :		Any 		=    AutoFeatureExtractor.from_pretrained(A_	)
										_UpperCAmelCase       :		Optional[Any] 		=    ObjectDetectionPipeline(model=A_						,					feature_extractor=A_	)

										_UpperCAmelCase       :		Dict 		=    object_detector("http://images.cocodataset.org/val2017/000000039769.jpg"	)
										self.assertEqual(
										    nested_simplify(A_						,					decimals=4	)						,					[
										        {"score": 0.99_82, "label": "remote", "box": {"xmin": 40, "ymin": 70, "xmax": 175, "ymax": 117}},
										        {"score": 0.99_60, "label": "remote", "box": {"xmin": 333, "ymin": 72, "xmax": 368, "ymax": 187}},
										        {"score": 0.99_55, "label": "couch", "box": {"xmin": 0, "ymin": 1, "xmax": 639, "ymax": 473}},
										        {"score": 0.99_88, "label": "cat", "box": {"xmin": 13, "ymin": 52, "xmax": 314, "ymax": 470}},
										        {"score": 0.99_87, "label": "cat", "box": {"xmin": 345, "ymin": 23, "xmax": 640, "ymax": 368}},
										    ]						,					)

										_UpperCAmelCase       :		Any 		=    object_detector(
										    [
										        "http://images.cocodataset.org/val2017/000000039769.jpg",
										        "http://images.cocodataset.org/val2017/000000039769.jpg",
										    ]	)
										self.assertEqual(
										    nested_simplify(A_						,					decimals=4	)						,					[
										        [
										            {"score": 0.99_82, "label": "remote", "box": {"xmin": 40, "ymin": 70, "xmax": 175, "ymax": 117}},
										            {"score": 0.99_60, "label": "remote", "box": {"xmin": 333, "ymin": 72, "xmax": 368, "ymax": 187}},
										            {"score": 0.99_55, "label": "couch", "box": {"xmin": 0, "ymin": 1, "xmax": 639, "ymax": 473}},
										            {"score": 0.99_88, "label": "cat", "box": {"xmin": 13, "ymin": 52, "xmax": 314, "ymax": 470}},
										            {"score": 0.99_87, "label": "cat", "box": {"xmin": 345, "ymin": 23, "xmax": 640, "ymax": 368}},
										        ],
										        [
										            {"score": 0.99_82, "label": "remote", "box": {"xmin": 40, "ymin": 70, "xmax": 175, "ymax": 117}},
										            {"score": 0.99_60, "label": "remote", "box": {"xmin": 333, "ymin": 72, "xmax": 368, "ymax": 187}},
										            {"score": 0.99_55, "label": "couch", "box": {"xmin": 0, "ymin": 1, "xmax": 639, "ymax": 473}},
										            {"score": 0.99_88, "label": "cat", "box": {"xmin": 13, "ymin": 52, "xmax": 314, "ymax": 470}},
										            {"score": 0.99_87, "label": "cat", "box": {"xmin": 345, "ymin": 23, "xmax": 640, "ymax": 368}},
										        ],
										    ]						,					)


						@require_torch
						@slow
						def        _UpperCAmelCase				(       self	):







										'''simple docstring'''


										_UpperCAmelCase       :		List[Any] 		=    "facebook/detr-resnet-50"

										_UpperCAmelCase       :		str 		=    pipeline("object-detection"						,					model=A_	)

										_UpperCAmelCase       :		List[Any] 		=    object_detector("http://images.cocodataset.org/val2017/000000039769.jpg"	)
										self.assertEqual(
										    nested_simplify(A_						,					decimals=4	)						,					[
										        {"score": 0.99_82, "label": "remote", "box": {"xmin": 40, "ymin": 70, "xmax": 175, "ymax": 117}},
										        {"score": 0.99_60, "label": "remote", "box": {"xmin": 333, "ymin": 72, "xmax": 368, "ymax": 187}},
										        {"score": 0.99_55, "label": "couch", "box": {"xmin": 0, "ymin": 1, "xmax": 639, "ymax": 473}},
										        {"score": 0.99_88, "label": "cat", "box": {"xmin": 13, "ymin": 52, "xmax": 314, "ymax": 470}},
										        {"score": 0.99_87, "label": "cat", "box": {"xmin": 345, "ymin": 23, "xmax": 640, "ymax": 368}},
										    ]						,					)

										_UpperCAmelCase       :		Dict 		=    object_detector(
										    [
										        "http://images.cocodataset.org/val2017/000000039769.jpg",
										        "http://images.cocodataset.org/val2017/000000039769.jpg",
										    ]	)
										self.assertEqual(
										    nested_simplify(A_						,					decimals=4	)						,					[
										        [
										            {"score": 0.99_82, "label": "remote", "box": {"xmin": 40, "ymin": 70, "xmax": 175, "ymax": 117}},
										            {"score": 0.99_60, "label": "remote", "box": {"xmin": 333, "ymin": 72, "xmax": 368, "ymax": 187}},
										            {"score": 0.99_55, "label": "couch", "box": {"xmin": 0, "ymin": 1, "xmax": 639, "ymax": 473}},
										            {"score": 0.99_88, "label": "cat", "box": {"xmin": 13, "ymin": 52, "xmax": 314, "ymax": 470}},
										            {"score": 0.99_87, "label": "cat", "box": {"xmin": 345, "ymin": 23, "xmax": 640, "ymax": 368}},
										        ],
										        [
										            {"score": 0.99_82, "label": "remote", "box": {"xmin": 40, "ymin": 70, "xmax": 175, "ymax": 117}},
										            {"score": 0.99_60, "label": "remote", "box": {"xmin": 333, "ymin": 72, "xmax": 368, "ymax": 187}},
										            {"score": 0.99_55, "label": "couch", "box": {"xmin": 0, "ymin": 1, "xmax": 639, "ymax": 473}},
										            {"score": 0.99_88, "label": "cat", "box": {"xmin": 13, "ymin": 52, "xmax": 314, "ymax": 470}},
										            {"score": 0.99_87, "label": "cat", "box": {"xmin": 345, "ymin": 23, "xmax": 640, "ymax": 368}},
										        ],
										    ]						,					)


						@require_torch
						@slow
						def        _UpperCAmelCase				(       self	):







										'''simple docstring'''


										_UpperCAmelCase       :		Any 		=    0.99_85
										_UpperCAmelCase       :		Optional[int] 		=    "facebook/detr-resnet-50"

										_UpperCAmelCase       :		Dict 		=    pipeline("object-detection"						,					model=A_	)

										_UpperCAmelCase       :		str 		=    object_detector("http://images.cocodataset.org/val2017/000000039769.jpg"						,					threshold=A_	)
										self.assertEqual(
										    nested_simplify(A_						,					decimals=4	)						,					[
										        {"score": 0.99_88, "label": "cat", "box": {"xmin": 13, "ymin": 52, "xmax": 314, "ymax": 470}},
										        {"score": 0.99_87, "label": "cat", "box": {"xmin": 345, "ymin": 23, "xmax": 640, "ymax": 368}},
										    ]						,					)





						@require_torch
						@require_pytesseract
						@slow
						def        _UpperCAmelCase				(       self	):







										'''simple docstring'''


										_UpperCAmelCase       :		Dict 		=    "Narsil/layoutlmv3-finetuned-funsd"
										_UpperCAmelCase       :		List[Any] 		=    0.99_93

										_UpperCAmelCase       :		List[str] 		=    pipeline("object-detection"						,					model=A_						,					threshold=A_	)

										_UpperCAmelCase       :		Optional[int] 		=    object_detector(
										    "https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png"	)
										self.assertEqual(
										    nested_simplify(A_						,					decimals=4	)						,					[
										        {"score": 0.99_93, "label": "I-ANSWER", "box": {"xmin": 294, "ymin": 254, "xmax": 343, "ymax": 264}},
										        {"score": 0.99_93, "label": "I-ANSWER", "box": {"xmin": 294, "ymin": 254, "xmax": 343, "ymax": 264}},
										    ]						,					)





from collections import OrderedDict
from typing import TYPE_CHECKING, Any, List, Mapping, Optional

from packaging import version


if TYPE_CHECKING:
					from ... import PreTrainedTokenizer, TensorType

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfigWithPast, PatchingSpec
from ...utils import is_torch_available, logging


SCREAMING_SNAKE_CASE_        =      logging.get_logger(__name__)

SCREAMING_SNAKE_CASE_        =      {
    'bigscience/bloom': 'https://huggingface.co/bigscience/bloom/resolve/main/config.json',
    'bigscience/bloom-560m': 'https://huggingface.co/bigscience/bloom-560m/blob/main/config.json',
    'bigscience/bloom-1b1': 'https://huggingface.co/bigscience/bloom-1b1/blob/main/config.json',
    'bigscience/bloom-1b7': 'https://huggingface.co/bigscience/bloom-1b7/blob/main/config.json',
    'bigscience/bloom-3b': 'https://huggingface.co/bigscience/bloom-3b/blob/main/config.json',
    'bigscience/bloom-7b1': 'https://huggingface.co/bigscience/bloom-7b1/blob/main/config.json',
}

class 				a  (	UpperCAmelCase				):
						_lowercase    						=			"bloom"
						_lowercase    						=			["past_key_values"]
						_lowercase    						=			{
						    "num_hidden_layers": "n_layer",
						    "num_attention_heads": "n_head",
						}


						def __init__(       self						,					A_=250880						,					A_=64						,					A_=2						,					A_=8						,					A_=1e-5						,					A_=0.02						,					A_=True						,					A_=1						,					A_=2						,					A_=False						,					A_=0.0						,					A_=0.0						,					A_=1						,					A_=False						,					**A_						,					):







										'''simple docstring'''


										_UpperCAmelCase       :		List[str] 		=    vocab_size
										# Backward compatibility with n_embed kwarg
										_UpperCAmelCase       :		str 		=    kwargs.pop("n_embed"						,					A_	)
										_UpperCAmelCase       :		List[Any] 		=    hidden_size if n_embed is None else n_embed
										_UpperCAmelCase       :		Dict 		=    n_layer
										_UpperCAmelCase       :		Optional[Any] 		=    n_head
										_UpperCAmelCase       :		Optional[Any] 		=    layer_norm_epsilon
										_UpperCAmelCase       :		List[Any] 		=    initializer_range
										_UpperCAmelCase       :		Union[str, Any] 		=    use_cache
										_UpperCAmelCase       :		List[str] 		=    pretraining_tp
										_UpperCAmelCase       :		List[Any] 		=    apply_residual_connection_post_layernorm
										_UpperCAmelCase       :		int 		=    hidden_dropout
										_UpperCAmelCase       :		List[str] 		=    attention_dropout

										_UpperCAmelCase       :		int 		=    bos_token_id
										_UpperCAmelCase       :		str 		=    eos_token_id
										_UpperCAmelCase       :		Optional[Any] 		=    slow_but_exact

										super().__init__(bos_token_id=A_						,					eos_token_id=A_						,					**A_	)







class 				a  (	UpperCAmelCase				):
						_lowercase    						=			version.parse("1.12"				)


						def __init__(       self						,					A_						,					A_ = "default"						,					A_ = None						,					A_ = False						,					):







										'''simple docstring'''


										super().__init__(A_						,					task=A_						,					patching_specs=A_						,					use_past=A_	)
										if not getattr(self._config						,					"pad_token_id"						,					A_	):
														# TODO: how to do that better?
														_UpperCAmelCase       :		str 		=    0


						@property
						def        _UpperCAmelCase				(       self	):







										'''simple docstring'''


										_UpperCAmelCase       :		List[Any] 		=    OrderedDict({"input_ids": {0: "batch", 1: "sequence"}}	)
										if self.use_past:
														# BLOOM stores values on dynamic axis 2. For more details see: https://github.com/huggingface/transformers/pull/18344
														self.fill_with_past_key_values_(A_						,					direction="inputs"						,					inverted_values_shape=A_	)
														_UpperCAmelCase       :		Optional[int] 		=    {0: "batch", 1: "past_sequence + sequence"}
										else:
														_UpperCAmelCase       :		Union[str, Any] 		=    {0: "batch", 1: "sequence"}

										return common_inputs


						@property
						def        _UpperCAmelCase				(       self	):







										'''simple docstring'''


										return self._config.n_layer


						@property
						def        _UpperCAmelCase				(       self	):







										'''simple docstring'''


										return self._config.n_head


						@property
						def        _UpperCAmelCase				(       self	):







										'''simple docstring'''


										return 1e-3


						def        _UpperCAmelCase				(       self						,					A_						,					A_ = -1						,					A_ = -1						,					A_ = False						,					A_ = None						,					):







										'''simple docstring'''


										_UpperCAmelCase       :		int 		=    super(A_						,					self	).generate_dummy_inputs(
										    A_						,					batch_size=A_						,					seq_length=A_						,					is_pair=A_						,					framework=A_	)

										# We need to order the input in the way they appears in the forward()
										_UpperCAmelCase       :		Tuple 		=    OrderedDict({"input_ids": common_inputs["input_ids"]}	)

										# Need to add the past_keys
										if self.use_past:
														if not is_torch_available():
																		raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed."	)
														else:
																		import torch

																		_UpperCAmelCase		,							_UpperCAmelCase       :		Union[str, Any] 		=    common_inputs["input_ids"].shape
																		# Not using the same length for past_key_values
																		_UpperCAmelCase       :		List[Any] 		=    seqlen + 2
																		_UpperCAmelCase       :		Dict 		=    self._config.hidden_size // self.num_attention_heads
																		_UpperCAmelCase       :		List[Any] 		=    (
																		    batch * self.num_attention_heads,
																		    head_dim,
																		    past_key_values_length,
																		)
																		_UpperCAmelCase       :		Optional[Any] 		=    (
																		    batch * self.num_attention_heads,
																		    past_key_values_length,
																		    head_dim,
																		)
																		_UpperCAmelCase       :		Tuple 		=    [
																		    (torch.zeros(A_	), torch.zeros(A_	)) for _ in range(self.num_layers	)
																		]

										_UpperCAmelCase       :		int 		=    common_inputs["attention_mask"]
										if self.use_past:
														_UpperCAmelCase       :		str 		=    ordered_inputs["attention_mask"].dtype
														_UpperCAmelCase       :		Optional[int] 		=    torch.cat(
														    [ordered_inputs["attention_mask"], torch.ones(A_						,					A_						,					dtype=A_	)]						,					dim=1	)

										return ordered_inputs





						@property
						def        _UpperCAmelCase				(       self	):







										'''simple docstring'''


										return 13


