
    Sh]                         d dl Z d dlm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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  G d	 d
ee                   ZddlmZmZmZ dS )    N)chain)
OptionalListDictIterableAnyoverloadIteratorTextIOTupleMutableSequence   )
IntOrFloat)SSAEvent)SSAStyle)	make_time	ms_to_strc                      e Zd ZU dZddddZeeef         ed<   dBd	Ze		 	 dCdedede
e         de
e         de
e         dedd fd            Ze	dDdede
e         de
e         dedd f
d            Ze	dDdede
e         de
e         dedd f
d            Z	 	 dCdedede
e         de
e         de
e         deddfdZdEdede
e         dedefdZdEdedede
e         deddf
dZ	 	 dFdedededede
e         de
e         ddfdZd ed!eddfd"Zd#ed$eddfd%ZdGd'd d(eddfd)ZdBd*Zdee         fd+Zd,d defd-Zdefd.Z dBd/Z!de"e         fd0Z#e$d1edefd2            Z%e$de&dee         fd3            Z%d1edefd4Z%e$d5ed6eddfd7            Z'e$d8e&d9e(e         ddfd:            Z'd5ed6eddfd;Z'e$d5eddfd<            Z)e$de&ddfd=            Z)d5eddfd>Z)defd?Z*d@ed6eddfdAZ+dS )HSSAFilea  
    Subtitle file in SubStation Alpha format.

    This class has a list-like interface which exposes :attr:`SSAFile.events`,
    list of subtitles in the file::

        subs = SSAFile.load("subtitles.srt")

        for line in subs:
            print(line.text)

        subs.insert(0, SSAEvent(start=0, end=make_time(s=2.5), text="New first subtitle"))

        del subs[0]

    0yesNormal)	WrapStyleScaledBorderAndShadow
