| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395 |
- 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": "缓存已清空"}
|