A community-maintained Python framework for creating mathematical animations.
Migrate more `os.path` to `pathlib` (#2980)
NotWearingPants9d1f066d637c
diff --git a/manim/_config/utils.py b/manim/_config/utils.pyindex 3b0dab628..90210b915 100644--- a/manim/_config/utils.py+++ b/manim/_config/utils.py@@ -74,7 +74,9 @@ def config_file_paths() -> list[Path]:return [library_wide, user_wide, folder_wide]-def make_config_parser(custom_file: str = None) -> configparser.ConfigParser:+def make_config_parser(+ custom_file: str | os.PathLike | None = None,+) -> configparser.ConfigParser:"""Make a :class:`ConfigParser` object and load any ``.cfg`` files.The user-wide file, if it exists, overrides the library-wide file. The@@ -85,7 +87,7 @@ def make_config_parser(custom_file: str = None) -> configparser.ConfigParser:Parameters----------- custom_file : :class:`str`+ custom_filePath to a custom config file. If used, the folder-wide file in therelevant directory will be ignored, if it exists. If None, thefolder-wide file will be used, if it exists.@@ -108,10 +110,10 @@ def make_config_parser(custom_file: str = None) -> configparser.ConfigParser:# read_file() before calling read() for any optional files."# https://docs.python.org/3/library/configparser.html#configparser.ConfigParser.readparser = configparser.ConfigParser()- with open(library_wide) as file:+ with library_wide.open() as file:parser.read_file(file) # necessary file- other_files = [user_wide, custom_file if custom_file else folder_wide]+ other_files = [user_wide, Path(custom_file) if custom_file else folder_wide]parser.read(other_files) # optional filesreturn parser@@ -809,7 +811,7 @@ class ManimConfig(MutableMapping):return self- def digest_file(self, filename: str) -> ManimConfig:+ def digest_file(self, filename: str | os.PathLike) -> ManimConfig:"""Process the config options present in a ``.cfg`` file.This method processes a single ``.cfg`` file, whereas@@ -818,7 +820,7 @@ class ManimConfig(MutableMapping):Parameters----------- filename : :class:`str`+ filenamePath to the ``.cfg`` file.Returns@@ -840,11 +842,11 @@ class ManimConfig(MutableMapping):multiple times."""- if not os.path.isfile(filename):+ if not Path(filename).is_file():raise FileNotFoundError(errno.ENOENT,"Error: --config_file could not find a valid config file.",- filename,+ str(filename),)return self.digest_parser(make_config_parser(filename))diff --git a/manim/cli/cfg/group.py b/manim/cli/cfg/group.pyindex eea9185e3..44fdff5ac 100644--- a/manim/cli/cfg/group.py+++ b/manim/cli/cfg/group.py@@ -233,7 +233,7 @@ modify write_cfg_subcmd_input to account for it.""",cfg_file_path = config_paths[2]guarantee_existence(config_paths[2].parents[0])console.print(CWD_CONFIG_MSG)- with open(cfg_file_path, "w") as fp:+ with cfg_file_path.open("w") as fp:parser.write(fp)if openfile:open_file(cfg_file_path)diff --git a/manim/cli/init/commands.py b/manim/cli/init/commands.pyindex 8124e687f..ef4a20188 100644--- a/manim/cli/init/commands.py+++ b/manim/cli/init/commands.py@@ -74,7 +74,7 @@ def update_cfg(cfg_dict, project_cfg_path):else:cli_config[key] = str(value)- with open(project_cfg_path, "w") as conf:+ with project_cfg_path.open("w") as conf:config.write(conf)@@ -154,32 +154,28 @@ def scene(**args):type=click.Choice(get_template_names(), False),default="Default",)- scene = ""- with open(Path.resolve(get_template_path() / f"{template_name}.mtp")) as f:- scene = f.read()- scene = scene.replace(template_name + "Template", args["scene_name"], 1)+ scene = (get_template_path() / f"{template_name}.mtp").resolve().read_text()+ scene = scene.replace(template_name + "Template", args["scene_name"], 1)if args["file_name"]:- if args["file_name"][-3:] == ".py":- file_name = args["file_name"]- else:- file_name = args["file_name"] + ".py"+ file_name = Path(args["file_name"])++ if file_name.suffix != ".py":+ file_name = file_name.with_suffix(file_name.suffix + ".py")- file_name = Path(file_name)if file_name.is_file():# file exists so we are going to append new scene to that file- with open(file_name, "a") as f:+ with file_name.open("a") as f:f.write("\n\n\n" + scene)else:# file does not exist so we create a new file, append the scene and prepend the import statement- with open(file_name, "w") as f:- f.write("\n\n\n" + scene)+ file_name.write_text("\n\n\n" + scene)add_import_statement(file_name)else:# file name is not provided so we assume it is main.py# if main.py does not exist we do not continue- with open(Path("main.py"), "a") as f:+ with Path("main.py").open("a") as f:f.write("\n\n\n" + scene)diff --git a/manim/cli/new/group.py b/manim/cli/new/group.pyindex 32fde0dfe..840698261 100644--- a/manim/cli/new/group.py+++ b/manim/cli/new/group.py@@ -67,7 +67,7 @@ def update_cfg(cfg_dict, project_cfg_path):else:cli_config[key] = str(value)- with open(project_cfg_path, "w") as conf:+ with project_cfg_path.open("w") as conf:config.write(conf)@@ -150,28 +150,25 @@ def scene(**args):type=click.Choice(get_template_names(), False),default="Default",)- scene = ""- with open(Path.resolve(get_template_path() / f"{template_name}.mtp")) as f:- scene = f.read()- scene = scene.replace(template_name + "Template", args["scene_name"], 1)+ scene = (get_template_path() / f"{template_name}.mtp").resolve().read_text()+ scene = scene.replace(template_name + "Template", args["scene_name"], 1)if args["file_name"]:file_name = Path(args["file_name"] + ".py")if file_name.is_file():# file exists so we are going to append new scene to that file- with open(file_name, "a") as f:+ with file_name.open("a") as f:f.write("\n\n\n" + scene)else:# file does not exist so we create a new file, append the scene and prepend the import statement- with open(file_name, "w") as f:- f.write("\n\n\n" + scene)+ file_name.write_text("\n\n\n" + scene)add_import_statement(file_name)else:# file name is not provided so we assume it is main.py# if main.py does not exist we do not continue- with open(Path("main.py"), "a") as f:+ with Path("main.py").open("a") as f:f.write("\n\n\n" + scene)diff --git a/manim/mobject/svg/svg_mobject.py b/manim/mobject/svg/svg_mobject.pyindex 077ccaa48..e92f1baa4 100644--- a/manim/mobject/svg/svg_mobject.py+++ b/manim/mobject/svg/svg_mobject.py@@ -3,6 +3,7 @@from __future__ import annotationsimport os+from pathlib import Pathfrom xml.etree import ElementTree as ETimport numpy as np@@ -86,7 +87,7 @@ class SVGMobject(VMobject, metaclass=ConvertToOpenGL):def __init__(self,- file_name: str | None = None,+ file_name: str | os.PathLike | None = None,should_center: bool = True,height: float | None = 2,width: float | None = None,@@ -104,7 +105,7 @@ class SVGMobject(VMobject, metaclass=ConvertToOpenGL):super().__init__(color=None, stroke_color=None, fill_color=None, **kwargs)# process keyword arguments- self.file_name = file_name+ self.file_name = Path(file_name) if file_name is not None else Noneself.should_center = should_centerself.svg_height = height@@ -182,18 +183,17 @@ class SVGMobject(VMobject, metaclass=ConvertToOpenGL):element_tree = ET.parse(file_path)new_tree = self.modify_xml_tree(element_tree)# Create a temporary svg file to dump modified svg to be parsed- root, ext = os.path.splitext(file_path)- modified_file_path = root + "_" + ext+ modified_file_path = file_path.with_name(f"{file_path.stem}_{file_path.suffix}")new_tree.write(modified_file_path)svg = se.SVG.parse(modified_file_path)- os.remove(modified_file_path)+ modified_file_path.unlink()mobjects = self.get_mobjects_from(svg)self.add(*mobjects)self.flip(RIGHT) # Flip y- def get_file_path(self) -> str:+ def get_file_path(self) -> Path:"""Search for an existing file based on the specified file name."""if self.file_name is None:raise ValueError("Must specify file for SVGMobject")diff --git a/manim/mobject/text/code_mobject.py b/manim/mobject/text/code_mobject.pyindex 229274be0..fcb42150c 100644--- a/manim/mobject/text/code_mobject.py+++ b/manim/mobject/text/code_mobject.py@@ -7,8 +7,8 @@ __all__ = []import html-import osimport re+from pathlib import Pathimport numpy as npfrom pygments import highlight@@ -88,7 +88,7 @@ class Code(VGroup):Parameters----------- file_name : :class:`str`+ file_nameName of the code file to display.code : :class:`str`If ``file_name`` is not specified, a code string can be@@ -153,7 +153,7 @@ class Code(VGroup):def __init__(self,- file_name=None,+ file_name: str | os.PathLike = None,code=None,tab_width=3,line_spacing=0.3,@@ -199,8 +199,7 @@ class Code(VGroup):self.file_name = file_nameif self.file_name:self._ensure_valid_file()- with open(self.file_path, encoding="utf-8") as f:- self.code_string = f.read()+ self.code_string = self.file_path.read_text(encoding="utf-8")elif code:self.code_string = codeelse:@@ -284,16 +283,16 @@ class Code(VGroup):if self.file_name is None:raise Exception("Must specify file for Code")possible_paths = [- os.path.join(os.path.join("assets", "codes"), self.file_name),- os.path.expanduser(self.file_name),+ Path() / "assets" / "codes" / self.file_name,+ Path(self.file_name).expanduser(),]for path in possible_paths:- if os.path.exists(path):+ if path.exists():self.file_path = pathreturnerror = (- f"From: {os.getcwd()}, could not find {self.file_name} at either "- + f"of these locations: {possible_paths}"+ f"From: {Path.cwd()}, could not find {self.file_name} at either "+ + f"of these locations: {list(map(str, possible_paths))}")raise OSError(error)@@ -369,20 +368,9 @@ class Code(VGroup):)if self.generate_html_file:- os.makedirs(- os.path.join("assets", "codes", "generated_html_files"),- exist_ok=True,- )- with open(- os.path.join(- "assets",- "codes",- "generated_html_files",- self.file_name + ".html",- ),- "w",- ) as file:- file.write(self.html_string)+ output_folder = Path() / "assets" / "codes" / "generated_html_files"+ output_folder.mkdir(parents=True, exist_ok=True)+ (output_folder / f"{self.file_name}.html").write_text(self.html_string)def _gen_code_json(self):"""Function to background_color, generate code_json and tab_spaces from html_string.@@ -559,7 +547,7 @@ def _hilite_me(Defines whether line numbers should be inserted in the html file.divstyles : :class:`str`Some html css styles.- file_path : :class:`str`+ file_path : :class:`pathlib.Path`Path of code file.line_no_from : :class:`int`Defines the first line's number in the line count.diff --git a/manim/renderer/shader.py b/manim/renderer/shader.pyindex ce40a701f..d1bba2750 100644--- a/manim/renderer/shader.py+++ b/manim/renderer/shader.py@@ -1,6 +1,5 @@from __future__ import annotations-import osimport reimport textwrapfrom pathlib import Path@@ -24,24 +23,23 @@ __all__ = []-def get_shader_code_from_file(file_path):+def get_shader_code_from_file(file_path: Path) -> str:if file_path in file_path_to_code_map:return file_path_to_code_map[file_path]- with open(file_path) as f:- source = f.read()- include_lines = re.finditer(- r"^#include (?P<include_path>.*\.glsl)$",- source,- flags=re.MULTILINE,+ source = file_path.read_text()+ include_lines = re.finditer(+ r"^#include (?P<include_path>.*\.glsl)$",+ source,+ flags=re.MULTILINE,+ )+ for match in include_lines:+ include_path = match.group("include_path")+ included_code = get_shader_code_from_file(+ file_path.parent / include_path,)- for match in include_lines:- include_path = match.group("include_path")- included_code = get_shader_code_from_file(- os.path.join(file_path.parent / include_path),- )- source = source.replace(match.group(0), included_code)- file_path_to_code_map[file_path] = source- return source+ source = source.replace(match.group(0), included_code)+ file_path_to_code_map[file_path] = source+ return sourcedef filter_attributes(unfiltered_attributes, attributes):diff --git a/manim/renderer/shader_wrapper.py b/manim/renderer/shader_wrapper.pyindex 9fe87f3c5..8eff1772c 100644--- a/manim/renderer/shader_wrapper.py+++ b/manim/renderer/shader_wrapper.py@@ -1,7 +1,6 @@from __future__ import annotationsimport copy-import osimport refrom pathlib import Path@@ -21,13 +20,13 @@ def get_shader_dir():return Path(__file__).parent / "shaders"-def find_file(file_name, directories=None):+def find_file(file_name: Path, directories: list[Path]) -> Path:# Check if what was passed in is already a valid path to a file- if os.path.exists(file_name):+ if file_name.exists():return file_name- possible_paths = (os.path.join(directory, file_name) for directory in directories)+ possible_paths = (directory / file_name for directory in directories)for path in possible_paths:- if os.path.exists(path):+ if path.exists():return pathelse:logger.debug(f"{path} does not exist.")@@ -48,7 +47,7 @@ class ShaderWrapper:self.vert_data = vert_dataself.vert_indices = vert_indicesself.vert_attributes = vert_data.dtype.names- self.shader_folder = shader_folder+ self.shader_folder = Path(shader_folder or "")self.uniforms = uniforms or {}self.texture_paths = texture_paths or {}self.depth_test = depth_test@@ -110,9 +109,9 @@ class ShaderWrapper:)def init_program_code(self):- def get_code(name):+ def get_code(name: str) -> str | None:return get_shader_code_from_file(- os.path.join(self.shader_folder, f"{name}.glsl"),+ self.shader_folder / f"{name}.glsl",)self.program_code = {@@ -157,22 +156,19 @@ class ShaderWrapper:filename_to_code_map: dict = {}-def get_shader_code_from_file(filename):- if not filename:- return None+def get_shader_code_from_file(filename: Path) -> str | None:if filename in filename_to_code_map:return filename_to_code_map[filename]try:filepath = find_file(filename,- directories=[get_shader_dir(), "/"],+ directories=[get_shader_dir(), Path("/")],)except OSError:return None- with open(filepath) as f:- result = f.read()+ result = filepath.read_text()# To share functionality between shaders, some functions are read in# from other files an inserted into the relevant strings before@@ -185,8 +181,10 @@ def get_shader_code_from_file(filename):)for line in insertions:inserted_code = get_shader_code_from_file(- os.path.join("include", line.replace("#include ../include/", "")),+ Path() / "include" / line.replace("#include ../include/", ""),)+ if inserted_code is None:+ return Noneresult = result.replace(line, inserted_code)filename_to_code_map[filename] = resultreturn resultdiff --git a/manim/scene/scene_file_writer.py b/manim/scene/scene_file_writer.pyindex 25763268d..48131c751 100644--- a/manim/scene/scene_file_writer.py+++ b/manim/scene/scene_file_writer.py@@ -50,7 +50,7 @@ class SceneFileWriter:sections : list of :class:`.Section`used to segment scene- sections_output_dir : str+ sections_output_dir : :class:`pathlib.Path`where are section videos storedoutput_name : str@@ -136,7 +136,7 @@ class SceneFileWriter:)# TODO: /dev/null would be good in case sections_output_dir is used without bein set (doesn't work on Windows), everyone likes defensive programming, right?- self.sections_output_dir = ""+ self.sections_output_dir = Path("")if config.save_sections:self.sections_output_dir = guarantee_existence(config.get_dir(@@ -540,21 +540,19 @@ class SceneFileWriter:def combine_files(self,input_files: list[str],- output_file: Path | str,+ output_file: Path,create_gif=False,includes_sound=False,):- file_list = str(self.partial_movie_directory / "partial_movie_file_list.txt")+ file_list = self.partial_movie_directory / "partial_movie_file_list.txt"logger.debug(f"Partial movie files to combine ({len(input_files)} files): %(p)s",{"p": input_files[:5]},)- with open(file_list, "w", encoding="utf-8") as fp:+ with file_list.open("w", encoding="utf-8") as fp:fp.write("# This file is used internally by FFMPEG.\n")for pf_path in input_files:- pf_path = str(pf_path)- if os.name == "nt":- pf_path = pf_path.replace("\\", "/")+ pf_path = Path(pf_path).as_posix()fp.write(f"file 'file:{pf_path}'\n")commands = [config.ffmpeg_executable,@@ -564,7 +562,7 @@ class SceneFileWriter:"-safe","0","-i",- file_list,+ str(file_list),"-loglevel",config.ffmpeg_loglevel.lower(),"-metadata",@@ -603,7 +601,6 @@ class SceneFileWriter:movie_file_path = self.movie_file_pathif is_gif_format():movie_file_path = self.gif_file_path- movie_file_path = str(movie_file_path)logger.info("Combining to Movie file.")self.combine_files(partial_movie_files,@@ -614,21 +611,22 @@ class SceneFileWriter:# handle soundif self.includes_sound:- extension = config["movie_file_extension"]- sound_file_path = movie_file_path.replace(extension, ".wav")+ sound_file_path = movie_file_path.with_suffix(".wav")# Makes sure sound file length will match video fileself.add_audio_segment(AudioSegment.silent(0))self.audio_segment.export(sound_file_path,bitrate="312k",)- temp_file_path = movie_file_path.replace(extension, f"_temp{extension}")+ temp_file_path = movie_file_path.with_name(+ f"{movie_file_path.stem}_temp{movie_file_path.suffix}"+ )commands = [config.ffmpeg_executable,"-i",- movie_file_path,+ str(movie_file_path),"-i",- sound_file_path,+ str(sound_file_path),"-y", # overwrite output file if it exists"-c:v","copy",@@ -647,13 +645,13 @@ class SceneFileWriter:"-metadata",f"comment=Rendered with Manim Community v{__version__}",# "-shortest",- temp_file_path,+ str(temp_file_path),]subprocess.call(commands)- shutil.move(temp_file_path, movie_file_path)- os.remove(sound_file_path)+ shutil.move(str(temp_file_path), str(movie_file_path))+ sound_file_path.unlink()- self.print_file_ready_message(movie_file_path)+ self.print_file_ready_message(str(movie_file_path))if write_to_movie():for file_path in partial_movie_files:# We have to modify the accessed time so if we have to clean the cache we remove the one used the longest.@@ -670,12 +668,10 @@ class SceneFileWriter:logger.info(f"Combining partial files for section '{section.name}'")self.combine_files(section.get_clean_partial_movie_files(),- os.path.join(self.sections_output_dir, section.video),+ self.sections_output_dir / section.video,)sections_index.append(section.get_dict(self.sections_output_dir))- with open(- os.path.join(self.sections_output_dir, f"{self.output_name}.json"), "w"- ) as file:+ with (self.sections_output_dir / f"{self.output_name}.json").open("w") as file:json.dump(sections_index, file, indent=4)def clean_cache(self):@@ -718,8 +714,7 @@ class SceneFileWriter:def write_subcaption_file(self):"""Writes the subcaption file."""subcaption_file = Path(config.output_file).with_suffix(".srt")- with open(subcaption_file, "w") as f:- f.write(srt.compose(self.subcaptions))+ subcaption_file.write_text(srt.compose(self.subcaptions))logger.info(f"Subcaption file has been written as {subcaption_file}")def print_file_ready_message(self, file_path):diff --git a/manim/scene/section.py b/manim/scene/section.pyindex 772035361..860a969ad 100644--- a/manim/scene/section.py+++ b/manim/scene/section.py@@ -2,8 +2,8 @@from __future__ import annotations-import osfrom enum import Enum+from pathlib import Pathfrom typing import Anyfrom manim import get_video_metadata@@ -76,7 +76,7 @@ class Section:"""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: str) -> dict[str, Any]:+ 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.@@ -88,7 +88,7 @@ class Section:f"Section '{self.name}' cannot be exported as dict, it does not have a video path assigned to it")- video_metadata = get_video_metadata(os.path.join(sections_dir, self.video))+ video_metadata = get_video_metadata(sections_dir / self.video)return dict({"name": self.name,diff --git a/manim/utils/docbuild/manim_directive.py b/manim/utils/docbuild/manim_directive.pyindex d7fa8a6eb..fe43764ed 100644--- a/manim/utils/docbuild/manim_directive.py+++ b/manim/utils/docbuild/manim_directive.py@@ -321,7 +321,7 @@ rendering_times_file_path = Path("../rendering_times.csv")def _write_rendering_stats(scene_name, run_time, file_name):- with open(rendering_times_file_path, "a") as file:+ with rendering_times_file_path.open("a") as file:csv.writer(file).writerow([re.sub(r"^(reference\/)|(manim\.)", "", file_name),@@ -333,33 +333,33 @@ def _write_rendering_stats(scene_name, run_time, file_name):def _log_rendering_times(*args):if rendering_times_file_path.exists():- with open(rendering_times_file_path) as file:+ with rendering_times_file_path.open() as file:data = list(csv.reader(file))- if len(data) == 0:- sys.exit()-- print("\nRendering Summary\n-----------------\n")-- max_file_length = max(len(row[0]) for row in data)- for key, group in it.groupby(data, key=lambda row: row[0]):- key = key.ljust(max_file_length + 1, ".")- group = list(group)- if len(group) == 1:- row = group[0]- print(f"{key}{row[2].rjust(7, '.')}s {row[1]}")- continue- time_sum = sum(float(row[2]) for row in group)- print(- f"{key}{f'{time_sum:.3f}'.rjust(7, '.')}s => {len(group)} EXAMPLES",- )- for row in group:- print(f"{' '*(max_file_length)} {row[2].rjust(7)}s {row[1]}")+ if len(data) == 0:+ sys.exit()++ print("\nRendering Summary\n-----------------\n")++ max_file_length = max(len(row[0]) for row in data)+ for key, group in it.groupby(data, key=lambda row: row[0]):+ key = key.ljust(max_file_length + 1, ".")+ group = list(group)+ if len(group) == 1:+ row = group[0]+ print(f"{key}{row[2].rjust(7, '.')}s {row[1]}")+ continue+ time_sum = sum(float(row[2]) for row in group)+ print(+ f"{key}{f'{time_sum:.3f}'.rjust(7, '.')}s => {len(group)} EXAMPLES",+ )+ for row in group:+ print(f"{' '*(max_file_length)} {row[2].rjust(7)}s {row[1]}")print("")def _delete_rendering_times(*args):if rendering_times_file_path.exists():- os.remove(rendering_times_file_path)+ rendering_times_file_path.unlink()def setup(app):diff --git a/manim/utils/file_ops.py b/manim/utils/file_ops.pyindex 3cddd1559..6a5a7f1f7 100644--- a/manim/utils/file_ops.py+++ b/manim/utils/file_ops.py@@ -134,15 +134,15 @@ def ensure_executable(path_to_exe: Path) -> bool:def add_extension_if_not_present(file_name: Path, extension: str) -> Path:if file_name.suffix != extension:- return file_name.with_suffix(extension)+ return file_name.with_suffix(file_name.suffix + extension)else:return file_namedef add_version_before_extension(file_name: Path) -> Path:- file_name = Path(file_name)- path, name, suffix = file_name.parent, file_name.stem, file_name.suffix- return Path(path, f"{name}_ManimCE_v{__version__}{suffix}")+ return file_name.with_name(+ f"{file_name.stem}_ManimCE_v{__version__}{file_name.suffix}"+ )def guarantee_existence(path: Path) -> Path:@@ -168,7 +168,10 @@ def seek_full_path_from_defaults(for path in possible_paths:if path.exists():return path- error = f"From: {os.getcwd()}, could not find {file_name} at either of these locations: {possible_paths}"+ error = (+ f"From: {Path.cwd()}, could not find {file_name} at either "+ f"of these locations: {list(map(str, possible_paths))}"+ )raise OSError(error)@@ -252,11 +255,11 @@ def add_import_statement(file):----------file : :class:`Path`"""- with open(file, "r+") as f:+ with file.open("r+") as f:import_line = "from manim import *"content = f.read()- f.seek(0, 0)- f.write(import_line.rstrip("\r\n") + "\n" + content)+ f.seek(0)+ f.write(import_line + "\n" + content)def copy_template_files(diff --git a/manim/utils/images.py b/manim/utils/images.pyindex 0731496dd..1ce3dd8c2 100644--- a/manim/utils/images.py+++ b/manim/utils/images.py@@ -9,6 +9,8 @@ __all__ = ["change_to_rgba_array",]+from pathlib import Path+import numpy as npfrom PIL import Image@@ -16,7 +18,7 @@ from .. import configfrom ..utils.file_ops import seek_full_path_from_defaults-def get_full_raster_image_path(image_file_name: str) -> str:+def get_full_raster_image_path(image_file_name: str) -> Path:return seek_full_path_from_defaults(image_file_name,default_dir=config.get_dir("assets_dir"),@@ -24,7 +26,7 @@ def get_full_raster_image_path(image_file_name: str) -> str:)-def get_full_vector_image_path(image_file_name: str):+def get_full_vector_image_path(image_file_name: str) -> Path:return seek_full_path_from_defaults(image_file_name,default_dir=config.get_dir("assets_dir"),diff --git a/manim/utils/ipython_magic.py b/manim/utils/ipython_magic.pyindex f41a3fb13..1e4fef9d9 100644--- a/manim/utils/ipython_magic.py+++ b/manim/utils/ipython_magic.py@@ -171,7 +171,7 @@ else:if local_path in self.rendered_files:self.rendered_files[local_path].unlink()self.rendered_files[local_path] = tmpfile- os.makedirs(tmpfile.parent, exist_ok=True)+ tmpfile.parent.mkdir(parents=True, exist_ok=True)shutil.copy(local_path, tmpfile)file_type = mimetypes.guess_type(config["output_file"])[0]diff --git a/manim/utils/module_ops.py b/manim/utils/module_ops.pyindex 60871cf42..ec588c0ef 100644--- a/manim/utils/module_ops.py+++ b/manim/utils/module_ops.py@@ -33,11 +33,11 @@ def get_module(file_name: Path):logger.error(f"Failed to render scene: {str(e)}")sys.exit(2)else:- if Path(file_name).exists():+ if file_name.exists():ext = file_name.suffixif ext != ".py":raise ValueError(f"{file_name} is not a valid Manim python script.")- module_name = ext.replace(os.sep, ".").split(".")[-1]+ module_name = ".".join(file_name.with_suffix("").parts)warnings.filterwarnings("default",@@ -123,7 +123,9 @@ def prompt_user_for_choice(scene_classes):sys.exit(1)-def scene_classes_from_file(file_path, require_single_scene=False, full_list=False):+def scene_classes_from_file(+ file_path: Path, require_single_scene=False, full_list=False+):module = get_module(file_path)all_scene_classes = get_scene_classes_from_module(module)if full_list:diff --git a/manim/utils/tex.py b/manim/utils/tex.pyindex a30533123..6e881ecfa 100644--- a/manim/utils/tex.py+++ b/manim/utils/tex.py@@ -8,7 +8,9 @@ __all__ = []import copy+import osimport re+from pathlib import Pathclass TexTemplate:@@ -246,7 +248,7 @@ class TexTemplateFromFile(TexTemplate):Other Parameters----------------- tex_filename : Optional[:class:`str`], optional+ tex_filenamePath to a valid TeX template fileAttributes@@ -261,13 +263,14 @@ class TexTemplateFromFile(TexTemplate):The output format resulting from compilation, e.g. ``.dvi`` or ``.pdf``"""- def __init__(self, **kwargs):- self.template_file = kwargs.pop("tex_filename", "tex_template.tex")+ def __init__(+ self, *, tex_filename: str | os.PathLike = "tex_template.tex", **kwargs+ ):+ self.template_file = Path(tex_filename)super().__init__(**kwargs)def _rebuild(self):- with open(self.template_file) as infile:- self.body = infile.read()+ self.body = self.template_file.read_text()def file_not_mutable(self):raise Exception("Cannot modify TexTemplate when using a template file.")diff --git a/manim/utils/tex_file_writing.py b/manim/utils/tex_file_writing.pyindex d90b8af0e..d53acbe0a 100644--- a/manim/utils/tex_file_writing.py+++ b/manim/utils/tex_file_writing.py@@ -39,7 +39,7 @@ def tex_to_svg_file(expression, environment=None, tex_template=None):Returns-------- :class:`str`+ :class:`Path`Path to generated SVG file."""if tex_template is None:@@ -68,7 +68,7 @@ def generate_tex_file(expression, environment=None, tex_template=None):Returns-------- :class:`str`+ :class:`Path`Path to generated TeX file"""if tex_template is None:@@ -82,29 +82,30 @@ def generate_tex_file(expression, environment=None, tex_template=None):if not tex_dir.exists():tex_dir.mkdir()- result = Path(tex_dir) / (tex_hash(output) + ".tex")+ result = 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.as_posix()+ result.write_text(output, encoding="utf-8")+ return result-def tex_compilation_command(tex_compiler, output_format, tex_file, tex_dir):+def tex_compilation_command(+ tex_compiler: str, output_format: str, tex_file: Path, tex_dir: Path+) -> str:"""Prepares the tex compilation command with all necessary cli flagsParameters----------- tex_compiler : :class:`str`+ tex_compilerString containing the compiler to be used, e.g. ``pdflatex`` or ``lualatex``- output_format : :class:`str`+ output_formatString containing the output format generated by the compiler, e.g. ``.dvi`` or ``.pdf``- tex_file : :class:`str`+ tex_fileFile name of TeX file to be typeset.- tex_dir : :class:`str`+ tex_dirPath to the directory where compiler output will be stored.Returns@@ -157,28 +158,26 @@ def insight_package_not_found_error(matching):yield f"Install {matching[1]} it using your LaTeX package manager, or check for typos."-def compile_tex(tex_file, tex_compiler, output_format):+def compile_tex(tex_file: Path, tex_compiler: str, output_format: str) -> Path:"""Compiles a tex_file into a .dvi or a .xdv or a .pdfParameters----------- tex_file : :class:`str`+ tex_fileFile name of TeX file to be typeset.- tex_compiler : :class:`str`+ tex_compilerString containing the compiler to be used, e.g. ``pdflatex`` or ``lualatex``- output_format : :class:`str`+ output_formatString containing the output format generated by the compiler, e.g. ``.dvi`` or ``.pdf``Returns-------- :class:`str`+ :class:`Path`Path to generated output file in desired format (DVI, XDV or PDF)."""- result = tex_file.replace(".tex", 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 Path(result).exists():+ result = tex_file.with_suffix(output_format)+ tex_dir = config.get_dir("tex_dir")+ if not result.exists():command = tex_compilation_command(tex_compiler,output_format,@@ -187,7 +186,7 @@ def compile_tex(tex_file, tex_compiler, output_format):)exit_code = os.system(command)if exit_code != 0:- log_file = tex_file.replace(".tex", ".log")+ log_file = tex_file.with_suffix(".log")print_all_tex_errors(log_file, tex_compiler, tex_file)raise ValueError(f"{tex_compiler} error converting to"@@ -202,7 +201,7 @@ def convert_to_svg(dvi_file, extension, page=1):Parameters----------- dvi_file : :class:`str`+ dvi_file : :class:`Path`File name of the input file to be converted.extension : :class:`str`String containing the file extension and thus indicating the file type, e.g. ``.dvi`` or ``.pdf``@@ -211,13 +210,10 @@ def convert_to_svg(dvi_file, extension, page=1):Returns-------- :class:`str`+ :class:`Path`Path to generated SVG file."""- result = dvi_file.replace(extension, ".svg")- result = Path(result)- result_str = result.as_posix()- dvi_file = Path(dvi_file).as_posix()+ result = dvi_file.with_suffix(".svg")if not result.exists():commands = ["dvisvgm",@@ -226,7 +222,7 @@ def convert_to_svg(dvi_file, extension, page=1):f'"{dvi_file}"',"-n","-v 0",- "-o " + f'"{result_str}"',+ "-o " + f'"{result}"',">",os.devnull,]@@ -235,33 +231,31 @@ def convert_to_svg(dvi_file, extension, page=1):# if the file does not exist now, this means conversion failedif not result.exists():raise ValueError(- f"Your installation does not support converting {extension} files to SVG."+ f"Your installation does not support converting {dvi_file.suffix} files to SVG."f" Consider updating dvisvgm to at least version 2.4."f" If this does not solve the problem, please refer to our troubleshooting guide at:"f" https://docs.manim.community/en/stable/installation/troubleshooting.html",)- return result_str+ return result-def print_all_tex_errors(log_file, tex_compiler, tex_file):- if not Path(log_file).exists():+def print_all_tex_errors(log_file: Path, tex_compiler: str, tex_file: Path) -> None:+ if not log_file.exists():raise RuntimeError(f"{tex_compiler} failed but did not produce a log file. ""Check your LaTeX installation.",)- with open(log_file, encoding="utf-8") as f:+ with log_file.open(encoding="utf-8") as f:tex_compilation_log = f.readlines()- error_indices = [- index- for index, line in enumerate(tex_compilation_log)- if line.startswith("!")- ]- if error_indices:- with open(tex_file) as g:- tex = g.readlines()- for error_index in error_indices:- print_tex_error(tex_compilation_log, error_index, tex)+ error_indices = [+ index for index, line in enumerate(tex_compilation_log) if line.startswith("!")+ ]+ if error_indices:+ with tex_file.open() as f:+ tex = f.readlines()+ for error_index in error_indices:+ print_tex_error(tex_compilation_log, error_index, tex)LATEX_ERROR_INSIGHTS = [diff --git a/scripts/dev_changelog.py b/scripts/dev_changelog.pyindex d5ecdd339..f84dbb1ca 100755--- a/scripts/dev_changelog.py+++ b/scripts/dev_changelog.py@@ -47,7 +47,6 @@ from __future__ import annotationsimport concurrent.futuresimport datetime-import osimport refrom collections import defaultdictfrom pathlib import Path@@ -85,17 +84,13 @@ SILENT_CONTRIBUTORS = [def update_citation(version, date):- current_directory = os.path.dirname(__file__)- parent_directory = os.path.split(current_directory)[0]- with open(os.path.join(current_directory, "TEMPLATE.cff")) as a, open(- os.path.join(parent_directory, "CITATION.cff"),- "w",- newline="\n",- ) as b:- contents = a.read()- contents = contents.replace("<version>", version)- contents = contents.replace("<date_released>", date)- b.write(contents)+ 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):diff --git a/scripts/extract_frames.py b/scripts/extract_frames.pyindex 8771bd391..7bebbb4b5 100644--- a/scripts/extract_frames.py+++ b/scripts/extract_frames.py@@ -1,4 +1,3 @@-import osimport sysimport numpy as np@@ -10,9 +9,9 @@ def main():print_usage()sys.exit(1)npz_file = sys.argv[1]- output_folder = sys.argv[2]- if not os.path.exists(output_folder):- os.makedirs(output_folder)+ output_folder = 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:@@ -22,7 +21,7 @@ def main():frames = data["frame_data"]for i, frame in enumerate(frames):img = Image.fromarray(frame)- img.save(os.path.join(output_folder, f"frame{i}.png"))+ img.save(output_folder / f"frame{i}.png")print(f"Saved {len(frames)} frames to {output_folder}")diff --git a/tests/test_scene_rendering/opengl/test_cli_flags_opengl.py b/tests/test_scene_rendering/opengl/test_cli_flags_opengl.pyindex 8f36200dd..d3ecb1cf2 100644--- a/tests/test_scene_rendering/opengl/test_cli_flags_opengl.py+++ b/tests/test_scene_rendering/opengl/test_cli_flags_opengl.py@@ -435,12 +435,8 @@ def test_gif_format_output(tmp_path, manim_cfg_file, simple_scenes_path):unexpected_mp4_path,)- expected_gif_path = (- tmp_path- / "videos"- / "simple_scenes"- / "480p15"- / add_version_before_extension("SquareToCircle.gif")+ expected_gif_path = add_version_before_extension(+ tmp_path / "videos" / "simple_scenes" / "480p15" / "SquareToCircle.gif")assert expected_gif_path.exists(), "gif file not found at " + str(expected_gif_path)@@ -466,12 +462,8 @@ def test_mp4_format_output(tmp_path, manim_cfg_file, simple_scenes_path):out, err, exit_code = capture(command)assert exit_code == 0, err- unexpected_gif_path = (- tmp_path- / "videos"- / "simple_scenes"- / "480p15"- / add_version_before_extension("SquareToCircle.gif")+ unexpected_gif_path = add_version_before_extension(+ tmp_path / "videos" / "simple_scenes" / "480p15" / "SquareToCircle.gif")assert not unexpected_gif_path.exists(), "unexpected gif file found at " + str(unexpected_gif_path,@@ -510,12 +502,8 @@ def test_videos_not_created_when_png_format_set(out, err, exit_code = capture(command)assert exit_code == 0, err- unexpected_gif_path = (- tmp_path- / "videos"- / "simple_scenes"- / "480p15"- / add_version_before_extension("SquareToCircle.gif")+ unexpected_gif_path = add_version_before_extension(+ tmp_path / "videos" / "simple_scenes" / "480p15" / "SquareToCircle.gif")assert not unexpected_gif_path.exists(), "unexpected gif file found at " + str(unexpected_gif_path,diff --git a/tests/test_scene_rendering/test_cli_flags.py b/tests/test_scene_rendering/test_cli_flags.pyindex 20bdf4fab..d8c76c020 100644--- a/tests/test_scene_rendering/test_cli_flags.py+++ b/tests/test_scene_rendering/test_cli_flags.py@@ -296,12 +296,8 @@ def test_custom_output_name_gif(tmp_path, simple_scenes_path):out, err, exit_code = capture(command)assert exit_code == 0, err- wrong_gif_path = (- tmp_path- / "videos"- / "simple_scenes"- / "480p15"- / add_version_before_extension(scene_name + ".gif")+ wrong_gif_path = add_version_before_extension(+ tmp_path / "videos" / "simple_scenes" / "480p15" / f"{scene_name}.gif")assert not wrong_gif_path.exists(), (@@ -350,12 +346,8 @@ def test_custom_output_name_mp4(tmp_path, simple_scenes_path):"The mp4 file does not respect the custom name: " + custom_name + ".mp4")- unexpected_gif_path = (- tmp_path- / "videos"- / "simple_scenes"- / "480p15"- / add_version_before_extension(custom_name + ".gif")+ unexpected_gif_path = add_version_before_extension(+ tmp_path / "videos" / "simple_scenes" / "480p15" / f"{custom_name}.gif")assert not unexpected_gif_path.exists(), "Found an unexpected gif file at " + str(unexpected_gif_path@@ -418,12 +410,8 @@ def test_gif_format_output(tmp_path, manim_cfg_file, simple_scenes_path):unexpected_mp4_path,)- expected_gif_path = (- tmp_path- / "videos"- / "simple_scenes"- / "480p15"- / add_version_before_extension("SquareToCircle.gif")+ expected_gif_path = add_version_before_extension(+ tmp_path / "videos" / "simple_scenes" / "480p15" / "SquareToCircle.gif")assert expected_gif_path.exists(), "gif file not found at " + str(expected_gif_path)@@ -447,12 +435,8 @@ def test_mp4_format_output(tmp_path, manim_cfg_file, simple_scenes_path):out, err, exit_code = capture(command)assert exit_code == 0, err- unexpected_gif_path = (- tmp_path- / "videos"- / "simple_scenes"- / "480p15"- / add_version_before_extension("SquareToCircle.gif")+ unexpected_gif_path = add_version_before_extension(+ tmp_path / "videos" / "simple_scenes" / "480p15" / "SquareToCircle.gif")assert not unexpected_gif_path.exists(), "unexpected gif file found at " + str(unexpected_gif_path,@@ -489,12 +473,8 @@ def test_videos_not_created_when_png_format_set(out, err, exit_code = capture(command)assert exit_code == 0, err- unexpected_gif_path = (- tmp_path- / "videos"- / "simple_scenes"- / "480p15"- / add_version_before_extension("SquareToCircle.gif")+ unexpected_gif_path = add_version_before_extension(+ tmp_path / "videos" / "simple_scenes" / "480p15" / "SquareToCircle.gif")assert not unexpected_gif_path.exists(), "unexpected gif file found at " + str(unexpected_gif_path,