
    U[i-p                    L   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 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 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)m*Z* erddl+m,Z, ddl-m.Z.  e        G d dee             Z/y)zgr.Video() component.    )annotationsN)CallableSequencePath)TYPE_CHECKINGAnyLiteralhandle_file)utils)document)processing_utilsr   )	ComponentStreamingOutput)Button)WatermarkOptionsWebcamOptions)FileDataMediaStreamChunk)Events)I18nData)get_upload_folderset_default_buttons)Timer)FFmpegc                  (    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 fd	Zd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   valueFr   )formatsourcesheightwidthlabeleveryinputs
show_label	containerscale	min_widthinteractivevisibleelem_idelem_classesrenderkeypreserved_by_keywebcam_optionsinclude_audioautoplaybuttonsloop	streaming	watermark	subtitlesplayback_positionc               ~   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        |t              r|n	t               | _        t        |t        t        f      r|| j                  _        ||nd| j                   v | _        t#        |dg      | _        || _        || _        d| _        |Pt        |t              r*t-        | j/                  |      j0                        | _        n| j3                  |      | _        t4        | m  ||||	|
||||||||||       d	| _        y)
a  
        Parameters:
            value: path or URL for the default value that Video component is going to take. 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. If "hidden", component will be visually hidden and not take up space in the layout but still exist in the DOM
            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.
            buttons: A list of buttons to show in the top right corner of the component. Valid options are "download", "share", or a gr.Button() instance. The "download" button allows the user to save the video to their device. The "share" button allows the user to share the video via Hugging Face Spaces Discussions. Custom gr.Button() instances will appear in the toolbar with their configured icon and/or label, and clicking them will trigger any .click() events registered on the button. By default, no buttons are shown if the component is interactive and both buttons are shown if the component is not interactive.
            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: A `gr.WatermarkOptions` instance that includes an image file and position to be used as a watermark on the video. The image is not scaled and is displayed on the provided position on 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
            subtitles: A subtitle file (srt, vtt, or json) for the video, or a list of subtitle dictionaries in the format [{"text": str, "timestamp": [start, end]}] where timestamps are in seconds. JSON files should contain an array of subtitle objects.
            playback_position: The starting playback position in seconds. This value is also updated as the video plays, reflecting the current playback position.
        uploadwebcamNc              3  &   K   | ]  }|v  
 y wN ).0svalid_sourcess     e/var/www/html/chatbot/Makanify-Chatbot-3/venv/lib/python3.12/site-packages/gradio/components/video.py	<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 download)r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   r0   r1   r2   r    za string filepath to a video)r"   
isinstancestrlistall
ValueErrorr!   r5   r#   r$   r7   r   r3   r   r9   r   r4   r   r6   r8   r;   r:   r   _process_json_subtitlespath_format_subtitlessuper__init___value_description) selfr    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   r0   r1   r2   r3   r4   r5   r6   r7   r8   r9   r:   r;   sourcerD   	__class__s                                  @rE   rQ   zVideo.__init__<   s   B =Eh;O?(DL%']*B#9DL&3.S7.S+S"DLEm_U  ll 	F]* F}oV 	
  
	,8Nmo 	
 $I/?@IFVFX 	 i#t-'0DNN$ +6MH<T 	 +7ZLA"!2 )T*!,00;@@" "&!7!7	!B!#%- 	 	
" #A    c                   |y|j                   st        d      t        |j                         }|j                  j	                  dd      }| j
                  duxr || j
                  k7  }| j                  dgk(  xr | j                  j                  }g d}| j                  j                  t        | j                  j                  t        t        f      s"t        d| j                  j                         t        | j                  j                        j                  |vrHt        dd	j                  |       d
t        | j                  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        |j#                               S t%        t        |      di|
|i      }|j'                          t        |j#                               S | j                  sot        |j                  d|j(                               }
t        |
      j!                         r|
