
    ;3hl                    n   d Z ddlmZ ddlZddlZddl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mZmZmZ ddlmZ ddlmZ dd	lmZ ddl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$ ddl%m&Z& ddl'm(Z( erddl)m*Z* ejV                  sddl,m-Z-  G d de#      Z. e        G d dee             Z/y)zgr.Video() component.    )annotationsN)CallableSequence)Path)TYPE_CHECKINGAnyLiteralOptionalhandle_file)utils)document)processing_utilsr   
wasm_utils)	ComponentStreamingOutput)WebcamOptions)FileDataGradioModelMediaStreamChunk)Events)I18nData)Timer)FFmpegc                  &    e Zd ZU ded<   dZded<   y)	VideoDatar   videoNzOptional[FileData]	subtitles)__name__
__module____qualname____annotations__r        W/var/www/html/audio-gradio/venv/lib/python3.12/site-packages/gradio/components/video.pyr   r   #   s    O$(I!(r$   r   c                   :    e Zd ZdZeZej                  ej                  ej                  ej                  ej                  ej                  ej                  ej                  ej                  g	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 fdZdd	Z	 	 	 	 dd
ZddZddZddZddZedd       Zed        Z	 	 d	 	 	 	 	 ddZ	 	 	 	 	 	 	 	 ddZ xZS )Videoa5  
    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.

    Demos: video_identity_2
    NT   valueF)formatsourcesheightwidthlabeleveryinputs
show_label	containerscale	min_widthinteractivevisibleelem_idelem_classesrenderkeypreserved_by_keymirror_webcamwebcam_optionsinclude_audioautoplayshow_share_buttonshow_download_button
min_length
max_lengthloop	streaming	watermarkwebcam_constraintsc                 ! ddg!|!| _         nWt        |t              r|!v r	|g| _         n:t        |t              rt	        !fd|D              r|| _         nt        d!       | j                   D ]  } | !vst        d!        || _        || _        || _        || _	        || _
        ||n	t               | _        |&t        j                  d       || j                  _        ||| j                  _        ||nd| j                   v | _        |t%        j&                         dun|| _        || _        || _        || _        || _        || _        t4        "| m  ||||	|
||||||||||       d	| _        y)
a  
        Parameters:
            value: 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: the file extension with which to save video, such as 'avi' or 'mp4'. This parameter applies both when this component is used as an input to determine which file format to convert user-provided video to, and when this component is used as an output to determine the format of video returned to the user. If None, no file format conversion is done and the video is kept as is. Use 'mp4' to ensure browser playability.
            sources: list of sources permitted for video. "upload" creates a box where user can drop a video file, "webcam" allows user to record a video from their webcam. If None, defaults to both ["upload, "webcam"].
            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 video file, but will affect the displayed video.
            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 video file, but will affect the displayed video.
            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.
            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 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.
            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.
            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.
            show_download_button: if True, will show a download icon in the corner of the component that allows user to download the output. If False, icon does not appear. By default, it will be True for output components and False for input components.
            min_length: the minimum length of video (in seconds) that the user can pass into the prediction function. If None, there is no minimum length.
            max_length: the maximum length of video (in seconds) that the user can pass into the prediction function. If None, there is no maximum length.
            loop: if True, the video will loop when it reaches the end and continue playing from the beginning.
            streaming: when used set as an output, takes video chunks yielded from the backend and combines them into one streaming video output. Each chunk should be a video file with a .ts extension using an h.264 encoding. Mp4 files are also accepted but they will be converted to h.264 encoding.
            watermark: an image file to be included as a watermark on the video. The image is not scaled and is displayed on the bottom right of the video. Valid formats for the image are: jpeg, png.
            webcam_options: A `gr.WebcamOptions` instance that allows developers to specify custom media constraints for the webcam stream. This parameter provides flexibility to control the video stream's properties, such as resolution and front or rear camera on mobile devices. See $demo/webcam_constraints
        uploadwebcamNc              3  &   K   | ]  }|v  
 y wNr#   ).0svalid_sourcess     r%   	<genexpr>z!Video.__init__.<locals>.<genexpr>   s     .SaqM/A.Ss   z3`sources` must be a list consisting of elements in z0`sources` must a list consisting of elements in zThe `mirror_webcam` parameter is deprecated. Please use the `webcam_options` parameter with a `gr.WebcamOptions` instance instead.)r.   r/   r0   r1   r2   r3   r4   r5   r6   r7   r8   r9   r:   r;   r)   za string filepath to a video)r+   
