Skip to content

オフライン OCR モデル管理

PDF Oxide の OCR は、ローカルのキャッシュディレクトリに配置された ONNX の検出モデルと認識モデルを使用します。Docker ビルド、CI、エアギャップ/オフライン環境では、最初の OCR 呼び出しより前にモデルを用意しておく必要があります。リクエスト時にダウンロードするのは避けましょう。PDF Oxide はそのための基本機能を 3 つ提供しています。

  • prefetch_models — 共有検出器と言語ごとの認識モデル・辞書をモデルキャッシュディレクトリにダウンロードします(ビルド時プロビジョニング)。
  • model_manifest — すべてのモデルファイルとそのソース URL をネットワーク不要で取得できる JSON マニフェスト。エアギャップホストでのミラーリング・検証に使います。
  • prefetch_available — このビルドが実際にダウンロード可能かどうか(ocr フィーチャー付きでコンパイルされているか)を返します。

キャッシュディレクトリは $PDF_OXIDE_MODEL_DIR が設定されていればそのパス、未設定の場合はプラットフォームキャッシュ(Linux では ~/.cache/pdf_oxide/models)が使われます。ファイルが揃えば、OCR は完全オフラインで動作します。

バインディングの対応状況。 モデルプロビジョニングは RustGoC#Swift で利用できます。model_manifestprefetch_availableWASM/JavaScript でも公開されています(prefetchAvailable() は WASM では常に false を返します。WASM にはネットワークフェッチャーがないため、マニフェストを使ってホスト側でプロビジョニングしてください)。Python および Node N-API バインディングでは v0.3.69 時点でこれらは公開されていません。

オフライン用に OCR モデルをプリフェッチするには?

prefetch_models はカンマ区切りの言語コードを受け取り(空の場合は英語)、共有検出器と各言語の認識モデル・辞書をキャッシュディレクトリにダウンロードし、そのディレクトリパスを返します。冪等性があります — すでに存在するファイルはスキップされます。

Rust

use pdf_oxide::extractors::auto::{AutoExtractor, OcrLanguage};

fn main() -> pdf_oxide::Result<()> {
    // AutoExtractor::prefetch_models(langs: &[OcrLanguage])
    //   -> Result<std::path::PathBuf>
    let dir = AutoExtractor::prefetch_models(&[
        OcrLanguage::English,
        OcrLanguage::Chinese,
        OcrLanguage::Arabic,
    ])?;
    println!("models cached in {}", dir.display());

    // One-shot English (the common case):
    let _ = AutoExtractor::prefetch_models_default()?;
    Ok(())
}

Go

package main

import (
	"fmt"
	"log"

	pdfoxide "github.com/yfedoseev/pdf_oxide/go"
)

func main() {
	if !pdfoxide.PrefetchAvailable() {
		log.Fatal("this build cannot download models (built without the ocr feature)")
	}

	// func PrefetchModels(langs ...string) (string, error)
	dir, err := pdfoxide.PrefetchModels("english", "chinese", "arabic")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("models cached in", dir)
}

C#

using System;
using PdfOxide.Core;

if (!PdfDocument.PrefetchAvailable())
    throw new InvalidOperationException("built without the ocr feature; cannot download models");

// static string PdfDocument.PrefetchModels(params string[] languages)
string dir = PdfDocument.PrefetchModels("english", "chinese", "arabic");
Console.WriteLine($"models cached in {dir}");

Swift

import PdfOxide

guard PdfOxide.prefetchAvailable() == 1 else {
    fatalError("built without the ocr feature; cannot download models")
}

// static func prefetchModels(languagesCsv: String) throws -> String
let dir = try PdfOxide.prefetchModels(languagesCsv: "english,chinese,arabic")
print("models cached in \(dir)")

PHP

use PdfOxide\Pdf;

if (!Pdf::prefetchAvailable()) {
    throw new RuntimeException('built without the ocr feature; cannot download models');
}

