tesstrain

repository·main·Indexed 20 days ago

https://github.com/tesseract-ocr/tesstrain

A Makefile-based training workflow and Python library for Tesseract 5 OCR models. It manages the complex process of training, including unicharset creation, proto-model building, checkpoint evaluation, and the generation of .traineddata files. It supports both training from scratch and fine-tuning of existing models, providing a CLI and Python API to handle ground truth data, image processing via Pillow, and character error rate (CER) plotting.

Tokens
3.8K
Snippets
10
Records
16
Agent score
71%

What's inside tesstrain

  1. Provide ground truth data for training

    main

    Ground truth data must be placed in a specific directory structure: data/MODEL_NAME-ground-truth.

    File Requirements

    • Images: Must be TIFF (.tif) or PNG (.png, .bin.png, or .nrm.png).
    • Transcriptions: Must be single-line plain text files with the same name as the image but with the extension replaced by .gt.txt (e.g., line01.png and line01.gt.txt).

    Data Splitting

    The files in this directory are split into training and evaluation sets based on the RATIO_TRAIN variable (default is 0.90).

  2. Run tesstrain via terminal or Python API

    main

    You can interact with tesstrain in two ways:

    1. Terminal Interface: Use the module as a CLI tool to interact with the training tools directly.
    2. Python API: Import the package and use the high-level tesstrain.run() function within your own Python scripts.
    # Using the terminal interface
    python -m tesstrain --help
    
    # Using the Python API (conceptual)
    import tesstrain
    tesstrain.run()
  3. Install tesstrain

    main

    To install the tesstrain package, you can use pip. Note that this package requires the Tesseract training tools to be installed and available on your system. A supported Python version of at least 3.7 is required.

    To install from PyPI:

    pip install tesstrain

    To install from a local source checkout:

    pip install .
  4. Prepare Tesseract language data

    main

    Tesseract requires configuration data (such as radical-stroke.txt and *.unicharset for all scripts) in the DATA_DIR. You can fetch these stock unicharsets using the following command. This is often done once before training, though it is implicitly included in the training target.

    make tesseract-langdata
  5. Plot Character Error Rate (CER) charts

    main

    You can visualize the training and evaluation progress by generating plots from the training log using the plot target. This target can be run even while training is still in progress.

    Generate plots

    make plot

    Evaluate models independently

    To evaluate .checkpoint models on the evaluation dataset without generating plots:

    make evaluation
    # Generate plots for a specific model
    make plot MODEL_NAME=ocrd
  6. Train a Tesseract model

    main

    To start the training process, use the make training target. This is a shortcut that runs unicharset, lists, proto-model, tesseract-langdata, and training.

    Basic Command

    make training MODEL_NAME=your_model_name

    Training Regimes

    • From Scratch: Specify a NET_SPEC (network specification in VGSL).
    • Fine-tuning: Provide a START_MODEL (the name of an existing model to continue from).
    make training MODEL_NAME=name-of-the-resulting-model
  7. Install tesstrain and its dependencies

    main

    To use tesstrain, you must install several system utilities and specific versions of Tesseract and Leptonica.

    System Auxiliaries

    Ensure you have the following installed:

    • GNU make (version 4.2 or higher)
    • wget
    • find
    • bash
    • unzip

    Tesseract and Leptonica

    You need a recent version (>= 5.3) of Tesseract built with training tools and matching Leptonica bindings.

    Python Dependencies

    You need Python 3.x. For image processing, Pillow is required. Install dependencies using the provided requirements file:

    pip install -r requirements.txt

    Windows Setup

    1. Install the latest Tesseract and add it to your PATH.
    2. Install Python 3.
    3. Install Git SCM to Windows. Add C:\Program Files\Git\usr\bin to the beginning of your PATH to avoid conflicts with native Windows tools like find or sort.
    4. Install make and wget via winget:
      winget install ezwinports.make
      winget install wget
  8. Generate `.traineddata` files from checkpoints

    main

    Once training is complete (or while it is running), you can convert intermediate .checkpoint files into usable .traineddata files using the traineddata target. This creates two directories, tessdata_best and tessdata_fast, in your OUTPUT_DIR.

    Create all traineddata files

    make traineddata

    Create from specific checkpoints

    You can use the CHECKPOINT_FILES variable to select specific checkpoints:

    • By age (e.g., last 21 days):
      make traineddata CHECKPOINT_FILES="$(find data/foo -name '*.checkpoint' -mtime -21)"
    • By most recent (e.g., last 2):
      make traineddata CHECKPOINT_FILES="$(ls -t data/foo/checkpoints/*.checkpoint | head -2)"
    • By error rate (e.g., CER better than 1%):
      make traineddata CHECKPOINT_FILES="$(ls data/foo/checkpoints/*[^1-9]0.*.checkpoint)"
    # Example: Create all traineddata files
    make traineddata
  9. How tesstrain handles input data defaults

    main

    If you do not explicitly provide input data via CLI flags, tesstrain automatically attempts to locate files within your specified --langdata_dir using the following pattern based on your --lang code:

    • Training Text: {langdata_dir}/{lang_code}/{lang_code}.training_text
    • Wordlist: {langdata_dir}/{lang_code}/{lang_code}.wordlist
    • Bigrams: {langdata_dir}/{lang_code}/{lang_code}.word.bigrams
    • Numbers: {langdata_dir}/{lang_code}/{lang_code}.numbers
    • Punctuation: {langdata_dir}/{lang_code}/{lang_code}.punc

    Additionally, frequency files like bigram_freqs, unigram_freqs, and train_ngrams are derived from the path of the chosen training_text file by replacing its suffix.

  10. Required environment variables and paths

    main

    To run tesstrain successfully, ensure the following requirements are met:

    1. Language Data: You must provide --langdata_dir.
    2. Tessdata: You must provide --tessdata_dir OR have the TESSDATA_PREFIX environment variable defined.
    3. Language Code: You must specify a language using --lang.

    If --output_dir is not provided, the tool will create a temporary directory named trained-{lang_code}-{timestamp}.

  11. Reference Makefile targets

    main

    Use make help to see all available targets. The primary targets are:

    • unicharset: Create unicharset
    • charfreq: Show character histogram
    • lists: Create lists of lstmf filenames for training and eval
    • training: Start training (creates .checkpoint files)
    • traineddata: Create best and fast .traineddata files from checkpoints
    • proto-model: Build the proto model
    • tesseract-langdata: Download stock unicharsets
    • evaluation: Evaluate .checkpoint models on eval dataset via lstmeval
    • plot: Generate train/eval error rate charts from training log
    • clean: Clean all generated files
  12. Reference Makefile variables

    main

    The following variables can be passed to make to configure the training process:

    VariableDescription
    MODEL_NAMEName of the model to be built. Default: foo
    START_MODELName of the model to continue from (fine-tune). Default: ''
    PROTO_MODELName of the prototype model. Default: OUTPUT_DIR/MODEL_NAME.traineddata
    WORDLIST_FILEOptional file for dictionary DAWG. Default: OUTPUT_DIR/MODEL_NAME.wordlist
    NUMBERS_FILEOptional file for number patterns DAWG. Default: OUTPUT_DIR/MODEL_NAME.numbers
    PUNC_FILEOptional file for punctuation DAWG. Default: OUTPUT_DIR/MODEL_NAME.punc
    DATA_DIRData directory for output files, proto model, etc. Default: data
    OUTPUT_DIROutput directory for generated files. Default: DATA_DIR/MODEL_NAME
    GROUND_TRUTH_DIRGround truth directory. Default: OUTPUT_DIR-ground-truth
    TESSDATA_REPOTesseract model repo to use (_fast or _best). Default: _best
    TESSDATAPath to the directory containing START_MODEL.traineddata. Default: ./usr/share/tessdata
    MAX_ITERATIONSMax iterations. Default: 10000
    EPOCHSSet max iterations based on the number of lines. Default: none
    DEBUG_INTERVALDebug Interval. Default: 0
    LEARNING_RATEDefault: 0.0001 with START_MODEL, otherwise 0.002
    NET_SPECNetwork specification (VGSL) for new models. Default: [1,36,0,1 Ct3,3,16 Mp3,3 Lfys48 Lfx96 Lrx96 Lfx256 O1c###]
    FINETUNE_TYPEFine-tune Training Type (Impact, Plus, Layer). Default: ''
    LANG_TYPELanguage Type (Indic, RTL). Default: ''
    PSMPage segmentation mode. Default: 13
    RANDOM_SEEDRandom seed for shuffling. Default: 0
    RATIO_TRAINRatio of train / eval training data. Default: 0.90
    TARGET_ERROR_RATEStop training if CER (percent) gets below this. Default: 0.01
    LOG_FILEFile to copy training output to. Default: OUTPUT_DIR/training.log