A Vision Encoder-Decoder model for converting mathematical formula images to LaTeX code. This project implements a state-of-the-art OCR system specifically designed for handwritten and printed mathematical formulas.

microsoft/swin-base-patch4-window7-224-in22k)git clone https://github.com/dotrunghieu0903/OCR-LaTeX-MD.git
cd OCR-LaTeX-MD
# Create a new conda environment
conda create -n ocr-latex python=3.9 -y
# Activate the environment
conda activate ocr-latex
# For CUDA 11.8 (adjust based on your CUDA version)
conda install pytorch torchvision torchaudio pytorch-cuda=11.8 -c pytorch -c nvidia
# For CPU only (not recommended for training)
# conda install pytorch torchvision torchaudio cpuonly -c pytorch
# Navigate to handwritten directory
cd handwritten
# Install required packages
pip install -r requirements.txt
# Additional conda packages for better performance
conda install pillow numpy scipy -c conda-forge
python -c "import torch; print(f'PyTorch version: {torch.__version__}'); print(f'CUDA available: {torch.cuda.is_available()}')"
The model is trained on high-quality mathematical formula datasets:
dataset = load_dataset("OleehyO/latex-formulas", "cleaned_formulas")
train_val_split = dataset["train"].train_test_split(test_size=0.2, seed=42)
train_ds = train_val_split["train"]
val_test_split = train_val_split["test"].train_test_split(test_size=0.5, seed=42)
val_ds = val_test_split["train"]
test_ds = val_test_split["test"]
# Activate conda environment
conda activate ocr-latex
# Navigate to training directory
cd handwritten
# Single GPU training
python train.py
# Multi-GPU training (if available)
python -m torch.distributed.launch --nproc_per_node=2 train.py
# Fine-tune a pre-trained model
python finetune.py
# Run inference on test samples
python inference.py
# For custom images (modify inference.py)
python inference.py --image_path "path/to/your/formula.png"
from transformers import VisionEncoderDecoderModel, AutoTokenizer, AutoFeatureExtractor
import torch
from PIL import Image
# Load model components
model = VisionEncoderDecoderModel.from_pretrained("path/to/your/checkpoint")
tokenizer = AutoTokenizer.from_pretrained("path/to/your/checkpoint")
feature_extractor = AutoFeatureExtractor.from_pretrained("path/to/your/checkpoint")
# Process image
image = Image.open("formula_image.png")
pixel_values = feature_extractor(images=image, return_tensors="pt").pixel_values
# Generate LaTeX
with torch.no_grad():
generated_ids = model.generate(
pixel_values,
max_length=512,
num_beams=4,
early_stopping=True
)
latex_formula = tokenizer.decode(generated_ids[0], skip_special_tokens=True)
print(f"Generated LaTeX: {latex_formula}")
# Process multiple images
images = [Image.open(f"formula_{i}.png") for i in range(5)]
pixel_values = feature_extractor(images=images, return_tensors="pt").pixel_values
generated_ids = model.generate(pixel_values, max_length=512, num_beams=4)
formulas = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)
for i, formula in enumerate(formulas):
print(f"Image {i+1}: {formula}")
OCR-LaTeX-MD/
├── README.md # This file
├── LICENSE # License information
├── Finetune_OCR_AllYouNeeded.ipynb # Jupyter notebook for fine-tuning
├── Multimodal_OCR.ipynb # Multimodal OCR experiments
├── TrOCR_Math_Retraining.ipynb # TrOCR retraining notebook
├── multimodal_ocr.py # Multimodal OCR script
└── handwritten/ # Main training directory
├── train.py # Training from scratch
├── finetune.py # Fine-tuning script
├── inference.py # Inference script
├── dataset.py # Dataset handling
├── utils.py # Utility functions
├── train_config.py # Training configuration
├── requirements.txt # Python dependencies
└── ...
train_config.py)class Config:
# Model parameters
encoder_name = "microsoft/swin-base-patch4-window7-224-in22k"
decoder_name = "gpt2"
# Training parameters
num_epochs = 10
batch_size_train = 32
learning_rate = 1e-4
max_grad_norm = 1.0
# Image parameters
image_size = (224, 468)
max_length = 512
# Checkpoint parameters
checkpoint_dir = "checkpoints"
eval_steps = 200
# For limited GPU memory
batch_size_train = 16 # Reduce batch size
batch_size_val = 16
# For faster training (with more GPUs)
batch_size_train = 64 # Increase batch size
learning_rate = 2e-4 # Increase learning rate
checkpoints/ directory# The training script automatically evaluates on test set
python train.py # Includes final evaluation
# Standalone evaluation
python -c "
from utils import evaluate_model
# Evaluation code here
"
# Test on sample images
python inference.py
# Check results
cat inference_results.json
# Reduce batch size in train_config.py
batch_size_train = 8 # or even smaller
batch_size_val = 8
# Increase learning rate
learning_rate = 2e-4
# Or train for more epochs
num_epochs = 20
# Reinstall PyTorch with correct CUDA version
conda uninstall pytorch torchvision torchaudio
conda install pytorch torchvision torchaudio pytorch-cuda=11.8 -c pytorch -c nvidia
# Reset conda environment
conda deactivate
conda remove -n ocr-latex --all
# Then follow installation steps again
Finetune_OCR_AllYouNeeded.ipynb for interactive traininggit checkout -b feature/amazing-feature)git commit -m 'Add amazing feature')git push origin feature/amazing-feature)This project is licensed under the MIT License - see the LICENSE file for details.
If you encounter any issues or have questions:
conda listHappy Training! 🚀
25 commits
Jupyter Notebook
87.1%
Python
12.2%
A Vision Encoder-Decoder model for converting mathematical formula images to LaTeX code. This project implements a state-of-the-art OCR system specifically designed for handwritten and printed mathematical formulas.

