goddddocr

package module
v1.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 18, 2026 License: MIT Imports: 30 Imported by: 0

README

goddddocr

CI Release

中文文档

Go OCR service/module based on ddddocr ONNX models, without a Python runtime. The OCR models and charsets are derived from https://github.com/sml2h3/ddddocr.

Quick Start

go test ./...
go run ./cmd/goddddocr-server -addr :8088
curl -s http://127.0.0.1:8088/health
curl -s -X POST http://127.0.0.1:8088/ocr \
  -H 'content-type: application/json' \
  -d "{\"image\":\"$(base64 -i samples/yzm1.png)\",\"confidence\":true}"

Before wiring the service into tsplay, run the local doctor command on the target machine. It checks ONNX Runtime loading, model/charset configuration, and optionally one sample OCR result without starting HTTP:

go run ./cmd/ocrdoctor -image samples/yzm1.png -expect 3n3d
go run ./cmd/ocrdoctor -json
scripts/smoke.sh

On Windows, use PowerShell:

.\scripts\smoke.ps1

The default OCR models, detection model, and charsets are embedded into the Go binaries with go:embed. Release users do not need to download separate model files unless they intentionally pass custom -model-path, -charset-path, or -det-model-path values.

Linux and macOS can install and start the latest release in one step:

curl -fsSL https://raw.githubusercontent.com/tensafe/goddddocr/main/scripts/install_run.sh | sh

Pin a release or pass server flags when needed:

curl -fsSL https://raw.githubusercontent.com/tensafe/goddddocr/main/scripts/install_run.sh \
  | GODDDDOCR_VERSION=v1.0.1 sh -s -- -addr :8088 -workers 2

Release Packages

GitHub Releases use v1.x.x SemVer tags. Each release archive contains the server and helper binaries, embedded models/charsets inside those binaries, the matching ONNX Runtime shared library, one-click run scripts, smoke scripts, sample images, English and Chinese docs, LICENSE, and NOTICE. Releases also publish goddddocr-onnxruntime-v1.x.x.tar.gz, an optional all-platform ONNX Runtime bundle with Windows Visual C++ Redistributable installers for offline redistribution.

Download the archive that matches the deployment host:

Target GitHub runner Archive ONNX Runtime Runtime library
linux/amd64 ubuntu-24.04 .tar.gz 1.25.0 libonnxruntime.so
linux/arm64 ubuntu-24.04-arm .tar.gz 1.25.0 libonnxruntime.so
darwin/amd64 macos-15-intel .tar.gz 1.23.2 onnxruntime.dylib
darwin/arm64 macos-15 .tar.gz 1.25.0 onnxruntime.dylib
windows/amd64 windows-2025 .zip 1.25.0 onnxruntime.dll
windows/arm64 windows-11-arm .zip 1.25.0 onnxruntime.dll

macOS Intel (darwin/amd64) uses ONNX Runtime 1.23.2 because the official 1.25.0 release no longer publishes a macOS amd64 CPU archive.

Linux and macOS:

tar -xzf goddddocr-v1.0.1-linux-amd64.tar.gz
cd goddddocr-v1.0.1-linux-amd64
scripts/smoke.sh
./goddddocr-server -addr :8088
# or:
scripts/run.sh -addr :8088

Windows PowerShell:

Expand-Archive .\goddddocr-v1.0.1-windows-amd64.zip
cd .\goddddocr-v1.0.1-windows-amd64\goddddocr-v1.0.1-windows-amd64
.\scripts\smoke.ps1
.\goddddocr-server.exe -addr :8088

Windows packages include onnxruntime.dll, but the DLL imports the Microsoft Visual C++ runtime (MSVCP140.dll, VCRUNTIME140.dll, VCRUNTIME140_1.dll, and UCRT API-set DLLs). Windows release packages include the matching Microsoft Visual C++ Redistributable installer under redist/windows/; run it only when the target host does not already have the runtime:

  • windows/amd64: redist/windows/vc_redist.x64.exe
  • windows/arm64: redist/windows/vc_redist.arm64.exe

Go Client

tsplay should call the service over HTTP first, so cgo and ONNX Runtime stay out of the tsplay process:

client := goddddocr.NewOCRClient("http://127.0.0.1:8088")
if err := client.Ready(ctx); err != nil {
    return err
}

result, err := client.ClassifyBytes(ctx, imageBytes, &goddddocr.RemoteClassifyOptions{
    CharsetRange: "0123456789abcdefghijklmnopqrstuvwxyz",
    Confidence: true,
})
if err != nil {
    return err
}
fmt.Println(result.Result)

