o
    e~#g>                     @  s.  d Z ddlmZ ddl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 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$ ddl%m&Z& e
rtddl'm(Z( ej)*  G dd de"Z+G dd de"Z,e G dd de eZ)dS )zgr.Image() component.    )annotationsN)CallableSequence)Path)TYPE_CHECKINGAnyLiteralOptionalcasthandle_file)document)ImageOps)
ConfigDictField)image_utilsutils)	ComponentStreamingInput)GradioModel)Events)Error)Timerc                   @  s   e Zd ZU edddZded< edddZded< edddZd	ed
< edddZded< edddZ	ded< edddZ
ded< ddiZded< eddidZdS )	ImageDataNzPath to a local file)defaultdescriptionzOptional[str]pathz.Publicly available url or base64 encoded imageurlzSize of image in byteszOptional[int]sizezOriginal filename	orig_namezmime type of image	mime_typeFzCan always be set to Falsebool	is_stream_typezgradio.FileDatadictmetar   zTFor input, either path or url must be provided. For output, path is always provided.)json_schema_extra)__name__
__module____qualname__r   r   __annotations__r   r   r   r    r"   r%   r   model_config r,   r,   |/var/www/static.ux5.de/https/Moving-Object-Detection-with-OpenCV/env/lib/python3.10/site-packages/gradio/components/image.pyr      s   
 
r   c                   @  s    e Zd ZU eddZded< dS )Base64ImageDatazbase64 encoded image)r   strr   N)r'   r(   r)   r   r   r*   r,   r,   r,   r-   r.   /   s   
 r.   c                      s   e Zd ZdZejejejejej	ej
gZeZ	dHd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	dI fd2d3ZdJd8d9ZdKd<d=ZdLd?d@ZdAdB ZdMdDdEZdMdFdGZ  ZS )NImageaB  
    Creates an image component that can be used to upload images (as an input) or display images (as an output).

    Demos: sepia_filter, fake_diffusion
    Guides: image-classification-in-pytorch, image-classification-in-tensorflow, image-classification-with-vision-transformers, create-your-own-friends-with-a-gan
    NwebpRGBnumpyT   F)formatheightwidth
image_modesourcestypelabeleveryinputs
show_labelshow_download_button	containerscale	min_widthinteractivevisible	streamingelem_idelem_classesrenderkeymirror_webcamshow_share_buttonplaceholdershow_fullscreen_buttonvalue4str | PIL.Image.Image | np.ndarray | Callable | Noner5   r/   r6   int | str | Noner7   r8   ULiteral['1', 'L', 'P', 'RGB', 'RGBA', 'CMYK', 'YCbCr', 'LAB', 'HSV', 'I', 'F'] | Noner9   `list[Literal['upload', 'webcam', 'clipboard']] | Literal['upload', 'webcam', 'clipboard'] | Noner:   #Literal['numpy', 'pil', 'filepath']r;   
str | Noner<   Timer | float | Noner=   7Component | Sequence[Component] | set[Component] | Noner>   bool | Noner?   r!   r@   rA   
int | NonerB   intrC   rD   rE   rF   rG   list[str] | str | NonerH   rI   rJ   rK   rL   rM   c                  s   || _ || _g d}||vrtd| d| || _|| _|| _|| _g d}|du r7|r1dgng d| _nt|t	rA|g| _n|| _| jD ]}||vrTtd| qG|| _
|| _|rg| jdgkrgtd|du rqt dun|| _|| _|| _t j||	|
|||||||||||d	 dS )
a}  
        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.
            format: File format (e.g. "png" or "gif"). Used 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. Applies both when this component is used as an input or output. This parameter has no effect on SVG files.
            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 file or numpy array, but will affect the displayed image.
            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 file or numpy array, but will affect the displayed image.
            image_mode: The pixel format and color depth that the image should be loaded and preprocessed as. "RGB" will load the image as a color image, or "L" as black-and-white. See https://pillow.readthedocs.io/en/stable/handbook/concepts.html for other supported image modes and their meaning. This parameter has no effect on SVG or GIF files. If set to None, the image_mode will be inferred from the image file type (e.g. "RGBA" for a .png image, "RGB" in most other cases).
            sources: List of sources for the 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. If None, defaults to ["upload", "webcam", "clipboard"] if streaming is False, otherwise defaults to ["webcam"].
            type: The format the image is converted 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. If the image is SVG, the `type` is ignored and the filepath of the SVG is returned. To support animated GIFs in input, the `type` should be set to "filepath" or "pil".
            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.
            streaming: If True when used in a `live` interface, will automatically stream webcam feed. Only valid is source is 'webcam'. If the component is an output component, will automatically convert images to base64.
            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: if assigned, will be used to assume identity across a re-render. Components that have the same key across a re-render will have their value preserved.
            mirror_webcam: If True webcam will be mirrored. Default is True.
            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.
            placeholder: Custom text for the upload area. Overrides default upload messages when provided. Accepts new lines and `#` to designate a heading.
            show_fullscreen_button: If True, will show a fullscreen icon in the corner of the component that allows user to view the image in fullscreen mode. If False, icon does not appear.
        r3   pilfilepathz$Invalid value for parameter `type`: z. Please choose from one of: )uploadwebcam	clipboardNr_   z0`sources` must a list consisting of elements in gImage streaming only available if sources is ['webcam']. Streaming not supported with multiple sources.)r;   r<   r=   r>   r@   rA   rB   rC   rD   rF   rG   rH   rI   rN   )r5   rJ   
