MostlyK commited on
Commit
d970572
·
1 Parent(s): 9c381cf

Manimator in HF

Browse files
.dockerignore ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .git
2
+ .gitignore
3
+ .gitattributes
4
+
5
+ .env*
6
+ src/.env
7
+
8
+ __pycache__/
9
+ *.pyc
10
+ *.pyo
11
+ *.pyd
12
+ venv/
13
+ .venv/
14
+
15
+ .vscode/
16
+ .idea/
17
+ *.DS_Store
18
+
19
+ media/*
20
+ !media/.keep # Optional: keep directory structure if needed
21
+ src/media/*
22
+ *.mp4
23
+ *.wav
24
+ *.svg
25
+ *.log
26
+ *.tex
27
+ generated_video.py
28
+ extended_video.mp4
29
+ final_output.mp4
30
+ output_*.wav
31
+
32
+
33
+ # Conda environment file (using requirements.txt)
34
+ environment.yml
35
+
36
+ src/tests/
37
+
38
+ LICENSE
39
+ README.md
40
+ packages.txt
.gitignore ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ video-gen
2
+ src/media/*
3
+ src/__pycache__/*
4
+ src/services/__pycache__/*
5
+ src/api/__pycache__/*
6
+ src/tests/__pycache__/*
7
+ .env
8
+ media/*
9
+ __pycache__/*
10
+ Manimator/*
11
+ Manimator/
12
+
Dockerfile ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.10-slim
2
+
3
+ ENV DEBIAN_FRONTEND=noninteractive
4
+ ENV PYTHONUNBUFFERED=1
5
+
6
+ # (ffmpeg, latexmk, texlive-full, libcairo2-dev, pkg-config)
7
+ RUN apt-get update && apt-get install -y --no-install-recommends \
8
+ ffmpeg \
9
+ latexmk \
10
+ texlive-full \
11
+ libcairo2-dev \
12
+ pkg-config \
13
+ libpango1.0-dev \
14
+ curl \
15
+ build-essential \
16
+ && apt-get clean \
17
+ && rm -rf /var/lib/apt/lists/*
18
+
19
+ WORKDIR /app
20
+
21
+ COPY requirements.txt .
22
+
23
+ RUN pip install --no-cache-dir --upgrade pip && \
24
+ pip install --no-cache-dir -r requirements.txt
25
+
26
+ COPY src/ ./src/
27
+
28
+ RUN mkdir -p media/videos/generated_video/1080p60 media/Tex media/texts media/images
29
+
30
+ EXPOSE 8501
31
+ #streamlit checks
32
+ HEALTHCHECK --interval=15s --timeout=5s --start-period=30s \
33
+ CMD curl --fail http://localhost:8501/_stcore/health || exit 1
34
+
35
+ # Pass GEMINI_API_KEY as an environment variable during `docker run`
36
+ # Example: docker run -p 8501:8501 -e GEMINI_API_KEY='your_api_key' manimator-image
37
+ CMD ["streamlit", "run", "src/app.py", "--server.port=8501", "--server.address=0.0.0.0"]
LICENSE ADDED
@@ -0,0 +1,674 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ GNU GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+ Preamble
9
+
10
+ The GNU General Public License is a free, copyleft license for
11
+ software and other kinds of works.
12
+
13
+ The licenses for most software and other practical works are designed
14
+ to take away your freedom to share and change the works. By contrast,
15
+ the GNU General Public License is intended to guarantee your freedom to
16
+ share and change all versions of a program--to make sure it remains free
17
+ software for all its users. We, the Free Software Foundation, use the
18
+ GNU General Public License for most of our software; it applies also to
19
+ any other work released this way by its authors. You can apply it to
20
+ your programs, too.
21
+
22
+ When we speak of free software, we are referring to freedom, not
23
+ price. Our General Public Licenses are designed to make sure that you
24
+ have the freedom to distribute copies of free software (and charge for
25
+ them if you wish), that you receive source code or can get it if you
26
+ want it, that you can change the software or use pieces of it in new
27
+ free programs, and that you know you can do these things.
28
+
29
+ To protect your rights, we need to prevent others from denying you
30
+ these rights or asking you to surrender the rights. Therefore, you have
31
+ certain responsibilities if you distribute copies of the software, or if
32
+ you modify it: responsibilities to respect the freedom of others.
33
+
34
+ For example, if you distribute copies of such a program, whether
35
+ gratis or for a fee, you must pass on to the recipients the same
36
+ freedoms that you received. You must make sure that they, too, receive
37
+ or can get the source code. And you must show them these terms so they
38
+ know their rights.
39
+
40
+ Developers that use the GNU GPL protect your rights with two steps:
41
+ (1) assert copyright on the software, and (2) offer you this License
42
+ giving you legal permission to copy, distribute and/or modify it.
43
+
44
+ For the developers' and authors' protection, the GPL clearly explains
45
+ that there is no warranty for this free software. For both users' and
46
+ authors' sake, the GPL requires that modified versions be marked as
47
+ changed, so that their problems will not be attributed erroneously to
48
+ authors of previous versions.
49
+
50
+ Some devices are designed to deny users access to install or run
51
+ modified versions of the software inside them, although the manufacturer
52
+ can do so. This is fundamentally incompatible with the aim of
53
+ protecting users' freedom to change the software. The systematic
54
+ pattern of such abuse occurs in the area of products for individuals to
55
+ use, which is precisely where it is most unacceptable. Therefore, we
56
+ have designed this version of the GPL to prohibit the practice for those
57
+ products. If such problems arise substantially in other domains, we
58
+ stand ready to extend this provision to those domains in future versions
59
+ of the GPL, as needed to protect the freedom of users.
60
+
61
+ Finally, every program is threatened constantly by software patents.
62
+ States should not allow patents to restrict development and use of
63
+ software on general-purpose computers, but in those that do, we wish to
64
+ avoid the special danger that patents applied to a free program could
65
+ make it effectively proprietary. To prevent this, the GPL assures that
66
+ patents cannot be used to render the program non-free.
67
+
68
+ The precise terms and conditions for copying, distribution and
69
+ modification follow.
70
+
71
+ TERMS AND CONDITIONS
72
+
73
+ 0. Definitions.
74
+
75
+ "This License" refers to version 3 of the GNU General Public License.
76
+
77
+ "Copyright" also means copyright-like laws that apply to other kinds of
78
+ works, such as semiconductor masks.
79
+
80
+ "The Program" refers to any copyrightable work licensed under this
81
+ License. Each licensee is addressed as "you". "Licensees" and
82
+ "recipients" may be individuals or organizations.
83
+
84
+ To "modify" a work means to copy from or adapt all or part of the work
85
+ in a fashion requiring copyright permission, other than the making of an
86
+ exact copy. The resulting work is called a "modified version" of the
87
+ earlier work or a work "based on" the earlier work.
88
+
89
+ A "covered work" means either the unmodified Program or a work based
90
+ on the Program.
91
+
92
+ To "propagate" a work means to do anything with it that, without
93
+ permission, would make you directly or secondarily liable for
94
+ infringement under applicable copyright law, except executing it on a
95
+ computer or modifying a private copy. Propagation includes copying,
96
+ distribution (with or without modification), making available to the
97
+ public, and in some countries other activities as well.
98
+
99
+ To "convey" a work means any kind of propagation that enables other
100
+ parties to make or receive copies. Mere interaction with a user through
101
+ a computer network, with no transfer of a copy, is not conveying.
102
+
103
+ An interactive user interface displays "Appropriate Legal Notices"
104
+ to the extent that it includes a convenient and prominently visible
105
+ feature that (1) displays an appropriate copyright notice, and (2)
106
+ tells the user that there is no warranty for the work (except to the
107
+ extent that warranties are provided), that licensees may convey the
108
+ work under this License, and how to view a copy of this License. If
109
+ the interface presents a list of user commands or options, such as a
110
+ menu, a prominent item in the list meets this criterion.
111
+
112
+ 1. Source Code.
113
+
114
+ The "source code" for a work means the preferred form of the work
115
+ for making modifications to it. "Object code" means any non-source
116
+ form of a work.
117
+
118
+ A "Standard Interface" means an interface that either is an official
119
+ standard defined by a recognized standards body, or, in the case of
120
+ interfaces specified for a particular programming language, one that
121
+ is widely used among developers working in that language.
122
+
123
+ The "System Libraries" of an executable work include anything, other
124
+ than the work as a whole, that (a) is included in the normal form of
125
+ packaging a Major Component, but which is not part of that Major
126
+ Component, and (b) serves only to enable use of the work with that
127
+ Major Component, or to implement a Standard Interface for which an
128
+ implementation is available to the public in source code form. A
129
+ "Major Component", in this context, means a major essential component
130
+ (kernel, window system, and so on) of the specific operating system
131
+ (if any) on which the executable work runs, or a compiler used to
132
+ produce the work, or an object code interpreter used to run it.
133
+
134
+ The "Corresponding Source" for a work in object code form means all
135
+ the source code needed to generate, install, and (for an executable
136
+ work) run the object code and to modify the work, including scripts to
137
+ control those activities. However, it does not include the work's
138
+ System Libraries, or general-purpose tools or generally available free
139
+ programs which are used unmodified in performing those activities but
140
+ which are not part of the work. For example, Corresponding Source
141
+ includes interface definition files associated with source files for
142
+ the work, and the source code for shared libraries and dynamically
143
+ linked subprograms that the work is specifically designed to require,
144
+ such as by intimate data communication or control flow between those
145
+ subprograms and other parts of the work.
146
+
147
+ The Corresponding Source need not include anything that users
148
+ can regenerate automatically from other parts of the Corresponding
149
+ Source.
150
+
151
+ The Corresponding Source for a work in source code form is that
152
+ same work.
153
+
154
+ 2. Basic Permissions.
155
+
156
+ All rights granted under this License are granted for the term of
157
+ copyright on the Program, and are irrevocable provided the stated
158
+ conditions are met. This License explicitly affirms your unlimited
159
+ permission to run the unmodified Program. The output from running a
160
+ covered work is covered by this License only if the output, given its
161
+ content, constitutes a covered work. This License acknowledges your
162
+ rights of fair use or other equivalent, as provided by copyright law.
163
+
164
+ You may make, run and propagate covered works that you do not
165
+ convey, without conditions so long as your license otherwise remains
166
+ in force. You may convey covered works to others for the sole purpose
167
+ of having them make modifications exclusively for you, or provide you
168
+ with facilities for running those works, provided that you comply with
169
+ the terms of this License in conveying all material for which you do
170
+ not control copyright. Those thus making or running the covered works
171
+ for you must do so exclusively on your behalf, under your direction
172
+ and control, on terms that prohibit them from making any copies of
173
+ your copyrighted material outside their relationship with you.
174
+
175
+ Conveying under any other circumstances is permitted solely under
176
+ the conditions stated below. Sublicensing is not allowed; section 10
177
+ makes it unnecessary.
178
+
179
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180
+
181
+ No covered work shall be deemed part of an effective technological
182
+ measure under any applicable law fulfilling obligations under article
183
+ 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184
+ similar laws prohibiting or restricting circumvention of such
185
+ measures.
186
+
187
+ When you convey a covered work, you waive any legal power to forbid
188
+ circumvention of technological measures to the extent such circumvention
189
+ is effected by exercising rights under this License with respect to
190
+ the covered work, and you disclaim any intention to limit operation or
191
+ modification of the work as a means of enforcing, against the work's
192
+ users, your or third parties' legal rights to forbid circumvention of
193
+ technological measures.
194
+
195
+ 4. Conveying Verbatim Copies.
196
+
197
+ You may convey verbatim copies of the Program's source code as you
198
+ receive it, in any medium, provided that you conspicuously and
199
+ appropriately publish on each copy an appropriate copyright notice;
200
+ keep intact all notices stating that this License and any
201
+ non-permissive terms added in accord with section 7 apply to the code;
202
+ keep intact all notices of the absence of any warranty; and give all
203
+ recipients a copy of this License along with the Program.
204
+
205
+ You may charge any price or no price for each copy that you convey,
206
+ and you may offer support or warranty protection for a fee.
207
+
208
+ 5. Conveying Modified Source Versions.
209
+
210
+ You may convey a work based on the Program, or the modifications to
211
+ produce it from the Program, in the form of source code under the
212
+ terms of section 4, provided that you also meet all of these conditions:
213
+
214
+ a) The work must carry prominent notices stating that you modified
215
+ it, and giving a relevant date.
216
+
217
+ b) The work must carry prominent notices stating that it is
218
+ released under this License and any conditions added under section
219
+ 7. This requirement modifies the requirement in section 4 to
220
+ "keep intact all notices".
221
+
222
+ c) You must license the entire work, as a whole, under this
223
+ License to anyone who comes into possession of a copy. This
224
+ License will therefore apply, along with any applicable section 7
225
+ additional terms, to the whole of the work, and all its parts,
226
+ regardless of how they are packaged. This License gives no
227
+ permission to license the work in any other way, but it does not
228
+ invalidate such permission if you have separately received it.
229
+
230
+ d) If the work has interactive user interfaces, each must display
231
+ Appropriate Legal Notices; however, if the Program has interactive
232
+ interfaces that do not display Appropriate Legal Notices, your
233
+ work need not make them do so.
234
+
235
+ A compilation of a covered work with other separate and independent
236
+ works, which are not by their nature extensions of the covered work,
237
+ and which are not combined with it such as to form a larger program,
238
+ in or on a volume of a storage or distribution medium, is called an
239
+ "aggregate" if the compilation and its resulting copyright are not
240
+ used to limit the access or legal rights of the compilation's users
241
+ beyond what the individual works permit. Inclusion of a covered work
242
+ in an aggregate does not cause this License to apply to the other
243
+ parts of the aggregate.
244
+
245
+ 6. Conveying Non-Source Forms.
246
+
247
+ You may convey a covered work in object code form under the terms
248
+ of sections 4 and 5, provided that you also convey the
249
+ machine-readable Corresponding Source under the terms of this License,
250
+ in one of these ways:
251
+
252
+ a) Convey the object code in, or embodied in, a physical product
253
+ (including a physical distribution medium), accompanied by the
254
+ Corresponding Source fixed on a durable physical medium
255
+ customarily used for software interchange.
256
+
257
+ b) Convey the object code in, or embodied in, a physical product
258
+ (including a physical distribution medium), accompanied by a
259
+ written offer, valid for at least three years and valid for as
260
+ long as you offer spare parts or customer support for that product
261
+ model, to give anyone who possesses the object code either (1) a
262
+ copy of the Corresponding Source for all the software in the
263
+ product that is covered by this License, on a durable physical
264
+ medium customarily used for software interchange, for a price no
265
+ more than your reasonable cost of physically performing this
266
+ conveying of source, or (2) access to copy the
267
+ Corresponding Source from a network server at no charge.
268
+
269
+ c) Convey individual copies of the object code with a copy of the
270
+ written offer to provide the Corresponding Source. This
271
+ alternative is allowed only occasionally and noncommercially, and
272
+ only if you received the object code with such an offer, in accord
273
+ with subsection 6b.
274
+
275
+ d) Convey the object code by offering access from a designated
276
+ place (gratis or for a charge), and offer equivalent access to the
277
+ Corresponding Source in the same way through the same place at no
278
+ further charge. You need not require recipients to copy the
279
+ Corresponding Source along with the object code. If the place to
280
+ copy the object code is a network server, the Corresponding Source
281
+ may be on a different server (operated by you or a third party)
282
+ that supports equivalent copying facilities, provided you maintain
283
+ clear directions next to the object code saying where to find the
284
+ Corresponding Source. Regardless of what server hosts the
285
+ Corresponding Source, you remain obligated to ensure that it is
286
+ available for as long as needed to satisfy these requirements.
287
+
288
+ e) Convey the object code using peer-to-peer transmission, provided
289
+ you inform other peers where the object code and Corresponding
290
+ Source of the work are being offered to the general public at no
291
+ charge under subsection 6d.
292
+
293
+ A separable portion of the object code, whose source code is excluded
294
+ from the Corresponding Source as a System Library, need not be
295
+ included in conveying the object code work.
296
+
297
+ A "User Product" is either (1) a "consumer product", which means any
298
+ tangible personal property which is normally used for personal, family,
299
+ or household purposes, or (2) anything designed or sold for incorporation
300
+ into a dwelling. In determining whether a product is a consumer product,
301
+ doubtful cases shall be resolved in favor of coverage. For a particular
302
+ product received by a particular user, "normally used" refers to a
303
+ typical or common use of that class of product, regardless of the status
304
+ of the particular user or of the way in which the particular user
305
+ actually uses, or expects or is expected to use, the product. A product
306
+ is a consumer product regardless of whether the product has substantial
307
+ commercial, industrial or non-consumer uses, unless such uses represent
308
+ the only significant mode of use of the product.
309
+
310
+ "Installation Information" for a User Product means any methods,
311
+ procedures, authorization keys, or other information required to install
312
+ and execute modified versions of a covered work in that User Product from
313
+ a modified version of its Corresponding Source. The information must
314
+ suffice to ensure that the continued functioning of the modified object
315
+ code is in no case prevented or interfered with solely because
316
+ modification has been made.
317
+
318
+ If you convey an object code work under this section in, or with, or
319
+ specifically for use in, a User Product, and the conveying occurs as
320
+ part of a transaction in which the right of possession and use of the
321
+ User Product is transferred to the recipient in perpetuity or for a
322
+ fixed term (regardless of how the transaction is characterized), the
323
+ Corresponding Source conveyed under this section must be accompanied
324
+ by the Installation Information. But this requirement does not apply
325
+ if neither you nor any third party retains the ability to install
326
+ modified object code on the User Product (for example, the work has
327
+ been installed in ROM).
328
+
329
+ The requirement to provide Installation Information does not include a
330
+ requirement to continue to provide support service, warranty, or updates
331
+ for a work that has been modified or installed by the recipient, or for
332
+ the User Product in which it has been modified or installed. Access to a
333
+ network may be denied when the modification itself materially and
334
+ adversely affects the operation of the network or violates the rules and
335
+ protocols for communication across the network.
336
+
337
+ Corresponding Source conveyed, and Installation Information provided,
338
+ in accord with this section must be in a format that is publicly
339
+ documented (and with an implementation available to the public in
340
+ source code form), and must require no special password or key for
341
+ unpacking, reading or copying.
342
+
343
+ 7. Additional Terms.
344
+
345
+ "Additional permissions" are terms that supplement the terms of this
346
+ License by making exceptions from one or more of its conditions.
347
+ Additional permissions that are applicable to the entire Program shall
348
+ be treated as though they were included in this License, to the extent
349
+ that they are valid under applicable law. If additional permissions
350
+ apply only to part of the Program, that part may be used separately
351
+ under those permissions, but the entire Program remains governed by
352
+ this License without regard to the additional permissions.
353
+
354
+ When you convey a copy of a covered work, you may at your option
355
+ remove any additional permissions from that copy, or from any part of
356
+ it. (Additional permissions may be written to require their own
357
+ removal in certain cases when you modify the work.) You may place
358
+ additional permissions on material, added by you to a covered work,
359
+ for which you have or can give appropriate copyright permission.
360
+
361
+ Notwithstanding any other provision of this License, for material you
362
+ add to a covered work, you may (if authorized by the copyright holders of
363
+ that material) supplement the terms of this License with terms:
364
+
365
+ a) Disclaiming warranty or limiting liability differently from the
366
+ terms of sections 15 and 16 of this License; or
367
+
368
+ b) Requiring preservation of specified reasonable legal notices or
369
+ author attributions in that material or in the Appropriate Legal
370
+ Notices displayed by works containing it; or
371
+
372
+ c) Prohibiting misrepresentation of the origin of that material, or
373
+ requiring that modified versions of such material be marked in
374
+ reasonable ways as different from the original version; or
375
+
376
+ d) Limiting the use for publicity purposes of names of licensors or
377
+ authors of the material; or
378
+
379
+ e) Declining to grant rights under trademark law for use of some
380
+ trade names, trademarks, or service marks; or
381
+
382
+ f) Requiring indemnification of licensors and authors of that
383
+ material by anyone who conveys the material (or modified versions of
384
+ it) with contractual assumptions of liability to the recipient, for
385
+ any liability that these contractual assumptions directly impose on
386
+ those licensors and authors.
387
+
388
+ All other non-permissive additional terms are considered "further
389
+ restrictions" within the meaning of section 10. If the Program as you
390
+ received it, or any part of it, contains a notice stating that it is
391
+ governed by this License along with a term that is a further
392
+ restriction, you may remove that term. If a license document contains
393
+ a further restriction but permits relicensing or conveying under this
394
+ License, you may add to a covered work material governed by the terms
395
+ of that license document, provided that the further restriction does
396
+ not survive such relicensing or conveying.
397
+
398
+ If you add terms to a covered work in accord with this section, you
399
+ must place, in the relevant source files, a statement of the
400
+ additional terms that apply to those files, or a notice indicating
401
+ where to find the applicable terms.
402
+
403
+ Additional terms, permissive or non-permissive, may be stated in the
404
+ form of a separately written license, or stated as exceptions;
405
+ the above requirements apply either way.
406
+
407
+ 8. Termination.
408
+
409
+ You may not propagate or modify a covered work except as expressly
410
+ provided under this License. Any attempt otherwise to propagate or
411
+ modify it is void, and will automatically terminate your rights under
412
+ this License (including any patent licenses granted under the third
413
+ paragraph of section 11).
414
+
415
+ However, if you cease all violation of this License, then your
416
+ license from a particular copyright holder is reinstated (a)
417
+ provisionally, unless and until the copyright holder explicitly and
418
+ finally terminates your license, and (b) permanently, if the copyright
419
+ holder fails to notify you of the violation by some reasonable means
420
+ prior to 60 days after the cessation.
421
+
422
+ Moreover, your license from a particular copyright holder is
423
+ reinstated permanently if the copyright holder notifies you of the
424
+ violation by some reasonable means, this is the first time you have
425
+ received notice of violation of this License (for any work) from that
426
+ copyright holder, and you cure the violation prior to 30 days after
427
+ your receipt of the notice.
428
+
429
+ Termination of your rights under this section does not terminate the
430
+ licenses of parties who have received copies or rights from you under
431
+ this License. If your rights have been terminated and not permanently
432
+ reinstated, you do not qualify to receive new licenses for the same
433
+ material under section 10.
434
+
435
+ 9. Acceptance Not Required for Having Copies.
436
+
437
+ You are not required to accept this License in order to receive or
438
+ run a copy of the Program. Ancillary propagation of a covered work
439
+ occurring solely as a consequence of using peer-to-peer transmission
440
+ to receive a copy likewise does not require acceptance. However,
441
+ nothing other than this License grants you permission to propagate or
442
+ modify any covered work. These actions infringe copyright if you do
443
+ not accept this License. Therefore, by modifying or propagating a
444
+ covered work, you indicate your acceptance of this License to do so.
445
+
446
+ 10. Automatic Licensing of Downstream Recipients.
447
+
448
+ Each time you convey a covered work, the recipient automatically
449
+ receives a license from the original licensors, to run, modify and
450
+ propagate that work, subject to this License. You are not responsible
451
+ for enforcing compliance by third parties with this License.
452
+
453
+ An "entity transaction" is a transaction transferring control of an
454
+ organization, or substantially all assets of one, or subdividing an
455
+ organization, or merging organizations. If propagation of a covered
456
+ work results from an entity transaction, each party to that
457
+ transaction who receives a copy of the work also receives whatever
458
+ licenses to the work the party's predecessor in interest had or could
459
+ give under the previous paragraph, plus a right to possession of the
460
+ Corresponding Source of the work from the predecessor in interest, if
461
+ the predecessor has it or can get it with reasonable efforts.
462
+
463
+ You may not impose any further restrictions on the exercise of the
464
+ rights granted or affirmed under this License. For example, you may
465
+ not impose a license fee, royalty, or other charge for exercise of
466
+ rights granted under this License, and you may not initiate litigation
467
+ (including a cross-claim or counterclaim in a lawsuit) alleging that
468
+ any patent claim is infringed by making, using, selling, offering for
469
+ sale, or importing the Program or any portion of it.
470
+
471
+ 11. Patents.
472
+
473
+ A "contributor" is a copyright holder who authorizes use under this
474
+ License of the Program or a work on which the Program is based. The
475
+ work thus licensed is called the contributor's "contributor version".
476
+
477
+ A contributor's "essential patent claims" are all patent claims
478
+ owned or controlled by the contributor, whether already acquired or
479
+ hereafter acquired, that would be infringed by some manner, permitted
480
+ by this License, of making, using, or selling its contributor version,
481
+ but do not include claims that would be infringed only as a
482
+ consequence of further modification of the contributor version. For
483
+ purposes of this definition, "control" includes the right to grant
484
+ patent sublicenses in a manner consistent with the requirements of
485
+ this License.
486
+
487
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
488
+ patent license under the contributor's essential patent claims, to
489
+ make, use, sell, offer for sale, import and otherwise run, modify and
490
+ propagate the contents of its contributor version.
491
+
492
+ In the following three paragraphs, a "patent license" is any express
493
+ agreement or commitment, however denominated, not to enforce a patent
494
+ (such as an express permission to practice a patent or covenant not to
495
+ sue for patent infringement). To "grant" such a patent license to a
496
+ party means to make such an agreement or commitment not to enforce a
497
+ patent against the party.
498
+
499
+ If you convey a covered work, knowingly relying on a patent license,
500
+ and the Corresponding Source of the work is not available for anyone
501
+ to copy, free of charge and under the terms of this License, through a
502
+ publicly available network server or other readily accessible means,
503
+ then you must either (1) cause the Corresponding Source to be so
504
+ available, or (2) arrange to deprive yourself of the benefit of the
505
+ patent license for this particular work, or (3) arrange, in a manner
506
+ consistent with the requirements of this License, to extend the patent
507
+ license to downstream recipients. "Knowingly relying" means you have
508
+ actual knowledge that, but for the patent license, your conveying the
509
+ covered work in a country, or your recipient's use of the covered work
510
+ in a country, would infringe one or more identifiable patents in that
511
+ country that you have reason to believe are valid.
512
+
513
+ If, pursuant to or in connection with a single transaction or
514
+ arrangement, you convey, or propagate by procuring conveyance of, a
515
+ covered work, and grant a patent license to some of the parties
516
+ receiving the covered work authorizing them to use, propagate, modify
517
+ or convey a specific copy of the covered work, then the patent license
518
+ you grant is automatically extended to all recipients of the covered
519
+ work and works based on it.
520
+
521
+ A patent license is "discriminatory" if it does not include within
522
+ the scope of its coverage, prohibits the exercise of, or is
523
+ conditioned on the non-exercise of one or more of the rights that are
524
+ specifically granted under this License. You may not convey a covered
525
+ work if you are a party to an arrangement with a third party that is
526
+ in the business of distributing software, under which you make payment
527
+ to the third party based on the extent of your activity of conveying
528
+ the work, and under which the third party grants, to any of the
529
+ parties who would receive the covered work from you, a discriminatory
530
+ patent license (a) in connection with copies of the covered work
531
+ conveyed by you (or copies made from those copies), or (b) primarily
532
+ for and in connection with specific products or compilations that
533
+ contain the covered work, unless you entered into that arrangement,
534
+ or that patent license was granted, prior to 28 March 2007.
535
+
536
+ Nothing in this License shall be construed as excluding or limiting
537
+ any implied license or other defenses to infringement that may
538
+ otherwise be available to you under applicable patent law.
539
+
540
+ 12. No Surrender of Others' Freedom.
541
+
542
+ If conditions are imposed on you (whether by court order, agreement or
543
+ otherwise) that contradict the conditions of this License, they do not
544
+ excuse you from the conditions of this License. If you cannot convey a
545
+ covered work so as to satisfy simultaneously your obligations under this
546
+ License and any other pertinent obligations, then as a consequence you may
547
+ not convey it at all. For example, if you agree to terms that obligate you
548
+ to collect a royalty for further conveying from those to whom you convey
549
+ the Program, the only way you could satisfy both those terms and this
550
+ License would be to refrain entirely from conveying the Program.
551
+
552
+ 13. Use with the GNU Affero General Public License.
553
+
554
+ Notwithstanding any other provision of this License, you have
555
+ permission to link or combine any covered work with a work licensed
556
+ under version 3 of the GNU Affero General Public License into a single
557
+ combined work, and to convey the resulting work. The terms of this
558
+ License will continue to apply to the part which is the covered work,
559
+ but the special requirements of the GNU Affero General Public License,
560
+ section 13, concerning interaction through a network will apply to the
561
+ combination as such.
562
+
563
+ 14. Revised Versions of this License.
564
+
565
+ The Free Software Foundation may publish revised and/or new versions of
566
+ the GNU General Public License from time to time. Such new versions will
567
+ be similar in spirit to the present version, but may differ in detail to
568
+ address new problems or concerns.
569
+
570
+ Each version is given a distinguishing version number. If the
571
+ Program specifies that a certain numbered version of the GNU General
572
+ Public License "or any later version" applies to it, you have the
573
+ option of following the terms and conditions either of that numbered
574
+ version or of any later version published by the Free Software
575
+ Foundation. If the Program does not specify a version number of the
576
+ GNU General Public License, you may choose any version ever published
577
+ by the Free Software Foundation.
578
+
579
+ If the Program specifies that a proxy can decide which future
580
+ versions of the GNU General Public License can be used, that proxy's
581
+ public statement of acceptance of a version permanently authorizes you
582
+ to choose that version for the Program.
583
+
584
+ Later license versions may give you additional or different
585
+ permissions. However, no additional obligations are imposed on any
586
+ author or copyright holder as a result of your choosing to follow a
587
+ later version.
588
+
589
+ 15. Disclaimer of Warranty.
590
+
591
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592
+ APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593
+ HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594
+ OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596
+ PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597
+ IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598
+ ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599
+
600
+ 16. Limitation of Liability.
601
+
602
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604
+ THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605
+ GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606
+ USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607
+ DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608
+ PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609
+ EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610
+ SUCH DAMAGES.
611
+
612
+ 17. Interpretation of Sections 15 and 16.
613
+
614
+ If the disclaimer of warranty and limitation of liability provided
615
+ above cannot be given local legal effect according to their terms,
616
+ reviewing courts shall apply local law that most closely approximates
617
+ an absolute waiver of all civil liability in connection with the
618
+ Program, unless a warranty or assumption of liability accompanies a
619
+ copy of the Program in return for a fee.
620
+
621
+ END OF TERMS AND CONDITIONS
622
+
623
+ How to Apply These Terms to Your New Programs
624
+
625
+ If you develop a new program, and you want it to be of the greatest
626
+ possible use to the public, the best way to achieve this is to make it
627
+ free software which everyone can redistribute and change under these terms.
628
+
629
+ To do so, attach the following notices to the program. It is safest
630
+ to attach them to the start of each source file to most effectively
631
+ state the exclusion of warranty; and each file should have at least
632
+ the "copyright" line and a pointer to where the full notice is found.
633
+
634
+ <one line to give the program's name and a brief idea of what it does.>
635
+ Copyright (C) <year> <name of author>
636
+
637
+ This program is free software: you can redistribute it and/or modify
638
+ it under the terms of the GNU General Public License as published by
639
+ the Free Software Foundation, either version 3 of the License, or
640
+ (at your option) any later version.
641
+
642
+ This program is distributed in the hope that it will be useful,
643
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
644
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645
+ GNU General Public License for more details.
646
+
647
+ You should have received a copy of the GNU General Public License
648
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
649
+
650
+ Also add information on how to contact you by electronic and paper mail.
651
+
652
+ If the program does terminal interaction, make it output a short
653
+ notice like this when it starts in an interactive mode:
654
+
655
+ <program> Copyright (C) <year> <name of author>
656
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657
+ This is free software, and you are welcome to redistribute it
658
+ under certain conditions; type `show c' for details.
659
+
660
+ The hypothetical commands `show w' and `show c' should show the appropriate
661
+ parts of the General Public License. Of course, your program's commands
662
+ might be different; for a GUI interface, you would use an "about box".
663
+
664
+ You should also get your employer (if you work as a programmer) or school,
665
+ if any, to sign a "copyright disclaimer" for the program, if necessary.
666
+ For more information on this, and how to apply and follow the GNU GPL, see
667
+ <https://www.gnu.org/licenses/>.
668
+
669
+ The GNU General Public License does not permit incorporating your program
670
+ into proprietary programs. If your program is a subroutine library, you
671
+ may consider it more useful to permit linking proprietary applications with
672
+ the library. If this is what you want to do, use the GNU Lesser General
673
+ Public License instead of this License. But first, please read
674
+ <https://www.gnu.org/licenses/why-not-lgpl.html>.
environment.yml ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: manimator
2
+ channels:
3
+ - defaults
4
+ - conda-forge
5
+ - pytorch
6
+ dependencies:
7
+ - python=3.10
8
+ - pip
9
+ - numpy>=1.24.0
10
+ - scipy>=1.10.0
11
+ - libstdcxx-ng #espeak problem bruh
12
+ - pip:
13
+ - streamlit>=1.27.0
14
+ - manim>=0.17.3
15
+ - kokoro>=0.3.1
16
+ - soundfile
17
+ - google-genai
18
+ - python-dotenv
19
+ - transformers
20
+ - accelerate
21
+ - httpx>=0.24.0
22
+ - pytorch
23
+ - torchvision
24
+ - torchaudio
25
+ - google-genai
packages.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ ffmpeg
2
+ latexmk
3
+ texlive-full
4
+ libcairo2-dev
5
+ pkg-config
6
+ libpango1.0-dev
requirements.txt ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ streamlit
2
+ manim
3
+ kokoro>=0.3.1
4
+ soundfile
5
+ google-genai
6
+ python-dotenv
7
+ numpy
8
+ httpx
9
+ torch
10
+ torchvision
11
+ torchaudio
12
+ accelerate
13
+ pydub
src/api/fallback_gemini.py ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import re
3
+ from google import genai
4
+ from google.genai import types as genai_types
5
+ import logging
6
+ from .gemini import SYSTEM_PROMPT, base_prompt_instructions
7
+
8
+ logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
9
+
10
+ def fix_manim_code(faulty_code: str, error_message: str, original_context: str):
11
+ api_key = os.getenv("GEMINI_API_KEY")
12
+ if not api_key:
13
+ logging.error("GEMINI_API_KEY not found in environment variables for fallback.")
14
+ return None, None
15
+
16
+ client = genai.Client(api_key=api_key)
17
+
18
+ fix_prompt_text = (
19
+ f"The following Manim code, intended to '{original_context}', failed with an error.\n\n"
20
+ "### FAULTY CODE:\n"
21
+ f"```python\n{faulty_code}\n```\n\n"
22
+ "### ERROR MESSAGE:\n"
23
+ f"```\n{error_message}\n```\n\n"
24
+ "### INSTRUCTIONS:\n"
25
+ "1. Analyze the error message and the faulty code.\n"
26
+ "2. Correct the code to fix the specific error reported.\n"
27
+ "3. Ensure the corrected code still fulfills the original request and adheres strictly to *all* the requirements listed below.\n"
28
+ "4. Pay close attention to vector dimensions, matrix operations, allowed Manim methods, and total duration (30 seconds).\n"
29
+ "5. If the code logic changes significantly, update the narration accordingly.\n"
30
+ "6. Return *only* the corrected code and narration using the '### MANIM CODE:' and '### NARRATION:' delimiters, just like the original request.\n\n"
31
+ "### REQUIREMENTS (Apply these to the corrected code):\n"
32
+ f"{base_prompt_instructions}"
33
+ )
34
+
35
+ contents = [fix_prompt_text]
36
+
37
+ logging.info("Attempting to fix Manim code via fallback...")
38
+ try:
39
+ generation_config = genai_types.GenerateContentConfig(
40
+ system_instruction=SYSTEM_PROMPT
41
+ )
42
+
43
+ response = client.models.generate_content(
44
+ model="gemini-2.0-flash",
45
+ contents=contents,
46
+ config=generation_config
47
+ )
48
+ if response:
49
+ try:
50
+ content = response.text
51
+ logging.info("Received response from fallback attempt.")
52
+
53
+ if "### NARRATION:" in content:
54
+ manim_code, narration = content.split("### NARRATION:", 1)
55
+ manim_code = re.sub(r"```python", "", manim_code).replace("```", "").strip()
56
+ narration = narration.strip()
57
+
58
+ if "from manim import *" not in manim_code:
59
+ logging.warning("Adding missing 'from manim import *' (fallback fix).")
60
+ manim_code = "from manim import *\nimport numpy as np\n" + manim_code
61
+ elif "import numpy as np" not in manim_code:
62
+ logging.warning("Adding missing 'import numpy as np' (fallback fix).")
63
+ lines = manim_code.splitlines()
64
+ for i, line in enumerate(lines):
65
+ if "from manim import *" in line:
66
+ lines.insert(i + 1, "import numpy as np")
67
+ manim_code = "\n".join(lines)
68
+ break
69
+
70
+ logging.info("Successfully parsed fixed code and narration from fallback.")
71
+ return {"manim_code": manim_code, "output_file": "output.mp4"}, narration
72
+ else:
73
+ logging.warning("Delimiter '### NARRATION:' not found in fallback response. Attempting fallback extraction.")
74
+ code_match = re.search(r'```python(.*?)```', content, re.DOTALL)
75
+ if code_match:
76
+ manim_code = code_match.group(1).strip()
77
+ narration_part = content.split('```', 2)[-1].strip()
78
+ narration = narration_part if len(narration_part) > 20 else ""
79
+ if not narration:
80
+ logging.warning("Fallback narration extraction resulted in empty or very short text (fallback fix).")
81
+ else:
82
+ logging.info("Successfully parsed code and narration using fallback regex (fallback fix).")
83
+
84
+ if "from manim import *" not in manim_code:
85
+ logging.warning("Adding missing 'from manim import *' (fallback fix, regex path).")
86
+ manim_code = "from manim import *\nimport numpy as np\n" + manim_code
87
+ elif "import numpy as np" not in manim_code:
88
+ logging.warning("Adding missing 'import numpy as np' (fallback fix, regex path).")
89
+ lines = manim_code.splitlines()
90
+ for i, line in enumerate(lines):
91
+ if "from manim import *" in line:
92
+ lines.insert(i + 1, "import numpy as np")
93
+ manim_code = "\n".join(lines)
94
+ break
95
+
96
+ logging.info("Successfully parsed fixed code using fallback extraction.")
97
+ return {"manim_code": manim_code, "output_file": "output.mp4"}, narration
98
+ else:
99
+ logging.error("Fallback extraction failed: No Python code block found in fallback response.")
100
+ logging.debug(f"Fallback content without code block:\n{content}")
101
+ return None, None
102
+
103
+ except ValueError:
104
+ logging.error("Could not extract text from the fallback response.")
105
+ if response.prompt_feedback and response.prompt_feedback.block_reason:
106
+ logging.error(f"Fallback content generation blocked. Reason: {response.prompt_feedback.block_reason.name}")
107
+ return None, None
108
+ except Exception as e:
109
+ logging.exception(f"Error processing fallback response: {e}")
110
+ return None, None
111
+ else:
112
+ logging.error("No response received from Gemini during fallback attempt.")
113
+ return None, None
114
+
115
+ except Exception as e:
116
+ logging.exception(f"Error calling Gemini API during fallback: {e}")
117
+ return None, None
src/api/gemini.py ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ from google import genai
3
+ from google.genai import types as genai_types
4
+ from dotenv import load_dotenv
5
+ import os
6
+ import pathlib
7
+ import logging
8
+
9
+ load_dotenv()
10
+
11
+ logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
12
+
13
+ # --- Global System Prompt ---
14
+ SYSTEM_PROMPT = """You are an expert Manim programmer specializing in creating crazy, cutting-edge, and visually striking animations based on user prompts or documents, strictly following Manim Community v0.19.0 standards.
15
+
16
+ Core Requirements:
17
+ - **API Version:** Use only Manim Community v0.19.0 API.
18
+ - **Vectors & Math:** Use 3D vectors (`np.array([x, y, 0])`) and ensure correct math operations.
19
+ - **Allowed Methods:** Strictly use the verified list of Manim methods provided in the detailed instructions. No external images.
20
+ - ** "\n - self.play(), self.wait(), Create(), Write(), Transform(), FadeIn(), FadeOut(), Add(), Remove(), MoveAlongPath(), Rotating(), Circumscribe(), Indicate(), FocusOn(), Shift(), Scale(), MoveTo(), NextTo(), Axes(), Plot(), LineGraph(), BarChart(), Dot(), Line(), Arrow(), Text(), Tex(), MathTex(), VGroup(), Mobject.animate, self.camera.frame.animate"
21
+ - **Matrix Visualization:** Use `MathTex` for displaying matrices in the format `r'\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}'`.
22
+ - **Duration:** The total animation duration MUST be exactly 30 seconds.
23
+ -**Error handling**:"An unexpected error occurred during video creation: No Scene class found in generated code, This error SHOULD NEVER occur. Make sure to validate the code before returning it. If this error occurs, please log the error and return None for both manim_code and narration.Make sure you don't do 3Dscene coz that gives this error"
24
+ - **Engagement:** Create visually stunning and crazy animations that push creative boundaries. Use vibrant colors, dynamic movements, and unexpected transformations.
25
+ - **Text Handling:** Fade out text and other elements as soon as they are no longer needed, ensuring a smooth transition.
26
+ - **Synchronization:** Align animation pacing (`run_time`, `wait`) roughly with the narration segments.
27
+ - **Output Format:** Return *only* the Python code and narration script, separated by '### MANIM CODE:' and '### NARRATION:' delimiters. Adhere strictly to this format.
28
+ - **Code Quality:** Generate error-free, runnable code with necessary imports (`from manim import *`, `import numpy as np`) and exactly one Scene class. Validate objects and animation calls.
29
+ """
30
+
31
+ # --- Detailed Instructions ---
32
+ base_prompt_instructions = (
33
+ "\nFollow these requirements strictly:"
34
+ "\n1. Use only Manim Community v0.19.0 API"
35
+ "\n2. Vector operations:"
36
+ "\n - All vectors must be 3D: np.array([x, y, 0])"
37
+ "\n - Matrix multiplication: result = np.dot(matrix, vector[:2])"
38
+ "\n - Append 0 for Z: np.append(result, 0)"
39
+ "\n3. Matrix visualization:"
40
+ "\n - Use MathTex for display"
41
+ "\n - Format: r'\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}'"
42
+ "\n4. Use only verified Manim methods:"
43
+ "\n - self.play(), self.wait(), Create(), Write(), Transform(), FadeIn(), FadeOut(), Add(), Remove(), MoveAlongPath(), Rotating(), Circumscribe(), Indicate(), FocusOn(), Shift(), Scale(), MoveTo(), NextTo(), Axes(), Plot(), LineGraph(), BarChart(), Dot(), Line(), Arrow(), Text(), Tex(), MathTex(), VGroup(), Mobject.animate, self.camera.frame.animate"
44
+ "\n5. DO NOT USE IMAGES IMPORTS."
45
+ "\n6. Make the video crazy and innovative by:"
46
+ "\n - Fading out text and other elements gracefully once they are no longer needed"
47
+ "\n - Adding creative interactive elements like arrows, labels, and transitions"
48
+ "\n - Incorporating graphs/plots (Axes, Plot, LineGraph, BarChart) where appropriate"
49
+ "\n - Leveraging smooth transitions and varied pacing to keep the viewer engaged."
50
+ "\n7. Ensure the video is error-free by:"
51
+ "\n - Validating all objects before animations"
52
+ "\n - Handling exceptions gracefully (in generated code if applicable)"
53
+ "\n - Ensuring operands for vector operations match in shape to avoid broadcasting errors"
54
+ "\n8. Validate that every arrow creation ensures its start and end points are distinct to prevent normalization errors."
55
+ "\n9. Use longer scenes (e.g., 5-6 seconds per major step) for complex transformations and shorter scenes for simple animations, with a total duration of exactly 30 seconds."
56
+ "\n10. Align the narration script with the animation pace for seamless storytelling."
57
+ "\n11. Ensure all objects in self.play() are valid animations (e.g., `Create(obj)`, `obj.animate.shift(UP)`)."
58
+ "\n12. Use Mobject.animate for animations involving Mobject methods."
59
+ "\n13. CRITICAL: DO NOT USE BARCHATS, LINEGRAPHS, OR PLOTTING WITHOUT EXPLICIT INSTRUCTIONS."
60
+ "\n14. Provide creative and sometimes crazy Manim video scripts that push the conventional boundaries."
61
+ "\n15. **Synchronization:** Structure the narration and Manim code for better synchronization:"
62
+ "\n - Keep narration segments concise and directly tied to the visual elements."
63
+ "\n - Use `self.wait(duration)` in the Manim code to match natural pauses in narration."
64
+ "\n - Adjust `run_time` in `self.play()` calls to match the speaking duration of the associated narration."
65
+ "\n - Ensure the animation and narration sum to exactly 30 seconds."
66
+ "\n### MANIM CODE:\n"
67
+ "Provide only valid Python code using Manim Community v0.19.0 to generate the video animation.\n\n"
68
+ "### NARRATION:\n"
69
+ "Provide a concise narration script for the video that aligns with the Manim code's pacing and visuals.DO NOT give timestamps.\n\n"
70
+ )
71
+
72
+
73
+ def load_manim_examples():
74
+ guide_path = pathlib.Path(__file__).parent / "guide.md"
75
+ if not guide_path.exists():
76
+ logging.warning(f"Manim examples guide not found at {guide_path}")
77
+ return ""
78
+
79
+ logging.info(f"Loading Manim examples from {guide_path}")
80
+ return guide_path.read_text(encoding="utf-8")
81
+
82
+
83
+ def generate_video(idea: str | None = None, pdf_path: str | None = None):
84
+ api_key = os.getenv("GEMINI_API_KEY")
85
+ if not api_key:
86
+ logging.error("GEMINI_API_KEY not found in environment variables")
87
+ raise Exception("GEMINI_API_KEY not found in environment variables")
88
+
89
+ if not idea and not pdf_path:
90
+ raise ValueError("Either an idea or a pdf_path must be provided.")
91
+ if idea and pdf_path:
92
+ logging.warning("Both idea and pdf_path provided. Using pdf_path.")
93
+ idea = None
94
+
95
+ client = genai.Client(api_key=api_key)
96
+ contents = []
97
+
98
+ manim_examples = load_manim_examples()
99
+ if manim_examples:
100
+ examples_prompt = "Below are examples of Manim code that demonstrate proper usage patterns. Use these as reference when generating your animation:\n\n" + manim_examples
101
+ contents.append(examples_prompt)
102
+ logging.info("Added Manim examples from guide.md to prime the model")
103
+ else:
104
+ logging.warning("No Manim examples were loaded from guide.md")
105
+
106
+ user_prompt_text = ""
107
+
108
+ if pdf_path:
109
+ pdf_file_path = pathlib.Path(pdf_path)
110
+ if not pdf_file_path.exists():
111
+ logging.error(f"PDF file not found at: {pdf_path}")
112
+ raise FileNotFoundError(f"PDF file not found at: {pdf_path}")
113
+
114
+ logging.info(f"Reading PDF: {pdf_path}")
115
+ pdf_data = pdf_file_path.read_bytes()
116
+ pdf_part = genai_types.Part.from_bytes(data=pdf_data, mime_type='application/pdf')
117
+ contents.append(pdf_part)
118
+
119
+ user_prompt_text = f"Create a 30-second Manim video script summarizing the key points or illustrating a core concept from the provided PDF document. {base_prompt_instructions}"
120
+ contents.append(user_prompt_text)
121
+
122
+ elif idea:
123
+ logging.info(f"Generating video based on idea: {idea[:50]}...")
124
+ user_prompt_text = f"Create a 30-second Manim video script about '{idea}'. {base_prompt_instructions}"
125
+ contents.append(user_prompt_text)
126
+
127
+ logging.info("Sending request to Gemini API...")
128
+ try:
129
+ generation_config = genai_types.GenerateContentConfig(
130
+ system_instruction=SYSTEM_PROMPT
131
+ )
132
+
133
+ response = client.models.generate_content(
134
+ model="gemini-1.5-pro",
135
+ contents=contents,
136
+ config=generation_config
137
+ )
138
+ except Exception as e:
139
+ logging.exception(f"Error calling Gemini API: {e}")
140
+ raise Exception(f"Error calling Gemini API: {e}")
141
+
142
+ if response:
143
+ try:
144
+ content = response.text
145
+ logging.info("Received response from Gemini.")
146
+ except ValueError:
147
+ logging.warning("Could not extract text from the response. Response details:")
148
+ logging.warning(response)
149
+ if response.prompt_feedback and response.prompt_feedback.block_reason:
150
+ logging.error(f"Content generation blocked. Reason: {response.prompt_feedback.block_reason.name}")
151
+ raise Exception(f"Content generation blocked. Reason: {response.prompt_feedback.block_reason.name}")
152
+ else:
153
+ logging.error("Failed to generate content. The response was empty or malformed.")
154
+ raise Exception("Failed to generate content. The response was empty or malformed.")
155
+
156
+ if "### NARRATION:" in content:
157
+ manim_code, narration = content.split("### NARRATION:", 1)
158
+ manim_code = re.sub(r"```python", "", manim_code).replace("```", "").strip()
159
+ narration = narration.strip()
160
+ logging.info("Successfully parsed code and narration using delimiter.")
161
+
162
+ if "from manim import *" not in manim_code:
163
+ logging.warning("Adding missing 'from manim import *'.")
164
+ manim_code = "from manim import *\nimport numpy as np\n" + manim_code
165
+ elif "import numpy as np" not in manim_code:
166
+ logging.warning("Adding missing 'import numpy as np'.")
167
+ lines = manim_code.splitlines()
168
+ for i, line in enumerate(lines):
169
+ if "from manim import *" in line:
170
+ lines.insert(i + 1, "import numpy as np")
171
+ manim_code = "\n".join(lines)
172
+ break
173
+
174
+ return {"manim_code": manim_code, "output_file": "output.mp4"}, narration
175
+ else:
176
+ logging.warning("Delimiter '### NARRATION:' not found. Attempting fallback extraction.")
177
+ code_match = re.search(r'```python(.*?)```', content, re.DOTALL)
178
+ if code_match:
179
+ manim_code = code_match.group(1).strip()
180
+ narration_part = content.split('```', 2)[-1].strip()
181
+ narration = narration_part if len(narration_part) > 20 else ""
182
+ if not narration:
183
+ logging.warning("Fallback narration extraction resulted in empty or very short text.")
184
+ else:
185
+ logging.info("Successfully parsed code and narration using fallback regex.")
186
+
187
+ if "from manim import *" not in manim_code:
188
+ logging.warning("Adding missing 'from manim import *' (fallback).")
189
+ manim_code = "from manim import *\nimport numpy as np\n" + manim_code
190
+ elif "import numpy as np" not in manim_code:
191
+ logging.warning("Adding missing 'import numpy as np' (fallback).")
192
+ lines = manim_code.splitlines()
193
+ for i, line in enumerate(lines):
194
+ if "from manim import *" in line:
195
+ lines.insert(i + 1, "import numpy as np")
196
+ manim_code = "\n".join(lines)
197
+ break
198
+
199
+ return {"manim_code": manim_code, "output_file": "output.mp4"}, narration
200
+ else:
201
+ logging.error("Fallback extraction failed: No Python code block found in response.")
202
+ logging.debug(f"Content without code block:\n{content}")
203
+ raise Exception("The response does not contain the expected '### NARRATION:' delimiter or a valid Python code block.")
204
+
205
+ else:
206
+ logging.error("Error generating video content. No response received from Gemini.")
207
+ raise Exception("Error generating video content. No response received.")
208
+
src/api/guide.md ADDED
@@ -0,0 +1,332 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Manim Code Examples (Community v0.19.0)
2
+
3
+ ## Example 1: Basic Shapes and Text
4
+
5
+ **Description:** Shows a circle and text, then fades them out.
6
+
7
+ ```python
8
+ # ### MANIM CODE:
9
+ from manim import *
10
+ import numpy as np
11
+
12
+ class BasicShapes(Scene):
13
+ def construct(self):
14
+ circle = Circle(color=BLUE, fill_opacity=0.5)
15
+ text = Text("Hello Manim!").next_to(circle, DOWN)
16
+ self.play(Create(circle), Write(text), run_time=5) # Longer duration for narration
17
+ self.wait(5) # Pause for narration
18
+ self.play(FadeOut(circle), FadeOut(text), run_time=5)
19
+ self.wait(15) # Fill remaining time
20
+ ```
21
+
22
+ ```text
23
+ # ### NARRATION:
24
+ Here we create a blue circle and display the text "Hello Manim!" below it. After a brief pause, both elements fade away.
25
+ ```
26
+
27
+ ## Example 2: Vector Transformation with Labels
28
+
29
+ **Description:** Creates a vector, displays a transformation matrix, applies the transformation, and labels the steps.
30
+
31
+ ```python
32
+ # ### MANIM CODE:
33
+ from manim import *
34
+ import numpy as np
35
+
36
+ class VectorTransform(Scene):
37
+ def construct(self):
38
+ # Setup
39
+ axes = Axes(x_range=[-5, 5, 1], y_range=[-5, 5, 1], x_length=6, y_length=6)
40
+ vec_start = np.array([1, 1, 0])
41
+ matrix = np.array([[0, -1], [1, 0]]) # 90 deg rotation
42
+
43
+ # Initial vector
44
+ vector = Arrow(ORIGIN, vec_start, buff=0, color=YELLOW)
45
+ vec_label = MathTex("v", color=YELLOW).next_to(vector.get_end(), UR, buff=0.1)
46
+ self.play(Create(axes), Create(vector), Write(vec_label), run_time=6) # Show initial state
47
+
48
+ # Matrix
49
+ matrix_tex = MathTex(r"M = \begin{bmatrix} 0 & -1 \\ 1 & 0 \end{bmatrix}", color=RED).to_corner(UL)
50
+ self.play(Write(matrix_tex), run_time=4) # Introduce matrix
51
+
52
+ # Transformation
53
+ vec_end = np.append(np.dot(matrix, vec_start[:2]), 0)
54
+ new_vector = Arrow(ORIGIN, vec_end, buff=0, color=GREEN)
55
+ new_vec_label = MathTex("Mv", color=GREEN).next_to(new_vector.get_end(), UR, buff=0.1)
56
+ transform_label = Text("Applying 90° Rotation", font_size=24).next_to(matrix_tex, DOWN, aligned_edge=LEFT)
57
+
58
+ self.play(Write(transform_label), run_time=3) # Explain transform
59
+ self.play(Transform(vector, new_vector), Transform(vec_label, new_vec_label), run_time=7) # Show transform
60
+
61
+ self.wait(10) # Hold final state
62
+ ```
63
+
64
+ ```text
65
+ # ### NARRATION:
66
+ We start with vector v in yellow on the coordinate plane. This is the rotation matrix M we'll use. Now, we apply the matrix M to rotate vector v by 90 degrees, resulting in the green vector Mv.
67
+ ```
68
+ ## Example 3: BraceAnnotation
69
+
70
+ **Description:** Shows how to create braces and attach text/latex to them.
71
+
72
+ ```python
73
+ # ### MANIM CODE:
74
+ from manim import *
75
+ import numpy as np
76
+
77
+ class BraceAnnotation(Scene):
78
+ def construct(self):
79
+ dot = Dot([-2, -1, 0])
80
+ dot2 = Dot([2, 1, 0])
81
+ line = Line(dot.get_center(), dot2.get_center()).set_color(ORANGE)
82
+ b1 = Brace(line)
83
+ b1text = b1.get_text("Horizontal distance")
84
+ b2 = Brace(line, direction=line.copy().rotate(PI / 2).get_unit_vector())
85
+ b2text = b2.get_tex("x-x_1")
86
+
87
+ self.play(Create(line), Create(dot), Create(dot2), run_time=3)
88
+ self.play(Create(b1), Write(b1text), run_time=3)
89
+ self.play(Create(b2), Write(b2text), run_time=3)
90
+ self.wait(21) # Fill remaining time
91
+ ```
92
+
93
+ ```text
94
+ # ### NARRATION:
95
+ Here we demonstrate how to add annotations with braces. First, we create a line between two dots. Then we add a horizontal brace with text below it showing "Horizontal distance." Finally, we add a vertical brace with mathematical notation showing the difference between x coordinates.
96
+ ```
97
+
98
+ ## Example 4: SinAndCosFunctionPlot
99
+
100
+ **Description:** Plots sine and cosine functions on an axis with labels.
101
+
102
+ ```python
103
+ # ### MANIM CODE:
104
+ from manim import *
105
+ import numpy as np
106
+
107
+ class SinAndCosFunctionPlot(Scene):
108
+ def construct(self):
109
+ axes = Axes(
110
+ x_range=[-10, 10.3, 1],
111
+ y_range=[-1.5, 1.5, 1],
112
+ x_length=10,
113
+ axis_config={"color": GREEN},
114
+ x_axis_config={
115
+ "numbers_to_include": np.arange(-10, 10.01, 2),
116
+ "numbers_with_elongated_ticks": np.arange(-10, 10.01, 2),
117
+ },
118
+ tips=False,
119
+ )
120
+ axes_labels = axes.get_axis_labels()
121
+ sin_graph = axes.plot(lambda x: np.sin(x), color=BLUE)
122
+ cos_graph = axes.plot(lambda x: np.cos(x), color=RED)
123
+
124
+ sin_label = axes.get_graph_label(
125
+ sin_graph, "\\sin(x)", x_val=-10, direction=UP / 2
126
+ )
127
+ cos_label = axes.get_graph_label(cos_graph, label="\\cos(x)")
128
+
129
+ vert_line = axes.get_vertical_line(
130
+ axes.i2gp(TAU, cos_graph), color=YELLOW, line_func=Line
131
+ )
132
+ line_label = axes.get_graph_label(
133
+ cos_graph, r"x=2\pi", x_val=TAU, direction=UR, color=WHITE
134
+ )
135
+
136
+ # Animation sequence
137
+ self.play(Create(axes), Write(axes_labels), run_time=3)
138
+ self.play(Create(sin_graph), Create(cos_graph), run_time=5)
139
+ self.play(Write(sin_label), Write(cos_label), run_time=3)
140
+ self.play(Create(vert_line), Write(line_label), run_time=3)
141
+ self.wait(16) # Fill remaining time
142
+ ```
143
+
144
+ ```text
145
+ # ### NARRATION:
146
+ In this animation, we plot the sine and cosine functions on a coordinate plane. The sine function is shown in blue, while the cosine function is shown in red. We add labels to each curve and mark a vertical line at x equals 2π to highlight this important value. Notice how the curves oscillate between -1 and 1 as they extend across the x-axis.
147
+ ```
148
+
149
+ ## Example 5: PointMovingOnShapes
150
+
151
+ **Description:** Demonstrates how to animate a dot moving along paths and rotating.
152
+
153
+ ```python
154
+ # ### MANIM CODE:
155
+ from manim import *
156
+ import numpy as np
157
+
158
+ class PointMovingOnShapes(Scene):
159
+ def construct(self):
160
+ circle = Circle(radius=1, color=BLUE)
161
+ dot = Dot()
162
+ dot2 = dot.copy().shift(RIGHT)
163
+ self.add(dot)
164
+
165
+ line = Line([3, 0, 0], [5, 0, 0])
166
+ self.play(Create(line), run_time=2)
167
+ self.play(GrowFromCenter(circle), run_time=2)
168
+ self.play(Transform(dot, dot2), run_time=2)
169
+ self.play(MoveAlongPath(dot, circle), run_time=7, rate_func=linear)
170
+ self.play(Rotating(dot, about_point=[2, 0, 0]), run_time=7)
171
+ self.wait(10) # Fill remaining time
172
+ ```
173
+
174
+ ```text
175
+ # ### NARRATION:
176
+ Here we demonstrate moving and transforming objects. We begin with a dot and create a line and circle. Then, we transform the dot by shifting it to the right. Watch as the dot moves along the circular path at a constant speed. Finally, the dot rotates around a fixed point, showing how we can create complex animations by combining different movements.
177
+ ```
178
+
179
+ ## Example 6: ThreeDSurfacePlot
180
+
181
+ **Description:** Creates a 3D Gaussian surface plot with colored checkerboard pattern.
182
+
183
+ ```python
184
+ # ### MANIM CODE:
185
+ from manim import *
186
+ import numpy as np
187
+
188
+ class ThreeDSurfacePlot(ThreeDScene):
189
+ def construct(self):
190
+ resolution_fa = 24
191
+ self.set_camera_orientation(phi=75 * DEGREES, theta=-30 * DEGREES)
192
+
193
+ def param_gauss(u, v):
194
+ x = u
195
+ y = v
196
+ sigma, mu = 0.4, [0.0, 0.0]
197
+ d = np.linalg.norm(np.array([x - mu[0], y - mu[1]]))
198
+ z = np.exp(-(d ** 2 / (2.0 * sigma ** 2)))
199
+ return np.array([x, y, z])
200
+
201
+ gauss_plane = Surface(
202
+ param_gauss,
203
+ resolution=(resolution_fa, resolution_fa),
204
+ v_range=[-2, +2],
205
+ u_range=[-2, +2]
206
+ )
207
+
208
+ gauss_plane.scale(2, about_point=ORIGIN)
209
+ gauss_plane.set_style(fill_opacity=1, stroke_color=GREEN)
210
+ gauss_plane.set_fill_by_checkerboard(ORANGE, BLUE, opacity=0.5)
211
+ axes = ThreeDAxes()
212
+
213
+ self.play(Create(axes), run_time=2)
214
+ self.play(Create(gauss_plane), run_time=3)
215
+ self.begin_ambient_camera_rotation(rate=0.1)
216
+ self.wait(25) # Fill remaining time
217
+ ```
218
+
219
+ ```text
220
+ # ### NARRATION:
221
+ In this animation, we're creating a three-dimensional Gaussian surface plot. We first set up the camera angle to view our 3D scene properly. The surface is defined by a Gaussian function that creates a bell curve shape in three dimensions. We apply a checkerboard pattern with orange and blue colors to highlight the surface features. Notice how the ambient camera rotation helps us visualize the 3D nature of the surface from multiple angles.
222
+ ```
223
+
224
+ ## Example 7: MovingAngle
225
+
226
+ **Description:** Shows an animated angle that changes based on a ValueTracker.
227
+
228
+ ```python
229
+ # ### MANIM CODE:
230
+ from manim import *
231
+ import numpy as np
232
+
233
+ class MovingAngle(Scene):
234
+ def construct(self):
235
+ rotation_center = LEFT
236
+
237
+ theta_tracker = ValueTracker(110)
238
+ line1 = Line(LEFT, RIGHT)
239
+ line_moving = Line(LEFT, RIGHT)
240
+ line_ref = line_moving.copy()
241
+ line_moving.rotate(
242
+ theta_tracker.get_value() * DEGREES, about_point=rotation_center
243
+ )
244
+ a = Angle(line1, line_moving, radius=0.5, other_angle=False)
245
+ tex = MathTex(r"\theta").move_to(
246
+ Angle(
247
+ line1, line_moving, radius=0.5 + 3 * SMALL_BUFF, other_angle=False
248
+ ).point_from_proportion(0.5)
249
+ )
250
+
251
+ self.play(Create(line1), Create(line_moving), run_time=2)
252
+ self.play(Create(a), Write(tex), run_time=2)
253
+ self.wait(2)
254
+
255
+ line_moving.add_updater(
256
+ lambda x: x.become(line_ref.copy()).rotate(
257
+ theta_tracker.get_value() * DEGREES, about_point=rotation_center
258
+ )
259
+ )
260
+
261
+ a.add_updater(
262
+ lambda x: x.become(Angle(line1, line_moving, radius=0.5, other_angle=False))
263
+ )
264
+ tex.add_updater(
265
+ lambda x: x.move_to(
266
+ Angle(
267
+ line1, line_moving, radius=0.5 + 3 * SMALL_BUFF, other_angle=False
268
+ ).point_from_proportion(0.5)
269
+ )
270
+ )
271
+
272
+ self.play(theta_tracker.animate.set_value(40), run_time=3)
273
+ self.play(theta_tracker.animate.increment_value(140), run_time=3)
274
+ self.play(tex.animate.set_color(RED), run_time=1)
275
+ self.play(theta_tracker.animate.set_value(350), run_time=7)
276
+ self.wait(10) # Fill remaining time
277
+ ```
278
+
279
+ ```text
280
+ # ### NARRATION:
281
+ This animation demonstrates how to create a dynamic angle that updates as values change. We start with two lines forming an angle of 110 degrees. Using updaters and a ValueTracker, we can animate the angle changing smoothly. Watch as we decrease the angle to 40 degrees, then increase it by 140 degrees. As the angle continues to change, we also highlight the theta symbol in red before completing a full rotation to 350 degrees.
282
+ ```
283
+
284
+ ## Example 8: GraphAreaPlot
285
+
286
+ **Description:** Demonstrates how to show areas between curves and Riemann rectangles.
287
+
288
+ ```python
289
+ # ### MANIM CODE:
290
+ from manim import *
291
+ import numpy as np
292
+
293
+ class GraphAreaPlot(Scene):
294
+ def construct(self):
295
+ ax = Axes(
296
+ x_range=[0, 5],
297
+ y_range=[0, 6],
298
+ x_axis_config={"numbers_to_include": [2, 3]},
299
+ tips=False,
300
+ )
301
+
302
+ labels = ax.get_axis_labels()
303
+
304
+ curve_1 = ax.plot(lambda x: 4 * x - x ** 2, x_range=[0, 4], color=BLUE_C)
305
+ curve_2 = ax.plot(
306
+ lambda x: 0.8 * x ** 2 - 3 * x + 4,
307
+ x_range=[0, 4],
308
+ color=GREEN_B,
309
+ )
310
+
311
+ line_1 = ax.get_vertical_line(ax.input_to_graph_point(2, curve_1), color=YELLOW)
312
+ line_2 = ax.get_vertical_line(ax.i2gp(3, curve_1), color=YELLOW)
313
+
314
+ riemann_area = ax.get_riemann_rectangles(
315
+ curve_1, x_range=[0.3, 0.6], dx=0.03, color=BLUE, fill_opacity=0.5
316
+ )
317
+ area = ax.get_area(
318
+ curve_2, [2, 3], bounded_graph=curve_1, color=GREY, opacity=0.5
319
+ )
320
+
321
+ self.play(Create(ax), Write(labels), run_time=3)
322
+ self.play(Create(curve_1), Create(curve_2), run_time=4)
323
+ self.play(Create(line_1), Create(line_2), run_time=3)
324
+ self.play(FadeIn(riemann_area), run_time=3)
325
+ self.play(FadeIn(area), run_time=3)
326
+ self.wait(14) # Fill remaining time
327
+ ```
328
+
329
+ ```text
330
+ # ### NARRATION:
331
+ In this animation, we visualize areas between curves using Manim's plotting capabilities. We create two functions, shown in blue and green, and mark two vertical lines at x equals 2 and x equals 3. The small blue rectangles demonstrate Riemann sums, which approximate the area under a curve. The gray shaded region shows the area between both curves from x equals 2 to x equals 3. These visualizations are powerful tools for understanding calculus concepts like integration and area between curves.
332
+ ```
src/app.py ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import os
3
+ import tempfile
4
+ import subprocess
5
+ import logging
6
+
7
+ from api.gemini import generate_video
8
+ from api.fallback_gemini import fix_manim_code
9
+ from services.manim_service import create_manim_video
10
+ from services.tts_service import generate_audio
11
+
12
+ logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
13
+
14
+ def main():
15
+ st.title("Manimator")
16
+ st.write("Generate videos from text ideas or PDF files, You can also just paste arxiv links ;p")
17
+ input_type = st.radio("Choose input type:", ("Text Idea", "Upload PDF"))
18
+
19
+ idea = None
20
+ uploaded_file = None
21
+ pdf_path = None
22
+ original_context = ""
23
+ audio_file = None
24
+ current_audio_file = None
25
+ if input_type == "Text Idea":
26
+ idea = st.text_area("Enter your idea:")
27
+ if idea:
28
+ original_context = idea
29
+ else:
30
+ uploaded_file = st.file_uploader("Choose a PDF file", type="pdf")
31
+ if uploaded_file:
32
+ original_context = f"Summary/concept from PDF: {uploaded_file.name}"
33
+
34
+ if st.button("Generate Video"):
35
+ temp_pdf_file = None
36
+ video_data = None
37
+ script = None
38
+ audio_file = None
39
+ final_video = None
40
+ max_retries = 1
41
+
42
+ try:
43
+ if input_type == "Text Idea" and idea:
44
+ with st.spinner("Generating initial script and code from idea..."):
45
+ logging.info(f"Generating video from idea: {idea[:50]}...")
46
+ video_data, script = generate_video(idea=idea)
47
+ elif input_type == "Upload PDF" and uploaded_file is not None:
48
+ with st.spinner("Generating initial script and code from PDF..."):
49
+ logging.info(f"Generating video from PDF: {uploaded_file.name}")
50
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as temp_pdf:
51
+ temp_pdf.write(uploaded_file.getvalue())
52
+ pdf_path = temp_pdf.name
53
+ temp_pdf_file = pdf_path
54
+ video_data, script = generate_video(pdf_path=pdf_path)
55
+ else:
56
+ st.error("Please provide an idea or upload a PDF.")
57
+ return
58
+
59
+ if not video_data or not script:
60
+ st.error("Failed to generate initial script/code from Gemini.")
61
+ return
62
+
63
+ with st.spinner("Generating audio..."):
64
+ logging.info("Generating audio for the script.")
65
+ try:
66
+ audio_file = generate_audio(script)
67
+ except ValueError as e:
68
+ st.warning(f"Could not generate audio: {e}. Proceeding without audio.")
69
+ audio_file = None
70
+
71
+ current_manim_code = video_data["manim_code"]
72
+ current_script = script
73
+ current_audio_file = audio_file
74
+
75
+ for attempt in range(max_retries + 1):
76
+ try:
77
+ with st.spinner(f"Attempt {attempt + 1}: Creating Manim video..."):
78
+ logging.info(f"Attempt {attempt + 1} to create Manim video.")
79
+ final_video = create_manim_video(
80
+ {"manim_code": current_manim_code, "output_file": "output.mp4"},
81
+ current_manim_code,
82
+ audio_file=current_audio_file
83
+ )
84
+ logging.info("Manim video creation successful.")
85
+ break
86
+ except subprocess.CalledProcessError as e:
87
+ logging.error(f"Manim execution failed on attempt {attempt + 1}.")
88
+ st.warning(f"Attempt {attempt + 1} failed. Manim error:\n```\n{e.stderr.decode() if e.stderr else 'No stderr captured.'}\n```")
89
+ if attempt < max_retries:
90
+ st.info("Attempting to fix the code using fallback...")
91
+ logging.info("Calling fallback Gemini to fix code.")
92
+ error_message = e.stderr.decode() if e.stderr else "Manim execution failed without specific error output."
93
+
94
+ fixed_video_data, fixed_script = fix_manim_code(
95
+ faulty_code=current_manim_code,
96
+ error_message=error_message,
97
+ original_context=original_context
98
+ )
99
+
100
+ if fixed_video_data and fixed_script is not None:
101
+ st.success("Fallback successful! Retrying video generation with fixed code.")
102
+ logging.info("Fallback successful. Received fixed code.")
103
+ current_manim_code = fixed_video_data["manim_code"]
104
+ if fixed_script != current_script and fixed_script:
105
+ st.info("Narration script was updated by the fallback. Regenerating audio...")
106
+ logging.info("Regenerating audio for updated script.")
107
+ current_script = fixed_script
108
+ try:
109
+ current_audio_file = generate_audio(current_script)
110
+ except ValueError as e:
111
+ st.warning(f"Could not generate audio for fixed script: {e}. Proceeding without audio.")
112
+ current_audio_file = None
113
+ elif not fixed_script:
114
+ st.warning("Fallback provided code but no narration. Using original audio (if any).")
115
+ logging.warning("Fallback provided empty narration.")
116
+ current_script = ""
117
+ current_audio_file = None
118
+ else:
119
+ logging.info("Fallback kept the original narration.")
120
+ else:
121
+ st.error("Fallback failed to fix the code. Stopping.")
122
+ logging.error("Fallback failed to return valid code/script.")
123
+ final_video = None
124
+ break
125
+ else:
126
+ st.error(f"Manim failed after {max_retries + 1} attempts. Could not generate video.")
127
+ logging.error(f"Manim failed after {max_retries + 1} attempts.")
128
+ final_video = None
129
+ except Exception as e:
130
+ st.error(f"An unexpected error occurred during video creation: {str(e)}")
131
+ logging.exception("Unexpected error during create_manim_video call.")
132
+ final_video = None
133
+ break
134
+
135
+ if final_video and os.path.exists(final_video):
136
+ st.success("Video generated successfully!")
137
+ st.video(final_video)
138
+ st.write("Generated Narration:")
139
+ st.text_area("Narration", current_script if current_script is not None else "Narration could not be generated.", height=150)
140
+ elif not final_video:
141
+ pass
142
+ else:
143
+ st.error("Error: Generated video file not found after processing.")
144
+ logging.error(f"Final video file '{final_video}' not found.")
145
+
146
+ except FileNotFoundError as e:
147
+ st.error(f"Error: A required file was not found. {str(e)}")
148
+ logging.exception("FileNotFoundError during generation process.")
149
+ except ValueError as e:
150
+ st.error(f"Input Error: {str(e)}")
151
+ logging.exception("ValueError during generation process.")
152
+ except Exception as e:
153
+ st.error(f"An unexpected error occurred: {str(e)}")
154
+ logging.exception("Unhandled exception in main generation block.")
155
+ finally:
156
+ if temp_pdf_file and os.path.exists(temp_pdf_file):
157
+ try:
158
+ os.remove(temp_pdf_file)
159
+ logging.info(f"Removed temporary file: {temp_pdf_file}")
160
+ except OSError as e:
161
+ logging.error(f"Error removing temporary file {temp_pdf_file}: {e}")
162
+ if audio_file and os.path.exists(audio_file) and audio_file != current_audio_file:
163
+ try:
164
+ os.remove(audio_file)
165
+ logging.info(f"Removed temporary audio file: {audio_file}")
166
+ except OSError as e:
167
+ logging.error(f"Error removing temporary audio file {audio_file}: {e}")
168
+ if current_audio_file and os.path.exists(current_audio_file):
169
+ try:
170
+ os.remove(current_audio_file)
171
+ logging.info(f"Removed potentially updated temporary audio file: {current_audio_file}")
172
+ except OSError as e:
173
+ logging.error(f"Error removing potentially updated temporary audio file {current_audio_file}: {e}")
174
+ st.markdown("<br><br>", unsafe_allow_html=True)
175
+ st.markdown("---")
176
+
177
+
178
+ st.markdown("""
179
+ ### Want to help improve this app?
180
+ - Give good Manim Examples and make PRs in guide.md, find it in repo [GitHub](https://github.com/mostlykiguess/Manimator)
181
+ - Report issues on [GitHub Issues](https://github.com/mostlykiguess/Manimator/issues)
182
+ - Email problematic prompts to me
183
+ """)
184
+
185
+
186
+ if __name__ == "__main__":
187
+ main()
src/services/manim_service.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ import subprocess
3
+ import os
4
+ import glob
5
+ import logging
6
+
7
+ def get_scene_name(manim_code):
8
+ match = re.search(r'class\s+(\w+)\s*\(\s*Scene\s*\)', manim_code)
9
+ if match:
10
+ return match.group(1)
11
+ raise ValueError("No Scene class found in generated code")
12
+
13
+ def create_manim_video(video_data, manim_code, audio_file=None):
14
+ logging.info("Starting to create Manim video")
15
+ with open("generated_video.py", "w") as f:
16
+ manim_code_clean = re.sub(r"```python", "", manim_code)
17
+ manim_code_clean = manim_code_clean.replace("```", "").strip()
18
+ f.write(manim_code_clean)
19
+
20
+ scene_name = get_scene_name(manim_code_clean)
21
+ logging.info(f"Identified scene name: {scene_name}")
22
+
23
+ command = ["manim", "-qh", "generated_video.py", scene_name]
24
+ logging.info(f"Running Manim with command: {' '.join(command)}")
25
+ subprocess.run(command, check=True)
26
+
27
+ search_pattern = os.path.join("media", "videos", "generated_video", "1080p60", f"{scene_name}.mp4")
28
+ if not os.path.exists(search_pattern):
29
+ logging.error(f"No rendered video found at: {search_pattern}")
30
+ raise Exception(f"No rendered video found for scene {scene_name}")
31
+
32
+ output_video = search_pattern
33
+ final_output = "final_output.mp4"
34
+
35
+ if audio_file and os.path.exists(audio_file):
36
+ logging.info(f"Merging video with audio file: {audio_file}")
37
+
38
+ video_duration_cmd = ["ffprobe", "-v", "error", "-show_entries", "format=duration",
39
+ "-of", "default=noprint_wrappers=1:nokey=1", output_video]
40
+ audio_duration_cmd = ["ffprobe", "-v", "error", "-show_entries", "format=duration",
41
+ "-of", "default=noprint_wrappers=1:nokey=1", audio_file]
42
+
43
+ video_duration = float(subprocess.check_output(video_duration_cmd).decode('utf-8').strip())
44
+ audio_duration = float(subprocess.check_output(audio_duration_cmd).decode('utf-8').strip())
45
+
46
+ logging.info(f"Video duration: {video_duration}s, Audio duration: {audio_duration}s")
47
+
48
+ if audio_duration > video_duration:
49
+ logging.info("Audio is longer than video, extending video duration")
50
+ extended_video = "extended_video.mp4"
51
+ padding_time = audio_duration - video_duration
52
+
53
+ extend_cmd = [
54
+ "ffmpeg", "-y",
55
+ "-i", output_video,
56
+ "-f", "lavfi", "-i", "color=black:s=1920x1080:r=60",
57
+ "-filter_complex", f"[0:v][1:v]concat=n=2:v=1:a=0[outv]",
58
+ "-map", "[outv]",
59
+ "-c:v", "libx264",
60
+ "-t", str(audio_duration),
61
+ extended_video
62
+ ]
63
+
64
+ logging.info(f"Extending video with command: {' '.join(extend_cmd)}")
65
+ subprocess.run(extend_cmd, check=True)
66
+ output_video = extended_video
67
+
68
+ merge_cmd = [
69
+ "ffmpeg", "-y",
70
+ "-i", output_video,
71
+ "-i", audio_file,
72
+ "-c:v", "copy",
73
+ "-c:a", "aac",
74
+ "-map", "0:v:0",
75
+ "-map", "1:a:0",
76
+ final_output
77
+ ]
78
+
79
+ logging.info(f"Merging with command: {' '.join(merge_cmd)}")
80
+ subprocess.run(merge_cmd, check=True)
81
+ output_video = final_output
82
+
83
+ if os.path.exists("extended_video.mp4"):
84
+ os.remove("extended_video.mp4")
85
+ logging.info("Removed temporary extended video file")
86
+
87
+ if os.path.exists("generated_video.py"):
88
+ os.remove("generated_video.py")
89
+ logging.info("Removed generated_video.py")
90
+
91
+ logging.info(f"Final video created at: {output_video}")
92
+ return output_video
src/services/tts_service.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from kokoro import KPipeline
2
+ import soundfile as sf
3
+ import os
4
+ from typing import Optional
5
+
6
+ class TTSService:
7
+ def __init__(self, lang_code: str = 'a'):
8
+ """Initialize the TTS service with Kokoro"""
9
+ self.pipeline = KPipeline(lang_code=lang_code)
10
+ self.voice_presets = {
11
+ 'en-us': 'af_heart', # American English
12
+ 'en-uk': 'bf_heart', # British English
13
+ 'es': 'es_heart', # Spanish
14
+ 'fr': 'fr_heart', # French
15
+ 'hi': 'hi_heart', # Hindi
16
+ 'it': 'it_heart', # Italian
17
+ 'pt-br': 'pt_heart', # Brazilian Portuguese
18
+ 'ja': 'ja_heart', # Japanese
19
+ 'zh': 'zh_heart', # Mandarin Chinese
20
+ }
21
+
22
+ def generate(self, text: str, voice: str = 'en-us', output_path: Optional[str] = None) -> str:
23
+ if not text:
24
+ raise ValueError("Text cannot be empty")
25
+
26
+ if voice not in self.voice_presets:
27
+ raise ValueError(f"Unsupported voice: {voice}. Available voices: {list(self.voice_presets.keys())}")
28
+
29
+ if output_path is None:
30
+ output_path = f'output_{voice}.wav'
31
+
32
+ generator = self.pipeline(text, voice=self.voice_presets[voice], speed=1, split_pattern=r'\n+')
33
+ audio_data = []
34
+ for _, _, audio in generator:
35
+ audio_data.extend(audio)
36
+
37
+ sf.write(output_path, audio_data, 24000)
38
+
39
+ return output_path
40
+
41
+ def generate_audio(text: str, voice: str = 'en-us') -> str:
42
+ """Generate audio from text using Kokoro TTS"""
43
+ service = TTSService()
44
+ return service.generate(text, voice)
src/tests/test_services.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # generated by AI to test stuff
2
+ # Python
3
+ import os
4
+ import glob
5
+ import time
6
+ import unittest
7
+ import subprocess
8
+
9
+ from services.tts_service import generate_audio
10
+ from services.manim_service import create_manim_video
11
+
12
+ # Import AudioSegment from pydub to check audio properties.
13
+ from pydub import AudioSegment
14
+
15
+
16
+ class TestTTSService(unittest.TestCase):
17
+ def setUp(self):
18
+ # Cleanup previous output file if exists.
19
+ self.audio_file = "output.wav"
20
+ if os.path.exists(self.audio_file):
21
+ os.remove(self.audio_file)
22
+
23
+ def test_generate_audio(self):
24
+ sample_text = "This is a test narration for the TTS service."
25
+ output_file = generate_audio(sample_text)
26
+ # Check that the file was created and is non-empty.
27
+ self.assertTrue(os.path.exists(output_file), "TTS output file was not created.")
28
+ self.assertGreater(os.path.getsize(output_file), 0, "TTS output file is empty.")
29
+
30
+ # Load the generated audio to check its duration and loudness.
31
+ audio = AudioSegment.from_wav(output_file)
32
+ self.assertGreater(audio.duration_seconds, 0, "TTS audio file has zero duration.")
33
+ self.assertNotEqual(audio.dBFS, float("-inf"), "Generated audio is completely silent.")
34
+ self.assertGreater(audio.dBFS, -35, "Audio seems too quiet; it may be silent.")
35
+
36
+ # Leave the file on disk so it can be inspected.
37
+ print(f"Test audio file saved at: {os.path.abspath(output_file)}")
38
+
39
+
40
+
41
+ class TestManimService(unittest.TestCase):
42
+ def setUp(self):
43
+ # Remove the generated video python file if it exists.
44
+ self.manim_py = "generated_video.py"
45
+ if os.path.exists(self.manim_py):
46
+ os.remove(self.manim_py)
47
+ # Remove previous output videos from Manim by searching the typical output folder.
48
+ self.video_files = glob.glob("media/videos/generated_video/**/*.mp4", recursive=True)
49
+ for f in self.video_files:
50
+ os.remove(f)
51
+
52
+ def test_create_manim_video_with_audio(self):
53
+ # Create a dummy manim code that creates a scene lasting at least 5 seconds.
54
+ dummy_code = """
55
+ from manim import *
56
+
57
+ class TestScene(Scene):
58
+ def construct(self):
59
+ self.wait(5)
60
+ """
61
+ video_data = {"output_file": "output.mp4", "manim_code": dummy_code}
62
+
63
+ # Generate a TTS audio so we have an audio file for merging.
64
+ audio_file = generate_audio("Test narration for merging with the Manim video.")
65
+ self.assertTrue(os.path.exists(audio_file), "TTS audio file for merging was not created.")
66
+
67
+ # Call the service that writes code, renders video, and merges audio using Manim.
68
+ create_manim_video(video_data, dummy_code, audio_file=audio_file)
69
+
70
+ # Allow enough time for Manim to finish rendering and merging.
71
+ time.sleep(10)
72
+
73
+ # Try to find the output video.
74
+ video_paths = glob.glob("media/videos/generated_video/**/*.mp4", recursive=True)
75
+ if not video_paths:
76
+ # Fallback in case the output video is in the current directory.
77
+ self.assertTrue(os.path.exists("output.mp4"), "No video file was produced by Manim.")
78
+ # Add these additional test methods to your existing test classes:
79
+
80
+ def test_generate_audio_empty_text(self):
81
+ """Test TTS service with empty text input"""
82
+ with self.assertRaises(ValueError):
83
+ generate_audio("")
84
+
85
+ def test_generate_audio_long_text(self):
86
+ """Test TTS with longer text input"""
87
+ long_text = "This is a longer test narrative. " * 10
88
+ output_file = generate_audio(long_text)
89
+ self.assertTrue(os.path.exists(output_file))
90
+ audio = AudioSegment.from_mp3(output_file)
91
+ self.assertGreater(audio.duration_seconds, 5)
92
+ os.remove(output_file)
93
+
94
+ def test_create_manim_video_without_audio(self):
95
+ """Test video creation without audio"""
96
+ dummy_code = """
97
+ class TestScene(Scene):
98
+ def construct(self):
99
+ circle = Circle()
100
+ self.play(Create(circle))
101
+ self.wait(2)
102
+ """
103
+ video_data = {"output_file": "output.mp4", "manim_code": dummy_code}
104
+ create_manim_video(video_data, dummy_code)
105
+
106
+ time.sleep(5)
107
+ video_paths = glob.glob("media/videos/generated_video/**/*.mp4", recursive=True)
108
+ self.assertTrue(video_paths, "No video file was produced")
109
+
110
+ for f in video_paths:
111
+ self.assertGreater(os.path.getsize(f), 0)
112
+ os.remove(f)
113
+
114
+ def test_create_manim_video_invalid_code(self):
115
+ """Test handling of invalid Manim code"""
116
+ invalid_code = "This is not valid Python code"
117
+ video_data = {"output_file": "output.mp4", "manim_code": invalid_code}
118
+ with self.assertRaises(subprocess.CalledProcessError):
119
+ create_manim_video(video_data, invalid_code)
120
+
121
+ def test_create_manim_video_with_text(self):
122
+ """Test video creation with text elements"""
123
+ code_with_text = """
124
+ class TextScene(Scene):
125
+ def construct(self):
126
+ text = Text("Hello World")
127
+ self.play(Write(text))
128
+ self.wait(2)
129
+ """
130
+ video_data = {"output_file": "output.mp4", "manim_code": code_with_text}
131
+ create_manim_video(video_data, code_with_text)
132
+
133
+ time.sleep(5)
134
+ video_paths = glob.glob("media/videos/generated_video/**/*.mp4", recursive=True)
135
+ self.assertTrue(video_paths)
136
+
137
+ for f in video_paths:
138
+ self.assertGreater(os.path.getsize(f), 0)
139
+ os.remove(f)
140
+
141
+ def test_audio_video_sync(self):
142
+ """Test audio-video synchronization"""
143
+ dummy_code = """
144
+ class SyncScene(Scene):
145
+ def construct(self):
146
+ circle = Circle()
147
+ self.play(Create(circle), run_time=3)
148
+ self.wait(2)
149
+ """
150
+ video_data = {"output_file": "output.mp4", "manim_code": dummy_code}
151
+ audio_text = "This circle appears over three seconds and then waits for two more seconds."
152
+ audio_file = generate_audio(audio_text)
153
+
154
+ create_manim_video(video_data, dummy_code, audio_file=audio_file)
155
+
156
+ time.sleep(10)
157
+ video_paths = glob.glob("media/videos/generated_video/**/*.mp4", recursive=True)
158
+ self.assertTrue(video_paths)
159
+
160
+ # Clean up
161
+ for f in video_paths:
162
+ os.remove(f)
163
+ os.remove(audio_file)