
    ;3hb                       d Z ddlmZ ddlZddl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mZmZmZm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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) erddl*m+Z+ eejX                  ejZ                  jZ                  e.f   Z/ G d de      Z0 G d de      Z1 G d de%      Z2 G d de%      Z3 G d de      Z4 G d de%      Z5 e       ejl                   G d d                    Z7 e       ejl                   G d d e7                    Z8 e       ejl                   G d! d"                    Z9 e       ejl                   G d# d$                    Z: e        G d% d&e!             Z;y)'zgr.ImageEditor() component.    )annotationsN)IterableSequence)BytesIO)Path)TYPE_CHECKINGAnyLiteralOptionalUnioncasthandle_file)document)	TypedDict)image_utilsutils)	Componentserver)FileDataGradioModel)Events)I18nData)Timerc                  ,    e Zd ZU ded<   ded<   ded<   y)EditorValuezOptional[ImageType]
backgroundzlist[ImageType]layers	compositeN__name__
__module____qualname____annotations__     ^/var/www/html/audio-gradio/venv/lib/python3.12/site-packages/gradio/components/image_editor.pyr   r   %   s    ##""r&   r   c                  ,    e Zd ZU ded<   ded<   ded<   y)EditorExampleValueOptional[str]r   z Optional[list[Union[str, None]]]r   r   Nr    r%   r&   r'   r)   r)   +   s    ,,r&   r)   c                  F    e Zd ZU dZded<   g Zded<   dZded<   dZded<   y)	
EditorDataNzOptional[FileData]r   zlist[FileData]r   r   r*   id)r!   r"   r#   r   r$   r   r   r-   r%   r&   r'   r,   r,   1   s,    %)J")FN$(I!(Br&   r,   c                  ,    e Zd ZU ded<   ded<   ded<   y)EditorDataBlobszOptional[bytes]r   zlist[Union[bytes, None]]r   r   Nr    r%   r&   r'   r/   r/   8   s    $$r&   r/   c                  6    e Zd ZU ded<   ded<   ded<   ded<   y)	BlobDatastrtypezOptional[int]indexbytesfiler-   Nr    r%   r&   r'   r1   r1   >   s    
I
KGr&   r1   c                  "    e Zd ZU ded<   ded<   y)AcceptBlobsr1   datazlist[tuple[str, bytes]]filesNr    r%   r&   r'   r8   r8   E   s    
N""r&   r8   c                       e Zd ZU dZdZded<   y)Erasera  
    A dataclass for specifying options for the eraser tool in the ImageEditor component. An instance of this class can be passed to the `eraser` parameter of `gr.ImageEditor`.
    Parameters:
        default_size: The default radius, in pixels, of the eraser tool. Defaults to "auto" in which case the radius is automatically determined based on the size of the image (generally 1/50th of smaller dimension).
    autozint | Literal['auto']default_sizeN)r!   r"   r#   __doc__r>   r$   r%   r&   r'   r<   r<   J   s     +1L'0r&   r<   c                  B    e Zd ZU dZdZded<   dZded<   dZded	<   d
 Zy)Brusha^  
    A dataclass for specifying options for the brush tool in the ImageEditor component. An instance of this class can be passed to the `brush` parameter of `gr.ImageEditor`.
    Parameters:
        default_size: The default radius, in pixels, of the brush tool. Defaults to "auto" in which case the radius is automatically determined based on the size of the image (generally 1/50th of smaller dimension).
        colors: A list of colors to make available to the user when using the brush. Defaults to a list of 5 colors.
        default_color: The default color of the brush. Defaults to the first color in the `colors` list.
        color_mode: If set to "fixed", user can only select from among the colors in `colors`. If "defaults", the colors in `colors` are provided as a default palette, but the user can also select any color using a color picker.
    Nz>list[str | tuple[str, float]] | str | tuple[str, float] | Nonecolorszstr | tuple[str, float] | Nonedefault_colordefaultszLiteral['fixed', 'defaults']
