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,197 @@
1
+ // The class rail: pick a class, or make one by typing its name.
2
+ //
3
+ // This is the component the whole product argument rests on. CVAT makes you
4
+ // define labels before a task exists; here a label is created by using it, and
5
+ // the rail is just a record of what you have used so far.
6
+ //
7
+ // Number keys pick a class. It is the largest throughput affordance in any
8
+ // annotator -- with a hand on the number row and a hand on the mouse, class
9
+ // switching costs nothing.
10
+
11
+ import { readableOn } from "./render.js";
12
+
13
+ export class LabelRail {
14
+ constructor(root, { onPick, onCreate, onRename, onRetire, onToggleHidden }) {
15
+ this.root = root;
16
+ this.list = root.querySelector('[data-role="label-list"]');
17
+ this.template = root.querySelector('[data-role="label-item"]');
18
+ this.input = root.querySelector('[data-role="label-input"]');
19
+ this.onPick = onPick;
20
+ this.onCreate = onCreate;
21
+ this.onRename = onRename;
22
+ this.onRetire = onRetire;
23
+ this.onToggleHidden = onToggleHidden || (() => {});
24
+ this.labels = [];
25
+ this.current = null;
26
+ this.hidden = new Set();
27
+ // What is typed filters the list, and arrows walk what is left. Past ten
28
+ // classes the number row runs out, and scrolling a list for "Handle" is
29
+ // slower than typing "han".
30
+ this.filter = "";
31
+ this.highlight = -1;
32
+
33
+ this.input.addEventListener("input", () => {
34
+ this.filter = this.input.value.trim().toLowerCase();
35
+ this.highlight = -1;
36
+ this.render();
37
+ });
38
+
39
+ this.input.addEventListener("keydown", (event) => {
40
+ if (event.key === "Enter") {
41
+ event.preventDefault();
42
+ this.commit(this.input.value.trim());
43
+ } else if (event.key === "ArrowDown" || event.key === "ArrowUp") {
44
+ event.preventDefault();
45
+ const matches = this.matches();
46
+ if (matches.length) {
47
+ const step = event.key === "ArrowDown" ? 1 : -1;
48
+ this.highlight = (this.highlight + step + matches.length) % matches.length;
49
+ this.render();
50
+ }
51
+ } else if (event.key === "Escape") {
52
+ this.releaseInput();
53
+ }
54
+ // Number keys must reach the canvas, not this field.
55
+ event.stopPropagation();
56
+ });
57
+ }
58
+
59
+ matches() {
60
+ if (!this.filter) return this.labels;
61
+ return this.labels.filter((l) => l.name.toLowerCase().includes(this.filter));
62
+ }
63
+
64
+ // Enter in the class box. An existing class wins over making a new one --
65
+ // **matched without regard to case**. Typing "open" while "Open" exists and
66
+ // getting a second class is precisely how the door set came to hold
67
+ // Close/close/Open/open, and every export after that splits one class in
68
+ // two. Making a case variant is still possible: rename one afterwards.
69
+ commit(name) {
70
+ if (!name) return;
71
+ const matches = this.matches();
72
+ const exact = this.labels.find((l) => l.name.toLowerCase() === name.toLowerCase());
73
+ const chosen = exact || (this.highlight >= 0 ? matches[this.highlight] : null);
74
+ if (chosen) {
75
+ this.releaseInput();
76
+ this.pick(chosen);
77
+ return;
78
+ }
79
+ this.releaseInput();
80
+ this.onCreate(name);
81
+ }
82
+
83
+ setHidden(hidden) {
84
+ this.hidden = new Set(hidden);
85
+ this.render();
86
+ }
87
+
88
+ focusInput() {
89
+ this.input.focus();
90
+ this.input.select();
91
+ }
92
+
93
+ // Naming a class is a step *inside* drawing, not a separate mode. Leaving
94
+ // focus in the text field means the next keystroke -- P for polygon, or a
95
+ // number key -- is typed into the box instead of reaching the canvas, and
96
+ // the tool appears to be broken.
97
+ releaseInput() {
98
+ this.input.value = "";
99
+ this.input.blur();
100
+ if (this.filter || this.highlight >= 0) {
101
+ this.filter = "";
102
+ this.highlight = -1;
103
+ this.render();
104
+ }
105
+ }
106
+
107
+ setLabels(labels) {
108
+ this.labels = labels;
109
+ if (this.current) {
110
+ // Keep the selection pointing at the same *index*, not the same object:
111
+ // a rename must not silently change which class you are drawing.
112
+ this.current = labels.find((l) => l.idx === this.current.idx) || null;
113
+ }
114
+ if (!this.current && labels.length) this.current = labels[0];
115
+ this.render();
116
+ }
117
+
118
+ pick(label) {
119
+ this.current = label || null;
120
+ this.render();
121
+ this.onPick(this.current);
122
+ }
123
+
124
+ // 1-9 then 0 map to the first ten classes, in index order.
125
+ pickByNumber(digit) {
126
+ const position = digit === 0 ? 9 : digit - 1;
127
+ const label = this.labels[position];
128
+ if (label) this.pick(label);
129
+ return !!label;
130
+ }
131
+
132
+ // The index a name maps to, or -1 for a class the server has not made yet.
133
+ indexFor(name) {
134
+ const label = this.labels.find((l) => l.name.toLowerCase() === String(name || "").toLowerCase());
135
+ return label ? label.idx : -1;
136
+ }
137
+
138
+ colourFor(shape) {
139
+ const label =
140
+ this.labels.find((l) => l.idx === shape.labelIdx) ||
141
+ this.labels.find((l) => l.name === shape.label);
142
+ return label ? label.colour : "#8a8a8a";
143
+ }
144
+
145
+ render() {
146
+ this.list.replaceChildren();
147
+ const matches = this.matches();
148
+ const highlighted = this.highlight >= 0 ? matches[this.highlight] : null;
149
+ this.labels.forEach((label, position) => {
150
+ const node = this.template.content.firstElementChild.cloneNode(true);
151
+ const swatch = node.querySelector('[data-role="swatch"]');
152
+ const name = node.querySelector('[data-role="name"]');
153
+ const key = node.querySelector('[data-role="key"]');
154
+ const retire = node.querySelector('[data-role="retire"]');
155
+ const eye = node.querySelector('[data-role="eye"]');
156
+
157
+ swatch.style.background = label.colour;
158
+ swatch.style.color = readableOn(label.colour);
159
+ swatch.textContent = String(label.idx);
160
+ name.textContent = label.name;
161
+ key.textContent = position < 10 ? String(position === 9 ? 0 : position + 1) : "";
162
+ node.dataset.idx = String(label.idx);
163
+ if (this.current && this.current.idx === label.idx) node.dataset.current = "true";
164
+ if (this.filter && !matches.includes(label)) node.hidden = true;
165
+ if (highlighted === label) node.dataset.highlight = "true";
166
+ if (this.hidden.has(label.idx)) {
167
+ node.dataset.hidden = "true";
168
+ eye.title = `Show "${label.name}"`;
169
+ } else {
170
+ eye.title = `Hide "${label.name}" while you work`;
171
+ }
172
+
173
+ node.addEventListener("click", (event) => {
174
+ if (event.target === retire || event.target === eye) return;
175
+ this.pick(label);
176
+ });
177
+ eye.addEventListener("click", (event) => {
178
+ event.stopPropagation();
179
+ this.onToggleHidden(label.idx);
180
+ });
181
+ // Double-click a name to fix a typo. The index does not move, so every
182
+ // file already exported keeps meaning what it meant.
183
+ name.addEventListener("dblclick", () => {
184
+ const next = prompt(`Rename "${label.name}" to:`, label.name);
185
+ if (next && next.trim() && next.trim() !== label.name) {
186
+ this.onRename(label.idx, next.trim());
187
+ }
188
+ });
189
+ retire.addEventListener("click", (event) => {
190
+ event.stopPropagation();
191
+ this.onRetire(label.idx, label.name);
192
+ });
193
+
194
+ this.list.append(node);
195
+ });
196
+ }
197
+ }
@@ -0,0 +1,286 @@
1
+ // Drawing the canvas. Carried over from the Phase 0 spike, which measured it
2
+ // at 0.6ms per frame with 300 shapes on a 4000x3000 image.
3
+ //
4
+ // Two things here are measurements, not preferences:
5
+ //
6
+ // * At full resolution use the plain three-argument drawImage. The explicit
7
+ // source-rectangle form costs 15ms against 4.8ms for identical output,
8
+ // because it drops a fast blit path.
9
+ // * Below full resolution, draw from a mip. Asking the browser to resample
10
+ // 12 megapixels down to 1600px every frame costs 29ms.
11
+ //
12
+ // And one that is a design decision: model shapes are dashed, human shapes
13
+ // solid. That reads at any zoom and survives colour-vision deficiency, which a
14
+ // difference in hue would not -- and hue is already spent on the class.
15
+
16
+ import { handlesOf, rotationHandle } from "./hit.js";
17
+ import { mipFor } from "./viewport.js";
18
+
19
+ const BACKGROUND = "#11100f";
20
+ const HOVER = "#ffffff";
21
+ const HANDLE_SIZE = 5;
22
+
23
+ export function draw(ctx, rect, scene, view, mips, options = {}) {
24
+ ctx.fillStyle = BACKGROUND;
25
+ ctx.fillRect(0, 0, rect.width, rect.height);
26
+
27
+ ctx.save();
28
+ ctx.translate(view.tx, view.ty);
29
+ ctx.scale(view.scale, view.scale);
30
+
31
+ if (mips && mips.length) {
32
+ // Brightness and contrast touch the picture only, never the outlines --
33
+ // a box must stay the same colour however dark the scene is made.
34
+ if (options.imageFilter) ctx.filter = options.imageFilter;
35
+ // Pick by *device* pixels. Choosing by CSS pixels on a 2x screen draws
36
+ // from a mip at half the resolution the display can show -- every fine
37
+ // edge comes out soft, exactly where a tight box needs to see it.
38
+ const dpr = Math.min(globalThis.devicePixelRatio || 1, 2);
39
+ const mip = mipFor(mips, view.width * view.scale * dpr);
40
+ if (mip.width === view.width) {
41
+ ctx.imageSmoothingEnabled = false;
42
+ ctx.drawImage(mip, 0, 0);
43
+ } else {
44
+ ctx.imageSmoothingEnabled = true;
45
+ ctx.drawImage(mip, 0, 0, mip.width, mip.height, 0, 0, view.width, view.height);
46
+ }
47
+ ctx.filter = "none";
48
+ }
49
+
50
+ // Every stroke is divided by the scale so it stays two screen pixels wide at
51
+ // any zoom. This is the difference between a canvas editor and a zoomed
52
+ // picture of one.
53
+ const unit = 1 / view.scale;
54
+
55
+ const visible = options.visible || (() => true);
56
+
57
+ for (const id of scene.order) {
58
+ const shape = scene.shapes.get(id);
59
+ if (!shape) continue;
60
+ // The confidence slider hides, it does not delete. A hidden shape is
61
+ // still in the scene and still saved -- filtering is a way of looking.
62
+ if (!visible(shape)) continue;
63
+ const colour = options.colourFor ? options.colourFor(shape) : "#4363d8";
64
+ const selected = scene.selection.has(id);
65
+ const hovered = scene.hover === id;
66
+
67
+ ctx.strokeStyle = hovered && !selected ? HOVER : colour;
68
+ ctx.lineWidth = (selected ? 3 : 2) * unit;
69
+ // A model shape a person has already corrected is theirs now, so it stops
70
+ // being dashed -- that is the visual feedback for "this one is done".
71
+ const dashed = shape.origin === "model" && !shape.edited && !selected;
72
+ ctx.setLineDash(dashed ? [8 * unit, 6 * unit] : []);
73
+ // Confidence fades the outline, so a wall of low-confidence guesses reads
74
+ // as noise rather than as ground truth.
75
+ ctx.globalAlpha =
76
+ shape.confidence == null ? 1 : 0.35 + 0.65 * Math.max(0, Math.min(1, shape.confidence));
77
+
78
+ const kind = shape.kind || (shape.polygon && shape.polygon.length >= 3 ? "polygon" : "box");
79
+ if (kind === "point") {
80
+ drawPoint(ctx, shape.bbox, colour, unit, selected);
81
+ } else if (kind === "line" && shape.polygon && shape.polygon.length >= 2) {
82
+ tracePath(ctx, shape.polygon, false);
83
+ ctx.stroke();
84
+ if (selected) drawVertices(ctx, shape.polygon, colour, unit);
85
+ } else if (shape.polygon && shape.polygon.length >= 3) {
86
+ tracePath(ctx, shape.polygon, true);
87
+ ctx.stroke();
88
+ if (selected) drawVertices(ctx, shape.polygon, colour, unit);
89
+ if (selected && kind === "obb") drawRotationHandle(ctx, shape, colour, unit, view.scale);
90
+ } else {
91
+ const [x1, y1, x2, y2] = shape.bbox;
92
+ ctx.strokeRect(x1, y1, x2 - x1, y2 - y1);
93
+ }
94
+
95
+ if (selected && (kind === "box" || kind === "polygon")) drawHandles(ctx, shape, colour, unit);
96
+ ctx.globalAlpha = 1;
97
+ }
98
+
99
+ if (options.draft) drawDraft(ctx, options.draft, unit);
100
+
101
+ ctx.globalAlpha = 1;
102
+ ctx.setLineDash([]);
103
+ ctx.restore();
104
+
105
+ // Labels are drawn in screen space, after restore, so text is always the
106
+ // same size and upright regardless of zoom.
107
+ if (options.showLabels !== false) drawLabels(ctx, scene, view, options);
108
+ if (options.crosshair) drawCrosshair(ctx, rect, options.crosshair);
109
+ if (options.draft && options.draft.kind === "box" && options.crosshair) {
110
+ drawSize(ctx, options.draft.bbox, options.crosshair);
111
+ }
112
+ }
113
+
114
+ // Full-canvas guides through the cursor. A box is only as tight as the
115
+ // person can judge where its edge meets the object, and a line running the
116
+ // whole width of the image makes that judgement against every pixel on the
117
+ // row instead of against the few under a mouse pointer. Two strokes -- dark
118
+ // under light -- so the guide reads on snow and on asphalt.
119
+ function drawCrosshair(ctx, rect, { x, y }) {
120
+ ctx.save();
121
+ const px = Math.round(x) + 0.5;
122
+ const py = Math.round(y) + 0.5;
123
+ for (const [style, width] of [["rgba(0,0,0,.55)", 3], ["rgba(255,255,255,.8)", 1]]) {
124
+ ctx.strokeStyle = style;
125
+ ctx.lineWidth = width;
126
+ ctx.beginPath();
127
+ ctx.moveTo(0, py);
128
+ ctx.lineTo(rect.width, py);
129
+ ctx.moveTo(px, 0);
130
+ ctx.lineTo(px, rect.height);
131
+ ctx.stroke();
132
+ }
133
+ ctx.restore();
134
+ }
135
+
136
+ // The size of the box being drawn, in image pixels, beside the cursor. Tiny
137
+ // boxes are the commonest label defect inspect.health finds; seeing "6 × 4"
138
+ // while drawing is cheaper than finding it after training.
139
+ function drawSize(ctx, bbox, { x, y }) {
140
+ const [x1, y1, x2, y2] = bbox;
141
+ const text = `${Math.round(Math.abs(x2 - x1))} × ${Math.round(Math.abs(y2 - y1))}`;
142
+ ctx.save();
143
+ ctx.font = "11px ui-monospace, monospace";
144
+ ctx.textBaseline = "top";
145
+ const width = ctx.measureText(text).width + 8;
146
+ ctx.fillStyle = "rgba(0,0,0,.7)";
147
+ ctx.fillRect(x + 12, y + 12, width, 16);
148
+ ctx.fillStyle = "#ffffff";
149
+ ctx.fillText(text, x + 16, y + 14);
150
+ ctx.restore();
151
+ }
152
+
153
+ function tracePath(ctx, polygon, closed) {
154
+ ctx.beginPath();
155
+ ctx.moveTo(polygon[0][0], polygon[0][1]);
156
+ for (let i = 1; i < polygon.length; i++) ctx.lineTo(polygon[i][0], polygon[i][1]);
157
+ if (closed) ctx.closePath();
158
+ }
159
+
160
+ // A point is a ring with a dot: the ring reads at any zoom, and the hollow
161
+ // between them leaves the pixel it marks visible.
162
+ function drawPoint(ctx, [x, y], colour, unit, selected) {
163
+ ctx.setLineDash([]);
164
+ const r = (selected ? 9 : 7) * unit;
165
+ ctx.beginPath();
166
+ ctx.arc(x, y, r, 0, Math.PI * 2);
167
+ ctx.lineWidth = 2 * unit;
168
+ ctx.strokeStyle = "#ffffff";
169
+ ctx.stroke();
170
+ ctx.beginPath();
171
+ ctx.arc(x, y, r - 1.5 * unit, 0, Math.PI * 2);
172
+ ctx.strokeStyle = colour;
173
+ ctx.stroke();
174
+ ctx.beginPath();
175
+ ctx.arc(x, y, 2 * unit, 0, Math.PI * 2);
176
+ ctx.fillStyle = colour;
177
+ ctx.fill();
178
+ }
179
+
180
+ function drawRotationHandle(ctx, shape, colour, unit, scale) {
181
+ const handle = rotationHandle(shape, scale);
182
+ if (!handle) return;
183
+ const [[ax, ay], [bx, by]] = shape.polygon;
184
+ ctx.setLineDash([]);
185
+ ctx.lineWidth = 1.5 * unit;
186
+ ctx.strokeStyle = colour;
187
+ ctx.beginPath();
188
+ ctx.moveTo((ax + bx) / 2, (ay + by) / 2);
189
+ ctx.lineTo(handle[0], handle[1]);
190
+ ctx.stroke();
191
+ ctx.beginPath();
192
+ ctx.arc(handle[0], handle[1], HANDLE_SIZE * 1.2 * unit, 0, Math.PI * 2);
193
+ ctx.fillStyle = "#ffffff";
194
+ ctx.fill();
195
+ ctx.stroke();
196
+ }
197
+
198
+ function drawHandles(ctx, shape, colour, unit) {
199
+ ctx.setLineDash([]);
200
+ ctx.fillStyle = colour;
201
+ const size = HANDLE_SIZE * unit;
202
+ for (const [hx, hy] of handlesOf(shape)) {
203
+ ctx.fillRect(hx - size, hy - size, size * 2, size * 2);
204
+ }
205
+ }
206
+
207
+ function drawVertices(ctx, polygon, colour, unit) {
208
+ ctx.setLineDash([]);
209
+ const size = HANDLE_SIZE * unit;
210
+ for (const [x, y] of polygon) {
211
+ ctx.fillStyle = "#ffffff";
212
+ ctx.fillRect(x - size, y - size, size * 2, size * 2);
213
+ ctx.fillStyle = colour;
214
+ ctx.fillRect(x - size * 0.6, y - size * 0.6, size * 1.2, size * 1.2);
215
+ }
216
+ }
217
+
218
+ // The shape currently being dragged out or clicked in. Kept out of the scene
219
+ // so an abandoned draw leaves nothing behind to clean up.
220
+ function drawDraft(ctx, draft, unit) {
221
+ ctx.setLineDash([6 * unit, 4 * unit]);
222
+ ctx.strokeStyle = "#ffffff";
223
+ ctx.lineWidth = 1.5 * unit;
224
+
225
+ if (draft.kind === "box") {
226
+ const [x1, y1, x2, y2] = draft.bbox;
227
+ ctx.strokeRect(x1, y1, x2 - x1, y2 - y1);
228
+ } else if ((draft.kind === "polygon" || draft.kind === "line") && draft.points.length) {
229
+ ctx.beginPath();
230
+ ctx.moveTo(draft.points[0][0], draft.points[0][1]);
231
+ for (let i = 1; i < draft.points.length; i++) {
232
+ ctx.lineTo(draft.points[i][0], draft.points[i][1]);
233
+ }
234
+ if (draft.cursor) ctx.lineTo(draft.cursor[0], draft.cursor[1]);
235
+ ctx.stroke();
236
+
237
+ ctx.setLineDash([]);
238
+ const size = HANDLE_SIZE * unit;
239
+ for (const [x, y] of draft.points) {
240
+ ctx.fillStyle = "#ffffff";
241
+ ctx.fillRect(x - size, y - size, size * 2, size * 2);
242
+ }
243
+ }
244
+ ctx.setLineDash([]);
245
+ }
246
+
247
+ function drawLabels(ctx, scene, view, options) {
248
+ ctx.save();
249
+ ctx.font = "12px ui-sans-serif, system-ui, sans-serif";
250
+ ctx.textBaseline = "bottom";
251
+
252
+ const visible = options.visible || (() => true);
253
+
254
+ for (const id of scene.order) {
255
+ const shape = scene.shapes.get(id);
256
+ if (!shape || !visible(shape)) continue;
257
+ const [x1, y1] = shape.bbox;
258
+ const [sx, sy] = view.toScreen(x1, y1);
259
+ // Off-screen labels are the bulk of the text cost on a busy image.
260
+ if (sx < -200 || sy < -40 || sx > ctx.canvas.width || sy > ctx.canvas.height) continue;
261
+
262
+ const colour = options.colourFor ? options.colourFor(shape) : "#4363d8";
263
+ const text =
264
+ shape.confidence == null
265
+ ? shape.label
266
+ : `${shape.label} ${Math.round(shape.confidence * 100)}%`;
267
+ const width = ctx.measureText(text).width;
268
+
269
+ ctx.globalAlpha = 0.92;
270
+ ctx.fillStyle = colour;
271
+ ctx.fillRect(sx, sy - 16, width + 10, 16);
272
+ ctx.globalAlpha = 1;
273
+ ctx.fillStyle = readableOn(colour);
274
+ ctx.fillText(text, sx + 5, sy - 3);
275
+ }
276
+ ctx.restore();
277
+ }
278
+
279
+ // Perceived luminance, so a label on pale yellow is not white-on-white.
280
+ export function readableOn(hex) {
281
+ const value = hex.replace("#", "");
282
+ const r = parseInt(value.slice(0, 2), 16);
283
+ const g = parseInt(value.slice(2, 4), 16);
284
+ const b = parseInt(value.slice(4, 6), 16);
285
+ return 0.299 * r + 0.587 * g + 0.114 * b > 140 ? "#101010" : "#ffffff";
286
+ }