scikit-ops 0.1.0.dev2__py3-none-any.whl → 0.1.0.dev3__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: scikit-ops
3
- Version: 0.1.0.dev2
3
+ Version: 0.1.0.dev3
4
4
  Summary: Appose-powered ops, and the machinery for running them.
5
5
  Project-URL: homepage, https://github.com/apposed/scikit-ops
6
6
  Project-URL: documentation, https://github.com/apposed/scikit-ops/blob/main/README.md
@@ -30,7 +30,7 @@ Classifier: Topic :: Utilities
30
30
  Requires-Python: >=3.10
31
31
  Requires-Dist: numpy
32
32
  Requires-Dist: ophelper==0.1.0.dev0
33
- Requires-Dist: oprunner==0.1.0.dev0
33
+ Requires-Dist: oprunner==0.1.0.dev1
34
34
  Requires-Dist: opspec==0.1.0.dev0
35
35
  Description-Content-Type: text/markdown
36
36
 
@@ -15,10 +15,9 @@ skop/ops/deconvolve/_edges.py,sha256=nlavBoTw1J8D_uHIMusWgXxBmkuD_OtQyEc7g0ehEBM
15
15
  skop/ops/deconvolve/_pad.py,sha256=0k3bnKJOLC9ihVXpS_Rhy-ti2CIeBeqZZmt1-0viaVA,3535
16
16
  skop/ops/deconvolve/richardson_lucy.py,sha256=rb_ePL1oLhfstpQqlLsqqw-6K_JC2jMK4JkTZjbSK04,3771
17
17
  skop/ops/deconvolve/richardson_lucy_cupy.py,sha256=jyFJxEEiXSyowAElUHAyMW3LAkz2R4giixFS78a2e34,4842
18
- skop/ops/detect/__init__.py,sha256=mSBR9M8xmfKBjGsN6ZBHqhDZsfkSeC9OJUdKJTq618Y,1145
18
+ skop/ops/detect/__init__.py,sha256=Bcjs9McgJdzHZoGwHXIBndTjR0RedvyEmtBC9_sbxOY,1383
19
19
  skop/ops/detect/_result.py,sha256=hQqN7TgLkK8ZcuydbGogbh1ydMgWqIZNVWLI1br6nq4,1578
20
20
  skop/ops/detect/fastsam.py,sha256=g1L4B29H4JtosA1gfuJzWsFlcTaQjbziI3Vf_W99j_w,3517
21
- skop/ops/detect/jdll_yolo.py,sha256=G55NAmLj2FN_to8Dt6nV5I56JijSv2JcBaoXy50P24A,4172
22
21
  skop/ops/detect/object_aware_yolo.py,sha256=ybY5fjTHR5zLLsBqJ_m1MJP4X7iwFdKlkOxbR2l1y9Q,4226
23
22
  skop/ops/detect/yolo.py,sha256=E43l_-j-WLeax2dTjedKNPBy5y1m1_o3RaKLEW3uTRE,18559
24
23
  skop/ops/kernels/__init__.py,sha256=GCCv7rT8Uu46oSh7emDwn-C1xm54zEYPGulTr1J7HFo,1422
@@ -39,11 +38,12 @@ skop/ops/segment/stardist2d.py,sha256=XSG4kabcfeY5fsQr1e3kYmGbkWOqyoTTyEp98MB679
39
38
  skop/ops/segment/starfun3d.py,sha256=03RB3QL59NkkbgVABXTf9_VKZ-1Li_wUeJFPFjTqeAQ,3417
40
39
  skop/ops/segment/unseg/__init__.py,sha256=nxfXLG3xmnL5zwAlUB7YPdFeLNQk5R6L8JZ8BQ3c1nk,5088
41
40
  skop/ops/segment/unseg/_algorithm.py,sha256=M1l3g8g7hBr3af9aEwLBvnUbo_PvikEoZHRNiED7mfA,68689
42
- skop/ops/train/__init__.py,sha256=dIxjseVRpKvmW9nPvfQCWmZUsBfs4t31CeJagj9Ym0s,3000
43
- skop/ops/train/_util.py,sha256=lZi2PjsJ4SQtir2pu7qAeZkZa53HenTbpl7aA1cijvk,5749
41
+ skop/ops/train/__init__.py,sha256=7t5uGBng74lcxXlF1HUckE7bhGMk1KCbesjOlepnU3g,3047
42
+ skop/ops/train/_util.py,sha256=xgQxx4PDBVODntPmmlNGQ65ICs8yAPKHQHHBHqFkg6I,6114
44
43
  skop/ops/train/cellpose3.py,sha256=uh1SI72eYwnmSQjo0jmKhlkTW3FE5MKTd_H9_6onwac,8482
45
44
  skop/ops/train/cellpose4.py,sha256=akcfij7wsR4kdqlw9AmBBZ5Jh3UCF6dMLSyUnxFhVYA,7212
46
45
  skop/ops/train/stardist2d.py,sha256=dioZYyyw6coHoPLGWIBJxVIYmAHtOp6GjxsDkGDBCSQ,18876
