Harry Pham commited on
Commit
08f9745
·
1 Parent(s): 0579d8b

update OCR

Browse files
Files changed (1) hide show
  1. src/inference.py +51 -31
src/inference.py CHANGED
@@ -1,3 +1,12 @@
 
 
 
 
 
 
 
 
 
1
  # src/inference.py
2
  import torch
3
  _orig_torch_load = torch.load
@@ -140,17 +149,25 @@ def ocr_table(img_path):
140
  # Fallback về OCR thường
141
  fallback_text = ocr_note(img_path)
142
  return {"rows": [], "text": fallback_text}
143
- def run_pipeline(image_path, output_dir="outputs",
144
- checkpoint="best.pt", conf_thresh=0.3):
145
  image_path = str(image_path)
146
- img_name = Path(image_path).name
147
- stem = Path(image_path).stem
148
- crop_dir = Path(output_dir) / stem / "crops"
149
  crop_dir.mkdir(parents=True, exist_ok=True)
150
 
151
- model = get_det_model(checkpoint)
152
- results = model(image_path, imgsz=1024, conf=conf_thresh,
153
- iou=0.5, device=DEVICE, verbose=False)
 
 
 
 
 
 
 
 
 
154
 
155
  img_bgr = cv2.imread(image_path)
156
  if img_bgr is None:
@@ -158,15 +175,18 @@ def run_pipeline(image_path, output_dir="outputs",
158
 
159
  objects = []
160
  for i, box in enumerate(results[0].boxes):
161
- x1,y1,x2,y2 = map(int, box.xyxy[0].tolist())
162
- cls_idx = int(box.cls[0])
163
  conf_val = round(float(box.conf[0]), 4)
164
- cls_raw = CLASS_NAMES[cls_idx]
165
- cls_show = CLASS_DISPLAY[cls_raw]
 
 
166
 
167
- pad = 6
168
- crop = img_bgr[max(0,y1-pad):min(img_bgr.shape[0],y2+pad),
169
- max(0,x1-pad):min(img_bgr.shape[1],x2+pad)]
 
170
  crop_path = str(crop_dir / f"{cls_show}_{i+1}.jpg")
171
  cv2.imwrite(crop_path, crop, [cv2.IMWRITE_JPEG_QUALITY, 95])
172
 
@@ -174,38 +194,38 @@ def run_pipeline(image_path, output_dir="outputs",
174
  if cls_raw == "note":
175
  print(f"[OCR] Note #{i+1}...")
176
  ocr_content = ocr_note(crop_path)
177
- print(f" → {repr(ocr_content[:80]) if ocr_content else 'EMPTY'}")
178
  elif cls_raw == "table":
179
  print(f"[OCR] Table #{i+1}...")
180
  ocr_content = ocr_table(crop_path)
181
- preview = ocr_content.get("text","")[:80]
182
- print(f" → {repr(preview) if preview else 'EMPTY'}")
183
 
184
  objects.append({
185
- "id": i+1, "class": cls_show,
 
186
  "confidence": conf_val,
187
- "bbox": {"x1":x1,"y1":y1,"x2":x2,"y2":y2},
188
  "crop_path": crop_path,
189
  "ocr_content": ocr_content,
190
  })
191
 
192
- color = COLORS[cls_raw]
193
- cv2.rectangle(img_bgr, (x1,y1), (x2,y2), color, 2)
 
194
  label = f"{cls_show} {conf_val:.2f}"
195
- (tw,th),_ = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.6, 2)
196
- cv2.rectangle(img_bgr, (x1,y1-th-10), (x1+tw+8,y1), color, -1)
197
- cv2.putText(img_bgr, label, (x1+4,y1-4),
198
- cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255,255,255), 2)
199
 
200
- vis_path = str(Path(output_dir)/stem/"result_vis.jpg")
 
201
  cv2.imwrite(vis_path, img_bgr)
202
 
203
- result = {"image": img_name, "objects": objects}
204
- json_path = str(Path(output_dir)/stem/"result.json")
205
- with open(json_path,"w",encoding="utf-8") as f:
206
  json.dump(result, f, ensure_ascii=False, indent=2)
207
 
208
- print(f"[✓] {len(objects)} objects | {vis_path} | {json_path}")
209
  return result, vis_path
210
 
211
  if __name__ == "__main__":
 
1
+ # ================== FIX LỖI PYTHON 3.12 + PADDLEOCR ==================
2
+ import os
3
+ os.environ["PADDLE_PDX_DISABLE_MODEL_SOURCE_CHECK"] = "True"
4
+ os.environ["PYTHONASYNCIODEBUG"] = "0"
5
+
6
+ import warnings
7
+ warnings.filterwarnings("ignore", category=UserWarning)
8
+ # =====================================================================
9
+
10
  # src/inference.py