isinstancestrlistall
ValueErrorr*   r?   r,   r-   rD   r   r=   warningswarnmirrorconstraintsr>   r   	get_spacer@   rA   rB   rC   rE   rF   super__init___value_description)#selfr)   r*   r+   r,   r-   r.   r/   r0   r1   r2   r3   r4   r5   r6   r7   r8   r9   r:   r;   r<   r=   r>   r?   r@   rA   rB   rC   rD   rE   rF   rG   sourcerO   	__class__s#                                    @r%   r\   zVideo.__init__B   s   N =Eh;O?(DL%']*B#9DL&3.S7.S+S"DLEm_U  ll 	F]* F}oV 	
  
	,8Nmo 	 $MM U *7D&).@D+ +6MH<T 	
 !( __d*" 	
 %9!$$""!#%- 	 	
" #Ar$   c                B   |y|j                   j                  st        d      t        |j                   j                        }|j                  j                  dd      }| j                  duxr || j                  k7  }| j                  dgk(  xr | j                  j                  }| j                  | j                  t        j                  |      }| j                  2|| j                  k  r#t        j                  d| j                   d      | j                  2|| j                  kD  r#t        j                  d| j                   d      g d	}| j                   t#        | j                   t$        t        f      st        d
| j                          t        | j                         j                  |vr>t        ddj'                  |       dt        | j                         j                   d      |s|rd|r| j                  n| }|rg dng }	|	| j(                  sdgng z  }	|rdnd}
t%        |j+                  |j,                   |
 |             }t        |      }|j/                         rt%        |j1                               S t2        j4                  rt3        j6                  d      t9        t%        |      di||	i      }|j;                          t%        |j1                               S | j(                  st%        |j+                  d|j<                               }t        |      j/                         r|S t2        j4                  rt3        j6                  d      t9        t%        |      di|dgi      }|j;                          |S t%        |      S )z
        Parameters:
            payload: An instance of VideoData containing the video and subtitle files.
        Returns:
            Passes the uploaded video as a `str` filepath or URL whose extension can be modified by `format`.
        NzPayload path missing. rJ   z)Video is too short, and must be at least z secondsz'Video is too long, and must be at most )z.pngz.jpgz.jpegz=Provided watermark file not an expected file type. Received: zDWatermark file does not have a supported extension. Expected one of ,z. Received: )z-vfhflipz-c:acopyz-an_flipz3Video formatting is not supported in the Wasm mode.)r0   outputsmuted_z6include_audio=False is not supported in the Wasm mode.)r   pathrU   r   suffixreplacer*   r+   r=   rX   rB   rC   r   get_video_lengthgrErrorrF   rQ   rR   joinr>   	with_namestemexistsresolver   IS_WASMWasmUnsupportedErrorr   runname)r^   payload	file_nameuploaded_formatneeds_formattingflipdurationvalid_watermark_extensionsr*   output_optionsflip_suffixoutput_file_nameoutput_filepathffs                 r%   
