-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathv0.py
More file actions
2189 lines (1839 loc) · 98.4 KB
/
v0.py
File metadata and controls
2189 lines (1839 loc) · 98.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import re
import json
import logging
from dotenv import load_dotenv
import textwrap # Added to normalize indentation
from langchain.chains import ConversationChain
from langchain_core.prompts import ChatPromptTemplate, HumanMessagePromptTemplate, MessagesPlaceholder
from langchain_core.messages import SystemMessage
from langchain.chains.conversation.memory import ConversationBufferWindowMemory
from langchain_google_genai import ChatGoogleGenerativeAI
# Basic logging configuration
logging.basicConfig(level=logging.INFO)
logging.getLogger('comtypes').setLevel(logging.WARNING)
load_dotenv('.env')
class ManIMCodeGenerator:
def __init__(self, google_api_key):
self.google_api_key = google_api_key
self.memory = ConversationBufferWindowMemory(k=3, memory_key="chat_history", return_messages=True)
self.google_chat = ChatGoogleGenerativeAI(
model="gemini-2.0-flash",
google_api_key=self.google_api_key,
temperature=0.7,
max_tokens=None,
timeout=None,
max_retries=2
)
# Enhanced Manim code generation prompt
self.manim_prompt = self._create_manim_generation_prompt()
# Manim conversation chain
self.manim_conversation = ConversationChain(
llm=self.google_chat,
prompt=self.manim_prompt,
verbose=True,
memory=self.memory,
input_key="human_input",
)
def generate_3b1b_manim_code(self, video_plan):
"""
Generate comprehensive, dynamic Manim code following 3Blue1Brown style.
This creates step-by-step animations with:
- Rich visual elements and smooth transitions
- Dynamic positioning and movement
- Scene progression without overlapping text
- Educational flow based on the video plan structure
Args:
video_plan (dict): Complete video plan from script generator
Returns:
str: Complete Manim Python code ready for execution
"""
if not video_plan:
raise ValueError("No video plan provided")
educational_breakdown = video_plan.get("educational_breakdown", {})
manim_structure = video_plan.get("manim_structure", {})
if not educational_breakdown:
raise ValueError("No educational content available")
try:
print("🎨 Generating Advanced Manim Code...")
print("📚 Topic: {}".format(educational_breakdown.get('title', 'Unknown')))
print("🎯 Educational Steps: {}".format(len(educational_breakdown.get('educational_steps', []))))
print("=" * 60)
# Display video plan details in terminal
self._display_video_plan(video_plan)
# Build comprehensive prompt for Manim code generation
manim_prompt = self._build_advanced_manim_prompt(video_plan)
print("🔄 Processing with AI...")
response = self.manim_conversation.predict(human_input=manim_prompt)
# Extract and validate Manim code
manim_code = self._extract_manim_code(response)
# Validate and fix the code to remove image references
if manim_code:
manim_code = self._validate_and_fix_manim_code(manim_code)
if manim_code:
print("✅ Advanced Manim Code Generated Successfully!")
print("📝 Code Length: {} characters".format(len(manim_code)))
print("🎬 Ready for animation rendering!")
# Display generated manim code in terminal
self._display_manim_code(manim_code)
return manim_code
else:
raise Exception("Code extraction failed")
except Exception as e:
print("❌ Error in Manim code generation: {}".format(e))
raise
def _build_advanced_manim_prompt(self, video_plan):
"""
Build a comprehensive prompt for advanced Manim code generation.
Args:
video_plan (dict): Complete video plan with educational breakdown
Returns:
str: Detailed prompt for Manim code generation
"""
educational_breakdown = video_plan.get("educational_breakdown", {})
manim_structure = video_plan.get("manim_structure", {})
title = educational_breakdown.get("title", "Educational Animation")
steps = educational_breakdown.get("educational_steps", [])
duration = educational_breakdown.get("metadata", {}).get("estimated_total_duration", 180)
prompt_parts = ["""
ADVANCED MANIM CODE GENERATION REQUEST
VIDEO PLAN TO IMPLEMENT:
Title: {title}
Duration: {duration} seconds
Educational Steps: {steps_count}""".format(title=title, duration=duration, steps_count=len(steps)) + """
REQUIREMENTS FOR MANIM CODE:
🎯 EDUCATIONAL FLOW:
- Convert each educational step into a distinct scene method
- Maintain pedagogical progression from the video plan
- Use dynamic positioning and smooth transitions
- Create engaging visual storytelling
🎨 ANIMATION STYLE (3Blue1Brown Inspired):
- Rich visual elements with proper spacing
- Dynamic camera movements when appropriate
- Smooth object transformations and reveals
- Color-coded elements for better understanding
- Mathematical notation rendered clearly
- No overlapping text or crowded scenes
🏗️ CODE STRUCTURE REQUIREMENTS:
- Main scene class inheriting from Scene
- Separate methods for each educational step
- construct() method orchestrating the flow
- Proper imports and dependencies
- Clean, well-documented code
- Modular design for easy modification
🎬 ANIMATION TECHNIQUES:
- Use Write(), FadeIn(), Transform(), Create() appropriately
- Implement proper timing with self.wait()
- Position elements using UP, DOWN, LEFT, RIGHT vectors
- Scale and rotate objects for visual interest
- Use color schemes that enhance understanding
- Clear scene transitions between steps
📊 VISUAL ELEMENTS TO INCLUDE:
- Title animations with engaging reveals
- Step-by-step concept introductions
- Mathematical equations and formulas
- Diagrams and geometric shapes (using built-in Manim objects)
- Text labels and annotations
- Real-world example descriptions (text-based, NO ImageMobject)
- Summary and key takeaway displays
⚠️ CRITICAL CONSTRAINTS:
- DO NOT use ImageMobject or any image file references
- Use only text, shapes, and built-in Manim objects
- Create visual diagrams using Circle, Rectangle, Line, etc.
- Represent real-world examples with text descriptions and geometric visualizations
- Focus on mathematical notation, graphs, and animated text elements
⚡ DYNAMIC FEATURES & SCENE MANAGEMENT:
- Objects that move and transform with smooth transitions
- Reveal animations for key concepts (Write, FadeIn, Transform)
- Highlighting and emphasis effects (Indicate, Flash, Wiggle)
- Clear scene transitions - remove old content before adding new
- Use self.clear() or FadeOut() to clean scenes between steps
- Dynamic positioning - move objects to different locations
- Interactive-style demonstrations with step-by-step reveals
- Progressive complexity building with animated transformations
- Avoid static layouts - everything should move and change
- No overlapping text - use proper spacing and timing
- Create visual flow with object movements and morphing
🎯 MANDATORY POSITIONING RULES:
- NEVER place text in the same position (0,0) or ORIGIN
- Use UP, DOWN, LEFT, RIGHT with multipliers (2*UP, 3*LEFT, etc.)
- Position titles at 3*UP, subtitles at 2*UP, content at ORIGIN to DOWN
- Move previous content OFF-SCREEN before adding new content
- Use .shift(LEFT*4) or .shift(RIGHT*4) to move objects sideways
- Scale objects (.scale(0.8)) to fit more content without overlap
- Always animate movements: self.play(obj.animate.shift(UP*2))
📺 16:9 ASPECT RATIO OPTIMIZATION:
- Standard Manim resolution is 1920x1080 (16:9)
- Horizontal safe zone: X positions from -7 to +7 units
- Vertical safe zone: Y positions from -4 to +4 units
- NEVER position text beyond X=±6 or Y=±3.5 to prevent cutoff
- Use .scale() to fit longer text instead of extending beyond screen bounds
- Position titles between Y=2.5 to Y=3.5 for optimal visibility
- Place main content between Y=-0.5 to Y=2 for best readability
- Use LEFT=-5, RIGHT=5 for wide layouts, LEFT=-3, RIGHT=3 for compact layouts
- Test positioning: title.shift(UP*3) should never go beyond screen top
- For wide equations, use font_size reduction instead of horizontal overflow
🚫 TEXT OVERLAP PREVENTION SYSTEM:
- MANDATORY: Track used positions and avoid conflicts
- Create position grid system: UP*3, UP*2, UP*1, ORIGIN, DOWN*1, DOWN*2, DOWN*3
- Horizontal slots: LEFT*4, LEFT*2, ORIGIN, RIGHT*2, RIGHT*4
- NEVER place two Text objects at same coordinates simultaneously
- Use .next_to() for automatic positioning relative to other objects
- Implement z-layering with .set_z_index() when objects must overlap
- Clear screen completely between major sections: self.play(FadeOut(*self.mobjects))
- Move existing objects before adding new ones: old_text.animate.shift(UP*1)
- Use VGroup() to manage multiple related text elements as single unit
- Stagger positioning: first text at UP*2, second at ORIGIN, third at DOWN*2
🎭 DYNAMIC VISUAL EXPLANATION REQUIREMENTS:
- EVERY concept must have animated visual representation
- Transform abstract ideas into moving geometric shapes
- Use morphing animations: circle.animate.transform(square)
- Implement step-by-step reveals with Write(), FadeIn(), Create()
- Show mathematical relationships through connecting arrows and lines
- Use color changes to highlight transformations: obj.animate.set_color(YELLOW)
- Create animated comparisons: split screen with before/after animations
- Build complexity progressively: start simple, add details with each step
- Use Indicate(), Flash(), Wiggle() to emphasize key moments
- Implement object journeys: move elements across screen to show relationships
- Create visual metaphors using basic shapes and their transformations
- Use growth animations: GrowFromCenter(), DrawBorderThenFill()
- Show cause-and-effect through animated sequences
- Implement visual proofs through animated geometric demonstrations
🎬 REQUIRED ANIMATION PATTERNS:
- Start each section by clearing: self.play(FadeOut(*self.mobjects))
- Introduce titles with Write() animation
- Move titles up: self.play(title.animate.shift(UP*2))
- Add content below with different Y positions
- Use Transform() to change content, not create new overlapping text
- End sections with content moving off-screen or fading out
🎬 ADVANCED DYNAMIC ANIMATION REQUIREMENTS:
- NO STATIC SCENES: Everything must move, transform, or animate
- Use continuous motion: objects entering, moving, transforming, exiting
- Implement smooth transitions between all visual elements
- Create visual flow: guide viewer's eye with moving objects
- Use multiple simultaneous animations: self.play(obj1.animate.shift(), obj2.animate.scale())
- Implement entrance animations: objects slide in from edges of screen
- Use exit animations: objects fade out or slide away before new content
- Create animated connections: lines/arrows that draw between related concepts
- Implement progressive disclosure: reveal information piece by piece
- Use animated highlighting: temporary color changes, scaling, rotation
- Create visual rhythms: alternating fast and slow animations for pacing
- Build anticipation: use small movements before major reveals
- Implement visual callbacks: return to previous elements with animations
💥 VISUAL EXPLANATION DYNAMICS:
- Transform equations step-by-step with intermediate states visible
- Use animated graphs that draw themselves progressively
- Create moving diagrams that demonstrate concepts in action
- Implement split-screen comparisons with synchronized animations
- Use object multiplication: show one object becoming many
- Create animated timelines: show progression of ideas over time
- Use perspective shifts: rotate 2D diagrams to show 3D relationships
- Implement animated analogies: transform familiar objects into mathematical concepts
- Create visual stories: sequences of scenes that build understanding
- Use animated emphasis: zoom, highlight, circle key elements temporarily
- Implement interactive-style reveals: as if responding to questions
- Create animated proofs: visual demonstrations that prove mathematical statements
🎨 VISUAL VARIETY REQUIREMENTS:
- Use different font sizes: font_size=48 for titles, 36 for subtitles, 24 for content
- Use colors: BLUE for titles, WHITE for content, YELLOW for emphasis
- Create diagrams with Circle(), Rectangle(), Line() objects
- Position diagrams LEFT and text RIGHT, or vice versa
- Use arrows (Arrow()) to connect related concepts
- Create mathematical plots with axes when relevant
🎨 ENHANCED VISUAL LAYOUT SYSTEM:
- Implement 3-column layout: LEFT (-4 to -2), ORIGIN (-1 to 1), RIGHT (2 to 4)
- Use 5-row system: TOP (Y=3), UPPER (Y=1.5), MIDDLE (Y=0), LOWER (Y=-1.5), BOTTOM (Y=-3)
- Create visual zones: Title zone (Y=2.5 to 3.5), Content zone (Y=-2 to 2), Footer zone (Y=-3 to -2)
- Use asymmetric layouts: 60% content area, 40% visual area for better balance
- Implement dynamic layouts that change during animation
- Create visual breathing room: minimum 0.5 unit spacing between text elements
- Use strategic white space: don't fill every pixel, leave empty areas for visual rest
- Scale elements responsively: larger diagrams get .scale(0.8), smaller text gets font_size=20
- Create visual hierarchy through size, color, and position combinations
- Use consistent margin system: 0.5 units from screen edges for all content
🎯 POSITIONING COORDINATION SYSTEM:
- Before placing any object, check what's already on screen
- Use incremental positioning: if UP*2 is taken, use UP*2.5 or UP*1.5
- Implement content zones: never place title text in diagram zone
- Create movement corridors: paths for objects to enter/exit without collision
- Use depth layering: background elements, main content, highlighting overlays
- Implement position memory: track where each object has been placed
- Use relative positioning: new_obj.next_to(existing_obj, direction=RIGHT, buff=0.5)
- Create position validation: ensure no object extends beyond screen boundaries
- Use smart scaling: automatically reduce font_size if text doesn't fit in allocated space
- Implement collision detection: check for overlap before finalizing positions
⚠️ CRITICAL MANIM POSITIONING CONSTANTS (MUST USE THESE EXACT NAMES):
- ORIGIN (center of screen, coordinates [0, 0, 0]) - NOT "CENTER"
- UP (positive Y direction)
- DOWN (negative Y direction)
- LEFT (negative X direction)
- RIGHT (positive X direction)
- UL (upper left), UR (upper right), DL (down left), DR (down right)
- Use multiples: UP*2, DOWN*3, LEFT*4, RIGHT*1.5
- Combine: UP*2 + LEFT*3, DOWN*1 + RIGHT*2
⚠️ NEVER USE THESE (they don't exist in Manim):
- CENTER (use ORIGIN instead)
- MIDDLE (use ORIGIN instead)
- TOP (use UP*3 instead)
- BOTTOM (use DOWN*3 instead)
📚 PROFESSIONAL MANIM EXAMPLES GALLERY:
Study these high-quality examples for code patterns and techniques:
Example 1: BraceAnnotation - Annotating geometric elements
```python
from manim import *
class BraceAnnotation(Scene):
def construct(self):
dot = Dot([-2, -1, 0])
dot2 = Dot([2, 1, 0])
line = Line(dot.get_center(), dot2.get_center()).set_color(ORANGE)
b1 = Brace(line)
b1text = b1.get_text("Horizontal distance")
b2 = Brace(line, direction=line.copy().rotate(PI / 2).get_unit_vector())
b2text = b2.get_tex("x-x_1")
self.add(line, dot, dot2, b1, b2, b1text, b2text)
```
Example 2: VectorArrow - Coordinate system visualization
```python
from manim import *
class VectorArrow(Scene):
def construct(self):
dot = Dot(ORIGIN)
arrow = Arrow(ORIGIN, [2, 2, 0], buff=0)
numberplane = NumberPlane()
origin_text = Text('(0, 0)').next_to(dot, DOWN)
tip_text = Text('(2, 2)').next_to(arrow.get_end(), RIGHT)
self.add(numberplane, dot, arrow, origin_text, tip_text)
```
Example 3: BooleanOperations - Interactive shape operations
```python
from manim import *
class BooleanOperations(Scene):
def construct(self):
ellipse1 = Ellipse(
width=4.0, height=5.0, fill_opacity=0.5, color=BLUE, stroke_width=10
).move_to(LEFT)
ellipse2 = ellipse1.copy().set_color(color=RED).move_to(RIGHT)
bool_ops_text = MarkupText("<u>Boolean Operation</u>").next_to(ellipse1, UP * 3)
ellipse_group = Group(bool_ops_text, ellipse1, ellipse2).move_to(LEFT * 3)
self.play(FadeIn(ellipse_group))
i = Intersection(ellipse1, ellipse2, color=GREEN, fill_opacity=0.5)
self.play(i.animate.scale(0.25).move_to(RIGHT * 5 + UP * 2.5))
intersection_text = Text("Intersection", font_size=23).next_to(i, UP)
self.play(FadeIn(intersection_text))
u = Union(ellipse1, ellipse2, color=ORANGE, fill_opacity=0.5)
union_text = Text("Union", font_size=23)
self.play(u.animate.scale(0.3).next_to(i, DOWN, buff=union_text.height * 3))
union_text.next_to(u, UP)
self.play(FadeIn(union_text))
```
Example 4: PointMovingOnShapes - Path animations and transformations
```python
from manim import *
class PointMovingOnShapes(Scene):
def construct(self):
circle = Circle(radius=1, color=BLUE)
dot = Dot()
dot2 = dot.copy().shift(RIGHT)
self.add(dot)
line = Line([3, 0, 0], [5, 0, 0])
self.add(line)
self.play(GrowFromCenter(circle))
self.play(Transform(dot, dot2))
self.play(MoveAlongPath(dot, circle), run_time=2, rate_func=linear)
self.play(Rotating(dot, about_point=[2, 0, 0]), run_time=1.5)
self.wait()
```
Example 5: MovingAround - Object transformations with animate
```python
from manim import *
class MovingAround(Scene):
def construct(self):
square = Square(color=BLUE, fill_opacity=1)
self.play(square.animate.shift(LEFT))
self.play(square.animate.set_fill(ORANGE))
self.play(square.animate.scale(0.3))
self.play(square.animate.rotate(0.4))
```
Example 6: MovingAngle - Dynamic angle measurement with updaters
```python
from manim import *
class MovingAngle(Scene):
def construct(self):
rotation_center = LEFT
theta_tracker = ValueTracker(110)
line1 = Line(LEFT, RIGHT)
line_moving = Line(LEFT, RIGHT)
line_ref = line_moving.copy()
line_moving.rotate(
theta_tracker.get_value() * DEGREES, about_point=rotation_center
)
a = Angle(line1, line_moving, radius=0.5, other_angle=False)
tex = MathTex(r"\theta").move_to(
Angle(
line1, line_moving, radius=0.5 + 3 * SMALL_BUFF, other_angle=False
).point_from_proportion(0.5)
)
self.add(line1, line_moving, a, tex)
self.wait()
line_moving.add_updater(
lambda x: x.become(line_ref.copy()).rotate(
theta_tracker.get_value() * DEGREES, about_point=rotation_center
)
)
a.add_updater(
lambda x: x.become(Angle(line1, line_moving, radius=0.5, other_angle=False))
)
tex.add_updater(
lambda x: x.move_to(
Angle(
line1, line_moving, radius=0.5 + 3 * SMALL_BUFF, other_angle=False
).point_from_proportion(0.5)
)
)
self.play(theta_tracker.animate.set_value(40))
self.play(theta_tracker.animate.increment_value(140))
self.play(tex.animate.set_color(RED), run_time=0.5)
self.play(theta_tracker.animate.set_value(350))
```
Example 7: MovingDots - Connected objects with updaters
```python
from manim import *
class MovingDots(Scene):
def construct(self):
d1,d2=Dot(color=BLUE),Dot(color=GREEN)
dg=VGroup(d1,d2).arrange(RIGHT,buff=1)
l1=Line(d1.get_center(),d2.get_center()).set_color(RED)
x=ValueTracker(0)
y=ValueTracker(0)
d1.add_updater(lambda z: z.set_x(x.get_value()))
d2.add_updater(lambda z: z.set_y(y.get_value()))
l1.add_updater(lambda z: z.become(Line(d1.get_center(),d2.get_center())))
self.add(d1,d2,l1)
self.play(x.animate.set_value(5))
self.play(y.animate.set_value(4))
self.wait()
```
Example 8: MovingFrameBox - Highlighting mathematical expressions
```python
from manim import *
class MovingFrameBox(Scene):
def construct(self):
self.play(Write(text))
framebox1 = SurroundingRectangle(text[1], buff = .1)
framebox2 = SurroundingRectangle(text[3], buff = .1)
self.play(Create(framebox1))
self.wait()
self.play(ReplacementTransform(framebox1,framebox2))
self.wait()
```
Example 9: SinAndCosFunctionPlot - Mathematical function plotting
```python
from manim import *
class SinAndCosFunctionPlot(Scene):
def construct(self):
axes = Axes(
x_range=[-10, 10.3, 1],
y_range=[-1.5, 1.5, 1],
x_length=10,
axis_config={"color": GREEN},
x_axis_config={
"numbers_to_include": np.arange(-10, 10.01, 2),
"numbers_with_elongated_ticks": np.arange(-10, 10.01, 2),
},
tips=False,
)
axes_labels = axes.get_axis_labels()
sin_graph = axes.plot(lambda x: np.sin(x), color=BLUE)
cos_graph = axes.plot(lambda x: np.cos(x), color=RED)
sin_label = axes.get_graph_label(
sin_graph, "\\sin(x)", x_val=-10, direction=UP / 2
)
cos_label = axes.get_graph_label(cos_graph, label="\\cos(x)")
vert_line = axes.get_vertical_line(
axes.i2gp(TAU, cos_graph), color=YELLOW, line_func=Line
)
line_label = axes.get_graph_label(
cos_graph, r"x=2\pi", x_val=TAU, direction=UR, color=WHITE
)
plot = VGroup(axes, sin_graph, cos_graph, vert_line)
labels = VGroup(axes_labels, sin_label, cos_label, line_label)
self.add(plot, labels)
```
Example 10: ArgMinExample - Interactive optimization visualization
```python
from manim import *
class ArgMinExample(Scene):
def construct(self):
ax = Axes(
x_range=[0, 10], y_range=[0, 100, 10], axis_config={"include_tip": False}
)
labels = ax.get_axis_labels(x_label="x", y_label="f(x)")
t = ValueTracker(0)
def func(x):
return 2 * (x - 5) ** 2
graph = ax.plot(func, color=MAROON)
initial_point = [ax.coords_to_point(t.get_value(), func(t.get_value()))]
dot = Dot(point=initial_point)
dot.add_updater(lambda x: x.move_to(ax.c2p(t.get_value(), func(t.get_value()))))
x_space = np.linspace(*ax.x_range[:2],200)
minimum_index = func(x_space).argmin()
self.add(ax, labels, graph, dot)
self.play(t.animate.set_value(x_space[minimum_index]))
self.wait()
```
Example 11: GraphAreaPlot - Area under curves and Riemann rectangles
```python
from manim import *
class GraphAreaPlot(Scene):
def construct(self):
ax = Axes(
x_range=[0, 5],
y_range=[0, 6],
x_axis_config={"numbers_to_include": [2, 3]},
tips=False,
)
labels = ax.get_axis_labels()
curve_1 = ax.plot(lambda x: 4 * x - x ** 2, x_range=[0, 4], color=BLUE_C)
curve_2 = ax.plot(
lambda x: 0.8 * x ** 2 - 3 * x + 4,
x_range=[0, 4],
color=GREEN_B,
)
line_1 = ax.get_vertical_line(ax.input_to_graph_point(2, curve_1), color=YELLOW)
line_2 = ax.get_vertical_line(ax.i2gp(3, curve_1), color=YELLOW)
riemann_area = ax.get_riemann_rectangles(curve_1, x_range=[0.3, 0.6], dx=0.03, color=BLUE, fill_opacity=0.5)
area = ax.get_area(curve_2, [2, 3], bounded_graph=curve_1, color=GREY, opacity=0.5)
self.add(ax, labels, curve_1, curve_2, line_1, line_2, riemann_area, area)
```
Example 12: PolygonOnAxes - Dynamic polygon areas with value tracking
```python
from manim import *
class PolygonOnAxes(Scene):
def get_rectangle_corners(self, bottom_left, top_right):
return [
(top_right[0], top_right[1]),
(bottom_left[0], top_right[1]),
(bottom_left[0], bottom_left[1]),
(top_right[0], bottom_left[1]),
]
def construct(self):
ax = Axes(
x_range=[0, 10],
y_range=[0, 10],
x_length=6,
y_length=6,
axis_config={"include_tip": False},
)
t = ValueTracker(5)
k = 25
graph = ax.plot(
lambda x: k / x,
color=YELLOW_D,
x_range=[k / 10, 10.0, 0.01],
use_smoothing=False,
)
def get_rectangle():
polygon = Polygon(
*[
ax.c2p(*i)
for i in self.get_rectangle_corners(
(0, 0), (t.get_value(), k / t.get_value())
)
]
)
polygon.stroke_width = 1
polygon.set_fill(BLUE, opacity=0.5)
polygon.set_stroke(YELLOW_B)
return polygon
polygon = always_redraw(get_rectangle)
dot = Dot()
dot.add_updater(lambda x: x.move_to(ax.c2p(t.get_value(), k / t.get_value())))
dot.set_z_index(10)
self.add(ax, graph, dot)
self.play(Create(polygon))
self.play(t.animate.set_value(10))
self.play(t.animate.set_value(k / 10))
self.play(t.animate.set_value(5))
```
Example 13: HeatDiagramPlot - Scientific data visualization
```python
from manim import *
class HeatDiagramPlot(Scene):
def construct(self):
ax = Axes(
x_range=[0, 40, 5],
y_range=[-8, 32, 5],
x_length=9,
y_length=6,
x_axis_config={"numbers_to_include": np.arange(0, 40, 5)},
y_axis_config={"numbers_to_include": np.arange(-5, 34, 5)},
tips=False,
)
labels = ax.get_axis_labels(
x_label=Tex(r"$\Delta Q$"), y_label=Tex(r"T[$^\circ C$]")
)
x_vals = [0, 8, 38, 39]
y_vals = [20, 0, 0, -5]
graph = ax.plot_line_graph(x_values=x_vals, y_values=y_vals)
self.add(ax, labels, graph)
```
Example 14: FollowingGraphCamera - Advanced camera movements
```python
from manim import *
class FollowingGraphCamera(MovingCameraScene):
def construct(self):
self.camera.frame.save_state()
# create the axes and the curve
ax = Axes(x_range=[-1, 10], y_range=[-1, 10])
graph = ax.plot(lambda x: np.sin(x), color=BLUE, x_range=[0, 3 * PI])
# create dots based on the graph
moving_dot = Dot(ax.i2gp(graph.t_min, graph), color=ORANGE)
dot_1 = Dot(ax.i2gp(graph.t_min, graph))
dot_2 = Dot(ax.i2gp(graph.t_max, graph))
self.add(ax, graph, dot_1, dot_2, moving_dot)
self.play(self.camera.frame.animate.scale(0.5).move_to(moving_dot))
def update_curve(mob):
mob.move_to(moving_dot.get_center())
self.camera.frame.add_updater(update_curve)
self.play(MoveAlongPath(moving_dot, graph, rate_func=linear))
self.camera.frame.remove_updater(update_curve)
self.play(Restore(self.camera.frame))
```
Example 15: ThreeDSurfacePlot - 3D mathematical surfaces
```python
from manim import *
class ThreeDSurfacePlot(ThreeDScene):
def construct(self):
resolution_fa = 24
self.set_camera_orientation(phi=75 * DEGREES, theta=-30 * DEGREES)
def param_gauss(u, v):
x = u
y = v
sigma, mu = 0.4, [0.0, 0.0]
d = np.linalg.norm(np.array([x - mu[0], y - mu[1]]))
z = np.exp(-(d ** 2 / (2.0 * sigma ** 2)))
return np.array([x, y, z])
gauss_plane = Surface(
param_gauss,
resolution=(resolution_fa, resolution_fa),
v_range=[-2, +2],
u_range=[-2, +2]
)
gauss_plane.scale(2, about_point=ORIGIN)
gauss_plane.set_style(fill_opacity=1,stroke_color=GREEN)
gauss_plane.set_fill_by_checkerboard(ORANGE, BLUE, opacity=0.5)
axes = ThreeDAxes()
self.add(axes,gauss_plane)
```
🎓 KEY PATTERNS FROM EXAMPLES:
- Use ValueTracker() for dynamic values that change over time
- Implement .add_updater() for objects that need to update automatically
- Use always_redraw() for objects that need constant redrawing
- Combine VGroup() to manage multiple related objects
- Apply .animate for smooth transformations
- Use proper positioning with .next_to(), .move_to(), .shift()
- Create custom functions for complex mathematical visualizations
- Use axes.plot() for mathematical functions and axes.get_area() for regions
- Implement SurroundingRectangle() for highlighting elements
- Use MathTex() for mathematical expressions and Text() for regular text
- Apply proper color schemes and opacity for visual clarity
- Use .set_z_index() to control layering of objects
EDUCATIONAL STEPS TO IMPLEMENT:"""]
# Add detailed information about each educational step
for i, step in enumerate(steps, 1):
step_title = step.get('step_title', 'Step {}'.format(i))
prompt_parts.append("""
Step {step_num}: {step_title}
- Duration: {duration} seconds
- Key Concepts: {key_concepts}
- Narration: {narration}
- Visual Plan: {visual_plan}
- Visual Elements: {visual_elements}
- Equations: {equations}
- Real-world Examples: {examples}""".format(
step_num=i,
step_title=step_title,
duration=step.get('duration_seconds', 30),
key_concepts=', '.join(step.get('key_concepts', [])),
narration=step.get('narration_script', ''),
visual_plan=step.get('animation_plan', ''),
visual_elements=step.get('visual_elements', {}),
equations=step.get('equations', []),
examples=step.get('real_world_examples', [])
))
# Create class name safely outside f-string
class_name = title.replace(' ', '').replace(':', '').replace('(', '').replace(')', '').replace('-', '').replace("'", "").replace('"', '')
if not class_name:
class_name = "Educational"
complexity = educational_breakdown.get('metadata', {}).get('difficulty_progression', 'intermediate')
prompt_parts.append("""
TOTAL DURATION: {duration} seconds
TARGET COMPLEXITY: {complexity}
OUTPUT FORMAT:
Provide complete, executable Manim Python code following this structure:
```python
from manim import *
class {class_name}Scene(Scene):
def construct(self):""".format(duration=duration, complexity=complexity, class_name=class_name) + """
# Main orchestration method - CLEAR between each step
self.intro_sequence()
self.clear_and_transition()
self.step_1_introduction()
self.clear_and_transition()
self.step_2_core_concepts()
self.clear_and_transition()
# ... more steps as needed
self.conclusion_summary()
def clear_and_transition(self):
# Clean transition between sections
self.play(FadeOut(*self.mobjects))
self.wait(0.5)
def intro_sequence(self):
# Engaging introduction with DYNAMIC positioning
title = Text("{{title}}", font_size=48, color=BLUE).shift(UP*3)
subtitle = Text("Educational Animation", font_size=32, color=WHITE).shift(UP*1.5)
self.play(Write(title))
self.wait(0.5)
self.play(Write(subtitle))
self.wait(1)
# Move content and add more
self.play(
title.animate.shift(LEFT*3).scale(0.7),
subtitle.animate.shift(RIGHT*3).scale(0.8)
)
intro_text = Text("Let's explore this concept step by step",
font_size=24, color=YELLOW).shift(DOWN*1)
self.play(FadeIn(intro_text))
self.wait(2)
def step_1_introduction(self):
# First educational step - NEW positions, no overlap
step_title = Text("Step 1: Foundation", font_size=40, color=BLUE).shift(UP*2.5)
self.play(Write(step_title))
# Create diagram on LEFT, text on RIGHT
diagram = Circle(radius=1, color=WHITE).shift(LEFT*3)
explanation = Text("Key concept explanation\\nwith multiple lines",
font_size=20, color=WHITE).shift(RIGHT*2)
self.play(Create(diagram), Write(explanation))
self.wait(1)
# Transform and move
new_shape = Square(side_length=2, color=YELLOW).shift(LEFT*3)
self.play(Transform(diagram, new_shape))
# Add connecting arrow
arrow = Arrow(LEFT*1, RIGHT*0.5, color=GREEN)
self.play(Create(arrow))
self.wait(2)
# CONTINUE with similar patterns for each step...
```
CRITICAL REQUIREMENTS:
1. Generate COMPLETE, EXECUTABLE code
2. Include ALL necessary imports
3. Follow proper Manim syntax and conventions
4. Create visually appealing, educational animations
5. Ensure smooth flow between all steps
6. Use dynamic positioning - avoid static layouts
7. Include proper documentation and comments
8. Make the code modular and easy to understand
9. Optimize for visual clarity and educational impact
10. Follow the educational step progression exactly
11. Must Contain all necessary imports and class definitions
12. def construct() method must orchestrate the entire scene flow
13. ⚠️ NEVER use ImageMobject or image file references ⚠️
14. Use only built-in Manim objects (Text, MathTex, shapes, etc.)
15. Create visual representations using geometric shapes and text
16. Represent real-world examples with descriptive text and shape-based diagrams
17. ANIMATE EVERYTHING - no static content allowed
18. Use self.clear() or FadeOut(*self.mobjects) between major sections
19. Move objects around the screen dynamically with .animate.shift()
20. Transform objects instead of creating new ones in same position
21. Use proper spacing - NEVER overlap text at same coordinates
22. Implement smooth transitions between concepts
23. Create engaging visual flow with object movements
24. ONLY use valid Scene methods: self.add(), self.play(), self.wait(), self.clear(), self.remove()
25. NEVER use self.set_background() or similar invalid methods
26. ALWAYS position objects at different coordinates using UP*2, DOWN*1, LEFT*3, RIGHT*2
27. Clear screen between sections: self.play(FadeOut(*self.mobjects))
28. Use different font sizes to create hierarchy: 48 for titles, 36 for subtitles, 24 for content
🎯 16:9 ASPECT RATIO CRITICAL REQUIREMENTS:
29. NEVER position objects beyond X=±6.5 or Y=±3.8 (safe viewing area)
30. Use responsive scaling: if text doesn't fit, reduce font_size, don't extend bounds
31. Test all positions: title.shift(UP*3.5) should be maximum upward positioning
32. Implement automatic bounds checking for all object placements
33. Use .get_width() and .get_height() to verify objects fit within screen
34. Scale down oversized objects: if obj.get_width() > 12, use obj.scale(12/obj.get_width())
35. Use multi-line text for long content instead of tiny fonts or overflow
36. Position wide equations at Y=0 (screen center) for maximum horizontal space
37. Create responsive layouts that adapt to content size automatically
🚫 OVERLAP PREVENTION CRITICAL REQUIREMENTS:
38. MANDATORY position tracking: maintain mental map of used screen areas
39. Use position validation: before placing object, verify area is clear
40. Implement smart positioning: if preferred position occupied, find nearest free space
41. Create position buffers: minimum 0.3 units between adjacent text objects
42. Use staged clearing: remove specific objects before adding new ones in same area
43. Implement position queuing: queue objects that will move to make space for new content
44. Use relative positioning chains: obj2.next_to(obj1, RIGHT).shift(DOWN*0.5)
45. Create temporary positioning: place objects off-screen, then animate to final position
46. Use position debugging: add brief pauses to verify no overlaps before proceeding
47. Implement content flow management: ensure logical movement paths don't cause collisions
💫 DYNAMIC VISUAL EXPLANATION CRITICAL REQUIREMENTS:
48. Every abstract concept MUST have concrete visual representation
49. Use transformation chains: circle → square → triangle to show concept evolution
50. Implement visual analogies: familiar objects that morph into mathematical concepts
51. Create animated cause-and-effect demonstrations
52. Use progressive complexity: start with simple shapes, add details through animation
53. Implement interactive-style responses: animations that react to previous content
54. Create visual proof sequences: step-by-step animated demonstrations
55. Use multi-perspective views: show same concept from different visual angles
56. Implement concept journeys: objects that travel across screen to demonstrate relationships
57. Create animated timelines: show historical or logical progression of ideas
⚠️ CRITICAL SYNTAX REQUIREMENTS ⚠️:
- NEVER write Text("text",.shift() - comma before method is SYNTAX ERROR
- ALWAYS write Text("text").shift() - proper method chaining
- NEVER write Text("text").shift(UP*2 - missing closing parenthesis is SYNTAX ERROR
- ALWAYS write Text("text").shift(UP*2) - complete parentheses
- NEVER split Text declarations across multiple lines
- ALWAYS complete Text objects on single lines
- NEVER create orphaned lines starting with font_size= or color=
- ALWAYS use proper 4-space indentation for class methods
ANIMATION REQUIREMENTS:
- Every text element should be animated (Write, FadeIn, etc.)
- Use Transform() to morph objects between states
- Implement smooth camera movements when appropriate
- Clear previous content before introducing new concepts: self.play(FadeOut(*self.mobjects))
- Position elements strategically using UP, DOWN, LEFT, RIGHT with multipliers
- Use scale and rotation for visual interest: .scale(0.8), .rotate(PI/4)
- Implement highlighting effects (Indicate, Flash, Wiggle)
- Create progressive reveals for complex concepts
- Use color changes to show relationships: .set_color(BLUE)
- Implement step-by-step builds for equations and diagrams
MANDATORY POSITIONING EXAMPLES:
- Title: Text("Title", font_size=48).shift(UP*3)
- Subtitle: Text("Subtitle", font_size=36).shift(UP*1.5)
- Content: Text("Content", font_size=24).shift(DOWN*1)
- Left diagram: Circle().shift(LEFT*4)
- Right text: Text("Explanation").shift(RIGHT*3)
- Multiple items: use UP*2, ORIGIN, DOWN*2 for vertical spacing
- NEVER put two Text objects in the same position
- ALWAYS move or remove old content before adding new content
📺 16:9 POSITIONING EXAMPLES (1920x1080 safe zones):
- Maximum title position: Text("Title").shift(UP*3.5) ✅
- Beyond safe zone: Text("Title").shift(UP*4.5) ❌ (will be cut off)
- Wide content max: Text("Long equation").shift(LEFT*6) ✅
- Too wide: Text("Content").shift(LEFT*8) ❌ (extends beyond screen)
- Vertical content distribution:
* Header zone: Y=3 to Y=2 (titles, section headers)
* Main zone: Y=1.5 to Y=-1.5 (primary content, diagrams)
* Footer zone: Y=-2 to Y=-3.5 (conclusions, notes)
- Horizontal content distribution:
* Left panel: X=-5 to X=-2 (diagrams, visual elements)
* Center panel: X=-1.5 to X=1.5 (main text, equations)
* Right panel: X=2 to X=5 (explanations, annotations)
🚫 OVERLAP PREVENTION EXAMPLES:
✅ CORRECT - Sequential positioning:
```python
title = Text("Title").shift(UP*3)
self.play(Write(title))
subtitle = Text("Subtitle").shift(UP*1.5) # Different Y position
self.play(Write(subtitle))
```
❌ WRONG - Same position overlap:
```python
title = Text("Title").shift(UP*2)
subtitle = Text("Subtitle").shift(UP*2) # OVERLAP! Same position
```
✅ CORRECT - Clear before new content:
```python
self.play(FadeOut(title)) # Remove old content first
new_title = Text("New Title").shift(UP*3)
self.play(Write(new_title))
```