§
    /Áôg¢+  ã                   óú  — d dl Z d dlZd dlmZ d dlmZmZmZmZm	Z	m
Z
 d dlZd dlZd dlmZmZmZmZmZmZ d dlmZmZ d dlmZ d dlmZ d dlmZ d d	lm Z  d d
l!m"Z" ddl#m$Z$ ddl%m%Z%m&Z& ddl'm(Z(  ej)        d¦  «          eed¦  «        Z* G d„ de¦  «        Z+dedede,de,de,defd„Z-dededefd„Z.dededefd„Z/dee         defd„Z0dededefd „Z1dej2        dej2        fd!„Z3ded"ee,e,e,e,f         defd#„Z4dedefd$„Z5d%e6e7d&f         ddfd'„Z8	 	 	 	 	 	 	 	 	 d8d+e	e9eej2        f         d,e:d-e,d.e,d/e,d0ee(         d1e:d2e:d3eee,e,e,e,f                  d4e:d5ee         d6ee         de	e9eej2        f         fd7„Z;dS )9é    N)ÚEnum)ÚAnyÚListÚOptionalÚTupleÚUnionÚcast)ÚBORDER_DEFAULTÚMORPH_ELLIPSEÚ
MORPH_OPENÚGaussianBlurÚgetStructuringElementÚmorphologyEx)ÚImageÚImageOps)r   )Úestimate_alpha_cf)Úestimate_foreground_ml)Ústack_images)Úbinary_erosioné   )Únew_session)ÚsessionsÚsessions_names)ÚBaseSessioné   )r   r   c                   ó   — e Zd ZdZdZdZdS )Ú
ReturnTyper   r   é   N)Ú__name__Ú
__module__Ú__qualname__ÚBYTESÚPILLOWÚNDARRAY© ó    úQ/var/www/html/bac/bac_backend/python/env/lib/python3.11/site-packages/rembg/bg.pyr   r       s   € € € € € Ø€EØ€FØ€G€G€Gr&   r   ÚimgÚmaskÚforeground_thresholdÚbackground_thresholdÚerode_structure_sizeÚreturnc                 óÆ  — | j         dk    s| j         dk    r|                      d¦  «        } t          j        | ¦  «        }t          j        |¦  «        }||k    }||k     }d}	|dk    r"t          j        ||ft          j        ¬¦  «        }	t          ||	¬¦  «        }t          ||	d¬	¦  «        }t          j        |j        t          j        d
¬¦  «        }
d|
|<   d|
|<   |dz  }|
dz  }t          ||¦  «        }t          ||¦  «        }t          ||¦  «        }t          j        |dz  dd¦  «                             t          j        ¦  «        }t          j        |¦  «        }|S )a  
    Perform alpha matting on an image using a given mask and threshold values.

    This function takes a PIL image `img` and a PIL image `mask` as input, along with
    the `foreground_threshold` and `background_threshold` values used to determine
    foreground and background pixels. The `erode_structure_size` parameter specifies
    the size of the erosion structure to be applied to the mask.

    The function returns a PIL image representing the cutout of the foreground object
    from the original image.
    ÚRGBAÚCMYKÚRGBNr   )Údtype)Ú	structurer   )r3   Úborder_valueé€   )r2   Ú