preprocesszVideo.preprocess   sd    ?}}!!344++,	#**223;;;d2U$++7U||z)Hd.A.A.H.H??&$//*E (88CH*x$///Ihh??PPXY  *x$///Ihh=doo=NhW  &?">>%dnnsDk: !!% 02  DNN#**2LL ''*xx0J'K&L M!!%dnn!5!<!< =Q@ 
 t(8oNOFAE=2NT-?-?ugRGN%)'rK"##y~~&6{mF8$LM  ##34O%%'?22455!! 55I  I-)>:B FFH..011##"9#6#6	?O7P#QR$%,,.''!! 55L  I-)E73B FFH##y>!r$   c                :   | j                   r|S ||ddgdfv ryt        |t        t        f      r| j	                  |      df}nt        |t
        t        f      rt        |      dk7  rt        d|       t        |d   t        t        f      rt        |d   t        t        f      st        d|       |d   }|d   }| j	                  |      | j                  |      f}nt        dt        |             |d   st        d	      t        |d   |d   
      S )a  
        Parameters:
            value: 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.
        Returns:
            VideoData object containing the video and subtitle files.
        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: zVideo data missing)r   r   )rE   rQ   rR   r   _format_videotuplerS   lenrU   	TypeError_format_subtitle	Exceptiontyper   )r^   r)   processed_filesr   subtitles        r%   postprocesszVideo.postprocess  s7    >>L=EtTlL%AAec4[)#11%8$?Ot}-5zQ RSXRYZ 
 58c4[1jqCQU;6Wghmgno  !HEQxH""5)%%h/O <T%[MJKKq!122q1_Q=OPPr$   c                   |yt        |      }|j                  d      d   j                         }| j                  || j                  k(  rd}nd}t	        j
                  |      }| j                  s|r|st        |      S |r!t        j                  || j                        }t        j                         r?t        j                  |      s*t        j                  d       t        j                  |      }t!        j"                  |      j                         }| j                  || j                  k7  s| j                  rt$        j&                  rt%        j(                  d	      d
g}|di}|d|j+                  d      dz    }| j                  || j                  z  }n||z  }| j                  rOd|t        | j                        <   d}|d|gz  }t-        |      j.                  dz   t-        |      j0                  z   }t3        ||di|      }	|	j5                          |}t        |t-        |      j6                        S )zy
        Processes a video to ensure that it is in the correct format
        and adds a watermark if requested.
        Nrb   FTrj   	cache_dirzMVideo does not have browser-compatible container or codec. Converting to mp4.z4Modifying a video is not supported in the Wasm mode.-yr   r   zoverlay=W-w-5:H-h-5z-filter_complex_watermarkedr0   rh   global_options)rj   	orig_name)rR   splitlowerr*   client_utilsis_http_url_likerF   r   r   save_url_to_cacheGRADIO_CACHEffmpeg_installedvideo_is_playablerV   rW   convert_video_to_playable_mp4r   #get_extension_from_file_path_or_urlr   ru   rv   rindexr   rr   rk   r   rw   rx   )
r^   r   returned_formatconversion_neededis_urlglobal_option_listinputs_dictr   watermark_cmdr   s
             r%   r   zVideo._format_videoD  s   
 =E
++c*2.446;;/T[["@ % $..u5 ~~62C'' $66!2!2E --/$66u=MM_ %BB5IECCEJPPRKK#4;;(F^^!! 55J  #' $-K$Qc):Q)>?{{& DKK/  O3 ~~37C/0 5"'8-&HH")*//$%+,334 !
 ")401B
 FFH$EUd5k.>.>??r$   c                >   d }|yd}t        |      j                  |vrt        d| d|       t        |      j                  dk(  rAt        j                  dd| j
                  	      } |||j                         |j                  }t        t        |      
      S )zq
        Convert subtitle format to VTT and process the video to ensure it meets the HTML5 requirements.
        c           	        t        | d      5 }t        |dd      5 }|j                  d       |j                         j                         j	                  d      D ]g  }|j	                  d      }|d   j                  dd	      }dj                  |d
d       }|j                  | d| d       |j                  | d       i 	 ddd       ddd       y# 1 sw Y   xY w# 1 sw Y   yxY w)z3Convert an SRT subtitle file to a VTT subtitle filezutf-8)encodingwzWEBVTT

z


