LaTeX-OCR README

The project's README from github.com/lukas-blecher/LaTeX-OCR. As one markdown file: README.md.

pix2tex - LaTeX OCR

GitHub Documentation Status PyPI PyPI - Downloads GitHub all releases Docker Pulls Open In Colab Hugging Face Spaces

The goal of this project is to create a learning based system that takes an image of a math formula and returns corresponding LaTeX code.

header

Using the model

To run the model you need Python 3.7+

If you don't have PyTorch installed. Follow their instructions here.

Install the package pix2tex:

pip install "pix2tex[gui]"

Model checkpoints will be downloaded automatically.

There are three ways to get a prediction from an image.

  1. You can use the command line tool by calling pix2tex. Here you can parse already existing images from the disk and images in your clipboard.

  2. Thanks to @katie-lim, you can use a nice user interface as a quick way to get the model prediction. Just call the GUI with latexocr. From here you can take a screenshot and the predicted latex code is rendered using MathJax and copied to your clipboard.

    Under linux, it is possible to use the GUI with gnome-screenshot (which comes with multiple monitor support). For other Wayland compositers, grim and slurp will be used for wlroots-based Wayland compositers and spectacle for KDE Plasma. Note that gnome-screenshot is not compatible with wlroots or Qt based compositers. Since gnome-screenshot will be preferred when available, you may have to set the environment variable SCREENSHOT_TOOL to grim or spectacle in these cases (other available values are gnome-screenshot and pil).

    demo

    If the model is unsure about the what's in the image it might output a different prediction every time you click "Retry". With the temperature parameter you can control this behavior (low temperature will produce the same result).

  3. You can use an API. This has additional dependencies. Install via pip install -U "pix2tex[api]" and run

    python -m pix2tex.api.run
    

    to start a Streamlit demo that connects to the API at port 8502. There is also a docker image available for the API: https://hub.docker.com/r/lukasblecher/pix2tex Docker Image Size (latest by date)

    docker pull lukasblecher/pix2tex:api
    docker run --rm -p 8502:8502 lukasblecher/pix2tex:api
    

    To also run the streamlit demo run

    docker run --rm -it -p 8501:8501 --entrypoint python lukasblecher/pix2tex:api pix2tex/api/run.py
    

    and navigate to http://localhost:8501/

  4. Use from within Python

    from PIL import Image
    from pix2tex.cli import LatexOCR
    
    img = Image.open('path/to/image.png')
    model = LatexOCR()
    print(model(img))
    

The model works best with images of smaller resolution. That's why I added a preprocessing step where another neural network predicts the optimal resolution of the input image. This model will automatically resize the custom image to best resemble the training data and thus increase performance of images found in the wild. Still it's not perfect and might not be able to handle huge images optimally, so don't zoom in all the way before taking a picture.

Always double check the result carefully. You can try to redo the prediction with an other resolution if the answer was wrong.

Want to use the package?

I'm trying to compile a documentation right now.

Visit here: https://pix2tex.readthedocs.io/

Training the model Open In Colab

Install a couple of dependencies pip install "pix2tex[train]".

  1. First we need to combine the images with their ground truth labels. I wrote a dataset class (which needs further improving) that saves the relative paths to the images with the LaTeX code they were rendered with. To generate the dataset pickle file run
python -m pix2tex.dataset.dataset --equations path_to_textfile --images path_to_images --out dataset.pkl

To use your own tokenizer pass it via --tokenizer (See below).

You can find my generated training data on the Google Drive as well (formulae.zip - images, math.txt - labels). Repeat the step for the validation and test data. All use the same label text file.

  1. Edit the data (and valdata) entry in the config file to the newly generated .pkl file. Change other hyperparameters if you want to. See pix2tex/model/settings/config.yaml for a template.
  2. Now for the actual training run
python -m pix2tex.train --config path_to_config_file

If you want to use your own data you might be interested in creating your own tokenizer with

