easyannotate 0.4.0__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.
Files changed (109) hide show
  1. data_factory/__init__.py +82 -0
  2. data_factory/__main__.py +6 -0
  3. data_factory/annotate/__init__.py +15 -0
  4. data_factory/annotate/attach.py +398 -0
  5. data_factory/annotate/demo.py +161 -0
  6. data_factory/annotate/images.py +443 -0
  7. data_factory/annotate/labels.py +399 -0
  8. data_factory/annotate/loop.py +359 -0
  9. data_factory/annotate/projects.py +207 -0
  10. data_factory/annotate/review.py +471 -0
  11. data_factory/annotate/schema.sql +171 -0
  12. data_factory/annotate/shapes.py +488 -0
  13. data_factory/annotate/store.py +292 -0
  14. data_factory/annotate/tools/__init__.py +39 -0
  15. data_factory/annotate/tools/fake.py +170 -0
  16. data_factory/annotate/tools/install.py +254 -0
  17. data_factory/annotate/tools/local.py +389 -0
  18. data_factory/annotate/tools/postprocess.py +175 -0
  19. data_factory/annotate/tools/protocol.py +238 -0
  20. data_factory/annotate/tools/registry.py +196 -0
  21. data_factory/annotate/tools/results.py +83 -0
  22. data_factory/annotate/tools/serve.py +106 -0
  23. data_factory/cli/__init__.py +21 -0
  24. data_factory/cli/main.py +837 -0
  25. data_factory/cli/menu.py +173 -0
  26. data_factory/cli/render.py +158 -0
  27. data_factory/core/__init__.py +11 -0
  28. data_factory/core/annotations/__init__.py +5 -0
  29. data_factory/core/annotations/coco.py +394 -0
  30. data_factory/core/annotations/csvfmt.py +174 -0
  31. data_factory/core/annotations/dota.py +98 -0
  32. data_factory/core/annotations/formats.py +626 -0
  33. data_factory/core/annotations/labelme.py +153 -0
  34. data_factory/core/annotations/model.py +334 -0
  35. data_factory/core/annotations/voc.py +231 -0
  36. data_factory/core/annotations/yolo.py +283 -0
  37. data_factory/core/bktree.py +89 -0
  38. data_factory/core/fs.py +245 -0
  39. data_factory/core/imaging.py +626 -0
  40. data_factory/core/ops/__init__.py +44 -0
  41. data_factory/core/ops/analyze.py +383 -0
  42. data_factory/core/ops/annotate_export.py +326 -0
  43. data_factory/core/ops/audit.py +274 -0
  44. data_factory/core/ops/augment.py +454 -0
  45. data_factory/core/ops/collect.py +241 -0
  46. data_factory/core/ops/combine.py +582 -0
  47. data_factory/core/ops/convert.py +212 -0
  48. data_factory/core/ops/dataset.py +246 -0
  49. data_factory/core/ops/dedup.py +235 -0
  50. data_factory/core/ops/export.py +168 -0
  51. data_factory/core/ops/image.py +407 -0
  52. data_factory/core/ops/labels.py +215 -0
  53. data_factory/core/ops/pairing.py +133 -0
  54. data_factory/core/ops/rename.py +154 -0
  55. data_factory/core/ops/report.py +323 -0
  56. data_factory/core/ops/visualize.py +164 -0
  57. data_factory/core/pairs.py +144 -0
  58. data_factory/core/parallel.py +191 -0
  59. data_factory/core/provenance.py +136 -0
  60. data_factory/core/registry.py +339 -0
  61. data_factory/core/stats.py +403 -0
  62. data_factory/core/types.py +148 -0
  63. data_factory/core/writer.py +194 -0
  64. data_factory/desktop.py +207 -0
  65. data_factory/hardware.py +243 -0
  66. data_factory/pipeline.py +192 -0
  67. data_factory/py.typed +0 -0
  68. data_factory/service/__init__.py +26 -0
  69. data_factory/service/app.py +483 -0
  70. data_factory/service/binding.py +174 -0
  71. data_factory/service/deps.py +133 -0
  72. data_factory/service/jobs.py +177 -0
  73. data_factory/service/limits.py +71 -0
  74. data_factory/service/routers/__init__.py +11 -0
  75. data_factory/service/routers/annotate.py +582 -0
  76. data_factory/service/routers/local.py +464 -0
  77. data_factory/service/routers/media.py +154 -0
  78. data_factory/service/routers/predictions.py +116 -0
  79. data_factory/service/routers/promote.py +182 -0
  80. data_factory/service/routers/tools.py +308 -0
  81. data_factory/service/static/annotate/api.js +246 -0
  82. data_factory/service/static/annotate/app.js +1696 -0
  83. data_factory/service/static/annotate/assist.js +106 -0
  84. data_factory/service/static/annotate/filmstrip.js +286 -0
  85. data_factory/service/static/annotate/hit.js +146 -0
  86. data_factory/service/static/annotate/labels.js +197 -0
  87. data_factory/service/static/annotate/render.js +286 -0
  88. data_factory/service/static/annotate/scene.js +277 -0
  89. data_factory/service/static/annotate/shapelist.js +72 -0
  90. data_factory/service/static/annotate/tools/box.js +96 -0
  91. data_factory/service/static/annotate/tools/line.js +96 -0
  92. data_factory/service/static/annotate/tools/obb.js +88 -0
  93. data_factory/service/static/annotate/tools/point.js +49 -0
  94. data_factory/service/static/annotate/tools/polygon.js +110 -0
  95. data_factory/service/static/annotate/tools/select.js +227 -0
  96. data_factory/service/static/annotate/undo.js +176 -0
  97. data_factory/service/static/annotate/viewport.js +156 -0
  98. data_factory/service/static/annotate.html +390 -0
  99. data_factory/service/static/index.html +632 -0
  100. data_factory/service/workspace.py +244 -0
  101. easyannotate/__init__.py +64 -0
  102. easyannotate/__main__.py +5 -0
  103. easyannotate/project.py +181 -0
  104. easyannotate/py.typed +0 -0
  105. easyannotate-0.4.0.dist-info/METADATA +767 -0
  106. easyannotate-0.4.0.dist-info/RECORD +109 -0
  107. easyannotate-0.4.0.dist-info/WHEEL +4 -0
  108. easyannotate-0.4.0.dist-info/entry_points.txt +4 -0
  109. easyannotate-0.4.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,582 @@
