
    g(C                         d Z ddlmZ ddlZddlmZmZ e edg      dd              Z G d d      Z	 G d	 d
e
      Ze	 dd       Zy)z?Contains everything that can help automate the cuts in MoviePy.    )defaultdictN)convert_parameter_to_secondsuse_clip_fps_by_default
start_timec           	            fd}t        j                  | j                  d|z        dd } |d      }|D cg c]!  }t        j                  | ||            d   # }}|t        j                  |         S c c}w )a  Find the period of a video based on frames correlation.

    Parameters
    ----------

    clip : moviepy.Clip.Clip
      Clip for which the video period will be computed.

    fps : int, optional
      Number of frames per second used computing the period. Higher values will
      produce more accurate periods, but the execution time will be longer.

    start_time : float, optional
      First timeframe used to calculate the period of the clip.

    Examples
    --------

    .. code:: python

        from moviepy import *
        from moviepy.video.tools.cuts import find_video_period

        clip = VideoFileClip("media/chaplin.mp4").subclipped(0, 1).loop(2)
        round(videotools.find_video_period(clip, fps=80), 6)
        1
    c                 B    j                  |       j                         S N)	get_frameflatten)tclips    a/var/www/it7/html/youtubeDownloader/venv/lib/python3.12/site-packages/moviepy/video/tools/cuts.pyframez find_video_period.<locals>.frame)   s    ~~a ((**       Nr   )r   r   )nparangedurationcorrcoefargmax)r   fpsr   r   timingsrefr   corrss   `       r   find_video_periodr   
   su    >+ ii
DMM1s7;AB?G
(C7>?!R[[eAh'-?E?299U#$$ @s   &A:c                   .    e Zd ZdZd Zd Zd Zd Zd Zy)FramesMatchaW  Frames match inside a set of frames.

    Parameters
    ----------

    start_time : float
      Starting time.

    end_time : float
      End time.

    min_distance : float
      Lower bound on the distance between the first and last frames

    max_distance : float
      Upper bound on the distance between the first and last frames
    c                 P    || _         || _        || _        || _        ||z
  | _        y r	   )r   end_timemin_distancemax_distance	time_span)selfr   r   r    r!   s        r   __init__zFramesMatch.__init__E   s,    $ ((!J.r   c                 d    d| j                   | j                  | j                  | j                  fz  S )Nz(%.04f, %.04f, %.04f, %.04f)r   r   r    r!   r#   s    r   __str__zFramesMatch.__str__L   s4    -OOMM	1
 
 	
r   c                 "    | j                         S r	   )r(   r'   s    r   __repr__zFramesMatch.__repr__T   s    ||~r   c                 p    t        | j                  | j                  | j                  | j                  f      S r	   )iterr   r   r    r!   r'   s    r   __iter__zFramesMatch.__iter__W   s/    __dmmT->->@Q@QR
 	
r   c                     |j                   | j                   k(  xrO |j                  | j                  k(  xr4 |j                  | j                  k(  xr |j                  | j                  k(  S r	   r&   )r#   others     r   __eq__zFramesMatch.__eq__\   sb    / 8$--/8""d&7&778 ""d&7&77		
r   N)	__name__
__module____qualname____doc__r$   r(   r*   r-   r0    r   r   r   r   2   s     $/



r   r   c                   \    e Zd ZdZd ZddZd Zd Zed        Z	edd       Z
	 dd	Zd
 Zy)FramesMatcheszFrames matches inside a set of frames.

    You can instantiate it passing a list of FramesMatch objects or
    using the class methods ``load`` and ``from_clip``.

    Parameters
    ----------

    lst : list
      Iterable of FramesMatch objects.
    c                 H    t         j                  | t        |d              y )Nc                     | j                   S r	   )r!   )es    r   <lambda>z(FramesMatches.__init__.<locals>.<lambda>s   s
    ann r   key)listr$   sorted)r#   lsts     r   r$   zFramesMatches.__init__r   s    dF3,DEFr   Nc                 j    |t        |       |z  dz  }|dk(  r| d   S t        | dt        |             S )a  Returns a new instance of FramesMatches object or a FramesMatch
        from the current class instance given different conditions.

        By default returns the first FramesMatch that the current instance
        stores.

        Parameters
        ----------

        n : int, optional
          Number of matches to retrieve from the current FramesMatches object.
          Only has effect when ``percent=None``.

        percent : float, optional
          Percent of the current match to retrieve.

        Returns
        -------

        FramesMatch or FramesMatches : If the number of matches to retrieve is
          greater than 1 returns a FramesMatches object, otherwise a
          FramesMatch.

        Nd   r   r   )lenr7   int)r#   npercents      r   bestzFramesMatches.bestu   sA    2 D	G#c)Aq&tAwCmD3q6N&CCr   c                 ,    t        t        ||             S )a  Return a FramesMatches object obtained by filtering out the
        FramesMatch which do not satistify a condition.

        Parameters
        ----------

        condition : func
          Function which takes a FrameMatch object as parameter and returns a
          bool.

        Examples
        --------
        .. code:: python

            # Only keep the matches corresponding to (> 1 second) sequences.
            new_matches = matches.filter(lambda match: match.time_span > 1)
        )r7   filter)r#   	conditions     r   rI   zFramesMatches.filter   s    $ VIt455r   c                     t        j                  |t        j                  | D cg c]   }t        j                  t        |            " c}      dd       yc c}w )zSave a FramesMatches object to a file.

        Parameters
        ----------

        filename : str
          Path to the file in which will be dumped the FramesMatches object data.
        z%.03f	)fmt	delimiterN)r   savetxtarrayr>   )r#   filenamer:   s      r   savezFramesMatches.save   s@     	

HH6AbhhtAw'67		
6s   %Ac                 v    t        j                  |       }|D cg c]
  }t        |  }}t        |      S c c}w )a  Load a FramesMatches object from a file.

        Parameters
        ----------

        filename : str
          Path to the file to use loading a FramesMatches object.

        Examples
        --------
        >>> matching_frames = FramesMatches.load("somefile")
        )r   loadtxtr   r7   )rQ   arrr:   mfss       r   loadzFramesMatches.load   s9     jj"(+,1{A,,S!! -s   6c           
      H   | j                   | j                  z  dz  fdi fd}g }| j                  d|      D ]  \  }}d|j                         z  }	 |	|	      }
t	        j
                  |
      }t        j                               D ]Y  }||z
  |kD  rj                  |       t        |   d   |z
        |   d   |z   d|   |<   |   |   d	   |kD  |   |   d
<   [ t        j                               }|	|
|d|<   t        |      D ]  \  }}|   |   d
   r |||      }|x|   |   d	<   |   |   d<   ||k\  |   |   d
<   ||dz   d D ]W  }|   |   |   |   }}t        |d   ||d   z         |d<   t        |d	   ||d   z
  |d	   |z
        |d	<   |d	   |kD  sSd|d
<   Y  |D cg c]*  }||k7  r#|   |   d
   s|||   |   d	   |   |   d   f, c}z  } t        |D cg c]
  }t        |  c}      S c c}w c c}w )a  Finds all the frames that look alike in a clip, for instance to make
        a looping GIF.

        Parameters
        ----------

        clip : moviepy.video.VideoClip.VideoClip
          A MoviePy video clip.

        distance_threshold : float
          Distance above which a match is rejected.

        max_duration : float
          Maximal duration (in seconds) between two matching frames.

        fps : int, optional
          Frames per second (default will be ``clip.fps``).

        logger : str, optional
          Either ``"bar"`` for progress bar or ``None`` or any Proglog logger.

        Returns
        -------

        FramesMatches
            All pairs of frames with ``end_time - start_time < max_duration``
            and whose distance is under ``distance_threshold``.

        Examples
        --------

        We find all matching frames in a given video and turn the best match
        with a duration of 1.5 seconds or more into a GIF:

        .. code:: python

            from moviepy import VideoFileClip
            from moviepy.video.tools.cuts import FramesMatches

            clip = VideoFileClip("foo.mp4").resize(width=200)
            matches = FramesMatches.from_clip(
                clip, distance_threshold=10, max_duration=3,  # will take time
            )
            best = matches.filter(lambda m: m.time_span > 1.5).best()
            clip.subclipped(best.start_time, best.end_time).write_gif("foo.gif")
           c                 0    | |z  j                         z  S r	   )sum)F1F2N_pixelss     r   dot_productz,FramesMatches.from_clip.<locals>.dot_product   s    G==?X--r   c                      |    d   |   d         }|    d   |   d   }}t        j                  ||z   d|z  z
        S )Nr   |F|sq   )r   sqrt)t1t2uvuvr_   
frame_dicts        r   distancez)FramesMatches.from_clip.<locals>.distance   sW    Z^G4jnW6MNBb>'*JrN7,CqA771q51r6>**r   T)
with_timeslogger      ?|F|)minmaxro   rejected)r   ra   rn   rp   r   N)whiter_framesr   r   rc   r>   keyspopabsr?   	enumeratero   rp   r7   r   )r   distance_thresholdmax_durationr   rl   rj   matching_framesr   r   
flat_frame	F_norm_sqF_normre   t_Fidistt3t3tt2t3rd   r:   r^   r_   ri   s                        @@@r   	from_clipzFramesMatches.from_clip   s   ` 66DFF?Q&	. 
	+
 ((D(H 1	HAuu}}.J#J
;IWWY'F:??,-  Fl*NN2&  #:b>%#86#AB)"~e4v=)JrN1%
 #2q)%03EE rN1%j1 *+C&09VTJqM"3 /2 b>!$Z02FJJ
2q!%(:b>!+<U+C048J0J
2q!*-a!eg, 	/B !+2q 1:b>"3EC!$SZU1C!DCJ!$SZU1CT%[SWEW!XCJ5z$66*.J	//, $ !GZ^A%6z%B Q
2q)%0*R.2CE2JK  O[1	f G!k1oGHH  Hs   /HHc           	         ||}t        d       }| D ]  \  }}}||   j                  ||g         t        |j                         d       }	g }
d}|	D ]  \  }}||k  r|D cg c]  \  }}}|
 }}}}|D cg c]  \  }}}||k  r|||f }}}}|D cg c]  \  }}}||z
  |kD  r|||f }}}}|sg|D ch c]  \  }}}||kD  r| }}}}|D ch c]  }||z
  dk  s| }}|j	                  |      st        d |D              t        fd|D              \  }}|
