Spaces:
Running
Running
File size: 12,978 Bytes
d806877 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 | /* Full-inventory annotation state and portable, locally verified checkpoints. */
export const VERSION = "0.1.0";
export const STATUSES = Object.freeze(["unlabelled", "labelled", "abstained"]);
const FILTERS = ["all", ...STATUSES];
const verifiedCheckpoints = new WeakSet();
const whitespace =
/^[\u0009-\u000d\u001c-\u0020\u0085\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000]+|[\u0009-\u000d\u001c-\u0020\u0085\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000]+$/gu;
const trim = (text) => text.replace(whitespace, "");
const clone = (value) => JSON.parse(JSON.stringify(value));
function freeze(value) {
if (value && typeof value === "object") {
Object.values(value).forEach(freeze);
Object.freeze(value);
}
return value;
}
function exactKeys(value, keys) {
return (
value &&
typeof value === "object" &&
!Array.isArray(value) &&
Object.keys(value).length === keys.length &&
keys.every((k) => Object.hasOwn(value, k))
);
}
function scalar(text) {
for (const c of text) {
const n = c.codePointAt(0);
if (n >= 0xd800 && n <= 0xdfff) return false;
}
return true;
}
function validString(value, max) {
return (
typeof value === "string" &&
value.length <= max &&
scalar(value) &&
trim(value).length > 0
);
}
export function parseTaxonomy(raw) {
if (typeof raw !== "string") throw Error("Enter one label per line.");
return validateTaxonomy(raw.split("\n").map(trim).filter(Boolean));
}
function validateTaxonomy(labels) {
if (
!Array.isArray(labels) ||
labels.length < 2 ||
labels.length > 9 ||
labels.some((l) => !validString(l, 64) || trim(l) !== l) ||
new Set(labels).size !== labels.length
) {
throw Error(
"Use 2–9 distinct, trimmed Unicode labels, up to 64 UTF-16 units each.",
);
}
return labels.slice();
}
export function normalizeInventory(value) {
if (!exactKeys(value, ["taxonomy", "items"]))
throw Error("Inventory needs exactly taxonomy and items.");
const taxonomy = validateTaxonomy(value.taxonomy);
if (
!Array.isArray(value.items) ||
value.items.length < 1 ||
value.items.length > 1000
) {
throw Error("Use 1–1,000 inventory records.");
}
const ids = new Set();
const items = value.items.map((r, i) => {
if (
!exactKeys(r, ["id", "group", "text"]) ||
!validString(r.id, 128) ||
!(r.group === null || validString(r.group, 128)) ||
!validString(r.text, 16384)
) {
throw Error(
`Record ${i + 1} needs a valid id, group (string or null) and text.`,
);
}
if (ids.has(r.id)) throw Error(`Record ${i + 1} has a duplicate id.`);
ids.add(r.id);
return { id: r.id, group: r.group, text: r.text };
});
return { taxonomy, items };
}
export function parseSetup(raw, taxonomyText) {
if (
typeof raw !== "string" ||
raw.length > 1048576 ||
new TextEncoder().encode(raw).length > 1048576
) {
throw Error("Setup JSONL exceeds 1 MiB UTF-8.");
}
let lines = raw.split("\n");
if (raw.endsWith("\n")) lines.pop();
const items = [];
let blank = 0;
for (const [i, line] of lines.entries()) {
if (!trim(line)) {
blank++;
continue;
}
if (items.length >= 1000) throw Error("Setup exceeds 1,000 records.");
try {
items.push(JSON.parse(line));
} catch {
throw Error(`Invalid JSON on line ${i + 1}.`);
}
}
return {
inventory: normalizeInventory({
taxonomy: parseTaxonomy(taxonomyText),
items,
}),
blank_lines_ignored: blank,
};
}
export async function sha256(text) {
if (!globalThis.crypto?.subtle)
throw Error("Use HTTPS or localhost for checkpoint digests.");
const result = await crypto.subtle.digest(
"SHA-256",
new TextEncoder().encode(text),
);
return Array.from(new Uint8Array(result), (b) =>
b.toString(16).padStart(2, "0"),
).join("");
}
function validRevision(n) {
return Number.isInteger(n) && n >= 0 && n <= 1000000000;
}
function validateAnnotations(rows, inventory) {
if (!Array.isArray(rows) || rows.length !== inventory.items.length)
throw Error("Checkpoint must keep one annotation per inventory id.");
const known = new Set(inventory.items.map((r) => r.id)),
found = new Map();
for (const row of rows) {
if (
!exactKeys(row, ["id", "status", "label"]) ||
!known.has(row.id) ||
found.has(row.id) ||
!STATUSES.includes(row.status) ||
(row.status === "labelled"
? !inventory.taxonomy.includes(row.label)
: row.label !== null)
) {
throw Error(
"Checkpoint has a missing, duplicate, foreign or invalid annotation.",
);
}
found.set(row.id, { id: row.id, status: row.status, label: row.label });
}
return inventory.items.map((r) => found.get(r.id));
}
class Session {
#annotations;
#history = [];
#revision;
#savedRevision;
#filter;
#activeId;
constructor(
inventory,
digest,
annotations,
revision = 0,
savedRevision = null,
) {
Object.defineProperty(this, "inventory", {
value: freeze(clone(inventory)),
});
Object.defineProperty(this, "inventoryHash", { value: digest });
this.#annotations = new Map(annotations.map((a) => [a.id, { ...a }]));
this.#revision = revision;
this.#savedRevision = savedRevision;
this.#filter = "all";
this.#activeId =
inventory.items.find(
(r) => this.#annotations.get(r.id).status === "unlabelled",
)?.id ?? inventory.items[0].id;
}
get revision() {
return this.#revision;
}
get savedRevision() {
return this.#savedRevision;
}
get filter() {
return this.#filter;
}
get activeId() {
return this.#activeId;
}
annotation(id) {
const row = this.#annotations.get(id);
if (!row) throw Error("Unknown inventory id.");
return { ...row };
}
visibleIds() {
return this.inventory.items
.filter(
(r) =>
this.#filter === "all" ||
this.#annotations.get(r.id).status === this.#filter,
)
.map((r) => r.id);
}
setFilter(filter) {
if (!FILTERS.includes(filter)) throw Error("Unknown queue filter.");
this.#filter = filter;
if (!this.visibleIds().includes(this.#activeId))
this.#activeId = this.visibleIds()[0] ?? null;
}
select(id) {
if (!this.visibleIds().includes(id))
throw Error("Record is not visible under this filter.");
this.#activeId = id;
}
navigate(direction) {
if (direction !== 1 && direction !== -1)
throw Error("Use previous or next.");
const ids = this.visibleIds(),
index = ids.indexOf(this.#activeId);
if (!ids.length) {
this.#activeId = null;
return;
}
const next =
index < 0
? direction === 1
? 0
: ids.length - 1
: Math.max(0, Math.min(ids.length - 1, index + direction));
this.#activeId = ids[next];
}
#bump() {
if (this.#revision >= 1000000000)
throw Error(
"Revision limit reached. Export the current checkpoint; further decisions are blocked.",
);
this.#revision++;
}
decide(status, label = null, id = this.#activeId) {
if (!this.#annotations.has(id))
throw Error("Choose a current record first.");
if (
!STATUSES.includes(status) ||
(status === "labelled"
? !this.inventory.taxonomy.includes(label)
: label !== null)
)
throw Error("Invalid annotation decision.");
const prior = this.#annotations.get(id);
if (prior.status === status && prior.label === label) return false;
this.#bump();
this.#history.push({ ...prior });
if (this.#history.length > 20) this.#history.shift();
this.#annotations.set(id, { id, status, label });
this.#activeId = id;
if (status !== "unlabelled") {
const start = this.inventory.items.findIndex((r) => r.id === id);
let next = null;
for (let d = 1; d <= this.inventory.items.length; d++) {
const candidate =
this.inventory.items[(start + d) % this.inventory.items.length].id;
if (this.#annotations.get(candidate).status === "unlabelled") {
next = candidate;
break;
}
}
if (next !== null) {
if (!this.visibleIds().includes(next)) this.#filter = "all";
this.#activeId = next;
} else if (!this.visibleIds().includes(id)) this.#activeId = null;
} else if (!this.visibleIds().includes(id)) this.#activeId = null;
return true;
}
undo() {
if (!this.#history.length) return false;
this.#bump();
const prior = this.#history.pop();
this.#annotations.set(prior.id, prior);
this.#filter = "all";
this.#activeId = prior.id;
return true;
}
get undoCount() {
return this.#history.length;
}
get dirty() {
return this.#savedRevision !== this.#revision;
}
markDownloaded(revision) {
if (revision !== this.#revision) return false;
this.#savedRevision = revision;
return true;
}
summary() {
const counts = { unlabelled: 0, labelled: 0, abstained: 0 };
const labels = new Map(this.inventory.taxonomy.map((l) => [l, 0]));
for (const row of this.#annotations.values()) {
counts[row.status]++;
if (row.status === "labelled")
labels.set(row.label, labels.get(row.label) + 1);
}
const total = this.inventory.items.length;
return {
total,
...counts,
reviewed: counts.labelled + counts.abstained,
reviewed_fraction: (counts.labelled + counts.abstained) / total,
unknown_group_records: this.inventory.items.filter(
(r) => r.group === null,
).length,
labels: [...labels].map(([label, count]) => ({ label, count })),
};
}
payload() {
if (!validRevision(this.#revision)) throw Error("Invalid revision.");
return {
schema_version: 1,
tool_version: VERSION,
inventory: clone(this.inventory),
inventory_sha256: this.inventoryHash,
annotations: this.inventory.items.map((r) => this.annotation(r.id)),
revision: this.#revision,
};
}
annotationJSONL() {
return (
this.inventory.items
.map((r) =>
JSON.stringify({
...r,
status: this.annotation(r.id).status,
label: this.annotation(r.id).label,
}),
)
.join("\n") + "\n"
);
}
}
export async function createSession(inventory) {
const accepted = normalizeInventory(inventory);
const hash = await sha256(JSON.stringify(accepted));
return new Session(
accepted,
hash,
accepted.items.map((r) => ({
id: r.id,
status: "unlabelled",
label: null,
})),
);
}
export async function exportCheckpoint(session) {
const payload = session.payload(); // Capture the revision before the first await.
const contentHash = await sha256(JSON.stringify(payload));
return freeze({ ...payload, content_sha256: contentHash });
}
export async function readCheckpoint(bytes) {
if (!(bytes instanceof Uint8Array) || bytes.byteLength > 4 * 1048576)
throw Error("Checkpoint must be UTF-8 and at most 4 MiB.");
let raw;
try {
raw = JSON.parse(
new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes),
);
} catch {
throw Error("Checkpoint is not valid UTF-8 JSON.");
}
if (
!exactKeys(raw, [
"schema_version",
"tool_version",
"inventory",
"inventory_sha256",
"annotations",
"revision",
"content_sha256",
]) ||
raw.schema_version !== 1 ||
raw.tool_version !== VERSION ||
!validRevision(raw.revision) ||
typeof raw.inventory_sha256 !== "string" ||
!/^[a-f0-9]{64}$/.test(raw.inventory_sha256) ||
typeof raw.content_sha256 !== "string" ||
!/^[a-f0-9]{64}$/.test(raw.content_sha256)
)
throw Error("Unsupported checkpoint schema, version or revision.");
const inventory = normalizeInventory(raw.inventory);
const annotations = validateAnnotations(raw.annotations, inventory);
if ((await sha256(JSON.stringify(inventory))) !== raw.inventory_sha256)
throw Error("Checkpoint inventory checksum does not match.");
const payload = {
schema_version: 1,
tool_version: VERSION,
inventory,
inventory_sha256: raw.inventory_sha256,
annotations,
revision: raw.revision,
};
if ((await sha256(JSON.stringify(payload))) !== raw.content_sha256)
throw Error("Checkpoint content checksum does not match.");
const accepted = freeze({ ...payload, content_sha256: raw.content_sha256 });
verifiedCheckpoints.add(accepted);
return accepted;
}
export function sessionFromCheckpoint(checkpoint) {
if (!verifiedCheckpoints.has(checkpoint))
throw Error("Verify the checkpoint bytes before restoring.");
return new Session(
checkpoint.inventory,
checkpoint.inventory_sha256,
checkpoint.annotations,
checkpoint.revision,
checkpoint.revision,
);
}
|