CollisionsDEFAULT_INFOreturnNc                     g | _         dt          j                                        i| _        | j                                        | _        i | _        i | _        i | _	        d | _
        d | _        d S )NDefault)eventsr   DEFAULT_STYLEcopystylesr   infoaegisub_projectfonts_opaquegraphics_opaquefpsformatselfs    U/var/www/html/movieo_spanner_bot/venv/lib/python3.11/site-packages/pysubs2/ssafile.py__init__zSSAFile.__init__%   sd    &(,5x7M7R7R7T7T+U$($5$:$:$<$<	/1,./1$(%)    utf-8pathencodingformat_r(   errorskwargsc                 |    t          |||          5 } | j        ||fd|i|cddd           S # 1 swxY w Y   dS )a7
  
        Load subtitle file from given path.

        This method is implemented in terms of :meth:`SSAFile.from_file()`.

        See also:
            Specific formats may implement additional loading options,
            please refer to documentation of the implementation classes
            (eg. :meth:`pysubs2.formats.subrip.SubripFormat.from_file()`)

        Arguments:
            path (str): Path to subtitle file.
            encoding (str): Character encoding of input file.
                Defaults to UTF-8, you may need to change this.
            errors (Optional[str]): Error handling for character encoding
                of input file. Defaults to ``None``; use the value ``"surrogateescape"``
                for pass-through of bytes not supported by selected encoding via
                `Unicode surrogate pairs <https://en.wikipedia.org/wiki/Universal_Character_Set_characters#Surrogates>`_.
                See documentation of builtin ``open()`` function for more.

                .. versionchanged:: 1.7.0
                    The ``errors`` parameter was introduced to facilitate
                    pass-through of subtitle files with unknown text encoding.
                    Previous versions of the library behaved as if ``errors=None``.

            format_ (str): Optional, forces use of specific parser
                (eg. `"srt"`, `"ass"`). Otherwise, format is detected
                automatically from file contents. This argument should
                be rarely needed.
            fps (float): Framerate for frame-based formats (MicroDVD),
                for other formats this argument is ignored. Framerate might
                be detected from the file, in which case you don't need
                to specify it here (when given, this argument overrides
                autodetection).
            kwargs: Extra options for the reader.

        Returns:
            SSAFile

        Raises:
            IOError
            UnicodeDecodeError
            pysubs2.exceptions.UnknownFPSError
            pysubs2.exceptions.UnknownFormatIdentifierError
            pysubs2.exceptions.FormatAutodetectionError

        Note:
            pysubs2 may autodetect subtitle format and/or framerate. These
            values are set as :attr:`SSAFile.format` and :attr:`SSAFile.fps`
            attributes.

        Example:
            >>> subs1 = pysubs2.load("subrip-subtitles.srt")
            >>> subs2 = pysubs2.load("microdvd-subtitles.sub",fps=23.976)
            >>> subs3 = pysubs2.load("subrip-subtitles-with-fancy-tags.srt",keep_unknown_html_tags=True)

        r1   r3   r(   N)open	from_file)clsr0   r1   r2   r(   r3   r4   fps           r,   loadzSSAFile.load3   s    x $&999 	AR 3=W@@#@@@	A 	A 	A 	A 	A 	A 	A 	A 	A 	A 	A 	A 	A 	A 	A 	A 	A 	As   155stringc                 L    t          j        |          } | j        ||fd|i|S )a)  
        Load subtitle file from string.

        See :meth:`SSAFile.load()` for full description.

        Arguments:
            string (str): Subtitle file in a string. Note that the string must be Unicode (``str``, not ``bytes``).
            format_ (str): Optional, forces use of specific parser
                (eg. `"srt"`, `"ass"`). Otherwise, format is detected
                automatically from file contents. This argument should
                be rarely needed.
            fps (float): Framerate for frame-based formats (MicroDVD),
                for other formats this argument is ignored. Framerate might
                be detected from the file, in which case you don't need
                to specify it here (when given, this argument overrides
                autodetection).

        Returns:
            SSAFile

        Example:
            >>> text = '''
            ... 1
            ... 00:00:00,000 --> 00:00:05,000
            ... An example SubRip file.
            ... '''
            >>> subs = SSAFile.from_string(text)

        r(   )ioStringIOr8   )r9   r<   r2   r(   r4   r:   s         r,   from_stringzSSAFile.from_stringr   s5    @ [  s}R<<c<V<<<r.   r:   c                     |A|                                 }|dd         }t          |          }t          j        |          }t	          |          } |             }||_        ||_         |j        |||fd|i| |S )a  
        Read subtitle file from file object.

        See :meth:`SSAFile.load()` for full description.

        Note:
            This is a low-level method. Usually, one of :meth:`SSAFile.load()`
            or :meth:`SSAFile.from_string()` is preferable.

        Arguments:
            fp (file object): A file object, ie. :class:`TextIO` instance.
                Note that the file must be opened in text mode (as opposed to binary).
            format_ (str): Optional, forces use of specific parser
                (eg. `"srt"`, `"ass"`). Otherwise, format is detected
                automatically from file contents. This argument should
                be rarely needed.
            fps (float): Framerate for frame-based formats (MicroDVD),
                for other formats this argument is ignored. Framerate might
                be detected from the file, in which case you don't need
                to specify it here (when given, this argument overrides
                autodetection).

        Returns:
            SSAFile

        Ni'  r(   )readautodetect_formatr>   r?   get_format_classr)   r(   r8   )	r9   r:   r2   r(   r4   textfragmentimplsubss	            r,   r8   zSSAFile.from_file   s    : ? 7799DFUF|H'11GT""B((suutR<<c<V<<<r.   c                    |Ft           j                            |          d                                         }t	          |          }t          |d||          5 } | j        ||fd|i| ddd           dS # 1 swxY w Y   dS )aA	  
        Save subtitle file to given path.

        This method is implemented in terms of :meth:`SSAFile.to_file()`.

        See also:
            Specific formats may implement additional saving options,
            please refer to documentation of the implementation classes
            (eg. :meth:`pysubs2.formats.subrip.SubripFormat.to_file()`)

        Arguments:
            path (str): Path to subtitle file.
            encoding (str): Character encoding of output file.
                Defaults to UTF-8, which should be fine for most purposes.
            format_ (str): Optional, specifies desired subtitle format
                (eg. `"srt"`, `"ass"`). Otherwise, format is detected
                automatically from file extension. Thus, this argument
                is rarely needed.
            fps (float): Framerate for frame-based formats (MicroDVD),
                for other formats this argument is ignored. When omitted,
                :attr:`SSAFile.fps` value is used (ie. the framerate used
                for loading the file, if any). When the :class:`SSAFile`
                wasn't loaded from MicroDVD, or if you wish save it with
                different framerate, use this argument. See also
                :meth:`SSAFile.transform_framerate()` for fixing bad
                frame-based to time-based conversions.
            errors (Optional[str]): Error handling for character encoding
                of input file. Defaults to ``None``; use the value ``"surrogateescape"``
                for pass-through of bytes not supported by selected encoding via
                `Unicode surrogate pairs <https://en.wikipedia.org/wiki/Universal_Character_Set_characters#Surrogates>`_.
                See documentation of builtin ``open()`` function for more.

                .. versionchanged:: 1.7.0
                    The ``errors`` parameter was introduced to facilitate
                    pass-through of subtitle files with unknown text encoding.
                    Previous versions of the library behaved as if ``errors=None``.

            kwargs: Extra options for the writer.

        Raises:
            IOError
            UnicodeEncodeError
            pysubs2.exceptions.UnknownFPSError
            pysubs2.exceptions.UnknownFormatIdentifierError
            pysubs2.exceptions.UnknownFileExtensionError

        Nr   wr6   r(   )osr0   splitextlowerget_format_identifierr7   to_file)	r+   r0   r1   r2   r(   r3   r4   extr:   s	            r,   savezSSAFile.save   s    b ?'""4((+1133C+C00G$hv>>> 	9"DLW88#8888	9 	9 	9 	9 	9 	9 	9 	9 	9 	9 	9 	9 	9 	9 	9 	9 	9 	9s   A;;A?A?c                 r    t          j                    } | j        ||fd|i| |                                S )z
        Get subtitle file as a string.

        See :meth:`SSAFile.save()` for full description.

        Returns:
            str

        r(   )r>   r?   rO   getvalue)r+   r2   r(   r4   r:   s        r,   	to_stringzSSAFile.to_string   s>     []]R44c4V444{{}}r.   c                 H    t          |          } |j        | ||fd|i| dS )a  
        Write subtitle file to file object.

        See :meth:`SSAFile.save()` for full description.

        Note:
            This is a low-level method. Usually, one of :meth:`SSAFile.save()`
            or :meth:`SSAFile.to_string()` is preferable.

        Arguments:
            fp (file object): A file object, ie. :class:`TextIO` instance.
                Note that the file must be opened in text mode (as opposed to binary).

        r(   N)rD   rO   )r+   r:   r2   r(   r4   rG   s         r,   rO   zSSAFile.to_file  s:      ((T2w::C:6:::::r.   r   hmsmsframesc                 z    t          ||||||          }| D ]"}|xj        |z  c_        |xj        |z  c_        #dS )aV  
        Shift all subtitles by constant time amount.

        Shift may be time-based (the default) or frame-based. In the latter
        case, specify both frames and fps. h, m, s, ms will be ignored.

        Arguments:
            h: Integer or float values, may be positive or negative (hours).
            m: Integer or float values, may be positive or negative (minutes).
            s: Integer or float values, may be positive or negative (seconds).
            ms: Integer or float values, may be positive or negative (milliseconds).
            frames (int): When specified, must be an integer number of frames.
                May be positive or negative. fps must be also specified.
            fps (float): When specified, must be a positive number.

        Raises:
            ValueError: Invalid fps or missing number of frames.

        )rV   rW   rX   rY   rZ   r(   N)r   startend)	r+   rV   rW   rX   rY   rZ   r(   deltalines	            r,   shiftzSSAFile.shift  sY    * AaBv3GGG 	 	DJJ%JJHHHHH	 	r.   in_fpsout_fpsc                     |dk    s|dk    rt          d| d|           ||z  }| D ]T}t          t          |j        |z                      |_        t          t          |j        |z                      |_        UdS )aJ  
        Rescale all timestamps by ratio of in_fps/out_fps.

        Can be used to fix files converted from frame-based to time-based
        with wrongly assumed framerate.

        Arguments:
            in_fps (float)
            out_fps (float)

        Raises:
            ValueError: Non-positive framerate given.

        r   z.Framerates must be positive, cannot transform z -> N)