python -m pix2tex.dataset.dataset --equations path_to_textfile --vocab-size 8000 --out tokenizer.json

Don't forget to update the path to the tokenizer in the config file and set num_tokens to your vocabulary size.

Model

The model consist of a ViT [1] encoder with a ResNet backbone and a Transformer [2] decoder.

Performance

BLEU score normed edit distance token accuracy
0.88 0.10 0.60

Data

We need paired data for the network to learn. Luckily there is a lot of LaTeX code on the internet, e.g. wikipedia, arXiv. We also use the formulae from the im2latex-100k [3] dataset. All of it can be found here

Dataset Requirements

In order to render the math in many different fonts we use XeLaTeX, generate a PDF and finally convert it to a PNG. For the last step we need to use some third party tools:

Fonts

Latin Modern Math, GFSNeohellenicMath.otf, Asana Math, XITS Math, Cambria Math

TODO

Contribution

Contributions of any kind are welcome.

Acknowledgment

Code taken and modified from lucidrains, rwightman, im2markup, arxiv_leaks, pkra: Mathjax, harupy: snipping tool

References

[1] An Image is Worth 16x16 Words

[2] Attention Is All You Need

[3] Image-to-Markup Generation with Coarse-to-Fine Attention

LaTeX-OCR (lukas-blecher/LaTeX-OCR)

Searching Database…

16.6K ·GitHub
这是什么?一个基于学习的 OCR 系统:给它一张数学公式的图片,它会返回对应的 LaTeX 代码。
这是我自己运行的应用,还是写代码时调用的库?两者都是。它以 pip 包(pix2tex)的形式发布,带有命令行工具、一个叫 latexocr 的桌面图形界面、API 模式和 Python API,还附带在你自己的数据上重新训练模型的工具。
怎么把它跑起来并转换我的第一个公式?安装 Python 3.7+ 然后运行 pip install pix2tex——模型权重会自动下载。用 latexocr 启动图形界面,截一张公式的图,渲染出的 LaTeX 就会复制到剪贴板;磁盘上的图片文件则用 pix2tex 命令行工具处理。
我需要先装 PyTorch 或其他东西吗?需要 Python 3.7+,如果还没装 PyTorch 的话也要先装(按 PyTorch 官方安装说明操作)。API 模式有额外依赖,通过 pip install -U 'pix2tex[api]' 安装。
它每次都能正确读出公式吗?不一定。它会用一个预处理网络把每张图片缩放到最佳分辨率,但特别大的图片效果很差——截图前不要把公式放大到最大。结果一定要再检查一遍,如果不对就换个分辨率重试。
截图功能在 Windows、macOS 和 Linux 上都一样吗?三个桌面系统都能运行。在 Linux 上,截图后端取决于合成器:有 gnome-screenshot 时优先使用它,wlroots Wayland 合成器用 grim 和 slurp,KDE Plasma 用 spectacle——如果选错了,可以用 SCREENSHOTTOOL 环境变量手动指定。
它内部用的是什么技术?一个带 ResNet 骨干网络的 ViT 编码器加一个 Transformer 解码器。训练数据是从 Wikipedia 和 arXiv 抓取的 LaTeX,加上渲染公式数据集 im2latex-100k。
它的准确度怎么样?在它的评测集上,报告的 BLEU 分数为 0.88,归一化编辑距离为 0.10,token 准确率为 0.60。
我能在自己的代码或服务器里使用它吗?可以——直接在 Python 里调用模型,或者用 pip install -U 'pix2tex[api]' 安装 API(一个 Streamlit 演示会连接到它的 8502 端口)。API 还有现成的 Docker 镜像。
它能识别手写公式吗?目前还不能很好地支持——手写识别仍是一个未完成的 TODO,不过 README 提到一个训练用 Colab 笔记本已经差不多实现了这个功能,所以只能当作实验性功能看待。
Size
9.3 MB
Stars
16.6K
Updated
CommitJan 18
Age
5y
Commits · 90 Days