Calibre 工具
一套全面的工具,用于与您的Calibre库进行交互,包括语义搜索、重复检测、ISBN工具以及与Claude的MCP集成。
  
✨ 特点
- 🔍 看起来像是一个放大镜的符号,常用于表示搜索、查看细节或调查等动作,在中文里可以翻译为“🔍(放大镜)”或者根据上下文意译为“🔍(查看/搜索)”等,但直接作为符号使用时,通常保留原样或简单说明其含义。 语义搜索使用由句子变换器支持的自然语言查询来查找书籍
- 📖 书籍或书本的符号 完整的元数据获取书籍的完整信息,包括描述、出版商、ISBN、格式
- 🚀 表示火箭或快速前进,常用来比喻快速发展、进步或激动人心的事情。 批量富集自动从在线资源中查找并补充缺少元数据的书籍信息
- 🌐 代表“互联网”或“全球网络”的符号,可翻译为“🌐(表示互联网或全球网络)”或根据上下文简化为“网络”等词汇,但直接以“🌐”开头并加注释是最准确的翻译方式。 在线元数据获取查询亚马逊、Goodreads、谷歌图书以获取丰富的元数据
- 🔄 旋转(或循环)符号 重复检测按标题、作者、ISBN或内容相似性查找重复书籍
- 📚 书籍 ISBN 工具提取、验证并搜索ISBN-10和ISBN-13
- 🛠️(工具/螺丝刀) Calibre 命令行界面(CLI)集成所有常见Calibre操作的Python封装器
- 🤖 机器人 MCP 集成通过模型上下文协议直接在Claude桌面中使用工具
- ⚡(闪电符号,常用于表示速度、能量、活力或紧急情况等) 性能优化懒加载、缓存以及对Apple Silicon的MPS支持
______________________________________________________________________
📦 安装
先决条件
- Python 3.11及以上版本
- Calibre已安装且已添加到系统路径中
- (可选)用于语义搜索的PyTorch
从源代码安装
git clone https://github.com/yourusername/calibre-tools.git
cd calibre-tools
pip install -e .安装依赖项
# Core dependencies
pip install sentence-transformers scikit-learn numpy
# Testing dependencies
pip install pytest pytest-cov
# MCP dependencies
pip install mcp______________________________________________________________________
🚀 快速入门
Python API
from calibre_tools import semantic_search, isbn_tools, duplicate_finder
# Semantic search
results = semantic_search.search("fantasy novels with dragons", top_n=5)
for result in results:
print(f"{result['metadata']['title']} (Score: {result['score']:.2f})")
# Validate ISBN
is_valid = isbn_tools.validate_isbn("978-0-547-92822-7")
print(f"ISBN valid: {is_valid}")
# Find duplicates
duplicates = duplicate_finder.find_all_duplicates()
print(f"Found {len(duplicates['exact_matches'])} exact duplicates")命令行脚本
批量富集(基于命令行界面):
# Find and enrich 10 books missing descriptions
python batch_enrich.py --limit 10 --missing comments
# Enrich 20 books automatically without prompts
python batch_enrich.py --limit 20 --auto-apply
# Just find candidates, don't enrich
python batch_enrich.py --find-only --limit 50
# Refresh semantic search cache after enrichment
python batch_enrich.py --limit 10 --refresh-search批量富集(基于SQL - 速度快35%):
# Same features as above, but uses direct SQL queries for faster candidate finding
python batch_enrich_sql.py --limit 20 --missing comments --auto-apply
# Find books missing publisher
python batch_enrich_sql.py --find-only --missing publisher --limit 50
# Find books missing ANY metadata field
python batch_enrich_sql.py --find-only --missing all --limit 100从文件中提取ISBN号:
# Extract ISBNs from EPUB files and enrich metadata
python extract_and_enrich_isbns.py --limit 20 --formats EPUB --auto-apply
# Extract from books missing descriptions (most likely to need enrichment)
python extract_and_enrich_isbns.py --limit 50 --missing-description --auto-apply
# Just extract ISBNs, don't enrich
python extract_and_enrich_isbns.py --find-only --limit 100
# Scan all formats
python extract_and_enrich_isbns.py --formats EPUB,PDF,MOBI,AZW3 --limit 200以ISBN/ASIN作为标题来丰富书籍信息:
# Find and enrich books where title is just an ISBN or ASIN
python enrich_identifier_titles.py --limit 10 --auto-apply通过标识符(ISBN/亚马逊/ASIN)进行丰富:
# Find and enrich books with identifiers but missing descriptions
python enrich_by_identifier_sql.py --limit 20 --auto-apply
# Just find candidates
python enrich_by_identifier_sql.py --find-only --limit 50
# Preview 10 books (interactive mode)
python enrich_by_identifier_sql.py --limit 10按标题/作者丰富(无ISBN):
# Find and enrich books without ISBNs but with good title/author info
python enrich_by_title_sql.py --limit 20 --auto-apply
# Just find candidates
python enrich_by_title_sql.py --find-only --limit 50
# Adjust minimum title length filter
python enrich_by_title_sql.py --min-title-length 15 --limit 30课程元数据抓取工具:
# Extract metadata for video courses (Udemy, Coursera, Pluralsight, LinkedIn Learning)
python course_scraper_enhanced.py
# Features: Full metadata, opening detection, file path tracking
# Extract metadata for chess courses (Chessable, ChessBase, Modern Chess, TheChessWorld, Lichess)
python chess_course_scraper.py
# Features: Chess-specific metadata (opening, level), content type detection (video/pgn/study/database/ebook)
# See COURSE_SCRAPER_README.md for detailed documentation查找并删除重复项:
# Find duplicates (no deletion)
python find_duplicates_sql.py --find-only
# Interactive mode (ask for each duplicate)
python find_duplicates_sql.py --interactive
# Dry run (show what would be deleted)
python find_duplicates_sql.py --auto-delete --dry-run
# Auto-delete duplicates with smart scoring
python find_duplicates_sql.py --auto-delete
# Custom format priority (EPUB preferred over PDF)
python find_duplicates_sql.py --auto-delete --format-priority "DJVU,AZW3,MOBI,PDF,EPUB"手动测试:
# Interactive test menu
python manual_test.pyPython API:
# Using Python directly
python -c "from calibre_tools.semantic_search import search; print(search('sci-fi', 3))"______________________________________________________________________
🧪 测试
自动化测试(pytest)
# Run all tests
pytest
# Run with coverage
pytest --cov=calibre_tools --cov-report=html
# Run specific test file
pytest tests/calibre_tools/test_isbn_tools.py
# Run specific test
pytest tests/calibre_tools/test_isbn_tools.py::TestISBNTools::test_validate_isbn10_valid -v
# View coverage report
open htmlcov/index.html测试结果:
- ✅ 86项测试 - 全部通过
- ⚡(闪电符号,常用于表示速度、能量或惊喜等) 约3秒 - 快速执行
- 📊 表格/数据图表 75%的覆盖率 - 高代码覆盖率
- 🎯(瞄准靶心) 100% 标准工具(或:100% 合格工具,具体翻译取决于“calibre_tools”在此上下文中的具体含义,这里提供了较为通用的翻译) - 核心模块已全面测试
手动/交互式测试
对于使用您实际的Calibre库进行测试:
python manual_test.py这将启动一个交互式菜单,您可以在其中:
CLI封装器测试:
- 列出书籍(支持搜索、排序、限制数量)
- 添加带有元数据的书籍 ⚠️
- 移除书籍 ⚠️
- 设置元数据 ⚠️
- 搜索库
ISBN工具: 6\. 验证ISBN号码 7\. 从文本中提取ISBN号 8\. 从文件中提取ISBN号 9\. 通过ISBN查找书籍
重复文件查找器: 10\. 查找所有重复项(完全相同、相似、ISBN相同)
语义搜索: 11\. 自然语言搜索
特点:
- ✅ 默认安全 - 在修改前发出警告
- ✅ 对于破坏性操作的交互式提示
- ✅ 格式化美观的JSON输出
- ✅ 使用真实的Calibre数据进行测试
- ✅ 常用操作的快速测试模式
示例会话:
$ python manual_test.py
Options:
1. Interactive menu
2. Quick test
3. Exit
Enter choice: 1
Using Calibre library: ~/Calibre Library
SELECT A TEST:
============================================================
CLI WRAPPER:
1. List books
...
Enter choice: 1
============================================================
LIST BOOKS
============================================================
Getting first 5 books from library...
Found 5 books:
[
{
"id": 1,
"title": "The Hobbit",
"authors": ["J.R.R. Tolkien"],
...
}
]______________________________________________________________________
🔧 配置
配置是通过环境变量来处理的,并且 calibre_tools/config.py:
环境变量
# Calibre library path
export CALIBRE_LIBRARY_PATH="~/Calibre Library"
# Force cache refresh
export FORCE_REFRESH=1
# Cache expiry (days)
export CACHE_EXPIRY_DAYS=7
# Force CUDA (otherwise auto-detects MPS on Mac)
export USE_CUDA=1设备检测
系统会自动检测并选择最佳可用设备:
- CUDA - 如果
USE_CUDA=1并且CUDA可用 - MPS(在不同上下文中可能代表不同含义,如“马来西亚邮政”、“多模态感知系统”等,具体需根据语境确定) - 如果是搭载Apple Silicon的Mac(具有回退选项)
- CPU(中央处理器) - 默认回退
缓存设置
嵌入向量被缓存于 ~/.calibre_tools/:
embeddings.pkl- 书籍嵌入metadata.json- 书籍元数据
缓存刷新时机为:
- 文件不存在
- 超过(某时间)的文件
CACHE_EXPIRY_DAYS FORCE_REFRESH=1设置
______________________________________________________________________
Claude的MCP集成机器人
设置
- 启动MCP服务器:
python -m calibre_mcp.app- 配置Claude桌面版(添加到
claude_desktop_config.json):
{
"mcpServers": {
"calibre": {
"command": "python",
"args": ["-m", "calibre_mcp.app"],
"env": {
"CALIBRE_LIBRARY_PATH": "/path/to/Calibre Library"
}
}
}
}可用工具(共22个)
搜索与发现:
calibre_semantic_search- 使用自然语言进行搜索calibre_list_books- 列出带过滤条件的书籍calibre_search_library- 使用Calibre语法进行搜索calibre_get_book_details- 获取特定书籍的完整元数据calibre_sql- 在 Calibre 的 metadata.db 上执行只读 SQL 查询
元数据丰富化:
calibre_fetch_metadata_by_identifier- 使用ASIN、ISBN或Goodreads ID获取元数据calibre_fetch_metadata_by_title- 通过标题/作者获取元数据calibre_enrich_book_metadata- 自动检测标识符并丰富(提供预览)calibre_apply_metadata_updates- 应用建议的元数据更新calibre_find_books_needing_enrichment- 查找ISBN中缺少元数据的书籍calibre_batch_enrich_books- 批量处理多本书籍calibre_enrich_identifier_titles- 查找并丰富那些书名即为ISBN/ASIN的书籍信息
重复检测:
calibre_find_duplicates- 通过书名、作者、ISBN查找重复书籍
ISBN工具:
calibre_isbn_extract_from_text- 从文本中提取ISBN号calibre_isbn_validate- 验证ISBNcalibre_isbn_find_books- 通过ISBN查找书籍
图书馆管理:
calibre_add_book- 将书籍添加到图书馆calibre_remove_book- 从图书馆移除书籍calibre_set_book_metadata- 更新书籍元数据(标题、作者、ISBN、标签、出版社、评论、出版日期、系列、评分、语言)calibre_bulk_update_comments- 批量更新多本书的评论/描述calibre_convert_format- 转换书籍格式calibre_export_book- 导出书籍文件
示例工作流程:在Claude Desktop中进行批量富集
以下是使用元数据增强工具自动为缺少元数据的书籍添加元数据的方法:
1. 寻找需要丰富内容的书籍:
You: "Find 10 books with ISBNs that are missing descriptions"
→ Uses calibre_find_books_needing_enrichment
→ Returns list of books with IDs, titles, ISBNs2. 丰富单一书籍内容(自动识别标识符):
You: "Enrich book ID 1762"
→ Uses calibre_enrich_book_metadata
→ Auto-detects ISBN/ASIN from title or identifiers field
→ Fetches metadata from Amazon/Goodreads/Google Books
→ Shows existing metadata vs. suggested updates3. 选择性地应用更新:
You: "Update the publisher and series for book 1762"
→ Uses calibre_apply_metadata_updates(1762, "Publisher,Series")
→ Applies only the specified fields
→ Returns confirmation of updates4. 批量处理多本书籍:
You: "Batch enrich 20 books with ISBNs missing metadata"
→ Uses calibre_batch_enrich_books(20)
→ Processes up to 20 books automatically
→ Returns summary: total processed, successful, failed
→ Shows detailed results for each book主要特点:
- ✅ 自动检测 - 在标题或标识符字段中查找ASIN/ISBN
- ✅ 应用前预览 - 在更新前查看建议的更改
- ✅ 选择性更新 - 选择要更新的字段
- ✅ 批处理 - 一次性丰富10-50本书的内容
- ✅ 关注ISBN(国际标准书号) - 相比ASIN,更可靠地获取元数据
示例工作流程:批量更新杂志评论
这个(或“它”) calibre_bulk_update_comments 该工具非常适合为书籍组(例如,杂志、期刊)添加通用描述,以防止它们被元数据增强工具抓取:
1. 查找杂志/期刊ID:
You: "Find all books with 'The Economist' in the title"
→ Uses calibre_search_library or calibre_list_books
→ Returns list of book IDs2. 批量更新评论:
You: "Update the comments for books [1234, 1235, 1236, ...] with the text 'This is a periodical/magazine issue and does not require metadata enrichment.'"
→ Uses calibre_bulk_update_comments
→ Updates all books at once
→ Returns success/failure count and detailed results示例回复:
{
"success_count": 290,
"failure_count": 0,
"total": 290,
"updated_ids": [1234, 1235, 1236, ...],
"errors": null
}用例:
- 📰(报纸) 杂志 - 标记期刊以排除在富集之外
- 📚 书籍 系列 - 为书籍系列添加统一描述
- 标签 分类 - 按类型批量分类书籍
- 🚫 排除 - 在自动化处理中标记要跳过的书籍
______________________________________________________________________
📁 项目结构
.
├── calibre_tools/ # Core functionality
│ ├── __init__.py
│ ├── config.py # Configuration & device detection
│ ├── semantic_search.py # Semantic search with embeddings
│ ├── duplicate_finder.py # Duplicate detection algorithms
│ ├── isbn_tools.py # ISBN extraction & validation
│ ├── cli_wrapper.py # Calibre CLI wrappers + bulk_update_comments
│ └── batch_enrichment.py # Batch enrichment tools
│
├── calibre_mcp/ # MCP integration
│ ├── __init__.py
│ ├── app.py # MCP server entry point
│ ├── server.py # MCP server instance
│ └── tools/ # MCP tool definitions
│ ├── __init__.py
│ ├── semantic_search.py
│ ├── book_details.py # calibre_get_book_details
│ ├── metadata_enrichment.py # 7 enrichment tools
│ ├── duplicate_finder.py
│ ├── isbn_tools.py
│ ├── calibre_cli.py # Library management + bulk_update_comments
│ └── sql_query.py # Direct SQL query tool
│
├── tests/ # Comprehensive test suite
│ ├── conftest.py # Shared fixtures
│ └── calibre_tools/
│ ├── test_config.py # 9 tests
│ ├── test_semantic_search.py # 14 tests
│ ├── test_duplicate_finder.py # 13 tests
│ ├── test_isbn_tools.py # 19 tests
│ └── test_cli_wrapper.py # 31 tests
│
├── Command-Line Scripts:
├── batch_enrich.py # CLI-based batch enrichment
├── batch_enrich_sql.py # SQL-based batch enrichment (35% faster)
├── extract_and_enrich_isbns.py # Extract ISBNs from files and enrich
├── enrich_identifier_titles.py # Enrich books with ISBN/ASIN as title
├── enrich_by_identifier_sql.py # Enrich books with identifiers but missing descriptions
├── enrich_by_title_sql.py # Title/author-based enrichment (no ISBN)
├── find_duplicates_sql.py # Find and remove duplicate books
├── course_scraper_enhanced.py # Scrape video course metadata (Udemy, Coursera, etc.)
├── chess_course_scraper.py # Scrape chess course metadata with content type detection
├── refresh_search_cache.py # Refresh semantic search cache
├── manual_test.py # Interactive testing script
│
├── pytest.ini # Pytest configuration
├── .coveragerc # Coverage configuration
├── TEST_RESULTS.md # Detailed test documentation
└── README.md # This file______________________________________________________________________
API 文档
语义搜索
from calibre_tools.semantic_search import search, CalibreSemanticSearch
# Quick search
results = search("epic fantasy adventure", top_n=5)
# Advanced usage
searcher = CalibreSemanticSearch(
library_path="~/Calibre Library",
model_name="all-MiniLM-L6-v2",
device="mps" # or "cuda", "cpu"
)
results = searcher.search("query", top_n=10)重复文件查找器
from calibre_tools.duplicate_finder import (
find_all_duplicates,
find_exact_duplicates,
find_similar_titles,
find_isbn_duplicates
)
# Find all types
results = find_all_duplicates(library_path="~/Calibre Library")
# Find specific types
exact = find_exact_duplicates(books, fields=['title', 'authors'])
similar = find_similar_titles(books, similarity_threshold=0.85)
isbn = find_isbn_duplicates(books)ISBN工具
from calibre_tools.isbn_tools import (
validate_isbn,
validate_isbn10,
validate_isbn13,
extract_isbn_from_text,
extract_isbn_from_file,
find_books_by_isbn,
get_book_isbn
)
# Validate
is_valid = validate_isbn("978-0-547-92822-7")
# Extract
isbns = extract_isbn_from_text("ISBN: 978-0-547-92822-7")
isbns = extract_isbn_from_file("book.epub")
# Find books
books = find_books_by_isbn("9780547928227")CLI 封装器
from calibre_tools.cli_wrapper import (
list_books,
add_book,
remove_book,
set_metadata,
bulk_update_comments,
convert_book,
search_library,
fetch_ebook_metadata,
get_book_metadata
)
# List with filters
books = list_books(
library_path="~/Calibre Library",
search_term="tolkien",
sort_by="title",
limit=10
)
# Add book
book_id = add_book(
"book.epub",
title="My Book",
authors="Author Name",
isbn="9780547928227"
)
# Update single book metadata
set_metadata(
book_id=1762,
library_path="~/Calibre Library",
publisher="Publisher Name",
comments="Book description",
tags="fiction,fantasy"
)
# Bulk update comments for multiple books
results = bulk_update_comments(
book_ids=[1234, 1235, 1236],
comment_text="This is a periodical/magazine issue.",
library_path="~/Calibre Library"
)
print(f"Updated {results['success_count']} books")
# Search
books = search_library("author:tolkien AND tags:fantasy")
# Fetch metadata from online sources
metadata = fetch_ebook_metadata(isbn="9780547928227", timeout=30)
# Or by ASIN
metadata = fetch_ebook_metadata(identifiers=["amazon:B004XFYWNY"])
# Get full book details from Calibre
details = get_book_metadata(book_id=1762)批量富集
from calibre_tools.batch_enrichment import (
find_books_needing_enrichment,
enrich_single_book,
batch_enrich_books
)
# Find books with ISBNs that are missing descriptions
candidates = find_books_needing_enrichment(
limit=10,
require_isbn=True,
missing_fields=['comments', 'publisher']
)
print(f"Found {len(candidates)} books needing enrichment")
for book in candidates:
print(f" {book['id']}: {book['title']} (ISBN: {book['isbn']})")
# Enrich a single book
result = enrich_single_book(book_id=1679)
if result['success']:
print(f"Fetched metadata: {result['fetched_metadata']}")
# Apply updates
from calibre_tools.cli_wrapper import set_metadata
set_metadata(
book_id=1679,
publisher=result['fetched_metadata']['Publisher'],
comments=result['fetched_metadata']['Comments']
)
# Batch process multiple books
results = batch_enrich_books(limit=10, find_candidates=True)
print(f"Processed: {results['total_processed']}")
print(f"Successful: {results['successful']}")
print(f"Failed: {results['failed']}")
for r in results['results']:
if r['success']:
print(f"✓ Book {r['book_id']}: Enriched with {r['identifier_used']}")
else:
print(f"✗ Book {r['book_id']}: {r['error']}")______________________________________________________________________
🐛 故障排除
常见问题
“未找到 calibredb”
- 确保已安装Calibre且已将其添加到PATH环境变量中
- 在Mac上:
/Applications/calibre.app/Contents/MacOS/calibredb
MPS 在 Mac 上无法运行
- 检查PyTorch版本:
python -c "import torch; print(torch.backends.mps.is_available())" - 系统自动回退到CPU
初步搜索较慢
- 首次运行时会下载嵌入模型(约90MB)
- 后续的搜索使用缓存的嵌入向量
导入错误
- 确保所有依赖项都已安装:
pip install -r requirements.txt
调试模式
import logging
logging.basicConfig(level=logging.DEBUG)______________________________________________________________________
🤝 贡献
欢迎投稿!请:
- 为仓库创建分支(或:克隆仓库)
- 创建一个特性分支
- 为新功能编写测试
- 确保所有测试通过:
pytest - 提交拉取请求
______________________________________________________________________
📄 许可证
MIT 许可证 - 详情请参阅 LICENSE 文件
______________________________________________________________________
🙏 致谢
- Calibre - 强大的电子书管理软件
- sentence-transformers - 语义搜索模型
- MCP - 由Anthropic提出的模型上下文协议
______________________________________________________________________
📞 支持
- 问题:
- 文档:参见
TEST_RESULTS.md用于详细的测试文档
______________________________________________________________________
为Calibre社区倾心打造
