
    lj9                       U 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	Z	ddl
mZ ddlmZ ddlmZmZmZ ddlZddlmZ ddlmZmZ dd	lmZ dd
lmZ ddlmZ erddlmZ dgZi a de!d<    G d de          Z" G d dej#        ej$                  Z%d1d2dZ&d3dZ'd4d!Z( G d" de          Z) ed#          Z*d5d(Z+d6d+Z,d6d,Z-d7d/Z.d0Z/dS )8a  
A directive for including Manim videos in a Sphinx document
===========================================================

When rendering the HTML documentation, the ``.. manim::`` directive
implemented here allows to include rendered videos.

Its basic usage that allows processing **inline content**
looks as follows::

    .. manim:: MyScene

        class MyScene(Scene):
            def construct(self):
                ...

It is required to pass the name of the class representing the
scene to be rendered to the directive.

As a second application, the directive can also be used to
render scenes that are defined within doctests, for example::

    .. manim:: DirectiveDoctestExample
        :ref_classes: Dot

        >>> from manim import Create, Dot, RED, Scene
        >>> dot = Dot(color=RED)
        >>> dot.color
        ManimColor('#FC6255')
        >>> class DirectiveDoctestExample(Scene):
        ...     def construct(self):
        ...         self.play(Create(dot))


Options
-------

Options can be passed as follows::

    .. manim:: <Class name>
        :<option name>: <value>

The following configuration options are supported by the
directive:

    hide_source
        If this flag is present without argument,
        the source code is not displayed above the rendered video.

    no_autoplay
        If this flag is present without argument,
        the video will not autoplay.

    quality : {'low', 'medium', 'high', 'fourk'}
        Controls render quality of the video, in analogy to
        the corresponding command line flags.

    save_as_gif
        If this flag is present without argument,
        the scene is rendered as a gif.

    save_last_frame
        If this flag is present without argument,
        an image representing the last frame of the scene will
        be rendered and displayed, instead of a video.

    ref_classes
        A list of classes, separated by spaces, that is
        rendered in a reference block after the source code.

    ref_functions
        A list of functions, separated by spaces,
        that is rendered in a reference block after the source code.

    ref_methods
        A list of methods, separated by spaces,
        that is rendered in a reference block after the source code.

    )annotationsN)Path)timeit)TYPE_CHECKINGAny	TypedDict)nodes)	Directive
directives)
StringList)	QUALITIES)__version__)SphinxManimDirectivezdict[str, int]classnamedictc                  $    e Zd ZU ded<   ded<   dS )SetupMetadataboolparallel_read_safeparallel_write_safeN)__name__
__module____qualname____annotations__     _/home/agentuser/manim-venv/lib/python3.11/site-packages/manim/utils/docbuild/manim_directive.pyr   r   o   s*         r   r   c                      e Zd ZdZdS )SkipManimNodezAuxiliary node class that is used when the ``skip-manim`` tag is present
    or ``.pot`` files are being built.

    Skips rendering the manim directive and outputs a placeholder instead.
    N)r   r   r   __doc__r   r   r   r   r   t   s          	Dr   r    selfnodenodes.ElementnamestrreturnNonec                    |                      ||           t          |d         t          j                  s+|                    dt          j        dd                     d S d S )Nr   
skip-manimzExample Placeholder)visit_admonition
isinstancer	   titleinsert)r"   r#   r%   s      r   visitr/   ~   sd    $%%%d1gu{++ IAu{<1FGGHHHHHI Ir   c                0    |                      |           d S N)depart_admonition)r"   r#   s     r   departr3      s    4     r   option_inputreference_type	list[str]c                D    fd|                                  D             S )a  Reformats a string of space separated class names
    as a list of strings containing valid Sphinx references.

    Tests
    -----

    ::

        >>> process_name_list("Tex TexTemplate", "class")
        [':class:`~.Tex`', ':class:`~.TexTemplate`']
        >>> process_name_list("Scene.play Mobject.rotate", "func")
        [':func:`~.Scene.play`', ':func:`~.Mobject.rotate`']
    c                "    g | ]}d  d| dS ):z:`~.`r   ).0r%   r5   s     r   
