Skill: baokui/pdf-parser-mineru (version 1.0.2)

--- name: pdf-process-mineru description: PDF document parsing tool based on local MinerU, supports converting PDF to Markdown, JSON, and other machine-readable formats. --- ## Tool List ### 1. pdf_to_markdown Convert PDF documents to Markdown format, preserving document structure, formulas, tables, and images. **Description**: Use MinerU to parse PDF documents and output in Markdown format, supporting OCR, formula recognition, table extraction, and other features. **Parameters**: - `file_path` (string, required): Absolute path to the PDF file - `output_dir` (string, required): Absolute path to the output directory - `backend` (string, optional): Parsing backend, options: `hybrid-auto-engine` (default), `pipeline`, `vlm-auto-engine` - `language` (string, optional): OCR language code, such as `en` (English), `ch` (Chinese), `ja` (Japanese), etc., defaults to auto-detection - `enable_formula` (boolean, optional): Whether to enable formula recognition, defaults to true - `enable_table` (boolean, optional): Whether to enable table extraction, defaults to true - `start_page` (integer, optional): Start page number (starting from 0), defaults to 0 - `end_page` (integer, optional): End page number (starting from 0), defaults to -1 meaning parse all pages **Return Value**: ```json { "success": true, "output_path": "/path/to/output", "markdown_content": "Converted Markdown content...", "images": ["List of image paths"], "tables": ["List of table information"], "formula_count": 10 } ``` **Examples**: ```bash python .claude/skills/pdf-process/script/pdf_parser.py \ '{"name": "pdf_to_markdown", "arguments": {"file_path": "/path/to/document.pdf", "output_dir": "/path/to/output"}}' # Use specific backend python .claude/skills/pdf-process/script/pdf_parser.py \ '{"name": "pdf_to_markdown", "arguments": {"file_path": "/path/to/document.pdf", "output_dir": "/path/to/output", "backend": "pipeline"}}' # Parse specific pages python .claude/skills/pdf-process/script/pdf_parser.py \ '{"name": "pdf_to_markdown", "arguments": {"file_path": "/path/to/document.pdf", "output_dir": "/path/to/output", "start_page": 0, "end_page": 5}}' ``` --- ### 2. pdf_to_json Convert PDF documents to JSON format, including detailed layout and structural information. **Description**: Use MinerU to parse PDF documents and output in JSON format, containing structured information such as text blocks, images, tables, formulas, etc. **Parameters**: - `file_path` (string, required): Absolute path to the PDF file - `output_dir` (string, required): Absolute path to the output directory - `backend` (string, optional): Parsing backend, options: `hybrid-auto-engine` (default), `pipeline`, `vlm-auto-engine` - `language` (string, optional): OCR language code, such as `en` (English), `ch` (Chinese), `ja` (Japanese), etc., defaults to auto-detection - `enable_formula` (boolean, optional): Whether to enable formula recognition, defaults to true - `enable_table` (boolean, optional): Whether to enable table extraction, defaults to true - `start_page` (integer, optional): Start page number (starting from 0), defaults to 0 - `end_page` (integer, optional): End page number (starting from 0), defaults to -1 meaning parse all pages **Return Value**: ```json { "success": true, "output_path": "/path/to/output.json", "pages": [ { "page_no": 0, "page_size": [595, 842], "blocks": [ { "type": "text", "text": "Text content", "bbox": [x, y, x, y] } ], "images": [], "tables": [], "formulas": [] } ], "metadata": { "total_pages": 10, "author": "Author", "title": "Title" } } ``` **Examples**: ```bash python .claude/skills/pdf-process/script/pdf_parser.py \ '{"name": "pdf_to_json", "arguments": {"file_path": "/path/to/document.pdf", "output_dir": "/path/to/output"}}' # Use specific backend and language python .claude/skills/pdf-process/script/pdf_parser.py \ '{"name": "pdf_to_json", "arguments": {"file_path": "/path/to/document.pdf", "output_dir": "/path/to/output", "backend": "hybrid-auto-engine", "language": "ch"}}' ``` --- ## Installation Instructions ### 1. Install MinerU ```bash # Update pip and install uv pip install --upgrade pip pip install uv # Install MinerU (including all features) uv pip install -U "mineru[all]" ``` ### 2. Verify Installation ```bash # Check if MinerU is installed successfully mineru --version # Test basic functionality mineru --help ``` ### 3. System Requirements - **Python Version**: 3.10-3.13 - **Operating System**: Linux / Windows / macOS 14.0+ - **Memory**: - Using `pipeline` backend: minimum 16GB, recommended 32GB+ - Using `hybrid/vlm` backend: minimum 16GB, recommended 32GB+ - **Disk Space**: minimum 20GB (SSD recommended) - **GPU** (optional): - `pipeline` backend: supports CPU-only - `hybrid/vlm` backend: requires NVIDIA GPU (Volta architecture and above) or Apple Silicon ## Use Cases 1. **Academic Paper Parsing**: Extract structured content such as formulas, tables, and images 2. **Technical Document Conversion**: Convert PDF documents to Markdown for version control and online publishing 3. **OCR Processing**: Process scanned PDFs and garbled PDFs 4. **Multilingual Documents**: Supports OCR recognition for 109 languages 5. **Batch Processing**: Batch convert multiple PDF documents ## Backend Selection Recommendations - **hybrid-auto-engine** (default): Balanced accuracy and speed, suitable for most scenarios - **pipeline**: Suitable for CPU-only environments, best compatibility - **vlm-auto-engine**: Highest accuracy, requires GPU acceleration ## Notes 1. **File Paths**: All paths must be absolute paths 2. **Output Directory**: Non-existent directories will be created automatically 3. **Performance**: Using GPU can significantly improve parsing speed 4. **Page Numbers**: Page numbers start counting from 0 5. **Memory**: Processing large documents may consume more memory ## Troubleshooting ### Common Issues 1. **Installation Failure**: - Ensure using Python 3.10-3.13 - Windows only supports Python 3.10-3.12 (ray does not support 3.13) - Using `uv pip install` can resolve most dependency conflicts 2. **Insufficient Memory**: - Use `pipeline` backend - Limit parsing pages: `start_page` and `end_page` - Reduce virtual memory allocation 3. **Slow Parsing Speed**: - Enable GPU acceleration - Use `hybrid-auto-engine` backend - Disable unnecessary features (formulas, tables) 4. **Low OCR Accuracy**: - Specify the correct document language - Ensure the backend supports OCR (use `pipeline` or `hybrid-*`) ## Related Resources - MinerU Official Documentation: https://opendatalab.github.io/MinerU/ - MinerU GitHub: https://github.com/opendatalab/MinerU - Online Demo: https://mineru.net/

path: install.sh
content: #!/bin/bash
# MinerU 安装脚本

set -e  # 遇到错误立即退出

echo "========================================"
echo "  PDF Process Skill - MinerU 安装脚本"
echo "========================================"
echo ""

# 检查 Python 版本
echo "1. 检查 Python 版本..."
python_version=$(python3 --version 2>&1 | awk '{print $2}')
echo "   检测到 Python 版本: $python_version"

# 检查 Python 版本是否在 3.10-3.13 范围内
python_major=$(echo $python_version | cut -d. -f1)
python_minor=$(echo $python_version | cut -d. -f2)

if [ "$python_major" -lt 3 ] || ([ "$python_major" -eq 3 ] && [ "$python_minor" -lt 10 ]); then
    echo "   ❌ 错误: Python 版本过低。需要 Python 3.10 或更高版本"
    echo "   当前版本: $python_version"
    exit 1
fi

if [ "$python_major" -gt 3 ] || ([ "$python_major" -eq 3 ] && [ "$python_minor" -gt 13 ]); then
    echo "   ⚠️  警告: Python 版本过高。推荐使用 Python 3.10-3.13"
fi

echo "   ✓ Python 版本符合要求"
echo ""

# 检查 pip
echo "2. 检查 pip..."
if ! command -v pip3 &> /dev/null; then
    echo "   ❌ 错误: 未找到 pip3"
    exit 1
fi
echo "   ✓ pip3 已安装"
echo ""

# 更新 pip
echo "3. 更新 pip..."
python3 -m pip install --upgrade pip
echo "   ✓ pip 已更新"
echo ""

# 安装 uv
echo "4. 安装 uv (快速包管理器)..."
if ! command -v uv &> /dev/null; then
    pip3 install uv
    echo "   ✓ uv 安装成功"
else
    echo "   ✓ uv 已安装"
fi
echo ""

# 安装 MinerU
echo "5. 安装 MinerU (包含所有功能)..."
echo "   这可能需要几分钟时间，请耐心等待..."
uv pip install -U "mineru[all]"
echo "   ✓ MinerU 安装成功"
echo ""

# 验证安装
echo "6. 验证安装..."
if command -v mineru &> /dev/null; then
    mineru_version=$(mineru --version 2>&1)
    echo "   ✓ mineru 命令可用"
    echo "   版本: $mineru_version"
else
    echo "   ❌ 错误: mineru 命令不可用"
    echo "   请检查安装是否成功"
    exit 1
fi
echo ""

# 测试帮助命令
echo "7. 测试 mineru --help..."
mineru --help > /dev/null 2>&1
if [ $? -eq 0 ]; then
    echo "   ✓ mineru 命令运行正常"
else
    echo "   ❌ 警告: mineru 命令运行异常"
fi
echo ""

echo "========================================"
echo "  ✅ 安装完成！"
echo "========================================"
echo ""
echo "现在可以使用 PDF Process Skill 了！"
echo ""
echo "测试命令:"
echo "  python .claude/skills/pdf-process/script/pdf_parser.py \\"
echo '    \'{"name": "pdf_to_markdown", "arguments": {"file_path": "/path/to/test.pdf", "output_dir": "/tmp/output"}}\''
echo ""
echo "更多信息请查看:"
echo "  .claude/skills/pdf-process/README.md"
echo ""


path: SKILL_zh.md
content: ---
name: pdf-process-mineru
description: 基于本地 MinerU 的 PDF 文档解析工具，支持将 PDF 转换为 Markdown、JSON 等机器可读格式。
---

## 工具列表

### 1. pdf_to_markdown

将 PDF 文档转换为 Markdown 格式，保留文档结构、公式、表格和图片。

**描述**: 使用 MinerU 解析 PDF 文档，输出为 Markdown 格式，支持 OCR、公式识别、表格提取等功能。

**参数**:
- `file_path` (string, required): PDF 文件的绝对路径
- `output_dir` (string, required): 输出目录的绝对路径
- `backend` (string, optional): 解析后端，可选值：`hybrid-auto-engine`(默认)、`pipeline`、`vlm-auto-engine`
- `language` (string, optional): OCR 语言代码，如 `en`(英语)、`ch`(中文)、`ja`(日语) 等，默认为自动检测
- `enable_formula` (boolean, optional): 是否启用公式识别，默认为 true
- `enable_table` (boolean, optional): 是否启用表格提取，默认为 true
- `start_page` (integer, optional): 起始页码（从 0 开始），默认为 0
- `end_page` (integer, optional): 结束页码（从 0 开始），默认为 -1 表示解析所有页面

**返回值**:
```json
{
  "success": true,
  "output_path": "/path/to/output",
  "markdown_content": "转换后的 Markdown 内容...",
  "images": ["图片路径列表"],
  "tables": ["表格信息列表"],
  "formula_count": 10
}
```

**示例**:
```bash
python .claude/skills/pdf-process/script/pdf_parser.py \
  '{"name": "pdf_to_markdown", "arguments": {"file_path": "/path/to/document.pdf", "output_dir": "/path/to/output"}}'

# 使用特定后端
python .claude/skills/pdf-process/script/pdf_parser.py \
  '{"name": "pdf_to_markdown", "arguments": {"file_path": "/path/to/document.pdf", "output_dir": "/path/to/output", "backend": "pipeline"}}'

# 解析特定页面
python .claude/skills/pdf-process/script/pdf_parser.py \
  '{"name": "pdf_to_markdown", "arguments": {"file_path": "/path/to/document.pdf", "output_dir": "/path/to/output", "start_page": 0, "end_page": 5}}'
```

---

### 2. pdf_to_json

将 PDF 文档转换为 JSON 格式，包含详细的布局和结构信息。

**描述**: 使用 MinerU 解析 PDF 文档，输出为 JSON 格式，包含文本块、图片、表格、公式等结构化信息。

**参数**:
- `file_path` (string, required): PDF 文件的绝对路径
- `output_dir` (string, required): 输出目录的绝对路径
- `backend` (string, optional): 解析后端，可选值：`hybrid-auto-engine`(默认)、`pipeline`、`vlm-auto-engine`
- `language` (string, optional): OCR 语言代码，如 `en`(英语)、`ch`(中文)、`ja`(日语) 等，默认为自动检测
- `enable_formula` (boolean, optional): 是否启用公式识别，默认为 true
- `enable_table` (boolean, optional): 是否启用表格提取，默认为 true
- `start_page` (integer, optional): 起始页码（从 0 开始），默认为 0
- `end_page` (integer, optional): 结束页码（从 0 开始），默认为 -1 表示解析所有页面

**返回值**:
```json
{
  "success": true,
  "output_path": "/path/to/output.json",
  "pages": [
    {
      "page_no": 0,
      "page_size": [595, 842],
      "blocks": [
        {
          "type": "text",
          "text": "文本内容",
          "bbox": [x, y, x, y]
        }
      ],
      "images": [],
      "tables": [],
      "formulas": []
    }
  ],
  "metadata": {
    "total_pages": 10,
    "author": "作者",
    "title": "标题"
  }
}
```

**示例**:
```bash
python .claude/skills/pdf-process/script/pdf_parser.py \
  '{"name": "pdf_to_json", "arguments": {"file_path": "/path/to/document.pdf", "output_dir": "/path/to/output"}}'

# 使用特定后端和语言
python .claude/skills/pdf-process/script/pdf_parser.py \
  '{"name": "pdf_to_json", "arguments": {"file_path": "/path/to/document.pdf", "output_dir": "/path/to/output", "backend": "hybrid-auto-engine", "language": "ch"}}'
```

---

## 安装说明

### 1. 安装 MinerU

```bash
# 更新 pip 并安装 uv
pip install --upgrade pip
pip install uv

# 安装 MinerU（包含所有功能）
uv pip install -U "mineru[all]"
```

### 2. 验证安装

```bash
# 检查 MinerU 是否安装成功
mineru --version

# 测试基本功能
mineru --help
```

### 3. 系统要求

- **Python 版本**: 3.10-3.13
- **操作系统**: Linux / Windows / macOS 14.0+
- **内存**:
  - 使用 `pipeline` 后端：最少 16GB，推荐 32GB+
  - 使用 `hybrid/vlm` 后端：最少 16GB，推荐 32GB+
- **磁盘空间**: 最少 20GB（SSD 推荐）
- **GPU**（可选）:
  - `pipeline` 后端：支持纯 CPU
  - `hybrid/vlm` 后端：需要 NVIDIA GPU（Volta 架构及以上）或 Apple Silicon

## 使用场景

1. **学术论文解析**: 提取公式、表格、图片等结构化内容
2. **技术文档转换**: 将 PDF 文档转换为 Markdown 以便于版本控制和在线发布
3. **OCR 处理**: 处理扫描 PDF 和乱码 PDF
4. **多语言文档**: 支持 109 种语言的 OCR 识别
5. **批量处理**: 批量转换多个 PDF 文档

## 后端选择建议

- **hybrid-auto-engine** (默认): 平衡准确率和速度，适合大多数场景
- **pipeline**: 适合纯 CPU 环境，兼容性最好
- **vlm-auto-engine**: 最高准确率，需要 GPU 加速

## 注意事项

1. **文件路径**: 所有路径必须是绝对路径
2. **输出目录**: 会自动创建不存在的目录
3. **性能**: 使用 GPU 可显著提升解析速度
4. **页码**: 页码从 0 开始计数
5. **内存**: 处理大型文档时可能占用较多内存

## 故障排除

### 常见问题

1. **安装失败**:
   - 确保使用 Python 3.10-3.13
   - Windows 上仅支持 Python 3.10-3.12（ray 不支持 3.13）
   - 使用 `uv pip install` 可以解决大部分依赖冲突

2. **内存不足**:
   - 使用 `pipeline` 后端
   - 限制解析页数：`start_page` 和 `end_page`
   - 减少虚拟显存分配

3. **解析速度慢**:
   - 启用 GPU 加速
   - 使用 `hybrid-auto-engine` 后端
   - 禁用不需要的功能（公式、表格）

4. **OCR 准确率低**:
   - 指定正确的文档语言
   - 确保后端支持 OCR（使用 `pipeline` 或 `hybrid-*`）

## 相关资源

- MinerU 官方文档: https://opendatalab.github.io/MinerU/
- MinerU GitHub: https://github.com/opendatalab/MinerU
- 在线体验: https://mineru.net/


path: script/pdf_parser.py
content: #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
PDF Parser Skill - 基于 MinerU 的 PDF 解析工具

支持将 PDF 转换为 Markdown 或 JSON 格式
"""

import json
import os
import re
import sys
import subprocess
import shutil
from pathlib import Path
from typing import Dict, Any, Optional


class PDFParser:
    """PDF 解析器封装类"""

    def __init__(self):
        self.mineru_cmd = self._find_mineru()

    def _find_mineru(self) -> str:
        """查找 mineru 命令"""
        # 优先使用 mineru 命令
        if shutil.which("mineru"):
            return "mineru"
        if os.path.exists('/home/research/miniconda3/bin/mineru'):
            return '/home/research/miniconda3/bin/mineru'
        # 检查是否在虚拟环境中
        venv_path = sys.prefix
        mineru_in_venv = os.path.join(venv_path, "bin", "mineru")
        if os.path.exists(mineru_in_venv):
            return mineru_in_venv

        raise RuntimeError(
            "未找到 mineru 命令。请先安装 MinerU:\n"
            "pip install --upgrade pip\n"
            "pip install uv\n"
            "uv pip install -U 'mineru[all]'"
        )

    def _build_command(
        self,
        tool_name: str,
        file_path: str,
        output_dir: str,
        backend: str = "hybrid-auto-engine",
        language: Optional[str] = None,
        enable_formula: bool = True,
        enable_table: bool = True,
        start_page: int = 0,
        end_page: int = -1,
    ) -> list:
        """构建 mineru 命令"""
        cmd = [
            self.mineru_cmd,
            "-p", file_path,
            "-o", output_dir,
            "-b", backend,
        ]

        # 添加语言参数
        if language:
            cmd.extend(["-l", language])

        # 添加公式开关
        cmd.extend(["-f", str(enable_formula).lower()])

        # 添加表格开关
        cmd.extend(["-t", str(enable_table).lower()])

        # 添加设备参数（强制使用 CPU，避免 MPS 限制）
        cmd.extend(["-d", "cpu"])

        # 添加页码范围
        if end_page != -1:
            cmd.extend(["-s", str(start_page)])
            cmd.extend(["-e", str(end_page)])

        return cmd

    def parse_to_markdown(
        self,
        file_path: str,
        output_dir: str,
        backend: str = "hybrid-auto-engine",
        language: Optional[str] = None,
        enable_formula: bool = True,
        enable_table: bool = True,
        start_page: int = 0,
        end_page: int = -1,
    ) -> Dict[str, Any]:
        """
        将 PDF 解析为 Markdown 格式

        Args:
            file_path: PDF 文件路径
            output_dir: 输出目录
            backend: 解析后端
            language: OCR 语言
            enable_formula: 是否启用公式识别
            enable_table: 是否启用表格提取
            start_page: 起始页码
            end_page: 结束页码

        Returns:
            包含解析结果的字典
        """
        # 验证输入文件
        if not os.path.exists(file_path):
            return {
                "success": False,
                "error": f"输入文件不存在: {file_path}"
            }

        # 创建输出目录
        os.makedirs(output_dir, exist_ok=True)

        # 构建命令
        cmd = self._build_command(
            "pdf_to_markdown",
            file_path,
            output_dir,
            backend,
            language,
            enable_formula,
            enable_table,
            start_page,
            end_page,
        )

        try:
            # 设置环境变量以强制使用 CPU（避免 MPS 设备限制）
            env = os.environ.copy()
            env["PYTORCH_ENABLE_MPS_FALLBACK"] = "1"
            env["MPS_DEVICE"] = "cpu"

            # 执行命令
            result = subprocess.run(
                cmd,
                capture_output=True,
                text=True,
                timeout=3600,  # 1小时超时
                env=env,
            )

            if result.returncode != 0:
                return {
                    "success": False,
                    "error": f"MinerU 执行失败: {result.stderr}",
                    "stdout": result.stdout,
                    "stderr": result.stderr,
                }

            # 查找输出的 markdown 文件
            output_files = list(Path(output_dir).rglob("*.md"))
            if not output_files:
                return {
                    "success": False,
                    "error": "未找到输出的 Markdown 文件"
                }

            # 读取第一个 markdown 文件
            md_file = output_files[0]
            with open(md_file, "r", encoding="utf-8") as f:
                md_content = f.read()

            # 统计信息
            images = list(Path(output_dir).rglob("*.png")) + list(Path(output_dir).rglob("*.jpg"))
            tables = len(re.findall(r"\\|.*\\|", md_content))
            formula_count = len(re.findall(r"\\$.*\\$|\\$\\$.*\\$\\$", md_content))

            return {
                "success": True,
                "output_path": str(md_file),
                "output_dir": output_dir,
                "markdown_content": md_content,
                "images": [str(img) for img in images],
                "tables": tables,
                "formula_count": formula_count,
                "file_size": os.path.getsize(file_path),
            }

        except subprocess.TimeoutExpired:
            return {
                "success": False,
                "error": "解析超时（超过1小时），请尝试减少页数或使用更快的后端"
            }
        except Exception as e:
            return {
                "success": False,
                "error": f"解析过程中发生错误: {str(e)}",
                "exception": str(e),
            }

    def parse_to_json(
        self,
        file_path: str,
        output_dir: str,
        backend: str = "hybrid-auto-engine",
        language: Optional[str] = None,
        enable_formula: bool = True,
        enable_table: bool = True,
        start_page: int = 0,
        end_page: int = -1,
    ) -> Dict[str, Any]:
        """
        将 PDF 解析为 JSON 格式

        Args:
            file_path: PDF 文件路径
            output_dir: 输出目录
            backend: 解析后端
            language: OCR 语言
            enable_formula: 是否启用公式识别
            enable_table: 是否启用表格提取
            start_page: 起始页码
            end_page: 结束页码

        Returns:
            包含解析结果的字典
        """
        # 验证输入文件
        if not os.path.exists(file_path):
            return {
                "success": False,
                "error": f"输入文件不存在: {file_path}"
            }

        # 创建输出目录
        os.makedirs(output_dir, exist_ok=True)

        # 构建命令
        cmd = self._build_command(
            "pdf_to_json",
            file_path,
            output_dir,
            backend,
            language,
            enable_formula,
            enable_table,
            start_page,
            end_page,
        )

        try:
            # 设置环境变量以强制使用 CPU（避免 MPS 设备限制）
            env = os.environ.copy()
            env["PYTORCH_ENABLE_MPS_FALLBACK"] = "1"
            env["MPS_DEVICE"] = "cpu"

            # 执行命令
            result = subprocess.run(
                cmd,
                capture_output=True,
                text=True,
                timeout=3600,  # 1小时超时
                env=env,
            )

            if result.returncode != 0:
                return {
                    "success": False,
                    "error": f"MinerU 执行失败: {result.stderr}",
                    "stdout": result.stdout,
                    "stderr": result.stderr,
                }

            # 查找输出的 JSON 文件
            output_files = list(Path(output_dir).rglob("*.json"))
            if not output_files:
                # 如果没有 JSON 文件，尝试读取其他文件
                all_files = list(Path(output_dir).rglob("*"))
                return {
                    "success": False,
                    "error": f"未找到输出的 JSON 文件。找到的文件: {[str(f) for f in all_files]}"
                }

            # 读取第一个 JSON 文件
            json_file = output_files[0]
            with open(json_file, "r", encoding="utf-8") as f:
                json_content = json.load(f)

            return {
                "success": True,
                "output_path": str(json_file),
                "output_dir": output_dir,
                "json_content": json_content,
                "file_size": os.path.getsize(file_path),
            }

        except subprocess.TimeoutExpired:
            return {
                "success": False,
                "error": "解析超时（超过1小时），请尝试减少页数或使用更快的后端"
            }
        except json.JSONDecodeError as e:
            return {
                "success": False,
                "error": f"JSON 解析失败: {str(e)}"
            }
        except Exception as e:
            return {
                "success": False,
                "error": f"解析过程中发生错误: {str(e)}",
                "exception": str(e),
            }


def main():
    """主函数"""
    if len(sys.argv) < 2:
        print(json.dumps({
            "success": False,
            "error": "缺少参数。使用方法: python pdf_parser.py '{\"name\": \"tool_name\", \"arguments\": {...}}'"
        }, ensure_ascii=False, indent=2))
        sys.exit(1)

    try:
        # 解析输入参数
        input_data = json.loads(sys.argv[1])
        tool_name = input_data.get("name")
        args = input_data.get("arguments", {})

        # 创建解析器
        parser = PDFParser()

        # 根据工具名称调用相应方法
        if tool_name == "pdf_to_markdown":
            result = parser.parse_to_markdown(**args)
        elif tool_name == "pdf_to_json":
            result = parser.parse_to_json(**args)
        else:
            result = {
                "success": False,
                "error": f"未知的工具名称: {tool_name}。支持的工具: pdf_to_markdown, pdf_to_json"
            }

        # 输出结果
        print(json.dumps(result, ensure_ascii=False, indent=2))

    except json.JSONDecodeError as e:
        print(json.dumps({
            "success": False,
            "error": f"JSON 解析失败: {str(e)}"
        }, ensure_ascii=False, indent=2))
        sys.exit(1)
    except Exception as e:
        print(json.dumps({
            "success": False,
            "error": f"执行失败: {str(e)}",
            "exception": str(e)
        }, ensure_ascii=False, indent=2))
        sys.exit(1)


if __name__ == "__main__":
    main()


Security scan verdicts — ClawScan: clean | static analysis: clean | VirusTotal: clean | SkillSpector: clean (LOW)