Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 18 additions & 1 deletion doctr/datasets/orientation.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,4 +37,21 @@
)

# initialize dataset with 0 degree rotation targets
self.data: list[tuple[str, np.ndarray]] = [(img_name, np.array([0])) for img_name in os.listdir(self.root)]
# a list-like sequence (only `len` and indexing are used by the base class), not a list: cf. _ZeroTargetSamples
self.data = _ZeroTargetSamples(os.listdir(self.root)) # type: ignore[assignment]


class _ZeroTargetSamples:
"""The (image name, 0 degree target) samples, with all the names in a single numpy array:

Check notice on line 45 in doctr/datasets/orientation.py

View check run for this annotation

Codacy Production / Codacy Static Code Analysis

doctr/datasets/orientation.py#L45

1 blank line required between summary line and description (found 0) (D205)

Check notice on line 45 in doctr/datasets/orientation.py

View check run for this annotation

Codacy Production / Codacy Static Code Analysis

doctr/datasets/orientation.py#L45

First line should end with a period, question mark, or exclamation point (not ':') (D415)

Check notice on line 45 in doctr/datasets/orientation.py

View check run for this annotation

Codacy Production / Codacy Static Code Analysis

doctr/datasets/orientation.py#L45

Multi-line docstring summary should start at the second line (D213)
a list of Python objects per image would be copied by every DataLoader worker (refcount updates trigger
copy-on-write), which takes tens of GB with millions of images.
"""

def __init__(self, img_names: list[str]) -> None:
self.img_names = np.array(img_names)

def __len__(self) -> int:
return len(self.img_names)

