Skip to content

The OSINT investigator's workbench. One case, one folder, every tool. Local-first: your media and your investigations never leave your machine.

JavaScript

Hand an analyzer or a piece of ground to another analyst as a file (#108)

OsintMeThat8a93f7f0efc3
diff --git a/docs/SPEC.md b/docs/SPEC.md
index d7a5406..fb37080 100644
--- a/docs/SPEC.md
+++ b/docs/SPEC.md
@@ -182,6 +182,7 @@ proof for publication.
| ✅ **Geolocation worklists** | Opens recent sheets, tracks imported files awaiting a proof and indexes every proof point with its date, source and coordinates. |
| ✅ **Files & navigation** | Files work into the active folder, offers contextual actions and filters, and retraces tools and documents with guarded Back and Forward. |
| ✅ **Command palette** | Ctrl+K or ⌘K searches tools, cases and current-case documents, starts with recently added items and protects unsaved work. |
+| ✅ **Shared analyzers & areas** | Exports an analyzer of your own as a file, checks included or left behind, and an area or a group as the ground it is, names, colours and folder kept. Imports either without overwriting what is here, so the work travels without the settings backup and its keys. |
| ✅ **Copernicus layers & figures** | Writes composite, index and script layers with a preview on the map, offers them in every map tab, reads an index or single-band layer as a Detect rule, draws a rule back as a layer and moves its line live on the last test's readings, and lays several renderings of one pass out as a captioned figure. |
---
@@ -238,9 +239,7 @@ GPS-tagged clips promotable to places.
Toward v3: GIF maker; curated tool links; full-text case search; clipboard
image/URL capture with provenance; EXIF/GPS import suggestions for place and
time; sun and moon times read against the terrain horizon the 3D map's DEM
-supplies, since a ridge ends the day well before the flat horizon does; export
-and import an analyzer as a file, checks included, so one can be shared without
-handing over the settings backup and its keys.
+supplies, since a ridge ends the day well before the flat horizon does.
### v4: investigation layer
diff --git a/docs/UI.md b/docs/UI.md
index 8f2b6c5..d83db4c 100644
--- a/docs/UI.md
+++ b/docs/UI.md
@@ -2526,7 +2526,21 @@ that membership. The dragged row fades, a rule marks its insertion point, and
the destination group lights up. Its menu can add the same area to another
group, move it or change the order without dragging. Folding a group does not
hide map outlines.
-Removing a group leaves its areas in the case. Older saved area sets become
+Removing a group leaves its areas in the case.
+
+**Share area** and **Share group** in those menus download the ground as a file
+to hand to another analyst: the shapes with their names, their colours and the
+folder they sit in, which no generic map format keeps. **Import**, beside
+**Draw an area**, takes one into the open case. It reads Azimut's own area files
+and nothing else, so nothing arrives that has to be triaged; a KML or a GeoJSON
+from elsewhere is still added as a followed layer in Layers, which is a
+different question. Nothing is written over: every shape is filed under a new
+id, a name already in the case is numbered, group included, and the ids inside
+the file only join a group to its areas. A group whose area was deleted sends
+what it still has. A file a newer Azimut wrote still imports, with a line naming
+the fields that went unread. What does not travel is the dates: the passes an
+area is read on belong to the detection, so the analyst who receives the ground
+picks their own. Older saved area sets become
groups on first read: shared outlines are reused, while temporary drawings and
outlines that have changed since the set was saved become shared areas with
their saved shapes. If a shared area's current outline differs from the saved
@@ -2734,9 +2748,19 @@ checks and all, under a free name, and opens it with its first check on the
map. A built-in opens read-only with **Copy to tune** (and **Open as rules**
where it has them, which is burn scars, vegetation loss and new water): the copy
keeps its calibrated method while its name, sizes, thresholds, candidate label
-and colour become yours. Your own can be edited or removed from the list. A
-detection being built keeps its place while the library is open, and an analyzer
-saved from there comes back picked.
+and colour become yours. Your own can be edited, shared or removed from the
+list. **Share** downloads the analyzer as a file to hand on: it carries the
+rules and none of your keys, which is what a settings backup cannot promise. One
+with checks asks first whether they go too, since they let the other analyst
+rerun the calibration and they carry the places and dates it was run on. Their
+last result stays behind, so the analyzer arrives having proved nothing yet.
+**Import**, beside **New analyzer**, takes one in and never writes over what is
+here: an id already in use is re-minted and a name already taken is numbered. A
+file a newer Azimut wrote still imports, with a line naming the fields that went
+unread. A check reading a Copernicus layer this machine has no script for is
+named the same way, and a radar check is retuned to the Sentinel-1 layer
+Settings found here. A detection being built keeps its place while the library
+is open, and an analyzer saved from there comes back picked.
The builder keeps the name, the locked chip and the sentence the analyzer reads
as at the top, and three tabs: **Rules**, **Checks** and **Settings** (sizes,
diff --git a/frontend/e2e/detect-groups.spec.js b/frontend/e2e/detect-groups.spec.js
index 7b4287b..85ed5a5 100644
--- a/frontend/e2e/detect-groups.spec.js
+++ b/frontend/e2e/detect-groups.spec.js
@@ -112,3 +112,42 @@ test('dragging an area between groups and into Ungrouped moves its membership',
await expect(ungrouped.getByRole('group', { name: 'Harbor' })).toHaveCount(1);
expect(groups.map((group) => group.area_ids)).toEqual([[], []]);
});
+
+test('a long group name gives way at the dock’s narrowest, so its count, eye and menu stay reachable', async ({ page }) => {
+ await installAppFixture(page);
+ await page.route('**/api/compare/analyzers', (route) => route.fulfill({ json: catalogue }));
+ const ring = [[2.29, 48.855], [2.3, 48.855], [2.3, 48.862], [2.29, 48.862], [2.29, 48.855]];
+ const areas = Array.from({ length: 5 }, (_, n) => ({
+ id: `${n}`.repeat(12), name: `Pumping station ${n + 1}`, colour: '#38bdf8',
+ geometry: { type: 'Polygon', coordinates: [ring] },
+ }));
+ const groups = [{ id: '111111111111', title: 'Pumping stations SAUDI ARABIA (E-W)',
+ area_ids: areas.map((area) => area.id), position: 0 }];
+ await page.route('**/api/cases/*/analysis/**', (route) => {
+ const path = new URL(route.request().url()).pathname;
+ route.fulfill({ json: path.endsWith('/analysis/areas') ? areas
+ : path.endsWith('/analysis/zones') ? groups : [] });
+ });
+ await page.goto('/#detect');
+ await awaitMapReady(page);
+ const dock = page.getByRole('complementary', { name: 'Detect' });
+ await dock.getByRole('button', { name: 'Areas', exact: true }).click();
+ const group = dock.getByRole('region', { name: 'Pumping stations SAUDI ARABIA (E-W)' });
+ await expect(group).toBeVisible();
+
+ await dock.getByRole('button', { name: 'Resize Detect panel' }).focus();
+ await page.keyboard.press('Home'); // the narrowest the dock goes
+ await expect(dock).toHaveCSS('width', '300px');
+
+ // Nothing in the row may be pushed past the panel's own edge.
+ const edge = (await dock.boundingBox()).x + (await dock.boundingBox()).width;
+ for (const part of ['.group-count', '.group-head > .cmp-icon', '.group-head > .item-menu']) {
+ const box = await group.locator(part).first().boundingBox();
+ expect(box.x + box.width).toBeLessThanOrEqual(edge + 1);
+ }
+ // The name is what gives way, and the swatches keep their place beside it.
+ const title = group.locator('.group-title');
+ await expect(title).toHaveCSS('text-overflow', 'ellipsis');
+ expect(await title.evaluate((node) => node.scrollWidth > node.clientWidth)).toBe(true);
+ expect((await group.locator('.group-tints').boundingBox()).width).toBeGreaterThan(0);
+});
diff --git a/frontend/src/components/ConfirmDialog.svelte b/frontend/src/components/ConfirmDialog.svelte
index 38976fa..1b99cc9 100644
--- a/frontend/src/components/ConfirmDialog.svelte
+++ b/frontend/src/components/ConfirmDialog.svelte
@@ -25,6 +25,9 @@
tone = 'default', // 'danger' | 'default'
icon = tone === 'danger' ? 'trash' : 'folderMinus',
busy = false,
+ // An optional choice the dialog is asking along with the confirmation, such
+ // as what an export should carry. Sits under the message, above the buttons.
+ children = null,
onconfirm,
oncancel,
} = $props();
@@ -122,6 +125,9 @@
</div>
</div>
{/if}
+ {#if children}
+ <div class="extra">{@render children()}</div>
+ {/if}
<div class="actions">
<button class="btn" bind:this={cancelBtn} onclick={oncancel} disabled={busy}>{cancelLabel}</button>
<button
@@ -238,6 +244,13 @@
text-overflow: ellipsis;
white-space: nowrap;
}
+ .extra {
+ margin-top: 12px;
+ padding: 9px 10px;
+ background: var(--bg-2);
+ border-radius: var(--r-sm);
+ font-size: var(--fs-xs);
+ }
.actions {
display: flex;
justify-content: flex-end;
diff --git a/frontend/src/lib/analyzerFile.js b/frontend/src/lib/analyzerFile.js
new file mode 100644
index 0000000..fecfc6f
--- /dev/null
+++ b/frontend/src/lib/analyzerFile.js
@@ -0,0 +1,54 @@
+/**
+ * An analyzer as a file: what leaves this machine, and what arrives from another.
+ *
+ * Sharing an analyzer is the one thing a settings backup could already do and
+ * shouldn't, since that backup carries the user's API keys. This file carries
+ * the rules, and the checks when they are let through.
+ */
+import { api } from './api.js';
+
+export function analyzerFileUrl(id, { checks = true } = {}) {
+ return `/api/compare/analyzers/${encodeURIComponent(id)}/share${checks ? '' : '?checks=false'}`;
+}
+
+/** Download it the way a case bundle downloads: a link the browser follows. */
+export function downloadAnalyzer(id, options) {
+ const link = document.createElement('a');
+ link.href = analyzerFileUrl(id, options);
+ link.download = '';
+ document.body.append(link);
+ link.click();
+ link.remove();
+}
+
+export async function importAnalyzerFile(file) {
+ let parsed;
+ try {
+ parsed = JSON.parse(await file.text());
+ } catch {
+ throw new Error('This file is not JSON. Use the Share button on an analyzer to make one.');
+ }
+ return api.post('/api/compare/analyzers/import', parsed);
+}
+
+/**
+ * What the analyst has to know about an analyzer that just arrived, in a line
+ * each. Nothing here stops it being used; it says where it may not behave like
+ * it did on the machine that sent it.
+ */
+export function importNotes(result) {
+ const notes = [];
+ if (result?.renamed_from) {
+ notes.push(`You already had an analyzer called “${result.renamed_from}”, so this one is “${result.analyzer.name}”.`);
+ }
+ const missing = result?.missing_layers ?? [];
+ if (missing.length) {
+ notes.push(`Its checks read ${missing.join(' and ')}, which this machine has no Copernicus layer for.`);
+ }
+ const ignored = result?.ignored_fields ?? [];
+ if (ignored.length) {
+ const by = result.written_by ? `Azimut ${result.written_by}` : 'a newer Azimut';
+ notes.push(`Written by ${by}, so ${ignored.join(', ')} went unread here and the analyzer may find less.`);
+ }
+ return notes;
+}
diff --git a/frontend/src/lib/analyzerFile.test.js b/frontend/src/lib/analyzerFile.test.js
new file mode 100644
index 0000000..5cee53c
--- /dev/null
+++ b/frontend/src/lib/analyzerFile.test.js
@@ -0,0 +1,50 @@
+import { beforeEach, expect, it, vi } from 'vitest';
+import { api } from './api.js';
+import { analyzerFileUrl, importAnalyzerFile, importNotes } from './analyzerFile.js';
+
+vi.mock('./api.js', () => ({ api: { post: vi.fn() } }));
+
+beforeEach(() => { vi.clearAllMocks(); });
+
+const asFile = (text) => ({ text: async () => text });
+
+it('asks for the checks unless they were left behind, and escapes the name in the path', () => {
+ expect(analyzerFileUrl('custom-abc')).toBe('/api/compare/analyzers/custom-abc/share');
+ expect(analyzerFileUrl('custom-abc', { checks: false })).toBe('/api/compare/analyzers/custom-abc/share?checks=false');
+ expect(analyzerFileUrl('a/b')).toBe('/api/compare/analyzers/a%2Fb/share');
+});
+
+it('sends the file it was handed, and says plainly when it is not JSON at all', async () => {
+ const file = asFile('{"azimut":"azimut-analyzer","version":1,"recipe":{"name":"Burn"}}');
+ await importAnalyzerFile(file);
+ expect(api.post).toHaveBeenCalledWith('/api/compare/analyzers/import', {
+ azimut: 'azimut-analyzer', version: 1, recipe: { name: 'Burn' },
+ });
+
+ await expect(importAnalyzerFile(asFile('not json at all'))).rejects.toThrow(/not JSON/);
+ expect(api.post).toHaveBeenCalledTimes(1);
+});
+
+it('says nothing about an analyzer that arrived able to do everything it did', () => {
+ expect(importNotes({ analyzer: { name: 'Burn' }, renamed_from: '', missing_layers: [], ignored_fields: [] })).toEqual([]);
+});
+
+it('names the rename, the layer this machine lacks and what a newer build wrote', () => {
+ const notes = importNotes({
+ analyzer: { name: 'Fresh burn 2' },
+ renamed_from: 'Fresh burn',
+ missing_layers: ['BURN_NBR', 'NBR2'],
+ ignored_fields: ['certainty'],
+ written_by: '9.9.9',
+ });
+ expect(notes).toHaveLength(3);
+ expect(notes[0]).toBe('You already had an analyzer called “Fresh burn”, so this one is “Fresh burn 2”.');
+ expect(notes[1]).toContain('BURN_NBR and NBR2');
+ expect(notes[2]).toContain('Azimut 9.9.9');
+ expect(notes[2]).toContain('certainty');
+});
+
+it('falls back to a newer Azimut when the file never said which build wrote it', () => {
+ const notes = importNotes({ analyzer: { name: 'X' }, ignored_fields: ['certainty'], written_by: '' });
+ expect(notes[0]).toContain('a newer Azimut');
+});
diff --git a/frontend/src/lib/areaFile.js b/frontend/src/lib/areaFile.js
new file mode 100644
index 0000000..01a18f6
--- /dev/null
+++ b/frontend/src/lib/areaFile.js
@@ -0,0 +1,61 @@
+/**
+ * An area, or a group of them, as a file between two Azimut analysts.
+ *
+ * Not a map file: GeoJSON and KML already come in as followed layers and
+ * answer another question. This carries the names, the colours and the folder,
+ * which no generic format keeps.
+ */
+import { api } from './api.js';
+
+export function areaFileUrl(caseId, kind, ident) {
+ return `/api/cases/${encodeURIComponent(caseId)}/analysis/${kind}/${encodeURIComponent(ident)}/share`;
+}
+
+/** Download it the way a case bundle downloads: a link the browser follows. */
+export function downloadAreas(caseId, kind, ident) {
+ const link = document.createElement('a');
+ link.href = areaFileUrl(caseId, kind, ident);
+ link.download = '';
+ document.body.append(link);
+ link.click();
+ link.remove();
+}
+
+export async function importAreasFile(caseId, file) {
+ let parsed;
+ try {
+ parsed = JSON.parse(await file.text());
+ } catch {
+ throw new Error('This file is not JSON. Use the Share action on an area or a group to make one.');
+ }
+ return api.post(`/api/cases/${encodeURIComponent(caseId)}/analysis/areas/import`, parsed);
+}
+
+/** What arrived, in one line. */
+export function importedGround(result) {
+ const parts = [];
+ const areas = result?.areas?.length ?? 0;
+ const groups = result?.groups?.length ?? 0;
+ parts.push(`${areas} area${areas === 1 ? '' : 's'}`);
+ if (groups) parts.push(`${groups} group${groups === 1 ? '' : 's'}`);
+ return parts.join(' and ');
+}
+
+/**
+ * What the analyst has to know about ground that just arrived, a line each.
+ * Nothing here stops it being used; it says where it differs from the case it
+ * was sent from.
+ */
+export function importAreaNotes(result) {
+ const notes = [];
+ const renamed = result?.renamed ?? [];
+ if (renamed.length) {
+ notes.push(`This case already had ${renamed.join(', ')}, so what arrived is numbered.`);
+ }
+ const ignored = result?.ignored_fields ?? [];
+ if (ignored.length) {
+ const by = result.written_by ? `Azimut ${result.written_by}` : 'a newer Azimut';
+ notes.push(`Written by ${by}, so ${ignored.join(', ')} went unread here.`);
+ }
+ return notes;
+}
diff --git a/frontend/src/lib/areaFile.test.js b/frontend/src/lib/areaFile.test.js
new file mode 100644
index 0000000..3831ecb
--- /dev/null
+++ b/frontend/src/lib/areaFile.test.js
@@ -0,0 +1,44 @@
+import { beforeEach, expect, it, vi } from 'vitest';
+import { api } from './api.js';
+import { areaFileUrl, importAreaNotes, importAreasFile, importedGround } from './areaFile.js';
+
+vi.mock('./api.js', () => ({ api: { post: vi.fn() } }));
+
+beforeEach(() => { vi.clearAllMocks(); });
+
+const asFile = (text) => ({ text: async () => text });
+
+it('points at the area or the group it was asked for, escaping both names', () => {
+ expect(areaFileUrl('case-1', 'areas', 'abc')).toBe('/api/cases/case-1/analysis/areas/abc/share');
+ expect(areaFileUrl('case-1', 'zones', 'g1')).toBe('/api/cases/case-1/analysis/zones/g1/share');
+ expect(areaFileUrl('a/b', 'areas', 'c d')).toBe('/api/cases/a%2Fb/analysis/areas/c%20d/share');
+});
+
+it('sends the file into the case it was dropped on, and says when it is not JSON', async () => {
+ await importAreasFile('case-1', asFile('{"azimut":"azimut-areas","version":1,"areas":[]}'));
+ expect(api.post).toHaveBeenCalledWith('/api/cases/case-1/analysis/areas/import', {
+ azimut: 'azimut-areas', version: 1, areas: [],
+ });
+
+ await expect(importAreasFile('case-1', asFile('nope'))).rejects.toThrow(/not JSON/);
+ expect(api.post).toHaveBeenCalledTimes(1);
+});
+
+it('counts what arrived, and leaves the folder out when none came', () => {
+ expect(importedGround({ areas: [1, 2, 3], groups: [1] })).toBe('3 areas and 1 group');
+ expect(importedGround({ areas: [1], groups: [] })).toBe('1 area');
+});
+
+it('says nothing about ground that arrived exactly as it was sent', () => {
+ expect(importAreaNotes({ areas: [1], groups: [], renamed: [], ignored_fields: [] })).toEqual([]);
+});
+
+it('names the clashes it numbered and what a newer build wrote', () => {
+ const notes = importAreaNotes({
+ renamed: ['Pump 1', 'Pumping stations'], ignored_fields: ['elevation'], written_by: '9.9.9',
+ });
+ expect(notes).toHaveLength(2);
+ expect(notes[0]).toBe('This case already had Pump 1, Pumping stations, so what arrived is numbered.');
+ expect(notes[1]).toContain('Azimut 9.9.9');
+ expect(notes[1]).toContain('elevation');
+});
diff --git a/frontend/src/lib/map/bench.svelte.js b/frontend/src/lib/map/bench.svelte.js
index bb46fc5..1214d16 100644
--- a/frontend/src/lib/map/bench.svelte.js
+++ b/frontend/src/lib/map/bench.svelte.js
@@ -138,7 +138,7 @@ export class Bench {
// a line moved on a slider costs no request and asks no question.
this.#dispose = $effect.root(() => {
$effect(() => {
- const offered = this.offered;
+ const offered = this.#choosable;
const layer = this.layer;
if (this.radar || !offered.some((entry) => entry.enabled !== false)) return;
const next = availableDisplayLayer(layer, offered);
@@ -179,6 +179,21 @@ export class Bench {
const layers = this.#layers();
return layers.length ? layers : DISPLAY_LAYERS;
}
+ /**
+ * The layers a display may be *moved to*, which is not the list on offer.
+ *
+ * A configured layer the instance has not confirmed yet is unproven, not
+ * missing, while a layer written here needs no confirmation at all. Pick over
+ * the unproven and the only candidates standing are the analyst's own, so the
+ * first of those takes the display and keeps it: confirmation arriving later
+ * makes TRUE_COLOR available again, it never asks for it back. An unproven
+ * display costs nothing — the map holds the basemap and `layersNote` says so.
+ */
+ get #choosable() {
+ const state = this.#layerState();
+ if (!state || state.layersSource === 'instance') return this.offered;
+ return displayLayers(state.layers, true, this.#radarLayer());
+ }
get layersBusy() { return this.#layerState()?.layersBusy ?? false; }
get layersNote() {
const state = this.#layerState();
@@ -447,16 +462,16 @@ export class Bench {
void clearPreview(this.#api).catch(() => {});
}
- /** The layer that shows best what the ranking rule reads, among those offered. */
+ /** The layer that shows best what the ranking rule reads, among those it may land on. */
#suggested() {
- return suggestedLayer(this.#recipe.rules[Math.max(0, signalOf(this.#recipe))], this.offered);
+ return suggestedLayer(this.#recipe.rules[Math.max(0, signalOf(this.#recipe))], this.#choosable);
}
#adoptLayer(check) {
// Another check, another ground: a rule drawn over the last one is let go of.
this.ruleLayer = null;
const own = check.b?.layer;
- this.layer = availableDisplayLayer(own || this.#suggested(), this.offered) || own || this.#suggested();
+ this.layer = availableDisplayLayer(own || this.#suggested(), this.#choosable) || own || this.#suggested();
this.displayNotice = own && own !== this.layer ? `${own} is unavailable; showing ${this.layer}.` : '';
}
diff --git a/frontend/src/lib/map/bench.svelte.test.js b/frontend/src/lib/map/bench.svelte.test.js
index a8e3180..e6e878d 100644
--- a/frontend/src/lib/map/bench.svelte.test.js
+++ b/frontend/src/lib/map/bench.svelte.test.js
@@ -242,6 +242,36 @@ describe('the imagery under the pins', () => {
expect(bench.imagery.b.layer).toBe('TRUE_COLOR');
});
+ it('holds the display through an unproven configuration rather than falling to a layer written here', () => {
+ // A layer written here needs no confirmation, a configured one does. Until
+ // the instance answers, picking over the unconfirmed leaves only the
+ // analyst's own standing — and the display never came back from them.
+ const state = $state({ layers: [{ id: 'TRUE_COLOR' }, { id: 'SWIR' }, { id: 'B12', custom: true }],
+ layersSource: 'catalogue', loadLayers: vi.fn(async () => true) });
+ const kept = made('Plot');
+ const { bench } = open({ checks: [kept], layerState: state });
+ flushSync();
+ expect(bench.layer).toBe('TRUE_COLOR');
+ expect(bench.suggestion).toBe('TRUE_COLOR');
+ bench.select(kept.id); flushSync();
+ expect(bench.layer).toBe('TRUE_COLOR');
+ expect(bench.layersNote).not.toContain('unavailable');
+ // Unproven costs the basemap, which the note explains, and nothing else.
+ expect(bench.imagery.mode).toBe('basemap');
+ state.layersSource = 'instance'; flushSync();
+ expect(bench.layer).toBe('TRUE_COLOR');
+ expect(bench.imagery.b.layer).toBe('TRUE_COLOR');
+ });
+
+ it('still repairs a display no configuration holds, to TRUE_COLOR over a layer written here', () => {
+ const state = $state({ layers: [{ id: 'TRUE_COLOR' }, { id: 'B12', custom: true }], layersSource: 'catalogue',
+ loadLayers: vi.fn(async () => true) });
+ const kept = made('Plot'); kept.b.layer = 'NDVI';
+ const { bench } = open({ checks: [kept], layerState: state });
+ bench.select(kept.id); flushSync();
+ expect(bench.layer).toBe('TRUE_COLOR');
+ });
+
it('repairs an unavailable saved display using its actual alias, without changing the rules', () => {
const state = $state({ layers: [{ id: 'TRUE_COLOR' }, { id: 'VEGETATION_INDEX' }], layersSource: 'instance',
loadLayers: vi.fn(async () => true) });
diff --git a/frontend/src/tools/detect/AnalyzerLibrary.svelte b/frontend/src/tools/detect/AnalyzerLibrary.svelte
index df1b8e5..b7a61b8 100644
--- a/frontend/src/tools/detect/AnalyzerLibrary.svelte
+++ b/frontend/src/tools/detect/AnalyzerLibrary.svelte
@@ -17,6 +17,7 @@
import { api } from '../../lib/api.js';
import { toast } from '../../lib/state.svelte.js';
import { analyzerGroups, analyzerLock, clone } from '../../lib/map/analyzers.js';
+ import { downloadAnalyzer, importAnalyzerFile, importNotes } from '../../lib/analyzerFile.js';
import { describeChecks, describeReads, newRecipe } from '../../lib/map/analyzerRules.js';
import AnalyzerBuilder from './AnalyzerBuilder.svelte';
import AnalyzerLabel from './AnalyzerLabel.svelte';
@@ -56,6 +57,14 @@
// The analyzer whose deletion is being confirmed: its rules, checks and calibration
// are app-wide and have no Trash to come back from.
let deleting = $state(null);
+ // The analyzer being handed on, and whether its checks go with it. Checks are
+ // what lets the other analyst rerun the calibration, and they carry the
+ // coordinates it was calibrated on, so the choice is made in the open.
+ let sharing = $state(null);
+ let withChecks = $state(true);
+ let fileInput = $state(null);
+ /** What an analyzer that just arrived may not do here. Stays until the next move. */
+ let notice = $state([]);
let error = $state('');
// The map holds the builder's bench only while a builder is open, and this is what lets it go: on
@@ -82,7 +91,31 @@
finally { busy = false; }
}
+ /**
+ * Hand this analyzer on as a file. Only checks are a decision, so an analyzer
+ * without any downloads on the press and the rest ask first.
+ */
+ function share(entry) {
+ if (!entry.checks?.length) { downloadAnalyzer(entry.id); return; }
+ withChecks = true;
+ sharing = entry;
+ }
+
+ async function importFile(event) {
+ const file = event.currentTarget.files?.[0];
+ event.currentTarget.value = ''; // so the same file picked twice fires again
+ if (!file) return;
+ notice = [];
+ await act(async () => {
+ const result = await importAnalyzerFile(file);
+ await onchanged();
+ notice = importNotes(result);
+ toast(`${result.analyzer.name} is in your analyzers`, 'ok');
+ });
+ }
+
function view(entry, opening = null) {
+ notice = [];
recipe = entry.method === 'rules' ? { checks: [], ...clone(entry) } : clone(entry);
readonly = builtins.some((r) => r.id === entry.id);
start = opening;
@@ -91,6 +124,7 @@
}
function build(from = newRecipe(catalogue?.methods ?? [], reads)) {
+ notice = [];
recipe = { checks: [], ...clone(from), id: 'custom' };
readonly = false;
start = null;
@@ -155,10 +189,20 @@
<div class="cmp-dock-body">
{#if error}<p class="warn" role="alert">{error}</p>{/if}
<p class="hint">Start from an example, build your own from rules you prove on the map, or copy a calibrated built-in to tune it.</p>
- <button class="btn btn-primary" onclick={() => (mode = 'base')}><Icon name="plus" size={14} /> New analyzer</button>
+ <div class="row">
+ <button class="btn btn-primary grow" onclick={() => (mode = 'base')}><Icon name="plus" size={14} /> New analyzer</button>
+ <button class="btn" title="Open an analyzer file someone shared with you" disabled={busy}
+ onclick={() => fileInput?.click()}><Icon name="upload" size={13} /> Import</button>
+ </div>
+ <input type="file" accept="application/json,.json" bind:this={fileInput} onchange={importFile} hidden />
<section aria-label="My analyzers">
<strong>Mine</strong>
+ {#if notice.length}
+ <ul class="notice" aria-label="About the analyzer you imported">
+ {#each notice as line (line)}<li>{line}</li>{/each}
+ </ul>
+ {/if}
{#if !custom.length}<p class="hint">None yet.</p>{/if}
{#each custom as entry (entry.id)}
<div class="row entry">
@@ -169,6 +213,8 @@
<button class="cmp-icon" title="Edit" aria-label={`Edit ${entry.name}`} disabled={busy} onclick={() => view(entry)}>
<Icon name="edit" size={13} />
</button>
+ <button class="cmp-icon" title="Share" aria-label={`Share ${entry.name}`} disabled={busy}
+ onclick={() => share(entry)}><Icon name="download" size={13} /></button>
<button class="cmp-icon" title="Delete" aria-label={`Delete ${entry.name}`} disabled={busy}
onclick={() => (deleting = entry)}><Icon name="trash" size={13} /></button>
</div>
@@ -288,6 +334,23 @@
</div>
{/if}
+{#if sharing}
+ <ConfirmDialog
+ title={`Share ${sharing.name}`}
+ message="Downloads a file to hand on. It carries the rules and none of your keys."
+ confirmLabel="Download"
+ icon="download"
+ onconfirm={() => { const entry = sharing; sharing = null; downloadAnalyzer(entry.id, { checks: withChecks }); }}
+ oncancel={() => (sharing = null)}>
+ <label class="opt">
+ <input type="checkbox" bind:checked={withChecks} />
+ <span>Include its {sharing.checks.length} check{sharing.checks.length === 1 ? '' : 's'}
+ <small>They let the other analyst rerun your calibration, and they carry the places and dates you ran it on.</small>
+ </span>
+ </label>
+ </ConfirmDialog>
+{/if}
+
{#if deleting}
<ConfirmDialog
title={`Delete ${deleting.name}`}
@@ -324,6 +387,10 @@
.base { border: 1px solid var(--border); background: var(--bg-2); }
.base:hover { border-color: var(--accent); }
.ask { color: var(--text-2); font-size: var(--fs-xs); font-weight: 700; }
+ .notice { margin: 0 0 2px; padding-left: 15px; color: var(--text-2); font-size: var(--fs-xs); line-height: 1.45; }
+ .opt { display: flex; align-items: flex-start; gap: 8px; cursor: pointer; }
+ .opt span { display: grid; gap: 3px; color: var(--text-1); font-weight: 600; }
+ .opt small { color: var(--text-3); font-weight: 400; line-height: 1.4; }
.name small.checked { color: var(--text-2); }
.swatch { flex: 0 0 auto; width: 9px; height: 9px; margin-top: 4px; border-radius: 50%; background: var(--tint); }
.name { display: grid; gap: 2px; min-width: 0; color: var(--text-1); font-size: var(--fs-xs); font-weight: 600; }
diff --git a/frontend/src/tools/detect/AnalyzerLibrary.svelte.test.js b/frontend/src/tools/detect/AnalyzerLibrary.svelte.test.js
new file mode 100644
index 0000000..0c5a2c3
--- /dev/null
+++ b/frontend/src/tools/detect/AnalyzerLibrary.svelte.test.js
@@ -0,0 +1,123 @@
+// @vitest-environment happy-dom
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { flushSync, mount, unmount } from 'svelte';
+
+vi.mock('../../lib/analyzerFile.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ downloadAnalyzer: vi.fn(),
+ importAnalyzerFile: vi.fn(),
+}));
+
+const { downloadAnalyzer, importAnalyzerFile } = await import('../../lib/analyzerFile.js');
+const AnalyzerLibrary = (await import('./AnalyzerLibrary.svelte')).default;
+
+const METHODS = [{ id: 'rules', label: 'Rules of your own', sizes: { all: {} } }];
+const RULE = { measure: 'index', index: 'ndvi', on: 'change', op: 'le', value: -0.2 };
+const mine = (over = {}) => ({
+ id: 'custom-abc', name: 'Fresh burn', description: 'Burn scars', method: 'rules', colour: '#f6a81a',
+ style: 'both', match: 'all', sensor: 'sentinel2', dates: 'two', rules: [RULE], checks: [], ...over,
+});
+const check = (id) => ({ id, name: `Check ${id}`, a: { date: '2026-05-04' }, b: { date: '2026-05-11' }, marks: [], result: null });
+
+let live, target;
+afterEach(() => { if (live) unmount(live); live = null; target?.remove(); });
+beforeEach(() => { vi.clearAllMocks(); });
+
+function open(custom, onchanged = async () => {}) {
+ const props = $state({
+ catalogue: { builtins: [], custom, examples: [], methods: METHODS, groups: [], reliability: {}, as_rules: {} },
+ onchanged,
+ });
+ target = document.createElement('div');
+ document.body.append(target);
+ live = mount(AnalyzerLibrary, { target, props });
+ flushSync();
+ return props;
+}
+const press = (label) => { document.querySelector(`[aria-label="${label}"]`).click(); flushSync(); };
+const button = (text) => [...document.querySelectorAll('button')].find((b) => b.textContent.trim() === text);
+
+it('hands an analyzer with nothing to decide straight to the browser', () => {
+ open([mine()]);
+ press('Share Fresh burn');
+ expect(downloadAnalyzer).toHaveBeenCalledWith('custom-abc');
+ expect(document.querySelector('[role="alertdialog"]')).toBe(null);
+});
+
+it('asks about the checks before they leave, since they carry where you calibrated', () => {
+ open([mine({ checks: [check('a'), check('b')] })]);
+ press('Share Fresh burn');
+ const dialog = document.querySelector('[role="alertdialog"]');
+ expect(dialog.getAttribute('aria-label')).toBe('Share Fresh burn');
+ expect(dialog.textContent).toContain('Include its 2 checks');
+ expect(dialog.textContent).toContain('none of your keys');
+
+ button('Download').click(); flushSync();
+ expect(downloadAnalyzer).toHaveBeenCalledWith('custom-abc', { checks: true });
+ expect(document.querySelector('[role="alertdialog"]')).toBe(null);
+});
+
+it('leaves the checks behind when the box is cleared', () => {
+ open([mine({ checks: [check('a')] })]);
+ press('Share Fresh burn');
+ expect(document.querySelector('[role="alertdialog"]').textContent).toContain('Include its 1 check');
+ const box = document.querySelector('[role="alertdialog"] input[type="checkbox"]');
+ box.checked = false;
+ box.dispatchEvent(new Event('change', { bubbles: true }));
+ flushSync();
+ button('Download').click(); flushSync();
+ expect(downloadAnalyzer).toHaveBeenCalledWith('custom-abc', { checks: false });
+});
+
+it('cancelling the share downloads nothing', () => {
+ open([mine({ checks: [check('a')] })]);
+ press('Share Fresh burn');
+ button('Cancel').click(); flushSync();
+ expect(downloadAnalyzer).not.toHaveBeenCalled();
+ expect(document.querySelector('[role="alertdialog"]')).toBe(null);
+});
+
+async function pick(text) {
+ const input = target.querySelector('input[type="file"]');
+ Object.defineProperty(input, 'files', { configurable: true, value: [{ text: async () => text }] });
+ input.dispatchEvent(new Event('change', { bubbles: true }));
+ await vi.waitFor(() => expect(importAnalyzerFile).toHaveBeenCalled());
+ await new Promise((resolve) => setTimeout(resolve, 0)); // the reload and the notes it leaves
+ flushSync();
+}
+
+it('reloads the library on an import and says what the analyzer cannot do here', async () => {
+ const onchanged = vi.fn(async () => {});
+ importAnalyzerFile.mockResolvedValue({
+ analyzer: { id: 'custom-def', name: 'Fresh burn 2' },
+ renamed_from: 'Fresh burn', missing_layers: ['BURN_NBR'], ignored_fields: [], written_by: '0.3.2',
+ });
+ open([mine()], onchanged);
+ await pick('{}');
+
+ expect(onchanged).toHaveBeenCalled();
+ const notes = [...target.querySelectorAll('.notice li')].map((li) => li.textContent);
+ expect(notes).toHaveLength(2);
+ expect(notes[0]).toContain('“Fresh burn 2”');
+ expect(notes[1]).toContain('BURN_NBR');
+});
+
+it('an analyzer that arrived whole leaves no note behind', async () => {
+ importAnalyzerFile.mockResolvedValue({
+ analyzer: { id: 'custom-def', name: 'Clearing' }, renamed_from: '', missing_layers: [], ignored_fields: [],
+ });
+ open([mine()]);
+ await pick('{}');
+ expect(target.querySelector('.notice')).toBe(null);
+ expect(target.querySelector('.warn')).toBe(null);
+});
+
+it('a file that is not an analyzer says so and changes nothing', async () => {
+ const onchanged = vi.fn(async () => {});
+ importAnalyzerFile.mockRejectedValue(new Error('this file is not an Azimut analyzer'));
+ open([mine()], onchanged);
+ await pick('nope');
+ expect(target.querySelector('.warn').textContent).toContain('not an Azimut analyzer');
+ expect(onchanged).not.toHaveBeenCalled();
+ expect(target.querySelector('.notice')).toBe(null);
+});
diff --git a/frontend/src/tools/detect/AreasPanel.svelte b/frontend/src/tools/detect/AreasPanel.svelte
index 4f8bfbc..2c4d0ff 100644
--- a/frontend/src/tools/detect/AreasPanel.svelte
+++ b/frontend/src/tools/detect/AreasPanel.svelte
@@ -16,6 +16,7 @@
import { api } from '../../lib/api.js';
import { ensureCase, prefs, reloadCase } from '../../lib/state.svelte.js';
import { zoneRing } from '../../lib/map/analyzers.js';
+ import { downloadAreas, importAreasFile, importAreaNotes, importedGround } from '../../lib/areaFile.js';
import { formatArea, polygonArea } from '../../lib/measure.js';
import { plural } from '../../lib/map/detections.js';
import { closeOnOutsidePointer } from '../../lib/dismiss.js';
@@ -46,6 +47,9 @@
let landing = $state(null);
/** The area whose corners are on the map, and whether it was drawn before. */
let reshaping = $state(null);
+ let fileInput = $state(null);
+ /** What ground that just arrived may not do here. Stays until the next import. */
+ let notice = $state([]);
const users = $derived(removing ? routines.filter((routine) => routine.zones?.some((z) => z.id === removing.id)) : []);
const usedBy = (area) => routines.filter((routine) => routine.zones?.some((z) => z.id === area.id)).length;
@@ -72,6 +76,18 @@
catch (e) { error = e.message; }
finally { busy = false; }
}
+ async function importFile(event) {
+ const file = event.currentTarget.files?.[0];
+ event.currentTarget.value = ''; // so the same file picked twice fires again
+ if (!file) return;
+ notice = [];
+ await act(async () => {
+ const owner = await ensureCase();
+ const result = await importAreasFile(owner.id, file);
+ notice = [`${importedGround(result)} added.`, ...importAreaNotes(result)];
+ });
+ }
+
async function save(zone) {
const owner = await ensureCase();
const ring = zoneRing(zone);
@@ -328,7 +344,16 @@
{#if areas.length > 1}
<button class="btn btn-sm" onclick={() => onframe(areas.flatMap(ringOf))}>Show all</button>
{/if}
+ <!-- a third way ground enters the case, beside drawing it and framing it -->
+ <button class="btn btn-sm" title="Open areas another analyst shared with you" disabled={busy}
+ onclick={() => fileInput?.click()}><Icon name="upload" size={13} /> Import</button>
+ <input type="file" accept="application/json,.json" bind:this={fileInput} onchange={importFile} hidden />
</div>
+{#if notice.length}
+ <ul class="notice" aria-label="About the areas you imported">
+ {#each notice as line (line)}<li>{line}</li>{/each}
+ </ul>
+{/if}
<div class="area-actions list-tools">
<input aria-label="Search areas or groups" placeholder="Search areas or groups…" bind:value={search} />
<button class="btn btn-sm" onclick={() => (creatingGroup = !creatingGroup)}>New group</button>
@@ -421,6 +446,7 @@
{#if groupId}
<button disabled={busy} onclick={() => removeFromGroup(area.id, groups.find((group) => group.id === groupId))}>Remove from this group</button>
{/if}
+ <button onclick={() => downloadAreas(caseId, 'areas', area.id)}>Share area</button>
<button disabled={busy} onclick={() => (removing = area)}>Delete area</button>
</div>
</details>
@@ -476,6 +502,7 @@
<button disabled={busy || index === 0} onclick={() => reorderGroups(group.id, groups[index - 1].id)}>Move up</button>
<button disabled={busy || index === groups.length - 1} onclick={() => reorderGroups(group.id, groups[index + 1].id)}>Move down</button>
<button onclick={() => (editingGroup = editingGroup === group.id ? null : group.id)}>Rename group</button>
+ <button onclick={() => downloadAreas(caseId, 'zones', group.id)}>Share group</button>
<button disabled={busy} onclick={() => (removingGroup = group)}>Delete group</button>
</div>
</details>
@@ -549,10 +576,14 @@
<style>
.area-actions, .draft, .edit { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; }
.primary-tools { padding-bottom: 10px; border-bottom: 1px solid var(--border); }
+ .notice { margin: 0 0 6px; padding-left: 15px; color: var(--text-2); font-size: var(--fs-xs); line-height: 1.45; }
.list-tools { flex-wrap: nowrap; padding: 4px 0 10px; }
.list-tools input { min-width: 0; }
.draft, .edit { padding: 7px 0; }
- .area-group { display: grid; gap: 0; margin-top: 8px; }
+ /* bounded like the dock body above it, which the nested grid would otherwise
+ undo by taking its own content's width: a long group name ellipsizes rather
+ than pushing its count, eye and menu out of the panel */
+ .area-group { display: grid; grid-template-columns: minmax(0, 1fr); gap: 0; margin-top: 8px; }
/* A group is a band and its areas hang off a rail under it, so a folder
never reads as one more area in the list. */
.group-members { margin: 2px 0 4px 12px; padding-left: 6px; border-left: 2px solid var(--border-strong); }
@@ -573,9 +604,14 @@
.ungrouped-head small { color: var(--text-3); font-size: 10px; }
.fold { display: flex; flex: 1; align-items: center; gap: 6px; min-width: 0; text-align: left; font-size: var(--fs-xs); }
.group-icon { display: grid; place-items: center; flex: 0 0 auto; color: var(--accent); }
- .group-title { flex: 0 1 auto; min-width: 0; overflow: hidden; font-size: var(--fs-sm); font-weight: 650;
+ /* grows into the leftover so the count keeps the right edge whatever the
+ name's length, and shrinks to an ellipsis when there is none */
+ .group-title { flex: 1 1 auto; min-width: 2.5em; overflow: hidden; font-size: var(--fs-sm); font-weight: 650;
text-overflow: ellipsis; white-space: nowrap; }
- .group-tints { display: flex; flex: 1; gap: 2px; min-width: 0; }
+ /* The swatches keep their size and their place: the name gives way first and
+ ellipsizes, and a group of many areas shows the ones that fit rather than
+ riding over the count beside it. */
+ .group-tints { display: flex; flex: 0 0 auto; gap: 2px; max-width: 72px; overflow: hidden; }
.group-tints .swatch { width: 7px; height: 7px; }
.group-count { flex: 0 0 auto; min-width: 18px; padding: 0 5px; border-radius: 9px; background: var(--bg-1);
color: var(--text-2); font-size: 10.5px; line-height: 16px; text-align: center; font-variant-numeric: tabular-nums; }
diff --git a/frontend/src/tools/detect/AreasPanel.svelte.test.js b/frontend/src/tools/detect/AreasPanel.svelte.test.js
new file mode 100644
index 0000000..0a0ab00
--- /dev/null
+++ b/frontend/src/tools/detect/AreasPanel.svelte.test.js
@@ -0,0 +1,91 @@
+// @vitest-environment happy-dom
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { flushSync, mount, unmount } from 'svelte';
+
+vi.mock('../../lib/state.svelte.js', () => ({
+ prefs: { units: 'metric' },
+ ensureCase: vi.fn(async () => ({ id: 'case-1' })),
+ reloadCase: vi.fn(async () => {}),
+}));
+vi.mock('../../lib/areaFile.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ downloadAreas: vi.fn(),
+ importAreasFile: vi.fn(),
+}));
+
+const { downloadAreas, importAreasFile } = await import('../../lib/areaFile.js');
+const AreasPanel = (await import('./AreasPanel.svelte')).default;
+
+const RING = [[2.29, 48.855], [2.3, 48.855], [2.3, 48.862], [2.29, 48.862], [2.29, 48.855]];
+const area = (id, name) => ({ id, name, colour: '#38bdf8', geometry: { type: 'Polygon', coordinates: [RING] } });
+
+let live, target;
+afterEach(() => { if (live) unmount(live); live = null; target?.remove(); });
+beforeEach(() => { vi.clearAllMocks(); });
+
+function open(extra = {}) {
+ const props = $state({
+ caseId: 'case-1', areas: [area('aaaaaaaaaaaa', 'Pump 1')], groups: [], routines: [],
+ onrefresh: async () => {}, ...extra,
+ });
+ target = document.createElement('div');
+ document.body.append(target);
+ live = mount(AreasPanel, { target, props });
+ flushSync();
+ return props;
+}
+const press = (label) => {
+ const button = [...target.querySelectorAll('button')].find((b) => b.textContent.trim() === label);
+ button.closest('details')?.setAttribute('open', '');
+ flushSync();
+ button.click();
+ flushSync();
+};
+
+it('hands one area on as a file of its own', () => {
+ open();
+ press('Share area');
+ expect(downloadAreas).toHaveBeenCalledWith('case-1', 'areas', 'aaaaaaaaaaaa');
+});
+
+it('hands a group on as the folder it is, not as its areas one by one', () => {
+ open({ groups: [{ id: '111111111111', title: 'Pumping stations', area_ids: ['aaaaaaaaaaaa'], position: 0 }] });
+ press('Share group');
+ expect(downloadAreas).toHaveBeenCalledWith('case-1', 'zones', '111111111111');
+});
+
+async function pick(text = '{}') {
+ const input = target.querySelector('input[type="file"]');
+ Object.defineProperty(input, 'files', { configurable: true, value: [{ text: async () => text }] });
+ input.dispatchEvent(new Event('change', { bubbles: true }));
+ await vi.waitFor(() => expect(importAreasFile).toHaveBeenCalled());
+ await new Promise((resolve) => setTimeout(resolve, 0)); // the reload and the note it leaves
+ flushSync();
+}
+
+it('reloads the list on an import and says what arrived and what was renamed', async () => {
+ const onrefresh = vi.fn(async () => {});
+ importAreasFile.mockResolvedValue({
+ areas: [{ id: 'b'.repeat(12), name: 'Pump 1 2' }], groups: [{ id: 'c'.repeat(12), title: 'Stations' }],
+ renamed: ['Pump 1'], ignored_fields: [],
+ });
+ open({ onrefresh });
+ await pick();
+
+ expect(importAreasFile).toHaveBeenCalledWith('case-1', expect.anything());
+ expect(onrefresh).toHaveBeenCalled();
+ const notes = [...target.querySelectorAll('.notice li')].map((li) => li.textContent);
+ expect(notes).toHaveLength(2);
+ expect(notes[0]).toBe('1 area and 1 group added.');
+ expect(notes[1]).toContain('Pump 1');
+});
+
+it('a file that is not areas says so and files nothing', async () => {
+ const onrefresh = vi.fn(async () => {});
+ importAreasFile.mockRejectedValue(new Error('this file is not Azimut areas'));
+ open({ onrefresh });
+ await pick('nope');
+ expect(target.querySelector('.warn').textContent).toContain('not Azimut areas');
+ expect(onrefresh).not.toHaveBeenCalled();
+ expect(target.querySelector('.notice')).toBe(null);
+});
diff --git a/frontend/src/tools/mapdock.css b/frontend/src/tools/mapdock.css
index ce3d4fb..27aff1e 100644
--- a/frontend/src/tools/mapdock.css
+++ b/frontend/src/tools/mapdock.css
@@ -159,6 +159,10 @@
.cmp-dock > header strong { flex: 1; font-size: var(--fs-sm); }
.cmp-dock-body {
display: grid;
+ /* A grid item's automatic minimum is its content, so one long name used to
+ widen the whole column past the dock and carry the row's own count, eye and
+ menu out of reach. Bounding the track makes the name ellipsize instead. */
+ grid-template-columns: minmax(0, 1fr);
flex: 1;
align-content: start;
gap: 14px;
diff --git a/src/azimut/api/analyzers.py b/src/azimut/api/analyzers.py
index df1b086..6cccee8 100644
--- a/src/azimut/api/analyzers.py
+++ b/src/azimut/api/analyzers.py
@@ -3,6 +3,7 @@
from __future__ import annotations
import io
+import json
import math
import secrets
from typing import Any, Literal, get_args
@@ -12,13 +13,13 @@ import httpx
from fastapi import APIRouter, HTTPException
from fastapi.responses import Response
from PIL import Image, ImageDraw, ImageFont
-from pydantic import Field, ValidationError
+from pydantic import BaseModel, ConfigDict, Field, ValidationError
from .. import config
from ..engine import analyzers as engine
from ..engine import (
- analysis_dating, analysis_examples, analysis_export, analysis_geometry, detect_rules, links, media, sentinel,
- workqueue,
+ analysis_dating, analysis_examples, analysis_export, analysis_geometry, analyzershare, areashare, detect_rules,
+ links, media, sentinel, workqueue,
)
from ..engine.analysis_models import (
BUILTINS, GROUPS, MAX_AROUND, MAX_BANDS, MAX_CHECKS, MAX_MARKS, MAX_RULES, METHODS, RELIABILITY, Area, AreaDates,
@@ -85,6 +86,100 @@ def delete_recipe(ident: str) -> dict[str, bool]:
return {"deleted": True}
[email protected]("/compare/analyzers/{ident}/share")
+def export_recipe(ident: str, checks: bool = True) -> Response:
+ """Download one of the analyst's own analyzers, to hand to someone else.
+
+ Built-ins are not offered: every install already has them, and a tuned copy
+ of one is an analyzer of your own like any other.
+ """
+ for raw in config.load_settings().get("analyzers", []):
+ if raw.get("id") != ident:
+ continue
+ try:
+ recipe = stored(Recipe, raw)
+ except ValueError as exc:
+ raise HTTPException(422, "this analyzer can no longer be read") from exc
+ return Response(
+ content=json.dumps(analyzershare.envelope(recipe, checks=checks), indent=2, ensure_ascii=False),
+ media_type="application/json",
+ headers={"Content-Disposition": f'attachment; filename="{analyzershare.filename(recipe)}"'},
+ )
+ raise HTTPException(404, "no analyzer of yours has that name")
+
+
+class SharedAnalyzer(BaseModel):
+ """An analyzer file as another Azimut wrote it.
+
+ Loosely typed on purpose. This is the one thing the app is handed from
+ outside the machine, so it has to say what is wrong with a file in words
+ rather than through a validator's field list, and a key a later build adds
+ to the envelope must not make the file unreadable here. The recipe inside is
+ read afterwards, as history rather than as a request.
+ """
+
+ model_config = ConfigDict(extra="ignore")
+
+ azimut: str = Field(default="", max_length=64)
+ version: int = Field(default=0, ge=0, le=10_000)
+ app: str = Field(default="", max_length=64)
+ recipe: dict[str, Any] = Field(default_factory=dict)
+ #: Not ours. Declared only so the other Azimut JSON a user is likely to grab
+ #: by mistake gets named back to them instead of a flat refusal.
+ settings: Any = None
+
+
[email protected]("/compare/analyzers/import")
+def import_recipe(body: SharedAnalyzer) -> dict[str, Any]:
+ """Take an analyzer someone else exported into this library.
+
+ It never writes over what is here: an id already in use is re-minted and a
+ name already taken is numbered, so importing the same file twice leaves a
+ visible duplicate rather than silently replacing an analyzer this analyst
+ had tuned.
+ """
+ if body.azimut != analyzershare.KIND:
+ if body.settings is not None:
+ raise HTTPException(422, "this is a settings backup; restore it in Settings → Storage")
+ raise HTTPException(422, "this file is not an Azimut analyzer")
+ if body.version > analyzershare.VERSION:
+ raise HTTPException(422, "this analyzer was written in a newer format than this version reads; "
+ "update Azimut and import it again")
+ try:
+ recipe = stored(Recipe, body.recipe)
+ except ValidationError as exc:
+ raise HTTPException(422, f"this analyzer could not be read: {exc.errors()[0]['msg']}") from exc
+
+ settings = config.load_settings()
+ recipe = analyzershare.for_this_machine(recipe, settings)
+ saved = [r for r in settings.get("analyzers", []) if isinstance(r, dict)]
+ if len(saved) >= 100:
+ raise HTTPException(409, "the analyzer library is full; remove an unused recipe")
+ taken = {str(r.get("id")) for r in saved} | {r.id for r in BUILTINS} | {"custom"}
+ sent = recipe.name
+ named = analyzershare.free_name(sent, {str(r.get("name")) for r in saved})
+ recipe = recipe.model_copy(update={
+ "id": recipe.id if recipe.id not in taken else f"custom-{secrets.token_hex(6)}",
+ "name": named,
+ })
+
+ def update(current: dict[str, Any]) -> None:
+ current["analyzers"] = [*current.get("analyzers", []), recipe.model_dump()]
+
+ config.update_settings(update)
+ return {
+ "analyzer": recipe.model_dump(),
+ # What the analyst has to know before trusting it here: the layers their
+ # configuration can't read, and anything a newer build wrote that this
+ # one dropped on the way in.
+ "missing_layers": analyzershare.missing_layers(recipe, settings),
+ "ignored_fields": analyzershare.unknown_fields(body.recipe),
+ #: The name it was sent under, when the library already held that name.
+ "renamed_from": sent if named != sent else "",
+ "written_by": body.app,
+ }
+
+
class CheckInput(Model):
"""An analyzer of your own as it stands, and one of its checks to try it on."""
recipe: Recipe
@@ -225,6 +320,139 @@ def update_zones(case_id: str, ident: str, body: AreaGroup) -> dict[str, Any]:
return engine.save(case, "zones", body.model_copy(update={"position": position}).model_dump(), ident)
+def _areas_file(shared: dict[str, Any], label: str) -> Response:
+ return Response(
+ content=json.dumps(shared, indent=2, ensure_ascii=False),
+ media_type="application/json",
+ headers={"Content-Disposition": f'attachment; filename="{areashare.filename(label)}"'},
+ )
+
+
+def _ground_of(case: Any, group: dict[str, Any]) -> list[dict[str, Any]]:
+ """The areas a group names and this case still has.
+
+ A deleted area stays named in its groups so the Trash can put it back, and
+ it has no ground to send in the meantime.
+ """
+ found = []
+ for area_id in group.get("area_ids") or []:
+ try:
+ found.append(engine.read(case, "areas", area_id))
+ except (FileNotFoundError, ValueError, OSError):
+ continue
+ return found
+
+
[email protected]("/cases/{case_id}/analysis/areas/{ident}/share")
+def share_area(case_id: str, ident: str) -> Response:
+ """Download one area as a file, to hand to another analyst."""
+ area = read(get_case(case_id), "areas", ident)
+ return _areas_file(areashare.envelope([area]), area["name"])
+
+
[email protected]("/cases/{case_id}/analysis/zones/{ident}/share")
+def share_group(case_id: str, ident: str) -> Response:
+ """Download a group and the ground in it, folder and names kept."""
+ case = get_case(case_id)
+ group = read(case, "zones", ident)
+ return _areas_file(areashare.envelope(_ground_of(case, group), group), group["title"])
+
+
+class SharedAreas(BaseModel):
+ """Areas as another Azimut wrote them.
+
+ Loosely typed for the same reason `SharedAnalyzer` is: a file handed to the
+ app from outside has to be told what is wrong with it in words. `settings`
+ and `recipe` are not ours — they are declared so the other two Azimut JSON
+ files a user might drop here get named back to them.
+ """
+
+ model_config = ConfigDict(extra="ignore")
+
+ azimut: str = Field(default="", max_length=64)
+ version: int = Field(default=0, ge=0, le=10_000)
+ app: str = Field(default="", max_length=64)
+ areas: list[dict[str, Any]] = Field(default_factory=list, max_length=1000)
+ groups: list[dict[str, Any]] = Field(default_factory=list, max_length=20)
+ settings: Any = None
+ recipe: Any = None
+
+
[email protected]("/cases/{case_id}/analysis/areas/import")
+def import_areas(case_id: str, body: SharedAreas) -> dict[str, Any]:
+ """Take areas another analyst shared into this case.
+
+ Nothing here is written over: every area is filed under a new id and a name
+ already taken is numbered, group included. The ids in the file join a group
+ to its areas and nothing else, so they are remapped to the ones this case
+ mints.
+ """
+ if body.azimut == analyzershare.KIND:
+ raise HTTPException(422, "this is an analyzer; import it from the analyzer library")
+ if body.azimut != areashare.KIND:
+ if body.settings is not None:
+ raise HTTPException(422, "this is a settings backup; restore it in Settings → Storage")
+ raise HTTPException(422, "this file is not Azimut areas")
+ if body.version > areashare.VERSION:
+ raise HTTPException(422, "these areas were written in a newer format than this version reads; "
+ "update Azimut and import them again")
+ if not body.areas:
+ raise HTTPException(422, "this file carries no area")
+
+ # Read every shape before writing any, so a file this build cannot make
+ # sense of leaves the case exactly as it was.
+ parsed: list[tuple[str, Area]] = []
+ for raw in body.areas:
+ try:
+ parsed.append((str(raw.get("id") or ""), stored(Area, raw)))
+ except ValidationError as exc:
+ raise HTTPException(422, f"an area in this file could not be read: {exc.errors()[0]['msg']}") from exc
+
+ case = get_case(case_id)
+ rows = engine.listing(case, "areas")
+ names = {str(row.get("name")) for row in rows}
+ spot = max([row["position"] for row in rows if row.get("position") is not None], default=-1) + 1
+ renamed: list[str] = []
+ minted: dict[str, str] = {}
+ filed = []
+ for key, area in parsed:
+ name = areashare.free_name(area.name, names)
+ if name != area.name:
+ renamed.append(area.name)
+ names.add(name)
+ saved = engine.save(case, "areas", area.model_copy(update={"name": name, "position": spot}).model_dump())
+ spot += 1
+ filed.append(saved)
+ if key:
+ minted[key] = saved["id"]
+
+ folders = engine.listing(case, "zones")
+ titles = {str(row.get("title")) for row in folders}
+ shelf = max([row["position"] for row in folders if row.get("position") is not None], default=-1) + 1
+ made = []
+ for raw in body.groups:
+ members = [minted[key] for key in (raw.get("area_ids") or []) if key in minted]
+ if not members:
+ continue # a folder whose ground did not come with it is not a folder
+ try:
+ group = stored(AreaGroup, {**raw, "area_ids": members, "pending_review": []})
+ except ValidationError:
+ continue
+ title = areashare.free_name(group.title, titles)
+ if title != group.title:
+ renamed.append(group.title)
+ titles.add(title)
+ made.append(engine.save(case, "zones", group.model_copy(
+ update={"title": title, "position": shelf}).model_dump()))
+ shelf += 1
+
+ return {"areas": filed, "groups": made,
+ #: Names the case already held, so the arrival says what it renamed.
+ "renamed": renamed,
+ "ignored_fields": areashare.unknown_fields(body.model_dump()),
+ "written_by": body.app}
+
+
@router.post("/cases/{case_id}/analysis/followups")
def save_followup(case_id: str, body: RunInput) -> dict[str, Any]:
data = body.model_dump()
diff --git a/src/azimut/engine/analyzershare.py b/src/azimut/engine/analyzershare.py
new file mode 100644
index 0000000..af9f6f1
--- /dev/null
+++ b/src/azimut/engine/analyzershare.py
@@ -0,0 +1,144 @@
+"""An analyzer as a file, so one analyst can hand it to another.
+
+A recipe is the one piece of app-wide work that means the same thing on every
+machine: its rules read Sentinel bands, its checks name Copernicus passes by
+date, and nothing in it points at this workspace. The only way to pass one on
+today is the settings backup, which carries the user's API keys — so sharing an
+analyzer means sharing secrets. This is the file that doesn't.
+
+How a shared file is read matters. It is history another build wrote, not a
+request: unknown fields are dropped (`stored`) instead of refusing the file, and
+the legacy readers in `analysis_models` migrate an older shape on the way in.
+Only the envelope carries a version, and only a change to the envelope's own
+shape would raise it.
+"""
+
+from __future__ import annotations
+
+import re
+from typing import Any
+
+from .. import __version__
+from . import sentinel
+from .analysis_models import Check, Recipe, Rule, Source
+
+#: What a shared analyzer file says it is, so an import can tell one from a
+#: settings backup or a case bundle and say which it was handed.
+KIND = "azimut-analyzer"
+
+#: The envelope's shape, not the recipe's. The recipe inside is versionless by
+#: design — it is read as history, which is what lets two analysts on two builds
+#: trade analyzers at all.
+VERSION = 1
+
+
+def envelope(recipe: Recipe, *, checks: bool = True) -> dict[str, Any]:
+ """The analyzer as it leaves this machine.
+
+ A check's `result` stays behind: it was read on this machine's images, and
+ the analyzer should arrive having proved nothing here yet. The receiving
+ analyst presses Test and earns the ticks.
+
+ The checks themselves travel unless the caller drops them, since rerunning
+ the calibration is the point of sharing a rule set — but they carry
+ coordinates, which is why it is a choice and not a default nobody sees.
+ """
+ kept = [check.model_copy(update={"result": None}) for check in recipe.checks] if checks else []
+ return {
+ "azimut": KIND,
+ "version": VERSION,
+ # Which build wrote it, so an import can say it was handed something
+ # newer than it reads rather than quietly narrowing the analyzer.
+ "app": __version__,
+ "recipe": recipe.model_copy(update={"checks": kept}).model_dump(),
+ }
+
+
+def filename(recipe: Recipe) -> str:
+ """A download name taken from the analyzer's own, safe as a header value."""
+ slug = re.sub(r"[^a-z0-9]+", "-", recipe.name.lower()).strip("-")[:60]
+ return f"azimut-analyzer-{slug or recipe.id}.json"
+
+
+def unknown_fields(raw: Any) -> list[str]:
+ """Field names in a shared file that this version does not know.
+
+ `stored` drops them in silence, which is right for the app's own history and
+ wrong for a file from another machine: a rule field a newer build added
+ changes what the analyzer finds, and the analyst has to hear it was left
+ out rather than wonder why the results differ from the sender's.
+ """
+ if not isinstance(raw, dict):
+ return []
+ found = set(raw) - set(Recipe.model_fields)
+ for rule in raw.get("rules") or []:
+ if isinstance(rule, dict):
+ found |= set(rule) - set(Rule.model_fields)
+ for check in raw.get("checks") or []:
+ if not isinstance(check, dict):
+ continue
+ found |= set(check) - set(Check.model_fields)
+ for side in ("a", "b"):
+ if isinstance(source := check.get(side), dict):
+ found |= set(source) - set(Source.model_fields)
+ return sorted(found)
+
+
+def for_this_machine(recipe: Recipe, settings: dict[str, Any]) -> Recipe:
+ """The analyzer retuned to what this configuration serves.
+
+ A Sentinel-1 layer is named by the instance it was found on, and two
+ configurations rarely name it alike, so a radar check that kept the sender's
+ name would read nothing here. The pass it names — the date and the time of
+ day that pick one look out of two — is what the check is actually about, and
+ that travels untouched.
+ """
+ radar = str(settings.get("sentinel1_layer") or "")
+ if not radar or recipe.sensor != "sentinel1":
+ return recipe
+ checks = [
+ check.model_copy(update={
+ side: source.model_copy(update={"layer": radar})
+ for side in ("a", "b")
+ if (source := getattr(check, side)).provider == "sentinel1"
+ })
+ for check in recipe.checks
+ ]
+ return recipe.model_copy(update={"checks": checks})
+
+
+def missing_layers(recipe: Recipe, settings: dict[str, Any]) -> list[str]:
+ """Copernicus layers this analyzer's checks read and this machine lacks.
+
+ A standard layer is taken as served: `sentinel.LAYERS` is a fallback list
+ rather than the instance's full catalogue, so flagging everything outside it
+ would cry wolf over layers that work. What really fails to travel is a layer
+ the sender wrote themselves, and that is what is left once the known ones go.
+
+ Radar is left out — its layer is retuned to this machine by
+ `for_this_machine`, and a configuration with no radar layer at all is
+ already told so by the analyzer's own lock.
+ """
+ known = {layer.id for layer in sentinel.LAYERS} | set(sentinel.KNOWN_HINTS)
+ mine = {layer["id"] for layer in sentinel.custom_layers(settings)}
+ used = {
+ source.layer
+ for check in recipe.checks
+ for source in (check.a, check.b)
+ if source.layer and source.provider != "sentinel1"
+ }
+ return sorted(used - known - mine)
+
+
+def free_name(name: str, taken: set[str]) -> str:
+ """A name the library doesn't already hold: "Fresh burn", then "Fresh burn 2".
+
+ Importing the same analyzer twice gives two rows rather than overwriting the
+ first, so the copies have to be told apart on sight.
+ """
+ next_name = name
+ count = 2
+ while next_name in taken:
+ next_name = f"{name} {count}"
+ count += 1
+ return next_name
diff --git a/src/azimut/engine/areashare.py b/src/azimut/engine/areashare.py
new file mode 100644
index 0000000..808b92a
--- /dev/null
+++ b/src/azimut/engine/areashare.py
@@ -0,0 +1,73 @@
+"""An area, or a group of them, as a file one analyst hands to another.
+
+Deliberately **not** a map file. GeoJSON and KML already have a road in and out
+of the app (`maplayers` reads them, a detection snapshots to one), and that road
+answers a different question: bringing a stranger's map in. This one answers
+"take my ground, as I filed it" — the names, the colours and the folder they sit
+in — and those survive no generic format. Since both ends are Azimut, nothing
+arrives that the models would refuse: no triage screen, no "12 of 20 shapes
+became areas", no vertex cap to explain.
+
+Like `analyzershare`, the file is read as history rather than as a request, so a
+build that wrote a field this one does not know still lands.
+"""
+
+from __future__ import annotations
+
+import re
+from typing import Any
+
+from .. import __version__
+from .analysis_models import Area, AreaGroup
+from .analyzershare import free_name
+
+#: What a shared area file says it is, so an import can tell one from an
+#: analyzer, a settings backup or a case bundle and name what it was handed.
+KIND = "azimut-areas"
+
+#: The envelope's shape, not the areas'. They are read through their own models,
+#: which is what lets two analysts on two builds trade ground.
+VERSION = 1
+
+
+def envelope(areas: list[dict[str, Any]], group: dict[str, Any] | None = None) -> dict[str, Any]:
+ """The ground as it leaves this case.
+
+ `id` travels only to join a group to its areas inside the file; the case
+ that receives them mints its own. Order is the list's order, so no position
+ is carried, and a group's `pending_review` stays behind: it is this case's
+ bookkeeping about shapes that were redrawn here.
+ """
+ kept = [{"id": area["id"], "name": area["name"], "colour": area["colour"], "geometry": area["geometry"]}
+ for area in areas]
+ shared: dict[str, Any] = {"azimut": KIND, "version": VERSION, "app": __version__, "areas": kept, "groups": []}
+ if group is not None:
+ shared["groups"] = [{"title": group["title"], "area_ids": [area["id"] for area in kept]}]
+ return shared
+
+
+def filename(label: str) -> str:
+ """A download name taken from the area or group's own, safe as a header value."""
+ slug = re.sub(r"[^a-z0-9]+", "-", label.lower()).strip("-")[:60]
+ return f"azimut-areas-{slug or 'ground'}.json"
+
+
+def unknown_fields(raw: dict[str, Any]) -> list[str]:
+ """Field names in a shared file that this version does not know.
+
+ Dropping them in silence is right for the app's own history and wrong for a
+ file from another machine, where a field a newer build wrote may be part of
+ what the ground means.
+ """
+ known = set(Area.model_fields) | {"id"}
+ found: set[str] = set()
+ for area in raw.get("areas") or []:
+ if isinstance(area, dict):
+ found |= set(area) - known
+ for group in raw.get("groups") or []:
+ if isinstance(group, dict):
+ found |= set(group) - set(AreaGroup.model_fields)
+ return sorted(found)
+
+
+__all__ = ["KIND", "VERSION", "envelope", "filename", "free_name", "unknown_fields"]
diff --git a/tests/test_analyzers.py b/tests/test_analyzers.py
index 1230463..d61fc68 100644
--- a/tests/test_analyzers.py
+++ b/tests/test_analyzers.py
@@ -7,7 +7,7 @@ import numpy as np
import pytest
from PIL import Image
-from azimut import config, layout
+from azimut import __version__, config, layout
from azimut.api import analyzers as analyzers_api
from azimut.engine import analyzers, sentinel, tilecache, workqueue
from azimut.engine.analysis_models import (
@@ -1408,3 +1408,124 @@ def test_a_deleted_area_leaves_its_groups_and_comes_back_with_a_restore(client,
assert client.post(f"/api/cases/{case.id}/trash/{entry['id']}/restore").status_code == 200
[group] = client.get(f"/api/cases/{case.id}/analysis/zones").json()
assert group["area_ids"] == [shared["id"]]
+
+
+# -- areas as a file, handed to another analyst ---------------------------------------
+
+RING = [[2.29, 48.855], [2.3, 48.855], [2.3, 48.862], [2.29, 48.862], [2.29, 48.855]]
+GROUND = {"type": "Polygon", "coordinates": [RING]}
+
+
+def ground_case(client, name="Ground"):
+ return client.post("/api/cases", json={"name": name}).json()["id"]
+
+
+def put_area(client, case_id, name, colour="#38bdf8"):
+ saved = client.post(f"/api/cases/{case_id}/analysis/areas",
+ json={"name": name, "colour": colour, "geometry": GROUND})
+ assert saved.status_code == 200, saved.text
+ return saved.json()
+
+
+def put_group(client, case_id, title, areas):
+ saved = client.post(f"/api/cases/{case_id}/analysis/zones",
+ json={"title": title, "area_ids": [area["id"] for area in areas]})
+ assert saved.status_code == 200, saved.text
+ return saved.json()
+
+
+def test_a_shared_group_carries_its_ground_its_colours_and_its_folder(client):
+ case_id = ground_case(client)
+ first, second = put_area(client, case_id, "Pump 1"), put_area(client, case_id, "Pump 2", "#f6a81a")
+ group = put_group(client, case_id, "Pumping stations", [first, second])
+
+ answer = client.get(f"/api/cases/{case_id}/analysis/zones/{group['id']}/share")
+ assert answer.status_code == 200, answer.text
+ assert answer.headers["content-disposition"] == 'attachment; filename="azimut-areas-pumping-stations.json"'
+ file = answer.json()
+ assert (file["azimut"], file["version"], file["app"]) == ("azimut-areas", 1, __version__)
+ assert [area["name"] for area in file["areas"]] == ["Pump 1", "Pump 2"]
+ # what no generic map format keeps: the colours and the folder they sit in
+ assert [area["colour"] for area in file["areas"]] == ["#38bdf8", "#f6a81a"]
+ assert file["groups"] == [{"title": "Pumping stations", "area_ids": [first["id"], second["id"]]}]
+ # this case's own bookkeeping about redrawn shapes stays behind
+ assert "pending_review" not in str(file)
+
+ alone = client.get(f"/api/cases/{case_id}/analysis/areas/{first['id']}/share").json()
+ assert [area["name"] for area in alone["areas"]] == ["Pump 1"] and alone["groups"] == []
+
+
+def test_imported_ground_is_filed_afresh_and_never_over_what_is_here(client):
+ case_id = ground_case(client)
+ first, second = put_area(client, case_id, "Pump 1"), put_area(client, case_id, "Pump 2")
+ group = put_group(client, case_id, "Pumping stations", [first, second])
+ file = client.get(f"/api/cases/{case_id}/analysis/zones/{group['id']}/share").json()
+
+ answer = client.post(f"/api/cases/{case_id}/analysis/areas/import", json=file)
+ assert answer.status_code == 200, answer.text
+ body = answer.json()
+ assert [area["name"] for area in body["areas"]] == ["Pump 1 2", "Pump 2 2"]
+ assert body["groups"][0]["title"] == "Pumping stations 2"
+ assert body["renamed"] == ["Pump 1", "Pump 2", "Pumping stations"]
+ # The ids in a file only join a group to its ground; the case mints its own.
+ assert body["groups"][0]["area_ids"] == [area["id"] for area in body["areas"]]
+ assert not {area["id"] for area in body["areas"]} & {first["id"], second["id"]}
+ assert client.get(f"/api/cases/{case_id}/analysis/zones/{group['id']}").json()["area_ids"] == [
+ first["id"], second["id"]]
+
+ # The point of the file: the same ground in somebody else's case.
+ other = ground_case(client, "Second case")
+ landed = client.post(f"/api/cases/{other}/analysis/areas/import", json=file).json()
+ assert [area["name"] for area in landed["areas"]] == ["Pump 1", "Pump 2"]
+ assert landed["renamed"] == [] and landed["groups"][0]["title"] == "Pumping stations"
+ assert landed["groups"][0]["area_ids"] == [area["id"] for area in landed["areas"]]
+
+
+def test_a_file_that_is_not_areas_is_named_back_rather_than_blankly_refused(client):
+ case_id = ground_case(client)
+ url = f"/api/cases/{case_id}/analysis/areas/import"
+ backup = client.post(url, json=client.get("/api/settings/export").json())
+ assert backup.status_code == 422 and "settings backup" in backup.text
+ analyzer = client.post(url, json={"azimut": "azimut-analyzer", "version": 1, "recipe": {}})
+ assert analyzer.status_code == 422 and "analyzer library" in analyzer.text
+ assert "not Azimut areas" in client.post(url, json={"a": 1}).text
+ newer = client.post(url, json={"azimut": "azimut-areas", "version": 2, "areas": [{}]})
+ assert newer.status_code == 422 and "newer format" in newer.text
+ empty = client.post(url, json={"azimut": "azimut-areas", "version": 1, "areas": []})
+ assert empty.status_code == 422 and "no area" in empty.text
+ torn = client.post(url, json={"azimut": "azimut-areas", "version": 1,
+ "areas": [{"name": "Open", "geometry": {"type": "Polygon",
+ "coordinates": [RING[:2]]}}]})
+ assert torn.status_code == 422 and "could not be read" in torn.text
+ # A file this build cannot make sense of leaves the case exactly as it was.
+ assert client.get(f"/api/cases/{case_id}/analysis/areas").json() == []
+
+
+def test_areas_from_a_newer_build_land_and_say_what_went_unread(client):
+ case_id = ground_case(client)
+ file = {"azimut": "azimut-areas", "version": 1, "app": "9.9.9",
+ "areas": [{"id": "aaaaaaaaaaaa", "name": "Pump 1", "colour": "#38bdf8",
+ "geometry": GROUND, "elevation": 42}],
+ "groups": [{"title": "Stations", "area_ids": ["aaaaaaaaaaaa"], "legend": "by depth"}]}
+ answer = client.post(f"/api/cases/{case_id}/analysis/areas/import", json=file)
+ assert answer.status_code == 200, answer.text
+ body = answer.json()
+ assert body["ignored_fields"] == ["elevation", "legend"]
+ assert body["written_by"] == "9.9.9"
+ assert body["areas"][0]["geometry"] == GROUND
+ assert body["groups"][0]["area_ids"] == [body["areas"][0]["id"]]
+
+
+def test_a_group_shares_the_ground_it_still_has(client):
+ case_id = ground_case(client)
+ first, second = put_area(client, case_id, "Pump 1"), put_area(client, case_id, "Pump 2")
+ group = put_group(client, case_id, "Pumping stations", [first, second])
+ assert client.delete(f"/api/cases/{case_id}/analysis/areas/{second['id']}").status_code == 200
+
+ file = client.get(f"/api/cases/{case_id}/analysis/zones/{group['id']}/share").json()
+ # A deleted area stays named in its group so the Trash can put it back, and
+ # has no ground to send in the meantime.
+ assert [area["name"] for area in file["areas"]] == ["Pump 1"]
+ assert file["groups"][0]["area_ids"] == [first["id"]]
+ landed = client.post(f"/api/cases/{ground_case(client, 'Third')}/analysis/areas/import", json=file).json()
+ assert len(landed["areas"]) == 1 and landed["groups"][0]["area_ids"] == [landed["areas"][0]["id"]]
diff --git a/tests/test_detect_rules.py b/tests/test_detect_rules.py
index 9a2912f..711b2d0 100644
--- a/tests/test_detect_rules.py
+++ b/tests/test_detect_rules.py
@@ -15,7 +15,7 @@ import pytest
from PIL import Image
from pydantic import ValidationError
-from azimut import config
+from azimut import __version__, config
from azimut.engine import analysis_examples, analysis_geometry, analyzers, detect_rules, sentinel, tilecache, workqueue
from azimut.engine.analysis_models import (
BUILTINS,
@@ -960,6 +960,137 @@ def test_an_example_copied_into_the_library_keeps_its_checks_and_the_backup_carr
assert example["recipe"]["checks"][0]["name"] in str(exported)
+# -- an analyzer as a file, handed to another analyst ----------------------------------
+
+
+def shared(client, ident, **params):
+ """The file the Share button downloads."""
+ answer = client.get(f"/api/compare/analyzers/{ident}/share", params=params)
+ assert answer.status_code == 200, answer.text
+ return answer
+
+
+def put_recipe(client, built, **fields):
+ saved = client.post("/api/compare/analyzers", json={**built.model_dump(), **fields})
+ assert saved.status_code == 200, saved.text
+ return saved.json()
+
+
+def file_of(built, **fields):
+ """An analyzer file as another machine would have written it."""
+ return {"azimut": "azimut-analyzer", "version": 1, "app": __version__,
+ "recipe": {**built.model_dump(), **fields}}
+
+
+def test_a_shared_analyzer_carries_its_checks_and_no_verdict_of_this_machine(client):
+ result = {"signature": "abc", "count": 2, "covered": [True]}
+ marks = [{"point": PLOT, "expect": "found"}]
+ saved = put_recipe(client, recipe(LOSS, name="Fresh burn"), checks=[check_body(marks, result=result)])
+
+ answer = shared(client, saved["id"])
+ assert answer.headers["content-disposition"] == 'attachment; filename="azimut-analyzer-fresh-burn.json"'
+ file = answer.json()
+ assert (file["azimut"], file["version"], file["app"]) == ("azimut-analyzer", 1, __version__)
+ check = file["recipe"]["checks"][0]
+ assert check["marks"] == marks and (check["a"]["date"], check["b"]["date"]) == (DAY_A, DAY_B)
+ # The ticks were read on this machine's images, so the analyzer arrives
+ # having proved nothing yet and the other analyst presses Test.
+ assert check["result"] is None
+ # No key of the sender's goes with it, which is what a settings backup can't promise.
+ assert "sentinelhub" not in str(file)
+
+ without = shared(client, saved["id"], checks="false").json()
+ assert without["recipe"]["checks"] == []
+ assert without["recipe"]["rules"] == file["recipe"]["rules"]
+
+ assert client.get("/api/compare/analyzers/large-change/share").status_code == 404
+
+
+def test_importing_the_same_analyzer_twice_never_writes_over_the_first(client):
+ saved = put_recipe(client, recipe(LOSS, name="Fresh burn"))
+ file = shared(client, saved["id"]).json()
+
+ first = client.post("/api/compare/analyzers/import", json=file)
+ assert first.status_code == 200, first.text
+ again = client.post("/api/compare/analyzers/import", json=file).json()
+ assert again["analyzer"]["id"] not in {saved["id"], first.json()["analyzer"]["id"]}
+ assert (again["analyzer"]["name"], again["renamed_from"]) == ("Fresh burn 3", "Fresh burn")
+ assert [row["name"] for row in client.get("/api/compare/analyzers").json()["custom"]] == [
+ "Fresh burn", "Fresh burn 2", "Fresh burn 3"]
+ # The rules of the one that was already here are untouched by either import.
+ assert client.get("/api/compare/analyzers").json()["custom"][0]["rules"] == file["recipe"]["rules"]
+
+
+def test_a_file_that_is_not_an_analyzer_is_named_back_rather_than_blankly_refused(client):
+ backup = client.post("/api/compare/analyzers/import", json=client.get("/api/settings/export").json())
+ assert backup.status_code == 422 and "settings backup" in backup.text
+ assert "not an Azimut analyzer" in client.post("/api/compare/analyzers/import", json={"a": 1}).text
+ newer = client.post("/api/compare/analyzers/import",
+ json={"azimut": "azimut-analyzer", "version": 2, "recipe": {}})
+ assert newer.status_code == 422 and "newer format" in newer.text
+ unreadable = client.post("/api/compare/analyzers/import", json=file_of(recipe(LOSS), rules=[]))
+ assert unreadable.status_code == 422 and "could not be read" in unreadable.text
+
+
+def test_an_analyzer_from_a_newer_build_arrives_and_says_what_went_unread(client):
+ file = file_of(recipe(LOSS, name="From the future"), mood="brave",
+ rules=[{**LOSS, "certainty": 0.9}],
+ checks=[{**check_body([{"point": PLOT, "expect": "found"}]), "weather": "clear"}])
+ file["app"] = "9.9.9"
+ answer = client.post("/api/compare/analyzers/import", json=file)
+ assert answer.status_code == 200, answer.text
+ body = answer.json()
+ # Dropping a field in silence is right for the app's own history and wrong
+ # for a file from elsewhere: it changes what the analyzer finds.
+ assert body["ignored_fields"] == ["certainty", "mood", "weather"]
+ assert body["written_by"] == "9.9.9"
+ assert body["analyzer"]["rules"][0]["value"] == LOSS["value"]
+ assert len(body["analyzer"]["checks"]) == 1
+
+
+def test_an_imported_analyzer_names_the_copernicus_layer_this_machine_lacks(client):
+ read_on = lambda layer: {"a": {"date": DAY_A, "layer": layer}, "b": {"date": DAY_B, "layer": layer}} # noqa: E731
+ marks = [{"point": PLOT, "expect": "found"}]
+ written = file_of(recipe(LOSS, name="Burn scar"), checks=[check_body(marks, **read_on("BURN_NBR"))])
+ assert client.post("/api/compare/analyzers/import", json=written).json()["missing_layers"] == ["BURN_NBR"]
+ # A layer the standard template ships is taken as served: LAYERS is a
+ # fallback list, not the instance's catalogue, so flagging it would cry wolf.
+ standard = file_of(recipe(LOSS, name="Clearing"), checks=[check_body(marks, **read_on("NDWI"))])
+ assert client.post("/api/compare/analyzers/import", json=standard).json()["missing_layers"] == []
+
+ written_here = client.put("/api/satellite/sentinel/custom-layers", json={
+ "id": "BURN_NBR", "label": "Burn", "base": "TRUE_COLOR", "script": "return [B08, B12, B04];"})
+ assert written_here.status_code == 200, written_here.text
+ assert client.post("/api/compare/analyzers/import", json=written).json()["missing_layers"] == []
+
+
+def test_a_shared_radar_analyzer_reads_through_this_machines_own_radar_layer(client):
+ client.put("/api/settings/prefs", json={"sentinel1_layer": "S1_GRD_HERE"})
+ pass_of = lambda day: {"provider": "sentinel1", "date": day, "time": SAR_TIME, "layer": SAR_LAYER} # noqa: E731
+ radar = recipe({"measure": "radar", "on": "change", "op": "moved", "value": 3}, name="Razed")
+ file = file_of(radar, checks=[check_body([{"point": PLOT, "expect": "found"}],
+ a=pass_of(DAY_A), b=pass_of(DAY_B))])
+
+ body = client.post("/api/compare/analyzers/import", json=file)
+ assert body.status_code == 200, body.text
+ check = body.json()["analyzer"]["checks"][0]
+ # Two instances rarely name their Sentinel-1 layer alike, and the pass the
+ # check is about is the date and the time of day, which travel untouched.
+ assert check["a"]["layer"] == check["b"]["layer"] == "S1_GRD_HERE"
+ assert (check["a"]["date"], check["b"]["time"]) == (DAY_A, SAR_TIME)
+ assert body.json()["missing_layers"] == []
+
+
+def test_a_full_library_refuses_an_import_instead_of_dropping_one(client):
+ def fill(settings):
+ settings["analyzers"] = [{**recipe(LOSS, name=f"Rule {n}").model_dump(), "id": f"custom-{n:012d}"}
+ for n in range(100)]
+ config.update_settings(fill)
+ refused = client.post("/api/compare/analyzers/import", json=file_of(recipe(LOSS, name="One more")))
+ assert refused.status_code == 409 and "full" in refused.text
+ assert len(client.get("/api/compare/analyzers").json()["custom"]) == 100
+
+
# -- a rule's reading, for moving its line without asking again ------------------------