// static Pdf::prefetchModels(array $languages): string
$dir = Pdf::prefetchModels(['english', 'chinese', 'arabic']);
echo "models cached in {$dir}\n";

Ruby

require 'pdf_oxide'

unless PdfOxide::Pdf.prefetch_available?
  raise 'built without the ocr feature; cannot download models'
end

# PdfOxide::Pdf.prefetch_models(languages) -> String (cache dir)
dir = PdfOxide::Pdf.prefetch_models(%w[english chinese arabic])
puts "models cached in #{dir}"

C++

#include <pdf_oxide/pdf_oxide.hpp>
#include <iostream>

if (pdf_oxide::prefetch_available() == 0)
    throw std::runtime_error("built without the ocr feature; cannot download models");

// std::string pdf_oxide::prefetch_models(const std::string& languages_csv)
auto dir = pdf_oxide::prefetch_models("english,chinese,arabic");
std::cout << "models cached in " << dir << "\n";

Dart

import 'package:pdf_oxide/pdf_oxide.dart' as pdf_oxide;

if (pdf_oxide.prefetchAvailable() == 0) {
  throw StateError('built without the ocr feature; cannot download models');
}

// String prefetchModels(String languagesCsv)
final dir = pdf_oxide.prefetchModels('english,chinese,arabic');
print('models cached in $dir');

R

library(pdfoxide)

if (pdf_prefetch_available() == 0)
  stop("built without the ocr feature; cannot download models")

# pdf_prefetch_models(languages_csv = NULL) -> cache directory path
dir <- pdf_prefetch_models("english,chinese,arabic")
cat("models cached in", dir, "\n")

Julia

using PdfOxide

prefetch_available() != 0 || error("built without the ocr feature; cannot download models")

# prefetch_models(languages_csv::AbstractString) -> cache directory path
dir = prefetch_models("english,chinese,arabic")
println("models cached in ", dir)

Zig

const pdf_oxide = @import("pdf_oxide");
const a = std.heap.page_allocator;

if (pdf_oxide.prefetchAvailable() == 0) return error.OcrFeatureMissing;

// prefetchModels(alloc, languages_csv) -> []u8 (cache dir; caller frees)
const dir = try pdf_oxide.prefetchModels(a, "english,chinese,arabic");
defer a.free(dir);
std.debug.print("models cached in {s}\n", .{dir});

Objective-C

#import "POXPdfOxide.h"
NSError *err = nil;

if ([POXModels prefetchAvailable] <= 0) {
    @throw [NSException exceptionWithName:@"PdfOxide" reason:@"no ocr feature" userInfo:nil];
}

// + prefetchModels:error: returns a status JSON (nil on error)
NSString *status = [POXModels prefetchModels:@"english,chinese,arabic" error:&err];
NSLog(@"prefetch status: %@", status);

Elixir

unless PdfOxide.prefetch_available() != 0 do
  raise "built without the ocr feature; cannot download models"
end

# prefetch_models(languages_csv \\ "") -> JSON status string
status = PdfOxide.prefetch_models("english,chinese,arabic")
IO.puts("prefetch status: #{status}")

言語コード

prefetch_models は以下のコードを受け付けます(不明なコードはスキップされ、空入力は英語にデフォルトします)。

english, chinese, chinese_cht, japan, korean, arabic, cyrillic, latin, devanagari, ta(タミル語), te(テルグ語), ka(カンナダ語)

エアギャップホストでモデルをプロビジョニングするには?

インターネット接続のないマシン(または WASM のようにフェッチャーを持たないターゲット)では prefetch_models を呼び出せません。代わりに model_manifest を使います。これはすべてのモデルファイルとそのアップストリーム URL を静的かつネットワーク不要で列挙した JSON です。URL をアーティファクトストア経由でミラーリングし、$PDF_OXIDE_MODEL_DIR にファイルを配置してください。

Rust

use pdf_oxide::extractors::auto::AutoExtractor;

fn main() {
    // AutoExtractor::model_manifest() -> String   (JSON, never errors)
    let manifest = AutoExtractor::model_manifest();
    println!("{manifest}");
}

