---
comments: true
---
# Formula Recognition Pipeline User Guide
## 1. Introduction to Formula Recognition Pipeline
Formula recognition is a technology that automatically identifies and extracts LaTeX formula content and structure from documents or images. It is widely used in fields such as mathematics, physics, and computer science for document editing and data analysis. By using computer vision and machine learning algorithms, formula recognition can convert complex mathematical formula information into editable LaTeX format, facilitating further processing and analysis of data.
The formula recognition pipeline is designed to solve formula recognition tasks by extracting formula information from images and outputting it in LaTeX source code format. This pipeline integrates the advanced formula recognition model PP-FormulaNet developed by the PaddlePaddle Vision Team and the well-known formula recognition model UniMERNet. It is an end-to-end formula recognition system that supports the recognition of simple printed formulas, complex printed formulas, and handwritten formulas. Additionally, it includes functions for image orientation correction and distortion correction. Based on this pipeline, precise formula content prediction can be achieved, covering various application scenarios in education, research, finance, manufacturing, and other fields. The pipeline also provides flexible deployment options, supporting multiple hardware devices and programming languages. Moreover, it offers the capability for secondary development. You can train and optimize the pipeline on your own dataset, and the trained model can be seamlessly integrated.
The formula recognition pipeline includes a mandatory formula recognition module, as well as optional layout detection, document image orientation classification, and text image unwarping modules. The document image orientation classification module and the text image unwarping module are integrated into the formula recognition pipeline as a document preprocessing sub-pipeline. Each module contains multiple models, and you can choose the model based on the benchmark test data below.
If you prioritize model accuracy, choose a model with higher precision; if you care more about inference speed, choose a faster model; if you are concerned about model storage size, choose a smaller model.
Document Image Orientation Classification Module (Optional):
| Model | Model Download Link | Top-1 Acc (%) | GPU Inference Time (ms) | CPU Inference Time (ms) | Model Storage Size (M) | Introduction |
|---|---|---|---|---|---|---|
| PP-LCNet_x1_0_doc_ori | Inference Model/Training Model | 99.06 | 3.84845 | 9.23735 | 7 | A document image classification model based on PP-LCNet_x1_0, with four categories: 0 degrees, 90 degrees, 180 degrees, and 270 degrees. |
Text Image Correction Module (Optional):
| Model | Model Download Link | CER | Model Storage Size (M) | Introduction |
|---|---|---|---|---|
| UVDoc | Inference Model/Training Model | 0.179 | 30.3 M | High-precision text image correction model |
Layout Detection Module (Optional):
| Model | Model Download Link | mAP(0.5) (%) | GPU Inference Time (ms) | CPU Inference Time (ms) | Model Storage Size (M) | Introduction |
|---|---|---|---|---|---|---|
| PP-DocLayout-L | Inference Model/Training Model | 90.4 | 34.5252 | 1454.27 | 123.76 M | A high-precision layout area localization model trained on a self-built dataset containing Chinese and English papers, magazines, contracts, books, exams, and research reports using RT-DETR-L. |
| PP-DocLayout-M | Inference Model/Training Model | 75.2 | 15.9 | 160.1 | 22.578 | A layout area localization model with balanced precision and efficiency, trained on a self-built dataset containing Chinese and English papers, magazines, contracts, books, exams, and research reports using PicoDet-L. |
| PP-DocLayout-S | Inference Model/Training Model | 70.9 | 13.8 | 46.7 | 4.834 | A high-efficiency layout area localization model trained on a self-built dataset containing Chinese and English papers, magazines, contracts, books, exams, and research reports using PicoDet-S. |
| Model | Model Download Link | mAP(0.5) (%) | GPU Inference Time (ms) | CPU Inference Time (ms) | Model Storage Size (M) | Introduction |
|---|---|---|---|---|---|---|
| PicoDet_layout_1x_table | Inference Model/Training Model | 97.5 | 12.623 | 90.8934 | 7.4 M | A high-efficiency layout area localization model trained on a self-built dataset using PicoDet-1x, capable of detecting table regions. |
| Model | Model Download Link | mAP(0.5) (%) | GPU Inference Time (ms) | CPU Inference Time (ms) | Model Storage Size (M) | Introduction |
|---|---|---|---|---|---|---|
| PicoDet-S_layout_3cls | Inference Model/Training Model | 88.2 | 13.5 | 45.8 | 4.8 | A high-efficiency layout area localization model trained on a self-built dataset of Chinese and English papers, magazines, and research reports using PicoDet-S. |
| PicoDet-L_layout_3cls | Inference Model/Training Model | 89.0 | 15.7 | 159.8 | 22.6 | A balanced efficiency and precision layout area localization model trained on a self-built dataset of Chinese and English papers, magazines, and research reports using PicoDet-L. |
| RT-DETR-H_layout_3cls | Inference Model/Training Model | 95.8 | 114.6 | 3832.6 | 470.1 | A high-precision layout area localization model trained on a self-built dataset of Chinese and English papers, magazines, and research reports using RT-DETR-H. |
| Model | Model Download Link | mAP(0.5) (%) | GPU Inference Time (ms) | CPU Inference Time (ms) | Model Storage Size (M) | Introduction |
|---|---|---|---|---|---|---|
| PicoDet_layout_1x | Inference Model/Training Model | 97.8 | 13.0 | 91.3 | 7.4 | A high-efficiency English document layout area localization model trained on the PubLayNet dataset using PicoDet-1x. |
| Model | Model Download Link | mAP(0.5) (%) | GPU Inference Time (ms) | CPU Inference Time (ms) | Model Storage Size (M) | Introduction |
|---|---|---|---|---|---|---|
| PicoDet-S_layout_17cls | Inference Model/Training Model | 87.4 | 13.6 | 46.2 | 4.8 | A high-efficiency layout area localization model trained on a self-built dataset of Chinese and English papers, magazines, and research reports using PicoDet-S. |
| PicoDet-L_layout_17cls | Inference Model/Training Model | 89.0 | 17.2 | 160.2 | 22.6 | A balanced efficiency and precision layout area localization model trained on a self-built dataset of Chinese and English papers, magazines, and research reports using PicoDet-L. |
| RT-DETR-H_layout_17cls | Inference Model/Training Model | 98.3 | 115.1 | 3827.2 | 470.2 | A high-precision layout area localization model trained on a self-built dataset of Chinese and English papers, magazines, and research reports using RT-DETR-H. |
Formula Recognition Module
| Model | Model Download Link | Avg-BLEU(%) | GPU Inference Time (ms) | Model Storage Size (M) | Introduction | UniMERNet | Inference Model/Training Model | 86.13 | 2266.96 | 1.4 G | UniMERNet is a formula recognition model developed by Shanghai AI Lab. It uses Donut Swin as the encoder and MBartDecoder as the decoder. The model is trained on a dataset of one million samples, including simple formulas, complex formulas, scanned formulas, and handwritten formulas, significantly improving the recognition accuracy of real-world formulas. |
|---|---|---|---|---|---|
| PP-FormulaNet-S | Inference Model/Training Model | 87.12 | 202.25 | 167.9 M | PP-FormulaNet is an advanced formula recognition model developed by the Baidu PaddlePaddle Vision Team. The PP-FormulaNet-S version uses PP-HGNetV2-B4 as its backbone network. Through parallel masking and model distillation techniques, it significantly improves inference speed while maintaining high recognition accuracy, making it suitable for applications requiring fast inference. The PP-FormulaNet-L version, on the other hand, uses Vary_VIT_B as its backbone network and is trained on a large-scale formula dataset, showing significant improvements in recognizing complex formulas compared to PP-FormulaNet-S. | PP-FormulaNet-L | Inference Model/Training Model | 92.13 | 1976.52 | 535.2 M |
| LaTeX_OCR_rec | Inference Model/Training Model | 71.63 | - | 89.7 M | LaTeX-OCR is a formula recognition algorithm based on an autoregressive large model. It uses Hybrid ViT as the backbone network and a transformer as the decoder, significantly improving the accuracy of formula recognition. |
If you need to visualize the formula recognition pipeline, you need to run the following command to install the LaTeX rendering environment. Currently, visualization of the formula recognition pipeline only supports the Ubuntu environment, and other environments are not supported. For complex formulas, the LaTeX result may contain some advanced representations that may not be successfully displayed in environments such as Markdown:
```bash
sudo apt-get update
sudo apt-get install texlive texlive-latex-base texlive-latex-extra -y
```
Note: Due to the need to render each formula image during the formula recognition visualization process, the process takes a long time. Please be patient.
### 2.2 Integration via Python Script
A few lines of code can quickly complete the production line inference. Taking the formula recognition production line as an example:
```python
from paddlex import create_pipeline
pipeline = create_pipeline(pipeline="formula_recognition")
output = pipeline.predict(
input="./general_formula_recognition_001.png",
use_layout_detection=True ,
use_doc_orientation_classify=False,
use_doc_unwarping=False,
layout_threshold=0.5,
layout_nms=True,
layout_unclip_ratio=1.0,
layout_merge_bboxes_mode="large"
)
for res in output:
res.print()
res.save_to_img(save_path="./output/")
res.save_to_json(save_path="./output/")
```
In the above Python script, the following steps are executed:
(1) Instantiate the formula recognition pipeline object through `create_pipeline()`, with specific parameters as follows:
| Parameter | Description | Type | Default |
|---|---|---|---|
pipeline |
Pipeline name or path to pipeline config file, if it's set as a pipeline name, it must be a pipeline supported by PaddleX. | str |
None |
config |
Specific configuration information for the pipeline (if set simultaneously with the pipeline, it takes precedence over the pipeline, and the pipeline name must match the pipeline).
|
dict[str, Any] |
None |
device |
Pipeline inference device. Supports specifying the specific GPU card number, such as "gpu:0", other hardware specific card numbers, such as "npu:0", CPU such as "cpu". | str |
None |
use_hpip |
Whether to enable high-performance inference, only available when the pipeline supports high-performance inference. | bool |
False |
| Parameter | Description | Type | Options | Default Value |
|---|---|---|---|---|
input |
Data to be predicted, supporting multiple input types, required | Python Var|str|list |
|
None |
device |
Production line inference device | str|None |
|
None |
use_layout_detection |
Whether to use the document layout detection module | bool|None |
|
None |
use_doc_orientation_classify |
Whether to use the document orientation classification module | bool|None |
|
None |
use_doc_unwarping |
Whether to use the document unwarping module | bool|None |
|
None |
layout_threshold |
Threshold for filtering low-confidence prediction results; if not specified, the default PaddleX official model configuration will be used | float/dict/None |
|
None |
layout_nms |
Whether to use NMS post-processing to filter overlapping bounding boxes; if not specified, the default PaddleX official model configuration will be used | bool/None |
|
None |
layout_unclip_ratio |
Scaling factor for the side length of bounding boxes; if not specified, the default PaddleX official model configuration will be used | float/list/None |
|
None |
layout_merge_bboxes_mode |
Merging mode for the bounding boxes output by the model; if not specified, the default PaddleX official model configuration will be used | string/None |
|
None |
| Method | Description | Parameter | Parameter Type | Parameter Description | Default Value |
|---|---|---|---|---|---|
print() |
Print results to terminal | format_json |
bool |
Whether to format the output content using JSON indentation |
True |
indent |
int |
Specify the indentation level to beautify the output JSON data, making it more readable. Effective only when format_json is True |
4 | ||
ensure_ascii |
bool |
Control whether to escape non-ASCII characters to Unicode. When set to True, all non-ASCII characters will be escaped; False retains the original characters. Effective only when format_json is True |
False |
||
save_to_json() |
Save results as a JSON file | save_path |
str |
Path to save the file. If it is a directory, the saved file will be named the same as the input file type | None |
indent |
int |
Specify the indentation level to beautify the output JSON data, making it more readable. Effective only when format_json is True |
4 | ||
ensure_ascii |
bool |
Control whether to escape non-ASCII characters to Unicode. When set to True, all non-ASCII characters will be escaped; False retains the original characters. Effective only when format_json is True |
False |
||
save_to_img() |
Save results as an image file | save_path |
str |
Path to save the file, supports directory or file path | None |
| Attribute | Attribute Description |
|---|---|
json |
Get the prediction results in json format |
img |
Get the visualization image in dict format |
For the main operations provided by the service:
200, and the attributes of the response body are as follows:| Name | Type | Meaning |
|---|---|---|
logId |
string |
The UUID of the request. |
errorCode |
integer |
Error code. Fixed as 0. |
errorMsg |
string |
Error message. Fixed as "Success". |
result |
object |
The result of the operation. |
| Name | Type | Meaning |
|---|---|---|
logId |
string |
The UUID of the request. |
errorCode |
integer |
Error code. Same as the response status code. |
errorMsg |
string |
Error message. |
The main operations provided by the service are as follows:
inferGet the formula recognition result of an image.
POST /formula-recognition
| Name | Type | Meaning | Required |
|---|---|---|---|
file |
string |
The URL of an image or PDF file accessible by the server, or the Base64-encoded content of the above file types. For PDF files exceeding 10 pages, only the content of the first 10 pages will be used. | Yes |
fileType |
integer |
The type of the file. 0 indicates a PDF file, and 1 indicates an image file. If this attribute is missing in the request body, the file type will be inferred from the URL. |
No |
result in the response body has the following attributes:| Name | Type | Meaning |
|---|---|---|
formulaRecResults |
object |
The formula recognition result. The length of the array is 1 (for image input) or the smaller of the number of document pages and 10 (for PDF input). For PDF input, each element in the array represents the processing result of each page in the PDF file. |
dataInfo |
object |
Information about the input data. |
Each element in formulaRecResults is an object with the following attributes:
| Name | Type | Meaning |
|---|---|---|
formulas |
array |
The positions and contents of the formulas. |
inputImage |
string |
The input image. The image is in JPEG format and is Base64-encoded. |
layoutImage |
string |
The layout detection result image. The image is in JPEG format and is Base64-encoded. |
Each element in formulas is an object with the following attributes:
| Name | Type | Meaning |
|---|---|---|
poly |
array |
The position of the formula. The elements in the array are the coordinates of the vertices of the polygon surrounding the text. |
latex |
string |
The content of the formula. |
import base64
import requests
API_URL = "http://localhost:8080/formula-recognition"
file_path = "./demo.jpg"
with open(file_path, "rb") as file:
file_bytes = file.read()
file_data = base64.b64encode(file_bytes).decode("ascii")
payload = {"file": file_data, "fileType": 1}
response = requests.post(API_URL, json=payload)
assert response.status_code == 200
result = response.json()["result"]
for i, res in enumerate(result["formulaRecResults"]):
print("Detected formulas:")
print(res["formulas"])
layout_img_path = f"layout_{i}.jpg"
with open(layout_img_path, "wb") as f:
f.write(base64.b64decode(res["layoutImage"]))
print(f"Output image saved at {layout_img_path}")
| Scenario | Fine-Tuning Module | Reference Link |
|---|---|---|
| Formulas are missing | Layout Detection Module | Link |
| Formula content is inaccurate | Formula Recognition Module | Link |
| Whole-image rotation correction is inaccurate | Document Image Orientation Classification Module | Link |
| Image distortion correction is inaccurate | Text Image Correction Module | Fine-tuning not supported |