j                  t        |||             ||z   } t        |
      S c c}}}w c c}}}w c c}}}w c c}}}w c c}w )av  Select the scenes at which a video clip can be reproduced as the
        smoothest possible way, mainly oriented for the creation of GIF images.

        Parameters
        ----------

        match_threshold : float
          Maximum distance possible between frames. The smaller, the
          better-looping the GIFs are.

        min_time_span : float
          Minimum duration for a scene. Only matches with a duration longer
          than the value passed to this parameters will be extracted.

        nomatch_threshold : float, optional
          Minimum distance possible between frames. If is ``None``, then it is
          chosen equal to ``match_threshold``.

        time_distance : float, optional
          Minimum time offset possible between matches.

        Returns
        -------

        FramesMatches : New instance of the class with the selected scenes.

        Examples
        --------

        .. code:: python

            from pprint import pprint
            from moviepy import *
            from moviepy.video.tools.cuts import FramesMatches

            ch_clip = VideoFileClip("media/chaplin.mp4").subclipped(1, 4)
            mirror_and_clip = [ch_clip.with_effects([vfx.TimeMirror()]), ch_clip]
            clip = concatenate_videoclips(mirror_and_clip)

            result = FramesMatches.from_clip(clip, 10, 3).select_scenes(
                1, 2, nomatch_threshold=0,
            )
            print(result)
            # [(1.0000, 4.0000, 0.0000, 0.0000),
            #  (1.1600, 3.8400, 0.0000, 0.0000),
            #  (1.2800, 3.7200, 0.0000, 0.0000),
            #  (1.4000, 3.6000, 0.0000, 0.0000)]
        c                      g S r	   r5   r5   r   r   r;   z-FramesMatches.select_scenes.<locals>.<lambda>q  s    " r   c                     | d   S Nr   r5   )ks    r   r;   z-FramesMatches.select_scenes.<locals>.<lambda>u  s
    ! r   r<   r   g333333?c              3   (   K   | ]
  \  }}}|  y wr	   r5   ).0endr    r!   s       r   	<genexpr>z.FramesMatches.select_scenes.<locals>.<genexpr>  s     V?sL,cVs   c              3   4   K   | ]  }|d    k(  s|  yw)r   Nr5   )r   r:   r   s     r   r   z.FramesMatches.select_scenes.<locals>.<genexpr>  s       313s   )	r   appendr?   itemsintersectionrp   nextr   r7   )r#   match_thresholdmin_time_spannomatch_thresholdtime_distancedict_startsstartr    r!   starts_endsresult	min_startends_distancesr   endsgreat_matchesgreat_long_matchespoor_matchesshort_matchess                `     r   select_sceneszFramesMatches.select_scenes;  s   f $ /!*-6: 	I2E3l%%sL,&GH	I [..0nE	%0 $	.!E>y AOPP=S,CPDP :H 5S,/1 lL1M  :G" "5S,%K=0 lL1" " & :H 5S,"33 L 
 -1ISS5[S4HSIMI,,];VCUVVC.2 3-3 /+C| MM+eS,MN-II$	.L V$$E Q"
 Js$   )E
 E$