Service Config

CLI flags can be supplied directly or through environment variables:

Flag Env Default
-addr GODDDDOCR_ADDR :8088
-model GODDDDOCR_MODEL old
-model-path GODDDDOCR_MODEL_PATH empty
-charset-path GODDDDOCR_CHARSET_PATH empty
-input-name GODDDDOCR_INPUT_NAME input1
-output-name GODDDDOCR_OUTPUT_NAME 387
-png-fix GODDDDOCR_PNG_FIX false
-det GODDDDOCR_DET false
-det-model-path GODDDDOCR_DET_MODEL_PATH empty
-det-input-name GODDDDOCR_DET_INPUT_NAME images
-det-output-name GODDDDOCR_DET_OUTPUT_NAME output
-det-input-size GODDDDOCR_DET_INPUT_SIZE 416
-det-score-threshold GODDDDOCR_DET_SCORE_THRESHOLD 0.1
-det-nms-threshold GODDDDOCR_DET_NMS_THRESHOLD 0.45
-workers GODDDDOCR_WORKERS 1
-log-format GODDDDOCR_LOG_FORMAT text
-max-image-bytes GODDDDOCR_MAX_IMAGE_BYTES 8388608
-shutdown-timeout GODDDDOCR_SHUTDOWN_TIMEOUT 10s
-onnxruntime-lib ONNXRUNTIME_SHARED_LIBRARY_PATH empty

-workers=N creates N independent OCR sessions behind the HTTP service. Start with 1, then increase gradually after checking /metrics latency and memory. Use -log-format json for one-JSON-object-per-line service and access logs.

Use -model old or -model beta for the embedded ddddocr OCR models. To load an external OCR model, provide both -model-path and -charset-path; the service reports the active model as custom. Custom charset files are JSON arrays whose first entry must be the CTC blank token, usually an empty string:

["", "0", "1", "2", "a", "b"]

Most ddddocr-compatible ONNX OCR models use input input1 and output 387. If your exported model uses different tensor names, pass -input-name and -output-name.

The same model flags are accepted by cmd/ocrdoctor, so deployment scripts can validate a custom model before starting the long-running service:

go run ./cmd/ocrdoctor \
  -model-path /opt/models/custom.onnx \
  -charset-path /opt/models/charset.json \
  -image /opt/models/smoke.png \
  -expect abcd \
  -json

The release smoke scripts wrap the same doctor command. They first try GODDDDOCR_DOCTOR_BIN, then a local ocrdoctor binary, then ocrdoctor from PATH, and finally go run ./cmd/ocrdoctor when running from a source checkout. Use GODDDDOCR_SMOKE_IMAGE and GODDDDOCR_SMOKE_EXPECT to point them at a deployment-specific captcha sample:

GODDDDOCR_SMOKE_IMAGE=/opt/models/smoke.png \
GODDDDOCR_SMOKE_EXPECT=abcd \
scripts/smoke.sh

CI And Releases

Linux CI uses the same smoke path intended for release packages:

scripts/ci_linux.sh

The script runs unit tests, builds all commands, installs the current platform ONNX Runtime with cmd/ortfetch, and then runs scripts/smoke.sh.

Build a local release package for the current platform:

GODDDDOCR_VERSION=v1.0.1 make package-release

Build the all-platform ONNX Runtime bundle:

GODDDDOCR_VERSION=v1.0.1 make package-onnxruntime

Publish an automated GitHub release by pushing a v1.x.x tag:

git tag v1.0.1
git push origin v1.0.1

The Release workflow builds Linux amd64/arm64, macOS amd64/arm64, and Windows amd64/arm64 packages, runs the bundled smoke check, uploads the archives, and publishes the all-platform ONNX Runtime bundle plus SHA256SUMS. The same workflow can be started manually with:

gh workflow run release.yml -f version=v1.0.1

Docker smoke is available as a manual GitHub Actions workflow named Docker Smoke. It builds the service image for linux/amd64 or linux/arm64, starts a temporary container, waits for /ready, and checks the bundled OCR sample through HTTP.

Endpoints:

  • GET /health
  • GET /ready
  • GET /metrics
  • POST /ocr
  • POST /ocr/file
  • POST /det
  • POST /det/file
  • POST /slide_comparison
  • POST /slide-comparison
  • POST /slide_comparison/file
  • POST /slide-comparison/file
  • POST /slide_match
  • POST /slide-match
  • POST /slide_match/file
  • POST /slide-match/file

