# linxueyuanstdio/latex_ocr architecture

> Architecture diagram of the GitHub repository linxueyuanstdio/latex_ocr, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2025-04-18). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/linxueyuanstdio/latex_ocr
- Repository: https://github.com/linxueyuanstdio/latex_ocr

## Overview

##### Project Type and Purpose
- This is an end‑to‑end deep‑learning OCR system for LaTeX formulas:
- It generates training data by rendering LaTeX → image.
- It trains a Seq2Seq+Attention+BeamSearch model.
- It performs inference and evaluates results.
- It provides visualization (attention maps, TensorBoard).

##### File Structure
- Top‐level scripts:
- build.py (data generation)
- train.py (model training)
- predict.py / evaluate_txt.py / evaluate_img.py (inference & evaluation)
- visualize_attention.py / .ipynb (attention viz)
- configs/: JSON files describing data paths, vocab, model hyperparameters, training schedules.
- data/: raw LaTeX formula files (small and full datasets).
- model/:
- components/ (CNN encoders, attention modules, decoder cells, beam‑search)
- utils/ (data generator, image/text preprocessing, LR schedules)
- base(.torch).py (training/inference harness)
- results/: where checkpoints, logs, tensorboard data, visualization outputs live.
- External dependencies: LaTeX, Ghostscript, ImageMagick, TensorFlow1.12, Python3.5.

##### README
- Describes workflow (small vs. full dataset), steps to “make small/full” for data‑gen → train → eval.
- Explains architecture: Seq2Seq (CNN encoder + Attention + LSTM/GRU decoder + BeamSearch).
- Outlines evaluation metrics and visualization tools.