color_modec                    | j                   	g d| _         | j                  ;t        | j                   t              r| j                   d   n| j                   | _        y y )N)zrgb(204, 50, 50)zrgb(173, 204, 50)zrgb(50, 204, 112)zrgb(50, 112, 204)zrgb(173, 50, 204)r   )rB   rC   
isinstancelistselfs    r'   __post_init__zBrush.__post_init__f   sN    ;;DK %",T[[$"?AT[[  &r&   )	r!   r"   r#   r?   rB   r$   rC   rE   rK   r%   r&   r'   rA   rA   V   s1     NRFJQ48M18/9J,9r&   rA   c                  B    e Zd ZU dZdZded<   dZded<   dZded	<   d
 Zy)LayerOptionsa  
    A dataclass for specifying options for the layer tool in the ImageEditor component. An instance of this class can be passed to the `layers` parameter of `gr.ImageEditor`.
    Parameters:
        allow_additional_layers: If True, users can add additional layers to the image. If False, the add layer button will not be shown.
        layers: A list of layers to make available to the user when using the layer tool. One layer must be provided, if the length of the list is 0 then a layer will be generated automatically.
    Tboolallow_additional_layersNzlist[str] | Noner   Fdisabledc                ^    | j                   t        | j                         dk(  r	dg| _         y y )Nr   zLayer 1)r   lenrI   s    r'   rK   zLayerOptions.__post_init__   s*    ;;#dkk"2a"7$+DK #8r&   )	r!   r"   r#   r?   rO   r$   r   rP   rK   r%   r&   r'   rM   rM   u   s.     %)T(#F#Hd&r&   rM   c                  .    e Zd ZU dZdZded<   dZded<   y)WebcamOptionsaD  
    A dataclass for specifying options for the webcam tool in the ImageEditor component. An instance of this class can be passed to the `webcam_options` parameter of `gr.ImageEditor`.
    Parameters:
        mirror: If True, the webcam will be mirrored.
        constraints: A dictionary of constraints for the webcam.
    TrN   mirrorNzdict[str, Any] | Noneconstraints)r!   r"   r#   r?   rU   r$   rV   r%   r&   r'   rT   rT      s     FD)-K&-r&   rT   c            $          e Zd ZdZej
                  ej                  ej                  ej                  ej                  ej                  gZeZ	 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	dd
dddddd	ddd"	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d fdZ	 	 	 	 ddZddZddZddZddZedd       Z xZS )ImageEditora  
    Creates an image component that, as an input, can be used to upload and edit images using simple editing tools such
    as brushes, strokes, cropping, and layers. Or, as an output, this component can be used to display images.

    Demos: image_editor
    NRGBAuploadwebcam	clipboardnumpyT   valueF)cropresizewebp)   rd   )"heightwidth
image_modesourcesr3   labeleveryinputs
show_labelshow_download_button	containerscale	min_widthinteractivevisibleelem_idelem_classesrenderkeypreserved_by_keyplaceholdermirror_webcamshow_share_button_selectable	crop_size
transformseraserbrushformatr   canvas_sizefixed_canvasshow_fullscreen_buttonwebcam_optionsc       "           || _         |#|#n	t               | _        |&t        j                  d       || j                  _        g d}$||$vrt        d| d|$       || _        || _        || _	        || _
        g d}%t        |t              r|g}|!|D ]  }&|&|%vst        d|%        || _        ng | _        || _        |t        j                          dun|| _        || t        j                  d       t        |t              rkt%        |j'                  d	      d
         t%        |j'                  d	      d         g}'|'d
   |'d   z  }(|(dkD  rt%        d|(z        dfndt%        d|(z        f} nt%        |d
         t%        |d         f} || _        |