POST /ocr accepts:

{
  "image": "base64-encoded-image",
  "png_fix": false,
  "charset_range": "0123456789abcdefghijklmnopqrstuvwxyz",
  "color_filter_colors": ["red", "blue"],
  "color_filter_custom_ranges": [[[90, 30, 30], [110, 255, 255]]],
  "confidence": true,
  "probability": false
}

charset_range may be a number, a string, or a string array. The response keeps result as the recognized text and includes confidence only when requested. Set probability to true to include a Python-compatible full probability matrix:

{
  "result": "3n3d",
  "probability": {
    "text": "3n3d",
    "charsets": ["", "0", "1"],
    "probability": [[0.01, 0.02, 0.97]],
    "confidence": 0.97
  }
}

color_filter_colors keeps only matching pixels and turns the rest white before OCR preprocessing. Presets match ddddocr's HSV ranges: red, blue, green, yellow, orange, purple, cyan, black, white, and gray. color_filter_custom_ranges accepts HSV ranges in OpenCV scale [[lower_hsv], [upper_hsv]], where H is 0..180 and S/V are 0..255.

Detection API

The Go module includes the embedded ddddocr detection model. Enable HTTP detection endpoints with -det:

go run ./cmd/goddddocr-server -det
curl -s -X POST http://127.0.0.1:8088/det \
  -H 'content-type: application/json' \
  -d "{\"image\":\"$(base64 -i samples/yzm2.jpeg)\"}"

POST /det accepts image, optional detailed, and optional per-request score_threshold / nms_threshold overrides. The result field is Python-compatible [][]int, where each box is [x1, y1, x2, y2]. When detailed is true, boxes also includes score and class id. Thresholds must be between 0 and 1; omitted values use the service defaults.

The HTTP client exposes the same endpoint:

scoreThreshold := 0.05
result, err := client.DetectBytes(ctx, imageBytes, &goddddocr.RemoteDetectOptions{
    Detailed: true,
    ScoreThreshold: &scoreThreshold,
})
fmt.Println(result.Result)

The library-level detector is available directly:

det, err := goddddocr.NewDetector(goddddocr.DetectionConfig{})
if err != nil {
    return err
}
defer det.Close()

boxes, err := det.DetectBytes(imageBytes)

DetectBytesDetailed returns score and class id.

Slide Comparison API

The diff-based ddddocr slide comparison path is pure Go and does not require ONNX Runtime. It is available whenever the HTTP service is running:

curl -s -X POST http://127.0.0.1:8088/slide_comparison \
  -H 'content-type: application/json' \
  -d "{\"target_image\":\"$(base64 -i target.png)\",\"background_image\":\"$(base64 -i background.png)\"}"

POST /slide_comparison and the original hyphenated alias POST /slide-comparison accept:

{
  "target_image": "base64-encoded-image-with-gap",
  "background_image": "base64-encoded-complete-background"
}

The response keeps ddddocr's result shape:

{
  "result": {
    "target": [51, 32],
    "target_x": 51,
    "target_y": 32
  }
}

The HTTP client exposes the same endpoint:

result, err := client.SlideComparisonBytes(ctx, targetImageBytes, backgroundImageBytes)
fmt.Println(result.Result.Target)

Slide Match API

Slide match locates a smaller slider image within a larger background. It is also pure Go. simple_target=true uses grayscale template matching; the default path uses a lightweight edge map before matching:

curl -s -X POST http://127.0.0.1:8088/slide_match \
  -H 'content-type: application/json' \
  -d "{\"target_image\":\"$(base64 -i target.png)\",\"background_image\":\"$(base64 -i background.png)\",\"simple_target\":true}"

POST /slide_match and POST /slide-match accept:

{
  "target_image": "base64-encoded-slider-piece",
  "background_image": "base64-encoded-background",
  "simple_target": true
}

The response includes the ddddocr target shape plus a normalized confidence score:

{
  "result": {
    "target": [73, 37],
    "target_x": 73,
    "target_y": 37,
    "confidence": 0.99
  }
}

The HTTP client exposes:

result, err := client.SlideMatchBytes(ctx, targetImageBytes, backgroundImageBytes, &goddddocr.RemoteSlideMatchOptions{
    SimpleTarget: true,
})
fmt.Println(result.Result.Target, result.Result.Confidence)

GET /metrics returns service counters and latency aggregates as JSON:

{
  "total_requests": 42,
  "completed_requests": 42,
  "error_requests": 1,
  "status_codes": {"200": 41, "400": 1},
  "average_latency_ms": 8.4,
  "max_latency_ms": 31.2
}

