U
    !?h{,                     @   s   d dl Z d dlmZ d dlmZ d dlZd dlZd dlZ	d dl
Z
d dlmZ d dlmZ d dlmZ ddlmZ eeedd	d
ZejdddZdd Zdd ZG dd deZdS )    N)deepcopy)List)validate)Image   )BaseSession)oldholdwlong_side_lengthc                 C   sD   |d t | | }| | ||  }}t|d }t|d }||fS )Ng      ?g      ?)maxint)r   r	   r
   scaleZnewhZneww r   D/var/www/html/venv/lib/python3.8/site-packages/rembg/sessions/sam.pyget_preprocess_shape   s
    r   )coordsc                 C   sZ   |\}}t |d |d |\}}t| t} | d ||  | d< | d ||  | d< | S )Nr   r   ).r   ).r   )r   r   astypefloat)r   original_sizeZtarget_lengthZold_hZold_wZnew_hZnew_wr   r   r   apply_coords   s      r   c                 C   s   g }g }| D ]}|d dkr:| |d  | |d  q|d dkr| |d d |d d g | |d d |d d	 g | d | d	 qt|t| }}||fS )
NtypepointdatalabelZ	rectangler   r         )appendnparray)promptZpointslabelsmarkr   r   r   get_input_points&   s    
r"   c                 C   s   g }t | jd D ]d}g }t | jd D ]B}| ||f }tj||d d |d |d ftjd}|| q(|| qt|S )Nr   r   r   flags)rangeshapecv2
warpAffineINTER_LINEARr   r   r   )masksr   transform_matrixZoutput_masksbatchZbatch_masksZmask_idmaskr   r   r   transform_masks8   s    
r.   c                   @   sP   e Zd ZdZdeejdddZee	e dddZ
ed	d
 Zedd ZdS )
SamSessiona  
    This class represents a session for the Sam model.

    Args:
        model_name (str): The name of the model.
        sess_opts (ort.SessionOptions): The session options.
        *args: Variable length argument list.
        **kwargs: Arbitrary keyword arguments.
    N)
model_name	sess_optsc           
      O   s   || _ g }t }|r8|pg D ]}||kr|| qn
|| | jj||}	tjt|	d ||d| _	tjt|	d ||d| _
dS )aF  
        Initialize a new SamSession with the given model name and session options.

        Args:
            model_name (str): The name of the model.
            sess_opts (ort.SessionOptions): The session options.
            *args: Variable length argument list.
            **kwargs: Arbitrary keyword arguments.
        r   )	providersZsess_optionsr   N)r0   ortZget_available_providersr   extend	__class__download_modelsZInferenceSessionstrencoderdecoder)
selfr0   r1   r2   argskwargsZvalid_providersZavailable_providersproviderpathsr   r   r   __init__V   s&    


zSamSession.__init__)imgreturnc              	   O   s  | dddt|jd t|jd gdg}dddd	idd
idddidddd}t||d d}d}| j d j}|d}t	
|}	|	jdd }
|d |	jd  }|d |	jd  }t||}t	
|ddgd|dgdddgg}tj|	|dd |d |d ftjd}	||	t	ji}| jd|}|d }||
|d}t|\}}t	j|t	
ddgggdddddddf }t	j|t	
dggdddddf t	j}t|||t	j}t	j|t	jd|jd dft	jdgdd}t	||j}|ddddddf t	j}t	jdt	jd}t	jdt	jd}|||||t	j
|t	jdd}| jd|\}}}t	j|}t||
|}t	j|jd |jd dft	jd}|dddddddf D ]}dddg||dk< qt |dgS )a}  
        Predict masks for an input image.

        This function takes an image as input and performs various preprocessing steps on the image. It then runs the image through an encoder to obtain an image embedding. The function also takes input labels and points as additional arguments. It concatenates the input points and labels with padding and transforms them. It creates an empty mask input and an indicator for no mask. The function then passes the image embedding, point coordinates, point labels, mask input, and has mask input to a decoder. The decoder generates masks based on the input and returns them as a list of images.

        Parameters:
            img (PILImage): The input image.
            *args: Additional arguments.
            **kwargs: Additional keyword arguments.

        Returns:
            List[PILImage]: A list of masks generated by the decoder.
        Z
