Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions src/annotation/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -699,6 +699,7 @@ export type Annotation =
export interface AnnotationTypeHandler<T extends Annotation = Annotation> {
icon: string;
description: string;
dataProperties: string[];
toJSON: (annotation: T, rank: number) => any;
restoreState: (annotation: T, obj: any, rank: number) => void;
/**
Expand Down Expand Up @@ -820,6 +821,7 @@ export const annotationTypeHandlers: Record<
[AnnotationType.LINE]: {
icon: "ꕹ",
description: "Line",
dataProperties: ["pointA", "pointB"],
toJSON(annotation: Line) {
return {
pointA: Array.from(annotation.pointA),
Expand Down Expand Up @@ -884,6 +886,7 @@ export const annotationTypeHandlers: Record<
[AnnotationType.POLYLINE]: {
icon: "⤤",
description: "Polyline",
dataProperties: ["points"],
toJSON(annotation: PolyLine) {
return {
points: annotation.points.map((point) => Array.from(point)),
Expand Down Expand Up @@ -1015,6 +1018,7 @@ export const annotationTypeHandlers: Record<
[AnnotationType.POINT]: {
icon: "⚬",
description: "Point",
dataProperties: ["point"],
toJSON: (annotation: Point) => {
return {
point: Array.from(annotation.point),
Expand Down Expand Up @@ -1063,6 +1067,7 @@ export const annotationTypeHandlers: Record<
[AnnotationType.AXIS_ALIGNED_BOUNDING_BOX]: {
icon: "❑",
description: "Bounding Box",
dataProperties: ["pointA", "pointB"],
toJSON: (annotation: AxisAlignedBoundingBox) => {
return {
pointA: Array.from(annotation.pointA),
Expand Down Expand Up @@ -1135,6 +1140,7 @@ export const annotationTypeHandlers: Record<
[AnnotationType.ELLIPSOID]: {
icon: "◎",
description: "Ellipsoid",
dataProperties: ["center", "radii"],
toJSON: (annotation: Ellipsoid) => {
return {
center: Array.from(annotation.center),
Expand Down
54 changes: 54 additions & 0 deletions src/layer/annotation/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ import type {
} from "#src/ui/annotations.js";
import { UserLayerWithAnnotationsMixin } from "#src/ui/annotations.js";
import { animationFrameDebounce } from "#src/util/animation_frame_debounce.js";
import { fromCSV, toCSV } from "#src/util/csv.js";
import type { Borrowed, Owned } from "#src/util/disposable.js";
import { RefCounted } from "#src/util/disposable.js";
import { updateChildren } from "#src/util/dom.js";
Expand Down Expand Up @@ -682,6 +683,13 @@ export class AnnotationUserLayer extends Base {
renderScaleControls.element,
tab.element.firstChild,
);
if (this.localAnnotations) {
const downloadButton = document.createElement("button");
downloadButton.textContent = "Download";
downloadButton.title = "Save as csv";
tab.element.appendChild(downloadButton);
downloadButton.addEventListener("click", () => this.saveToCSV());
}
{
const checkbox = tab.registerDisposer(
new TrackableBooleanCheckbox(
Expand Down Expand Up @@ -734,6 +742,52 @@ export class AnnotationUserLayer extends Base {
return x;
}

saveToCSV() {
const { localAnnotations } = this;
if (!localAnnotations) return;
const json = this.toJSON();
const saveToFile = (data: string, filename: string) => {
const blob = new Blob([data], {
type: "text/csv;charset=utf-8;",
});
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = filename;
a.click();
URL.revokeObjectURL(url);
};
const { [ANNOTATIONS_JSON_KEY]: annotations, ...metadata } = json;
saveToFile(JSON.stringify(metadata), `annotations_metadata.json`);
const typeToAnnotations = new Map<string, any[]>();
for (const [index, annotation] of annotations.entries()) {
annotation.index = index;
typeToAnnotations.set(
annotation.type,
(typeToAnnotations.get(annotation.type) ?? []).concat([annotation]),
);
}
for (const [type, annotations] of typeToAnnotations) {
saveToFile(toCSV(annotations), `annotations_${type}.csv`);
}
}

loadFromCSV(metadata: any, csvs: string[]) {
const { localAnnotations } = this;
if (!localAnnotations) return;
const annotations: any[] = [];
for (const csv of csvs) {
for (const { index, ...annotation } of fromCSV(csv)) {
annotations[index ?? annotations.length] = annotation;
}
}
this.dataSources = [];
this.restoreState({
...metadata,
[ANNOTATIONS_JSON_KEY]: annotations,
});
}

observeLayerColor(callback: () => void) {
const disposer = super.observeLayerColor(callback);
const subDisposer = observeWatchable(
Expand Down
56 changes: 55 additions & 1 deletion src/ui/layer_data_sources_tab.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@
* @file Tab for showing layer data sources and coordinate transforms.
*/

import "#src/ui/layer_data_sources_tab.css";
import { LocalDataSource } from "#src/datasource/local.js";
import { AnnotationUserLayer } from "#src/layer/annotation/index.js";
import type { UserLayer, UserLayerConstructor } from "#src/layer/index.js";
import {
changeLayerName,
Expand All @@ -40,6 +40,7 @@ import { MultiscaleVolumeChunkSource } from "#src/sliceview/volume/frontend.js";
import { TrackableBooleanCheckbox } from "#src/trackable_boolean.js";
import type { WatchableValueInterface } from "#src/trackable_value.js";
import { WatchableValue } from "#src/trackable_value.js";
import "#src/ui/layer_data_sources_tab.css";
import type { DebouncedFunction } from "#src/util/animation_frame_debounce.js";
import { animationFrameDebounce } from "#src/util/animation_frame_debounce.js";
import { DataType } from "#src/util/data_type.js";
Expand Down Expand Up @@ -300,6 +301,59 @@ export class LoadedDataSourceView extends RefCounted {
.element,
);
}
const localSubsource = source.subsources.find(
(x) => x.subsourceEntry.subsource.local === LocalDataSource.annotations,
);
const { layer } = source;
if (localSubsource && layer instanceof AnnotationUserLayer) {
const importButton = document.createElement("input");
importButton.type = "file";
importButton.multiple = true;
importButton.accept = ".csv,.json,application/json,text/csv";
importButton.title = "Import annotation state from a CSV file";
element.appendChild(importButton);
importButton.addEventListener("change", async () => {
const files = importButton.files;
if (!files) return;
const processedFiles = await Promise.all(
Array.from(files).map((f) => {
return new Promise<string>((resolve, reject) => {
const reader = new FileReader();
reader.onload = (e) => {
const result = e.target?.result;
if (typeof result !== "string") {
reject(new Error("FileReader result is not a string"));
return;
}
resolve(result);
};
reader.onerror = (e) => {
reject(e);
};
reader.readAsText(f);
});
}),
);
const contentByType = new Map<string, string[]>();
for (const [index, content] of processedFiles.entries()) {
const file = files[index];
contentByType.set(
file.type,
(contentByType.get(file.type) ?? []).concat([content]),
);
}
const metadata = contentByType.get("application/json") ?? [];
if (metadata.length > 1) {
throw new Error("Multiple metadata files provided");
}
if (metadata.length === 0) {
throw new Error("No metadata file provided");
}
const csvs = contentByType.get("text/csv") ?? [];
layer.loadFromCSV(JSON.parse(metadata[0]), csvs);
});
}

const { transform } = source;
if (transform.mutableSourceRank || transform.value.sourceRank !== 0) {
const transformWidget = this.registerDisposer(
Expand Down
89 changes: 89 additions & 0 deletions src/util/csv.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
/**
* @license
* Copyright 2025 Google Inc.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

// TODO, support nested properties

export function toCSV(data: any[]): string {
const header: string[] = [];
const csvRows: string[][] = [];
const addValue = (row: string[], key: string, val: unknown) => {
if (Array.isArray(val)) {
for (const [i, v] of val.entries()) {
addValue(row, `${key}[${i}]`, v);
}
} else {
let columnIdx = header.indexOf(key);
if (columnIdx === -1) {
columnIdx = header.push(key.includes(",") ? `"${key}"` : key) - 1;
}
row[columnIdx] = `${val}`;
}
};
for (const obj of data) {
const row: string[] = [];
for (const [key, val] of Object.entries(obj)) {
if (val !== undefined) {
addValue(row, key, val);
}
}
csvRows.push(row);
}
const sortedHeader = header.slice().sort();
const sortMap = new Map<number, number>();
for (let i = 0; i < header.length; i++) {
sortMap.set(sortedHeader.indexOf(header[i]), i);
}
const sortedRows = csvRows.map((row) => {
const sortedRow = new Array(sortedHeader.length).fill("");
for (let i = 0; i < sortedRow.length; i++) {
sortedRow[i] = row[sortMap.get(i)!];
}
return sortedRow;
});
return [sortedHeader, ...sortedRows].map((row) => row.join(",")).join("\n");
}

export function fromCSV(csv: string) {
const rows = csv.split("\n");
if (rows.length < 2) return []; // need a header and a row
const result: any[] = [];
const [header, ...dataRows] = rows;
const columnNames = header.split(",");
for (const row of dataRows) {
const columns = row.split(",");
const obj = {};
for (const [index, value] of columns.entries()) {
if (value === "") continue;
const column = columnNames[index];
if (column === undefined) {
throw new Error("bad csv");
}
const [name, _] = column.split("[");
let currentTarget: any = obj;
let key: string = name;
const arrayIndices = column
.matchAll(/\[(\d+)\]/g)
.map(([_, index]) => index);
for (const index of arrayIndices) {
currentTarget = currentTarget[key] = currentTarget[key] ?? [];
key = index;
}
currentTarget[key] = value;
}
result.push(obj);
}
return result;
}
Loading