
    :She                        U d dl 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	m
Z
mZmZmZmZmZ d dlZd dlmZmZ d dlmZmZmZmZmZmZmZmZmZmZm Z  d dl!m"Z" d dl#m$Z$m%Z% d dl&m'Z'm(Z(m)Z) d d	l*m+Z+ d d
l,m-Z-m.Z. d dl/m0Z0  ej1        e2          Z3ej4        e5d<   de j6        de	dee7e	f         fdZ8dee7         dee7         fdZ9de j6        dee7         de:de;fdZ<de j6        dee7         de
ee=         gee$e
e=ge$f         f         f         fdZ>de j6        deee=                  fdZ?de j6        dee$         dee7e	f         de:fdZ@de j6        de$fdZAde j6        de;fdZBde j6        ddfdZCde j6        ddfdZDde j6        deee7         eejE                 f         fd ZFde j6        de7fd!ZGde j6        dee7e	f         de:fd"ZHd#ee jI        e j6        f         dee j6                 fd$ZJd#ee jI        e j6        f         dee7e	f         fd%ZKd&e jI        ddfd'ZLd&e jI        ddfd(ZMde jI        fd)ZNde;fd*ZOe2d+k    r ejP         eO                       dS dS ),    N)datetime)castAnyCallableDictListOptionalTupleUnion)
FFTAlignerMaxScoreAligner)DEFAULT_APPLY_OFFSET_SECONDSDEFAULT_FRAME_RATEDEFAULT_MAX_OFFSET_SECONDSDEFAULT_MAX_SUBTITLE_SECONDSDEFAULT_NON_SPEECH_LABELDEFAULT_START_SECONDSDEFAULT_VADDEFAULT_ENCODINGFRAMERATE_RATIOSSAMPLE_RATESUBTITLE_EXTENSIONS)ffmpeg_bin_path)PipelineTransformerMixin)VideoSpeechTransformerDeserializeSpeechTransformermake_subtitle_speech_pipeline)make_subtitle_parser)SubtitleMergerSubtitleShifter)get_versionloggerargskwargsreturnc                 X    t          | j                  }|                    |           |S )N)dict__dict__update)r$   r%   	args_dicts      Y/var/www/html/movieo_spanner_bot/venv/lib/python3.11/site-packages/ffsubsync/ffsubsync.pyoverrider-   +   s+    T]##IV    	ref_fnamec                     | d S | dd          S )N )r/   s    r,   _ref_formatr3   1   s    tRSS>r.   npy_savenamesync_was_successfulc                    |t          d          d                    | j        t          j                                        d                    }t                              d                    |                     t          j	        |           	 d}| j
        It          j                            | j
                  r%t          j                            | j
        |          }t          j        ||           t          j        | j        d         |           |rt          j        | j        |           t'          | j                  t(          v rt          j        | j        |           n=| j        s| j        |k    rt          j        ||           nt          j        ||           t-          t/          t1          t          j                               d                   }g d}|D ])}||v r#t          j        ||t          j        |            n2*t                              d           	 t          j        |           d	S t                              d
           t          j        |           n# t          j        |           w xY wdS )Nzneed non-null npy_savenamez{}.{}z%Y-%m-%d-%H-%M-%Sz"creating test archive {}.tar.gz...ffsubsync.logr   )gztarbztarxztarziptarzLfailed to create test archive; no formats supported (this should not happen)   ...done)
