📄 English | 中文
TexTeller is an end-to-end formula recognition model, capable of converting images into corresponding LaTeX formulas.
TexTeller is built on a Vision Encoder-Decoder architecture using Hugging Face Transformers:
https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip)VisionEncoderDecoderModel from Transformerstexteller/api/detection/)texteller/paddleocr/)det_db_thresh: Binarization threshold (default: 0.3)det_db_box_thresh: Box confidence threshold (default: 0.5)det_db_unclip_ratio: Box expansion ratio (default: 1.6)https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip)$...$) and display ($$...$$) mathPython API (texteller/api/)
img2latex()pdf2md()mixed2md()Ray Serve Backend (texteller/cli/commands/launch/)
Streamlit Web Interface (texteller/cli/commands/web/)
Command-Line Interface (texteller/cli/)
The model uses HuggingFace Accelerate for distributed training:
https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zipCore Dependencies:
torch >= 2.6.0: Deep learning frameworktransformers == 4.47: Model architecture and tokenizationoptimum[onnxruntime] >= 1.24.0: ONNX optimizationopencv-python-headless >= 4.11: Image processingray[serve] >= 2.44.1: API server and scalingOCR Components:
pyclipper >= 1.3: Polygon processing for text boxesshapely >= 2.1: Geometric operationsPDF Support:
pymupdf >= 1.24: PDF rendering and text extractionWeb Interface:
streamlit >= 1.44: Interactive web applicationstreamlit-paste-button >= 0.1: Clipboard image supportThis project is based on TexTeller
by OleehyO, licensed under the Apache License 2.0.
I have modified and extended the original codebase.
All changes from the original are documented in this repository.
TexTeller was trained with 80M image-formula pairs (previous dataset can be obtained here), compared to LaTeX-OCR which used a 100K dataset, TexTeller has stronger generalization abilities and higher accuracy, covering most use cases.
| Feature | TexTeller 3.0 | LaTeX-OCR | Mathpix | Pix2Tex |
|---|---|---|---|---|
| Training Data | 80M pairs | 100K pairs | Proprietary | ~1M pairs |
| Model Size | ~180MB | ~50MB | Unknown | ~200MB |
| Open Source | ✅ Full | ✅ Full | ❌ API only | ✅ Full |
| Handwritten Support | ✅ Yes | ⚠️ Limited | ✅ Yes | ⚠️ Limited |
| Multi-line Formulas | ✅ Excellent | ⚠️ Good | ✅ Excellent | ⚠️ Good |
| Chinese/Multilingual | ✅ Yes | ❌ No | ✅ Yes | ❌ No |
| PDF Processing | ✅ Built-in | ❌ No | ✅ Yes | ❌ No |
| Formula Detection | ✅ RT-DETR | ❌ No | ✅ Yes | ❌ No |
| ONNX Acceleration | ✅ Yes | ❌ No | N/A | ❌ No |
| API Server | ✅ Ray Serve | ❌ No | ✅ Cloud | ❌ No |
| Inference Speed (GPU) | ~50-100ms | ~200ms | ~100ms | ~150ms |
| License | Apache 2.0 | MIT | Commercial | MIT |
| Rare Symbols | ✅ Excellent | ⚠️ Fair | ✅ Excellent | ⚠️ Good |
| Training Support | ✅ Full scripts | ⚠️ Manual | ❌ No | ⚠️ Manual |
Key Advantages:
[!NOTE] If you would like to provide feedback or suggestions for this project, feel free to start a discussion in the Discussions section.
🔖 Table of Contents |
Images that can be recognized by TexTeller |
┌─────────────────────────────────────────────────────────────────┐
│ INPUT LAYER │
│ Images (JPG/PNG) │ PDF Documents │ Numpy Arrays │ PIL Images │
└────────────────────────┬────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ PREPROCESSING PIPELINE │
│ • Image normalization (448×448, grayscale) │
│ • PDF rendering (PyMuPDF, configurable DPI) │
│ • Text extraction from PDF layers │
└────────────────────────┬────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ DETECTION LAYER │
│ ┌────────────────────┐ ┌──────────────────────┐ │
│ │ Formula Detection │ │ Text Detection │ │
│ │ (RT-DETR) │ │ (PaddleOCR DB) │ │
│ │ • Isolated │ │ • Chinese support │ │
│ │ • Embedded │ │ • English support │ │
│ └────────────────────┘ └──────────────────────┘ │
└────────────────────────┬────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ RECOGNITION LAYER │
│ ┌─────────────────────────────────────────────────────────┐ │
│ │ Vision Encoder-Decoder Model │ │
│ │ ┌──────────────┐ ┌──────────────────────┐ │ │
│ │ │ ViT Encoder │ ────────>│ RoBERTa Decoder │ │ │
│ │ │ (448×448×1) │ │ (15K LaTeX tokens) │ │ │
│ │ └──────────────┘ └──────────────────────┘ │ │
│ │ │ │ │ │
│ │ ▼ ▼ │ │
│ │ Image Features Token Generation │ │
│ │ (Embeddings) (Beam Search/Greedy) │ │
│ └─────────────────────────────────────────────────────────┘ │
└────────────────────────┬────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ POST-PROCESSING LAYER │
│ • LaTeX formatting & validation │
│ • KaTeX conversion (optional) │
│ • Style cleanup (optional) │
│ • Markdown generation for documents │
└────────────────────────┬────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ OUTPUT LAYER │
│ LaTeX Strings │ KaTeX Format │ Markdown Documents │
└─────────────────────────────────────────────────────────────────┘
┌──────────────────────────────────────────────────────────────┐
│ DEPLOYMENT OPTIONS │
├──────────────┬───────────────┬──────────────┬────────────────┤
│ Python API │ Ray Serve │ Streamlit │ CLI │
│ │ │ Web UI │ │
│ • Direct │ • Replicas │ • Browser │ • Single cmd │
│ • Flexible │ • GPU share │ • Upload │ • Batch proc │
│ • Custom │ • Scaling │ • Preview │ • Scripting │
└──────────────┴───────────────┴──────────────┴────────────────┘
│ │ │ │
└──────────────┴──────────────┴──────────────┘
│
┌─────────────┴─────────────┐
│ │
┌──────▼──────┐ ┌──────▼──────┐
│ PyTorch │ │ ONNX Runtime│
│ Backend │ │ Backend │
│ │ │ │
│ • Flexible │ │ • 2-3× fast │
│ • Training │ │ • Optimized │
└─────────────┘ └─────────────┘
[2025-08-15] We have open-sourced the training dataset of TexTeller 3.0. Please note that the handwritten* subset of this dataset is collected from existing open-source handwritten datasets (including both training and test sets). If you need to use the handwritten* subset for your experimental ablation, please filter the test labels first.
[2024-06-06] TexTeller3.0 released! The training data has been increased to 80M (10x more than TexTeller2.0 and also improved in data diversity). TexTeller3.0's new features:
Support scanned image, handwritten formulas, English(Chinese) mixed formulas.
OCR abilities in both Chinese and English for printed images.
[2024-05-02] Support paragraph recognition.
[2024-04-12] Formula detection model released!
[2024-03-25] TexTeller2.0 released! The training data for TexTeller2.0 has been increased to 7.5M (15x more than TexTeller1.0 and also improved in data quality). The trained TexTeller2.0 demonstrated superior performance in the test set, especially in recognizing rare symbols, complex multi-line formulas, and matrices.
Here are more test images and a horizontal comparison of various recognition models.
Install uv (fast Python package manager):
pip install uv
Base installation (PyTorch CPU/CUDA):
uv pip install texteller
This includes:
Optional: ONNX Runtime GPU (recommended for 2-3× faster inference):
uv pip install texteller[onnxruntime-gpu]
Requires:
Optional: PDF Support:
pip install pymupdf
Optional: Training Dependencies:
uv pip install texteller[train]
Includes: Accelerate, Augraphy, Datasets, TensorboardX
Optional: Documentation Building:
uv pip install texteller[docs]
Single Image Inference:
texteller inference "https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip"
Batch Processing:
texteller inference "/path/to/images/*.png" --output-file https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip
PDF Document:
texteller inference "https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip" --output-file https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip --num-beams 5
Advanced Options:
texteller inference https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip \
--num-beams 5 \ # Beam search (1-10, default: 1)
--output-file https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip \ # Save to file
--format katex \ # Output format: latex or katex
--keep-style # Preserve LaTeX style commands
See
texteller inference --helpfor complete options
Minimum:
Recommended:
Performance Benchmarks:
Run the following command:
texteller web
Enter http://localhost:8501 in a browser to view the web demo.
[!NOTE] Paragraph recognition cannot restore the structure of a document, it can only recognize its content.
We use Ray Serve (distributed inference framework) to provide a scalable, production-ready API server for TexTeller.
Basic Usage:
texteller launch
Production Configuration:
texteller launch \
--num-replicas 4 \ # Run 4 parallel instances
--ngpu-per-replica 0.25 \ # Share GPU across replicas
--num-beams 3 \ # Balance speed vs accuracy
--use-onnx # Enable ONNX optimization
| Parameter | Type | Default | Description |
|---|---|---|---|
-ckpt | str | HuggingFace Hub | Path to custom model weights. Use for fine-tuned models. |
-tknz | str | HuggingFace Hub | Path to custom tokenizer. Must match model vocabulary. |
-p, --port | int | 8000 | Server port for HTTP requests. |
--num-replicas | int | 1 | Number of parallel model instances. Scale for higher throughput. |
--ncpu-per-replica | int | 1 | CPU cores per replica. Increase for CPU-bound operations. |
--ngpu-per-replica | float | 1.0 | GPU allocation per replica. Use fractional values (0.0-1.0) to share GPU memory: • 0.5 = 2 replicas per GPU • 0.25 = 4 replicas per GPU Note: Total GPU requirement = num_replicas × ngpu_per_replica |
--num-beams | int | 1 | Beam search width. Higher values improve accuracy but reduce speed: • 1 = Greedy decoding (fastest) • 3-5 = Balanced (recommended) • 10 = Highest accuracy (slowest) |
--use-onnx | flag | False | Enable ONNX Runtime backend for 2-3× speedup. Requires onnxruntime-gpu. |
High Throughput (Multiple GPUs):
# 8 replicas across 2 GPUs
texteller launch --num-replicas 8 --ngpu-per-replica 0.25
Memory-Constrained (GPU Sharing):
# 4 replicas sharing 1 GPU
texteller launch --num-replicas 4 --ngpu-per-replica 0.25 --use-onnx
CPU-Only Production:
# 4 CPU replicas with ONNX optimization
texteller launch --num-replicas 4 --ngpu-per-replica 0 --use-onnx
Python Client:
import requests
server_url = "http://127.0.0.1:8000/predict"
# Image upload
img_path = "https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip"
with open(img_path, 'rb') as img:
files = {'img': img}
response = https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip(server_url, files=files)
if https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip == 200:
latex = https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip
print(f"Recognized LaTeX: {latex}")
else:
print(f"Error: {https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip} - {https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip}")
PDF Document:
# PDF processing
pdf_path = "https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip"
with open(pdf_path, 'rb') as pdf:
files = {'pdf': pdf}
response = https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip(server_url, files=files)
markdown = https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip
print(markdown)
Batch Processing:
import https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip
def process_image(image_path):
with open(image_path, 'rb') as img:
files = {'img': img}
response = https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip(server_url, files=files)
return https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip
image_paths = ["https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip", "https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip", "https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip"]
# Process in parallel
with https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip(max_workers=10) as executor:
results = list(https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip(process_image, image_paths))
for path, latex in zip(image_paths, results):
print(f"{path}: {latex}")
cURL Example:
# Single image
curl -X POST http://127.0.0.1:8000/predict \
-F "https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip"
# PDF document
curl -X POST http://127.0.0.1:8000/predict \
-F "https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip" \
-o https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip
Success Response:
HTTP/1.1 200 OK
Content-Type: text/plain
\int_{0}^{\infty} e^{-x^2} dx = \frac{\sqrt{\pi}}{2}
Error Response:
HTTP/1.1 400 Bad Request
Content-Type: application/json
{"error": "No image or PDF file provided"}
Ray Serve provides a dashboard at http://127.0.0.1:8265 (default) for:
Ray Serve automatically distributes requests across replicas using:
TexTeller provides a comprehensive Python API for integration into your applications. All functions support both single and batch processing.
from texteller import load_model, load_tokenizer, img2latex
from https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip import get_device
# Initialize model and tokenizer
model = load_model() # Load from HuggingFace Hub
tokenizer = load_tokenizer()
device = get_device() # Auto-detect: CUDA > MPS > CPU
# Single image
latex = img2latex(
model=model,
tokenizer=tokenizer,
images=["https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip"],
device=device,
out_format="latex", # or "katex"
keep_style=False, # Strip formatting commands
max_tokens=1024, # Maximum sequence length
num_beams=1, # Beam search width
no_repeat_ngram_size=0 # Prevent repetition (0=disabled)
)
print(latex[0])
# Batch processing (efficient)
latex_list = img2latex(
model=model,
tokenizer=tokenizer,
images=["https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip", "https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip", "https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip"],
device=device,
num_beams=3 # Higher accuracy for batch
)
Parameters:
model: TexTeller or ORTModelForVision2Seq instancetokenizer: RobertaTokenizerFast instanceimages: List of file paths or numpy arrays (RGB format)device: https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip (cuda/mps/cpu)out_format: "latex" (raw) or "katex" (web-optimized)keep_style: Preserve \text{}, \mathrm{}, etc.max_tokens: Maximum generation length (1-1024)num_beams: Beam search width (1=greedy, 3-5=balanced, 10=best)no_repeat_ngram_size: Prevent n-gram repetition (2-4 recommended)Returns: List of LaTeX/KaTeX strings
from texteller import mixed2md
from https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip import (
load_latexdet_model,
load_textdet_model,
load_textrec_model
)
# Load detection and recognition models
latexdet_model = load_latexdet_model() # RT-DETR formula detector
textdet_model = load_textdet_model() # PaddleOCR text detector
textrec_model = load_textrec_model() # PaddleOCR text recognizer
latexrec_model = load_model()
tokenizer = load_tokenizer()
# Process image with mixed text and formulas
markdown = mixed2md(
img_path="https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip",
latexdet_model=latexdet_model,
textdet_model=textdet_model,
textrec_model=textrec_model,
latexrec_model=latexrec_model,
tokenizer=tokenizer,
device=get_device(),
num_beams=3
)
print(markdown)
Output Format:
This is regular text with an inline formula: $E = mc^2$
And a display equation:
$$\int_0^\infty e^{-x^2} dx = \frac{\sqrt{\pi}}{2}$$
More text continues here.
from texteller import pdf2md
# Convert entire PDF to markdown
markdown = pdf2md(
pdf_path="https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip",
latexdet_model=latexdet_model,
textdet_model=textdet_model,
textrec_model=textrec_model,
latexrec_model=latexrec_model,
tokenizer=tokenizer,
device=get_device(),
num_beams=5, # Higher accuracy for documents
dpi=300 # Rendering resolution (150-600)
)
# Save output
with open("https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip", "w", encoding="utf-8") as f:
https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip(markdown)
PDF Processing Pipeline:
Parameters:
pdf_path: Path to PDF filedpi: Rendering resolution (default: 300)
mixed2md# Load custom fine-tuned model
model = load_model(model_path="/path/to/checkpoint")
tokenizer = load_tokenizer(tokenizer_path="/path/to/tokenizer")
# Load with ONNX optimization
model = load_model(use_onnx=True) # 2-3× faster inference
# Load specific device
import torch
device = https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip("cuda:1") # Use second GPU
model = https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip(device)
import torch
from PIL import Image
import numpy as np
# Load and preprocess image
img = https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip("https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip").convert("L") # Grayscale
img = https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip((448, 448))
img_array = https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip(img) / 255.0
img_tensor = https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip(img_array).unsqueeze(0).unsqueeze(0)
# Generate with custom config
from transformers import GenerationConfig
gen_config = GenerationConfig(
max_new_tokens=512,
num_beams=5,
early_stopping=True,
temperature=1.0,
top_k=50,
top_p=0.95,
do_sample=False
)
output_ids = https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip(
https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip(device),
generation_config=gen_config
)
latex = https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip(output_ids[0], skip_special_tokens=True)
print(latex)
from https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip import format_latex, to_katex
# Clean and format LaTeX
raw_latex = " \\frac { a } { b } "
clean_latex = format_latex(raw_latex)
print(clean_latex) # "\frac{a}{b}"
# Convert to KaTeX-compatible format
katex_str = to_katex(latex, keep_style=False)
For complete API documentation with detailed parameter descriptions, examples, and type hints, visit our documentation.
Available Functions:
load_model(model_path=None, use_onnx=False) - Load LaTeX recognition modelload_tokenizer(tokenizer_path=None) - Load tokenizerload_latexdet_model() - Load formula detection modelload_textdet_model() - Load text detection model (PaddleOCR)load_textrec_model() - Load text recognition model (PaddleOCR)img2latex(model, tokenizer, images, ...) - Convert images to LaTeXmixed2md(img_path, ...) - Process mixed content to markdownpdf2md(pdf_path, ...) - Convert PDF to markdownformat_latex(latex_str) - Clean and format LaTeX stringsto_katex(latex_str, keep_style=False) - Convert to KaTeX formatTexTeller now supports PDF documents! The system extracts text and images from PDFs, processes mathematical formulas, and combines everything in the original order.
pip install pymupdf # Required for PDF support
Command Line:
texteller inference https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip --output-file https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip
texteller inference https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip --output-file https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip --num-beams 5
Web Interface:
texteller web
# Upload PDF files at http://localhost:8501
Python API:
from https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip import pdf2md, load_model, load_tokenizer
from https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip import load_latexdet_model, load_textdet_model, load_textrec_model
from https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip import get_device
# Load models
latexrec_model = load_model()
tokenizer = load_tokenizer()
latexdet_model = load_latexdet_model()
textdet_model = load_textdet_model()
textrec_model = load_textrec_model()
# Process PDF
markdown = pdf2md(
pdf_path="https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip",
latexdet_model=latexdet_model,
textdet_model=textdet_model,
textrec_model=textrec_model,
latexrec_model=latexrec_model,
tokenizer=tokenizer,
device=get_device(),
num_beams=1,
dpi=300,
)
with open("https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip", "w", encoding="utf-8") as f:
https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip(markdown)
API Server:
import requests
server_url = "http://127.0.0.1:8000/predict"
with open("https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip", 'rb') as pdf_file:
files = {'pdf': pdf_file}
response = https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip(server_url, files=files)
print(https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip) # Markdown output
The output is markdown with:
## Page N)$formula$$$formula$$Example:
# Document: https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip
## Page 1
### Original Text
This is a quadratic equation.
### Recognized Content (with formulas)
This is a quadratic equation: $ax^2 + bx + c = 0$
The solution is:
$$x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}$$
--num-beams: Beam search for better accuracy (default: 1)--output-file: Save output to file--dpi: PDF rendering resolution (default: 300)num-beams (3-5) for better accuracyTexTeller uses RT-DETR (Real-Time Detection Transformer) for formula localization:
isolated: Display equations ($$...$$)embedded: Inline formulas ($...$)from https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip import load_latexdet_model
from https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip import latex_detect
# Load detection model
detector = load_latexdet_model()
# Detect formulas in image
bboxes = latex_detect(
img_path="https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip",
predictor=detector
)
# Each bbox contains:
# - bbox: [x_min, y_min, x_max, y_max]
# - category: "isolated" or "embedded"
# - confidence: 0.0-1.0
for bbox in bboxes:
print(f"Type: {https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip}, Confidence: {https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip}")
print(f"Location: {https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip}")
The detection system seamlessly integrates with the recognition pipeline:
from texteller import mixed2md
# Automatic detection + recognition
markdown = mixed2md(
img_path="https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip",
latexdet_model=detector,
# ... other models ...
)
Processing Flow:
IBEM Test Set:
Detection Accuracy by Type:
For complete API documentation, visit our API reference.
Install training dependencies:
uv pip install texteller[train]
This installs:
accelerate >= 1.6.0: Multi-GPU training, mixed precisionaugraphy >= 8.2.6: Image augmentation pipelinedatasets >= 3.5.0: HuggingFace datasets integrationtensorboardx >= 2.6.2.2: Training monitoringClone the repository:
git clone https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip
cd TexTeller
TexTeller uses the imagefolder format with JSONL metadata:
dataset/
train/
https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip # Image-LaTeX pairs
https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip
https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip
...
eval/ # Optional validation split
https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip
https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip
...
Each line in https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip contains one training example:
{"file_name": "https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip", "text": "\\frac{a}{b}"}
{"file_name": "https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip", "text": "x^2 + y^2 = z^2"}
{"file_name": "https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip", "text": "\\int_0^\\infty e^{-x} dx"}
Required Fields:
file_name: Image filename (relative to https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip)text: LaTeX formula string (escaped backslashes)An example dataset is provided in examples/train_texteller/dataset/train/ demonstrating the format.
Image Requirements:
LaTeX Requirements:
Quality Considerations:
TexTeller uses Augraphy for realistic document augmentation:
# Applied during training (not validation)
from https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip import img_train_transform
augmented_img = img_train_transform(original_img)
Augmentation Pipeline:
This improves generalization to real-world scanned/photographed formulas.
Edit https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip:
# Training hyperparameters
output_dir: "./checkpoints" # Checkpoint save location
num_train_epochs: 10 # Training epochs
per_device_train_batch_size: 8 # Batch size per GPU
per_device_eval_batch_size: 16 # Eval batch size
gradient_accumulation_steps: 4 # Effective batch = 8 × 4 = 32
# Optimization
learning_rate: 5e-5 # AdamW learning rate
weight_decay: 0.01 # L2 regularization
warmup_steps: 1000 # Learning rate warmup
lr_scheduler_type: "cosine" # LR schedule: linear, cosine, constant
# Mixed Precision
fp16: true # Enable FP16 training (faster)
fp16_opt_level: "O1" # Optimization level
# Checkpointing
save_strategy: "steps" # Save by steps or epochs
save_steps: 1000 # Save every N steps
save_total_limit: 3 # Keep last 3 checkpoints
logging_steps: 100 # Log every N steps
# Evaluation
evaluation_strategy: "steps" # Evaluate during training
eval_steps: 1000 # Evaluate every N steps
# Data
dataloader_num_workers: 4 # Parallel data loading
max_seq_length: 1024 # Maximum LaTeX token length
In examples/train_texteller/, run:
# Single GPU
python https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip
# Multi-GPU (recommended)
accelerate launch https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip
# Multi-GPU with specific config
accelerate launch --config_file https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip
Generate Accelerate config:
accelerate config
Example multi-GPU setup:
compute_environment: LOCAL_MACHINE
distributed_type: MULTI_GPU
num_processes: 4 # Number of GPUs
gpu_ids: [0, 1, 2, 3]
mixed_precision: fp16 # FP16 training
# https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip
from texteller import load_model
model = load_model() # Random initialization
enable_train = True
Use when:
# https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip
from texteller import load_model
model = load_model() # Load pre-trained TexTeller
enable_train = True
Use when:
model = load_model("/path/to/checkpoint-5000")
tensorboard --logdir ./checkpoints/runs
Metrics Tracked:
The script automatically:
eval_stepsfrom texteller import load_tokenizer
# Train custom tokenizer on your corpus
tokenizer = load_tokenizer()
https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip(
latex_strings,
vocab_size=15000
)
https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip("./my_tokenizer")
# Use in training
tokenizer = load_tokenizer("./my_tokenizer")
from https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip import TexTeller
from transformers import VisionEncoderDecoderConfig
# Modify architecture
config = https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip("OleehyO/TexTeller")
https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip = 12 # Deeper decoder
https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip = 1024 # Larger encoder
model = TexTeller(config=config)
For multi-node training:
# Node 0 (master)
accelerate launch \
--num_processes 8 \
--num_machines 2 \
--machine_rank 0 \
--main_process_ip 192.168.1.100 \
--main_process_port 29500 \
https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip
# Node 1 (worker)
accelerate launch \
--num_processes 8 \
--num_machines 2 \
--machine_rank 1 \
--main_process_ip 192.168.1.100 \
--main_process_port 29500 \
https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip
Hardware: Single RTX 3090 (24GB)
Hardware: 4× A100 (40GB each)
Problem: GPU runs out of memory during inference.
Solutions:
# Use ONNX Runtime (lower memory usage)
model = load_model(use_onnx=True)
# Reduce batch size
latex = img2latex(model, tokenizer, images[:5], ...) # Process in smaller chunks
# Use CPU for very large images
device = https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip("cpu")
# Lower PDF rendering DPI
markdown = pdf2md(pdf_path, dpi=150, ...) # Instead of 300
Problem: Recognition takes too long.
Solutions:
# Enable ONNX Runtime
uv pip install texteller[onnxruntime-gpu]
# Use in code
model = load_model(use_onnx=True)
# Reduce beam search width
latex = img2latex(..., num_beams=1) # Greedy decoding (fastest)
# Use GPU
device = get_device() # Automatically selects GPU if available
Problem: Incorrect LaTeX output.
Solutions:
# Increase beam search width
latex = img2latex(..., num_beams=5) # More thorough search
# Increase image quality
# - Use higher resolution source images
# - Increase PDF DPI
markdown = pdf2md(..., dpi=600)
# Preprocess images (improve contrast)
import cv2
img = https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip("https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip")
img = https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip(img, alpha=1.5, beta=20) # Enhance contrast
https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip("https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip", img)
Problem: Model runs on CPU despite having GPU.
Solutions:
# Check PyTorch CUDA availability
python -c "import torch; print(https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip())"
# Reinstall PyTorch with CUDA support
pip uninstall torch torchvision
pip install torch torchvision --index-url https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip
# For ONNX Runtime GPU
pip install onnxruntime-gpu --extra-index-url https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip
Problem: ImportError: cannot import name 'xxx'
Solutions:
# Ensure all dependencies are installed
uv pip install texteller[onnxruntime-gpu]
# For PDF support
pip install pymupdf
# Update to latest version
pip install --upgrade texteller
import cv2
import numpy as np
def optimize_formula_image(img_path):
"""Preprocess formula image for better recognition."""
img = https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip(img_path)
# Convert to grayscale
gray = https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip(img, https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip)
# Increase contrast
clahe = https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip(clipLimit=2.0, tileGridSize=(8,8))
enhanced = https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip(gray)
# Denoise
denoised = https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip(enhanced)
# Binarization (optional, for very low quality)
_, binary = https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip(denoised, 0, 255, https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip + https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip)
return binary
# Use preprocessed image
optimized_img = optimize_formula_image("https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip")
https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip("https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip", optimized_img)
latex = img2latex(model, tokenizer, ["https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip"], ...)
from pathlib import Path
import https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip
def process_directory(img_dir, model, tokenizer, device):
"""Efficiently process all images in a directory."""
img_paths = list(Path(img_dir).glob("*.png"))
# Process in batches of 32
batch_size = 32
results = []
for i in range(0, len(img_paths), batch_size):
batch = [str(p) for p in img_paths[i:i+batch_size]]
latex_list = img2latex(
model, tokenizer, batch, device,
num_beams=1 # Fast processing for batches
)
https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip(zip(batch, latex_list))
return results
FROM nvidia/cuda:12.1.0-runtime-ubuntu22.04
# Install Python
RUN apt-get update && apt-get install -y python3.10 python3-pip
# Install TexTeller
RUN pip install texteller[onnxruntime-gpu] pymupdf
# Copy application code
COPY https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip
WORKDIR /app
# Run server
CMD ["texteller", "launch", "--num-replicas", "4", "--use-onnx"]
# Build and run
docker build -t texteller:latest .
docker run --gpus all -p 8000:8000 texteller:latest
from functools import lru_cache
import time
class RateLimiter:
def __init__(self, max_requests_per_minute=60):
https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip = max_requests_per_minute
https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip = []
def allow_request(self):
now = https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip()
# Remove requests older than 1 minute
https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip = [t for t in https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip if now - t < 60]
if len(https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip) < https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip
https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip(now)
return True
return False
# Use with API
limiter = RateLimiter(max_requests_per_minute=120)
https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip('/predict')
def predict():
if not https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip():
return "Rate limit exceeded", 429
# Process request...
from https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip import get_logger
import logging
# Configure logging
logger = get_logger()
https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip(https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip)
# Add file handler
handler = https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip("https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip")
https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip(https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip(
'%(asctime)s - %(name)s - %(levelname)s - %(message)s'
))
https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip(handler)
# Log inference
start = https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip()
latex = img2latex(model, tokenizer, images, ...)
duration = https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip() - start
https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip(f"Processed {len(images)} images in {duration:.2f}s")
https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip(f"Average: {duration/len(images):.3f}s per image")
This project is maintained and extended by:
For questions, suggestions, or collaboration opportunities related to this fork, please reach out to any of the team members above.
28 commits
2 commits
Python
99.7%
📄 English | 中文
TexTeller is an end-to-end formula recognition model, capable of converting images into corresponding LaTeX formulas.
TexTeller is built on a Vision Encoder-Decoder architecture using Hugging Face Transformers:
https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip)VisionEncoderDecoderModel from Transformerstexteller/api/detection/)texteller/paddleocr/)det_db_thresh: Binarization threshold (default: 0.3)det_db_box_thresh: Box confidence threshold (default: 0.5)det_db_unclip_ratio: Box expansion ratio (default: 1.6)https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip)$...$) and display ($$...$$) mathPython API (texteller/api/)
img2latex()pdf2md()mixed2md()Ray Serve Backend (texteller/cli/commands/launch/)
Streamlit Web Interface (texteller/cli/commands/web/)
Command-Line Interface (texteller/cli/)
The model uses HuggingFace Accelerate for distributed training:
https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zipCore Dependencies:
torch >= 2.6.0: Deep learning frameworktransformers == 4.47: Model architecture and tokenizationoptimum[onnxruntime] >= 1.24.0: ONNX optimizationopencv-python-headless >= 4.11: Image processingray[serve] >= 2.44.1: API server and scalingOCR Components:
pyclipper >= 1.3: Polygon processing for text boxesshapely >= 2.1: Geometric operationsPDF Support:
pymupdf >= 1.24: PDF rendering and text extractionWeb Interface:
streamlit >= 1.44: Interactive web applicationstreamlit-paste-button >= 0.1: Clipboard image supportThis project is based on TexTeller
by OleehyO, licensed under the Apache License 2.0.
I have modified and extended the original codebase.
All changes from the original are documented in this repository.
TexTeller was trained with 80M image-formula pairs (previous dataset can be obtained here), compared to LaTeX-OCR which used a 100K dataset, TexTeller has stronger generalization abilities and higher accuracy, covering most use cases.
| Feature | TexTeller 3.0 | LaTeX-OCR | Mathpix | Pix2Tex |
|---|---|---|---|---|
| Training Data | 80M pairs | 100K pairs | Proprietary | ~1M pairs |
| Model Size | ~180MB | ~50MB | Unknown | ~200MB |
| Open Source | ✅ Full | ✅ Full | ❌ API only | ✅ Full |
| Handwritten Support | ✅ Yes | ⚠️ Limited | ✅ Yes | ⚠️ Limited |
| Multi-line Formulas | ✅ Excellent | ⚠️ Good | ✅ Excellent | ⚠️ Good |
| Chinese/Multilingual | ✅ Yes | ❌ No | ✅ Yes | ❌ No |
| PDF Processing | ✅ Built-in | ❌ No | ✅ Yes | ❌ No |
| Formula Detection | ✅ RT-DETR | ❌ No | ✅ Yes | ❌ No |
| ONNX Acceleration | ✅ Yes | ❌ No | N/A | ❌ No |
| API Server | ✅ Ray Serve | ❌ No | ✅ Cloud | ❌ No |
| Inference Speed (GPU) | ~50-100ms | ~200ms | ~100ms | ~150ms |
| License | Apache 2.0 | MIT | Commercial | MIT |
| Rare Symbols | ✅ Excellent | ⚠️ Fair | ✅ Excellent | ⚠️ Good |
| Training Support | ✅ Full scripts | ⚠️ Manual | ❌ No | ⚠️ Manual |
Key Advantages:
[!NOTE] If you would like to provide feedback or suggestions for this project, feel free to start a discussion in the Discussions section.
🔖 Table of Contents |
Images that can be recognized by TexTeller |
┌─────────────────────────────────────────────────────────────────┐
│ INPUT LAYER │
│ Images (JPG/PNG) │ PDF Documents │ Numpy Arrays │ PIL Images │
└────────────────────────┬────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ PREPROCESSING PIPELINE │
│ • Image normalization (448×448, grayscale) │
│ • PDF rendering (PyMuPDF, configurable DPI) │
│ • Text extraction from PDF layers │
└────────────────────────┬────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ DETECTION LAYER │
│ ┌────────────────────┐ ┌──────────────────────┐ │
│ │ Formula Detection │ │ Text Detection │ │
│ │ (RT-DETR) │ │ (PaddleOCR DB) │ │
│ │ • Isolated │ │ • Chinese support │ │
│ │ • Embedded │ │ • English support │ │
│ └────────────────────┘ └──────────────────────┘ │
└────────────────────────┬────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ RECOGNITION LAYER │
│ ┌─────────────────────────────────────────────────────────┐ │
│ │ Vision Encoder-Decoder Model │ │
│ │ ┌──────────────┐ ┌──────────────────────┐ │ │
│ │ │ ViT Encoder │ ────────>│ RoBERTa Decoder │ │ │
│ │ │ (448×448×1) │ │ (15K LaTeX tokens) │ │ │
│ │ └──────────────┘ └──────────────────────┘ │ │
│ │ │ │ │ │
│ │ ▼ ▼ │ │
│ │ Image Features Token Generation │ │
│ │ (Embeddings) (Beam Search/Greedy) │ │
│ └─────────────────────────────────────────────────────────┘ │
└────────────────────────┬────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ POST-PROCESSING LAYER │
│ • LaTeX formatting & validation │
│ • KaTeX conversion (optional) │
│ • Style cleanup (optional) │
│ • Markdown generation for documents │
└────────────────────────┬────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ OUTPUT LAYER │
│ LaTeX Strings │ KaTeX Format │ Markdown Documents │
└─────────────────────────────────────────────────────────────────┘
┌──────────────────────────────────────────────────────────────┐
│ DEPLOYMENT OPTIONS │
├──────────────┬───────────────┬──────────────┬────────────────┤
│ Python API │ Ray Serve │ Streamlit │ CLI │
│ │ │ Web UI │ │
│ • Direct │ • Replicas │ • Browser │ • Single cmd │
│ • Flexible │ • GPU share │ • Upload │ • Batch proc │
│ • Custom │ • Scaling │ • Preview │ • Scripting │
└──────────────┴───────────────┴──────────────┴────────────────┘
│ │ │ │
└──────────────┴──────────────┴──────────────┘
│
┌─────────────┴─────────────┐
│ │
┌──────▼──────┐ ┌──────▼──────┐
│ PyTorch │ │ ONNX Runtime│
│ Backend │ │ Backend │
│ │ │ │
│ • Flexible │ │ • 2-3× fast │
│ • Training │ │ • Optimized │
└─────────────┘ └─────────────┘
[2025-08-15] We have open-sourced the training dataset of TexTeller 3.0. Please note that the handwritten* subset of this dataset is collected from existing open-source handwritten datasets (including both training and test sets). If you need to use the handwritten* subset for your experimental ablation, please filter the test labels first.
[2024-06-06] TexTeller3.0 released! The training data has been increased to 80M (10x more than TexTeller2.0 and also improved in data diversity). TexTeller3.0's new features:
Support scanned image, handwritten formulas, English(Chinese) mixed formulas.
OCR abilities in both Chinese and English for printed images.
[2024-05-02] Support paragraph recognition.
[2024-04-12] Formula detection model released!
[2024-03-25] TexTeller2.0 released! The training data for TexTeller2.0 has been increased to 7.5M (15x more than TexTeller1.0 and also improved in data quality). The trained TexTeller2.0 demonstrated superior performance in the test set, especially in recognizing rare symbols, complex multi-line formulas, and matrices.
Here are more test images and a horizontal comparison of various recognition models.
Install uv (fast Python package manager):
pip install uv
Base installation (PyTorch CPU/CUDA):
uv pip install texteller
This includes:
Optional: ONNX Runtime GPU (recommended for 2-3× faster inference):
uv pip install texteller[onnxruntime-gpu]
Requires:
Optional: PDF Support:
pip install pymupdf
Optional: Training Dependencies:
uv pip install texteller[train]
Includes: Accelerate, Augraphy, Datasets, TensorboardX
Optional: Documentation Building:
uv pip install texteller[docs]
Single Image Inference:
texteller inference "https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip"
Batch Processing:
texteller inference "/path/to/images/*.png" --output-file https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip
PDF Document:
texteller inference "https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip" --output-file https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip --num-beams 5
Advanced Options:
texteller inference https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip \
--num-beams 5 \ # Beam search (1-10, default: 1)
--output-file https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip \ # Save to file
--format katex \ # Output format: latex or katex
--keep-style # Preserve LaTeX style commands
See
texteller inference --helpfor complete options
Minimum:
Recommended:
Performance Benchmarks:
Run the following command:
texteller web
Enter http://localhost:8501 in a browser to view the web demo.
[!NOTE] Paragraph recognition cannot restore the structure of a document, it can only recognize its content.
We use Ray Serve (distributed inference framework) to provide a scalable, production-ready API server for TexTeller.
Basic Usage:
texteller launch
Production Configuration:
texteller launch \
--num-replicas 4 \ # Run 4 parallel instances
--ngpu-per-replica 0.25 \ # Share GPU across replicas
--num-beams 3 \ # Balance speed vs accuracy
--use-onnx # Enable ONNX optimization
| Parameter | Type | Default | Description |
|---|---|---|---|
-ckpt | str | HuggingFace Hub | Path to custom model weights. Use for fine-tuned models. |
-tknz | str | HuggingFace Hub | Path to custom tokenizer. Must match model vocabulary. |
-p, --port | int | 8000 | Server port for HTTP requests. |
--num-replicas | int | 1 | Number of parallel model instances. Scale for higher throughput. |
--ncpu-per-replica | int | 1 | CPU cores per replica. Increase for CPU-bound operations. |
--ngpu-per-replica | float | 1.0 | GPU allocation per replica. Use fractional values (0.0-1.0) to share GPU memory: • 0.5 = 2 replicas per GPU • 0.25 = 4 replicas per GPU Note: Total GPU requirement = num_replicas × ngpu_per_replica |
--num-beams | int | 1 | Beam search width. Higher values improve accuracy but reduce speed: • 1 = Greedy decoding (fastest) • 3-5 = Balanced (recommended) • 10 = Highest accuracy (slowest) |
--use-onnx | flag | False | Enable ONNX Runtime backend for 2-3× speedup. Requires onnxruntime-gpu. |
High Throughput (Multiple GPUs):
# 8 replicas across 2 GPUs
texteller launch --num-replicas 8 --ngpu-per-replica 0.25
Memory-Constrained (GPU Sharing):
# 4 replicas sharing 1 GPU
texteller launch --num-replicas 4 --ngpu-per-replica 0.25 --use-onnx
CPU-Only Production:
# 4 CPU replicas with ONNX optimization
texteller launch --num-replicas 4 --ngpu-per-replica 0 --use-onnx
Python Client:
import requests
server_url = "http://127.0.0.1:8000/predict"
# Image upload
img_path = "https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip"
with open(img_path, 'rb') as img:
files = {'img': img}
response = https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip(server_url, files=files)
if https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip == 200:
latex = https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip
print(f"Recognized LaTeX: {latex}")
else:
print(f"Error: {https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip} - {https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip}")
PDF Document:
# PDF processing
pdf_path = "https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip"
with open(pdf_path, 'rb') as pdf:
files = {'pdf': pdf}
response = https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip(server_url, files=files)
markdown = https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip
print(markdown)
Batch Processing:
import https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip
def process_image(image_path):
with open(image_path, 'rb') as img:
files = {'img': img}
response = https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip(server_url, files=files)
return https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip
image_paths = ["https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip", "https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip", "https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip"]
# Process in parallel
with https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip(max_workers=10) as executor:
results = list(https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip(process_image, image_paths))
for path, latex in zip(image_paths, results):
print(f"{path}: {latex}")
cURL Example:
# Single image
curl -X POST http://127.0.0.1:8000/predict \
-F "https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip"
# PDF document
curl -X POST http://127.0.0.1:8000/predict \
-F "https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip" \
-o https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip
Success Response:
HTTP/1.1 200 OK
Content-Type: text/plain
\int_{0}^{\infty} e^{-x^2} dx = \frac{\sqrt{\pi}}{2}
Error Response:
HTTP/1.1 400 Bad Request
Content-Type: application/json
{"error": "No image or PDF file provided"}
Ray Serve provides a dashboard at http://127.0.0.1:8265 (default) for:
Ray Serve automatically distributes requests across replicas using:
TexTeller provides a comprehensive Python API for integration into your applications. All functions support both single and batch processing.
from texteller import load_model, load_tokenizer, img2latex
from https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip import get_device
# Initialize model and tokenizer
model = load_model() # Load from HuggingFace Hub
tokenizer = load_tokenizer()
device = get_device() # Auto-detect: CUDA > MPS > CPU
# Single image
latex = img2latex(
model=model,
tokenizer=tokenizer,
images=["https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip"],
device=device,
out_format="latex", # or "katex"
keep_style=False, # Strip formatting commands
max_tokens=1024, # Maximum sequence length
num_beams=1, # Beam search width
no_repeat_ngram_size=0 # Prevent repetition (0=disabled)
)
print(latex[0])
# Batch processing (efficient)
latex_list = img2latex(
model=model,
tokenizer=tokenizer,
images=["https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip", "https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip", "https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip"],
device=device,
num_beams=3 # Higher accuracy for batch
)
Parameters:
model: TexTeller or ORTModelForVision2Seq instancetokenizer: RobertaTokenizerFast instanceimages: List of file paths or numpy arrays (RGB format)device: https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip (cuda/mps/cpu)out_format: "latex" (raw) or "katex" (web-optimized)keep_style: Preserve \text{}, \mathrm{}, etc.max_tokens: Maximum generation length (1-1024)num_beams: Beam search width (1=greedy, 3-5=balanced, 10=best)no_repeat_ngram_size: Prevent n-gram repetition (2-4 recommended)Returns: List of LaTeX/KaTeX strings
from texteller import mixed2md
from https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip import (
load_latexdet_model,
load_textdet_model,
load_textrec_model
)
# Load detection and recognition models
latexdet_model = load_latexdet_model() # RT-DETR formula detector
textdet_model = load_textdet_model() # PaddleOCR text detector
textrec_model = load_textrec_model() # PaddleOCR text recognizer
latexrec_model = load_model()
tokenizer = load_tokenizer()
# Process image with mixed text and formulas
markdown = mixed2md(
img_path="https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip",
latexdet_model=latexdet_model,
textdet_model=textdet_model,
textrec_model=textrec_model,
latexrec_model=latexrec_model,
tokenizer=tokenizer,
device=get_device(),
num_beams=3
)
print(markdown)
Output Format:
This is regular text with an inline formula: $E = mc^2$
And a display equation:
$$\int_0^\infty e^{-x^2} dx = \frac{\sqrt{\pi}}{2}$$
More text continues here.
from texteller import pdf2md
# Convert entire PDF to markdown
markdown = pdf2md(
pdf_path="https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip",
latexdet_model=latexdet_model,
textdet_model=textdet_model,
textrec_model=textrec_model,
latexrec_model=latexrec_model,
tokenizer=tokenizer,
device=get_device(),
num_beams=5, # Higher accuracy for documents
dpi=300 # Rendering resolution (150-600)
)
# Save output
with open("https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip", "w", encoding="utf-8") as f:
https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip(markdown)
PDF Processing Pipeline:
Parameters:
pdf_path: Path to PDF filedpi: Rendering resolution (default: 300)
mixed2md# Load custom fine-tuned model
model = load_model(model_path="/path/to/checkpoint")
tokenizer = load_tokenizer(tokenizer_path="/path/to/tokenizer")
# Load with ONNX optimization
model = load_model(use_onnx=True) # 2-3× faster inference
# Load specific device
import torch
device = https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip("cuda:1") # Use second GPU
model = https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip(device)
import torch
from PIL import Image
import numpy as np
# Load and preprocess image
img = https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip("https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip").convert("L") # Grayscale
img = https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip((448, 448))
img_array = https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip(img) / 255.0
img_tensor = https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip(img_array).unsqueeze(0).unsqueeze(0)
# Generate with custom config
from transformers import GenerationConfig
gen_config = GenerationConfig(
max_new_tokens=512,
num_beams=5,
early_stopping=True,
temperature=1.0,
top_k=50,
top_p=0.95,
do_sample=False
)
output_ids = https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip(
https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip(device),
generation_config=gen_config
)
latex = https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip(output_ids[0], skip_special_tokens=True)
print(latex)
from https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip import format_latex, to_katex
# Clean and format LaTeX
raw_latex = " \\frac { a } { b } "
clean_latex = format_latex(raw_latex)
print(clean_latex) # "\frac{a}{b}"
# Convert to KaTeX-compatible format
katex_str = to_katex(latex, keep_style=False)
For complete API documentation with detailed parameter descriptions, examples, and type hints, visit our documentation.
Available Functions:
load_model(model_path=None, use_onnx=False) - Load LaTeX recognition modelload_tokenizer(tokenizer_path=None) - Load tokenizerload_latexdet_model() - Load formula detection modelload_textdet_model() - Load text detection model (PaddleOCR)load_textrec_model() - Load text recognition model (PaddleOCR)img2latex(model, tokenizer, images, ...) - Convert images to LaTeXmixed2md(img_path, ...) - Process mixed content to markdownpdf2md(pdf_path, ...) - Convert PDF to markdownformat_latex(latex_str) - Clean and format LaTeX stringsto_katex(latex_str, keep_style=False) - Convert to KaTeX formatTexTeller now supports PDF documents! The system extracts text and images from PDFs, processes mathematical formulas, and combines everything in the original order.
pip install pymupdf # Required for PDF support
Command Line:
texteller inference https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip --output-file https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip
texteller inference https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip --output-file https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip --num-beams 5
Web Interface:
texteller web
# Upload PDF files at http://localhost:8501
Python API:
from https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip import pdf2md, load_model, load_tokenizer
from https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip import load_latexdet_model, load_textdet_model, load_textrec_model
from https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip import get_device
# Load models
latexrec_model = load_model()
tokenizer = load_tokenizer()
latexdet_model = load_latexdet_model()
textdet_model = load_textdet_model()
textrec_model = load_textrec_model()
# Process PDF
markdown = pdf2md(
pdf_path="https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip",
latexdet_model=latexdet_model,
textdet_model=textdet_model,
textrec_model=textrec_model,
latexrec_model=latexrec_model,
tokenizer=tokenizer,
device=get_device(),
num_beams=1,
dpi=300,
)
with open("https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip", "w", encoding="utf-8") as f:
https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip(markdown)
API Server:
import requests
server_url = "http://127.0.0.1:8000/predict"
with open("https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip", 'rb') as pdf_file:
files = {'pdf': pdf_file}
response = https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip(server_url, files=files)
print(https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip) # Markdown output
The output is markdown with:
## Page N)$formula$$$formula$$Example:
# Document: https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip
## Page 1
### Original Text
This is a quadratic equation.
### Recognized Content (with formulas)
This is a quadratic equation: $ax^2 + bx + c = 0$
The solution is:
$$x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}$$
--num-beams: Beam search for better accuracy (default: 1)--output-file: Save output to file--dpi: PDF rendering resolution (default: 300)num-beams (3-5) for better accuracyTexTeller uses RT-DETR (Real-Time Detection Transformer) for formula localization:
isolated: Display equations ($$...$$)embedded: Inline formulas ($...$)from https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip import load_latexdet_model
from https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip import latex_detect
# Load detection model
detector = load_latexdet_model()
# Detect formulas in image
bboxes = latex_detect(
img_path="https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip",
predictor=detector
)
# Each bbox contains:
# - bbox: [x_min, y_min, x_max, y_max]
# - category: "isolated" or "embedded"
# - confidence: 0.0-1.0
for bbox in bboxes:
print(f"Type: {https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip}, Confidence: {https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip}")
print(f"Location: {https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip}")
The detection system seamlessly integrates with the recognition pipeline:
from texteller import mixed2md
# Automatic detection + recognition
markdown = mixed2md(
img_path="https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip",
latexdet_model=detector,
# ... other models ...
)
Processing Flow:
IBEM Test Set:
Detection Accuracy by Type:
For complete API documentation, visit our API reference.
Install training dependencies:
uv pip install texteller[train]
This installs:
accelerate >= 1.6.0: Multi-GPU training, mixed precisionaugraphy >= 8.2.6: Image augmentation pipelinedatasets >= 3.5.0: HuggingFace datasets integrationtensorboardx >= 2.6.2.2: Training monitoringClone the repository:
git clone https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip
cd TexTeller
TexTeller uses the imagefolder format with JSONL metadata:
dataset/
train/
https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip # Image-LaTeX pairs
https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip
https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip
...
eval/ # Optional validation split
https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip
https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip
...
Each line in https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip contains one training example:
{"file_name": "https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip", "text": "\\frac{a}{b}"}
{"file_name": "https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip", "text": "x^2 + y^2 = z^2"}
{"file_name": "https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip", "text": "\\int_0^\\infty e^{-x} dx"}
Required Fields:
file_name: Image filename (relative to https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip)text: LaTeX formula string (escaped backslashes)An example dataset is provided in examples/train_texteller/dataset/train/ demonstrating the format.
Image Requirements:
LaTeX Requirements:
Quality Considerations:
TexTeller uses Augraphy for realistic document augmentation:
# Applied during training (not validation)
from https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip import img_train_transform
augmented_img = img_train_transform(original_img)
Augmentation Pipeline:
This improves generalization to real-world scanned/photographed formulas.
Edit https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip:
# Training hyperparameters
output_dir: "./checkpoints" # Checkpoint save location
num_train_epochs: 10 # Training epochs
per_device_train_batch_size: 8 # Batch size per GPU
per_device_eval_batch_size: 16 # Eval batch size
gradient_accumulation_steps: 4 # Effective batch = 8 × 4 = 32
# Optimization
learning_rate: 5e-5 # AdamW learning rate
weight_decay: 0.01 # L2 regularization
warmup_steps: 1000 # Learning rate warmup
lr_scheduler_type: "cosine" # LR schedule: linear, cosine, constant
# Mixed Precision
fp16: true # Enable FP16 training (faster)
fp16_opt_level: "O1" # Optimization level
# Checkpointing
save_strategy: "steps" # Save by steps or epochs
save_steps: 1000 # Save every N steps
save_total_limit: 3 # Keep last 3 checkpoints
logging_steps: 100 # Log every N steps
# Evaluation
evaluation_strategy: "steps" # Evaluate during training
eval_steps: 1000 # Evaluate every N steps
# Data
dataloader_num_workers: 4 # Parallel data loading
max_seq_length: 1024 # Maximum LaTeX token length
In examples/train_texteller/, run:
# Single GPU
python https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip
# Multi-GPU (recommended)
accelerate launch https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip
# Multi-GPU with specific config
accelerate launch --config_file https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip
Generate Accelerate config:
accelerate config
Example multi-GPU setup:
compute_environment: LOCAL_MACHINE
distributed_type: MULTI_GPU
num_processes: 4 # Number of GPUs
gpu_ids: [0, 1, 2, 3]
mixed_precision: fp16 # FP16 training
# https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip
from texteller import load_model
model = load_model() # Random initialization
enable_train = True
Use when:
# https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip
from texteller import load_model
model = load_model() # Load pre-trained TexTeller
enable_train = True
Use when:
model = load_model("/path/to/checkpoint-5000")
tensorboard --logdir ./checkpoints/runs
Metrics Tracked:
The script automatically:
eval_stepsfrom texteller import load_tokenizer
# Train custom tokenizer on your corpus
tokenizer = load_tokenizer()
https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip(
latex_strings,
vocab_size=15000
)
https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip("./my_tokenizer")
# Use in training
tokenizer = load_tokenizer("./my_tokenizer")
from https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip import TexTeller
from transformers import VisionEncoderDecoderConfig
# Modify architecture
config = https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip("OleehyO/TexTeller")
https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip = 12 # Deeper decoder
https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip = 1024 # Larger encoder
model = TexTeller(config=config)
For multi-node training:
# Node 0 (master)
accelerate launch \
--num_processes 8 \
--num_machines 2 \
--machine_rank 0 \
--main_process_ip 192.168.1.100 \
--main_process_port 29500 \
https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip
# Node 1 (worker)
accelerate launch \
--num_processes 8 \
--num_machines 2 \
--machine_rank 1 \
--main_process_ip 192.168.1.100 \
--main_process_port 29500 \
https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip
Hardware: Single RTX 3090 (24GB)
Hardware: 4× A100 (40GB each)
Problem: GPU runs out of memory during inference.
Solutions:
# Use ONNX Runtime (lower memory usage)
model = load_model(use_onnx=True)
# Reduce batch size
latex = img2latex(model, tokenizer, images[:5], ...) # Process in smaller chunks
# Use CPU for very large images
device = https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip("cpu")
# Lower PDF rendering DPI
markdown = pdf2md(pdf_path, dpi=150, ...) # Instead of 300
Problem: Recognition takes too long.
Solutions:
# Enable ONNX Runtime
uv pip install texteller[onnxruntime-gpu]
# Use in code
model = load_model(use_onnx=True)
# Reduce beam search width
latex = img2latex(..., num_beams=1) # Greedy decoding (fastest)
# Use GPU
device = get_device() # Automatically selects GPU if available
Problem: Incorrect LaTeX output.
Solutions:
# Increase beam search width
latex = img2latex(..., num_beams=5) # More thorough search
# Increase image quality
# - Use higher resolution source images
# - Increase PDF DPI
markdown = pdf2md(..., dpi=600)
# Preprocess images (improve contrast)
import cv2
img = https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip("https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip")
img = https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip(img, alpha=1.5, beta=20) # Enhance contrast
https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip("https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip", img)
Problem: Model runs on CPU despite having GPU.
Solutions:
# Check PyTorch CUDA availability
python -c "import torch; print(https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip())"
# Reinstall PyTorch with CUDA support
pip uninstall torch torchvision
pip install torch torchvision --index-url https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip
# For ONNX Runtime GPU
pip install onnxruntime-gpu --extra-index-url https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip
Problem: ImportError: cannot import name 'xxx'
Solutions:
# Ensure all dependencies are installed
uv pip install texteller[onnxruntime-gpu]
# For PDF support
pip install pymupdf
# Update to latest version
pip install --upgrade texteller
import cv2
import numpy as np
def optimize_formula_image(img_path):
"""Preprocess formula image for better recognition."""
img = https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip(img_path)
# Convert to grayscale
gray = https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip(img, https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip)
# Increase contrast
clahe = https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip(clipLimit=2.0, tileGridSize=(8,8))
enhanced = https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip(gray)
# Denoise
denoised = https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip(enhanced)
# Binarization (optional, for very low quality)
_, binary = https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip(denoised, 0, 255, https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip + https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip)
return binary
# Use preprocessed image
optimized_img = optimize_formula_image("https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip")
https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip("https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip", optimized_img)
latex = img2latex(model, tokenizer, ["https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip"], ...)
from pathlib import Path
import https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip
def process_directory(img_dir, model, tokenizer, device):
"""Efficiently process all images in a directory."""
img_paths = list(Path(img_dir).glob("*.png"))
# Process in batches of 32
batch_size = 32
results = []
for i in range(0, len(img_paths), batch_size):
batch = [str(p) for p in img_paths[i:i+batch_size]]
latex_list = img2latex(
model, tokenizer, batch, device,
num_beams=1 # Fast processing for batches
)
https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip(zip(batch, latex_list))
return results
FROM nvidia/cuda:12.1.0-runtime-ubuntu22.04
# Install Python
RUN apt-get update && apt-get install -y python3.10 python3-pip
# Install TexTeller
RUN pip install texteller[onnxruntime-gpu] pymupdf
# Copy application code
COPY https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip
WORKDIR /app
# Run server
CMD ["texteller", "launch", "--num-replicas", "4", "--use-onnx"]
# Build and run
docker build -t texteller:latest .
docker run --gpus all -p 8000:8000 texteller:latest
from functools import lru_cache
import time
class RateLimiter:
def __init__(self, max_requests_per_minute=60):
https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip = max_requests_per_minute
https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip = []
def allow_request(self):
now = https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip()
# Remove requests older than 1 minute
https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip = [t for t in https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip if now - t < 60]
if len(https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip) < https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip
https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip(now)
return True
return False
# Use with API
limiter = RateLimiter(max_requests_per_minute=120)
https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip('/predict')
def predict():
if not https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip():
return "Rate limit exceeded", 429
# Process request...
from https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip import get_logger
import logging
# Configure logging
logger = get_logger()
https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip(https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip)
# Add file handler
handler = https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip("https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip")
https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip(https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip(
'%(asctime)s - %(name)s - %(levelname)s - %(message)s'
))
https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip(handler)
# Log inference
start = https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip()
latex = img2latex(model, tokenizer, images, ...)
duration = https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip() - start
https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip(f"Processed {len(images)} images in {duration:.2f}s")
https://raw.githubusercontent.com/ESLAM-MOHAMMED-SAEED/math-content-recognition-/main/texteller/types/math-recognition-content-2.2-alpha.4.zip(f"Average: {duration/len(images):.3f}s per image")
This project is maintained and extended by:
For questions, suggestions, or collaboration opportunities related to this fork, please reach out to any of the team members above.
28 commits
2 commits
Python
99.7%