mcpField
C
convert-pdf-to-epub

convert-pdf-to-epub

github.com/koreybaドキュメント3840 回インストール38 週間前に更新
リポジトリ

convert-pdf-to-epub について

convert-pdf-to-epubは、PDFをEPUBに変換するスキルです。異なるレイアウトを扱うユーザー向けに、PDFの分析、設定可能な変換、検証を順に行い、読み順や画像、脚注も処理します。

主な機能

  1. 01PDF構造の分析
  2. 02設定可能なEPUB変換
  3. 03章と読み順の検出
  4. 04画像の最適化
  5. 05脚注のハイパーリンク化
  6. 06テキストと順序の検証

活用シーン

  1. 01シンプルなレイアウトの小説PDFの変換
  2. 022段組み学術論文の処理
  3. 03画像の多い雑誌の変換
  4. 04テキスト欠落や順序の問題の診断

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/koreyba/claude-skill-pdf-to-epub --skill convert-pdf-to-epub

インストール後、Claude Code で/convert-pdf-to-epubを入力して読み込まれたか確認します。

同梱ファイル

SKILL.md と一緒にインストールされる参考資料やスクリプト。

__init__.py
conversion/
__init__.py
converter.py
models.py
pdf_analyzer.py
report.py
conversion/detectors/
__init__.py
endnote_formatter.py
font_analyzer.py
footnote_detector.py
models.py
structure_builder.py
structure_classifier.py
conversion/detectors/reading_order/
__init__.py
base.py
xy_cut_sorter.py
y_sorter.py
conversion/strategies/
__init__.py
base_strategy.py
simple_strategy.py
core/
__init__.py
epub_builder.py
epub_extractor.py
image_optimizer.py
pdf_extractor.py
text_segmenter.py
utils.py
examples/
academic-multicol.json
fiction-simple.json
magazine-images.json

詳細

PDF から EPUB への変換

PDF ドキュメントを、高品質な EPUB ファイルに変換します。章の自動検出、画像の最適化、脚注のハイパーリンク化に対応しています。

クイックスタート

# Run conversion (from skill directory)
python -m scripts.convert input.pdf output.epub

# Validate result
python -m scripts.validate input.pdf output.epub

ワークフローの概要

変換は3段階のプロセスで行われ、必要に応じて4段階目で調整します。

┌─────────────────┐     ┌─────────────────┐     ┌─────────────────┐
│  1. ANALYZE     │ ──► │  2. CONVERT     │ ──► │  3. VALIDATE    │
│  - PDF structure│     │  - Apply config │     │  - Check quality│
│  - Generate cfg │     │  - Build EPUB   │     │  - Report issues│
└─────────────────┘     └─────────────────┘     └─────────────────┘
                                                        │
                                                        ▼
                                              ┌─────────────────┐
                                              │  4. ADAPT       │
                                              │  (if needed)    │
                                              │  - Tune config  │
                                              │  - Modify code  │
                                              └─────────────────┘
フェーズ1:分析

変換する前に、最適な設定を決定するため PDF を分析します。

# Open PDF and examine structure
import fitz  # pymupdf
doc = fitz.open("input.pdf")

# Check for:
# 1. Number of pages
# 2. Presence of images
# 3. Multi-column layout (compare text block x-coordinates)
# 4. Footnotes/endnotes (numbers in margins or at page bottom)
# 5. Font sizes (for heading detection thresholds)

分析に基づいて初期設定を生成します。

  • フィクション作品:デフォルトの y_sort 読み順を使用します
  • 学術論文:段組みの場合は xy_cut を有効にします
  • 雑誌:画像を最適化し、xy_cut を使用します

提案した設定を確認するようユーザーに依頼してから、次の手順に進みます。

フェーズ2:変換

生成した設定で変換を実行します。

from conversion.converter import Converter
from conversion.models import ConversionConfig

config = ConversionConfig(
    page_ranges=PageRanges(skip=[1, 2], content=(3, -3)),
    exclude_regions=ExcludeRegions(top=0.05, bottom=0.05),
    reading_order_strategy="y_sort",  # or "xy_cut" for columns
    image_optimization=ImageOptimizationConfig(enabled=True),
)

converter = Converter(strategy="simple")
result = converter.convert(pdf_path, epub_path, config)

# Check confidence
if result.reading_order_confidence < 0.7:
    print("Warning: Low confidence in reading order")
フェーズ3:検証

変換結果は必ず検証します。

from validation.completeness_checker import CompletenessChecker
from validation.order_checker import OrderChecker

# Check text completeness
completeness = CompletenessChecker().check(pdf_text, epub_text)
print(f"Completeness: {completeness.score:.1%}")  # Should be > 95%

# Check reading order
order = OrderChecker().check(pdf_chunks, epub_chunks)
print(f"Order score: {order.score:.1%}")  # Should be > 80%

品質ゲート:

  • 完全性が95%未満:テキストが欠落しています
  • 順序スコアが80%未満:読み順が正しくありません
フェーズ4:調整(検証に失敗した場合)

以下の判断ツリーを参照してください。


判断ツリー:問題が発生したとき