ValueErrorformat	referencer   nowstrftimer#   infoosmkdirlog_dir_pathpathisdirjoinshutilcopysrtinmovesrtoutr3   r   serialize_speechsetlistr;   get_archive_formatsmake_archivecurdirerrorrmtree)r$   r4   r5   tar_dirlog_pathsupported_formatspreferred_formatsarchive_formats           r,   make_test_caser]   7   s\    5666nn//0CDD G KK4;;GDDEEEHW"(RW]]4;L-M-M(w||D$5x@@HHg&&&DJqM7+++ 	.KW---t~&&*===K0000" 	/dn&D&DKg....Kg...S&*D*F*F%G H H KLLEEE/ 		 		N!222#G^RYPPP 3 LL+    	g 	Igg1s   FI3 I3 3J	rM   c                      |d}n-t           j                            |          d         dd          }t          d|dd j         fdS )Nsrtr=   T)fmtcachingc           	      <    t          di t          |           S )N)scale_factorparserr2   )r   r-   )rd   r$   re   s    r,   <lambda>z$get_srt_pipe_maker.<locals>.<lambda>i   s.     = ! !
4l6
B
B
B! ! r.   r2   )rE   rH   splitextr   r)   )r$   rM   srtin_formatre   s   `  @r,   get_srt_pipe_makerri   a   so     }w''..r21226!RlDRRDMRRF     r.   c           	          | j         rg S t          t          j        t          j        t
                    dt          j        t
                    z  g                    }| j        r|                    d            |S )N      ?)no_fix_frameraterR   npconcatenatearrayr   gssappend)r$   framerate_ratioss     r,   get_framerate_ratios_to_tryrs   n   sz     
 	N*++S28<L3M3M-MN 
 

 8 	*##D)))r.   reference_piperesultc           	         d|d<   d}t                               d| j        sdnd                    | j                             | j        sd g| _        | j        D ]}	 | j        p|d u }| j        p|d u }| j        r|n| j        }t          | |          t          |           } d          gfd|D             z   }	|	D ]'}
t          |
          r|
                    |           (|st          |d	         d
          rt          |d	         j                  t          t           |	d                   d	         j        z  }t                               d|z             |	                    t          t            |                                        |                     t                               d           t                               d           |r d}t          t           |	d                   }d}nSt%          t&          |t(          | j                                      |                    | j                  |	          \  \  }}}|dk     rd}t                               d           |t          t(                    z  | j        z   }|j        d         }t                               d|           t                               d|           t                               d|j                   dt9          |          fg}| j        r4|                    dt=          |j        d         j                  f           t!          |          }|                    |j                  }| j         dk    r|!                    | j                   }| j"        }||pt          d          k    rEt                               d                    |pd                     |#                    |           n!t           $                    d|| j"                   ||d<   |j        |d<   # tJ          $ r! d}t           &                    d|           Y w xY w||d<   |S )NFr5   Tz%extracting speech segments from %s...stdinzsubtitles file(s) {}rk   c                 &    g | ]} |          S r2   r2   ).0ratsrt_pipe_makers     r,   
<listcomp>ztry_sync.<locals>.<listcomp>   s0     1 1 1(+s##1 1 1r.   r`   
num_framesr   zinferred frameratio ratio: %.3fr>   zcomputing alignments...g        scalezscore: %.3fzoffset seconds: %.3fzframerate scale factor: %.3fshiftmergeparsesamez-infzwriting output to {}stdoutzKsuppressing output because offset %s was less than suppression threshold %soffset_secondsframerate_scale_factorzfailed to sync %s)'r#   rD   rM   r@   	skip_syncskip_infer_framerate_ratiooverwrite_inputrO   ri   rs   callablefithasattrfloatr}   r   r   rq   r   r   r   max_offset_secondsfit_transform	transformrA   apply_offset_secondsnamed_stepsrd   r!   merge_with_referencer    subs_output_encodingset_encoding#suppress_output_if_offset_less_than
write_filewarning	Exception	exception)r$   rt   ru   r5   rM   r   r   rO   rr   	srt_pipessrt_pipe$inferred_framerate_ratio_from_length
best_scorebest_srt_pipeoffset_samplesr   
scale_stepoutput_stepsoutput_pipeout_subssuppress_output_threshr{   s                        @r,   try_syncr   |   s    %*F !
KK/zP'='D'DTZ'P'P   : V
 RG RGQ	G@.D*@I/I>T3I ' #2CUUF/e<<N:4@@',,- 1 1 1 1/?1 1 1 I & ( (H%% (LL''''- ''r"L3 3 ' .,7888Yq\2226AB 5 5:;      ..1U"V"V c%jj  
 I&&&KK1222 
 
 $Xy| < <!">M{D4K? ?-",,T^<<  <,^m A~~&+#KK	"""{!3!33d6OO  '27;JKKz222KK.???KK6
8OPPP/.99:@L ( ##n^-G-P-VWWX   #<00K"001ABBH#v--#001EFF%)%M""8"IE&MMJJ299&:LHMMNNN##F++++a"<   (6F#$/9/FF+,,  	9 	9 	9"'0%88888	9 %8F !s   N.P'Q	Q	c                    t          | j                  }|t          v r]| j        t                              d           t          t          t          d
d|it          | | j
        pt                              S |dv rE| j        t                              d           t          dt          | j                  fg          S | j        pt          }| j
        t                              d           | j        }||                    d          sd|z   }t          dt#          |t$          | j        | j        | j        | j        || j        | j        		  	        fg          S )Nz,Vad specified, but reference was not a moviera   )encoding)npynpzdeserializez@Reference srt encoding specified, but reference was a video file0:speech_extract)	vadsample_rate
frame_ratenon_speech_labelstart_secondsffmpeg_path
ref_streamvlc_modegui_moder2   )r3   rA   r   r   r#   r   r   r   r   r-   reference_encodingr   r   r   r   reference_stream
startswithr   r   r   r   r   r   r   )r$   
ref_formatr   r   s       r,   make_reference_piper      s   T^,,J(((8NNIJJJ)  4$*A*UEUVVV 
 
 	
 
~	%	%8NNIJJJ9$:OPPQR
 
 	
 h%+".NNR   *
!**?*?*E*E!
*J %*$/#'?)-)>&*&8$($4#-!%!%
 
 

 
 	
r.   c                 ~   | j         }|                    d          sd                    |          }n?|                    d          s*|                    d          rd                    |          }|                    d          s t                              d| j                    t          d| j        | j                  g}|                    d	d
ddd| j	        dd                    |          ddg
           | j
        |                    d           n|                    | j
                   t                              d                    | j
        dn| j
                             t          j        |          }|dk    rt                              d           nt                              d|           |S )Nz0:s:z0:s:{}r   zs:z0:{}z*invalid stream for subtitle extraction: %sffmpeg)ffmpeg_resources_pathz-yz-nostdinz	-loglevelfatal-iz-mapz{}z-fr_   -z)attempting to extract subtitles to {} ...r   r   r>   zAffmpeg unable to extract subtitles from reference; return code %d)extract_subs_from_streamr   r@   r#   rV   r   r   r   extendrA   rO   rq   rD   
subprocesscall)r$   streamffmpeg_argsretcodes       r,    extract_subtitles_from_referencer     s   *FV$$ '((t$$ '):):4)@)@ 'v&&V$$ 
8$:W	
 	
 	
 	$-tGWXXXK NKK	
   {34;'''
KK3::+HH	
 	
  
 ok**G!||IOQX	
 	
 	
 Nr.   c                    | j         r$t                              t          j                   | j        !| j        dk    s| j        st          d          | j        dk    r*| j        s| j        g| _        | j        st          d          | j        rt          | j                  dk    r| j
        st          d          t          | j                  dk    r| j        rt          d          t          | j                  dk    r| j        rt          d          | j        r$| j        s| j        r| j        t          d          | j
        rB| j        t          d	          | j        st          d
          | j        t          d          | j        ,| j        rt          d          | j        rt          d          d S d S )Nr   z>`reference` required unless `--apply-offset-seconds` specifiedzPat least one of `srtin` or `reference` must be specified to apply offset secondsr=   z;cannot specify multiple input srt files without overwritingz6cannot specify multiple input srt files for test casesz3cannot specify multiple input srt files in GUI modez9need to specify input and output srt files for test caseszEinput overwriting not allowed for extracting subtitles from referencez[need to specify input srt if --overwrite-input is specified since we cannot overwrite stdinz\overwrite input set but output file specified; refusing to run in case this was not intendedz1test case is for sync and not subtitle extractionzVstream specified for reference subtitle extraction; -i flag for sync input not allowed)r   r#   setLevelloggingCRITICALrA   r   rM   r?   lenr   r]   r   rO   r   r$   s    r,   validate_argsr   ;  s0   } *()))~$)))P    A%%z 	*.)DJz 	b   z Ttz??Qt';M   tz??Q4#6UVVVtz??Q4=RSSS$(M z 	T[0K    (4W   z 	?   ;"@   $0 	RPQQQ: 	5  	 10	 	r.   c                 l   d}| j         Mt          j        | j         t          j                  s)t	          |                    d| j                             | j        rO| j        D ]G}|Ct          j        |t          j                  s$t	          |                    d|                    H| j        qt          j        	                    | j                  rMt          j        | j        t          j
                  s)t	          |                    d| j                            | j        s| j        rt          j                            | j                   d         dz   }t          j        	                    |          r1t          j        |t          j
                  st	          d|z            d S d S d S )	NzOunable to {action} {file}; try ensuring file exists and has correct permissionszread reference)actionfilezread input subtitleszwrite output subtitlesr   .npzzDunable to write test case file archive %s (try checking permissions))rA   rE   accessR_OKr?   r@   rM   rO   rH   existsW_OKr]   rP   rg   )r$   error_string_templaterM   r4   s       r,   validate_file_permissionsr   s  s   	?  ~!")DNBG*L*L!!((0@t~(VV
 
 	
 z Z 	 	E 5"')B)B  )005E 1     	GNN4;'' 	 	$+rw// 	  !((/dk )  
 
 	

  d3 w''77:VC7>>,'' 		,0P0P 	V  	 	 	 	r.   c                    d }d }| j         s| j        d}| j        It          j                            | j                  r%t          j                            | j        |          }t          j        |          }t          	                    |           t          
                    dt          j                            |                     ||fS )Nr7   zthis log will be written to %s)r]   rG   rE   rH   rI   rJ   r   FileHandlerr#   
