ソースを参照

init: OCR service (RapidOCR + OpenVINO, PP-OCRv4)

root 3 ヶ月 前
コミット
e8530343b2
7 ファイル変更、572 行追加、0 行削除
  1. 6 0
      .gitignore
  2. 22 0
      Dockerfile
  3. 87 0
      README.md
  4. 395 0
      app.py
  5. 36 0
      config.yaml
  6. 18 0
      docker-compose.yml
  7. 8 0
      requirements.txt

+ 6 - 0
.gitignore

@@ -0,0 +1,6 @@
+*.pyc
+__pycache__/
+.env
+*.log
+.idea/
+.vscode/

+ 22 - 0
Dockerfile

@@ -0,0 +1,22 @@
+FROM python:3.10-slim
+
+RUN apt-get update && apt-get install -y --no-install-recommends \
+    libglib2.0-0 libsm6 libxext6 libxrender1 libgl1 \
+    libgomp1 libgfortran5 \
+    && rm -rf /var/lib/apt/lists/*
+
+WORKDIR /app
+
+COPY requirements.txt .
+RUN pip install --no-cache-dir -r requirements.txt
+
+# 预下载 RapidOCR 模型
+RUN python -c "from rapidocr_openvino import RapidOCR; RapidOCR()"
+
+COPY app.py .
+COPY config.yaml .
+
+EXPOSE 8082
+
+# 1 worker 避免多进程内存叠加 OOM
+CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8082", "--workers", "1", "--timeout-keep-alive", "120"]

+ 87 - 0
README.md

@@ -0,0 +1,87 @@
+# OCR 文字识别服务
+
+基于 [RapidOCR](https://github.com/RapidAI/RapidOCR) + Intel OpenVINO 的 OCR 服务,使用 PP-OCRv4 模型,CPU 推理加速。
+
+## 技术栈
+
+| 组件 | 版本 |
+|---|---|
+| RapidOCR-OpenVINO | 1.4.4 |
+| Intel OpenVINO | 2024.0.0 |
+| 检测模型 | ch_PP-OCRv4_det_infer |
+| 识别模型 | ch_PP-OCRv4_rec_infer |
+| 方向分类 | ch_ppocr_mobile_v2.0_cls_infer |
+| Web 框架 | FastAPI + Uvicorn |
+| Python | 3.10 |
+
+## 快速部署
+
+```bash
+# 克隆
+git clone https://gitlab.wxapp.info/lio/ocr-service.git
+cd ocr-service
+
+# 一键启动(构建镜像 + 后台运行)
+docker compose up -d --build
+```
+
+服务启动后监听 `8082` 端口。
+
+## 接口
+
+### 图片/PDF 文字识别
+
+```
+POST /api/ocr
+```
+
+支持两种方式:
+- `file`: 上传图片或 PDF 文件(PNG/JPG/BMP/WebP/TIFF/PDF,最大 30MB)
+- `image_base64`: base64 编码的图片
+
+返回:识别文本、每行坐标+置信度、耗时、缓存命中状态。
+
+### 表格识别
+
+```
+POST /api/table
+```
+
+参数同上,返回单元格级别的识别结果。
+
+### 其他
+
+| 接口 | 方法 | 说明 |
+|---|---|---|
+| `/` | GET | 服务状态 |
+| `/api/health` | GET | 健康检查 |
+| `/api/cache/stats` | GET | 缓存命中率统计 |
+| `/api/cache` | DELETE | 清空缓存 |
+
+## 性能优化
+
+- **LRU 缓存**: 500 条结果缓存,相同文件秒返回
+- **线程安全锁**: OCR 引擎单实例 + 线程锁,单 worker 避免多进程内存叠加
+- **PDF 支持**: PyMuPDF 逐页 300 DPI 渲染
+- **资源限制**: Docker 内存上限 4G,Uvicorn 单 worker + 120s keep-alive
+- **引擎调参**: 推理 6 线程,置信度阈值 0.5,方向分类阈值 0.9
+
+## 配置说明
+
+`config.yaml` 可调整引擎参数:
+- `text_score`: 识别置信度阈值(默认 0.5)
+- `Det.inference_num_threads`: 检测线程数(默认 6)
+- `Rec.inference_num_threads`: 识别线程数(默认 6)
+- `max_side_len`: 最大边长(默认 2560)
+
+## Nginx 反代配置
+
+```nginx
+location /ocr-api/ {
+    proxy_pass http://127.0.0.1:8082/api/;
+    proxy_set_header Host $host;
+    proxy_set_header X-Real-IP $remote_addr;
+    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
+    proxy_set_header X-Forwarded-Proto https;
+}
+```

+ 395 - 0
app.py

@@ -0,0 +1,395 @@
+import os
+import io
+import time
+import base64
+import hashlib
+import threading
+from collections import OrderedDict
+from typing import Optional
+
+from fastapi import FastAPI, File, UploadFile, Form, HTTPException, Query
+from fastapi.middleware.cors import CORSMiddleware
+from fastapi.responses import JSONResponse
+from rapidocr_openvino import RapidOCR
+import cv2
+import numpy as np
+from PIL import Image
+
+app = FastAPI(title="OCR Service", description="RapidOCR 图片文字识别服务")
+
+app.add_middleware(
+    CORSMiddleware,
+    allow_origins=["*"],
+    allow_methods=["*"],
+    allow_headers=["*"],
+)
+
+MAX_UPLOAD_SIZE = 30 * 1024 * 1024
+MAX_IMAGE_DIM = 2560
+MAX_PIXELS = 2560 * 2560  # 最大总像素,超过才缩放
+
+# ==================== OCR 引擎 ====================
+
+ocr_engine = RapidOCR(config_path="config.yaml")
+ocr_lock = threading.Lock()
+
+# ==================== 结果缓存(LRU,最多 500 条) ====================
+
+class LRUCache:
+    """简单线程安全 LRU 缓存"""
+    def __init__(self, maxsize=500):
+        self.maxsize = maxsize
+        self.cache = OrderedDict()
+        self.lock = threading.Lock()
+        self.hits = 0
+        self.misses = 0
+
+    def get(self, key):
+        with self.lock:
+            if key in self.cache:
+                self.cache.move_to_end(key)
+                self.hits += 1
+                return self.cache[key]
+            self.misses += 1
+            return None
+
+    def put(self, key, value):
+        with self.lock:
+            if key in self.cache:
+                self.cache.move_to_end(key)
+            else:
+                self.cache[key] = value
+            if len(self.cache) > self.maxsize:
+                self.cache.popitem(last=False)
+
+    def stats(self):
+        with self.lock:
+            total = self.hits + self.misses
+            hit_rate = round(self.hits / total * 100, 1) if total > 0 else 0
+            return {"size": len(self.cache), "max_size": self.maxsize,
+                    "hits": self.hits, "misses": self.misses, "hit_rate": f"{hit_rate}%"}
+
+result_cache = LRUCache(maxsize=500)
+
+def file_hash(data: bytes) -> str:
+    """计算文件 SHA256 哈希(用于缓存 key)"""
+    return hashlib.sha256(data).hexdigest()[:32]
+
+
+# ==================== PDF 支持 ====================
+
+def is_pdf(data: bytes) -> bool:
+    """通过文件头判断是否为 PDF"""
+    return data[:5] == b"%PDF-"
+
+def pdf_to_images(data: bytes) -> list:
+    """
+    将 PDF 每页转为 PIL Image 列表。
+    优先用 PyMuPDF(fitz),不可用则回退 pdf2image。
+    """
+    images = []
+
+    # 方式1:PyMuPDF(纯 Python,无需系统依赖)
+    try:
+        import fitz  # PyMuPDF
+        doc = fitz.open(stream=data, filetype="pdf")
+        for page_num in range(len(doc)):
+            page = doc[page_num]
+            # 渲染为图片(300 DPI 保证清晰度)
+            mat = fitz.Matrix(300 / 72, 300 / 72)
+            pix = page.get_pixmap(matrix=mat)
+            img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
+            images.append(img)
+        doc.close()
+        return images
+    except ImportError:
+        pass
+
+    # 方式2:pdf2image(需要系统装 poppler)
+    try:
+        from pdf2image import convert_from_bytes
+        images = convert_from_bytes(data, dpi=300)
+        return images
+    except Exception:
+        pass
+
+    return None  # 两种方式都不可用
+
+
+# ==================== 表格识别 ====================
+
+def recognize_table(img_array):
+    """
+    使用 OCR 识别表格区域,返回单元格内容
+    (RapidOCR 无表格结构识别,仅返回文字识别结果,保持接口兼容)
+    """
+    lines, text, _, _ = do_ocr(img_array)
+    cells = []
+    for line in lines:
+        cells.append({
+            "text": line["text"],
+            "confidence": line["confidence"],
+            "box": line["box"],
+        })
+    return {
+        "cells": cells,
+        "cell_count": len(cells),
+        "text": text,
+    }
+
+
+# ==================== 图片预处理 ====================
+
+def preprocess_image(img_bytes: bytes) -> tuple:
+    """仅做格式转换,不做图像处理。让 OCR 引擎自己处理最佳。"""
+    image = Image.open(io.BytesIO(img_bytes))
+    orig_w, orig_h = image.size
+
+    if image.mode != "RGB":
+        image = image.convert("RGB")
+
+    img = np.array(image)
+    return img, orig_w, orig_h, []
+
+
+def do_ocr(img_array) -> tuple:
+    """执行 OCR 并返回 (lines, text, elapsed, timing)"""
+    start = time.time()
+    with ocr_lock:
+        result, elapse_list = ocr_engine(img_array)
+    elapsed = round(time.time() - start, 3)
+
+    lines = []
+    text_parts = []
+    if result:
+        for item in result:
+            box, text, confidence = item
+            lines.append({
+                "text": text,
+                "confidence": round(confidence, 4),
+                "box": box,
+            })
+            text_parts.append(text)
+
+    # elapse_list = [det_time, cls_time, rec_time]
+    timing = {}
+    if elapse_list:
+        if len(elapse_list) >= 3:
+            timing = {"det": elapse_list[0], "cls": elapse_list[1], "rec": elapse_list[2]}
+        elif len(elapse_list) >= 1:
+            timing = {"det": elapse_list[0], "cls": 0, "rec": 0}
+
+    return lines, "\n".join(text_parts), elapsed, timing
+
+
+# ==================== 接口 ====================
+
+@app.get("/")
+async def index():
+    return {"service": "OCR Service", "status": "running", "engine": "RapidOCR"}
+
+
+@app.post("/api/ocr")
+async def recognize_text(
+    file: UploadFile = File(None),
+    image_base64: str = Form(None),
+):
+    """
+    OCR 识别接口(支持图片和 PDF)
+    
+    - 图片:PNG/JPG/BMP/WebP/TIFF,自动预处理+识别
+    - PDF:逐页提取图片识别,返回每页结果
+    - 结果缓存:相同文件秒返回
+    """
+    if not file and not image_base64:
+        raise HTTPException(status_code=400, detail="请上传图片(file)或提供 base64 编码(image_base64)")
+
+    img_bytes = None
+    if file:
+        img_bytes = await file.read()
+        if len(img_bytes) == 0:
+            raise HTTPException(status_code=400, detail="上传文件为空")
+        if len(img_bytes) > MAX_UPLOAD_SIZE:
+            raise HTTPException(status_code=400, detail=f"文件过大,最大支持 {MAX_UPLOAD_SIZE // 1024 // 1024}MB")
+    elif image_base64:
+        try:
+            img_bytes = base64.b64decode(image_base64)
+        except Exception:
+            raise HTTPException(status_code=400, detail="base64 解码失败")
+        if len(img_bytes) > MAX_UPLOAD_SIZE:
+            raise HTTPException(status_code=400, detail=f"图片过大,最大支持 {MAX_UPLOAD_SIZE // 1024 // 1024}MB")
+
+    # ---- 缓存检查 ----
+    cache_key = file_hash(img_bytes)
+    cached = result_cache.get(cache_key)
+    if cached is not None:
+        cached["cached"] = True
+        return JSONResponse(cached)
+
+    # ---- PDF 处理 ----
+    if is_pdf(img_bytes):
+        return await _handle_pdf(img_bytes, cache_key)
+
+    # ---- 图片处理 ----
+    total_start = time.time()
+    try:
+        img_array, orig_w, orig_h, preprocess_steps = preprocess_image(img_bytes)
+    except Exception as e:
+        raise HTTPException(status_code=400, detail=f"图片解析失败: {str(e)}")
+
+    preprocess_elapsed = round(time.time() - total_start, 3)
+    lines, text, elapsed, timing = do_ocr(img_array)
+    total_elapsed = round(time.time() - total_start, 3)
+
+    resp = {
+        "success": True,
+        "text": text,
+        "lines": lines,
+        "line_count": len(lines),
+        "original_size": f"{orig_w}x{orig_h}",
+        "preprocess_seconds": preprocess_elapsed,
+        "ocr_seconds": elapsed,
+        "elapsed_seconds": total_elapsed,
+        "timing": timing,
+    }
+    if preprocess_steps:
+        resp["preprocess_steps"] = preprocess_steps
+
+    # 写入缓存
+    result_cache.put(cache_key, resp.copy())
+    resp["cached"] = False
+
+    return JSONResponse(resp)
+
+
+async def _handle_pdf(data: bytes, cache_key: str):
+    """PDF 逐页 OCR 处理"""
+    images = pdf_to_images(data)
+    if images is None:
+        raise HTTPException(status_code=400, detail="PDF 解析失败:缺少依赖库(PyMuPDF 或 poppler)")
+
+    if len(images) == 0:
+        raise HTTPException(status_code=400, detail="PDF 无有效页面")
+
+    total_start = time.time()
+    pages_result = []
+    all_lines = []
+
+    for i, pil_img in enumerate(images):
+        if pil_img.mode != "RGB":
+            pil_img = pil_img.convert("RGB")
+        img_array = np.array(pil_img)
+
+        # 缩放大页(按总像素控制)
+        h, w = img_array.shape[:2]
+        if w * h > MAX_PIXELS:
+            scale = (MAX_PIXELS / (w * h)) ** 0.5
+            new_w, new_h = int(w * scale), int(h * scale)
+            pil_img = pil_img.resize((new_w, new_h), Image.LANCZOS)
+            img_array = np.array(pil_img)
+
+        lines, text, elapsed, _ = do_ocr(img_array)
+        all_lines.extend(lines)
+
+        pages_result.append({
+            "page": i + 1,
+            "text": text,
+            "line_count": len(lines),
+            "elapsed_seconds": elapsed,
+        })
+
+    total_elapsed = round(time.time() - total_start, 3)
+    full_text = "\n\n".join(
+        f"--- 第{p['page']}页 ---\n{p['text']}" for p in pages_result
+    )
+
+    resp = {
+        "success": True,
+        "type": "pdf",
+        "page_count": len(images),
+        "text": full_text,
+        "lines": all_lines,
+        "line_count": len(all_lines),
+        "pages": pages_result,
+        "elapsed_seconds": total_elapsed,
+    }
+
+    result_cache.put(cache_key, resp.copy())
+    resp["cached"] = False
+
+    return JSONResponse(resp)
+
+
+@app.post("/api/table")
+async def recognize_table_api(
+    file: UploadFile = File(None),
+    image_base64: str = Form(None),
+):
+    """
+    表格识别接口
+    识别图片中的表格结构,返回单元格内容
+    """
+    if not file and not image_base64:
+        raise HTTPException(status_code=400, detail="请上传图片(file)或提供 base64 编码(image_base64)")
+
+    img_bytes = None
+    if file:
+        img_bytes = await file.read()
+        if len(img_bytes) == 0:
+            raise HTTPException(status_code=400, detail="上传文件为空")
+    elif image_base64:
+        try:
+            img_bytes = base64.b64decode(image_base64)
+        except Exception:
+            raise HTTPException(status_code=400, detail="base64 解码失败")
+
+    # 缓存检查
+    cache_key = "table_" + file_hash(img_bytes)
+    cached = result_cache.get(cache_key)
+    if cached is not None:
+        cached["cached"] = True
+        return JSONResponse(cached)
+
+    try:
+        img_array, orig_w, orig_h, preprocess_steps = preprocess_image(img_bytes)
+    except Exception as e:
+        raise HTTPException(status_code=400, detail=f"图片解析失败: {str(e)}")
+
+    start = time.time()
+    table_result = recognize_table(img_array)
+    elapsed = round(time.time() - start, 3)
+
+    resp = {
+        "success": True,
+        "type": "table",
+        "text": table_result["text"],
+        "cells": table_result["cells"],
+        "cell_count": table_result["cell_count"],
+        "original_size": f"{orig_w}x{orig_h}",
+        "elapsed_seconds": elapsed,
+    }
+    if preprocess_steps:
+        resp["preprocess_steps"] = preprocess_steps
+
+    result_cache.put(cache_key, resp.copy())
+    resp["cached"] = False
+
+    return JSONResponse(resp)
+
+
+@app.get("/api/health")
+async def health():
+    return {"status": "ok"}
+
+
+@app.get("/api/cache/stats")
+async def cache_stats():
+    """查看缓存统计"""
+    return result_cache.stats()
+
+
+@app.delete("/api/cache")
+async def cache_clear():
+    """清空缓存"""
+    result_cache.cache.clear()
+    return {"success": True, "message": "缓存已清空"}

+ 36 - 0
config.yaml

@@ -0,0 +1,36 @@
+Global:
+    text_score: 0.5
+    use_det: true
+    use_cls: true
+    use_rec: true
+    print_verbose: false
+    min_height: 30
+    width_height_ratio: 8
+    max_side_len: 2560
+    min_side_len: 30
+    return_word_box: false
+Det:
+    inference_num_threads: 6
+    model_path: models/ch_PP-OCRv4_det_infer.onnx
+    limit_side_len: 480
+    limit_type: max
+    std: [ 0.5, 0.5, 0.5 ]
+    mean: [ 0.5, 0.5, 0.5 ]
+    thresh: 0.3
+    box_thresh: 0.5
+    max_candidates: 1000
+    unclip_ratio: 1.6
+    use_dilation: true
+    score_mode: fast
+Cls:
+    inference_num_threads: 6
+    model_path: models/ch_ppocr_mobile_v2.0_cls_infer.onnx
+    cls_image_shape: [3, 48, 192]
+    cls_batch_num: 8
+    cls_thresh: 0.9
+    label_list: ['0', '180']
+Rec:
+    inference_num_threads: 6
+    model_path: models/ch_PP-OCRv4_rec_infer.onnx
+    rec_img_shape: [3, 48, 320]
+    rec_batch_num: 6

+ 18 - 0
docker-compose.yml

@@ -0,0 +1,18 @@
+services:
+  ocr:
+    build: .
+    container_name: ocr-service
+    restart: unless-stopped
+    ports:
+      - "8082:8082"
+    environment:
+      - TZ=Asia/Shanghai
+    volumes:
+      - ocr-models:/root/.rapidocr
+    deploy:
+      resources:
+        limits:
+          memory: 4G
+
+volumes:
+  ocr-models:

+ 8 - 0
requirements.txt

@@ -0,0 +1,8 @@
+fastapi==0.115.0
+uvicorn[standard]==0.30.6
+python-multipart==0.0.9
+rapidocr_openvino
+Pillow==10.4.0
+opencv-python-headless==4.11.0.86
+PyMuPDF==1.25.3
+numpy<2