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.innerHTML = "" 232 233new_radio = document.createElement("input") 234new_radio.setAttribute("type", "radio") 235new_radio.setAttribute("name", "object-type") 236new_radio.setAttribute("value", "") 237new_label = document.createElement("label") 238new_label.appendChild(new_radio) 239new_label.append("Undefined") 240object_list.appendChild(new_label) 241new_radio.addEventListener("change", change_object_type_proxy) 242 243selected_object = selected_shape.getAttribute("data-object-type") 244if not selected_object: 245new_radio.setAttribute("checked", "") 246 247for object, description in objects.items(): 248new_radio = document.createElement("input") 249new_radio.setAttribute("type", "radio") 250new_radio.setAttribute("name", "object-type") 251new_radio.setAttribute("value", object) 252if selected_object == object: 253new_radio.setAttribute("checked", "") 254new_label = document.createElement("label") 255new_label.appendChild(new_radio) 256new_label.append(object) 257object_list.appendChild(new_label) 258new_radio.addEventListener("change", change_object_type_proxy) 259 260object_list.style.display = "flex" 261object_list.style.left = str(get_centre(shape)[0] / image.naturalWidth * 100) + "%" 262object_list.style.top = str(get_centre(shape)[1] / image.naturalHeight * 100) + "%" 263object_list.style.right = "auto" 264object_list.style.bottom = "auto" 265 266if (get_centre(shape)[0] + object_list.offsetWidth) / image.naturalWidth > 1: 267object_list.style.left = "auto" 268object_list.style.right = str((image.naturalWidth - get_centre(shape)[0]) / image.naturalWidth * 100) + "%" 269 270if (get_centre(shape)[1] + object_list.offsetHeight) / image.naturalHeight > 1: 271object_list.style.top = "auto" 272object_list.style.bottom = str((image.naturalHeight - get_centre(shape)[1]) / image.naturalHeight * 100) + "%" 273 274 275async def select_shape(event): 276await focus_shape(event.target) 277 278 279async def next_shape(event): 280global selected_shape 281if selected_shape is None: 282return 283 284selected_svg = selected_shape.parentNode 285 286while selected_svg is not None: 287next_sibling = selected_svg.nextElementSibling 288if next_sibling and next_sibling.classList.contains("shape-container"): 289selected_svg = next_sibling 290break 291elif next_sibling is None: 292# If no more siblings, loop back to the first child 293selected_svg = selected_svg.parentNode.firstElementChild 294while selected_svg is not None and not selected_svg.classList.contains( 295"shape-container"): 296selected_svg = selected_svg.nextElementSibling 297break 298else: 299selected_svg = next_sibling 300 301if selected_svg: 302shape = selected_svg.firstElementChild 303await focus_shape(shape) 304 305 306async def previous_shape(event): 307global selected_shape 308if selected_shape is None: 309return 310 311selected_svg = selected_shape.parentNode 312 313while selected_svg is not None: 314next_sibling = selected_svg.previousElementSibling 315if next_sibling and next_sibling.classList.contains("shape-container"): 316selected_svg = next_sibling 317break 318elif next_sibling is None: 319# If no more siblings, loop back to the last child 320selected_svg = selected_svg.parentNode.lastElementChild 321while selected_svg is not None and not selected_svg.classList.contains( 322"shape-container"): 323selected_svg = selected_svg.previousElementSibling 324break 325else: 326selected_svg = next_sibling 327 328if selected_svg: 329shape = selected_svg.firstElementChild 330await focus_shape(shape) 331 332 333def unselect_shape(event): 334global selected_shape 335 336if selected_shape is not None: 337selected_shape.classList.remove("selected") 338selected_shape = None 339 340object_list.innerHTML = "" 341object_list.style.display = "none" 342delete_button.style.display = "none" 343next_button.style.display = "none" 344previous_button.style.display = "none" 345document.removeEventListener("keydown", delete_shape_key_proxy) 346document.removeEventListener("keydown", next_shape_key_proxy) 347document.removeEventListener("keydown", previous_shape_key_proxy) 348 349 350def delete_shape(event): 351global selected_shape 352if selected_shape is None: 353return 354# Shape is SVG shape inside SVG so we need to remove the parent SVG 355selected_shape.parentNode.remove() 356selected_shape = None 357object_list.innerHTML = "" 358object_list.style.display = "none" 359delete_button.style.display = "none" 360next_button.style.display = "none" 361previous_button.style.display = "none" 362document.removeEventListener("keydown", delete_shape_key_proxy) 363document.removeEventListener("keydown", next_shape_key_proxy) 364document.removeEventListener("keydown", previous_shape_key_proxy) 365 366 367select_shape_proxy = create_proxy(select_shape) 368unselect_shape_proxy = create_proxy(unselect_shape) 369delete_shape_proxy = create_proxy(delete_shape) 370next_shape_proxy = create_proxy(next_shape) 371previous_shape_proxy = create_proxy(previous_shape) 372 373delete_button.addEventListener("click", delete_shape_proxy) 374next_button.addEventListener("click", next_shape_proxy) 375previous_button.addEventListener("click", previous_shape_proxy) 376 377# These are functions usable in JS 378cancel_bbox_proxy = create_proxy(lambda event: cancel_bbox(event)) 379make_bbox_proxy = create_proxy(lambda event: make_bbox(event)) 380make_polygon_proxy = create_proxy(lambda event: make_polygon(event)) 381follow_cursor_proxy = create_proxy(follow_cursor) 382 383 384def switch_shape(event): 385global shape_type 386object_list.innerHTML = "" 387unselect_shape(None) 388shape = event.currentTarget.id 389shape_type = shape 390if shape_type == "select": 391# Add event listeners to existing shapes 392print(len(list(document.getElementsByClassName("shape"))), "shapes found") 393for shape in document.getElementsByClassName("shape"): 394print("Adding event listener to shape:", shape) 395shape.addEventListener("click", select_shape_proxy) 396image.addEventListener("click", unselect_shape_proxy) 397helper_message.innerText = "Click on a shape to select" 398# Cancel the current shape creation 399if shape_type == "shape-bbox": 400cancel_bbox(None) 401elif shape_type == "shape-polygon": 402cancel_polygon(None) 403elif shape_type == "shape-polyline": 404cancel_polygon(None) 405else: 406# Remove event listeners for selection 407for shape in document.getElementsByClassName("shape"): 408print("Removing event listener from shape:", shape) 409shape.removeEventListener("click", select_shape_proxy) 410image.removeEventListener("click", unselect_shape_proxy) 411helper_message.innerText = "Select a shape type then click on the image to begin defining it" 412print("Shape is now of type:", shape) 413 414 415def select_mode(): 416global shape_type 417shape_type = "select" 418document.getElementById("select").click() 419 420 421vertical_ruler = document.getElementById("annotation-ruler-vertical") 422horizontal_ruler = document.getElementById("annotation-ruler-horizontal") 423vertical_ruler_2 = document.getElementById("annotation-ruler-vertical-secondary") 424horizontal_ruler_2 = document.getElementById("annotation-ruler-horizontal-secondary") 425helper_message = document.getElementById("annotation-helper-message") 426 427helper_message.innerText = "Select a shape type then click on the image to begin defining it" 428 429 430def cancel_bbox(event): 431global bbox_pos, new_shape 432 433# Key must be ESCAPE 434if event is not None and hasattr(event, "key") and event.key != "Escape": 435return 436 437if new_shape is not None and event is not None: 438# Require event so the shape is kept when it ends normally 439new_shape.remove() 440zone.removeEventListener("click", make_bbox_proxy) 441document.removeEventListener("keydown", cancel_bbox_proxy) 442cancel_button.removeEventListener("click", cancel_bbox_proxy) 443 444bbox_pos = None 445vertical_ruler.style.display = "none" 446horizontal_ruler.style.display = "none" 447vertical_ruler_2.style.display = "none" 448horizontal_ruler_2.style.display = "none" 449zone.style.cursor = "auto" 450cancel_button.style.display = "none" 451helper_message.innerText = "Select a shape type then click on the image to begin defining it" 452new_shape = None 453 454 455def make_bbox(event): 456global new_shape, bbox_pos 457zone_rect = zone.getBoundingClientRect() 458 459if bbox_pos is None: 460helper_message.innerText = "Now define the second point" 461 462bbox_pos = [(event.clientX - zone_rect.left) / zone_rect.width, 463(event.clientY - zone_rect.top) / zone_rect.height] 464vertical_ruler_2.style.left = str(bbox_pos[0] * 100) + "%" 465horizontal_ruler_2.style.top = str(bbox_pos[1] * 100) + "%" 466vertical_ruler_2.style.display = "block" 467horizontal_ruler_2.style.display = "block" 468 469else: 470x0, y0 = bbox_pos.copy() 471x1 = (event.clientX - zone_rect.left) / zone_rect.width 472y1 = (event.clientY - zone_rect.top) / zone_rect.height 473 474rectangle = document.createElementNS("http://www.w3.org/2000/svg", "rect") 475 476new_shape = make_shape_container() 477zone_rect = zone.getBoundingClientRect() 478 479new_shape.appendChild(rectangle) 480zone.appendChild(new_shape) 481 482minx = min(x0, x1) 483miny = min(y0, y1) 484maxx = max(x0, x1) 485maxy = max(y0, y1) 486 487rectangle.setAttribute("x", str(minx * image.naturalWidth)) 488rectangle.setAttribute("y", str(miny * image.naturalHeight)) 489rectangle.setAttribute("width", str((maxx - minx) * image.naturalWidth)) 490rectangle.setAttribute("height", str((maxy - miny) * image.naturalHeight)) 491rectangle.setAttribute("fill", "none") 492rectangle.setAttribute("data-object-type", "") 493rectangle.classList.add("shape-bbox") 494rectangle.classList.add("shape") 495 496# Add event listeners to the new shape 497rectangle.addEventListener("click", select_shape_proxy) 498 499cancel_bbox(None) 500 501 502polygon_points = [] 503 504 505def make_polygon(event): 506global new_shape, polygon_points 507 508polygon = new_shape.children[0] 509 510zone_rect = zone.getBoundingClientRect() 511 512polygon_points.append(((event.clientX - zone_rect.left) / zone_rect.width, 513(event.clientY - zone_rect.top) / zone_rect.height)) 514 515# Update the polygon 516polygon.setAttribute("points", " ".join( 517[f"{point[0] * image.naturalWidth},{point[1] * image.naturalHeight}" for point in 518polygon_points])) 519 520 521def reset_polygon(): 522global new_shape, polygon_points 523 524zone.removeEventListener("click", make_polygon_proxy) 525document.removeEventListener("keydown", close_polygon_proxy) 526document.removeEventListener("keydown", cancel_polygon_proxy) 527document.removeEventListener("keydown", backspace_polygon_proxy) 528confirm_button.style.display = "none" 529cancel_button.style.display = "none" 530backspace_button.style.display = "none" 531confirm_button.removeEventListener("click", close_polygon_proxy) 532cancel_button.removeEventListener("click", cancel_polygon_proxy) 533backspace_button.removeEventListener("click", backspace_polygon_proxy) 534polygon_points.clear() 535 536zone.style.cursor = "auto" 537new_shape = None 538 539 540def close_polygon(event): 541if event is not None and hasattr(event, "key") and event.key != "Enter": 542return 543# Polygon is already there, but we need to remove the events 544reset_polygon() 545 546 547def cancel_polygon(event): 548if event is not None and hasattr(event, "key") and event.key != "Escape": 549return 550# Delete the polygon 551new_shape.remove() 552reset_polygon() 553 554 555def backspace_polygon(event): 556if event is not None and hasattr(event, "key") and event.key != "Backspace": 557return 558if not polygon_points: 559return 560polygon_points.pop() 561polygon = new_shape.children[0] 562polygon.setAttribute("points", " ".join( 563[f"{point[0] * image.naturalWidth},{point[1] * image.naturalHeight}" for point in 564polygon_points])) 565 566 567close_polygon_proxy = create_proxy(close_polygon) 568cancel_polygon_proxy = create_proxy(cancel_polygon) 569backspace_polygon_proxy = create_proxy(backspace_polygon) 570 571 572def open_shape(event): 573global new_shape, bbox_pos 574if bbox_pos or shape_type == "select": 575return 576print("Creating a new shape of type:", shape_type) 577 578if shape_type == "shape-bbox": 579helper_message.innerText = ("Define the first point at the intersection of the lines " 580"by clicking on the image, or click the cross to cancel") 581 582cancel_button.addEventListener("click", cancel_bbox_proxy) 583document.addEventListener("keydown", cancel_bbox_proxy) 584cancel_button.style.display = "block" 585bbox_pos = None 586zone.addEventListener("click", make_bbox_proxy) 587vertical_ruler.style.display = "block" 588horizontal_ruler.style.display = "block" 589zone.style.cursor = "crosshair" 590elif shape_type == "shape-polygon" or shape_type == "shape-polyline": 591if shape_type == "shape-polygon": 592helper_message.innerText = ("Click on the image to define the points of the polygon, " 593"press escape to cancel, enter to close, or backspace to " 594"remove the last point") 595elif shape_type == "shape-polyline": 596helper_message.innerText = ("Click on the image to define the points of the polyline, " 597"press escape to cancel, enter to finish, or backspace to " 598"remove the last point") 599 600if not polygon_points and not new_shape: 601new_shape = make_shape_container() 602zone_rect = zone.getBoundingClientRect() 603 604if not polygon_points and int(new_shape.children.length) == 0: 605zone.addEventListener("click", make_polygon_proxy) 606document.addEventListener("keydown", close_polygon_proxy) 607document.addEventListener("keydown", cancel_polygon_proxy) 608document.addEventListener("keydown", backspace_polygon_proxy) 609cancel_button.addEventListener("click", cancel_polygon_proxy) 610cancel_button.style.display = "block" 611confirm_button.addEventListener("click", close_polygon_proxy) 612confirm_button.style.display = "block" 613backspace_button.addEventListener("click", backspace_polygon_proxy) 614backspace_button.style.display = "block" 615if shape_type == "shape-polygon": 616polygon = document.createElementNS("http://www.w3.org/2000/svg", "polygon") 617polygon.classList.add("shape-polygon") 618elif shape_type == "shape-polyline": 619polygon = document.createElementNS("http://www.w3.org/2000/svg", "polyline") 620polygon.classList.add("shape-polyline") 621polygon.setAttribute("fill", "none") 622polygon.setAttribute("data-object-type", "") 623polygon.classList.add("shape") 624new_shape.appendChild(polygon) 625zone.appendChild(new_shape) 626zone.style.cursor = "crosshair" 627elif shape_type == "shape-point": 628point = document.createElementNS("http://www.w3.org/2000/svg", "circle") 629zone_rect = zone.getBoundingClientRect() 630point.setAttribute("cx", str((event.clientX - zone_rect.left) / zone_rect.width * image.naturalWidth)) 631point.setAttribute("cy", str((event.clientY - zone_rect.top) / zone_rect.height * image.naturalHeight)) 632point.setAttribute("r", "0") 633point.classList.add("shape-point") 634point.classList.add("shape") 635point.setAttribute("data-object-type", "") 636 637new_shape = make_shape_container() 638zone_rect = zone.getBoundingClientRect() 639 640new_shape.appendChild(point) 641zone.appendChild(new_shape) 642 643new_shape = None 644 645 646 647for button in list(document.getElementById("shape-selector").children): 648button.addEventListener("click", create_proxy(switch_shape)) 649print("Shape", button.id, "is available") 650 651zone.addEventListener("mousemove", follow_cursor_proxy) 652zone.addEventListener("click", create_proxy(open_shape)) 653 654# Load existing annotations, if any 655put_shapes(await load_shapes()) 656print("Ready!") 657