A community-maintained Python framework for creating mathematical animations.
solve merge conflicts
leotrsb16210912211
diff --cc example_scenes/customtex.pyindex 000000000,db301c72c..ed62ec4d4mode 000000,100644..100644--- a/example_scenes/customtex.py+++ b/example_scenes/customtex.py@@@ -1,0 -1,27 +1,28 @@@+ from manim import *++ # Test cases:+ # 1. manim customtex.py ExampleFileScene -pl+ # --> should fail, because \vv is not defined+ #+ # 2. manim customtex.py ExampleFileScene --tex_template custom_template.tex -pl+ # --> should succeed as custom template includes package esvect (which defines \vv)+ #+ # 3. manim customtex.py ExampleClassScene -pl+ # --> should succeed as the package esvect is included in template object++ class ExampleFileScene(Scene):+ def construct(self):- text=TexMobject(r"\vv{vb}")++ text = TexMobject(r"\vv{vb}")+ #text=TextMobject(r"$\vv{vb}$")+ self.play(Write(text))++++ class ExampleClassScene(Scene):+ def construct(self):- tpl=TexTemplate()++ tpl = TexTemplate()+ tpl.append_package(["esvect",["f"]])+ config.register_tex_template(tpl)++ #text=TextMobject(r"$\vv{vb}$")- text=TexMobject(r"\vv{vb}")++ text = TexMobject(r"\vv{vb}")+ self.play(Write(text))diff --cc manim/__main__.pyindex e6e30ff84,1eaeefde5..b14c2cad6--- a/manim/__main__.py+++ b/manim/__main__.py@@@ -1,11 -1,15 +1,13 @@@- from .config import config++from .config import initialize_tex, configfrom . import extract_scene-from . import configfrom . import constantsdef main():- args = config.parse_cli()- cfg = config.get_configuration(args)- config.initialize_directories(cfg)- config.initialize_tex(cfg)- extract_scene.main(cfg)++ initialize_tex(config)+ extract_scene.main(config)++if __name__ == "__main__":main()diff --cc manim/config.pyindex bb405bd36,2529221d8..e49c29976--- a/manim/config.py+++ b/manim/config.py@@@ -1,331 -1,226 +1,335 @@@-import argparse-import colour+"""+config.py+---------++Process the manim.cfg file and the command line arguments into a single+config object.++"""+import osimport sys-import types--from .utils.tex import *-from . import constants-from . import dirs+import argparse+import configparser+import colour-++from .utils.tex import TexTemplateFromFile, TexTemplatefrom .logger import logger- __all__ = ['config']-__all__ = ["parse_cli", "get_configuration", "initialize_directories","register_tex_template","initialize_tex"]++__all__ = ["config", "register_tex_template", "initialize_tex"]-def parse_cli():- try:- parser = argparse.ArgumentParser()- parser.add_argument(- "file",- help="Path to file holding the python code for the scene",- )- parser.add_argument(- "scene_names",- nargs="*",- help="Name of the Scene class you want to see",- )- parser.add_argument(- "-p", "--preview",- action="store_true",- help="Automatically open the saved file once its done",- )- parser.add_argument(- "-w", "--write_to_movie",- action="store_true",- help="Render the scene as a movie file",- )- parser.add_argument(- "-s", "--save_last_frame",- action="store_true",- help="Save the last frame",- )- parser.add_argument(- "--dry_run",- action="store_true",- help= "Do a dry run (render scenes but generate no output files)",- )- parser.add_argument(- "-l", "--low_quality",- action="store_true",- help="Render at low quality (for fastest rendering)",- ),- parser.add_argument(- "-m", "--medium_quality",- action="store_true",- help="Render at medium quality (for much faster rendering)",- ),- parser.add_argument(- "-e", "--high_quality",- action="store_true",- help="Render at high quality (for slightly faster rendering)",- ),- parser.add_argument(- "-k", "--four_k",- action="store_true",- help="Render at 4K quality (slower rendering)",- ),- parser.add_argument(- "-g", "--save_pngs",- action="store_true",- help="Save each frame as a png",- )- parser.add_argument(- "-i", "--save_as_gif",- action="store_true",- help="Save the video as gif",- )- parser.add_argument(- "-f", "--show_file_in_finder",- action="store_true",- help="Show the output file in finder",- )- parser.add_argument(- "-t", "--transparent",- action="store_true",- help="Render to a movie file with an alpha channel",- )- parser.add_argument(- "-q", "--quiet",- action="store_true",- help="",- )- parser.add_argument(- "-a", "--write_all",- action="store_true",- help="Write all the scenes from a file",- )- parser.add_argument(- "-o", "--file_name",- help="Specify the name of the output file, if"- " it should be different from the scene class name",- )- parser.add_argument(- "-n", "--start_at_animation_number",- help="Start rendering not from the first animation, but"- " from another, specified by its index. If you pass"- " in two comma separated values, e.g. \"3,6\", it will end"- " the rendering at the second value",- )- parser.add_argument(- "-r", "--resolution",- help="Resolution, passed as \"height,width\"",- )- parser.add_argument(- "-c", "--color",- help="Background color",- )- parser.add_argument(- "--sound",- action="store_true",- help="Play a success/failure sound",- )- parser.add_argument(- "--leave_progress_bars",- action="store_true",- help="Leave progress bars displayed in terminal",- )- parser.add_argument(- "--media_dir",- help="Directory to write media",- )- video_group = parser.add_mutually_exclusive_group()- video_group.add_argument(- "--video_dir",- help="Directory to write file tree for video",- )- parser.add_argument(- "--tex_dir",- help="Directory to write tex",- )- parser.add_argument(- "--text_dir",- help="Directory to write text",- )- parser.add_argument(- "--tex_template",- help="Specify a custom TeX template file",- )- return parser.parse_args()-- except argparse.ArgumentError as err:- logger.error(str(err))- sys.exit(2)---def get_configuration(args):- file_writer_config = {- # By default, write to file- "write_to_movie": (args.write_to_movie or not args.save_last_frame) and not args.dry_run,- "save_last_frame": args.save_last_frame and not args.dry_run,- "save_pngs": args.save_pngs,- "save_as_gif": args.save_as_gif,- # If -t is passed in (for transparent), this will be RGBA- "png_mode": "RGBA" if args.transparent else "RGB",- "movie_file_extension": ".mov" if args.transparent else ".mp4",- "file_name": args.file_name,- "input_file_path": args.file,- }- config = {- "file": args.file,- "scene_names": args.scene_names,- "open_video_upon_completion": args.preview,- "show_file_in_finder": args.show_file_in_finder,- "file_writer_config": file_writer_config,- "quiet": args.quiet or args.write_all,- "ignore_waits": args.preview,- "write_all": args.write_all,- "start_at_animation_number": args.start_at_animation_number,- "end_at_animation_number": None,- "sound": args.sound,- "leave_progress_bars": args.leave_progress_bars,- "media_dir": args.media_dir,- "video_dir": args.video_dir,- "tex_dir": args.tex_dir,- "text_dir": args.text_dir,- "tex_template": args.tex_template,- }-- # Camera configuration- config["camera_config"] = get_camera_configuration(args)-- # Arguments related to skipping- stan = config["start_at_animation_number"]- if stan is not None:- if "," in stan:- start, end = stan.split(",")- config["start_at_animation_number"] = int(start)- config["end_at_animation_number"] = int(end)- else:- config["start_at_animation_number"] = int(stan)+def _parse_config(input_file, config_files):+ # This only loads the [CLI] section of the manim.cfg file. If using+ # CLI arguments, the _update_config_with_args function will take care+ # of overriding any of these defaults.+ config_parser = configparser.ConfigParser()+ successfully_read_files = config_parser.read(config_files)+ if not successfully_read_files:+ raise FileNotFoundError('Config file could not be read')++ # Put everything in a dict+ config = {}++ # Make sure we have an input file+ config['INPUT_FILE'] = input_file++ # ConfigParser options are all strings, so need to convert to the+ # appropriate type++ # booleans+ for opt in ['PREVIEW', 'SHOW_FILE_IN_FINDER', 'QUIET', 'SOUND',+ 'LEAVE_PROGRESS_BARS', 'WRITE_ALL', 'WRITE_TO_MOVIE',+ 'SAVE_LAST_FRAME', 'DRY_RUN', 'SAVE_PNGS', 'SAVE_AS_GIF']:+ config[opt] = config_parser['CLI'].getboolean(opt)++ # numbers+ for opt in ['FROM_ANIMATION_NUMBER', 'UPTO_ANIMATION_NUMBER',+ 'BACKGROUND_OPACITY']:+ config[opt] = config_parser['CLI'].getint(opt)++ # UPTO_ANIMATION_NUMBER is special because -1 actually means np.inf+ if config['UPTO_ANIMATION_NUMBER'] == -1:+ import numpy as np+ config['UPTO_ANIMATION_NUMBER'] = np.inf++ # strings+ for opt in ['PNG_MODE', 'MOVIE_FILE_EXTENSION', 'MEDIA_DIR',+ 'OUTPUT_FILE', 'VIDEO_DIR', 'TEX_DIR', 'TEXT_DIR',+ 'BACKGROUND_COLOR']:+ config[opt] = config_parser['CLI'][opt]++ # streaming section -- all values are strings+ config['STREAMING'] = {}+ for opt in ['LIVE_STREAM_NAME', 'TWITCH_STREAM_KEY',+ 'STREAMING_PROTOCOL', 'STREAMING_PROTOCOL', 'STREAMING_IP',+ 'STREAMING_PORT', 'STREAMING_PORT', 'STREAMING_CLIENT',+ 'STREAMING_CONSOLE_BANNER']:+ config['STREAMING'][opt] = config_parser['streaming'][opt]- config["skip_animations"] = any([- file_writer_config["save_last_frame"],- config["start_at_animation_number"],+ # for internal use (no CLI flag)+ config['SKIP_ANIMATIONS'] = any([+ config['SAVE_LAST_FRAME'],+ config['FROM_ANIMATION_NUMBER'],])- return config+ # camera config -- all happen to be integers+ config['CAMERA_CONFIG'] = {}+ for opt in ['FRAME_RATE', 'PIXEL_HEIGHT', 'PIXEL_WIDTH']:+ config['CAMERA_CONFIG'][opt] = config_parser['CLI'].getint(opt)-def get_camera_configuration(args):- camera_config = {}- if args.low_quality:- camera_config.update(constants.LOW_QUALITY_CAMERA_CONFIG)- elif args.medium_quality:- camera_config.update(constants.MEDIUM_QUALITY_CAMERA_CONFIG)- elif args.high_quality:- camera_config.update(constants.HIGH_QUALITY_CAMERA_CONFIG)- elif args.four_k:- camera_config.update(constants.FOURK_CAMERA_CONFIG)- else:- camera_config.update(constants.PRODUCTION_QUALITY_CAMERA_CONFIG)+ # file writer config -- just pull them from the overall config for now+ config['FILE_WRITER_CONFIG'] = {key: config[key] for key in [+ "WRITE_TO_MOVIE", "SAVE_LAST_FRAME", "SAVE_PNGS",+ "SAVE_AS_GIF", "PNG_MODE", "MOVIE_FILE_EXTENSION",+ "OUTPUT_FILE", "INPUT_FILE"]}++ return config, config_parser+++def _parse_cli():+ parser = argparse.ArgumentParser(+ description='Animation engine for explanatory math videos',+ epilog='Made with <3 by the manim community devs'+ )+ parser.add_argument(+ "file",+ help="path to file holding the python code for the scene",+ )+ parser.add_argument(+ "--scene_names",+ nargs="*",+ help="Name of the Scene class you want to see",+ )+ parser.add_argument(+ "-o", "--output_file",+ help="Specify the name of the output file, if"+ "it should be different from the scene class name",+ )++ # Note the following use (action='store_const', const=True),+ # instead of using the built-in (action='store_true'). The reason+ # is that these two are not equivalent. The latter is equivalent+ # to (action='store_const', const=True, default=False), while the+ # former sets no default value. We do not want to set the default+ # here, but in the manim.cfg file. Therefore we use the latter,+ # (action='store_const', const=True).+ parser.add_argument(+ "-p", "--preview",+ action="store_const",+ const=True,+ help="Automatically open the saved file once its done",+ )+ parser.add_argument(+ "-f", "--show_file_in_finder",+ action="store_const",+ const=True,+ help="Show the output file in finder",+ )+ parser.add_argument(+ "-q", "--quiet",+ action="store_const",+ const=True,+ help="Quiet mode",+ )+ parser.add_argument(+ "--sound",+ action="store_const",+ const=True,+ help="Play a success/failure sound",+ )+ parser.add_argument(+ "--leave_progress_bars",+ action="store_const",+ const=True,+ help="Leave progress bars displayed in terminal",+ )+ parser.add_argument(+ "-a", "--write_all",+ action="store_const",+ const=True,+ help="Write all the scenes from a file",+ )+ parser.add_argument(+ "-w", "--write_to_movie",+ action="store_const",+ const=True,+ help="Render the scene as a movie file",+ )+ parser.add_argument(+ "-s", "--save_last_frame",+ action="store_const",+ const=True,+ help="Save the last frame",+ )+ parser.add_argument(+ "-g", "--save_pngs",+ action="store_const",+ const=True,+ help="Save each frame as a png",+ )+ parser.add_argument(+ "-i", "--save_as_gif",+ action="store_const",+ const=True,+ help="Save the video as gif",+ )++ # The default value of the following is set in manim.cfg+ parser.add_argument(+ "-c", "--color",+ help="Background color",+ )+ parser.add_argument(+ "--background_opacity",+ help="Background opacity",+ )+ parser.add_argument(+ "--media_dir",+ help="directory to write media",+ )+ video_group = parser.add_mutually_exclusive_group()+ video_group.add_argument(+ "--video_dir",+ help="directory to write file tree for video",+ )+ parser.add_argument(+ "--tex_dir",+ help="directory to write tex",+ )+ parser.add_argument(+ "--text_dir",+ help="directory to write text",+ )++ parser.add_argument(++ "--tex_template",++ help="Specify a custom TeX template file",++ )++ # All of the following use (action="store_true"). This means that+ # they are by default False. In contrast to the previous ones that+ # used (action="store_const", const=True), the following do not+ # correspond to a single configuration option. Rather, they+ # override several options at the same time.++ # The following overrides -w, -a, -g, and -i+ parser.add_argument(+ "--dry_run",+ action="store_true",+ help="Do a dry run (render scenes but generate no output files)",+ )++ # The following overrides PNG_MODE, MOVIE_FILE_EXTENSION, and+ # BACKGROUND_OPACITY+ parser.add_argument(+ "-t", "--transparent",+ action="store_true",+ help="Render to a movie file with an alpha channel",+ )++ # The following are mutually exclusive and each overrides+ # FRAME_RATE, PIXEL_HEIGHT, and PIXEL_WIDTH,+ parser.add_argument(+ "-l", "--low_quality",+ action="store_true",+ help="Render at low quality (for fastest rendering)",+ )+ parser.add_argument(+ "-m", "--medium_quality",+ action="store_true",+ help="Render at medium quality (for much faster rendering)",+ )+ parser.add_argument(+ "-e", "--high_quality",+ action="store_true",+ help="Render at high quality (for slightly faster rendering)",+ )+ parser.add_argument(+ "-k", "--fourk_quality",+ action="store_true",+ help="Render at 4K quality (slower rendering)",+ )++ # This overrides any of the above+ parser.add_argument(+ "-r", "--resolution",+ help="Resolution, passed as \"height,width\"",+ )++ # This sets FROM_ANIMATION_NUMBER and UPTO_ANIMATION_NUMBER+ parser.add_argument(+ "-n", "--from_animation_number",+ help="Start rendering not from the first animation, but"+ "from another, specified by its index. If you pass"+ "in two comma separated values, e.g. \"3,6\", it will end"+ "the rendering at the second value",+ )++ # Specify the manim.cfg file+ parser.add_argument(+ "--config_file",+ help="Specify the configuration file",+ )++ return parser.parse_args()+++def _update_config_with_args(config, config_parser, args):+ # Take care of options that do not have defaults in manim.cfg+ config['FILE'] = args.file+ config['SCENE_NAMES'] = (args.scene_names+ if args.scene_names is not None else [])++ # Flags that directly override config defaults.+ for opt in ['PREVIEW', 'SHOW_FILE_IN_FINDER', 'QUIET', 'SOUND',+ 'LEAVE_PROGRESS_BARS', 'WRITE_ALL', 'WRITE_TO_MOVIE',+ 'SAVE_LAST_FRAME', 'SAVE_PNGS', 'SAVE_AS_GIF', 'MEDIA_DIR',+ 'VIDEO_DIR', 'TEX_DIR', 'TEXT_DIR', 'BACKGROUND_OPACITY',+ 'OUTPUT_FILE']:+ if getattr(args, opt.lower()) is not None:+ config[opt] = getattr(args, opt.lower())+- # Parse the -n flag.++ # Parse the -n flag.+ nflag = args.from_animation_number+ if nflag is not None:+ if ',' in nflag:+ start, end = nflag.split(',')+ config['FROM_ANIMATION_NUMBER'] = int(start)+ config['UPTO_ANIMATION_NUMBER'] = int(end)+ else:+ config['FROM_ANIMATION_NUMBER'] = int(nflag)- # If the resolution was passed in via -r- if args.resolution:- if "," in args.resolution:+ # The following flags use the options in the corresponding manim.cfg+ # sections to override default options. For example, passing the -t+ # (--transparent) flag takes all of the options defined in the+ # [transparent] section of manim.cfg and uses their values to override+ # the values of those options defined in CLI.++ # -t, --transparent+ if args.transparent:+ config.update({+ 'PNG_MODE': config_parser['transparent']['PNG_MODE'],+ 'MOVIE_FILE_EXTENSION': config_parser['transparent']['MOVIE_FILE_EXTENSION'],+ 'BACKGROUND_OPACITY': config_parser['transparent'].getfloat('BACKGROUND_OPACITY')+ })++ # --dry_run happens to override options that are all booleans+ if args.dry_run:+ config.update({opt.upper(): config_parser['dry_run'].getboolean(opt)+ for opt in config_parser['dry_run']})++ # the *_quality arguments happen to override options that are all ints+ for flag in ['fourk_quality', 'high_quality', 'medium_quality',+ 'low_quality']:+ if getattr(args, flag) is not None:+ config['CAMERA_CONFIG'].update(+ {opt.upper(): config_parser[flag].getint(opt)+ for opt in config_parser[flag]})++ # Parse the -r (--resolution) flag. Note the -r flag does not+ # correspond to any section in manim.cfg, but overrides the same+ # options as the *_quality sections.+ if args.resolution is not None:- if "," in args.resolution:++ if "," in args.resolution:height_str, width_str = args.resolution.split(",")height = int(height_str)width = int(width_str)@@@ -371,38 -270,57 +375,79 @@@ def _init_dirs(config)"Ignoring --media_dir, since both --tex_dir and --video_dir were passed.")- dir_config["tex_dir"] = (config["tex_dir"]- or dirs.TEX_DIR- or os.path.join(dir_config["media_dir"], "Tex"))- dir_config["text_dir"] = (config["text_dir"]- or dirs.TEXT_DIR- or os.path.join(dir_config["media_dir"], "texts"))-- if not config["video_dir"] or dirs.VIDEO_DIR:- dir_config["video_dir"] = os.path.join(dir_config["media_dir"], "videos")-- for folder in [dir_config["video_dir"], dir_config["tex_dir"], dir_config["text_dir"]]:- if folder != "" and not os.path.exists(folder):+ # Make sure all folders exist+ for folder in [config["VIDEO_DIR"], config["TEX_DIR"], config["TEXT_DIR"]]:+ if not os.path.exists(folder):os.makedirs(folder)- dirs.MEDIA_DIR = dir_config["media_dir"]- dirs.VIDEO_DIR = dir_config["video_dir"]- dirs.TEX_DIR = dir_config["tex_dir"]- dirs.TEXT_DIR = dir_config["text_dir"]+ def register_tex_template(tpl):+ """Register the given LaTeX template for later use.++ Parameters+ ----------+ tpl : :class:`~.TexTemplate`+ The LaTeX template to register.+ """- constants.TEX_TEMPLATE = tpl++ config['tex_template'] = tpl++++ def initialize_tex(config):+ """Safely create a LaTeX template object from a file.+ If file is not readable, the default template file is used.++ Parameters+ ----------+ filename : :class:`str`+ The name of the file with the LaTeX template.+ """- filename=""++ filename = ""+ if config["tex_template"]:+ filename = os.path.expanduser(config["tex_template"])+ if filename and not os.access(filename, os.R_OK):+ # custom template not available, fallback to default+ logger.warning(+ f"Custom TeX template {filename} not found or not readable. "+ "Falling back to the default template."+ )+ filename = ""+ if filename:+ # still having a filename -> use the file- constants.TEX_TEMPLATE = TexTemplateFromFile(filename=filename)++ config['tex_template'] = TexTemplateFromFile(filename=filename)+ else:+ # use the default template- constants.TEX_TEMPLATE = TexTemplate()++ config['tex_template'] = TexTemplate()+++++# Config files to be parsed, in ascending priority+library_wide = os.path.join(os.path.dirname(__file__), 'default.cfg'),+config_files = [+ # Lowest priority: library-wide defaults+ library_wide,+ # Medium priority: look for a 'manim.cfg' in the user home+ os.path.expanduser('~/.manim.cfg'),+ # Highest priority: look for a 'manim.cfg' in the current dir+ os.path.join(os.getcwd(), 'manim.cfg'),+ ]++prog = os.path.split(sys.argv[0])[-1]+if prog in ['manim', 'manimcm']:+ # If called as entrypoint, set default config, and override the+ # defaults using CLI arguments+ args = _parse_cli()++ # If the user specified a config file, only use that one and the+ # library-wide defaults.+ if args.config_file is not None:+ config_files = [library_wide, args.config_file]++ config, config_parser = _parse_config(args.file, config_files)+ _update_config_with_args(config, config_parser, args)++else:+ config, _ = _parse_config('', config_files)+++######### ########## ##########++# make sure to set dirs.TEX_DIR somewhere++######### ########## ##########+_init_dirs(config)diff --cc manim/constants.pyindex 205d97655,8edad0dd3..f73f74a6e--- a/manim/constants.py+++ b/manim/constants.py@@@ -15,6 -13,15 +15,7 @@@ class MyText(Text)'font': 'My Font'}'''-START_X = 30-START_Y = 20-NORMAL = 'NORMAL'-ITALIC = 'ITALIC'-OBLIQUE = 'OBLIQUE'-BOLD = 'BOLD'--TEX_TEMPLATE = None+SCENE_NOT_FOUND_MESSAGE = """{} is not in the script"""@@@ -72,38 -116,6 +73,27 @@@ BOTTOM = FRAME_Y_RADIUS * DOWLEFT_SIDE = FRAME_X_RADIUS * LEFTRIGHT_SIDE = FRAME_X_RADIUS * RIGHT+# 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 = 250+DEFAULT_STROKE_WIDTH = 4++# Tex stuff- TEX_USE_CTEX = False- TEX_TEXT_TO_REPLACE = "YourTextHere"- TEMPLATE_TEX_FILE = os.path.join(- os.path.dirname(os.path.realpath(__file__)),- "tex_template.tex" if not TEX_USE_CTEX else "ctex_template.tex"- )- with open(TEMPLATE_TEX_FILE, "r") as infile:- TEMPLATE_TEXT_FILE_BODY = infile.read()- TEMPLATE_TEX_FILE_BODY = TEMPLATE_TEXT_FILE_BODY.replace(- TEX_TEXT_TO_REPLACE,- "\\begin{align*}\n" + TEX_TEXT_TO_REPLACE + "\n\\end{align*}",- )++TEX_TEMPLATE = None++# Mathematical constantsPI = np.piTAU = 2 * PIDEGREES = TAU / 360diff --cc manim/utils/tex_file_writing.pyindex 72b3f3a20,3ab8f6f9f..a51f4b931--- a/manim/utils/tex_file_writing.py+++ b/manim/utils/tex_file_writing.py@@@ -3,29 -3,32 +3,32 @@@ import hashlifrom pathlib import Path-from .. import constants-from .. import dirs+from ..config import config- from ..constants import TEX_TEXT_TO_REPLACE- from ..constants import TEX_USE_CTEX++from ..constants import TEX_TEXT_TO_REPLACE, TEX_USE_CTEXfrom ..logger import logger- def tex_hash(expression, template_tex_file_body):- id_str = str(expression + template_tex_file_body)+ def tex_hash(expression):+ id_str = str(expression)hasher = hashlib.sha256()hasher.update(id_str.encode())# Truncating at 16 bytes for cleanlinessreturn hasher.hexdigest()[:16]+ def tex_to_svg_file(expression, source_type):+ tex_template = constants.TEX_TEMPLATE+ tex_file = generate_tex_file(expression, tex_template, source_type)+ dvi_file = tex_to_dvi(tex_file, tex_template.use_ctex)+ return dvi_to_svg(dvi_file, use_ctex=tex_template.use_ctex)- def tex_to_svg_file(expression, template_tex_file_body):- tex_file = generate_tex_file(expression, template_tex_file_body)- dvi_file = tex_to_dvi(tex_file)- return dvi_to_svg(dvi_file)+ def generate_tex_file(expression, tex_template, source_type):+ if source_type == "text":+ output = tex_template.get_text_for_text_mode(expression)+ elif source_type == "tex":+ output = tex_template.get_text_for_tex_mode(expression)-- def generate_tex_file(expression, template_tex_file_body):result = os.path.join(- dirs.TEX_DIR,+ config['TEX_DIR'],- tex_hash(expression, template_tex_file_body)+ tex_hash(output)) + ".tex"if not os.path.exists(result):logger.info("Writing \"%s\" to %s" % (@@@ -39,11 -39,11 +39,11 @@@return result- def tex_to_dvi(tex_file):- result = tex_file.replace(".tex", ".dvi" if not TEX_USE_CTEX else ".xdv")+ def tex_to_dvi(tex_file, use_ctex = False):+ result = tex_file.replace(".tex", ".dvi" if not use_ctex else ".xdv")result = Path(result).as_posix()tex_file = Path(tex_file).as_posix()- tex_dir = Path(dirs.TEX_DIR).as_posix()+ tex_dir = Path(config['TEX_DIR']).as_posix()if not os.path.exists(result):commands = ["latex",