Skip to content

armgit / manim

Public Imported from GitHub
0

A community-maintained Python framework for creating mathematical animations.

Migrate from os.path to pathlib in SVGMobject and other locations (#2687)

Jonathan Alperta20f8aeb6ccd
diff --git a/manim/cli/cfg/group.py b/manim/cli/cfg/group.py
index 474de60f9..eea9185e3 100644
--- a/manim/cli/cfg/group.py
+++ b/manim/cli/cfg/group.py
@@ -9,6 +9,7 @@ from __future__ import annotations
import os
from ast import literal_eval
+from pathlib import Path
import click
import cloup
@@ -257,10 +258,11 @@ def show():
@cfg.command(context_settings=cli_ctx_settings)
[email protected]("-d", "--directory", default=os.getcwd())
[email protected]("-d", "--directory", default=Path.cwd())
@click.pass_context
def export(ctx, directory):
- if os.path.abspath(directory) == os.path.abspath(os.getcwd()):
+ directory_path = Path(directory)
+ if directory_path.absolute == Path.cwd().absolute:
console.print(
"""You are reading the config from the same directory you are exporting to.
This means that the exported config will overwrite the config for this directory.
@@ -272,13 +274,14 @@ Are you sure you want to continue? (y/n)""",
else:
proceed = True
if proceed:
- if not os.path.isdir(directory):
+ if not directory_path.is_dir():
console.print(f"Creating folder: {directory}.", style="red bold")
- os.mkdir(directory)
- with open(os.path.join(directory, "manim.cfg"), "w") as outpath:
- ctx.invoke(write)
- from_path = os.path.join(os.getcwd(), "manim.cfg")
- to_path = os.path.join(directory, "manim.cfg")
+ directory_path.mkdir(parents=True)
+
+ ctx.invoke(write)
+ from_path = Path.cwd() / "manim.cfg"
+ to_path = directory_path / "manim.cfg"
+
console.print(f"Exported final Config at {from_path} to {to_path}.")
else:
console.print("Aborted...", style="red bold")
diff --git a/manim/mobject/svg/svg_mobject.py b/manim/mobject/svg/svg_mobject.py
index b5ebd856d..ec838a7a1 100644
--- a/manim/mobject/svg/svg_mobject.py
+++ b/manim/mobject/svg/svg_mobject.py
@@ -9,6 +9,7 @@ import os
import re
import string
import warnings
+from pathlib import Path
from xml.dom.minidom import Element as MinidomElement
from xml.dom.minidom import parse as minidom_parse
@@ -46,7 +47,7 @@ class SVGMobject(VMobject, metaclass=ConvertToOpenGL):
Parameters
--------
- file_name : :class:`str`
+ file_name : :class:`str` or :class:`pathlib.Path`
The file's path name. When possible, the full path is preferred but a
relative path may be used as well. Relative paths are relative to the
directory specified by the `--assets_dir` command line argument.
@@ -87,7 +88,7 @@ class SVGMobject(VMobject, metaclass=ConvertToOpenGL):
):
self.def_map = {}
- self.file_name = file_name or self.file_name
+ self.file_name = Path(file_name)
self._ensure_valid_file()
self.should_center = should_center
self.unpack_groups = unpack_groups
@@ -124,28 +125,28 @@ class SVGMobject(VMobject, metaclass=ConvertToOpenGL):
if self.file_name is None:
raise Exception("Must specify file for SVGMobject")
- if os.path.exists(self.file_name):
+ if self.file_name.exists():
self.file_path = self.file_name
return
- relative = os.path.join(os.getcwd(), self.file_name)
- if os.path.exists(relative):
+ relative = Path.cwd() / self.file_name
+ if relative.exists():
self.file_path = relative
return
possible_paths = [
- os.path.join(config.get_dir("assets_dir"), self.file_name),
- os.path.join(config.get_dir("assets_dir"), self.file_name + ".svg"),
- os.path.join(config.get_dir("assets_dir"), self.file_name + ".xdv"),
- self.file_name,
- self.file_name + ".svg",
- self.file_name + ".xdv",
+ config.get_dir("assets_dir") / self.file_name,
+ config.get_dir("assets_dir") / self.file_name.with_suffix(".svg"),
+ config.get_dir("assets_dir") / self.file_name.with_suffix(".xdv"),
+ self.file_path,
+ self.file_path.with_suffix(".svg"),
+ self.file_path.with_suffix(".xdv"),
]
for path in possible_paths:
- if os.path.exists(path):
+ if path.exists():
self.file_path = path
return
- error = f"From: {os.getcwd()}, could not find {self.file_name} at either of these locations: {possible_paths}"
+ error = f"From: {Path.cwd()}, could not find {self.file_name} at either of these locations: {possible_paths}"
raise OSError(error)
def generate_points(self):
@@ -153,7 +154,7 @@ class SVGMobject(VMobject, metaclass=ConvertToOpenGL):
the SVGMobject's points from XML tags, populating self.mobjects, and
any submobjects within self.mobjects.
"""
- doc = minidom_parse(self.file_path)
+ doc = minidom_parse(str(self.file_path))
for node in doc.childNodes:
if not isinstance(node, MinidomElement) or node.tagName != "svg":
continue
diff --git a/manim/mobject/text/text_mobject.py b/manim/mobject/text/text_mobject.py
index 3b12db559..2ed192ecf 100644
--- a/manim/mobject/text/text_mobject.py
+++ b/manim/mobject/text/text_mobject.py
@@ -752,13 +752,13 @@ class Text(SVGMobject):
line_spacing /= TEXT2SVG_ADJUSTMENT_FACTOR
dir_name = config.get_dir("text_dir")
- if not os.path.exists(dir_name):
- os.makedirs(dir_name)
+ if not dir_name.is_dir():
+ dir_name.mkdir(parents=True)
hash_name = self._text2hash(color)
- file_name = os.path.join(dir_name, hash_name) + ".svg"
+ file_name = dir_name / (hash_name + ".svg")
- if os.path.exists(file_name):
- svg_file = file_name
+ if file_name.exists():
+ svg_file = str(file_name.resolve())
else:
settings = self._text2settings(color)
width = config["pixel_width"]
@@ -769,7 +769,7 @@ class Text(SVGMobject):
size,
line_spacing,
self.disable_ligatures,
- file_name,
+ str(file_name.resolve()),
START_X,
START_Y,
width,
@@ -1245,12 +1245,12 @@ class MarkupText(SVGMobject):
line_spacing /= TEXT2SVG_ADJUSTMENT_FACTOR
dir_name = config.get_dir("text_dir")
- if not os.path.exists(dir_name):
- os.makedirs(dir_name)
+ if not dir_name.exists():
+ dir_name.mkdir(parents=True)
hash_name = self._text2hash(color)
- file_name = os.path.join(dir_name, hash_name) + ".svg"
- if os.path.exists(file_name):
- svg_file = file_name
+ file_name = dir_name / (hash_name + ".svg")
+ if file_name.exists():
+ svg_file = str(file_name.resolve())
else:
final_text = (
f'<span foreground="{color}">{self.text}</span>'
@@ -1266,7 +1266,7 @@ class MarkupText(SVGMobject):
size,
line_spacing,
self.disable_ligatures,
- file_name,
+ str(file_name.resolve()),
START_X,
START_Y,
600, # width
diff --git a/manim/utils/tex_file_writing.py b/manim/utils/tex_file_writing.py
index 8bdb0c3c4..d335691da 100644
--- a/manim/utils/tex_file_writing.py
+++ b/manim/utils/tex_file_writing.py
@@ -79,18 +79,18 @@ def generate_tex_file(expression, environment=None, tex_template=None):
output = tex_template.get_texcode_for_expression(expression)
tex_dir = config.get_dir("tex_dir")
- if not os.path.exists(tex_dir):
- os.makedirs(tex_dir)
+ if not tex_dir.exists():
+ tex_dir.mkdir()
- result = os.path.join(tex_dir, tex_hash(output)) + ".tex"
- if not os.path.exists(result):
+ result = Path(tex_dir) / (tex_hash(output) + ".tex")
+ if not result.exists():
logger.info(
"Writing %(expression)s to %(path)s",
{"expression": expression, "path": f"{result}"},
)
with open(result, "w", encoding="utf-8") as outfile:
outfile.write(output)
- return result
+ return result.as_posix()
def tex_compilation_command(tex_compiler, output_format, tex_file, tex_dir):
@@ -178,7 +178,7 @@ def compile_tex(tex_file, tex_compiler, output_format):
result = Path(result).as_posix()
tex_file = Path(tex_file).as_posix()
tex_dir = Path(config.get_dir("tex_dir")).as_posix()
- if not os.path.exists(result):
+ if not Path(result).exists():
command = tex_compilation_command(
tex_compiler,
output_format,
@@ -215,9 +215,10 @@ def convert_to_svg(dvi_file, extension, page=1):
Path to generated SVG file.
"""
result = dvi_file.replace(extension, ".svg")
- result = Path(result).as_posix()
+ result = Path(result)
+ result_str = result.as_posix()
dvi_file = Path(dvi_file).as_posix()
- if not os.path.exists(result):
+ if not result.exists():
commands = [
"dvisvgm",
"--pdf" if extension == ".pdf" else "",
@@ -225,14 +226,14 @@ def convert_to_svg(dvi_file, extension, page=1):
f'"{dvi_file}"',
"-n",
"-v 0",
- "-o " + f'"{result}"',
+ "-o " + f'"{result_str}"',
">",
os.devnull,
]
os.system(" ".join(commands))
# if the file does not exist now, this means conversion failed
- if not os.path.exists(result):
+ if not result.exists():
raise ValueError(
f"Your installation does not support converting {extension} files to SVG."
f" Consider updating dvisvgm to at least version 2.4."
@@ -240,7 +241,7 @@ def convert_to_svg(dvi_file, extension, page=1):
f" https://docs.manim.community/en/stable/installation/troubleshooting.html",
)
- return result
+ return result_str
def print_all_tex_errors(log_file, tex_compiler, tex_file):