<listcomp>z%process_name_list.<locals>.<listcomp>   s-    MMM+++D+++MMMr   )split)r4   r5   s    `r   process_name_listr>      s,     NMMM8J8J8L8LMMMMr   c            
      L    e Zd ZdZdZdZdZeed eed d d d	 d
	ZdZ	ddZ
dS )r   zThe manim directive, rendering videos while building
    the documentation.

    See the module docstring for documentation.
    T   r   c                ,    t          j        | d          S )N)lowmediumhighfourk)r   choiceargs    r   <lambda>zManimDirective.<lambda>   s    z0. 
  
 r   c                "    t          | d          S )Nmodr>   rG   s    r   rI   zManimDirective.<lambda>   s    #4S%#@#@ r   c                "    t          | d          S )NclassrL   rG   s    r   rI   zManimDirective.<lambda>   s    #4S'#B#B r   c                "    t          | d          S )NfuncrL   rG   s    r   rI   zManimDirective.<lambda>   s    %6sF%C%C r   c                "    t          | d          S )NmethrL   rG   s    r   rI   zManimDirective.<lambda>   s    #4S&#A#A r   )	hide_sourceno_autoplayqualitysave_as_gifsave_last_frameref_modulesref_classesref_functionsref_methodsr'   list[nodes.Element]c                  # d| j         j        j        j        j        j        j        v p(| j         j        j        j        j        j        j        dk    }|r| j        d         }t                      }| j         
                    t          d| ddddgd | j        D             z   dd	dd
| dgz   d | j        D             z   dgz             | j        |           |gS ddlm}m} | j        d         }|t"          vrdt"          |<   nt"          |xx         dz  cc<   d| j        v }d| j        v }d| j        v }d| j        v }	|r|	rJ | j                            dg           | j                            dg           z   | j                            dg           z   | j                            dg           z   }
|
rdd                    |
          z   nd}d| j        v r| j        d          d}nd}t*          |         d         }t*          |         d         }t*          |         d         }| j        }|j        }t/          |j        d                    }|                    t4          j                  }|j        d         }t/          t4          j        j        j        |                                          }|                                s|                     d!d!"           ddd#gd$ | j        D             dd	dd
| dd% | j        D             dd}d&                    |          }t/          t4          j                  d'z                                  |_!        d(|_"        d)|_#        | d*t"          |          }t/          d+          |_$        d,|_%        d-|_&        |||||	|	 |d.}|	rd |d/<   |rd0|d/<   tO          | j                  }|d         (                    d1          rd2 |D             }d3g|| d4#	  ||          5  tS          #fd5d6          }|*                    d7          }|*                    d8          }d d d            n# 1 swxY w Y   n%# tV          $ r}tY          d9|           |d }~ww xY wt[          ||| j         j        j        j        j.                   |s2|	s0| d:}||z  } t/          ||          }!t_          j0        | |!           n)|r| d;}||z  } n|	r| d<}||z  } ntc          d=          te          j3        th                    5                    ||6                                |t/          |                               t4          j                  7                                |||	|||>
  
        }"|8                    |"9                    d&          |j        d          ?           g S )@Nr*   gettextr   zPlaceholder block for ``z``.r!   z.. code-block:: pythonc                    g | ]}d |z   S     r   r;   lines     r   r<   z&ManimDirective.run.<locals>.<listcomp>       >>>v}>>>r   z.. raw:: htmlz1    <pre data-manim-binder data-manim-classname="z">c                    g | ]}d |z   S r`   r   rb   s     r   r<   z&ManimDirective.run.<locals>.<listcomp>   rd   r   z
    </pre>)config