ValueErrorr:   r6   r7   r8   r9   
isinstancer/   rE   r?   r   	get_spacerK   rM   rL   super__init__)selfrN   r5   r6   r7   r8   r9   r:   r;   r<   r=   r>   r?   r@   rA   rB   rC   rD   rE   rF   rG   rH   rI   rJ   rK   rL   rM   valid_typesvalid_sourcessource	__class__r,   r-   rf   G   sh   @



zImage.__init__payloadImageData | Nonereturn)np.ndarray | PIL.Image.Image | str | Nonec                 C  s  |du r|S |j r4|j dr4| jdkrt|j S | jdkr%t|j S | jdkr4t|j | j| jS |j	du r=t
dt|j	}|jr[t|j}|j}|jdd}|d	v rZd
}nd}d}| dkrr| jdkrnt|S tdtj|}| jdkr| jd|jfv rt|S | }|dddkrttdrzt|}W n ty   td| d Y nw | dkr|durt   t!d | jdur|"| j}W d   n1 sw   Y  tj#|t$t%d | j| j||dS )a/  
        Parameters:
            payload: image data in the form of a FileData object
        Returns:
            Passes the uploaded image as a `numpy.array`, `PIL.Image` or `str` filepath depending on `type`. For SVGs, the `type` parameter is ignored and the filepath of the SVG is returned.
        Nzdata:r\   r3   r]   zImage path is None.. )jpgjpegrt   imager1   svgz,SVG files are not supported as input images.i     exif_transposezFailed to transpose image z based on EXIF data.gifignorer[   )namer5   )&r   
startswithr:   r   decode_base64_to_imagedecode_base64_to_image_arraydecode_base64_to_fileGRADIO_CACHEr5   r   rb   r   r   stemsuffixreplacelowerr/   r   PILr0   openr8   modegetexifgethasattrr   rx   	Exceptionwarningswarncatch_warningssimplefilterconvertformat_imager
   r   )rg   rm   	file_pathpr{   r   imexifr,   r,   r-   
preprocess   sj   	










zImage.preprocess0np.ndarray | PIL.Image.Image | str | Path | None"ImageData | Base64ImageData | Nonec                 C  s   |du rdS t |tr| drt|t|jdS | jrJt |tj	r,t
t|dS t |tjjr;t
t|dS t |ttfrJt
t|dS t|| j| j}t| r^t|jnd}t||dS )z
        Parameters:
            value: Expects a `numpy.array`, `PIL.Image`, or `str` or `pathlib.Path` filepath to an image which is displayed.
        Returns:
            Returns the image as a `FileData` object.
        Nz.svg)r   r   )r   )rc   r/   r   endswithr   r   r{   rE   npndarrayr.   r   encode_image_array_to_base64r   r0   encode_image_to_base64encode_image_file_to_base64
save_imager   r5   exists)rg   rN   savedr   r,   r,   r-   postprocess   s$   	zImage.postprocessdict[str, Any]c                 C  s*   | j dkrt }|dd  |S |  S )Nbase64r   )rE   r.   model_json_schemapopapi_info)rg   schemar,   r,   r-   api_info_as_output  s
   
zImage.api_info_as_outputc                 C  s"   | j r| jdgkrtdd S d S )Nr_   ra   )rE   r9   rb   rg   r,   r,   r-   check_streamable"  s
   zImage.check_streamabler   c                 C  s   t dS NzPhttps://raw.githubusercontent.com/gradio-app/gradio/main/test/test_files/bus.pngr   r   r,   r,   r-   example_payload(  s   zImage.example_payloadc                 C  s   dS r   r,   r   r,   r,   r-   example_value-  s   zImage.example_value)N)4rN   rO   r5   r/   r6   rP   r7   rP   r8   rQ   r9   rR   r:   rS   r;   rT   r<   rU   r=   rV   r>   rW   r?   r!   r@   r!   rA   rX   rB   rY   rC   rW   rD   r!   rE   r!   rF   rT   rG   rZ   rH   r!   rI   rP   rJ   r!   rK   rW   rL   rT   rM   r!   )rm   rn   ro   rp   )rN   r   ro   r   )ro   r   )ro   r   )r'   r(   r)   __doc__r   clearchangestreamselectr^   inputEVENTSr   
data_modelrf   r   r   r   r   r   r   __classcell__r,   r,   rk   r-   r0   3   sX    	
w
@

r0   )-r   
__future__r   r   collections.abcr   r   pathlibr   typingr   r   r   r	   r
   r3   r   	PIL.Imager   gradio_clientr   gradio_client.documentationr   r   pydanticr   r   gradior   r   gradio.components.baser   r   gradio.data_classesr   gradio.eventsr   gradio.exceptionsr   gradio.componentsr   r0   initr   r.   r,   r,   r,   r-   <module>   s0    