##### Main Components
a. Data Generation & Storage
- Raw LaTeX formulas (data/*.formulas)
- build.py + configs/data*.json → latex → PDF → gs+magick → PNG images + .matching.txt
- Vocabulary files (configs/vocab*.json)
b. Data Loading & Preprocessing
- model/utils/data_generator.py reads (image, token sequence) pairs
- image/text preprocessing utilities
c. Model Core
- Encoder: SimpleCNN / ResNet / DenseNet
- Attention Mechanism (custom op for visualization)
- Decoder: LSTM or GRU + Beam‐Search or Greedy
- model/base_torch.py orchestrates forward/backward pass
d. Training Engine
- train.py uses configs/training*.json, configs/model.json
- Checkpoint saving, dynamic LR schedule (lr_schedule.py)
- TensorBoard logging
e. Inference & Evaluation
- predict.py / evaluate_txt.py / evaluate_img.py
- Generates predicted LaTeX, computes perplexity, EditDistance, BLEU, ExactMatch
f. Visualization
- visualize_attention.py / .ipynb for attention heatmaps
- TensorBoard dashboard for training curves

##### Relationships and Data Flow
1. Raw LaTeX → build.py → Image Store + .matching.txt + Vocab
2. Images + .matching.txt + Vocab → Data Generator → Batches
3. Batches → Training Engine → Model Checkpoints + TensorBoard logs
4. Checkpoints → Inference Engine → Predicted Formulas
5. Predicted Formulas → Evaluation Module → Metrics Reports
6. Attention Weights (via custom op) → Visualization Tool → Heatmaps
7. TensorBoard logs → TensorBoard UI

##### Architectural Patterns & Tech Stack
- Layered architecture: Data layer, Model layer, Script layer
- Modular components (encoders, attention, decoders)
- Config‑driven pipeline (all paths and hyperparams in JSON)
- External tools invoked by scripts: latex, ghostscript, magick
- Framework: Python3.5 + TensorFlow1.12

## Diagram (Mermaid)

```mermaid
flowchart TB
    %% Data Generation
    subgraph "Data Generation"
        DG_Build["build.py"]:::process
        ConfigData[/configs/data.json<br/>configs/data_small.json/]:::config
        LATEX("LaTeX"):::external
        GS("Ghostscript"):::external
        MAGICK("ImageMagick"):::external
        RawFormulas(["Raw LaTeX Formulas"]):::dataStore
        Images(["PNG Images"]):::dataStore
        MatchTxt([".matching.txt"]):::dataStore
        Vocab(["Vocabulary JSON"]):::dataStore

        DG_Build -->|"reads"| ConfigData
        DG_Build -->|"calls"| LATEX
        LATEX -->|"PDF"| GS
        GS -->|"renders"| MAGICK
        MAGICK -->|"produces"| Images
        DG_Build --> Images
        DG_Build --> MatchTxt
        DG_Build --> RawFormulas
        DG_Build --> Vocab
    end

    %% Data Preprocessing
    subgraph "Data Preprocessing"
        DataGen["model/utils/data_generator.py"]:::process
        ImgPre["model/utils/image.py"]:::process
        TxtPre["model/utils/text.py"]:::process
        GenUtil["model/utils/general.py"]:::process
        Batches(["(ImageTensor, TokenSeq) Batches"]):::dataStore

        Images --> DataGen
        MatchTxt --> DataGen
        Vocab --> DataGen
        DataGen --> Batches
        DataGen --> ImgPre
        DataGen --> TxtPre
        DataGen --> GenUtil
    end

    %% Model Core
    subgraph "Model Core"
        ENC_Simple["model/components/SimpleCNN.py"]:::process
        ENC_Res["model/components/ResNet.py"]:::process
        ENC_Dense["model/components/DenseNet.py"]:::process
        ATTn["model/components/attention_mechanism.py"]:::process
        ATT_Cell["model/components/attention_cell.py"]:::process
        DEC_Beam["model/components/beam_search_decoder_cell.py"]:::process
        DEC_Greedy["model/components/greedy_decoder_cell.py"]:::process
        DEC_Dyn["model/components/dynamic_decode.py"]:::process
        Seq2Seq["model/components/seq2seq_torch.py"]:::process
        Encoder["model/encoder.py"]:::process
        Decoder["model/decoder.py"]:::process
        BaseTorch["model/base_torch.py"]:::process
        Base["model/base.py"]:::process

        Batches --> Seq2Seq
        Seq2Seq --> ENC_Simple
        Seq2Seq --> ENC_Res
        Seq2Seq --> ENC_Dense
        Seq2Seq --> ATTn
        Seq2Seq --> ATT_Cell
        Seq2Seq --> DEC_Beam
        Seq2Seq --> DEC_Greedy
        Seq2Seq --> DEC_Dyn
        Seq2Seq --> Encoder
        Seq2Seq --> Decoder
        Seq2Seq --> BaseTorch
        BaseTorch --> Base
    end

    %% Training Engine
    subgraph "Training Engine"
        TrainScript["train.py"]:::process
        ConfigTrain[/configs/training.json<br/>configs/training_small.json<br/>configs/model.json/]:::config
        LRSched["model/utils/lr_schedule.py"]:::process
        Checkpoints(["Model Checkpoints"]):::dataStore
        TensorBoard(["TensorBoard Logs"]):::dataStore

        Batches --> TrainScript
        TrainScript --> ConfigTrain
        TrainScript --> LRSched
        TrainScript --> Checkpoints
        TrainScript --> TensorBoard
    end

    %% Inference & Evaluation
    subgraph "Inference & Evaluation"
        Predict["predict.py"]:::process
        EvalTxtScript["evaluate_txt.py"]:::process
        EvalImgScript["evaluate_img.py"]:::process
        EvalTextMod["model/evaluation/text.py"]:::process
        EvalImgMod["model/evaluation/image.py"]:::process
        PredFormulas(["Predicted LaTeX Formulas"]):::dataStore
        Metrics(["Metrics Reports"]):::dataStore

        Checkpoints --> Predict
        Predict --> EvalTxtScript
        Predict --> EvalImgScript
        EvalTxtScript --> EvalTextMod
        EvalImgScript --> EvalImgMod
        Predict -->|"outputs"| PredFormulas
        EvalTextMod -->|"computes"| Metrics
        EvalImgMod --> Metrics
    end

    %% Visualization
    subgraph "Visualization"
        VizScript["visualize_attention.py"]:::process
        VizNB["visualize_attention.ipynb"]:::process
        VisualizationZip(["visualization.zip"]):::dataStore
        AttentionMaps(["Attention Heatmaps"]):::dataStore
        TensorBoardUI(["TensorBoard UI"]):::external

        BaseTorch -->|"attention weights"| VizScript
        VizScript --> AttentionMaps
        VizNB --> AttentionMaps
        TensorBoard --> TensorBoardUI
        VisualizationZip
    end

    %% Styles
    classDef dataStore fill:#ADD8E6,stroke:#000;
    classDef process fill:#90EE90,stroke:#000;
    classDef config fill:#FFA500,stroke:#000;
    classDef external fill:#D3D3D3,stroke:#000;

    %% Click Events
    click DG_Build "https://github.com/linxueyuanstdio/latex_ocr/blob/master/build.py"
    click ConfigData "https://github.com/linxueyuanstdio/latex_ocr/blob/master/configs/data.json"
    click DataGen "https://github.com/linxueyuanstdio/latex_ocr/blob/master/model/utils/data_generator.py"
    click ImgPre "https://github.com/linxueyuanstdio/latex_ocr/blob/master/model/utils/image.py"
    click TxtPre "https://github.com/linxueyuanstdio/latex_ocr/blob/master/model/utils/text.py"
    click GenUtil "https://github.com/linxueyuanstdio/latex_ocr/blob/master/model/utils/general.py"
    click ENC_Simple "https://github.com/linxueyuanstdio/latex_ocr/blob/master/model/components/SimpleCNN.py"
    click ENC_Res "https://github.com/linxueyuanstdio/latex_ocr/blob/master/model/components/ResNet.py"
    click ENC_Dense "https://github.com/linxueyuanstdio/latex_ocr/blob/master/model/components/DenseNet.py"
    click ATTn "https://github.com/linxueyuanstdio/latex_ocr/blob/master/model/components/attention_mechanism.py"
    click ATT_Cell "https://github.com/linxueyuanstdio/latex_ocr/blob/master/model/components/attention_cell.py"
    click DEC_Beam "https://github.com/linxueyuanstdio/latex_ocr/blob/master/model/components/beam_search_decoder_cell.py"
    click DEC_Greedy "https://github.com/linxueyuanstdio/latex_ocr/blob/master/model/components/greedy_decoder_cell.py"
    click DEC_Dyn "https://github.com/linxueyuanstdio/latex_ocr/blob/master/model/components/dynamic_decode.py"
    click Seq2Seq "https://github.com/linxueyuanstdio/latex_ocr/blob/master/model/components/seq2seq_torch.py"
    click Encoder "https://github.com/linxueyuanstdio/latex_ocr/blob/master/model/encoder.py"
    click Decoder "https://github.com/linxueyuanstdio/latex_ocr/blob/master/model/decoder.py"
    click BaseTorch "https://github.com/linxueyuanstdio/latex_ocr/blob/master/model/base_torch.py"
    click TrainScript "https://github.com/linxueyuanstdio/latex_ocr/blob/master/train.py"
    click ConfigTrain "https://github.com/linxueyuanstdio/latex_ocr/blob/master/configs/training.json"
    click LRSched "https://github.com/linxueyuanstdio/latex_ocr/blob/master/model/utils/lr_schedule.py"
    click Predict "https://github.com/linxueyuanstdio/latex_ocr/blob/master/predict.py"
    click EvalTxtScript "https://github.com/linxueyuanstdio/latex_ocr/blob/master/evaluate_txt.py"
    click EvalImgScript "https://github.com/linxueyuanstdio/latex_ocr/blob/master/evaluate_img.py"
    click EvalTextMod "https://github.com/linxueyuanstdio/latex_ocr/blob/master/model/evaluation/text.py"
    click EvalImgMod "https://github.com/linxueyuanstdio/latex_ocr/blob/master/model/evaluation/image.py"
    click VizScript "https://github.com/linxueyuanstdio/latex_ocr/blob/master/visualize_attention.py"
    click VizNB "https://github.com/linxueyuanstdio/latex_ocr/blob/master/visualize_attention.ipynb"
```
