


'''simple docstring'''




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

__snake_case    						=logging.get_logger(__name__)


__snake_case    						=Dict[str, Any]
__snake_case    						=List[Prediction]

@add_end_docstrings(UpperCAmelCase__		)
class 		UpperCAmelCase_      (  UpperCAmelCase__		):





     def __init__( self       :      List[str]    ,      *UpperCAmelCase__       :      Union[str, Any]    ,      **UpperCAmelCase__       :      str    )				->  List[str]:
        super().__init__(*__lowercase    ,      **__lowercase    )

        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 							__UpperCAmelCase      ( self       :      Optional[Any]    ,      **UpperCAmelCase__       :      str    )				->  Any:
        lowerCAmelCase     =			{}
        if "threshold" in kwargs:
           lowerCAmelCase     =			kwargs['threshold']
        return {}, {}, postprocess_kwargs





     def __call__( self       :      List[Any]    ,      *UpperCAmelCase__       :      str    ,      **UpperCAmelCase__       :      Optional[Any]    )				->  List[Any]:
        return super().__call__(*__lowercase    ,      **__lowercase    )





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





     def 							__UpperCAmelCase      ( self       :      int    ,      UpperCAmelCase__       :      Dict    )				->  Optional[int]:
        lowerCAmelCase     =			model_inputs.pop('target_size'    )
        lowerCAmelCase     =			self.model(**__lowercase    )
        lowerCAmelCase     =			outputs.__class__({'target_size': target_size, **outputs}    )
        if self.tokenizer is not None:
           lowerCAmelCase     =			model_inputs['bbox']
        return model_outputs





     def 							__UpperCAmelCase      ( self       :      Union[str, Any]    ,      UpperCAmelCase__       :      List[str]    ,      UpperCAmelCase__       :      List[str]=0.9    )				->  List[str]:
        lowerCAmelCase     =			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.
           lowerCAmelCase     ,  lowerCAmelCase     =			target_size[0].tolist()

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

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

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

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

        return annotation





     def 							__UpperCAmelCase      ( self       :      str    ,      UpperCAmelCase__       :      "torch.Tensor"    )				->  Any:






        if self.framework != "pt":
           raise ValueError('The ObjectDetectionPipeline is only available in PyTorch.'    )
        lowerCAmelCase     ,  lowerCAmelCase     ,  lowerCAmelCase     ,  lowerCAmelCase     =			box.int().tolist()
        lowerCAmelCase     =			{
            'xmin': xmin,
            'ymin': ymin,
            'xmax': xmax,
            'ymax': ymax,
        }
        return bbox











def 						lowerCamelCase__    (		):







	'''simple docstring'''





	snake_case_		    =     []
	snake_case_		    =     1

	while len(_A							) < 1E6:
		constant.append(str(_A							)							)
		i += 1

	snake_case_		    =     "".join(_A							)

	return (
	    int(constant[0]							)
	    * int(constant[9]							)
	    * int(constant[99]							)
	    * int(constant[999]							)
	    * int(constant[9999]							)
	    * int(constant[99999]							)
	    * int(constant[999999]							)
	)


if __name__ == "__main__":
		print(solution())