sam_promptr   r   r   )r   r   r   r   objectr   stringintegernumber)r   items)r   
properties)instanceschema   )i  rJ   r   RGBNr#   )image_embeddingr   r+   g        )Zaxis)Zdtype)r   r      rN   )Zimage_embeddingsZpoint_coordsZpoint_labelsZ
mask_inputZhas_mask_inputZorig_im_sizer      L)!getr   widthheightr   r8   
get_inputsnameconvertr   r   r&   minr'   r(   r)   r   Zfloat32runr"   Zconcatenater   ZonesmatmulTZzerosr9   Zlinalginvr.   Zuint8r   Z	fromarray)r:   r@   r;   r<   r   rI   Ztarget_sizeZ
input_sizeZencoder_input_nameZcv_imager   Zscale_xZscale_yr   r+   Zencoder_inputsZencoder_outputrL   Z	embeddingZinput_pointsZinput_labelsZ
onnx_coordZ
onnx_labelZonnx_mask_inputZonnx_has_mask_inputZdecoder_inputsr*   _Zinv_transform_matrixr-   mr   r   r   predict   s    




 
"	" zSamSession.predictc              	   O   s  | dd}| dd}| d}| d}|rD| d}| d}tjd	| d
|| j||dd tjd	| d
|| j||dd |dkrbtjtj| j||dsbt }t	ddD ]l}tjd| dd
d| d| j||dd tj| j||d| d}	|
t|	d  t|	 qttj| j||dd}
|
| W 5 Q R X tj| j|||tj| j|||fS )ad  
        Class method to download ONNX model files.

        This method is responsible for downloading two ONNX model files from specified URLs and saving them locally. The downloaded files are saved with the naming convention 'name_encoder.onnx' and 'name_decoder.onnx', where 'name' is the value returned by the 'name' method.

        Parameters:
            cls: The class object.
            *args: Variable length argument list.
            **kwargs: Arbitrary keyword arguments.

        Returns:
            tuple: A tuple containing the file paths of the downloaded encoder and decoder models.
        Z	sam_modelZsam_vit_b_01ec64Z	sam_quantFz.encoder.onnxz.decoder.onnxz.encoder.quant.onnxz.decoder.quant.onnxz>https://github.com/danielgatis/rembg/releases/download/v0.0.0/NT)fnamepathZprogressbarzsam_vit_h_4b8939.encoder.onnxz!sam_vit_h_4b8939.encoder_data.binr      z\https://github.com/danielgatis/rembg/releases/download/v0.0.0/sam_vit_h_4b8939.encoder_data.z.binzsam_vit_h_4b8939.encoder_data.rbwb)rQ   poochretrieveZ
u2net_homeosr`   existsjoin	bytearrayr%   r4   openreadremovewrite)clsr;   r<   r0   ZquantZfname_encoderZfname_decodercontentiZfbinfpr   r   r   r6     sl    






 





zSamSession.download_modelsc                 O   s   dS )aE  
        Class method to return a string value.

        This method returns the string value 'sam'.

        Parameters:
            cls: The class object.
            *args: Variable length argument list.
            **kwargs: Arbitrary keyword arguments.

        Returns:
            str: The string value 'sam'.
        Zsamr   )rn   r;   r<   r   r   r   rU   R  s    zSamSession.name)N)__name__
__module____qualname____doc__r7   r3   ZSessionOptionsr?   PILImager   r^   classmethodr6   rU   r   r   r   r   r/   K   s    + 
Mr/   )rf   copyr   typingr   r'   numpyr   Zonnxruntimer3   rd   Z
jsonschemar   ZPILr   Z	PIL.Imagerv   baser   r   r   Zndarrayr   r"   r.   r/   r   r   r   r   <module>   s   	