


"""simple docstring"""







from collections.abc import Callable
def _A						(						lowercase	,   lowercase	,   lowercase		):







    """simple docstring"""
    a					=a
    a					=b
    if function(lowercase		) == 0:  # one of the a or b is a root for the function
        return a
    elif function(lowercase		) == 0:
        return b
    elif (
        function(lowercase		) * function(lowercase		) > 0
    ):  # if none of these are root and they are both positive or negative,
        # then this algorithm can't find the root
        raise ValueError('''could not find root in given interval.'''		)
    else:
        a					=start + (end - start) / 2.0
        while abs(start - mid		) > 10**-7:  # until precisely equals to 10^-7
            if function(lowercase		) == 0:
                return mid
            elif function(lowercase		) * function(lowercase		) < 0:
                a					=mid
            else:
                a					=mid
            a					=start + (end - start) / 2.0
        return mid
def _A						(						lowercase		):







    """simple docstring"""
    return x**3 - 2 * x - 5


if __name__ == "__main__":
       print(bisection(f, 1, 1_0_0_0))

       import doctest

       doctest.testmod()



"""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, ChunkPipeline


if is_vision_available():
       from PIL import Image

       from ..image_utils import load_image

if is_torch_available():
       import torch

       from transformers.modeling_outputs import BaseModelOutput

       from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING

lowerCamelCase_       :       Dict      						=  logging.get_logger(__name__)






@add_end_docstrings(_SCREAMING_SNAKE_CASE      )
class 				__A    (	_SCREAMING_SNAKE_CASE      ):






 """simple docstring"""




 def __init__(		self			,   **__A						) ->					Dict:
     super().__init__(**__A						)

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

     requires_backends(self			,   '''vision'''						)
     self.check_model_type(__A						)


 def __call__(		self			,   __A			,   __A = None			,   **__A			,   ) ->					List[str]:
     if "text_queries" in kwargs:
         a					=kwargs.pop('''text_queries'''						)

     if isinstance(__A			,   (str, Image.Image)						):
         a					={'''image''': image, '''candidate_labels''': candidate_labels}
     else:
         a					=image
     a					=super().__call__(__A			,   **__A						)
     return results


 def 				SCREAMING_SNAKE_CASE							(		self			,   **__A						) ->					Optional[Any]:
     a					={}
     if "threshold" in kwargs:
         a					=kwargs['''threshold''']
     if "top_k" in kwargs:
         a					=kwargs['''top_k''']
     return {}, {}, postprocess_params


 def 				SCREAMING_SNAKE_CASE							(		self			,   __A						) ->					str:
     a					=load_image(inputs['''image''']						)
     a					=inputs['''candidate_labels''']
     if isinstance(__A			,   __A						):
         a					=candidate_labels.split(''','''						)

     a					=torch.tensor([[image.height, image.width]]			,   dtype=torch.intaa						)
     for i, candidate_label in enumerate(__A						):
         a					=self.tokenizer(__A			,   return_tensors=self.framework						)
         a					=self.image_processor(__A			,   return_tensors=self.framework						)
         yield {
             "is_last": i == len(__A						) - 1,
             "target_size": target_size,
             "candidate_label": candidate_label,
             **text_inputs,
             **image_features,
         }


 def 				SCREAMING_SNAKE_CASE							(		self			,   __A						) ->					List[Any]:
     a					=model_inputs.pop('''target_size'''						)
     a					=model_inputs.pop('''candidate_label'''						)
     a					=model_inputs.pop('''is_last'''						)

     a					=self.model(**__A						)

     a					={'''target_size''': target_size, '''candidate_label''': candidate_label, '''is_last''': is_last, **outputs}
     return model_outputs


 def 				SCREAMING_SNAKE_CASE							(		self			,   __A			,   __A=0.1			,   __A=None						) ->					List[str]:
     a					=[]
     for model_output in model_outputs:
         a					=model_output['''candidate_label''']
         a					=BaseModelOutput(__A						)
         a					=self.image_processor.post_process_object_detection(
             outputs=__A			,   threshold=__A			,   target_sizes=model_output['''target_size''']						)[0]

         for index in outputs["scores"].nonzero():
             a					=outputs['''scores'''][index].item()
             a					=self._get_bounding_box(outputs['''boxes'''][index][0]						)

             a					={'''score''': score, '''label''': label, '''box''': box}
             results.append(__A						)

     a					=sorted(__A			,   key=lambda __A						: x["score"]			,   reverse=__A						)
     if top_k:
         a					=results[:top_k]

     return results





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