addHandlerrD   abspath)r$   log_handlerrY   s      r,   _setup_loggingr     s     KH Qd/;"(RW]]4;L-M-M(w||D$5x@@H)(33+&&&4bgooh6O6OPPP[  r.   c                 \    t           j                            | j                  d         dz   S )Nr   r   )rE   rH   rg   rA   r   s    r,   _npy_savenamer     s$    7DN++A.77r.   c                    | j         t          |           |d<   dS | j        F| j        .t	          | j                  dk    r'| j        d         | j        k    rt          | d |          S t          |           }t                              d| j                   |	                    | j                   t                              d           | j
        s| j        rt                              d           t          j        t          |           |                    | j                             t                              d           | j        st                              d	           d
S t          | ||          S )NretvalTr=   r   z1extracting speech segments from reference '%s'...r>   zserializing speech...)speechzDunsynchronized subtitle file not specified; skipping synchronizationF)r   r   rM   rA   r   r   r   r#   rD   r   r]   rP   rm   savez_compressedr   r   )r$   ru   rt   s      r,   	_run_implr     sd   $0;DAAxtz
OOq  TZ]dn%D%DdF+++(..N
KKCT^TTTt~&&&
KK	 
d3 
+,,,
$(@(@(P(P	
 	
 	
 	
 	Iz 	KKV   5D.&111r.   parser_or_argsc                    t          | t          j                  rd }| }n| }|                                }	 t	          |           nH# t
          $ r;}t                              |           ||                                 Y d }~d S d }~ww xY w|j	        rO|j
        Hd                    t          j                            |j        d                   d                   |_
        	 t!          |           n2# t
          $ r%}t                              |           Y d }~d S d }~ww xY wt#          |j                  }|j        r%|t(          vrt                              d           d S |S )Nz{}.synced.srtr   zTmerging synced output with reference only valid when reference composed of subtitles)
