picture-annotation.py
Python script, ASCII text executable
1from pyscript import document, fetch as pyfetch 2from pyscript.ffi import create_proxy 3import asyncio 4import json 5 6document.getElementById("shape-options").style.display = "flex" 7 8image = document.getElementById("annotation-image") 9zone = document.getElementById("annotation-zone") 10confirm_button = document.getElementById("annotation-confirm") 11cancel_button = document.getElementById("annotation-cancel") 12backspace_button = document.getElementById("annotation-backspace") 13delete_button = document.getElementById("annotation-delete") 14previous_button = document.getElementById("annotation-previous") 15next_button = document.getElementById("annotation-next") 16save_button = document.getElementById("annotation-save") 17 18object_list = document.getElementById("object-types") 19 20confirm_button.style.display = "none" 21cancel_button.style.display = "none" 22backspace_button.style.display = "none" 23delete_button.style.display = "none" 24previous_button.style.display = "none" 25next_button.style.display = "none" 26shape_type = "" 27bbox_pos = None 28new_shape = None 29selected_shape = None 30 31 32def make_shape_container(): 33shape = document.createElementNS("http://www.w3.org/2000/svg", "svg") 34shape.setAttribute("width", "100%") 35shape.setAttribute("height", "100%") 36shape.setAttribute("viewBox", f"0 0 {image.naturalWidth} {image.naturalHeight}") 37shape.classList.add("shape-container") 38 39return shape 40 41 42async def get_all_objects(): 43response = await pyfetch("/api/object-types") 44if response.ok: 45return await response.json() 46 47 48def follow_cursor(event): 49rect = zone.getBoundingClientRect() 50x = event.clientX - rect.left 51y = event.clientY - rect.top 52vertical_ruler.style.left = str(x) + "px" 53horizontal_ruler.style.top = str(y) + "px" 54 55 56def change_object_type(event): 57global selected_shape 58if selected_shape is None: 59return 60selected_shape.setAttribute("data-object-type", event.currentTarget.value) 61 62 63change_object_type_proxy = create_proxy(change_object_type) 64 65 66def list_shapes(): 67shapes = list(zone.getElementsByClassName("shape")) 68json_shapes = [] 69for shape in shapes: 70shape_dict = {} 71if shape.tagName == "rect": 72shape_dict["type"] = "bbox" 73shape_dict["shape"] = { 74"x": float(shape.getAttribute("x")) / image.naturalWidth, 75"y": float(shape.getAttribute("y")) / image.naturalHeight, 76"w": float(shape.getAttribute("width")) / image.naturalWidth, 77"h": float(shape.getAttribute("height")) / image.naturalHeight 78} 79elif shape.tagName == "polygon" or shape.tagName == "polyline": 80if shape.tagName == "polygon": 81shape_dict["type"] = "polygon" 82elif shape.tagName == "polyline": 83shape_dict["type"] = "polyline" 84 85points = shape.getAttribute("points").split(" ") 86json_points = [] 87for point in points: 88x, y = point.split(",") 89x, y = float(x), float(y) 90json_points.append({ 91"x": x / image.naturalWidth, 92"y": y / image.naturalHeight 93}) 94 95shape_dict["shape"] = json_points 96elif shape.tagName == "circle" and shape.classList.contains("shape-point"): 97shape_dict["type"] = "point" 98shape_dict["shape"] = { 99"x": float(shape.getAttribute("cx")) / image.naturalWidth, 100"y": float(shape.getAttribute("cy")) / image.naturalHeight 101} 102else: 103continue 104 105shape_dict["object"] = shape.getAttribute("data-object-type") 106json_shapes.append(shape_dict) 107 108return json_shapes 109 110 111def put_shapes(json_shapes): 112for shape in json_shapes: 113new_shape = make_shape_container() 114zone_rect = zone.getBoundingClientRect() 115 116if shape["type"] == "bbox": 117rectangle = document.createElementNS("http://www.w3.org/2000/svg", "rect") 118rectangle.setAttribute("x", str(shape["shape"]["x"] * image.naturalWidth)) 119rectangle.setAttribute("y", str(shape["shape"]["y"] * image.naturalHeight)) 120rectangle.setAttribute("width", str(shape["shape"]["w"] * image.naturalWidth)) 121rectangle.setAttribute("height", str(shape["shape"]["h"] * image.naturalHeight)) 122rectangle.setAttribute("fill", "none") 123rectangle.setAttribute("data-object-type", shape["object"] or "") 124rectangle.classList.add("shape-bbox") 125rectangle.classList.add("shape") 126new_shape.appendChild(rectangle) 127elif shape["type"] == "polygon" or shape["type"] == "polyline": 128polygon = document.createElementNS("http://www.w3.org/2000/svg", shape["type"]) 129points = " ".join( 130[f"{point['x'] * image.naturalWidth},{point['y'] * image.naturalHeight}" for point in shape["shape"]]) 131polygon.setAttribute("points", points) 132polygon.setAttribute("fill", "none") 133polygon.setAttribute("data-object-type", shape["object"] or "") 134polygon.classList.add(f"shape-{shape['type']}") 135polygon.classList.add("shape") 136new_shape.appendChild(polygon) 137elif shape["type"] == "point": 138point = document.createElementNS("http://www.w3.org/2000/svg", "circle") 139point.setAttribute("cx", str(shape["shape"]["x"] * image.naturalWidth)) 140point.setAttribute("cy", str(shape["shape"]["y"] * image.naturalHeight)) 141point.setAttribute("r", "0") 142point.classList.add("shape-point") 143point.classList.add("shape") 144point.setAttribute("data-object-type", shape["object"] or "") 145new_shape.appendChild(point) 146 147zone.appendChild(new_shape) 148 149 150async def load_shapes(): 151resource_id = document.getElementById("resource-id").value 152response = await pyfetch(f"/picture/{resource_id}/get-annotations") 153if response.ok: 154shapes = await response.json() 155return shapes 156 157 158async def save_shapes(event): 159shapes = list_shapes() 160resource_id = document.getElementById("resource-id").value 161print("Saving shapes:", shapes) 162response = await pyfetch(f"/picture/{resource_id}/save-annotations", 163method="POST", 164headers={ 165"Content-Type": "application/json" 166}, 167body=json.dumps(shapes) 168) 169if response.ok: 170return await response 171 172 173save_shapes_proxy = create_proxy(save_shapes) 174save_button.addEventListener("click", save_shapes_proxy) 175delete_shape_key_proxy = create_proxy(lambda event: event.key == "Delete" and delete_shape_proxy(None)) 176next_shape_key_proxy = create_proxy(lambda event: event.key == "ArrowRight" and next_shape_proxy(None)) 177previous_shape_key_proxy = create_proxy(lambda event: event.key == "ArrowLeft" and previous_shape_proxy(None)) 178 179 180def get_centre(shape): 181if shape.tagName == "rect": 182x = float(shape.getAttribute("x")) + float(shape.getAttribute("width")) / 2 183y = float(shape.getAttribute("y")) + float(shape.getAttribute("height")) / 2 184elif shape.tagName == "polygon": 185points = shape.getAttribute("points").split(" ") 186# Average of the extreme points 187sorted_x = sorted([float(point.split(",")[0]) for point in points]) 188sorted_y = sorted([float(point.split(",")[1]) for point in points]) 189top = sorted_y[0] 190bottom = sorted_y[-1] 191left = sorted_x[0] 192right = sorted_x[-1] 193 194x = (left + right) / 2 195y = (top + bottom) / 2 196elif shape.tagName == "polyline": 197points = shape.getAttribute("points").split(" ") 198# Median point 199x = float(points[len(points) // 2].split(",")[0]) 200y = float(points[len(points) // 2].split(",")[1]) 201elif shape.tagName == "circle" and shape.classList.contains("shape-point"): 202x = float(shape.getAttribute("cx")) 203y = float(shape.getAttribute("cy")) 204else: 205return None 206 207return x, y 208 209 210async def focus_shape(shape): 211global selected_shape 212 213if shape_type != "select": 214return 215if selected_shape is not None: 216selected_shape.classList.remove("selected") 217 218selected_shape = shape 219 220selected_shape.classList.add("selected") 221 222objects = await get_all_objects() 223 224delete_button.style.display = "block" 225next_button.style.display = "block" 226previous_button.style.display = "block" 227document.addEventListener("keydown", delete_shape_key_proxy) 228document.addEventListener("keydown", next_shape_key_proxy) 229document.addEventListener("keydown", previous_shape_key_proxy) 230 231object_list.style.display = "flex" 232object_list.style.left = str(get_centre(shape)[0] / image.naturalWidth * 100) + "%" 233object_list.style.top = str(get_centre(shape)[1] / image.naturalHeight * 100) + "%" 234 235object_list.innerHTML = "" 236 237new_radio = document.createElement("input") 238new_radio.setAttribute("type", "radio") 239new_radio.setAttribute("name", "object-type") 240new_radio.setAttribute("value", "") 241new_label = document.createElement("label") 242new_label.appendChild(new_radio) 243new_label.append("Undefined") 244object_list.appendChild(new_label) 245new_radio.addEventListener("change", change_object_type_proxy) 246 247selected_object = selected_shape.getAttribute("data-object-type") 248if not selected_object: 249new_radio.setAttribute("checked", "") 250 251for object, description in objects.items(): 252new_radio = document.createElement("input") 253new_radio.setAttribute("type", "radio") 254new_radio.setAttribute("name", "object-type") 255new_radio.setAttribute("value", object) 256if selected_object == object: 257new_radio.setAttribute("checked", "") 258new_label = document.createElement("label") 259new_label.appendChild(new_radio) 260new_label.append(object) 261object_list.appendChild(new_label) 262new_radio.addEventListener("change", change_object_type_proxy) 263 264 265async def select_shape(event): 266await focus_shape(event.target) 267 268 269async def next_shape(event): 270global selected_shape 271if selected_shape is None: 272return 273 274selected_svg = selected_shape.parentNode 275 276while selected_svg is not None: 277next_sibling = selected_svg.nextElementSibling 278if next_sibling and next_sibling.classList.contains("shape-container"): 279selected_svg = next_sibling 280break 281elif next_sibling is None: 282# If no more siblings, loop back to the first child 283selected_svg = selected_svg.parentNode.firstElementChild 284while selected_svg is not None and not selected_svg.classList.contains( 285"shape-container"): 286selected_svg = selected_svg.nextElementSibling 287break 288else: 289selected_svg = next_sibling 290 291if selected_svg: 292shape = selected_svg.firstElementChild 293await focus_shape(shape) 294 295 296async def previous_shape(event): 297global selected_shape 298if selected_shape is None: 299return 300 301selected_svg = selected_shape.parentNode 302 303while selected_svg is not None: 304next_sibling = selected_svg.previousElementSibling 305if next_sibling and next_sibling.classList.contains("shape-container"): 306selected_svg = next_sibling 307break 308elif next_sibling is None: 309# If no more siblings, loop back to the last child 310selected_svg = selected_svg.parentNode.lastElementChild 311while selected_svg is not None and not selected_svg.classList.contains( 312"shape-container"): 313selected_svg = selected_svg.previousElementSibling 314break 315else: 316selected_svg = next_sibling 317 318if selected_svg: 319shape = selected_svg.firstElementChild 320await focus_shape(shape) 321 322 323def unselect_shape(event): 324global selected_shape 325 326if selected_shape is not None: 327selected_shape.classList.remove("selected") 328selected_shape = None 329 330object_list.innerHTML = "" 331object_list.style.display = "none" 332delete_button.style.display = "none" 333next_button.style.display = "none" 334previous_button.style.display = "none" 335document.removeEventListener("keydown", delete_shape_key_proxy) 336document.removeEventListener("keydown", next_shape_key_proxy) 337document.removeEventListener("keydown", previous_shape_key_proxy) 338 339 340def delete_shape(event): 341global selected_shape 342if selected_shape is None: 343return 344# Shape is SVG shape inside SVG so we need to remove the parent SVG 345selected_shape.parentNode.remove() 346selected_shape = None 347object_list.innerHTML = "" 348object_list.style.display = "none" 349delete_button.style.display = "none" 350next_button.style.display = "none" 351previous_button.style.display = "none" 352document.removeEventListener("keydown", delete_shape_key_proxy) 353document.removeEventListener("keydown", next_shape_key_proxy) 354document.removeEventListener("keydown", previous_shape_key_proxy) 355 356 357select_shape_proxy = create_proxy(select_shape) 358unselect_shape_proxy = create_proxy(unselect_shape) 359delete_shape_proxy = create_proxy(delete_shape) 360next_shape_proxy = create_proxy(next_shape) 361previous_shape_proxy = create_proxy(previous_shape) 362 363delete_button.addEventListener("click", delete_shape_proxy) 364next_button.addEventListener("click", next_shape_proxy) 365previous_button.addEventListener("click", previous_shape_proxy) 366 367# These are functions usable in JS 368cancel_bbox_proxy = create_proxy(lambda event: cancel_bbox(event)) 369make_bbox_proxy = create_proxy(lambda event: make_bbox(event)) 370make_polygon_proxy = create_proxy(lambda event: make_polygon(event)) 371follow_cursor_proxy = create_proxy(follow_cursor) 372 373 374def switch_shape(event): 375global shape_type 376object_list.innerHTML = "" 377unselect_shape(None) 378shape = event.currentTarget.id 379shape_type = shape 380if shape_type == "select": 381# Add event listeners to existing shapes 382print(len(list(document.getElementsByClassName("shape"))), "shapes found") 383for shape in document.getElementsByClassName("shape"): 384print("Adding event listener to shape:", shape) 385shape.addEventListener("click", select_shape_proxy) 386image.addEventListener("click", unselect_shape_proxy) 387helper_message.innerText = "Click on a shape to select" 388# Cancel the current shape creation 389if shape_type == "shape-bbox": 390cancel_bbox(None) 391elif shape_type == "shape-polygon": 392cancel_polygon(None) 393elif shape_type == "shape-polyline": 394cancel_polygon(None) 395else: 396# Remove event listeners for selection 397for shape in document.getElementsByClassName("shape"): 398print("Removing event listener from shape:", shape) 399shape.removeEventListener("click", select_shape_proxy) 400image.removeEventListener("click", unselect_shape_proxy) 401helper_message.innerText = "Select a shape type then click on the image to begin defining it" 402print("Shape is now of type:", shape) 403 404 405def select_mode(): 406global shape_type 407shape_type = "select" 408document.getElementById("select").click() 409 410 411vertical_ruler = document.getElementById("annotation-ruler-vertical") 412horizontal_ruler = document.getElementById("annotation-ruler-horizontal") 413vertical_ruler_2 = document.getElementById("annotation-ruler-vertical-secondary") 414horizontal_ruler_2 = document.getElementById("annotation-ruler-horizontal-secondary") 415helper_message = document.getElementById("annotation-helper-message") 416 417helper_message.innerText = "Select a shape type then click on the image to begin defining it" 418 419 420def cancel_bbox(event): 421global bbox_pos, new_shape 422 423# Key must be ESCAPE 424if event is not None and hasattr(event, "key") and event.key != "Escape": 425return 426 427if new_shape is not None and event is not None: 428# Require event so the shape is kept when it ends normally 429new_shape.remove() 430zone.removeEventListener("click", make_bbox_proxy) 431document.removeEventListener("keydown", cancel_bbox_proxy) 432cancel_button.removeEventListener("click", cancel_bbox_proxy) 433 434bbox_pos = None 435vertical_ruler.style.display = "none" 436horizontal_ruler.style.display = "none" 437vertical_ruler_2.style.display = "none" 438horizontal_ruler_2.style.display = "none" 439zone.style.cursor = "auto" 440cancel_button.style.display = "none" 441helper_message.innerText = "Select a shape type then click on the image to begin defining it" 442new_shape = None 443 444 445def make_bbox(event): 446global new_shape, bbox_pos 447zone_rect = zone.getBoundingClientRect() 448 449if bbox_pos is None: 450helper_message.innerText = "Now define the second point" 451 452bbox_pos = [(event.clientX - zone_rect.left) / zone_rect.width, 453(event.clientY - zone_rect.top) / zone_rect.height] 454vertical_ruler_2.style.left = str(bbox_pos[0] * 100) + "%" 455horizontal_ruler_2.style.top = str(bbox_pos[1] * 100) + "%" 456vertical_ruler_2.style.display = "block" 457horizontal_ruler_2.style.display = "block" 458 459else: 460x0, y0 = bbox_pos.copy() 461x1 = (event.clientX - zone_rect.left) / zone_rect.width 462y1 = (event.clientY - zone_rect.top) / zone_rect.height 463 464rectangle = document.createElementNS("http://www.w3.org/2000/svg", "rect") 465 466new_shape = make_shape_container() 467zone_rect = zone.getBoundingClientRect() 468 469new_shape.appendChild(rectangle) 470zone.appendChild(new_shape) 471 472minx = min(x0, x1) 473miny = min(y0, y1) 474maxx = max(x0, x1) 475maxy = max(y0, y1) 476 477rectangle.setAttribute("x", str(minx * image.naturalWidth)) 478rectangle.setAttribute("y", str(miny * image.naturalHeight)) 479rectangle.setAttribute("width", str((maxx - minx) * image.naturalWidth)) 480rectangle.setAttribute("height", str((maxy - miny) * image.naturalHeight)) 481rectangle.setAttribute("fill", "none") 482rectangle.setAttribute("data-object-type", "") 483rectangle.classList.add("shape-bbox") 484rectangle.classList.add("shape") 485 486# Add event listeners to the new shape 487rectangle.addEventListener("click", select_shape_proxy) 488 489cancel_bbox(None) 490 491 492polygon_points = [] 493 494 495def make_polygon(event): 496global new_shape, polygon_points 497 498polygon = new_shape.children[0] 499 500zone_rect = zone.getBoundingClientRect() 501 502polygon_points.append(((event.clientX - zone_rect.left) / zone_rect.width, 503(event.clientY - zone_rect.top) / zone_rect.height)) 504 505# Update the polygon 506polygon.setAttribute("points", " ".join( 507[f"{point[0] * image.naturalWidth},{point[1] * image.naturalHeight}" for point in 508polygon_points])) 509 510 511def reset_polygon(): 512global new_shape, polygon_points 513 514zone.removeEventListener("click", make_polygon_proxy) 515document.removeEventListener("keydown", close_polygon_proxy) 516document.removeEventListener("keydown", cancel_polygon_proxy) 517document.removeEventListener("keydown", backspace_polygon_proxy) 518confirm_button.style.display = "none" 519cancel_button.style.display = "none" 520backspace_button.style.display = "none" 521confirm_button.removeEventListener("click", close_polygon_proxy) 522cancel_button.removeEventListener("click", cancel_polygon_proxy) 523backspace_button.removeEventListener("click", backspace_polygon_proxy) 524polygon_points.clear() 525 526zone.style.cursor = "auto" 527new_shape = None 528 529 530def close_polygon(event): 531if event is not None and hasattr(event, "key") and event.key != "Enter": 532return 533# Polygon is already there, but we need to remove the events 534reset_polygon() 535 536 537def cancel_polygon(event): 538if event is not None and hasattr(event, "key") and event.key != "Escape": 539return 540# Delete the polygon 541new_shape.remove() 542reset_polygon() 543 544 545def backspace_polygon(event): 546if event is not None and hasattr(event, "key") and event.key != "Backspace": 547return 548if not polygon_points: 549return 550polygon_points.pop() 551polygon = new_shape.children[0] 552polygon.setAttribute("points", " ".join( 553[f"{point[0] * image.naturalWidth},{point[1] * image.naturalHeight}" for point in 554polygon_points])) 555 556 557close_polygon_proxy = create_proxy(close_polygon) 558cancel_polygon_proxy = create_proxy(cancel_polygon) 559backspace_polygon_proxy = create_proxy(backspace_polygon) 560 561 562def open_shape(event): 563global new_shape, bbox_pos 564if bbox_pos or shape_type == "select": 565return 566print("Creating a new shape of type:", shape_type) 567 568if shape_type == "shape-bbox": 569helper_message.innerText = ("Define the first point at the intersection of the lines " 570"by clicking on the image, or click the cross to cancel") 571 572cancel_button.addEventListener("click", cancel_bbox_proxy) 573document.addEventListener("keydown", cancel_bbox_proxy) 574cancel_button.style.display = "block" 575bbox_pos = None 576zone.addEventListener("click", make_bbox_proxy) 577vertical_ruler.style.display = "block" 578horizontal_ruler.style.display = "block" 579zone.style.cursor = "crosshair" 580elif shape_type == "shape-polygon" or shape_type == "shape-polyline": 581if shape_type == "shape-polygon": 582helper_message.innerText = ("Click on the image to define the points of the polygon, " 583"press escape to cancel, enter to close, or backspace to " 584"remove the last point") 585elif shape_type == "shape-polyline": 586helper_message.innerText = ("Click on the image to define the points of the polyline, " 587"press escape to cancel, enter to finish, or backspace to " 588"remove the last point") 589 590if not polygon_points and not new_shape: 591new_shape = make_shape_container() 592zone_rect = zone.getBoundingClientRect() 593 594if not polygon_points and int(new_shape.children.length) == 0: 595zone.addEventListener("click", make_polygon_proxy) 596document.addEventListener("keydown", close_polygon_proxy) 597document.addEventListener("keydown", cancel_polygon_proxy) 598document.addEventListener("keydown", backspace_polygon_proxy) 599cancel_button.addEventListener("click", cancel_polygon_proxy) 600cancel_button.style.display = "block" 601confirm_button.addEventListener("click", close_polygon_proxy) 602confirm_button.style.display = "block" 603backspace_button.addEventListener("click", backspace_polygon_proxy) 604backspace_button.style.display = "block" 605if shape_type == "shape-polygon": 606polygon = document.createElementNS("http://www.w3.org/2000/svg", "polygon") 607polygon.classList.add("shape-polygon") 608elif shape_type == "shape-polyline": 609polygon = document.createElementNS("http://www.w3.org/2000/svg", "polyline") 610polygon.classList.add("shape-polyline") 611polygon.setAttribute("fill", "none") 612polygon.setAttribute("data-object-type", "") 613polygon.classList.add("shape") 614new_shape.appendChild(polygon) 615zone.appendChild(new_shape) 616zone.style.cursor = "crosshair" 617elif shape_type == "shape-point": 618point = document.createElementNS("http://www.w3.org/2000/svg", "circle") 619zone_rect = zone.getBoundingClientRect() 620point.setAttribute("cx", str((event.clientX - zone_rect.left) / zone_rect.width * image.naturalWidth)) 621point.setAttribute("cy", str((event.clientY - zone_rect.top) / zone_rect.height * image.naturalHeight)) 622point.setAttribute("r", "0") 623point.classList.add("shape-point") 624point.classList.add("shape") 625point.setAttribute("data-object-type", "") 626 627new_shape = make_shape_container() 628zone_rect = zone.getBoundingClientRect() 629 630new_shape.appendChild(point) 631zone.appendChild(new_shape) 632 633new_shape = None 634 635 636 637for button in list(document.getElementById("shape-selector").children): 638button.addEventListener("click", create_proxy(switch_shape)) 639print("Shape", button.id, "is available") 640 641zone.addEventListener("mousemove", follow_cursor_proxy) 642zone.addEventListener("click", create_proxy(open_shape)) 643 644# Load existing annotations, if any 645put_shapes(await load_shapes()) 646print("Ready!") 647