tempconfigr@   rS   rT   rV   rW   rX   rY   rZ   r[   zReferences:  rU   _qualityexample_quality
frame_ratepixel_heightpixel_widthsourceT)parentsexist_okz    from manim import *
c              3      K   | ]	}d |z   V  
dS ra   Nr   rb   s     r   	<genexpr>z%ManimDirective.run.<locals>.<genexpr>  &      55ftm555555r   c              3      K   | ]	}d |z   V  
dS rr   r   rb   s     r   rs   z%ManimDirective.run.<locals>.<genexpr>	  rt   r   
mediaz{media_dir}/imagesz{media_dir}/videos/{quality}-_staticnoneWARNING)rk   rT   rl   rm   rW   write_to_movieoutput_fileformatgif>>> c                L    g | ]!}|                     d           |dd         "S ))r   z...    N)
startswithrb   s     r   r<   z&ManimDirective.run.<locals>.<listcomp>'  sB       !$//BR2S2SQRR  r   zfrom manim import *z().render()c                 b    t          d                               t                                S )Nrv   )execjoinglobals)codes   r   rI   z$ManimDirective.run.<locals>.<lambda>3  s    $tyy		*J*J r   )number	video_dir
images_dirzError while rendering example z.mp4z.gifz.pngz-Invalid combination of render flags received.)
clsnameclsname_lowercaserS   filesrc_relrT   r}   rW   rV   source_block	ref_block)rn   ):statedocumentsettingsenvappbuildertagsr%   	argumentsr   nested_parser   contentcontent_offsetmanimrf   rg   r   optionsgetr   r   state_machiner   
attributesrelative_tosetupconfdirro   outdirabsoluteexistsmkdir	media_dirr   r   
assets_dirprogress_bar	verbositylistr   r   get_dir	ExceptionRuntimeError_write_rendering_statsdocnameshutilcopyfile
ValueErrorjinja2TemplateTEMPLATErenderloweras_posixinsert_inputr=   )$r"   should_skipr   r#   rf   rg   rS   rT   rV   rW   ref_contentr   rU   rk   rl   rm   r   r   source_file_namesource_rel_namesource_rel_dirdest_dirsource_block_inr   r}   example_config	user_coderun_timer   r   efilenamefilesrcdestfilerendered_templater   s$                                      @r   runzManimDirective.run   s`    DJ/8<@HMM Nz"+/3;@IM 	  	nQ'G ??DJ##?7???0	 ?>>>>? 'WGWWW	 ?>>>>? $n% " #'  * 6M,,,,,,,, .#-''%&M'""'"""a'"""#t|3#t|3#t|3+t|;4O444 L]B//l}b112l334 l}b112 	 ?JQNSXXk%:%:::r	$$i0:::GG'Gw'5
 ).9(7* ) 3H =>>*66u}EE(03	)0.AAJJLL   	8NN4$N777 %'
 65555	

 
 
 
 LKKK
 65555
 
 
 yy11 //'9CCEE09 ;;=#9;; OO$$ %&(&."11&
 
  	,'+N8$ 	-',N8$&&	Q<""6** 	 %.  I
 "

 ###
	RN++ : :!"J"J"J"JSTUUU"NN;77	#^^L99
: : : : : : : : : : : : : : :  	R 	R 	RIIIJJPQQ	R 	J(,4	
 	
 	
  	N 	N%+++H(*GHh//HOGX.... 	N%+++H(*GG 	N%+++H 8+GGLMMM"OH55<<%mmoo#W11%-@@IIKK##+#% = 
 
 	""##D))&x0 	# 	
 	
 	

 	s<   8Q ?QQ QQ QQ 
Q<$Q77Q<N)r'   r\   )r   r   r   r    has_contentrequired_argumentsoptional_argumentsr   option_specfinal_argument_whitespacer   r   r   r   r   r      s          K
 
 @@BBCCAA K !%i i i i i ir   z../rendering_times.csv
scene_namer   float	file_namec                    t                               d          5 }t          j        |                              t          j        dd|          | |dg           d d d            d S # 1 swxY w Y   d S )Naz^(reference\/)|(manim\.)r!   .3f)rendering_times_file_pathopencsvwriterwriterowresub)r   r   r   files       r   r   r   d  s    	"	'	'	,	, 

4!!2B	BB!!	
 	
 	

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
s   AA))A-0A-args
tuple[Any]c            
        t                                           rt                                           5 }t          t	          j        |                    }d d d            n# 1 swxY w Y   t          |          dk    rt          j                     t          d           d |D             }t          d |D                       }t          j        |d           D ]\  }}|                    |dz   d          }t          |          }t          |          dk    r?|d         }t          | |d	                             d
d           d|d                     t          d |D                       }t          | |d                    d
d           dt          |           d           |D ];}t          d|z   d|d	                             d
           d|d                     <t          d           d S d S )Nr   z%