def __getitem__(self, index: int) -> tuple[str, np.ndarray]:
return str(self.img_names[index]), np.array([0])
4 changes: 2 additions & 2 deletions doctr/models/classification/mobilenet/pytorch.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,14 +61,14 @@
"std": (0.299, 0.296, 0.301),
"input_shape": (3, 256, 256),
"classes": [0, -90, 180, 90],
"url": "https://doctr-static.mindee.com/models?id=v0.8.1/mobilenet_v3_small_crop_orientation-f0847a18.pt&src=0",
"url": "https://github.com/mindee/doctr/releases/download/v1.2.0/crop_orientation_mnv3s-3753d2cd.pt",
},
"mobilenet_v3_small_page_orientation": {
"mean": (0.694, 0.695, 0.693),
"std": (0.299, 0.296, 0.301),
"input_shape": (3, 512, 512),
"classes": [0, -90, 180, 90],
"url": "https://doctr-static.mindee.com/models?id=v0.8.1/mobilenet_v3_small_page_orientation-8e60325c.pt&src=0",
"url": "https://github.com/mindee/doctr/releases/download/v1.2.0/page_orientation_mnv3s-58e44dbb.pt",
},
"mobilenet_v3_small_font_style": {
"mean": (0.694, 0.695, 0.693),
Expand Down
2 changes: 1 addition & 1 deletion doctr/transforms/modules/pytorch.py
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ def forward(
else:
offset = (0, 0)

if isinstance(target, str) or (isinstance(target, np.ndarray) and target.ndim < 2):
if isinstance(target, (str, int, np.integer)) or (isinstance(target, np.ndarray) and target.ndim < 2):
# Special case for class targets (e.g. orientation, font style), which are not boxes to resize
pass
elif isinstance(target, dict):
Expand Down
2 changes: 2 additions & 0 deletions references/classification/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ python references/classification/train_orientation.py resnet18 --type page --tra

The type can be either `page` for document images or `crop` for word crops.

The training images are expected upright: each sample is rotated by one of the 4 orientations before being resized and padded, like the inputs at inference. `--class-prior` draws the orientations with the given probabilities (order `0 -90 180 90`, uniform by default): most pages and crops are upright in practice, and a prior such as `--class-prior 0.4 0.2 0.2 0.2` keeps ambiguous inputs (digits, short tokens, single characters) upright instead of rotating them at random. The validation set always uses uniform orientations.

## Usage font style classification

The font style classifier predicts, for each word crop, its emphasis (bold, italic, underline, strikethrough), its text and highlight colors, whether it is handwritten, its font category and its closest font family (cf. `doctr.datasets.FONT_STYLE_ATTRIBUTES`). The model outputs the logits of all these attributes concatenated, and is trained with the sum of their cross entropies.
Expand Down
66 changes: 43 additions & 23 deletions references/classification/train_orientation.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
# See LICENSE or go to <https://opensource.org/licenses/Apache-2.0> for full license details.

import datetime
import functools
import logging
import multiprocessing as mp
import os
Expand Down Expand Up @@ -60,14 +61,24 @@
return torch.amp.GradScaler("cuda", enabled=AMP_DTYPE == torch.float16)


def rnd_rotate(sample: Sample) -> Sample:
angle = int(np.random.choice(CLASSES))
idx = CLASSES.index(angle)
def rnd_rotate(sample: Sample, class_prior: list[float] | None = None) -> Sample:
"""Rotate the image before it is resized and padded, like the crops / pages at inference.

Check notice on line 65 in references/classification/train_orientation.py

View check run for this annotation

Codacy Production / Codacy Static Code Analysis

references/classification/train_orientation.py#L65

Multi-line docstring summary should start at the second line (D213)

The orientation is drawn with the probabilities `class_prior` (uniform by default): a prior favoring the upright
class teaches the model the real-world distribution, so that ambiguous inputs (digits, short tokens, single
CJK characters...) are not rotated at random.

Rotating an already padded image leaks the label: the odd remainder of the symmetric padding always goes to the
top / left (cf. `Resize`), so a rotation moves it to the bottom / right and the model learns that cue instead of
the text orientation (unseen at inference, where the input is padded after being rotated).
"""
idx = int(np.random.choice(len(CLASSES), p=class_prior))
# class index k <=> rotated counter-clockwise by k * 90 degrees (cf. `rectify_crops`): exact, no interpolation
rotated_img = torch.rot90(sample.image, idx, dims=(-2, -1))
# augment the angle randomly with a probability of 0.5
if np.random.rand() < 0.5:
angle += float(np.random.choice(np.arange(-25, 25, 5)))
rotated_img = F.rotate(sample.image, angle=-angle, fill=0, expand=angle not in CLASSES)[:3]
return Sample(image=rotated_img, target=idx)
rotated_img = F.rotate(rotated_img, angle=float(np.random.choice(np.arange(-25, 30, 5))), fill=0, expand=True)
return Sample(image=rotated_img[:3], target=idx)


def record_lr(
Expand Down Expand Up @@ -249,12 +260,10 @@
st = time.time()
val_set = OrientationDataset(
img_folder=os.path.join(args.val_path, "images"),
img_transforms=Compose([
T.Resize(input_size, preserve_aspect_ratio=True, symmetric_pad=True),
]),
# rotate first, then resize & pad: same order as at inference (cf. `rnd_rotate`)
sample_transforms=T.SampleCompose([
rnd_rotate,
T.Resize(input_size),
T.Resize(input_size, preserve_aspect_ratio=True, symmetric_pad=True),
]),
)
val_loader = DataLoader(
Expand Down Expand Up @@ -294,20 +303,20 @@
st = time.time()
train_set = OrientationDataset(
img_folder=os.path.join(args.train_path, "images"),
img_transforms=Compose([
T.Resize(input_size, preserve_aspect_ratio=True, symmetric_pad=True),
# Augmentations
T.RandomApply(T.ColorInversion(), 0.1),
T.RandomApply(T.GaussianNoise(mean=0.1, std=0.1), 0.1),
T.RandomApply(T.RandomShadow(), 0.2),
T.RandomApply(T.GaussianBlur(sigma=(0.5, 1.5)), 0.3),
T.ImageTorchvisionTransform(RandomPhotometricDistort(p=0.1)),
T.ImageTorchvisionTransform(RandomGrayscale(p=0.1)),
T.ImageTorchvisionTransform(RandomPerspective(distortion_scale=0.1, p=0.3)),
]),
# rotate first, then resize & pad: same order as at inference (cf. `rnd_rotate`)
sample_transforms=T.SampleCompose([
rnd_rotate,
T.Resize(input_size),
functools.partial(rnd_rotate, class_prior=args.class_prior),
Compose([
T.Resize(input_size, preserve_aspect_ratio=True, symmetric_pad=True),
# Augmentations (independent of the orientation)
T.RandomApply(T.ColorInversion(), 0.1),
T.RandomApply(T.GaussianNoise(mean=0.1, std=0.1), 0.1),
T.RandomApply(T.RandomShadow(), 0.2),
T.RandomApply(T.GaussianBlur(sigma=(0.5, 1.5)), 0.3),
T.ImageTorchvisionTransform(RandomPhotometricDistort(p=0.1)),
T.ImageTorchvisionTransform(RandomGrayscale(p=0.1)),
T.ImageTorchvisionTransform(RandomPerspective(distortion_scale=0.1, p=0.3)),
]),
]),
)

Expand Down Expand Up @@ -373,6 +382,7 @@
"optimizer": args.optim,
"framework": "pytorch",
"classes": CLASSES,
"class_prior": args.class_prior,
"scheduler": args.sched,
"pretrained": args.pretrained,
}
Expand Down Expand Up @@ -548,10 +558,20 @@
help="autocast dtype for --amp; bfloat16 (Ampere+ GPUs) avoids float16 overflows, no loss scaling",
)
parser.add_argument("--find-lr", action="store_true", help="Gridsearch the optimal LR")
parser.add_argument(
"--class-prior",
type=float,
nargs=4,
default=None,
help="probabilities of the training orientations [0, -90, 180, 90] (default: uniform), e.g. 0.4 0.2 0.2 0.2",
)
parser.add_argument("--early-stop", action="store_true", help="Enable early stopping")
parser.add_argument("--early-stop-epochs", type=int, default=5, help="Patience for early stopping")
parser.add_argument("--early-stop-delta", type=float, default=0.01, help="Minimum Delta for early stopping")
args = parser.parse_args()
if args.class_prior is not None:
if any(p < 0 for p in args.class_prior) or abs(sum(args.class_prior) - 1) > 1e-6:
parser.error("--class-prior must be 4 non-negative probabilities summing to 1")

return args

Expand Down
8 changes: 8 additions & 0 deletions tests/pytorch/test_transforms_pt.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,14 @@ def test_resize_preserve_aspect_ratio(symmetric_pad, content_rows):
assert torch.equal(mask, expected_mask)


@pytest.mark.parametrize("target", [2, np.int64(2), "label", np.array([2])])
def test_resize_class_target(target):
# Class targets (e.g. an orientation index) are not boxes: kept as is when the aspect ratio is preserved
data = Resize((32, 32), preserve_aspect_ratio=True, symmetric_pad=True)(Sample(image=_ones(16, 64), target=target))
assert data.image.shape[-2:] == (32, 32)
assert np.array_equal(data.target, target) if isinstance(target, np.ndarray) else data.target == target


def test_resize_repr_and_shapes():
transfo = Resize(32, preserve_aspect_ratio=True, symmetric_pad=True)
expected = "Resize(output_size=(32, 32), interpolation='bilinear', preserve_aspect_ratio=True, symmetric_pad=True)"
Expand Down
Loading