E+
E2
E9,E9c                 ~    | D ]8  \  }}}}d|d|z  d|z  fz  } |j                  ||      j                  |fi | : y)aN  Extract the matching frames represented by the instance from a clip
        and write them as GIFs in a directory, one GIF for each matching frame.

        Parameters
        ----------

        clip : video.VideoClip.VideoClip
          A video clip whose frames scenes you want to obtain as GIF images.

        gif_dir : str
          Directory in which the GIF images will be written.

        kwargs
          Passed as ``clip.write_gif`` optional arguments.

        Examples
        --------

        .. code:: python

            import os
            from pprint import pprint
            from moviepy import *
            from moviepy.video.tools.cuts import FramesMatches

            ch_clip = VideoFileClip("media/chaplin.mp4").subclipped(1, 4)
            clip = concatenate_videoclips([ch_clip.time_mirror(), ch_clip])

            result = FramesMatches.from_clip(clip, 10, 3).select_scenes(
                1, 2, nomatch_threshold=0,
            )

            os.mkdir("foo")
            result.write_gifs(clip, "foo")
            # MoviePy - Building file foo/00000100_00000400.gif with imageio.
            # MoviePy - Building file foo/00000115_00000384.gif with imageio.
            # MoviePy - Building file foo/00000128_00000372.gif with imageio.
            # MoviePy - Building file foo/00000140_00000360.gif with imageio.
        z%s/%08d_%08d.gifrB   N)