fill_valueéÿ   g     ào@)ÚmodeÚconvertÚnpÚasarrayÚonesÚuint8r   ÚfullÚshaper   r   r   ÚclipÚastyper   Ú	fromarray)r(   r)   r*   r+   r,   Ú	img_arrayÚ
mask_arrayÚis_foregroundÚis_backgroundr3   ÚtrimapÚimg_normalizedÚtrimap_normalizedÚalphaÚ
foregroundÚcutouts                   r'   Úalpha_matting_cutoutrM   &   sh  € ð$ „x�6ÒÐ˜SœX¨Ò/Ð/Ø�kŠk˜%Ñ Ô ˆå”
˜3‘”€IÝ”˜DÑ!Ô!€JàÐ!5Ò5€MØÐ!5Ò5€Mà€IØ˜aÒÐÝ”GØ!Ð#7Ð8ÅÄð
ñ 
ô 
ˆ	õ # =¸IÐFÑFÔF€MÝ" =¸IÐTUÐVÑVÔV€MåŒW�ZÔ%­R¬XÀ#ÐFÑFÔF€FØ€Fˆ=ÑØ€Fˆ=Ñà Ñ&€NØ ™Ðå˜nÐ.?Ñ@Ô@€EÝ'¨¸Ñ>Ô>€JÝ˜* eÑ,Ô,€FåŒW�V˜c‘\ 1 cÑ*Ô*×1Ò1µ"´(Ñ;Ô;€FÝŒ_˜VÑ$Ô$€Fà€Mr&   c                 óh   — t          j        d| j        d¦  «        }t          j        | ||¦  «        }|S )ac  
    Perform a simple cutout operation on an image using a mask.

    This function takes a PIL image `img` and a PIL image `mask` as input.
    It uses the mask to create a new image where the pixels from `img` are
    cut out based on the mask.

    The function returns a PIL image representing the cutout of the original
    image using the mask.
    r/   r   )r   ÚnewÚsizeÚ	composite)r(   r)   ÚemptyrL   s       r'   Únaive_cutoutrS   [   s1   € õ ŒI�f˜sœx¨!Ñ,Ô,€EÝŒ_˜S %¨Ñ.Ô.€FØ€Mr&   c                 ó0   — |                       |¦  «         | S )a  
    Apply the specified mask to the image as an alpha cutout.

    Args:
        img (PILImage): The image to be modified.
        mask (PILImage): The mask to be applied.

    Returns:
        PILImage: The modified image with the alpha cutout applied.
    )Úputalpha)r(   r)   s     r'   Úputalpha_cutoutrV   k   s   € ð ‡L‚L�ÑÔÐØ€Jr&   Úimgsc                 óZ   — |                       d¦  «        }| D ]}t          ||¦  «        }Œ|S )zº
    Concatenate multiple images vertically.

    Args:
        imgs (List[PILImage]): The list of images to be concatenated.

    Returns:
        PILImage: The concatenated image.
    r   )ÚpopÚget_concat_v)rW   ÚpivotÚims      r'   Úget_concat_v_multir]   z   s8   € ð �HŠH�Q‰KŒK€EØð (ð (ˆÝ˜U BÑ'Ô'ˆˆØ€Lr&   Úimg1Úimg2c                 ó¾   — t          j        d| j        | j        |j        z   f¦  «        }|                     | d¦  «         |                     |d| j        f¦  «         |S )zí
    Concatenate two images vertically.

    Args:
        img1 (PILImage): The first image.
        img2 (PILImage): The second image to be concatenated below the first image.

    Returns:
        PILImage: The concatenated image.
    r/   )r   r   r   )r   rO   ÚwidthÚheightÚpaste)r^   r_   Údsts      r'   rZ   rZ   Š   sY   € õ Œ)�F˜TœZ¨¬°t´{Ñ)BÐCÑ
DÔ
D€CØ‡I‚Iˆd�FÑÔÐØ‡I‚Iˆd�Q˜œÐ$Ñ%Ô%Ð%Ø€Jr&   c                 óÜ   — t          | t          t          ¦  «        } t          | dddt          ¬¦  «        } t          j        | dk     dd¦  «                             t
          j        ¦  «        } | S )zå
    Post Process the mask for a smooth boundary by applying Morphological Operations
    Research based on paper: https://www.sciencedirect.com/science/article/pii/S2352914821000757
    args:
        mask: Binary Numpy Mask
    )é   rf   r   )ÚsigmaXÚsigmaYÚ
