a
    dLI                     @  s   d Z ddlm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 dd
lmZ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! ej"sddl#m$Z$ ed e G dd deeee e!ee	Z%dS )zgr.Video() component.    )annotationsN)Path)CallableLiteral)utils)FileData)documentset_documentation_group)VideoSerializable)processing_utilsr   
wasm_utils)IOComponent	_Keywords)warn_style_method_deprecation)
Changeable	ClearablePlayable
Recordable
Uploadable)FFmpeg	componentc                   @  s  e Zd Zd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dddddZdd Zeejddddddddddddfddddd	dddddddddddZ	dd	dddZ
dd d!d"d#Zd$d%d&d'd(Zd$d%d)d*d+Zddd,ddd,d-d.ZdS )0Videoa  
    Creates a video component that can be used to upload/record videos (as an input) or display videos (as an output).
    For the video to be playable in the browser it must have a compatible container and codec combination. Allowed
    combinations are .mp4 with h264 codec, .ogg with theora codec, and .webm with vp9 codec. If the component detects
    that the output video would not be playable in the browser it will attempt to convert it to a playable mp4 video.
    If the conversion fails, the original video is returned.
    Preprocessing: passes the uploaded video as a {str} filepath or URL whose extension can be modified by `format`.
    Postprocessing: expects a {str} or {pathlib.Path} filepath to a video which is displayed, or a {Tuple[str | pathlib.Path, str | pathlib.Path | None]} where the first element is a filepath to a video and the second element is an optional filepath to a subtitle file.
    Examples-format: a {str} filepath to a local file that contains the video, or a {Tuple[str, str]} where the first element is a filepath to a video file and the second element is a filepath to a subtitle file.
    Demos: video_identity, video_subtitle
    NuploadT   F)formatsourceheightwidthlabelevery
show_label	containerscale	min_widthinteractivevisibleelem_idelem_classesmirror_webcaminclude_audioautoplayshow_share_buttonzCstr | Path | tuple[str | Path, str | Path | None] | Callable | Nonez
str | NonezLiteral['upload', 'webcam']z
int | Nonezfloat | Nonezbool | Noneboolintzlist[str] | str | None)valuer   r   r   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   c                K  s   || _ || _ddg}||vr0td| d| || _|| _|| _|| _|durT|n|dk| _|du rrt	 dun|| _
tj| f||||	|
||||||d| dS )a&  
        Parameters:
            value: A path or URL for the default value that Video component is going to take. Can also be a tuple consisting of (video filepath, subtitle filepath). If a subtitle file is provided, it should be of type .srt or .vtt. Or can be callable, in which case the function will be called whenever the app loads to set the initial value of the component.
            format: Format of video format to be returned by component, such as 'avi' or 'mp4'. Use 'mp4' to ensure browser playability. If set to None, video will keep uploaded format.
            source: Source of video. "upload" creates a box where user can drop an video file, "webcam" allows user to record a video from their webcam.
            height: Height of the displayed video in pixels.
            width: Width of the displayed video in pixels.
            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.
            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 a video; if False, can only be used to display videos. 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.
            mirror_webcam: If True webcam will be mirrored. Default is True.
            include_audio: Whether the component should record/retain the audio track for a video. By default, audio is excluded for webcam videos and included for uploaded videos.
            autoplay: Whether to automatically play the video when the component is used as an output. Note: browsers will not autoplay video files if the user has not interacted with the page yet.
            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   webcamz&Invalid value for parameter `source`: z. Please choose from one of: N)r   r   r    r!   r"   r#   r$   r%   r&   r'   r.   )r   r*   
