document-parsers について
document-parsersは、文書処理やRAGワークフロー向けの解析スキルです。PDF、DOCX、HTML、Markdown、TXT用のスクリプトとテンプレートを備え、形式に応じたパーサー選択や表・メタデータの抽出、分割に対応します。
主な機能
- 01複数の文書形式を解析
- 02複数のPDFバックエンドを提供
- 03表とメタデータを抽出
- 04文書の分割と構造化出力
- 05研究・法律文書の例を収録
活用シーン
- 01RAGパイプライン用の文書分割
- 02PDFからテキストや表を抽出
- 03複数形式の文書を一括処理
- 04研究論文や法律文書を解析
インストール
コマンドをコピーしてターミナルで実行します。
npx skills add https:/ / github.com/ vanman2024/ ai-dev-marketplace --skill document-parsersインストール後、Claude Code で/document-parsersを入力して読み込まれたか確認します。
同梱ファイル
SKILL.md と一緒にインストールされる参考資料やスクリプト。
examples/parse-legal-document.pyparse-research-paper.pyscripts/parse-docx.pyparse-html.pyparse-pdf.pysetup-llamaparse.shsetup-unstructured.shtemplates/multi-format-parser.pytable-extraction.py詳細
ドキュメントパーサー
目的: 業界標準のライブラリと AI を活用した解析ツールを使用して、複数のドキュメント形式(PDF、DOCX、HTML、Markdown)のコンテンツを自律的に解析・抽出します。
有効化のきっかけ:
- RAG(検索拡張生成)パイプラインの構築
- ドキュメントからのテキスト、表、メタデータの抽出
- 大量のドキュメントコレクションの処理
- ドキュメントの構造化形式への変換
- 表やレイアウトを含む複雑な PDF の処理
- スキャンしたドキュメントの OCR
- ベクトル埋め込み用のドキュメントのチャンク化
- ドキュメント検索システムの構築
主なリソース:
scripts/setup-llamaparse.sh- LlamaParse(AI を活用した解析)のインストールと設定scripts/setup-unstructured.sh- Unstructured.io ライブラリのインストールscripts/parse-pdf.py- 複数のバックエンドオプションに対応する実用的な PDF パーサーscripts/parse-docx.py- DOCX ドキュメントパーサーscripts/parse-html.py- HTML を構造化テキストに変換するパーサーtemplates/multi-format-parser.py- 汎用ドキュメントパーサーのテンプレートtemplates/table-extraction.py- 表抽出に特化したテンプレートexamples/parse-research-paper.py- 引用を含む研究論文の解析examples/parse-legal-document.py- セクションを含む法律文書の解析
パーサーの比較と選択ガイド
1. LlamaParse(AI を活用したプレミアムサービス)
最適な用途:
- 表、グラフ、複合レイアウトを含む複雑な PDF
- OCR が必要なスキャン済みドキュメント
- 正確性が重要なドキュメント
- 複数列のレイアウトや科学論文
- 財務報告書や請求書
利点:
- AI によるレイアウト理解
- 優れた表抽出精度
- OCR を標準搭載
- 複雑な書式に対応
- 構造化出力(Markdown/JSON)
欠点:
- API キーが必要(有料サービス)
- API のレート制限
- ネットワークへの依存
- ローカルパーサーより処理が遅い
ドキュメント: https://docs.cloud.llamaindex.ai/llamaparse
セットアップ:
./scripts/setup-llamaparse.sh
使用パターン:
from llama_parse import LlamaParse
parser = LlamaParse(
api_key="llx-...",
result_type="markdown", # or "text"
language="en",
verbose=True
)
documents = parser.load_data("document.pdf")
for doc in documents:
print(doc.text)
2. Unstructured.io(ローカル処理)
最適な用途:
- 大量のドキュメントのバッチ処理
- 複数形式への対応(PDF、DOCX、HTML、PPTX、画像)
- API に依存しないローカル処理
- 構造化された要素の抽出
- 本番環境の RAG パイプライン
利点:
- オープンソースで無料
- 複数形式に対応
- ローカルで実行可能(API キー不要)
- 良好な表検出機能
- 要素ベースのチャンク化
欠点:
- システム依存関係が必要(poppler、tesseract)
- インストールが複雑
- 複雑なレイアウトでは LlamaParse より精度が低い
ドキュメント: https://unstructured-io.github.io/unstructured/
セットアップ:
./scripts/setup-unstructured.sh
使用パターン:
from unstructured.partition.auto import partition
elements = partition("document.pdf")
for element in elements:
print(f"{element.category}: {element.text}")
3. PyPDF2(シンプルな PDF テキスト抽出)
最適な用途:
- シンプルなテキストベースの PDF
- 迅速なプロトタイピング
- メタデータの抽出
- PDF の操作(結合、分割)
利点:
- 純粋な Python(依存関係なし)
- 高速で軽量
- シンプルな PDF に適している
- 継続的にメンテナンスされている
欠点:
- 表の抽出が不得意
- 複雑なレイアウトの処理が難しい
- OCR に非対応
- 書式の保持機能が限定的
ドキュメント: https://github.com/py-pdf/pypdf2
セットアップ:
pip install pypdf2
使用パターン:
from PyPDF2 import PdfReader
reader = PdfReader("document.pdf")
for page in reader.pages:
print(page.extract_text())
4. PDFPlumber(高度な PDF 分析)
最適な用途:
- PDF からの表の抽出
- 表形式のデータを含む PDF
- 財務諸表や報告書
- 座標ベースの抽出
利点:
- 優れた表抽出機能
- 視覚的なデバッグツール
- 座標レベルでの制御
- メタデータとレイアウト情報
欠点:
- PyPDF2 より処理が遅い
- pdfminer.six への依存が必要
- OCR に非対応
ドキュメント: https://github.com/jsvine/pdfplumber
セットアップ:
pip install pdfplumber
使用パターン:
import pdfplumber
with pdfplumber.open("document.pdf") as pdf:
for page in pdf.pages:
tables = page.extract_tables()
text = page.extract_text()
5. python-docx(Word 文書)
最適な用途:
- Microsoft Word(.docx)文書
- 段落、テーブル、ヘッダーの抽出
- 文書のメタデータ
- テンプレートベースの文書生成
長所:
- DOCX のネイティブサポート
- 構造(段落、テーブル、セクション)を保持
- スタイルと書式設定にアクセス可能
- DOCX の書き込みや変更も可能
短所:
- .docx のみ対応(.doc には非対応)
- 画像の抽出機能が限定的
ドキュメント: https://github.com/python-openxml/python-docx
セットアップ:
pip install python-docx
使用パターン:
from docx import Document
doc = Document("document.docx")
for para in doc.paragraphs:
print(para.text)
for table in doc.tables:
for row in table.rows:
print([cell.text for cell in row.cells])
選択マトリックス
| 用途 | 推奨パーサー | 代替 |
|---|---|---|
| シンプルな PDF テキスト抽出 | PyPDF2 | Unstructured |
| テーブルを含む複雑な PDF | LlamaParse | PDFPlumber |
| スキャン文書(OCR) | LlamaParse | Unstructured + Tesseract |
| Word 文書(.docx) | python-docx | Unstructured |
| HTML からテキストへの変換 | parse-html.py | Unstructured |
| 複数形式の一括処理 | Unstructured | Multi-format-parser |
| テーブル抽出 | PDFPlumber | LlamaParse |
| 研究論文 | LlamaParse | Unstructured |
| 法的文書 | LlamaParse | PDFPlumber |
| 本番環境の RAG パイプライン | Unstructured | LlamaParse |
機能スクリプト
1. PDF の解析(scripts/parse-pdf.py)
複数のバックエンドに対応したコマンドライン PDF パーサー:
# Using PyPDF2 (default)
python scripts/parse-pdf.py document.pdf
# Using PDFPlumber (better for tables)
python scripts/parse-pdf.py document.pdf --backend pdfplumber
# Using LlamaParse (AI-powered)
python scripts/parse-pdf.py document.pdf --backend llamaparse --api-key llx-...
# Output to file
python scripts/parse-pdf.py document.pdf --output output.txt
# Extract tables as JSON
python scripts/parse-pdf.py document.pdf --backend pdfplumber --tables-only --output tables.json
機能:
- 複数のバックエンドに対応(PyPDF2、PDFPlumber、LlamaParse)
- テーブル抽出
- メタデータ抽出
- ページ範囲の選択
- JSON/テキストの出力形式
2. DOCX の解析(scripts/parse-docx.py)
構造を保持する Word 文書パーサー:
# Basic extraction
python scripts/parse-docx.py document.docx
# Extract with structure
python scripts/parse-docx.py document.docx --preserve-structure
# Extract tables only
python scripts/parse-docx.py document.docx --tables-only
# Output as JSON
python scripts/parse-docx.py document.docx --output output.json --format json
機能:
- スタイル付きの段落抽出
- テーブル抽出
- ヘッダー/フッターの抽出
- メタデータ(作成者、作成日など)
- 構造化された JSON 出力
3. HTML の解析(scripts/parse-html.py)
HTML をクリーンなテキストに変換:
# Basic HTML parsing
python scripts/parse-html.py document.html
# From URL
python scripts/parse-html.py https://example.com/article
# Preserve links
python scripts/parse-html.py document.html --preserve-links
# Extract specific selector
python scripts/parse-html.py document.html --selector "article.content"
機能:
- クリーンなテキストの抽出(スクリプトとスタイルを削除)
- リンクの保持
- CSS セレクターのサポート
- URL の取得
- Markdown 出力オプション
テンプレート
マルチフォーマットパーサー(templates/multi-format-parser.py)
形式を自動検出して複数の形式を処理するユニバーサルパーサー:
from multi_format_parser import MultiFormatParser
parser = MultiFormatParser(
llamaparse_api_key="llx-...", # Optional
use_ocr=True,
chunk_size=1000
)
# Automatic format detection
result = parser.parse_file("document.pdf")
print(result.text)
print(result.metadata)
print(result.tables)
# Batch processing
results = parser.parse_directory("./documents/")
for filename, result in results.items():
print(f"{filename}: {len(result.text)} characters")
対応形式:
- PDF、DOCX、HTML、Markdown、TXT
- RAG 用の自動チャンク分割
- メタデータ抽出
- 全形式にわたるテーブル抽出
- エラー処理とフォールバック
テーブル抽出(templates/table-extraction.py)
複数の方法でテーブルを抽出する専用機能:
from table_extraction import TableExtractor
extractor = TableExtractor(
prefer_llamaparse=True,
fallback_to_pdfplumber=True
)
# Extract all tables from document
tables = extractor.extract_tables("financial_report.pdf")
for i, table in enumerate(tables):
print(f"Table {i + 1}:")
print(table.to_markdown()) # or .to_csv(), .to_json()
print(f"Confidence: {table.confidence}")
機能:
- 複数の抽出方法
- 自動フォールバック
- テーブルの検証
- 形式変換(CSV、JSON、Markdown、DataFrame)
- 信頼度スコアリング
例
研究論文の解析(examples/parse-research-paper.py)
学術論文を解析する完全な例:
# Extracts title, abstract, sections, citations, tables, figures
python examples/parse-research-paper.py paper.pdf --output paper.json
抽出項目:
- タイトルと著者
- 要旨
- セクション構成(序論、方法、結果など)
- 引用と参考文献
- キャプション付きのテーブルと図
- メタデータ(DOI、発行日、学術誌)
法的文書の解析(examples/parse-legal-document.py)
法的文書向けの専用パーサー:
# Extracts clauses, sections, definitions, parties
python examples/parse-legal-document.py contract.pdf --output contract.json
抽出項目:
- 文書の種類(契約書、合意書など)
- 関係者
- 定義のセクション
- 番号付きの条項とセクション
- 署名欄
- 日付と期限
RAG パイプラインの統合
埋め込み用の文書チャンク分割
from multi_format_parser import MultiFormatParser
parser = MultiFormatParser(chunk_size=512, chunk_overlap=50)
result = parser.parse_file("document.pdf")
# Chunks ready for embedding
for chunk in result.chunks:
print(f"Chunk {chunk.id}: {chunk.text[:100]}...")
print(f"Metadata: {chunk.metadata}")
# Send to embedding model
一括処理パイプライン
import glob
from multi_format_parser import MultiFormatParser
parser = MultiFormatParser()
# Process all documents in directory
for filepath in glob.glob("./documents/**/*", recursive=True):
try:
result = parser.parse_file(filepath)
# Store in vector database
store_embeddings(result.chunks)
print(f"✓ Processed {filepath}")
except Exception as e:
print(f"✗ Failed {filepath}: {e}")
ベストプラクティス
パーサーの選択:
- シンプルな PDF には PyPDF2 から始め、必要に応じて別のものに切り替えます
- 複雑なレイアウトには LlamaParse を使用します(予算に余裕がある場合)
- 複数の形式を扱う本番システムには Unstructured を使用します
- テーブルの抽出には PDFPlumber を使用します
パフォーマンス:
- 再処理を避けるため、解析結果をキャッシュします
- 複数のドキュメントにはバッチ処理を使用します
- 大規模なコレクションには非同期処理を検討します
- LlamaParse の API レート制限を監視します
精度:
- テーブル抽出の結果を検証します
- フォールバック戦略を実装します
- デバッグ用に解析エラーを記録します
- 利用可能な場合は信頼度スコアを使用します
RAG の最適化:
- チャンクサイズ:埋め込みには 512~1024 トークン
- オーバーラップ:コンテキスト保持のため 10~20%
- 検索用にメタデータ(ページ番号、セクション)を保持します
- 抽出したテキストをクリーンアップします(ヘッダー/フッターを削除)
トラブルシューティング
PyPDF2 が文字化けしたテキストを返す:
- PDFPlumber または LlamaParse を試します
- PDF の文字エンコーディングが標準的でない可能性があります
- PDF がスキャンされたものか確認します(OCR が必要です)
Unstructured のインストールに失敗する:
- システム依存関係をインストールします:
sudo apt-get install poppler-utils tesseract-ocr - macOS の場合:
brew install poppler tesseract
LlamaParse の API エラー:
- API キーが正しいことを確認します
- ダッシュボードでレート制限を確認します
- ドキュメントのサイズが制限内であることを確認します
テーブル抽出で列が欠落する:
- 別のパーサー(PDFPlumber または LlamaParse)を試します
- テーブル検出の設定を調整します
- テーブル構造を手動で検証します
DOCX の解析に失敗する:
- ファイルが .doc ではなく .docx であることを確認します
- ファイルが破損していないことを確認します
- LibreOffice で .docx に変換してみます
依存関係
コア:
pip install pypdf2 pdfplumber python-docx beautifulsoup4 lxml markdown
オプション(Unstructured):
pip install unstructured[local-inference]
sudo apt-get install poppler-utils tesseract-ocr # Linux
brew install poppler tesseract # macOS
オプション(LlamaParse):
pip install llama-parse
# Requires API key from https://cloud.llamaindex.ai
対応形式: PDF、DOCX、HTML、Markdown、TXT パーサー: LlamaParse、Unstructured.io、PyPDF2、PDFPlumber、python-docx バージョン: 1.0.0