Coverage for collectra/tasks/machine_learning/training.py: 84.51%

142 statements  

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

1"""Opt-in utilities for training task implementations.""" 

2 

3from __future__ import annotations 

4 

5import shutil 

6from datetime import datetime 

7from pathlib import Path 

8from typing import Callable 

9 

10import yaml 

11from rich.console import Console 

12from rich.table import Table 

13 

14from collectra.types.base import ArtefactNode 

15from collectra.types.images import Image, ImageCrop 

16from collectra.commons.results import peek_header 

17from collectra.utils import change_dir 

18 

19from ...logger import get_logger 

20from .class_names import read_class_names, write_class_names 

21 

22logger = get_logger(__name__) 

23 

24 

25def print_distribution_table( 

26 title: str, 

27 classes: list[str], 

28 train_counts: dict[str, int], 

29 validation_counts: dict[str, int], 

30 train_images: tuple[int, int] | None = None, 

31 validation_images: tuple[int, int] | None = None, 

32) -> None: 

33 """Print class counts and each class's held-out validation percentage. 

34 

35 ``train_images`` and ``validation_images`` are optional 

36 ``(with objects, background)`` image counts. Background images have no 

37 objects but are still used as negative training examples. 

38 """ 

39 table = Table(title=title, show_lines=True) 

40 table.add_column( 

41 "Class Name", justify="left", style="green", header_style="bold green" 

42 ) 

43 table.add_column( 

44 "Train Count", justify="right", style="red", header_style="bold red" 

45 ) 

46 table.add_column( 

47 "Validation Count", justify="right", style="blue", header_style="bold blue" 

48 ) 

49 table.add_column("Validation %", justify="right", header_style="bold") 

50 

51 total_train = 0 

52 total_validation = 0 

53 for class_name in classes: 

54 train_count = train_counts[class_name] 

55 validation_count = validation_counts[class_name] 

56 total = train_count + validation_count 

57 percentage = 100 * validation_count / total if total else 0.0 

58 table.add_row( 

59 class_name, 

60 str(train_count), 

61 str(validation_count), 

62 f"{percentage:.1f}%", 

63 ) 

64 total_train += train_count 

65 total_validation += validation_count 

66 

67 grand_total = total_train + total_validation 

68 total_percentage = 100 * total_validation / grand_total if grand_total else 0.0 

69 table.add_row( 

70 "Total", 

71 str(total_train), 

72 str(total_validation), 

73 f"{total_percentage:.1f}%", 

74 style="bold", 

75 ) 

76 if train_images is not None and validation_images is not None: 

77 rows = [ 

78 ("Images with objects", train_images[0], validation_images[0]), 

79 ("Background images (no objects)", train_images[1], validation_images[1]), 

80 ("Total images", sum(train_images), sum(validation_images)), 

81 ] 

82 for label, train_count, validation_count in rows: 

83 total = train_count + validation_count 

84 percentage = 100 * validation_count / total if total else 0.0 

85 table.add_row( 

86 label, 

87 str(train_count), 

88 str(validation_count), 

89 f"{percentage:.1f}%", 

90 style="bold" if label == "Total images" else None, 

91 ) 

92 Console().print(table) 

93 

94 

95def prepare_object_detection_inputs( 

96 processed_inputs: list, 

97 processed_parents: list, 

98 input_maps: dict[str, list], 

99 parent_input_maps: dict[str, list], 

100) -> list: 

101 """Attach source images to detection crops and return the task inputs.""" 

102 for item in processed_inputs: 

103 if type(item) is Image: 

104 continue 

105 if type(item) is not ImageCrop: 

106 raise TypeError(f"Input {item.id} is not an ImageCrop") 

107 if isinstance(item.parents, str): 

108 parent_id = item.parents 

109 elif isinstance(item.parents, list) and len(item.parents) == 1: 

110 parent_id = item.parents[0] 

111 else: 

112 continue 

113 parent = next( 

114 ( 

115 candidate 

116 for candidate in processed_parents 

117 if candidate.id == parent_id and item.data == candidate.data 

118 ), 

119 None, 

120 ) 

121 if not isinstance(parent, Image): 

122 raise ValueError( 

123 f"Image parent {parent_id!r} for input {item.id!r} was not found" 

124 ) 

125 item.add_source_parent(parent) 

126 return processed_inputs 

127 

128 

129def _training_files(task, inputs: list[str]) -> list[Path]: 

130 pipeline = _pipeline_for(task) 

131 files = [] 

132 for value in inputs: 

133 path = Path(value) 

134 if path.is_dir(): 

135 files.extend(path.glob(f"*.{pipeline.ext}")) 

136 elif path.suffix == f".{pipeline.ext}": 

137 files.append(path) 

138 return files 

139 

140 

141def _file_partition(item_file: Path) -> str: 

142 result_file = item_file / "results.yaml" 

143 if not result_file.exists(): 

144 return "" 

145 with open(result_file, "r") as f: 

146 file_data = yaml.safe_load(f) or {} 

147 return peek_header(file_data, source=result_file).partition or "" 

148 

149 

150def _limit_training_files( 

151 files: list[Path], max_items: int, validation: str = "", exclude: str = "" 

152) -> list[Path]: 

153 """Keep the first ``max_items`` training and ``max_items`` validation files. 

154 

155 Only the partition metadata is read, and reading stops once both 

156 quotas are filled, so large datasets are not loaded for quick tests. 

157 """ 