Baseline Load Test

Use ocrbench while tuning -workers:

go run ./cmd/goddddocr-server -addr :8088 -workers 2
go run ./cmd/ocrbench -url http://127.0.0.1:8088 \
  -image samples/yzm1.png \
  -requests 100 \
  -concurrency 4 \
  -expect 3n3d

Run the same image and request count with -workers 1, 2, and 4, then compare QPS, p50, p95, p99, errors, and /metrics output.

For a repeatable worker sweep, use:

scripts/bench_workers.sh

By default this tests workers=1 2 4 8, sends 100 requests at concurrency 4, and writes JSON results, server logs, metrics snapshots, and a Markdown summary with server RSS memory under /tmp/goddddocr-bench-*. Useful overrides:

GODDDDOCR_BENCH_WORKERS="1 2 4 8" \
GODDDDOCR_BENCH_REQUESTS=200 \
GODDDDOCR_BENCH_CONCURRENCY=8 \
GODDDDOCR_BENCH_OUT=/tmp/goddddocr-baseline \
scripts/bench_workers.sh

The current local baseline is recorded in BENCHMARKS.md.

ONNX Runtime

The code is portable across Windows, macOS, and Linux. The only platform-native piece is the ONNX Runtime shared library. Loading order:

  1. Config.SharedLibraryPath or -onnxruntime-lib
  2. ONNXRUNTIME_SHARED_LIBRARY_PATH
  3. ONNXRUNTIME_HOME
  4. third_party/onnxruntime/<GOOS>_<GOARCH>/
  5. embedded darwin/arm64 runtime, when available
  6. system library path

Install the runtime for the current system:

go run ./cmd/ortfetch

Or install for another target:

go run ./cmd/ortfetch -goos linux -goarch amd64
go run ./cmd/ortfetch -goos linux -goarch arm64
go run ./cmd/ortfetch -goos windows -goarch amd64
go run ./cmd/ortfetch -goos windows -goarch arm64
go run ./cmd/ortfetch -goos darwin -goarch amd64
go run ./cmd/ortfetch -goos darwin -goarch arm64

cmd/ortfetch uses target-specific defaults: darwin/amd64 downloads ONNX Runtime 1.23.2; all other bundled targets download 1.25.0.

Manual setup also works:

export ONNXRUNTIME_SHARED_LIBRARY_PATH=/path/to/libonnxruntime.so

Windows uses onnxruntime.dll; macOS uses libonnxruntime.dylib or onnxruntime.dylib; Linux uses libonnxruntime.so.

Because github.com/yalue/onnxruntime_go uses cgo, build on the target system or install the matching cross C compiler:

  • Windows: MSYS2/mingw-w64 or build natively on Windows. Release builds use static MinGW runtime linking for the Go binaries, but onnxruntime.dll still may require the bundled Microsoft Visual C++ Redistributable on the target host.
  • Linux: build natively or use a Linux cross compiler/container.
  • macOS: Xcode command line tools.

Docker

docker compose up --build

The container exposes 8088 and uses /ready for health checks.

For a full Docker smoke test, build the image, start a temporary container, wait for /ready, and classify the bundled sample:

scripts/docker_smoke.sh

Set GODDDDOCR_DOCKER_PORT, GODDDDOCR_SMOKE_IMAGE, and GODDDDOCR_SMOKE_EXPECT when the default 18088 port or bundled sample is not appropriate. Set GODDDDOCR_DOCKER_PLATFORM=linux/amd64 or linux/arm64 to force a target platform.

Golden OCR Fixtures

fixtures/ocr_golden.json records Python ddddocr outputs for sample images and keeps the Go port honest as preprocessing and model options evolve. These fixtures are test data only; the library and service still run without Python.

go test . -run TestGoldenOCRFixtures
go test ./...

Each fixture can set model, charset_range, png_fix, and min_confidence. Add new representative captcha images under samples/ or an ignored local sample directory, record the Python ddddocr output in python_ddddocr, and keep expected equal to that value unless the fixture is documenting an intentional compatibility difference. If Python tooling is not available yet, expected may still be used as a Go model regression baseline.

Golden Detection And Slide Fixtures

fixtures/detection_golden.json and fixtures/slide_golden.json cover the non-OCR ddddocr features. Detection fixtures pin expected bounding boxes and minimum scores. Slide fixtures pin target, target_x, target_y, and optional confidence thresholds for comparison and match modes.