r   rd   rb   r   Nz --> )openwritereadstripr   rl   rp   )srt_file_pathvtt_file_pathsrt_filevtt_filesubtitle_blocksubtitle_linessubtitle_timingsubtitle_texts           r%   
srt_to_vttz*Video._format_subtitle.<locals>.srt_to_vtt  s     ]W5
;9A]C':
;>F|,&.mmo&;&;&=&C&CF&K ;N%3%9%9$%?N&4Q&7&?&?S&IO$(IInQR.@$AMNNo%6eO;LB#OPNNm_D#9:;
; 
; 
; 
; 
; 
;s#   C$B)CC$C!	C$$C-N).srt.vttz(Invalid value for parameter `subtitle`: z5. Please choose a file with one of these extensions: r   Fr   deleterk   dirr   )	r   rk   rU   tempfileNamedTemporaryFiler   rx   r   rR   )r^   r   r   valid_extensions	temp_files        r%   r   zVideo._format_subtitle  s    
	; +>  (88:8*Dy  {K  zL  M 
 >  F* 33V1B1BI x0 ~~HS]++r$   c                    dt        d      iS )Nr   Rhttps://github.com/gradio-app/gradio/raw/main/demo/video_component/files/world.mp4r   r^   s    r%   example_payloadzVideo.example_payload  s    [d
 	
r$   c                     y)Nr   r#   r   s    r%   example_valuezVideo.example_value  s    cr$   c           
     f   t         j                  rt        j                  d      t        j                  ddddddd| gd	d	
      }t        j                  |j                        }d }d|v rd|d   v rt        |d   d         }|S |j                  dg       D ]  }d|v st        |d         } |S  |S )Nz*ffprobe is not supported in the Wasm mode.ffprobez-vquietz-print_formatjsonz-show_formatz-show_streamsT)capture_outputcheckr*   r~   streams)
r   ru   rv   
subprocessrw   r   loadsstdoutfloatget)filenameresultdatar~   streams        r%   get_video_duration_ffprobez Video.get_video_duration_ffprobe  s    11<  	  
 zz&--(t
d8n <T(^J78H  ((9b1 '$VJ%78H
 r$   c                  K   t         j                  rt        j                  d      t        | d i|didg      }|j                  j                  d      }t        j                  |t        j                  j                  t        j                  j                  d d {   }|j                          d {   \  }}|j                  dk7  r,|j                         j                         }t        d|       |S 7 \7 Fw)	N,Streaming is not supported in the Wasm mode.zL-c:v libx264 -c:a aac -f mpegts -bsf:v h264_mp4toannexb -bsf:a aac_adtstoascr   r    r   stderrr   FFmpeg command failed: )r   ru   rv   r   cmdr   asynciocreate_subprocess_execr   PIPEcommunicate
returncodedecoder   RuntimeError)mp4_filets_filer   commandprocess_r   error_messages           r%   async_convert_mp4_to_tszVideo.async_convert_mp4_to_ts  s     11>  d#g !6
 &&,,s#66W//44W=O=O=T=T
 
 "--//	6""MMO113M!8HII
 0s%   BD C< D 7C>8AD >D c           	       K   t         j                  rt        j                  d      t        j                  dd| j
                        }|D cg c]$  }t        j                  |d| j
                        & }}ddd	d
j                  |       ddddd|j                  g	}t        j                  |t        j                  j                  t        j                  j                  d d{   }|j                          d{   \  }	}
|j                  dk7  r,|
j!                         j#                         }t%        d|       t'        |j                  dd      }|r|S t)        |      }|S c c}w 7 7 sw)zCombine video chunks into a single video file.

        Do not take desired_output_format into consideration as
        mp4 is a safe format for playing in browser.
        r   F.mp4r   zvideo_chunk.tsr   ffmpegz-izconcat:|r   z-safe0z-crf   r   Nr   r   video-stream.mp4)rj   	is_streamr   )r   )r   ru   rv   r   r   r   r   save_bytes_to_cacherp   rx   r   r   r   r   r   r   r   r   r   r   r   )r^   r   desired_output_format	only_fileoutput_filerN   ts_filesr   r   r   r   r   r   outputs                 r%   combine_streamzVideo.combine_stream  s     11>  11T->->
 	
  00#t/@/@
 
 chhx()*

  66W//44W=O=O=T=T
 
 "--//	6""MMO113M!8HII!!(

 L'I
