Initial release: PDF OCR Skill v1.0.0

This commit is contained in:
yeeeeeeeeee
2026-02-27 14:14:15 +08:00
commit 6b67b79949
12 changed files with 930 additions and 0 deletions
+3
View File
@@ -0,0 +1,3 @@
# 硅基流动 API 配置
SILICON_FLOW_API_KEY=your_api_key_here
SILICON_FLOW_OCR_MODEL=deepseek-ai/DeepSeek-OCR
+51
View File
@@ -0,0 +1,51 @@
# 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
*.log
+21
View File
@@ -0,0 +1,21 @@
MIT 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.
+7
View File
@@ -0,0 +1,7 @@
include README.md
include LICENSE.txt
include SKILL.md
include requirements.txt
recursive-include scripts *.py
recursive-exclude * __pycache__
recursive-exclude * *.py[co]
+109
View File
@@ -0,0 +1,109 @@
# PDF OCR Skill
一个使用硅基流动大模型进行OCR识别的技能支持从影印版PDF文件和图片文件中提取文字内容。
## 功能特性
- ✅ 支持影印版PDF文件的文字提取
- ✅ 支持多种图片格式的文字识别JPG、PNG、BMP、GIF、TIFF、WEBP
- ✅ 使用硅基流动大模型进行OCR识别
- ✅ 支持中文和英文文字识别
- ✅ 保持文字的顺序和结构
- ✅ 自动将PDF页面转换为图片进行识别
## 安装
### 依赖要求
```bash
pip install pymupdf pillow requests python-dotenv
```
### 环境变量配置
1. 复制 `.env.example` 文件并重命名为 `.env`
2. 填入您的硅基流动 API 密钥:
```env
SILICON_FLOW_API_KEY=your_api_key_here
SILICON_FLOW_OCR_MODEL=deepseek-ai/DeepSeek-OCR
```
## 快速开始
### 识别PDF文件
```python
from pdf_ocr_processor import PDFOCRProcessor
# 创建处理器实例
processor = PDFOCRProcessor()
# 执行PDF OCR识别
result = processor.ocr_pdf('path/to/your/scanned.pdf')
# 获取识别结果
print(f"识别完成,共 {result['page_count']}")
print(result['text'])
```
### 识别图片文件
```python
from pdf_ocr_processor import PDFOCRProcessor
# 创建处理器实例
processor = PDFOCRProcessor()
# 执行图片OCR识别
result = processor.ocr_image_file('path/to/your/image.jpg')
# 获取识别结果
print(f"识别结果: {result['text']}")
```
## 支持的文件格式
- **PDF文件**: .pdf
- **图片文件**: .jpg, .jpeg, .png, .bmp, .gif, .tiff, .webp
## 输出格式
```python
{
"text": "识别的完整文本内容",
"page_count": 页数 # 图片文件始终为1
}
```
## 使用场景
- 处理扫描版合同、协议等文档
- 提取影印版书籍、报告中的文字
- 处理无法直接复制文字的PDF文件
- 批量处理扫描版PDF文档
- 识别截图、扫描件等图片中的文字
- 处理手写体或印刷体图片文字识别
## 注意事项
1. OCR识别需要调用硅基流动API可能会产生费用
2. 识别速度取决于文件页数、图片大小和网络状况
3. 对于复杂的扫描版PDF或图片识别准确率可能会有所不同
4. 建议使用高清晰度的扫描版PDF或图片以获得更好的识别效果
## 许可证
MIT License - 详见 [LICENSE.txt](LICENSE.txt)
## 贡献
欢迎提交问题和拉取请求!
## 更新日志
### v1.0.0 (2025-02-27)
- 初始版本发布
- 支持PDF文件OCR识别
- 支持多种图片格式OCR识别
- 支持中英文文字识别
+116
View File
@@ -0,0 +1,116 @@
---
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
---
# PDF OCR Skill
PDF OCR技能用于从影印版PDF文件和图片文件中提取文字内容。该技能使用硅基流动大模型进行光学字符识别OCR能够识别扫描版PDF和图片中的中文和英文文字。
## 功能特性
- 支持影印版PDF文件的文字提取
- 支持多种图片格式的文字识别JPG、PNG、BMP、GIF、TIFF、WEBP
- 使用硅基流动大模型进行OCR识别
- 支持中文和英文文字识别
- 保持文字的顺序和结构
- 自动将PDF页面转换为图片进行识别
## 安装
### 依赖要求
```bash
pip install pymupdf pillow requests python-dotenv
```
### 环境变量配置
1. 复制 `.env.example` 文件并重命名为 `.env`
2. 填入您的硅基流动 API 密钥:
```env
SILICON_FLOW_API_KEY=your_api_key_here
SILICON_FLOW_OCR_MODEL=deepseek-ai/DeepSeek-OCR
```
## 快速开始
### 识别PDF文件
```python
# 导入OCR处理器
from pdf_ocr_processor import PDFOCRProcessor
# 创建处理器实例
processor = PDFOCRProcessor()
# 执行PDF OCR识别
result = processor.ocr_pdf('path/to/your/scanned.pdf')
# 获取识别结果
print(f"识别完成,共 {result['page_count']}")
print(result['text'])
```
### 识别图片文件
```python
# 导入OCR处理器
from pdf_ocr_processor import PDFOCRProcessor
# 创建处理器实例
processor = PDFOCRProcessor()
# 执行图片OCR识别
result = processor.ocr_image_file('path/to/your/image.jpg')
# 获取识别结果
print(f"识别结果: {result['text']}")
```
## 支持的文件格式
- **PDF文件**: .pdf
- **图片文件**: .jpg, .jpeg, .png, .bmp, .gif, .tiff, .webp
## 输出格式
```python
{
"text": "识别的完整文本内容",
"page_count": 页数 # 图片文件始终为1
}
```
## 使用场景
- 处理扫描版合同、协议等文档
- 提取影印版书籍、报告中的文字
- 处理无法直接复制文字的PDF文件
- 批量处理扫描版PDF文档
- 识别截图、扫描件等图片中的文字
- 处理手写体或印刷体图片文字识别
## 注意事项
1. OCR识别需要调用硅基流动API可能会产生费用
2. 识别速度取决于文件页数、图片大小和网络状况
3. 对于复杂的扫描版PDF或图片识别准确率可能会有所不同
4. 建议使用高清晰度的扫描版PDF或图片以获得更好的识别效果
## 许可证
MIT License - 详见 [LICENSE.txt](LICENSE.txt)
+13
View File
@@ -0,0 +1,13 @@
# PDF OCR Skill Requirements
# PDF处理
pymupdf>=1.23.0
# 图片处理
pillow>=9.0.0
# HTTP请求
requests>=2.28.0
# 环境变量管理
python-dotenv>=1.0.0
+9
View File
@@ -0,0 +1,9 @@
"""
PDF OCR Skill Scripts Package
"""
from .pdf_ocr_processor import PDFOCRProcessor
__all__ = ['PDFOCRProcessor']
__version__ = '1.0.0'
+205
View File
@@ -0,0 +1,205 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
PDF OCR处理脚本
使用硅基流动大模型进行OCR识别处理影印版PDF文件
"""
import os
import sys
import base64
import requests
from typing import Dict, Any, List
from dotenv import load_dotenv
# 加载环境变量
load_dotenv()
class PDFOCRProcessor:
"""PDF OCR处理器"""
def __init__(self):
self.api_key = os.getenv("SILICON_FLOW_API_KEY", "")
self.base_url = "https://api.siliconflow.cn/v1/chat/completions"
# 使用专门的OCR模型
self.model = os.getenv("SILICON_FLOW_OCR_MODEL", "deepseek-ai/DeepSeek-OCR")
self.headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {self.api_key}"
}
def pdf_to_images(self, pdf_path: str) -> List[str]:
"""将PDF转换为图片列表返回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)
# 转换为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("请安装依赖: pip install pymupdf pillow")
except Exception as e:
raise Exception(f"PDF转图片失败: {str(e)}")
def ocr_image(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)}"
def image_to_base64(self, image_path: str) -> str:
"""将图片文件转换为base64编码"""
try:
from PIL import Image
import io
# 打开图片
img = Image.open(image_path)
# 转换为RGB格式如果需要
if img.mode != 'RGB':
img = img.convert('RGB')
# 转换为base64
buffered = io.BytesIO()
img.save(buffered, format="PNG")
img_base64 = base64.b64encode(buffered.getvalue()).decode()
return img_base64
except ImportError:
raise Exception("请安装依赖: pip install pillow")
except Exception as e:
raise Exception(f"图片转base64失败: {str(e)}")
def ocr_image_file(self, image_path: str) -> Dict[str, Any]:
"""OCR识别单个图片文件"""
result = {
"text": "",
"page_count": 1
}
try:
# 将图片转换为base64
img_base64 = self.image_to_base64(image_path)
# 进行OCR识别
text = self.ocr_image(img_base64, 1)
result["text"] = text
except Exception as e:
raise Exception(f"图片OCR识别失败: {str(e)}")
return result
def ocr_pdf(self, pdf_path: str) -> Dict[str, Any]:
"""OCR识别整个PDF"""
result = {
"text": "",
"page_count": 0
}
try:
images = self.pdf_to_images(pdf_path)
result["page_count"] = len(images)
text_parts = []
for idx, img_base64 in enumerate(images, 1):
page_text = self.ocr_image(img_base64, idx)
text_parts.append(f"=== 第 {idx} 页 (OCR) ===\n{page_text}")
result["text"] = "\n\n".join(text_parts)
except Exception as e:
raise Exception(f"OCR识别失败: {str(e)}")
return result
def process_pdf_ocr(pdf_path: str) -> Dict[str, Any]:
"""处理PDF OCR的主函数"""
processor = PDFOCRProcessor()
return processor.ocr_pdf(pdf_path)
if __name__ == "__main__":
# 测试代码
import json
if len(sys.argv) > 1:
pdf_path = sys.argv[1]
else:
print("使用方法: python pdf_ocr_processor.py <pdf_file_path>")
sys.exit(1)
if not os.path.exists(pdf_path):
print(f"文件不存在: {pdf_path}")
sys.exit(1)
try:
result = process_pdf_ocr(pdf_path)
print(f"OCR识别完成{result['page_count']}")
print(f"文本长度: {len(result['text'])} 字符")
print("\n前500字符:")
print(result['text'][:500])
except Exception as e:
print(f"OCR识别失败: {str(e)}")
sys.exit(1)
+41
View File
@@ -0,0 +1,41 @@
"""
PDF OCR Skill Setup
"""
from setuptools import setup, find_packages
with open("README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
with open("requirements.txt", "r", encoding="utf-8") as fh:
requirements = [line.strip() for line in fh if line.strip() and not line.startswith("#")]
setup(
name="pdf-ocr-skill",
version="1.0.0",
author="PDF OCR Skill Team",
author_email="",
description="PDF OCR Skill - 使用硅基流动大模型进行OCR识别",
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/yejinlei/pdf-ocr-skill",
packages=find_packages(),
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"Topic :: Scientific/Engineering :: Artificial Intelligence",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
],
python_requires=">=3.8",
install_requires=requirements,
keywords="ocr pdf image recognition siliconflow chinese english",
project_urls={
"Bug Reports": "https://github.com/yejinlei/pdf-ocr-skill/issues",
"Source": "https://github.com/yejinlei/pdf-ocr-skill",
},
)
+213
View File
@@ -0,0 +1,213 @@
# PDF OCR Skill 发布指南
## 通过npx skills add安装
发布到GitHub后用户可以通过以下命令安装
### 基本安装
```bash
# 从GitHub仓库安装
npx skills add yejinlei/pdf-ocr-skill
# 或者使用完整URL
npx skills add https://github.com/yejinlei/pdf-ocr-skill
```
### 指定技能安装
```bash
# 只安装pdf-ocr技能
npx skills add yejinlei/pdf-ocr-skill --skill pdf-ocr
```
### 全局安装
```bash
# 安装到全局目录
npx skills add yejinlei/pdf-ocr-skill --global
```
### 非交互式安装CI/CD友好
```bash
# 跳过确认提示
npx skills add yejinlei/pdf-ocr-skill --yes
```
## 发布步骤
### 1. 创建GitHub仓库
1. 在GitHub上创建新仓库`pdf-ocr-skill`
2. 将pdf-ocr目录内容推送到仓库
### 2. 推送代码
```bash
# 初始化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 --tags
```
### 3. 用户安装
用户可以通过以下方式安装:
#### 方式1直接安装
```bash
npx skills add yejinlei/pdf-ocr-skill
```
#### 方式2搜索安装
```bash
# 搜索技能
npx skills find ocr
# 选择pdf-ocr技能进行安装
```
#### 方式3列出已安装技能
```bash
# 列出所有已安装技能
npx skills list
# 列出全局安装的技能
npx skills list --global
```
### 4. 环境变量配置
1. 复制 `.env.example` 文件并重命名为 `.env`
2. 填入您的硅基流动 API 密钥:
```env
SILICON_FLOW_API_KEY=your_api_key_here
SILICON_FLOW_OCR_MODEL=deepseek-ai/DeepSeek-OCR
```
## 技能使用
安装后技能会自动集成到支持的agents中。用户可以通过自然语言描述来使用技能
```python
# 在agent中使用
agent.add_task("识别这张图片中的文字")
# 或者直接调用
from pdf_ocr_processor import PDFOCRProcessor
processor = PDFOCRProcessor()
result = processor.ocr_image_file('image.jpg')
```
## 更新技能
### 检查更新
```bash
# 检查是否有更新
npx skills check
```
### 更新技能
```bash
# 更新所有已安装技能
npx skills update
```
### 更新特定技能
```bash
# 更新pdf-ocr技能
npx skills add yejinlei/pdf-ocr-skill --skill pdf-ocr
```
## 移除技能
```bash
# 移除pdf-ocr技能
npx skills remove pdf-ocr
# 从全局移除
npx skills remove --global pdf-ocr
# 移除所有技能
npx skills remove --all
```
## 技能搜索
```bash
# 交互式搜索
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
```yaml
---
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官方仓库如果适用
+142
View File
@@ -0,0 +1,142 @@
# 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. 测试
```bash
# 安装依赖
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. 打包
```bash
# 构建源码包
python setup.py sdist
# 构建wheel包
python setup.py bdist_wheel
```
### 3. 发布到PyPI
```bash
# 安装twine
pip install twine
# 上传到PyPI
twine upload dist/*
```
### 4. 发布到GitHub
```bash
# 初始化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
```
## 使用示例
### 安装
```bash
pip install pdf-ocr-skill
```
### 使用
```python
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. 添加更多文档和示例