app.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. import os
  2. import io
  3. import time
  4. import base64
  5. import hashlib
  6. import threading
  7. from collections import OrderedDict
  8. from typing import Optional
  9. from fastapi import FastAPI, File, UploadFile, Form, HTTPException, Query
  10. from fastapi.middleware.cors import CORSMiddleware
  11. from fastapi.responses import JSONResponse
  12. from rapidocr_openvino import RapidOCR
  13. import cv2
  14. import numpy as np
  15. from PIL import Image
  16. app = FastAPI(title="OCR Service", description="RapidOCR 图片文字识别服务")
  17. app.add_middleware(
  18. CORSMiddleware,
  19. allow_origins=["*"],
  20. allow_methods=["*"],
  21. allow_headers=["*"],
  22. )
  23. MAX_UPLOAD_SIZE = 30 * 1024 * 1024
  24. MAX_IMAGE_DIM = 2560
  25. MAX_PIXELS = 2560 * 2560 # 最大总像素,超过才缩放
  26. # ==================== OCR 引擎 ====================
  27. ocr_engine = RapidOCR(config_path="config.yaml")
  28. ocr_lock = threading.Lock()
  29. # ==================== 结果缓存(LRU,最多 500 条) ====================
  30. class LRUCache:
  31. """简单线程安全 LRU 缓存"""
  32. def __init__(self, maxsize=500):
  33. self.maxsize = maxsize
  34. self.cache = OrderedDict()
  35. self.lock = threading.Lock()
  36. self.hits = 0
  37. self.misses = 0
  38. def get(self, key):
  39. with self.lock:
  40. if key in self.cache:
  41. self.cache.move_to_end(key)
  42. self.hits += 1
  43. return self.cache[key]
  44. self.misses += 1
  45. return None
  46. def put(self, key, value):
  47. with self.lock:
  48. if key in self.cache:
  49. self.cache.move_to_end(key)
  50. else:
  51. self.cache[key] = value
  52. if len(self.cache) > self.maxsize:
  53. self.cache.popitem(last=False)
  54. def stats(self):
  55. with self.lock:
  56. total = self.hits + self.misses
  57. hit_rate = round(self.hits / total * 100, 1) if total > 0 else 0
  58. return {"size": len(self.cache), "max_size": self.maxsize,
  59. "hits": self.hits, "misses": self.misses, "hit_rate": f"{hit_rate}%"}
  60. result_cache = LRUCache(maxsize=500)
  61. def file_hash(data: bytes) -> str:
  62. """计算文件 SHA256 哈希(用于缓存 key)"""
  63. return hashlib.sha256(data).hexdigest()[:32]
  64. # ==================== PDF 支持 ====================
  65. def is_pdf(data: bytes) -> bool:
  66. """通过文件头判断是否为 PDF"""
  67. return data[:5] == b"%PDF-"
  68. def pdf_to_images(data: bytes) -> list:
  69. """
  70. 将 PDF 每页转为 PIL Image 列表。
  71. 优先用 PyMuPDF(fitz),不可用则回退 pdf2image。
  72. """
  73. images = []
  74. # 方式1:PyMuPDF(纯 Python,无需系统依赖)
  75. try:
  76. import fitz # PyMuPDF
  77. doc = fitz.open(stream=data, filetype="pdf")
  78. for page_num in range(len(doc)):
  79. page = doc[page_num]
  80. # 渲染为图片(300 DPI 保证清晰度)
  81. mat = fitz.Matrix(300 / 72, 300 / 72)
  82. pix = page.get_pixmap(matrix=mat)
  83. img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
  84. images.append(img)
  85. doc.close()
  86. return images
  87. except ImportError:
  88. pass
  89. # 方式2:pdf2image(需要系统装 poppler)
  90. try:
  91. from pdf2image import convert_from_bytes
  92. images = convert_from_bytes(data, dpi=300)
  93. return images
  94. except Exception:
  95. pass
  96. return None # 两种方式都不可用
  97. # ==================== 表格识别 ====================
  98. def recognize_table(img_array):
  99. """
  100. 使用 OCR 识别表格区域,返回单元格内容
  101. (RapidOCR 无表格结构识别,仅返回文字识别结果,保持接口兼容)
  102. """
  103. lines, text, _, _ = do_ocr(img_array)
  104. cells = []
  105. for line in lines:
  106. cells.append({
  107. "text": line["text"],
  108. "confidence": line["confidence"],
  109. "box": line["box"],
  110. })
  111. return {
  112. "cells": cells,
  113. "cell_count": len(cells),
  114. "text": text,
  115. }
  116. # ==================== 图片预处理 ====================
  117. def preprocess_image(img_bytes: bytes) -> tuple:
  118. """仅做格式转换,不做图像处理。让 OCR 引擎自己处理最佳。"""
  119. image = Image.open(io.BytesIO(img_bytes))
  120. orig_w, orig_h = image.size
  121. if image.mode != "RGB":
  122. image = image.convert("RGB")
  123. img = np.array(image)
  124. return img, orig_w, orig_h, []
  125. def do_ocr(img_array) -> tuple:
  126. """执行 OCR 并返回 (lines, text, elapsed, timing)"""
  127. start = time.time()
  128. with ocr_lock:
  129. result, elapse_list = ocr_engine(img_array)
  130. elapsed = round(time.time() - start, 3)
  131. lines = []
  132. text_parts = []
  133. if result:
  134. for item in result:
  135. box, text, confidence = item
  136. lines.append({
  137. "text": text,
  138. "confidence": round(confidence, 4),
  139. "box": box,
  140. })
  141. text_parts.append(text)
  142. # elapse_list = [det_time, cls_time, rec_time]
  143. timing = {}
  144. if elapse_list:
  145. if len(elapse_list) >= 3:
  146. timing = {"det": elapse_list[0], "cls": elapse_list[1], "rec": elapse_list[2]}
  147. elif len(elapse_list) >= 1:
  148. timing = {"det": elapse_list[0], "cls": 0, "rec": 0}
  149. return lines, "\n".join(text_parts), elapsed, timing
  150. # ==================== 接口 ====================
  151. @app.get("/")
  152. async def index():
  153. return {"service": "OCR Service", "status": "running", "engine": "RapidOCR"}
  154. @app.post("/api/ocr")
  155. async def recognize_text(
  156. file: UploadFile = File(None),
  157. image_base64: str = Form(None),
  158. ):
  159. """
  160. OCR 识别接口(支持图片和 PDF)
  161. - 图片:PNG/JPG/BMP/WebP/TIFF,自动预处理+识别
  162. - PDF:逐页提取图片识别,返回每页结果
  163. - 结果缓存:相同文件秒返回
  164. """
  165. if not file and not image_base64:
  166. raise HTTPException(status_code=400, detail="请上传图片(file)或提供 base64 编码(image_base64)")
  167. img_bytes = None
  168. if file:
  169. img_bytes = await file.read()
  170. if len(img_bytes) == 0:
  171. raise HTTPException(status_code=400, detail="上传文件为空")
  172. if len(img_bytes) > MAX_UPLOAD_SIZE:
  173. raise HTTPException(status_code=400, detail=f"文件过大,最大支持 {MAX_UPLOAD_SIZE // 1024 // 1024}MB")
  174. elif image_base64:
  175. try:
  176. img_bytes = base64.b64decode(image_base64)
  177. except Exception:
  178. raise HTTPException(status_code=400, detail="base64 解码失败")
  179. if len(img_bytes) > MAX_UPLOAD_SIZE:
  180. raise HTTPException(status_code=400, detail=f"图片过大,最大支持 {MAX_UPLOAD_SIZE // 1024 // 1024}MB")
  181. # ---- 缓存检查 ----
  182. cache_key = file_hash(img_bytes)
  183. cached = result_cache.get(cache_key)
  184. if cached is not None:
  185. cached["cached"] = True
  186. return JSONResponse(cached)
  187. # ---- PDF 处理 ----
  188. if is_pdf(img_bytes):
  189. return await _handle_pdf(img_bytes, cache_key)
  190. # ---- 图片处理 ----
  191. total_start = time.time()
  192. try:
  193. img_array, orig_w, orig_h, preprocess_steps = preprocess_image(img_bytes)
  194. except Exception as e:
  195. raise HTTPException(status_code=400, detail=f"图片解析失败: {str(e)}")
  196. preprocess_elapsed = round(time.time() - total_start, 3)
  197. lines, text, elapsed, timing = do_ocr(img_array)
  198. total_elapsed = round(time.time() - total_start, 3)
  199. resp = {
  200. "success": True,
  201. "text": text,
  202. "lines": lines,
  203. "line_count": len(lines),
  204. "original_size": f"{orig_w}x{orig_h}",
  205. "preprocess_seconds": preprocess_elapsed,
  206. "ocr_seconds": elapsed,
  207. "elapsed_seconds": total_elapsed,
  208. "timing": timing,
  209. }
  210. if preprocess_steps:
  211. resp["preprocess_steps"] = preprocess_steps
  212. # 写入缓存
  213. result_cache.put(cache_key, resp.copy())
  214. resp["cached"] = False
  215. return JSONResponse(resp)
  216. async def _handle_pdf(data: bytes, cache_key: str):
  217. """PDF 逐页 OCR 处理"""
  218. images = pdf_to_images(data)
  219. if images is None:
  220. raise HTTPException(status_code=400, detail="PDF 解析失败:缺少依赖库(PyMuPDF 或 poppler)")
  221. if len(images) == 0:
  222. raise HTTPException(status_code=400, detail="PDF 无有效页面")
  223. total_start = time.time()
  224. pages_result = []
  225. all_lines = []
  226. for i, pil_img in enumerate(images):
  227. if pil_img.mode != "RGB":
  228. pil_img = pil_img.convert("RGB")
  229. img_array = np.array(pil_img)
  230. # 缩放大页(按总像素控制)
  231. h, w = img_array.shape[:2]
  232. if w * h > MAX_PIXELS:
  233. scale = (MAX_PIXELS / (w * h)) ** 0.5
  234. new_w, new_h = int(w * scale), int(h * scale)
  235. pil_img = pil_img.resize((new_w, new_h), Image.LANCZOS)
  236. img_array = np.array(pil_img)
  237. lines, text, elapsed, _ = do_ocr(img_array)
  238. all_lines.extend(lines)
  239. pages_result.append({
  240. "page": i + 1,
  241. "text": text,
  242. "line_count": len(lines),
  243. "elapsed_seconds": elapsed,
  244. })
  245. total_elapsed = round(time.time() - total_start, 3)
  246. full_text = "\n\n".join(
  247. f"--- 第{p['page']}页 ---\n{p['text']}" for p in pages_result
  248. )
  249. resp = {
  250. "success": True,
  251. "type": "pdf",
  252. "page_count": len(images),
  253. "text": full_text,
  254. "lines": all_lines,
  255. "line_count": len(all_lines),
  256. "pages": pages_result,
  257. "elapsed_seconds": total_elapsed,
  258. }
  259. result_cache.put(cache_key, resp.copy())
  260. resp["cached"] = False
  261. return JSONResponse(resp)
  262. @app.post("/api/table")
  263. async def recognize_table_api(
  264. file: UploadFile = File(None),
  265. image_base64: str = Form(None),
  266. ):
  267. """
  268. 表格识别接口
  269. 识别图片中的表格结构,返回单元格内容
  270. """
  271. if not file and not image_base64:
  272. raise HTTPException(status_code=400, detail="请上传图片(file)或提供 base64 编码(image_base64)")
  273. img_bytes = None
  274. if file:
  275. img_bytes = await file.read()
  276. if len(img_bytes) == 0:
  277. raise HTTPException(status_code=400, detail="上传文件为空")
  278. elif image_base64:
  279. try:
  280. img_bytes = base64.b64decode(image_base64)
  281. except Exception:
  282. raise HTTPException(status_code=400, detail="base64 解码失败")
  283. # 缓存检查
  284. cache_key = "table_" + file_hash(img_bytes)
  285. cached = result_cache.get(cache_key)
  286. if cached is not None:
  287. cached["cached"] = True
  288. return JSONResponse(cached)
  289. try:
  290. img_array, orig_w, orig_h, preprocess_steps = preprocess_image(img_bytes)
  291. except Exception as e:
  292. raise HTTPException(status_code=400, detail=f"图片解析失败: {str(e)}")
  293. start = time.time()
  294. table_result = recognize_table(img_array)
  295. elapsed = round(time.time() - start, 3)
  296. resp = {
  297. "success": True,
  298. "type": "table",
  299. "text": table_result["text"],
  300. "cells": table_result["cells"],
  301. "cell_count": table_result["cell_count"],
  302. "original_size": f"{orig_w}x{orig_h}",
  303. "elapsed_seconds": elapsed,
  304. }
  305. if preprocess_steps:
  306. resp["preprocess_steps"] = preprocess_steps
  307. result_cache.put(cache_key, resp.copy())
  308. resp["cached"] = False
  309. return JSONResponse(resp)
  310. @app.get("/api/health")
  311. async def health():
  312. return {"status": "ok"}
  313. @app.get("/api/cache/stats")
  314. async def cache_stats():
  315. """查看缓存统计"""
  316. return result_cache.stats()
  317. @app.delete("/api/cache")
  318. async def cache_clear():
  319. """清空缓存"""
  320. result_cache.cache.clear()
  321. return {"success": True, "message": "缓存已清空"}