Spaces:
Sleeping
Sleeping
Harry Pham commited on
Commit ·
f69131e
1
Parent(s): 1813932
update OCR
Browse files- src/inference.py +614 -275
src/inference.py
CHANGED
|
@@ -1,315 +1,665 @@
|
|
| 1 |
# src/inference.py
|
| 2 |
-
# ── Patch torch.load — DÒNG ĐẦU TIÊN ──────────────────────
|
| 3 |
import torch
|
| 4 |
_orig_torch_load = torch.load
|
| 5 |
def _patched_load(*args, **kwargs):
|
| 6 |
kwargs.setdefault("weights_only", False)
|
| 7 |
return _orig_torch_load(*args, **kwargs)
|
| 8 |
torch.load = _patched_load
|
| 9 |
-
# ───────────────────────────────────────────────────────────
|
| 10 |
|
| 11 |
import cv2
|
| 12 |
import json
|
| 13 |
import numpy as np
|
| 14 |
from pathlib import Path
|
| 15 |
-
from PIL import Image
|
| 16 |
from ultralytics import RTDETR
|
|
|
|
| 17 |
|
| 18 |
-
# ── Device ──────────────────────────────────────────────────
|
| 19 |
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
| 20 |
print(f"[INFO] Device: {DEVICE}")
|
| 21 |
|
| 22 |
-
# ── Class config ─────────────────────────────────────────────
|
| 23 |
CLASS_NAMES = ["note", "part-drawing", "table"]
|
| 24 |
-
CLASS_DISPLAY = {
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
# DETECTION MODEL
|
| 37 |
-
# ─────────────────────────────────────────────────────────────
|
| 38 |
-
_det_model = None
|
| 39 |
-
|
| 40 |
-
def get_det_model(checkpoint: str = "best.pt") -> RTDETR:
|
| 41 |
global _det_model
|
| 42 |
if _det_model is None:
|
| 43 |
-
print(f"[INFO] Loading
|
| 44 |
_det_model = RTDETR(checkpoint)
|
| 45 |
return _det_model
|
| 46 |
|
| 47 |
|
| 48 |
-
|
| 49 |
-
# TrOCR — engine chính cho handwritten text
|
| 50 |
-
# microsoft/trocr-large-handwritten (tốt nhất, ~1.3GB)
|
| 51 |
-
# microsoft/trocr-base-handwritten (nhỏ hơn, ~400MB)
|
| 52 |
-
# ─────────────────────────────────────────────────────────────
|
| 53 |
-
_trocr_processor = None
|
| 54 |
-
_trocr_model = None
|
| 55 |
-
TROCR_MODEL_ID = "microsoft/trocr-large-handwritten"
|
| 56 |
-
|
| 57 |
-
def get_trocr():
|
| 58 |
-
global _trocr_processor, _trocr_model
|
| 59 |
-
if _trocr_processor is None:
|
| 60 |
-
from transformers import TrOCRProcessor, VisionEncoderDecoderModel
|
| 61 |
-
print(f"[INFO] Loading TrOCR ({TROCR_MODEL_ID})...")
|
| 62 |
-
_trocr_processor = TrOCRProcessor.from_pretrained(TROCR_MODEL_ID)
|
| 63 |
-
_trocr_model = VisionEncoderDecoderModel.from_pretrained(TROCR_MODEL_ID)
|
| 64 |
-
_trocr_model.to(DEVICE)
|
| 65 |
-
_trocr_model.eval()
|
| 66 |
-
print("[INFO] TrOCR ready.")
|
| 67 |
-
return _trocr_processor, _trocr_model
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
def trocr_predict_line(pil_img: Image.Image) -> str:
|
| 71 |
"""
|
| 72 |
-
|
| 73 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
"""
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
)
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
|
| 88 |
-
# ─────────────────────────────────────────────────────────────
|
| 89 |
-
# EasyOCR — fallback + text detection (tìm vị trí dòng text)
|
| 90 |
-
# ─────────────────────────────────────────────────────────────
|
| 91 |
-
_easy_reader = None
|
| 92 |
|
| 93 |
-
def
|
| 94 |
-
global
|
| 95 |
-
if
|
| 96 |
import easyocr
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
|
|
|
| 100 |
|
| 101 |
|
| 102 |
-
#
|
| 103 |
-
# PREPROCESSING
|
| 104 |
-
#
|
| 105 |
-
def preprocess_for_ocr(img_bgr
|
| 106 |
-
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 107 |
h, w = img_bgr.shape[:2]
|
| 108 |
-
|
| 109 |
-
#
|
| 110 |
-
if w <
|
| 111 |
-
scale
|
| 112 |
-
img_bgr = cv2.resize(img_bgr,
|
| 113 |
-
(int(w * scale), int(h * scale)),
|
| 114 |
interpolation=cv2.INTER_CUBIC)
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 133 |
"""
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
Trả về list of (pil_crop, bbox, easy_text, easy_conf).
|
| 137 |
"""
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
)
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 176 |
|
| 177 |
|
| 178 |
-
|
| 179 |
-
# OCR PIPELINE: kết hợp EasyOCR detect + TrOCR recognize
|
| 180 |
-
# ─────────────────────────────────────────────────────────────
|
| 181 |
-
def hybrid_ocr_lines(img_bgr: np.ndarray, conf_threshold: float = 0.3) -> list:
|
| 182 |
"""
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
"""
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
|
|
|
| 194 |
try:
|
| 195 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 196 |
except Exception as e:
|
| 197 |
-
print(f"
|
|
|
|
|
|
|
|
|
|
| 198 |
|
| 199 |
-
# Chọn text tốt hơn giữa TrOCR và EasyOCR
|
| 200 |
-
# TrOCR ưu tiên nếu có output đủ dài
|
| 201 |
-
if len(trocr_text) >= max(2, len(lc["easy_text"]) * 0.4):
|
| 202 |
-
final_text = trocr_text
|
| 203 |
-
else:
|
| 204 |
-
final_text = lc["easy_text"]
|
| 205 |
|
| 206 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 207 |
items.append({
|
| 208 |
-
"text":
|
| 209 |
-
"
|
| 210 |
-
"
|
|
|
|
|
|
|
| 211 |
})
|
| 212 |
-
|
| 213 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 214 |
|
| 215 |
|
| 216 |
-
#
|
| 217 |
-
#
|
| 218 |
-
#
|
| 219 |
-
def
|
| 220 |
-
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 221 |
if not items:
|
| 222 |
return []
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
if len(y_vals) > 1:
|
| 228 |
-
gaps
|
| 229 |
-
|
|
|
|
| 230 |
else:
|
| 231 |
thresh = 12
|
| 232 |
-
|
| 233 |
-
rows
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
|
|
|
| 237 |
else:
|
| 238 |
-
|
| 239 |
-
rows.append(
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
return rows
|
| 245 |
|
| 246 |
|
| 247 |
-
#
|
| 248 |
-
# PUBLIC OCR FUNCTIONS
|
| 249 |
-
# ─────────────────────────────────────────────────────────────
|
| 250 |
-
def ocr_note(img_path: str) -> str:
|
| 251 |
-
"""OCR vùng Note → plain text, preserve line order."""
|
| 252 |
-
img = cv2.imread(img_path)
|
| 253 |
-
if img is None:
|
| 254 |
-
return ""
|
| 255 |
-
|
| 256 |
-
items = hybrid_ocr_lines(img)
|
| 257 |
-
# Sắp xếp theo y (trên xuống dưới), x (trái sang phải)
|
| 258 |
-
items.sort(key=lambda x: (round(x["y"] / 15), x["x"]))
|
| 259 |
-
return "\n".join(it["text"] for it in items)
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
def ocr_table(img_path: str) -> dict:
|
| 263 |
-
"""OCR vùng Table → giữ cấu trúc rows × cols."""
|
| 264 |
-
img = cv2.imread(img_path)
|
| 265 |
-
if img is None:
|
| 266 |
-
return {"rows": [], "text": ""}
|
| 267 |
-
|
| 268 |
-
items = hybrid_ocr_lines(img)
|
| 269 |
-
if not items:
|
| 270 |
-
return {"rows": [], "text": ""}
|
| 271 |
-
|
| 272 |
-
rows = group_into_rows(items)
|
| 273 |
-
text = "\n".join(" | ".join(r) for r in rows)
|
| 274 |
-
return {"rows": rows, "text": text}
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
# ─────────────────────────────────────────────────────────────
|
| 278 |
# MAIN PIPELINE
|
| 279 |
-
#
|
| 280 |
-
def run_pipeline(
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
checkpoint: str = "best.pt",
|
| 284 |
-
conf_thresh: float = 0.3,
|
| 285 |
-
) -> tuple:
|
| 286 |
-
"""
|
| 287 |
-
Full pipeline: detect → crop → OCR → JSON + visualize.
|
| 288 |
-
Returns (result_dict, vis_image_path).
|
| 289 |
-
"""
|
| 290 |
image_path = str(image_path)
|
| 291 |
img_name = Path(image_path).name
|
| 292 |
stem = Path(image_path).stem
|
| 293 |
crop_dir = Path(output_dir) / stem / "crops"
|
| 294 |
crop_dir.mkdir(parents=True, exist_ok=True)
|
| 295 |
|
| 296 |
-
# 1. Detect
|
| 297 |
model = get_det_model(checkpoint)
|
| 298 |
-
results = model(
|
| 299 |
-
|
| 300 |
-
imgsz=1024,
|
| 301 |
-
conf=conf_thresh,
|
| 302 |
-
iou=0.5,
|
| 303 |
-
device=DEVICE,
|
| 304 |
-
verbose=False,
|
| 305 |
-
)
|
| 306 |
|
| 307 |
img_bgr = cv2.imread(image_path)
|
| 308 |
if img_bgr is None:
|
| 309 |
-
raise ValueError(f"Cannot read
|
| 310 |
|
| 311 |
objects = []
|
| 312 |
-
|
| 313 |
for i, box in enumerate(results[0].boxes):
|
| 314 |
x1, y1, x2, y2 = map(int, box.xyxy[0].tolist())
|
| 315 |
cls_idx = int(box.cls[0])
|
|
@@ -317,66 +667,55 @@ def run_pipeline(
|
|
| 317 |
cls_raw = CLASS_NAMES[cls_idx]
|
| 318 |
cls_show = CLASS_DISPLAY[cls_raw]
|
| 319 |
|
| 320 |
-
#
|
| 321 |
-
pad
|
| 322 |
-
crop = img_bgr[
|
| 323 |
-
|
| 324 |
-
max(0, x1 - pad): min(img_bgr.shape[1], x2 + pad),
|
| 325 |
-
]
|
| 326 |
crop_path = str(crop_dir / f"{cls_show}_{i+1}.jpg")
|
| 327 |
-
|
|
|
|
| 328 |
|
| 329 |
-
# 3. OCR
|
| 330 |
ocr_content = None
|
| 331 |
if cls_raw == "note":
|
| 332 |
-
print(f"[OCR] Note #{i+1}...")
|
| 333 |
-
ocr_content = ocr_note(crop_path)
|
| 334 |
-
print(f" → {repr(ocr_content[:
|
| 335 |
-
|
| 336 |
elif cls_raw == "table":
|
| 337 |
-
print(f"[OCR] Table #{i+1}...")
|
| 338 |
-
ocr_content = ocr_table(crop_path)
|
| 339 |
-
preview = ocr_content.get("text", "")[:
|
| 340 |
print(f" → {repr(preview) if preview else 'EMPTY'}")
|
| 341 |
|
| 342 |
objects.append({
|
| 343 |
-
"id":
|
| 344 |
-
"
|
| 345 |
-
"
|
| 346 |
-
"
|
| 347 |
-
"crop_path": crop_path,
|
| 348 |
"ocr_content": ocr_content,
|
| 349 |
})
|
| 350 |
|
| 351 |
-
# 4. Vẽ bbox
|
| 352 |
color = COLORS[cls_raw]
|
| 353 |
cv2.rectangle(img_bgr, (x1, y1), (x2, y2), color, 2)
|
| 354 |
label = f"{cls_show} {conf_val:.2f}"
|
| 355 |
-
(tw, th), _ = cv2.getTextSize(
|
| 356 |
-
|
| 357 |
-
cv2.
|
| 358 |
-
(x1, y1 - th - 10), (x1 + tw + 8, y1),
|
| 359 |
-
color, -1)
|
| 360 |
-
cv2.putText(img_bgr, label, (x1 + 4, y1 - 4),
|
| 361 |
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 2)
|
| 362 |
|
| 363 |
-
# 5. Lưu visualize
|
| 364 |
vis_path = str(Path(output_dir) / stem / "result_vis.jpg")
|
| 365 |
cv2.imwrite(vis_path, img_bgr)
|
| 366 |
|
| 367 |
-
# 6. Lưu JSON
|
| 368 |
result = {"image": img_name, "objects": objects}
|
| 369 |
json_path = str(Path(output_dir) / stem / "result.json")
|
| 370 |
with open(json_path, "w", encoding="utf-8") as f:
|
| 371 |
json.dump(result, f, ensure_ascii=False, indent=2)
|
| 372 |
|
| 373 |
-
print(f"
|
| 374 |
return result, vis_path
|
| 375 |
|
| 376 |
|
| 377 |
-
# ── CLI ──────────────────────────────────────────────────────
|
| 378 |
if __name__ == "__main__":
|
| 379 |
import sys
|
| 380 |
img = sys.argv[1] if len(sys.argv) > 1 else "test.jpg"
|
| 381 |
-
result, _ = run_pipeline(img)
|
| 382 |
print(json.dumps(result, ensure_ascii=False, indent=2))
|
|
|
|
| 1 |
# src/inference.py
|
|
|
|
| 2 |
import torch
|
| 3 |
_orig_torch_load = torch.load
|
| 4 |
def _patched_load(*args, **kwargs):
|
| 5 |
kwargs.setdefault("weights_only", False)
|
| 6 |
return _orig_torch_load(*args, **kwargs)
|
| 7 |
torch.load = _patched_load
|
|
|
|
| 8 |
|
| 9 |
import cv2
|
| 10 |
import json
|
| 11 |
import numpy as np
|
| 12 |
from pathlib import Path
|
|
|
|
| 13 |
from ultralytics import RTDETR
|
| 14 |
+
import re
|
| 15 |
|
|
|
|
| 16 |
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
| 17 |
print(f"[INFO] Device: {DEVICE}")
|
| 18 |
|
|
|
|
| 19 |
CLASS_NAMES = ["note", "part-drawing", "table"]
|
| 20 |
+
CLASS_DISPLAY = {"note": "Note", "part-drawing": "PartDrawing", "table": "Table"}
|
| 21 |
+
COLORS = {"note": (0,165,255), "part-drawing": (0,200,0), "table": (0,0,220)}
|
| 22 |
+
|
| 23 |
+
_det_model = None
|
| 24 |
+
_ocr_paddle = None
|
| 25 |
+
_ocr_paddle_en = None
|
| 26 |
+
_ocr_easyocr = None
|
| 27 |
+
|
| 28 |
+
# ============================================================
|
| 29 |
+
# MODEL LOADERS
|
| 30 |
+
# ============================================================
|
| 31 |
+
def get_det_model(checkpoint="best.pt"):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
global _det_model
|
| 33 |
if _det_model is None:
|
| 34 |
+
print(f"[INFO] Loading detection model: {checkpoint}")
|
| 35 |
_det_model = RTDETR(checkpoint)
|
| 36 |
return _det_model
|
| 37 |
|
| 38 |
|
| 39 |
+
def get_paddle_reader(lang='vi'):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
"""
|
| 41 |
+
PaddleOCR PP-OCRv4 — cải thiện chính:
|
| 42 |
+
- ocr_version='PP-OCRv4' (mới nhất, chính xác hơn v3)
|
| 43 |
+
- det_db_thresh thấp hơn → phát hiện chữ nhỏ/mờ
|
| 44 |
+
- det_db_unclip_ratio lớn hơn → box chữ rộng hơn, không cắt dấu
|
| 45 |
+
- use_dilation=True → kết nối các phần chữ bị đứt
|
| 46 |
+
- det_db_score_mode='slow' → chính xác hơn 'fast'
|
| 47 |
"""
|
| 48 |
+
global _ocr_paddle, _ocr_paddle_en
|
| 49 |
+
|
| 50 |
+
if lang == 'en':
|
| 51 |
+
if _ocr_paddle_en is not None:
|
| 52 |
+
return _ocr_paddle_en
|
| 53 |
+
else:
|
| 54 |
+
if _ocr_paddle is not None:
|
| 55 |
+
return _ocr_paddle
|
| 56 |
+
|
| 57 |
+
try:
|
| 58 |
+
from paddleocr import PaddleOCR
|
| 59 |
+
print(f"[INFO] Initializing PaddleOCR PP-OCRv4 (lang={lang})...")
|
| 60 |
+
reader = PaddleOCR(
|
| 61 |
+
lang=lang,
|
| 62 |
+
use_angle_cls=True,
|
| 63 |
+
use_gpu=(DEVICE == "cuda"),
|
| 64 |
+
show_log=False,
|
| 65 |
+
ocr_version='PP-OCRv4', # ← KEY: dùng v4
|
| 66 |
+
det_db_thresh=0.15, # ← giảm để phát hiện chữ mờ
|
| 67 |
+
det_db_box_thresh=0.2, # ← giảm
|
| 68 |
+
det_db_unclip_ratio=2.0, # ← tăng để không cắt dấu tiếng Việt
|
| 69 |
+
use_dilation=True, # ← kết nối chữ bị đứt
|
| 70 |
+
det_db_score_mode='slow', # ← chính xác hơn
|
| 71 |
+
rec_image_shape="3,48,320",
|
| 72 |
+
max_text_length=80,
|
| 73 |
+
rec_batch_num=6,
|
| 74 |
)
|
| 75 |
+
if lang == 'en':
|
| 76 |
+
_ocr_paddle_en = reader
|
| 77 |
+
else:
|
| 78 |
+
_ocr_paddle = reader
|
| 79 |
+
return reader
|
| 80 |
+
except Exception as e:
|
| 81 |
+
print(f"[WARN] PaddleOCR init failed: {e}")
|
| 82 |
+
return None
|
| 83 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 84 |
|
| 85 |
+
def get_easyocr_reader():
|
| 86 |
+
global _ocr_easyocr
|
| 87 |
+
if _ocr_easyocr is None:
|
| 88 |
import easyocr
|
| 89 |
+
_ocr_easyocr = easyocr.Reader(
|
| 90 |
+
["vi", "en"], gpu=(DEVICE == "cuda"), verbose=False
|
| 91 |
+
)
|
| 92 |
+
return _ocr_easyocr
|
| 93 |
|
| 94 |
|
| 95 |
+
# ============================================================
|
| 96 |
+
# PREPROCESSING — Nguyên tắc: UPSCALE MẠNH, XỬ LÝ NHẸ
|
| 97 |
+
# ============================================================
|
| 98 |
+
def preprocess_for_ocr(img_bgr, min_width=1500, mode="note"):
|
| 99 |
+
"""
|
| 100 |
+
Tiền xử lý cho OCR trên bản vẽ kỹ thuật.
|
| 101 |
+
|
| 102 |
+
THAY ĐỔI QUAN TRỌNG so với bản cũ:
|
| 103 |
+
1. Upscale mạnh hơn (min 1500px thay vì 800px)
|
| 104 |
+
2. KHÔNG convert sang grayscale rồi threshold → phá hủy dấu tiếng Việt
|
| 105 |
+
3. Dùng CLAHE trên kênh L (LAB) → giữ nguyên cấu trúc ảnh
|
| 106 |
+
4. Bilateral filter thay vì fastNlMeansDenoising → giữ edge tốt hơn
|
| 107 |
+
5. Sharpening nhẹ hơn nhiều
|
| 108 |
+
"""
|
| 109 |
h, w = img_bgr.shape[:2]
|
| 110 |
+
|
| 111 |
+
# === BƯỚC 1: UPSCALE MẠNH (quan trọng nhất!) ===
|
| 112 |
+
if w < min_width:
|
| 113 |
+
scale = min_width / w
|
| 114 |
+
img_bgr = cv2.resize(img_bgr, None, fx=scale, fy=scale,
|
|
|
|
| 115 |
interpolation=cv2.INTER_CUBIC)
|
| 116 |
+
h, w = img_bgr.shape[:2]
|
| 117 |
+
|
| 118 |
+
if mode == "note":
|
| 119 |
+
# === BƯỚC 2: Gentle denoising (giữ edge, giữ dấu) ===
|
| 120 |
+
img_proc = cv2.bilateralFilter(img_bgr, 9, 75, 75)
|
| 121 |
+
|
| 122 |
+
# === BƯỚC 3: CLAHE trên kênh L (LAB colorspace) ===
|
| 123 |
+
# Không convert grayscale → giữ info cho PaddleOCR
|
| 124 |
+
lab = cv2.cvtColor(img_proc, cv2.COLOR_BGR2LAB)
|
| 125 |
+
l, a, b = cv2.split(lab)
|
| 126 |
+
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
|
| 127 |
+
l = clahe.apply(l)
|
| 128 |
+
lab = cv2.merge([l, a, b])
|
| 129 |
+
img_proc = cv2.cvtColor(lab, cv2.COLOR_LAB2BGR)
|
| 130 |
+
|
| 131 |
+
# === BƯỚC 4: Sharpening NHẸ (không dùng kernel quá mạnh) ===
|
| 132 |
+
# Kernel cũ [-1,-1,-1; -1,9,-1; -1,-1,-1] quá mạnh → tạo artifact
|
| 133 |
+
kernel = np.array([[0, -0.5, 0],
|
| 134 |
+
[-0.5, 3, -0.5],
|
| 135 |
+
[0, -0.5, 0]])
|
| 136 |
+
img_proc = cv2.filter2D(img_proc, -1, kernel)
|
| 137 |
+
|
| 138 |
+
return img_proc
|
| 139 |
+
|
| 140 |
+
else: # table
|
| 141 |
+
# Với table: tăng contrast mạnh hơn, nhưng vẫn giữ BGR
|
| 142 |
+
img_proc = cv2.bilateralFilter(img_bgr, 11, 80, 80)
|
| 143 |
+
|
| 144 |
+
lab = cv2.cvtColor(img_proc, cv2.COLOR_BGR2LAB)
|
| 145 |
+
l, a, b = cv2.split(lab)
|
| 146 |
+
clahe = cv2.createCLAHE(clipLimit=3.0, tileGridSize=(4, 4))
|
| 147 |
+
l = clahe.apply(l)
|
| 148 |
+
lab = cv2.merge([l, a, b])
|
| 149 |
+
img_proc = cv2.cvtColor(lab, cv2.COLOR_LAB2BGR)
|
| 150 |
+
|
| 151 |
+
return img_proc
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def preprocess_grayscale_variant(img_bgr, min_width=1500):
|
| 155 |
"""
|
| 156 |
+
Biến thể grayscale để dùng trong multi-pass OCR.
|
| 157 |
+
Chỉ dùng Otsu thay vì adaptive threshold → ít artifact hơn.
|
|
|
|
| 158 |
"""
|
| 159 |
+
h, w = img_bgr.shape[:2]
|
| 160 |
+
if w < min_width:
|
| 161 |
+
scale = min_width / w
|
| 162 |
+
img_bgr = cv2.resize(img_bgr, None, fx=scale, fy=scale,
|
| 163 |
+
interpolation=cv2.INTER_CUBIC)
|
| 164 |
+
|
| 165 |
+
gray = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2GRAY)
|
| 166 |
+
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
|
| 167 |
+
gray = clahe.apply(gray)
|
| 168 |
+
# Otsu threshold — tự động chọn ngưỡng tối ưu
|
| 169 |
+
_, binary = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
|
| 170 |
+
return cv2.cvtColor(binary, cv2.COLOR_GRAY2BGR)
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
# ============================================================
|
| 174 |
+
# MULTI-PASS OCR — Thử nhiều cách, chọn kết quả tốt nhất
|
| 175 |
+
# ============================================================
|
| 176 |
+
def ocr_single_pass(reader, img_bgr):
|
| 177 |
+
"""Chạy OCR 1 lần, trả về (texts, avg_confidence)."""
|
| 178 |
+
if hasattr(reader, 'ocr'): # PaddleOCR
|
| 179 |
+
result = reader.ocr(img_bgr, cls=True)
|
| 180 |
+
if not result or not result[0]:
|
| 181 |
+
return [], 0.0
|
| 182 |
+
texts = []
|
| 183 |
+
confs = []
|
| 184 |
+
for line in result[0]:
|
| 185 |
+
box, (text, conf) = line
|
| 186 |
+
if conf >= 0.2 and text.strip():
|
| 187 |
+
texts.append(text.strip())
|
| 188 |
+
confs.append(conf)
|
| 189 |
+
avg_conf = np.mean(confs) if confs else 0.0
|
| 190 |
+
return texts, avg_conf
|
| 191 |
+
else: # EasyOCR
|
| 192 |
+
results = reader.readtext(img_bgr, detail=1, paragraph=False)
|
| 193 |
+
texts = []
|
| 194 |
+
confs = []
|
| 195 |
+
for (pts, text, conf) in results:
|
| 196 |
+
if conf >= 0.15 and text.strip():
|
| 197 |
+
texts.append(text.strip())
|
| 198 |
+
confs.append(conf)
|
| 199 |
+
avg_conf = np.mean(confs) if confs else 0.0
|
| 200 |
+
return texts, avg_conf
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
def multi_pass_ocr(img_bgr, reader, ocr_type="note"):
|
| 204 |
+
"""
|
| 205 |
+
Multi-pass OCR: thử nhiều preprocessing, chọn kết quả confidence cao nhất.
|
| 206 |
+
|
| 207 |
+
Pass 1: Preprocessing nhẹ (CLAHE + bilateral) — tốt cho chữ rõ
|
| 208 |
+
Pass 2: Grayscale + Otsu — tốt cho chữ mờ trên nền phức tạp
|
| 209 |
+
Pass 3: Scale 2x thêm — tốt cho chữ rất nhỏ
|
| 210 |
+
"""
|
| 211 |
+
best_texts = []
|
| 212 |
+
best_conf = 0.0
|
| 213 |
+
|
| 214 |
+
# Pass 1: Color preprocessing (gentle)
|
| 215 |
+
img_v1 = preprocess_for_ocr(img_bgr, min_width=1500, mode=ocr_type)
|
| 216 |
+
texts1, conf1 = ocr_single_pass(reader, img_v1)
|
| 217 |
+
if conf1 > best_conf:
|
| 218 |
+
best_conf = conf1
|
| 219 |
+
best_texts = texts1
|
| 220 |
+
|
| 221 |
+
# Pass 2: Grayscale variant
|
| 222 |
+
img_v2 = preprocess_grayscale_variant(img_bgr, min_width=1500)
|
| 223 |
+
texts2, conf2 = ocr_single_pass(reader, img_v2)
|
| 224 |
+
if conf2 > best_conf:
|
| 225 |
+
best_conf = conf2
|
| 226 |
+
best_texts = texts2
|
| 227 |
+
|
| 228 |
+
# Pass 3: Extra upscale (2x more than pass 1)
|
| 229 |
+
img_v3 = preprocess_for_ocr(img_bgr, min_width=2500, mode=ocr_type)
|
| 230 |
+
texts3, conf3 = ocr_single_pass(reader, img_v3)
|
| 231 |
+
if conf3 > best_conf:
|
| 232 |
+
best_conf = conf3
|
| 233 |
+
best_texts = texts3
|
| 234 |
+
|
| 235 |
+
print(f" Multi-pass confidences: {conf1:.3f}, {conf2:.3f}, {conf3:.3f} → best={best_conf:.3f}")
|
| 236 |
+
return best_texts, best_conf
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
# ============================================================
|
| 240 |
+
# DUAL-ENGINE OCR — PaddleOCR (vi) + PaddleOCR (en), chọn tốt hơn
|
| 241 |
+
# ============================================================
|
| 242 |
+
def dual_engine_ocr(img_bgr, ocr_type="note"):
|
| 243 |
+
"""
|
| 244 |
+
Chạy PaddleOCR với cả lang='vi' và lang='en',
|
| 245 |
+
chọn kết quả có confidence cao hơn.
|
| 246 |
+
Nếu PaddleOCR fail → fallback EasyOCR.
|
| 247 |
+
"""
|
| 248 |
+
reader_vi = get_paddle_reader('vi')
|
| 249 |
+
reader_en = get_paddle_reader('en')
|
| 250 |
+
|
| 251 |
+
if reader_vi is None and reader_en is None:
|
| 252 |
+
# Fallback to EasyOCR
|
| 253 |
+
reader = get_easyocr_reader()
|
| 254 |
+
texts, conf = multi_pass_ocr(img_bgr, reader, ocr_type)
|
| 255 |
+
return texts, conf
|
| 256 |
+
|
| 257 |
+
best_texts = []
|
| 258 |
+
best_conf = 0.0
|
| 259 |
+
best_lang = ""
|
| 260 |
+
|
| 261 |
+
# Try Vietnamese
|
| 262 |
+
if reader_vi:
|
| 263 |
+
texts_vi, conf_vi = multi_pass_ocr(img_bgr, reader_vi, ocr_type)
|
| 264 |
+
if conf_vi > best_conf:
|
| 265 |
+
best_conf = conf_vi
|
| 266 |
+
best_texts = texts_vi
|
| 267 |
+
best_lang = "vi"
|
| 268 |
+
|
| 269 |
+
# Try English
|
| 270 |
+
if reader_en:
|
| 271 |
+
texts_en, conf_en = multi_pass_ocr(img_bgr, reader_en, ocr_type)
|
| 272 |
+
if conf_en > best_conf:
|
| 273 |
+
best_conf = conf_en
|
| 274 |
+
best_texts = texts_en
|
| 275 |
+
best_lang = "en"
|
| 276 |
+
|
| 277 |
+
print(f" Best language: {best_lang} (conf={best_conf:.3f})")
|
| 278 |
+
return best_texts, best_conf
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
# ============================================================
|
| 282 |
+
# POST-PROCESSING — Sửa lỗi OCR phổ biến
|
| 283 |
+
# ============================================================
|
| 284 |
+
def post_process_ocr_text(text):
|
| 285 |
+
"""
|
| 286 |
+
Sửa các lỗi OCR phổ biến trong bản vẽ kỹ thuật.
|
| 287 |
+
"""
|
| 288 |
+
if not text:
|
| 289 |
+
return text
|
| 290 |
+
|
| 291 |
+
# Fix: số 0 bị nhận thành O và ngược lại trong context kỹ thuật
|
| 292 |
+
# Ví dụ: "M1O" → "M10", "Ø2O" → "Ø20"
|
| 293 |
+
text = re.sub(r'(?<=[0-9])O(?=[0-9])', '0', text) # 1O5 → 105
|
| 294 |
+
text = re.sub(r'(?<=M)O', '0', text) # MO → M0... (rồi thành M10 nếu phù hợp)
|
| 295 |
+
text = re.sub(r'(?<=Ø)O', '0', text)
|
| 296 |
+
|
| 297 |
+
# Fix: số 1 bị nhận thành l/I
|
| 298 |
+
text = re.sub(r'(?<=[0-9])[lI](?=[0-9])', '1', text) # 2l5 → 215
|
| 299 |
+
|
| 300 |
+
# Fix: dấu × bị nhận thành x
|
| 301 |
+
text = re.sub(r'(\d+)\s*[xX]\s*(\d+)', r'\1×\2', text)
|
| 302 |
+
|
| 303 |
+
# Fix: Thép bị nhận sai
|
| 304 |
+
text = re.sub(r'[Tt]h[eé]p\s*', 'Thép ', text, flags=re.IGNORECASE)
|
| 305 |
+
|
| 306 |
+
# Clean extra spaces
|
| 307 |
+
text = re.sub(r'\s+', ' ', text).strip()
|
| 308 |
+
|
| 309 |
+
return text
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
# ============================================================
|
| 313 |
+
# OCR NOTE — Cải thiện
|
| 314 |
+
# ============================================================
|
| 315 |
+
def ocr_note(img_path, backend="paddle"):
|
| 316 |
+
"""
|
| 317 |
+
OCR cho vùng Note — cải thiện:
|
| 318 |
+
1. Upscale mạnh (min 1500px width)
|
| 319 |
+
2. Multi-pass với nhiều preprocessing
|
| 320 |
+
3. Dual-engine (vi + en)
|
| 321 |
+
4. Post-processing
|
| 322 |
+
"""
|
| 323 |
+
img = cv2.imread(img_path)
|
| 324 |
+
if img is None:
|
| 325 |
+
return ""
|
| 326 |
+
|
| 327 |
+
texts, conf = dual_engine_ocr(img, ocr_type="note")
|
| 328 |
+
|
| 329 |
+
# Post-process từng dòng
|
| 330 |
+
processed = [post_process_ocr_text(t) for t in texts]
|
| 331 |
+
processed = [t for t in processed if t] # remove empty
|
| 332 |
+
|
| 333 |
+
return "\n".join(processed)
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
# ============================================================
|
| 337 |
+
# OCR TABLE — Cải thiện với PPStructure
|
| 338 |
+
# ============================================================
|
| 339 |
+
_pp_structure = None
|
| 340 |
+
|
| 341 |
+
def get_pp_structure():
|
| 342 |
+
"""Load PPStructure cho table recognition."""
|
| 343 |
+
global _pp_structure
|
| 344 |
+
if _pp_structure is not None:
|
| 345 |
+
return _pp_structure
|
| 346 |
+
try:
|
| 347 |
+
from paddleocr import PPStructure
|
| 348 |
+
print("[INFO] Initializing PPStructure for table recognition...")
|
| 349 |
+
_pp_structure = PPStructure(
|
| 350 |
+
table=True,
|
| 351 |
+
ocr=True,
|
| 352 |
+
lang='vi',
|
| 353 |
+
show_log=False,
|
| 354 |
+
use_gpu=(DEVICE == "cuda"),
|
| 355 |
+
table_char_type='vi',
|
| 356 |
+
)
|
| 357 |
+
return _pp_structure
|
| 358 |
+
except Exception as e:
|
| 359 |
+
print(f"[WARN] PPStructure init failed: {e}")
|
| 360 |
+
return None
|
| 361 |
+
|
| 362 |
+
|
| 363 |
+
def parse_html_table(html_str):
|
| 364 |
+
"""Parse HTML table string thành list of rows."""
|
| 365 |
+
rows = []
|
| 366 |
+
# Tìm tất cả <tr>...</tr>
|
| 367 |
+
tr_pattern = re.findall(r'<tr>(.*?)</tr>', html_str, re.DOTALL)
|
| 368 |
+
for tr in tr_pattern:
|
| 369 |
+
# Tìm tất cả <td>...</td>
|
| 370 |
+
cells = re.findall(r'<td[^>]*>(.*?)</td>', tr, re.DOTALL)
|
| 371 |
+
# Clean HTML tags trong cell
|
| 372 |
+
clean_cells = []
|
| 373 |
+
for cell in cells:
|
| 374 |
+
clean = re.sub(r'<[^>]+>', '', cell).strip()
|
| 375 |
+
clean_cells.append(clean)
|
| 376 |
+
if clean_cells:
|
| 377 |
+
rows.append(clean_cells)
|
| 378 |
+
return rows
|
| 379 |
|
| 380 |
|
| 381 |
+
def ocr_table(img_path, backend="paddle"):
|
|
|
|
|
|
|
|
|
|
| 382 |
"""
|
| 383 |
+
OCR cho vùng Table — cải thiện:
|
| 384 |
+
1. Thử PPStructure trước (table structure recognition tốt nhất)
|
| 385 |
+
2. Fallback: detect cells thủ công + OCR từng cell
|
| 386 |
+
3. Post-processing
|
| 387 |
"""
|
| 388 |
+
img = cv2.imread(img_path)
|
| 389 |
+
if img is None:
|
| 390 |
+
return {"rows": [], "text": ""}
|
| 391 |
+
|
| 392 |
+
# === Strategy 1: PPStructure (best for tables) ===
|
| 393 |
+
pp_engine = get_pp_structure()
|
| 394 |
+
if pp_engine is not None:
|
| 395 |
try:
|
| 396 |
+
# Upscale trước khi đưa vào PPStructure
|
| 397 |
+
h, w = img.shape[:2]
|
| 398 |
+
if w < 1200:
|
| 399 |
+
scale = 1200 / w
|
| 400 |
+
img_scaled = cv2.resize(img, None, fx=scale, fy=scale,
|
| 401 |
+
interpolation=cv2.INTER_CUBIC)
|
| 402 |
+
else:
|
| 403 |
+
img_scaled = img
|
| 404 |
+
|
| 405 |
+
result = pp_engine(img_scaled)
|
| 406 |
+
for item in result:
|
| 407 |
+
if item.get('type') == 'table':
|
| 408 |
+
html = item.get('res', {}).get('html', '')
|
| 409 |
+
if html:
|
| 410 |
+
rows = parse_html_table(html)
|
| 411 |
+
if rows:
|
| 412 |
+
# Post-process mỗi cell
|
| 413 |
+
rows = [[post_process_ocr_text(cell) for cell in row]
|
| 414 |
+
for row in rows]
|
| 415 |
+
text = "\n".join(" | ".join(r) for r in rows)
|
| 416 |
+
print(f" PPStructure: {len(rows)} rows detected")
|
| 417 |
+
return {"rows": rows, "text": text, "html": html}
|
| 418 |
+
|
| 419 |
+
# PPStructure ran but no table found → extract text
|
| 420 |
+
all_texts = []
|
| 421 |
+
for item in result:
|
| 422 |
+
res = item.get('res', [])
|
| 423 |
+
if isinstance(res, list):
|
| 424 |
+
for line in res:
|
| 425 |
+
if isinstance(line, dict) and 'text' in line:
|
| 426 |
+
all_texts.append(line['text'])
|
| 427 |
+
elif isinstance(line, (list, tuple)) and len(line) >= 2:
|
| 428 |
+
text_info = line[1]
|
| 429 |
+
if isinstance(text_info, (list, tuple)):
|
| 430 |
+
all_texts.append(str(text_info[0]))
|
| 431 |
+
else:
|
| 432 |
+
all_texts.append(str(text_info))
|
| 433 |
+
if all_texts:
|
| 434 |
+
return {"rows": [all_texts], "text": "\n".join(all_texts)}
|
| 435 |
+
|
| 436 |
except Exception as e:
|
| 437 |
+
print(f" PPStructure error: {e}, falling back to manual")
|
| 438 |
+
|
| 439 |
+
# === Strategy 2: Manual cell detection + OCR ===
|
| 440 |
+
return ocr_table_manual(img, img_path, backend)
|
| 441 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 442 |
|
| 443 |
+
def ocr_table_manual(img, img_path, backend="paddle"):
|
| 444 |
+
"""
|
| 445 |
+
Fallback: detect table cells thủ công + OCR từng cell.
|
| 446 |
+
Cải thiện: upscale mỗi cell riêng, multi-pass OCR.
|
| 447 |
+
"""
|
| 448 |
+
cells = detect_table_structure(img)
|
| 449 |
+
|
| 450 |
+
if cells:
|
| 451 |
+
reader = get_paddle_reader('vi') or get_easyocr_reader()
|
| 452 |
+
ocr_results = []
|
| 453 |
+
|
| 454 |
+
for (x1, y1, x2, y2) in cells:
|
| 455 |
+
# Bỏ cell quá lớn (toàn bộ bảng) hoặc quá nhỏ
|
| 456 |
+
cell_w, cell_h = x2 - x1, y2 - y1
|
| 457 |
+
img_h, img_w = img.shape[:2]
|
| 458 |
+
if cell_w > img_w * 0.9 and cell_h > img_h * 0.9:
|
| 459 |
+
continue # Skip full-table contour
|
| 460 |
+
if cell_w < 15 or cell_h < 15:
|
| 461 |
+
continue
|
| 462 |
+
|
| 463 |
+
pad = 3
|
| 464 |
+
cy1 = max(0, y1 - pad)
|
| 465 |
+
cx1 = max(0, x1 - pad)
|
| 466 |
+
cy2 = min(img.shape[0], y2 + pad)
|
| 467 |
+
cx2 = min(img.shape[1], x2 + pad)
|
| 468 |
+
cell_img = img[cy1:cy2, cx1:cx2]
|
| 469 |
+
|
| 470 |
+
text = ocr_cell_improved(cell_img, reader)
|
| 471 |
+
if text:
|
| 472 |
+
ocr_results.append({
|
| 473 |
+
"text": post_process_ocr_text(text),
|
| 474 |
+
"x": (x1 + x2) // 2,
|
| 475 |
+
"y": (y1 + y2) // 2,
|
| 476 |
+
"box": (x1, y1, x2, y2)
|
| 477 |
+
})
|
| 478 |
+
|
| 479 |
+
if ocr_results:
|
| 480 |
+
rows = group_rows(ocr_results, vertical_thresh_ratio=0.5)
|
| 481 |
+
return {
|
| 482 |
+
"rows": rows,
|
| 483 |
+
"text": "\n".join(" | ".join(r) for r in rows)
|
| 484 |
+
}
|
| 485 |
+
|
| 486 |
+
# === Strategy 3: OCR toàn bộ ảnh table, group theo hàng ===
|
| 487 |
+
return ocr_table_fullimage(img, backend)
|
| 488 |
+
|
| 489 |
+
|
| 490 |
+
def ocr_cell_improved(img_cell, reader):
|
| 491 |
+
"""OCR 1 cell — upscale mạnh, multi-preprocessing."""
|
| 492 |
+
if img_cell.size == 0:
|
| 493 |
+
return ""
|
| 494 |
+
|
| 495 |
+
h, w = img_cell.shape[:2]
|
| 496 |
+
|
| 497 |
+
# Upscale cell nhỏ rất mạnh
|
| 498 |
+
target_w = max(300, w)
|
| 499 |
+
if w < target_w:
|
| 500 |
+
scale = target_w / w
|
| 501 |
+
img_cell = cv2.resize(img_cell, None, fx=scale, fy=scale,
|
| 502 |
+
interpolation=cv2.INTER_CUBIC)
|
| 503 |
+
|
| 504 |
+
# Try 2 variants
|
| 505 |
+
best_text = ""
|
| 506 |
+
best_conf = 0
|
| 507 |
+
|
| 508 |
+
for variant in ["color", "binary"]:
|
| 509 |
+
if variant == "color":
|
| 510 |
+
# Gentle enhancement
|
| 511 |
+
img_proc = cv2.bilateralFilter(img_cell, 5, 50, 50)
|
| 512 |
+
lab = cv2.cvtColor(img_proc, cv2.COLOR_BGR2LAB)
|
| 513 |
+
l, a, b = cv2.split(lab)
|
| 514 |
+
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(4, 4))
|
| 515 |
+
l = clahe.apply(l)
|
| 516 |
+
lab = cv2.merge([l, a, b])
|
| 517 |
+
img_proc = cv2.cvtColor(lab, cv2.COLOR_LAB2BGR)
|
| 518 |
+
else:
|
| 519 |
+
gray = cv2.cvtColor(img_cell, cv2.COLOR_BGR2GRAY)
|
| 520 |
+
_, binary = cv2.threshold(gray, 0, 255,
|
| 521 |
+
cv2.THRESH_BINARY + cv2.THRESH_OTSU)
|
| 522 |
+
img_proc = cv2.cvtColor(binary, cv2.COLOR_GRAY2BGR)
|
| 523 |
+
|
| 524 |
+
texts, conf = ocr_single_pass(reader, img_proc)
|
| 525 |
+
combined = " ".join(texts)
|
| 526 |
+
if conf > best_conf and combined.strip():
|
| 527 |
+
best_conf = conf
|
| 528 |
+
best_text = combined
|
| 529 |
+
|
| 530 |
+
return best_text
|
| 531 |
+
|
| 532 |
+
|
| 533 |
+
def ocr_table_fullimage(img, backend="paddle"):
|
| 534 |
+
"""OCR toàn bộ ảnh table (không chia cell), group by rows."""
|
| 535 |
+
reader = get_paddle_reader('vi') or get_easyocr_reader()
|
| 536 |
+
img_proc = preprocess_for_ocr(img, min_width=1500, mode="table")
|
| 537 |
+
|
| 538 |
+
items = []
|
| 539 |
+
if hasattr(reader, 'ocr'):
|
| 540 |
+
result = reader.ocr(img_proc, cls=True)
|
| 541 |
+
if result and result[0]:
|
| 542 |
+
for line in result[0]:
|
| 543 |
+
box, (text, conf) = line
|
| 544 |
+
if conf < 0.2 or not text.strip():
|
| 545 |
+
continue
|
| 546 |
+
xs = [p[0] for p in box]
|
| 547 |
+
ys = [p[1] for p in box]
|
| 548 |
+
items.append({
|
| 549 |
+
"text": post_process_ocr_text(text.strip()),
|
| 550 |
+
"conf": conf,
|
| 551 |
+
"x": np.mean(xs),
|
| 552 |
+
"y": np.mean(ys),
|
| 553 |
+
"box": box
|
| 554 |
+
})
|
| 555 |
+
else:
|
| 556 |
+
results = reader.readtext(img_proc, detail=1, paragraph=False)
|
| 557 |
+
for (pts, text, conf) in results:
|
| 558 |
+
if conf < 0.15 or not text.strip():
|
| 559 |
+
continue
|
| 560 |
items.append({
|
| 561 |
+
"text": post_process_ocr_text(text.strip()),
|
| 562 |
+
"conf": conf,
|
| 563 |
+
"x": sum(p[0] for p in pts) / 4,
|
| 564 |
+
"y": sum(p[1] for p in pts) / 4,
|
| 565 |
+
"box": pts
|
| 566 |
})
|
| 567 |
+
|
| 568 |
+
if not items:
|
| 569 |
+
return {"rows": [], "text": ""}
|
| 570 |
+
|
| 571 |
+
rows = group_rows(items, vertical_thresh_ratio=0.6)
|
| 572 |
+
return {"rows": rows, "text": "\n".join(" | ".join(r) for r in rows)}
|
| 573 |
|
| 574 |
|
| 575 |
+
# ============================================================
|
| 576 |
+
# TABLE STRUCTURE DETECTION (giữ nguyên, có cải thiện nhỏ)
|
| 577 |
+
# ============================================================
|
| 578 |
+
def detect_table_structure(img_bgr):
|
| 579 |
+
"""Phát hiện cells trong bảng dựa trên đường kẻ."""
|
| 580 |
+
h, w = img_bgr.shape[:2]
|
| 581 |
+
gray = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2GRAY)
|
| 582 |
+
_, binary = cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY_INV)
|
| 583 |
+
|
| 584 |
+
# Adaptive kernel size based on image size
|
| 585 |
+
h_kernel_len = max(40, w // 15)
|
| 586 |
+
v_kernel_len = max(40, h // 15)
|
| 587 |
+
|
| 588 |
+
horizontal_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (h_kernel_len, 1))
|
| 589 |
+
horizontal_lines = cv2.morphologyEx(binary, cv2.MORPH_OPEN, horizontal_kernel, iterations=2)
|
| 590 |
+
|
| 591 |
+
vertical_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (1, v_kernel_len))
|
| 592 |
+
vertical_lines = cv2.morphologyEx(binary, cv2.MORPH_OPEN, vertical_kernel, iterations=2)
|
| 593 |
+
|
| 594 |
+
table_structure = cv2.add(horizontal_lines, vertical_lines)
|
| 595 |
+
contours, hierarchy = cv2.findContours(table_structure, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
|
| 596 |
+
|
| 597 |
+
cells = []
|
| 598 |
+
min_cell_area = (w * h) * 0.001 # ít nhất 0.1% diện tích ảnh
|
| 599 |
+
max_cell_area = (w * h) * 0.85 # không quá 85% (tránh lấy toàn bảng)
|
| 600 |
+
|
| 601 |
+
for cnt in contours:
|
| 602 |
+
x, y, cw, ch = cv2.boundingRect(cnt)
|
| 603 |
+
area = cw * ch
|
| 604 |
+
if min_cell_area < area < max_cell_area and cw > 15 and ch > 15:
|
| 605 |
+
cells.append((x, y, x + cw, y + ch))
|
| 606 |
+
|
| 607 |
+
cells = sorted(set(cells), key=lambda r: (r[1], r[0]))
|
| 608 |
+
return cells
|
| 609 |
+
|
| 610 |
+
|
| 611 |
+
# ============================================================
|
| 612 |
+
# GROUP ROWS (giữ nguyên)
|
| 613 |
+
# ============================================================
|
| 614 |
+
def group_rows(items, vertical_thresh_ratio=0.6):
|
| 615 |
if not items:
|
| 616 |
return []
|
| 617 |
+
items_sorted = sorted(items, key=lambda x: x["y"])
|
| 618 |
+
y_vals = [it["y"] for it in items_sorted]
|
| 619 |
+
|
|
|
|
| 620 |
if len(y_vals) > 1:
|
| 621 |
+
gaps = [y_vals[i+1] - y_vals[i] for i in range(len(y_vals)-1)]
|
| 622 |
+
median_gap = np.median(gaps)
|
| 623 |
+
thresh = max(8, median_gap * vertical_thresh_ratio)
|
| 624 |
else:
|
| 625 |
thresh = 12
|
| 626 |
+
|
| 627 |
+
rows = []
|
| 628 |
+
current_row = [items_sorted[0]]
|
| 629 |
+
for it in items_sorted[1:]:
|
| 630 |
+
if it["y"] - current_row[-1]["y"] < thresh:
|
| 631 |
+
current_row.append(it)
|
| 632 |
else:
|
| 633 |
+
current_row.sort(key=lambda x: x["x"])
|
| 634 |
+
rows.append(current_row)
|
| 635 |
+
current_row = [it]
|
| 636 |
+
current_row.sort(key=lambda x: x["x"])
|
| 637 |
+
rows.append(current_row)
|
| 638 |
+
|
| 639 |
+
return [[it["text"] for it in row] for row in rows]
|
| 640 |
|
| 641 |
|
| 642 |
+
# ============================================================
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 643 |
# MAIN PIPELINE
|
| 644 |
+
# ============================================================
|
| 645 |
+
def run_pipeline(image_path, output_dir="outputs",
|
| 646 |
+
checkpoint="best.pt", conf_thresh=0.3,
|
| 647 |
+
ocr_backend="paddle"):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 648 |
image_path = str(image_path)
|
| 649 |
img_name = Path(image_path).name
|
| 650 |
stem = Path(image_path).stem
|
| 651 |
crop_dir = Path(output_dir) / stem / "crops"
|
| 652 |
crop_dir.mkdir(parents=True, exist_ok=True)
|
| 653 |
|
|
|
|
| 654 |
model = get_det_model(checkpoint)
|
| 655 |
+
results = model(image_path, imgsz=1024, conf=conf_thresh,
|
| 656 |
+
iou=0.5, device=DEVICE, verbose=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 657 |
|
| 658 |
img_bgr = cv2.imread(image_path)
|
| 659 |
if img_bgr is None:
|
| 660 |
+
raise ValueError(f"Cannot read: {image_path}")
|
| 661 |
|
| 662 |
objects = []
|
|
|
|
| 663 |
for i, box in enumerate(results[0].boxes):
|
| 664 |
x1, y1, x2, y2 = map(int, box.xyxy[0].tolist())
|
| 665 |
cls_idx = int(box.cls[0])
|
|
|
|
| 667 |
cls_raw = CLASS_NAMES[cls_idx]
|
| 668 |
cls_show = CLASS_DISPLAY[cls_raw]
|
| 669 |
|
| 670 |
+
# Padding lớn hơn → bao thêm context cho OCR
|
| 671 |
+
pad = 10
|
| 672 |
+
crop = img_bgr[max(0, y1-pad):min(img_bgr.shape[0], y2+pad),
|
| 673 |
+
max(0, x1-pad):min(img_bgr.shape[1], x2+pad)]
|
|
|
|
|
|
|
| 674 |
crop_path = str(crop_dir / f"{cls_show}_{i+1}.jpg")
|
| 675 |
+
# Lưu với quality cao hơn
|
| 676 |
+
cv2.imwrite(crop_path, crop, [cv2.IMWRITE_JPEG_QUALITY, 98])
|
| 677 |
|
|
|
|
| 678 |
ocr_content = None
|
| 679 |
if cls_raw == "note":
|
| 680 |
+
print(f"[OCR] Note #{i+1} ({x2-x1}x{y2-y1}px)...")
|
| 681 |
+
ocr_content = ocr_note(crop_path, backend=ocr_backend)
|
| 682 |
+
print(f" → {repr(ocr_content[:120]) if ocr_content else 'EMPTY'}")
|
|
|
|
| 683 |
elif cls_raw == "table":
|
| 684 |
+
print(f"[OCR] Table #{i+1} ({x2-x1}x{y2-y1}px)...")
|
| 685 |
+
ocr_content = ocr_table(crop_path, backend=ocr_backend)
|
| 686 |
+
preview = ocr_content.get("text", "")[:120]
|
| 687 |
print(f" → {repr(preview) if preview else 'EMPTY'}")
|
| 688 |
|
| 689 |
objects.append({
|
| 690 |
+
"id": i+1, "class": cls_show,
|
| 691 |
+
"confidence": conf_val,
|
| 692 |
+
"bbox": {"x1": x1, "y1": y1, "x2": x2, "y2": y2},
|
| 693 |
+
"crop_path": crop_path,
|
|
|
|
| 694 |
"ocr_content": ocr_content,
|
| 695 |
})
|
| 696 |
|
|
|
|
| 697 |
color = COLORS[cls_raw]
|
| 698 |
cv2.rectangle(img_bgr, (x1, y1), (x2, y2), color, 2)
|
| 699 |
label = f"{cls_show} {conf_val:.2f}"
|
| 700 |
+
(tw, th), _ = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.6, 2)
|
| 701 |
+
cv2.rectangle(img_bgr, (x1, y1-th-10), (x1+tw+8, y1), color, -1)
|
| 702 |
+
cv2.putText(img_bgr, label, (x1+4, y1-4),
|
|
|
|
|
|
|
|
|
|
| 703 |
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 2)
|
| 704 |
|
|
|
|
| 705 |
vis_path = str(Path(output_dir) / stem / "result_vis.jpg")
|
| 706 |
cv2.imwrite(vis_path, img_bgr)
|
| 707 |
|
|
|
|
| 708 |
result = {"image": img_name, "objects": objects}
|
| 709 |
json_path = str(Path(output_dir) / stem / "result.json")
|
| 710 |
with open(json_path, "w", encoding="utf-8") as f:
|
| 711 |
json.dump(result, f, ensure_ascii=False, indent=2)
|
| 712 |
|
| 713 |
+
print(f"[✓] {len(objects)} objects | {vis_path} | {json_path}")
|
| 714 |
return result, vis_path
|
| 715 |
|
| 716 |
|
|
|
|
| 717 |
if __name__ == "__main__":
|
| 718 |
import sys
|
| 719 |
img = sys.argv[1] if len(sys.argv) > 1 else "test.jpg"
|
| 720 |
+
result, _ = run_pipeline(img, ocr_backend="paddle")
|
| 721 |
print(json.dumps(result, ensure_ascii=False, indent=2))
|