11
  import torch
12
  _orig_torch_load = torch.load
 
149
  # Fallback về OCR thường
150
  fallback_text = ocr_note(img_path)
151
  return {"rows": [], "text": fallback_text}
152
+ def run_pipeline(image_path, output_dir="outputs", checkpoint="best.pt", conf_thresh=0.25):
 
153
  image_path = str(image_path)
154
+ img_name = Path(image_path).name
155
+ stem = Path(image_path).stem
156
+ crop_dir = Path(output_dir) / stem / "crops"
157
  crop_dir.mkdir(parents=True, exist_ok=True)
158
 
159
+ model = get_det_model(checkpoint)
160
+
161
+ # === DEBUG: In ra tất cả box mà model detect được ===
162
+ print(f"\n🔍 [DEBUG] Running detection on {img_name} (conf={conf_thresh})")
163
+ results = model(image_path, imgsz=1024, conf=conf_thresh, iou=0.5, device=DEVICE, verbose=False)
164
+
165
+ print(f" → Tổng số box detect được: {len(results[0].boxes)}")
166
+ for i, box in enumerate(results[0].boxes):
167
+ cls_idx = int(box.cls[0])
168
+ cls_name_raw = CLASS_NAMES[cls_idx] if cls_idx < len(CLASS_NAMES) else f"unknown_{cls_idx}"
169
+ conf = float(box.conf[0])
170
+ print(f" Box {i+1}: class = '{cls_name_raw}' | conf = {conf:.3f}")
171
 
172
  img_bgr = cv2.imread(image_path)
173
  if img_bgr is None:
 
175
 
176
  objects = []
177
  for i, box in enumerate(results[0].boxes):
178
+ x1, y1, x2, y2 = map(int, box.xyxy[0].tolist())
179
+ cls_idx = int(box.cls[0])
180
  conf_val = round(float(box.conf[0]), 4)
181
+
182
+ # Map class an toàn
183
+ cls_raw = CLASS_NAMES[cls_idx] if cls_idx < len(CLASS_NAMES) else "unknown"
184
+ cls_show = CLASS_DISPLAY.get(cls_raw, cls_raw.capitalize())
185
 
186
+ pad = 6
187
+ crop = img_bgr[max(0, y1-pad):min(img_bgr.shape[0], y2+pad),
188
+ max(0, x1-pad):min(img_bgr.shape[1], x2+pad)]
189
+
190
  crop_path = str(crop_dir / f"{cls_show}_{i+1}.jpg")
191
  cv2.imwrite(crop_path, crop, [cv2.IMWRITE_JPEG_QUALITY, 95])
192
 
 
194
  if cls_raw == "note":
195
  print(f"[OCR] Note #{i+1}...")
196
  ocr_content = ocr_note(crop_path)
 
197
  elif cls_raw == "table":
198
  print(f"[OCR] Table #{i+1}...")
199
  ocr_content = ocr_table(crop_path)
 
 
200
 
201
  objects.append({
202
+ "id": i + 1,
203
+ "class": cls_show,
204
  "confidence": conf_val,
205
+ "bbox": {"x1": x1, "y1": y1, "x2": x2, "y2": y2},
206
  "crop_path": crop_path,
207
  "ocr_content": ocr_content,
208
  })
209
 
210
+ # Vẽ box
211
+ color = COLORS.get(cls_raw, (255, 255, 255))
212
+ cv2.rectangle(img_bgr, (x1, y1), (x2, y2), color, 2)
213
  label = f"{cls_show} {conf_val:.2f}"
214
+ (tw, th), _ = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.6, 2)
215
+ cv2.rectangle(img_bgr, (x1, y1 - th - 10), (x1 + tw + 8, y1), color, -1)
216
+ cv2.putText(img_bgr, label, (x1 + 4, y1 - 4),
217
+ cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 2)
218
 
219
+ # Lưu visualization và JSON
220
+ vis_path = str(Path(output_dir) / stem / "result_vis.jpg")
221
  cv2.imwrite(vis_path, img_bgr)
222
 
223
+ result = {"image": img_name, "objects": objects}
224
+ json_path = str(Path(output_dir) / stem / "result.json")
225
+ with open(json_path, "w", encoding="utf-8") as f:
226
  json.dump(result, f, ensure_ascii=False, indent=2)
227
 
228
+ print(f"\n[✓] Hoàn thành: {len(objects)} objects | JSON: {json_path} | Vis: {vis_path}")
229
  return result, vis_path
230
 
231
  if __name__ == "__main__":