Typ in Manim. Ich mache Manim, um die typstarme Sprache zu unterstützenPython

Python-Programme
Anonymous
 Typ in Manim. Ich mache Manim, um die typstarme Sprache zu unterstützen

Post by Anonymous »

Ich mache Manim, um die typst -tectioning -Sprache zu unterstützen, aber es scheint, als würde eine horizontale Linie zwischen Zähler und Nenner wie (z^2)/(w^2) nicht angezeigt werden. Scheinen Demo (Szene) .

Code: Select all

from manim import *
import os
import shutil
import subprocess

# Define a temporary directory for Typst output
TYPST_TEMP_DIR = "typst_temp_files"

def str_to_valid_filename(s: str) -> str:
"""Converts a string to a valid filename."""
return "".join((c for c in s if c.isalnum() or c in "._-")).strip()

def common_str_to_typst_str(common_str: str, font_size_pt: int = 50, color_hex: str = "#FFFFFF") -> str:
"""
Generates a Typst string with specified font size and color.
The font_size_pt here is the actual font size Typst will render at.
"""
# Ensure background is transparent and text color/size are set
template = rf"""#set page(fill: none)
#set text(fill: rgb("{color_hex}"), size: {font_size_pt}pt)
// Set page width to auto to prevent excessive padding, allowing Typst to fit content
#set page(width: auto, height: auto)
{common_str}"""
return template

def math_str_to_common_str(math_str: str) -> str:
"""Wraps a math string in Typst's inline math delimiters."""
return f"$ {math_str} $"

def typst_str_to_typ(typst_str: str, typst_file_name: str, folder: str = TYPST_TEMP_DIR) -> str:
"""Writes the Typst content to a .typ file."""
os.makedirs(folder, exist_ok=True) # Use exist_ok=True to avoid error if folder exists
file_path = os.path.join(folder, typst_file_name)
with open(file_path, "w", encoding="utf-8") as f:
f.write(typst_str)
return file_path

def typ_to_svg(typ_file_path: str) -> str:
"""Compiles a .typ file to an SVG file using the Typst CLI."""
svg_file_path = typ_file_path.replace(".typ", ".svg")

if os.path.exists(svg_file_path):
return svg_file_path # Return existing SVG for caching, avoiding re-compilation

command = [
'typst', 'compile',
'--format', 'svg',
typ_file_path,
svg_file_path
]

try:
# Use subprocess.run for better error handling and simplicity
result = subprocess.run(command, check=True, capture_output=True, text=True, encoding="utf-8")
if result.stdout:
print(f"Typst stdout: {result.stdout}")
if result.stderr:
print(f"Typst stderr: {result.stderr}")
except subprocess.CalledProcessError as e:
print(f"Error compiling Typst file: {typ_file_path}")
print(f"Typst stderr: {e.stderr}")
raise RuntimeError(f"Typst compilation failed: {e.stderr}") from e
except FileNotFoundError:
raise RuntimeError("Typst command not found.  Please ensure Typst is installed and in your system's PATH.")

if not os.path.exists(svg_file_path):
raise RuntimeError(f"SVG file not generated at expected path: {svg_file_path}")

return svg_file_path

def common_str_to_svg(common_str: str, font_size_pt: int = 50, color_hex: str = "#FFFFFF", folder: str = TYPST_TEMP_DIR) -> str:
"""
Converts a common string to an SVG file path by rendering it with Typst.
This function will generate temporary .typ and .svg files.
"""
# Create a unique filename for the Typst file to avoid conflicts
unique_filename = f"{str_to_valid_filename(common_str)}_{hash(common_str) % 100000}.typ"

typst_str = common_str_to_typst_str(common_str, font_size_pt, color_hex)
typ_file_path = typst_str_to_typ(typst_str, unique_filename, folder)
svg_file_path = typ_to_svg(typ_file_path)
return svg_file_path

class Typst(SVGMobject):
"""
A Manim Mobject for rendering Typst content.

Parameters
----------
common_str
The string content to be rendered by Typst.
font_size
The desired visual font size in Manim units (similar to Text/MathTex).
color
The color of the text, as a ManimColor or hex string.
folder
The directory to store temporary Typst files.
kwargs
Additional keyword arguments passed to SVGMobject.
"""
def __init__(self, common_str: str, font_size: float = 0.7, color: ManimColor | str = WHITE, folder: str = TYPST_TEMP_DIR, **kwargs):
TYPST_RENDER_FONT_SIZE_PT = 200 # Render Typst at a large, fixed point size for quality

# Ensure color is a hex string for Typst
if isinstance(color, ManimColor):
color_hex = color.to_hex() #  1e-9:
self.scale(font_size / self.height)
else:
self.set_height(font_size)

self.set_color(self._color)

@property
def font_size(self) -> float:
return self._font_size

@font_size.setter
def font_size(self, new_font_size: float):
if new_font_size

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post