S t%        t        |      di|
dgi      }|j'                          |
S t        |      S )z
        Parameters:
            payload: An instance of FileData containing the video file.
        Returns:
            Passes the uploaded video as a `str` filepath or URL whose extension can be modified by `format`.
        NzPayload path missing. r>   )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_flip)r'   outputsmuted_)rN   rL   r   suffixreplacer!   r"   r3   mirrorr9   rH   rI   joinr4   	with_namestemexistsresolver   runname)rS   payload	file_nameuploaded_formatneeds_formattingflipvalid_watermark_extensionsr!   output_optionsflip_suffixoutput_file_nameoutput_filepathffs                rE   
preprocesszVideo.preprocess   s    ?||344&	#**223;;;d2U$++7U||z)Hd.A.A.H.H%>">>##/dnn66dD !!%!9!9 :<  DNN,,-44<VV ''*xx0J'K&L M!!%dnn&>&>!?!F!F GqJ 
 t(8oNOFAE=2NT-?-?ugRGN%)'rK"##y~~&6{mF8$LM  ##34O%%'?22455I-)>:B FFH..011##"9#6#6	?O7P#QR$%,,.''I-)E73B FFH##y>!rV   c                    | j                   r|S ||ddgdfv ryt        |t        t        f      r| j	                  |      }S )ar  
        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:
            FileData object containing the video file.
        N)NN)r8   rH   rI   r   _format_video)rS   r    processed_videos      rE   postprocesszVideo.postprocess   sL     >>L=EtTlL%AAec4[)"007OrV   c                j   |yt        |      }|j                  d      d   j                         }| j                  || j                  k(  rd}nd}t	        j
                  |      }| 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                  j                  r>d	g}|di}|d
|j%                  d      dz    }| j                  || j                  z  }n||z  }| j                  j                  rd|t        | j                  j                        <   | j                  j&                  }d}	t)        |t*              r|\  }
}d|
 d| }n:|dk(  r	d|	 d|	 }n,|dk(  r	d|	 d|	 }n|dk(  r	d|	 d|	 }n|dk(  r	d|	 d|	 }n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.
        NrX   FTrN   	cache_dirzMVideo does not have browser-compatible container or codec. Converting to mp4.-yr         zoverlay=:ztop-leftz	top-rightzoverlay=W-w-zbottom-leftz:H-h-zbottom-rightzoverlay=W-w-5:H-h-5z-filter_complex_watermarkedr'   r^   global_options)rN   	orig_name)rI   splitlowerr!   client_utilsis_http_url_liker9   r   r   save_url_to_cacheGRADIO_CACHEffmpeg_installedvideo_is_playablewarningswarnconvert_video_to_playable_mp4r   #get_extension_from_file_path_or_urlrindexpositionrH   tupler   re   r`   r   rh   ri   )rS   videoreturned_formatconversion_neededis_urlglobal_option_listinputs_dictrr   posmarginxywatermark_cmdrt   s                 rE   rw   zVideo._format_video
  s   
 =E
++c*2.446;;/T[["@ % $..u5 ~~''V<M'' $66!2!2E --/$66u=MM_ %BB5IECCEJPPRKK#4;;(F^^%%"& $-K$Qc):Q)>?{{& DKK/  O3 ~~''=AC 8 89:nn--c5)DAq&.qc1#$6MJ&&.vhax$@MK'&26(!F8$DMM)&.vheF8$DMN*&26(%x$HM$9M"'8-&HH")*//$%+,334 !
 ")401B
 FFH$EUd5k.>.>??rV   c                   dd}t        |      D ]  \  }}t        |t              st        d| d      d|vrt        d| d      d|vrt        d| d      t        |d   t        t
        f      rt        |d         dk7  svt        d| d	       t        j                  d
dt               dd      }	 |j                  d       |D ]N  } ||d   d         } ||d   d         }|d   }|j                  | d| d       |j                  | d       P |j                          t        t        |j                              S # t        $ r$}	|j                          t        d|	       |	d}	~	ww xY w)z%Convert JSON subtitles to VTT format.c                d    t        | dz        }t        | dz  dz        }| dz  }|dd|dd|dS )z6Convert seconds to VTT timestamp format (HH:MM:SS.mmm)i  <   02dr   z06.3f)int)secondshoursminutessecss       rE   seconds_to_vtt_timestampz?Video._process_json_subtitles.<locals>.seconds_to_vtt_timestamp_  sI    4(E7T>b01GR<DC['#aU|<<rV   zSubtitle at index z must be a dictionarytextz missing required 'text' field	timestampz# missing required 'timestamp' field   z1 'timestamp' must be a list/tuple of [start, end]F.vttwutf-8)deleter`   dirmodeencodingWEBVTT