t+               n|| _        |
t/               n|| _        i | _        || _        |du r
t7               n|du rt7        d      n|| _        | | _        |!| _        |"| _        || _         tB        )|   |||	|
|||||||||||       d| j                  dk(  rdn| j                  dk(  rdnd d| _#        y)ar  
        Parameters:
            value: Optional initial image(s) to populate the image editor. Should be a dictionary with keys: `background`, `layers`, and `composite`. The values corresponding to `background` and `composite` should be images or None, while `layers` should be a list of images. Images can be of type PIL.Image, np.array, or str filepath/URL. Or, the value can be a callable, in which case the function will be called whenever the app loads to set the initial value of the component.
            height: The height of the component, specified in pixels if a number is passed, or in CSS units if a string is passed. This has no effect on the preprocessed image files or numpy arrays, but will affect the displayed images. Beware of conflicting values with the canvas_size paramter. If the canvas_size is larger than the height, the editing canvas will not fit in the component.
            width: The width of the component, specified in pixels if a number is passed, or in CSS units if a string is passed. This has no effect on the preprocessed image files or numpy arrays, but will affect the displayed images. Beware of conflicting values with the canvas_size paramter. If the canvas_size is larger than the height, the editing canvas will not fit in the component.
            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.
            sources: List of sources that can be used to set the background image. "upload" creates a box where user can drop an image file, "webcam" allows user to take snapshot from their webcam, "clipboard" allows users to paste an image from the clipboard.
            type: The format the images are converted to before being passed into the prediction function. "numpy" converts the images to numpy arrays with shape (height, width, 3) and values from 0 to 255, "pil" converts the images to PIL image objects, "filepath" passes images as str filepaths to temporary copies of the images.
            label: the label for this component. Appears above the component and is also used as the header if there are a table of examples for this component. If None and used in a `gr.Interface`, the label will be the name of the parameter this component is assigned to.
            every: Continously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer.
            inputs: Components that are used as inputs to calculate `value` if `value` is a function (has no effect otherwise). `value` is recalculated any time the inputs change.
            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 size compared to adjacent Components. For example if Components A and B are in a Row, and A has scale=2, and B has scale=1, A will be twice as wide as B. Should be an integer. scale applies in Rows, and to top-level Components in Blocks where fill_height=True.
            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.
            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.
            render: If False, component will not render be rendered in the Blocks context. Should be used if the intention is to assign event listeners now but render the component later.
            key: in a gr.render, Components with the same key across re-renders are treated as the same component, not a new component. Properties set in 'preserved_by_key' are not reset across a re-render.
            preserved_by_key: A list of parameters from this component's constructor. Inside a gr.render() function, if a component is re-rendered with the same key, these (and only these) parameters will be preserved in the UI (if they have been changed by the user or an event listener) instead of re-rendered based on the values provided during constructor.
            placeholder: Custom text for the upload area. Overrides default upload messages when provided. Accepts new lines and `#` to designate a heading.
            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.
            crop_size: Deprecated. Used to set the `canvas_size` parameter.
            transforms: The transforms tools to make available to users. "crop" allows the user to crop the image.
            eraser: The options for the eraser tool in the image editor. Should be an instance of the `gr.Eraser` class, or None to use the default settings. Can also be False to hide the eraser tool. [See `gr.Eraser` docs](#eraser).
            brush: The options for the brush tool in the image editor. Should be an instance of the `gr.Brush` class, or None to use the default settings. Can also be False to hide the brush tool, which will also hide the eraser tool. [See `gr.Brush` docs](#brush).
            format: Format to save image if it does not already have a valid format (e.g. if the image is being returned to the frontend as a numpy array or PIL Image).  The format should be supported by the PIL library. This parameter has no effect on SVG files.
            layers: The options for the layer tool in the image editor. Can be a boolean     or an instance of the `gr.LayerOptions` class. If True, will allow users to add layers to the image. If False, the layers option will be hidden. If an instance of `gr.LayerOptions`, it will be used to configure the layer tool. [See `gr.LayerOptions` docs](#layer-options).
            canvas_size: The initial size of the canvas in pixels. The first value is the width and the second value is the height. If `fixed_canvas` is `True`, uploaded images will be rescaled to fit the canvas size while preserving the aspect ratio. Otherwise, the canvas size will change to match the size of an uploaded image.
            fixed_canvas: If True, the canvas size will not change based on the size of the background image and the image will be rescaled to fit (while preserving the aspect ratio) and placed in the center of the canvas.
            show_fullscreen_button: If True, will display button to view image in fullscreen mode.
            webcam_options: The options for the webcam tool in the image editor. Can be an instance of the `gr.WebcamOptions` class, or None to use the default settings. [See `gr.WebcamOptions` docs](#webcam-options).
        NzThe `mirror_webcam` parameter is deprecated. Please use the `webcam_options` parameter with a `gr.WebcamOptions` instance instead.r^   pilfilepathz$Invalid value for parameter `type`: z. Please choose from one of: rZ   z3`sources` must be a list consisting of elements in zF`crop_size` parameter is deprecated. Please use `canvas_size` instead.:r      rd   TF)rP   )ri   rj   rk   rl   rn   ro   rp   rq   rr   rs   rt   ru   rv   rw   r`   zta dictionary with structure {'background': image, 'layers': list of images, 'composite': image} where each image is r   z
a filepathr^   za numpy arrayza PIL Image object.)$r{   rT   r   warningswarnrU   
ValueErrorr3   re   rf   rg   rG   r2   rh   rm   r   	get_spacerz   intsplitr}   r<   r~   rA   r   blob_storager   rM   r   r   r   r   rx   super__init___value_description)*rJ   r`   re   rf   rg   rh   r3   ri   rj   rk   rl   rm   rn   ro   rp   rq   rr   rs   rt   ru   rv   rw   rx   ry   rz   r{   r|   r}   r~   r   r   r   r   r   r   r   valid_typesvalid_sourcessource
proportionratio	__class__s*                                            r'   r   zImageEditor.__init__   s   j ' -8Nmo 	 $MM U *7D&2{"6tf<YZeYfg  	
$9gs#iG! .$Mm_] 
 #DLDL$8! !( __d*" 	  [%8MMX )S) 	,Q/0	,Q/0
 #1
15/4qySu%s+sCeDT>U   #9Q<0#il2CD$"(.fhf %UW5
8: ~ N  t, 	 '(&<#&!#%- 	 	
" %[  lp  lu  lu  yC  lC  \h  \`  \e  \e  ip  \p  IX  vJ  [K  KL  #Mr&   c                
   |y t        |t              r)t        j                  j	                  |j
                        n't        j                  j	                  t        |            }t        |t        t        t        f      rd}| j                  }n^|j                  rDt        |j                        }|j                  }|j                  j                  dd      }|dv rd}nd}| j                  }t!        j"                         5  t!        j$                  d       |j'                  | j(                        }d d d        t+        j,                  |t/        t0        d   | j2                        | j4                  ||      S # 1 sw Y   HxY w)	Nimager    )jpgjpegr   ignorer   )r   name)rG   r   PILImageopenpathr   r5   	bytearray
memoryviewr   	orig_namer   stemsuffixreplacer   catch_warningssimplefilterconvertrg   r   format_imager   r
   r3   GRADIO_CACHE)rJ   r6   imr   r   ps         r'   convert_and_format_imagez$ImageEditor.convert_and_format_image]  s3    < $) IINN499%. 	
 dUIz:;D[[F^^T^^$A66DXX%%c2.F(D[[F$$& 	-!!(+DOO,B	- ''34dii@
 	
	- 	-s   1E99Fc                   ||S |j                   V| j                  j                  |j                         }|r,t        |j                  |j
                  |j                        nd}n|}d}d}d}|m| j                  |j                        }|j
                  r)|j
                  D cg c]  }| j                  |       c}nd}| j                  |j                        }|j                   =|j                   | j                  v r%| j                  j                  |j                          ||r|D cg c]  }||	 c}|dS g |dS c c}w c c}w )a  
        Parameters:
            payload: An instance of `EditorData` consisting of the background image, layers, and composite image.
        Returns:
            Passes the uploaded images as an instance of EditorValue, which is just a `dict` with keys: 'background', 'layers', and 'composite'. The values corresponding to 'background' and 'composite' are images, while 'layers' is a `list` of images. The images are of type `PIL.Image`, `np.array`, or `str` filepath, depending on the `type` parameter.
        Nr   r   r   )	r-   r   getr/   r   r   r   r   pop)	rJ   payloadcached_payloadbgr   r   layerxs	            r'   