$
 0s2   AE7)E.7A2E7)E3*E7E5A2E75E7c                d  K   d|ddddidi}|d |fS |}|j                  d      sH|j                  d      st        d	      |j                  dd      }| j                  ||       d {    | j	                  |      }|st        d
      t        |      j                         |dd}||fS 7 Cw)Nr   Tr   _typezgradio.FileData)rj   r   r   metaz.tsr   z<Video must be in .mp4 or .ts format to be streamed as chunksz%Cannot determine video chunk duration)r   r~   	extension)endswithr   rl   r   r   r   
read_bytes)r^   r)   	output_idfirst_chunkr   r   r~   chunks           r%   stream_outputzVideo.stream_output7  s      !! 0 "34	
 =$$~~e$>>&)"R  mmFE2G..ug>>>227;FGGM,,. #

 k!! ?s   A(B0*B.+AB0rL   )>r)   zCstr | Path | tuple[str | Path, str | Path | None] | Callable | Noner*   
str | Noner+   zFlist[Literal['upload', 'webcam']] | Literal['upload', 'webcam'] | Noner,   int | str | Noner-   r  r.   zstr | I18nData | Noner/   zTimer | float | Noner0   z7Component | Sequence[Component] | set[Component] | Noner1   bool | Noner2   boolr3   
int | Noner4   intr5   r  r6   r  r7   r  r8   list[str] | str | Noner9   r  r:   z(int | str | tuple[int | str, ...] | Noner;   r  r<   r  r=   zWebcamOptions | Noner>   r  r?   r  r@   r  rA   r  rB   r  rC   r  rD   r  rE   r  rF   str | Path | NonerG   zdict[str, Any] | None)ry   VideoData | Nonereturnr  )r)   z8str | Path | tuple[str | Path, str | Path | None] | Noner  r  )r   r  r  FileData | None)r   r  r  r  )r  r   )r   rR   )NF)r   zlist[bytes]r   r  r  zVideoData | FileData)r)   r  r	  rR   r
  r  r  z$tuple[MediaStreamChunk | None, dict])r   r    r!   __doc__r   
data_modelr   changeclearstart_recordingstop_recordingstopplaypauseendrI   EVENTSr\   r   r   r   r   r   r   staticmethodr   r   r  r  __classcell__)r`   s   @r%   r'   r'   (   s    J 	


F  	GA " #'"&'+&*JN"& #'"/38<3:%)/3%))-,0!%!%'+48KGA PGA GA SGA !GA  GA %GA $GA HGA  GA  !GA" #GA$ %GA& !'GA( )GA* +GA, --GA. /GA0 61GA2 13GA4 #5GA6 -7GA8 #9GA: ;GA< '=GA> *?GA@ AGAB CGAD EGAF GGAH %IGAJ 2KGARN"`'QM'Q	'QRD@L&,P
d    D  < -1	::  *:
 
:x$"$" $" 	$"
 
.$"r$   r'   )0r  
__future__r   r   r   r   r   rV   collections.abcr   r   pathlibr   typingr   r   r	   r
   gradio_clientr   r   r   gradio_client.documentationr   gradiorn   r   r   gradio.components.baser   r   gradio.components.image_editorr   gradio.data_classesr   r   r   gradio.eventsr   gradio.i18nr   gradio.componentsr   ru   ffmpyr   r   r'   r#   r$   r%   <module>r3     s     "      .  8 8 % / 0  6 6 = 8 G G    ' ) )
 
r"OY r" r"r$   