r   r    --> 


r|   z-Error creating VTT file from JSON subtitles: N)r   floatreturnrI   )	enumeraterH   dictrL   rJ   r   lentempfileNamedTemporaryFiler   writecloser   rI   ri   	Exception)
rS   r:   r   isubtitle	temp_file
start_timeend_timer   es
             rE   rM   zVideo._process_json_subtitles\  s   	= %Y/ 	KAxh- #5aS8M!NOOX% #5aS8V!WXX(* (+NO  x4tUmDx,-2 (+\] 	$ //!#
		YOOL)% /5h{6KA6NO
3H[4I!4LM':,eH:R @A4&./ OOY^^!455 	YOOLQCPQWXX	Ys   9BE 	E9E44E9c                   ddl }ddlm} d } ||      }|j                  j	                         dk(  ri	 t        |d      5 } |j                  |      }ddd       t        t              r$t        | j                  |      j                        S t        d      d|yd}	 ||      j                  |	vrt        d| d|	        ||      j                  dk(  r?t        j                   ddt#                     }
 |||
j$                         |
j$                  }t        |      S # 1 sw Y   xY w# |j                  $ r}t        d	|       |d}~wt        $ r}t        d
|       |d}~ww xY w)zq
        Convert subtitle format to VTT and process the video to ensure it meets the HTML5 requirements.
        r   Nr   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 filer   r   r   r   r   r   r   rZ   rX   r   Nr   )openr   readstripr   ra   rc   )srt_file_pathvtt_file_pathsrt_filevtt_filesubtitle_blocksubtitle_linessubtitle_timingsubtitle_texts           rE   
srt_to_vttz+Video._format_subtitles.<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-.jsonr   r   z:JSON subtitle file must contain a list of subtitle objectsz&Invalid JSON format in subtitle file: z"Error reading JSON subtitle file: ).srtr   r   z(Invalid value for parameter `subtitle`: z5. Please choose a file with one of these extensions: r   Fr   r   r`   r   )jsonpathlibr   r`   r   r   loadrH   rJ   r   rM   rN   rL   JSONDecodeErrorr   r   r   r   ri   )rS   r   r   r   r   	file_pathf	json_datar   valid_extensionsr   s              rE   rO   zVideo._format_subtitles  s    	 	; N	!!#w.R)g6 -! )		!I-i.&t'C'CI'N'S'STT$T  4>  (88:8*Dy  {K  zL  M 
 >  F* 33V1B1DI x0 ~~H8$$C- - '' V #I!!MNTUU R #EaS!IJPQQRsA   D1 D%;D1 D1 %D.*D1 1E/ EE/E**E/c                    t        d      S NzRhttps://github.com/gradio-app/gradio/raw/main/gradio/media_assets/videos/world.mp4r   rS   s    rE   example_payloadzVideo.example_payload  s    `
 	
rV   c                     yr   rA   r   s    rE   example_valuezVideo.example_value  s    crV   c           
        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 )Nffprobez-vquietz-print_formatr   z-show_formatz-show_streamsT)capture_outputcheckr!   durationstreams)
