# GLM-OCR Python API调用详解:4行代码集成文本/表格/公式识别功能
你是不是经常需要从图片里提取文字、识别表格数据,或者把复杂的数学公式转成可编辑的格式?手动处理这些任务不仅耗时费力,还容易出错。今天我要分享一个超级实用的工具——GLM-OCR,它能让你用短短4行Python代码,就搞定文本、表格、公式的智能识别。
GLM-OCR是智谱AI基于GLM-V架构开发的多模态OCR模型,专门为复杂文档理解而生。它不像传统的OCR工具只能识别简单文字,而是能理解文档的结构和内容,把图片里的信息真正“读懂”。最棒的是,它提供了简洁的Python API,让你能轻松集成到自己的项目中。
接下来,我会带你从零开始,一步步掌握GLM-OCR的API调用方法。无论你是想批量处理文档图片,还是想在应用中添加OCR功能,这篇文章都能帮到你。
## 1. 环境准备:快速搭建GLM-OCR服务
在开始写代码之前,我们需要先把GLM-OCR服务跑起来。别担心,这个过程很简单,我已经帮你把步骤都整理好了。
### 1.1 启动GLM-OCR服务
首先,确保你已经按照项目文档部署好了GLM-OCR。如果还没做,这里有个快速回顾:
```bash
# 进入项目目录
cd /root/GLM-OCR
# 启动服务
./start_vllm.sh
```
启动后,你会看到类似这样的输出:
```
Starting GLM-OCR service on port 7860...
Loading model from /root/ai-models/ZhipuAI/GLM-OCR...
Model loaded successfully! Service is ready.
```
**重要提示**:第一次启动需要加载模型,大概需要1-2分钟,请耐心等待。看到"Service is ready"就表示服务启动成功了。
### 1.2 验证服务状态
服务启动后,你可以通过两种方式验证是否正常运行:
**方法一:浏览器访问**
打开浏览器,输入 `http://你的服务器IP:7860`,如果能看到GLM-OCR的Web界面,说明服务运行正常。
**方法二:命令行检查**
```bash
# 检查端口是否被监听
netstat -tlnp | grep 7860
# 或者查看进程
ps aux | grep serve_gradio
```
如果服务没启动起来,最常见的问题是端口冲突。7860端口被占用的话,可以换个端口,或者停止占用该端口的进程:
```bash
# 查看哪个进程占用了7860端口
lsof -i :7860
# 停止该进程(如果需要)
kill <进程ID>
```
### 1.3 安装Python客户端库
GLM-OCR的Python API基于Gradio Client,所以我们需要先安装这个库:
```bash
pip install gradio_client
```
如果你用的是项目提供的conda环境,可能已经安装好了。可以这样检查:
```bash
/opt/miniconda3/envs/py310/bin/pip list | grep gradio-client
```
现在环境准备好了,让我们进入最激动人心的部分——写代码!
## 2. 基础API调用:4行代码搞定OCR
GLM-OCR的API设计得非常简洁,核心调用真的只需要4行代码。我们先从最简单的文本识别开始。
### 2.1 文本识别:最基础的用法
假设你有一张包含文字的图片 `document.png`,想提取里面的文字:
```python
from gradio_client import Client
# 第1行:创建客户端连接
client = Client("http://localhost:7860")
# 第2-4行:调用识别功能
result = client.predict(
image_path="/path/to/document.png", # 图片路径
prompt="Text Recognition:", # 任务提示
api_name="/predict" # API名称
)
print("识别结果:", result)
```
就这么简单!让我解释一下这几行代码:
1. **创建客户端**:连接到本地的GLM-OCR服务(如果你把服务部署在其他机器,把`localhost`换成对应的IP地址)
2. **指定图片路径**:告诉模型要处理哪张图片
3. **设置任务类型**:`"Text Recognition:"`表示进行文本识别
4. **调用API**:`/predict`是GLM-OCR的主要接口
运行这段代码,你会得到图片中所有文字的识别结果。比如一张会议纪要的图片,可能返回:
```
会议主题:季度工作总结
时间:2024年3月15日
参会人员:张三、李四、王五...
```
### 2.2 表格识别:保持数据结构
表格识别是GLM-OCR的强项。它能识别表格的边框、行列结构,并以结构化的格式返回数据:
```python
from gradio_client import Client
client = Client("http://localhost:7860")
# 注意:这里把prompt改为表格识别
result = client.predict(
image_path="/path/to/table.png",
prompt="Table Recognition:", # 关键变化在这里
api_name="/predict"
)
print("表格识别结果:")
print(result)
```
对于一张销售数据表格,返回结果可能是这样的:
```
| 月份 | 产品A | 产品B | 产品C |
|------|-------|-------|-------|
| 1月 | 1200 | 800 | 1500 |
| 2月 | 1300 | 850 | 1600 |
| 3月 | 1400 | 900 | 1700 |
```
GLM-OCR不仅能识别表格内容,还能保持表格的Markdown格式,方便你直接复制到文档或代码中。
### 2.3 公式识别:数学表达式的克星
对于学术论文、技术文档中的数学公式,GLM-OCR也能准确识别:
```python
from gradio_client import Client
client = Client("http://localhost:7860")
result = client.predict(
image_path="/path/to/formula.png",
prompt="Formula Recognition:", # 公式识别模式
api_name="/predict"
)
print("公式识别结果:", result)
```
比如识别一个二次方程公式,可能返回:
```
x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}
```
返回的是LaTeX格式,你可以直接用在论文写作或数学软件中。
## 3. 实战技巧:让API调用更高效
掌握了基础用法后,我们来看看如何在实际项目中更好地使用GLM-OCR API。
### 3.1 批量处理多张图片
如果你有很多图片需要处理,一个一个调用太麻烦了。我们可以写个简单的批量处理函数:
```python
from gradio_client import Client
import os
from pathlib import Path
def batch_ocr(image_folder, task_type="Text Recognition:"):
"""
批量处理文件夹中的所有图片
Args:
image_folder: 图片文件夹路径
task_type: 任务类型,可选 "Text Recognition:"、"Table Recognition:"、"Formula Recognition:"
"""
client = Client("http://localhost:7860")
# 支持常见的图片格式
image_extensions = ['.png', '.jpg', '.jpeg', '.webp']
image_folder = Path(image_folder)
results = {}
for image_file in image_folder.iterdir():
if image_file.suffix.lower() in image_extensions:
print(f"正在处理: {image_file.name}")
try:
result = client.predict(
image_path=str(image_file),
prompt=task_type,
api_name="/predict"
)
results[image_file.name] = result
print(f" 完成!")
except Exception as e:
print(f" 处理失败: {e}")
results[image_file.name] = f"错误: {str(e)}"
return results
# 使用示例:批量识别一个文件夹中的所有文本图片
text_results = batch_ocr("/path/to/images", "Text Recognition:")
for filename, content in text_results.items():
print(f"\n{filename}:")
print(content[:200] + "..." if len(content) > 200 else content) # 只打印前200字符
```
这个函数会自动遍历文件夹,处理所有支持的图片格式,并把结果保存到字典里。你可以根据需要修改,比如把结果保存到文件或数据库。
### 3.2 错误处理与重试机制
网络服务难免会有不稳定的时候,加上适当的错误处理能让你的代码更健壮:
```python
from gradio_client import Client
import time
def robust_ocr(image_path, prompt, max_retries=3):
"""
带重试机制的OCR调用
Args:
image_path: 图片路径
prompt: 任务提示
max_retries: 最大重试次数
"""
client = Client("http://localhost:7860")
for attempt in range(max_retries):
try:
result = client.predict(
image_path=image_path,
prompt=prompt,
api_name="/predict"
)
return result
except ConnectionError as e:
if attempt < max_retries - 1:
wait_time = 2 ** attempt # 指数退避
print(f"连接失败,{wait_time}秒后重试... (尝试 {attempt + 1}/{max_retries})")
time.sleep(wait_time)
else:
raise Exception(f"服务连接失败,已重试{max_retries}次: {e}")
except Exception as e:
# 其他错误直接抛出
raise Exception(f"OCR处理失败: {e}")
# 使用示例
try:
result = robust_ocr("/path/to/image.png", "Text Recognition:")
print("识别成功:", result)
except Exception as e:
print("处理失败:", str(e))
```
这个`robust_ocr`函数会在连接失败时自动重试,采用指数退避策略(等待1秒、2秒、4秒...),避免给服务端造成太大压力。
### 3.3 处理大图片和复杂文档
GLM-OCR对图片大小有一定限制,如果遇到大图片或复杂文档,可以这样处理:
```python
from PIL import Image
import os
def process_large_document(image_path, prompt, max_size=2048):
"""
处理大尺寸图片,自动调整大小
Args:
image_path: 原始图片路径
prompt: 任务提示
max_size: 最大边长(像素)
"""
# 打开图片
img = Image.open(image_path)
# 如果图片太大,等比例缩小
if max(img.size) > max_size:
print(f"图片尺寸过大 ({img.size}),正在调整...")
# 计算新的尺寸
ratio = max_size / max(img.size)
new_size = tuple(int(dim * ratio) for dim in img.size)
# 调整大小
img_resized = img.resize(new_size, Image.Resampling.LANCZOS)
# 保存临时文件
temp_path = "/tmp/resized_image.png"
img_resized.save(temp_path)
# 使用调整后的图片
image_path = temp_path
# 调用OCR
client = Client("http://localhost:7860")
result = client.predict(
image_path=image_path,
prompt=prompt,
api_name="/predict"
)
# 清理临时文件
if 'temp_path' in locals():
os.remove(temp_path)
return result
# 使用示例
result = process_large_document("/path/to/large_document.jpg", "Text Recognition:")
```
这个函数会自动检测图片尺寸,如果超过设定值(默认2048像素),就等比例缩小,既保证识别效果,又避免内存问题。
## 4. 高级应用:构建完整的OCR处理流程
现在你已经掌握了GLM-OCR的基本用法,让我们看看如何在实际项目中应用它。
### 4.1 构建文档自动化处理管道
假设你要处理一批扫描的PDF文档,提取其中的文字、表格和公式:
```python
from gradio_client import Client
import fitz # PyMuPDF
from PIL import Image
import io
import json
class DocumentProcessor:
"""文档处理管道"""
def __init__(self, server_url="http://localhost:7860"):
self.client = Client(server_url)
def pdf_to_images(self, pdf_path, dpi=150):
"""将PDF转换为图片列表"""
doc = fitz.open(pdf_path)
images = []
for page_num in range(len(doc)):
page = doc.load_page(page_num)
pix = page.get_pixmap(dpi=dpi)
img_data = pix.tobytes("png")
img = Image.open(io.BytesIO(img_data))
images.append(img)
doc.close()
return images
def extract_text_from_image(self, image, save_path=None):
"""从单张图片提取文本"""
if save_path:
image.save(save_path)
image_path = save_path
else:
# 保存到临时文件
temp_path = "/tmp/temp_ocr.png"
image.save(temp_path)
image_path = temp_path
try:
result = self.client.predict(
image_path=image_path,
prompt="Text Recognition:",
api_name="/predict"
)
return result
finally:
if not save_path and os.path.exists(temp_path):
os.remove(temp_path)
def process_pdf(self, pdf_path, output_json=None):
"""处理整个PDF文档"""
print(f"开始处理: {pdf_path}")
# 1. PDF转图片
images = self.pdf_to_images(pdf_path)
print(f" 共 {len(images)} 页")
# 2. 逐页处理
results = []
for i, img in enumerate(images):
print(f" 处理第 {i+1} 页...")
# 保存临时图片
temp_path = f"/tmp/page_{i+1}.png"
img.save(temp_path)
# 识别文本
text = self.extract_text_from_image(img, temp_path)
# 这里可以添加表格和公式识别的逻辑
# table = self.extract_table_from_image(img)
# formula = self.extract_formula_from_image(img)
results.append({
"page": i + 1,
"text": text,
# "tables": table,
# "formulas": formula
})
# 清理临时文件
os.remove(temp_path)
# 3. 保存结果
if output_json:
with open(output_json, 'w', encoding='utf-8') as f:
json.dump(results, f, ensure_ascii=False, indent=2)
print(f"结果已保存到: {output_json}")
return results
# 使用示例
processor = DocumentProcessor()
# 处理单个PDF
results = processor.process_pdf(
"/path/to/document.pdf",
output_json="/path/to/output.json"
)
# 查看结果
for page in results:
print(f"\n=== 第 {page['page']} 页 ===")
print(page['text'][:500] + "..." if len(page['text']) > 500 else page['text'])
```
这个`DocumentProcessor`类提供了一个完整的处理框架,你可以根据需要扩展表格识别、公式识别等功能。
### 4.2 与现有工作流集成
GLM-OCR可以轻松集成到各种工作流中。比如,结合FastAPI构建一个OCR微服务:
```python
from fastapi import FastAPI, File, UploadFile
from gradio_client import Client
from PIL import Image
import io
import uvicorn
app = FastAPI(title="GLM-OCR API服务")
client = Client("http://localhost:7860")
@app.post("/ocr/text")
async def ocr_text(file: UploadFile = File(...)):
"""文本识别接口"""
# 读取上传的图片
image_data = await file.read()
image = Image.open(io.BytesIO(image_data))
# 保存临时文件
temp_path = "/tmp/uploaded_image.png"
image.save(temp_path)
# 调用GLM-OCR
result = client.predict(
image_path=temp_path,
prompt="Text Recognition:",
api_name="/predict"
)
# 清理临时文件
import os
os.remove(temp_path)
return {
"status": "success",
"task": "text_recognition",
"result": result
}
@app.post("/ocr/table")
async def ocr_table(file: UploadFile = File(...)):
"""表格识别接口"""
image_data = await file.read()
image = Image.open(io.BytesIO(image_data))
temp_path = "/tmp/uploaded_image.png"
image.save(temp_path)
result = client.predict(
image_path=temp_path,
prompt="Table Recognition:",
api_name="/predict"
)
import os
os.remove(temp_path)
return {
"status": "success",
"task": "table_recognition",
"result": result
}
@app.post("/ocr/formula")
async def ocr_formula(file: UploadFile = File(...)):
"""公式识别接口"""
image_data = await file.read()
image = Image.open(io.BytesIO(image_data))
temp_path = "/tmp/uploaded_image.png"
image.save(temp_path)
result = client.predict(
image_path=temp_path,
prompt="Formula Recognition:",
api_name="/predict"
)
import os
os.remove(temp_path)
return {
"status": "success",
"task": "formula_recognition",
"result": result
}
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000)
```
启动这个服务后,你就可以通过HTTP请求调用OCR功能了:
```bash
# 启动服务
python ocr_api.py
# 使用curl测试
curl -X POST "http://localhost:8000/ocr/text" \
-F "file=@/path/to/image.png"
```
### 4.3 性能优化建议
在实际生产环境中,你可能需要处理大量图片。这里有一些性能优化建议:
1. **连接池管理**:避免频繁创建和销毁客户端连接
2. **异步处理**:对于批量任务,使用异步提高吞吐量
3. **结果缓存**:对相同的图片进行缓存,避免重复识别
4. **资源监控**:监控GPU内存使用,避免服务崩溃
这里是一个简单的连接池实现:
```python
import threading
from queue import Queue
from gradio_client import Client
class OCRClientPool:
"""GLM-OCR客户端连接池"""
def __init__(self, server_url, pool_size=5):
self.server_url = server_url
self.pool_size = pool_size
self._pool = Queue(maxsize=pool_size)
self._lock = threading.Lock()
# 初始化连接池
for _ in range(pool_size):
client = Client(server_url)
self._pool.put(client)
def get_client(self):
"""从池中获取客户端"""
return self._pool.get()
def release_client(self, client):
"""释放客户端回池"""
self._pool.put(client)
def ocr_with_pool(self, image_path, prompt):
"""使用连接池进行OCR识别"""
client = self.get_client()
try:
result = client.predict(
image_path=image_path,
prompt=prompt,
api_name="/predict"
)
return result
finally:
self.release_client(client)
# 使用示例
pool = OCRClientPool("http://localhost:7860", pool_size=3)
# 在多线程环境中使用
import concurrent.futures
def process_image(image_info):
image_path, task_type = image_info
result = pool.ocr_with_pool(image_path, task_type)
return image_path, result
# 批量处理
image_tasks = [
("/path/to/image1.png", "Text Recognition:"),
("/path/to/image2.png", "Table Recognition:"),
("/path/to/image3.png", "Formula Recognition:"),
]
with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:
results = list(executor.map(process_image, image_tasks))
for image_path, result in results:
print(f"{image_path}: {result[:100]}...")
```
## 5. 总结
通过这篇文章,你应该已经掌握了GLM-OCR Python API的核心用法。让我们回顾一下重点:
**核心要点回顾**:
1. **4行代码基础调用**:使用`gradio_client`库,4行代码就能完成文本、表格、公式的识别
2. **三种任务模式**:通过不同的prompt参数(`Text Recognition:`、`Table Recognition:`、`Formula Recognition:`)切换识别模式
3. **错误处理很重要**:添加重试机制和适当的错误处理,让代码更健壮
4. **批量处理效率高**:对于大量图片,使用批量处理函数可以显著提高效率
**实际应用建议**:
- 对于简单的一次性任务,直接使用基础API调用就够了
- 如果需要处理大量文档,建议构建完整的处理管道,加入错误处理和日志记录
- 在生产环境中,考虑使用连接池和异步处理来提高性能
- 记得处理大图片,避免内存问题
**下一步学习方向**:
1. 尝试将GLM-OCR集成到你现有的项目中
2. 探索更多高级功能,比如自定义prompt进行特定类型的识别
3. 学习如何微调模型以适应你的特定需求
4. 研究如何将OCR结果进一步处理,比如提取关键信息、构建知识图谱等
GLM-OCR的强大之处在于它不仅能识别文字,还能理解文档的结构和内容。无论是处理扫描文档、提取表格数据,还是识别数学公式,它都能提供准确的结果。而且简洁的API设计让集成变得非常容易。
现在你已经有了所有需要的工具和知识,接下来就是动手实践了。选一个你手头的OCR需求,用GLM-OCR试试看,相信你会被它的效果和易用性惊艳到。
---
> **获取更多AI镜像**
>
> 想探索更多AI镜像和应用场景?访问 [CSDN星图镜像广场](https://ai.csdn.net/?utm_source=mirror_blog_end),提供丰富的预置镜像,覆盖大模型推理、图像生成、视频生成、模型微调等多个领域,支持一键部署。