Go

// func ModelManifest() string   (JSON, never errors)
fmt.Println(pdfoxide.ModelManifest())

C#

// static string PdfDocument.ModelManifest()
Console.WriteLine(PdfDocument.ModelManifest());

Swift

// static func modelManifest() -> String   (JSON)
print(PdfOxide.modelManifest())

JavaScript (WASM)

import init, { modelManifest, prefetchAvailable } from "pdf-oxide-wasm";

await init();

// prefetchAvailable() is always false in WASM — provision host-side.
console.log("can download here?", prefetchAvailable()); // false
console.log(modelManifest());                            // JSON manifest

PHP

use PdfOxide\FFI\FunctionBindings;

// (new FunctionBindings())->pdfOxideModelManifest(): string  (JSON, never errors)
$manifest = (new FunctionBindings())->pdfOxideModelManifest();
echo $manifest, "\n";

C++

#include <pdf_oxide/pdf_oxide.hpp>
#include <iostream>

// std::string pdf_oxide::model_manifest()   (JSON, never errors)
std::cout << pdf_oxide::model_manifest() << "\n";

Dart

import 'package:pdf_oxide/pdf_oxide.dart' as pdf_oxide;

// String modelManifest()   (JSON)
print(pdf_oxide.modelManifest());

R

library(pdfoxide)

# pdf_model_manifest() -> JSON string
cat(pdf_model_manifest(), "\n")

Julia

using PdfOxide

# model_manifest() -> JSON String
println(model_manifest())

Zig

const pdf_oxide = @import("pdf_oxide");
const a = std.heap.page_allocator;

// modelManifest(alloc) -> []u8 (JSON; caller frees)
const manifest = try pdf_oxide.modelManifest(a);
defer a.free(manifest);
std.debug.print("{s}\n", .{manifest});

Objective-C

#import "POXPdfOxide.h"
NSError *err = nil;

// + manifestWithError: -> JSON string (nil on error)
NSString *manifest = [POXModels manifestWithError:&err];
NSLog(@"%@", manifest);

Elixir

# model_manifest() -> JSON string
IO.puts(PdfOxide.model_manifest())

マニフェストの構造

{
  "detector": {
    "file": "det.onnx",
    "url": "https://.../det.onnx"
  },
  "languages": [
    {
      "language": "english",
      "rec_file": "rec.onnx",
      "dict_file": "en_dict.txt",
      "rec_url": "https://.../rec.onnx",
      "dict_url": "https://.../en_dict.txt"
    }
  ],
  "note": "Hebrew has no upstream PaddleOCR recognition model; the loader is ready if one is provided."
}

detector.url と各言語の rec_url / dict_url をミラーリングし、det.onnx と各 rec_file / dict_filePDF_OXIDE_MODEL_DIR に配置してください。これで OCR はネットワークアクセスなしで動作します。

このビルドはモデルのダウンロードに対応しているか?

prefetch_available は、ネイティブライブラリが ocr フィーチャー(HTTP フェッチャーを含む)付きでコンパイルされているかどうかを返します。false の場合、prefetch_models はキャッシュディレクトリを作成するものの、ダウンロードは行いません。フェッチに依存する前に必ず確認してください。

Rust

use pdf_oxide::extractors::auto::AutoExtractor;

// AutoExtractor::prefetch_available() -> bool
if AutoExtractor::prefetch_available() {
    let _ = AutoExtractor::prefetch_models_default();
} else {
    eprintln!("OCR feature not compiled in — provision via model_manifest()");
}

Gopdfoxide.PrefetchAvailable() bool C#PdfDocument.PrefetchAvailable() -> bool SwiftPdfOxide.prefetchAvailable() -> Int32 (1 == yes)

Dockerfile の例

ビルド時にモデルをイメージに組み込み、実行中のコンテナがネットワークにアクセスしないようにします。

