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) с CLI, настольным GUI под названием latexocr, режимом API и Python API, а также с инструментами для дообучения модели на своих данных.
Как его установить и распознать первую формулу?Установите Python 3.7+ и выполните pip install pix2tex — контрольные точки модели скачаются автоматически. Запустите GUI командой latexocr, сделайте скриншот формулы — и готовый LaTeX-код скопируется в буфер обмена; CLI pix2tex обрабатывает картинки с диска.
Нужно ли сначала ставить PyTorch или что-то ещё?Требуется Python 3.7+, а также PyTorch, если он ещё не установлен (следуйте инструкциям по установке с сайта PyTorch). У режима API есть дополнительные зависимости — через pip install -U 'pix2tex[api]'.
Всегда ли он правильно распознаёт формулу?Не всегда. Отдельная сеть предобработки подгоняет каждое изображение под оптимальное разрешение, но очень большие картинки обрабатываются плохо — не приближайте слишком сильно перед снятием скриншота. Всегда проверяйте результат и, если он неверный, попробуйте другое разрешение.
Снятие формулы со скриншота работает одинаково на Windows, macOS и Linux?Работает на всех трёх настольных системах. В Linux скриншотный бэкенд зависит от композитора: если доступен gnome-screenshot, используется он; для Wayland-композиторов на wlroots — grim и slurp, в KDE Plasma — spectacle; неверный выбор можно переопределить переменной окружения SCREENSHOTTOOL.
Как он устроен внутри?ViT-энкодер с ResNet-бэкбоном и Transformer-декодер. Модель обучали на LaTeX, собранном из Википедии и arXiv, плюс на датасете im2latex-100k из отрисованных формул.
Насколько он точный?На своей оценочной выборке показывает BLEU 0.88, нормированное расстояние редактирования 0.10 и точность по токенам 0.60.
Можно ли использовать его из своего кода или на сервере?Да — вызывайте модель прямо из Python или установите API через pip install -U 'pix2tex[api]' (Streamlit-демо подключается к нему на порт 8502). Есть также Docker-образ для API.
А рукописные формулы он понимает?Пока как следует нет — поддержка рукописного ввода всё ещё числится в TODO, хотя в README сказано, что она «почти готова» через Colab-ноутбук для обучения, так что считайте это экспериментальной возможностью.
Size
9.3 MB
Stars
16.6K
Updated
CommitJan 18
Age
5y
Commits · 90 Days