subclipped	write_gif)r#   r   gifs_dirkwargsr   r   _names           r   
write_gifszFramesMatches.write_gifs  sX    P !% 	BE31%3;c	(JJD1DOOE3'11$A&A	Br   )r   N)Nbarr   )r1   r2   r3   r4   r$   rG   rI   rR   staticmethodrW   r   r   r   r5   r   r   r7   r7   e   s^    
GD:6(
  " "" pI pIf UVd%L*Br   r7   c                 4   |/| j                  |d|      D cg c]  }|j                          }}t        j                  |t              }| | j
                  }nt        |      d|z  z  }t        t        j                  |            }|j                         }dt        j                  t        j                  |||z  kD              d   z   }	dgt        d|z  |	z        z   |gz   }
t        |
|
dd       D cg c]	  \  }}||f }}}||fS c c}w c c}}w )a+  Detects scenes of a clip based on luminosity changes.

    Note that for large clip this may take some time.

    Returns
    -------

    tuple : cuts, luminosities
      cuts is a series of cuts [(0,t1), (t1,t2),...(...,tf)]
      luminosities are the luminosities computed for each
      frame of the clip.

    Parameters
    ----------

    clip : video.VideoClip.VideoClip, optional
      A video clip. Can be None if a list of luminosities is
      provided instead. If provided, the luminosity of each
      frame of the clip will be computed. If the clip has no
      'fps' attribute, you must provide it.

    luminosities : list, optional
      A list of luminosities, e.g. returned by detect_scenes
      in a previous run.

    luminosity_threshold : float, optional
      Determines a threshold above which the 'luminosity jumps'
      will be considered as scene changes. A scene change is defined
      as a change between 2 consecutive frames that is larger than
      (avg * thr) where avg is the average of the absolute changes
      between consecutive frames.

    logger : str, optional
      Either ``"bar"`` for progress bar or ``None`` or any Proglog logger.

    fps : int, optional
      Frames per second value. Must be provided if you provide
      no clip or a clip without fps attribute.
    Nuint32)r   dtyperl   )r   rm   r   r   )rt   r[   r   rP   floatr   rC   rw   diffmeannonzeror>   zip)r   luminositiesluminosity_thresholdrl   r   fr   luminosity_diffsavgluminosity_jumpsr   rd   re   cutss                 r   detect_scenesr     s%   V !--#Xf-U
AEEG
 
 88L6Lmm,39-277<01



!C	BHHRZZ 03G#3M MNOPQRR  cD#)'7788C5@G#&w#<=RRH=D=!
 >s   D:D)Ng333333?)NN
   r   N)r4   collectionsr   numpyr   moviepy.decoratorsr   r   r   r   r>   r7   r   r5   r   r   <module>r      sh    E #  T |n-#% . #%L0
 0
ffBD fBR MQ; ;r   