isinstanceargparse	Namespace
parse_argsr   r?   r#   rV   print_usager   rO   r@   rE   rH   rg   rM   r   r3   rA   r   r   )r   re   r$   er   s        r,   validate_and_transform_argsr     s    .("455 #  ""d   Q   ttttt	
 } Q,%,,RW-=-=djm-L-LQ-OPP!$''''   Qttttt T^,,J  Z7J%J%J3	
 	
 	
 tKs/   A 
B0BB&C6 6
D% D  D%c                 <   d}dd d d}t          |           }|d|d<   |S t          |          \  }}	 t          ||          }||d<   ||||                                 t                              |           |j        r,|dxx         t          |t          |          |          z  cc<   |j        $t          j
                            |j                  st          j        |           S S S S # |||                                 t                              |           |j        r,|dxx         t          |t          |          |          z  cc<   |j        $t          j
                            |j                  st          j        |           w w w w xY w)NFr   )r   r   r   r=   r   r5   )r   r   r   closer#   removeHandlerr]   r   rG   rE   rH   rI   remove)r   r5   ru   r$   rY   r   s         r,   runr     s     "& F
 '~66D|x*400Hk$'f55(;$%"x';  ---" x   N---/B% %      (d>O0P0P(	(#### #'; ) "x';  ---" x   N---/B% %      (d>O0P0P(	(#### #'; )s   C2 2B)Fre   c                 2   |                      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 S )NrA   ?zgReference (video, subtitles, or a numpy array with VAD speech) to which to synchronize input subtitles.)nargshelpr   z--srtin*z%Input subtitles file (default=stdin).z-oz--srtoutz'Output subtitles file (default=stdout).r   z--merge-with-referencez--merge
store_truez7Merge reference subtitles with synced output subtitles.r   r   z--make-test-casez--create-test-casezIf specified, serialize reference speech to a numpy array, and create an archive with input/output subtitles and serialized speech.z--reference-streamz--refstreamz--reference-trackz
--reftrackaG  Which stream/track in the video file to use as reference, formatted according to ffmpeg conventions. For example, 0:s:0 uses the first subtitle track; 0:a:3 would use the third audio track. You can also drop the leading `0:`; i.e. use s:0 or a:3, respectively. Example: `ffs ref.mkv -i in.srt -o out.srt --reference-stream s:2`defaultr   )add_argumentre   s    r,   add_main_args_for_clir    s   
7	     is)P     jH      F	     !	     Q      r.   c           
      R   |                      dddd                    t          t                                           |                      ddd	
           |                      dt          dt          z             |                      dt
          t          dt          z             |                      dt          t          dt          z             |                      dt
          t          dt          z             |                      dt
          t          dt          z             |                      dt          t          dt          z             |                      ddd
           |                      dt
          t          dt          z             |                      ddd           |                      d d!"           |                      d#g d$d d%                    t                    &           |                      d'dd(
           |                      d)dd*
           |                      d+d,d d-           |                      d.t
          d d/           |                      d0d1d d2           |                      d3d d4           |                      d5dd6
           |                      d7dd8
           |                      d9dt          j        
           |                      d:dt          j        
           |                      d;dt          j        
           d S )<Nz-vz	--versionversionz{package} {version})packager  )r   r  z--overwrite-inputr   zWIf specified, will overwrite the input srt instead of writing the output to a new file.r   z
--encodingz>What encoding to use for reading input subtitles (default=%s).r   z--max-subtitle-secondszKMaximum duration for a subtitle to appear on-screen (default=%.3f seconds).)typer   r   z--start-secondsz/Start time for processing (default=%d seconds).z--max-offset-secondszMThe max allowed offset seconds for any subtitle segment (default=%d seconds).z--apply-offset-secondszSApply a predefined offset in seconds to all subtitle segments (default=%d seconds).z--frame-ratez-Frame rate for audio extraction (default=%d).z--skip-infer-framerate-ratiozDIf set, do not try to infer framerate ratio based on duration ratio.z--non-speech-labelz;Label to use for frames detected as non-speech (default=%f)z--output-encodingzutf-8zWhat encoding to use for writing output subtitles (default=utf-8). Can indicate "same" to use same encoding as that of the input.z--reference-encodingz^What encoding to use for reading / writing reference subtitles (if applicable, default=infer).r   z--vad)subs_then_webrtcwebrtcsubs_then_auditokauditoksubs_then_silerosilerozoWhich voice activity detector to use for speech extraction (if using video / audio as a reference, default={}).)choicesr   r   z--no-fix-frameratezgIf specified, subsync will not attempt to correct a framerate mismatch between reference and subtitles.z--serialize-speechz:If specified, serialize reference speech to a numpy array.z--extract-subs-from-streamz--extract-subtitles-from-streamzqIf specified, do not attempt sync; instead, just extract subtitles from the specified stream using the reference.z%--suppress-output-if-offset-less-thanzGIf specified, do not produce output if offset below provided threshold.z--ffmpeg-pathz--ffmpegpathzFWhere to look for ffmpeg and ffprobe. Uses the system PATH by default.z--log-dir-pathz[If provided, will save log file ffsubsync.log to this path (must be an existing directory).z--gssznIf specified, use golden-section search to try to findthe optimal framerate ratio between video and subtitles.z--strictz?If specified, refuse to parse srt files with formatting issues.z
--vlc-modez
--gui-modez--skip-sync)r   r@   __package__r"   r   r   r   intr   r   r   r   r   r   r   SUPPRESSr  s    r,   add_cli_only_argsr  1  sS   
%,, - 
 
	     ;	      *+      ,"$@A	     % "78	     * "<=	      , ">?	     "<?QQ	     &S    
 (J
"#	     )     *    
 
 
 
 ??Evk?R?R     4     I    
 $):	     /V	     U	     /	     C     N    
 \@QRRR
\@QRRR
lARSSSSSr.   c                  l    t          j        d          } t          |            t          |            | S )Nz!Synchronize subtitles with video.)description)r   ArgumentParserr  r  r  s    r,   make_parserr    s7    $1TUUUF&!!!fMr.   c                  H    t                      } t          |           d         S )Nr   )r  r   r  s    r,   mainr    s    ]]Fv;;x  r.   __main__)Qr   r   r   rE   rK   r   systypingr   r   r   r   r   r	   r
   r   numpyrm   ffsubsync.alignersr   r   ffsubsync.constantsr   r   r   r   r   r   r   r   r   r   r   ffsubsync.ffmpeg_utilsr   ffsubsync.sklearn_shimr   r   ffsubsync.speech_transformersr   r   r   ffsubsync.subtitle_parserr   ffsubsync.subtitle_transformersr    r!   ffsubsync.versionr"   	getLogger__name__r#   Logger__annotations__r   strr-   r3   boolr  r]   r   ri   rs   r   r   r   r   r   r   r   r   r   r  r   r   r  r  r  r  exitr2   r.   r,   <module>r+     s           				      



 J J J J J J J J J J J J J J J J J J J J     : : : : : : : :                          3 2 2 2 2 2 = = = = = = = =         
 ; : : : : : K K K K K K K K ) ) ) ) ) ) +*844 4 4 48%  c3h    8C= Xc]    '

',4SM'PT'' ' ' 'T



%-c]
xx5'8:K1L'L!MMN
 
 
 
 h&8  T(5/=R        _

_.6x.@_JNsTWx._	_ _ _ _D,
h0 ,
X ,
 ,
 ,
 ,
^+8+= +# + + + +\5* 5t 5 5 5 5p!H$6 !4 ! ! ! !H!

!
8C=(7#6778! ! ! !8* 8s 8 8 8 82H& 2S#X 24 2 2 2 26(183EEFh !   B$(183EEF$	#s(^$ $ $ $<*("9 *d * * * *ZRTh5 RT$ RT RT RT RTjX,    !c ! ! ! !
 zCHTTVV r.   