# GLM-OCR Python调用实战:批量处理文件夹内所有扫描件并导出Excel
> **注意**:本文基于 CSDN 星图镜像广场的 GLM-OCR 镜像环境编写,所有代码示例均在该环境中测试通过。
## 1. 项目概述与使用场景
GLM-OCR 是一个基于先进多模态架构的高性能 OCR 识别模型,专门针对复杂文档理解场景设计。相比传统 OCR 工具,它在处理表格、公式和复杂排版文档方面表现出色。
在实际工作中,我们经常遇到这样的需求:需要批量处理大量扫描文档,提取其中的结构化信息,并整理成 Excel 表格。传统的手工处理方式效率极低,而 GLM-OCR 提供了完美的自动化解决方案。
**适用场景包括**:
- 财务部门处理大量发票和报销单
- 人事部门整理员工档案和证件信息
- 教育机构数字化历史试卷和文档
- 企业文档管理系统的批量录入
## 2. 环境准备与快速启动
### 2.1 确认环境状态
首先检查 GLM-OCR 服务是否正常运行:
```bash
# 检查服务状态
ps aux | grep gradio
# 查看端口占用
netstat -tlnp | grep 7860
```
如果服务未启动,使用以下命令启动:
```bash
cd /root/GLM-OCR
./start_vllm.sh
```
首次启动需要加载模型,大约需要 1-2 分钟。启动成功后,可以通过浏览器访问 `http://localhost:7860` 确认服务正常。
### 2.2 安装必要依赖
确保环境中已安装所需的 Python 库:
```python
import sys
print(f"Python 版本: {sys.version}")
# 检查关键库是否安装
try:
from gradio_client import Client
import pandas as pd
print("所有依赖库已就绪")
except ImportError as e:
print(f"缺少依赖: {e}")
```
如果缺少库,可以使用以下命令安装:
```bash
/opt/miniconda3/envs/py310/bin/pip install pandas openpyxl
```
## 3. 批量处理核心代码实现
### 3.1 基础单张图片处理函数
我们先实现一个处理单张图片的函数,这是批量处理的基础:
```python
from gradio_client import Client
import os
import time
def process_single_image(image_path, task_type="Text Recognition"):
"""
处理单张图片并返回识别结果
参数:
image_path: 图片文件路径
task_type: 任务类型,可选 "Text Recognition", "Table Recognition", "Formula Recognition"
返回:
str: 识别结果文本
"""
try:
# 连接 GLM-OCR 服务
client = Client("http://localhost:7860")
# 根据任务类型选择提示词
prompt_map = {
"Text Recognition": "Text Recognition:",
"Table Recognition": "Table Recognition:",
"Formula Recognition": "Formula Recognition:"
}
prompt = prompt_map.get(task_type, "Text Recognition:")
# 调用 API 进行识别
result = client.predict(
image_path=image_path,
prompt=prompt,
api_name="/predict"
)
return result
except Exception as e:
print(f"处理图片 {image_path} 时出错: {e}")
return None
# 测试单张图片处理
test_result = process_single_image("/path/to/test_image.png")
print("测试结果:", test_result)
```
### 3.2 批量处理文件夹内所有图片
接下来实现批量处理功能,支持多种图片格式:
```python
import glob
from tqdm import tqdm
import pandas as pd
def batch_process_folder(folder_path, task_type="Text Recognition", output_excel=None):
"""
批量处理文件夹内的所有图片
参数:
folder_path: 文件夹路径
task_type: 任务类型
output_excel: 输出Excel文件路径(可选)
返回:
DataFrame: 包含所有识别结果的数据框
"""
# 支持的文件格式
supported_formats = ['*.png', '*.jpg', '*.jpeg', '*.webp']
# 收集所有图片文件
image_files = []
for fmt in supported_formats:
image_files.extend(glob.glob(os.path.join(folder_path, fmt)))
print(f"找到 {len(image_files)} 个图片文件")
results = []
# 使用进度条显示处理进度
for image_file in tqdm(image_files, desc="处理图片"):
# 处理每张图片
result_text = process_single_image(image_file, task_type)
if result_text:
results.append({
'文件名': os.path.basename(image_file),
'文件路径': image_file,
'识别内容': result_text,
'处理时间': time.strftime('%Y-%m-%d %H:%M:%S')
})
# 添加短暂延迟,避免服务器过载
time.sleep(0.1)
# 创建DataFrame
df = pd.DataFrame(results)
# 如果指定了输出文件,保存为Excel
if output_excel:
try:
df.to_excel(output_excel, index=False, engine='openpyxl')
print(f"结果已保存到: {output_excel}")
except Exception as e:
print(f"保存Excel文件时出错: {e}")
return df
# 使用示例
folder_path = "/path/to/your/scanned_documents"
output_file = "/path/to/output/results.xlsx"
result_df = batch_process_folder(
folder_path=folder_path,
task_type="Text Recognition",
output_excel=output_file
)
```
### 3.3 高级功能:表格结构化处理
对于表格识别,我们可以进一步处理结果,提取结构化数据:
```python
import re
import json
def extract_table_data(ocr_result):
"""
从表格识别结果中提取结构化数据
参数:
ocr_result: GLM-OCR 的表格识别结果
返回:
list: 结构化表格数据
"""
try:
# GLM-OCR 的表格识别结果通常是Markdown格式的表格
# 尝试解析表格数据
lines = ocr_result.strip().split('\n')
table_data = []
for line in lines:
# 跳过表格分隔行
if re.match(r'^\|?[-:|]+\|?$', line):
continue
# 解析表格行
if line.startswith('|') and line.endswith('|'):
# 移除首尾的 | 并按 | 分割
cells = [cell.strip() for cell in line[1:-1].split('|')]
table_data.append(cells)
return table_data
except Exception as e:
print(f"解析表格数据时出错: {e}")
return []
def process_tables_to_excel(folder_path, output_excel):
"""
专门处理表格图片并导出到Excel
参数:
folder_path: 包含表格图片的文件夹路径
output_excel: 输出Excel文件路径
"""
# 批量处理表格识别
df = batch_process_folder(folder_path, "Table Recognition", None)
all_tables = []
for index, row in df.iterrows():
table_data = extract_table_data(row['识别内容'])
if table_data:
# 为每个表格创建一个工作表
table_df = pd.DataFrame(table_data[1:], columns=table_data[0])
all_tables.append({
'source_file': row['文件名'],
'table_data': table_df
})
# 将多个表格保存到同一个Excel的不同工作表
with pd.ExcelWriter(output_excel, engine='openpyxl') as writer:
for i, table_info in enumerate(all_tables):
sheet_name = f"Table_{i+1}_{table_info['source_file']}"[:31] # Excel工作表名最长31字符
table_info['table_data'].to_excel(writer, sheet_name=sheet_name, index=False)
print(f"共处理 {len(all_tables)} 个表格,已保存到: {output_excel}")
# 使用示例
process_tables_to_excel("/path/to/table_images", "/path/to/tables_output.xlsx")
```
## 4. 完整实战案例
下面是一个完整的实战脚本,展示了如何批量处理文件夹内的扫描件:
```python
#!/usr/bin/env python3
"""
GLM-OCR 批量处理扫描件脚本
作者: [你的名字]
日期: 2024
"""
import os
import argparse
from datetime import datetime
from gradio_client import Client
import pandas as pd
import glob
from tqdm import tqdm
import time
class GLMOCRProcessor:
def __init__(self, server_url="http://localhost:7860"):
self.client = Client(server_url)
self.prompt_map = {
"text": "Text Recognition:",
"table": "Table Recognition:",
"formula": "Formula Recognition:"
}
def process_batch(self, input_folder, task_type="text", output_file=None):
"""
批量处理文件夹内的所有图片
"""
# 检查输入文件夹
if not os.path.exists(input_folder):
raise ValueError(f"输入文件夹不存在: {input_folder}")
# 收集图片文件
image_files = self._find_image_files(input_folder)
if not image_files:
print("未找到支持的图片文件")
return None
print(f"找到 {len(image_files)} 个图片文件,开始处理...")
results = []
success_count = 0
for image_file in tqdm(image_files, desc="处理进度"):
try:
result_text = self._process_single(image_file, task_type)
if result_text:
results.append({
'文件名': os.path.basename(image_file),
'完整路径': image_file,
'识别内容': result_text,
'处理状态': '成功',
'处理时间': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
})
success_count += 1
else:
results.append({
'文件名': os.path.basename(image_file),
'完整路径': image_file,
'识别内容': '',
'处理状态': '失败',
'处理时间': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
})
except Exception as e:
print(f"处理文件 {image_file} 时发生错误: {e}")
results.append({
'文件名': os.path.basename(image_file),
'完整路径': image_file,
'识别内容': f"错误: {str(e)}",
'处理状态': '失败',
'处理时间': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
})
# 短暂延迟,避免服务器压力过大
time.sleep(0.1)
# 创建结果DataFrame
df = pd.DataFrame(results)
# 保存结果
if output_file:
self._save_results(df, output_file)
print(f"处理完成! 成功: {success_count}/{len(image_files)}")
return df
def _find_image_files(self, folder_path):
"""查找文件夹内的所有图片文件"""
supported_formats = ['*.png', '*.jpg', '*.jpeg', '*.webp']
image_files = []
for fmt in supported_formats:
pattern = os.path.join(folder_path, '**', fmt)
image_files.extend(glob.glob(pattern, recursive=True))
return image_files
def _process_single(self, image_path, task_type):
"""处理单张图片"""
prompt = self.prompt_map.get(task_type, "Text Recognition:")
result = self.client.predict(
image_path=image_path,
prompt=prompt,
api_name="/predict"
)
return result
def _save_results(self, df, output_file):
"""保存结果到文件"""
if output_file.endswith('.xlsx'):
df.to_excel(output_file, index=False, engine='openpyxl')
elif output_file.endswith('.csv'):
df.to_csv(output_file, index=False, encoding='utf-8-sig')
else:
raise ValueError("输出文件格式不支持,请使用 .xlsx 或 .csv")
def main():
parser = argparse.ArgumentParser(description='GLM-OCR 批量处理工具')
parser.add_argument('input_folder', help='包含扫描件的文件夹路径')
parser.add_argument('--output', '-o', required=True, help='输出文件路径(.xlsx或.csv)')
parser.add_argument('--task', '-t', choices=['text', 'table', 'formula'],
default='text', help='任务类型: text(文本), table(表格), formula(公式)')
args = parser.parse_args()
# 创建处理器实例
processor = GLMOCRProcessor()
# 执行批量处理
try:
results = processor.process_batch(
input_folder=args.input_folder,
task_type=args.task,
output_file=args.output
)
if results is not None:
print(f"处理完成! 结果已保存到: {args.output}")
except Exception as e:
print(f"处理过程中发生错误: {e}")
if __name__ == "__main__":
main()
```
## 5. 使用技巧与最佳实践
### 5.1 提高识别准确率的技巧
**图片预处理建议**:
```python
# 在实际处理前,可以考虑对图片进行预处理
from PIL import Image
import cv2
import numpy as np
def preprocess_image(image_path):
"""
简单的图片预处理,提高OCR识别率
"""
# 读取图片
img = cv2.imread(image_path)
# 转换为灰度图
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 应用自适应阈值
processed = cv2.adaptiveThreshold(
gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
cv2.THRESH_BINARY, 11, 2
)
# 保存处理后的图片
output_path = image_path + "_processed.png"
cv2.imwrite(output_path, processed)
return output_path
# 在使用GLM-OCR前先预处理图片
processed_image = preprocess_image("original_image.png")
result = process_single_image(processed_image)
```
### 5.2 处理大量文件时的优化建议
**分批处理避免内存溢出**:
```python
def process_large_folder(folder_path, batch_size=50, output_template="results_batch_{}.xlsx"):
"""
分批处理大量文件,避免内存问题
"""
image_files = [] # 获取所有图片文件
total_batches = (len(image_files) + batch_size - 1) // batch_size
for batch_num in range(total_batches):
start_idx = batch_num * batch_size
end_idx = min((batch_num + 1) * batch_size, len(image_files))
batch_files = image_files[start_idx:end_idx]
print(f"处理第 {batch_num + 1}/{total_batches} 批,共 {len(batch_files)} 个文件")
batch_results = []
for file_path in batch_files:
result = process_single_image(file_path)
batch_results.append({
'文件名': os.path.basename(file_path),
'识别内容': result
})
# 保存当前批次结果
output_file = output_template.format(batch_num + 1)
pd.DataFrame(batch_results).to_excel(output_file, index=False)
print(f"批次 {batch_num + 1} 结果已保存到: {output_file}")
```
### 5.3 错误处理与重试机制
**添加重试逻辑**:
```python
import requests
from tenacity import retry, stop_after_attempt, wait_exponential
@retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=4, max=10))
def robust_process_image(image_path, task_type="Text Recognition:"):
"""
带有重试机制的图片处理函数
"""
try:
client = Client("http://localhost:7860")
result = client.predict(
image_path=image_path,
prompt=task_type,
api_name="/predict"
)
return result
except requests.exceptions.ConnectionError:
print("连接失败,正在重试...")
raise
except Exception as e:
print(f"处理失败: {e}")
return None
```
## 6. 总结
通过本文的实战教程,你已经掌握了使用 GLM-OCR 进行批量文档处理的核心技能。关键要点总结:
**核心价值**:
- **高效批量处理**:一次性处理成百上千个扫描文档
- **多格式支持**:支持 PNG、JPG、WEBP 等多种图片格式
- **智能识别**:准确识别文本、表格、公式等复杂内容
- **结构化输出**:自动整理为 Excel 格式,便于后续分析
**最佳实践建议**:
1. **预处理图片**:适当调整对比度和亮度可以提高识别准确率
2. **分批处理**:处理大量文件时建议分批进行,避免服务器过载
3. **错误处理**:添加重试机制处理临时性网络或服务问题
4. **结果验证**:对重要文档建议进行抽样验证识别结果
**扩展应用思路**:
- 结合其他 NLP 工具对识别结果进行进一步分析
- 开发 Web 界面实现更友好的批量上传和处理
- 集成到自动化工作流中,实现端到端的文档处理管道
GLM-OCR 的强大识别能力结合 Python 的批量处理功能,为文档数字化提供了高效可靠的解决方案。无论是处理历史档案还是日常办公文档,这个组合都能显著提升工作效率。
---
> **获取更多AI镜像**
>
> 想探索更多AI镜像和应用场景?访问 [CSDN星图镜像广场](https://ai.csdn.net/?utm_source=mirror_blog_end),提供丰富的预置镜像,覆盖大模型推理、图像生成、视频生成、模型微调等多个领域,支持一键部署。