ValueErrorintroundr\   r]   )r+   ra   rb   ratior_   s        r,   transform_frameratezSSAFile.transform_framerate8  s     Q;;'Q,,cfccZaccddd  	4 	4DU4:#56677DJ5E!12233DHH	4 	4r.   old_namenew_namec                 "   ddl m} || j        vrt          d|d          || j        v rt	          d|           ||          st	          |d          | j        |         | j        |<   | j        |= | D ]}|j        |k    r||_        dS )aw  
        Rename a style, including references to it.

        Arguments:
            old_name (str): Style to be renamed.
            new_name (str): New name for the style (must be unused).

        Raises:
            KeyError: No style named old_name.
            ValueError: new_name is not a legal name (cannot use commas)
                or new_name is taken.

        r   )is_valid_field_contentzStyle z
 not foundz There is already a style called z is not a valid nameN)formats.substationrl   r#   KeyErrorrd   style)r+   ri   rj   rl   r_   s        r,   rename_stylezSSAFile.rename_styleS  s     	?>>>>>4;&&:H:::;;;t{""LLLMMM%%h// 	B@@@AAA $H 5HK! 	& 	&DzX%%%
	& 	&r.   TrH   	overwritec                     t          |t                    st          d          |j                                        D ]\  }}|| j        vs|r