46
+ skop/ops/train/yolo.py,sha256=nof2iyvy79tIpYU15hqN5CRGIEuGmbAApX5Ma6jGMjI,20348
47
47
  skop/ops/workflows/__init__.py,sha256=7GyWvVd9hIuDhup-ElcIeinjoI6xAe_JLwS67UDsIZM,1934
48
48
  skop/ops/workflows/deconvolve/__init__.py,sha256=7f6Sd4cJCfPPfEVwlXo3TIyN00P974zjXA-s3xv5YZ8,189
49
49
  skop/ops/workflows/deconvolve/with_psf.py,sha256=yATu3eqPW37haDJPEFxtI3DEMuWqaMxtrgFK0glZadM,4260
@@ -60,7 +60,7 @@ skop/envs/segment-everything/pixi.toml,sha256=1EmfO-fL9bj6SH-RnxdZpGw75pXmx6-g4E
60
60
  skop/envs/skimage/pixi.toml,sha256=wAfyOSuvsUpmKIj_Hqk3ylxck_uh6wYeMZ2BTjoSBTI,1136
61
61
  skop/envs/stardist-tf/pixi.toml,sha256=oIY1XmErvbApe_pLGyQzzSf1K_RgN2rrgAvyVWYfKag,3487
62
62
  skop/envs/unseg-cv/pixi.toml,sha256=TwcYzpAnfBd5taAB0b-kRXBhbw5aXHoLzoKRaebvyDw,1065
63
- scikit_ops-0.1.0.dev2.dist-info/METADATA,sha256=_slMnyAKToraL0PX1q1pY4muQAqPYKpCHit0mQ6ObZA,1935
64
- scikit_ops-0.1.0.dev2.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
65
- scikit_ops-0.1.0.dev2.dist-info/entry_points.txt,sha256=0gDhmxYQNjvBwJO4L0Q2fB-5fIEBbRVUS5u5heCYulQ,43
66
- scikit_ops-0.1.0.dev2.dist-info/RECORD,,
63
+ scikit_ops-0.1.0.dev3.dist-info/METADATA,sha256=ZbjL7LFHIKnwwg7NmiHNY5Ix4MRL7Oh7B02istNnaoc,1935
64
+ scikit_ops-0.1.0.dev3.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
65
+ scikit_ops-0.1.0.dev3.dist-info/entry_points.txt,sha256=0gDhmxYQNjvBwJO4L0Q2fB-5fIEBbRVUS5u5heCYulQ,43
66
+ scikit_ops-0.1.0.dev3.dist-info/RECORD,,
@@ -13,16 +13,19 @@ One op per environment, since ``@op(env=...)`` is fixed per function:
13
13
  of its own, because segment-everything vendors an ultralytics fork that must
14
14
  not meet the real one.
15
15
 
