flat_ocr.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. # -*- coding: utf-8 -*-
  2. """
  3. flat_ocr.py - 平铺版 PaddleOCR (对 crops/ 里的评级标签条识别分行文本)
  4. 环境: paddleocr
  5. 输出: OUT/ocr_result.json
  6. """
  7. import os, sys, json, time, datetime
  8. sys.stdout.reconfigure(encoding="utf-8")
  9. OUT = os.environ.get("OUT_DIR", "/home/martin/顾工交接/wzj/_infer_out")
  10. RECORDS = os.path.join(OUT, "crop_records.json")
  11. print("[OCR] 初始化 PaddleOCR ...")
  12. from paddleocr import PaddleOCR
  13. _t = time.perf_counter()
  14. ocr = PaddleOCR(use_doc_orientation_classify=True, use_doc_unwarping=False,
  15. use_textline_orientation=True)
  16. t_load = time.perf_counter() - _t
  17. print(f"[OCR] 加载完成 ({t_load:.2f}s)\n")
  18. records = json.load(open(RECORDS, encoding="utf-8"))
  19. ocr_results = {}
  20. t_ocr = 0.0
  21. _t_all = time.perf_counter()
  22. for i, rec in enumerate(records):
  23. name = rec["file"]; cp = rec["crop_path"]
  24. try:
  25. _t = time.perf_counter()
  26. result = ocr.predict(cp)
  27. t_ocr += time.perf_counter() - _t
  28. except Exception as e:
  29. ocr_results[name] = {"lines": [], "error": str(e)}; continue
  30. lines = []
  31. for res in result:
  32. if isinstance(res, dict):
  33. t = res.get("rec_texts")
  34. if t: lines.extend(list(t))
  35. elif hasattr(res, "rec_texts") and res.rec_texts:
  36. lines.extend(list(res.rec_texts))
  37. ocr_results[name] = {"lines": lines, "text": " | ".join(lines)}
  38. if (i + 1) % 200 == 0:
  39. print(f" [{i+1}/{len(records)}] 完成", flush=True)
  40. json.dump(ocr_results, open(os.path.join(OUT, "ocr_result.json"), "w", encoding="utf-8"),
  41. ensure_ascii=False, indent=2)
  42. n = max(len(records), 1); t_all = time.perf_counter() - _t_all
  43. print(f"\n[OCR] 完成 {n} 张")
  44. print("=" * 50)
  45. print(f"⏱ flat_ocr (PaddleOCR) | {n} 张")
  46. print(f" 加载 {t_load:.2f}s | OCR推理 {t_ocr:.2f}s (均{t_ocr/n*1000:.1f}ms) | 总 {t_all:.2f}s ({n/t_all:.2f}张/s)")
  47. print("=" * 50)
  48. with open(os.path.join(OUT, "timing.log"), "a", encoding="utf-8") as lf:
  49. lf.write(f"\n[{datetime.datetime.now():%Y-%m-%d %H:%M:%S}] === 步骤② flat_ocr.py (PaddleOCR 评级标签) ===\n")
  50. lf.write(f" 样本 {n} 张\n")
  51. lf.write(f" PaddleOCR 加载 : {t_load:.2f}s\n")
  52. lf.write(f" OCR 推理累计 : {t_ocr:.2f}s (均 {t_ocr/n*1000:.1f} ms/张)\n")
  53. lf.write(f" 总耗时 : {t_all:.2f}s (均 {t_all/n*1000:.1f} ms/张, 吞吐 {n/t_all:.2f} 张/s)\n")
  54. print(f"✓ 输出: {OUT}/ocr_result.json | 计时→ timing.log")