borderTypeé   r   r7   )	r   r   Úkernelr   r
   r:   ÚwhererA   r=   )r)   s    r'   Úpost_processrm   ›   sY   € õ ˜�j­&Ñ1Ô1€DÝ˜˜f¨Q°qÅ^ÐTÑTÔT€DÝŒ8�D˜3’J  3Ñ'Ô'×.Ò.­r¬xÑ8Ô8€DØ€Kr&   Úcolorc                 ó€   — t          j        d| j        t          |¦  «        ¦  «        }t          j        || ¦  «        }|S )a  
    Apply the specified background color to the image.

    Args:
        img (PILImage): The image to be modified.
        color (Tuple[int, int, int, int]): The RGBA color to be applied.

    Returns:
        PILImage: The modified image with the background color applied.
    r/   )r   rO   rP   ÚtupleÚalpha_composite)r(   rn   Ú
backgroundÚcolored_images       r'   Úapply_background_colorrt   ¨   s7   € õ ”˜6 3¤8­U°5©\¬\Ñ:Ô:€JÝÔ)¨*°cÑ:Ô:€MàÐr&   c                 óP   — t          t          t          j        | ¦  «        ¦  «        S )z­
    Fix the orientation of the image based on its EXIF data.

    Args:
        img (PILImage): The image to be fixed.

    Returns:
        PILImage: The fixed image.
    )r	   ÚPILImager   Úexif_transpose)r(   s    r'   Úfix_image_orientationrx   ¹   s   € õ •�(Ô1°#Ñ6Ô6Ñ7Ô7Ð7r&   Úmodels.c                 óB  — t          | ¦  «        dk    r#t          d¦  «         t          t          ¦  «        } | D ]e}t	          j        |¦  «        }|€'t          d|› �¦  «         t          j        d¦  «         Œ?t          d|› �¦  «         |                     ¦   «          ŒfdS )z/
    Download models for image processing.
    r   z+No models specified, downloading all modelsNzError: no model found: r   zDownloading model: )	ÚlenÚprintrp   r   r   ÚgetÚsysÚexitÚdownload_models)ry   ÚmodelÚsessions      r'   r€   r€   Æ   s°   € õ ˆ6�{„{�aÒÐÝÐ;Ñ<Ô<Ð<Ý•~Ñ&Ô&ˆàð &ð &ˆÝ”,˜uÑ%Ô%ˆØˆ?ÝÐ3¨EÐ3Ð3Ñ4Ô4Ð4ÝŒH�Q‰KŒKˆKˆKåÐ/¨Ð/Ð/Ñ0Ô0Ð0Ø×#Ò#Ñ%Ô%Ð%Ð%ð&ð &r&   Féð   é
   ÚdataÚalpha_mattingÚ"alpha_matting_foreground_thresholdÚ"alpha_matting_background_thresholdÚalpha_matting_erode_sizer‚   Ú	only_maskÚpost_process_maskÚbgcolorÚforce_return_bytesÚargsÚkwargsc
                 óà  — t          | t          ¦  «        s|	rYt          j        }t	          t
          t          j        t          j	        t	          t          | ¦  «        ¦  «        ¦  «        ¦  «        }n´t          | t
          ¦  «        r"t          j
        }t	          t
          | ¦  «        }n}t          | t          j        ¦  «        r4t          j        }t	          t
          t          j        | ¦  «        ¦  «        }n/t          d                     t#          | ¦  «        ¦  «        ¦  «        ‚|                     dd¦  «        }t'          |¦  «        }|€t)          dg|
¢R i |¤Ž} |j        |g|
¢R i |¤Ž}g }|D ]¾}|r3t          j        t-          t          j        |¦  «        ¦  «        ¦  «        }|r|}nm|rH	 t1          |||||¦  «        }nV# t          $ r& |rt3          ||¦  «        }nt5          ||¦  «        }Y n'w xY w|rt3          ||¦  «        }nt5          ||¦  «        }|                     |¦  «         Œ¿|}t9          |¦  «        dk    rt;          |¦  «        }|�|st=          ||¦  «        }t          j
        |k    r|S t          j        |k    rt          j        |¦  «        S t          j	        ¦   «         }|                      |d¦  «         | !                    d¦  «         | "                    ¦   «         S )aŸ  
    Remove the background from an input image.

    This function takes in various parameters and returns a modified version of the input image with the background removed. The function can handle input data in the form of bytes, a PIL image, or a numpy array. The function first checks the type of the input data and converts it to a PIL image if necessary. It then fixes the orientation of the image and proceeds to perform background removal using the 'u2net' model. The result is a list of binary masks representing the foreground objects in the image. These masks are post-processed and combined to create a final cutout image. If a background color is provided, it is applied to the cutout image. The function returns the resulting cutout image in the format specified by the input 'return_type' parameter or as python bytes if force_return_bytes is true.

    Parameters:
        data (Union[bytes, PILImage, np.ndarray]): The input image data.
        alpha_matting (bool, optional): Flag indicating whether to use alpha matting. Defaults to False.
        alpha_matting_foreground_threshold (int, optional): Foreground threshold for alpha matting. Defaults to 240.
        alpha_matting_background_threshold (int, optional): Background threshold for alpha matting. Defaults to 10.
        alpha_matting_erode_size (int, optional): Erosion size for alpha matting. Defaults to 10.
        session (Optional[BaseSession], optional): A session object for the 'u2net' model. Defaults to None.
        only_mask (bool, optional): Flag indicating whether to return only the binary masks. Defaults to False.
        post_process_mask (bool, optional): Flag indicating whether to post-process the masks. Defaults to False.
        bgcolor (Optional[Tuple[int, int, int, int]], optional): Background color for the cutout image. Defaults to None.
        force_return_bytes (bool, optional): Flag indicating whether to return the cutout image as bytes. Defaults to False.
        *args (Optional[Any]): Additional positional arguments.
        **kwargs (Optional[Any]): Additional keyword arguments.

    Returns:
        Union[bytes, PILImage, np.ndarray]: The cutout image with the background removed.
    z^Input type {} is not supported. Try using force_return_bytes=True to force python bytes outputrU   FNÚu2netr   ÚPNG)#Ú
isinstanceÚbytesr   r"   r	   rv   r   ÚopenÚioÚBytesIOr#   r:   Úndarrayr$   rB   Ú
ValueErrorÚformatÚtyperY   rx   r   Úpredictrm   ÚarrayrM   rV   rS   Úappendr{   r]   rt   r;   ÚsaveÚseekÚread)r…   r†   r‡   rˆ   r‰   r‚   rŠ   r‹   rŒ   r�   rŽ   r�   Úreturn_typer(   rU   ÚmasksÚcutoutsr)   rL   Úbios                       r'   Úremover¦   Ø   sõ  € õH �$�ÑÔð 
Ð"4ð 
Ý Ô&ˆÝ•8�UœZ­¬
µ4½¸tÑ3DÔ3DÑ(EÔ(EÑFÔFÑGÔGˆˆÝ	�D�(Ñ	#Ô	#ð 
Ý Ô'ˆÝ•8˜TÑ"Ô"ˆˆÝ	�D�"œ*Ñ	%Ô	%ð 
Ý Ô(ˆÝ•8�Uœ_¨TÑ2Ô2Ñ3Ô3ˆˆåØl×sÒsÝ�T‘
”
ñô ñ
ô 
ð 	
ð �zŠz˜* eÑ,Ô,€Hõ   Ñ
$Ô
$€Cà€Ý˜gÐ7¨Ð7Ð7Ð7°Ð7Ð7ˆàˆGŒO˜CÐ1 $Ð1Ð1Ð1¨&Ð1Ð1€EØ€Gàð ð ˆØð 	AÝ”?¥<µ´¸±´Ñ#?Ô#?Ñ@Ô@ˆDàð 	1ØˆFˆFàð 	1ð5Ý-ØØØ6Ø6Ø,ñô ��øõ ð 5ð 5ð 5Øð 5Ý,¨S°$Ñ7Ô7�F�Få)¨#¨tÑ4Ô4�Føøð	5øøøð ð 1Ý(¨¨dÑ3Ô3��å% c¨4Ñ0Ô0�à�Š�vÑÔÐÐà€FÝ
ˆ7�|„|�aÒÐÝ# GÑ,Ô,ˆàÐ 9ÐÝ'¨°Ñ8Ô8ˆåÔ˜KÒ'Ð'ØˆåÔ˜[Ò(Ð(ÝŒz˜&Ñ!Ô!Ð!å
Œ*‰,Œ,€CØ
‡K‚K��UÑÔÐØ‡H‚HˆQ�K„K€Kà�8Š8‰:Œ:Ðs   Æ0GÇ-G4Ç3G4)	Frƒ   r„   r„   NFFNF)<r–   r~   Úenumr   Útypingr   r   r   r   r   r	   Únumpyr:   ÚonnxruntimeÚortÚcv2r
   r   r   r   r   r   ÚPILr   r   Ú	PIL.Imagerv   Ú!pymatting.alpha.estimate_alpha_cfr   Ú+pymatting.foreground.estimate_foreground_mlr   Úpymatting.util.utilr   Úscipy.ndimager   Úsession_factoryr   r   r   Úsessions.baser   Úset_default_logger_severityrk   r   ÚintrM   rS   rV   r]   rZ   r˜   rm   rt   rx   rp   Ústrr€   r”   Úboolr¦   r%   r&   r'   ú<module>r¹      se  ðØ 	€	€	€	Ø 
€
€
€
Ø Ð Ð Ð Ð Ð Ø :Ð :Ð :Ð :Ð :Ð :Ð :Ð :Ð :Ð :Ð :Ð :Ð :Ð :Ð :Ð :à Ð Ð Ð Ø Ð Ð Ð ðð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð  Ð Ð Ð Ð Ð Ð Ð Ø 'Ð 'Ð 'Ð 'Ð 'Ð 'Ø ?Ð ?Ð ?Ð ?Ð ?Ð ?Ø NÐ NÐ NÐ NÐ NÐ NØ ,Ð ,Ð ,Ð ,Ð ,Ð ,Ø (Ð (Ð (Ð (Ð (Ð (à (Ð (Ð (Ð (Ð (Ð (Ø .Ð .Ð .Ð .Ð .Ð .Ð .Ð .Ø &Ð &Ð &Ð &Ð &Ð &à €Ô  Ñ "Ô "Ð "à	Ð	˜}¨fÑ	5Ô	5€ðð ð ð ð �ñ ô ð ð2Ø	ð2à
ð2ð ð2ð ð	2ð
 ð2ð ð2ð 2ð 2ð 2ðj�hð  hð °8ð ð ð ð ð ˜ð ¨ð °hð ð ð ð ð˜T (œ^ð °ð ð ð ð ð �xð  xð °Hð ð ð ð ð"
�r”zð 
 b¤jð 
ð 
ð 
ð 
ð ð °°s¸CÀÀcÐ7IÔ1Jð Èxð ð ð ð ð"
8˜xð 
8¨Hð 
8ð 
8ð 
8ð 
8ð&˜E # s (œOð &°ð &ð &ð &ð &ð(  Ø.1Ø.0Ø$&Ø%)ØØ#Ø37Ø$ðmð mØ
��x ¤Ð+Ô
,ðmàðmð ),ðmð ),ð	mð
 "ðmð �kÔ"ðmð ðmð ðmð �e˜C  c¨3Ð.Ô/Ô0ðmð ðmð �CŒ=ðmð �sŒmðmð ˆ5�(˜BœJÐ&Ô'ðmð mð mð mð mð mr&   