Validation failed?
│
├─► Text loss > 5%?
│   ├─► Check exclude_regions (headers/footers being cut?)
│   │   → Try: exclude_regions.top: 0.03 (reduce from 0.05)
│   ├─► Check page_ranges (skipping too many pages?)
│   │   → Try: page_ranges.skip: [] (don't skip any)
│   └─► Still failing? → See reference/troubleshooting.md#text-loss
│
├─► Wrong reading order?
│   ├─► PDF has columns?
│   │   → Try: reading_order_strategy: "xy_cut"
│   ├─► Columns detected but wrong?
│   │   → Try: multi_column.threshold: 0.3 (more sensitive)
│   └─► Still failing? → See reference/troubleshooting.md#order
│
├─► Headings not detected?
│   ├─► Headings only slightly larger than body?
│   │   → Try: heading_detection.font_size_threshold: 1.1
│   └─► Custom font patterns?
│   │   → May need to modify structure_classifier.py (ADAPTABLE)
│
├─► Footnotes not linking?
│   ├─► Non-standard format (not [1] or (1))?
│   │   → Add pattern to FootnoteDetector.PATTERNS
│   └─► See reference/troubleshooting.md#footnotes
│
└─► Other issue?
    └─► See reference/troubleshooting.md

3層アーキテクチャ

コードベースは、変更方針が異なる3つの層で構成されています。

層1:FROZEN(変更禁止)

これらのファイルは、固定仕様または決定論的アルゴリズムを実装しています。

ファイル理由
core/epub_builder.pyEPUB3 の仕様は固定されています
core/text_segmenter.py検証は同一の分割に依存します
validation/*メトリクスは再現可能でなければなりません

根本的なバグがある場合を除き、これらのファイルは変更しないでください。

層2:CONFIGURABLE(まず設定を試す)

コードを変更する前に、設定の調整を試してください。

ConversionConfig:
├── page_ranges         # Which pages to process
├── exclude_regions     # Margins to ignore (headers/footers)
├── multi_column        # Column detection settings
├── reading_order_strategy  # "y_sort" or "xy_cut"
├── heading_detection   # Font size thresholds
├── footnote_processing # Footnote patterns
├── image_optimization  # Compression settings
└── metadata           # Title, author, language

すべてのパラメーターについては、reference/config-tuning.mdを参照してください。

層3:ADAPTABLE(設定で解決できない場合は変更可能)

これらのファイルには、特定の PDF に合わせた調整が必要になる場合のあるヒューリスティックが含まれています。

ファイル変更できる内容
conversion/strategies/*新しい戦略サブクラスの作成
detectors/structure_classifier.py見出し検出のヒューリスティック
detectors/reading_order/*カスタムソーターアルゴリズムの追加
detectors/footnote_detector.py新しい脚注パターンの追加

ガイドラインについては、reference/code-adaptation.mdを参照してください。


プロジェクト構成

<skill-directory>/
├── SKILL.md                     # This file
├── requirements.txt             # Python dependencies
├── core/                        # FROZEN: Core algorithms
│   ├── epub_builder.py          # EPUB3 file creation
│   ├── pdf_extractor.py         # PDF text/image extraction
│   ├── text_segmenter.py        # Deterministic chunking
│   └── image_optimizer.py       # Image compression
│
├── conversion/                  # Main conversion logic
│   ├── converter.py             # Orchestrator
│   ├── models.py                # Data classes & configs
│   ├── strategies/              # ADAPTABLE: Conversion strategies
│   │   ├── base_strategy.py     # Template method pattern
│   │   └── simple_strategy.py
│   └── detectors/               # ADAPTABLE: Detection heuristics
│       ├── structure_classifier.py
│       ├── reading_order/
│       ├── footnote_detector.py
│       └── endnote_formatter.py
│
├── validation/                  # FROZEN: Quality checking
│   ├── completeness_checker.py
│   └── order_checker.py
│
├── scripts/                     # CLI entry points
│   ├── analyze.py
│   ├── convert.py
│   └── validate.py
│
├── reference/                   # Documentation
│   ├── workflow.md
│   ├── architecture.md
│   ├── troubleshooting.md
│   ├── config-tuning.md
│   └── code-adaptation.md
│
└── examples/                    # Example configurations
    ├── fiction-simple.json
    ├── academic-multicol.json
    └── magazine-images.json

設定例

フィクション作品(シンプルなレイアウト)
{
  "page_ranges": {"skip": [1, 2], "content": [3, -3]},
  "exclude_regions": {"top": 0.05, "bottom": 0.05},
  "reading_order_strategy": "y_sort",
  "heading_detection": {"font_size_threshold": 1.2}
}
学術論文(2段組み)
{
  "page_ranges": {"skip": [1], "content": [2, -1]},
  "exclude_regions": {"top": 0.08, "bottom": 0.08},
  "reading_order_strategy": "xy_cut",
  "multi_column": {"enabled": true, "threshold": 0.4}
}
雑誌(画像+段組み)
{
  "reading_order_strategy": "xy_cut",
  "multi_column": {"enabled": true, "column_count": 2},
  "image_optimization": {
    "enabled": true,
    "max_width": 800,
    "jpeg_quality": 75
  }
}

リファレンスドキュメント

詳細については、以下を参照してください。


よく使うコマンド

# Full conversion with validation (from skill directory)
python -m scripts.convert input.pdf output.epub && \
python -m scripts.validate input.pdf output.epub

# Analyze PDF structure
python -m scripts.analyze input.pdf

品質メトリクス

変換後は、必ず以下を確認してください。

メトリクス良好注意不良
テキストの完全性> 98%95-98%< 95%
読み順> 90%80-90%< 80%
信頼度> 0.80.6-0.8< 0.6

いずれかのメトリクスが「注意」または「不良」の範囲にある場合は、上記の判断ツリーに従ってください。

コメント