Dataset Viewer
file_path
stringlengths 29
93
| content
stringlengths 0
117k
|
---|---|
manim_ManimCommunity/.readthedocs.yml
|
version: 2
build:
os: ubuntu-22.04
tools:
python: "3.11"
apt_packages:
- libpango1.0-dev
- ffmpeg
- graphviz
python:
install:
- requirements: docs/rtd-requirements.txt
- requirements: docs/requirements.txt
- method: pip
path: .
|
manim_ManimCommunity/conftest.py
|
# This file is automatically picked by pytest
# while running tests. So, that each test is
# run on difference temporary directories and avoiding
# errors.
from __future__ import annotations
try:
# https://github.com/moderngl/moderngl/issues/517
import readline # required to prevent a segfault on Python 3.10
except ModuleNotFoundError: # windows
pass
import cairo
import moderngl
# If it is running Doctest the current directory
# is changed because it also tests the config module
# itself. If it's a normal test then it uses the
# tempconfig to change directories.
import pytest
from _pytest.doctest import DoctestItem
from manim import config, tempconfig
@pytest.fixture(autouse=True)
def temp_media_dir(tmpdir, monkeypatch, request):
if isinstance(request.node, DoctestItem):
monkeypatch.chdir(tmpdir)
yield tmpdir
else:
with tempconfig({"media_dir": str(tmpdir)}):
assert config.media_dir == str(tmpdir)
yield tmpdir
def pytest_report_header(config):
ctx = moderngl.create_standalone_context()
info = ctx.info
ctx.release()
return (
f"\nCairo Version: {cairo.cairo_version()}",
"\nOpenGL information",
"------------------",
f"vendor: {info['GL_VENDOR'].strip()}",
f"renderer: {info['GL_RENDERER'].strip()}",
f"version: {info['GL_VERSION'].strip()}\n",
)
|
manim_ManimCommunity/README.md
|
<p align="center">
<a href="https://www.manim.community/"><img src="https://raw.githubusercontent.com/ManimCommunity/manim/main/logo/cropped.png"></a>
<br />
<br />
<a href="https://pypi.org/project/manim/"><img src="https://img.shields.io/pypi/v/manim.svg?style=flat&logo=pypi" alt="PyPI Latest Release"></a>
<a href="https://hub.docker.com/r/manimcommunity/manim"><img src="https://img.shields.io/docker/v/manimcommunity/manim?color=%23099cec&label=docker%20image&logo=docker" alt="Docker image"> </a>
<a href="https://mybinder.org/v2/gh/ManimCommunity/jupyter_examples/HEAD?filepath=basic_example_scenes.ipynb"><img src="https://mybinder.org/badge_logo.svg"></a>
<a href="http://choosealicense.com/licenses/mit/"><img src="https://img.shields.io/badge/license-MIT-red.svg?style=flat" alt="MIT License"></a>
<a href="https://www.reddit.com/r/manim/"><img src="https://img.shields.io/reddit/subreddit-subscribers/manim.svg?color=orange&label=reddit&logo=reddit" alt="Reddit" href=></a>
<a href="https://twitter.com/manim_community/"><img src="https://img.shields.io/twitter/url/https/twitter.com/cloudposse.svg?style=social&label=Follow%20%40manim_community" alt="Twitter">
<a href="https://www.manim.community/discord/"><img src="https://img.shields.io/discord/581738731934056449.svg?label=discord&color=yellow&logo=discord" alt="Discord"></a>
<a href="https://github.com/psf/black"><img src="https://img.shields.io/badge/code%20style-black-000000.svg" alt="Code style: black">
<a href="https://docs.manim.community/"><img src="https://readthedocs.org/projects/manimce/badge/?version=latest" alt="Documentation Status"></a>
<a href="https://pepy.tech/project/manim"><img src="https://pepy.tech/badge/manim/month?" alt="Downloads"> </a>
<img src="https://github.com/ManimCommunity/manim/workflows/CI/badge.svg" alt="CI">
<br />
<br />
<i>An animation engine for explanatory math videos</i>
</p>
<hr />
Manim is an animation engine for explanatory math videos. It's used to create precise animations programmatically, as demonstrated in the videos of [3Blue1Brown](https://www.3blue1brown.com/).
> NOTE: This repository is maintained by the Manim Community and is not associated with Grant Sanderson or 3Blue1Brown in any way (although we are definitely indebted to him for providing his work to the world). If you would like to study how Grant makes his videos, head over to his repository ([3b1b/manim](https://github.com/3b1b/manim)). This fork is updated more frequently than his, and it's recommended to use this fork if you'd like to use Manim for your own projects.
## Table of Contents:
- [Installation](#installation)
- [Usage](#usage)
- [Documentation](#documentation)
- [Docker](#docker)
- [Help with Manim](#help-with-manim)
- [Contributing](#contributing)
- [License](#license)
## Installation
> **WARNING:** These instructions are for the community version _only_. Trying to use these instructions to install [3b1b/manim](https://github.com/3b1b/manim) or instructions there to install this version will cause problems. Read [this](https://docs.manim.community/en/stable/faq/installation.html#why-are-there-different-versions-of-manim) and decide which version you wish to install, then only follow the instructions for your desired version.
Manim requires a few dependencies that must be installed prior to using it. If you
want to try it out first before installing it locally, you can do so
[in our online Jupyter environment](https://try.manim.community/).
For local installation, please visit the [Documentation](https://docs.manim.community/en/stable/installation.html)
and follow the appropriate instructions for your operating system.
## Usage
Manim is an extremely versatile package. The following is an example `Scene` you can construct:
```python
from manim import *
class SquareToCircle(Scene):
def construct(self):
circle = Circle()
square = Square()
square.flip(RIGHT)
square.rotate(-3 * TAU / 8)
circle.set_fill(PINK, opacity=0.5)
self.play(Create(square))
self.play(Transform(square, circle))
self.play(FadeOut(square))
```
In order to view the output of this scene, save the code in a file called `example.py`. Then, run the following in a terminal window:
```sh
manim -p -ql example.py SquareToCircle
```
You should see your native video player program pop up and play a simple scene in which a square is transformed into a circle. You may find some more simple examples within this
[GitHub repository](example_scenes). You can also visit the [official gallery](https://docs.manim.community/en/stable/examples.html) for more advanced examples.
Manim also ships with a `%%manim` IPython magic which allows to use it conveniently in JupyterLab (as well as classic Jupyter) notebooks. See the
[corresponding documentation](https://docs.manim.community/en/stable/reference/manim.utils.ipython_magic.ManimMagic.html) for some guidance and
[try it out online](https://mybinder.org/v2/gh/ManimCommunity/jupyter_examples/HEAD?filepath=basic_example_scenes.ipynb).
## Command line arguments
The general usage of Manim is as follows:

The `-p` flag in the command above is for previewing, meaning the video file will automatically open when it is done rendering. The `-ql` flag is for a faster rendering at a lower quality.
Some other useful flags include:
- `-s` to skip to the end and just show the final frame.
- `-n <number>` to skip ahead to the `n`'th animation of a scene.
- `-f` show the file in the file browser.
For a thorough list of command line arguments, visit the [documentation](https://docs.manim.community/en/stable/guides/configuration.html).
## Documentation
Documentation is in progress at [ReadTheDocs](https://docs.manim.community/).
## Docker
The community also maintains a docker image (`manimcommunity/manim`), which can be found [on DockerHub](https://hub.docker.com/r/manimcommunity/manim).
Instructions on how to install and use it can be found in our [documentation](https://docs.manim.community/en/stable/installation/docker.html).
## Help with Manim
If you need help installing or using Manim, feel free to reach out to our [Discord
Server](https://www.manim.community/discord/) or [Reddit Community](https://www.reddit.com/r/manim). If you would like to submit a bug report or feature request, please open an issue.
## Contributing
Contributions to Manim are always welcome. In particular, there is a dire need for tests and documentation. For contribution guidelines, please see the [documentation](https://docs.manim.community/en/stable/contributing.html).
However, please note that Manim is currently undergoing a major refactor. In general,
contributions implementing new features will not be accepted in this period.
The contribution guide may become outdated quickly; we highly recommend joining our
[Discord server](https://www.manim.community/discord/) to discuss any potential
contributions and keep up to date with the latest developments.
Most developers on the project use `poetry` for management. You'll want to have poetry installed and available in your environment.
Learn more about `poetry` at its [documentation](https://python-poetry.org/docs/) and find out how to install manim with poetry at the [manim dev-installation guide](https://docs.manim.community/en/stable/contributing/development.html) in the manim documentation.
## How to Cite Manim
We acknowledge the importance of good software to support research, and we note
that research becomes more valuable when it is communicated effectively. To
demonstrate the value of Manim, we ask that you cite Manim in your work.
Currently, the best way to cite Manim is to go to our
[repository page](https://github.com/ManimCommunity/manim) (if you aren't already) and
click the "cite this repository" button on the right sidebar. This will generate
a citation in your preferred format, and will also integrate well with citation managers.
## Code of Conduct
Our full code of conduct, and how we enforce it, can be read on [our website](https://docs.manim.community/en/stable/conduct.html).
## License
The software is double-licensed under the MIT license, with copyright by 3blue1brown LLC (see LICENSE), and copyright by Manim Community Developers (see LICENSE.community).
|
manim_ManimCommunity/lgtm.yml
|
queries:
- exclude: py/init-calls-subclass
- exclude: py/unexpected-raise-in-special-method
- exclude: py/modification-of-locals
- exclude: py/multiple-calls-to-init
- exclude: py/missing-call-to-init
|
manim_ManimCommunity/CODE_OF_CONDUCT.md
|
# Code of Conduct
> TL;DR Be excellent to each other; we're a community after all. If you run into issues with others in our community, please [contact](https://www.manim.community/discord/) a Manim Community Dev, or Moderator.
## Purpose
The Manim Community includes members of varying skills, languages, personalities, cultural backgrounds, and experiences from around the globe. Through these differences, we continue to grow and collectively improve upon an open-source animation engine. When working in a community, it is important to remember that you are interacting with humans on the other end of your screen. This code of conduct will guide your interactions and keep Manim a positive environment for our developers, users, and fundamentally our growing community.
## Our Community
Members of Manim Community are respectful, open, and considerate. Behaviors that reinforce these values contribute to our positive environment, and include:
- **Being respectful.** Respectful of others, their positions, experiences, viewpoints, skills, commitments, time, and efforts.
- **Being open.** Open to collaboration, whether it's on problems, Pull Requests, issues, or otherwise.
- **Being considerate.** Considerate of their peers -- other Manim users and developers.
- **Focusing on what is best for the community.** We're respectful of the processes set forth in the community, and we work within them.
- **Showing empathy towards other community members.** We're attentive in our communications, whether in person or online, and we're tactful when approaching differing views.
- **Gracefully accepting constructive criticism.** When we disagree, we are courteous in raising our issues.
- **Using welcoming and inclusive language.** We're accepting of all who wish to take part in our activities, fostering an environment where anyone can participate and everyone can make a difference.
## Our Standards
Every member of our community has the right to have their identity respected. Manim Community is dedicated to providing a positive environment for everyone, regardless of age, gender identity and expression, sexual orientation, disability, physical appearance, body size, ethnicity, nationality, race, religion (or lack thereof), education, or socioeconomic status.
## Inappropriate Behavior
Examples of unacceptable behavior by participants include:
* Harassment of any participants in any form
* Deliberate intimidation, stalking, or following
* Logging or taking screenshots of online activity for harassment purposes
* Publishing others' private information, such as a physical or electronic address, without explicit permission
* Violent threats or language directed against another person
* Incitement of violence or harassment towards any individual, including encouraging a person to commit suicide or to engage in self-harm
* Creating additional online accounts in order to harass another person or circumvent a ban
* Sexual language and imagery in online communities or any conference venue, including talks
* Insults, put-downs, or jokes that are based upon stereotypes, that are exclusionary, or that hold others up for ridicule
* Excessive swearing
* Unwelcome sexual attention or advances
* Unwelcome physical contact, including simulated physical contact (eg, textual descriptions like "hug" or "backrub") without consent or after a request to stop
* Pattern of inappropriate social contact, such as requesting/assuming inappropriate levels of intimacy with others
* Sustained disruption of online community discussions, in-person presentations, or other in-person events
* Continued one-on-one communication after requests to cease
* Other conduct that is inappropriate for a professional audience including people of many different backgrounds
Community members asked to stop any inappropriate behavior are expected to comply immediately.
## Manim Community Online Spaces
This Code of Conduct applies to the following online spaces:
- The [ManimCommunity GitHub Organization](https://github.com/ManimCommunity) and all of its repositories
- The Manim [Discord](https://www.manim.community/discord/)
- The Manim [Reddit](https://www.reddit.com/r/manim/)
- The Manim [Twitter](https://twitter.com/manim\_community/)
This Code of Conduct applies to every member in official Manim Community online spaces, including:
- Moderators
- Maintainers
- Developers
- Reviewers
- Contributors
- Users
- All community members
## Consequences
If a member's behavior violates this code of conduct, the Manim Community Code of Conduct team may take any action they deem appropriate, including, but not limited to: warning the offender, temporary bans, deletion of offending messages, and expulsion from the community and its online spaces. The full list of consequences for inappropriate behavior is listed below in the Enforcement Procedures.
Thank you for helping make this a welcoming, friendly community for everyone.
## Contact Information
If you believe someone is violating the code of conduct, or have any other concerns, please contact a Manim Community Dev, or Moderator immediately. They can be reached on Manim's Community [Discord](https://www.manim.community/discord/).
<hr style="border:2px solid gray"> </hr>
<hr style="border:2px solid gray"> </hr>
## Enforcement Procedures
This document summarizes the procedures the Manim Community Code of Conduct team uses to enforce the Code of Conduct.
### Summary of processes
When the team receives a report of a possible Code of Conduct violation, it will:
1. Acknowledge the receipt of the report.
1. Evaluate conflicts of interest.
1. Call a meeting of code of conduct team members without a conflict of interest.
1. Evaluate the reported incident.
1. Propose a behavioral modification plan.
1. Propose consequences for the reported behavior.
1. Vote on behavioral modification plan and consequences for the reported person.
1. Contact Manim Community moderators to approve the behavioral modification plan and consequences.
1. Follow up with the reported person.
1. Decide further responses.
1. Follow up with the reporter.
### Acknowledge the report
Reporters should receive an acknowledgment of the receipt of their report within 48 hours.
### Conflict of interest policy
Examples of conflicts of interest include:
* You have a romantic or platonic relationship with either the reporter or the reported person. It's fine to participate if they are an acquaintance.
* The reporter or reported person is someone you work closely with. This could be someone on your team or someone who works on the same project as you.
* The reporter or reported person is a maintainer who regularly reviews your contributions
* The reporter or reported person is your metamour.
* The reporter or reported person is your family member
Committee members do not need to state why they have a conflict of interest, only that one exists. Other team members should not ask why the person has a conflict of interest.
Anyone who has a conflict of interest will remove themselves from the discussion of the incident, and recluse themselves from voting on a response to the report.
### Evaluating a report
#### Jurisdiction
* *Is this a Code of Conduct violation?* Is this behavior on our list of inappropriate behavior? Is it borderline inappropriate behavior? Does it violate our community norms?
* *Did this occur in a space that is within our Code of Conduct's scope?* If the incident occurred outside the community, but a community member's mental health or physical safety may be negatively impacted if no action is taken, the incident may be in scope. Private conversations in community spaces are also in scope.
#### Impact
* *Did this incident occur in a private conversation or a public space?* Incidents that all community members can see will have a more negative impact.
* *Does this behavior negatively impact a marginalized group in our community?* Is the reporter a person from a marginalized group in our community? How is the reporter being negatively impacted by the reported person's behavior? Are members of the marginalized group likely to disengage with the community if no action was taken on this report?
* *Does this incident involve a community leader?* Community members often look up to community leaders to set the standard of acceptable behavior
#### Risk
* *Does this incident include sexual harassment?*
* *Does this pose a safety risk?* Does the behavior put a person's physical safety at risk? Will this incident severely negatively impact someone's mental health?
* *Is there a risk of this behavior being repeated?* Does the reported person understand why their behavior was inappropriate? Is there an established pattern of behavior from past reports?
Reports which involve higher risk or higher impact may face more severe consequences than reports which involve lower risk or lower impact.
### Propose consequences
What follows are examples of possible consequences of an incident report. This list of consequences is not exhaustive, and the Manim Community Code of Conduct team reserves the right to take any action it deems necessary.
Possible private responses to an incident include:
* Nothing, if the behavior was determined to not be a Code of Conduct violation
* A warning
* A final warning
* Temporarily removing the reported person from the community's online space(s)
* Permanently removing the reported person from the community's online space(s)
* Publishing an account of the incident
### Team vote
Some team members may have a conflict of interest and may be excluded from discussions of a particular incident report. Excluding those members, decisions on the behavioral modification plans and consequences will be determined by a two-thirds majority vote of the Manim Community Code of Conduct team.
### Moderators approval
Once the team has approved the behavioral modification plans and consequences, they will communicate the recommended response to the Manim Community moderators. The team should not state who reported this incident. They should attempt to anonymize any identifying information from the report.
Moderators are required to respond with whether they accept the recommended response to the report. If they disagree with the recommended response, they should provide a detailed response or additional context as to why they disagree. Moderators are encouraged to respond within a week.
In cases where the moderators disagree on the suggested resolution for a report, the Manim Community Code of Conduct team may choose to notify the Manim Community Moderators.
### Follow up with the reported person
The Manim Community Code of Conduct team will work with Manim Community moderators to draft a response to the reported person. The response should contain:
* A description of the person's behavior in neutral language
* The negative impact of that behavior
* A concrete behavioral modification plan
* Any consequences of their behavior
The team should not state who reported this incident. They should attempt to anonymize any identifying information from the report. The reported person should be discouraged from contacting the reporter to discuss the report. If they wish to apologize to the reporter, the team can accept the apology on behalf of the reporter.
### Decide further responses
If the reported person provides additional context, the Manim Community Code of Conduct team may need to re-evaluate the behavioral modification plan and consequences.
### Follow up with the reporter
A person who makes a report should receive a follow-up response stating what action was taken in response to the report. If the team decided no response was needed, they should provide an explanation why it was not a Code of Conduct violation. Reports that are not made in good faith (such as "reverse sexism" or "reverse racism") may receive no response.
The follow-up should be sent no later than one week after the receipt of the report. If deliberation or follow-up with the reported person takes longer than one week, the team should send a status update to the reporter.
### Changes to Code of Conduct
When discussing a change to the Manim Community code of conduct or enforcement procedures, the Manim Community Code of Conduct team will follow this decision-making process:
* **Brainstorm options.** Team members should discuss any relevant context and brainstorm a set of possible options. It is important to provide constructive feedback without getting side-tracked from the main question.
* **Vote.** Proposed changes to the code of conduct will be decided by a two-thirds majority of all voting members of the Code of Conduct team. Team members are listed in the charter. Currently active voting members are listed in the following section.
* **Board Vote.** Once a working draft is in place for the Code of Conduct and procedures, the Code of Conduct team shall provide the Manim Community Moderators with a draft of the changes. The Manim Community Moderators will vote on the changes at a board meeting.
### Current list of voting members
- All available Community Developers (i.e. those with "write" permissions, or above, on the Manim Community GitHub organization).
## License
This Code of Conduct is licensed under the [Creative Commons Attribution-ShareAlike 3.0 Unported License](https://creativecommons.org/licenses/by-sa/3.0/).
## Attributions
This Code of Conduct was forked from the code of conduct from the [Python Software Foundation](https://www.python.org/psf/conduct/) and adapted by Manim Community.
|
manim_ManimCommunity/.codecov.yml
|
codecov:
notify:
require_ci_to_pass: no
after_n_builds: 1
coverage:
status:
project:
default:
# Require 1% coverage, i.e., always succeed
target: 1
patch: true
changes: false
comment: off
|
manim_ManimCommunity/CONTRIBUTING.md
|
# Thanks for your interest in contributing!
Please read our contributing guidelines which are hosted at https://docs.manim.community/en/latest/contributing.html
|
manim_ManimCommunity/crowdin.yml
|
files:
- source: /docs/i18n/gettext/**/*.pot
translation: /docs/i18n/%two_letters_code%/LC_MESSAGES/**/%file_name%.po
|
manim_ManimCommunity/docker/readme.md
|
See the [main README](https://github.com/ManimCommunity/manim/blob/main/README.md) for some instructions on how to use this image.
# Building the image
The docker image corresponding to the checked out version of the git repository
can be built by running
```
docker build -t manimcommunity/manim:TAG -f docker/Dockerfile .
```
from the root directory of the repository.
Multi-platform builds are possible by running
```
docker buildx build --push --platform linux/arm64/v8,linux/amd64 --tag manimcommunity/manim:TAG -f docker/Dockerfile .
```
from the root directory of the repository.
|
manim_ManimCommunity/.github/PULL_REQUEST_TEMPLATE.md
|
<!-- Thank you for contributing to Manim! Learn more about the process in our contributing guidelines: https://docs.manim.community/en/latest/contributing.html -->
## Overview: What does this pull request change?
<!-- If there is more information than the PR title that should be added to our release changelog, add it in the following changelog section. This is optional, but recommended for larger pull requests. -->
<!--changelog-start-->
<!--changelog-end-->
## Motivation and Explanation: Why and how do your changes improve the library?
<!-- Optional for bugfixes, small enhancements, and documentation-related PRs. Otherwise, please give a short reasoning for your changes. -->
## Links to added or changed documentation pages
<!-- Please add links to the affected documentation pages (edit the description after opening the PR). The link to the documentation for your PR is https://manimce--####.org.readthedocs.build/en/####/, where #### represents the PR number. -->
## Further Information and Comments
<!-- If applicable, put further comments for the reviewers here. -->
<!-- Thank you again for contributing! Do not modify the lines below, they are for reviewers. -->
## Reviewer Checklist
- [ ] The PR title is descriptive enough for the changelog, and the PR is labeled correctly
- [ ] If applicable: newly added non-private functions and classes have a docstring including a short summary and a PARAMETERS section
- [ ] If applicable: newly added functions and classes are tested
|
manim_ManimCommunity/.github/dependabot.yml
|
version: 2
updates:
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "monthly"
ignore:
- dependency-name: "*"
update-types:
- "version-update:semver-minor"
- "version-update:semver-patch"
|
manim_ManimCommunity/.github/codeql.yml
|
query-filters:
- exclude:
id: py/init-calls-subclass
- exclude:
id: py/unexpected-raise-in-special-method
- exclude:
id: py/modification-of-locals
- exclude:
id: py/multiple-calls-to-init
- exclude:
id: py/missing-call-to-init
paths:
- manim
paths-ignore:
- tests/
- example_scenes/
|
manim_ManimCommunity/.github/workflows/cffconvert.yml
|
name: cffconvert
on:
push:
paths:
- CITATION.cff
jobs:
validate:
name: "validate"
runs-on: ubuntu-latest
steps:
- name: Check out a copy of the repository
uses: actions/checkout@v4
- name: Check whether the citation metadata from CITATION.cff is valid
uses: citation-file-format/cffconvert-github-action@2.0.0
with:
args: "--validate"
|
manim_ManimCommunity/.github/workflows/dependent-issues.yml
|
name: Dependent Issues
on:
issues:
types:
- opened
- edited
- reopened
pull_request_target:
types:
- opened
- edited
- reopened
- synchronize
schedule:
- cron: '0 0 * * *' # schedule daily check
jobs:
check:
runs-on: ubuntu-latest
steps:
- uses: z0al/dependent-issues@v1
env:
# (Required) The token to use to make API calls to GitHub.
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
# (Optional) The label to use to mark dependent issues
label: dependent
# (Optional) Enable checking for dependencies in issues. Enable by
# setting the value to "on". Default "off"
check_issues: on
# (Optional) A comma-separated list of keywords. Default
# "depends on, blocked by"
keywords: depends on, blocked by
|
manim_ManimCommunity/.github/workflows/ci.yml
|
name: CI
concurrency:
group: ${{ github.ref }}
cancel-in-progress: true
on:
push:
branches:
- main
pull_request:
branches:
- main
jobs:
test:
runs-on: ${{ matrix.os }}
env:
DISPLAY: :0
PYTEST_ADDOPTS: "--color=yes" # colors in pytest
strategy:
fail-fast: false
matrix:
os: [ubuntu-22.04, macos-latest, windows-latest]
python: ["3.9", "3.10", "3.11", "3.12"]
steps:
- name: Checkout the repository
uses: actions/checkout@v4
- name: Install Poetry
run: |
pipx install "poetry==1.7.*"
poetry config virtualenvs.prefer-active-python true
- name: Setup Python ${{ matrix.python }}
uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python }}
cache: "poetry"
- name: Setup macOS PATH
if: runner.os == 'macOS'
run: |
echo "$HOME/.local/bin" >> $GITHUB_PATH
- name: Setup cache variables
shell: bash
id: cache-vars
run: |
echo "date=$(/bin/date -u "+%m%w%Y")" >> $GITHUB_OUTPUT
- name: Install and cache ffmpeg (all OS)
uses: FedericoCarboni/setup-ffmpeg@v2
with:
token: ${{ secrets.GITHUB_TOKEN }}
id: setup-ffmpeg
- name: Install system dependencies (Linux)
if: runner.os == 'Linux'
uses: awalsh128/cache-apt-pkgs-action@latest
with:
packages: python3-opengl libpango1.0-dev xvfb freeglut3-dev
version: 1.0
- name: Install Texlive (Linux)
if: runner.os == 'Linux'
uses: teatimeguest/setup-texlive-action@v3
with:
cache: true
packages: scheme-basic fontspec inputenc fontenc tipa mathrsfs calligra xcolor standalone preview doublestroke ms everysel setspace rsfs relsize ragged2e fundus-calligra microtype wasysym physics dvisvgm jknapltx wasy cm-super babel-english gnu-freefont mathastext cbfonts-fd xetex
- name: Start virtual display (Linux)
if: runner.os == 'Linux'
run: |
# start xvfb in background
sudo /usr/bin/Xvfb $DISPLAY -screen 0 1280x1024x24 &
- name: Setup Cairo Cache
uses: actions/cache@v3
id: cache-cairo
if: runner.os == 'Linux' || runner.os == 'macOS'
with:
path: ${{ github.workspace }}/third_party
key: ${{ runner.os }}-dependencies-cairo-${{ hashFiles('.github/scripts/ci_build_cairo.py') }}
- name: Build and install Cairo (Linux and macOS)
if: (runner.os == 'Linux' || runner.os == 'macOS') && steps.cache-cairo.outputs.cache-hit != 'true'
run: python .github/scripts/ci_build_cairo.py
- name: Set env vars for Cairo (Linux and macOS)
if: runner.os == 'Linux' || runner.os == 'macOS'
run: python .github/scripts/ci_build_cairo.py --set-env-vars
- name: Setup macOS cache
uses: actions/cache@v3
id: cache-macos
if: runner.os == 'macOS'
with:
path: ${{ github.workspace }}/macos-cache
key: ${{ runner.os }}-dependencies-tinytex-${{ hashFiles('.github/manimdependency.json') }}-${{ steps.cache-vars.outputs.date }}-1
- name: Install system dependencies (MacOS)
if: runner.os == 'macOS' && steps.cache-macos.outputs.cache-hit != 'true'
run: |
tinyTexPackages=$(python -c "import json;print(' '.join(json.load(open('.github/manimdependency.json'))['macos']['tinytex']))")
IFS=' '
read -a ttp <<< "$tinyTexPackages"
oriPath=$PATH
sudo mkdir -p $PWD/macos-cache
echo "Install TinyTeX"
sudo curl -L -o "/tmp/TinyTeX.tgz" "https://github.com/yihui/tinytex-releases/releases/download/daily/TinyTeX-1.tgz"
sudo tar zxf "/tmp/TinyTeX.tgz" -C "$PWD/macos-cache"
export PATH="$PWD/macos-cache/TinyTeX/bin/universal-darwin:$PATH"
sudo tlmgr update --self
for i in "${ttp[@]}"; do
sudo tlmgr install "$i"
done
export PATH="$oriPath"
echo "Completed TinyTeX"
- name: Add macOS dependencies to PATH
if: runner.os == 'macOS'
shell: bash
run: |
echo "/Library/TeX/texbin" >> $GITHUB_PATH
echo "$HOME/.poetry/bin" >> $GITHUB_PATH
echo "$PWD/macos-cache/TinyTeX/bin/universal-darwin" >> $GITHUB_PATH
- name: Setup Windows cache
id: cache-windows
if: runner.os == 'Windows'
uses: actions/cache@v3
with:
path: ${{ github.workspace }}\ManimCache
key: ${{ runner.os }}-dependencies-tinytex-${{ hashFiles('.github/manimdependency.json') }}-${{ steps.cache-vars.outputs.date }}-1
- uses: ssciwr/setup-mesa-dist-win@v1
- name: Install system dependencies (Windows)
if: runner.os == 'Windows' && steps.cache-windows.outputs.cache-hit != 'true'
run: |
$tinyTexPackages = $(python -c "import json;print(' '.join(json.load(open('.github/manimdependency.json'))['windows']['tinytex']))") -Split ' '
$OriPath = $env:PATH
echo "Install Tinytex"
Invoke-WebRequest "https://github.com/yihui/tinytex-releases/releases/download/daily/TinyTeX-1.zip" -OutFile "$($env:TMP)\TinyTex.zip"
Expand-Archive -LiteralPath "$($env:TMP)\TinyTex.zip" -DestinationPath "$($PWD)\ManimCache\LatexWindows"
$env:Path = "$($PWD)\ManimCache\LatexWindows\TinyTeX\bin\windows;$($env:PATH)"
tlmgr update --self
foreach ($c in $tinyTexPackages){
$c=$c.Trim()
tlmgr install $c
}
$env:PATH=$OriPath
echo "Completed Latex"
- name: Add Windows dependencies to PATH
if: runner.os == 'Windows'
run: |
$env:Path += ";" + "$($PWD)\ManimCache\LatexWindows\TinyTeX\bin\windows"
$env:Path = "$env:USERPROFILE\.poetry\bin;$($env:PATH)"
echo "$env:Path" | Out-File -FilePath $env:GITHUB_PATH -Encoding utf8 -Append
- name: Install manim
run: |
poetry config installer.modern-installation false
poetry install
- name: Run tests
run: |
poetry run python -m pytest
- name: Run module doctests
run: |
poetry run python -m pytest -v --cov-append --ignore-glob="*opengl*" --doctest-modules manim
- name: Run doctests in rst files
run: |
cd docs && poetry run make doctest O=-tskip-manim
|
manim_ManimCommunity/.github/workflows/publish-docker.yml
|
name: Publish Docker Image
on:
push:
branches:
- main
release:
types: [released]
jobs:
docker-latest:
runs-on: ubuntu-latest
if: github.event_name != 'release'
steps:
- name: Set up QEMU
uses: docker/setup-qemu-action@v3
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Login to DockerHub
uses: docker/login-action@v3
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Build and push
uses: docker/build-push-action@v5
with:
platforms: linux/arm64,linux/amd64
push: true
file: docker/Dockerfile
tags: |
manimcommunity/manim:latest
docker-release:
runs-on: ubuntu-latest
if: github.event_name == 'release'
steps:
- name: Set up QEMU
uses: docker/setup-qemu-action@v3
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Login to DockerHub
uses: docker/login-action@v3
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Get Version
id: create_release
shell: python
env:
tag_act: ${{ github.ref }}
run: |
import os
ref_tag = os.getenv('tag_act').split('/')[-1]
with open(os.getenv('GITHUB_OUTPUT'), 'w') as f:
print(f"tag_name={ref_tag}", file=f)
- name: Build and push
uses: docker/build-push-action@v5
with:
platforms: linux/arm64,linux/amd64
push: true
file: docker/Dockerfile
tags: |
manimcommunity/manim:stable
manimcommunity/manim:latest
manimcommunity/manim:${{ steps.create_release.outputs.tag_name }}
|
manim_ManimCommunity/.github/workflows/codeql.yml
|
name: "CodeQL"
on:
push:
branches: [ "main" ]
pull_request:
branches: [ "main" ]
schedule:
- cron: "21 16 * * 3"
jobs:
analyze:
name: Analyze
runs-on: ubuntu-latest
permissions:
actions: read
contents: read
security-events: write
strategy:
fail-fast: false
matrix:
language: [ python ]
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Initialize CodeQL
uses: github/codeql-action/init@v3
with:
languages: ${{ matrix.language }}
config-file: ./.github/codeql.yml
queries: +security-and-quality
- name: Autobuild
uses: github/codeql-action/autobuild@v3
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v3
with:
category: "/language:${{ matrix.language }}"
|
manim_ManimCommunity/.github/workflows/release-publish-documentation.yml
|
name: Publish downloadable documentation
on:
release:
types: [released]
workflow_dispatch:
jobs:
build-and-publish-htmldocs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up Python 3.11
uses: actions/setup-python@v5
with:
python-version: 3.11
- name: Install system dependencies
run: |
sudo apt update && sudo apt install -y \
pkg-config libcairo-dev libpango1.0-dev ffmpeg wget fonts-roboto
wget -qO- "https://yihui.org/tinytex/install-bin-unix.sh" | sh
echo ${HOME}/.TinyTeX/bin/x86_64-linux >> $GITHUB_PATH
- name: Install LaTeX and Python dependencies
run: |
tlmgr install \
babel-english ctex doublestroke dvisvgm frcursive fundus-calligra jknapltx \
mathastext microtype physics preview ragged2e relsize rsfs setspace standalone \
wasy wasysym
python -m pip install --upgrade poetry
poetry install
- name: Build and package documentation
run: |
cd docs/
poetry run make html
cd build/html/
tar -czvf ../html-docs.tar.gz *
- name: Store artifacts
uses: actions/upload-artifact@v4
with:
path: ${{ github.workspace }}/docs/build/html-docs.tar.gz
name: html-docs.tar.gz
- name: Install Dependency
run: pip install requests
- name: Get Upload URL
if: github.event == 'release'
id: create_release
shell: python
env:
access_token: ${{ secrets.GITHUB_TOKEN }}
tag_act: ${{ github.ref }}
run: |
import requests
import os
ref_tag = os.getenv('tag_act').split('/')[-1]
access_token = os.getenv('access_token')
headers = {
"Accept":"application/vnd.github.v3+json",
"Authorization": f"token {access_token}"
}
url = f"https://api.github.com/repos/ManimCommunity/manim/releases/tags/{ref_tag}"
c = requests.get(url,headers=headers)
upload_url=c.json()['upload_url']
with open(os.getenv('GITHUB_OUTPUT'), 'w') as f:
print(f"upload_url={upload_url}", file=f)
print(f"tag_name={ref_tag[1:]}", file=f)
- name: Upload Release Asset
if: github.event == 'release'
id: upload-release
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: ${{ github.workspace }}/docs/build/html-docs.tar.gz
asset_name: manim-htmldocs-${{ steps.create_release.outputs.tag_name }}.tar.gz
asset_content_type: application/gzip
|
manim_ManimCommunity/.github/workflows/python-publish.yml
|
name: Publish Release
on:
release:
types: [released]
jobs:
release:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up Python 3.11
uses: actions/setup-python@v5
with:
python-version: 3.11
- name: Install dependencies
run: python -m pip install --upgrade poetry
# TODO: Set PYPI_API_TOKEN to api token from pip in secrets
- name: Configure pypi credentials
env:
PYPI_API_TOKEN: ${{ secrets.PYPI_API_TOKEN }}
run: poetry config http-basic.pypi __token__ "$PYPI_API_TOKEN"
- name: Publish release to pypi
run: |
poetry publish --build
poetry build
- name: Store artifacts
uses: actions/upload-artifact@v4
with:
path: dist/*.tar.gz
name: manim.tar.gz
- name: Install Dependency
run: pip install requests
- name: Get Upload URL
id: create_release
shell: python
env:
access_token: ${{ secrets.GITHUB_TOKEN }}
tag_act: ${{ github.ref }}
run: |
import requests
import os
ref_tag = os.getenv('tag_act').split('/')[-1]
access_token = os.getenv('access_token')
headers = {
"Accept":"application/vnd.github.v3+json",
"Authorization": f"token {access_token}"
}
url = f"https://api.github.com/repos/ManimCommunity/manim/releases/tags/{ref_tag}"
c = requests.get(url,headers=headers)
upload_url=c.json()['upload_url']
with open(os.getenv('GITHUB_OUTPUT'), 'w') as f:
print(f"upload_url={upload_url}", file=f)
print(f"tag_name={ref_tag[1:]}", file=f)
- name: Upload Release Asset
id: upload-release
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: dist/manim-${{ steps.create_release.outputs.tag_name }}.tar.gz
asset_name: manim-${{ steps.create_release.outputs.tag_name }}.tar.gz
asset_content_type: application/gzip
|
manim_ManimCommunity/.github/scripts/ci_build_cairo.py
|
# Logic is as follows:
# 1. Download cairo source code: https://cairographics.org/releases/cairo-<version>.tar.xz
# 2. Verify the downloaded file using the sha256sums file: https://cairographics.org/releases/cairo-<version>.tar.xz.sha256sum
# 3. Extract the downloaded file.
# 4. Create a virtual environment and install meson and ninja.
# 5. Run meson build in the extracted directory. Also, set required prefix.
# 6. Run meson compile -C build.
# 7. Run meson install -C build.
import hashlib
import logging
import os
import subprocess
import sys
import tarfile
import tempfile
import typing
import urllib.request
from contextlib import contextmanager
from pathlib import Path
from sys import stdout
CAIRO_VERSION = "1.18.0"
CAIRO_URL = f"https://cairographics.org/releases/cairo-{CAIRO_VERSION}.tar.xz"
CAIRO_SHA256_URL = f"{CAIRO_URL}.sha256sum"
VENV_NAME = "meson-venv"
BUILD_DIR = "build"
INSTALL_PREFIX = Path(__file__).parent.parent.parent / "third_party" / "cairo"
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
logger = logging.getLogger(__name__)
def is_ci():
return os.getenv("CI", None) is not None
def download_file(url, path):
logger.info(f"Downloading {url} to {path}")
block_size = 1024 * 1024
with urllib.request.urlopen(url) as response, open(path, "wb") as file:
while True:
data = response.read(block_size)
if not data:
break
file.write(data)
def verify_sha256sum(path, sha256sum):
with open(path, "rb") as file:
file_hash = hashlib.sha256(file.read()).hexdigest()
if file_hash != sha256sum:
raise Exception("SHA256SUM does not match")
def extract_tar_xz(path, directory):
with tarfile.open(path) as file:
file.extractall(directory)
def run_command(command, cwd=None, env=None):
process = subprocess.Popen(command, cwd=cwd, env=env)
process.communicate()
if process.returncode != 0:
raise Exception("Command failed")
@contextmanager
def gha_group(title: str) -> typing.Generator:
if not is_ci():
yield
return
print(f"\n::group::{title}")
stdout.flush()
try:
yield
finally:
print("::endgroup::")
stdout.flush()
def set_env_var_gha(name: str, value: str) -> None:
if not is_ci():
return
env_file = os.getenv("GITHUB_ENV", None)
if env_file is None:
return
with open(env_file, "a") as file:
file.write(f"{name}={value}\n")
stdout.flush()
def get_ld_library_path(prefix: Path) -> str:
# given a prefix, the ld library path can be found at
# <prefix>/lib/* or sometimes just <prefix>/lib
# this function returns the path to the ld library path
# first, check if the ld library path exists at <prefix>/lib/*
ld_library_paths = list(prefix.glob("lib/*"))
if len(ld_library_paths) == 1:
return ld_library_paths[0].absolute().as_posix()
# if the ld library path does not exist at <prefix>/lib/*,
# return <prefix>/lib
ld_library_path = prefix / "lib"
if ld_library_path.exists():
return ld_library_path.absolute().as_posix()
return ""
def main():
if sys.platform == "win32":
logger.info("Skipping build on windows")
return
with tempfile.TemporaryDirectory() as tmpdir:
with gha_group("Downloading and Extracting Cairo"):
logger.info(f"Downloading cairo version {CAIRO_VERSION}")
download_file(CAIRO_URL, os.path.join(tmpdir, "cairo.tar.xz"))
logger.info("Downloading cairo sha256sum")
download_file(CAIRO_SHA256_URL, os.path.join(tmpdir, "cairo.sha256sum"))
logger.info("Verifying cairo sha256sum")
with open(os.path.join(tmpdir, "cairo.sha256sum")) as file:
sha256sum = file.read().split()[0]
verify_sha256sum(os.path.join(tmpdir, "cairo.tar.xz"), sha256sum)
logger.info("Extracting cairo")
extract_tar_xz(os.path.join(tmpdir, "cairo.tar.xz"), tmpdir)
with gha_group("Installing meson and ninja"):
logger.info("Creating virtual environment")
run_command([sys.executable, "-m", "venv", os.path.join(tmpdir, VENV_NAME)])
logger.info("Installing meson and ninja")
run_command(
[
os.path.join(tmpdir, VENV_NAME, "bin", "pip"),
"install",
"meson",
"ninja",
]
)
env_vars = {
# add the venv bin directory to PATH so that meson can find ninja
"PATH": f"{os.path.join(tmpdir, VENV_NAME, 'bin')}{os.pathsep}{os.environ['PATH']}",
}
with gha_group("Building and Installing Cairo"):
logger.info("Running meson setup")
run_command(
[
os.path.join(tmpdir, VENV_NAME, "bin", "meson"),
"setup",
BUILD_DIR,
f"--prefix={INSTALL_PREFIX.absolute().as_posix()}",
"--buildtype=release",
"-Dtests=disabled",
],
cwd=os.path.join(tmpdir, f"cairo-{CAIRO_VERSION}"),
env=env_vars,
)
logger.info("Running meson compile")
run_command(
[
os.path.join(tmpdir, VENV_NAME, "bin", "meson"),
"compile",
"-C",
BUILD_DIR,
],
cwd=os.path.join(tmpdir, f"cairo-{CAIRO_VERSION}"),
env=env_vars,
)
logger.info("Running meson install")
run_command(
[
os.path.join(tmpdir, VENV_NAME, "bin", "meson"),
"install",
"-C",
BUILD_DIR,
],
cwd=os.path.join(tmpdir, f"cairo-{CAIRO_VERSION}"),
env=env_vars,
)
logger.info(f"Successfully built cairo and installed it to {INSTALL_PREFIX}")
if __name__ == "__main__":
if "--set-env-vars" in sys.argv:
with gha_group("Setting environment variables"):
# append the pkgconfig directory to PKG_CONFIG_PATH
set_env_var_gha(
"PKG_CONFIG_PATH",
f"{Path(get_ld_library_path(INSTALL_PREFIX), 'pkgconfig').as_posix()}{os.pathsep}"
f'{os.getenv("PKG_CONFIG_PATH", "")}',
)
set_env_var_gha(
"LD_LIBRARY_PATH",
f"{get_ld_library_path(INSTALL_PREFIX)}{os.pathsep}"
f'{os.getenv("LD_LIBRARY_PATH", "")}',
)
sys.exit(0)
main()
|
manim_ManimCommunity/.github/PULL_REQUEST_TEMPLATE/hackathon.md
|
Thanks for your contribution for the manim community hackathon!
Please make sure your pull request has a meaningful title.
E.g. "Example for the class Angle".
Details for the submissions can be found in the [discord announcement channel](https://discord.com/channels/581738731934056449/581739610154074112/846460718479966228
).
Docstrings can be created in the discord channel with the manimator like this:
```
!mdocstring
```
```python
class HelloWorld(Scene):
def construct(self):
self.add(Circle())
```
Copy+paste the output docstring to the right place in the source code.
If you need any help, do not hesitate to ask the hackathon-mentors in the discord channel.
|
manim_ManimCommunity/.github/PULL_REQUEST_TEMPLATE/documentation.md
|
<!-- Thank you for contributing to ManimCommunity!
Before filling in the details, ensure:
- The title of your PR gives a descriptive summary to end-users. Some examples:
- Fixed last animations not running to completion
- Added gradient support and documentation for SVG files
-->
## Summary of Changes
## Changelog
<!-- Optional: more descriptive changelog entry than just the title for the upcoming
release. Write RST between the following start and end comments.-->
<!--changelog-start-->
<!--changelog-end-->
## Checklist
- [ ] I have read the [Contributing Guidelines](https://docs.manim.community/en/latest/contributing.html)
- [ ] I have written a descriptive PR title (see top of PR template for examples)
- [ ] My new documentation builds, looks correctly formatted, and adds no additional build warnings
<!-- Do not modify the lines below. These are for the reviewers of your PR -->
## Reviewer Checklist
- [ ] The PR title is descriptive enough
- [ ] The PR is labeled appropriately
- [ ] Newly added documentation builds, looks correctly formatted, and adds no additional build warnings
|
manim_ManimCommunity/.github/PULL_REQUEST_TEMPLATE/bugfix.md
|
<!-- Thank you for contributing to ManimCommunity!
Before filling in the details, ensure:
- The title of your PR gives a descriptive summary to end-users. Some examples:
- Fixed last animations not running to completion
- Added gradient support and documentation for SVG files
-->
## Changelog
<!-- Optional: more descriptive changelog entry than just the title for the upcoming
release. Write RST between the following start and end comments.-->
<!--changelog-start-->
<!--changelog-end-->
## Summary of Changes
## Checklist
- [ ] I have read the [Contributing Guidelines](https://docs.manim.community/en/latest/contributing.html)
- [ ] I have written a descriptive PR title (see top of PR template for examples)
- [ ] I have added a test case to prevent software regression
<!-- Do not modify the lines below. These are for the reviewers of your PR -->
## Reviewer Checklist
- [ ] The PR title is descriptive enough
- [ ] The PR is labeled appropriately
- [ ] Regression test(s) are implemented
|
manim_ManimCommunity/.github/ISSUE_TEMPLATE/bug_report.md
|
---
name: Manim bug
about: Report a bug or unexpected behavior when running Manim
title: ""
labels: bug
assignees: ''
---
## Description of bug / unexpected behavior
<!-- Add a clear and concise description of the problem you encountered. -->
## Expected behavior
<!-- Add a clear and concise description of what you expected to happen. -->
## How to reproduce the issue
<!-- Provide a piece of code illustrating the undesired behavior. -->
<details><summary>Code for reproducing the problem</summary>
```py
Paste your code here.
```
</details>
## Additional media files
<!-- Paste in the files manim produced on rendering the code above. -->
<details><summary>Images/GIFs</summary>
<!-- PASTE MEDIA HERE -->
</details>
## Logs
<details><summary>Terminal output</summary>
<!-- Add "-v DEBUG" when calling manim to generate more detailed logs -->
```
PASTE HERE OR PROVIDE LINK TO https://pastebin.com/ OR SIMILAR
```
<!-- Insert screenshots here (only when absolutely necessary, we prefer copy/pasted output!) -->
</details>
## System specifications
<details><summary>System Details</summary>
- OS (with version, e.g., Windows 10 v2004 or macOS 10.15 (Catalina)):
- RAM:
- Python version (`python/py/python3 --version`):
- Installed modules (provide output from `pip list`):
```
PASTE HERE
```
</details>
<details><summary>LaTeX details</summary>
+ LaTeX distribution (e.g. TeX Live 2020):
+ Installed LaTeX packages:
<!-- output of `tlmgr list --only-installed` for TeX Live or a screenshot of the Packages page for MikTeX -->
</details>
<details><summary>FFMPEG</summary>
Output of `ffmpeg -version`:
```
PASTE HERE
```
</details>
## Additional comments
<!-- Add further context that you think might be relevant for this issue here. -->
|
manim_ManimCommunity/.github/ISSUE_TEMPLATE/installation_issue.md
|
---
name: Installation issue
about: Report issues with the installation process of Manim
title: ""
labels: bug, installation
assignees: ''
---
#### Preliminaries
- [ ] I have followed the latest version of the
[installation instructions](https://docs.manim.community/en/stable/installation.html).
- [ ] I have checked the [installation FAQ](https://docs.manim.community/en/stable/faq/installation.html) and my problem is either not mentioned there,
or the solution given there does not help.
## Description of error
<!-- Add a clear and concise description of the problem you encountered. -->
## Installation logs
<!-- Please paste the **full** terminal output; we can only help to identify the issue
when we receive all required information. -->
<details><summary>Terminal output</summary>
```
PASTE HERE OR PROVIDE LINK TO https://pastebin.com/ OR SIMILAR
```
<!-- Insert screenshots here (only when absolutely necessary, we prefer copy/pasted output!) -->
</details>
## System specifications
<details><summary>System Details</summary>
- OS (with version, e.g., Windows 10 v2004 or macOS 10.15 (Catalina)):
- RAM:
- Python version (`python/py/python3 --version`):
- Installed modules (provide output from `pip list`):
```
PASTE HERE
```
</details>
<details><summary>LaTeX details</summary>
+ LaTeX distribution (e.g. TeX Live 2020):
+ Installed LaTeX packages:
<!-- output of `tlmgr list --only-installed` for TeX Live or a screenshot of the Packages page for MikTeX -->
</details>
<details><summary>FFMPEG</summary>
Output of `ffmpeg -version`:
```
PASTE HERE
```
</details>
## Additional comments
<!-- Add further context that you think might be relevant for this issue here. -->
|
manim_ManimCommunity/.github/ISSUE_TEMPLATE/feature_request.md
|
---
name: Feature request
about: Request a new feature for Manim
title: ""
labels: new feature
assignees: ''
---
## Description of proposed feature
<!-- Add a clear and concise description of the new feature, including a motivation: why do you think this will be useful? -->
## How can the new feature be used?
<!-- If possible, illustrate how this new feature could be used. -->
## Additional comments
<!-- Add further context that you think might be relevant. -->
|
manim_ManimCommunity/scripts/extract_frames.py
|
import pathlib
import sys
import numpy as np
from PIL import Image
def main():
if len(sys.argv) != 3:
print_usage()
sys.exit(1)
npz_file = sys.argv[1]
output_folder = pathlib.Path(sys.argv[2])
if not output_folder.exists():
output_folder.mkdir(parents=True)
data = np.load(npz_file)
if "frame_data" not in data:
print("The given file did not have frame_data.")
print("Are you sure this is from a Manim Graphical Unit Test?")
sys.exit(2)
frames = data["frame_data"]
for i, frame in enumerate(frames):
img = Image.fromarray(frame)
img.save(output_folder / f"frame{i}.png")
print(f"Saved {len(frames)} frames to {output_folder}")
def print_usage():
print("Manim Graphical Test Frame Extractor")
print(
"This tool outputs the frames of a Graphical Unit Test "
"stored within a .npz file, typically found under "
r"//tests/test_graphical_units/control_data"
)
print()
print("usage:")
print("python3 extract_frames.py npz_file output_directory")
if __name__ == "__main__":
main()
|
manim_ManimCommunity/scripts/template_docsting_with_example.py
|
# see more documentation guidelines online here: https://github.com/ManimCommunity/manim/wiki/Documentation-guidelines-(WIP)
from __future__ import annotations
class SomeClass:
"""A one line description of the Class.
A short paragraph providing more details.
Extended Summary
Parameters
----------
scale_factor
The factor used for scaling.
Returns
-------
:class:`~.VMobject`
Returns the modified :class:`~.VMobject`.
Tests
-----
Yields
-------
Receives
----------
Other Parameters
-----------------
Raises
------
:class:`TypeError`
If one element of the list is not an instance of VMobject
Warns
-----
Warnings
--------
Notes
-----
Examples
--------
.. manim:: AddTextLetterByLetterScene
:save_last_frame:
class AddTextLetterByLetterScene(Scene):
def construct(self):
t = Text("Hello World word by word")
self.play(AddTextWordByWord(t))
See Also
--------
:class:`Create`, :class:`~.ShowPassingFlash`
References
----------
Other useful directives:
.. tip::
This is currently only possible for class:`~.Text` and not for class:`~.MathTex`.
.. note::
This is something to note.
"""
|
manim_ManimCommunity/scripts/dev_changelog.py
|
#!/usr/bin/env python
"""Script to generate contributor and pull request lists.
This script generates contributor and pull request lists for release
changelogs using Github v3 protocol. Use requires an authentication token in
order to have sufficient bandwidth, you can get one following the directions at
`<https://help.github.com/articles/creating-an-access-token-for-command-line-use/>_
Don't add any scope, as the default is read access to public information. The
token may be stored in an environment variable as you only get one chance to
see it.
Usage::
$ ./scripts/dev_changelog.py [OPTIONS] TOKEN PRIOR TAG [ADDITIONAL]...
The output is utf8 rst.
Dependencies
------------
- gitpython
- pygithub
Examples
--------
From a bash command line with $GITHUB environment variable as the GitHub token::
$ ./scripts/dev_changelog.py $GITHUB v0.3.0 v0.4.0
This would generate 0.4.0-changelog.rst file and place it automatically under
docs/source/changelog/.
As another example, you may also run include PRs that have been excluded by
providing a space separated list of ticket numbers after TAG::
$ ./scripts/dev_changelog.py $GITHUB v0.3.0 v0.4.0 1911 1234 1492 ...
Note
----
This script was taken from Numpy under the terms of BSD-3-Clause license.
"""
from __future__ import annotations
import concurrent.futures
import datetime
import re
from collections import defaultdict
from pathlib import Path
from textwrap import dedent, indent
import cloup
from git import Repo
from github import Github
from tqdm import tqdm
from manim.constants import CONTEXT_SETTINGS, EPILOG
this_repo = Repo(str(Path(__file__).resolve().parent.parent))
PR_LABELS = {
"breaking changes": "Breaking changes",
"highlight": "Highlights",
"pr:deprecation": "Deprecated classes and functions",
"new feature": "New features",
"enhancement": "Enhancements",
"pr:bugfix": "Fixed bugs",
"documentation": "Documentation-related changes",
"testing": "Changes concerning the testing system",
"infrastructure": "Changes to our development infrastructure",
"maintenance": "Code quality improvements and similar refactors",
"revert": "Changes that needed to be reverted again",
"release": "New releases",
"unlabeled": "Unclassified changes",
}
SILENT_CONTRIBUTORS = [
"dependabot[bot]",
]
def update_citation(version, date):
current_directory = Path(__file__).parent
parent_directory = current_directory.parent
contents = (current_directory / "TEMPLATE.cff").read_text()
contents = contents.replace("<version>", version)
contents = contents.replace("<date_released>", date)
with (parent_directory / "CITATION.cff").open("w", newline="\n") as f:
f.write(contents)
def process_pullrequests(lst, cur, github_repo, pr_nums):
lst_commit = github_repo.get_commit(sha=this_repo.git.rev_list("-1", lst))
lst_date = lst_commit.commit.author.date
authors = set()
reviewers = set()
pr_by_labels = defaultdict(list)
with concurrent.futures.ThreadPoolExecutor() as executor:
future_to_num = {
executor.submit(github_repo.get_pull, num): num for num in pr_nums
}
for future in tqdm(
concurrent.futures.as_completed(future_to_num), "Processing PRs"
):
pr = future.result()
authors.add(pr.user)
reviewers = reviewers.union(rev.user for rev in pr.get_reviews())
pr_labels = [label.name for label in pr.labels]
for label in PR_LABELS.keys():
if label in pr_labels:
pr_by_labels[label].append(pr)
break # ensure that PR is only added in one category
else:
pr_by_labels["unlabeled"].append(pr)
# identify first-time contributors:
author_names = []
for author in authors:
name = author.name if author.name is not None else author.login
if name in SILENT_CONTRIBUTORS:
continue
if github_repo.get_commits(author=author, until=lst_date).totalCount == 0:
name += " +"
author_names.append(name)
reviewer_names = []
for reviewer in reviewers:
name = reviewer.name if reviewer.name is not None else reviewer.login
if name in SILENT_CONTRIBUTORS:
continue
reviewer_names.append(name)
# Sort items in pr_by_labels
for i in pr_by_labels:
pr_by_labels[i] = sorted(pr_by_labels[i], key=lambda pr: pr.number)
return {
"authors": sorted(author_names),
"reviewers": sorted(reviewer_names),
"PRs": pr_by_labels,
}
def get_pr_nums(lst, cur):
print("Getting PR Numbers:")
prnums = []
# From regular merges
merges = this_repo.git.log("--oneline", "--merges", f"{lst}..{cur}")
issues = re.findall(r".*\(\#(\d+)\)", merges)
prnums.extend(int(s) for s in issues)
# From fast forward squash-merges
commits = this_repo.git.log(
"--oneline",
"--no-merges",
"--first-parent",
f"{lst}..{cur}",
)
split_commits = list(
filter(
lambda x: not any(
["pre-commit autoupdate" in x, "New Crowdin updates" in x]
),
commits.split("\n"),
),
)
commits = "\n".join(split_commits)
issues = re.findall(r"^.*\(\#(\d+)\)$", commits, re.M)
prnums.extend(int(s) for s in issues)
print(prnums)
return prnums
def get_summary(body):
pattern = '<!--changelog-start-->([^"]*)<!--changelog-end-->'
try:
has_changelog_pattern = re.search(pattern, body)
if has_changelog_pattern:
return has_changelog_pattern.group()[22:-21].strip()
except Exception:
print(f"Error parsing body for changelog: {body}")
@cloup.command(
context_settings=CONTEXT_SETTINGS,
epilog=EPILOG,
)
@cloup.argument("token")
@cloup.argument("prior")
@cloup.argument("tag")
@cloup.argument(
"additional",
nargs=-1,
required=False,
type=int,
)
@cloup.option(
"-o",
"--outfile",
type=str,
help="Path and file name of the changelog output.",
)
def main(token, prior, tag, additional, outfile):
"""Generate Changelog/List of contributors/PRs for release.
TOKEN is your GitHub Personal Access Token.
PRIOR is the tag/commit SHA of the previous release.
TAG is the tag of the new release.
ADDITIONAL includes additional PR(s) that have not been recognized automatically.
"""
lst_release, cur_release = prior, tag
github = Github(token)
github_repo = github.get_repo("ManimCommunity/manim")
pr_nums = get_pr_nums(lst_release, cur_release)
if additional:
print(f"Adding {additional} to the mix!")
pr_nums = pr_nums + list(additional)
# document authors
contributions = process_pullrequests(lst_release, cur_release, github_repo, pr_nums)
authors = contributions["authors"]
reviewers = contributions["reviewers"]
# update citation file
today = datetime.date.today()
update_citation(tag, str(today))
if not outfile:
outfile = (
Path(__file__).resolve().parent.parent / "docs" / "source" / "changelog"
)
outfile = outfile / f"{tag[1:] if tag.startswith('v') else tag}-changelog.rst"
else:
outfile = Path(outfile).resolve()
with outfile.open("w", encoding="utf8", newline="\n") as f:
f.write("*" * len(tag) + "\n")
f.write(f"{tag}\n")
f.write("*" * len(tag) + "\n\n")
f.write(f":Date: {today.strftime('%B %d, %Y')}\n\n")
heading = "Contributors"
f.write(f"{heading}\n")
f.write("=" * len(heading) + "\n\n")
f.write(
dedent(
f"""\
A total of {len(set(authors).union(set(reviewers)))} people contributed to this
release. People with a '+' by their names authored a patch for the first
time.\n
""",
),
)
for author in authors:
f.write(f"* {author}\n")
f.write("\n")
f.write(
dedent(
"""
The patches included in this release have been reviewed by
the following contributors.\n
""",
),
)
for reviewer in reviewers:
f.write(f"* {reviewer}\n")
# document pull requests
heading = "Pull requests merged"
f.write("\n")
f.write(heading + "\n")
f.write("=" * len(heading) + "\n\n")
f.write(
f"A total of {len(pr_nums)} pull requests were merged for this release.\n\n",
)
pr_by_labels = contributions["PRs"]
for label in PR_LABELS.keys():
pr_of_label = pr_by_labels[label]
if pr_of_label:
heading = PR_LABELS[label]
f.write(f"{heading}\n")
f.write("-" * len(heading) + "\n\n")
for PR in pr_by_labels[label]:
num = PR.number
url = PR.html_url
title = PR.title
label = PR.labels
f.write(f"* :pr:`{num}`: {title}\n")
overview = get_summary(PR.body)
if overview:
f.write(indent(f"{overview}\n\n", " "))
else:
f.write("\n\n")
print(f"Wrote changelog to: {outfile}")
if __name__ == "__main__":
main()
|
manim_ManimCommunity/scripts/make_and_open_docs.py
|
from __future__ import annotations
import os
import sys
import webbrowser
from pathlib import Path
path_makefile = Path(__file__).parents[1] / "docs"
os.system(f"cd {path_makefile} && make html")
website = (path_makefile / "build" / "html" / "index.html").absolute().as_uri()
try: # Allows you to pass a custom browser if you want.
webbrowser.get(sys.argv[1]).open_new_tab(f"{website}")
except IndexError:
webbrowser.open_new_tab(f"{website}")
|
manim_ManimCommunity/example_scenes/advanced_tex_fonts.py
|
from manim import *
# French Cursive LaTeX font example from http://jf.burnol.free.fr/showcase.html
# Example 1 Manually creating a Template
TemplateForFrenchCursive = TexTemplate(
preamble=r"""
\usepackage[english]{babel}
\usepackage{amsmath}
\usepackage{amssymb}
\usepackage[T1]{fontenc}
\usepackage[default]{frcursive}
\usepackage[eulergreek,noplusnominus,noequal,nohbar,%
nolessnomore,noasterisk]{mathastext}
""",
)
def FrenchCursive(*tex_strings, **kwargs):
return Tex(*tex_strings, tex_template=TemplateForFrenchCursive, **kwargs)
class TexFontTemplateManual(Scene):
"""An example scene that uses a manually defined TexTemplate() object to create
LaTeX output in French Cursive font"""
def construct(self):
self.add(Tex("Tex Font Example").to_edge(UL))
self.play(Create(FrenchCursive("$f: A \\longrightarrow B$").shift(UP)))
self.play(Create(FrenchCursive("Behold! We can write math in French Cursive")))
self.wait(1)
self.play(
Create(
Tex(
"See more font templates at \\\\ http://jf.burnol.free.fr/showcase.html",
).shift(2 * DOWN),
),
)
self.wait(2)
# Example 2, using a Template from the collection
class TexFontTemplateLibrary(Scene):
"""An example scene that uses TexTemplate objects from the TexFontTemplates collection
to create sample LaTeX output in every font that will compile on the local system.
Please Note:
Many of the in the TexFontTemplates collection require that specific fonts
are installed on your local machine.
For example, choosing the template TexFontTemplates.comic_sans will
not compile if the Comic Sans Micrososft font is not installed.
This scene will only render those Templates that do not cause a TeX
compilation error on your system. Furthermore, some of the ones that do render,
may still render incorrectly. This is beyond the scope of manim.
Feel free to experiment.
"""
def construct(self):
def write_one_line(template):
x = Tex(template.description, tex_template=template).shift(UP)
self.play(Create(x))
self.wait(1)
self.play(FadeOut(x))
examples = [
TexFontTemplates.american_typewriter, # "American Typewriter"
TexFontTemplates.antykwa, # "Antykwa Półtawskiego (TX Fonts for Greek and math symbols)"
TexFontTemplates.apple_chancery, # "Apple Chancery"
TexFontTemplates.auriocus_kalligraphicus, # "Auriocus Kalligraphicus (Symbol Greek)"
TexFontTemplates.baskervald_adf_fourier, # "Baskervald ADF with Fourier"
TexFontTemplates.baskerville_it, # "Baskerville (Italic)"
TexFontTemplates.biolinum, # "Biolinum"
TexFontTemplates.brushscriptx, # "BrushScriptX-Italic (PX math and Greek)"
TexFontTemplates.chalkboard_se, # "Chalkboard SE"
TexFontTemplates.chalkduster, # "Chalkduster"
TexFontTemplates.comfortaa, # "Comfortaa"
TexFontTemplates.comic_sans, # "Comic Sans MS"
TexFontTemplates.droid_sans, # "Droid Sans"
TexFontTemplates.droid_sans_it, # "Droid Sans (Italic)"
TexFontTemplates.droid_serif, # "Droid Serif"
TexFontTemplates.droid_serif_px_it, # "Droid Serif (PX math symbols) (Italic)"
TexFontTemplates.ecf_augie, # "ECF Augie (Euler Greek)"
TexFontTemplates.ecf_jd, # "ECF JD (with TX fonts)"
TexFontTemplates.ecf_skeetch, # "ECF Skeetch (CM Greek)"
TexFontTemplates.ecf_tall_paul, # "ECF Tall Paul (with Symbol font)"
TexFontTemplates.ecf_webster, # "ECF Webster (with TX fonts)"
TexFontTemplates.electrum_adf, # "Electrum ADF (CM Greek)"
TexFontTemplates.epigrafica, # Epigrafica
TexFontTemplates.fourier_utopia, # "Fourier Utopia (Fourier upright Greek)"
TexFontTemplates.french_cursive, # "French Cursive (Euler Greek)"
TexFontTemplates.gfs_bodoni, # "GFS Bodoni"
TexFontTemplates.gfs_didot, # "GFS Didot (Italic)"
TexFontTemplates.gfs_neoHellenic, # "GFS NeoHellenic"
TexFontTemplates.gnu_freesans_tx, # "GNU FreeSerif (and TX fonts symbols)"
TexFontTemplates.gnu_freeserif_freesans, # "GNU FreeSerif and FreeSans"
TexFontTemplates.helvetica_fourier_it, # "Helvetica with Fourier (Italic)"
TexFontTemplates.latin_modern_tw_it, # "Latin Modern Typewriter Proportional (CM Greek) (Italic)"
TexFontTemplates.latin_modern_tw, # "Latin Modern Typewriter Proportional"
TexFontTemplates.libertine, # "Libertine"
TexFontTemplates.libris_adf_fourier, # "Libris ADF with Fourier"
TexFontTemplates.minion_pro_myriad_pro, # "Minion Pro and Myriad Pro (and TX fonts symbols)"
TexFontTemplates.minion_pro_tx, # "Minion Pro (and TX fonts symbols)"
TexFontTemplates.new_century_schoolbook, # "New Century Schoolbook (Symbol Greek)"
TexFontTemplates.new_century_schoolbook_px, # "New Century Schoolbook (Symbol Greek, PX math symbols)"
TexFontTemplates.noteworthy_light, # "Noteworthy Light"
TexFontTemplates.palatino, # "Palatino (Symbol Greek)"
TexFontTemplates.papyrus, # "Papyrus"
TexFontTemplates.romande_adf_fourier_it, # "Romande ADF with Fourier (Italic)"
TexFontTemplates.slitex, # "SliTeX (Euler Greek)"
TexFontTemplates.times_fourier_it, # "Times with Fourier (Italic)"
TexFontTemplates.urw_avant_garde, # "URW Avant Garde (Symbol Greek)"
TexFontTemplates.urw_zapf_chancery, # "URW Zapf Chancery (CM Greek)"
TexFontTemplates.venturis_adf_fourier_it, # "Venturis ADF with Fourier (Italic)"
TexFontTemplates.verdana_it, # "Verdana (Italic)"
TexFontTemplates.vollkorn_fourier_it, # "Vollkorn with Fourier (Italic)"
TexFontTemplates.vollkorn, # "Vollkorn (TX fonts for Greek and math symbols)"
TexFontTemplates.zapf_chancery, # "Zapf Chancery"
]
self.add(Tex("Tex Font Template Example").to_edge(UL))
for font in examples:
try:
write_one_line(font)
except Exception:
print("FAILURE on ", font.description, " - skipping.")
self.play(
Create(
Tex(
"See more font templates at \\\\ http://jf.burnol.free.fr/showcase.html",
).shift(2 * DOWN),
),
)
self.wait(2)
|
manim_ManimCommunity/example_scenes/opengl.py
|
from pathlib import Path
import manim.utils.opengl as opengl
from manim import *
from manim.opengl import * # type: ignore
# Copied from https://3b1b.github.io/manim/getting_started/example_scenes.html#surfaceexample.
# Lines that do not yet work with the Community Version are commented.
def get_plane_mesh(context):
shader = Shader(context, name="vertex_colors")
attributes = np.zeros(
18,
dtype=[
("in_vert", np.float32, (4,)),
("in_color", np.float32, (4,)),
],
)
attributes["in_vert"] = np.array(
[
# xy plane
[-1, -1, 0, 1],
[-1, 1, 0, 1],
[1, 1, 0, 1],
[-1, -1, 0, 1],
[1, -1, 0, 1],
[1, 1, 0, 1],
# yz plane
[0, -1, -1, 1],
[0, -1, 1, 1],
[0, 1, 1, 1],
[0, -1, -1, 1],
[0, 1, -1, 1],
[0, 1, 1, 1],
# xz plane
[-1, 0, -1, 1],
[-1, 0, 1, 1],
[1, 0, 1, 1],
[-1, 0, -1, 1],
[1, 0, -1, 1],
[1, 0, 1, 1],
],
)
attributes["in_color"] = np.array(
[
# xy plane
[1, 0, 0, 1],
[1, 0, 0, 1],
[1, 0, 0, 1],
[1, 0, 0, 1],
[1, 0, 0, 1],
[1, 0, 0, 1],
# yz plane
[0, 1, 0, 1],
[0, 1, 0, 1],
[0, 1, 0, 1],
[0, 1, 0, 1],
[0, 1, 0, 1],
[0, 1, 0, 1],
# xz plane
[0, 0, 1, 1],
[0, 0, 1, 1],
[0, 0, 1, 1],
[0, 0, 1, 1],
[0, 0, 1, 1],
[0, 0, 1, 1],
],
)
return Mesh(shader, attributes)
class TextTest(Scene):
def construct(self):
import string
text = Text(string.ascii_lowercase, stroke_width=4, stroke_color=BLUE).scale(2)
text2 = (
Text(string.ascii_uppercase, stroke_width=4, stroke_color=BLUE)
.scale(2)
.next_to(text, DOWN)
)
# self.add(text, text2)
self.play(Write(text))
self.play(Write(text2))
self.interactive_embed()
class GuiTest(Scene):
def construct(self):
mesh = get_plane_mesh(self.renderer.context)
# mesh.attributes["in_vert"][:, 0]
self.add(mesh)
def update_mesh(mesh, dt):
mesh.model_matrix = np.matmul(
opengl.rotation_matrix(z=dt),
mesh.model_matrix,
)
mesh.add_updater(update_mesh)
self.interactive_embed()
class GuiTest2(Scene):
def construct(self):
mesh = get_plane_mesh(self.renderer.context)
mesh.attributes["in_vert"][:, 0] -= 2
self.add(mesh)
mesh2 = get_plane_mesh(self.renderer.context)
mesh2.attributes["in_vert"][:, 0] += 2
self.add(mesh2)
def callback(sender, data):
mesh2.attributes["in_color"][:, 3] = dpg.get_value(sender)
self.widgets.append(
{
"name": "mesh2 opacity",
"widget": "slider_float",
"callback": callback,
"min_value": 0,
"max_value": 1,
"default_value": 1,
},
)
self.interactive_embed()
class ThreeDMobjectTest(Scene):
def construct(self):
# config["background_color"] = "#333333"
s = Square(fill_opacity=0.5).shift(2 * RIGHT)
self.add(s)
sp = Sphere().shift(2 * LEFT)
self.add(sp)
mesh = get_plane_mesh(self.renderer.context)
self.add(mesh)
def update_mesh(mesh, dt):
mesh.model_matrix = np.matmul(
opengl.rotation_matrix(z=dt),
mesh.model_matrix,
)
mesh.add_updater(update_mesh)
self.interactive_embed()
class NamedFullScreenQuad(Scene):
def construct(self):
surface = FullScreenQuad(self.renderer.context, fragment_shader_name="design_3")
surface.shader.set_uniform(
"u_resolution",
(config["pixel_width"], config["pixel_height"], 0.0),
)
surface.shader.set_uniform("u_time", 0)
self.add(surface)
t = 0
def update_surface(surface, dt):
nonlocal t
t += dt
surface.shader.set_uniform("u_time", t / 4)
surface.add_updater(update_surface)
# self.wait()
self.interactive_embed()
class InlineFullScreenQuad(Scene):
def construct(self):
surface = FullScreenQuad(
self.renderer.context,
"""
#version 330
#define TWO_PI 6.28318530718
uniform vec2 u_resolution;
uniform float u_time;
out vec4 frag_color;
// Function from Iñigo Quiles
// https://www.shadertoy.com/view/MsS3Wc
vec3 hsb2rgb( in vec3 c ){
vec3 rgb = clamp(abs(mod(c.x*6.0+vec3(0.0,4.0,2.0),
6.0)-3.0)-1.0,
0.0,
1.0 );
rgb = rgb*rgb*(3.0-2.0*rgb);
return c.z * mix( vec3(1.0), rgb, c.y);
}
void main(){
vec2 st = gl_FragCoord.xy/u_resolution;
vec3 color = vec3(0.0);
// Use polar coordinates instead of cartesian
vec2 toCenter = vec2(0.5)-st;
float angle = atan(toCenter.y,toCenter.x);
angle += u_time;
float radius = length(toCenter)*2.0;
// Map the angle (-PI to PI) to the Hue (from 0 to 1)
// and the Saturation to the radius
color = hsb2rgb(vec3((angle/TWO_PI)+0.5,radius,1.0));
frag_color = vec4(color,1.0);
}
""",
)
surface.shader.set_uniform(
"u_resolution",
(config["pixel_width"], config["pixel_height"]),
)
shader_time = 0
def update_surface(surface):
nonlocal shader_time
surface.shader.set_uniform("u_time", shader_time)
shader_time += 1 / 60.0
surface.add_updater(update_surface)
self.add(surface)
# self.wait(5)
self.interactive_embed()
class SimpleInlineFullScreenQuad(Scene):
def construct(self):
surface = FullScreenQuad(
self.renderer.context,
"""
#version 330
uniform float v_red;
uniform float v_green;
uniform float v_blue;
out vec4 frag_color;
void main() {
frag_color = vec4(v_red, v_green, v_blue, 1);
}
""",
)
surface.shader.set_uniform("v_red", 0)
surface.shader.set_uniform("v_green", 0)
surface.shader.set_uniform("v_blue", 0)
increase = True
val = 0.5
surface.shader.set_uniform("v_red", val)
surface.shader.set_uniform("v_green", val)
surface.shader.set_uniform("v_blue", val)
def update_surface(mesh, dt):
nonlocal increase
nonlocal val
if increase:
val += dt
else:
val -= dt
if val >= 1:
increase = False
elif val <= 0:
increase = True
surface.shader.set_uniform("v_red", val)
surface.shader.set_uniform("v_green", val)
surface.shader.set_uniform("v_blue", val)
surface.add_updater(update_surface)
self.add(surface)
self.wait(5)
class InlineShaderExample(Scene):
def construct(self):
config["background_color"] = "#333333"
c = Circle(fill_opacity=0.7).shift(UL)
self.add(c)
shader = Shader(
self.renderer.context,
source={
"vertex_shader": """
#version 330
in vec4 in_vert;
in vec4 in_color;
out vec4 v_color;
uniform mat4 u_model_view_matrix;
uniform mat4 u_projection_matrix;
void main() {
v_color = in_color;
vec4 camera_space_vertex = u_model_view_matrix * in_vert;
vec4 clip_space_vertex = u_projection_matrix * camera_space_vertex;
gl_Position = clip_space_vertex;
}
""",
"fragment_shader": """
#version 330
in vec4 v_color;
out vec4 frag_color;
void main() {
frag_color = v_color;
}
""",
},
)
shader.set_uniform("u_model_view_matrix", opengl.view_matrix())
shader.set_uniform(
"u_projection_matrix",
opengl.orthographic_projection_matrix(),
)
attributes = np.zeros(
6,
dtype=[
("in_vert", np.float32, (4,)),
("in_color", np.float32, (4,)),
],
)
attributes["in_vert"] = np.array(
[
[-1, -1, 0, 1],
[-1, 1, 0, 1],
[1, 1, 0, 1],
[-1, -1, 0, 1],
[1, -1, 0, 1],
[1, 1, 0, 1],
],
)
attributes["in_color"] = np.array(
[
[0, 0, 1, 1],
[0, 0, 1, 1],
[0, 0, 1, 1],
[0, 0, 1, 1],
[0, 0, 1, 1],
[0, 0, 1, 1],
],
)
mesh = Mesh(shader, attributes)
self.add(mesh)
self.wait(5)
# self.embed_2()
class NamedShaderExample(Scene):
def construct(self):
shader = Shader(self.renderer.context, "manim_coords")
shader.set_uniform("u_color", (0.0, 1.0, 0.0, 1.0))
view_matrix = self.camera.formatted_view_matrix
shader.set_uniform("u_model_view_matrix", view_matrix)
shader.set_uniform(
"u_projection_matrix",
opengl.perspective_projection_matrix(),
)
attributes = np.zeros(
6,
dtype=[
("in_vert", np.float32, (4,)),
],
)
attributes["in_vert"] = np.array(
[
[-1, -1, 0, 1],
[-1, 1, 0, 1],
[1, 1, 0, 1],
[-1, -1, 0, 1],
[1, -1, 0, 1],
[1, 1, 0, 1],
],
)
mesh = Mesh(shader, attributes)
self.add(mesh)
self.wait(5)
class InteractiveDevelopment(Scene):
def construct(self):
circle = Circle()
circle.set_fill(BLUE, opacity=0.5)
circle.set_stroke(BLUE_E, width=4)
square = Square()
self.play(Create(square))
self.wait()
# This opens an iPython termnial where you can keep writing
# lines as if they were part of this construct method.
# In particular, 'square', 'circle' and 'self' will all be
# part of the local namespace in that terminal.
# self.embed()
# Try copying and pasting some of the lines below into
# the interactive shell
self.play(ReplacementTransform(square, circle))
self.wait()
self.play(circle.animate.stretch(4, 0))
self.play(Rotate(circle, 90 * DEGREES))
self.play(circle.animate.shift(2 * RIGHT).scale(0.25))
# text = Text(
# """
# In general, using the interactive shell
# is very helpful when developing new scenes
# """
# )
# self.play(Write(text))
# # In the interactive shell, you can just type
# # play, add, remove, clear, wait, save_state and restore,
# # instead of self.play, self.add, self.remove, etc.
# # To interact with the window, type touch(). You can then
# # scroll in the window, or zoom by holding down 'z' while scrolling,
# # and change camera perspective by holding down 'd' while moving
# # the mouse. Press 'r' to reset to the standard camera position.
# # Press 'q' to stop interacting with the window and go back to
# # typing new commands into the shell.
# # In principle you can customize a scene to be responsive to
# # mouse and keyboard interactions
# always(circle.move_to, self.mouse_point)
class SurfaceExample(Scene):
def construct(self):
# surface_text = Text("For 3d scenes, try using surfaces")
# surface_text.fix_in_frame()
# surface_text.to_edge(UP)
# self.add(surface_text)
# self.wait(0.1)
torus1 = Torus(major_radius=1, minor_radius=1)
torus2 = Torus(major_radius=3, minor_radius=1)
sphere = Sphere(radius=3, resolution=torus1.resolution)
# You can texture a surface with up to two images, which will
# be interpreted as the side towards the light, and away from
# the light. These can be either urls, or paths to a local file
# in whatever you've set as the image directory in
# the custom_config.yml file
script_location = Path(__file__).resolve().parent
day_texture = (
script_location / "assets" / "1280px-Whole_world_-_land_and_oceans.jpg"
)
night_texture = script_location / "assets" / "1280px-The_earth_at_night.jpg"
surfaces = [
OpenGLTexturedSurface(surface, day_texture, night_texture)
for surface in [sphere, torus1, torus2]
]
for mob in surfaces:
mob.shift(IN)
mob.mesh = OpenGLSurfaceMesh(mob)
mob.mesh.set_stroke(BLUE, 1, opacity=0.5)
# Set perspective
frame = self.renderer.camera
frame.set_euler_angles(
theta=-30 * DEGREES,
phi=70 * DEGREES,
)
surface = surfaces[0]
self.play(
FadeIn(surface),
Create(surface.mesh, lag_ratio=0.01, run_time=3),
)
for mob in surfaces:
mob.add(mob.mesh)
surface.save_state()
self.play(Rotate(surface, PI / 2), run_time=2)
for mob in surfaces[1:]:
mob.rotate(PI / 2)
self.play(Transform(surface, surfaces[1]), run_time=3)
self.play(
Transform(surface, surfaces[2]),
# Move camera frame during the transition
frame.animate.increment_phi(-10 * DEGREES),
frame.animate.increment_theta(-20 * DEGREES),
run_time=3,
)
# Add ambient rotation
frame.add_updater(lambda m, dt: m.increment_theta(-0.1 * dt))
# Play around with where the light is
# light_text = Text("You can move around the light source")
# light_text.move_to(surface_text)
# light_text.fix_in_frame()
# self.play(FadeTransform(surface_text, light_text))
light = self.camera.light_source
self.add(light)
light.save_state()
self.play(light.animate.move_to(3 * IN), run_time=5)
self.play(light.animate.shift(10 * OUT), run_time=5)
# drag_text = Text("Try moving the mouse while pressing d or s")
# drag_text.move_to(light_text)
# drag_text.fix_in_frame()
|
manim_ManimCommunity/example_scenes/basic.py
|
#!/usr/bin/env python
from manim import *
# To watch one of these scenes, run the following:
# python --quality m manim -p example_scenes.py SquareToCircle
#
# Use the flag --quality l for a faster rendering at a lower quality.
# Use -s to skip to the end and just save the final frame
# Use the -p to have preview of the animation (or image, if -s was
# used) pop up once done.
# Use -n <number> to skip ahead to the nth animation of a scene.
# Use -r <number> to specify a resolution (for example, -r 1920,1080
# for a 1920x1080 video)
class OpeningManim(Scene):
def construct(self):
title = Tex(r"This is some \LaTeX")
basel = MathTex(r"\sum_{n=1}^\infty \frac{1}{n^2} = \frac{\pi^2}{6}")
VGroup(title, basel).arrange(DOWN)
self.play(
Write(title),
FadeIn(basel, shift=DOWN),
)
self.wait()
transform_title = Tex("That was a transform")
transform_title.to_corner(UP + LEFT)
self.play(
Transform(title, transform_title),
LaggedStart(*(FadeOut(obj, shift=DOWN) for obj in basel)),
)
self.wait()
grid = NumberPlane()
grid_title = Tex("This is a grid", font_size=72)
grid_title.move_to(transform_title)
self.add(grid, grid_title) # Make sure title is on top of grid
self.play(
FadeOut(title),
FadeIn(grid_title, shift=UP),
Create(grid, run_time=3, lag_ratio=0.1),
)
self.wait()
grid_transform_title = Tex(
r"That was a non-linear function \\ applied to the grid",
)
grid_transform_title.move_to(grid_title, UL)
grid.prepare_for_nonlinear_transform()
self.play(
grid.animate.apply_function(
lambda p: p
+ np.array(
[
np.sin(p[1]),
np.sin(p[0]),
0,
],
),
),
run_time=3,
)
self.wait()
self.play(Transform(grid_title, grid_transform_title))
self.wait()
class SquareToCircle(Scene):
def construct(self):
circle = Circle()
square = Square()
square.flip(RIGHT)
square.rotate(-3 * TAU / 8)
circle.set_fill(PINK, opacity=0.5)
self.play(Create(square))
self.play(Transform(square, circle))
self.play(FadeOut(square))
class WarpSquare(Scene):
def construct(self):
square = Square()
self.play(
ApplyPointwiseFunction(
lambda point: complex_to_R3(np.exp(R3_to_complex(point))),
square,
),
)
self.wait()
class WriteStuff(Scene):
def construct(self):
example_text = Tex("This is a some text", tex_to_color_map={"text": YELLOW})
example_tex = MathTex(
"\\sum_{k=1}^\\infty {1 \\over k^2} = {\\pi^2 \\over 6}",
)
group = VGroup(example_text, example_tex)
group.arrange(DOWN)
group.width = config["frame_width"] - 2 * LARGE_BUFF
self.play(Write(example_text))
self.play(Write(example_tex))
self.wait()
class UpdatersExample(Scene):
def construct(self):
decimal = DecimalNumber(
0,
show_ellipsis=True,
num_decimal_places=3,
include_sign=True,
)
square = Square().to_edge(UP)
decimal.add_updater(lambda d: d.next_to(square, RIGHT))
decimal.add_updater(lambda d: d.set_value(square.get_center()[1]))
self.add(square, decimal)
self.play(
square.animate.to_edge(DOWN),
rate_func=there_and_back,
run_time=5,
)
self.wait()
class SpiralInExample(Scene):
def construct(self):
logo_green = "#81b29a"
logo_blue = "#454866"
logo_red = "#e07a5f"
font_color = "#ece6e2"
pi = MathTex(r"\pi").scale(7).set_color(font_color)
pi.shift(2.25 * LEFT + 1.5 * UP)
circle = Circle(color=logo_green, fill_opacity=0.7, stroke_width=0).shift(LEFT)
square = Square(color=logo_blue, fill_opacity=0.8, stroke_width=0).shift(UP)
triangle = Triangle(color=logo_red, fill_opacity=0.9, stroke_width=0).shift(
RIGHT
)
pentagon = Polygon(
*[
[np.cos(2 * np.pi / 5 * i), np.sin(2 * np.pi / 5 * i), 0]
for i in range(5)
],
color=PURPLE_B,
fill_opacity=1,
stroke_width=0
).shift(UP + 2 * RIGHT)
shapes = VGroup(triangle, square, circle, pentagon, pi)
self.play(SpiralIn(shapes, fade_in_fraction=0.9))
self.wait()
self.play(FadeOut(shapes))
Triangle.set_default(stroke_width=20)
class LineJoints(Scene):
def construct(self):
t1 = Triangle()
t2 = Triangle(joint_type=LineJointType.ROUND)
t3 = Triangle(joint_type=LineJointType.BEVEL)
grp = VGroup(t1, t2, t3).arrange(RIGHT)
grp.set(width=config.frame_width - 1)
self.add(grp)
# See many more examples at https://docs.manim.community/en/stable/examples.html
|
manim_ManimCommunity/example_scenes/customtex.py
|
from manim import *
class TexTemplateFromCLI(Scene):
"""This scene uses a custom TexTemplate file.
The path of the TexTemplate _must_ be passed with the command line
argument `--tex_template <path to template>`.
For this scene, you can use the custom_template.tex file next to it.
This scene will fail to render if a tex_template.tex that doesn't
import esvect is passed, and will throw a LaTeX error in that case.
"""
def construct(self):
text = MathTex(r"\vv{vb}")
self.play(Write(text))
self.wait(1)
class InCodeTexTemplate(Scene):
"""This example scene demonstrates how to modify the tex template
for a particular scene from the code for the scene itself.
"""
def construct(self):
# Create a new template
myTemplate = TexTemplate()
# Add packages to the template
myTemplate.add_to_preamble(r"\usepackage{esvect}")
# Set the compiler and output format (default: latex and .dvi)
# possible tex compilers: "latex", "pdflatex", "xelatex", "lualatex", "luatex"
# possible output formats: ".dvi", ".pdf", and ".xdv"
myTemplate.tex_compiler = "latex"
myTemplate.output_format = ".dvi"
# To use this template in a Tex() or MathTex() object
# use the keyword argument tex_template
text = MathTex(r"\vv{vb}", tex_template=myTemplate)
self.play(Write(text))
self.wait(1)
|
manim_ManimCommunity/manim/__main__.py
|
from __future__ import annotations
import sys
import click
import cloup
from . import __version__, cli_ctx_settings, console
from .cli.cfg.group import cfg
from .cli.checkhealth.commands import checkhealth
from .cli.default_group import DefaultGroup
from .cli.init.commands import init
from .cli.plugins.commands import plugins
from .cli.render.commands import render
from .constants import EPILOG
def show_splash(ctx, param, value):
if value:
console.print(f"Manim Community [green]v{__version__}[/green]\n")
def print_version_and_exit(ctx, param, value):
show_splash(ctx, param, value)
if value:
ctx.exit()
@cloup.group(
context_settings=cli_ctx_settings,
cls=DefaultGroup,
default="render",
no_args_is_help=True,
help="Animation engine for explanatory math videos.",
epilog="See 'manim <command>' to read about a specific subcommand.\n\n"
"Note: the subcommand 'manim render' is called if no other subcommand "
"is specified. Run 'manim render --help' if you would like to know what the "
f"'-ql' or '-p' flags do, for example.\n\n{EPILOG}",
)
@cloup.option(
"--version",
is_flag=True,
help="Show version and exit.",
callback=print_version_and_exit,
is_eager=True,
expose_value=False,
)
@click.option(
"--show-splash/--hide-splash",
is_flag=True,
default=True,
help="Print splash message with version information.",
callback=show_splash,
is_eager=True,
expose_value=False,
)
@cloup.pass_context
def main(ctx):
"""The entry point for manim."""
pass
main.add_command(checkhealth)
main.add_command(cfg)
main.add_command(plugins)
main.add_command(init)
main.add_command(render)
if __name__ == "__main__":
main()
|
manim_ManimCommunity/manim/__init__.py
|
#!/usr/bin/env python
from __future__ import annotations
from importlib.metadata import version
__version__ = version(__name__)
# isort: off
# Importing the config module should be the first thing we do, since other
# modules depend on the global config dict for initialization.
from ._config import *
# many scripts depend on this -> has to be loaded first
from .utils.commands import *
# isort: on
import numpy as np
from .animation.animation import *
from .animation.changing import *
from .animation.composition import *
from .animation.creation import *
from .animation.fading import *
from .animation.growing import *
from .animation.indication import *
from .animation.movement import *
from .animation.numbers import *
from .animation.rotation import *
from .animation.specialized import *
from .animation.speedmodifier import *
from .animation.transform import *
from .animation.transform_matching_parts import *
from .animation.updaters.mobject_update_utils import *
from .animation.updaters.update import *
from .camera.camera import *
from .camera.mapping_camera import *
from .camera.moving_camera import *
from .camera.multi_camera import *
from .camera.three_d_camera import *
from .constants import *
from .mobject.frame import *
from .mobject.geometry.arc import *
from .mobject.geometry.boolean_ops import *
from .mobject.geometry.labeled import *
from .mobject.geometry.line import *
from .mobject.geometry.polygram import *
from .mobject.geometry.shape_matchers import *
from .mobject.geometry.tips import *
from .mobject.graph import *
from .mobject.graphing.coordinate_systems import *
from .mobject.graphing.functions import *
from .mobject.graphing.number_line import *
from .mobject.graphing.probability import *
from .mobject.graphing.scale import *
from .mobject.logo import *
from .mobject.matrix import *
from .mobject.mobject import *
from .mobject.opengl.dot_cloud import *
from .mobject.opengl.opengl_point_cloud_mobject import *
from .mobject.svg.brace import *
from .mobject.svg.svg_mobject import *
from .mobject.table import *
from .mobject.text.code_mobject import *
from .mobject.text.numbers import *
from .mobject.text.tex_mobject import *
from .mobject.text.text_mobject import *
from .mobject.three_d.polyhedra import *
from .mobject.three_d.three_d_utils import *
from .mobject.three_d.three_dimensions import *
from .mobject.types.image_mobject import *
from .mobject.types.point_cloud_mobject import *
from .mobject.types.vectorized_mobject import *
from .mobject.value_tracker import *
from .mobject.vector_field import *
from .renderer.cairo_renderer import *
from .scene.moving_camera_scene import *
from .scene.scene import *
from .scene.scene_file_writer import *
from .scene.section import *
from .scene.three_d_scene import *
from .scene.vector_space_scene import *
from .scene.zoomed_scene import *
from .utils import color, rate_functions, unit
from .utils.bezier import *
from .utils.color import *
from .utils.config_ops import *
from .utils.debug import *
from .utils.file_ops import *
from .utils.images import *
from .utils.iterables import *
from .utils.paths import *
from .utils.rate_functions import *
from .utils.simple_functions import *
from .utils.sounds import *
from .utils.space_ops import *
from .utils.tex import *
from .utils.tex_templates import *
try:
from IPython import get_ipython
from .utils.ipython_magic import ManimMagic
except ImportError:
pass
else:
ipy = get_ipython()
if ipy is not None:
ipy.register_magics(ManimMagic)
from .plugins import *
|
manim_ManimCommunity/manim/constants.py
|
"""
Constant definitions.
"""
from __future__ import annotations
from enum import Enum
import numpy as np
from cloup import Context
from PIL.Image import Resampling
from manim.typing import Vector3D
__all__ = [
"SCENE_NOT_FOUND_MESSAGE",
"CHOOSE_NUMBER_MESSAGE",
"INVALID_NUMBER_MESSAGE",
"NO_SCENE_MESSAGE",
"NORMAL",
"ITALIC",
"OBLIQUE",
"BOLD",
"THIN",
"ULTRALIGHT",
"LIGHT",
"SEMILIGHT",
"BOOK",
"MEDIUM",
"SEMIBOLD",
"ULTRABOLD",
"HEAVY",
"ULTRAHEAVY",
"RESAMPLING_ALGORITHMS",
"ORIGIN",
"UP",
"DOWN",
"RIGHT",
"LEFT",
"IN",
"OUT",
"X_AXIS",
"Y_AXIS",
"Z_AXIS",
"UL",
"UR",
"DL",
"DR",
"START_X",
"START_Y",
"DEFAULT_DOT_RADIUS",
"DEFAULT_SMALL_DOT_RADIUS",
"DEFAULT_DASH_LENGTH",
"DEFAULT_ARROW_TIP_LENGTH",
"SMALL_BUFF",
"MED_SMALL_BUFF",
"MED_LARGE_BUFF",
"LARGE_BUFF",
"DEFAULT_MOBJECT_TO_EDGE_BUFFER",
"DEFAULT_MOBJECT_TO_MOBJECT_BUFFER",
"DEFAULT_POINTWISE_FUNCTION_RUN_TIME",
"DEFAULT_WAIT_TIME",
"DEFAULT_POINT_DENSITY_2D",
"DEFAULT_POINT_DENSITY_1D",
"DEFAULT_STROKE_WIDTH",
"DEFAULT_FONT_SIZE",
"SCALE_FACTOR_PER_FONT_POINT",
"PI",
"TAU",
"DEGREES",
"QUALITIES",
"DEFAULT_QUALITY",
"EPILOG",
"CONTEXT_SETTINGS",
"SHIFT_VALUE",
"CTRL_VALUE",
"RendererType",
"LineJointType",
"CapStyleType",
]
# Messages
SCENE_NOT_FOUND_MESSAGE = """
{} is not in the script
"""
CHOOSE_NUMBER_MESSAGE = """
Choose number corresponding to desired scene/arguments.
(Use comma separated list for multiple entries)
Choice(s): """
INVALID_NUMBER_MESSAGE = "Invalid scene numbers have been specified. Aborting."
NO_SCENE_MESSAGE = """
There are no scenes inside that module
"""
# Pango stuff
NORMAL = "NORMAL"
ITALIC = "ITALIC"
OBLIQUE = "OBLIQUE"
BOLD = "BOLD"
# Only for Pango from below
THIN = "THIN"
ULTRALIGHT = "ULTRALIGHT"
LIGHT = "LIGHT"
SEMILIGHT = "SEMILIGHT"
BOOK = "BOOK"
MEDIUM = "MEDIUM"
SEMIBOLD = "SEMIBOLD"
ULTRABOLD = "ULTRABOLD"
HEAVY = "HEAVY"
ULTRAHEAVY = "ULTRAHEAVY"
RESAMPLING_ALGORITHMS = {
"nearest": Resampling.NEAREST,
"none": Resampling.NEAREST,
"lanczos": Resampling.LANCZOS,
"antialias": Resampling.LANCZOS,
"bilinear": Resampling.BILINEAR,
"linear": Resampling.BILINEAR,
"bicubic": Resampling.BICUBIC,
"cubic": Resampling.BICUBIC,
"box": Resampling.BOX,
"hamming": Resampling.HAMMING,
}
# Geometry: directions
ORIGIN: Vector3D = np.array((0.0, 0.0, 0.0))
"""The center of the coordinate system."""
UP: Vector3D = np.array((0.0, 1.0, 0.0))
"""One unit step in the positive Y direction."""
DOWN: Vector3D = np.array((0.0, -1.0, 0.0))
"""One unit step in the negative Y direction."""
RIGHT: Vector3D = np.array((1.0, 0.0, 0.0))
"""One unit step in the positive X direction."""
LEFT: Vector3D = np.array((-1.0, 0.0, 0.0))
"""One unit step in the negative X direction."""
IN: Vector3D = np.array((0.0, 0.0, -1.0))
"""One unit step in the negative Z direction."""
OUT: Vector3D = np.array((0.0, 0.0, 1.0))
"""One unit step in the positive Z direction."""
# Geometry: axes
X_AXIS: Vector3D = np.array((1.0, 0.0, 0.0))
Y_AXIS: Vector3D = np.array((0.0, 1.0, 0.0))
Z_AXIS: Vector3D = np.array((0.0, 0.0, 1.0))
# Geometry: useful abbreviations for diagonals
UL: Vector3D = UP + LEFT
"""One step up plus one step left."""
UR: Vector3D = UP + RIGHT
"""One step up plus one step right."""
DL: Vector3D = DOWN + LEFT
"""One step down plus one step left."""
DR: Vector3D = DOWN + RIGHT
"""One step down plus one step right."""
# Geometry
START_X = 30
START_Y = 20
DEFAULT_DOT_RADIUS = 0.08
DEFAULT_SMALL_DOT_RADIUS = 0.04
DEFAULT_DASH_LENGTH = 0.05
DEFAULT_ARROW_TIP_LENGTH = 0.35
# Default buffers (padding)
SMALL_BUFF = 0.1
MED_SMALL_BUFF = 0.25
MED_LARGE_BUFF = 0.5
LARGE_BUFF = 1
DEFAULT_MOBJECT_TO_EDGE_BUFFER = MED_LARGE_BUFF
DEFAULT_MOBJECT_TO_MOBJECT_BUFFER = MED_SMALL_BUFF
# Times in seconds
DEFAULT_POINTWISE_FUNCTION_RUN_TIME = 3.0
DEFAULT_WAIT_TIME = 1.0
# Misc
DEFAULT_POINT_DENSITY_2D = 25
DEFAULT_POINT_DENSITY_1D = 10
DEFAULT_STROKE_WIDTH = 4
DEFAULT_FONT_SIZE = 48
SCALE_FACTOR_PER_FONT_POINT = 1 / 960
# Mathematical constants
PI = np.pi
"""The ratio of the circumference of a circle to its diameter."""
TAU = 2 * PI
"""The ratio of the circumference of a circle to its radius."""
DEGREES = TAU / 360
"""The exchange rate between radians and degrees."""
# Video qualities
QUALITIES: dict[str, dict[str, str | int | None]] = {
"fourk_quality": {
"flag": "k",
"pixel_height": 2160,
"pixel_width": 3840,
"frame_rate": 60,
},
"production_quality": {
"flag": "p",
"pixel_height": 1440,
"pixel_width": 2560,
"frame_rate": 60,
},
"high_quality": {
"flag": "h",
"pixel_height": 1080,
"pixel_width": 1920,
"frame_rate": 60,
},
"medium_quality": {
"flag": "m",
"pixel_height": 720,
"pixel_width": 1280,
"frame_rate": 30,
},
"low_quality": {
"flag": "l",
"pixel_height": 480,
"pixel_width": 854,
"frame_rate": 15,
},
"example_quality": {
"flag": None,
"pixel_height": 480,
"pixel_width": 854,
"frame_rate": 30,
},
}
DEFAULT_QUALITY = "high_quality"
EPILOG = "Made with <3 by Manim Community developers."
SHIFT_VALUE = 65505
CTRL_VALUE = 65507
CONTEXT_SETTINGS = Context.settings(
align_option_groups=True,
align_sections=True,
show_constraints=True,
)
class RendererType(Enum):
"""An enumeration of all renderer types that can be assigned to
the ``config.renderer`` attribute.
Manim's configuration allows assigning string values to the renderer
setting, the values are then replaced by the corresponding enum object.
In other words, you can run::
config.renderer = "opengl"
and checking the renderer afterwards reveals that the attribute has
assumed the value::
<RendererType.OPENGL: 'opengl'>
"""
CAIRO = "cairo" #: A renderer based on the cairo backend.
OPENGL = "opengl" #: An OpenGL-based renderer.
class LineJointType(Enum):
"""Collection of available line joint types.
See the example below for a visual illustration of the different
joint types.
Examples
--------
.. manim:: LineJointVariants
:save_last_frame:
class LineJointVariants(Scene):
def construct(self):
mob = VMobject(stroke_width=20, color=GREEN).set_points_as_corners([
np.array([-2, 0, 0]),
np.array([0, 0, 0]),
np.array([-2, 1, 0]),
])
lines = VGroup(*[mob.copy() for _ in range(len(LineJointType))])
for line, joint_type in zip(lines, LineJointType):
line.joint_type = joint_type
lines.arrange(RIGHT, buff=1)
self.add(lines)
for line in lines:
label = Text(line.joint_type.name).next_to(line, DOWN)
self.add(label)
"""
AUTO = 0
ROUND = 1
BEVEL = 2
MITER = 3
class CapStyleType(Enum):
"""Collection of available cap styles.
See the example below for a visual illustration of the different
cap styles.
Examples
--------
.. manim:: CapStyleVariants
:save_last_frame:
class CapStyleVariants(Scene):
def construct(self):
arcs = VGroup(*[
Arc(
radius=1,
start_angle=0,
angle=TAU / 4,
stroke_width=20,
color=GREEN,
cap_style=cap_style,
)
for cap_style in CapStyleType
])
arcs.arrange(RIGHT, buff=1)
self.add(arcs)
for arc in arcs:
label = Text(arc.cap_style.name, font_size=24).next_to(arc, DOWN)
self.add(label)
"""
AUTO = 0
ROUND = 1
BUTT = 2
SQUARE = 3
|
manim_ManimCommunity/manim/typing.py
|
"""Custom type definitions used in Manim.
.. admonition:: Note for developers
:class: important
Around the source code there are multiple strings which look like this:
.. code-block::
'''
[CATEGORY]
<category_name>
'''
All type aliases defined under those strings will be automatically
classified under that category.
If you need to define a new category, respect the format described above.
"""
from __future__ import annotations
from os import PathLike
from typing import Callable, Union
import numpy as np
import numpy.typing as npt
from typing_extensions import TypeAlias
__all__ = [
"ManimFloat",
"ManimInt",
"ManimColorDType",
"RGB_Array_Float",
"RGB_Tuple_Float",
"RGB_Array_Int",
"RGB_Tuple_Int",
"RGBA_Array_Float",
"RGBA_Tuple_Float",
"RGBA_Array_Int",
"RGBA_Tuple_Int",
"HSV_Array_Float",
"HSV_Tuple_Float",
"ManimColorInternal",
"PointDType",
"InternalPoint2D",
"Point2D",
"InternalPoint2D_Array",
"Point2D_Array",
"InternalPoint3D",
"Point3D",
"InternalPoint3D_Array",
"Point3D_Array",
"Vector2D",
"Vector2D_Array",
"Vector3D",
"Vector3D_Array",
"VectorND",
"VectorND_Array",
"RowVector",
"ColVector",
"MatrixMN",
"Zeros",
"QuadraticBezierPoints",
"QuadraticBezierPoints_Array",
"QuadraticBezierPath",
"QuadraticSpline",
"CubicBezierPoints",
"CubicBezierPoints_Array",
"CubicBezierPath",
"CubicSpline",
"BezierPoints",
"BezierPoints_Array",
"BezierPath",
"Spline",
"FlatBezierPoints",
"FunctionOverride",
"PathFuncType",
"MappingFunction",
"Image",
"GrayscaleImage",
"RGBImage",
"RGBAImage",
"StrPath",
"StrOrBytesPath",
]
"""
[CATEGORY]
Primitive data types
"""
ManimFloat: TypeAlias = np.float64
"""A double-precision floating-point value (64 bits, or 8 bytes),
according to the IEEE 754 standard.
"""
ManimInt: TypeAlias = np.int64
r"""A long integer (64 bits, or 8 bytes).
It can take values between :math:`-2^{63}` and :math:`+2^{63} - 1`,
which expressed in base 10 is a range between around
:math:`-9.223 \cdot 10^{18}` and :math:`+9.223 \cdot 10^{18}`.
"""
"""
[CATEGORY]
Color types
"""
ManimColorDType: TypeAlias = ManimFloat
"""Data type used in :class:`~.ManimColorInternal`: a
double-precision float between 0 and 1.
"""
RGB_Array_Float: TypeAlias = npt.NDArray[ManimColorDType]
"""``shape: (3,)``
A :class:`numpy.ndarray` of 3 floats between 0 and 1, representing a
color in RGB format.
Its components describe, in order, the intensity of Red, Green, and
Blue in the represented color.
"""
RGB_Tuple_Float: TypeAlias = tuple[float, float, float]
"""``shape: (3,)``
A tuple of 3 floats between 0 and 1, representing a color in RGB
format.
Its components describe, in order, the intensity of Red, Green, and
Blue in the represented color.
"""
RGB_Array_Int: TypeAlias = npt.NDArray[ManimInt]
"""``shape: (3,)``
A :class:`numpy.ndarray` of 3 integers between 0 and 255,
representing a color in RGB format.
Its components describe, in order, the intensity of Red, Green, and
Blue in the represented color.
"""
RGB_Tuple_Int: TypeAlias = tuple[int, int, int]
"""``shape: (3,)``
A tuple of 3 integers between 0 and 255, representing a color in RGB
format.
Its components describe, in order, the intensity of Red, Green, and
Blue in the represented color.
"""
RGBA_Array_Float: TypeAlias = npt.NDArray[ManimColorDType]
"""``shape: (4,)``
A :class:`numpy.ndarray` of 4 floats between 0 and 1, representing a
color in RGBA format.
Its components describe, in order, the intensity of Red, Green, Blue
and Alpha (opacity) in the represented color.
"""
RGBA_Tuple_Float: TypeAlias = tuple[float, float, float, float]
"""``shape: (4,)``
A tuple of 4 floats between 0 and 1, representing a color in RGBA
format.
Its components describe, in order, the intensity of Red, Green, Blue
and Alpha (opacity) in the represented color.
"""
RGBA_Array_Int: TypeAlias = npt.NDArray[ManimInt]
"""``shape: (4,)``
A :class:`numpy.ndarray` of 4 integers between 0 and 255,
representing a color in RGBA format.
Its components describe, in order, the intensity of Red, Green, Blue
and Alpha (opacity) in the represented color.
"""
RGBA_Tuple_Int: TypeAlias = tuple[int, int, int, int]
"""``shape: (4,)``
A tuple of 4 integers between 0 and 255, representing a color in RGBA
format.
Its components describe, in order, the intensity of Red, Green, Blue
and Alpha (opacity) in the represented color.
"""
HSV_Array_Float: TypeAlias = RGB_Array_Float
"""``shape: (3,)``
A :class:`numpy.ndarray` of 3 floats between 0 and 1, representing a
color in HSV (or HSB) format.
Its components describe, in order, the Hue, Saturation and Value (or
Brightness) in the represented color.
"""
HSV_Tuple_Float: TypeAlias = RGB_Tuple_Float
"""``shape: (3,)``
A tuple of 3 floats between 0 and 1, representing a color in HSV (or
HSB) format.
Its components describe, in order, the Hue, Saturation and Value (or
Brightness) in the represented color.
"""
ManimColorInternal: TypeAlias = RGBA_Array_Float
"""``shape: (4,)``
Internal color representation used by :class:`~.ManimColor`,
following the RGBA format.
It is a :class:`numpy.ndarray` consisting of 4 floats between 0 and
1, describing respectively the intensities of Red, Green, Blue and
Alpha (opacity) in the represented color.
"""
"""
[CATEGORY]
Point types
"""
PointDType: TypeAlias = ManimFloat
"""Default type for arrays representing points: a double-precision
floating point value.
"""
InternalPoint2D: TypeAlias = npt.NDArray[PointDType]
"""``shape: (2,)``
A 2-dimensional point: ``[float, float]``.
.. note::
This type alias is mostly made available for internal use, and
only includes the NumPy type.
"""
Point2D: TypeAlias = Union[InternalPoint2D, tuple[float, float]]
"""``shape: (2,)``
A 2-dimensional point: ``[float, float]``.
Normally, a function or method which expects a `Point2D` as a
parameter can handle being passed a `Point3D` instead.
"""
InternalPoint2D_Array: TypeAlias = npt.NDArray[PointDType]
"""``shape: (N, 2)``
An array of `InternalPoint2D` objects: ``[[float, float], ...]``.
.. note::
This type alias is mostly made available for internal use, and
only includes the NumPy type.
"""
Point2D_Array: TypeAlias = Union[InternalPoint2D_Array, tuple[Point2D, ...]]
"""``shape: (N, 2)``
An array of `Point2D` objects: ``[[float, float], ...]``.
Normally, a function or method which expects a `Point2D_Array` as a
parameter can handle being passed a `Point3D_Array` instead.
Please refer to the documentation of the function you are using for
further type information.
"""
InternalPoint3D: TypeAlias = npt.NDArray[PointDType]
"""``shape: (3,)``
A 3-dimensional point: ``[float, float, float]``.
.. note::
This type alias is mostly made available for internal use, and
only includes the NumPy type.
"""
Point3D: TypeAlias = Union[InternalPoint3D, tuple[float, float, float]]
"""``shape: (3,)``
A 3-dimensional point: ``[float, float, float]``.
"""
InternalPoint3D_Array: TypeAlias = npt.NDArray[PointDType]
"""``shape: (N, 3)``
An array of `Point3D` objects: ``[[float, float, float], ...]``.
.. note::
This type alias is mostly made available for internal use, and
only includes the NumPy type.
"""
Point3D_Array: TypeAlias = Union[InternalPoint3D_Array, tuple[Point3D, ...]]
"""``shape: (N, 3)``
An array of `Point3D` objects: ``[[float, float, float], ...]``.
Please refer to the documentation of the function you are using for
further type information.
"""
"""
[CATEGORY]
Vector types
"""
Vector2D: TypeAlias = npt.NDArray[PointDType]
"""``shape: (2,)``
A 2-dimensional vector: ``[float, float]``.
Normally, a function or method which expects a `Vector2D` as a
parameter can handle being passed a `Vector3D` instead.
.. caution::
Do not confuse with the :class:`~.Vector` or :class:`~.Arrow`
VMobjects!
"""
Vector2D_Array: TypeAlias = npt.NDArray[PointDType]
"""``shape: (M, 2)``
An array of `Vector2D` objects: ``[[float, float], ...]``.
Normally, a function or method which expects a `Vector2D_Array` as a
parameter can handle being passed a `Vector3D_Array` instead.
"""
Vector3D: TypeAlias = npt.NDArray[PointDType]
"""``shape: (3,)``
A 3-dimensional vector: ``[float, float, float]``.
.. caution::
Do not confuse with the :class:`~.Vector` or :class:`~.Arrow3D`
VMobjects!
"""
Vector3D_Array: TypeAlias = npt.NDArray[PointDType]
"""``shape: (M, 3)``
An array of `Vector3D` objects: ``[[float, float, float], ...]``.
"""
VectorND: TypeAlias = npt.NDArray[PointDType]
"""``shape (N,)``
An :math:`N`-dimensional vector: ``[float, ...]``.
.. caution::
Do not confuse with the :class:`~.Vector` VMobject! This type alias
is named "VectorND" instead of "Vector" to avoid potential name
collisions.
"""
VectorND_Array: TypeAlias = npt.NDArray[PointDType]
"""``shape (M, N)``
An array of `VectorND` objects: ``[[float, ...], ...]``.
"""
RowVector: TypeAlias = npt.NDArray[PointDType]
"""``shape: (1, N)``
A row vector: ``[[float, ...]]``.
"""
ColVector: TypeAlias = npt.NDArray[PointDType]
"""``shape: (N, 1)``
A column vector: ``[[float], [float], ...]``.
"""
"""
[CATEGORY]
Matrix types
"""
MatrixMN: TypeAlias = npt.NDArray[PointDType]
"""``shape: (M, N)``
A matrix: ``[[float, ...], [float, ...], ...]``.
"""
Zeros: TypeAlias = MatrixMN
"""``shape: (M, N)``
A `MatrixMN` filled with zeros, typically created with
``numpy.zeros((M, N))``.
"""
"""
[CATEGORY]
Bézier types
"""
QuadraticBezierPoints: TypeAlias = Union[
npt.NDArray[PointDType], tuple[Point3D, Point3D, Point3D]
]
"""``shape: (3, 3)``
A `Point3D_Array` of 3 control points for a single quadratic Bézier
curve:
``[[float, float, float], [float, float, float], [float, float, float]]``.
"""
QuadraticBezierPoints_Array: TypeAlias = Union[
npt.NDArray[PointDType], tuple[QuadraticBezierPoints, ...]
]
"""``shape: (N, 3, 3)``
An array of :math:`N` `QuadraticBezierPoints` objects:
``[[[float, float, float], [float, float, float], [float, float, float]], ...]``.
"""
QuadraticBezierPath: TypeAlias = Point3D_Array
"""``shape: (3*N, 3)``
A `Point3D_Array` of :math:`3N` points, where each one of the
:math:`N` consecutive blocks of 3 points represents a quadratic
Bézier curve:
``[[float, float, float], ...], ...]``.
Please refer to the documentation of the function you are using for
further type information.
"""
QuadraticSpline: TypeAlias = QuadraticBezierPath
"""``shape: (3*N, 3)``
A special case of `QuadraticBezierPath` where all the :math:`N`
quadratic Bézier curves are connected, forming a quadratic spline:
``[[float, float, float], ...], ...]``.
Please refer to the documentation of the function you are using for
further type information.
"""
CubicBezierPoints: TypeAlias = Union[
npt.NDArray[PointDType], tuple[Point3D, Point3D, Point3D, Point3D]
]
"""``shape: (4, 3)``
A `Point3D_Array` of 4 control points for a single cubic Bézier
curve:
``[[float, float, float], [float, float, float], [float, float, float], [float, float, float]]``.
"""
CubicBezierPoints_Array: TypeAlias = Union[
npt.NDArray[PointDType], tuple[CubicBezierPoints, ...]
]
"""``shape: (N, 4, 3)``
An array of :math:`N` `CubicBezierPoints` objects:
``[[[float, float, float], [float, float, float], [float, float, float], [float, float, float]], ...]``.
"""
CubicBezierPath: TypeAlias = Point3D_Array
"""``shape: (4*N, 3)``
A `Point3D_Array` of :math:`4N` points, where each one of the
:math:`N` consecutive blocks of 4 points represents a cubic Bézier
curve:
``[[float, float, float], ...], ...]``.
Please refer to the documentation of the function you are using for
further type information.
"""
CubicSpline: TypeAlias = CubicBezierPath
"""``shape: (4*N, 3)``
A special case of `CubicBezierPath` where all the :math:`N` cubic
Bézier curves are connected, forming a quadratic spline:
``[[float, float, float], ...], ...]``.
Please refer to the documentation of the function you are using for
further type information.
"""
BezierPoints: TypeAlias = Point3D_Array
r"""``shape: (PPC, 3)``
A `Point3D_Array` of :math:`\text{PPC}` control points
(:math:`\text{PPC: Points Per Curve} = n + 1`) for a single
:math:`n`-th degree Bézier curve:
``[[float, float, float], ...]``.
Please refer to the documentation of the function you are using for
further type information.
"""
BezierPoints_Array: TypeAlias = Union[npt.NDArray[PointDType], tuple[BezierPoints, ...]]
r"""``shape: (N, PPC, 3)``
An array of :math:`N` `BezierPoints` objects containing
:math:`\text{PPC}` `Point3D` objects each
(:math:`\text{PPC: Points Per Curve} = n + 1`):
``[[[float, float, float], ...], ...]``.
Please refer to the documentation of the function you are using for
further type information.
"""
BezierPath: TypeAlias = Point3D_Array
r"""``shape: (PPC*N, 3)``
A `Point3D_Array` of :math:`\text{PPC} \cdot N` points, where each
one of the :math:`N` consecutive blocks of :math:`\text{PPC}` control
points (:math:`\text{PPC: Points Per Curve} = n + 1`) represents a
Bézier curve of :math:`n`-th degree:
``[[float, float, float], ...], ...]``.
Please refer to the documentation of the function you are using for
further type information.
"""
Spline: TypeAlias = BezierPath
r"""``shape: (PPC*N, 3)``
A special case of `BezierPath` where all the :math:`N` Bézier curves
consisting of :math:`\text{PPC}` `Point3D` objects
(:math:`\text{PPC: Points Per Curve} = n + 1`) are connected, forming
an :math:`n`-th degree spline:
``[[float, float, float], ...], ...]``.
Please refer to the documentation of the function you are using for
further type information.
"""
FlatBezierPoints: TypeAlias = Union[npt.NDArray[PointDType], tuple[float, ...]]
"""``shape: (3*PPC*N,)``
A flattened array of Bézier control points:
``[float, ...]``.
"""
"""
[CATEGORY]
Function types
"""
# Due to current limitations
# (see https://github.com/python/mypy/issues/14656 / 8263),
# we don't specify the first argument type (Mobject).
# Nor are we able to specify the return type (Animation) since we cannot import
# that here.
FunctionOverride: TypeAlias = Callable
"""Function type returning an :class:`~.Animation` for the specified
:class:`~.Mobject`.
"""
PathFuncType: TypeAlias = Callable[[Point3D, Point3D, float], Point3D]
"""Function mapping two `Point3D` objects and an alpha value to a new
`Point3D`.
"""
MappingFunction: TypeAlias = Callable[[Point3D], Point3D]
"""A function mapping a `Point3D` to another `Point3D`."""
"""
[CATEGORY]
Image types
"""
Image: TypeAlias = npt.NDArray[ManimInt]
"""``shape: (height, width) | (height, width, 3) | (height, width, 4)``
A rasterized image with a height of ``height`` pixels and a width of
``width`` pixels.
Every value in the array is an integer from 0 to 255.
Every pixel is represented either by a single integer indicating its
lightness (for greyscale images), an `RGB_Array_Int` or an
`RGBA_Array_Int`.
"""
GrayscaleImage: TypeAlias = Image
"""``shape: (height, width)``
A 100% opaque grayscale `Image`, where every pixel value is a
`ManimInt` indicating its lightness (black -> gray -> white).
"""
RGBImage: TypeAlias = Image
"""``shape: (height, width, 3)``
A 100% opaque `Image` in color, where every pixel value is an
`RGB_Array_Int` object.
"""
RGBAImage: TypeAlias = Image
"""``shape: (height, width, 4)``
An `Image` in color where pixels can be transparent. Every pixel
value is an `RGBA_Array_Int` object.
"""
"""
[CATEGORY]
Path types
"""
StrPath: TypeAlias = Union[str, PathLike[str]]
"""A string or :class:`os.PathLike` representing a path to a
directory or file.
"""
StrOrBytesPath: TypeAlias = Union[str, bytes, PathLike[str], PathLike[bytes]]
"""A string, bytes or :class:`os.PathLike` object representing a path
to a directory or file.
"""
|
manim_ManimCommunity/manim/plugins/__init__.py
|
from __future__ import annotations
from manim import config, logger
from .plugins_flags import get_plugins, list_plugins
__all__ = [
"get_plugins",
"list_plugins",
]
requested_plugins: set[str] = set(config["plugins"])
missing_plugins = requested_plugins - set(get_plugins().keys())
if missing_plugins:
logger.warning("Missing Plugins: %s", missing_plugins)
|
manim_ManimCommunity/manim/plugins/plugins_flags.py
|
"""Plugin Managing Utility"""
from __future__ import annotations
import sys
from typing import Any
if sys.version_info < (3, 10):
from importlib_metadata import entry_points
else:
from importlib.metadata import entry_points
from manim import console
__all__ = ["list_plugins"]
def get_plugins() -> dict[str, Any]:
plugins: dict[str, Any] = {
entry_point.name: entry_point.load()
for entry_point in entry_points(group="manim.plugins")
}
return plugins
def list_plugins() -> None:
console.print("[green bold]Plugins:[/green bold]", justify="left")
plugins = get_plugins()
for plugin in plugins:
console.print(f" • {plugin}")
|
manim_ManimCommunity/manim/scene/__init__.py
| |
manim_ManimCommunity/manim/scene/section.py
|
"""building blocks of segmented video API"""
from __future__ import annotations
from enum import Enum
from pathlib import Path
from typing import Any
from manim import get_video_metadata
__all__ = ["Section", "DefaultSectionType"]
class DefaultSectionType(str, Enum):
"""The type of a section can be used for third party applications.
A presentation system could for example use the types to created loops.
Examples
--------
This class can be reimplemented for more types::
class PresentationSectionType(str, Enum):
# start, end, wait for continuation by user
NORMAL = "presentation.normal"
# start, end, immediately continue to next section
SKIP = "presentation.skip"
# start, end, restart, immediately continue to next section when continued by user
LOOP = "presentation.loop"
# start, end, restart, finish animation first when user continues
COMPLETE_LOOP = "presentation.complete_loop"
"""
NORMAL = "default.normal"
class Section:
"""A :class:`.Scene` can be segmented into multiple Sections.
Refer to :doc:`the documentation</tutorials/output_and_config>` for more info.
It consists of multiple animations.
Attributes
----------
type
Can be used by a third party applications to classify different types of sections.
video
Path to video file with animations belonging to section relative to sections directory.
If ``None``, then the section will not be saved.
name
Human readable, non-unique name for this section.
skip_animations
Skip rendering the animations in this section when ``True``.
partial_movie_files
Animations belonging to this section.
See Also
--------
:class:`.DefaultSectionType`
:meth:`.CairoRenderer.update_skipping_status`
:meth:`.OpenGLRenderer.update_skipping_status`
"""
def __init__(self, type: str, video: str | None, name: str, skip_animations: bool):
self.type = type
# None when not to be saved -> still keeps section alive
self.video: str | None = video
self.name = name
self.skip_animations = skip_animations
self.partial_movie_files: list[str | None] = []
def is_empty(self) -> bool:
"""Check whether this section is empty.
Note that animations represented by ``None`` are also counted.
"""
return len(self.partial_movie_files) == 0
def get_clean_partial_movie_files(self) -> list[str]:
"""Return all partial movie files that are not ``None``."""
return [el for el in self.partial_movie_files if el is not None]
def get_dict(self, sections_dir: Path) -> dict[str, Any]:
"""Get dictionary representation with metadata of output video.
The output from this function is used from every section to build the sections index file.
The output video must have been created in the ``sections_dir`` before executing this method.
This is the main part of the Segmented Video API.
"""
if self.video is None:
raise ValueError(
f"Section '{self.name}' cannot be exported as dict, it does not have a video path assigned to it"
)
video_metadata = get_video_metadata(sections_dir / self.video)
return dict(
{
"name": self.name,
"type": self.type,
"video": self.video,
},
**video_metadata,
)
def __repr__(self):
return f"<Section '{self.name}' stored in '{self.video}'>"
|
End of preview. Expand
in Data Studio
README.md exists but content is empty.
- Downloads last month
- 18