xberg について
xbergは、ドキュメント処理を実装する開発者向けの抽出ライブラリ兼コーディングスキルです。多数の形式に対応し、各言語バインディングとCLIからテキスト、表、メタデータ、画像、OCR、バッチ抽出を利用できます。
主な機能
- 01多数のドキュメント形式から抽出
- 02テキスト・表・メタデータ・画像の抽出
- 03画像やスキャンPDFのOCR
- 04入力ごとのエラーを扱うバッチ処理
- 05出力形式・分割・言語検出の設定
活用シーン
- 01後続処理向けのドキュメント内容抽出
- 02スキャンファイルのOCR実行
- 03複数ドキュメントの一括処理
MCP 対応
セッションにxberg MCPサーバーが登録されている場合、構造化された引数と結果を使える抽出ツールを利用するよう案内しています。サーバーはCLIと同じ抽出機能を提供します。
インストール
コマンドをコピーしてターミナルで実行します。
npx skills add https:/ / github.com/ xberg-io/ xberg --skill xbergインストール後、Claude Code で/xbergを入力して読み込まれたか確認します。
同梱ファイル
SKILL.md と一緒にインストールされる参考資料やスクリプト。
index.mdreferences/cli-reference.mdadvanced-features.mdother-bindings.mdconfiguration.mdpython-api.mdrust-api.mdsupported-formats.mdnodejs-api.md詳細
Xberg ドキュメント抽出
Xberg は Rust コアを備え、Python、TypeScript/Node.js、Ruby、PHP、Go、Java、C#、Elixir、WebAssembly、Dart、Kotlin Android、Swift、Zig、C 向けのバインディングを提供するドキュメントインテリジェンスライブラリです。PDF、Office ドキュメント、画像、HTML、メール、アーカイブ、学術文書など、140 種類の固有のファイル拡張子にわたる107形式から、テキスト、表、メタデータ、画像を抽出します。また、53種類の互換 MIME エイリアスを受け付けます。
以下のようなコードを書く場合に、このスキルを使用してください。
- ドキュメントからテキストやメタデータを抽出する
- スキャンしたドキュメントや画像に OCR を実行する
- 複数のファイルを一括処理する
- 抽出オプション(出力形式、チャンク化、OCR、言語検出)を設定する
- カスタムプラグイン(後処理器、バリデーター、OCR バックエンド)を実装する
このセッションに
xbergMCP サーバーが登録されている場合、CLI をシェルから実行するよりも、そのツールを優先してください。同じ抽出機能を、構造化された引数と結果で利用できます。
インストール
Python
pip install xberg
Node.js
npm install @xberg-io/xberg
Rust
cargo add xberg
# Cargo.toml
[dependencies]
xberg = { version = "1.1.0", features = ["full"] }
tokio = { version = "1", features = ["full"] }
# feature flags: pdf, ocr, chunking, embeddings, language-detection, keywords, api, mcp
# (or "formats" / "full" aggregates); tokio-runtime is on by default
CLI
brew install xberg-io/tap/xberg
# or run without a persistent install (the CLI proxy package self-installs the binary):
npx @xberg-io/[email protected] --help
uvx --from xberg-cli==1.3.8 xberg --help
# or download a prebuilt binary from the latest GitHub release:
# https://github.com/xberg-io/xberg/releases/latest
# or build from source:
cargo install xberg-cli
クイックスタート
ライブラリのエントリーポイントは extract(input, config) と extract_batch(inputs, config) です。どちらも ExtractionResult エンベロープを返します。抽出されたドキュメントは result.results に格納され、ドキュメントごとのデータ(content、tables、metadata など)は各 result.results[i] に格納されます。Python と Node は非同期のみです。
Python
import asyncio
from xberg import ExtractInput, extract, ExtractionConfig
async def main() -> None:
result = await extract(ExtractInput(uri="document.pdf"), ExtractionConfig())
doc = result.results[0]
print(doc.content) # extracted text
print(doc.metadata) # document metadata
print(doc.tables) # extracted tables
asyncio.run(main())
Node.js
import { extract } from "@xberg-io/xberg";
const output = await extract({ kind: "uri", uri: "document.pdf" });
const doc = output.results[0];
console.log(doc.content);
console.log(doc.metadata);
console.log(doc.tables);
Rust
use xberg::{extract, ExtractInput, ExtractionConfig};
#[tokio::main]
async fn main() -> xberg::Result<()> {
let output = extract(ExtractInput::from_uri("document.pdf"), &ExtractionConfig::default()).await?;
println!("{}", output.results[0].content);
Ok(())
}
CLI
xberg extract document.pdf
xberg extract document.pdf --format json
xberg extract document.pdf --content-format markdown
設定
すべての言語で同じ設定構造を使用し、各言語に適した命名規則に従います。
Python(snake_case)
from xberg import (
ExtractInput, extract,
ExtractionConfig, OcrConfig, TesseractConfig, PdfConfig, ChunkingConfig, OutputFormat,
)
config = ExtractionConfig(
ocr=OcrConfig(
backend="tesseract",
language=["eng"],
tesseract_config=TesseractConfig(psm=6, enable_table_detection=True),
),
pdf_options=PdfConfig(passwords=["secret123"]),
chunking=ChunkingConfig(max_characters=1000, overlap=200),
output_format=OutputFormat("markdown"),
)
result = await extract(ExtractInput(uri="document.pdf"), config)
Node.js(camelCase)
import { extract, type ExtractionConfig } from "@xberg-io/xberg";
const config: ExtractionConfig = {
ocr: { backend: "tesseract", language: ["eng"] },
pdfOptions: { passwords: ["secret123"] },
chunking: { maxCharacters: 1000, overlap: 200 },
outputFormat: "markdown",
};
const output = await extract({ kind: "uri", uri: "document.pdf" }, config);
Rust(snake_case)
use xberg::{extract, ExtractInput, ExtractionConfig, OcrConfig, ChunkingConfig, OutputFormat};
let config = ExtractionConfig {
ocr: Some(OcrConfig {
backend: "tesseract".into(),
language: vec!["eng".to_string()],
..Default::default()
}),
chunking: Some(ChunkingConfig {
max_characters: 1000,
overlap: 200,
..Default::default()
}),
output_format: OutputFormat::Markdown,
..Default::default()
};
let output = extract(ExtractInput::from_uri("document.pdf"), &config).await?;
設定ファイル(TOML)
output_format = "markdown"
[ocr]
backend = "tesseract"
language = "eng"
[chunking]
max_characters = 1000
overlap = 200
[pdf_options]
passwords = ["secret123"]
# CLI: auto-discovers xberg.toml/yaml/yml/json in current/parent directories
xberg extract doc.pdf
# or explicit:
xberg extract doc.pdf --config xberg.toml
xberg extract doc.pdf --config-json '{"ocr":{"backend":"tesseract","language":"deu"}}'
バッチ処理
extract_batch は ExtractInput のリストを受け取り、results 配列に検出順でドキュメントを格納した1つのエンベロープを返します。1つの入力から複数のドキュメントが生成される場合があります。入力ごとの失敗は、入力インデックスとともに result.errors に報告されます。
Python
from xberg import ExtractInput, extract_batch, ExtractionConfig
inputs = [
ExtractInput(uri="doc1.pdf"),
ExtractInput(uri="doc2.docx"),
ExtractInput(uri="doc3.xlsx"),
]
output = await extract_batch(inputs, ExtractionConfig())
for doc in output.results:
print(f"{len(doc.content)} chars extracted")
Node.js
import { extractBatch } from "@xberg-io/xberg";
const output = await extractBatch([
{ kind: "uri", uri: "doc1.pdf" },
{ kind: "uri", uri: "doc2.docx" },
]);
for (const doc of output.results) {
console.log(`${doc.content.length} chars`);
}
Rust
use xberg::{extract_batch, ExtractInput, ExtractionConfig};
let config = ExtractionConfig::default();
let inputs = vec![ExtractInput::from_uri("doc1.pdf"), ExtractInput::from_uri("doc2.docx")];
let output = extract_batch(inputs, &config).await?;
CLI
xberg batch *.pdf --format json
xberg batch docs/*.docx --content-format markdown
OCR
画像とスキャンされた PDF には、自動的に OCR が実行されます。デフォルトのバックエンドは Tesseract です(ネイティブバインディングを使用するため、外部インストールは不要です)。
バックエンド
OcrConfig.backend で選択します。
- tesseract(デフォルト):組み込みのネイティブバインディングです。Tesseract がサポートするすべての言語を使用できます。
- paddleocr(
"paddleocr"/"paddle-ocr"):ONNX ベースの PaddleOCR です。 - vlm:Vision-Language-Model OCR(
OcrConfig.vlm_configで設定します)。
カスタムバックエンドは、Python/Node で register_ocr_backend を使って登録できます(高度な機能を参照)。
言語コード
config = ExtractionConfig(ocr=OcrConfig(language=["eng"])) # English
config = ExtractionConfig(ocr=OcrConfig(language=["eng", "deu"])) # Multiple
# The single-string shorthand ("eng+deu") is only accepted in config files / --config-json,
# not in the OcrConfig constructor (Python takes a list, Node takes an array).
OCR の強制実行
config = ExtractionConfig(force_ocr=True) # OCR even if text is extractable
結果エンベロープとドキュメントフィールド
extract/extract_batch は ExtractionResult エンベロープを返します。内容は results(ドキュメントのリスト)、errors(入力ごとの失敗)、summary(件数)です。ドキュメントごとのフィールドは results 内の各ドキュメントにあります。まず doc = result.results[0](Python/Node)または &output.results[0](Rust)をバインドしてください。
| フィールド | Python(doc.) | Node.js(doc.) | Rust(document.) | 説明 |
|---|---|---|---|---|
| テキストコンテンツ | content | content | content | 抽出されたテキスト(str/String) |
| MIME タイプ | mime_type | mimeType | mime_type | 入力ドキュメントの MIME タイプ |
| メタデータ | metadata | metadata | metadata | ドキュメントのメタデータ(フラットマッピング) |
| テーブル | tables | tables | tables | セルと Markdown を含む抽出済みテーブル |
| 言語 | detected_languages | detectedLanguages | detected_languages | 検出された言語(有効な場合) |
| チャンク | chunks | chunks | chunks | テキストチャンク(チャンク化が有効な場合) |
| 画像 | images | images | images | 抽出された画像(有効な場合) |
| 要素 | elements | elements | elements | セマンティック要素(element_based 形式の場合) |
| ページ | pages | pages | pages | ページごとのコンテンツ(ページ抽出が有効な場合) |
| キーワード | extracted_keywords | extractedKeywords | extracted_keywords | 抽出されたキーワード(有効な場合) |
エラー処理
Python
extract/extract_batch は失敗時に通常の RuntimeError を送出します。これらのエントリーポイントでは型付きの XbergError サブクラスは送出されないため、RuntimeError を捕捉してください。extract_batch の入力ごとの失敗は、致命的ではないエラーとして result.errors に報告されます。
from xberg import ExtractInput, extract, ExtractionConfig
try:
result = await extract(ExtractInput(uri="file.pdf"), ExtractionConfig())
for err in result.errors:
print(f"Per-input error: {err}")
except RuntimeError as e:
print(f"Extraction failed: {e}")
Node.js
Node バインディングは通常の Error オブジェクトを送出します(型付きエラーサブクラスはエクスポートされません)。instanceof Error で捕捉し、致命的ではない入力ごとの失敗については output.errors を確認してください。
import { extract } from "@xberg-io/xberg";
try {
const output = await extract({ kind: "uri", uri: "file.pdf" });
if (output.errors.length > 0) {
console.error("Per-input errors:", output.errors);
}
} catch (e) {
if (e instanceof Error) {
console.error(`Extraction failed: ${e.message}`);
}
}
Rust
use xberg::{extract, ExtractInput, ExtractionConfig, XbergError};
let config = ExtractionConfig::default();
match extract(ExtractInput::from_uri("file.pdf"), &config).await {
Ok(output) => println!("{}", output.results[0].content),
Err(XbergError::Parsing { message, .. }) => eprintln!("Parse error: {message}"),
Err(XbergError::Ocr { message, .. }) => eprintln!("OCR error: {message}"),
Err(XbergError::UnsupportedFormat(mime)) => eprintln!("Unsupported: {mime}"),
Err(e) => eprintln!("Error: {e}"),
}
よくある落とし穴
- 結果はエンベロープです:
extract/extract_batchは、results、errors、summaryを含むExtractionResultを返します。ドキュメントごとのフィールド(content、tables、chunksなど)はresult.results[i]にあり、最上位の戻り値にはありません。 - 非同期のみです:Python と Node には同期版がありません。必ず
extract(...)をawaitしてください。Rust のextractは非同期です。#[tokio::main]または非同期コンテキストを使用してください。 - 入力を構築してください:単なるパスではなく、
ExtractInputを渡してください。ExtractInput(uri=...)/ExtractInput::from_uri(...)(Python/Rust)または{ kind: "uri", uri: "..." }(Node)を使用します。バイト列の場合は、bytes/mime_typeとともにkind="bytes"を使用してください。 - Python の ChunkingConfig フィールド:
max_charactersとoverlapを指定して構築します(デフォルトは 1000 / 200)。これらは読み取り可能な属性でもあります。設定を dict/JSON として渡す場合は、max_chars/max_overlapという別名も使用できます。Node ではmaxCharacters/overlapを使用し、Rust の構造体フィールドはmax_characters/overlapです。 - Python のエラー:
extract/extract_batchが失敗すると、型付きのXbergErrorサブクラスではなく、通常のRuntimeErrorが発生します。RuntimeErrorを捕捉してください。Node では型付きのエラーサブクラスを持たない通常のErrorがスローされます。 - Rust の extract のシグネチャ:
extract(input, &config)のように、設定は参照として渡します。デフォルト値を使う場合は&ExtractionConfig::default()を使用してください。 - CLI の --format と --content-format:
--formatは CLI の出力(text、json、toon)を制御します。--content-formatはコンテンツのレンダリング(plain、markdown、djot、html、json、doctags)を制御します。 - 設定ファイルのフィールド名:TOML/YAML/JSON の設定ファイルでは、snake_case を使用します。
[chunking]のフィールドはmax_charactersとoverlap、その他のフィールドはoutput_format、pdf_optionsのような名前です。
対応フォーマット(概要)
| カテゴリ | 拡張子 |
|---|---|
.pdf | |
| Word | .docx, .docm, .doc, .dotx, .dotm, .dot, .odt, .pages, .wpd, .wp, .wp5, .wp6, .hwp, .hwpx |
| スプレッドシート | .xlsx, .xlsm, .xlsb, .xls, .xla, .xlam, .xltm, .xltx, .xlt, .ods, .numbers |
| プレゼンテーション | .pptx, .pptm, .ppt, .pps, .ppsx, .potx, .potm, .pot, .odp, .key |
| 電子書籍 | .epub, .fb2 |
| 画像 | .png, .jpg, .jpeg, .gif, .webp, .bmp, .tiff, .tif, .jp2, .jpg2, .j2c, .j2k, .jpc, .jbig2, .jb2, .pnm, .pbm, .pgm, .ppm, .heic, .heics, .heif, .heifs, .hif, .avif, .avcs, .svg |
| マークアップ | .html, .htm, .xhtml, .xht, .xml, .kml |
| データ | .json, .geojson, .jsonl, .ndjson, .yaml, .yml, .toml, .csv, .tsv, .dbf, .sqlite, .sqlite3, .db, .gpkg, .gpkx |
| テキスト | .txt, .adoc, .asciidoc, .vtt, .md, .markdown, .commonmark, .qmd, .rmd, .mdx, .djot, .dj, .doctags, .rst, .org, .rtf |
| メール | .eml, .msg, .pst |
| アーカイブ | .zip, .tar, .tgz, .gz, .7z |
| 音声/動画 | .mp3, .mpga, .m4a, .wav, .webm, .mp4, .mpg4, .mp4v, .m4v, .mpeg, .mpg, .mpe, .m1v, .m2v |
| 学術 | .bib, .ris, .nbib, .enw, .tex, .latex, .typ, .typst, .jats, .nxml, .ipynb, .docbook, .dbk, .docbook4, .docbook5, .opml |
CSL JSONは、明示的なMIMEタイプを指定してサポートされていますが、登録済みのファイル拡張子はありません。
MIMEタイプを含む完全なフォーマット一覧については、references/supported-formats.mdを参照してください。
追加リソース
特定のトピックについて詳しく解説したリファレンスファイル:
- Python API リファレンス — すべての関数、設定クラス、プラグインプロトコル、正確なシグネチャ
- Node.js API リファレンス — すべての関数、TypeScript インターフェース、ワーカープール API
- Rust API リファレンス — フィーチャーゲート、構造体、Cargo.toml の例を含むすべての関数
- CLI リファレンス — すべてのコマンド、フラグ、設定の優先順位、終了コード
- 設定リファレンス — TOML/YAML/JSON 形式、自動検出、環境変数、完全なスキーマ
- サポート対象の形式 — 形式の種類、拡張子、機能、信頼できる検出コマンド
- 高度な機能 — プラグイン、埋め込み、MCP サーバー、API サーバー、セキュリティ上限
- その他の言語バインディング — Go、Ruby、Java、C#、PHP、Elixir、WASM、Dart、Kotlin Android、Swift、Zig、C、Docker
関連スキル
タスクに特化した関連スキルでは、この概要より詳しく解説しています:
- xberg-extracting-with-ocr — OCR バックエンド、言語パック、OCR の強制、調整。
- xberg-extracting-tables — レイアウトを考慮した表の検出と表モデル。
- xberg-chunking — チャンクサイズ/オーバーラップ、Markdown/YAML/セマンティックチャンカー、
chunkコマンド。 - xberg-extracting-keywords — YAKE/RAKE キーワード、言語検出、
embedコマンド。 - xberg-batch-extraction —
batchコマンド、--file-configs、並列処理、エラーからの復旧。 - xberg-picking-a-format — 利用者に応じた
--format/--content-formatの選択。
完全なドキュメント:https://docs.xberg.io GitHub:https://github.com/xberg-io/xberg