go test . -run 'TestGolden(Detection|Slide)Fixtures'

Use the development helper to refresh references from Python ddddocr when the Python dependencies are available:

PYTHONPATH=/path/to/ddddocr \
  python3 scripts/python_feature_reference.py \
  -mode det \
  -image samples/yzm2.jpeg \
  -out /tmp/python-detection-reference.json

PYTHONPATH=/path/to/ddddocr \
  python3 scripts/python_feature_reference.py \
  -mode slide-match \
  -target /path/to/target.png \
  -background /path/to/background.png \
  -simple-target \
  -out /tmp/python-slide-reference.json

The helper is development-only; Go tests consume committed JSON fixtures and do not import Python.

Local Sample Accuracy

Use ocreval for private or real-world captcha samples that should not be committed to the repository. Directory mode treats each image filename stem as the expected OCR text:

mkdir -p samples/local
# put files such as samples/local/3n3d.png or samples/local/abcd.jpg here
go run ./cmd/ocreval -dir samples/local -csv /tmp/ocr-eval.csv -markdown /tmp/ocr-eval.md

Manifest mode uses the same fields as fixtures/ocr_golden.json, including model, charset_range, png_fix, color_filter_colors, and color_filter_custom_ranges:

go run ./cmd/ocreval -manifest fixtures/ocr_golden.json -json

Ignored local paths are available for private runs: samples/local/, samples/private/, and reports/ocr-eval/.

Preprocessing Debug

Use ocrprep when comparing Go preprocessing against Python/PIL. It exports the 64px-high grayscale model input as a PNG, optional pixel matrix CSV, and a JSON report with dimensions, min/max/mean, and SHA-256 of the grayscale bytes:

go run ./cmd/ocrprep \
  -image samples/yzm1.png \
  -out /tmp/goddddocr-preprocess.png \
  -matrix-csv /tmp/goddddocr-preprocess.csv \
  -json /tmp/goddddocr-preprocess.json

The command also accepts -png-fix, -color-filter-colors, and -color-filter-custom-ranges, matching OCR request preprocessing options. When you have a Python/PIL reference export, compare it directly:

python3 scripts/python_preprocess_reference.py \
  -image samples/yzm1.png \
  -out /tmp/python-preprocess.png \
  -matrix-csv /tmp/python-preprocess.csv \
  -json /tmp/python-preprocess.json

go run ./cmd/ocrprep \
  -image samples/yzm1.png \
  -compare-csv /tmp/python-preprocess.csv \
  -diff-png /tmp/goddddocr-preprocess-diff.png

Use -compare-png for grayscale PNG references. The JSON report includes exact-match, differing pixel count, max absolute difference, mean absolute difference, RMSE, differing pixel rate, the first sampled pixel differences, and the reference SHA-256. The optional -diff-png output is black where pixels match, red where Go preprocessing is darker than the reference, and blue where Go preprocessing is brighter. scripts/python_preprocess_reference.py is a development-only helper for exporting Python/Pillow reference files; the Go module, CLI, and HTTP service do not use Python at runtime.

For a repeatable local comparison workflow, install Pillow in your Python environment and run:

