U
    5Af                     @   s   d dl mZmZ d dlZddlmZmZmZm	Z	m
Z
 ddlmZmZ e rbd dlmZ ddlmZ e r|d dlZdd	lmZ e	eZeed
dG dd deZdS )    )ListUnionN   )add_end_docstringsis_torch_availableis_vision_availableloggingrequires_backends   )Pipelinebuild_pipeline_init_args)Image)
load_image)(MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMEST)Zhas_image_processorc                       sj   e Zd ZdZ fddZeeee ded f d fddZdd	d
Z	dddZ
dd Zdd Z  ZS )DepthEstimationPipelinea  
    Depth estimation pipeline using any `AutoModelForDepthEstimation`. This pipeline predicts the depth of an image.

    Example:

    ```python
    >>> from transformers import pipeline

    >>> depth_estimator = pipeline(task="depth-estimation", model="LiheYoung/depth-anything-base-hf")
    >>> output = depth_estimator("http://images.cocodataset.org/val2017/000000039769.jpg")
    >>> # This is a tensor with the values being the depth expressed in meters for each pixel
    >>> output["predicted_depth"].shape
    torch.Size([1, 384, 384])
    ```

    Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)


    This depth estimation pipeline can currently be loaded from [`pipeline`] using the following task identifier:
    `"depth-estimation"`.

    See the list of available models on [huggingface.co/models](https://huggingface.co/models?filter=depth-estimation).
    c                    s&   t  j|| t| d | t d S )NZvision)super__init__r	   Zcheck_model_typer   )selfargskwargs	__class__ K/tmp/pip-unpacked-wheel-zw5xktn0/transformers/pipelines/depth_estimation.pyr   0   s    
z DepthEstimationPipeline.__init__zImage.Image)imagesc                    s   t  j|f|S )a  
        Predict the depth(s) of the image(s) passed as inputs.

        Args:
            images (`str`, `List[str]`, `PIL.Image` or `List[PIL.Image]`):
                The pipeline handles three types of images:

                - A string containing a http link pointing to an image
                - A string containing a local path to an image
                - An image loaded in PIL directly

                The pipeline accepts either a single image or a batch of images, which must then be passed as a string.
                Images in a batch must all be in the same format: all as http links, all as local paths, or all as PIL
                images.
            timeout (`float`, *optional*, defaults to None):
                The maximum time in seconds to wait for fetching images from the web. If None, no timeout is set and
                the call may block forever.

        Return:
            A dictionary or a list of dictionaries containing result. If the input is a single image, will return a
            dictionary, if the input is a list of several images, will return a list of dictionaries corresponding to
            the images.

            The dictionaries contain the following keys:

            - **predicted_depth** (`torch.Tensor`) -- The predicted depth by the model as a `torch.Tensor`.
            - **depth** (`PIL.Image`) -- The predicted depth by the model as a `PIL.Image`.
        )r   __call__)r   r   r   r   r   r   r   5   s    z DepthEstimationPipeline.__call__Nc                 K   s   i }|d k	r||d< |i i fS )Ntimeoutr   )r   r   r   Zpreprocess_paramsr   r   r   _sanitize_parametersT   s    z,DepthEstimationPipeline._sanitize_parametersc                 C   s<   t ||}|j| _| j|| jd}| jdkr8|| j}|S )N)r   Zreturn_tensorspt)r   size
image_sizeZimage_processorZ	frameworktoZtorch_dtype)r   imager   model_inputsr   r   r   
preprocessZ   s    

z"DepthEstimationPipeline.preprocessc                 C   s   | j f |}|S )N)model)r   r#   model_outputsr   r   r   _forwardb   s    z DepthEstimationPipeline._forwardc                 C   sx   |j }tjjj|d| jd d d ddd}|  	 }|d t
| d}t|}i }||d< ||d	< |S )
Nr
   ZbicubicF)r   modeZalign_corners   Zuint8predicted_depthdepth)r+   torchnnZ
functionalZinterpolateZ	unsqueezer    ZsqueezecpunumpynpmaxZastyper   Z	fromarray)r   r&   r+   Z
predictionoutput	formattedr,   Zoutput_dictr   r   r   postprocessf   s       
z#DepthEstimationPipeline.postprocess)N)N)__name__
__module____qualname____doc__r   r   strr   r   r   r$   r'   r5   __classcell__r   r   r   r   r      s   &

r   )typingr   r   r0   r1   utilsr   r   r   r   r	   baser   r   ZPILr   Zimage_utilsr   r-   Zmodels.auto.modeling_autor   Z
get_loggerr6   loggerr   r   r   r   r   <module>   s   
