--- comments: true --- # Formula Recognition Module Tutorial ## I. Overview The formula recognition module is a crucial component of OCR (Optical Character Recognition) systems, responsible for converting mathematical formulas in images into editable text or computer-readable formats. The performance of this module directly impacts the accuracy and efficiency of the entire OCR system. The module typically outputs LaTeX or MathML codes of mathematical formulas, which are then passed on to the text understanding module for further processing. ## II. Supported Model List
| Model | Model Download Link | Avg-BLEU(%) | GPU Inference Time (ms) [Normal Mode / High-Performance Mode] |
CPU Inference Time (ms) [Normal Mode / High-Performance Mode] |
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. |
| Mode | GPU Configuration | CPU Configuration | Acceleration Technology Combination |
|---|---|---|---|
| Normal Mode | FP32 Precision / No TRT Acceleration | FP32 Precision / 8 Threads | PaddleInference |
| High-Performance Mode | Optimal combination of pre-selected precision types and acceleration strategies | FP32 Precision / 8 Threads | Pre-selected optimal backend (Paddle/OpenVINO/TRT, etc.) |
Note: If you need to visualize the formula recognition pipeline, you need to run the following commands to install the LaTeX rendering environment. Currently, the formula recognition visualization pipeline only supports the Ubuntu environment; other environments are not supported at this time. For complex formulas, the LaTeX results may include some advanced representations that might not be displayed successfully in environments like Markdown:
```bash
sudo apt-get update
sudo apt-get install texlive texlive-latex-base texlive-latex-extra -y
````
The explanations for the methods, parameters, etc., are as follows:
* The `create_model` method instantiates the formula recognition model (here, `PP-FormulaNet-S` is used as an example), and the specific explanations are as follows:
| Parameter | Parameter Description | Parameter Type | Options | Default Value |
|---|---|---|---|---|
model_name |
Name of the model | str |
All model names supported by PaddleX | None |
model_dir |
Path to store the model | str |
None | None |
device |
The device used for model inference | str |
It supports specifying specific GPU card numbers, such as "gpu:0", other hardware card numbers, such as "npu:0", or CPU, such as "cpu". | gpu:0 |
use_hpip |
Whether to enable the high-performance inference plugin | bool |
None | False |
hpi_config |
High-performance inference configuration | dict | None |
None | None |
| Parameter | Parameter Description | Parameter Type | Options | Default Value |
|---|---|---|---|---|
input |
Data to be predicted, supporting multiple input types | Python Var/str/list |
|
None |
batch_size |
Batch size | int |
Any integer | 1 |
| Method | Method Description | Parameter | Parameter Type | Parameter Description | Default Value |
|---|---|---|---|---|---|
print() |
Print the results to the 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, only effective when format_json is True |
4 | ||
ensure_ascii |
bool |
Control whether to escape non-ASCII characters to Unicode. If set to True, all non-ASCII characters will be escaped; False retains the original characters, only effective when format_json is True |
False |
||
save_to_json() |
Save the results as a JSON file | save_path |
str |
The path to save the file. If it is a directory, the saved file name will be consistent with the input file name | None |
indent |
int |
Specify the indentation level to beautify the output JSON data, making it more readable, only effective when format_json is True |
4 | ||
ensure_ascii |
bool |
Control whether to escape non-ASCII characters to Unicode. If set to True, all non-ASCII characters will be escaped; False retains the original characters, only effective when format_json is True |
False |
||
save_to_img() |
Save the results as an image file | save_path |
str |
The path to save the file. If it is a directory, the saved file name will be consistent with the input file name | None |
| Attribute | Attribute Description |
|---|---|
json |
Get the prediction result in json format |
img |
Get the visualization image in dict format |
The specific content of the validation result file is:
{
"done_flag": true,
"check_pass": true,
"attributes": {
"train_samples": 10001,
"train_sample_paths": [
"..\/dataset\/ocr_rec_latexocr_dataset_example\/images\/train_0077809.png",
"..\/dataset\/ocr_rec_latexocr_dataset_example\/images\/train_0161600.png",
"..\/dataset\/ocr_rec_latexocr_dataset_example\/images\/train_0002077.png",
"..\/dataset\/ocr_rec_latexocr_dataset_example\/images\/train_0178425.png",
"..\/dataset\/ocr_rec_latexocr_dataset_example\/images\/train_0010959.png",
"..\/dataset\/ocr_rec_latexocr_dataset_example\/images\/train_0079266.png",
"..\/dataset\/ocr_rec_latexocr_dataset_example\/images\/train_0142495.png",
"..\/dataset\/ocr_rec_latexocr_dataset_example\/images\/train_0196376.png",
"..\/dataset\/ocr_rec_latexocr_dataset_example\/images\/train_0185513.png",
"..\/dataset\/ocr_rec_latexocr_dataset_example\/images\/train_0217146.png"
],
"val_samples": 501,
"val_sample_paths": [
"..\/dataset\/ocr_rec_latexocr_dataset_example\/images\/val_0053264.png",
"..\/dataset\/ocr_rec_latexocr_dataset_example\/images\/val_0100521.png",
"..\/dataset\/ocr_rec_latexocr_dataset_example\/images\/val_0146333.png",
"..\/dataset\/ocr_rec_latexocr_dataset_example\/images\/val_0072788.png",
"..\/dataset\/ocr_rec_latexocr_dataset_example\/images\/val_0002022.png",
"..\/dataset\/ocr_rec_latexocr_dataset_example\/images\/val_0203664.png",
"..\/dataset\/ocr_rec_latexocr_dataset_example\/images\/val_0082217.png",
"..\/dataset\/ocr_rec_latexocr_dataset_example\/images\/val_0208199.png",
"..\/dataset\/ocr_rec_latexocr_dataset_example\/images\/val_0111236.png",
"..\/dataset\/ocr_rec_latexocr_dataset_example\/images\/val_0204453.png"
]
},
"analysis": {
"histogram": "check_dataset\/histogram.png"
},
"dataset_path": "ocr_rec_latexocr_dataset_example",
"show_type": "image",
"dataset_type": "FormulaRecDataset"
}
In the above validation results, check_pass being True indicates that the dataset format meets the requirements. Explanations for other indicators are as follows:
attributes.train_samples: The number of training samples in this dataset is 9452;attributes.val_samples: The number of validation samples in this dataset is 1050;attributes.train_sample_paths: A list of relative paths to the visualized training samples in this dataset;attributes.val_sample_paths: A list of relative paths to the visualized validation samples in this dataset;Additionally, the dataset verification also analyzes the distribution of sample numbers across all categories in the dataset and generates a distribution histogram (histogram.png):

(1) Dataset Format Conversion
The formula recognition supports converting FormulaRecDataset format datasets to LaTeXOCRDataset format ( PKL format ). The parameters for dataset format conversion can be set by modifying the fields under CheckDataset in the configuration file. Examples of some parameters in the configuration file are as follows:
CheckDataset:convert:enable: Whether to perform dataset format conversion. Formula recognition supports converting FormulaRecDataset format datasets to LaTeXOCRDataset format, default is True;src_dataset_type: If dataset format conversion is performed, the source dataset format needs to be set, default is FormulaRecDataset;For example, if you want to convert a FormulaRecDataset format dataset to LaTeXOCRDataset format, you need to modify the configuration file as follows:
......
CheckDataset:
......
convert:
enable: True
src_dataset_type: FormulaRecDataset
......
Then execute the command:
python main.py -c paddlex/configs/modules/formula_recognition/PP-FormulaNet-S.yaml \
-o Global.mode=check_dataset \
-o Global.dataset_dir=./dataset/ocr_rec_latexocr_dataset_example
After the data conversion is executed, the original annotation files will be renamed to xxx.bak in the original path.
The above parameters also support being set by appending command line arguments:
python main.py -c paddlex/configs/modules/formula_recognition/PP-FormulaNet-S.yaml \
-o Global.mode=check_dataset \
-o Global.dataset_dir=./dataset/ocr_rec_latexocr_dataset_example \
-o CheckDataset.convert.enable=True \
-o CheckDataset.convert.src_dataset_type=FormulaRecDataset
(2) Dataset Splitting
The parameters for dataset splitting can be set by modifying the fields under CheckDataset in the configuration file. Examples of some parameters in the configuration file are as follows:
CheckDataset:split:enable: Whether to re-split the dataset. When set to True, dataset splitting is performed, default is False;train_percent: If the dataset is re-split, the percentage of the training set needs to be set, which is an integer between 0 and 100, and the sum with val_percent should be 100;For example, if you want to re-split the dataset with 90% for the training set and 10% for the validation set, you need to modify the configuration file as follows:
......
CheckDataset:
......
split:
enable: True
train_percent: 90
val_percent: 10
......
Then execute the command:
python main.py -c paddlex/configs/modules/formula_recognition/PP-FormulaNet-S.yaml \
-o Global.mode=check_dataset \
-o Global.dataset_dir=./dataset/ocr_rec_latexocr_dataset_example
After the data splitting is executed, the original annotation files will be renamed to xxx.bak in the original path.
The above parameters also support being set by appending command line arguments:
python main.py -c paddlex/configs/modules/formula_recognition/PP-FormulaNet-S.yaml \
-o Global.mode=check_dataset \
-o Global.dataset_dir=./dataset/ocr_rec_latexocr_dataset_example \
-o CheckDataset.split.enable=True \
-o CheckDataset.split.train_percent=90 \
-o CheckDataset.split.val_percent=10
output. If you need to specify a save path, you can set it through the -o Global.output field in the configuration file.After completing the model training, all outputs are saved in the specified output directory (default is ./output/), typically including:
train_result.json: Training result record file, recording whether the training task was completed normally, as well as the output weight metrics, related file paths, etc.;
train.log: Training log file, recording changes in model metrics and loss during training;config.yaml: Training configuration file, recording the hyperparameter configuration for this training session;.pdparams, .pdema, .pdopt.pdstate, .pdiparams, .json: Model weight-related files, including network parameters, optimizer, EMA, static graph network parameters, static graph network structure, etc.;.json file) from protobuf(the former.pdmodel file) to be compatible with PIR and more flexible and scalable.When evaluating the model, you need to specify the model weights file path. Each configuration file has a default weight save path built-in. If you need to change it, simply set it by appending a command line parameter, such as -o Evaluate.weight_path=./output/best_accuracy/best_accuracy.pdparams.
After completing the model evaluation, an evaluate_result.json file will be produced, which records the evaluation results, specifically, whether the evaluation task was completed successfully and the model's evaluation metrics, including exp_rate;