microsoft/swin-base-patch4-window7-224-in22k)git clone https://github.com/dotrunghieu0903/OCR-LaTeX-MD.git
cd OCR-LaTeX-MD
# Create a new conda environment
conda create -n ocr-latex python=3.9 -y
# Activate the environment
conda activate ocr-latex
# For CUDA 11.8 (adjust based on your CUDA version)
conda install pytorch torchvision torchaudio pytorch-cuda=11.8 -c pytorch -c nvidia
# For CPU only (not recommended for training)
# conda install pytorch torchvision torchaudio cpuonly -c pytorch
# Navigate to handwritten directory
cd handwritten
# Install required packages
pip install -r requirements.txt
# Additional conda packages for better performance
conda install pillow numpy scipy -c conda-forge
python -c "import torch; print(f'PyTorch version: {torch.__version__}'); print(f'CUDA available: {torch.cuda.is_available()}')"
The model is trained on high-quality mathematical formula datasets:
dataset = load_dataset("OleehyO/latex-formulas", "cleaned_formulas")
train_val_split = dataset["train"].train_test_split(test_size=0.2, seed=42)
train_ds = train_val_split["train"]
val_test_split = train_val_split["test"].train_test_split(test_size=0.5, seed=42)
val_ds = val_test_split["train"]
test_ds = val_test_split["test"]
# Activate conda environment
conda activate ocr-latex
# Navigate to training directory
cd handwritten
# Single GPU training
python train.py
# Multi-GPU training (if available)
python -m torch.distributed.launch --nproc_per_node=2 train.py
# Fine-tune a pre-trained model
python finetune.py
# Run inference on test samples
python inference.py
# For custom images (modify inference.py)
python inference.py --image_path "path/to/your/formula.png"
from transformers import VisionEncoderDecoderModel, AutoTokenizer, AutoFeatureExtractor
import torch
from PIL import Image
# Load model components
model = VisionEncoderDecoderModel.from_pretrained("path/to/your/checkpoint")
tokenizer = AutoTokenizer.from_pretrained("path/to/your/checkpoint")
feature_extractor = AutoFeatureExtractor.from_pretrained("path/to/your/checkpoint")
# Process image
image = Image.open("formula_image.png")
pixel_values = feature_extractor(images=image, return_tensors="pt").pixel_values
# Generate LaTeX
with torch.no_grad():
generated_ids = model.generate(
pixel_values,
max_length=512,
num_beams=4,
early_stopping=True
)
latex_formula = tokenizer.decode(generated_ids[0], skip_special_tokens=True)
print(f"Generated LaTeX: {latex_formula}")
# Process multiple images
images = [Image.open(f"formula_{i}.png") for i in range(5)]
pixel_values = feature_extractor(images=images, return_tensors="pt").pixel_values
generated_ids = model.generate(pixel_values, max_length=512, num_beams=4)
formulas = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)
for i, formula in enumerate(formulas):
print(f"Image {i+1}: {formula}")
OCR-LaTeX-MD/
├── README.md # This file
├── LICENSE # License information
├── Finetune_OCR_AllYouNeeded.ipynb # Jupyter notebook for fine-tuning
├── Multimodal_OCR.ipynb # Multimodal OCR experiments
├── TrOCR_Math_Retraining.ipynb # TrOCR retraining notebook
├── multimodal_ocr.py # Multimodal OCR script
└── handwritten/ # Main training directory
├── train.py # Training from scratch
├── finetune.py # Fine-tuning script
├── inference.py # Inference script
├── dataset.py # Dataset handling
├── utils.py # Utility functions
├── train_config.py # Training configuration
├── requirements.txt # Python dependencies
└── ...
train_config.py)class Config:
# Model parameters
encoder_name = "microsoft/swin-base-patch4-window7-224-in22k"
decoder_name = "gpt2"
# Training parameters
num_epochs = 10
batch_size_train = 32
learning_rate = 1e-4
max_grad_norm = 1.0
# Image parameters
image_size = (224, 468)
max_length = 512
# Checkpoint parameters
checkpoint_dir = "checkpoints"
eval_steps = 200
# For limited GPU memory
batch_size_train = 16 # Reduce batch size
batch_size_val = 16
# For faster training (with more GPUs)
batch_size_train = 64 # Increase batch size
learning_rate = 2e-4 # Increase learning rate
checkpoints/ directory# The training script automatically evaluates on test set
python train.py # Includes final evaluation
# Standalone evaluation
python -c "
from utils import evaluate_model
# Evaluation code here
"
# Test on sample images
python inference.py
# Check results
cat inference_results.json
# Reduce batch size in train_config.py
batch_size_train = 8 # or even smaller
batch_size_val = 8
# Increase learning rate
learning_rate = 2e-4
# Or train for more epochs
num_epochs = 20
# Reinstall PyTorch with correct CUDA version
conda uninstall pytorch torchvision torchaudio
conda install pytorch torchvision torchaudio pytorch-cuda=11.8 -c pytorch -c nvidia
# Reset conda environment
conda deactivate
conda remove -n ocr-latex --all
# Then follow installation steps again
Finetune_OCR_AllYouNeeded.ipynb for interactive traininggit checkout -b feature/amazing-feature)git commit -m 'Add amazing feature')git push origin feature/amazing-feature)This project is licensed under the MIT License - see the LICENSE file for details.
If you encounter any issues or have questions:
conda listHappy Training! 🚀
25 commits
Jupyter Notebook
87.1%
Python
12.2%