|| j        |<   dS )z
        Merge in styles from other SSAFile.

        Arguments:
            subs (SSAFile): Subtitle file imported from.
            overwrite (bool): On name conflict, use style from the other file
                (default: True).

        zMust supply an SSAFile.N)
isinstancer   	TypeErrorr#   items)r+   rH   rq   namero   s        r,   import_styleszSSAFile.import_stylesr  so     $(( 	75666;,,.. 	* 	*KD%4;&&)&$)D!	* 	*r.   c                    g }t                      }i }t          |           D ]t\  }}|                    |j        |j        fg           }|                    |j                  dk    r|                    |           |                    |j                   ut          |           D ]Y\  }}|j	        s|j
        rt          |j                                                  dk     r?||v rD|                    |           Z|| _        dS )a]  
        Remove subtitles which appear to be non-essential (the --clean in CLI)

        Currently, this removes events matching any of these criteria:
        - SSA event type Comment
        - SSA drawing tags
        - Less than two characters of text
        - Duplicated text with identical time interval (only the first event is kept)
        r      N)set	enumerate
setdefaultr\   r]   count	plaintextaddappend
is_drawing
is_commentlenstripr    )r+   
new_eventsduplicate_text_idstimes_to_textsietmps          r,   remove_miscellaneous_eventsz#SSAFile.remove_miscellaneous_events  s    
 UU;=dOO 	$ 	$DAq ++QWae,<bAACyy%%))"&&q)))JJq{####dOO 	! 	!DAq| q| 1;$$&&''!++&&&a     r.   c                     d | D             S )zc
        Return list of events excluding SSA comment lines and lines with SSA drawing tags
        c                      g | ]}|j         	|S  )is_text).0r   s     r,   
<listcomp>z+SSAFile.get_text_events.<locals>.<listcomp>  s    ---a19----r.   r   r*   s    r,   get_text_eventszSSAFile.get_text_events  s     .-4----r.   otherc                 	   t          |t                    rt          t          | j                                        |j                                                            dhz
  D ]}| j                            |          |j                            |          }}|t          j        d|            dS |t          j        d|            dS ||k    rt          j        d|||            dS t          t          | j	                                        |j	                                                            D ]}| j	                            |          |j	                            |          }}|t          j        d|            dS |t          j        d|            dS ||k    rt          j        d	|||            dS t          t          | j
                                        |j
                                                            D ]}| j
                            |          |j
                            |          }}|t          j        d
