Spaces:
Sleeping
Sleeping
Harry Pham commited on
Commit ·
9d7abf9
1
Parent(s): a4853dc
update OCR
Browse files- src/inference.py +110 -36
src/inference.py
CHANGED
|
@@ -52,20 +52,119 @@ def preprocess_for_ocr(img_bgr):
|
|
| 52 |
gray = cv2.filter2D(gray, -1, kernel)
|
| 53 |
return cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR)
|
| 54 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
def ocr_note(img_path):
|
| 56 |
img = cv2.imread(img_path)
|
| 57 |
-
if img is None:
|
| 58 |
-
|
| 59 |
-
img_proc =
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
width_ths=0.7, height_ths=0.7)
|
| 64 |
-
lines = [t for (_,t,c) in results if c >= 0.2 and t.strip()]
|
| 65 |
-
return "\n".join(lines)
|
| 66 |
-
except Exception as e:
|
| 67 |
-
print(f"[WARN] ocr_note: {e}")
|
| 68 |
return ""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
|
| 70 |
def _group_rows(items):
|
| 71 |
if not items:
|
|
@@ -89,31 +188,6 @@ def _group_rows(items):
|
|
| 89 |
rows.append([i["text"] for i in cur])
|
| 90 |
return rows
|
| 91 |
|
| 92 |
-
def ocr_table(img_path):
|
| 93 |
-
img = cv2.imread(img_path)
|
| 94 |
-
if img is None:
|
| 95 |
-
return {"rows":[], "text":""}
|
| 96 |
-
img_proc = preprocess_for_ocr(img)
|
| 97 |
-
items = []
|
| 98 |
-
try:
|
| 99 |
-
reader = get_easy_reader()
|
| 100 |
-
results = reader.readtext(img_proc, detail=1, paragraph=False,
|
| 101 |
-
width_ths=0.5, height_ths=0.5)
|
| 102 |
-
for (pts, text, conf) in results:
|
| 103 |
-
if conf < 0.2 or not text.strip():
|
| 104 |
-
continue
|
| 105 |
-
items.append({
|
| 106 |
-
"text": text.strip(),
|
| 107 |
-
"y": sum(p[1] for p in pts)/4,
|
| 108 |
-
"x": sum(p[0] for p in pts)/4,
|
| 109 |
-
})
|
| 110 |
-
except Exception as e:
|
| 111 |
-
print(f"[WARN] ocr_table: {e}")
|
| 112 |
-
if not items:
|
| 113 |
-
return {"rows":[], "text":""}
|
| 114 |
-
rows = _group_rows(items)
|
| 115 |
-
return {"rows": rows, "text": "\n".join(" | ".join(r) for r in rows)}
|
| 116 |
-
|
| 117 |
def run_pipeline(image_path, output_dir="outputs",
|
| 118 |
checkpoint="best.pt", conf_thresh=0.3):
|
| 119 |
image_path = str(image_path)
|
|
|
|
| 52 |
gray = cv2.filter2D(gray, -1, kernel)
|
| 53 |
return cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR)
|
| 54 |
|
| 55 |
+
import cv2
|
| 56 |
+
import numpy as np
|
| 57 |
+
from paddleocr import PaddleOCR
|
| 58 |
+
|
| 59 |
+
# Khởi tạo PaddleOCR (tự động tải PP-OCRv4 siêu nhẹ và chính xác)
|
| 60 |
+
# use_angle_cls=True giúp lật lại các chữ bị nghiêng trên bản vẽ
|
| 61 |
+
print("[INFO] Loading PaddleOCR...")
|
| 62 |
+
_ocr_engine = PaddleOCR(use_angle_cls=True, lang='vi', show_log=False)
|
| 63 |
+
|
| 64 |
+
def enhance_image_for_ocr(img_bgr):
|
| 65 |
+
"""
|
| 66 |
+
Tiền xử lý nhẹ nhàng: Tăng độ tương phản nhưng không làm đứt nét chữ.
|
| 67 |
+
"""
|
| 68 |
+
# Resize nếu ảnh quá nhỏ
|
| 69 |
+
h, w = img_bgr.shape[:2]
|
| 70 |
+
if w < 1000:
|
| 71 |
+
scale = 1000 / w
|
| 72 |
+
img_bgr = cv2.resize(img_bgr, (int(w*scale), int(h*scale)), interpolation=cv2.INTER_CUBIC)
|
| 73 |
+
|
| 74 |
+
gray = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2GRAY)
|
| 75 |
+
# Tăng độ tương phản cục bộ (CLAHE)
|
| 76 |
+
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))
|
| 77 |
+
gray = clahe.apply(gray)
|
| 78 |
+
|
| 79 |
+
# Không dùng Denoise mạnh, chỉ chuyển lại sang BGR cho PaddleOCR
|
| 80 |
+
return cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR)
|
| 81 |
+
|
| 82 |
+
|
| 83 |
def ocr_note(img_path):
|
| 84 |
img = cv2.imread(img_path)
|
| 85 |
+
if img is None: return ""
|
| 86 |
+
|
| 87 |
+
img_proc = enhance_image_for_ocr(img)
|
| 88 |
+
result = _ocr_engine.ocr(img_proc, cls=True)
|
| 89 |
+
|
| 90 |
+
if not result or not result[0]:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
return ""
|
| 92 |
+
|
| 93 |
+
# PaddleOCR format: [[[x1,y1], [x2,y2], [x3,y3], [x4,y4]], ('text', conf)]
|
| 94 |
+
lines = [line[1][0] for line in result[0] if line[1][1] > 0.6] # Lấy conf > 0.6
|
| 95 |
+
return "\n".join(lines)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def ocr_table(img_path):
|
| 99 |
+
img = cv2.imread(img_path)
|
| 100 |
+
if img is None: return {"rows": [], "text": ""}
|
| 101 |
+
|
| 102 |
+
img_proc = enhance_image_for_ocr(img)
|
| 103 |
+
result = _ocr_engine.ocr(img_proc, cls=True)
|
| 104 |
+
|
| 105 |
+
if not result or not result[0]:
|
| 106 |
+
return {"rows": [], "text": ""}
|
| 107 |
+
|
| 108 |
+
items = []
|
| 109 |
+
heights = []
|
| 110 |
+
|
| 111 |
+
# 1. Trích xuất text và tọa độ tâm
|
| 112 |
+
for line in result[0]:
|
| 113 |
+
box = line[0] # 4 điểm của bounding box
|
| 114 |
+
text = line[1][0] # Nội dung text
|
| 115 |
+
conf = line[1][1] # Độ tin cậy
|
| 116 |
+
|
| 117 |
+
if conf < 0.5 or not text.strip():
|
| 118 |
+
continue
|
| 119 |
+
|
| 120 |
+
# Tính tâm cy, cx và chiều cao của text box
|
| 121 |
+
y_top = min(box[0][1], box[1][1])
|
| 122 |
+
y_bottom = max(box[2][1], box[3][1])
|
| 123 |
+
x_left = min(box[0][0], box[3][0])
|
| 124 |
+
x_right = max(box[1][0], box[2][0])
|
| 125 |
+
|
| 126 |
+
cy = (y_top + y_bottom) / 2
|
| 127 |
+
cx = (x_left + x_right) / 2
|
| 128 |
+
h = y_bottom - y_top
|
| 129 |
+
|
| 130 |
+
items.append({"text": text.strip(), "cx": cx, "cy": cy, "h": h})
|
| 131 |
+
heights.append(h)
|
| 132 |
+
|
| 133 |
+
if not items:
|
| 134 |
+
return {"rows": [], "text": ""}
|
| 135 |
+
|
| 136 |
+
# 2. Thuật toán Dynamic Clustering (Gom hàng thông minh)
|
| 137 |
+
# Tính chiều cao median của các chữ làm chuẩn
|
| 138 |
+
median_h = np.median(heights)
|
| 139 |
+
# Nếu lệch tâm Y nhỏ hơn 40% chiều cao chữ thì coi như cùng 1 hàng
|
| 140 |
+
tolerance = median_h * 0.4
|
| 141 |
+
|
| 142 |
+
# Sắp xếp các cụm chữ từ trên xuống dưới
|
| 143 |
+
items.sort(key=lambda x: x["cy"])
|
| 144 |
+
|
| 145 |
+
rows = []
|
| 146 |
+
current_row = [items[0]]
|
| 147 |
+
|
| 148 |
+
for item in items[1:]:
|
| 149 |
+
# So sánh Y của item hiện tại với trung bình Y của hàng hiện tại
|
| 150 |
+
avg_y_current_row = sum(i["cy"] for i in current_row) / len(current_row)
|
| 151 |
+
|
| 152 |
+
if abs(item["cy"] - avg_y_current_row) <= tolerance:
|
| 153 |
+
current_row.append(item)
|
| 154 |
+
else:
|
| 155 |
+
# Chuyển sang hàng mới: Xếp các chữ trong hàng cũ từ trái qua phải
|
| 156 |
+
current_row.sort(key=lambda x: x["cx"])
|
| 157 |
+
rows.append([i["text"] for i in current_row])
|
| 158 |
+
current_row = [item] # Bắt đầu hàng mới
|
| 159 |
+
|
| 160 |
+
# Add hàng cuối cùng
|
| 161 |
+
current_row.sort(key=lambda x: x["cx"])
|
| 162 |
+
rows.append([i["text"] for i in current_row])
|
| 163 |
+
|
| 164 |
+
# Format đầu ra giống code cũ
|
| 165 |
+
formatted_text = "\n".join(" | ".join(r) for r in rows)
|
| 166 |
+
return {"rows": rows, "text": formatted_text}
|
| 167 |
+
|
| 168 |
|
| 169 |
def _group_rows(items):
|
| 170 |
if not items:
|
|
|
|
| 188 |
rows.append([i["text"] for i in cur])
|
| 189 |
return rows
|
| 190 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 191 |
def run_pipeline(image_path, output_dir="outputs",
|
| 192 |
checkpoint="best.pt", conf_thresh=0.3):
|
| 193 |
image_path = str(image_path)
|