ValueErrorr   r   r   r(   r)   r   Z	get_spacer+   r   __init__)selfr.   r   r   r   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   kwargsZvalid_sources r4   `/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/gradio/components/video.pyr1   1   sD    2zVideo.__init__c              	   C  s0   | j | j| j| j| j| j| j| jdt	| S )N)r   r.   r   r   r(   r)   r*   r+   )
r   r.   r   r   r(   r)   r*   r+   r   
get_config)r2   r4   r4   r5   r6      s    	zVideo.get_configzAstr | tuple[str, str | None] | Literal[_Keywords.NO_VALUE] | Nonez"Literal['upload', 'webcam'] | Noner.   r   r   r   r   r    r!   r"   r#   r$   r%   r*   r+   c                 C  s"   |||||||||	|
| ||ddS )Nupdate)r   r   r   r   r    r!   r"   r#   r$   r%   r.   r*   r+   Z__type__r4   r7   r4   r4   r5   r8      s    zVideo.updatez2tuple[FileData, FileData | None] | FileData | None)xreturnc                 C  s  |du rdS t |tr|}n|d }|d|d |dd  }}}|r|dusZJ dt|rl| j}n| j}t||}n |dusJ dt| ||}|j	
d	d
}| jduo|| jk}| jdko| j}	|s|	rd	|r| jn| }
|	rg dng }|| jsdgng 7 }|	r dnd
}t||j | |
 }t| rR|S tjrdtdtt|di||id}|  |S | jst|d|j }t| r|S tjrtdtt|di|dgid}|  |S t|S dS )z
        Parameters:
            x: A tuple of (video file data, subtitle file data) or just video file data.
        Returns:
            A string file path or URL to the preprocessed video. Subtitle file data is ignored.
        Nr   namedatais_fileFz'Received file data without a file name.zReceived empty file data.. r/   )z-vfZhflipz-c:acopyz-anZ_flipz3Video formatting is not supported in the Wasm mode.)inputsoutputsZmuted_z6include_audio=False is not supported in the Wasm mode.)
isinstancedictgetclient_utilsis_http_url_likedownload_temp_copy_if_neededmake_temp_copy_if_neededr   Zbase64_to_temp_file_if_neededsuffixreplacer   r   r(   r)   str	with_namestemexistsr   IS_WASMWasmUnsupportedErrorr   runr;   )r2   r9   video	file_nameZ	file_datar=   fnZuploaded_formatZneeds_formattingZflipr   Zoutput_optionsZflip_suffixoutput_file_nameffr4   r4   r5   
preprocess   sn    	






zVideo.preprocessz8str | Path | tuple[str | Path, str | Path | None] | Nonez.tuple[FileData | None, FileData | None] | None)yr:   c                 C  s   |du s|ddgks|dkr dS t |ttfr>| |df}nt |ttfrt|dksfJ d| t |d ttfrt |d ttfsJ d| |d }|d }| || |f}ntdt	| |S )	a  
        Processes a video to ensure that it is in the correct format before returning it to the front end.
        Parameters:
            y: video data in either of the following formats: a tuple of (video filepath, optional subtitle filepath), or just a filepath or URL to an video file, or None.
        Returns:
            a tuple with the two dictionary, reresent to video and (optional) subtitle, which following formats:
            - The first dictionary represents the video file and contains the following keys:
                - 'name': a file path to a temporary copy of the processed video.
                - 'data': None
                - 'is_file': True
            - The second dictionary represents the subtitle file and contains the following keys:
                - 'name': None
                - 'data': Base64 encode the processed subtitle data.
                - 'is_file': False
            - If subtitle is None, returns (video, None).
            - If both video and subtitle are None, returns None.
        N)NN   z<Expected lists of length 2 or tuples of length 2. Received: r      zQIf a tuple is provided, both elements must be strings or Path objects. Received: zCannot process type as video: )
rC   rL   r   _format_videotuplelistlen_format_subtitle	Exceptiontype)r2   rY   Zprocessed_filesrS   subtitler4   r4   r5   postprocess  s*    
zVideo.postprocesszstr | Path | NonezFileData | None)rS   r:   c                 C  s,  |du rdS t |}|dd  }| jdu s:|| jkr@d}nd}t|}|rb|sb|dddS |rp| |}t rt	|st
d t|}|dd  }| jdur|| jkrtjrtd|d	|dd
  | j }t|di|didd}|  |}| |}|ddt|jdS )a  
        Processes a video to ensure that it is in the correct format.
        Parameters:
            video: video data in either of the following formats: a string filepath or URL to an video file, or None.
        Returns:
            a dictionary with the following keys:

            - 'name': a file path to a temporary copy of the processed video.
            - 'data': None
            - 'is_file': True
        Nr>   FTr;   r<   r=   zLVideo does not have browser-compatible container or codec. Converting to mp4zJReturning a video in a different format is not supported in the Wasm mode.r   r[   z-y)rA   rB   global_options)r;   r<   r=   Z	orig_name)rL   splitlowerr   rF   rG   rH   r   Zffmpeg_installedZvideo_is_playablewarningswarnZconvert_video_to_playable_mp4r   rP   rQ   rindexr   rR   rI   r   r;   )r2   rS   Zreturned_formatZconversion_neededis_urlrV   rW   r4   r4   r5   r\   ,  sP    



zVideo._format_video)rc   r:   c                 C  s   dd }|du rdS d}t |j|vr:td| d| t |jdkrltjdd	| jd
}|||j |j}t|}d|ddS )a  
        Convert subtitle format to VTT and process the video to ensure it meets the HTML5 requirements.
        Parameters:
            subtitle: subtitle path in either of the VTT and SRT format.
        Returns:
            a dictionary with the following keys:
            - 'name': None
            - 'data': base64-encoded subtitle data.
            - 'is_file': False
        c              	   S  s   t | dd}t |ddd}|d |  dD ]V}|d}|d dd	}d|d
d }|| d| d || d q:W d   n1 s0    Y  W d   n1 s0    Y  dS )z3Convert an SRT subtitle file to a VTT subtitle filezutf-8)encodingwzWEBVTT

z


r[   ,r>   rZ   Nz --> )openwritereadstriprh   rK   join)Zsrt_file_pathZvtt_file_pathZsrt_fileZvtt_fileZsubtitle_blockZsubtitle_linesZsubtitle_timingZsubtitle_textr4   r4   r5   
srt_to_vttx  s    

z*Video._format_subtitle.<locals>.srt_to_vttN).srt.vttz(Invalid value for parameter `subtitle`: z5. Please choose a file with one of these extensions: rx   Fry   )deleterJ   dirrf   )	r   rJ   r0   tempfileNamedTemporaryFileZDEFAULT_TEMP_DIRr;   rF   Zencode_url_or_file_to_base64)r2   rc   rw   Zvalid_extensions	temp_fileZsubtitle_datar4   r4   r5   r`   l  s     
zVideo._format_subtitle)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   )r2   r   r   r3   r4   r4   r5   style  s    zVideo.style)N)__name__
__module____qualname____doc__r1   r6   staticmethodr   ZNO_VALUEr8   rX   rd   r\   r`   r   r4   r4   r4   r5   r      sV   
 6U*#J+@/r   )&r   
__future__r   r|   rj   pathlibr   typingr   r   Zgradio_clientr   rF   Zgradio_client.data_classesr   Zgradio_client.documentationr   r	   Zgradio_client.serializingr
   Zgradior   r   Zgradio.components.baser   r   Zgradio.deprecationr   Zgradio.eventsr   r   r   r   r   rP   Zffmpyr   r   r4   r4   r4   r5   <module>   s4   
