ocris 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
ocris/detector.py ADDED
@@ -0,0 +1,1090 @@
1
+ """GeoDBDet: Oriented & Curved Differentiable Binarization Text Detector on NetCL OpenCL.
2
+
3
+ Architecture:
4
+ - GeoBackbone: 5-stage ResNet+SE with large depthwise kernels + Stride-32 Global 2D Self-Attention
5
+ - ASF-FPN: Top-down FPN with bilinear upsampling + Adaptive Scale Fusion at stride 4
6
+ - Decoupled Heads:
7
+ * prob_logits (B, 1, H/4, W/4): full word/polygon interior probability
8
+ * thresh (B, 1, H/4, W/4): adaptive border threshold in (0, 1)
9
+ * kernel_logits (B, 1, H/4, W/4): shrunk instance core separating touching words/lines
10
+ * geo (B, 8, H/4, W/4): [cos2t, sin2t, cost, sint, cosp, sinp, log(h/16), sd_norm]
11
+ """
12
+ import json
13
+ import math
14
+ from pathlib import Path
15
+
16
+ import numpy as np
17
+ from netcl import autograd as ag
18
+ from netcl.core.tensor import Tensor, spec_mode
19
+ from netcl.nn import Module
20
+ from netcl.nn.layers import Conv2d
21
+ from netcl.nn.state import flatten_state_dict
22
+
23
+ from .nn_blocks import ConvNormAct, GlobalContext2DBlock, ResSEBlock, constant
24
+
25
+ OUT_STRIDE = 4
26
+ GEO_CH = 8
27
+ LOG_SCALE = 16.0
28
+ SHRINK_RATIO = 0.28
29
+ CHECKPOINT_FORMAT = 'omni.geodb_det.1'
30
+
31
+
32
+ # ---------------------------------------------------------------------------- Model
33
+
34
+ class GeoDBDet(Module):
35
+ def __init__(
36
+ self,
37
+ queue,
38
+ widths: tuple[int, ...] = (48, 96, 192, 288, 384),
39
+ fpn_dim: int = 160,
40
+ norm: str = 'bn',
41
+ global_layers: int = 2,
42
+ ):
43
+ c2, c4, c8, c16, c32 = widths
44
+ self.queue = queue
45
+ self.widths = tuple(widths)
46
+ self.fpn_dim = int(fpn_dim)
47
+ self.norm_type = norm
48
+ self.global_layers = int(global_layers)
49
+
50
+ # Backbone
51
+ self.stem1 = ConvNormAct(queue, 3, 48, k=3, s=2, norm=norm)
52
+ self.stem2 = ConvNormAct(queue, 48, c2, k=3, s=1, norm=norm)
53
+ self.stem3 = ResSEBlock(queue, c2, c2, s=1, norm=norm)
54
+
55
+ self.s4 = [ResSEBlock(queue, c2, c4, s=2, norm=norm),
56
+ ResSEBlock(queue, c4, c4, dw_k=0, norm=norm),
57
+ ResSEBlock(queue, c4, c4, dw_k=0, norm=norm)]
58
+ self.s8 = [ResSEBlock(queue, c4, c8, s=2, norm=norm),
59
+ ResSEBlock(queue, c8, c8, dw_k=0, norm=norm),
60
+ ResSEBlock(queue, c8, c8, dw_k=0, norm=norm)]
61
+ self.s16 = [ResSEBlock(queue, c8, c16, s=2, norm=norm),
62
+ ResSEBlock(queue, c16, c16, dw_k=0, norm=norm),
63
+ ResSEBlock(queue, c16, c16, dw_k=0, norm=norm)]
64
+ self.s32 = [ResSEBlock(queue, c16, c32, s=2, norm=norm),
65
+ ResSEBlock(queue, c32, c32, norm=norm)]
66
+ n_heads = 8 if c32 % 8 == 0 else 6
67
+ self.global_ctx = GlobalContext2DBlock(queue, c32, n_heads=n_heads, n_layers=global_layers) if global_layers > 0 else None
68
+
69
+ # Top-down FPN + ASF
70
+ self.lat32 = ConvNormAct(queue, c32, fpn_dim, k=1, pad=0, norm=norm, act='none')
71
+ self.lat16 = ConvNormAct(queue, c16, fpn_dim, k=1, pad=0, norm=norm, act='none')
72
+ self.lat8 = ConvNormAct(queue, c8, fpn_dim, k=1, pad=0, norm=norm, act='none')
73
+ self.lat4 = ConvNormAct(queue, c4, fpn_dim, k=1, pad=0, norm=norm, act='none')
74
+
75
+ self.smooth16 = ConvNormAct(queue, fpn_dim, fpn_dim, k=3, norm=norm)
76
+ self.smooth8 = ConvNormAct(queue, fpn_dim, fpn_dim, k=3, norm=norm)
77
+ self.smooth4 = ConvNormAct(queue, fpn_dim, fpn_dim, k=3, norm=norm)
78
+
79
+ sc = fpn_dim // 4
80
+ self.red32 = ConvNormAct(queue, fpn_dim, sc, k=3, norm=norm)
81
+ self.red16 = ConvNormAct(queue, fpn_dim, sc, k=3, norm=norm)
82
+ self.red8 = ConvNormAct(queue, fpn_dim, sc, k=3, norm=norm)
83
+ self.red4 = ConvNormAct(queue, fpn_dim, sc, k=3, norm=norm)
84
+
85
+ self.asf_ctx = ConvNormAct(queue, fpn_dim, sc, k=3, norm=norm)
86
+ self.asf_attn = Conv2d(queue, sc, 4, kernel_size=1, pad=0, bias=True)
87
+
88
+ # Decoupled Heads
89
+ self.prob_feat = ConvNormAct(queue, fpn_dim, 96, k=3, norm=norm)
90
+ self.prob_out = Conv2d(queue, 96, 1, kernel_size=1, pad=0, bias=True)
91
+
92
+ self.thresh_feat = ConvNormAct(queue, fpn_dim, 96, k=3, norm=norm)
93
+ self.thresh_out = Conv2d(queue, 96, 1, kernel_size=1, pad=0, bias=True)
94
+
95
+ self.kernel_feat = ConvNormAct(queue, fpn_dim, 96, k=3, norm=norm)
96
+ self.kernel_out = Conv2d(queue, 96, 1, kernel_size=1, pad=0, bias=True)
97
+
98
+ self.geo_feat = ConvNormAct(queue, fpn_dim, 128, k=3, norm=norm)
99
+ self.geo_out = Conv2d(queue, 128, GEO_CH, kernel_size=1, pad=0, bias=True)
100
+
101
+ # Focal-friendly priors
102
+ for head, bias_val in ((self.prob_out, -3.0), (self.kernel_out, -3.5)):
103
+ sd = head.state_dict()
104
+ head.load_state_dict({'weight': sd['weight'] * 0.1, 'bias': np.full_like(sd['bias'], bias_val)})
105
+ sd = self.geo_out.state_dict()
106
+ self.geo_out.load_state_dict({'weight': sd['weight'] * 0.1, 'bias': np.zeros_like(sd['bias'])})
107
+
108
+ @staticmethod
109
+ def _seq(blocks, x):
110
+ for b in blocks:
111
+ x = b(x)
112
+ return x
113
+
114
+ def forward(self, images):
115
+ x = ag.tensor(images) if not isinstance(images, ag.Node) else images
116
+ f2 = self.stem3(self.stem2(self.stem1(x)))
117
+ f4 = self._seq(self.s4, f2)
118
+ f8 = self._seq(self.s8, f4)
119
+ f16 = self._seq(self.s16, f8)
120
+ f32 = self._seq(self.s32, f16)
121
+ if self.global_ctx is not None:
122
+ f32 = self.global_ctx(f32)
123
+
124
+ p32 = self.lat32(f32)
125
+ p16 = self.smooth16(ag.upsample(p32, size=f16.shape[2:], mode='bilinear') + self.lat16(f16))
126
+ p8 = self.smooth8(ag.upsample(p16, size=f8.shape[2:], mode='bilinear') + self.lat8(f8))
127
+ p4 = self.smooth4(ag.upsample(p8, size=f4.shape[2:], mode='bilinear') + self.lat4(f4))
128
+
129
+ target_hw = p4.shape[2:]
130
+ r4 = self.red4(p4)
131
+ r8 = ag.upsample(self.red8(p8), size=target_hw, mode='bilinear')
132
+ r16 = ag.upsample(self.red16(p16), size=target_hw, mode='bilinear')
133
+ r32 = ag.upsample(self.red32(p32), size=target_hw, mode='bilinear')
134
+ concat = ag.cat([r4, r8, r16, r32], axis=1)
135
+
136
+ w = ag.softmax(self.asf_attn(self.asf_ctx(concat)), axis=1)
137
+ fused = ag.cat([
138
+ r4 * ag.narrow(w, 1, 0, 1),
139
+ r8 * ag.narrow(w, 1, 1, 1),
140
+ r16 * ag.narrow(w, 1, 2, 1),
141
+ r32 * ag.narrow(w, 1, 3, 1),
142
+ ], axis=1)
143
+
144
+ prob_logits = self.prob_out(self.prob_feat(fused))
145
+ thresh = ag.sigmoid(self.thresh_out(self.thresh_feat(fused)))
146
+ kernel_logits = self.kernel_out(self.kernel_feat(fused))
147
+ geo = self.geo_out(self.geo_feat(fused))
148
+ return prob_logits, thresh, kernel_logits, geo
149
+
150
+
151
+ # ---------------------------------------------------------------------------- Targets
152
+
153
+ def _poly_signed_dist(pts_xy: np.ndarray, poly: np.ndarray) -> np.ndarray:
154
+ """Exact signed Euclidean distance from (N, 2) points to closed (K, 2) polygon."""
155
+ a = poly.astype(np.float64)
156
+ b = np.roll(a, -1, axis=0)
157
+ ab = b - a
158
+ ab2 = np.sum(ab * ab, axis=1) + 1e-12
159
+ ap = pts_xy[:, None, :] - a[None, :, :]
160
+ t = np.clip(np.sum(ap * ab[None, :, :], axis=2) / ab2[None, :], 0.0, 1.0)
161
+ proj = a[None, :, :] + t[:, :, None] * ab[None, :, :]
162
+ dist = np.linalg.norm(pts_xy[:, None, :] - proj, axis=2).min(axis=1)
163
+
164
+ x, y = pts_xy[:, 0:1], pts_xy[:, 1:2]
165
+ ax, ay = a[None, :, 0], a[None, :, 1]
166
+ bx, by = b[None, :, 0], b[None, :, 1]
167
+ cond = ((ay > y) != (by > y)) & (x < (bx - ax) * (y - ay) / (by - ay + 1e-12) + ax)
168
+ inside = (np.sum(cond, axis=1) % 2) == 1
169
+ return np.where(inside, dist, -dist)
170
+
171
+
172
+ def _instance_geometry(inst: dict) -> tuple[np.ndarray, float, np.ndarray | None, np.ndarray, np.ndarray, np.ndarray]:
173
+ """Return (poly[K,2], height_px, centerline[M,2]|None, u_segs[S,2], v_segs[S,2], h_segs[S])."""
174
+ if 'polygon' in inst and inst['polygon'] is not None:
175
+ poly = np.asarray(inst['polygon'], dtype=np.float64)
176
+ else:
177
+ poly = np.asarray(inst['quad'], dtype=np.float64)
178
+
179
+ cl = inst.get('centerline')
180
+ if cl is not None and len(cl) >= 2:
181
+ cl_arr = np.asarray(cl, dtype=np.float64)
182
+ segs = cl_arr[1:] - cl_arr[:-1]
183
+ norms = np.maximum(np.linalg.norm(segs, axis=1, keepdims=True), 1e-6)
184
+ u_segs = segs / norms
185
+ # Infer v per segment: match quad up-vector if available, else perpendicular (-uy, ux) with y down -> (uy, -ux)
186
+ if 'quad' in inst and inst['quad'] is not None:
187
+ q = np.asarray(inst['quad'], dtype=np.float64)
188
+ v_ref = (q[3] - q[0]) + (q[2] - q[1])
189
+ else:
190
+ v_ref = np.array([u_segs[:, 1].mean(), -u_segs[:, 0].mean()])
191
+ v_segs = np.stack([u_segs[:, 1], -u_segs[:, 0]], axis=1)
192
+ if np.dot(v_segs.mean(axis=0), v_ref) < 0:
193
+ v_segs = -v_segs
194
+ h_px = float(inst.get('height', 0.0))
195
+ if h_px <= 1e-3:
196
+ import cv2 as cv
197
+ rect = cv.minAreaRect(poly.astype(np.float32))
198
+ h_px = max(float(min(rect[1])), 1.0)
199
+ h_segs = np.full(len(u_segs), h_px, dtype=np.float64)
200
+ return poly, h_px, cl_arr, u_segs, v_segs, h_segs
201
+
202
+ # Quad or 4-point box
203
+ if len(poly) == 4:
204
+ q = poly
205
+ u = (q[1] - q[0]) + (q[2] - q[3])
206
+ u /= max(float(np.linalg.norm(u)), 1e-6)
207
+ v_raw = (q[3] - q[0]) + (q[2] - q[1])
208
+ h_px = float(0.5 * (np.linalg.norm(q[3] - q[0]) + np.linalg.norm(q[2] - q[1])))
209
+ v = v_raw / max(float(np.linalg.norm(v_raw)), 1e-6)
210
+ return poly, max(h_px, 1.0), None, u[None, :], v[None, :], np.array([max(h_px, 1.0)])
211
+
212
+ # General polygon without explicit centerline: use minAreaRect axis (training-only)
213
+ import cv2 as cv
214
+ rect = cv.minAreaRect(poly.astype(np.float32))
215
+ box = cv.boxPoints(rect)
216
+ e0 = box[1] - box[0]
217
+ e1 = box[2] - box[1]
218
+ if np.linalg.norm(e0) >= np.linalg.norm(e1):
219
+ u = e0 / max(float(np.linalg.norm(e0)), 1e-6)
220
+ h_px = float(np.linalg.norm(e1))
221
+ else:
222
+ u = e1 / max(float(np.linalg.norm(e1)), 1e-6)
223
+ h_px = float(np.linalg.norm(e0))
224
+ if u[0] < 0:
225
+ u = -u
226
+ v = np.array([u[1], -u[0]], dtype=np.float64)
227
+ return poly, max(h_px, 1.0), None, u[None, :], v[None, :], np.array([max(h_px, 1.0)])
228
+
229
+
230
+ def _poly_area_abs(pts: np.ndarray) -> float:
231
+ """Absolute polygon area via Shoelace formula (zero cv2)."""
232
+ if len(pts) < 3:
233
+ return 0.0
234
+ x = pts[:, 0].astype(np.float64)
235
+ y = pts[:, 1].astype(np.float64)
236
+ return 0.5 * abs(float(np.dot(x, np.roll(y, -1)) - np.dot(y, np.roll(x, -1))))
237
+
238
+
239
+ def _dilate_bool(mask: np.ndarray, radius: int) -> np.ndarray:
240
+ """Pure-NumPy square binary dilation of boolean 2D mask (radius=1 -> 3x3, radius=2 -> 5x5)."""
241
+ h, w = mask.shape
242
+ padded = np.pad(mask.astype(bool), radius, mode='constant', constant_values=False)
243
+ out = np.zeros((h, w), dtype=bool)
244
+ k = 2 * radius + 1
245
+ for dy in range(k):
246
+ y1 = dy + h
247
+ for dx in range(k):
248
+ out |= padded[dy:y1, dx:dx + w]
249
+ return out
250
+
251
+
252
+ def make_det_targets(words: list[dict], h: int, w: int, out_stride: int = OUT_STRIDE) -> dict[str, np.ndarray]:
253
+ """Generate sub-pixel exact DBNet++ + 8-channel geometry targets at stride `out_stride`."""
254
+ fh, fw = h // out_stride, w // out_stride
255
+ prob_gt = np.zeros((fh, fw), np.float32)
256
+ valid_mask = np.ones((fh, fw), np.float32)
257
+ kernel_gt = np.zeros((fh, fw), np.float32)
258
+ thresh_gt = np.full((fh, fw), 0.3, np.float32)
259
+ thresh_mask = np.zeros((fh, fw), np.float32)
260
+ geo_gt = np.zeros((GEO_CH, fh, fw), np.float32)
261
+ geo_w = np.zeros((fh, fw), np.float32)
262
+ dir_w = np.zeros((fh, fw), np.float32)
263
+ kern_owner = np.zeros((fh, fw), np.int32)
264
+ prob_touch = np.zeros((fh, fw), np.uint16)
265
+ kern_touch = np.zeros((fh, fw), np.uint16)
266
+
267
+ items = []
268
+ for word in words:
269
+ poly, h_px, cl, u_segs, v_segs, h_segs = _instance_geometry(word)
270
+ area = _poly_area_abs(poly)
271
+ items.append((area, word, poly, h_px, cl, u_segs, v_segs, h_segs))
272
+ # Draw larger instances first so smaller nested/overlapping text wins cell ownership
273
+ items.sort(key=lambda t: -t[0])
274
+
275
+ n_pos_words = 0
276
+ for wid, (_, word, poly, h_px, cl, u_segs, v_segs, h_segs) in enumerate(items, start=1):
277
+ pad_px = max(8.0, 0.5 * h_px + 2 * out_stride)
278
+ x0 = max(0, int(math.floor((poly[:, 0].min() - pad_px) / out_stride)))
279
+ y0 = max(0, int(math.floor((poly[:, 1].min() - pad_px) / out_stride)))
280
+ x1 = min(fw, int(math.ceil((poly[:, 0].max() + pad_px) / out_stride)) + 1)
281
+ y1 = min(fh, int(math.ceil((poly[:, 1].max() + pad_px) / out_stride)) + 1)
282
+ if x0 >= x1 or y0 >= y1:
283
+ continue
284
+
285
+ gy, gx = np.mgrid[y0:y1, x0:x1]
286
+ pts = np.stack([(gx.ravel() + 0.5) * out_stride, (gy.ravel() + 0.5) * out_stride], axis=1)
287
+ sd = _poly_signed_dist(pts, poly).reshape(y1 - y0, x1 - x0)
288
+ inside = sd >= 0.0
289
+ if not inside.any():
290
+ # Sub-cell word: pick nearest grid cell to centroid
291
+ c = poly.mean(axis=0)
292
+ cx = int(np.clip(round(c[0] / out_stride - 0.5), x0, x1 - 1)) - x0
293
+ cy = int(np.clip(round(c[1] / out_stride - 0.5), y0, y1 - 1)) - y0
294
+ inside[cy, cx] = True
295
+
296
+ usable = (not word.get('ignore', False)) and h_px >= 5.0
297
+ if not usable:
298
+ # Ignore mask covers polygon + slight dilation so ignored ink is neither pos nor neg
299
+ ign_zone = sd >= -float(out_stride)
300
+ valid_mask[y0:y1, x0:x1][ign_zone] = 0.0
301
+ continue
302
+
303
+ n_pos_words += 1
304
+ prob_gt[y0:y1, x0:x1][inside] = 1.0
305
+ valid_mask[y0:y1, x0:x1][inside] = 1.0
306
+
307
+ # Shrunk kernel (guaranteed >= 1 cell at distance maximum) with 8-connected moat vs other words
308
+ d_in = min(SHRINK_RATIO * h_px, 0.45 * float(max(sd.max(), 0.0)))
309
+ kern = (sd >= d_in) if d_in > 0 else inside.copy()
310
+ if not kern.any():
311
+ max_idx = int(np.argmax(sd))
312
+ kern = np.zeros_like(inside)
313
+ kern.flat[max_idx] = True
314
+ ro = kern_owner[y0:y1, x0:x1]
315
+ other = (ro != 0) & (ro != wid)
316
+ if other.any():
317
+ touch = _dilate_bool(other, 1)
318
+ kern_moat = kern & (~touch)
319
+ if kern_moat.any():
320
+ kern = kern_moat
321
+ else:
322
+ max_idx = int(np.argmax(sd))
323
+ kern = np.zeros_like(inside)
324
+ kern.flat[max_idx] = True
325
+ kernel_gt[y0:y1, x0:x1][kern] = 1.0
326
+ ro[kern] = wid
327
+ p_dil = _dilate_bool(inside, 1)
328
+ k_dil = _dilate_bool(kern, 2)
329
+ prob_touch[y0:y1, x0:x1][p_dil] += 1
330
+ kern_touch[y0:y1, x0:x1][k_dil] += 1
331
+
332
+ # DBNet++ threshold border band (|sd| <= border_d -> linearly 1.0 on edge to 0.3 at margin)
333
+ border_d = max(1.5 * out_stride, 0.35 * h_px)
334
+ in_band = np.abs(sd) <= border_d
335
+ t_val = np.clip(1.0 - 0.7 * (np.abs(sd) / border_d), 0.3, 1.0).astype(np.float32)
336
+ tm = thresh_mask[y0:y1, x0:x1]
337
+ tg = thresh_gt[y0:y1, x0:x1]
338
+ # Keep max threshold target when words sit near each other
339
+ tg[in_band] = np.where(tm[in_band] > 0, np.maximum(tg[in_band], t_val[in_band]), t_val[in_band])
340
+ tm[in_band] = 1.0
341
+
342
+ # Dense 8-channel local frame targets inside the word (supervised on kernel + 1-cell margin)
343
+ sup_mask = kern
344
+ sup_pts = pts.reshape(y1 - y0, x1 - x0, 2)[sup_mask]
345
+ if cl is not None and len(u_segs) > 1:
346
+ # Nearest centerline segment per supervised cell
347
+ a_s = cl[:-1]
348
+ ab_s = cl[1:] - a_s
349
+ ab2_s = np.sum(ab_s * ab_s, axis=1) + 1e-12
350
+ ap_s = sup_pts[:, None, :] - a_s[None, :, :]
351
+ ts = np.clip(np.sum(ap_s * ab_s[None, :, :], axis=2) / ab2_s[None, :], 0.0, 1.0)
352
+ proj_s = a_s[None, :, :] + ts[:, :, None] * ab_s[None, :, :]
353
+ seg_idx = np.argmin(np.linalg.norm(sup_pts[:, None, :] - proj_s, axis=2), axis=1)
354
+ ux, uy = u_segs[seg_idx, 0], u_segs[seg_idx, 1]
355
+ vx, vy = v_segs[seg_idx, 0], v_segs[seg_idx, 1]
356
+ hs = h_segs[seg_idx]
357
+ else:
358
+ n_sup = len(sup_pts)
359
+ ux = np.full(n_sup, u_segs[0, 0], dtype=np.float64)
360
+ uy = np.full(n_sup, u_segs[0, 1], dtype=np.float64)
361
+ vx = np.full(n_sup, v_segs[0, 0], dtype=np.float64)
362
+ vy = np.full(n_sup, v_segs[0, 1], dtype=np.float64)
363
+ hs = np.full(n_sup, h_segs[0], dtype=np.float64)
364
+
365
+ theta2 = 2.0 * np.arctan2(uy, ux)
366
+ sd_norm = np.clip(sd[sup_mask] / np.maximum(hs, 1.0), 0.0, 2.0)
367
+ vals = np.stack([
368
+ np.cos(theta2), np.sin(theta2),
369
+ ux, uy,
370
+ vx, vy,
371
+ np.log(np.maximum(hs, 1.0) / LOG_SCALE),
372
+ sd_norm,
373
+ ], axis=0).astype(np.float32)
374
+
375
+ g_roi = geo_gt[:, y0:y1, x0:x1]
376
+ g_roi[:, sup_mask] = vals
377
+ w_inst = 1.0 / float(sup_mask.sum())
378
+ geo_w[y0:y1, x0:x1][sup_mask] = w_inst
379
+ dir_w[y0:y1, x0:x1][sup_mask] = 0.0 if word.get('dir_ignore', False) else w_inst
380
+
381
+ kern_sep_mask = ((kern_touch >= 2) & (kernel_gt < 0.5) & (valid_mask > 0.5)).astype(np.float32)
382
+ kern_rim_mask = ((prob_gt > 0.5) & (kernel_gt < 0.5) & (valid_mask > 0.5)).astype(np.float32)
383
+ prob_sep_mask = ((prob_touch >= 2) & (prob_gt < 0.5) & (valid_mask > 0.5)).astype(np.float32)
384
+
385
+ return {
386
+ 'prob_gt': prob_gt[None].astype(np.float32),
387
+ 'valid_mask': valid_mask[None].astype(np.float32),
388
+ 'kernel_gt': kernel_gt[None].astype(np.float32),
389
+ 'thresh_gt': thresh_gt[None].astype(np.float32),
390
+ 'thresh_mask': thresh_mask[None].astype(np.float32),
391
+ 'kern_sep_mask': kern_sep_mask[None].astype(np.float32),
392
+ 'kern_rim_mask': kern_rim_mask[None].astype(np.float32),
393
+ 'prob_sep_mask': prob_sep_mask[None].astype(np.float32),
394
+ 'geo_gt': geo_gt.astype(np.float32),
395
+ 'geo_w': geo_w[None].astype(np.float32),
396
+ 'dir_w': dir_w[None].astype(np.float32),
397
+ 'n_words': np.array([n_pos_words], dtype=np.int32),
398
+ }
399
+
400
+
401
+ def collate_det_targets(batch_items: list[tuple[np.ndarray, dict]]) -> tuple[np.ndarray, dict]:
402
+ images = np.stack([img for img, _ in batch_items], axis=0).transpose(0, 3, 1, 2).astype(np.float32)
403
+ images = np.ascontiguousarray((images / 255.0 - 0.5) / 0.25)
404
+ keys = (
405
+ 'prob_gt', 'valid_mask', 'kernel_gt', 'thresh_gt', 'thresh_mask',
406
+ 'kern_sep_mask', 'kern_rim_mask', 'prob_sep_mask',
407
+ 'geo_gt', 'geo_w', 'dir_w',
408
+ )
409
+ out = {k: np.stack([t[k] for _, t in batch_items], axis=0) for k in keys}
410
+ out['n_words'] = int(sum(int(t['n_words'][0]) for _, t in batch_items))
411
+ return images, out
412
+
413
+
414
+ # ---------------------------------------------------------------------------- Losses
415
+
416
+ def _ohem_mask(prob_pred_np: np.ndarray, prob_gt_np: np.ndarray, valid_np: np.ndarray, ratio: float = 3.0) -> np.ndarray:
417
+ """Hard negative mining mask (1:ratio pos:neg) computed per batch on valid background pixels."""
418
+ pos = (prob_gt_np > 0.5) & (valid_np > 0.5)
419
+ neg = (prob_gt_np <= 0.5) & (valid_np > 0.5)
420
+ n_pos = int(pos.sum())
421
+ n_neg_keep = max(256, int(ratio * max(n_pos, 1)))
422
+ neg_scores = np.where(neg, prob_pred_np, -1.0).ravel()
423
+ total_neg = int(neg.sum())
424
+ if total_neg <= n_neg_keep:
425
+ return (pos | neg).astype(np.float32)
426
+ kth = neg_scores.size - n_neg_keep
427
+ thresh = np.partition(neg_scores, kth)[kth]
428
+ hard_neg = neg & (prob_pred_np >= thresh)
429
+ return (pos | hard_neg).astype(np.float32)
430
+
431
+
432
+ def det_losses(
433
+ outputs: tuple[ag.Node, ag.Node, ag.Node, ag.Node],
434
+ targets: dict,
435
+ *,
436
+ db_k: float = 50.0,
437
+ ) -> tuple[ag.Node, dict[str, ag.Node]]:
438
+ prob_logits, thresh, kernel_logits, geo = outputs
439
+ q = prob_logits.value.queue
440
+
441
+ prob_gt = constant(q, targets['prob_gt'])
442
+ valid = constant(q, targets['valid_mask'])
443
+ kern_gt = constant(q, targets['kernel_gt'])
444
+ thresh_gt = constant(q, targets['thresh_gt'])
445
+ thresh_mask = constant(q, targets['thresh_mask'])
446
+ geo_gt = constant(q, targets['geo_gt'])
447
+ geo_w = constant(q, targets['geo_w'])
448
+ dir_w = constant(q, targets['dir_w'])
449
+
450
+ prob = ag.sigmoid(prob_logits)
451
+ kern = ag.sigmoid(kernel_logits)
452
+
453
+ # 1. OHEM-BCE + Dice on full-word probability
454
+ prob_np = prob.value.to_host()
455
+ ohem_np = _ohem_mask(prob_np, targets['prob_gt'], targets['valid_mask'], ratio=3.0)
456
+ ohem = constant(q, ohem_np)
457
+ n_ohem = max(1.0, float(ohem_np.sum()))
458
+ loss_prob_bce = ag.sum(ohem * (ag.softplus(prob_logits) - prob_gt * prob_logits)) / n_ohem
459
+ loss_prob_dice = 1.0 - (2.0 * ag.sum(prob * prob_gt * valid) + 1.0) / (
460
+ ag.sum(prob * valid) + ag.sum(prob_gt * valid) + 1.0
461
+ )
462
+
463
+ # 2. Differentiable Binarization map Dice loss
464
+ bin_map = ag.sigmoid(db_k * (prob - thresh))
465
+ loss_bin = 1.0 - (2.0 * ag.sum(bin_map * prob_gt * valid) + 1.0) / (
466
+ ag.sum(bin_map * valid) + ag.sum(prob_gt * valid) + 1.0
467
+ )
468
+
469
+ # 3. Threshold border L1 loss inside border band
470
+ n_tm = max(1.0, float(targets['thresh_mask'].sum()))
471
+ loss_thresh = ag.sum(thresh_mask * ag.abs(thresh - thresh_gt)) / n_tm
472
+
473
+ # 4. Kernel OHEM-BCE + Dice loss + explicit inter-word separation losses
474
+ kern_np = kern.value.to_host()
475
+ kohem_np = _ohem_mask(kern_np, targets['kernel_gt'], targets['valid_mask'], ratio=3.0)
476
+ kohem = constant(q, kohem_np)
477
+ n_kohem = max(1.0, float(kohem_np.sum()))
478
+ loss_kern_bce = ag.sum(kohem * (ag.softplus(kernel_logits) - kern_gt * kernel_logits)) / n_kohem
479
+ loss_kern_dice = 1.0 - (2.0 * ag.sum(kern * kern_gt * valid) + 1.0) / (
480
+ ag.sum(kern * valid) + ag.sum(kern_gt * valid) + 1.0
481
+ )
482
+
483
+ ksep_np = targets.get('kern_sep_mask')
484
+ psep_np = targets.get('prob_sep_mask')
485
+ ksep = constant(q, ksep_np if ksep_np is not None else np.zeros_like(targets['kernel_gt']))
486
+ psep = constant(q, psep_np if psep_np is not None else np.zeros_like(targets['prob_gt']))
487
+ n_ksep = max(1.0, float(ksep_np.sum()) if ksep_np is not None else 0.0)
488
+ n_psep = max(1.0, float(psep_np.sum()) if psep_np is not None else 0.0)
489
+ loss_kern_sep = ag.sum(ksep * ag.softplus(kernel_logits)) / n_ksep
490
+ loss_prob_sep = ag.sum(psep * ag.softplus(prob_logits)) / n_psep
491
+
492
+ # 5. Geometry losses (axis cos2t/sin2t, directed tangent u, glyph-up v, log_h, sd_norm)
493
+ ch = lambda t, k: ag.narrow(t, 1, k, 1)
494
+
495
+ def cos_dist(c_idx, s_idx):
496
+ a, b = ch(geo, c_idx), ch(geo, s_idx)
497
+ norm = ag.sqrt(a * a + b * b + 1e-4)
498
+ return 1.0 - (a * ch(geo_gt, c_idx) + b * ch(geo_gt, s_idx)) / norm
499
+
500
+ n_words = max(1.0, float(targets['n_words']))
501
+ n_dir = max(1.0, float((targets['dir_w'].sum() > 0) and targets['n_words'] or 1))
502
+ loss_axis = ag.sum(geo_w * cos_dist(0, 1)) / n_words
503
+ loss_dir = ag.sum(dir_w * (cos_dist(2, 3) + 0.75 * cos_dist(4, 5))) / n_dir
504
+ loss_size = ag.sum(geo_w * (ag.abs(ch(geo, 6) - ch(geo_gt, 6)) + 0.5 * ag.abs(ch(geo, 7) - ch(geo_gt, 7)))) / n_words
505
+
506
+ total = (
507
+ loss_prob_bce + loss_prob_dice
508
+ + 1.0 * loss_bin
509
+ + 2.0 * loss_thresh
510
+ + 1.0 * (loss_kern_bce + loss_kern_dice)
511
+ + 0.8 * loss_kern_sep
512
+ + 0.5 * loss_prob_sep
513
+ + 1.5 * loss_axis + 1.2 * loss_dir + 1.0 * loss_size
514
+ )
515
+ parts = {
516
+ 'prob': loss_prob_bce + loss_prob_dice,
517
+ 'bin': loss_bin,
518
+ 'thresh': loss_thresh,
519
+ 'kernel': loss_kern_bce + loss_kern_dice,
520
+ 'sep': loss_kern_sep + loss_prob_sep,
521
+ 'geo': loss_axis + loss_dir + loss_size,
522
+ }
523
+ return total, parts
524
+
525
+
526
+ # ---------------------------------------------------------------------------- Pure-NumPy Vision & Decoder
527
+
528
+
529
+ def _connected_components_8_with_stats(mask: np.ndarray) -> tuple[int, np.ndarray, np.ndarray]:
530
+ """Exact 8-connected components with stats [left, top, width, height, area] in pure NumPy."""
531
+ h, w = mask.shape
532
+ labels = np.zeros((h, w), dtype=np.int32)
533
+ padded = np.zeros((h, w + 2), dtype=np.int8)
534
+ padded[:, 1:-1] = (mask > 0).astype(np.int8)
535
+ diff = np.diff(padded, axis=1)
536
+ r_start, c_start = np.nonzero(diff == 1)
537
+ r_end, c_end = np.nonzero(diff == -1)
538
+ if r_start.size == 0:
539
+ return 1, labels, np.zeros((1, 5), dtype=np.int32)
540
+
541
+ n_runs = int(r_start.size)
542
+ parent = list(range(n_runs))
543
+ rs_list = r_start.tolist()
544
+ cs_list = c_start.tolist()
545
+ ce_list = c_end.tolist()
546
+
547
+ # Row-to-run index boundaries
548
+ row_ranges: list[tuple[int, int]] = [(0, 0)] * h
549
+ i = 0
550
+ while i < n_runs:
551
+ r = rs_list[i]
552
+ j = i + 1
553
+ while j < n_runs and rs_list[j] == r:
554
+ j += 1
555
+ row_ranges[r] = (i, j)
556
+ i = j
557
+
558
+ def find(x: int) -> int:
559
+ while parent[x] != x:
560
+ parent[x] = parent[parent[x]]
561
+ x = parent[x]
562
+ return x
563
+
564
+ def union(a: int, b: int) -> None:
565
+ ra, rb = find(a), find(b)
566
+ if ra != rb:
567
+ if ra < rb:
568
+ parent[rb] = ra
569
+ else:
570
+ parent[ra] = rb
571
+
572
+ for r in range(1, h):
573
+ p0, p1 = row_ranges[r - 1]
574
+ c0, c1 = row_ranges[r]
575
+ if p0 == p1 or c0 == c1:
576
+ continue
577
+ pi, ci = p0, c0
578
+ while pi < p1 and ci < c1:
579
+ ps, pe = cs_list[pi], ce_list[pi]
580
+ cs_, ce_ = cs_list[ci], ce_list[ci]
581
+ # 8-connected overlap: [ps - 1, pe] intersects [cs_, ce_ - 1]
582
+ if ps <= ce_ and cs_ <= pe:
583
+ union(pi, ci)
584
+ if pe < ce_:
585
+ pi += 1
586
+ else:
587
+ ci += 1
588
+
589
+ # Assign dense component IDs in raster run order (matching cv.connectedComponentsWithStats order)
590
+ root_to_cid: dict[int, int] = {}
591
+ run_cid = [0] * n_runs
592
+ min_x = [0]
593
+ max_x = [0]
594
+ min_y = [0]
595
+ max_y = [0]
596
+ areas = [0]
597
+
598
+ for k in range(n_runs):
599
+ rk = find(k)
600
+ cid = root_to_cid.get(rk)
601
+ r = rs_list[k]
602
+ s = cs_list[k]
603
+ e = ce_list[k]
604
+ if cid is None:
605
+ cid = len(root_to_cid) + 1
606
+ root_to_cid[rk] = cid
607
+ min_x.append(s)
608
+ max_x.append(e)
609
+ min_y.append(r)
610
+ max_y.append(r + 1)
611
+ areas.append(e - s)
612
+ else:
613
+ if s < min_x[cid]:
614
+ min_x[cid] = s
615
+ if e > max_x[cid]:
616
+ max_x[cid] = e
617
+ if r + 1 > max_y[cid]:
618
+ max_y[cid] = r + 1
619
+ areas[cid] += (e - s)
620
+ run_cid[k] = cid
621
+ labels[r, s:e] = cid
622
+
623
+ n_lbl = len(root_to_cid) + 1
624
+ stats = np.zeros((n_lbl, 5), dtype=np.int32)
625
+ stats[0, :] = [0, 0, w, h, h * w - int(sum(areas[1:]))]
626
+ for cid in range(1, n_lbl):
627
+ stats[cid, 0] = min_x[cid]
628
+ stats[cid, 1] = min_y[cid]
629
+ stats[cid, 2] = max_x[cid] - min_x[cid]
630
+ stats[cid, 3] = max_y[cid] - min_y[cid]
631
+ stats[cid, 4] = areas[cid]
632
+ return n_lbl, labels, stats
633
+
634
+
635
+ def _voronoi_bounded_exact(k_lbl: np.ndarray, active_mask: np.ndarray, max_r: int) -> np.ndarray:
636
+ """Exact 2-pass separable Euclidean Voronoi owner map within radius `max_r` on `active_mask`."""
637
+ h, w = k_lbl.shape
638
+ INF = np.int32(1 << 28)
639
+ seed_mask = k_lbl > 0
640
+ ys_idx = np.arange(h, dtype=np.int32)[:, None]
641
+
642
+ seed_y = np.where(seed_mask, ys_idx, np.int32(-1000000))
643
+ above_y = np.maximum.accumulate(seed_y, axis=0)
644
+ seed_y_rev = np.where(seed_mask[::-1], ys_idx[::-1], np.int32(1000000))
645
+ below_y = np.minimum.accumulate(seed_y_rev, axis=0)[::-1]
646
+
647
+ da = ys_idx - above_y
648
+ db = below_y - ys_idx
649
+ use_above = da <= db
650
+ best_dy = np.where(use_above, da, db)
651
+ best_sy = np.where(use_above, above_y, below_y)
652
+
653
+ valid_v = best_dy <= max_r
654
+ best_dy2 = np.where(valid_v, best_dy * best_dy, INF)
655
+ best_sy_safe = np.clip(best_sy, 0, h - 1)
656
+ xs_idx = np.arange(w, dtype=np.int32)[None, :]
657
+ col_owner = np.where(valid_v, k_lbl[best_sy_safe, xs_idx], np.int32(0))
658
+
659
+ ay, ax = np.nonzero(active_mask & (~seed_mask))
660
+ owner = k_lbl.copy()
661
+ if ay.size == 0:
662
+ return owner
663
+
664
+ best_d2 = best_dy2[ay, ax].copy()
665
+ best_own = col_owner[ay, ax].copy()
666
+ max_r2 = max_r * max_r
667
+ for dx in range(1, max_r + 1):
668
+ dx2 = np.int32(dx * dx)
669
+ ok_l = ax >= dx
670
+ if ok_l.any():
671
+ idx = np.nonzero(ok_l)[0]
672
+ cand = best_dy2[ay[idx], ax[idx] - dx] + dx2
673
+ better = (cand < best_d2[idx]) & (cand <= max_r2)
674
+ if better.any():
675
+ bidx = idx[better]
676
+ best_d2[bidx] = cand[better]
677
+ best_own[bidx] = col_owner[ay[bidx], ax[bidx] - dx]
678
+ ok_r = (ax + dx) < w
679
+ if ok_r.any():
680
+ idx = np.nonzero(ok_r)[0]
681
+ cand = best_dy2[ay[idx], ax[idx] + dx] + dx2
682
+ better = (cand < best_d2[idx]) & (cand <= max_r2)
683
+ if better.any():
684
+ bidx = idx[better]
685
+ best_d2[bidx] = cand[better]
686
+ best_own[bidx] = col_owner[ay[bidx], ax[bidx] + dx]
687
+
688
+ owner[ay, ax] = best_own
689
+ return owner
690
+
691
+
692
+ def _edt_from_seeds_2d(seed_mask: np.ndarray) -> np.ndarray:
693
+ """Exact 2-pass Euclidean distance from each pixel to the nearest True pixel in `seed_mask`."""
694
+ h, w = seed_mask.shape
695
+ INF = np.int32(1 << 28)
696
+ ys_idx = np.arange(h, dtype=np.int32)[:, None]
697
+ seed_y = np.where(seed_mask, ys_idx, np.int32(-1000000))
698
+ above_y = np.maximum.accumulate(seed_y, axis=0)
699
+ seed_y_rev = np.where(seed_mask[::-1], ys_idx[::-1], np.int32(1000000))
700
+ below_y = np.minimum.accumulate(seed_y_rev, axis=0)[::-1]
701
+ best_dy = np.minimum(ys_idx - above_y, below_y - ys_idx)
702
+ col_d2 = np.where(best_dy < max(h, w) + 2, best_dy * best_dy, INF)
703
+
704
+ out_d2 = col_d2.copy()
705
+ for dx in range(1, w):
706
+ dx2 = np.int32(dx * dx)
707
+ out_d2[:, dx:] = np.minimum(out_d2[:, dx:], col_d2[:, :-dx] + dx2)
708
+ out_d2[:, :-dx] = np.minimum(out_d2[:, :-dx], col_d2[:, dx:] + dx2)
709
+ return np.sqrt(out_d2.astype(np.float32))
710
+
711
+
712
+ def _rdp_simplify(pts: np.ndarray, eps: float) -> np.ndarray:
713
+ """Iterative Ramer-Douglas-Peucker polyline simplification on closed ring."""
714
+ n = len(pts)
715
+ if n <= 4:
716
+ return pts
717
+ keep = np.zeros(n, dtype=bool)
718
+ keep[0] = True
719
+ keep[-1] = True
720
+ stack = [(0, n - 1)]
721
+ while stack:
722
+ s, e = stack.pop()
723
+ if e - s <= 1:
724
+ continue
725
+ a, b = pts[s], pts[e]
726
+ ab = b - a
727
+ ab2 = float(ab[0] * ab[0] + ab[1] * ab[1])
728
+ seg = pts[s + 1:e]
729
+ if ab2 <= 1e-12:
730
+ d2 = np.sum((seg - a) ** 2, axis=1)
731
+ else:
732
+ cross = (seg[:, 0] - a[0]) * ab[1] - (seg[:, 1] - a[1]) * ab[0]
733
+ d2 = (cross * cross) / ab2
734
+ idx = int(np.argmax(d2))
735
+ if d2[idx] > eps * eps:
736
+ mid = s + 1 + idx
737
+ keep[mid] = True
738
+ stack.append((s, mid))
739
+ stack.append((mid, e))
740
+ return pts[keep]
741
+
742
+
743
+ def _extract_curved_polygon(expanded: np.ndarray) -> np.ndarray | None:
744
+ """Moore-neighbor outer boundary trace + RDP simplification on local binary mask."""
745
+ n_c, c_lbl, c_stats = _connected_components_8_with_stats(expanded)
746
+ if n_c <= 1:
747
+ return None
748
+ best_cid = 1 + int(np.argmax(c_stats[1:, 4]))
749
+ mask = (c_lbl == best_cid)
750
+ ys, xs = np.nonzero(mask)
751
+ if ys.size < 4:
752
+ return None
753
+ h, w = mask.shape
754
+ # Pad by 1 False pixel on all sides to simplify boundary checks
755
+ pad = np.zeros((h + 2, w + 2), dtype=bool)
756
+ pad[1:-1, 1:-1] = mask
757
+ sy, sx = int(ys[0]) + 1, int(xs[0]) + 1
758
+ # Top-leftmost pixel has (sy, sx - 1) empty -> start backtrack there
759
+ # 8-neighbor CW offsets from (dy, dx): N, NE, E, SE, S, SW, W, NW
760
+ dirs = [(-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1)]
761
+ # Direction index from (sy, sx) to (sy, sx - 1) is 6 (W)
762
+ back_dir = 6
763
+ cy, cx = sy, sx
764
+ contour = [(float(cx - 1), float(cy - 1))]
765
+ max_steps = int(mask.sum()) * 4 + 16
766
+ for _ in range(max_steps):
767
+ start_d = (back_dir + 1) % 8
768
+ found = False
769
+ for k in range(8):
770
+ d = (start_d + k) % 8
771
+ ny, nx = cy + dirs[d][0], cx + dirs[d][1]
772
+ if pad[ny, nx]:
773
+ prev_d = (d + 7) % 8
774
+ # Next backtrack direction relative to new pixel (ny, nx) points back toward the last empty pixel
775
+ py, px = cy + dirs[prev_d][0], cx + dirs[prev_d][1]
776
+ back_dir = next(
777
+ (idx for idx, (ody, odx) in enumerate(dirs) if ny + ody == py and nx + odx == px),
778
+ (d + 4) % 8,
779
+ )
780
+ cy, cx = ny, nx
781
+ found = True
782
+ break
783
+ if not found or (cy == sy and cx == sx and len(contour) > 2):
784
+ break
785
+ contour.append((float(cx - 1), float(cy - 1)))
786
+
787
+ if len(contour) < 4:
788
+ return None
789
+ pts = np.asarray(contour, dtype=np.float64)
790
+ # Closed perimeter
791
+ segs = np.linalg.norm(np.roll(pts, -1, axis=0) - pts, axis=1)
792
+ perim = float(segs.sum())
793
+ eps = max(1.0, 0.015 * perim)
794
+ # Run RDP from farthest pair split so closed ring simplifies symmetrically
795
+ d_mat = np.sum((pts - pts[0]) ** 2, axis=1)
796
+ split = int(np.argmax(d_mat))
797
+ part1 = _rdp_simplify(pts[:split + 1], eps)
798
+ part2 = _rdp_simplify(np.vstack([pts[split:], pts[:1]]), eps)
799
+ poly = np.vstack([part1[:-1], part2[:-1]])
800
+ return poly if len(poly) >= 4 else None
801
+
802
+
803
+ def _trace_centerline(pts: np.ndarray, ux: np.ndarray, uy: np.ndarray, n_pts: int = 8) -> np.ndarray:
804
+ """Order curved component interior points into a smooth reading-direction centerline."""
805
+ if len(pts) < 4:
806
+ return pts[:2] if len(pts) >= 2 else np.vstack([pts, pts])
807
+ # Fit rough curvature center via dominant mean tangent vs perpendicular spread, or greedy chain
808
+ u_mean = np.array([ux.mean(), uy.mean()], dtype=np.float64)
809
+ u_mean /= max(float(np.linalg.norm(u_mean)), 1e-6)
810
+ v_mean = np.array([u_mean[1], -u_mean[0]], dtype=np.float64)
811
+ # Angular sweep check around centroid offset along -v_mean (center of circle for arcs)
812
+ c = pts.mean(axis=0)
813
+ # Check correlation between position along v_mean and angle change
814
+ proj_u = (pts - c) @ u_mean
815
+ order = np.argsort(proj_u)
816
+ sorted_pts = pts[order]
817
+ # Check if endpoints curl back (U-turn > 120 deg); if so, order by polar angle around curvature center
818
+ angs = np.unwrap(np.arctan2(uy, ux))
819
+ span = float(angs.max() - angs.min())
820
+ if span > math.radians(80):
821
+ # Estimate circle center from normals of first & last thirds
822
+ pts_u = sorted_pts
823
+ n_q = max(1, len(pts_u) // 4)
824
+ p1, p2 = pts_u[:n_q].mean(0), pts_u[-n_q:].mean(0)
825
+ # Midpoint + perpendicular bisector
826
+ center_est = c - v_mean * float(np.linalg.norm(p2 - p1)) * 0.6
827
+ rel = pts - center_est
828
+ ang_p = np.arctan2(rel[:, 1], rel[:, 0])
829
+ # Determine CW vs CCW from mean cross product (rel x u)
830
+ cross = rel[:, 0] * uy - rel[:, 1] * ux
831
+ if cross.mean() < 0:
832
+ ang_p = -ang_p
833
+ # Unwrap around largest angular gap
834
+ s_idx = np.argsort(ang_p)
835
+ ang_s = ang_p[s_idx]
836
+ gaps = np.diff(np.append(ang_s, ang_s[0] + 2 * math.pi))
837
+ split = int(np.argmax(gaps))
838
+ s_idx = np.roll(s_idx, -(split + 1))
839
+ sorted_pts = pts[s_idx]
840
+
841
+ # Bin into n_pts equal-count segments along sorted_pts
842
+ bins = np.array_split(sorted_pts, min(n_pts, len(sorted_pts)))
843
+ return np.array([b.mean(axis=0) for b in bins if len(b) > 0], dtype=np.float64)
844
+
845
+
846
+ def decode_det(
847
+ prob_map: np.ndarray,
848
+ kernel_map: np.ndarray,
849
+ geo_map: np.ndarray,
850
+ *,
851
+ out_stride: int = OUT_STRIDE,
852
+ kernel_thresh: float = 0.45,
853
+ prob_thresh: float = 0.45,
854
+ min_score: float = 0.50,
855
+ min_area: int = 2,
856
+ ) -> list[dict]:
857
+ """Decode dense detector maps (single image: prob(H,W), kernel(H,W), geo(8,H,W)) -> list of detections.
858
+
859
+ Each detection dict has:
860
+ - 'quad': (4, 2) float64 [p0, p1, p2, p3] in input pixel coords (p0->p1 reading, p0->p3 glyph-up)
861
+ - 'polygon': (K, 2) float64 boundary polygon in pixel coords
862
+ - 'centerline': (M, 2) float64 centerline polyline
863
+ - 'score': float confidence
864
+ - 'height': float estimated word height in pixels
865
+ - 'is_curved': bool
866
+ """
867
+ fh, fw = prob_map.shape
868
+ seeds = ((kernel_map >= kernel_thresh) & (prob_map >= 0.25)).astype(np.uint8)
869
+ n_lbl, labels, stats = _connected_components_8_with_stats(seeds)
870
+ if n_lbl <= 1:
871
+ return []
872
+
873
+ # Build tight active ROI mask covering candidate strip + Voronoi margin (fast exact Voronoi)
874
+ pad_est = 12
875
+ # Estimate max needed expansion radius across components (matches per-component pad_c below)
876
+ max_dim = np.maximum(stats[1:, 2], stats[1:, 3])
877
+ min_dim = np.minimum(stats[1:, 2], stats[1:, 3])
878
+ est_r = int(min(32, max(pad_est, math.ceil(float(np.max(min_dim)) * 1.5) + 4)))
879
+ active_mask = np.zeros((fh, fw), dtype=bool)
880
+ for cid in range(1, n_lbl):
881
+ area_c = int(stats[cid, 4])
882
+ if area_c < min_area and not (area_c == 1 and min_area <= 2):
883
+ continue
884
+ x0_c, y0_c, bw_c, bh_c, _ = stats[cid]
885
+ pad_c_est = min(est_r, max(6, int(max(bw_c, bh_c) // 2) + 6))
886
+ active_mask[max(0, y0_c - pad_c_est):min(fh, y0_c + bh_c + pad_c_est),
887
+ max(0, x0_c - pad_c_est):min(fw, x0_c + bw_c + pad_c_est)] = True
888
+ owner = _voronoi_bounded_exact(labels, active_mask, max_r=est_r)
889
+ prob_fg = (prob_map >= prob_thresh)
890
+
891
+ detections = []
892
+ for cid in range(1, n_lbl):
893
+ area = int(stats[cid, 4])
894
+ single_cell_ok = (area == 1 and min_area <= 2)
895
+ if area < min_area and not single_cell_ok:
896
+ continue
897
+ x0, y0, bw, bh, _ = stats[cid]
898
+ comp_local = (labels[y0:y0 + bh, x0:x0 + bw] == cid)
899
+ ys_l, xs_l = np.nonzero(comp_local)
900
+ ys, xs = ys_l + y0, xs_l + x0
901
+
902
+ wt = np.maximum(kernel_map[ys, xs], 1e-4)
903
+ score = float(np.sum(prob_map[ys, xs] * wt) / np.sum(wt))
904
+ if score < min_score:
905
+ continue
906
+ if single_cell_ok and (score < max(min_score, 0.80) or float(kernel_map[ys, xs].max()) < max(kernel_thresh, 0.72)):
907
+ continue
908
+
909
+ g = geo_map[:, ys, xs] # (8, N)
910
+ pts = np.stack([(xs + 0.5) * out_stride, (ys + 0.5) * out_stride], axis=1)
911
+
912
+ # Weighted orientation integration
913
+ c2 = float(np.sum(g[0] * wt) / np.sum(wt))
914
+ s2 = float(np.sum(g[1] * wt) / np.sum(wt))
915
+ r2 = math.hypot(c2, s2)
916
+ t_axis = 0.5 * math.atan2(s2, c2)
917
+ u_ax = np.array([math.cos(t_axis), math.sin(t_axis)], dtype=np.float64)
918
+
919
+ uc = float(np.sum(g[2] * wt) / np.sum(wt))
920
+ us = float(np.sum(g[3] * wt) / np.sum(wt))
921
+ u_dir = np.array([uc, us], dtype=np.float64)
922
+ if np.dot(u_dir, u_ax) < 0:
923
+ u = -u_ax
924
+ else:
925
+ u = u_ax
926
+
927
+ vc = float(np.sum(g[4] * wt) / np.sum(wt))
928
+ vs = float(np.sum(g[5] * wt) / np.sum(wt))
929
+ v_pred = np.array([vc, vs], dtype=np.float64)
930
+ v_ortho = np.array([u[1], -u[0]], dtype=np.float64)
931
+ if np.linalg.norm(v_pred) > 0.25:
932
+ # Keep predicted skew/up polarity but guard against near-collinearity with u
933
+ v_norm = v_pred / np.linalg.norm(v_pred)
934
+ if abs(float(np.dot(v_norm, u))) < 0.55:
935
+ v = v_norm
936
+ else:
937
+ v = v_ortho if np.dot(v_ortho, v_norm) >= 0 else -v_ortho
938
+ else:
939
+ v = v_ortho
940
+
941
+ h_px = float(LOG_SCALE * math.exp(float(np.clip(np.sum(g[6] * wt) / np.sum(wt), -3.5, 4.5))))
942
+ h_px = max(h_px, 4.0)
943
+
944
+ # Curvature check: if axis varies smoothly along the component, treat as curved text
945
+ local_c2 = g[0] / np.maximum(np.hypot(g[0], g[1]), 1e-5)
946
+ local_s2 = g[1] / np.maximum(np.hypot(g[0], g[1]), 1e-5)
947
+ axis_coherence = math.hypot(float(np.mean(local_c2)), float(np.mean(local_s2)))
948
+ is_curved = (axis_coherence < 0.90) and (area >= 12)
949
+
950
+ # Straight quad reconstruction (always computed; primary for straight, fallback/bbox for curved)
951
+ # Decompose pts into skewed basis: p = a*u + b*v -> solve 2x2 basis matrix B = [u, v]
952
+ basis = np.column_stack([u, v])
953
+ det_b = float(np.linalg.det(basis))
954
+ if abs(det_b) < 0.3:
955
+ v = v_ortho
956
+ basis = np.column_stack([u, v])
957
+ inv_b = np.linalg.inv(basis).T
958
+ ab = pts @ inv_b # (N, 2) -> (along u, along v)
959
+ b_ctr = float(np.mean(ab[:, 1]))
960
+ ab_min, ab_max = float(ab[:, 0].min()), float(ab[:, 0].max())
961
+ a0_k = ab_min - SHRINK_RATIO * h_px - 0.5 * out_stride
962
+ a1_k = ab_max + SHRINK_RATIO * h_px + 0.5 * out_stride
963
+
964
+ # Refine and clamp ends along u strictly inside Voronoi-owned strip so boxes never bleed into neighbors
965
+ pad_c = max(3, int(math.ceil((SHRINK_RATIO * h_px + out_stride) / out_stride)) + 2)
966
+ rx0, ry0 = max(0, x0 - pad_c), max(0, y0 - pad_c)
967
+ rx1, ry1 = min(fw, x0 + bw + pad_c), min(fh, y0 + bh + pad_c)
968
+ own_roi = owner[ry0:ry1, rx0:rx1] == cid
969
+ if own_roi.any():
970
+ oy_l, ox_l = np.nonzero(own_roi)
971
+ opts = np.stack([(ox_l + rx0 + 0.5) * out_stride, (oy_l + ry0 + 0.5) * out_stride], axis=1)
972
+ o_ab = opts @ inv_b
973
+ strip = (np.abs(o_ab[:, 1] - b_ctr) <= 0.55 * h_px) & (o_ab[:, 0] >= a0_k - out_stride) & (o_ab[:, 0] <= a1_k + out_stride)
974
+ a0 = max(a0_k, float(o_ab[strip, 0].min()) - 0.5 * out_stride) if strip.any() else a0_k
975
+ a1 = min(a1_k, float(o_ab[strip, 0].max()) + 0.5 * out_stride) if strip.any() else a1_k
976
+
977
+ own_fg = own_roi & prob_fg[ry0:ry1, rx0:rx1]
978
+ if own_fg.any():
979
+ fy_l, fx_l = np.nonzero(own_fg)
980
+ fpts = np.stack([(fx_l + rx0 + 0.5) * out_stride, (fy_l + ry0 + 0.5) * out_stride], axis=1)
981
+ f_ab = fpts @ inv_b
982
+ near = (np.abs(f_ab[:, 1] - b_ctr) <= 0.65 * h_px) & (f_ab[:, 0] >= a0 - out_stride) & (f_ab[:, 0] <= a1 + out_stride)
983
+ if near.any():
984
+ a0 = 0.5 * (a0 + float(f_ab[near, 0].min()) - 0.5 * out_stride)
985
+ a1 = 0.5 * (a1 + float(f_ab[near, 0].max()) + 0.5 * out_stride)
986
+ if strip.any():
987
+ a0 = max(a0, float(o_ab[strip, 0].min()) - 0.5 * out_stride)
988
+ a1 = min(a1, float(o_ab[strip, 0].max()) + 0.5 * out_stride)
989
+ a0 = min(a0, ab_min - 0.5 * out_stride)
990
+ a1 = max(a1, ab_max + 0.5 * out_stride)
991
+ else:
992
+ a0, a1 = a0_k, a1_k
993
+
994
+ b_lo = b_ctr - 0.5 * h_px
995
+ b_hi = b_ctr + 0.5 * h_px
996
+ quad = np.array([
997
+ a0 * u + b_lo * v,
998
+ a1 * u + b_lo * v,
999
+ a1 * u + b_hi * v,
1000
+ a0 * u + b_hi * v,
1001
+ ], dtype=np.float64)
1002
+
1003
+ if is_curved:
1004
+ # Expand kernel mask outward on padded local ROI using exact distance transform (clamped by Voronoi owner)
1005
+ pad = max(3, int(math.ceil(SHRINK_RATIO * h_px / out_stride)) + 2)
1006
+ rx0, ry0 = max(0, x0 - pad), max(0, y0 - pad)
1007
+ rx1, ry1 = min(fw, x0 + bw + pad), min(fh, y0 + bh + pad)
1008
+ roi_seed = (labels[ry0:ry1, rx0:rx1] == cid)
1009
+ dist_out = _edt_from_seeds_2d(roi_seed)
1010
+ d_out_f = max(0.5, (SHRINK_RATIO * h_px) / out_stride)
1011
+ expanded = ((dist_out <= d_out_f) & (owner[ry0:ry1, rx0:rx1] == cid))
1012
+ approx = _extract_curved_polygon(expanded)
1013
+ if approx is not None:
1014
+ polygon = (approx + np.array([rx0 + 0.5, ry0 + 0.5])) * out_stride
1015
+ else:
1016
+ polygon = quad.copy()
1017
+ centerline = _trace_centerline(pts, g[2], g[3], n_pts=10)
1018
+ else:
1019
+ polygon = quad.copy()
1020
+ centerline = np.array([0.5 * (quad[0] + quad[3]), 0.5 * (quad[1] + quad[2])], dtype=np.float64)
1021
+
1022
+ detections.append({
1023
+ 'quad': quad,
1024
+ 'polygon': polygon,
1025
+ 'centerline': centerline,
1026
+ 'score': score,
1027
+ 'height': h_px,
1028
+ 'is_curved': bool(is_curved),
1029
+ })
1030
+
1031
+ detections.sort(key=lambda d: -d['score'])
1032
+ return detections
1033
+
1034
+
1035
+ # ---------------------------------------------------------------------------- Checkpointing
1036
+
1037
+ def save_detector(path: Path | str, model: GeoDBDet, metadata: dict, optimizer=None, ema_state=None) -> Path:
1038
+ arrays = {f'model.{k}': v for k, v in flatten_state_dict(model.state_dict(), arrays_only=True).items()}
1039
+ meta = dict(
1040
+ metadata,
1041
+ format=CHECKPOINT_FORMAT,
1042
+ widths=list(model.widths),
1043
+ fpn_dim=model.fpn_dim,
1044
+ norm=model.norm_type,
1045
+ global_layers=model.global_layers,
1046
+ )
1047
+ arrays['metadata'] = np.asarray(json.dumps(meta))
1048
+ if optimizer is not None:
1049
+ st = optimizer.state_dict()
1050
+ arrays['optimizer.t'] = np.asarray(st['t'], np.int64)
1051
+ for i, (m, v) in enumerate(st['moments']):
1052
+ arrays[f'optimizer.m{i}'] = m
1053
+ arrays[f'optimizer.v{i}'] = v
1054
+ if ema_state is not None:
1055
+ for k, v in ema_state.items():
1056
+ arrays[f'ema.{k}'] = v
1057
+ path = Path(path)
1058
+ path.parent.mkdir(parents=True, exist_ok=True)
1059
+ tmp = path.with_suffix('.tmp.npz')
1060
+ np.savez(tmp, **arrays)
1061
+ tmp.replace(path)
1062
+ return path
1063
+
1064
+
1065
+ def load_detector(path: Path | str, queue, *, with_optimizer: bool = False):
1066
+ with np.load(path, allow_pickle=False) as st:
1067
+ meta = json.loads(st['metadata'].item())
1068
+ if meta.get('format') != CHECKPOINT_FORMAT:
1069
+ raise ValueError(f'{path} is not a {CHECKPOINT_FORMAT} checkpoint')
1070
+ model = GeoDBDet(
1071
+ queue,
1072
+ widths=tuple(meta['widths']),
1073
+ fpn_dim=int(meta['fpn_dim']),
1074
+ norm=meta.get('norm', 'bn'),
1075
+ global_layers=int(meta.get('global_layers', 2)),
1076
+ )
1077
+ arrays = {k[6:]: st[k] for k in st.files if k.startswith('model.')}
1078
+ with spec_mode():
1079
+ expected = flatten_state_dict(model.state_dict(), arrays_only=True)
1080
+ if arrays.keys() != expected.keys():
1081
+ raise ValueError('Incompatible GeoDBDet weights')
1082
+ model.load_state_dict(arrays, strict=False)
1083
+ opt = None
1084
+ if with_optimizer and 'optimizer.t' in st.files:
1085
+ n = len(model.parameters())
1086
+ opt = {
1087
+ 't': int(st['optimizer.t'].item()),
1088
+ 'moments': [(st[f'optimizer.m{i}'], st[f'optimizer.v{i}']) for i in range(n)],
1089
+ }
1090
+ return (model, meta, opt) if with_optimizer else (model, meta)