FROM rust:1 AS models
WORKDIR /app
COPY . .
# Build the CLI / your binary with the `ocr` feature, then prefetch.
ENV PDF_OXIDE_MODEL_DIR=/models
RUN cargo run --features ocr --bin prefetch -- english chinese

FROM debian:stable-slim
ENV PDF_OXIDE_MODEL_DIR=/models
COPY --from=models /models /models
# OCR now runs fully offline against /models

グローバルエンジン設定

抽出エンジンを調整するプロセスグローバルなセッターが 2 つあります。どちらも C-ABI バインディング全体で公開されており、直前の値を返し、エラーチャンネルはありません(失敗しません)。プロセスグローバルなため、一方のスレッドで設定すると、並行するすべての抽出に影響します。

コンテンツストリームの演算子上限を引き上げるには?

PDF Oxide はコンテンツストリームの演算子数をストリームごとに制限しています(デフォルト 1,000,000)。これは悪意あるインプットのコストを抑えるためです。合法的な大規模 PDF(教科書、ISO 規格など)ではこの上限を超えることがあります。set_max_ops_per_stream で上限を引き上げ(または引き下げ)ることができ、直前の値を返します。

Rust

// pdf_oxide::content::parser::set_max_ops_per_stream(limit: Option<usize>)
//   -> Option<usize>   (None restores the 1,000,000 default)
use pdf_oxide::content::parser::set_max_ops_per_stream;

let prev = set_max_ops_per_stream(Some(5_000_000));
// ... extract a huge trusted PDF ...
set_max_ops_per_stream(prev); // restore

Go

// func SetMaxOpsPerStream(limit int64) int64   (returns previous cap)
prev := pdfoxide.SetMaxOpsPerStream(5_000_000)
defer pdfoxide.SetMaxOpsPerStream(prev)

C#

// static long CAbi.SetMaxOpsPerStream(long limit)   (returns previous cap)
long prev = PdfOxide.Core.CAbi.SetMaxOpsPerStream(5_000_000);
try { /* extract huge trusted PDF */ }
finally { PdfOxide.Core.CAbi.SetMaxOpsPerStream(prev); }

Swift

// static func setMaxOpsPerStream(_ limit: Int64) -> Int64
let prev = PdfOxide.setMaxOpsPerStream(5_000_000)
defer { _ = PdfOxide.setMaxOpsPerStream(prev) }

PHP

use PdfOxide\FFI\FunctionBindings;

$bindings = new FunctionBindings();
// pdfOxideSetMaxOpsPerStream(int $limit): int   (returns previous cap; -1 = default was active)
$prev = $bindings->pdfOxideSetMaxOpsPerStream(5_000_000);
try { /* extract huge trusted PDF */ }
finally { $bindings->pdfOxideSetMaxOpsPerStream($prev); }

Ruby

require 'pdf_oxide'

# PdfOxide.set_max_ops_per_stream(limit) -> previous cap (-1 = default was active)
prev = PdfOxide.set_max_ops_per_stream(5_000_000)
begin
  # ... extract a huge trusted PDF ...
ensure
  PdfOxide.set_max_ops_per_stream(prev)
end

C++

#include <pdf_oxide/pdf_oxide.hpp>

// std::int64_t pdf_oxide::set_max_ops_per_stream(std::int64_t limit) -> previous cap
auto prev = pdf_oxide::set_max_ops_per_stream(5'000'000);
// ... extract a huge trusted PDF ...
pdf_oxide::set_max_ops_per_stream(prev); // restore

Dart

import 'package:pdf_oxide/pdf_oxide.dart' as pdf_oxide;

// int setMaxOpsPerStream(int limit) -> previous cap
final prev = pdf_oxide.setMaxOpsPerStream(5000000);
// ... extract a huge trusted PDF ...
pdf_oxide.setMaxOpsPerStream(prev); // restore

R

library(pdfoxide)

# pdf_set_max_ops_per_stream(limit) -> previous cap (negative limit restores default)
prev <- pdf_set_max_ops_per_stream(5000000)
# ... extract a huge trusted PDF ...
pdf_set_max_ops_per_stream(prev)  # restore

