
Pdf Ocr Skill
- 1.6k installs
- 13 repo stars
- Updated April 20, 2026
- yejinlei/pdf-ocr-skill
pdf-ocr-skill extracts bilingual text from scanned PDFs and images via four OCR engines.
About
The pdf-ocr-skill extracts text from scanned PDF files and images in Chinese and English using four OCR engines: RapidOCR local, RapidDoc enhanced, PaddleOCR local, and SiliconFlow cloud API. Dependencies include pymupdf, pillow, requests, and python-dotenv with optional RapidOCR install for offline use. Supports JPG, PNG, BMP, GIF, TIFF, and WEBP images plus PDF page rasterization before recognition. Smart engine switching falls back to SiliconFlow API when RapidOCR initialization fails. Preserves text order and structure across pages. Agents invoke when users need OCR on scanned documents, bilingual text extraction, or local versus cloud engine selection for PDF and image inputs. Four engines: RapidOCR, RapidDoc, PaddleOCR, SiliconFlow API. Scanned PDF and image OCR for Chinese and English text. Auto-fallback to SiliconFlow when RapidOCR init fails. Formats: JPG, PNG, BMP, GIF, TIFF, WEBP, and PDF pages.
- Four engines: RapidOCR, RapidDoc, PaddleOCR, SiliconFlow API.
- Scanned PDF and image OCR for Chinese and English text.
- Auto-fallback to SiliconFlow when RapidOCR init fails.
- Formats: JPG, PNG, BMP, GIF, TIFF, WEBP, and PDF pages.
- Preserves text order and structure across extracted content.
Pdf Ocr Skill by the numbers
- 1,646 all-time installs (skills.sh)
- +18 installs in the week ending Aug 5, 2026 (Skillselion tracking)
- Ranked #125 of 688 Office & Documents skills by installs in the Skillselion catalog
- Security screen: MEDIUM risk (skills.sh audit)
- Data as of Aug 5, 2026 (Skillselion catalog sync)
pdf-ocr-skill capabilities & compatibility
- Capabilities
- multi engine ocr · pdf page rasterization · bilingual extraction · engine auto fallback
- Use cases
- pdf parsing · translation
- Pricing
- Freemium
What pdf-ocr-skill says it does
PDF OCR技能用于从影印版PDF文件和图片文件中提取文字内容。
npx skills add https://github.com/yejinlei/pdf-ocr-skill --skill pdf-ocr-skillAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 1.6k |
|---|---|
| repo stars | ★ 13 |
| Security audit | 2 / 3 scanners passed |
| Last updated | April 20, 2026 |
| Repository | yejinlei/pdf-ocr-skill ↗ |
How do I OCR a scanned PDF or image in Chinese and English?
Extract Chinese and English text from scanned PDFs and images using RapidOCR, PaddleOCR, or SiliconFlow cloud engines.
Who is it for?
Document pipelines processing scanned PDFs and bilingual images.
Skip if: Native digital PDF text layers without OCR need.
When should I use this skill?
User needs PDF OCR, scanned document text extraction, or Chinese English OCR.
What you get
Extracted text with preserved order from chosen local or cloud OCR engine.
- extracted text files
- structured OCR output
- engine-specific recognition logs
By the numbers
- Version 2.5.0 with quadruple-engine OCR support
- Accepts 6 image formats: JPG, PNG, BMP, GIF, TIFF, WEBP
- Supports 2 languages: Chinese and English
Files
PDF OCR Skill
中文版本
PDF OCR技能用于从影印版PDF文件和图片文件中提取文字内容。该技能支持两种OCR引擎:
- RapidOCR(本地引擎):无需API密钥,免费使用,识别速度快
- 硅基流动大模型(云端引擎):使用AI大模型进行高精度OCR识别
功能特性
- 支持影印版PDF文件的文字提取
- 支持多种图片格式的文字识别(JPG、PNG、BMP、GIF、TIFF、WEBP)
- 四引擎支持:RapidOCR(本地)、RapidDoc(增强)、PaddleOCR(本地)和硅基流动API(云端)
- 支持中文和英文文字识别
- 保持文字的顺序和结构
- 自动将PDF页面转换为图片进行识别
- 智能引擎切换:当RapidOCR初始化失败时自动切换到硅基流动API
安装
依赖要求
pip install pymupdf pillow requests python-dotenv可选依赖(推荐)
安装RapidOCR以获得本地识别能力:
pip install rapidocr_onnxruntime环境变量配置
1. 复制 .env.example 文件并重命名为 .env 2. 根据需要配置以下选项:
# OCR引擎选择
# - "rapid": 使用RapidOCR本地引擎(默认,无需API密钥)
# - "rapidoc": 使用RapidDoc增强引擎(无需API密钥)
# - "paddle": 使用PaddleOCR本地引擎(无需API密钥)
# - "siliconflow": 使用硅基流动API引擎(需要API密钥)
OCR_ENGINE=rapid
# 如果使用硅基流动API引擎,需要配置以下选项:
SILICON_FLOW_API_KEY=your_api_key_here
SILICON_FLOW_OCR_MODEL=deepseek-ai/DeepSeek-OCR快速开始
使用默认引擎(RapidOCR本地识别)
# 导入OCR处理器
from scripts.pdf_ocr_processor import PDFOCRProcessor
# 创建处理器实例(默认使用RapidOCR)
processor = PDFOCRProcessor()
# 执行PDF OCR识别
result = processor.ocr_pdf('path/to/your/scanned.pdf')
# 获取识别结果
print(f"识别完成,共 {result['page_count']} 页")
print(f"使用引擎: {result['engine']}")
print(result['text'])使用硅基流动API引擎
# 导入OCR处理器
from scripts.pdf_ocr_processor import PDFOCRProcessor
# 创建处理器实例,指定使用硅基流动API
processor = PDFOCRProcessor(engine="siliconflow")
# 执行PDF OCR识别
result = processor.ocr_pdf('path/to/your/scanned.pdf')
# 获取识别结果
print(f"识别完成,共 {result['page_count']} 页")
print(result['text'])识别图片文件
# 导入OCR处理器
from scripts.pdf_ocr_processor import PDFOCRProcessor
# 创建处理器实例
processor = PDFOCRProcessor() # 或 PDFOCRProcessor(engine="siliconflow")
# 执行图片OCR识别
result = processor.ocr_image_file('path/to/your/image.jpg')
# 获取识别结果
print(f"识别结果: {result['text']}")命令行使用
# 使用默认RapidOCR引擎
python pdf_ocr_processor.py your_document.pdf
# 使用硅基流动API引擎
python pdf_ocr_processor.py your_document.pdf siliconflow
# 使用RapidDoc增强引擎
python pdf_ocr_processor.py your_document.pdf rapidoc
# 使用PaddleOCR引擎
python pdf_ocr_processor.py your_document.pdf paddle进阶使用示例
批量处理多个PDF文件
import os
from scripts.pdf_ocr_processor import PDFOCRProcessor
# 创建处理器实例
processor = PDFOCRProcessor()
# 批量处理目录中的所有PDF文件
pdf_dir = "path/to/pdf/files"
output_dir = "path/to/output"
os.makedirs(output_dir, exist_ok=True)
for pdf_file in os.listdir(pdf_dir):
if pdf_file.endswith('.pdf'):
pdf_path = os.path.join(pdf_dir, pdf_file)
output_path = os.path.join(output_dir, f"{os.path.splitext(pdf_file)[0]}.txt")
print(f"处理文件: {pdf_file}")
try:
result = processor.ocr_pdf(pdf_path)
# 保存识别结果到文本文件
with open(output_path, 'w', encoding='utf-8') as f:
f.write(f"=== PDF OCR 识别结果 ===\n")
f.write(f"文件名: {pdf_file}\n")
f.write(f"页数: {result['page_count']}\n")
f.write(f"使用引擎: {result['engine']}\n\n")
f.write(result['text'])
print(f"处理完成,结果已保存到: {output_path}")
except Exception as e:
print(f"处理失败: {e}")混合使用两种引擎
from scripts.pdf_ocr_processor import PDFOCRProcessor
def process_with_best_engine(pdf_path):
"""尝试使用RapidOCR,如果效果不佳则使用硅基流动API"""
# 首先使用RapidOCR本地引擎
rapid_processor = PDFOCRProcessor(engine="rapid")
rapid_result = rapid_processor.ocr_pdf(pdf_path)
# 简单评估识别效果(例如:检查识别出的文本长度)
text_length = len(rapid_result['text'])
if text_length < 100: # 如果识别出的文本太短,可能效果不佳
print("RapidOCR识别效果可能不佳,尝试使用硅基流动API...")
silicon_processor = PDFOCRProcessor(engine="siliconflow")
silicon_result = silicon_processor.ocr_pdf(pdf_path)
return silicon_result
else:
return rapid_result
# 使用示例
result = process_with_best_engine('path/to/your/document.pdf')
print(f"识别完成,使用引擎: {result['engine']}")
print(result['text'])支持的文件格式
- PDF文件: .pdf
- 图片文件: .jpg, .jpeg, .png, .bmp, .gif, .tiff, .webp
输出格式
{
"text": "识别的完整文本内容",
"page_count": 页数, # 图片文件始终为1
"engine": "rapid" | "rapidoc" | "paddle" | "siliconflow" # 使用的OCR引擎
}使用场景
- 处理扫描版合同、协议等文档
- 提取影印版书籍、报告中的文字
- 处理无法直接复制文字的PDF文件
- 批量处理扫描版PDF文档
- 识别截图、扫描件等图片中的文字
- 处理手写体或印刷体图片文字识别
注意事项
1. RapidOCR引擎:
- 完全免费,无需网络连接
- 首次使用会自动下载模型文件
- 识别速度取决于CPU性能
2. 硅基流动API引擎:
- 需要有效的API密钥
- 可能会产生费用
- 识别速度取决于文件页数、图片大小和网络状况
3. RapidDoc引擎:
- 完全免费,无需网络连接
- 支持版面分析、表格识别、公式识别和阅读顺序恢复
- 提供更结构化的输出,包括Markdown格式
- 处理时间可能比RapidOCR长,因为需要进行额外的分析
4. PaddleOCR引擎:
- 完全免费,无需网络连接
- 使用PP-OCRv5模型,具有较高的识别准确率
- 首次使用会自动下载模型文件
- 支持多种语言和场景的文字识别
4. 对于复杂的扫描版PDF或图片,识别准确率可能会有所不同 5. 建议使用高清晰度的扫描版PDF或图片以获得更好的识别效果
触发使用不同引擎的提示词
在与 AI IDE 中的助手交互时,您可以使用以下提示词来指定使用不同的 OCR 引擎:
📍 触发 RapidOCR(本地引擎)的提示词
- "使用本地 OCR 引擎处理这个 PDF"
- "用 RapidOCR 识别这个文件"
- "本地处理,不需要 API"
- "快速识别这个文档"
- "离线处理这个 PDF"
- "不使用硅基流动 API,用本地引擎"
📍 触发硅基流动 API(云端引擎)的提示词
- "使用硅基流动 API 处理这个 PDF"
- "用大模型 OCR 识别这个文件"
- "高精度识别这个文档"
- "处理复杂的扫描件"
- "用云端 OCR 引擎"
- "使用 AI 大模型识别"
📍 触发 RapidDoc(增强引擎)的提示词
- "使用 RapidDoc 处理这个 PDF"
- "用增强 OCR 识别这个文件"
- "处理带有版面分析的 PDF"
- "提取带有表格识别的文本"
- "用 RapidDoc 获得更好的格式"
- "增强 OCR 与版面分析"
📍 触发 PaddleOCR(本地引擎)的提示词
- "使用 PaddleOCR 处理这个 PDF"
- "用 PaddleOCR 识别这个文件"
- "使用 PP-OCRv5 模型识别"
- "用 PaddleOCR 进行高精度识别"
- "PaddleOCR 本地处理"
- "使用 PaddleOCR 引擎提取文字"
📍 示例对话
示例 1:使用本地引擎
用户:帮我处理这个扫描版 PDF,用本地 OCR 引擎快速识别
助手:好的,我将使用 RapidOCR 本地引擎为您处理。请提供 PDF 文件路径。示例 2:使用云端引擎
用户:这个 PDF 包含手写体,需要高精度识别,用硅基流动 API
助手:理解,我将使用硅基流动 API 大模型为您处理。请提供 PDF 文件路径和您的 API 密钥(如果尚未配置)。示例 3:自动选择
用户:帮我识别这个 PDF,选择最合适的引擎
助手:我将默认使用 RapidOCR 本地引擎为您处理。如果识别效果不理想,我们可以尝试使用硅基流动 API。🔧 技术实现
当 AI 助手接收到这些提示词时,会:
1. 解析用户意图,确定要使用的引擎 2. 调用 PDFOCRProcessor(engine="rapid")、PDFOCRProcessor(engine="rapidoc")、PDFOCRProcessor(engine="paddle") 或 PDFOCRProcessor(engine="siliconflow") 3. 执行 OCR 识别并返回结果
🎯 最佳实践
- 明确指定引擎:如果您对引擎有特定要求,最好在提示词中明确说明
- 提供上下文:说明文档类型(如手写体、复杂格式等)有助于助手选择合适的引擎
- 测试不同引擎:对于重要文档,可以尝试两种引擎并比较结果
通过使用这些提示词,您可以在与 AI IDE 交互时灵活控制 OCR 引擎的选择,获得最佳的识别效果
故障排除
常见问题及解决方案
1. RapidOCR初始化失败
- 问题:
ModuleNotFoundError: No module named 'rapidocr_onnxruntime' - 解决方案:安装RapidOCR依赖:
pip install rapidocr_onnxruntime
2. 硅基流动API 401错误
- 问题:
Unauthorized: 401 Client Error - 解决方案:检查API密钥是否正确配置在
.env文件中
3. PDF转图片失败
- 问题:
ImportError: No module named 'fitz' - 解决方案:安装PyMuPDF依赖:
pip install pymupdf
4. 识别结果为空
- 问题:识别结果文本长度为0
- 解决方案:
- 检查PDF是否为扫描版(非文本PDF)
- 尝试使用硅基流动API引擎
- 确保PDF或图片清晰可读
English Version
PDF OCR Skill
PDF OCR Skill is used to extract text content from scanned PDF files and image files. This skill supports two OCR engines:
- RapidOCR (local engine): No API key required, free to use, fast recognition speed
- SiliconFlow Large Model (cloud engine): Uses AI large model for high-precision OCR recognition
Features
- Support text extraction from scanned PDF files
- Support text recognition from multiple image formats (JPG, PNG, BMP, GIF, TIFF, WEBP)
- Quadruple-engine support: RapidOCR (local), RapidDoc (enhanced), PaddleOCR (local), and SiliconFlow API (cloud)
- Support Chinese and English text recognition
- Maintain text order and structure
- Automatically convert PDF pages to images for recognition
- Intelligent engine switching: automatically switch to SiliconFlow API when RapidOCR initialization fails
Installation
Dependencies
pip install pymupdf pillow requests python-dotenvOptional Dependencies (Recommended)
Install RapidOCR for local recognition capability:
pip install rapidocr_onnxruntimeEnvironment Configuration
1. Copy .env.example file and rename it to .env 2. Configure the following options as needed:
# OCR engine selection
# - "rapid": Use RapidOCR local engine (default, no API key required)
# - "rapidoc": Use RapidDoc enhanced engine (no API key required)
# - "paddle": Use PaddleOCR local engine (no API key required)
# - "siliconflow": Use SiliconFlow API engine (API key required)
OCR_ENGINE=rapid
# If using SiliconFlow API engine, configure the following options:
SILICON_FLOW_API_KEY=your_api_key_here
SILICON_FLOW_OCR_MODEL=deepseek-ai/DeepSeek-OCRQuick Start
Using Default Engine (RapidOCR Local Recognition)
# Import OCR processor
from scripts.pdf_ocr_processor import PDFOCRProcessor
# Create processor instance (default uses RapidOCR)
processor = PDFOCRProcessor()
# Perform PDF OCR recognition
result = processor.ocr_pdf('path/to/your/scanned.pdf')
# Get recognition result
print(f"Recognition completed, total {result['page_count']} pages")
print(f"Engine used: {result['engine']}")
print(result['text'])Using SiliconFlow API Engine
# Import OCR processor
from scripts.pdf_ocr_processor import PDFOCRProcessor
# Create processor instance, specify to use SiliconFlow API
processor = PDFOCRProcessor(engine="siliconflow")
# Perform PDF OCR recognition
result = processor.ocr_pdf('path/to/your/scanned.pdf')
# Get recognition result
print(f"Recognition completed, total {result['page_count']} pages")
print(result['text'])Recognizing Image Files
# Import OCR processor
from scripts.pdf_ocr_processor import PDFOCRProcessor
# Create processor instance
processor = PDFOCRProcessor() # or PDFOCRProcessor(engine="siliconflow")
# Perform image OCR recognition
result = processor.ocr_image_file('path/to/your/image.jpg')
# Get recognition result
print(f"Recognition result: {result['text']}")Command Line Usage
# Use default RapidOCR engine
python pdf_ocr_processor.py your_document.pdf
# Use SiliconFlow API engine
python pdf_ocr_processor.py your_document.pdf siliconflow
# Use RapidDoc enhanced engine
python pdf_ocr_processor.py your_document.pdf rapidoc
# Use PaddleOCR engine
python pdf_ocr_processor.py your_document.pdf paddleAdvanced Usage Examples
Batch Processing Multiple PDF Files
import os
from scripts.pdf_ocr_processor import PDFOCRProcessor
# Create processor instance
processor = PDFOCRProcessor()
# Batch process all PDF files in directory
pdf_dir = "path/to/pdf/files"
output_dir = "path/to/output"
os.makedirs(output_dir, exist_ok=True)
for pdf_file in os.listdir(pdf_dir):
if pdf_file.endswith('.pdf'):
pdf_path = os.path.join(pdf_dir, pdf_file)
output_path = os.path.join(output_dir, f"{os.path.splitext(pdf_file)[0]}.txt")
print(f"Processing file: {pdf_file}")
try:
result = processor.ocr_pdf(pdf_path)
# Save recognition result to text file
with open(output_path, 'w', encoding='utf-8') as f:
f.write(f"=== PDF OCR Recognition Result ===\n")
f.write(f"File name: {pdf_file}\n")
f.write(f"Pages: {result['page_count']}\n")
f.write(f"Engine used: {result['engine']}\n\n")
f.write(result['text'])
print(f"Processing completed, result saved to: {output_path}")
except Exception as e:
print(f"Processing failed: {e}")Using Both Engines
from scripts.pdf_ocr_processor import PDFOCRProcessor
def process_with_best_engine(pdf_path):
"""Try using RapidOCR, if not good enough then use SiliconFlow API"""
# First use RapidOCR local engine
rapid_processor = PDFOCRProcessor(engine="rapid")
rapid_result = rapid_processor.ocr_pdf(pdf_path)
# Simple evaluation of recognition effect (e.g., check recognized text length)
text_length = len(rapid_result['text'])
if text_length < 100: # If recognized text is too short, may not be good enough
print("RapidOCR recognition effect may not be good enough, trying SiliconFlow API...")
silicon_processor = PDFOCRProcessor(engine="siliconflow")
silicon_result = silicon_processor.ocr_pdf(pdf_path)
return silicon_result
else:
return rapid_result
# Usage example
result = process_with_best_engine('path/to/your/document.pdf')
print(f"Recognition completed, engine used: {result['engine']}")
print(result['text'])Supported File Formats
- PDF files: .pdf
- Image files: .jpg, .jpeg, .png, .bmp, .gif, .tiff, .webp
Output Format
{
"text": "Recognized full text content",
"page_count": number_of_pages, # Always 1 for image files
"engine": "rapid" | "rapidoc" | "paddle" | "siliconflow" # OCR engine used
}Use Cases
- Processing scanned contracts, agreements and other documents
- Extracting text from photocopied books and reports
- Processing PDF files with non-copyable text
- Batch processing scanned PDF documents
- Recognizing text in screenshots and scanned images
- Processing handwritten or printed text in images
Notes
1. RapidOCR Engine:
- Completely free, no network connection required
- Model files will be automatically downloaded on first use
- Recognition speed depends on CPU performance
2. SiliconFlow API Engine:
- Requires a valid API key
- May incur costs
- Recognition speed depends on number of pages, image size, and network conditions
3. RapidDoc Engine:
- Completely free, no network connection required
- Supports layout analysis, table recognition, formula recognition, and reading order recovery
- Provides more structured output including markdown format
- Processing time may be longer than RapidOCR due to additional analysis
4. PaddleOCR Engine:
- Completely free, no network connection required
- Uses PP-OCRv5 model with high recognition accuracy
- Model files will be automatically downloaded on first use
- Supports text recognition for multiple languages and scenarios
4. Recognition accuracy may vary for complex scanned PDFs or images 5. It is recommended to use high-resolution scanned PDFs or images for better recognition results
Prompt Words for Different Engines
When interacting with assistants in AI IDEs, you can use the following prompt words to specify different OCR engines:
📍 Prompt Words for RapidOCR (Local Engine)
- "Use local OCR engine to process this PDF"
- "Recognize this file with RapidOCR"
- "Local processing, no API needed"
- "Quickly recognize this document"
- "Process this PDF offline"
- "Don't use SiliconFlow API, use local engine"
📍 Prompt Words for SiliconFlow API (Cloud Engine)
- "Use SiliconFlow API to process this PDF"
- "Recognize this file with large model OCR"
- "High-precision recognition for this document"
- "Process complex scanned documents"
- "Use cloud OCR engine"
- "Use AI large model for recognition"
📍 Prompt Words for RapidDoc (Enhanced Engine)
- "Use RapidDoc to process this PDF"
- "Recognize this file with enhanced OCR"
- "Process PDF with layout analysis"
- "Extract text with table recognition"
- "Use RapidDoc for better formatting"
- "Enhanced OCR with layout analysis"
📍 Prompt Words for PaddleOCR (Local Engine)
- "Use PaddleOCR to process this PDF"
- "Recognize this file with PaddleOCR"
- "Use PP-OCRv5 model for recognition"
- "Use PaddleOCR for high-precision recognition"
- "PaddleOCR local processing"
- "Extract text using PaddleOCR engine"
📍 Example Conversations
Example 1: Using Local Engine
User: Help me process this scanned PDF, use local OCR engine for quick recognition
Assistant: Sure, I'll use the RapidOCR local engine for you. Please provide the PDF file path.Example 2: Using Cloud Engine
User: This PDF contains handwritten text, need high-precision recognition, use SiliconFlow API
Assistant: Understood, I'll use the SiliconFlow API large model for you. Please provide the PDF file path and your API key (if not already configured).Example 3: Automatic Selection
User: Help me recognize this PDF, choose the most suitable engine
Assistant: I'll default to using the RapidOCR local engine for you. If the recognition effect is not ideal, we can try using SiliconFlow API.🔧 Technical Implementation
When the AI assistant receives these prompt words, it will:
1. Parse the user's intent to determine the engine to use 2. Call PDFOCRProcessor(engine="rapid"), PDFOCRProcessor(engine="rapidoc"), PDFOCRProcessor(engine="paddle"), or PDFOCRProcessor(engine="siliconflow") 3. Execute OCR recognition and return the result
🎯 Best Practices
- Clearly specify the engine: If you have specific requirements for the engine, it's best to clearly state it in the prompt
- Provide context: Explaining the document type (e.g., handwritten, complex format) helps the assistant choose the appropriate engine
- Test different engines: For important documents, you can try both engines and compare the results
By using these prompt words, you can flexibly control the OCR engine selection when interacting with AI IDEs to get the best recognition results
Troubleshooting
Common Issues and Solutions
1. RapidOCR Initialization Failure
- Issue:
ModuleNotFoundError: No module named 'rapidocr_onnxruntime' - Solution: Install RapidOCR dependency:
pip install rapidocr_onnxruntime
2. SiliconFlow API 401 Error
- Issue:
Unauthorized: 401 Client Error - Solution: Check if the API key is correctly configured in the
.envfile
3. PDF to Image Conversion Failure
- Issue:
ImportError: No module named 'fitz' - Solution: Install PyMuPDF dependency:
pip install pymupdf
4. Empty Recognition Result
- Issue: Recognition result text length is 0
- Solution:
- Check if the PDF is a scanned version (non-text PDF)
- Try using SiliconFlow API engine
- Ensure the PDF or image is clear and readable
License
MIT License - See LICENSE.txt
# 硅基流动平台API密钥(从硅基流动控制台获取)
# 如果使用本地RapidOCR引擎,则不需要填写
SILICON_FLOW_API_KEY=your_api_key_here
# 硅基流动OCR模型(可选)
SILICON_FLOW_OCR_MODEL=deepseek-ai/DeepSeek-OCR
# OCR引擎选择
# 可选值:
# - "rapid": 使用RapidOCR本地引擎(默认,无需API密钥,免费)
# - "siliconflow": 使用硅基流动API引擎(需要API密钥)
OCR_ENGINE=rapid
# Python
__pycache__/
*.py[cod]
*$py.class
*.so
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
# Virtual Environment
venv/
ENV/
env/
# IDE
.vscode/
.idea/
*.swp
*.swo
*~
# OS
.DS_Store
Thumbs.db
# Environment
.env
.env.local
# Testing
.pytest_cache/
.coverage
htmlcov/
# Temporary files
*.tmp
*.bak
*.logMIT License
Copyright (c) 2025 PDF OCR Skill
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.include README.md
include LICENSE.txt
include SKILL.md
include requirements.txt
recursive-include scripts *.py
recursive-exclude * __pycache__
recursive-exclude * *.py[co]PDF OCR Skill
中文版本
一个支持多种OCR引擎的PDF文字提取技能,可以从影印版PDF文件和图片文件中提取文字内容。
功能特性
- ✅ 支持影印版PDF文件的文字提取
- ✅ 支持多种图片格式的文字识别(JPG、PNG、BMP、GIF、TIFF、WEBP)
- ✅ 三引擎支持:
- RapidOCR(本地引擎,默认):无需API密钥,免费使用,识别速度快
- RapidDoc(增强引擎):支持版面分析、表格识别、公式识别和阅读顺序恢复
- 硅基流动API(云端引擎):使用大模型进行OCR识别
- ✅ 支持中文和英文文字识别
- ✅ 保持文字的顺序和结构
- ✅ 自动将PDF页面转换为图片进行识别
- ✅ 智能引擎切换:当RapidOCR初始化失败时自动切换到硅基流动API
安装
依赖要求
pip install pymupdf pillow requests python-dotenv可选依赖(推荐安装)
安装RapidOCR以获得更好的本地识别效果:
pip install rapidocr_onnxruntime配置
环境变量配置
1. 复制 .env.example 文件并重命名为 .env 2. 根据需要配置以下选项:
# OCR引擎选择
# - "rapid": 使用RapidOCR本地引擎(默认,无需API密钥)
# - "rapidoc": 使用RapidDoc增强引擎(无需API密钥)
# - "siliconflow": 使用硅基流动API引擎(需要API密钥)
OCR_ENGINE=rapid
# 如果使用硅基流动API引擎,需要配置以下选项:
SILICON_FLOW_API_KEY=your_api_key_here
SILICON_FLOW_OCR_MODEL=deepseek-ai/DeepSeek-OCR快速开始
使用默认引擎(RapidOCR本地识别)
from scripts.pdf_ocr_processor import PDFOCRProcessor
# 创建处理器实例(默认使用RapidOCR)
processor = PDFOCRProcessor()
# 执行PDF OCR识别
result = processor.ocr_pdf('path/to/your/scanned.pdf')
# 获取识别结果
print(f"识别完成,共 {result['page_count']} 页")
print(f"使用引擎: {result['engine']}")
print(result['text'])使用硅基流动API引擎
from scripts.pdf_ocr_processor import PDFOCRProcessor
# 创建处理器实例,指定使用硅基流动API
processor = PDFOCRProcessor(engine="siliconflow")
# 执行PDF OCR识别
result = processor.ocr_pdf('path/to/your/scanned.pdf')
# 获取识别结果
print(f"识别完成,共 {result['page_count']} 页")
print(result['text'])使用RapidDoc增强引擎
from scripts.pdf_ocr_processor import PDFOCRProcessor
# 创建处理器实例,指定使用RapidDoc增强引擎
processor = PDFOCRProcessor(engine="rapidoc")
# 执行PDF OCR识别
result = processor.ocr_pdf('path/to/your/scanned.pdf')
# 获取识别结果
print(f"识别完成,共 {result['page_count']} 页")
print(f"使用引擎: {result['engine']}")
print(f"提取的图片数量: {result['images_count']}")
print("\n识别结果:")
print(result['text'])
if 'markdown' in result:
print("\nMarkdown结果:")
print(result['markdown'])识别图片文件
from scripts.pdf_ocr_processor import PDFOCRProcessor
# 创建处理器实例
processor = PDFOCRProcessor() # 或 PDFOCRProcessor(engine="siliconflow")
# 执行图片OCR识别
result = processor.ocr_image_file('path/to/your/image.jpg')
# 获取识别结果
print(f"识别结果: {result['text']}")命令行使用
# 使用默认RapidOCR引擎
python pdf_ocr_processor.py your_document.pdf
# 使用硅基流动API引擎
python pdf_ocr_processor.py your_document.pdf siliconflow
# 使用RapidDoc增强引擎
python pdf_ocr_processor.py your_document.pdf rapidoc详细使用示例
示例1:批量处理多个PDF文件
import os
from scripts.pdf_ocr_processor import PDFOCRProcessor
# 创建处理器实例
processor = PDFOCRProcessor()
# 批量处理目录中的所有PDF文件
pdf_dir = "path/to/pdf/files"
output_dir = "path/to/output"
os.makedirs(output_dir, exist_ok=True)
for pdf_file in os.listdir(pdf_dir):
if pdf_file.endswith('.pdf'):
pdf_path = os.path.join(pdf_dir, pdf_file)
output_path = os.path.join(output_dir, f"{os.path.splitext(pdf_file)[0]}.txt")
print(f"处理文件: {pdf_file}")
try:
result = processor.ocr_pdf(pdf_path)
# 保存识别结果到文本文件
with open(output_path, 'w', encoding='utf-8') as f:
f.write(f"=== PDF OCR 识别结果 ===\n")
f.write(f"文件名: {pdf_file}\n")
f.write(f"页数: {result['page_count']}\n")
f.write(f"使用引擎: {result['engine']}\n\n")
f.write(result['text'])
print(f"处理完成,结果已保存到: {output_path}")
except Exception as e:
print(f"处理失败: {e}")示例2:混合使用两种引擎
from scripts.pdf_ocr_processor import PDFOCRProcessor
def process_with_best_engine(pdf_path):
"""尝试使用RapidOCR,如果效果不佳则使用硅基流动API"""
# 首先使用RapidOCR本地引擎
rapid_processor = PDFOCRProcessor(engine="rapid")
rapid_result = rapid_processor.ocr_pdf(pdf_path)
# 简单评估识别效果(例如:检查识别出的文本长度)
text_length = len(rapid_result['text'])
if text_length < 100: # 如果识别出的文本太短,可能效果不佳
print("RapidOCR识别效果可能不佳,尝试使用硅基流动API...")
silicon_processor = PDFOCRProcessor(engine="siliconflow")
silicon_result = silicon_processor.ocr_pdf(pdf_path)
return silicon_result
else:
return rapid_result
# 使用示例
result = process_with_best_engine('path/to/your/document.pdf')
print(f"识别完成,使用引擎: {result['engine']}")
print(f"识别结果长度: {len(result['text'])} 字符")
print(result['text'])示例3:保存中间图片
from scripts.pdf_ocr_processor import PDFOCRProcessor
# 创建处理器实例
processor = PDFOCRProcessor()
# 执行PDF OCR识别并保存中间图片
result = processor.ocr_pdf('path/to/your/scanned.pdf', save_images=True)
print(f"识别完成,共 {result['page_count']} 页")
print(f"使用引擎: {result['engine']}")
if 'images_dir' in result and result['images_dir']:
print(f"中间图片已保存到: {result['images_dir']}")
print(result['text'])示例4:处理图片文件夹
import os
from scripts.pdf_ocr_processor import PDFOCRProcessor
# 创建处理器实例
processor = PDFOCRProcessor()
# 处理图片文件夹中的所有图片
image_dir = "path/to/images"
output_dir = "path/to/image_output"
os.makedirs(output_dir, exist_ok=True)
supported_formats = ['.jpg', '.jpeg', '.png', '.bmp', '.gif', '.tiff', '.webp']
for image_file in os.listdir(image_dir):
ext = os.path.splitext(image_file)[1].lower()
if ext in supported_formats:
image_path = os.path.join(image_dir, image_file)
output_path = os.path.join(output_dir, f"{os.path.splitext(image_file)[0]}.txt")
print(f"处理图片: {image_file}")
try:
result = processor.ocr_image_file(image_path)
# 保存识别结果到文本文件
with open(output_path, 'w', encoding='utf-8') as f:
f.write(f"=== 图片OCR 识别结果 ===\n")
f.write(f"文件名: {image_file}\n")
f.write(f"使用引擎: {result['engine']}\n\n")
f.write(result['text'])
print(f"处理完成,结果已保存到: {output_path}")
except Exception as e:
print(f"处理失败: {e}")引擎对比
| 特性 | RapidOCR(本地) | 硅基流动API(云端) |
|---|---|---|
| 需要API密钥 | ❌ 不需要 | ✅ 需要 |
| 费用 | 免费 | 按调用计费 |
| 识别速度 | 快(本地运行) | 较慢(网络请求) |
| 准确性 | 高 | 高 |
| 网络依赖 | 不需要 | 需要 |
| 输出格式 | 纯文本 | 可能包含HTML标签 |
支持的文件格式
- PDF文件: .pdf
- 图片文件: .jpg, .jpeg, .png, .bmp, .gif, .tiff, .webp
输出格式
{
"text": "识别的完整文本内容",
"page_count": 页数, # 图片文件始终为1
"engine": "rapid" | "siliconflow" # 使用的OCR引擎
}使用场景
- 处理扫描版合同、协议等文档
- 提取影印版书籍、报告中的文字
- 处理无法直接复制文字的PDF文件
- 批量处理扫描版PDF文档
- 识别截图、扫描件等图片中的文字
- 处理手写体或印刷体图片文字识别
注意事项
1. RapidOCR引擎:
- 完全免费,无需网络连接
- 首次使用会自动下载模型文件
- 识别速度取决于CPU性能
2. 硅基流动API引擎:
- 需要有效的API密钥
- 可能会产生费用
- 识别速度取决于文件页数、图片大小和网络状况
3. 对于复杂的扫描版PDF或图片,识别准确率可能会有所不同 4. 建议使用高清晰度的扫描版PDF或图片以获得更好的识别效果
触发使用不同引擎的提示词
在与 AI IDE 中的助手交互时,您可以使用以下提示词来指定使用不同的 OCR 引擎:
📍 触发 RapidOCR(本地引擎)的提示词
- "使用本地 OCR 引擎处理这个 PDF"
- "用 RapidOCR 识别这个文件"
- "本地处理,不需要 API"
- "快速识别这个文档"
- "离线处理这个 PDF"
- "不使用硅基流动 API,用本地引擎"
📍 触发硅基流动 API(云端引擎)的提示词
- "使用硅基流动 API 处理这个 PDF"
- "用大模型 OCR 识别这个文件"
- "高精度识别这个文档"
- "处理复杂的扫描件"
- "用云端 OCR 引擎"
- "使用 AI 大模型识别"
📍 示例对话
示例 1:使用本地引擎
用户:帮我处理这个扫描版 PDF,用本地 OCR 引擎快速识别
助手:好的,我将使用 RapidOCR 本地引擎为您处理。请提供 PDF 文件路径。示例 2:使用云端引擎
用户:这个 PDF 包含手写体,需要高精度识别,用硅基流动 API
助手:理解,我将使用硅基流动 API 大模型为您处理。请提供 PDF 文件路径和您的 API 密钥(如果尚未配置)。示例 3:自动选择
用户:帮我识别这个 PDF,选择最合适的引擎
助手:我将默认使用 RapidOCR 本地引擎为您处理。如果识别效果不理想,我们可以尝试使用硅基流动 API。🔧 技术实现
当 AI 助手接收到这些提示词时,会:
1. 解析用户意图,确定要使用的引擎 2. 调用 PDFOCRProcessor(engine="rapid") 或 PDFOCRProcessor(engine="siliconflow") 3. 执行 OCR 识别并返回结果
🎯 最佳实践
- 明确指定引擎:如果您对引擎有特定要求,最好在提示词中明确说明
- 提供上下文:说明文档类型(如手写体、复杂格式等)有助于助手选择合适的引擎
- 测试不同引擎:对于重要文档,可以尝试两种引擎并比较结果
通过使用这些提示词,您可以在与 AI IDE 交互时灵活控制 OCR 引擎的选择,获得最佳的识别效果
故障排除
常见问题及解决方案
1. RapidOCR初始化失败
- 问题:
ModuleNotFoundError: No module named 'rapidocr_onnxruntime' - 解决方案:安装RapidOCR依赖:
pip install rapidocr_onnxruntime
2. 硅基流动API 401错误
- 问题:
Unauthorized: 401 Client Error - 解决方案:检查API密钥是否正确配置在
.env文件中
3. PDF转图片失败
- 问题:
ImportError: No module named 'fitz' - 解决方案:安装PyMuPDF依赖:
pip install pymupdf
4. 识别结果为空
- 问题:识别结果文本长度为0
- 解决方案:
- 检查PDF是否为扫描版(非文本PDF)
- 尝试使用硅基流动API引擎
- 确保PDF或图片清晰可读
English Version
PDF OCR Skill
A PDF text extraction skill that supports multiple OCR engines, capable of extracting text content from scanned PDF files and image files.
Features
- ✅ Support text extraction from scanned PDF files
- ✅ Support text recognition from multiple image formats (JPG, PNG, BMP, GIF, TIFF, WEBP)
- ✅ Triple-engine support:
- RapidOCR (local engine, default): No API key required, free to use, fast recognition speed
- RapidDoc (enhanced engine): Supports layout analysis, table recognition, formula recognition, and reading order recovery
- SiliconFlow API (cloud engine): Uses large model for OCR recognition
- ✅ Support Chinese and English text recognition
- ✅ Maintain text order and structure
- ✅ Automatically convert PDF pages to images for recognition
- ✅ Intelligent engine switching: automatically switch to SiliconFlow API when RapidOCR initialization fails
Installation
Dependencies
pip install pymupdf pillow requests python-dotenvOptional Dependencies (Recommended)
Install RapidOCR for better local recognition performance:
pip install rapidocr_onnxruntimeConfiguration
Environment Variable Configuration
1. Copy .env.example file and rename it to .env 2. Configure the following options as needed:
# OCR engine selection
# - "rapid": Use RapidOCR local engine (default, no API key required)
# - "rapidoc": Use RapidDoc enhanced engine (no API key required)
# - "siliconflow": Use SiliconFlow API engine (API key required)
OCR_ENGINE=rapid
# If using SiliconFlow API engine, configure the following options:
SILICON_FLOW_API_KEY=your_api_key_here
SILICON_FLOW_OCR_MODEL=deepseek-ai/DeepSeek-OCRQuick Start
Using Default Engine (RapidOCR Local Recognition)
from scripts.pdf_ocr_processor import PDFOCRProcessor
# Create processor instance (default uses RapidOCR)
processor = PDFOCRProcessor()
# Perform PDF OCR recognition
result = processor.ocr_pdf('path/to/your/scanned.pdf')
# Get recognition result
print(f"Recognition completed, total {result['page_count']} pages")
print(f"Engine used: {result['engine']}")
print(result['text'])Using SiliconFlow API Engine
from scripts.pdf_ocr_processor import PDFOCRProcessor
# Create processor instance, specify to use SiliconFlow API
processor = PDFOCRProcessor(engine="siliconflow")
# Perform PDF OCR recognition
result = processor.ocr_pdf('path/to/your/scanned.pdf')
# Get recognition result
print(f"Recognition completed, total {result['page_count']} pages")
print(result['text'])Recognizing Image Files
from scripts.pdf_ocr_processor import PDFOCRProcessor
# Create processor instance
processor = PDFOCRProcessor() # or PDFOCRProcessor(engine="siliconflow")
# Perform image OCR recognition
result = processor.ocr_image_file('path/to/your/image.jpg')
# Get recognition result
print(f"Recognition result: {result['text']}")Command Line Usage
# Use default RapidOCR engine
python pdf_ocr_processor.py your_document.pdf
# Use SiliconFlow API engine
python pdf_ocr_processor.py your_document.pdf siliconflow
# Use RapidDoc enhanced engine
python pdf_ocr_processor.py your_document.pdf rapidocDetailed Usage Examples
Example 1: Batch Processing Multiple PDF Files
import os
from scripts.pdf_ocr_processor import PDFOCRProcessor
# Create processor instance
processor = PDFOCRProcessor()
# Batch process all PDF files in directory
pdf_dir = "path/to/pdf/files"
output_dir = "path/to/output"
os.makedirs(output_dir, exist_ok=True)
for pdf_file in os.listdir(pdf_dir):
if pdf_file.endswith('.pdf'):
pdf_path = os.path.join(pdf_dir, pdf_file)
output_path = os.path.join(output_dir, f"{os.path.splitext(pdf_file)[0]}.txt")
print(f"Processing file: {pdf_file}")
try:
result = processor.ocr_pdf(pdf_path)
# Save recognition result to text file
with open(output_path, 'w', encoding='utf-8') as f:
f.write(f"=== PDF OCR Recognition Result ===\n")
f.write(f"File name: {pdf_file}\n")
f.write(f"Pages: {result['page_count']}\n")
f.write(f"Engine used: {result['engine']}\n\n")
f.write(result['text'])
print(f"Processing completed, result saved to: {output_path}")
except Exception as e:
print(f"Processing failed: {e}")Example 2: Using Both Engines
from scripts.pdf_ocr_processor import PDFOCRProcessor
def process_with_best_engine(pdf_path):
"""Try using RapidOCR, if not good enough then use SiliconFlow API"""
# First use RapidOCR local engine
rapid_processor = PDFOCRProcessor(engine="rapid")
rapid_result = rapid_processor.ocr_pdf(pdf_path)
# Simple evaluation of recognition effect (e.g., check recognized text length)
text_length = len(rapid_result['text'])
if text_length < 100: # If recognized text is too short, may not be good enough
print("RapidOCR recognition effect may not be good enough, trying SiliconFlow API...")
silicon_processor = PDFOCRProcessor(engine="siliconflow")
silicon_result = silicon_processor.ocr_pdf(pdf_path)
return silicon_result
else:
return rapid_result
# Usage example
result = process_with_best_engine('path/to/your/document.pdf')
print(f"Recognition completed, engine used: {result['engine']}")
print(f"Recognition result length: {len(result['text'])} characters")
print(result['text'])Example 3: Save Intermediate Images
from scripts.pdf_ocr_processor import PDFOCRProcessor
# Create processor instance
processor = PDFOCRProcessor()
# Perform PDF OCR recognition and save intermediate images
result = processor.ocr_pdf('path/to/your/scanned.pdf', save_images=True)
print(f"Recognition completed, total {result['page_count']} pages")
print(f"Engine used: {result['engine']}")
if 'images_dir' in result and result['images_dir']:
print(f"Intermediate images saved to: {result['images_dir']}")
print(result['text'])Example 4: Processing Image Folder
import os
from scripts.pdf_ocr_processor import PDFOCRProcessor
# Create processor instance
processor = PDFOCRProcessor()
# Process all images in folder
image_dir = "path/to/images"
output_dir = "path/to/image_output"
os.makedirs(output_dir, exist_ok=True)
supported_formats = ['.jpg', '.jpeg', '.png', '.bmp', '.gif', '.tiff', '.webp']
for image_file in os.listdir(image_dir):
ext = os.path.splitext(image_file)[1].lower()
if ext in supported_formats:
image_path = os.path.join(image_dir, image_file)
output_path = os.path.join(output_dir, f"{os.path.splitext(image_file)[0]}.txt")
print(f"Processing image: {image_file}")
try:
result = processor.ocr_image_file(image_path)
# Save recognition result to text file
with open(output_path, 'w', encoding='utf-8') as f:
f.write(f"=== Image OCR Recognition Result ===\n")
f.write(f"File name: {image_file}\n")
f.write(f"Engine used: {result['engine']}\n\n")
f.write(result['text'])
print(f"Processing completed, result saved to: {output_path}")
except Exception as e:
print(f"Processing failed: {e}")Engine Comparison
| Feature | RapidOCR (Local) | RapidDoc (Enhanced) | SiliconFlow API (Cloud) |
|---|---|---|---|
| API Key Required | ❌ No | ❌ No | ✅ Yes |
| Cost | Free | Free | Pay per call |
| Recognition Speed | Fast (local execution) | Slower (additional analysis) | Slower (network request) |
| Accuracy | High | High | High |
| Network Dependency | No | No | Yes |
| Output Format | Plain text | Plain text + Markdown | May include HTML tags |
| Layout Analysis | ❌ No | ✅ Yes | ❌ No |
| Table Recognition | ❌ No | ✅ Yes | ❌ No |
| Formula Recognition | ❌ No | ✅ Yes | ❌ No |
Supported File Formats
- PDF files: .pdf
- Image files: .jpg, .jpeg, .png, .bmp, .gif, .tiff, .webp
Output Format
{
"text": "Recognized full text content",
"page_count": number_of_pages, # Always 1 for image files
"engine": "rapid" | "rapidoc" | "siliconflow" # OCR engine used
}Use Cases
- Processing scanned contracts, agreements and other documents
- Extracting text from photocopied books and reports
- Processing PDF files with non-copyable text
- Batch processing scanned PDF documents
- Recognizing text in screenshots and scanned images
- Processing handwritten or printed text in images
Notes
1. RapidOCR Engine:
- Completely free, no network connection required
- Model files will be automatically downloaded on first use
- Recognition speed depends on CPU performance
2. SiliconFlow API Engine:
- Requires a valid API key
- May incur costs
- Recognition speed depends on number of pages, image size, and network conditions
3. RapidDoc Engine:
- Completely free, no network connection required
- Supports layout analysis, table recognition, formula recognition, and reading order recovery
- Provides more structured output including markdown format
- Processing time may be longer than RapidOCR due to additional analysis
4. Recognition accuracy may vary for complex scanned PDFs or images 5. It is recommended to use high-resolution scanned PDFs or images for better recognition results
Prompt Words for Different Engines
When interacting with assistants in AI IDEs, you can use the following prompt words to specify different OCR engines:
📍 Prompt Words for RapidOCR (Local Engine)
- "Use local OCR engine to process this PDF"
- "Recognize this file with RapidOCR"
- "Local processing, no API needed"
- "Quickly recognize this document"
- "Process this PDF offline"
- "Don't use SiliconFlow API, use local engine"
📍 Prompt Words for SiliconFlow API (Cloud Engine)
- "Use SiliconFlow API to process this PDF"
- "Recognize this file with large model OCR"
- "High-precision recognition for this document"
- "Process complex scanned documents"
- "Use cloud OCR engine"
- "Use AI large model for recognition"
📍 Prompt Words for RapidDoc (Enhanced Engine)
- "Use RapidDoc to process this PDF"
- "Recognize this file with enhanced OCR"
- "Process PDF with layout analysis"
- "Extract text with table recognition"
- "Use RapidDoc for better formatting"
- "Enhanced OCR with layout analysis"
📍 Example Conversations
Example 1: Using Local Engine
User: Help me process this scanned PDF, use local OCR engine for quick recognition
Assistant: Sure, I'll use the RapidOCR local engine for you. Please provide the PDF file path.Example 2: Using Cloud Engine
User: This PDF contains handwritten text, need high-precision recognition, use SiliconFlow API
Assistant: Understood, I'll use the SiliconFlow API large model for you. Please provide the PDF file path and your API key (if not already configured).Example 3: Automatic Selection
User: Help me recognize this PDF, choose the most suitable engine
Assistant: I'll default to using the RapidOCR local engine for you. If the recognition effect is not ideal, we can try using SiliconFlow API.🔧 Technical Implementation
When the AI assistant receives these prompt words, it will:
1. Parse the user's intent to determine the engine to use 2. Call PDFOCRProcessor(engine="rapid"), PDFOCRProcessor(engine="rapidoc"), or PDFOCRProcessor(engine="siliconflow") 3. Execute OCR recognition and return the result
🎯 Best Practices
- Clearly specify the engine: If you have specific requirements for the engine, it's best to clearly state it in the prompt
- Provide context: Explaining the document type (e.g., handwritten, complex format) helps the assistant choose the appropriate engine
- Test different engines: For important documents, you can try both engines and compare the results
By using these prompt words, you can flexibly control the OCR engine selection when interacting with AI IDEs to get the best recognition results
Troubleshooting
Common Issues and Solutions
1. RapidOCR Initialization Failure
- Issue:
ModuleNotFoundError: No module named 'rapidocr_onnxruntime' - Solution: Install RapidOCR dependency:
pip install rapidocr_onnxruntime
2. SiliconFlow API 401 Error
- Issue:
Unauthorized: 401 Client Error - Solution: Check if the API key is correctly configured in the
.envfile
3. PDF to Image Conversion Failure
- Issue:
ImportError: No module named 'fitz' - Solution: Install PyMuPDF dependency:
pip install pymupdf
4. Empty Recognition Result
- Issue: Recognition result text length is 0
- Solution:
- Check if the PDF is a scanned version (non-text PDF)
- Try using SiliconFlow API engine
- Ensure the PDF or image is clear and readable
License
MIT License - See LICENSE.txt
# PDF OCR Skill Requirements
# PDF处理
pymupdf>=1.23.0
# 图片处理
pillow>=9.0.0
# HTTP请求
requests>=2.28.0
# 环境变量管理
python-dotenv>=1.0.0
# 本地OCR引擎(可选,推荐安装以获得更好的识别效果)
rapidocr_onnxruntime>=1.3.0
"""
PDF OCR Skill Scripts Package
"""
from .pdf_ocr_processor import PDFOCRProcessor
__all__ = ['PDFOCRProcessor']
__version__ = '2.5.0'#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
PDF OCR处理脚本
支持两种OCR引擎:
1. 硅基流动大模型API(云端)
2. RapidOCR(本地,无需API)
支持自动安装缺失的依赖
"""
import os
import sys
import base64
import requests
import subprocess
from typing import Dict, Any, List, Optional
from dotenv import load_dotenv
# 加载环境变量
load_dotenv()
def install_dependency(package):
"""自动安装缺失的依赖"""
print(f"正在安装依赖: {package}")
try:
subprocess.check_call([sys.executable, "-m", "pip", "install", package])
print(f"依赖 {package} 安装成功")
return True
except subprocess.CalledProcessError as e:
print(f"依赖 {package} 安装失败: {e}")
return False
class RapidOCREngine:
"""RapidOCR本地OCR引擎"""
def __init__(self):
self.ocr = None
self._init_engine()
def _init_engine(self):
"""初始化RapidOCR引擎"""
try:
from rapidocr_onnxruntime import RapidOCR
self.ocr = RapidOCR()
except ImportError:
print("RapidOCR依赖未安装,正在尝试自动安装...")
if install_dependency("rapidocr_onnxruntime"):
try:
from rapidocr_onnxruntime import RapidOCR
self.ocr = RapidOCR()
except ImportError:
raise Exception("RapidOCR依赖安装失败,请手动安装: pip install rapidocr_onnxruntime")
else:
raise Exception("RapidOCR依赖安装失败,请手动安装: pip install rapidocr_onnxruntime")
def recognize(self, image_path: str) -> str:
"""识别单张图片"""
if self.ocr is None:
raise Exception("RapidOCR引擎未初始化")
result, _ = self.ocr(image_path)
if not result:
return ""
# 提取文本
texts = []
for line in result:
if len(line) >= 2:
texts.append(line[1])
return "\n".join(texts)
class PaddleOCREngine:
"""PaddleOCR本地OCR引擎"""
def __init__(self):
self.ocr = None
self._init_engine()
def _init_engine(self):
"""初始化PaddleOCR引擎"""
try:
from paddleocr import PaddleOCR
# 使用PP-OCRv5模型
print("正在初始化PaddleOCR引擎...")
self.ocr = PaddleOCR(use_textline_orientation=True, lang='ch')
print("PaddleOCR引擎初始化成功")
except ImportError as e:
print(f"PaddleOCR导入失败: {e}")
print("PaddleOCR依赖未安装,正在尝试自动安装...")
if install_dependency("paddleocr"):
try:
from paddleocr import PaddleOCR
# 使用PP-OCRv5模型
print("正在初始化PaddleOCR引擎...")
self.ocr = PaddleOCR(use_textline_orientation=True, lang='ch')
print("PaddleOCR引擎初始化成功")
except ImportError as e:
print(f"PaddleOCR导入失败: {e}")
raise Exception("PaddleOCR依赖安装失败,请手动安装: pip install paddleocr")
else:
raise Exception("PaddleOCR依赖安装失败,请手动安装: pip install paddleocr")
except Exception as e:
print(f"PaddleOCR初始化失败: {e}")
raise
def recognize(self, image_path: str) -> str:
"""识别单张图片"""
if self.ocr is None:
raise Exception("PaddleOCR引擎未初始化")
result = self.ocr.predict(image_path)
if not result:
return ""
# 提取文本
texts = []
for page in result:
for line in page:
if len(line) >= 2:
texts.append(line[1][0])
return "\n".join(texts)
class SiliconFlowOCREngine:
"""硅基流动API OCR引擎"""
def __init__(self, api_key: str = "", model: str = "deepseek-ai/DeepSeek-OCR"):
self.api_key = api_key or os.getenv("SILICON_FLOW_API_KEY", "")
self.model = model or os.getenv("SILICON_FLOW_OCR_MODEL", "deepseek-ai/DeepSeek-OCR")
self.base_url = "https://api.siliconflow.cn/v1/chat/completions"
self.headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {self.api_key}"
}
def recognize(self, image_base64: str, page_num: int = 1) -> str:
"""使用硅基流动大模型识别单张图片"""
prompt = f"""请仔细识别这张图片中的所有文字内容。
这是第 {page_num} 页的内容。
要求:
1. 完整提取所有可见文字
2. 保持文字的顺序和结构
3. 识别中文和英文
4. 输出纯文本格式,不要添加任何额外说明
请直接输出识别的文字内容:"""
payload = {
"model": self.model,
"messages": [
{
"role": "user",
"content": [
{
"type": "text",
"text": prompt
},
{
"type": "image_url",
"image_url": {
"url": f"data:image/png;base64,{image_base64}"
}
}
]
}
],
"temperature": 0.1,
"max_tokens": 4000
}
try:
response = requests.post(
self.base_url,
headers=self.headers,
json=payload,
timeout=120
)
response.raise_for_status()
return response.json()["choices"][0]["message"]["content"].strip()
except Exception as e:
return f"【OCR识别失败: {str(e)}】"
class RapidDocEngine:
"""RapidDoc增强OCR引擎"""
def __init__(self):
self.doc = None
self._init_engine()
def _init_engine(self):
"""初始化RapidDoc引擎"""
try:
from rapid_doc import RapidDoc
self.doc = RapidDoc()
except ImportError:
print("RapidDoc依赖未安装,正在尝试自动安装...")
if install_dependency("rapid-doc"):
try:
from rapid_doc import RapidDoc
self.doc = RapidDoc()
except ImportError:
raise Exception("RapidDoc依赖安装失败,请手动安装: pip install rapid-doc")
else:
raise Exception("RapidDoc依赖安装失败,请手动安装: pip install rapid-doc")
def recognize(self, file_path: str) -> Dict[str, Any]:
"""识别PDF或图片文件
Args:
file_path: PDF或图片文件路径
Returns:
包含text和markdown的字典
"""
if self.doc is None:
raise Exception("RapidDoc引擎未初始化")
# 处理文件
result = self.doc(file_path)
# 提取文本内容(去除Markdown格式)
import re
text_content = re.sub(r'!\[.*?\]\(.*?\)', '', result.markdown) # 移除图片
text_content = re.sub(r'\|.*?\|', '', text_content) # 移除表格
text_content = re.sub(r'#+', '', text_content) # 移除标题
text_content = '\n'.join([line.strip() for line in text_content.split('\n') if line.strip()]) # 清理空行
return {
"text": text_content,
"markdown": result.markdown,
"images_count": len(result.images)
}
class PDFOCRProcessor:
"""PDF OCR处理器 - 支持多种OCR引擎"""
def __init__(self, engine: Optional[str] = None):
"""
初始化PDF OCR处理器
Args:
engine: OCR引擎类型,可选值:
- "rapid": 使用RapidOCR本地引擎(默认,无需API)
- "rapidoc": 使用RapidDoc增强引擎
- "paddle": 使用PaddleOCR本地引擎
- "siliconflow": 使用硅基流动API引擎
- None: 从环境变量 OCR_ENGINE 读取,默认为 "rapid"
"""
self.engine_type = engine or os.getenv("OCR_ENGINE", "rapid")
self.rapid_engine: Optional[RapidOCREngine] = None
self.rapidoc_engine: Optional[RapidDocEngine] = None
self.paddle_engine: Optional[PaddleOCREngine] = None
self.siliconflow_engine: Optional[SiliconFlowOCREngine] = None
# 初始化选定的引擎
self._init_engine()
def _init_engine(self):
"""初始化OCR引擎"""
if self.engine_type == "rapid":
try:
self.rapid_engine = RapidOCREngine()
except Exception as e:
print(f"RapidOCR初始化失败: {e}")
print("将尝试使用硅基流动API引擎...")
self.engine_type = "siliconflow"
self.siliconflow_engine = SiliconFlowOCREngine()
elif self.engine_type == "rapidoc":
try:
self.rapidoc_engine = RapidDocEngine()
except Exception as e:
print(f"RapidDoc初始化失败: {e}")
print("将尝试使用RapidOCR引擎...")
self.engine_type = "rapid"
self.rapid_engine = RapidOCREngine()
elif self.engine_type == "paddle":
try:
self.paddle_engine = PaddleOCREngine()
except Exception as e:
print(f"PaddleOCR初始化失败: {e}")
print("将尝试使用RapidOCR引擎...")
self.engine_type = "rapid"
self.rapid_engine = RapidOCREngine()
elif self.engine_type == "siliconflow":
self.siliconflow_engine = SiliconFlowOCREngine()
else:
raise ValueError(f"不支持的OCR引擎类型: {self.engine_type}")
def pdf_to_images(self, pdf_path: str, output_dir: Optional[str] = None) -> List[str]:
"""
将PDF转换为图片列表
Args:
pdf_path: PDF文件路径
output_dir: 图片输出目录,如果为None则返回base64编码列表
Returns:
如果output_dir为None,返回base64编码列表;否则返回图片文件路径列表
"""
try:
import fitz # PyMuPDF
from PIL import Image
import io
doc = fitz.open(pdf_path)
images = []
for page_num in range(len(doc)):
page = doc[page_num]
# 将PDF页面转换为图片
zoom = 2 # 放大倍数
mat = fitz.Matrix(zoom, zoom)
pix = page.get_pixmap(matrix=mat)
# 转换为PIL Image
img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
if output_dir:
# 保存到文件
os.makedirs(output_dir, exist_ok=True)
img_path = os.path.join(output_dir, f"page_{page_num + 1}.png")
img.save(img_path, "PNG")
images.append(img_path)
else:
# 转换为base64
buffered = io.BytesIO()
img.save(buffered, format="PNG")
img_base64 = base64.b64encode(buffered.getvalue()).decode()
images.append(img_base64)
doc.close()
return images
except ImportError:
print("PDF处理依赖未安装,正在尝试自动安装...")
if install_dependency("pymupdf") and install_dependency("pillow"):
try:
import fitz # PyMuPDF
from PIL import Image
import io
doc = fitz.open(pdf_path)
images = []
for page_num in range(len(doc)):
page = doc[page_num]
# 将PDF页面转换为图片
zoom = 2 # 放大倍数
mat = fitz.Matrix(zoom, zoom)
pix = page.get_pixmap(matrix=mat)
# 转换为PIL Image
img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
if output_dir:
# 保存到文件
os.makedirs(output_dir, exist_ok=True)
img_path = os.path.join(output_dir, f"page_{page_num + 1}.png")
img.save(img_path, "PNG")
images.append(img_path)
else:
# 转换为base64
buffered = io.BytesIO()
img.save(buffered, format="PNG")
img_base64 = base64.b64encode(buffered.getvalue()).decode()
images.append(img_base64)
doc.close()
return images
except ImportError:
raise Exception("PDF处理依赖安装失败,请手动安装: pip install pymupdf pillow")
else:
raise Exception("PDF处理依赖安装失败,请手动安装: pip install pymupdf pillow")
except Exception as e:
raise Exception(f"PDF转图片失败: {str(e)}")
def ocr_pdf(self, pdf_path: str, save_images: bool = False) -> Dict[str, Any]:
"""
OCR识别整个PDF
Args:
pdf_path: PDF文件路径
save_images: 是否保存中间图片文件(RapidOCR和PaddleOCR模式下)
Returns:
包含text和page_count的字典
"""
result = {
"text": "",
"page_count": 0,
"engine": self.engine_type
}
try:
if self.engine_type == "rapid":
# 使用RapidOCR本地识别
result = self._ocr_with_rapid(pdf_path, save_images)
elif self.engine_type == "rapidoc":
# 使用RapidDoc增强识别
result = self._ocr_with_rapidoc(pdf_path)
elif self.engine_type == "paddle":
# 使用PaddleOCR本地识别
result = self._ocr_with_paddle(pdf_path, save_images)
else:
# 使用硅基流动API识别
result = self._ocr_with_siliconflow(pdf_path)
except Exception as e:
raise Exception(f"OCR识别失败: {str(e)}")
return result
def _ocr_with_rapid(self, pdf_path: str, save_images: bool = False) -> Dict[str, Any]:
"""使用RapidOCR识别PDF"""
import tempfile
import shutil
# 创建临时目录存放图片
if save_images:
temp_dir = os.path.join(os.path.dirname(pdf_path), "pdf_images")
else:
temp_dir = tempfile.mkdtemp()
try:
# 转换PDF为图片
image_paths = self.pdf_to_images(pdf_path, output_dir=temp_dir)
text_parts = []
for idx, img_path in enumerate(image_paths, 1):
page_text = self.rapid_engine.recognize(img_path)
text_parts.append(f"=== 第 {idx} 页 ===\n{page_text}")
return {
"text": "\n\n".join(text_parts),
"page_count": len(image_paths),
"engine": "rapid",
"images_dir": temp_dir if save_images else None
}
finally:
# 清理临时文件
if not save_images and os.path.exists(temp_dir):
shutil.rmtree(temp_dir)
def _ocr_with_paddle(self, pdf_path: str, save_images: bool = False) -> Dict[str, Any]:
"""使用PaddleOCR识别PDF"""
import tempfile
import shutil
# 创建临时目录存放图片
if save_images:
temp_dir = os.path.join(os.path.dirname(pdf_path), "pdf_images")
else:
temp_dir = tempfile.mkdtemp()
try:
# 转换PDF为图片
image_paths = self.pdf_to_images(pdf_path, output_dir=temp_dir)
text_parts = []
for idx, img_path in enumerate(image_paths, 1):
page_text = self.paddle_engine.recognize(img_path)
text_parts.append(f"=== 第 {idx} 页 ===\n{page_text}")
return {
"text": "\n\n".join(text_parts),
"page_count": len(image_paths),
"engine": "paddle",
"images_dir": temp_dir if save_images else None
}
finally:
# 清理临时文件
if not save_images and os.path.exists(temp_dir):
shutil.rmtree(temp_dir)
def _ocr_with_rapidoc(self, pdf_path: str) -> Dict[str, Any]:
"""使用RapidDoc识别PDF"""
try:
# 直接使用RapidDoc处理PDF
result = self.rapidoc_engine.recognize(pdf_path)
# 计算页数
page_count = 1
try:
import fitz # PyMuPDF
doc = fitz.open(pdf_path)
page_count = len(doc)
doc.close()
except:
pass
return {
"text": result["text"],
"page_count": page_count,
"engine": "rapidoc",
"markdown": result["markdown"],
"images_count": result["images_count"]
}
except Exception as e:
raise Exception(f"RapidDoc识别失败: {str(e)}")
def _ocr_with_siliconflow(self, pdf_path: str) -> Dict[str, Any]:
"""使用硅基流动API识别PDF"""
images = self.pdf_to_images(pdf_path)
text_parts = []
for idx, img_base64 in enumerate(images, 1):
page_text = self.siliconflow_engine.recognize(img_base64, idx)
text_parts.append(f"=== 第 {idx} 页 ===\n{page_text}")
return {
"text": "\n\n".join(text_parts),
"page_count": len(images),
"engine": "siliconflow"
}
def process(self, input_data: Dict[str, Any]) -> Dict[str, Any]:
"""
处理入口点(供skill-loader调用)
Args:
input_data: 包含file_path和可选engine的字典
Returns:
包含success、text、page_count和engine的字典
"""
pdf_path = input_data.get('file_path', '')
engine = input_data.get('engine', None)
if not pdf_path:
return {"success": False, "error": "PDF file path is required"}
return process_pdf_ocr(pdf_path, engine=engine)
def ocr_image_file(self, image_path: str) -> Dict[str, Any]:
"""OCR识别单个图片文件"""
result = {
"text": "",
"page_count": 1,
"engine": self.engine_type
}
try:
if self.engine_type == "rapid":
result["text"] = self.rapid_engine.recognize(image_path)
elif self.engine_type == "rapidoc":
# 使用RapidDoc识别图片
rapidoc_result = self.rapidoc_engine.recognize(image_path)
result["text"] = rapidoc_result["text"]
result["markdown"] = rapidoc_result["markdown"]
result["images_count"] = rapidoc_result["images_count"]
elif self.engine_type == "paddle":
# 使用PaddleOCR识别图片
result["text"] = self.paddle_engine.recognize(image_path)
else:
# 将图片转换为base64
try:
from PIL import Image
import io
except ImportError:
print("图片处理依赖未安装,正在尝试自动安装...")
if install_dependency("pillow"):
from PIL import Image
import io
else:
raise Exception("图片处理依赖安装失败,请手动安装: pip install pillow")
img = Image.open(image_path)
if img.mode != 'RGB':
img = img.convert('RGB')
buffered = io.BytesIO()
img.save(buffered, format="PNG")
img_base64 = base64.b64encode(buffered.getvalue()).decode()
result["text"] = self.siliconflow_engine.recognize(img_base64, 1)
except Exception as e:
raise Exception(f"图片OCR识别失败: {str(e)}")
return result
def process_pdf_ocr(pdf_path: str, engine: Optional[str] = None) -> Dict[str, Any]:
"""
处理PDF OCR的主函数
Args:
pdf_path: PDF文件路径
engine: OCR引擎类型,可选 "rapid" 或 "siliconflow"
Returns:
包含success、text、page_count和engine的字典
"""
processor = PDFOCRProcessor(engine=engine)
result = processor.ocr_pdf(pdf_path)
result['success'] = True
return result
def main(input_data: Dict[str, Any] = None) -> Dict[str, Any]:
"""SKILL 入口点"""
if input_data is None:
input_data = {}
pdf_path = input_data.get('file_path', '')
engine = input_data.get('engine', None)
if not pdf_path:
return {"success": False, "error": "PDF file path is required"}
return process_pdf_ocr(pdf_path, engine=engine)
if __name__ == "__main__":
# 测试代码
if len(sys.argv) > 1:
pdf_path = sys.argv[1]
engine = sys.argv[2] if len(sys.argv) > 2 else None
else:
print("使用方法: python pdf_ocr_processor.py <pdf_file_path> [engine]")
print("engine可选值: rapid (默认) | rapidoc | paddle | siliconflow")
sys.exit(1)
if not os.path.exists(pdf_path):
print(f"文件不存在: {pdf_path}")
sys.exit(1)
try:
result = process_pdf_ocr(pdf_path, engine=engine)
print(f"OCR识别完成,共 {result['page_count']} 页")
print(f"使用引擎: {result['engine']}")
if 'images_count' in result:
print(f"提取的图片数量: {result['images_count']}")
print("\n识别结果:")
print(result['text'])
if 'markdown' in result and len(result['markdown']) > 500:
print("\nMarkdown结果预览:")
print(result['markdown'][:500] + "...")
except Exception as e:
print(f"处理失败: {e}")
sys.exit(1)
from setuptools import setup, find_packages
# 读取README.md作为长描述
with open("README.md", "r", encoding="utf-8") as f:
long_description = f.read()
setup(
name="pdf-ocr-skill",
version="2.5.0",
author="PDF OCR Skill Team",
author_email="",
description="支持四引擎的PDF OCR识别技能,可从影印版PDF文件和图片文件中提取中英文文字内容 | PDF OCR Skill with quadruple-engine support, capable of extracting Chinese and English text from scanned PDF files and image files",
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/yejinlei/pdf-ocr-skill",
packages=find_packages(),
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
],
python_requires=">=3.6",
install_requires=[
"pymupdf",
"pillow",
"requests",
"python-dotenv"
],
extras_require={
"full": [
"rapidocr_onnxruntime",
"rapid-doc",
"paddleocr"
]
},
entry_points={
"console_scripts": [
"pdf-ocr=scripts.pdf_ocr_processor:main",
],
},
)PDF OCR Skill 发布指南
通过npx skills add安装
发布到GitHub后,用户可以通过以下命令安装:
基本安装
# 从GitHub仓库安装
npx skills add yejinlei/pdf-ocr-skill
# 或者使用完整URL
npx skills add https://github.com/yejinlei/pdf-ocr-skill指定技能安装
# 只安装pdf-ocr技能
npx skills add yejinlei/pdf-ocr-skill --skill pdf-ocr全局安装
# 安装到全局目录
npx skills add yejinlei/pdf-ocr-skill --global非交互式安装(CI/CD友好)
# 跳过确认提示
npx skills add yejinlei/pdf-ocr-skill --yes发布步骤
1. 创建GitHub仓库
1. 在GitHub上创建新仓库:pdf-ocr-skill 2. 将pdf-ocr目录内容推送到仓库
2. 推送代码
# 初始化Git仓库
cd pdf-ocr
git init
# 添加所有文件
git add .
# 提交
git commit -m "Initial release: PDF OCR Skill v1.0.0"
# 创建标签
git tag v1.0.0
# 添加远程仓库
git remote add origin https://github.com/yejinlei/pdf-ocr-skill.git
# 推送到GitHub
git push -u origin main
git push --tags3. 用户安装
用户可以通过以下方式安装:
方式1:直接安装
npx skills add yejinlei/pdf-ocr-skill方式2:搜索安装
# 搜索技能
npx skills find ocr
# 选择pdf-ocr技能进行安装方式3:列出已安装技能
# 列出所有已安装技能
npx skills list
# 列出全局安装的技能
npx skills list --global4. 环境变量配置
1. 复制 .env.example 文件并重命名为 .env 2. 填入您的硅基流动 API 密钥:
SILICON_FLOW_API_KEY=your_api_key_here
SILICON_FLOW_OCR_MODEL=deepseek-ai/DeepSeek-OCR技能使用
安装后,技能会自动集成到支持的agents中。用户可以通过自然语言描述来使用技能:
# 在agent中使用
agent.add_task("识别这张图片中的文字")
# 或者直接调用
from pdf_ocr_processor import PDFOCRProcessor
processor = PDFOCRProcessor()
result = processor.ocr_image_file('image.jpg')更新技能
检查更新
# 检查是否有更新
npx skills check更新技能
# 更新所有已安装技能
npx skills update更新特定技能
# 更新pdf-ocr技能
npx skills add yejinlei/pdf-ocr-skill --skill pdf-ocr移除技能
# 移除pdf-ocr技能
npx skills remove pdf-ocr
# 从全局移除
npx skills remove --global pdf-ocr
# 移除所有技能
npx skills remove --all技能搜索
# 交互式搜索
npx skills find
# 按关键词搜索
npx skills find ocr
npx skills find pdf
npx skills find image支持的Agents
根据skills CLI的文档,支持以下agents:
- Claude Code
- Cursor
- Codex
- 以及其他37+个agents
注意事项
1. YAML Frontmatter: SKILL.md文件必须包含YAML frontmatter,包含name、description等字段 2. 文件结构: 必须包含SKILL.md文件作为技能描述 3. 依赖管理: 技能应该能够独立运行,不依赖特定环境 4. 版本管理: 使用语义化版本号(如1.0.0) 5. 标签系统: 使用相关标签便于搜索和发现
示例SKILL.md Frontmatter
---
name: pdf-ocr
description: 使用硅基流动大模型进行OCR识别,支持从影印版PDF文件和图片文件中提取文字内容
version: 1.0.0
author: PDF OCR Skill Team
license: MIT
tags:
- ocr
- pdf
- image
- text-extraction
- chinese
- english
- siliconflow
- deepseek
---发布检查清单
- ✅ SKILL.md包含YAML frontmatter
- ✅ 仓库已推送到GitHub
- ✅ 创建了版本标签
- ✅ README.md包含安装说明
- ✅ LICENSE.txt文件存在
- ✅ requirements.txt列出所有依赖
- ✅ 技能可以独立运行
下一步
1. 更新GitHub仓库URL 2. 添加测试用例 3. 创建CI/CD配置 4. 添加更多文档和示例 5. 提交到skills.sh官方仓库(如果适用)
PDF OCR Skill 发布检查清单
目录结构检查
pdf-ocr/
├── SKILL.md ✅ 技能说明文档(必需)
├── LICENSE.txt ✅ 许可证文件
├── README.md ✅ 项目说明文档
├── requirements.txt ✅ 依赖文件
├── setup.py ✅ Python包设置文件
├── MANIFEST.in ✅ 包清单文件
├── .gitignore ✅ Git忽略文件
└── scripts/ ✅ 脚本目录
├── __init__.py ✅ Python包初始化文件
└── pdf_ocr_processor.py ✅ OCR处理脚本发布要求检查
必需文件
- ✅ SKILL.md - 技能说明文档
- ✅ LICENSE.txt - 许可证文件
- ✅ README.md - 项目说明文档
- ✅ requirements.txt - 依赖文件
可选但推荐文件
- ✅ setup.py - Python包设置文件
- ✅ MANIFEST.in - 包清单文件
- ✅ .gitignore - Git忽略文件
- ✅ scripts/__init__.py - Python包初始化文件
代码质量检查
- ✅ 无内部依赖(不依赖anthropics_skills)
- ✅ 完整的错误处理
- ✅ 清晰的文档说明
- ✅ 支持多种文件格式
- ✅ 环境变量配置说明
文档质量检查
- ✅ 功能特性描述清晰
- ✅ 使用方法详细完整
- ✅ 输入输出格式说明
- ✅ 依赖要求明确
- ✅ 环境变量配置说明
- ✅ 注意事项和使用场景
发布步骤
1. 测试
# 安装依赖
pip install -r requirements.txt
# 测试PDF识别
python -c "from pdf_ocr_processor import PDFOCRProcessor; print('PDF OCR Skill ready')"
# 测试图片识别
python -c "from pdf_ocr_processor import PDFOCRProcessor; print('Image OCR ready')"2. 打包
# 构建源码包
python setup.py sdist
# 构建wheel包
python setup.py bdist_wheel3. 发布到PyPI
# 安装twine
pip install twine
# 上传到PyPI
twine upload dist/*4. 发布到GitHub
# 初始化Git仓库
git init
# 添加文件
git add .
# 提交
git commit -m "Initial release: PDF OCR Skill v1.0.0"
# 创建标签
git tag v1.0.0
# 推送到GitHub
git remote add origin https://github.com/yourusername/pdf-ocr-skill.git
git push -u origin main
git push --tags使用示例
安装
pip install pdf-ocr-skill使用
from pdf_ocr_processor import PDFOCRProcessor
processor = PDFOCRProcessor()
# 识别PDF
result = processor.ocr_pdf('document.pdf')
# 识别图片
result = processor.ocr_image_file('image.jpg')
print(result['text'])注意事项
1. 确保所有文档都是UTF-8编码 2. 测试所有支持的文件格式 3. 验证环境变量配置说明 4. 检查依赖版本兼容性 5. 确保代码符合PEP8规范
发布状态
✅ 所有必需文件已创建 ✅ 所有文档已完善 ✅ 代码质量符合要求 ✅ 可以发布到网上
下一步
1. 更新GitHub仓库URL 2. 添加测试用例 3. 创建CI/CD配置 4. 添加更多文档和示例
Related skills
How it compares
Pick Pdf-ocr-skill for bilingual scanned-document OCR in agents; use born-digital PDF parsers when text layers already exist without OCR.
FAQ
Which engines work without an API key?
RapidOCR, RapidDoc, and PaddleOCR run locally without cloud keys.
What happens if RapidOCR fails to initialize?
The skill automatically switches to the SiliconFlow cloud API engine.
Which image formats are supported?
JPG, PNG, BMP, GIF, TIFF, and WEBP plus PDF page conversion.
Is Pdf Ocr Skill safe to install?
skills.sh reports 2 of 3 security scanners passed. Review the Security Audits panel on this page before installing in production.