---
title: "Fine-tune a custom document field extractor in C#"
url: https://recursiveai.org/oneocr/cookbook/fine-tune-custom-document-extractor/
description: "Train OneOcr to find a custom lot number in OCR pages, then read the result as an integer and trace it back to its source word."
version: "1.0.0"
---

Teach a local model to find lot numbers in words OCR has already read. The zip has the labels. The snippet needs `start.onm`, which the full program exports from the bundled extraction weights.

```shell
dotnet add package RecursiveAI.OneOcr.Training
dotnet add package RecursiveAI.OneOcr.Models.Documents
```

Requires [.NET 10](https://dotnet.microsoft.com/download/dotnet/10.0) (net10.0); .NET 9 and earlier aren’t supported.

```csharp
using OneOcr;
using OneOcr.Documents;
using OneOcr.Training;

var lot = LotJson.Default.Lot;
var report = new ExtractionTrainer(new() {
    ModelPath = "start.onm",
    WorkDirectory = "work",
    Schema = ExtractionSchema.From(lot),
    Steps = 12, BatchSize = 1, Restart = true
}).Train();
var model = DocumentExtractor.Load(
    report.ModelPath);
var page = OcrPageJson.Parse(
    File.ReadAllText("new-lot.page.json"))[0];
var number = model.Extract(page, lot)
    .Value.LotNumber;
Console.WriteLine($"Lot number: {number}");
```

Unzip [the example](https://recursiveai.org/oneocr/cookbook/fine-tune-custom-document-extractor/fine-tune-custom-document-extractor.zip), then `dotnet run`.

Writes `work/model.onm` and prints the lot number from a separate page:

```text
Lot number: 76
```

The zip includes `work/extract-labels/`, `new-lot.page.json`, and `Lot.cs`. The .NET JSON source generator supplies `LotJson.Default.Lot` from this declaration in `Lot.cs`:

```csharp
using System.Text.Json.Serialization;

public sealed record Lot([property: JsonPropertyName("lotNumber")] int? LotNumber);

[JsonSerializable(typeof(Lot))]
internal partial class LotJson : JsonSerializerContext;
```

One training input, `work/extract-labels/lot-17.json`, looks like this:

```json
{
  "format": "oneocr.extraction-labels", "version": 1,
  "id": "lot-17", "document": "Lot 17",
  "width": 200, "height": 80, "usable": true,
  "words": ["Lot", "17"],
  "boxes": [10, 10, 35, 26, 42, 10, 62, 26],
  "fields": [
    { "name": "lotNumber", "value": "17", "words": [1], "contiguous": true }
  ]
}
```

`new-lot.page.json` is a synthetic `oneocr.page` containing `Lot 76`, not a training label file. Its `words` array, excerpted here, gives the text and position of each word:

```json
[{"text": "Lot", "bounds": [10, 10, 35, 26]},
 {"text": "76", "bounds": [42, 10, 62, 26]}]
```

## Full program

The full program exports the starting file, trains the extractor, and prints the typed result and the word it came from. `Steps` sets the number of weight updates; `Restart = true` discards any existing training checkpoint and starts over.

```csharp
using OneOcr;
using OneOcr.Documents;
using OneOcr.Models.Documents;
using OneOcr.Training;

if (!DocumentModels.TryReadExtractor(out var weights, out var reason))
    throw new InvalidOperationException(reason);
File.WriteAllBytes("start.onm", weights);

var lot = LotJson.Default.Lot;
var trainer = new ExtractionTrainer(new()
{
    ModelPath = "start.onm",
    WorkDirectory = "work",
    Schema = ExtractionSchema.From(lot),
    Steps = 12,
    BatchSize = 1,
    Restart = true
});
var report = trainer.Train();
var extractor = DocumentExtractor.Load(report.ModelPath);
var json = File.ReadAllText("new-lot.page.json");
var page = OcrPageJson.Parse(json)[0];
var result = extractor.Extract(page, lot);
Console.WriteLine($"Lot number: {result.Value.LotNumber}");
if (result.Fields.TryGetValue("lotNumber", out var field))
    Console.WriteLine($"Source words: {field.Text}");
Console.WriteLine($"Held-out pages: {report.HeldOutDocuments}");
```

Output:

```text
Lot number: 76
Source words: 76
Held-out pages: 1
```

`Train()` throws `InvalidOperationException` if there are no usable labeled pages. At extraction time, a missing or unparseable lot number leaves the nullable property `null`.

## Variations

Add this after extraction to get the number of word boxes containing the value. This example prints `1`:

```csharp
Console.WriteLine(result.WordBoxes("lotNumber").Count);
```

## Related recipes

- [Read OCR words and coordinates as JSON](https://recursiveai.org/oneocr/cookbook/page-json/)
- [Fine-tune an OCR recognizer offline](https://recursiveai.org/oneocr/cookbook/fine-tune-local-ocr-recognizer/)

## The short answer

Define the fields as a C# type, build an `ExtractionSchema` from its JSON type information, and call `ExtractionTrainer.Train()` on existing local labels. Load the resulting model with `DocumentExtractor.Load`, then call `Extract(page, typeInfo)`. The example returns a nullable integer for `lotNumber`, plus the text and word locations from the page. The extractor does not learn to read pixels; it learns which already-read words belong to each field.

## How do I label documents for custom field extraction?

For your own documents, [run OCR and read the page JSON](https://recursiveai.org/oneocr/cookbook/page-json/), then copy word text and bounds into the label file and mark the word indices for each field. The built-in labeling command needs a labeling provider; for an offline run, write the labels yourself.

Use one JSON label file per page in `extract-labels`. List the words in reading order, with four coordinates per word: left, top, right, bottom, in the same units as the page width and height. Each field names a top-level scalar property by its JSON name and points to the zero-based indices of the words containing the value. In `Lot 17`, index `1` is `17`; index `0` is the label `Lot`, not part of the value.

Use contiguous spans of words for the fields you expect the model to learn. The trainer skips noncontiguous spans for that field rather than treating intervening text as part of the answer. Use `usable: true` only for pages you can label from what is actually there. The label file’s `id` must match its filename without `.json`. See the [pinned label reader](https://github.com/recursive-ai-oss/oneocr-csharp/blob/8db430fb77c4d86d51686f15dfd9b5ccc20c99a7/src/OneOcr.Training/ExtractionTrainer.cs#L743-L776) for the file checks.

## How do I check a custom extraction model on new documents?

Separate pages used to update the weights from those used to check the result. The trainer picks its holdout from usable pages by ID and seed. The example reserves one of six labeled pages for evaluation and uses a seventh, unlabeled page for the typed extraction shown above. A single success on this layout does not establish accuracy on other layouts.

Inspect field accuracy on held-out pages, then check the extracted text and source words against the page when a result looks wrong. A correct field span can still fail to parse as the requested type. If your lot numbers have leading zeroes or contain letters, use a string property rather than an integer so those characters can be preserved. A value that is absent from the OCR words cannot be recovered by training the field extractor alone.