|            dS |t          j        d|            dS ||k    rt          j        d|||            dS t          t          | j                                        |j                                                            D ]}| j                            |          |j                            |          }
}	|	t          j        d|            dS |
t          j        d|            dS |	|
k    r|	j        D ]9}t          |	|          t          |
|          k    rt          j        d|           :t          j        d||	                                |
                                            dS t          |           t          |          k    r2t          j        dt          |           t          |                     dS t!          t#          | j        |j                            D ]\  }\  }}|                    |          s|j        D ]9}t          ||          t          ||          k    rt          j        d|           :t          j        d||                                |                                            dS dS t)          d          )ah  
        Equality of two SSAFiles.

        Compares :attr:`SSAFile.info`, :attr:`SSAFile.styles` and :attr:`SSAFile.events`.
        Order of entries in OrderedDicts does not matter. "ScriptType" key in info is
        considered an implementation detail and thus ignored.

        Useful mostly in unit tests. Differences are logged at DEBUG level.

        
ScriptTypeNz%r missing in self.infoFz%r missing in other.infoz#info %r differs (self=%r, other=%r)z%r missing in self.fonts_opaquez %r missing in other.fonts_opaquez+fonts_opaque %r differs (self=%r, other=%r)z"%r missing in self.graphics_opaquez#%r missing in other.graphics_opaquez.graphics_opaque %r differs (self=%r, other=%r)z%r missing in self.stylesz%r missing in other.styleszdifference in field %rz$style %r differs (self=%r, other=%r)z,different # of subtitles (self=%d, other=%d)z$event %d differs (self=%r, other=%r)Tz$Cannot compare to non-SSAFile object)rs   r   rz   r   r$   keysgetloggingdebugr&   r'   r#   FIELDSgetattras_dictr   r{   zipr    equalsrt   )r+   r   key	self_info
other_info	self_font
other_font
self_imageother_image
self_styleother_stylekr   
self_eventother_events                  r,   r   zSSAFile.equals  s    eW%% B	D5!1!15:??3D3DEEFF,W 
! 
!(,	c(:(:EJNN3<O<O:	$M";SAAA 55'M"<cBBB 55*,,M"GiYcddd 55 - 5!2!7!7!9!95;M;R;R;T;TUUVV 
! 
!(,(9(=(=c(B(BEDVDZDZ[^D_D_:	$M"CSIII 55'M"DcJJJ 55*,,M"OQTV_aklll 55 - 5!5!:!:!<!<e>S>X>X>Z>Z[[\\ 
! 
!*.*>*B*B3*G*GI^IbIbcfIgIgK
%M"FLLL 55 (M"GMMM 55;..M"RTWYcepqqq 55 / 5!1!1!3!3U\5F5F5H5HIIJJ ! !*.+//#*>*>@P@PQT@U@UK
%M"=sCCC 55 (M">DDD 55;..'. G G":q11W[!5L5LLL#M*BAFFFM"H#zOaOaOcOcepexexezez{{{ 55 / 4yyCJJ&&LcRViiY\]bYcYcdddu09#dk5<:X:X0Y0Y ! !,,J!((55 !'. G G":q11W[!5L5LLL#M*BAFFFM"H!ZM_M_MaMacncvcvcxcxyyy 55! 4BCCCr.   c                     | j         rRt          d | D                       }dt          |            dt          | j                   dt	          |           d}ndt          | j                   d}|S )Nc              3   $   K   | ]}|j         V  d S N)r]   )r   evs     r,   	<genexpr>z#SSAFile.__repr__.<locals>.<genexpr>  s$      11b26111111r.   z<SSAFile with z events and z styles, last timestamp >z<SSAFile with 0 events and z styles>)r    maxr   r#   r   )r+   max_timerX   s      r,   __repr__zSSAFile.__repr__  s    ; 	I11D11111HxTxxDK8H8HxxbkltbubuxxxAAHc$+.>.>HHHAr.   c                 8    | j                                          dS )z#Sort subtitles time-wise, in-place.N)r    sortr*   s    r,   r   zSSAFile.sort
  s    r.   c                 *    t          | j                  S r   )iterr    r*   s    r,   __iter__zSSAFile.__iter__  s    DK   r.   itemc                     d S r   r   r+   r   s     r,   __getitem__zSSAFile.__getitem__      r.   c                     d S r   r   r+   rX   s     r,   r   zSSAFile.__getitem__  r   r.   c                     | j         |         S r   r    r   s     r,   r   zSSAFile.__getitem__  s    {4  r.   r   valuec                     d S r   r   )r+   r   r   s      r,   __setitem__zSSAFile.__setitem__  r   r.   r   valuesc                     d S r   r   )r+   r   r   s      r,   r   zSSAFile.__setitem__   r   r.   c                 Z   t          |t                    r0t          |t                    r|| j        |<   d S t	          d          t          |t
                    rCt          |          }t          d |D                       r|| j        |<   d S t	          d          t	          d          )N1SSAFile.events must contain only SSAEvent objectsc              3   @   K   | ]}t          |t                    V  d S r   )rs   r   )r   vs     r,   r   z&SSAFile.__setitem__.<locals>.<genexpr>,  s,      ;;q:a**;;;;;;r.   zBad key type)rs   re   r   r    rt   slicelistall)r+   r   r   r   s       r,   r   zSSAFile.__setitem__$  s    c3 	,%** U#(C    STTTU## 	,%[[F;;F;;;;; U#)C    STTTN+++r.   c                     d S r   r   r+   r   s     r,   __delitem__zSSAFile.__delitem__3  r   r.   c                     d S r   r   r   s     r,   r   zSSAFile.__delitem__7  r   r.   c                     | j         |= d S r   r   r   s     r,   r   zSSAFile.__delitem__;  s    Kr.   c                 *    t          | j                  S r   )r   r    r*   s    r,   __len__zSSAFile.__len__>  s    4;r.   indexc                     t          |t                    r| j                            ||           d S t	          d          )Nr   )rs   r   r    insertrt   )r+   r   r   s      r,   r   zSSAFile.insertA  sB    eX&& 	QKue,,,,,OPPPr.   )r   N)r/   NNN)NNr   )r   r   r   r   NN)T),__name__
