torchocr 0.4.1__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.
torchocr/decoders.py ADDED
@@ -0,0 +1,283 @@
1
+ """Decoders that map model logits to human-readable strings."""
2
+
3
+ import json
4
+ import math
5
+ from pathlib import Path
6
+
7
+ import torch
8
+ from torch import Tensor
9
+
10
+
11
+ class CTCGreedyDecoder:
12
+ """Greedy CTC decoder for CRNN-style logits.
13
+
14
+ Implements the canonical CTC decoding rule: take the per-step argmax,
15
+ collapse consecutive duplicate indices (treating blanks as ordinary
16
+ symbols during the collapse), then remove the remaining blank
17
+ indices. Padding the recognizer's input with blanks therefore
18
+ encodes "same character twice" correctly.
19
+
20
+ Args:
21
+ charset: Character strings indexed by class id. The string at
22
+ ``charset[blank_index]`` is unused; only the index matters.
23
+ blank_index: Index of the CTC blank class. Default 0, matching
24
+ the convention used by ``torch.nn.CTCLoss``.
25
+ """
26
+
27
+ def __init__(self, charset: list[str], blank_index: int = 0) -> None:
28
+ if not 0 <= blank_index < len(charset):
29
+ raise ValueError(
30
+ f"blank_index {blank_index} is outside charset of size {len(charset)}."
31
+ )
32
+ self.charset = list(charset)
33
+ self.blank_index = blank_index
34
+
35
+ @property
36
+ def num_classes(self) -> int:
37
+ return len(self.charset)
38
+
39
+ def __call__(self, logits: Tensor) -> list[str]:
40
+ """Decode ``(T, B, num_classes)`` logits into a list of B strings."""
41
+ if logits.ndim != 3:
42
+ raise ValueError(
43
+ f"Expected logits of shape (T, B, num_classes); got {tuple(logits.shape)}."
44
+ )
45
+ if logits.shape[2] != self.num_classes:
46
+ raise ValueError(
47
+ f"Logits' num_classes={logits.shape[2]} does not match "
48
+ f"charset size {self.num_classes}."
49
+ )
50
+
51
+ indices = logits.argmax(dim=-1)
52
+ time_steps, batch_size = indices.shape
53
+ if time_steps == 0:
54
+ return [""] * batch_size
55
+
56
+ prev_equal = torch.zeros_like(indices, dtype=torch.bool)
57
+ prev_equal[1:] = indices[1:] == indices[:-1]
58
+ keep = (~prev_equal) & (indices != self.blank_index)
59
+
60
+ results: list[str] = []
61
+ for b in range(batch_size):
62
+ kept = indices[:, b][keep[:, b]].tolist()
63
+ results.append("".join(self.charset[i] for i in kept))
64
+ return results
65
+
66
+
67
+ _BOS = "\x02" # start-of-word context symbol
68
+ _EOS = "\x03" # end-of-word event
69
+
70
+
71
+ class CharNGramLM:
72
+ """Case-insensitive character n-gram language model (interpolated Witten-Bell).
73
+
74
+ ``P(c | h) = (C(h, c) + T(h) * P(c | h')) / (C(h) + T(h))`` where ``h'``
75
+ drops the oldest character of ``h``, ``T(h)`` counts the distinct
76
+ continuations of ``h`` and the recursion ends at a uniform distribution
77
+ over :attr:`vocabulary` (which includes an end-of-word event). Every
78
+ distribution therefore sums to one and unseen characters keep non-zero
79
+ mass. Text is lowercased, so the model judges spelling while the optical
80
+ model keeps choosing case.
81
+
82
+ Args:
83
+ counts: ``{context: {char: count}}`` for contexts of length
84
+ ``0 .. order - 1``.
85
+ order: n-gram order (context length + 1).
86
+ """
87
+
88
+ def __init__(self, counts: dict[str, dict[str, int]], order: int) -> None:
89
+ if order < 1:
90
+ raise ValueError(f"order must be >= 1; got {order}.")
91
+ self.order = order
92
+ self.counts = counts
93
+ self.vocabulary = sorted({c for continuations in counts.values() for c in continuations} | {_EOS})
94
+ self._totals = {h: sum(cs.values()) for h, cs in counts.items()}
95
+ self._cache: dict[tuple[str, str], float] = {}
96
+
97
+ @classmethod
98
+ def from_texts(cls, texts: list[str], order: int = 5) -> "CharNGramLM":
99
+ """Count n-grams over ``texts`` (one word or line each)."""
100
+ counts: dict[str, dict[str, int]] = {}
101
+ for text in texts:
102
+ chars = [_BOS] * (order - 1) + list(text.lower()) + [_EOS]
103
+ for i in range(order - 1, len(chars)):
104
+ for n in range(order): # contexts of length 0 .. order-1
105
+ context = "".join(chars[i - n : i])
106
+ bucket = counts.setdefault(context, {})
107
+ bucket[chars[i]] = bucket.get(chars[i], 0) + 1
108
+ return cls(counts, order)
109
+
110
+ def log_prob(self, history: str, char: str) -> float:
111
+ """``log P(char | history)``; ``char=""`` scores the end of the word."""
112
+ context = (_BOS * (self.order - 1) + history.lower())[-(self.order - 1) :] if self.order > 1 else ""
113
+ key = (context, char.lower() or _EOS)
114
+ if key not in self._cache:
115
+ self._cache[key] = math.log(self._prob(*key))
116
+ return self._cache[key]
117
+
118
+ def score(self, text: str) -> float:
119
+ """Total log-probability of ``text`` as a complete word."""
120
+ return sum(self.log_prob(text[:i], text[i]) for i in range(len(text))) + self.log_prob(text, "")
121
+
122
+ def _prob(self, context: str, char: str) -> float:
123
+ lower = self._prob(context[1:], char) if context else 1.0 / len(self.vocabulary)
124
+ continuations = self.counts.get(context)
125
+ if not continuations:
126
+ return lower
127
+ distinct, total = len(continuations), self._totals[context]
128
+ return (continuations.get(char, 0) + distinct * lower) / (total + distinct)
129
+
130
+ def save(self, path: str | Path) -> None:
131
+ Path(path).write_text(json.dumps({"order": self.order, "counts": self.counts}, ensure_ascii=False))
132
+
133
+ @classmethod
134
+ def load(cls, path: str | Path) -> "CharNGramLM":
135
+ state = json.loads(Path(path).read_text())
136
+ return cls(state["counts"], state["order"])
137
+
138
+
139
+ class CTCBeamDecoder:
140
+ """CTC prefix beam search with optional character-LM shallow fusion.
141
+
142
+ Implements the prefix beam search of Hannun et al. (2014): each prefix
143
+ tracks the probability of ending in blank and in its last character, so
144
+ "ll" (separated by a blank) and "l" (one repeated character) stay
145
+ distinct. When a character is appended its LM log-probability, scaled by
146
+ ``lm_weight``, is added; at the end every beam also pays the LM's
147
+ end-of-word probability. Frames whose blank probability exceeds
148
+ ``blank_skip`` are treated as pure blank and only the ``top_k`` most
149
+ likely characters are expanded per frame, which keeps a pure-Python
150
+ search fast on short words.
151
+
152
+ Args:
153
+ charset: Character strings indexed by class id.
154
+ beam_width: Prefixes kept per frame. Default 10.
155
+ lm: Optional :class:`CharNGramLM`.
156
+ lm_weight: LM scale in log space. Default 0.3.
157
+ blank_index: CTC blank class. Default 0.
158
+ top_k: Characters expanded per frame. Default 8.
159
+ blank_skip: Blank probability above which a frame is skipped. Default 0.999.
160
+ """
161
+
162
+ def __init__(
163
+ self,
164
+ charset: list[str],
165
+ beam_width: int = 10,
166
+ lm: CharNGramLM | None = None,
167
+ lm_weight: float = 0.3,
168
+ blank_index: int = 0,
169
+ top_k: int = 8,
170
+ blank_skip: float = 0.999,
171
+ ) -> None:
172
+ if not 0 <= blank_index < len(charset):
173
+ raise ValueError(f"blank_index {blank_index} is outside charset of size {len(charset)}.")
174
+ if beam_width < 1 or top_k < 1:
175
+ raise ValueError(f"beam_width and top_k must be >= 1; got {beam_width}, {top_k}.")
176
+ self.charset = list(charset)
177
+ self.beam_width = beam_width
178
+ self.lm = lm
179
+ self.lm_weight = lm_weight
180
+ self.blank_index = blank_index
181
+ self.top_k = top_k
182
+ self.blank_skip = blank_skip
183
+
184
+ @property
185
+ def num_classes(self) -> int:
186
+ return len(self.charset)
187
+
188
+ def __call__(self, logits: Tensor) -> list[str]:
189
+ """Decode ``(T, B, num_classes)`` logits into a list of B strings."""
190
+ if logits.ndim != 3:
191
+ raise ValueError(f"Expected logits of shape (T, B, num_classes); got {tuple(logits.shape)}.")
192
+ if logits.shape[2] != self.num_classes:
193
+ raise ValueError(
194
+ f"Logits' num_classes={logits.shape[2]} does not match charset size {self.num_classes}."
195
+ )
196
+ log_probs = logits.float().log_softmax(-1).detach().cpu()
197
+ k = min(self.top_k, self.num_classes - 1)
198
+ top = log_probs.topk(k + 1, dim=-1) # +1: the blank may be among them
199
+ return [self._decode(log_probs[:, b, self.blank_index], top.values[:, b], top.indices[:, b])
200
+ for b in range(log_probs.shape[1])]
201
+
202
+ def _decode(self, blank_lp: Tensor, top_lp: Tensor, top_ids: Tensor) -> str:
203
+ neg_inf = -math.inf
204
+ # prefix (tuple of class ids) -> (log P ending in blank, log P ending in last char)
205
+ beams: dict[tuple[int, ...], tuple[float, float]] = {(): (0.0, neg_inf)}
206
+ skip = math.log(self.blank_skip)
207
+ for t in range(blank_lp.shape[0]):
208
+ p_blank = float(blank_lp[t])
209
+ if p_blank > skip: # (almost) pure blank: every prefix just absorbs it
210
+ beams = {prefix: (_logsumexp(pb, pnb) + p_blank, neg_inf) for prefix, (pb, pnb) in beams.items()}
211
+ continue
212
+ candidates = [(int(c), float(lp)) for c, lp in zip(top_ids[t], top_lp[t]) if int(c) != self.blank_index]
213
+ nxt: dict[tuple[int, ...], list[float]] = {}
214
+
215
+ def add(prefix, pb=neg_inf, pnb=neg_inf):
216
+ entry = nxt.setdefault(prefix, [neg_inf, neg_inf])
217
+ entry[0] = _logsumexp(entry[0], pb)
218
+ entry[1] = _logsumexp(entry[1], pnb)
219
+
220
+ for prefix, (pb, pnb) in beams.items():
221
+ total = _logsumexp(pb, pnb)
222
+ add(prefix, pb=total + p_blank) # emit blank
223
+ last = prefix[-1] if prefix else None
224
+ for c, p in candidates:
225
+ if c == last:
226
+ add(prefix, pnb=pnb + p) # repeat collapses into the same prefix
227
+ if pb > neg_inf: # blank in between: a genuinely new character
228
+ add(prefix + (c,), pnb=pb + p + self._lm(prefix, c))
229
+ else:
230
+ add(prefix + (c,), pnb=total + p + self._lm(prefix, c))
231
+ beams = dict(sorted(((k, tuple(v)) for k, v in nxt.items()),
232
+ key=lambda kv: _logsumexp(*kv[1]), reverse=True)[: self.beam_width])
233
+
234
+ def final(item):
235
+ prefix, (pb, pnb) = item
236
+ end = self.lm_weight * self.lm.log_prob(self._text(prefix), "") if self.lm else 0.0
237
+ return _logsumexp(pb, pnb) + end
238
+
239
+ return self._text(max(beams.items(), key=final)[0])
240
+
241
+ def _lm(self, prefix: tuple[int, ...], c: int) -> float:
242
+ if self.lm is None:
243
+ return 0.0
244
+ return self.lm_weight * self.lm.log_prob(self._text(prefix), self.charset[c])
245
+
246
+ def _text(self, prefix: tuple[int, ...]) -> str:
247
+ return "".join(self.charset[i] for i in prefix)
248
+
249
+
250
+ def _logsumexp(a: float, b: float) -> float:
251
+ if a == -math.inf:
252
+ return b
253
+ if b == -math.inf:
254
+ return a
255
+ m = max(a, b)
256
+ return m + math.log(math.exp(a - m) + math.exp(b - m))
257
+
258
+
259
+ def build_decoder(
260
+ weights, charset: list[str], kind: str = "auto"
261
+ ) -> CTCGreedyDecoder | CTCBeamDecoder:
262
+ """The decoder a recognizer checkpoint was benchmarked with.
263
+
264
+ ``weights.meta["decoder"]`` may declare ``{"type": "ctc_beam",
265
+ "beam_width", "lm_weight", "lm_url"}``; the language model is downloaded
266
+ (hash-checked) on first use.
267
+
268
+ Args:
269
+ weights: A recognizer weights enum member.
270
+ charset: Its charset (``load_charset(meta["charset"], meta["num_classes"])``).
271
+ kind: ``"auto"`` (the declared decoder, else greedy), ``"greedy"`` or ``"beam"``.
272
+ """
273
+ if kind not in ("auto", "greedy", "beam"):
274
+ raise ValueError(f"kind must be 'auto', 'greedy' or 'beam'; got '{kind}'.")
275
+ spec = weights.meta.get("decoder")
276
+ if kind == "greedy" or (kind == "auto" and spec is None):
277
+ return CTCGreedyDecoder(charset)
278
+ if spec is None:
279
+ raise ValueError(f"{weights!r} does not declare a beam decoder in meta['decoder'].")
280
+ from .models import hub # lazy: keeps decoders importable on their own
281
+
282
+ lm = CharNGramLM.load(hub.download_asset(spec["lm_url"])) if spec.get("lm_url") else None
283
+ return CTCBeamDecoder(charset, beam_width=spec.get("beam_width", 10), lm=lm, lm_weight=spec.get("lm_weight", 0.3))
@@ -0,0 +1,21 @@
1
+ """I/O helpers for reading OCR inputs."""
2
+
3
+ from pathlib import Path
4
+
5
+ from torch import Tensor
6
+ from torchvision.io import ImageReadMode, decode_image
7
+
8
+ from .pdf import load_pdf
9
+
10
+
11
+ def load_image(path: str | Path, mode: ImageReadMode = ImageReadMode.RGB) -> Tensor:
12
+ """Load an image as a ``(C, H, W)`` ``uint8`` tensor, RGB by default.
13
+
14
+ Grayscale scans and RGBA screenshots are converted to the 3-channel RGB
15
+ that pretrained models and :class:`~torchocr.OCRPipeline` expect; pass
16
+ ``mode=ImageReadMode.UNCHANGED`` to keep the file's own channels.
17
+ """
18
+ return decode_image(str(path), mode=mode)
19
+
20
+
21
+ __all__ = ["load_image", "load_pdf"]
torchocr/io/pdf.py ADDED
@@ -0,0 +1,45 @@
1
+ """PDF loading via PyMuPDF (``import fitz``)."""
2
+
3
+ from pathlib import Path
4
+
5
+ import fitz
6
+ import numpy as np
7
+ import torch
8
+ from torch import Tensor
9
+
10
+
11
+ def load_pdf(path: str | Path, dpi: int = 200) -> list[Tensor]:
12
+ """Load a PDF and return one ``(3, H, W) uint8`` RGB tensor per page.
13
+
14
+ Each page is rendered to a PyMuPDF ``Pixmap`` at the requested DPI
15
+ and converted into a fresh PyTorch tensor that does not alias the
16
+ pixmap's underlying memory. The pixmap and its sample buffer are
17
+ released between pages, keeping peak memory bounded by the largest
18
+ single page rather than the whole document.
19
+
20
+ Args:
21
+ path: Filesystem path to the PDF.
22
+ dpi: Render resolution in dots-per-inch. Default 200 -- a sane
23
+ OCR baseline. PyMuPDF's native unit is the PostScript point
24
+ (1/72 inch); the conversion is ``Matrix(dpi/72, dpi/72)``.
25
+
26
+ Returns:
27
+ A list of ``(3, H, W) uint8`` tensors, one per page in document
28
+ order. Channel order is RGB.
29
+ """
30
+ if dpi <= 0:
31
+ raise ValueError(f"dpi must be positive; got {dpi}.")
32
+
33
+ matrix = fitz.Matrix(dpi / 72.0, dpi / 72.0)
34
+ pages: list[Tensor] = []
35
+
36
+ with fitz.open(str(path)) as document:
37
+ for page in document:
38
+ pixmap = page.get_pixmap(matrix=matrix, colorspace=fitz.csRGB, alpha=False)
39
+ arr_hwc = np.frombuffer(pixmap.samples, dtype=np.uint8).reshape(
40
+ pixmap.height, pixmap.width, 3
41
+ )
42
+ arr_chw = np.transpose(arr_hwc, (2, 0, 1)).copy()
43
+ pages.append(torch.from_numpy(arr_chw))
44
+
45
+ return pages
torchocr/losses.py ADDED
@@ -0,0 +1,208 @@
1
+ """Loss functions for training torchocr models."""
2
+
3
+ import torch
4
+ from torch import Tensor, nn
5
+ from torch.nn import functional as F
6
+
7
+ from .models.detection import DBNetOutput
8
+
9
+
10
+ class DBLoss(nn.Module):
11
+ """Differentiable Binarization training loss.
12
+
13
+ Combines the three components of Liao et al. (AAAI 2020):
14
+
15
+ 1. **Probability-map BCE with online hard example mining (OHEM).**
16
+ OHEM keeps every positive pixel plus the
17
+ ``negative_ratio * n_pos`` hardest negatives, preventing the
18
+ background class from drowning the loss.
19
+ 2. **Threshold-map L1 loss** restricted to the boundary band where
20
+ the GT threshold is non-zero.
21
+ 3. **Approximate-binary Dice loss** computed on
22
+ ``B_hat = sigmoid(k * (P - T))``. The factor ``k`` controls how
23
+ sharply this differentiable form approximates the true
24
+ Heaviside step ``P > T``: as ``k -> infinity`` ``B_hat`` becomes
25
+ a step function, but its gradient also vanishes away from the
26
+ decision boundary. The paper's ``k = 50`` is a tested
27
+ compromise -- a tight transition (``~0.04`` units in ``P - T``)
28
+ that still leaves backprop signal. Lower ``k`` flattens the
29
+ step toward ``0.5``; higher ``k`` starves the gradients.
30
+
31
+ Total loss: ``Lp + binary_weight * Lb + threshold_weight * Lt``.
32
+
33
+ Args:
34
+ k: Steepness of the differentiable binarization. Default 50.
35
+ threshold_weight: Multiplier on the threshold-map L1 loss.
36
+ Default 10, matching the paper's beta.
37
+ binary_weight: Multiplier on the dice loss over the
38
+ approximate binary map. Default 1, matching the paper's
39
+ alpha. Set to 0 to disable the binary term entirely.
40
+ negative_ratio: Negatives-to-positives ratio for the OHEM
41
+ sampling in the probability BCE. Default 3.0.
42
+ eps: Numerical-stability epsilon for BCE clamping and Dice.
43
+ """
44
+
45
+ def __init__(
46
+ self,
47
+ k: float = 50.0,
48
+ threshold_weight: float = 10.0,
49
+ binary_weight: float = 1.0,
50
+ negative_ratio: float = 3.0,
51
+ eps: float = 1e-6,
52
+ ) -> None:
53
+ super().__init__()
54
+ if k <= 0:
55
+ raise ValueError(f"k must be positive; got {k}.")
56
+ if negative_ratio <= 0:
57
+ raise ValueError(f"negative_ratio must be positive; got {negative_ratio}.")
58
+ self.k = k
59
+ self.threshold_weight = threshold_weight
60
+ self.binary_weight = binary_weight
61
+ self.negative_ratio = negative_ratio
62
+ self.eps = eps
63
+
64
+ def forward(
65
+ self,
66
+ prediction: DBNetOutput,
67
+ gt_probability: Tensor,
68
+ gt_threshold: Tensor,
69
+ training_mask: Tensor | None = None,
70
+ ) -> dict[str, Tensor]:
71
+ """Compute DB loss components and their weighted sum.
72
+
73
+ Args:
74
+ prediction: Output of :class:`DBNet` for one batch.
75
+ gt_probability: ``(B, 1, H, W)`` 0/1 (or soft) text mask.
76
+ gt_threshold: ``(B, 1, H, W)`` float threshold-map target.
77
+ training_mask: Optional ``(B, 1, H, W)`` boolean tensor of
78
+ valid pixels. ``False`` entries are excluded from all
79
+ three losses (use this to ignore "don't care" regions
80
+ such as overlapping or illegible text).
81
+
82
+ Returns:
83
+ ``{"loss", "probability", "threshold", "binary"}``. Call
84
+ ``.backward()`` on the ``"loss"`` entry; log the others.
85
+ """
86
+ prob = prediction.probability
87
+ thresh = prediction.threshold
88
+ if prob.shape != gt_probability.shape or thresh.shape != gt_threshold.shape:
89
+ raise ValueError(
90
+ f"Predictions and targets must share shape; got prob {tuple(prob.shape)} vs "
91
+ f"{tuple(gt_probability.shape)}, threshold {tuple(thresh.shape)} vs "
92
+ f"{tuple(gt_threshold.shape)}."
93
+ )
94
+
95
+ if training_mask is None:
96
+ mask = torch.ones_like(gt_probability, dtype=torch.bool)
97
+ else:
98
+ mask = training_mask.to(torch.bool)
99
+
100
+ prob_loss = self._bce_ohem(prob, gt_probability, mask)
101
+ thresh_loss = self._threshold_l1(thresh, gt_threshold, mask)
102
+ binary_loss = self._dice(prob, thresh, gt_probability, mask)
103
+
104
+ total = (
105
+ prob_loss
106
+ + self.binary_weight * binary_loss
107
+ + self.threshold_weight * thresh_loss
108
+ )
109
+ return {
110
+ "loss": total,
111
+ "probability": prob_loss,
112
+ "threshold": thresh_loss,
113
+ "binary": binary_loss,
114
+ }
115
+
116
+ def _bce_ohem(self, pred: Tensor, target: Tensor, mask: Tensor) -> Tensor:
117
+ clamped = pred.clamp(min=self.eps, max=1.0 - self.eps)
118
+ losses = F.binary_cross_entropy(clamped, target, reduction="none")
119
+
120
+ positives = (target > 0.5) & mask
121
+ negatives = (target <= 0.5) & mask
122
+ n_pos = int(positives.sum().item())
123
+ n_neg_cap = int(negatives.sum().item())
124
+ n_neg = int(min(n_neg_cap, max(n_pos, 1) * self.negative_ratio))
125
+
126
+ if n_pos == 0 and n_neg == 0:
127
+ return (losses * mask).sum() / mask.sum().clamp(min=1)
128
+
129
+ pos_loss = losses[positives].sum() if n_pos > 0 else losses.new_zeros(())
130
+ if n_neg > 0:
131
+ neg_losses = losses[negatives]
132
+ if neg_losses.numel() > n_neg:
133
+ neg_loss = neg_losses.topk(n_neg)[0].sum()
134
+ else:
135
+ neg_loss = neg_losses.sum()
136
+ else:
137
+ neg_loss = losses.new_zeros(())
138
+ return (pos_loss + neg_loss) / max(n_pos + n_neg, 1)
139
+
140
+ def _threshold_l1(self, pred: Tensor, target: Tensor, mask: Tensor) -> Tensor:
141
+ active = mask & (target > 0)
142
+ if not active.any():
143
+ return pred.new_zeros(())
144
+ return F.l1_loss(pred[active], target[active])
145
+
146
+ def _dice(self, prob: Tensor, thresh: Tensor, target: Tensor, mask: Tensor) -> Tensor:
147
+ binary = torch.sigmoid(self.k * (prob - thresh))
148
+ valid = mask.to(binary.dtype)
149
+ binary = binary * valid
150
+ target = target * valid
151
+ intersection = (binary * target).sum()
152
+ return 1.0 - (2.0 * intersection + self.eps) / (binary.sum() + target.sum() + self.eps)
153
+
154
+
155
+ class CRNNLoss(nn.Module):
156
+ """Wrapper around :class:`torch.nn.CTCLoss` for CRNN-style logits.
157
+
158
+ Applies ``log_softmax`` to the recognizer's logits before
159
+ delegating to ``nn.CTCLoss``, which expects log probabilities.
160
+ The blank index defaults to 0, matching :class:`CTCGreedyDecoder`.
161
+
162
+ Args:
163
+ blank_index: CTC blank class index. Default 0.
164
+ reduction: Reduction passed to ``nn.CTCLoss`` -- 'mean', 'sum',
165
+ or 'none'. Default 'mean'.
166
+ zero_infinity: Whether to zero out infinite losses (caused by
167
+ input lengths shorter than target lengths). Default True
168
+ for training stability.
169
+ """
170
+
171
+ def __init__(
172
+ self,
173
+ blank_index: int = 0,
174
+ reduction: str = "mean",
175
+ zero_infinity: bool = True,
176
+ ) -> None:
177
+ super().__init__()
178
+ self.ctc = nn.CTCLoss(
179
+ blank=blank_index,
180
+ reduction=reduction,
181
+ zero_infinity=zero_infinity,
182
+ )
183
+
184
+ def forward(
185
+ self,
186
+ logits: Tensor,
187
+ targets: Tensor,
188
+ input_lengths: Tensor,
189
+ target_lengths: Tensor,
190
+ ) -> Tensor:
191
+ """Compute the CTC loss.
192
+
193
+ Args:
194
+ logits: ``(T, B, num_classes)`` raw recognizer outputs.
195
+ targets: Either ``(B, S_max)`` padded or
196
+ ``(sum(target_lengths),)`` concatenated label tensor,
197
+ per ``nn.CTCLoss`` convention.
198
+ input_lengths: ``(B,)`` int tensor giving each sequence's
199
+ effective length in time-steps.
200
+ target_lengths: ``(B,)`` int tensor giving each target's
201
+ length.
202
+ """
203
+ if logits.ndim != 3:
204
+ raise ValueError(
205
+ f"Expected logits of shape (T, B, num_classes); got {tuple(logits.shape)}."
206
+ )
207
+ log_probs = logits.log_softmax(dim=-1)
208
+ return self.ctc(log_probs, targets, input_lengths, target_lengths)
@@ -0,0 +1,6 @@
1
+ """Evaluation metrics for OCR tasks."""
2
+
3
+ from .detection import DetectionHmean, EndToEndHmean, HmeanResult
4
+ from .recognition import RecognitionAccuracy, RecognitionResult
5
+
6
+ __all__ = ["DetectionHmean", "EndToEndHmean", "HmeanResult", "RecognitionAccuracy", "RecognitionResult"]