Julia

using PdfOxide

# set_max_ops_per_stream(limit::Integer) -> previous cap
prev = set_max_ops_per_stream(5_000_000)
# ... extract a huge trusted PDF ...
set_max_ops_per_stream(prev)  # restore

Zig

const pdf_oxide = @import("pdf_oxide");

// setMaxOpsPerStream(limit: i64) i64   (returns previous cap)
const prev = pdf_oxide.setMaxOpsPerStream(5_000_000);
// ... extract a huge trusted PDF ...
_ = pdf_oxide.setMaxOpsPerStream(prev); // restore

Objective-C

#import "POXPdfOxide.h"

// + setMaxOpsPerStream: -> previous cap
int64_t prev = [POXConfig setMaxOpsPerStream:5000000];
// ... extract a huge trusted PDF ...
[POXConfig setMaxOpsPerStream:prev]; // restore

Elixir

# set_max_ops_per_stream(limit) -> previous cap (-1 = default was active)
prev = PdfOxide.set_max_ops_per_stream(5_000_000)
# ... extract a huge trusted PDF ...
PdfOxide.set_max_ops_per_stream(prev)

C ABI では、pdf_oxide_set_max_ops_per_stream(limit)負の値を渡すと「デフォルトに戻す」として扱われ、直前がデフォルト値だった場合は -1 を返します。

マッピングされていない(U+FFFD)グリフを保持するには?

デフォルトでは、高レベルアクセサ(extract_text / extract_words / extract_spans)は Unicode マッピングを持たないグリフをフィルタリングします(これらは U+FFFD として表面化します)。可視グリフがすべて U+FFFD にマップされるページ(例:MSAM10 のような数学記号フォント)では、空の出力が生成されることがあります。set_preserve_unmapped_glyphs(true) を呼び出すと、これらのアクセサが置換文字を保持するようになり、後処理が可能になります。以前の設定値が返されます。

Rust

// pdf_oxide::extractors::text::set_preserve_unmapped_glyphs(preserve: bool)
//   -> bool   (returns previous value)
use pdf_oxide::extractors::text::set_preserve_unmapped_glyphs;

let prev = set_preserve_unmapped_glyphs(true);
// ... extract a math-heavy PDF; U+FFFD glyphs are now kept ...
set_preserve_unmapped_glyphs(prev);

Go

// func SetPreserveUnmappedGlyphs(preserve int) int   (1 = preserve; returns previous)
prev := pdfoxide.SetPreserveUnmappedGlyphs(1)
defer pdfoxide.SetPreserveUnmappedGlyphs(prev)

C#

// static int CAbi.SetPreserveUnmappedGlyphs(bool preserve)   (returns previous, 0/1)
int prev = PdfOxide.Core.CAbi.SetPreserveUnmappedGlyphs(true);
try { /* extract math-heavy PDF */ }
finally { PdfOxide.Core.CAbi.SetPreserveUnmappedGlyphs(prev != 0); }

Swift

// static func setPreserveUnmappedGlyphs(_ preserve: Int32) -> Int32
let prev = PdfOxide.setPreserveUnmappedGlyphs(1)
defer { _ = PdfOxide.setPreserveUnmappedGlyphs(prev) }

PHP

use PdfOxide\FFI\FunctionBindings;

$bindings = new FunctionBindings();
// pdfOxideSetPreserveUnmappedGlyphs(int $preserve): int   (1 = preserve; returns previous, 0/1)
$prev = $bindings->pdfOxideSetPreserveUnmappedGlyphs(1);
try { /* extract math-heavy PDF */ }
finally { $bindings->pdfOxideSetPreserveUnmappedGlyphs($prev); }

Ruby

require 'pdf_oxide'

# PdfOxide.set_preserve_unmapped_glyphs(preserve) -> previous value (0 or 1)
prev = PdfOxide.set_preserve_unmapped_glyphs(true)
begin
  # ... extract a math-heavy PDF; U+FFFD glyphs are now kept ...