preprocesszImageEditor.preprocess  sT    ?N::!&&**7::6F   %00!==$..   H	..x/B/BCB ?? DL??S%..u5S 
 55h6H6HII::!gjjD4E4E&E!!'**- >D&:QAMq:"
 	
JL"
 	
 T ;s   &E.E
6E
c                |   |yt        |t              rnKt        |t        j                  t        j
                  j
                  t        f      r|g |d}nt        d      |d   r|d   D cg c]v  }t        t        j                  t        t        t        j                  t        j
                  j
                  t        f   |      | j                  | j                              x c}ng }t        |d   9t        t        j                  |d   | j                  | j                              nd||d   |t        t        j                  t        t        t        j                  t        j
                  j
                  t        f   |d         | j                  | j                                    S d      S c c}w )	a?  
        Parameters:
            value: Expects a EditorValue, which is just a dictionary with keys: 'background', 'layers', and 'composite'. The values corresponding to 'background' and 'composite' should be images or None, while `layers` should be a list of images. Images can be of type `PIL.Image`, `np.array`, or `str` filepath/URL. Or, the value can be simply a single image (`ImageType`), in which case it will be used as the background.
        Returns:
            An instance of `EditorData` consisting of the background image, layers, and composite image.
        Nr   zOThe value to `gr.ImageEditor` must be a dictionary of images or a single image.r   )r   )r   r   r   )rG   dictnpndarrayr   r   r2   r   r   r   
