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.
@@ -0,0 +1,9 @@
1
+ """OCR datasets with typed targets, mirroring ``torchvision.datasets``."""
2
+
3
+ from ..core.structures import TextDetectionTarget
4
+ from .funsd import FUNSD
5
+ from .icdar import ICDAR2015
6
+ from .lmdb_words import LMDBWords
7
+ from .totaltext import TotalText
8
+
9
+ __all__ = ["FUNSD", "ICDAR2015", "LMDBWords", "TextDetectionTarget", "TotalText"]
@@ -0,0 +1,90 @@
1
+ """FUNSD: word-level text in noisy scanned forms."""
2
+
3
+ import json
4
+ import re
5
+ from collections.abc import Callable
6
+ from pathlib import Path
7
+ from typing import Literal
8
+
9
+ import torch
10
+ from torch import Tensor
11
+ from torch.utils.data import Dataset
12
+ from torchvision.io import ImageReadMode, read_image
13
+
14
+ from ..core.structures import TextDetectionTarget
15
+
16
+
17
+ _SPLITS = {"train": "training_data", "test": "testing_data"}
18
+
19
+
20
+ class FUNSD(Dataset[tuple[Tensor, TextDetectionTarget]]):
21
+ """FUNSD (Jaume et al., ICDAR-OST 2019): 149 train / 50 test noisy scanned
22
+ business forms with word-level boxes and transcriptions.
23
+
24
+ A *document* benchmark, unlike ICDAR-2015 and Total-Text: use it to check
25
+ how a scene-text model transfers to scans. Words with an empty
26
+ transcription (check boxes, rules) are marked ``ignore``.
27
+
28
+ Download and unzip https://guillaumejaume.github.io/FUNSD/dataset.zip
29
+ (no registration); ``root`` is the extracted ``dataset`` folder::
30
+
31
+ root/training_data/{images,annotations}/ root/testing_data/{images,annotations}/
32
+
33
+ Args:
34
+ root: The extracted ``dataset`` directory.
35
+ split: ``"train"`` or ``"test"``. Default ``"test"``.
36
+ transforms: Optional callable ``(image, target) -> (image, target)``.
37
+
38
+ Returns:
39
+ ``(image, target)``: ``(3, H, W)`` ``uint8`` RGB (scans are
40
+ grayscale, replicated to three channels) and a
41
+ :class:`TextDetectionTarget` of axis-aligned ``(N, 4, 2)`` word quads.
42
+ """
43
+
44
+ def __init__(
45
+ self,
46
+ root: str | Path,
47
+ split: Literal["train", "test"] = "test",
48
+ transforms: Callable[[Tensor, TextDetectionTarget], tuple[Tensor, TextDetectionTarget]] | None = None,
49
+ ) -> None:
50
+ if split not in _SPLITS:
51
+ raise ValueError(f"split must be one of {sorted(_SPLITS)}; got '{split}'.")
52
+ self.root = Path(root)
53
+ self.split = split
54
+ self.transforms = transforms
55
+ base = self.root / _SPLITS[split]
56
+ self.annotations_dir = base / "annotations"
57
+ images_dir = base / "images"
58
+ if not images_dir.is_dir() or not self.annotations_dir.is_dir():
59
+ raise FileNotFoundError(
60
+ f"FUNSD '{split}' split not found under {self.root}: expected {_SPLITS[split]}/images and "
61
+ f"{_SPLITS[split]}/annotations. Unzip https://guillaumejaume.github.io/FUNSD/dataset.zip and "
62
+ "pass its 'dataset' folder."
63
+ )
64
+ self.image_paths = sorted(images_dir.glob("*.png"), key=_natural_key)
65
+
66
+ def __len__(self) -> int:
67
+ return len(self.image_paths)
68
+
69
+ def load_target(self, index: int) -> TextDetectionTarget:
70
+ """The annotations of sample ``index``, without decoding its image."""
71
+ form = json.loads((self.annotations_dir / f"{self.image_paths[index].stem}.json").read_text())["form"]
72
+ words = [word for entity in form for word in entity["words"]]
73
+ if not words:
74
+ return TextDetectionTarget(torch.zeros(0, 4, 2), [], torch.zeros(0, dtype=torch.bool))
75
+ boxes = torch.tensor([word["box"] for word in words], dtype=torch.float32)
76
+ x1, y1, x2, y2 = boxes.unbind(-1)
77
+ quads = torch.stack([torch.stack(p, -1) for p in ((x1, y1), (x2, y1), (x2, y2), (x1, y2))], dim=1)
78
+ texts = [word["text"] for word in words]
79
+ return TextDetectionTarget(quads, texts, torch.tensor([not t.strip() for t in texts]))
80
+
81
+ def __getitem__(self, index: int) -> tuple[Tensor, TextDetectionTarget]:
82
+ image = read_image(str(self.image_paths[index]), mode=ImageReadMode.RGB)
83
+ target = self.load_target(index)
84
+ if self.transforms is not None:
85
+ image, target = self.transforms(image, target)
86
+ return image, target
87
+
88
+
89
+ def _natural_key(path: Path) -> list:
90
+ return [int(part) if part.isdigit() else part for part in re.split(r"(\d+)", path.stem)]
@@ -0,0 +1,116 @@
1
+ """ICDAR Robust Reading datasets."""
2
+
3
+ import re
4
+ from collections.abc import Callable
5
+ from pathlib import Path
6
+ from typing import Literal
7
+
8
+ import torch
9
+ from torch import Tensor
10
+ from torch.utils.data import Dataset
11
+ from torchvision.io import ImageReadMode, read_image
12
+
13
+ from ..core.structures import TextDetectionTarget
14
+
15
+
16
+ _SPLITS = {
17
+ "train": ("ch4_training_images", "ch4_training_localization_transcription_gt"),
18
+ "test": ("ch4_test_images", "Challenge4_Test_Task1_GT"),
19
+ }
20
+ _DONT_CARE = "###"
21
+ _IMAGE_INDEX = re.compile(r"img_(\d+)\.jpg$")
22
+
23
+
24
+ class ICDAR2015(Dataset[tuple[Tensor, TextDetectionTarget]]):
25
+ """ICDAR 2015 Incidental Scene Text, Task 4.1 (text localization).
26
+
27
+ 1000 training and 500 test images of street-level scenes captured
28
+ with wearable cameras; text regions are word-level quadrilaterals.
29
+
30
+ The dataset requires registration, so it cannot be downloaded
31
+ automatically. Get the four archives from
32
+ https://rrc.cvc.uab.es/?ch=4&com=downloads and extract each into a
33
+ folder of the same name under ``root``::
34
+
35
+ root/
36
+ ch4_training_images/ img_1.jpg ...
37
+ ch4_training_localization_transcription_gt/ gt_img_1.txt ...
38
+ ch4_test_images/ img_1.jpg ...
39
+ Challenge4_Test_Task1_GT/ gt_img_1.txt ...
40
+
41
+ Args:
42
+ root: Directory holding the extracted archives.
43
+ split: ``"train"`` or ``"test"``. Default ``"test"``.
44
+ transforms: Optional callable ``(image, target) -> (image, target)``
45
+ applied to every sample.
46
+
47
+ Returns:
48
+ ``(image, target)`` where ``image`` is a ``(3, H, W)`` ``uint8``
49
+ RGB tensor and ``target`` a :class:`TextDetectionTarget` with
50
+ ``(N, 4, 2)`` polygons in original-image pixels.
51
+ """
52
+
53
+ def __init__(
54
+ self,
55
+ root: str | Path,
56
+ split: Literal["train", "test"] = "test",
57
+ transforms: Callable[[Tensor, TextDetectionTarget], tuple[Tensor, TextDetectionTarget]]
58
+ | None = None,
59
+ ) -> None:
60
+ if split not in _SPLITS:
61
+ raise ValueError(f"split must be one of {sorted(_SPLITS)}; got '{split}'.")
62
+ self.root = Path(root)
63
+ self.split = split
64
+ self.transforms = transforms
65
+
66
+ images_dir, gt_dir = (self.root / name for name in _SPLITS[split])
67
+ missing = [d.name for d in (images_dir, gt_dir) if not d.is_dir()]
68
+ if missing:
69
+ raise FileNotFoundError(
70
+ f"ICDAR2015 '{split}' split not found under {self.root} (missing: {', '.join(missing)}). "
71
+ "Download the archives from https://rrc.cvc.uab.es/?ch=4&com=downloads "
72
+ "(registration required) and extract each into a folder of the same name."
73
+ )
74
+ self.gt_dir = gt_dir
75
+ self.image_paths = sorted(
76
+ (p for p in images_dir.iterdir() if _IMAGE_INDEX.search(p.name)),
77
+ key=lambda p: int(_IMAGE_INDEX.search(p.name).group(1)),
78
+ )
79
+
80
+ def __len__(self) -> int:
81
+ return len(self.image_paths)
82
+
83
+ def load_target(self, index: int) -> TextDetectionTarget:
84
+ """The annotations of sample ``index``, without decoding its image."""
85
+ return _parse_ground_truth(self.gt_dir / f"gt_{self.image_paths[index].stem}.txt")
86
+
87
+ def __getitem__(self, index: int) -> tuple[Tensor, TextDetectionTarget]:
88
+ image = read_image(str(self.image_paths[index]), mode=ImageReadMode.RGB)
89
+ target = self.load_target(index)
90
+ if self.transforms is not None:
91
+ image, target = self.transforms(image, target)
92
+ return image, target
93
+
94
+
95
+ def _parse_ground_truth(path: Path) -> TextDetectionTarget:
96
+ """Parse ``x1,y1,...,x4,y4,transcription`` lines (UTF-8 with BOM, CRLF)."""
97
+ polygons: list[list[float]] = []
98
+ texts: list[str] = []
99
+ for line_no, line in enumerate(path.read_text(encoding="utf-8-sig").splitlines(), start=1):
100
+ if not line.strip():
101
+ continue
102
+ fields = line.split(",")
103
+ try:
104
+ if len(fields) < 9:
105
+ raise ValueError("expected 8 coordinates and a transcription")
106
+ coords = [float(v) for v in fields[:8]]
107
+ except ValueError as exc:
108
+ raise ValueError(f"{path}:{line_no}: malformed ICDAR line {line!r}.") from exc
109
+ polygons.append(coords)
110
+ # Transcriptions may themselves contain commas.
111
+ texts.append(",".join(fields[8:]))
112
+ return TextDetectionTarget(
113
+ polygons=torch.tensor(polygons, dtype=torch.float32).reshape(-1, 4, 2),
114
+ texts=texts,
115
+ ignore=torch.tensor([t == _DONT_CARE for t in texts], dtype=torch.bool),
116
+ )
@@ -0,0 +1,73 @@
1
+ """Word crops stored in the deep-text-recognition-benchmark LMDB layout."""
2
+
3
+ from collections.abc import Callable
4
+ from pathlib import Path
5
+
6
+ import torch
7
+ from torch import Tensor
8
+ from torch.utils.data import Dataset
9
+ from torchvision.io import ImageReadMode, decode_image
10
+
11
+
12
+ class LMDBWords(Dataset[tuple[Tensor, str]]):
13
+ """Cropped word images in the LMDB layout of clovaai's
14
+ deep-text-recognition-benchmark.
15
+
16
+ This is how the standard recognition corpora circulate (MJSynth,
17
+ SynthText, IIIT5K, SVT, ICDAR 2013/2015 crops, CUTE80, MLT word crops):
18
+ ``num-samples`` holds the count and samples ``i = 1..N`` are stored under
19
+ ``image-%09d`` (encoded image bytes) and ``label-%09d`` (UTF-8 text).
20
+
21
+ Requires the optional ``lmdb`` package (``pip install torchocr[lmdb]``).
22
+
23
+ Args:
24
+ root: Directory containing ``data.mdb``.
25
+ label_filter: Optional predicate on the label; only matching samples
26
+ are kept. Evaluated once on all labels at construction (images are
27
+ not decoded), e.g. to drop words outside a model's charset.
28
+ transform: Optional callable applied to the ``uint8`` image.
29
+
30
+ Returns:
31
+ ``(image, text)``: a ``(3, H, W)`` ``uint8`` RGB crop and its label.
32
+ """
33
+
34
+ def __init__(
35
+ self,
36
+ root: str | Path,
37
+ label_filter: Callable[[str], bool] | None = None,
38
+ transform: Callable[[Tensor], Tensor] | None = None,
39
+ ) -> None:
40
+ self.root = Path(root)
41
+ if not (self.root / "data.mdb").is_file():
42
+ raise FileNotFoundError(f"No LMDB database (data.mdb) under {self.root}.")
43
+ self.transform = transform
44
+ self._env = None
45
+ with self._open().begin() as txn:
46
+ count = int(txn.get(b"num-samples"))
47
+ labels = [txn.get(f"label-{i:09d}".encode()).decode("utf-8") for i in range(1, count + 1)]
48
+ keep = [i for i, label in enumerate(labels, start=1) if label_filter is None or label_filter(label)]
49
+ self.indices = keep
50
+ self.labels = [labels[i - 1] for i in keep]
51
+ # LMDB environments must not cross fork(): DataLoader workers reopen lazily.
52
+ self._env.close()
53
+ self._env = None
54
+
55
+ def _open(self):
56
+ try:
57
+ import lmdb
58
+ except ImportError as exc:
59
+ raise ImportError("LMDBWords needs the lmdb package: pip install torchocr[lmdb]") from exc
60
+ if self._env is None:
61
+ self._env = lmdb.open(str(self.root), readonly=True, lock=False, readahead=False, meminit=False)
62
+ return self._env
63
+
64
+ def __len__(self) -> int:
65
+ return len(self.indices)
66
+
67
+ def __getitem__(self, index: int) -> tuple[Tensor, str]:
68
+ with self._open().begin() as txn:
69
+ data = txn.get(f"image-{self.indices[index]:09d}".encode())
70
+ image = decode_image(torch.frombuffer(bytearray(data), dtype=torch.uint8), mode=ImageReadMode.RGB)
71
+ if self.transform is not None:
72
+ image = self.transform(image)
73
+ return image, self.labels[index]
@@ -0,0 +1,118 @@
1
+ """Total-Text: curved scene text with word-level polygons."""
2
+
3
+ import re
4
+ from collections.abc import Callable
5
+ from pathlib import Path
6
+ from typing import Literal
7
+
8
+ import torch
9
+ from torch import Tensor
10
+ from torch.utils.data import Dataset
11
+ from torchvision.io import ImageReadMode, read_image
12
+
13
+ from ..core.structures import TextDetectionTarget
14
+
15
+
16
+ _SPLITS = {"train": "Train", "test": "Test"}
17
+ _IMAGE = re.compile(r"img(\d+)\.(jpe?g|png)$", re.IGNORECASE)
18
+ _COORDS = re.compile(r"([xy]): \[\[([-\d\s]+)\]\]")
19
+ _TEXT = re.compile(r"transcriptions: \[\s*u?(['\"])(.*)\1")
20
+ _DONT_CARE = "#"
21
+
22
+
23
+ class TotalText(Dataset[tuple[Tensor, TextDetectionTarget]]):
24
+ """Total-Text (Ch'ng & Chan, ICDAR 2017): 1255 train / 300 test images of
25
+ horizontal, multi-oriented and *curved* scene text, annotated with
26
+ word-level polygons of 3 to 19 vertices.
27
+
28
+ Expected layout (the released images plus the ``txt_format`` ground truth)::
29
+
30
+ root/
31
+ Images/Train/img11.jpg ... Images/Test/img1.jpg ...
32
+ txt_format/Train/poly_gt_img11.txt txt_format/Test/poly_gt_img1.txt
33
+
34
+ Polygons are padded to the largest vertex count of their image by
35
+ repeating their last vertex, which changes neither area, IoU nor
36
+ rasterization, so they fit one ``(N, P, 2)`` tensor. Words transcribed
37
+ ``#`` (illegible) or with an empty transcription, and polygons with fewer
38
+ than 3 vertices, are marked ``ignore``.
39
+
40
+ Images are read *without* applying EXIF orientation: the annotations
41
+ follow the stored pixels (checked on the six EXIF-rotated images).
42
+
43
+ Args:
44
+ root: Directory holding ``Images/`` and ``txt_format/``.
45
+ split: ``"train"`` or ``"test"``. Default ``"test"``.
46
+ transforms: Optional callable ``(image, target) -> (image, target)``.
47
+
48
+ Returns:
49
+ ``(image, target)``: ``(3, H, W)`` ``uint8`` RGB and a
50
+ :class:`TextDetectionTarget` with ``(N, P, 2)`` polygons.
51
+ """
52
+
53
+ def __init__(
54
+ self,
55
+ root: str | Path,
56
+ split: Literal["train", "test"] = "test",
57
+ transforms: Callable[[Tensor, TextDetectionTarget], tuple[Tensor, TextDetectionTarget]] | None = None,
58
+ ) -> None:
59
+ if split not in _SPLITS:
60
+ raise ValueError(f"split must be one of {sorted(_SPLITS)}; got '{split}'.")
61
+ self.root = Path(root)
62
+ self.split = split
63
+ self.transforms = transforms
64
+ images_dir = self.root / "Images" / _SPLITS[split]
65
+ self.gt_dir = self.root / "txt_format" / _SPLITS[split]
66
+ missing = [str(d.relative_to(self.root)) for d in (images_dir, self.gt_dir) if not d.is_dir()]
67
+ if missing:
68
+ raise FileNotFoundError(
69
+ f"Total-Text '{split}' split not found under {self.root} (missing: {', '.join(missing)}). "
70
+ "Get the images and the txt_format ground truth from "
71
+ "https://github.com/cs-chan/Total-Text-Dataset and arrange them as Images/{Train,Test} "
72
+ "and txt_format/{Train,Test}."
73
+ )
74
+ self.image_paths = sorted(
75
+ (p for p in images_dir.iterdir() if _IMAGE.search(p.name)),
76
+ key=lambda p: int(_IMAGE.search(p.name).group(1)),
77
+ )
78
+
79
+ def __len__(self) -> int:
80
+ return len(self.image_paths)
81
+
82
+ def load_target(self, index: int) -> TextDetectionTarget:
83
+ """The annotations of sample ``index``, without decoding its image."""
84
+ return parse_totaltext_ground_truth(self.gt_dir / f"poly_gt_{self.image_paths[index].stem}.txt")
85
+
86
+ def __getitem__(self, index: int) -> tuple[Tensor, TextDetectionTarget]:
87
+ image = read_image(str(self.image_paths[index]), mode=ImageReadMode.RGB)
88
+ target = self.load_target(index)
89
+ if self.transforms is not None:
90
+ image, target = self.transforms(image, target)
91
+ return image, target
92
+
93
+
94
+ def parse_totaltext_ground_truth(path: Path) -> TextDetectionTarget:
95
+ """Parse a ``poly_gt_*.txt`` file, tolerating the release's malformed lines."""
96
+ # An entry starts with "x:"; a few entries wrap onto the next physical line.
97
+ entries = [e for e in re.split(r"\n(?=x:)", path.read_text(encoding="utf-8")) if e.strip()]
98
+ polygons: list[list[list[float]]] = []
99
+ texts: list[str] = []
100
+ for entry in entries:
101
+ coords = {axis: [float(v) for v in values.split()] for axis, values in _COORDS.findall(entry)}
102
+ xs, ys = coords.get("x", []), coords.get("y", [])
103
+ if not xs or len(xs) != len(ys):
104
+ raise ValueError(f"{path}: malformed Total-Text entry {entry.strip()!r}.")
105
+ match = _TEXT.search(entry)
106
+ texts.append(match.group(2) if match else "")
107
+ polygons.append([[x, y] for x, y in zip(xs, ys)])
108
+
109
+ if not polygons:
110
+ return TextDetectionTarget(torch.zeros(0, 4, 2), [], torch.zeros(0, dtype=torch.bool))
111
+ vertices = max(4, max(len(p) for p in polygons))
112
+ padded = [p + [p[-1]] * (vertices - len(p)) for p in polygons]
113
+ ignore = [t in (_DONT_CARE, "") or len(p) < 3 for t, p in zip(texts, polygons)]
114
+ return TextDetectionTarget(
115
+ polygons=torch.tensor(padded, dtype=torch.float32),
116
+ texts=texts,
117
+ ignore=torch.tensor(ignore, dtype=torch.bool),
118
+ )