Google|Colab 自动化:利用 OCR 提取图片文字并批量重命名文件

在处理大量纸质单据、快递面单或表格截图时,手动提取图片中的关键信息(如单号、姓名)并重命名文件是一项耗时且极易出错的工作。

本文将分享一套基于 Google Colab + Python + Google Cloud Vision API 的自动化解决方案,实现从 Google Drive 中的图片自动提取关键信息,并按 单号_姓名.jpg 的格式完成批量重命名。

一,为什么选择 Google Colab 而非 Google Apps Script (GAS)?

在项目初期,我分别测试了 Google Apps Script (GAS) 与 Google Colab 两种方案,最终选择了后者。原因如下:

  • 识别精度与灵活性:GAS 内置的简单的 OCR 在处理中文字符和特定格式字段时,精准度较低且难以灵活调优;而在 Colab 中,可以用 Python 轻松对接 Gemini Vision、Claude 或 Google Cloud Vision API,结合强大的正则表达式进行精准清洗。
  • 突破执行时长限制:GAS 的单次脚本运行上限为 6 分钟,处理大量图片时极易超时崩溃;而 Colab(Python)更适合批处理任务,稳定性和扩展性更好。

二,具体步骤与核心代码

整个流程分为 环境挂载、参数配置 和 识别重命名 三部分。

1. 挂载 Google Drive

在 Google Colab 中新建 Notebook,运行以下代码绑定 Google 云端硬盘:

import os
import re
import base64
import requests
from google.colab import drive

# 挂载 Google Drive 到 Colab 环境(首次运行需授权)
drive.mount('/content/drive')

2. 配置 API Key 与文件夹路径

添加新的代码块,填写你的 Google Cloud Vision API Key 以及存放图片的 Google Drive 绝对路径:

# 填写你的 API 密钥与图片文件夹路径
API_KEY = 'YOUR_VISION_API_KEY'
FOLDER_PATH = '/content/drive/MyDrive/图片'  # 替换为实际文件夹路径

VISION_API_URL = f'https://vision.googleapis.com/v1/images:annotate?key={API_KEY}'

3. 执行识别与智能重命名

以下代码将遍历文件夹中的图片,通过 API 提取文本,并使用正则规则精准截取“单号”与“姓名”进行文件重命名:

print(f"开始扫描文件夹: {FOLDER_PATH}")

for filename in os.listdir(FOLDER_PATH):
    # 仅处理常见图片格式
    if not filename.lower().endswith(('.jpg', '.jpeg', '.png')):
        continue
        
    # 如果文件名已经是 "数字_名字" 格式则直接跳过,防止重复运行
    if re.match(r'^\d+_[^\d]+', filename):
        print(f"跳过已处理文件: {filename}")
        continue

    file_path = os.path.join(FOLDER_PATH, filename)
    print(f"\n正在处理: {filename}...")

    # 将图片编码为 Base64 格式发送给 API
    with open(file_path, "rb") as image_file:
        encoded_image = base64.b64encode(image_file.read()).decode('utf-8')

    payload = {
        "requests": [{
            "image": {"content": encoded_image},
            "features": [{"type": "DOCUMENT_TEXT_DETECTION"}]
        }]
    }

    try:
        response = requests.post(VISION_API_URL, json=payload)
        result = response.json()

        if 'error' in result:
            print(f"API 报错: {result['error']['message']}")
            continue

        if 'responses' in result and 'fullTextAnnotation' in result['responses'][0]:
            text = result['responses'][0]['fullTextAnnotation']['text']

            # --- 智能提取逻辑 ---
            order_number = None
            name = None

            # 1. 提取单号(匹配“序号”后 5-10 位数字)
            order_match = re.search(r'序号[^\d]{0,20}(\d{5,10})', text)
            if order_match:
                order_number = order_match.group(1)

            # 2. 提取姓名(截取“姓名”与地址/邮编之间的文本,排查纯数字)
            chunk_match = re.search(r'姓名([\s\S]*?)(?=〒|邮编|地址|住址|电话)', text)
            if chunk_match:
                lines = chunk_match.group(1).split('\n')
                for line in lines:
                    clean_line = re.sub(r'\s+', '', line)
                    # 规则:长度>1,包含中文/日文/英文,排查纯数字
                    if len(clean_line) > 1 and re.search(r'[ぁ-んァ-ン一-龥a-zA-Z]', clean_line) and not re.search(r'\d', clean_line):
                        name = clean_line
                        break

            # --- 执行重命名 ---
            if order_number and name:
                new_filename = f"{order_number}_{name}.jpg"
                new_file_path = os.path.join(FOLDER_PATH, new_filename)
                
                # 直接重命名 Google Drive 挂载路径下的文件
                os.rename(file_path, new_file_path)
                print(f"✅ 成功重命名: {filename} -> {new_filename}")
            else:
                print(f"❌ 识别失败(数字或姓名缺失): {filename}")

    except Exception as e:
        print(f"处理出错: {e}")

print("\n🎉 全部处理完成!")