Coverage for collectra/tasks/machine_learning/orienters.py: 100.00%

83 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-11-13 04:26 +0000

1from __future__ import annotations 

2 

3from pathlib import Path 

4from typing import TYPE_CHECKING, Any 

5 

6from pydantic import PrivateAttr 

7 

8from collectra.types.images import Image, ImageCrop, Orientation 

9 

10from ..base import Task 

11from ..object_detection.batching import image_cache_key 

12 

13if TYPE_CHECKING: 

14 from torchvision.models import EfficientNet 

15 

16__all__ = ["ImageOrienter", "default_orienter_checkpoint"] 

17 

18# The published model of https://github.com/duartebarbosadev/deep-image-orientation-detection 

19# (MIT licensed), used when no orientation model is given. 

20DEFAULT_ORIENTER_REPO = "DuarteBarbosa/deep-image-orientation-detection" 

21DEFAULT_ORIENTER_FILE = "orientation_model_v2_0.9882.pth" 

22 

23 

24def default_orienter_checkpoint() -> Path: 

25 """The default orientation checkpoint, downloaded once into the Hugging Face cache.""" 

26 from huggingface_hub import hf_hub_download 

27 

28 return Path( 

29 hf_hub_download(repo_id=DEFAULT_ORIENTER_REPO, filename=DEFAULT_ORIENTER_FILE) 

30 ) 

31 

32 

33class ImageOrienter(Task): 

34 

35 # A checkpoint path, a loaded torchvision EfficientNet, or None for the default. 

36 model: Any = None 

37 _prefetched: dict = PrivateAttr(default_factory=dict) 

38 

39 def __init__(self, name, model: str | Path | EfficientNet | None = None, **kwargs): 

40 super().__init__(name, model=model, **kwargs) 

41 self.transforms = None 

42 

43 def _init_model(self): 

44 """Initialisation code here is emulated from https://github.com/duartebarbosadev/deep-image-orientation-detection""" 

45 import torch 

46 import torchvision.transforms as transforms 

47 from torchvision.models import EfficientNet 

48 

49 image_size = 384 

50 self.transforms = transforms.Compose( 

51 [ 

52 transforms.Resize((image_size + 32, image_size + 32)), 

53 transforms.CenterCrop(image_size), 

54 transforms.ToTensor(), 

55 transforms.Normalize( 

56 mean=[0.485, 0.456, 0.406], 

57 std=[0.229, 0.224, 0.225], 

58 ), 

59 ] 

60 ) 

61 

62 device = torch.device( 

63 "mps" 

64 if torch.backends.mps.is_available() 

65 else "cuda" if torch.cuda.is_available() else "cpu" 

66 ) 

67 

68 if isinstance(self.model, EfficientNet): 

69 self.model.to(device) 

70 self.device = device 

71 return 

72 

73 import torchvision.models as models 

74 

75 model = models.efficientnet_v2_s(weights=None) 

76 

77 num_ftrs = model.classifier[1].in_features 

78 

79 model.classifier = torch.nn.Sequential( 

80 torch.nn.Dropout(p=0.2, inplace=True), 

81 torch.nn.Linear(num_ftrs, 4), 

82 ) 

83 

84 checkpoint = default_orienter_checkpoint() if self.model is None else self.model 

85 state_dict = torch.load(checkpoint, map_location=device) 

86 model.load_state_dict(state_dict) 

87 model.to(device) 

88 model.eval() 

89 

90 self.model = model 

91 self.device = device 

92 

93 def _processed_image(self, img: Image): 

94 from PIL import Image as PILImage 

95 

96 image = img.pil() 

97 

98 if image.mode in ("RGB", "L"): 

99 return image.convert("RGB") 

100 

101 converted_image = image.convert("RGBA") 

102 background = PILImage.new("RGBA", converted_image.size, (255, 255, 255)) 

103 background.paste(converted_image, mask=converted_image) 

104 return background.convert("RGB") 

105 

106 def _predict_batch(self, images: list[Image]) -> list[Orientation]: 

107 """The orientation of each image, from one pass of the model over all of them.""" 

108 import torch 

109 

110 batch = torch.stack( 

111 [self.transforms(self._processed_image(image)) for image in images] 

112 ).to(self.device) 

113 with torch.no_grad(): 

114 predicted = torch.max(self.model(batch), 1)[1] 

115 return [Orientation(int(index)) for index in predicted] 

116 

117 @staticmethod 

118 def _prefetch_key(image: Image) -> tuple: 

119 return image_cache_key(image) 

120 

121 def prefetch(self, entries: list[list]) -> None: 

122 """Orient many images in batches of ``batch_size``, caching the results for ``run``.""" 

123 self._init_model() 

124 images = [ 

125 entry[0] 

126 for entry in entries 

127 if len(entry) == 1 and isinstance(entry[0], Image) 

128 ] 

129 self._prefetched = {} 

130 for start in range(0, len(images), self.batch_size): 

131 batch = images[start : start + self.batch_size] 

132 for image, orientation in zip(batch, self._predict_batch(batch)): 

133 self._prefetched[self._prefetch_key(image)] = orientation 

134 

135 def clear_prefetch(self) -> None: 

136 self._prefetched = {} 

137 

138 def run(self, *args: Image) -> Image: 

139 if len(args) != 1: 

140 raise ValueError("This task only supports a single Image input.") 

141 self._init_model() 

142 img = args[0] 

143 orientation = self._prefetched.pop(self._prefetch_key(img), None) 

144 if orientation is None: 

145 orientation = self._predict_batch([img])[0] 

146 

147 name = self.get_output_name() 

148 

149 if isinstance(img, ImageCrop): 

150 new_image = ImageCrop( 

151 name=name, 

152 data=img.data, 

153 x_center=float(img.x_center), 

154 y_center=float(img.y_center), 

155 width_relative=float(img.width_relative), 

156 height_relative=float(img.height_relative), 

157 orientation=orientation, 

158 ) 

159 return new_image 

160 

161 new_image = Image( 

162 name=name, 

163 data=img.data, 

164 orientation=orientation, 

165 ) 

166 

167 return new_image