make prep-compare
# or compare private samples:
GODDDDOCR_PREP_REPORT_DIR=reports/preprocess \
  scripts/preprocess_compare.sh samples/local/*.png

The script writes per-sample Python references, Go preprocessing outputs, JSON reports, and diff PNGs under reports/preprocess/. It reports mismatches without failing by default; set GODDDDOCR_PREP_FAIL_ON_DIFF=true when you want CI-like failure on any preprocessing difference. For tolerance-based checks, set one or more thresholds:

GODDDDOCR_PREP_MAX_DIFF_PIXELS=2 \
GODDDDOCR_PREP_MAX_ABS_DIFF=1 \
GODDDDOCR_PREP_MAX_RMSE=0.02 \
  scripts/preprocess_compare.sh samples/yzm1.png

Status

  • OCR classification: implemented.
  • HTTP service: /health, /ocr, /ocr/file, /det, /det/file, /slide_comparison, /slide_match.
  • Detection: module and HTTP API implemented.
  • Slide comparison: module and HTTP API implemented.
  • Slide matching: module and HTTP API implemented.

License

goddddocr is released under the MIT License. Model and charset assets derived from ddddocr are tracked in NOTICE; keep that notice with source and binary redistributions.

Documentation

Index

Constants

View Source
const (
	DefaultMaxImageBytes = 8 << 20
	DefaultMaxBodyBytes  = 12 << 20
)
View Source
const DefaultClientTimeout = 10 * time.Second

Variables

This section is empty.

Functions

func InitRuntime

func InitRuntime(sharedLibraryPath string) error

InitRuntime initializes ONNX Runtime once for the process.

If sharedLibraryPath is empty, the function first checks ONNXRUNTIME_SHARED_LIBRARY_PATH, then ONNXRUNTIME_HOME, then a local third_party/onnxruntime/<GOOS>_<GOARCH>/ directory, then an embedded runtime if this build includes one. Finally, it asks the system dynamic loader for the platform's default ONNX Runtime library name.

func RuntimeLibraryPath

func RuntimeLibraryPath() string

RuntimeLibraryPath returns the path that initialized ONNX Runtime, or an empty string if InitRuntime has not succeeded yet.

func ShutdownRuntime

func ShutdownRuntime() error

ShutdownRuntime releases the ONNX Runtime process-wide environment. Most long-running services do not need to call this until process shutdown.

Types

type CharsetRange

type CharsetRange struct {
	// contains filtered or unexported fields
}

func NewCharsetRangeChars

func NewCharsetRangeChars(chars []string) *CharsetRange

func NewCharsetRangeLimit

func NewCharsetRangeLimit(maxIndex int) *CharsetRange

func NewCharsetRangeString

func NewCharsetRangeString(chars string) *CharsetRange

type ClassifyOptions

type ClassifyOptions struct {
	PNGFix       *bool
	CharsetRange *CharsetRange
	ColorFilter  *ColorFilterOptions
	Probability  bool
}

type ClassifyResult

type ClassifyResult struct {
	Text        string             `json:"text"`
	Confidence  float64            `json:"confidence"`
	Probability *ProbabilityMatrix `json:"probability,omitempty"`
}

type ColorFilterOptions

type ColorFilterOptions struct {
	Colors []string   `json:"colors,omitempty"`
	Ranges []HSVRange `json:"ranges,omitempty"`
}

func NewColorFilterColors

func NewColorFilterColors(colors ...string) *ColorFilterOptions

func NewColorFilterRanges

func NewColorFilterRanges(ranges ...HSVRange) *ColorFilterOptions

type Config

type Config struct {
	Model             Model
	ModelPath         string
	CharsetPath       string
	InputName         string
	OutputName        string
	SharedLibraryPath string
	PNGFix            bool
}

type DetectionBox

type DetectionBox struct {
	X1      int     `json:"x1"`
	Y1      int     `json:"y1"`
	X2      int     `json:"x2"`
	Y2      int     `json:"y2"`
	Score   float64 `json:"score,omitempty"`
	ClassID int     `json:"class_id,omitempty"`
}

func (DetectionBox) Rect

func (b DetectionBox) Rect() []int

type DetectionConfig

type DetectionConfig struct {
	ModelPath         string
	InputName         string
	OutputName        string
	SharedLibraryPath string
	InputSize         int
	ScoreThreshold    float64
	NMSThreshold      float64
}

type DetectionEngine

type DetectionEngine interface {
	DetectBytesDetailed(data []byte) ([]DetectionBox, error)
}

type DetectionOptions

type DetectionOptions struct {
	ScoreThreshold *float64 `json:"score_threshold,omitempty"`
	NMSThreshold   *float64 `json:"nms_threshold,omitempty"`
}

type Detector

type Detector struct {
	// contains filtered or unexported fields
}

func NewDetector

func NewDetector(config DetectionConfig) (*Detector, error)

func (*Detector) Close

func (d *Detector) Close() error

func (*Detector) DetectBytes

func (d *Detector) DetectBytes(data []byte) ([][]int, error)

func (*Detector) DetectBytesDetailed

func (d *Detector) DetectBytesDetailed(data []byte) ([]DetectionBox, error)

func (*Detector) DetectBytesDetailedWithOptions

func (d *Detector) DetectBytesDetailedWithOptions(data []byte, options *DetectionOptions) ([]DetectionBox, error)

func (*Detector) DetectImageDetailed

func (d *Detector) DetectImageDetailed(img image.Image) ([]DetectionBox, error)

func (*Detector) DetectImageDetailedWithOptions

func (d *Detector) DetectImageDetailedWithOptions(img image.Image, options *DetectionOptions) ([]DetectionBox, error)

type HSVRange

type HSVRange struct {
	Lower [3]int `json:"lower"`
	Upper [3]int `json:"upper"`
}

func (*HSVRange) UnmarshalJSON

func (r *HSVRange) UnmarshalJSON(data []byte) error

type LogFormat

type LogFormat string
const (
	LogFormatText LogFormat = "text"
	LogFormatJSON LogFormat = "json"
)

func ParseLogFormat

func ParseLogFormat(value string) (LogFormat, error)

type Model

type Model string
const (
	ModelOld    Model = "old"
	ModelBeta   Model = "beta"
	ModelCustom Model = "custom"
)

type OCR

type OCR struct {
	// contains filtered or unexported fields
}

func NewOCR

func NewOCR(config Config) (*OCR, error)

func (*OCR) Charset

func (o *OCR) Charset() []string

func (*OCR) ClassifyBytes

func (o *OCR) ClassifyBytes(data []byte, options *ClassifyOptions) (string, error)

func (*OCR) ClassifyBytesDetailed

func (o *OCR) ClassifyBytesDetailed(data []byte, options *ClassifyOptions) (*ClassifyResult, error)

func (*OCR) ClassifyImage

func (o *OCR) ClassifyImage(img image.Image, options *ClassifyOptions) (string, error)

func (*OCR) ClassifyImageDetailed

func (o *OCR) ClassifyImageDetailed(img image.Image, options *ClassifyOptions) (*ClassifyResult, error)

func (*OCR) Close

func (o *OCR) Close() error

func (*OCR) Model

func (o *OCR) Model() Model

type OCRClient

type OCRClient struct {
	// contains filtered or unexported fields
}

func NewOCRClient

func NewOCRClient(baseURL string, options ...OCRClientOption) *OCRClient

func (*OCRClient) ClassifyBytes

func (c *OCRClient) ClassifyBytes(ctx context.Context, image []byte, options *RemoteClassifyOptions) (*RemoteClassifyResult, error)

func (*OCRClient) DetectBytes

func (c *OCRClient) DetectBytes(ctx context.Context, image []byte, options *RemoteDetectOptions) (*RemoteDetectResult, error)

func (*OCRClient) Ready

func (c *OCRClient) Ready(ctx context.Context) error

func (*OCRClient) SlideComparisonBytes

func (c *OCRClient) SlideComparisonBytes(ctx context.Context, targetImage []byte, backgroundImage []byte) (*RemoteSlideComparisonResult, error)

func (*OCRClient) SlideMatchBytes

func (c *OCRClient) SlideMatchBytes(ctx context.Context, targetImage []byte, backgroundImage []byte, options *RemoteSlideMatchOptions) (*RemoteSlideMatchResult, error)

type OCRClientOption

type OCRClientOption func(*OCRClient)

func WithClientMaxImageBytes

func WithClientMaxImageBytes(n int64) OCRClientOption

func WithClientTimeout

func WithClientTimeout(timeout time.Duration) OCRClientOption

func WithHTTPClient

func WithHTTPClient(client *http.Client) OCRClientOption

type OCREngine

type OCREngine interface {
	Model() Model
	ClassifyBytesDetailed(data []byte, options *ClassifyOptions) (*ClassifyResult, error)
}

type OCRPool

type OCRPool struct {
	// contains filtered or unexported fields
}

func NewOCRPool

func NewOCRPool(config Config, workers int) (*OCRPool, error)

func (*OCRPool) ClassifyBytesDetailed

func (p *OCRPool) ClassifyBytesDetailed(data []byte, options *ClassifyOptions) (*ClassifyResult, error)

func (*OCRPool) Close

func (p *OCRPool) Close() error

func (*OCRPool) Model

func (p *OCRPool) Model() Model

func (*OCRPool) Size

func (p *OCRPool) Size() int

type PreprocessOptions

type PreprocessOptions struct {
	PNGFix      bool
	ColorFilter *ColorFilterOptions
}

type PreprocessResult

type PreprocessResult struct {
	Width  int       `json:"width"`
	Height int       `json:"height"`
	Data   []float32 `json:"data"`
}

func PreprocessOCRBytes

func PreprocessOCRBytes(data []byte, options *PreprocessOptions) (*PreprocessResult, error)

func PreprocessOCRImage

func PreprocessOCRImage(img image.Image, options *PreprocessOptions) (*PreprocessResult, error)

func (*PreprocessResult) GrayImage

func (r *PreprocessResult) GrayImage() (*image.Gray, error)

type ProbabilityMatrix

type ProbabilityMatrix struct {
	Text        string      `json:"text"`
	Charsets    []string    `json:"charsets"`
	Probability [][]float64 `json:"probability"`
	Confidence  float64     `json:"confidence"`
}

type RemoteClassifyOptions

type RemoteClassifyOptions struct {
	PNGFix                  *bool
	CharsetRange            any
	ColorFilterColors       []string
	ColorFilterCustomRanges []HSVRange
	Confidence              bool
	Probability             bool
}

type RemoteClassifyResult

type RemoteClassifyResult struct {
	Result           string             `json:"result"`
	ProcessingTimeMS float64            `json:"processing_time_ms"`
	RequestID        string             `json:"request_id,omitempty"`
	Confidence       float64            `json:"confidence,omitempty"`
	Probability      *ProbabilityMatrix `json:"probability,omitempty"`
}

type RemoteDetectOptions

type RemoteDetectOptions struct {
	Detailed       bool
	ScoreThreshold *float64
	NMSThreshold   *float64
}

type RemoteDetectResult

type RemoteDetectResult struct {
	Result           [][]int        `json:"result"`
	Boxes            []DetectionBox `json:"boxes,omitempty"`
	ProcessingTimeMS float64        `json:"processing_time_ms"`
	RequestID        string         `json:"request_id,omitempty"`
}

type RemoteError

type RemoteError struct {
	StatusCode int
	Code       string
	Message    string
	RequestID  string
}

func (*RemoteError) Error

func (e *RemoteError) Error() string

type RemoteSlideComparisonResult

type RemoteSlideComparisonResult struct {
	Result           SlideResult `json:"result"`
	ProcessingTimeMS float64     `json:"processing_time_ms"`
	RequestID        string      `json:"request_id,omitempty"`
}

type RemoteSlideMatchOptions

type RemoteSlideMatchOptions struct {
	SimpleTarget bool
}

type RemoteSlideMatchResult

type RemoteSlideMatchResult struct {
	Result           SlideResult `json:"result"`
	ProcessingTimeMS float64     `json:"processing_time_ms"`
	RequestID        string      `json:"request_id,omitempty"`
}

type Server

type Server struct {
	// contains filtered or unexported fields
}

func NewServer

func NewServer(ocr OCREngine, options ...ServerOption) *Server

func (*Server) Handler

func (s *Server) Handler() http.Handler

func (*Server) Metrics

func (s *Server) Metrics() ServerMetricsSnapshot

type ServerMetricsSnapshot

type ServerMetricsSnapshot struct {
	StartedAt          string            `json:"started_at"`
	UptimeSeconds      float64           `json:"uptime_seconds"`
	TotalRequests      uint64            `json:"total_requests"`
	InFlightRequests   int64             `json:"in_flight_requests"`
	CompletedRequests  uint64            `json:"completed_requests"`
	ErrorRequests      uint64            `json:"error_requests"`
	StatusCodes        map[string]uint64 `json:"status_codes"`
	TotalLatencyMS     float64           `json:"total_latency_ms"`
	AverageLatencyMS   float64           `json:"average_latency_ms"`
	MaxLatencyMS       float64           `json:"max_latency_ms"`
	LastRequestAt      string            `json:"last_request_at,omitempty"`
	LastRequestStatus  int               `json:"last_request_status,omitempty"`
	LastRequestLatency float64           `json:"last_request_latency_ms,omitempty"`
}

type ServerOption

type ServerOption func(*Server)

func WithDetector

func WithDetector(detector DetectionEngine) ServerOption

func WithLogFormat

func WithLogFormat(format LogFormat) ServerOption

func WithLogger

func WithLogger(logger *log.Logger) ServerOption

func WithMaxBodyBytes

func WithMaxBodyBytes(n int64) ServerOption

func WithMaxImageBytes

func WithMaxImageBytes(n int64) ServerOption

type SlideResult

type SlideResult struct {
	Target     []int   `json:"target"`
	TargetX    int     `json:"target_x"`
	TargetY    int     `json:"target_y"`
	Confidence float64 `json:"confidence,omitempty"`
}

func SlideComparisonBytes

func SlideComparisonBytes(targetData []byte, backgroundData []byte) (*SlideResult, error)

func SlideComparisonImages

func SlideComparisonImages(target image.Image, background image.Image) (*SlideResult, error)

func SlideMatchBytes

func SlideMatchBytes(targetData []byte, backgroundData []byte, simpleTarget bool) (*SlideResult, error)

func SlideMatchImages

func SlideMatchImages(target image.Image, background image.Image, simpleTarget bool) (*SlideResult, error)

Directories

Path Synopsis
cmd
goddddocr command
ocrbench command
ocrdoctor command
ocreval command
ocrprep command
ortfetch command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL