咀嚼者
  
快速浏览任何文档。 一个MCP服务器,为克劳德等人工智能系统解析36种以上的文件格式。
特性
- 15+格式类别:PDF、DOCX、PPTX、Excel、CSV、HTML、Markdown、文本、代码(10多种语言)、JSON、YAML、XML、电子邮件(EML/MSG)、EPUB、RTF
- 智能令牌管理:默认情况下为摘要模式(5000个字符),对大型文档进行分页
- TOON输出格式:令牌优化对象表示法可将令牌使用量减少约40%
- 语义分块:使用句子变换器进行基于嵌入的分块,以实现更好的RAG检索
- 图像提取:PDF图像作为ImageContent返回,用于直接AI分析
- MCP提示:内置文档分析提示(汇总、提取实体、问答等)
- 元数据:作者、标题、页数、字数、阅读时间、复杂性得分
- 批处理:在单个请求中解析多个文档
快速开始
安装
# Clone the repository
git clone https://github.com/IcHiGo-KuRoSaKiI/Chomper.git
cd chomper
# Create virtual environment and install
python -m venv venv
source venv/bin/activate # or `venv\Scripts\activate` on Windows
pip install -e .运行服务器
# Direct execution
python server.py
# Or via the installed command
chomper在Claude代码中配置
claude mcp add -s user chomper -- /path/to/chomper/venv/bin/python /path/to/chomper/server.py在Claude桌面中配置
添加到您的Claude Desktop配置(~/Library/Application Support/Claude/claude_desktop_config.json 在macOS上):
{
"mcpServers": {
"chomper": {
"command": "/path/to/chomper/venv/bin/python",
"args": ["/path/to/chomper/server.py"]
}
}
}Python库
Chomper可以作为一个独立的Python库用于文档解析:
import chomper
# Parse a document
result = chomper.parse("/path/to/document.pdf")
print(result.text)
print(result.metadata)
print(f"Words: {result.word_count}, Format: {result.format}")
# Parse from base64 (cloud storage, APIs, databases)
import base64
with open("doc.pdf", "rb") as f:
content = base64.b64encode(f.read()).decode()
result = chomper.parse_bytes(content, "doc.pdf")
# Quick metadata extraction
meta = chomper.extract_metadata("/path/to/report.pdf")
print(f"Author: {meta.author}, Pages: {meta.page_count}")
# Chunk for RAG/embeddings
chunks = chomper.chunk("/path/to/doc.pdf", strategy="semantic")
for chunk in chunks:
print(f"Chunk {chunk.chunk_id}: {chunk.word_count} words")
print(f"Keywords: {chunk.keywords}")
# Check format support
if chomper.is_supported("report.pdf"):
result = chomper.parse("report.pdf")
# List all formats
formats = chomper.list_formats()
for ext, info in formats.items():
if info["available"]:
print(f"{ext}: {info['description']}")API 参考
| 功能 | 说明 |
|---|---|
chomper.parse(file_path) | 解析文档,返回 ParseResult |
chomper.parse_bytes(content, filename) | 从字节/base64解析 |
chomper.chunk(file_path, strategy) | 为RAG拆分成块 |
chomper.extract_metadata(file_path) | 快速元数据提取 |
chomper.list_formats() | 列出支持的格式 |
chomper.is_supported(file_path) | 检查是否支持格式 |
结果对象
# ParseResult
result.text # Extracted text content
result.metadata # Document metadata dict
result.format # File format (pdf, docx, etc.)
result.word_count # Total word count
result.char_count # Total character count
# ChunkResult (from chomper.chunk())
chunk.text # Chunk text
chunk.chunk_id # Chunk index (0-based)
chunk.word_count # Words in chunk
chunk.keywords # Extracted keywords
chunk.section_name # Detected section name
# MetadataResult (from chomper.extract_metadata())
meta.filename # Base filename
meta.format # File format
meta.file_size # Size in bytes
meta.author # Author (if available)
meta.title # Title (if available)
meta.page_count # Pages (if applicable)命令行界面
直接从命令行解析文档:
# Parse and print text
chomper-parse document.pdf
# Output as JSON
chomper-parse report.docx --json
# Output in different formats (csv, markdown, xml)
chomper-parse report.pdf --format markdown
chomper-parse data.xlsx --format csv
# Show metadata only
chomper-parse data.xlsx --metadata
# Split into chunks
chomper-parse book.pdf --chunk --strategy semantic
# Save to file
chomper-parse document.pdf -o output.txt
# List supported formats
chomper-parse --formats
# Quiet mode (no progress messages)
chomper-parse document.pdf -q输出格式
# Plain text (default)
chomper-parse document.pdf
# JSON output
chomper-parse document.pdf --format json
chomper-parse document.pdf --json # shortcut
# CSV output
chomper-parse document.pdf --format csv
# Markdown output
chomper-parse document.pdf --format markdown
# XML output
chomper-parse document.pdf --format xml
# Custom Jinja2 template
chomper-parse document.pdf --format template --template my_template.j2观看模式
监控目录中新的/更改的文件并自动解析它们:
# Watch a directory
chomper-parse --watch ./documents
# Watch with JSON output saved to files
chomper-parse --watch ./inbox --format json --output-dir ./parsed
# Watch only PDFs, check every 5 seconds
chomper-parse --watch ./docs --pattern "*.pdf" --interval 5
# Watch recursively (including subdirectories)
chomper-parse --watch ./project --recursive
# Watch with metadata only
chomper-parse --watch ./docs --metadata --format json交互模式
启动一个交互式shell来解析多个文档:
$ chomper-parse -i
Chomper Interactive Mode
Type 'help' for commands, 'exit' to quit.
chomper> parse ~/Documents/report.pdf
[Document content displayed...]
chomper> set format json
Output format set to: json
chomper> metadata ~/Documents/report.pdf
{
"filename": "report.pdf",
"format": "pdf",
"page_count": 5
}
chomper> history
Files parsed this session:
1. /Users/me/Documents/report.pdf
chomper> help
[Shows all available commands]
chomper> exit交互式命令:
| 命令 | 描述 |
|---|---|
parse | 解析文档 |
metadata | 仅显示元数据 |
chunk | 分成块 |
formats | 列出支持的格式 |
set format | 设置输出格式 |
set json on/off | 切换JSON模式 |
set max-chars N | 限制输出 |
history | 显示解析后的文件 |
status | 显示当前设置 |
help | 显示所有命令 |
exit | 退出交互模式 |
CLI选项
| 选项 | 描述 |
|---|---|
-f, --format | 输出格式: text, json, csv, markdown, xml, template |
--template | Jinja2模板文件(含 --format template) |
--json | 快捷方式 --format json |
--metadata | 仅显示元数据 |
--chunk | 分成块 |
--strategy | Chunking: auto, semantic, fixed |
--chunk-size | 每块单词数(默认值:1000) |
--max-chars | 限制输出字符数 |
-o, --output | 保存到文件 |
-i, --interactive | 启动交互模式 |
-w, --watch | 监视目录的更改 |
--interval | 观察间隔(秒)(默认值:2) |
--output-dir | 将手表输出保存到目录 |
--pattern | 手表模式的文件模式 |
--recursive | 监视子目录 |
--formats | 列出支持的格式 |
-q, --quiet | 抑制进度消息 |
MCP工具
以下工具可通过MCP服务器获得:
可用工具
1. parse_document
解析文档并提取文本、元数据和图像。 默认情况下返回摘要 (前5000个字符)保持在令牌限制范围内。
参数:
| 名称 | 类型 | 默认值 | 描述 |
|---|---|---|---|
file_path | string | 必需 | 文档的绝对路径 |
full_text | 布尔值 | false | 返回完整文本(可能超过令牌限制) |
include_images | 布尔值 | false | 将图像包含为ImageContent |
output_format | 字符串 | "json" | 输出格式: "json" 或 "toon" (令牌优化) |
答复:
TextContent[0]:纯提取文本(无JSON包装)TextContent[1]:JSON格式的元数据(如果截断,则包括继续提示)ImageContent[]:图像如果include_images=true
例子:
parse_document(file_path: "/path/to/doc.pdf")
→ Returns first 5000 chars + metadata with hint to fetch more
parse_document(file_path: "/path/to/doc.pdf", output_format: "toon")
→ Returns in TOON format (~40% fewer tokens)2. parse_document_bytes
从以下位置解析文档 base64编码内容。非常适合来自云存储(S3、Azure Blob)、API响应、数据库Blob或内存中文档的文档。
参数:
| 名称 | 类型 | 默认值 | 描述 |
|---|---|---|---|
content_base64 | string | 必填 | Base64编码文件内容 |
filename | string | required | 带扩展名的文件名(例如。, "report.pdf")用于格式检测 |
full_text | 布尔值 | false | 返回完整文本 |
include_images | 布尔值 | false | 将图像包含为ImageContent |
output_format | 字符串 | "json" | 输出格式: "json" 或 "toon" |
例子:
import base64
# Read file and encode to base64
with open("document.pdf", "rb") as f:
content = base64.b64encode(f.read()).decode()
# Send via MCP
parse_document_bytes(
content_base64=content,
filename="document.pdf"
)
→ Returns extracted text + metadata (same as parse_document)使用案例:
- 从云存储(S3、Azure Blob、GCS)获取的文档
- 从API响应收到的文件
- 以BLOB形式存储在数据库中的文档
- 无需磁盘I/O的内存文档处理
4. get_document_chunk
获取文档文本的特定部分。 用于对大型文档进行分页检索。
参数:
| 名称 | 类型 | 默认值 | 描述 |
|---|---|---|---|
file_path | string | 必需 | 文档的绝对路径 |
offset | 整数 | 0 | 字符偏移量从开始 |
limit | 整数 | 5000 | 要返回的最大字符数 |
output_format | 字符串 | "json" | 输出格式: "json" 或 "toon" |
工作流程示例:
1. parse_document(file_path: "doc.pdf")
→ Returns chars 0-5000, hint: "use get_document_chunk(offset=5000)"
2. get_document_chunk(file_path: "doc.pdf", offset: 5000)
→ Returns chars 5000-10000
3. get_document_chunk(file_path: "doc.pdf", offset: 10000)
→ Returns chars 10000-15000, etc.5. get_document_images
按需从文档中检索图像。将图像作为ImageContent对象返回。
参数:
| 名称 | 类型 | 默认值 | 描述 |
|---|---|---|---|
file_path | string | 必需 | 文档的绝对路径 |
page | integer | 全部 | 特定页码(1-索引) |
max_images | 整数 | 5 | 要返回的最大图像数 |
例子:
get_document_images(file_path: "doc.pdf", page: 1, max_images: 3)
→ Returns first 3 images from page 1 as ImageContent6. parse_document_chunked
将文档解析为具有可配置大小和重叠的语义块。非常适合RAG系统。
参数:
| 名称 | 类型 | 默认值 | 描述 |
|---|---|---|---|
file_path | string | 必需 | 文档的绝对路径 |
chunk_size | 整数 | 1000 | 每个块的目标单词 |
overlap | 整数 | 100 | 单词在块之间重叠 |
chunking_strategy | 字符串 | "auto" | 战略: "auto", "semantic", "fixed", "recursive" |
embedding_model | 字符串 | "fast" | 语义方面: "fast" (~80MB)或 "balanced" (约420 MB) |
output_format | 字符串 | "json" | 输出格式: "json" 或 "toon" |
分块策略:
auto:格式感知分块(对每种文件类型使用专门的分块器)semantic:使用句子变换器进行基于嵌入的分块(最适合RAG)fixed:简单的字符数拆分recursive:段落/句子边界分割
响应(JSON):
{
"success": true,
"total_chunks": 25,
"chunking_strategy": "semantic",
"embedding_model": "fast",
"chunks": [
{
"chunk_id": 0,
"text": "Chunk content...",
"word_count": 250,
"keywords": ["key", "terms"],
"section_name": "Introduction",
"metadata": {
"chunk_strategy": "semantic",
"breakpoint_strategy": "percentile"
}
}
],
"statistics": {
"total_words": 6000,
"average_chunk_words": 240
}
}7. extract_metadata
无需完全文档处理即可快速提取元数据。
参数:
| 名称 | 类型 | 默认值 | 描述 |
|---|---|---|---|
file_path | string | 必需 | 文档的绝对路径 |
output_format | 字符串 | "json" | 输出格式: "json" 或 "toon" |
响应(JSON):
{
"success": true,
"metadata": {
"author": "John Doe",
"title": "Document Title",
"page_count": 10
},
"document_info": {
"text_length": 35000,
"image_count": 5
}
}8. list_supported_formats
列出所有支持的文档格式及其可用性状态。
9. batch_parse
在单个请求中解析多个文档。
参数:
| 名称 | 类型 | 默认值 | 描述 |
|---|---|---|---|
file_paths | string\[\] | 必填 | 文件路径数组 |
include_images | 布尔值 | false | 包括图像 |
continue_on_error | 布尔值 | true | 如果文件失败,请继续 |
MCP提示
服务器公开了5个可用于Claude的文档分析提示:
| 提示 | 描述 | 参数 |
|---|---|---|
summarize-document | 生成全面的文档摘要 | file_path, length (短/中/长) |
extract-key-points | 提取主要要点和关键点 | file_path, max_points |
explain-document | 为不同受众解释文档 | file_path, audience (儿童/将军/专家) |
extract-entities | 提取命名实体(人员、组织、位置) | file_path, entity_types |
document-qa | 为文档设置问答上下文 | file_path |
Claude中的用法:
Use the summarize-document prompt with file_path="/path/to/doc.pdf"TOON格式(令牌优化输出)
与JSON相比,TOON格式将令牌使用量减少了约40%,非常适合LLM上下文:
d:report.pdf|t:pdf|w:5000|c:25000|n:10
m:author=John Doe,title=Annual Report
---
0|0-2500|text|Introduction
The document begins with an overview...
k:overview,introduction,summary
---
1|2500-5000|text|Methodology
The methodology section describes...
k:methodology,approach,methods启用: output_format: "toon" 在任何工具上。
支持的格式
| 类别 | 扩展 | 描述 |
|---|---|---|
| 文件 | .pdf, .docx, .doc, .pptx, .ppt | 结构完整的办公文件 |
| 电子表格 | .xlsx, .xlsm, .xltx, .xltm, .csv, .tsv | 带类型推断的表 |
| 网络 | .html, .htm, .md, .markdown | 语义结构保存 |
| 文本 | .txt, .text, .log | 带段落检测的纯文本 |
| 代码 | .py, .js, .ts, .jsx, .tsx, .java, .cpp, .c, .go, .rs | 语言感知解析 |
| 数据 | .json, .yaml, .yml, .xml | 具有模式检测的结构化数据 |
| 电子邮件 | .eml, .msg | 带有标题、正文和附件的电子邮件 |
| 电子书 | .epub | TOC章节提取 |
| 富文本 | .rtf | 富文本格式文档 |
总计:支持36个文件扩展名
推荐使用模式
对于具有令牌限制的AI系统,要获得最佳结果:
# 1. Start with summary (default behavior)
parse_document(file_path: "large_doc.pdf")
# 2. If you need more content, paginate
get_document_chunk(file_path: "large_doc.pdf", offset: 5000)
get_document_chunk(file_path: "large_doc.pdf", offset: 10000)
# 3. Fetch images separately when needed
get_document_images(file_path: "large_doc.pdf", max_images: 3)
# 4. For RAG pipelines, use semantic chunking
parse_document_chunked(file_path: "doc.pdf", chunking_strategy: "semantic")避免:
# DON'T use full_text=true for large documents - will exceed token limits!
parse_document(file_path: "large_doc.pdf", full_text: true) # Bad建筑
服务器封装了一个4层文档处理管道:
┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ Extractors │ -> │ Chunkers │ -> │ Enrichers │ -> │ Formatters │
│ (Layer 1) │ │ (Layer 2) │ │ (Layer 3) │ │ (Layer 4) │
└─────────────┘ └─────────────┘ └─────────────┘ └─────────────┘
│ │ │ │
v v v v
Raw text + Semantic Keywords + JSON/TOON
Structure Chunks Metadata Output提取器: 格式特定的文本和元数据提取 Chunkers: 自动、语义(嵌入)、固定、递归策略 Enrichers: 关键词、章节、标题、复杂性得分 格式化程序: JSON(默认)或TOON(令牌优化)
依赖项
核心(始终可用):
mcp>=1.0.0-模型上下文协议- 代码、文本、Markdown提取器(无严重依赖关系)
可选(用于其他格式):
- PDF:
pymupdf,pymupdf4llm,pillow - 办公室:
python-docx,python-pptx,openpyxl - 网状物:
beautifulsoup4,lxml,trafilatura - 数据:
pyyaml(YAML),lxml(XML) - 电子邮件:
extract-msg(MSG文件) - 电子书:
ebooklib(EPUB) - 富文本:
striprtf(RTF) - 语义分块:
sentence-transformers
安装所有依赖项:
pip install -r requirements.txt错误处理
所有响应均包含有关故障的适当错误信息:
{
"success": false,
"error": "File not found: /path/to/missing.pdf",
"error_type": "ValueError"
}发展
# Install dev dependencies
pip install -e ".[dev]"
# Run tests
pytest
python src/tests/test_lightweight.py
# Format code
black .
# Lint
ruff check .与其他工具的比较
| 功能 | Chomper | LlamaParse | 文档处理 | 非结构化 |
|---|---|---|---|---|
| MCP本机 | 是 | 否 | 否 | 不 |
| 格式计数 | 36 | ~15 | ~10 | ~20 |
| 代币优化 | TOON(约节省40%) | 否 | 否 | |
| 语义分块 | 内置 | 分离 | 分离 | 独立 |
| MCP提示 | 5内置 | 否 | 否 | 无 |
| 复杂表格 | 良好(pymupdf4llm) | 优秀 | 优秀(AI) | 一般 |
| 是否需要云 | 否(本地) | 是 | 否 | 可选 |
| 成本 | 免费 | 付费 | 免费 | 免费增值 |
贡献
欢迎投稿!请阅读 贡献.md 作为指导方针。
贡献者快速入门
# Fork and clone
git clone https://github.com/YOUR_USERNAME/chomper.git
cd chomper
# Setup dev environment
python -m venv venv
source venv/bin/activate
pip install -e ".[dev]"
# Run tests
pytest
# Format code
black .
ruff check .许可证
MIT许可证-请参阅 许可证 了解详情。
______________________________________________________________________
用爱建造 @IcHiGo KuRoSaKiI
