Package: pix2tex
pix2tex - LaTeX OCRThe goal of this project is to create a learning based system that takes an image of a math formula and returns corresponding LaTeX code.Using the modelTo run the model you need Python 3.7+If you don't have PyTorch installed. Follow their instructionshere.Install the packagepix2tex:pip install pix2tex[gui]Model checkpoints will be downloaded automatically.There are three ways to get a prediction from an image.You can use the command line tool by callingpix2tex. Here you can parse already existing images from the disk and images in your clipboard.Thanks to@katie-lim, you can use a nice user interface as a quick way to get the model prediction. Just call the GUI withlatexocr. From here you can take a screenshot and the predicted latex code is rendered usingMathJaxand copied to your clipboard.Under linux, it is possible to use the GUI withgnome-screenshotwhich comes with multiple monitor support ifgnome-screenshotwas installed beforehand.If the model is unsure about the what's in the image it might output a different prediction every time you click "Retry". With thetemperatureparameter you can control this behavior (low temperature will produce the same result).You can use an API. This has additional dependencies. Install viapip install -U pix2tex[api]and runpython-mpix2tex.api.runto start aStreamlitdemo that connects to the API at port 8502. There is also a docker image  available for the API:https://hub.docker.com/r/lukasblecher/pix2texdocker pull lukasblecher/pix2tex:api
docker run --rm -p 8502:8502 lukasblecher/pix2tex:apiTo also run the streamlit demo rundocker run --rm -it -p 8501:8501 --entrypoint python lukasblecher/pix2tex:api pix2tex/api/run.pyand navigate tohttp://localhost:8501/Use from within PythonfromPILimportImagefrompix2tex.cliimportLatexOCRimg=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 modelInstall a couple of dependenciespip install pix2tex[train].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 runpython -m pix2tex.dataset.dataset --equations path_to_textfile --images path_to_images --out dataset.pklTo use your own tokenizer pass it via--tokenizer(See below).You can find my generated training data on theGoogle Driveas well (formulae.zip - images, math.txt - labels). Repeat the step for the validation and test data. All use the same label text file.Edit thedata(andvaldata) entry in the config file to the newly generated.pklfile. Change other hyperparameters if you want to. Seepix2tex/model/settings/config.yamlfor a template.Now for the actual training runpython -m pix2tex.train --config path_to_config_fileIf you want to use your own data you might be interested in creating your own tokenizer withpython -m pix2tex.dataset.dataset --equations path_to_textfile --vocab-size 8000 --out tokenizer.jsonDon't forget to update the path to the tokenizer in the config file and setnum_tokensto your vocabulary size.ModelThe model consist of a ViT [1] encoder with a ResNet backbone and a Transformer [2] decoder.PerformanceBLEU scorenormed edit distancetoken accuracy0.880.100.60DataWe 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 theim2latex-100k[3] dataset.
All of it can be foundhereDataset RequirementsIn 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:XeLaTeXImageMagickwithGhostscript. (for converting pdf to png)Node.jsto runKaTeX(for normalizing Latex code)Python 3.7+ & dependencies (specified insetup.py)FontsLatin Modern Math, GFSNeohellenicMath.otf, Asana Math, XITS Math, Cambria MathTODOadd more evaluation metricscreate a GUIadd beam searchsupport handwritten formulae (kinda done, see training colab notebook)reduce model size (distillation)find optimal hyperparameterstweak model structurefix data scraping and scrape more datatrace the model (#2)ContributionContributions of any kind are welcome.AcknowledgmentCode taken and modified fromlucidrains,rwightman,im2markup,arxiv_leaks,pkra: Mathjax,harupy: snipping toolReferences[1]An Image is Worth 16x16 Words[2]Attention Is All You Need[3]Image-to-Markup Generation with Coarse-to-Fine Attention