16
- ``yolo`` runs a user's detection checkpoint on overlapping tiles, returning
17
- boxes, confidences and class IDs. It shares the 'pytorch' environment.
16
+ ``yolo`` is the main one: any trained YOLO checkpoint -- a stock COCO model
17
+ or one from ``skop.ops.train.train_yolo`` -- on the whole image, or on
18
+ overlapping tiles when objects are small, returning boxes, confidences and
19
+ class IDs. It shares the 'pytorch' environment. ``fastsam`` and
20
+ ``object_aware_yolo`` are the special ones, each with its own fixed model.
21
+ (``jdll_yolo``, a port of JDLL's YOLO inference, was retired for it.)
18
22
  """
19
23
 
20
24
  from __future__ import annotations
21
25
 
22
26
  from ._result import Boxes, Detections
23
27
  from .fastsam import fastsam
24
- from .jdll_yolo import jdll_yolo
25
28
  from .object_aware_yolo import object_aware_yolo
26
29
  from .yolo import yolo
27
30
 
28
- __all__ = ["Boxes", "Detections", "fastsam", "jdll_yolo", "object_aware_yolo", "yolo"]
31
+ __all__ = ["Boxes", "Detections", "fastsam", "object_aware_yolo", "yolo"]
@@ -22,11 +22,13 @@ import numpy as np
22
22
  from .cellpose4 import train_cellpose4
23
23
  from .cellpose3 import train_cellpose3
24
24
  from .stardist2d import receptive_field_stardist2d, train_stardist2d
25
+ from .yolo import train_yolo
25
26
 
26
27
  __all__ = [
27
28
  "train_cellpose4",
28
29
  "train_cellpose3",
29
30
  "train_stardist2d",
31
+ "train_yolo",
30
32
  "receptive_field_stardist2d",
31
33
  "extent",
32
34
  "theoretical_receptive_field",
skop/ops/train/_util.py CHANGED
@@ -83,19 +83,29 @@ def continued_from(model_path, initial_model: str) -> bool:
83
83
 
84
84
 
85
85
  def write_history(
86
- model_path, history, name: str, dataset_id: str, initial_model: str = ""
86
+ model_path,
87
+ history,
88
+ name: str,
89
+ dataset_id: str,
90
+ initial_model: str = "",
91
+ extra_columns: list[str] = (),
87
92
  ) -> str:
88
93
  """Write this run's epochs to ``<model file>_history.csv``. Columns match
89
94
  ``train_stardist2d``. Rewritten rather than appended: an older file has a
90
95
  shorter header, and wider rows read back wrong.
91
96
 
97
+ Each history row is ``(epoch, loss, val_loss, *extra)``, the extras
98
+ named by ``extra_columns`` and written after ``val_loss`` -- YOLO's
99
+ mAP, which a loss curve alone does not show.
100
+
92
101
  Kept epochs continue the old ones only when this run continued the old
93
102
  *weights* -- see ``continued_from``. Otherwise the previous history is
94
103
  dropped, because Cellpose has just overwritten the model it described:
95
104
  keeping a curve for weights that no longer exist draws one training run
96
105
  as though it were the tail of another.
97
106
  """
98
- columns = ["epoch", "loss", "val_loss", "run", "model", "dataset"]
107
+ extra_columns = list(extra_columns)
108
+ columns = ["epoch", "loss", "val_loss", *extra_columns, "run", "model", "dataset"]
99
109
  path = f"{model_path}_history.csv"
100
110
 
101
111
  previous = []
@@ -112,12 +122,13 @@ def write_history(
112
122
  writer.writeheader()
113
123
  for row in previous:
114
124
  writer.writerow({k: row.get(k, "") for k in columns})
115
- for epoch, loss, val_loss in history:
125
+ for epoch, loss, val_loss, *extra in history:
116
126
  writer.writerow(
117
127
  {
118
128
  "epoch": done + epoch,
119
129
  "loss": loss,
120
130
  "val_loss": val_loss,
131
+ **dict(zip(extra_columns, extra)),
121
132
  "run": last_run + 1,
122
133
  "model": name,
123
134
  "dataset": dataset_id,
skop/ops/train/yolo.py ADDED
@@ -0,0 +1,504 @@
1
+ """Train a YOLO detector on your own boxes.
2
+
3
+ Runs in the shared 'pytorch' environment, beside ``skop.ops.detect.yolo``,
4
+ which runs what this writes.
5
+
6
+ Shaped like the Cellpose and StarDist trainers (design 0011): paths in, a path
7
+ out, the last ``val_size`` pairs held back, one framework callback relaying
8
+ each epoch to ``progress()``. What it learned from JDLL's YOLO training
9
+ (``docs/spec/jdll-yolo-train.py``) is which arguments the op owns rather than
10
+ the caller, and that ultralytics' console output has to be kept off the
11
+ runner's stdout. Design 0023 has the reasoning.
12
+
13
+ The one thing the other trainers do not have to do: ultralytics reads its
14
+ training set from disk, in its own layout, so the op writes one -- links to
15
+ the images and cleaned copies of the labels -- before it trains.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import os
21
+ import shutil
22
+ from enum import Enum
23
+ from typing import Annotated
24
+
25
+ from opspec.op import op
26
+ from opspec.runtime import cancel_requested, progress
27
+
28
+ from ._util import write_history
29
+
30
+ #: Ultralytics' validation numbers, under the names the history file uses.
31
+ _METRICS = {
32
+ "mAP50": "metrics/mAP50(B)",
33
+ "mAP50_95": "metrics/mAP50-95(B)",
34
+ "precision": "metrics/precision(B)",
35
+ "recall": "metrics/recall(B)",
36
+ }
37
+
38
+
39
+ class Optimizer(Enum):
40
+ """Ultralytics' optimisers. ``auto`` picks one, and a learning rate, from
41
+ the length of the run, and ignores ``learning_rate``."""
42
+
43
+ auto = "auto"
44
+ SGD = "SGD"
45
+ AdamW = "AdamW"
46
+
47
+
48
+ class Cache(Enum):
49
+ """Where ultralytics keeps decoded images between epochs. ``off`` reads
50
+ and decodes every image every epoch; ``ram`` decodes each once and keeps
51
+ it (falling back to ``off`` if it will not fit); ``disk`` saves decoded
52
+ copies as ``.npy`` beside the dataset."""
53
+
54
+ off = "off"
55
+ ram = "ram"
56
+ disk = "disk"
57
+
58
+
59
+ #: Every inline augmentation ultralytics applies to detection, at the value
60
+ #: that turns it off.
61
+ _NO_AUGMENT = {
62
+ "hsv_h": 0.0,
63
+ "hsv_s": 0.0,
64
+ "hsv_v": 0.0,
65
+ "degrees": 0.0,
66
+ "translate": 0.0,
67
+ "scale": 0.0,
68
+ "shear": 0.0,
69
+ "perspective": 0.0,
70
+ "flipud": 0.0,
71
+ "fliplr": 0.0,
72
+ "bgr": 0.0,
73
+ "mosaic": 0.0,
74
+ "mixup": 0.0,
75
+ "cutmix": 0.0,
76
+ "close_mosaic": 0,
77
+ }
78
+
79
+
80
+ @op(env="pytorch")
81
+ def train_yolo(
82
+ images: list[str],
83
+ labels: list[str],
84
+ model_dir: str,
85
+ name: str = "yolo_model",
86
+ class_names: list[str] | None = None,
87
+ initial_model: str = "yolo11n.pt",
88
+ epochs: Annotated[int, {"widget_type": "SpinBox", "min": 1, "max": 5000}] = 100,
89
+ imgsz: Annotated[
90
+ int, {"widget_type": "SpinBox", "min": 32, "max": 4096, "step": 32}
91
+ ] = 640,
92
+ batch_size: Annotated[int, {"widget_type": "SpinBox", "min": -1, "max": 256}] = 16,
93
+ optimizer: Optimizer = Optimizer.auto,
94
+ learning_rate: float = 0.01,
95
+ patience: Annotated[int, {"widget_type": "SpinBox", "min": 0, "max": 5000}] = 100,
96
+ fliplr: float = 0.5,
97
+ flipud: float = 0.0,
98
+ degrees: float = 0.0,
99
+ scale: float = 0.5,
100
+ shear: float = 0.0,
101
+ perspective: float = 0.0,
102
+ mosaic: float = 1.0,
103
+ augment: bool = True,
104
+ cache: Cache = Cache.off,
105
+ val_size: Annotated[int, {"widget_type": "SpinBox", "min": 0, "max": 100000}] = 2,
106
+ seed: int = 0,
107
+ dataset_id: str = "",
108
+ ) -> str:
109
+ """Train, or finetune, a YOLO detector and write it to disk.
110
+
111
+ Args:
112
+ images: Paths to the training images, in order. Any format
113
+ ultralytics reads (jpg, png, tif, ...); not HEIC.
114
+ labels: Paths to YOLO ``.txt`` box files. ``labels[k]`` is the truth
115
+ for ``images[k]`` -- the pairing is positional, and the caller
116
+ owns it. One line per box, ``class x_center y_center width
117
+ height``, normalised to the image. A sixth column, a prediction's
118
+ confidence, is dropped, so predicted boxes can be trained on
119
+ directly. An empty file is an image with nothing in it, which
120
+ teaches as much as one with boxes.
121
+ model_dir: Directory the model is written to, as ``<name>.pt``.
122
+ Training's working files go in ``<name>_training/`` beside it.
123
+ name: Filename for the trained model, without ``.pt``.
124
+ class_names: Name of each class id, in order. Empty takes the
125
+ classes from the labels and calls them ``class0``, ``class1``...,
126
+ or ``object`` when there is only class 0.
127
+ initial_model: What to start from. A stock ``.pt`` (``yolo11n.pt``,
128
+ ``yolo11m.pt``, ``yolo26n.pt``, ... -- ultralytics downloads it)
129
+ finetunes, which is the usual thing and needs far fewer boxes. A
130
+ ``.yaml`` (``yolo11n.yaml``) starts from nothing. The path this op
131
+ returned carries on from that model, and its history continues.
132
+ epochs: Passes over the training set.
133
+ imgsz: Size training resizes each image to. Objects should end up the
134
+ size they will be when the model is run, so train at the
135
+ ``imgsz`` you will detect at.
136
+ batch_size: Images per batch. -1 lets ultralytics choose from the
137
+ GPU's memory. If the first epoch runs out of memory, ultralytics
138
+ halves it and starts the epoch again, by itself. Ultralytics
139
+ steps the optimiser every 64 images whatever the batch, so a
140
+ training set of a handful of images learns very slowly: give it
141
+ more images (copies, or augmented crops), not more epochs.
142
+ optimizer: ``auto`` lets ultralytics choose, and is what to leave it
143
+ at unless you are matching another run.
144
+ learning_rate: Initial learning rate (ultralytics' ``lr0``). Ignored
145
+ when ``optimizer`` is ``auto``.
146
+ patience: Stop when validation has not improved for this many epochs.
147
+ 0 never stops early.
148
+ fliplr: Chance of a left-right flip. Ultralytics' default; set it to
149
+ 0 for anything with a handedness -- text, numbers, bibs.
150
+ flipud: Chance of an upside-down flip. 0 for photos; microscopy has no
151
+ up and wants 0.5.
152
+ degrees: Random rotation range, +/- degrees.
153
+ scale: Random zoom range, +/- this fraction. Ultralytics' default of
154
+ 0.5 is half to one and a half times.
155
+ shear: Random shear range, +/- degrees.
156
+ perspective: Random perspective warp, 0 to 0.001.
157
+ mosaic: Chance of a four-image mosaic. Ultralytics turns it off for
158
+ the last 10 epochs.
159
+ augment: False turns off all of ultralytics' inline augmentation --
160
+ the six above, and the colour jitter and shifts that are not
161
+ parameters here -- so each image is only resized to ``imgsz``.
162
+ For a training set augmented beforehand, as napari-ai-lab and
163
+ photo-enhance's ``bib-patches`` make one: what is left per batch
164
+ is reading the image, and with ``cache`` nothing at all, so the
165
+ GPU, not one CPU thread, sets the pace. The cost is that every
166
+ epoch sees the same images; make more of them, or make a fresh
167
+ set now and then and continue from the last model.
168
+ cache: Keep decoded images between epochs. ``ram`` is the fast one,
169
+ and needs about ``imgsz * imgsz * 3`` bytes an image (1024 px:
170
+ 3 MB, so 3000 crops is 9 GB). Worth it with or without
171
+ ``augment``; it saves the reading, not the augmenting.
172
+ val_size: How many pairs, taken from the end, to hold out for
173
+ validation. Put whole photos there, not crops of photos that are
174
+ also in training, or the validation numbers flatter the model.
175
+ 0 validates on the training set -- for checking the wiring on one
176
+ image, where a near-perfect score is the right answer.
177
+ seed: Seed for ultralytics' shuffling and augmentation.
178
+ dataset_id: Opaque label for the training data, recorded in the
179
+ history file so a plot can mark where it changed.
180
+
181
+ Returns:
182
+ The path of the model file, ``<model_dir>/<name>.pt``. A
183
+ ``<model file>_history.csv`` is written beside it -- epoch, loss,
184
+ val_loss, mAP50, mAP50_95, precision, recall, run, model, dataset --
185
+ continued when ``initial_model`` is this same file, as the Cellpose
186
+ trainers do.
187
+ """
188
+ import contextlib
189
+ import logging
190
+ import sys
191
+
192
+ import torch
193
+ from ultralytics import YOLO
194
+ from ultralytics.utils import LOGGER
195
+
196
+ # Absolute, because training runs in the workspace (below).
197
+ model_dir = os.path.abspath(model_dir)
198
+ if os.path.exists(initial_model):
199
+ initial_model = os.path.abspath(initial_model)
200
+ os.makedirs(model_dir, exist_ok=True)
201
+ model_path = os.path.join(model_dir, f"{name}.pt")
202
+ workspace = os.path.join(model_dir, f"{name}_training")
203
+ os.makedirs(workspace, exist_ok=True)
204
+
205
+ data_yaml, n_train, n_val = write_dataset(
206
+ images, labels, os.path.join(workspace, "dataset"), val_size, class_names
207
+ )
208
+
209
+ if torch.cuda.is_available():
210
+ device = 0
211
+ elif torch.backends.mps.is_available():
212
+ device = "mps"
213
+ else:
214
+ device = "cpu"
215
+
216
+ # Ultralytics writes to stdout -- its logger, and its progress bars --
217
+ # which is the Appose protocol's channel. Both go to a log file while it
218
+ # trains, and progress() is given the real stdout back each time it
219
+ # reports.
220
+ real_stdout = sys.stdout
221
+
222
+ def report(*args, **kwargs):
223
+ current, sys.stdout = sys.stdout, real_stdout
224
+ try:
225
+ progress(*args, **kwargs)
226
+ finally:
227
+ sys.stdout = current
228
+
229
+ history = []
230
+ trained = [] # epochs that trained, as on_train_epoch_end saw them
231
+
232
+ def on_train_epoch_end(trainer):
233
+ trained.append(int(trainer.epoch) + 1)
234
+
235
+ def on_train_batch_end(trainer):
236
+ # Ultralytics checks trainer.stop after every batch; it validates and
237
+ # saves what it has, then stops.
238
+ if cancel_requested():
239
+ trainer.stop = True
240
+
241
+ def on_fit_epoch_end(trainer):
242
+ epoch = int(trainer.epoch) + 1
243
+ # Called once more after training, to score best.pt -- and after an
244
+ # early stop the epoch counter has moved on by then. Only an epoch
245
+ # that trained, once.
246
+ if not trained or epoch != trained[-1] or (history and history[-1][0] == epoch):
247
+ return
248
+ losses = trainer.label_loss_items(trainer.tloss, prefix="train")
249
+ loss = _total(losses)
250
+ metrics = dict(trainer.metrics or {})
251
+ val_loss = _total({k: v for k, v in metrics.items() if k.startswith("val/")})
252
+ scores = {k: _number(metrics.get(v)) for k, v in _METRICS.items()}
253
+ history.append((epoch, loss, val_loss, *scores.values()))
254
+ report(
255
+ f"Epoch {epoch}/{epochs} — loss {loss:.4f}, "
256
+ f"mAP50 {scores['mAP50']:.3f}, mAP50-95 {scores['mAP50_95']:.3f}",
257
+ epoch,
258
+ epochs,
259
+ )
260
+
261
+ log_path = os.path.join(workspace, "training.log")
262
+ handler = logging.FileHandler(log_path, mode="a", encoding="utf-8")
263
+ saved = LOGGER.handlers[:], LOGGER.propagate
264
+ LOGGER.handlers, LOGGER.propagate = [handler], False
265
+ model = None
266
+ cwd = os.getcwd()
267
+ try:
268
+ # Ultralytics drops downloads in the current directory -- its AMP
269
+ # check fetches yolo26n.pt -- so let that be the workspace.
270
+ os.chdir(workspace)
271
+ with (
272
+ open(log_path, "a", encoding="utf-8") as log,
273
+ contextlib.redirect_stdout(log),
274
+ ):
275
+ # Inside the redirect: loading a stock model downloads it, with
276
+ # a progress bar on stdout.
277
+ report(f"Loading YOLO model {initial_model}")
278
+ model = YOLO(_stock_weights(initial_model))
279
+ model.add_callback("on_train_epoch_end", on_train_epoch_end)
280
+ model.add_callback("on_train_batch_end", on_train_batch_end)
281
+ model.add_callback("on_fit_epoch_end", on_fit_epoch_end)
282
+ report(
283
+ f"Training {name}: {n_train} train, {n_val or n_train} val"
284
+ f"{'' if n_val else ' (the training set)'}, {epochs} epochs",
285
+ 0,
286
+ epochs,
287
+ )
288
+ augmentation = {
289
+ "fliplr": fliplr,
290
+ "flipud": flipud,
291
+ "degrees": degrees,
292
+ "scale": scale,
293
+ "shear": shear,
294
+ "perspective": perspective,
295
+ "mosaic": mosaic,
296
+ }
297
+ if not augment:
298
+ augmentation = _NO_AUGMENT
299
+ model.train(
300
+ data=data_yaml,
301
+ epochs=epochs,
302
+ imgsz=imgsz,
303
+ batch=batch_size,
304
+ optimizer=optimizer.value,
305
+ lr0=learning_rate,
306
+ patience=patience,
307
+ **augmentation,
308
+ cache=False if cache is Cache.off else cache.value,
309
+ seed=seed,
310
+ # The op's, not the caller's: where things go, and how.
311
+ project=workspace,
312
+ name="run",
313
+ exist_ok=True,
314
+ device=device,
315
+ # Worker processes re-import the op's host; JDLL uses 0 too.
316
+ workers=0,
317
+ plots=False,
318
+ verbose=False,
319
+ deterministic=True,
320
+ )
321
+ trainer = model.trainer
322
+ best, last = str(trainer.best), str(trainer.last)
323
+ source = best if os.path.isfile(best) else last
324
+ if not os.path.isfile(source):
325
+ raise RuntimeError(f"Training wrote no checkpoint in {workspace}")
326
+ shutil.copy2(source, model_path)
327
+ # The copy is the model. Left in place, the run's best.pt and last.pt
328
+ # are two more models for anyone listing the folder to choose from.
329
+ shutil.rmtree(os.path.dirname(source), ignore_errors=True)
330
+ # So is the yolo26n.pt the AMP check downloaded into the workspace.
331
+ for stray in os.listdir(workspace):
332
+ if stray.endswith(".pt"):
333
+ os.remove(os.path.join(workspace, stray))
334
+ finally:
335
+ os.chdir(cwd)
336
+ LOGGER.handlers, LOGGER.propagate = saved
337
+ handler.close()
338
+ del model
339
+ if torch.cuda.is_available():
340
+ torch.cuda.empty_cache()
341
+
342
+ write_history(
343
+ model_path,
344
+ history,
345
+ name,
346
+ dataset_id,
347
+ initial_model,
348
+ extra_columns=list(_METRICS),
349
+ )
350
+ report(f"Saved {model_path}")
351
+ return model_path
352
+
353
+
354
+ def write_dataset(
355
+ images: list[str],
356
+ labels: list[str],
357
+ root: str,
358
+ val_size: int,
359
+ class_names: list[str] | None = None,
360
+ ) -> tuple[str, int, int]:
361
+ """Lay the pairs out the way ultralytics reads them, under ``root``.
362
+
363
+ ``images/{train,val}`` and ``labels/{train,val}``, with each pair's
364
+ files sharing a stem -- ultralytics finds a label by swapping ``images``
365
+ for ``labels`` in the image's path -- and a ``data.yaml``. The stems are
366
+ numbered, so two images called ``0001.png`` in different folders stay
367
+ apart. Images are hard links where the disk allows, copies where not.
368
+ Labels are rewritten: five columns, checked.
369
+
370
+ Pure python, so it runs and is tested wherever skop is. Returns the
371
+ yaml's path and the train and val counts.
372
+ """
373
+ if len(images) != len(labels):
374
+ raise ValueError(
375
+ f"{len(images)} images and {len(labels)} labels: a training set "
376
+ f"is pairs, so the two lists must be the same length."
377
+ )
378
+ if val_size < 0 or len(images) <= val_size:
379
+ raise ValueError(
380
+ f"{len(images)} pairs is not enough to hold {val_size} back for "
381
+ f"validation and still train on the rest."
382
+ )
383
+
384
+ # Last time's files would be trained on too.
385
+ shutil.rmtree(root, ignore_errors=True)
386
+ split = len(images) - val_size
387
+ top_class = -1
388
+ for k, (image, label) in enumerate(zip(images, labels)):
389
+ part = "train" if k < split else "val"
390
+ stem = f"{k:05d}_{os.path.splitext(os.path.basename(image))[0]}"
391
+ ext = os.path.splitext(image)[1].lower()
392
+ image_dir = os.path.join(root, "images", part)
393
+ label_dir = os.path.join(root, "labels", part)
394
+ os.makedirs(image_dir, exist_ok=True)
395
+ os.makedirs(label_dir, exist_ok=True)
396
+ _link_or_copy(image, os.path.join(image_dir, stem + ext))
397
+ rows = read_yolo_label(label)
398
+ if rows:
399
+ top_class = max(top_class, max(r[0] for r in rows))
400
+ with open(os.path.join(label_dir, stem + ".txt"), "w") as f:
401
+ f.writelines(
402
+ f"{c} {xc:.6f} {yc:.6f} {w:.6f} {h:.6f}\n" for c, xc, yc, w, h in rows
403
+ )
404
+
405
+ if class_names:
406
+ if top_class >= len(class_names):
407
+ raise ValueError(
408
+ f"The labels use class {top_class}, but only "
409
+ f"{len(class_names)} class names were given."
410
+ )
411
+ names = list(class_names)
412
+ elif top_class <= 0:
413
+ names = ["object"]
414
+ else:
415
+ names = [f"class{i}" for i in range(top_class + 1)]
416
+
417
+ data_yaml = os.path.join(root, "data.yaml")
418
+ with open(data_yaml, "w", encoding="utf-8") as f:
419
+ f.write(f"path: {_yaml_str(os.path.abspath(root))}\n")
420
+ f.write("train: images/train\n")
421
+ # No val pairs: validate on the training set.
422
+ f.write(f"val: images/{'val' if val_size else 'train'}\n")
423
+ f.write("names:\n")
424
+ f.writelines(f" {i}: {_yaml_str(n)}\n" for i, n in enumerate(names))
425
+ return data_yaml, split, val_size
426
+
427
+
428
+ def read_yolo_label(path: str) -> list[tuple[int, float, float, float, float]]:
429
+ """A YOLO box file's rows, as ``(class, xc, yc, w, h)``.
430
+
431
+ Five columns or six -- the sixth, a prediction's confidence, is dropped.
432
+ Anything else, or coordinates outside 0..1, is an error naming the line:
433
+ ultralytics would skip the whole image, quietly.
434
+ """
435
+ rows = []
436
+ with open(path) as f:
437
+ for n, line in enumerate(f, 1):
438
+ parts = line.split()
439
+ if not parts:
440
+ continue
441
+ if len(parts) not in (5, 6):
442
+ raise ValueError(
443
+ f"{path}, line {n}: {len(parts)} columns; a YOLO box is "
444
+ f"'class x_center y_center width height [confidence]'"
445
+ )
446
+ c = int(float(parts[0]))
447
+ xc, yc, w, h = (float(p) for p in parts[1:5])
448
+ if c < 0 or not all(0.0 <= v <= 1.0 for v in (xc, yc, w, h)):
449
+ raise ValueError(
450
+ f"{path}, line {n}: a class below 0, or a coordinate "
451
+ f"outside 0..1: {line.strip()!r}"
452
+ )
453
+ rows.append((c, xc, yc, w, h))
454
+ return rows
455
+
456
+
457
+ def _stock_weights(initial_model: str) -> str:
458
+ """A bare stock name, ``yolo11n.pt``, as a file in ophelper's cache.
459
+
460
+ Ultralytics downloads a stock model into the current directory, which in
461
+ a worker is wherever the worker happened to start. Given a path in the
462
+ cache instead, it downloads there, once. Paths, and ``.yaml``
463
+ architectures, are left alone.
464
+ """
465
+ if (
466
+ not initial_model.endswith(".pt")
467
+ or os.path.dirname(initial_model)
468
+ or os.path.exists(initial_model)
469
+ ):
470
+ return initial_model
471
+ from ultralytics.utils.downloads import attempt_download_asset
472
+
473
+ from ophelper.assets import cache_dir
474
+
475
+ target = cache_dir() / "yolo" / initial_model
476
+ target.parent.mkdir(parents=True, exist_ok=True)
477
+ return attempt_download_asset(str(target))
478
+
479
+
480
+ def _link_or_copy(source: str, target: str) -> None:
481
+ try:
482
+ os.link(source, target)
483
+ except OSError: # another drive, or a filesystem without hard links
484
+ shutil.copy2(source, target)
485
+
486
+
487
+ def _yaml_str(value: str) -> str:
488
+ """Quoted for YAML: a Windows path or a class name can hold ':' or '#'."""
489
+ return "'" + str(value).replace("'", "''") + "'"
490
+
491
+
492
+ def _number(value) -> float:
493
+ try:
494
+ return float(value)
495
+ except (TypeError, ValueError):
496
+ return float("nan")
497
+
498
+
499
+ def _total(values) -> float:
500
+ # label_loss_items returns the bare key list when there is no loss yet.
501
+ if not isinstance(values, dict):
502
+ return float("nan")
503
+ numbers = [_number(v) for v in values.values()]
504
+ return float(sum(numbers)) if numbers else float("nan")
@@ -1,115 +0,0 @@
1
- """YOLO detection with any ultralytics weights, ported from JDLL.
2
-
3
- JDLL (https://github.com/bioimage-io/JDLL) runs YOLO from Java by building
4
- Python as strings in ``model/special/yolo/Yolo.java`` and sending it to an
5
- Appose worker. This is that Python, as an op. The readable copy it came from
6
- is docs/spec/jdll-yolo-infer.py.
7
-
8
- Kept from JDLL: the device choice, the hand-written letterbox, and handing
9
- ultralytics a tensor, which skips its own preprocessing. Dropped: the shared
10
- memory, the axis-letter reordering, and the UUID-suffixed names, all of which
11
- the runner already does or makes unnecessary.
12
-
13
- Unlike ``fastsam`` and ``object_aware_yolo`` this is not class-agnostic: it
14
- runs whatever model it is given, trained for whatever classes. The classes
15
- are dropped for now, as everywhere in this package -- see _result.py.
16
- """
17
-
18
- from __future__ import annotations
19
-
20
- from pathlib import Path
21
- from typing import Annotated
22
-
23
- import numpy as np
24
-
25
- import ophelper.boxes
26
- from opspec.op import Axes, op
27
- from opspec.runtime import progress
28
- from opspec.types import ImageOf
29
-
30
- from .._util import to_rgb
31
- from ._result import Boxes
32
-
33
-
34
- @op(env="pytorch")
35
- def jdll_yolo(
36
- image: Annotated[ImageOf[np.ndarray], Axes("y", "x", "c?")],
37
- weights: Path,
38
- conf: Annotated[
39
- float,
40
- {"widget_type": "FloatSlider", "min": 0.0, "max": 1.0, "step": 0.05},
41
- ] = 0.25,
42
- iou: Annotated[
43
- float,
44
- {"widget_type": "FloatSlider", "min": 0.0, "max": 1.0, "step": 0.05},
45
- ] = 0.7,
46
- imgsz: int = 640,
47
- ) -> Boxes:
48
- """Find objects with a trained YOLO model.
49
-
50
- Args:
51
- image: Image to detect in. 2-D or RGB; anything else is stretched to
52
- 8-bit RGB first.
53
- weights: A YOLO ``.pt`` file, such as the ``best.pt`` training writes.
54
- conf: Confidence threshold. Lower finds more, and more spuriously.
55
- iou: NMS threshold. Two detections overlapping by more than this are
56
- treated as one object.
57
- imgsz: Size the longest side is resized to. JDLL fixes this at 640.
58
-
59
- Returns:
60
- boxes: (N, 4) as [min_y, min_x, max_y, max_x], in image coordinates.
61
- """
62
- import numpy as np
63
- import torch
64
- import torch.nn.functional as F
65
- from ultralytics import YOLO
66
-
67
- if torch.cuda.is_available():
68
- device = "cuda"
69
- elif torch.backends.mps.is_available():
70
- device = "mps"
71
- else:
72
- device = "cpu"
73
-
74
- # An empty file picker sends Path('.'), which YOLO accepts and only
75
- # rejects deep inside predict.
76
- if not Path(weights).is_file():
77
- raise FileNotFoundError(
78
- f"weights must be a YOLO .pt file, got {str(weights)!r}"
79
- )
80
-
81
- progress(f"Loading {Path(weights).name}")
82
- model = YOLO(str(weights))
83
-
84
- # (Y, X, 3) uint8 -> (1, 3, Y, X) float, still 0-255. Ultralytics sees
85
- # values above 1 and divides by 255 itself, with a warning.
86
- rgb = to_rgb(image)
87
- x = torch.as_tensor(
88
- np.ascontiguousarray(rgb.transpose(2, 0, 1)[None]), dtype=torch.float32
89
- )
90
- x = x.to(device)
91
-
92
- # JDLL's letterbox: longest side to imgsz, then pad each side to a
93
- # multiple of 32, centred, with ultralytics' grey.
94
- _, _, height, width = x.shape
95
- scale = imgsz / max(height, width)
96
- new_h, new_w = round(height * scale), round(width * scale)
97
- x = F.interpolate(x, size=(new_h, new_w), mode="bilinear", align_corners=False)
98
- pad_h, pad_w = (-new_h) % 32, (-new_w) % 32
99
- top, left = pad_h // 2, pad_w // 2
100
- x = F.pad(x, (left, pad_w - left, top, pad_h - top), value=114.0)
101
-
102
- progress("Detecting objects")
103
- results = model(x.contiguous(), conf=conf, iou=iou, device=device, verbose=False)
104
-
105
- if not results or results[0].boxes is None or len(results[0].boxes) == 0:
106
- return Boxes(ophelper.boxes.EMPTY.copy())
107
-
108
- found = results[0].boxes
109
- progress(f"Found {len(found)} objects")
110
-
111
- # Undo the letterbox: shift off the padding, scale back, clip to the image.
112
- xyxy = found.xyxy.cpu().numpy()
113
- xyxy[:, [0, 2]] = np.clip((xyxy[:, [0, 2]] - left) / scale, 0, width)
114
- xyxy[:, [1, 3]] = np.clip((xyxy[:, [1, 3]] - top) / scale, 0, height)
115
- return Boxes(ophelper.boxes.from_xyxy(xyxy))