158 selected = [] 

159 counts = {"train": 0, "validation": 0} 

160 for item_file in sorted(files): 

161 partition = _file_partition(item_file) 

162 if exclude and partition == exclude: 

163 continue 

164 split = "validation" if validation and partition == validation else "train" 

165 if counts[split] < max_items: 

166 selected.append(item_file) 

167 counts[split] += 1 

168 if counts["train"] >= max_items and ( 

169 not validation or counts["validation"] >= max_items 

170 ): 

171 break 

172 logger.info( 

173 "max_items=%d: using %d training and %d validation files", 

174 max_items, 

175 counts["train"], 

176 counts["validation"], 

177 ) 

178 return selected 

179 

180 

181def _prepare_data( 

182 task, 

183 files: list[Path], 

184 nodes: list[ArtefactNode], 

185 *, 

186 include_unlabelled: bool = False, 

187): 

188 processed = [] 

189 input_maps = {} 

190 for item_file in files: 

191 input_maps[item_file.name] = ArtefactNode.batch_process( 

192 item_file, 

193 nodes, 

194 include_unlabelled=include_unlabelled, 

195 ) 

196 processed.extend(input_maps[item_file.name]) 

197 return processed, input_maps 

198 

199 

200def _pipeline_for(task): 

201 if task.pipeline is None: 

202 raise RuntimeError(f"Task {task.name!r} is not attached to a pipeline") 

203 return task.pipeline 

204 

205 

206def save_training_result(task, results, *, log: str, **kwargs) -> None: 

207 """Copy the best model and optional class metadata into the pipeline.""" 

208 pipeline = _pipeline_for(task) 

209 best_model_path = results.save_dir / "weights" / "best.pt" 

210 if not best_model_path.exists(): 

211 raise FileNotFoundError(f"Best model file not found at {best_model_path}") 

212 logger.info("Training metrics: %s", results.results_dict) 

213 current_model = pipeline.data.get(task.name, {}).get("model", "") 

214 if best_model_path.name == current_model: 

215 return 

216 new_model_path = f"{task.name}-{Path(log).name}.pt" 

217 shutil.copy(best_model_path, new_model_path) 

218 pipeline.data[task.name]["model"] = new_model_path 

219 classes = read_class_names(best_model_path) 

220 if classes is not None: 

221 write_class_names(Path(f"{Path(new_model_path).stem}.classes.yaml"), classes) 

222 

223 

224def train_from_files( 

225 task, 

226 inputs: list[str], 

227 trainer: Callable, 

228 *, 

229 prepare_inputs: Callable | None = None, 

230 include_unlabelled: bool = False, 

231 **kwargs, 

232): 

233 """Resolve pipeline artefacts and invoke a concrete backend trainer.""" 

234 pipeline = _pipeline_for(task) 

235 task_node = pipeline.node_manager.resolve_node(task.name) 

236 children = pipeline.node_manager.get_children_artefact(task_node) 

237 parents = pipeline.node_manager.get_ancestor_artefacts(task_node) 

238 kwargs["classes"] = kwargs.get("classes", [child.name for child in children]) 

239 kwargs = pipeline._merge_task_params(task.name, kwargs) 

240 files = _training_files(task, inputs) 

241 max_items = int(kwargs.get("max_items", 0) or 0) 

242 if max_items > 0: 

243 files = _limit_training_files( 

244 files, 

245 max_items, 

246 validation=kwargs.get("validation", ""), 

247 exclude=kwargs.get("exclude", ""), 

248 ) 

249 processed_inputs, input_maps = _prepare_data( 

250 task, 

251 files, 

252 children, 

253 include_unlabelled=include_unlabelled, 

254 ) 

255 processed_parents, parent_input_maps = _prepare_data(task, files, parents) 

256 if prepare_inputs is not None: 

257 processed_inputs = prepare_inputs( 

258 processed_inputs, 

259 processed_parents, 

260 input_maps, 

261 parent_input_maps, 

262 ) 

263 with change_dir(pipeline.path): 

264 results = trainer(*processed_inputs, **kwargs) 

265 save_training_result(task, results, **kwargs) 

266 return results 

267 

268 

269def run_training_command( 

270 task, 

271 inputs: list[str], 

272 trainer: Callable, 

273 *, 

274 keep_log: bool, 

275 output: Path | None, 

276 validation: str, 

277 exclude: str, 

278 prepare_inputs: Callable | None = None, 

279 include_unlabelled: bool = False, 

280 **kwargs, 

281): 

282 """Run the common filesystem lifecycle requested by a concrete command.""" 

283 pipeline = _pipeline_for(task) 

284 log = ( 

285 Path(output).expanduser().resolve() 

286 if output is not None 

287 else Path.cwd() / datetime.now().strftime("%Y%m%d_%H%M%S") 

288 ) 

289 results = train_from_files( 

290 task, 

291 inputs, 

292 trainer, 

293 prepare_inputs=prepare_inputs, 

294 include_unlabelled=include_unlabelled, 

295 project=f"{pipeline.name}-{task.name}", 

296 log=log, 

297 base_folder=Path.cwd(), 

298 validation=validation, 

299 exclude=exclude, 

300 **kwargs, 

301 ) 

302 pipeline.save(task.name) 

303 if not keep_log: 

304 shutil.rmtree(log, ignore_errors=True) 

305 return results