ensure
  PdfOxide.set_preserve_unmapped_glyphs(prev)
end

C++

#include <pdf_oxide/pdf_oxide.hpp>

// int pdf_oxide::set_preserve_unmapped_glyphs(int preserve) -> previous value
int prev = pdf_oxide::set_preserve_unmapped_glyphs(1);
// ... extract a math-heavy PDF; U+FFFD glyphs are now kept ...
pdf_oxide::set_preserve_unmapped_glyphs(prev); // restore

Dart

import 'package:pdf_oxide/pdf_oxide.dart' as pdf_oxide;

// int setPreserveUnmappedGlyphs(int preserve) -> previous value
final prev = pdf_oxide.setPreserveUnmappedGlyphs(1);
// ... extract a math-heavy PDF; U+FFFD glyphs are now kept ...
pdf_oxide.setPreserveUnmappedGlyphs(prev); // restore

R

library(pdfoxide)

# pdf_set_preserve_unmapped_glyphs(preserve) -> previous value (0 or 1)
prev <- pdf_set_preserve_unmapped_glyphs(1L)
# ... extract a math-heavy PDF; U+FFFD glyphs are now kept ...
pdf_set_preserve_unmapped_glyphs(prev)  # restore

Julia

using PdfOxide

# set_preserve_unmapped_glyphs(preserve::Integer) -> previous value (0 or 1)
prev = set_preserve_unmapped_glyphs(1)
# ... extract a math-heavy PDF; U+FFFD glyphs are now kept ...
set_preserve_unmapped_glyphs(prev)  # restore

Zig

const pdf_oxide = @import("pdf_oxide");

// setPreserveUnmappedGlyphs(preserve: bool) i32   (returns previous value)
const prev = pdf_oxide.setPreserveUnmappedGlyphs(true);
// ... extract a math-heavy PDF; U+FFFD glyphs are now kept ...
_ = pdf_oxide.setPreserveUnmappedGlyphs(prev != 0); // restore

Objective-C

#import "POXPdfOxide.h"

// + setPreserveUnmappedGlyphs: -> previous value (0 or 1)
int32_t prev = [POXConfig setPreserveUnmappedGlyphs:1];
// ... extract a math-heavy PDF; U+FFFD glyphs are now kept ...
[POXConfig setPreserveUnmappedGlyphs:prev]; // restore

Elixir

# set_preserve_unmapped_glyphs(preserve) -> previous value (0 or 1)
prev = PdfOxide.set_preserve_unmapped_glyphs(1)
# ... extract a math-heavy PDF; U+FFFD glyphs are now kept ...
PdfOxide.set_preserve_unmapped_glyphs(prev)

C ABI では、pdf_oxide_set_preserve_unmapped_glyphs(preserve)1 で保持・0 でフィルタリングを設定し、直前の値を 0 または 1 で返します。

FAQ

OCR モデルはどこに保存されますか? $PDF_OXIDE_MODEL_DIR が設定されていればそのパス、未設定の場合はプラットフォームキャッシュ(Linux では ~/.cache/pdf_oxide/models)です。このパスは prefetch_models の戻り値でもあります。

prefetch_models を繰り返し呼び出しても安全ですか? はい、冪等です。既存のファイルはスキップされるため、起動のたびにセーフネットとして呼び出しても問題ありません。

prefetch_available が false を返すのに prefetch を呼び出した場合はどうなりますか? ビルドが ocr フィーチャーなしでコンパイルされているため HTTP フェッチャーがありません。prefetch_models はキャッシュディレクトリを作成しますが何もダウンロードしません。model_manifest を使って手動でファイルを用意してください。

グローバルセッターはリセットが必要ですか? プロセスグローバルで変更するまで維持されます。特定のドキュメントだけに上書きを適用したい場合は、セッターが返す直前の値を使って復元してください。どちらのセッターも失敗せず、エラーチャンネルもありません。

関連ページ