o
    eCO                     @  s  d Z ddlmZ ddlZddlmZ ddlmZmZ ddl	Z
ddlZddlZddlmZ ddlmZmZ ddlmZ dd	lmZ dd
lmZmZ ddlmZmZ ddlmZ ddlmZm Z m!Z!m"Z"m#Z#m$Z$m%Z% ddl&m'Z' ed e(  e G dd de!e ee$e#e%eee'ZdS )zgr.Image() component.    )annotationsN)Path)AnyLiteral)utils)documentset_documentation_group)ImgSerializable)Image)processing_utilsr   )IOComponent	_Keywords)warn_style_method_deprecation)
Changeable	ClearableEditableEventListenerMethod
Selectable
Streamable
Uploadable)TokenInterpretable	componentc                   @  s   e Zd ZdZ	daddddddddddddddddddddddd	d
dddbd5d6Zd7d8 Zeejddddddddddddddfdcd:d;Z	ddd@dAZ
dedEdFZdfdIdJZdgdhdMdNZdOdP ZdQdR ZdSdT Z	dadidVdWZdddXdjdYdZZd[d\ Zdkd_d`ZdS )lr
   ab  
    Creates an image component that can be used to upload/draw images (as an input) or display images (as an output).
    Preprocessing: passes the uploaded image as a {numpy.array}, {PIL.Image} or {str} filepath depending on `type` -- unless `tool` is `sketch` AND source is one of `upload` or `webcam`. In these cases, a {dict} with keys `image` and `mask` is passed, and the format of the corresponding values depends on `type`.
    Postprocessing: expects a {numpy.array}, {PIL.Image} or {str} or {pathlib.Path} filepath to an image and displays the image.
    Examples-format: a {str} local filepath or URL to an image.
    Demos: image_mod, image_mod_default_image
    Guides: image-classification-in-pytorch, image-classification-in-tensorflow, image-classification-with-vision-transformers, building-a-pictionary_app, create-your-own-friends-with-a-gan
    NRGBFuploadnumpyT   z#000000gffffff?)shapeheightwidth
image_modeinvert_colorssourcetooltypelabelevery
show_labelshow_download_button	containerscale	min_widthinteractivevisible	streamingelem_idelem_classesmirror_webcambrush_radiusbrush_colormask_opacityshow_share_buttonvalue&str | _Image.Image | np.ndarray | Noner   tuple[int, int] | Noner   
int | Noner   r   NLiteral['1', 'L', 'P', 'RGB', 'RGBA', 'CMYK', 'YCbCr', 'LAB', 'HSV', 'I', 'F']r    boolr!   %Literal['upload', 'webcam', 'canvas']r"   <Literal['editor', 'select', 'sketch', 'color-sketch'] | Noner#   #Literal['numpy', 'pil', 'filepath']r$   
str | Noner%   float | Noner&   bool | Noner'   r(   r)   r*   intr+   r,   r-   r.   r/   list[str] | str | Noner0   r1   r2   strr3   floatr4   c                K  s$  || _ || _|| _|| _g d}|	|vrtd|	 d| |	| _|| _|| _|| _|| _	g d}||vr?td| d| || _
|du rP|dkrLdnd	| _n|| _|| _|| _|| _|rf|d
krftd|  	 |du rst dun|| _tj| f|
||||||||||d| t|  dS )aN  
        Parameters:
            value: A PIL Image, numpy array, path or URL for the default value that Image component is going to take. If callable, the function will be called whenever the app loads to set the initial value of the component.
            shape: (width, height) shape to crop and resize image when passed to function. If None, matches input image size. Pass None for either width or height to only crop and resize the other.
            height: Height of the displayed image in pixels.
            width: Width of the displayed image in pixels.
            image_mode: "RGB" if color, or "L" if black and white. See https://pillow.readthedocs.io/en/stable/handbook/concepts.html for other supported image modes and their meaning.
            invert_colors: whether to invert the image as a preprocessing step.
            source: Source of image. "upload" creates a box where user can drop an image file, "webcam" allows user to take snapshot from their webcam, "canvas" defaults to a white image that can be edited and drawn upon with tools.
            tool: Tools used for editing. "editor" allows a full screen editor (and is the default if source is "upload" or "webcam"), "select" provides a cropping and zoom tool, "sketch" allows you to create a binary sketch (and is the default if source="canvas"), and "color-sketch" allows you to created a sketch in different colors. "color-sketch" can be used with source="upload" or "webcam" to allow sketching on an image. "sketch" can also be used with "upload" or "webcam" to create a mask over an image and in that case both the image and mask are passed into the function as a dictionary with keys "image" and "mask" respectively.
            type: The format the image is converted to before being passed into the prediction function. "numpy" converts the image to a numpy array with shape (height, width, 3) and values from 0 to 255, "pil" converts the image to a PIL image object, "filepath" passes a str path to a temporary file containing the image.
            label: component name in interface.
            every: If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute.
            show_label: if True, will display label.
            show_download_button: If True, will display button to download image.
            container: If True, will place the component in a container - providing some extra padding around the border.
            scale: relative width compared to adjacent Components in a Row. For example, if Component A has scale=2, and Component B has scale=1, A will be twice as wide as B. Should be an integer.
            min_width: minimum pixel width, will wrap if not sufficient screen space to satisfy this value. If a certain scale value results in this Component being narrower than min_width, the min_width parameter will be respected first.
            interactive: if True, will allow users to upload and edit an image; if False, can only be used to display images. If not provided, this is inferred based on whether the component is used as an input or output.
            visible: If False, component will be hidden.
            streaming: If True when used in a `live` interface, will automatically stream webcam feed. Only valid is source is 'webcam'.
            elem_id: An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles.
            elem_classes: An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles.
            mirror_webcam: If True webcam will be mirrored. Default is True.
            brush_radius: Size of the brush for Sketch. Default is None which chooses a sensible default
            brush_color: Color of the brush for Sketch as hex string. Default is "#000000".
            mask_opacity: Opacity of mask drawn on image, as a value between 0 and 1.
            show_share_button: If True, will show a share icon in the corner of the component that allows user to share outputs to Hugging Face Spaces Discussions. If False, icon does not appear. If set to None (default behavior), then the icon appears if this Gradio app is launched on Spaces, but not otherwise.
        )r   pilfilepathz$Invalid value for parameter `type`: z. Please choose from one of: )r   webcamcanvasz&Invalid value for parameter `source`: NrH   sketchZeditorrG   5Image streaming only available if source is 'webcam'.)r$   r%   r&   r(   r)   r*   r+   r,   r.   r/   r5   )r1   r2   r3   r0   
ValueErrorr#   r   r   r   r   r!   r"   r    r-   r'   r   Z	get_spacer4   r   __init__r   )selfr5   r   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   r0   r1   r2   r3   r4   kwargsZvalid_typesZvalid_sources rO   GD:\Projects\ConvertPro\env\Lib\site-packages\gradio/components/image.pyrL   8   sh   >zImage.__init__c                 C  sL   | j | j| j| j| j| j| j| j| j| j	| j
| j| j| j| jdt| S )N)r   r   r   r   r!   r"   r5   r-   r0   r1   r2   r3   
selectabler4   r'   )r   r   r   r   r!   r"   r5   r-   r0   r1   r2   r3   rQ   r4   r'   r   
get_configrM   rO   rO   rP   rR      s$   zImage.get_config(Any | Literal[_Keywords.NO_VALUE] | Nonec                 C  sd   i d|d|d|d|d|d|d|d|d	|	d
|
d| d|d|d|d|ddS )Nr   r   r$   r&   r'   r(   r)   r*   r+   r,   r5   r1   r2   r3   r4   Z__type__updaterO   )r5   r   r   r$   r&   r'   r(   r)   r*   r+   r,   r1   r2   r3   r4   rO   rO   rP   rU      sB   	
zImage.updateim_Image.Image | Nonereturn&np.ndarray | _Image.Image | str | Nonec                 C  sz   |du r|S |j }| jdkr|S | jdkrt|S | jdkr2| j|| j|p'dd}| j| |S tdt	| j d )	z3Helper method to format an image based on self.typeNrE   r   rF   Zpng)dirformatzUnknown type: z1. Please choose from: 'numpy', 'pil', 'filepath'.)
r[   r#   nparrayZpil_to_temp_fileZDEFAULT_TEMP_DIRZ
temp_filesaddrK   rC   )rM   rV   fmtpathrO   rO   rP   _format_image   s(   



zImage._format_imagexstr | dict[str, str]-np.ndarray | _Image.Image | str | dict | Nonec                 C  sX  |du r|S d}| j dkr"| jdv r"t|tsJ |d |d }}t|ts)J t|}t  t	d |
| j}W d   n1 sHw   Y  | jdurYt|| j}| jrbtj|}| jdkrw| jd	u rw| j d
krwtj|}| j dkr| jdv rt|}|jdkr|d
d}td|||g}| || |dS | |S )z
        Parameters:
            x: base64 url data, or (if tool == "sketch") a dict of image and mask base64 url data
        Returns:
            image in requested format, or (if tool == "sketch") a dict of image and mask in requested format
        N rI   )r   rG   imagemaskignorerG   Tzcolor-sketchZRGBAALr   )rf   rg   )r"   r!   
isinstancedictrC   r   decode_base64_to_imagewarningscatch_warningssimplefilterconvertr   r   resize_and_cropr    PILZImageOpsinvertr0   ZmirrormodeZ
getchannel_Imagemergera   )rM   rb   rg   rV   Zmask_imZ
alpha_datarO   rO   rP   
preprocess   s:   	









zImage.preprocessy-np.ndarray | _Image.Image | str | Path | Nonec                 C  sX   |du rdS t |tjrt|S t |tjrt|S t |tt	fr(t
|S td)z
        Parameters:
            y: image as a numpy array, PIL Image, string/Path filepath, or string URL
        Returns:
            base64 url data
        Nz%Cannot process this value as an Image)rk   r\   Zndarrayr   encode_array_to_base64rv   r
   Zencode_pil_to_base64rC   r   client_utilsZencode_url_or_file_to_base64rK   )rM   ry   rO   rO   rP   postprocess.  s   	


zImage.postprocess   segmentsc                 C  s
   || _ | S )ai  
        Calculates interpretation score of image subsections by splitting the image into subsections, then using a "leave one out" method to calculate the score of each subsection by whiting out the subsection and measuring the delta of the output value.
        Parameters:
            segments: Number of interpretation segments to split image into.
        )interpretation_segments)rM   r   rO   rO   rP   set_interpret_parametersB  s   zImage.set_interpret_parametersc              
   C  s   t |}| jdurt || j}t|}zddlm} W n tt	fy1 } zt
d|d}~ww z||| jdddd}W ||fS  tyV   ||| jddd}Y ||fS w )	z
        Helper method that segments an image into superpixels using slic.
        Parameters:
            x: base64 representation of an image
        Nr   )slicz]Error: running this interpretation for images requires scikit-image, please install it first.
      )compactnesssigmaZstart_label)r   r   )r   rm   r   rr   r\   r]   Zskimage.segmentationr   ImportErrorModuleNotFoundErrorrK   r   	TypeError)rM   rb   resized_and_cropped_imager   errsegments_slicrO   rO   rP   _segment_by_slicK  s@   


zImage._segment_by_slicc                 C  s   |  |\}}g g g }}}tj|dd}t|D ].}||k}	t|}
||
||k< |t|
 t|}d|||k< || ||	 q|||fS )a  
        Segments image into tokens, masks, and leave-one-out-tokens
        Parameters:
            x: base64 representation of an image
        Returns:
            tokens: list of tokens, used by the get_masked_input() method
            leave_one_out_tokens: list of left-out tokens, used by the get_interpretation_neighbors() method
            masks: list of masks, used by the get_interpretation_neighbors() method
        )r   r   )Zaxisr   )r   r\   meanuniquecopyappendr   r{   )rM   rb   r   r   tokensmasksZleave_one_out_tokensZreplace_colorZsegment_valuerg   Zimage_screentokenrO   rO   rP   tokenizel  s   




zImage.tokenizec                 C  sX   g }|D ]%}t j|d td}t||D ]\}}||t|  }q|t| q|S )Nr   )Zdtype)r\   Z
zeros_likerA   zipr   r   r{   )rM   r   Zbinary_mask_matrixZmasked_inputsZbinary_mask_vectorZmasked_inputr   brO   rO   rP   get_masked_inputs  s   zImage.get_masked_inputslist[list[float]]c                 K  s   t |}| jdurt || j}t|}t|jd |jd f}t||D ]
\}}	|||	 7 }q(t|t	|}
}|
dkrJ|| |
|  }|
 S )zs
        Returns:
            A 2D array representing the interpretation score of each pixel of the image.
        Nr   r   )r   rm   r   rr   r\   r]   Zzerosr   maxmintolist)rM   rb   Z	neighborsZscoresr   r   rN   Zoutput_scoresZscorerg   Zmax_valZmin_valrO   rO   rP   get_interpretation_scores  s   


zImage.get_interpretation_scores)r   r   c                K  s&   t   |dur
|| _|dur|| _| S )zc
        This method is deprecated. Please set these arguments in the constructor instead.
        N)r   r   r   )rM   r   r   rN   rO   rO   rP   style  s   zImage.stylec                 C  s   | j dkr	tdd S )NrG   rJ   )r!   rK   rS   rO   rO   rP   check_streamable  s   
zImage.check_streamable
input_datastr | Path | Nonec                 C  s6   |d u rdS t |}| jst|r|S t t|S )Nre   )rC   Zroot_urlr|   Zis_http_url_liker   abspath)rM   r   rO   rO   rP   
as_example  s   zImage.as_example)N)4r5   r6   r   r7   r   r8   r   r8   r   r9   r    r:   r!   r;   r"   r<   r#   r=   r$   r>   r%   r?   r&   r@   r'   r:   r(   r:   r)   r8   r*   rA   r+   r@   r,   r:   r-   r:   r.   r>   r/   rB   r0   r:   r1   r?   r2   rC   r3   rD   r4   r@   )r5   rT   r   r8   r   r8   r$   r>   r&   r@   r'   r@   r(   r@   r)   r8   r*   r8   r+   r@   r,   r@   r1   r?   r2   r>   r3   r?   r4   r@   )rV   rW   rX   rY   )rb   rc   rX   rd   )ry   rz   rX   r>   )r~   )r   rA   )rX   r   )r   r8   r   r8   )r   r   rX   rC   )__name__
__module____qualname____doc__rL   rR   staticmethodr   ZNO_VALUErU   ra   rx   r}   r   r   r   r   r   r   r   r   rO   rO   rO   rP   r
   #   sx    w
$

.	!
r
   ))r   
__future__r   rn   pathlibr   typingr   r   r   r\   rs   ZPIL.ImageOpsZgradio_clientr   r|   Zgradio_client.documentationr   r   Zgradio_client.serializingr	   r
   rv   Zgradior   Zgradio.components.baser   r   Zgradio.deprecationr   Zgradio.eventsr   r   r   r   r   r   r   Zgradio.interpretationr   initrO   rO   rO   rP   <module>   s>    $	