1
+ """Annotation routes: projects, labels, images and shapes.
2
+
3
+ Thin on purpose. Every rule that matters -- ownership, label index allocation,
4
+ coordinate clamping, save conflicts -- lives in ``data_factory/annotate/`` and
5
+ is tested without an HTTP client. What is left here is translation: domain
6
+ exceptions to status codes, and JSON to domain objects.
7
+
8
+ The one rule this layer owns is the same one the batch API owns: **a client
9
+ never names a path.** It names a project id and an image id; every path is
10
+ derived server-side.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from pathlib import Path
16
+ from typing import Any
17
+
18
+ from fastapi import APIRouter, Depends, HTTPException
19
+ from pydantic import BaseModel, Field
20
+
21
+ from ...annotate import images as images_mod
22
+ from ...annotate import labels as labels_mod
23
+ from ...annotate import projects as projects_mod
24
+ from ...annotate import shapes as shapes_mod
25
+ from ...annotate.store import Conflict, NotFound, Store, StoreError, valid_id
26
+ from ...core.annotations.model import AnnotationError, Shape
27
+ from ..deps import get_store, media_root, principal, require_key
28
+
29
+ router = APIRouter(prefix="/api", tags=["annotate"], dependencies=[Depends(require_key)])
30
+
31
+ #: One save carries one image's shapes. A cap turns "a client sent us 40
32
+ #: million boxes" from an out-of-memory event into a 400.
33
+ MAX_SHAPES_PER_SAVE = 5000
34
+
35
+ #: Images registered in a single scan request.
36
+ MAX_IMAGES_PER_CALL = 50_000
37
+
38
+
39
+ # ------------------------------------------------------------------ wire
40
+
41
+ class ProjectIn(BaseModel):
42
+ name: str = Field(default="Untitled project", max_length=200)
43
+
44
+
45
+ class LabelIn(BaseModel):
46
+ name: str = Field(max_length=labels_mod.MAX_NAME)
47
+
48
+
49
+ class LabelPatch(BaseModel):
50
+ name: str | None = Field(default=None, max_length=labels_mod.MAX_NAME)
51
+ colour: str | None = Field(default=None, max_length=7)
52
+
53
+
54
+ class StatePatch(BaseModel):
55
+ state: str
56
+
57
+
58
+ #: Shape fields the editor may not send, and which a save must therefore keep.
59
+ KEPT_ATTRIBUTES = ("pose", "truncated", "difficult", "occluded")
60
+
61
+
62
+ class ShapesIn(BaseModel):
63
+ version: int | None = Field(
64
+ default=None,
65
+ description="The image version this edit was based on. Omit to force.",
66
+ )
67
+ shapes: list[dict[str, Any]] = Field(default_factory=list)
68
+ advance_state: bool = True
69
+
70
+
71
+ # -------------------------------------------------------------- plumbing
72
+
73
+ def _fail(exc: Exception) -> HTTPException:
74
+ """Map a domain exception onto a status code.
75
+
76
+ ``NotFound`` covers both "no such project" and "not yours" deliberately --
77
+ telling them apart would tell a stranger which ids are real.
78
+ """
79
+ if isinstance(exc, NotFound):
80
+ return HTTPException(404, str(exc))
81
+ if isinstance(exc, Conflict):
82
+ return HTTPException(409, str(exc))
83
+ if isinstance(exc, (StoreError, AnnotationError)):
84
+ return HTTPException(400, str(exc))
85
+ return HTTPException(400, "that request could not be completed")
86
+
87
+
88
+ def _project(store: Store, project_id: str, owner: str):
89
+ try:
90
+ return projects_mod.get(store, project_id, owner)
91
+ except StoreError as exc:
92
+ raise _fail(exc) from None
93
+
94
+
95
+ def _image(store: Store, project, image_id: str):
96
+ try:
97
+ return images_mod.get(store, project, image_id)
98
+ except StoreError as exc:
99
+ raise _fail(exc) from None
100
+
101
+
102
+ def _sync_disk(store: Store, project, image_ids) -> list[str]:
103
+ """Write changed images back to an attached folder's own label files."""
104
+ if not project.is_attached:
105
+ return []
106
+ from ...annotate import attach
107
+
108
+ return attach.sync(store, project, image_ids)
109
+
110
+
111
+ def attach_images_using(store: Store, project, idx: int) -> list[str]:
112
+ if not project.is_attached:
113
+ return []
114
+ from ...annotate import attach
115
+
116
+ return attach.images_using(store, project, idx)
117
+
118
+
119
+ def _with_disk(payload: dict[str, Any], problems: list[str]) -> dict[str, Any]:
120
+ if problems:
121
+ payload["sidecar_errors"] = problems
122
+ return payload
123
+
124
+
125
+ def _image_payload(store: Store, project, image) -> dict[str, Any]:
126
+ stored = shapes_mod.listing(store, project, image)
127
+ return {
128
+ **image.as_dict(),
129
+ "shapes": [s.as_dict() for s in stored],
130
+ }
131
+
132
+
133
+ # -------------------------------------------------------------- projects
134
+
135
+ @router.post("/projects", status_code=201)
136
+ def create_project(
137
+ body: ProjectIn,
138
+ store: Store = Depends(get_store),
139
+ owner: str = Depends(principal),
140
+ ) -> dict[str, Any]:
141
+ """Start a project. No labels, no task, no organisation -- just a name."""
142
+ try:
143
+ project = projects_mod.create(store, body.name, owner_id=owner)
144
+ except StoreError as exc:
145
+ raise _fail(exc) from None
146
+ media_root(project.id).mkdir(parents=True, exist_ok=True)
147
+ return project.as_dict()
148
+
149
+
150
+ @router.get("/projects")
151
+ def list_projects(
152
+ store: Store = Depends(get_store),
153
+ owner: str = Depends(principal),
154
+ ) -> dict[str, Any]:
155
+ return {"projects": [p.as_dict() for p in projects_mod.listing(store, owner)]}
156
+
157
+
158
+ @router.get("/projects/{project_id}")
159
+ def project_detail(
160
+ project_id: str,
161
+ store: Store = Depends(get_store),
162
+ owner: str = Depends(principal),
163
+ ) -> dict[str, Any]:
164
+ """Everything the editor needs to open a project in one round trip."""
165
+ project = _project(store, project_id, owner)
166
+ resume = images_mod.resume_point(store, project)
167
+ return {
168
+ **project.as_dict(),
169
+ "labels": [label.as_dict() for label in labels_mod.listing(store, project)],
170
+ "counts": images_mod.counts(store, project),
171
+ "resume": resume.as_dict() if resume else None,
172
+ "agreement": shapes_mod.agreement(store, project),
173
+ }
174
+
175
+
176
+ @router.patch("/projects/{project_id}")
177
+ def rename_project(
178
+ project_id: str,
179
+ body: ProjectIn,
180
+ store: Store = Depends(get_store),
181
+ owner: str = Depends(principal),
182
+ ) -> dict[str, Any]:
183
+ project = _project(store, project_id, owner)
184
+ try:
185
+ return projects_mod.rename(store, project, body.name).as_dict()
186
+ except StoreError as exc:
187
+ raise _fail(exc) from None
188
+
189
+
190
+ @router.delete("/projects/{project_id}", status_code=204)
191
+ def delete_project(
192
+ project_id: str,
193
+ store: Store = Depends(get_store),
194
+ owner: str = Depends(principal),
195
+ ) -> None:
196
+ project = _project(store, project_id, owner)
197
+ projects_mod.delete(store, project)
198
+ # Media is removed after the rows, so a crash between the two leaves
199
+ # orphaned files rather than rows pointing at nothing.
200
+ import shutil
201
+
202
+ shutil.rmtree(media_root(project.id), ignore_errors=True)
203
+
204
+
205
+ # ---------------------------------------------------------------- labels
206
+
207
+ @router.get("/projects/{project_id}/labels")
208
+ def list_labels(
209
+ project_id: str,
210
+ include_retired: bool = False,
211
+ store: Store = Depends(get_store),
212
+ owner: str = Depends(principal),
213
+ ) -> dict[str, Any]:
214
+ project = _project(store, project_id, owner)
215
+ return {
216
+ "labels": [
217
+ label.as_dict()
218
+ for label in labels_mod.listing(store, project, include_retired=include_retired)
219
+ ],
220
+ # The export order, including retired slots. Shown so nobody has to
221
+ # guess why index 3 is missing from the palette.
222
+ "class_list": labels_mod.class_list(store, project),
223
+ # Classes differing only by case or spacing. Surfaced rather than
224
+ # merged: folding them silently would change somebody's data.
225
+ "variants": {
226
+ key: [label.idx for label in found]
227
+ for key, found in labels_mod.variants(store, project).items()
228
+ },
229
+ }
230
+
231
+
232
+ @router.post("/projects/{project_id}/labels", status_code=201)
233
+ def create_label(
234
+ project_id: str,
235
+ body: LabelIn,
236
+ store: Store = Depends(get_store),
237
+ owner: str = Depends(principal),
238
+ ) -> dict[str, Any]:
239
+ """Create a label by naming it. Idempotent, so the editor can just call it."""
240
+ project = _project(store, project_id, owner)
241
+ try:
242
+ return labels_mod.ensure(store, project, body.name).as_dict()
243
+ except StoreError as exc:
244
+ raise _fail(exc) from None
245
+
246
+
247
+ @router.patch("/projects/{project_id}/labels/{idx}")
248
+ def patch_label(
249
+ project_id: str,
250
+ idx: int,
251
+ body: LabelPatch,
252
+ store: Store = Depends(get_store),
253
+ owner: str = Depends(principal),
254
+ ) -> dict[str, Any]:
255
+ """Rename or recolour. Neither moves the index."""
256
+ project = _project(store, project_id, owner)
257
+ try:
258
+ label = labels_mod.get(store, project, idx)
259
+ problems: list[str] = []
260
+ if body.name is not None:
261
+ label = labels_mod.rename(store, project, idx, body.name)
262
+ problems = _sync_disk(store, project, attach_images_using(store, project, idx))
263
+ if body.colour is not None:
264
+ label = labels_mod.recolour(store, project, idx, body.colour)
265
+ return _with_disk(label.as_dict(), problems)
266
+ except StoreError as exc:
267
+ raise _fail(exc) from None
268
+
269
+
270
+ @router.delete("/projects/{project_id}/labels/{idx}")
271
+ def retire_label(
272
+ project_id: str,
273
+ idx: int,
274
+ store: Store = Depends(get_store),
275
+ owner: str = Depends(principal),
276
+ ) -> dict[str, Any]:
277
+ """Retire a label. Never a DELETE: shapes still reference it, and its
278
+ index must stay occupied so later classes do not shift."""
279
+ project = _project(store, project_id, owner)
280
+ try:
281
+ retired = labels_mod.retire(store, project, idx)
282
+ except StoreError as exc:
283
+ raise _fail(exc) from None
284
+ problems = _sync_disk(store, project, attach_images_using(store, project, idx))
285
+ return _with_disk(retired.as_dict(), problems)
286
+
287
+
288
+ class MergeIn(BaseModel):
289
+ into: int
290
+
291
+
292
+ @router.post("/projects/{project_id}/labels/{idx}/merge")
293
+ def merge_label(
294
+ project_id: str,
295
+ idx: int,
296
+ body: MergeIn,
297
+ store: Store = Depends(get_store),
298
+ owner: str = Depends(principal),
299
+ ) -> dict[str, Any]:
300
+ """Fold one class into another -- the fix for case-variant duplicates.
301
+
302
+ The source index is retired, not deleted, so it keeps its slot and no
303
+ later class shifts.
304
+ """
305
+ project = _project(store, project_id, owner)
306
+ affected = attach_images_using(store, project, idx)
307
+ try:
308
+ moved = labels_mod.merge(store, project, idx, body.into)
309
+ except StoreError as exc:
310
+ raise _fail(exc) from None
311
+ problems = _sync_disk(store, project, affected)
312
+ return _with_disk({
313
+ "moved": moved,
314
+ "labels": [label.as_dict() for label in labels_mod.listing(store, project)],
315
+ "class_list": labels_mod.class_list(store, project),
316
+ }, problems)
317
+
318
+
319
+ @router.post("/projects/{project_id}/labels/{idx}/restore")
320
+ def restore_label(
321
+ project_id: str,
322
+ idx: int,
323
+ store: Store = Depends(get_store),
324
+ owner: str = Depends(principal),
325
+ ) -> dict[str, Any]:
326
+ project = _project(store, project_id, owner)
327
+ try:
328
+ restored = labels_mod.restore(store, project, idx)
329
+ except StoreError as exc:
330
+ raise _fail(exc) from None
331
+ problems = _sync_disk(store, project, attach_images_using(store, project, idx))
332
+ return _with_disk(restored.as_dict(), problems)
333
+
334
+
335
+ # ---------------------------------------------------------------- images
336
+
337
+ @router.get("/projects/{project_id}/images")
338
+ def list_images(
339
+ project_id: str,
340
+ state: str = "",
341
+ limit: int = 500,
342
+ offset: int = 0,
343
+ locate: str = "",
344
+ order: str = "",
345
+ store: Store = Depends(get_store),
346
+ owner: str = Depends(principal),
347
+ ) -> dict[str, Any]:
348
+ """A page of images. ``locate`` names an image whose position in this
349
+ listing is returned as ``position`` -- null if the filter excludes it."""
350
+ project = _project(store, project_id, owner)
351
+ try:
352
+ found = images_mod.listing(
353
+ store, project, state=state, limit=limit, offset=offset, order=order
354
+ )
355
+ payload: dict[str, Any] = {
356
+ "images": [i.as_dict() for i in found],
357
+ "counts": images_mod.counts(store, project),
358
+ "offset": offset,
359
+ }
360
+ if locate:
361
+ payload["position"] = images_mod.position(
362
+ store, project, locate, state=state, order=order
363
+ )
364
+ except StoreError as exc:
365
+ raise _fail(exc) from None
366
+ return payload
367
+
368
+
369
+ @router.get("/projects/{project_id}/resume")
370
+ def resume(
371
+ project_id: str,
372
+ store: Store = Depends(get_store),
373
+ owner: str = Depends(principal),
374
+ ) -> dict[str, Any]:
375
+ """Where to carry on. Opening a project lands here, always."""
376
+ project = _project(store, project_id, owner)
377
+ image = images_mod.resume_point(store, project)
378
+ if image is None:
379
+ return {"image": None}
380
+ return {"image": _image_payload(store, project, image)}
381
+
382
+
383
+ @router.get("/projects/{project_id}/images/{image_id}")
384
+ def image_detail(
385
+ project_id: str,
386
+ image_id: str,
387
+ store: Store = Depends(get_store),
388
+ owner: str = Depends(principal),
389
+ ) -> dict[str, Any]:
390
+ project = _project(store, project_id, owner)
391
+ image = _image(store, project, image_id)
392
+ payload = _image_payload(store, project, image)
393
+ nxt = images_mod.neighbour(store, project, image, 1)
394
+ prv = images_mod.neighbour(store, project, image, -1)
395
+ payload["next"] = nxt.id if nxt else None
396
+ payload["previous"] = prv.id if prv else None
397
+ return payload
398
+
399
+
400
+ @router.patch("/projects/{project_id}/images/{image_id}")
401
+ def patch_image(
402
+ project_id: str,
403
+ image_id: str,
404
+ body: StatePatch,
405
+ store: Store = Depends(get_store),
406
+ owner: str = Depends(principal),
407
+ ) -> dict[str, Any]:
408
+ project = _project(store, project_id, owner)
409
+ image = _image(store, project, image_id)
410
+ try:
411
+ return images_mod.set_state(store, project, image, body.state).as_dict()
412
+ except StoreError as exc:
413
+ raise _fail(exc) from None
414
+
415
+
416
+ # ---------------------------------------------------------------- shapes
417
+
418
+ @router.put("/projects/{project_id}/images/{image_id}/shapes")
419
+ def save_shapes(
420
+ project_id: str,
421
+ image_id: str,
422
+ body: ShapesIn,
423
+ store: Store = Depends(get_store),
424
+ owner: str = Depends(principal),
425
+ ) -> dict[str, Any]:
426
+ """Save one image's shapes.
427
+
428
+ Labels named here that do not exist yet are created -- that is the whole
429
+ "draw a box, type a name, Enter" flow, and why there is no schema step.
430
+
431
+ A 409 carries the server's current state so the editor can reconcile
432
+ against it rather than asking the user to redo the work.
433
+ """
434
+ project = _project(store, project_id, owner)
435
+ image = _image(store, project, image_id)
436
+
437
+ if len(body.shapes) > MAX_SHAPES_PER_SAVE:
438
+ raise HTTPException(
439
+ 413, f"an image can hold at most {MAX_SHAPES_PER_SAVE:,} shapes in one save"
440
+ )
441
+
442
+ # A client that omits an attribute means "unchanged", not "reset". Older
443
+ # editors sent none of these, and every save cleared VOC's difficult,
444
+ # truncated, occluded and pose -- into the user's own XML in attached mode.
445
+ stored = {s.id: s.shape for s in shapes_mod.listing(store, project, image)}
446
+ incoming: list[tuple[str | None, Shape]] = []
447
+ try:
448
+ for raw in body.shapes:
449
+ raw_id = raw.get("id")
450
+ shape_id = raw_id if isinstance(raw_id, str) and valid_id(raw_id) else None
451
+ before = stored.get(shape_id) if shape_id else None
452
+ if before is not None:
453
+ raw = {
454
+ **{key: getattr(before, key) for key in KEPT_ATTRIBUTES if key not in raw},
455
+ **raw,
456
+ }
457
+ incoming.append((shape_id, Shape.from_dict(raw)))
458
+ except AnnotationError as exc:
459
+ raise _fail(exc) from None
460
+
461
+ try:
462
+ saved = shapes_mod.save(
463
+ store,
464
+ project,
465
+ image,
466
+ incoming,
467
+ base_version=body.version,
468
+ advance_state=body.advance_state,
469
+ )
470
+ except Conflict as exc:
471
+ raise HTTPException(
472
+ 409,
473
+ detail={
474
+ "message": str(exc),
475
+ "current": _image_payload(store, project, _image(store, project, image_id)),
476
+ },
477
+ ) from None
478
+ except StoreError as exc:
479
+ raise _fail(exc) from None
480
+
481
+ # Write-through, for a folder opened in place. The database already has the
482
+ # edit, so a folder that has gone read-only degrades to "saved, but not
483
+ # written to disk" with a reason -- never to a lost edit.
484
+ written = ""
485
+ sidecar_error = ""
486
+ if project.is_attached:
487
+ from ...annotate import attach
488
+
489
+ try:
490
+ target = attach.write_through(store, project, image)
491
+ written = target.name if target else ""
492
+ except StoreError as exc:
493
+ sidecar_error = str(exc)
494
+
495
+ return {
496
+ "version": saved.version,
497
+ "inserted": saved.inserted,
498
+ "updated": saved.updated,
499
+ "deleted": saved.deleted,
500
+ "labels_created": saved.labels_created,
501
+ "sidecar": written,
502
+ "sidecar_error": sidecar_error,
503
+ # In submission order, so a client can turn its local drafts into real
504
+ # shapes. Without this the next save would re-send them with no id and
505
+ # insert them a second time.
506
+ "ids": saved.ids,
507
+ "state": image.state,
508
+ "labels": [label.as_dict() for label in labels_mod.listing(store, project)],
509
+ }
510
+
511
+
512
+ # ---------------------------------------------------------------- review
513
+
514
+ @router.post("/projects/{project_id}/images/{image_id}/accept")
515
+ def accept_image(
516
+ project_id: str,
517
+ image_id: str,
518
+ store: Store = Depends(get_store),
519
+ owner: str = Depends(principal),
520
+ ) -> dict[str, Any]:
521
+ """Take this image's predictions as correct and mark it reviewed.
522
+
523
+ What ``Space`` calls. The shapes keep ``origin='model'`` -- an accepted
524
+ prediction is still a prediction, and rewriting that away would empty out
525
+ the agreement metric's denominator.
526
+ """
527
+ from ...annotate import review
528
+
529
+ project = _project(store, project_id, owner)
530
+ image = _image(store, project, image_id)
531
+ confirmed = review.accept_all(store, project, image)
532
+ problems = _sync_disk(store, project, [image.id])
533
+ nxt = images_mod.neighbour(store, project, image, 1)
534
+ return _with_disk({
535
+ "confirmed": confirmed,
536
+ "state": image.state,
537
+ "next": nxt.id if nxt else None,
538
+ "counts": images_mod.counts(store, project),
539
+ "agreement": shapes_mod.agreement(store, project),
540
+ }, problems)
541
+
542
+
543
+ @router.get("/projects/{project_id}/runs")
544
+ def list_runs(
545
+ project_id: str,
546
+ store: Store = Depends(get_store),
547
+ owner: str = Depends(principal),
548
+ ) -> dict[str, Any]:
549
+ from ...annotate import review
550
+
551
+ project = _project(store, project_id, owner)
552
+ return {"runs": review.runs(store, project)}
553
+
554
+
555
+ # ---------------------------------------------------------------- summary
556
+
557
+ @router.get("/projects/{project_id}/summary")
558
+ def summary(
559
+ project_id: str,
560
+ store: Store = Depends(get_store),
561
+ owner: str = Depends(principal),
562
+ ) -> dict[str, Any]:
563
+ """Class balance and model agreement -- the two numbers worth watching."""
564
+ project = _project(store, project_id, owner)
565
+ return {
566
+ "counts": images_mod.counts(store, project),
567
+ "classes": shapes_mod.label_histogram(store, project),
568
+ "agreement": shapes_mod.agreement(store, project),
569
+ "class_list": labels_mod.class_list(store, project),
570
+ }
571
+
572
+
573
+ def register_images(
574
+ store: Store,
575
+ project,
576
+ root: Path,
577
+ entries: list[tuple[str, int, int]],
578
+ ) -> list[Any]:
579
+ """Shared by promotion and by the attached-folder scan."""
580
+ if len(entries) > MAX_IMAGES_PER_CALL:
581
+ raise HTTPException(413, f"at most {MAX_IMAGES_PER_CALL:,} images at a time")
582
+ return images_mod.add_many(store, project, entries)