Rendering Summary
-----------------
c                    g | ]}||S r   r   r;   rows     r   r<   z(_log_rendering_times.<locals>.<listcomp>y  s    +++s++++r   c              3  @   K   | ]}t          |d                    V  dS )r   N)lenr   s     r   rs   z'_log_rendering_times.<locals>.<genexpr>{  s,      ::cc#a&kk::::::r   c                    | d         S )Nr   r   )r   s    r   rI   z&_log_rendering_times.<locals>.<lambda>|  s
    A r   )keyr@   .      zs c              3  @   K   | ]}t          |d                    V  dS )r   N)r   r   s     r   rs   z'_log_rendering_times.<locals>.<genexpr>  s,      ::S5Q==::::::r   r   zs  => z	 EXAMPLESrh   r!   )r   r   r   r   r   readerr   sysexitprintmaxitgroupbyljustrjustsum)	r   r   datamax_file_lengthr   
group_itergroupr   time_sums	            r   _log_rendering_timesr   o  s]    '')) &++-- 	*
4(())D	* 	* 	* 	* 	* 	* 	* 	* 	* 	* 	* 	* 	* 	* 	*t99>>HJJJ8999 ,+t+++::T:::::!z$4F4FGGG 	N 	NOC))Oa/55C$$E5zzQAh>c!fll1c22>>c!f>>???::E:::::HT8))//377TTs5zzTTT    N N.LLQaLLCFLLMMMMNb					3 s   "A""A&)A&c                 n    t                                           rt                                            d S d S r1   )r   r   unlink)r   s    r   _delete_rendering_timesr     s8     '')) +!((*****+ +r   r   r   c                   |                      t          t          t          fd d f           | t          _        | j        t          _        | j        t          _        |                     dt                     | 
                    dt                     | 
                    dt                     |                     d           |                     d t          j        dt            d	                                          
           ddd}|S )Nc                    d S r1   r   r   bs     r   rI   zsetup.<locals>.<lambda>  s    D r   c                    d S r1   r   r  s     r   rI   zsetup.<locals>.<lambda>  s    t r   )htmllatexr   zbuilder-initedzbuild-finishedzmanim-binder.min.jsz2                window.initManimBinder({branch: "vz"})
            )bodyFT)r   r   )add_noder   r/   r3   r   r   rf   r   add_directiver   connectr   r   add_js_filetextwrapdedentmanim_versionstrip)r   metadatas     r   r   r     s   LLV_  "3"34     EI:ELKEMg~...KK "9:::KK "6777OO)***OO_4A  
 
 %''     $# H Or   u  
{% if not hide_source %}
.. raw:: html

    <div id="{{ clsname_lowercase }}" class="admonition admonition-manim-example">
    <p class="admonition-title">Example: {{ clsname }} <a class="headerlink" href="#{{ clsname_lowercase }}">¶</a></p>

{% endif %}

{% if not (save_as_gif or save_last_frame) %}
.. raw:: html

    <video
        class="manim-video"
        controls
        loop
        {{ '' if no_autoplay else 'autoplay' }}
        src="./{{ output_file }}.mp4">
    </video>

{% elif save_as_gif %}
.. image:: /{{ filesrc_rel }}
    :align: center

{% elif save_last_frame %}
.. image:: /{{ filesrc_rel }}
    :align: center

{% endif %}
{% if not hide_source %}
{{ source_block }}

{{ ref_block }}

.. raw:: html

    </div>

{% endif %}
)r!   )r"   r   r#   r$   r%   r&   r'   r(   )r"   r   r#   r$   r'   r(   )r4   r&   r5   r&   r'   r6   )r   r&   r   r   r   r&   r'   r(   )r   r   r'   r(   )r   r   r'   r   )0r    
__future__r   r   	itertoolsr   r   r   r   r  pathlibr   r   typingr   r   r   r   docutilsr	   docutils.parsers.rstr
   r   docutils.statemachiner   r   r   r   r  sphinx.applicationr   __all__r   r   r   
AdmonitionElementr   r/   r3   r>   r   r   r   r   r   r   r   r   r   r   <module>r     s  N N N` # " " " " " 



     				  



              0 0 0 0 0 0 0 0 0 0        6 6 6 6 6 6 6 6 , , , , , ,       . . . . . . *)))))) 
 !# " " " "    I   
	 	 	 	 	E$em 	 	 	I I I I I! ! ! !
N N N N"C C C C CY C C CL !D!9:: 
 
 
 
   :+ + + +
   B'r   