save_imager   r   r   r   r,   )rJ   r`   r   r   s       r'   postprocesszImageEditor.postprocess  s    =t$

CIIOOSAB#(BUKEa  X #8_	  $//U2::syy#CDeL))#{{	  	  &2 $//l+T->->t{{  %1 $//!"**ciioos"BCU;EW ))#{{
 	
, -
 	
	s   ,A;F9c                     t        d      g d dS NzPhttps://raw.githubusercontent.com/gradio-app/gradio/main/test/test_files/bus.pngr   r   rI   s    r'   example_payloadzImageEditor.example_payload  s    %b 
 	
r&   c                    dg d dS r   r%   rI   s    r'   example_valuezImageEditor.example_value  s    l
 	
r&   c                H   |j                   d   }|j                   d   r*|j                   d   dk7  rt        |j                   d         nd}|j                  d   d   }|j                   d   }| j                  j	                  |t        dg d            }|d	k(  rb|`|t        |j                        k\  r8|j                  j                  dg|dz   t        |j                        z
  z         ||j                  |<   n|d
k(  r||_	        n|dk(  r||_
        || j                  |<   y)z
        Accepts a dictionary of image blobs, where the keys are 'background', 'layers', and 'composite', and the values are binary file-like objects.
        r3   r4   nullNr   r   r-   r   r   r   r   )r9   r   r:   r   r   r/   rR   r   extendr   r   )rJ   r9   r3   r4   r6   r-   currents          r'   accept_blobszImageEditor.accept_blobs  s    yy  yy!dii&8F&B 		'"# 	
 zz!}QYYt_##''4dK
 7?u0GNN++%%tf	C<O0O&PQ$(GNN5!\!!%G[  $G '"r&   )N)Fr`   EditorValue | ImageType | Nonere   int | str | Nonerf   r   rg   zNLiteral['1', 'L', 'P', 'RGB', 'RGBA', 'CMYK', 'YCbCr', 'LAB', 'HSV', 'I', 'F']rh   zdIterable[Literal['upload', 'webcam', 'clipboard']] | Literal['upload', 'webcam', 'clipboard'] | Noner3   z#Literal['numpy', 'pil', 'filepath']ri   zstr | I18nData | Nonerj   zTimer | float | Nonerk   z7Component | Sequence[Component] | set[Component] | Nonerl   bool | Nonerm   rN   rn   rN   ro   z
int | Nonerp   r   rq   r   rr   rN   rs   
str | Nonert   list[str] | str | Noneru   rN   rv   z(int | str | tuple[int | str, ...] | Nonerw   r   rx   r   ry   r   rz   r   r{   rN   r|   z,tuple[int | float, int | float] | str | Noner}   z*Iterable[Literal['crop', 'resize']] | Noner~   zEraser | None | Literal[False]r   zBrush | None | Literal[False]r   r2   r   zbool | LayerOptionsr   ztuple[int, int]r   rN   r   rN   r   zWebcamOptions | None)r6   zFileData | None | bytesreturnz)np.ndarray | PIL.Image.Image | str | None)r   EditorData | Noner   zEditorValue | None)r`   r   r   r   )r   r	   )r9   r8   )r!   r"   r#   r?   r   clearchangeinputselectr[   applyEVENTSr,   
data_modelr   r   r   r   r   r   r   r   __classcell__)r   s   @r'   rX   rX      s    	F J 15qM $("& 


 5<'+&*JN"&%) #'"/38<3:"&%))-!BFAS15/3&*'1"'+/3_qM-qM !	qM
  qM
qMqM$ 2%qM& %'qM( $)qM* H+qM,  -qM. #/qM0 1qM2 3qM4 5qM6 !7qM8 9qM: ;qM< -=qM> ?qM@ 6AqMB 1CqMD  EqMF #GqMH 'IqMJ KqML @MqMN ?OqMP /QqMR -SqMT UqMV $WqMX %YqMZ [qM\ !%]qM^ -_qMf 
% 
 
3 
D,
\9
v

 ( (r&   rX   )<r?   
__future__r   dataclassesr   collections.abcr   r   ior   pathlibr   typingr   r	   r
   r   r   r   r^   r   	PIL.Imager   gradio_clientr   gradio_client.documentationr   typing_extensionsr   gradior   r   gradio.components.baser   r   gradio.data_classesr   r   gradio.eventsr   gradio.i18nr   gradio.componentsr   r   r   r2   	ImageTyper   r)   r,   r/   r1   r8   	dataclassr<   rA   rM   rT   rX   r%   r&   r'   <module>r      su   " "   .      % 0 ' % 4 5    '"**ciioos23	#) #  k y #+ #
 
1 1  1 
F   : 
& &  &" 
	. 	.  	. 
}() }( }(r&   