subprocessrh   r   loadsstdoutr   get)filenameresultdatar   streams        rE   get_video_duration_ffprobez Video.get_video_duration_ffprobe  s    	  
 zz&--(t
d8n <T(^J78H  ((9b1 '$VJ%78H
 rV   c                  K   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)NzL-c:v libx264 -c:a aac -f mpegts -bsf:v h264_mp4toannexb -bsf:a aac_adtstoascr   r    r   stderrr   FFmpeg command failed: )r   cmdr   asynciocreate_subprocess_execr   PIPEcommunicate
returncodedecoder   RuntimeError)mp4_filets_filert   commandprocess_r   error_messages           rE   async_convert_mp4_to_tszVideo.async_convert_mp4_to_ts  s     d#g !6
 &&,,s#66%%**%%**
 
 "--//	6""MMO113M!8HII
 0s%   A8C:C;CCACCc           	       K   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 |S c c}w 7 }7 g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.
        F.mp4r   zvideo_chunk.tsr}   ffmpegz-izconcat:|r   z-safe0z-cr\   r   Nr   r   video-stream.mp4)rN   	is_streamr   )r   r   r   r   save_bytes_to_cacherc   ri   r   r   r   r  r  r  r  r   r  r   )rS   r   desired_output_format	only_fileoutput_filerC   ts_filesr  r	  r
  r   r  r   s                rE   combine_streamzVideo.combine_stream	  sW     11T->->
 	
  00#t/@/@
 
 chhx()*

  66%%**%%**
 
 "--//	6""MMO113M!8HII!!(

 LK
$
 0s0   'E)D=A2EEEEA&EE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)rN   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  ra   r  r   r   
read_bytes)rS   r    	output_idfirst_chunkr  r  r   chunks           rE   stream_outputzVideo.stream_outputB  s      !! 0 "34	
 =$$~~e$>>&)"R  mmFE2G..ug>>>227;FGGM,,. #

 k!! ?s   A(B0*B.+AB0r@   )8r    zstr | Path | Callable | Noner!   
str | Noner"   zFlist[Literal['upload', 'webcam']] | Literal['upload', 'webcam'] | Noner#   int | str | Noner$   r%  r%   zstr | I18nData | Noner&   zTimer | float | Noner'   z7Component | Sequence[Component] | set[Component] | Noner(   bool | Noner)   boolr*   z
int | Noner+   r   r,   r&  r-   zbool | Literal['hidden']r.   r$  r/   list[str] | str | Noner0   r'  r1   z(int | str | tuple[int | str, ...] | Noner2   r(  r3   zWebcamOptions | Noner4   r&  r5   r'  r6   z2list[Literal['download', 'share'] | Button] | Noner7   r'  r8   r'  r9   zWatermarkOptions | Noner:   z(str | Path | list[dict[str, Any]] | Noner;   r   )rj   FileData | Noner   r$  )r    str | Path | Noner   r)  )r   r*  r   r)  )r:   zlist[dict[str, Any]]r   r   )r   r*  r   r)  )r   r	   )r   rI   )NF)r   zlist[bytes]r  r$  r   r   )r    r$  r   rI   r!  r'  r   z$tuple[MediaStreamChunk | None, dict])__name__
__module____qualname____doc__r   
data_modelr   changeclearstart_recordingstop_recordingstopplaypauseendr=   EVENTSrQ   ru   ry   rw   rM   rO   r   r   staticmethodr   r  r  r#  __classcell__)rU   s   @rE   r   r   "   s    J 	


F 15@A " #'"&'+&*JN"& #',0"/38<3:/3%)FJ-1>B#$A@A,@A 	@A S@A !@A  @A %@A $@A H@A  @A @A @A  !@A" !#@A$ *%@A& '@A( -)@A* +@A, 6-@A. 1/@A0 -1@A2 #3@A4 5@A6 D7@A8 9@A: ;@A< +=@A> <?@A@ !A@AD;"zP@d1Yf9%v

d  :  6 -1	77  *7
 
7r$"$" $" 	$"
 
.$"rV   r   )0r.  
__future__r   r   r   r   r   r   collections.abcr   r   r   r   typingr   r	   r
   gradio_clientr   r   r   gradio_client.documentationr   gradior   gradio.components.baser   r   gradio.components.buttonr   gradio.components.image_editorr   r   gradio.data_classesr   r   gradio.eventsr   gradio.i18nr   gradio.utilsr   r   gradio.componentsr   ffmpyr   r   rA   rV   rE   <module>rJ     st     "      .  . . % / 0 * = + J :     ?'  
C	"OY C	" C	"rV   