Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,8 @@ rkyv = "0.7.42"
serde = "1.0.188"
serde_json = "1.0.106"

pyo3 = { version = "0.19", features = ["extension-module"] }

[profile.release]
lto = true # Enable link-time optimization
strip = true # Strip symbols from binary*
Expand Down
17 changes: 17 additions & 0 deletions crates/mitex-python/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
[package]
name = "mitex-python"
description.workspace = true
authors.workspace = true
version.workspace = true
edition.workspace = true
license.workspace = true
homepage.workspace = true
repository.workspace = true

[lib]
name = "mitex_python"
crate-type = ["cdylib"]

[dependencies]
pyo3.workspace = true
mitex.workspace = true
23 changes: 23 additions & 0 deletions crates/mitex-python/Makefile
Copy link
Member

@OrangeX4 OrangeX4 Nov 11, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the pull request. Sorry for that I was a bit busy and didn't have time to look at it. Could you consider replacing this with a better solution instead of a Makefile? For example, using pyproject.toml, which would also eliminate the need for requirements.txt. And could you consider adding it to CI to upload the build artifacts to artifacts?

Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
PY := python
BUILD := build.py

.PHONY: develop release wheel wheel-release test clean

develop:
$(PY) $(BUILD)

release:
$(PY) $(BUILD) --release

wheel:
$(PY) $(BUILD) --wheel

wheel-release:
$(PY) $(BUILD) --wheel --release

test:
$(PY) $(BUILD) --test

clean:
cargo clean
rm -rf target/wheels
69 changes: 69 additions & 0 deletions crates/mitex-python/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
# mitex-python

Python bindings for the mitex LaTeX to Typst converter.

## Description

`mitex-python` provides Python bindings for the [mitex](https://github.com/mitex-rs/mitex) library, a fast and reliable LaTeX to Typst converter written in Rust. This package allows Python developers to easily convert LaTeX math expressions to Typst syntax.

## Features

- Convert LaTeX math expressions to Typst syntax
- High performance through Rust implementation
- Seamless Python integration via PyO3

## Installation

Currently only available by building from source. See the Development section below.

## Usage

```python
import mitex_python

# Convert a simple LaTeX expression
result = mitex_python.convert_latex_math("\\frac{1}{2}")
print(result) # Output: "$frac(1, 2)$"

# Convert a more complex expression
complex_expr = "\\int_{0}^{\\infty} e^{-x^2} dx = \\frac{\\sqrt{\\pi}}{2}"
result = mitex_python.convert_latex_math(complex_expr)
print(result)
```

## Development

To build and install `mitex-python`, we need few things.

Prerequisites:
- Rust toolchain
- Python 3.8+

First, navigate to the project directory:
```
cd crates/mitex-python
```

The building needs `maturin`
```
pip install -r requirements.txt
# or
pip install maturin
```

To install `mitex-python`,
```
cd crates/mitex-python && make develop
```

Common commands (from `crates/mitex-python`):
- Install: `make` or `make develop`

- `make release`: Builds an optimized version and installs it directly in your current Python environment (using `maturin develop --release`)
- `make wheel`: Only builds a wheel file without installing it (using `maturin build`). Creates unoptimized debug wheels in target/wheels
- `make wheel-release`: Only builds an optimized wheel file without installing it (using `maturin build --release`). Creates release/optimized wheels in target/wheels
- `make test` : Run tests (needs `pytest`)


You can also call the script directly:
- `python3 crates/mitex-python/build.py [--release] [--wheel] [--test]`
49 changes: 49 additions & 0 deletions crates/mitex-python/build.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
#!/usr/bin/env python3
import argparse
import subprocess
import sys
import shutil
from pathlib import Path

def run_command(cmd, cwd=None):
print(f"Running: {' '.join(cmd)}")
result = subprocess.run(cmd, cwd=cwd)
if result.returncode != 0:
sys.exit(result.returncode)

def ensure_maturin():
if shutil.which("maturin") is None:
print("Error: maturin not found. Install it with:")
print(" python3 -m pip install maturin")
sys.exit(1)

def main():
parser = argparse.ArgumentParser(description="Build mitex-python")
parser.add_argument("--release", action="store_true", help="Build in release mode")
parser.add_argument("--wheel", action="store_true", help="Build wheel for distribution")
parser.add_argument("--test", action="store_true", help="Run tests after building")
args = parser.parse_args()

crate_path = Path(__file__).parent
project_root = crate_path.parent.parent # repo root
build_opts = ["--release"] if args.release else []

ensure_maturin()

if args.wheel:
run_command(["maturin", "build", *build_opts], cwd=crate_path)
print(f"Wheel(s) in: {project_root / 'target' / 'wheels'}")
else:
run_command(["maturin", "develop", *build_opts], cwd=crate_path)

if args.test:
try:
import pytest # noqa: F401
except ImportError:
print("Installing pytest...")
run_command([sys.executable, "-m", "pip", "install", "pytest"])

run_command([sys.executable, "-m", "pytest", str(crate_path / "test.py"), "-v"])

if __name__ == "__main__":
main()
1 change: 1 addition & 0 deletions crates/mitex-python/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
maturin==1.9.4
16 changes: 16 additions & 0 deletions crates/mitex-python/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
use pyo3::prelude::*;
use mitex::convert_math; // Your existing converter function

#[pyfunction]
fn convert_latex_to_typst(text: &str) -> PyResult<String> {
match convert_math(text, None) {
Ok(result) => Ok(result),
Err(e) => Err(PyErr::new::<pyo3::exceptions::PyValueError, _>(e.to_string()))
}
}

#[pymodule]
fn mitex_python(_py: Python, m: &PyModule) -> PyResult<()> {
m.add_function(wrap_pyfunction!(convert_latex_to_typst, m)?)?;
Ok(())
}
37 changes: 37 additions & 0 deletions crates/mitex-python/test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
"""
Tests for mitex_python module using pytest.
"""
import mitex_python

def test_basic_fraction():
"""Test conversion of a basic fraction."""
result = mitex_python.convert_latex_to_typst("\\frac{1}{2}")
# Normalize whitespace for comparison
normalized_result = result.replace(" ", "")
assert "frac(1,2)" in normalized_result

def test_complex_expression():
"""Test conversion of a more complex expression."""
latex = "\\int_{0}^{\\infty} e^{-x^2} dx = \\frac{\\sqrt{\\pi}}{2}"
result = mitex_python.convert_latex_to_typst(latex)
# integral _(0 )^(oo ) e ^(- x ^(2 )) d x = frac(mitexsqrt(pi ),2 )
# Just verify it runs without error and returns a non-empty string
assert result and isinstance(result, str)

def test_math_operators():
"""Test conversion of common math operators."""
result = mitex_python.convert_latex_to_typst("a + b - c \\times d \\div e")
assert "+" in result
assert "-" in result
assert "times" in result or "*" in result
assert "div" in result or "/" in result

def test_error_handling():
"""Test handling of malformed input."""
# This should not crash but might return an error message or do partial conversion
result = mitex_python.convert_latex_to_typst("\\frac{1}{")
assert isinstance(result, str)

if __name__ == "__main__":
import pytest
pytest.main([__file__, "-v"])