__module____qualname____doc__r   r   str__annotations__r-   classmethodr   floatr   r;   r@   r   r8   rQ   rT   rO   r   re   r`   rh   rp   boolrw   r   r   r   r   r   r   r   r
   r   r	   r   r   r   r   r   r   r   r   r.   r,   r   r      s         $ !&$ $L$sCx.   * * * * lp%)<A <A <As <Ax} <AZbchZi <Ac]<A58<A=F<A <A <A [<A|  =  =  =x}  =(SX/  =! =&/ =  =  = [ =D * *6 *HSM *xPU **$-* * * [*X nr%)69 69 69 69 69[cdi[j 69c]695869=A69 69 69 69p  8E? S UX    ; ;& ;3 ;Xe_ ;WZ ;_c ; ; ; ;, _`CG z * Z Q[ sm19%LP   44% 4% 4D 4 4 4 46&S &C &D & & & &>* *) * * * * * **! ! ! !@.h . . . .NDI ND$ ND ND ND ND`#       !(8, ! ! ! !      X U tH~    X! ! ! ! ! ! s 8     X  x/A d    X,s ,3 ,4 , , , , s t    X U t    Xs t             QC Q QT Q Q Q Q Q Qr.   r   )rC   rD   rN   )r>   	itertoolsr   os.pathrK   r   typingr   r   r   r   r   r	   r
   r   r   r   commonr   ssaeventr   ssastyler   timer   r   r   formatsrC   rD   rN   r   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 j j j j                   & & & & & & & &xQ xQ xQ xQ xQoh' xQ xQ xQv P O O O O O O O O O O Or.   