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

Give a case folder its real name, and let the collage canvas follow the stitch (#66)

OsintMeThat1dbf3cbacf2f
diff --git a/docs/SPEC.md b/docs/SPEC.md
index 09bce46..b4ce174 100644
--- a/docs/SPEC.md
+++ b/docs/SPEC.md
@@ -276,6 +276,7 @@ stops making sense.
- **Free-form montage editor:** consider only if it stays distinct from Geo Proof and Inspect collage.
- **In-app OSINT assistant:** local chat and vision suggestions for analyst confirmation, with no cloud or API key by default.
- **Geographic playback:** step through dated case items on the map instead of showing one fixed Timeline window.
+- **A deleted case waits before it is gone:** artifacts, entities and bulk deletes are all recoverable, while removing a case is the one act with no way back and only a typed DELETE in front of it. Move the folder aside instead, and empty it later.
## 8. Explicit non-goals
diff --git a/frontend/src/lib/inspect.js b/frontend/src/lib/inspect.js
index cd00f77..09821b2 100644
--- a/frontend/src/lib/inspect.js
+++ b/frontend/src/lib/inspect.js
@@ -545,6 +545,55 @@ export function scaleQuads(quads, k, center = null) {
return quads.map((q) => scaleQuad(q, k, c));
}
+// A collage canvas is the resolution ceiling of everything on it: a piece is
+// added at whatever fits it (`initialQuad`), auto-stitch fits its answer into it,
+// and the export follows the pieces' bounds. So the size is the analyst's, within
+// the bounds the compose route accepts (`api/inspect.ComposeIn`).
+export const COLLAGE_MIN_DIM = 16;
+export const COLLAGE_MAX_DIM = 8192;
+export const COLLAGE_DEFAULT_SIZE = { width: 1600, height: 800 };
+
+/** A new, empty collage — one spelling, used wherever one is created. */
+export function newCollage(name) {
+ return {
+ id: uid('cl'),
+ name,
+ ...COLLAGE_DEFAULT_SIZE,
+ background: '#12141c',
+ transparent: true,
+ nodes: [],
+ };
+}
+
+/**
+ * A collage side, held inside the bounds the compose route accepts.
+ *
+ * An empty field is nothing said, not zero: `Number('')` is 0, and clamping that
+ * would answer a cleared box by collapsing the canvas to its floor.
+ */
+export function clampCollageDim(value, fallback) {
+ const typed = String(value ?? '').trim();
+ const n = Math.round(Number(typed));
+ if (!typed || !Number.isFinite(n)) return fallback;
+ return Math.min(COLLAGE_MAX_DIM, Math.max(COLLAGE_MIN_DIM, n));
+}
+
+/**
+ * The canvas an auto-stitch answer asks for, and the factor that carries a piece
+ * it could not place into it.
+ *
+ * The solver works in source pixels and answers with the canvas that holds its
+ * layout at full detail, so the canvas follows the stitch rather than the stitch
+ * being squeezed into the canvas — that squeeze is a downscale of the very detail
+ * the pieces were stitched for. `scale` is the smaller of the two ratios, so an
+ * unplaced piece grows with the canvas without changing shape.
+ */
+export function stitchCanvas(canvas, current) {
+ const width = clampCollageDim(canvas?.width, current.width);
+ const height = clampCollageDim(canvas?.height, current.height);
+ return { width, height, scale: Math.min(width / current.width, height / current.height) };
+}
+
/** A sensible starting quad: the image scaled to fit `maxW`, placed at (ox, oy). */
export function initialQuad(natW, natH, maxW, ox, oy) {
const scale = Math.min(1, maxW / (natW || maxW));
diff --git a/frontend/src/lib/inspect.test.js b/frontend/src/lib/inspect.test.js
index d8d47cd..3df8c3f 100644
--- a/frontend/src/lib/inspect.test.js
+++ b/frontend/src/lib/inspect.test.js
@@ -5,6 +5,8 @@ import {
quadsBounds, translateQuad, moveQuads, rotateQuads, scaleQuads, pinholeOps,
buildFrameOps, hasVideoEdits, normalizeRightAngleRotation, rotationOps,
sourceStem, timecode, frameSaveName, frameSaveNames, autoSaveNames, saveNameOf,
+ newCollage, clampCollageDim, stitchCanvas, COLLAGE_MIN_DIM, COLLAGE_MAX_DIM,
+ COLLAGE_DEFAULT_SIZE,
} from './inspect.js';
const near = (a, b, eps = 1e-6) => Math.abs(a - b) < eps;
@@ -478,3 +480,69 @@ describe('saveNameOf', () => {
expect(saveNameOf(item)).toBe('00-01-00 roof');
});
});
+
+describe('newCollage', () => {
+ it('starts every collage the same way, whoever creates it', () => {
+ const a = newCollage('Collage 1');
+ expect(a.name).toBe('Collage 1');
+ expect([a.width, a.height]).toEqual([COLLAGE_DEFAULT_SIZE.width, COLLAGE_DEFAULT_SIZE.height]);
+ expect(a.nodes).toEqual([]);
+ expect(a.transparent).toBe(true);
+ });
+
+ it('gives each one its own id and its own node list', () => {
+ const a = newCollage('Collage 1');
+ const b = newCollage('Collage 2');
+ a.nodes.push({});
+ expect(a.id).not.toBe(b.id);
+ expect(b.nodes).toEqual([]);
+ });
+});
+
+describe('clampCollageDim', () => {
+ it('keeps a side the compose route accepts', () => {
+ expect(clampCollageDim(4000, 800)).toBe(4000);
+ expect(clampCollageDim(COLLAGE_MAX_DIM, 800)).toBe(COLLAGE_MAX_DIM);
+ });
+
+ it('holds a number typed past either bound', () => {
+ expect(clampCollageDim(99999, 800)).toBe(COLLAGE_MAX_DIM);
+ expect(clampCollageDim(0, 800)).toBe(COLLAGE_MIN_DIM);
+ expect(clampCollageDim(-40, 800)).toBe(COLLAGE_MIN_DIM);
+ });
+
+ it('rounds a fractional one rather than sizing a canvas in half pixels', () => {
+ expect(clampCollageDim('1600.6', 800)).toBe(1601);
+ });
+
+ it('falls back to the size in place when the field says nothing', () => {
+ expect(clampCollageDim('', 800)).toBe(800);
+ expect(clampCollageDim('wide', 800)).toBe(800);
+ expect(clampCollageDim(null, 800)).toBe(800);
+ });
+});
+
+describe('stitchCanvas', () => {
+ const current = { width: 1600, height: 800 };
+
+ it('takes the canvas the solver asked for', () => {
+ expect(stitchCanvas({ width: 4800, height: 2400 }, current))
+ .toEqual({ width: 4800, height: 2400, scale: 3 });
+ });
+
+ it('scales an unplaced piece by the smaller ratio, so it keeps its shape', () => {
+ const { scale } = stitchCanvas({ width: 6400, height: 1600 }, current);
+ expect(scale).toBe(2); // 4x wider, 2x taller — the piece grows twice
+ });
+
+ it('holds the answer inside the bounds compose accepts', () => {
+ const { width, height } = stitchCanvas({ width: 20000, height: 90000 }, current);
+ expect(width).toBe(COLLAGE_MAX_DIM);
+ expect(height).toBe(COLLAGE_MAX_DIM);
+ });
+
+ it('leaves the canvas alone when the answer says nothing about it', () => {
+ expect(stitchCanvas(undefined, current)).toEqual({ ...current, scale: 1 });
+ expect(stitchCanvas({}, current)).toEqual({ ...current, scale: 1 });
+ });
+});
diff --git a/frontend/src/tools/Inspector.svelte b/frontend/src/tools/Inspector.svelte
index e0ca027..5a23828 100644
--- a/frontend/src/tools/Inspector.svelte
+++ b/frontend/src/tools/Inspector.svelte
@@ -8,6 +8,7 @@
adjustDefaults, buildFrameOps, previewStyle, uid, videoSeed, initialQuad, VIDEO_ADJUST_IDS,
collageBounds, quadFromCropRect, cropImgStyle, cropAspect, styleText, hasVideoEdits,
normalizeRightAngleRotation, rotationOps, sourceStem, frameSaveNames, autoSaveNames, saveNameOf,
+ newCollage, COLLAGE_DEFAULT_SIZE,
} from '../lib/inspect.js';
import {
isDefaultName, nextName, savedSlugs, savedTitles, savedTitle, slugify, specAttr, specPath,
@@ -95,13 +96,9 @@
// Loading can be slow because each frame and collage node is rendered in sequence.
let sessionLoading = $state(false);
- // A session can hold several collages and edits one at a time.
- function makeCollage(name) {
- return { id: uid('cl'), name, width: 1600, height: 800, background: '#12141c', transparent: true, nodes: [] };
- }
-
- // the live session (reset on source / case change)
- const _firstCollage = makeCollage('Collage 1');
+ // A session can hold several collages and edits one at a time; this is the
+ // live one (reset on source / case change).
+ const _firstCollage = newCollage('Collage 1');
// Bumped every time the session is cleared, so work started against the old
// one can tell it is stale (`resetSession`, `capture`).
let sessionRun = 0;
@@ -554,7 +551,7 @@
session.videoRotation = 0;
session.frames = [];
session.activeFrameId = null;
- const c0 = makeCollage('Collage 1');
+ const c0 = newCollage('Collage 1');
session.collages = [c0];
session.activeCollageId = c0.id;
for (const p of Object.values(collagePreviews)) if (p?.url) URL.revokeObjectURL(p.url);
@@ -1203,14 +1200,14 @@
collages.push({
id: sc.id ?? uid('cl'),
name: sc.name ?? `Collage ${collages.length + 1}`,
- width: sc.width ?? 1600,
- height: sc.height ?? 800,
+ width: sc.width ?? COLLAGE_DEFAULT_SIZE.width,
+ height: sc.height ?? COLLAGE_DEFAULT_SIZE.height,
background: sc.background ?? '#12141c',
transparent: sc.transparent ?? false,
nodes,
});
}
- if (!collages.length) collages.push(makeCollage('Collage 1'));
+ if (!collages.length) collages.push(newCollage('Collage 1'));
session.collages = collages;
session.activeCollageId =
collages.find((c) => c.id === spec.activeCollageId)?.id ?? collages[0].id;
diff --git a/frontend/src/tools/inspect/CollageMenu.svelte b/frontend/src/tools/inspect/CollageMenu.svelte
index 40a0d5c..4bb6132 100644
--- a/frontend/src/tools/inspect/CollageMenu.svelte
+++ b/frontend/src/tools/inspect/CollageMenu.svelte
@@ -1,7 +1,8 @@
<script>
import {
- previewStyle, scaleQuad, rotateQuad, quadCentroid, cropImgStyle, styleText, uid,
- rotateQuads, scaleQuads, pinholeOps,
+ previewStyle, scaleQuad, rotateQuad, quadCentroid, cropImgStyle, styleText,
+ rotateQuads, scaleQuads, pinholeOps, newCollage, clampCollageDim, stitchCanvas,
+ COLLAGE_MIN_DIM, COLLAGE_MAX_DIM,
} from '../../lib/inspect.js';
import { api } from '../../lib/api.js';
import { caseState, toast } from '../../lib/state.svelte.js';
@@ -73,12 +74,21 @@
function addCollage() {
const nums = session.collages.map((c) => parseInt((c.name?.match(/\d+/) ?? [])[0]) || 0);
const next = Math.max(0, ...nums) + 1;
- const c = { id: uid('cl'), name: `Collage ${next}`, width: 1600, height: 800, background: '#12141c', transparent: true, nodes: [] };
+ const c = newCollage(`Collage ${next}`);
session.collages.push(c);
session.activeCollageId = c.id;
selectedIds = [];
}
+ // The canvas is the resolution everything on it is worked and exported at, so
+ // it is the analyst's to set. Held inside the bounds compose accepts, and the
+ // field is put back to what was taken so a refused number never sits there.
+ function setDim(event, axis) {
+ const next = clampCollageDim(event.currentTarget.value, active[axis]);
+ active[axis] = next;
+ event.currentTarget.value = next;
+ }
+
function removeCollage(id) {
if (session.collages.length <= 1) return; // always keep at least one
session.collages = session.collages.filter((c) => c.id !== id);
@@ -170,12 +180,30 @@
w: n.w, h: n.h, frameOps: n.frameOps, crop: n.crop, save: n.save,
});
+ /**
+ * Resize the canvas to what the solver asked for, carrying the pieces it did
+ * not place along with it. They are scaled uniformly, by the smaller of the two
+ * ratios, so a piece left in place keeps its shape and stays on the canvas.
+ */
+ function applyCanvas(canvas, placed) {
+ if (!canvas) return;
+ const { width, height, scale } = stitchCanvas(canvas, active);
+ if (width === active.width && height === active.height) return;
+ if (scale !== 1) {
+ active.nodes.forEach((n, i) => {
+ if (!placed.has(i)) n.quad = n.quad.map(([x, y]) => [x * scale, y * scale]);
+ });
+ }
+ active.width = width;
+ active.height = height;
+ }
+
async function autoStitch() {
if (!active || active.nodes.length < 2) return;
stitching = true;
try {
const nodes = active.nodes;
- const before = nodes.map(snapshot);
+ const before = { nodes: nodes.map(snapshot), width: active.width, height: active.height };
const res = await api.post(`/api/cases/${caseState.current.id}/inspect/auto-stitch`, {
width: active.width,
height: active.height,
@@ -183,6 +211,11 @@
// frozen snapshot recipes (path/time/ops), stripped back to pinhole pixels
nodes: nodes.map((n) => ({ ...n.save, ops: pinholeOps(n.save) })),
});
+ // A stitch is solved in source pixels, so the canvas follows it: the answer
+ // carries the size that keeps the pieces at full resolution, and the export
+ // is the pieces' bounds, so a canvas left too small *is* the lost detail.
+ // Pieces the solver could not place keep their place as it grows.
+ applyCanvas(res.canvas, new Set(res.nodes.map((n) => n.index)));
for (const { index, quad, op } of res.nodes) {
const node = nodes[index];
const base = pinholeOps(node.save);
@@ -210,10 +243,13 @@
}
function undoStitch() {
- for (const snap of undoSnap) {
+ for (const snap of undoSnap.nodes) {
const node = active.nodes.find((n) => n.id === snap.id);
if (node) Object.assign(node, snap);
}
+ // The canvas moved with the stitch, so it comes back with it.
+ active.width = undoSnap.width;
+ active.height = undoSnap.height;
undoSnap = null;
}
</script>
@@ -251,6 +287,33 @@
{/each}
<button class="ctab add" onclick={addCollage} title="New collage"><Icon name="plus" size={13} /></button>
</div>
+ {#if active}
+ <div class="scale-row">
+ <span class="lbl">Canvas</span>
+ <input
+ class="input dim"
+ type="number"
+ min={COLLAGE_MIN_DIM}
+ max={COLLAGE_MAX_DIM}
+ value={active.width}
+ onchange={(e) => setDim(e, 'width')}
+ aria-label="Canvas width in pixels"
+ />
+ <span class="sub">×</span>
+ <input
+ class="input dim"
+ type="number"
+ min={COLLAGE_MIN_DIM}
+ max={COLLAGE_MAX_DIM}
+ value={active.height}
+ onchange={(e) => setDim(e, 'height')}
+ aria-label="Canvas height in pixels"
+ />
+ <span class="sub">px</span>
+ </div>
+ <p class="hint">Pieces are placed and exported at this scale, so raise it to keep a
+ high-resolution frame sharp.</p>
+ {/if}
</div>
<p class="hint">Drag pieces to arrange them, pull corners to warp; shift-click selects several.</p>
@@ -344,7 +407,8 @@
<div class="section-head"><span>Auto panorama</span></div>
<p class="hint">
Solves the layout from the overlapping imagery itself, then drops the pieces back on the
- canvas. You can still drag pieces to correct the result.
+ canvas, which grows to hold them at full resolution. You can still drag pieces to correct
+ the result.
</p>
<div class="modes">
{#each MODES as m (m.id)}
@@ -558,6 +622,11 @@
font-size: var(--fs-xs);
color: var(--text-3);
}
+ .dim {
+ width: 5.5em;
+ padding: 4px 6px;
+ font-size: var(--fs-xs);
+ }
.btn.sq {
min-width: 30px;
justify-content: center;
diff --git a/frontend/src/tools/inspect/CollageMenu.test.js b/frontend/src/tools/inspect/CollageMenu.test.js
index 89d3f21..ae3fb51 100644
--- a/frontend/src/tools/inspect/CollageMenu.test.js
+++ b/frontend/src/tools/inspect/CollageMenu.test.js
@@ -55,3 +55,40 @@ describe('CollageMenu frame tray', () => {
expect(source).not.toContain('max-height: 200px');
});
});
+
+describe('CollageMenu canvas', () => {
+ it('holds a typed side inside the bounds compose accepts, in the field too', () => {
+ expect(source).toContain(` const next = clampCollageDim(event.currentTarget.value, active[axis]);
+ active[axis] = next;
+ event.currentTarget.value = next;`);
+ expect(source).toContain('min={COLLAGE_MIN_DIM}');
+ expect(source).toContain('max={COLLAGE_MAX_DIM}');
+ });
+
+ it('names both fields for a screen reader, which has no × to read', () => {
+ expect(source).toContain('aria-label="Canvas width in pixels"');
+ expect(source).toContain('aria-label="Canvas height in pixels"');
+ });
+
+ it('resizes the canvas to what the solver asked for', () => {
+ expect(source).toContain('applyCanvas(res.canvas, new Set(res.nodes.map((n) => n.index)));');
+ });
+
+ it('carries the pieces the solver could not place into the new canvas', () => {
+ expect(source).toContain(` active.nodes.forEach((n, i) => {
+ if (!placed.has(i)) n.quad = n.quad.map(([x, y]) => [x * scale, y * scale]);
+ });`);
+ });
+
+ it('leaves the canvas alone when the answer matches what is there', () => {
+ expect(source).toContain('if (width === active.width && height === active.height) return;');
+ });
+
+ it('brings the canvas back with the undo, not just the pieces', () => {
+ expect(source).toContain(
+ 'const before = { nodes: nodes.map(snapshot), width: active.width, height: active.height };'
+ );
+ expect(source).toContain(` active.width = undoSnap.width;
+ active.height = undoSnap.height;`);
+ });
+});
diff --git a/src/azimut/api/cases/lifecycle.py b/src/azimut/api/cases/lifecycle.py
index 4b036e3..84de22d 100644
--- a/src/azimut/api/cases/lifecycle.py
+++ b/src/azimut/api/cases/lifecycle.py
@@ -27,15 +27,14 @@ workspace_router = APIRouter(prefix="/api/workspace", tags=["cases"])
def _ensure_name_free(name: str, *, exclude_id: str | None = None) -> None:
- """Reject a case name already taken by another (non-scratch) case, matched
- case-insensitively on the trimmed name. ``exclude_id`` lets a rename keep
- its own name."""
- wanted = name.strip().casefold()
- for c in Case.list_all():
- if c.get("scratch") or c["id"] == exclude_id:
- continue
- if str(c.get("name", "")).strip().casefold() == wanted:
- raise HTTPException(status_code=409, detail=f"a case named '{name}' already exists")
+ """Reject a case name another case already answers to (`Case.name_taken`).
+
+ The only thing standing between two cases, now that the folder underneath
+ gets numbered instead of refusing: a name is what the analyst reads, so it is
+ what the app protects and what the message is about.
+ """
+ if Case.name_taken(name, exclude_id=exclude_id):
+ raise HTTPException(status_code=409, detail=f"a case named '{name}' already exists")
class CreateCase(BaseModel):
name: str = Field(min_length=1, max_length=120)
diff --git a/src/azimut/engine/bundles.py b/src/azimut/engine/bundles.py
index bea17c1..6962dae 100644
--- a/src/azimut/engine/bundles.py
+++ b/src/azimut/engine/bundles.py
@@ -937,17 +937,19 @@ def imported_name(name: str) -> str:
def create_import_case(name: str) -> Case:
- """Create a distinct destination, adding a number only when needed."""
+ """Create a destination no other case answers to, numbering only when needed.
+
+ The question is asked of the *name*, not of the folder: `Case.create` now
+ numbers a taken folder itself, so importing the same bundle twice would
+ otherwise leave two cases the switcher shows under one name.
+ """
base = imported_name(name)
candidate = base
index = 2
- while True:
- try:
- return Case.create(candidate)
- except CaseError:
- pass
+ while Case.name_taken(candidate):
candidate = f"{base} {index}"
index += 1
+ return Case.create(candidate)
def _install_running_job(db_path: Path, job: dict[str, Any]) -> None:
diff --git a/src/azimut/engine/diagnostics.py b/src/azimut/engine/diagnostics.py
index 70b71a2..1962a7c 100644
--- a/src/azimut/engine/diagnostics.py
+++ b/src/azimut/engine/diagnostics.py
@@ -23,8 +23,8 @@ holds a few kilobytes and no log file ever grows in the workspace.
or a provider key, and an issue is public, so every string goes through
:func:`scrub`: the home directory and the workspace root collapse to placeholders,
and so do the account name, the case folder and any credential-shaped query
-parameter. A case folder is a slug of the name the analyst typed, which in this
-tool is routinely a subject's — that one is not a nicety. The workspace path is
+parameter. A case folder carries the name the analyst typed, which in this tool
+is routinely a subject's — that one is not a nicety. The workspace path is
also absent from the report outright: About shows it locally, a report does not
need it.
"""
@@ -197,10 +197,12 @@ def scrub(text: str) -> str:
- this machine's name becomes ``<machine>``. The workspace lock names the
host holding a folder, which on a corporate laptop is an asset tag and a
company domain.
- - a case folder becomes ``<case>``. A case directory is a slug of the name the
- analyst gave it (``workspace._slugify``), and in this tool that name is
+ - a case folder becomes ``<case>``. A case directory carries the name the
+ analyst gave it (``layout.case_folder_name``), and in this tool that name is
routinely a subject's — so the segment goes even though the path around it
- is useful.
+ is useful. Twice over: the folders on disk are matched by name
+ (:func:`_hide_case_folders`), and whatever that misses is caught by
+ position.
- a credential-shaped query parameter becomes ``<redacted>``
None of this makes an arbitrary string safe to publish; it removes what this
@@ -212,9 +214,15 @@ def scrub(text: str) -> str:
root = ""
if root and root not in ("~", "/"):
text = _path_pattern(root).sub(_WORKSPACE_PLACEHOLDER, text)
- # Permanent cases now sit directly below the workspace root. The one
- # reserved first segment is `.azimut`; every other directory there is
- # an analyst-named case and must not reach a public issue report.
+ # Before the pattern below, which stops at whitespace and would leave two
+ # thirds of "Operation Blue Heron" standing.
+ text = _hide_case_folders(text)
+ if root and root not in ("~", "/"):
+ # The fallback, for a folder the names pass cannot know about: one this
+ # very line reports deleting, or one under a workspace this process has
+ # moved away from. Permanent cases sit directly below the workspace root,
+ # where the one reserved first segment is `.azimut`; every other
+ # directory there is analyst-named and must not reach a public report.
workspace = re.escape(_WORKSPACE_PLACEHOLDER)
text = re.sub(
rf"({workspace})([/\\])(?!\.azimut(?:[/\\]|$))[^/\\\s\"'<>]+",
@@ -270,6 +278,58 @@ def _case_parents() -> tuple[Path, ...]:
return ()
+def _case_folder_names() -> tuple[str, ...]:
+ """The case folder names on disk, longest first.
+
+ Read rather than inferred, because a case folder carries the name the analyst
+ typed (`layout.case_folder_name`) and that name holds spaces. A pattern over
+ path segments has to stop at whitespace — what follows a path on a log line
+ is prose — so on ``Operation Blue Heron`` it would redact one word and
+ publish two. An exact name has no such ambiguity.
+
+ Longest first, so a case called ``Kyiv`` cannot take the front of
+ ``Kyiv 4 June`` and leave the rest of it standing. Dotted directories are
+ skipped: `.azimut` is the workspace's own machinery, and no case folder
+ starts with a dot (`layout.usable_case_name`).
+
+ Two directory listings, on a report that carries at most
+ :data:`LOG_LINES` + 1 scrubbed strings.
+ """
+ try:
+ parents = (config.cases_dir(), *_case_parents())
+ except Exception:
+ return ()
+ names: set[str] = set()
+ for directory in parents:
+ try:
+ names.update(
+ entry.name
+ for entry in directory.iterdir()
+ if not entry.name.startswith(".") and entry.is_dir()
+ )
+ except OSError: # a workspace that isn't there yet, or isn't readable
+ continue
+ return tuple(sorted(names, key=len, reverse=True))
+
+
+def _hide_case_folders(text: str) -> str:
+ """Replace every case folder named on disk, wherever a path names it.
+
+ Anchored on the separator before the name and a boundary after it, so a case
+ called ``Kyiv`` does not turn ``/Kyivograd/`` into a placeholder. Case
+ insensitive on Windows, for the reason :func:`_path_pattern` gives.
+ """
+ flags = re.IGNORECASE if os.name == "nt" else 0
+ for name in _case_folder_names():
+ text = re.sub(
+ rf"(?<=[/\\]){re.escape(name)}(?=[/\\\s\"'<>]|$)",
+ _CASE_PLACEHOLDER,
+ text,
+ flags=flags,
+ )
+ return text
+
+
# ---- the report ---------------------------------------------------------------
diff --git a/src/azimut/engine/inspect.py b/src/azimut/engine/inspect.py
index d1fa016..2ca84f1 100644
--- a/src/azimut/engine/inspect.py
+++ b/src/azimut/engine/inspect.py
@@ -838,6 +838,11 @@ def solve_collage_layout(
piece's recipe, which is how the warp survives to the full-res export. Callers
must hand in *un-remapped* recipes; a cylinder is not a pinhole view, so
solving cameras from already-warped pixels would measure the wrong scene.
+
+ ``width`` and ``height`` are the caller's current canvas, and ``canvas`` in the
+ answer is the one the quads are expressed in: the solver grows it to whatever
+ the stitch is worth in source pixels rather than shrinking the stitch to fit.
+ The caller resizes its canvas to match, or the detail is lost on the way back.
"""
if mode not in STITCH_MODES:
raise ValueError(f"unknown panorama mode {mode!r}")
@@ -864,6 +869,7 @@ def solve_collage_layout(
for i, q in sorted(solved["quads"].items())
],
"dropped": solved["dropped"],
+ "canvas": solved["canvas"],
}
diff --git a/src/azimut/engine/stitch.py b/src/azimut/engine/stitch.py
index cf14329..f946334 100644
--- a/src/azimut/engine/stitch.py
+++ b/src/azimut/engine/stitch.py
@@ -57,6 +57,16 @@ MIN_INLIER_RATIO = 0.5
# back so every homography stays in full-resolution image coordinates.
WORK_DIM = 1000
+# A solved layout comes out in source pixels — five 1080p frames panned across a
+# facade span some 4500 of them — so the canvas follows the stitch rather than
+# the other way round. Fitting that answer into whatever size the collage
+# happened to open at is a downscale, and thin detail (a cable, a pipe) is what
+# goes first. Bounded, because the canvas still has to be composable: the compose
+# route refuses a side over 8192, and the compositor paints RGBA, so 40 MP is
+# already a 160 MB canvas before a single piece is warped onto it.
+MAX_CANVAS_DIM = 8192
+MAX_CANVAS_PIXELS = 40_000_000
+
_RATIO = 0.75 # Lowe ratio test
_RANSAC_PX = 4.0
@@ -357,12 +367,62 @@ def fit_quads_to_canvas(
return [[[x * scale + off_x, y * scale + off_y] for x, y in q] for q in quads]
+def canvas_for_layout(
+ quads: list[Quad],
+ *,
+ detail: float = 1.0,
+ minimum: tuple[int, int] = (1, 1),
+ margin: float = 0.02,
+) -> tuple[int, int]:
+ """The canvas that holds ``quads`` without scaling their pixels down.
+
+ ``detail`` is how many source pixels one unit of the solved geometry is worth:
+ 1 for the planar solver, whose homographies are already in full-resolution
+ coordinates, and the work-image factor for the rotation solver, which projects
+ a downscaled copy of every piece. The span is divided by the fraction
+ :func:`fit_quads_to_canvas` leaves usable, so fitting into this answer scales
+ the geometry by exactly one.
+
+ The bounds above hold what the *solver* asks for, and it stays under them by
+ shrinking both sides together, so a clamped canvas still carries the shape it
+ found. They are not a ceiling on the canvas: ``minimum`` is the one the
+ analyst is already working on, and this never answers below it — growing to
+ hold a stitch must not become a way of shrinking a canvas that was already
+ bigger, which would take the size off the pieces sitting on it.
+ """
+ if not quads:
+ return max(1, minimum[0]), max(1, minimum[1])
+ xs = [p[0] for q in quads for p in q]
+ ys = [p[1] for q in quads for p in q]
+ usable = max(1e-6, 1.0 - 2.0 * margin)
+ width = max(1, math.ceil((max(xs) - min(xs)) * detail / usable))
+ height = max(1, math.ceil((max(ys) - min(ys)) * detail / usable))
+ shrink = min(
+ 1.0,
+ MAX_CANVAS_DIM / max(width, height),
+ math.sqrt(MAX_CANVAS_PIXELS / (width * height)),
+ )
+ if shrink < 1.0:
+ width = max(1, int(width * shrink))
+ height = max(1, int(height * shrink))
+ width = max(1, minimum[0], width)
+ height = max(1, minimum[1], height)
+ return width, height
+
+
def solve_layout(images: list[Image.Image], *, width: int, height: int) -> dict[str, Any]:
"""Solve collage quads for ``images`` (canvas pixels), reporting what failed.
- Returns ``{"quads": {index: quad}, "dropped": [index, ...], "anchor": index}``.
- ``dropped`` holds images that matched nothing (or projected degenerately) —
- they keep whatever the caller had; nothing is invented for them.
+ Returns ``{"quads": {index: quad}, "dropped": [...], "anchor": index,
+ "canvas": {"width", "height"}}``. ``dropped`` holds images that matched
+ nothing (or projected degenerately) — they keep whatever the caller had;
+ nothing is invented for them.
+
+ ``width`` and ``height`` are the canvas the caller already has, and the answer
+ is fitted into the larger of that and the layout's own extent
+ (:func:`canvas_for_layout`) — so a wide pan of full-resolution frames is not
+ squeezed into a small canvas, which is a downscale of the very detail it was
+ stitched for. ``canvas`` reports the size the quads are expressed in.
"""
if len(images) < 2:
raise ValueError("auto-stitch needs at least two pieces")
@@ -414,11 +474,16 @@ def solve_layout(images: list[Image.Image], *, width: int, height: int) -> dict[
raise RuntimeError("auto-stitch could not place any piece")
order = sorted(solved)
- fitted = fit_quads_to_canvas([solved[i] for i in order], width, height)
+ # The homographies are in full-resolution coordinates (`_features` scales its
+ # keypoints back), so a unit of this geometry is already one source pixel.
+ raw = [solved[i] for i in order]
+ canvas = canvas_for_layout(raw, minimum=(width, height))
+ fitted = fit_quads_to_canvas(raw, *canvas)
return {
"quads": {i: q for i, q in zip(order, fitted)},
"dropped": sorted(dropped),
"anchor": anchor,
+ "canvas": {"width": canvas[0], "height": canvas[1]},
}
@@ -676,11 +741,12 @@ def solve_rotation_layout(
) -> dict[str, Any]:
"""Solve a panorama layout under the rotation model — geometry *and* a remap.
- Returns ``{"quads": {index: quad}, "remaps": {index: params}, "dropped": [...]}``.
- Each quad is the upright rectangle the piece's remapped pixels fill, in canvas
- pixels; each remap is the op that produces those pixels from the piece's
- recipe. ``dropped`` holds the pieces no trusted match reached — the caller
- leaves them untouched, exactly as in :func:`solve_layout`.
+ Returns ``{"quads": {index: quad}, "remaps": {index: params}, "dropped": [...],
+ "canvas": {"width", "height"}}``. Each quad is the upright rectangle the
+ piece's remapped pixels fill, in canvas pixels; each remap is the op that
+ produces those pixels from the piece's recipe. ``dropped`` holds the pieces no
+ trusted match reached — the caller leaves them untouched, and ``canvas`` sizes
+ the answer, both exactly as in :func:`solve_layout`.
"""
import numpy as np
@@ -741,9 +807,17 @@ def solve_rotation_layout(
raise RuntimeError("auto-stitch could not place any piece")
order = sorted(quads)
- fitted = fit_quads_to_canvas([quads[i] for i in order], width, height)
+ raw = [quads[i] for i in order]
+ # This model projects the *work* copy of each piece, so one unit of its
+ # geometry is worth however much the finest piece was downscaled by. Sizing on
+ # the largest factor is what keeps that piece at full detail; a coarser one is
+ # merely upscaled into a canvas with room to spare.
+ detail = max((1.0 / _work_scale(images[i].size) for i in order), default=1.0)
+ canvas = canvas_for_layout(raw, detail=detail, minimum=(width, height))
+ fitted = fit_quads_to_canvas(raw, *canvas)
return {
"quads": {i: q for i, q in zip(order, fitted)},
"remaps": remaps,
"dropped": sorted(dropped),
+ "canvas": {"width": canvas[0], "height": canvas[1]},
}
diff --git a/src/azimut/layout.py b/src/azimut/layout.py
index a6a6e58..1f1e65a 100644
--- a/src/azimut/layout.py
+++ b/src/azimut/layout.py
@@ -259,26 +259,40 @@ def names_one_child(name: str) -> bool:
return name == PurePosixPath(name).name == PureWindowsPath(name).name
+def case_folder_name(name: str | None, fallback: str = "case") -> str:
+ """The folder name a case is given, out of the name the analyst typed.
+
+ `slugify` is this repo's naming rule and answers most of it: the folder is
+ the name Azimut shows, so case, spaces and Unicode survive and only what
+ Windows refuses is replaced. A case folder carries one rule more, because
+ its name *is* the case id and the id travels in a URL path, so
+ `URL_HOSTILE_CHARS` go as well.
+
+ Held to `MAX_CASE_SLUG`, which the path budget above is computed from.
+ """
+ value = str(name or "")
+ for char in URL_HOSTILE_CHARS:
+ value = value.replace(char, "_")
+ return slugify(value, fallback, limit=MAX_CASE_SLUG)
+
+
def usable_case_name(name: str) -> bool:
"""Whether a folder can hold a case under the name it already has.
- A case made in the app is named by `Case.create`, which slugs whatever was
- typed. A folder the analyst made themselves arrives already named, and
- adopting it must not rename it — so the name has to clear on its own the bar
- a slug clears by construction: inside `MAX_CASE_SLUG` (the path budget above
- is computed from it), no character Windows refuses, no reserved device name,
- no leading dot, no trailing dot or space.
-
- `slugify` encodes every one of those rules, so the question is whether the
- name is already its own slug. Compared against the composed form because
- macOS hands back decomposed names from a directory listing, and "Café" is
- not two different folders.
+ A case made in the app is named by `Case.create`, which runs whatever was
+ typed through `case_folder_name`. A folder the analyst made themselves
+ arrives already named, and adopting it must not rename it — so the name has
+ to clear on its own the bar a generated one clears by construction.
+
+ Which is exactly this question: is the name already its own answer? Asking it
+ that way is what keeps the folder Azimut names and the folder the analyst
+ named under one rule, with no second spelling to drift from. Compared against
+ the composed form because macOS hands back decomposed names from a directory
+ listing, and "Café" is not two different folders.
"""
if not name or name in {".", ".."}:
return False
- if set(name) & set(URL_HOSTILE_CHARS):
- return False
- return slugify(name, "", limit=MAX_CASE_SLUG) == unicodedata.normalize("NFC", name)
+ return case_folder_name(name) == unicodedata.normalize("NFC", name)
class LayoutError(ValueError):
diff --git a/src/azimut/workspace.py b/src/azimut/workspace.py
index 3a461fa..d0f26dd 100644
--- a/src/azimut/workspace.py
+++ b/src/azimut/workspace.py
@@ -12,7 +12,6 @@ from __future__ import annotations
import json
import logging
-import re
import shutil
import sqlite3
import threading
@@ -123,9 +122,29 @@ def _now() -> str:
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
-def _slugify(name: str) -> str:
- slug = re.sub(r"[^a-z0-9]+", "-", name.lower()).strip("-")
- return slug[:MAX_CASE_SLUG].strip("-") or "case"
+def _free_case_path(parent: Path, name: str) -> Path:
+ """A directory in ``parent`` for a case called ``name``, guaranteed free.
+
+ The folder carries the analyst's own name (`layout.case_folder_name`), and a
+ name that lands on a folder already there is numbered rather than refused.
+ Two cases may not share a *name* — the routes refuse that, in the name's own
+ words — but the folder is the tool's business, and different names can
+ perfectly well reduce to one: "Kyiv, 4 June" and "Kyiv — 4 June" do, and so
+ did every pair of names written in a script the old ASCII slug could not
+ spell, which left both of them on the folder `case` and the second case
+ impossible to create at all.
+
+ Never answers with a path that exists, so a case is never born over one.
+ """
+ base = layout.case_folder_name(name)
+ candidate = parent / base
+ index = 2
+ while candidate.exists():
+ suffix = f" {index}"
+ stem = base[: MAX_CASE_SLUG - len(suffix)].rstrip(" .") or "case"
+ candidate = parent / f"{stem}{suffix}"
+ index += 1
+ return candidate
def _new_id(prefix: str) -> str:
@@ -257,13 +276,19 @@ class Case(CaseStore):
@classmethod
def create(cls, name: str, *, scratch: bool = False) -> "Case":
"""Create a new case. Every case is born on the SQLite backend; a legacy
- json case only ever arrives from disk and is converted on open."""
+ json case only ever arrives from disk and is converted on open.
+
+ Whether the *name* is free is the caller's question, and the routes ask it
+ (`api/cases/lifecycle._ensure_name_free`) so the analyst hears about their
+ own case rather than about a folder. This only picks a folder to put it
+ in, and picks one nothing is in.
+ """
parent = config.scratch_dir() if scratch else config.cases_dir()
parent.mkdir(parents=True, exist_ok=True)
- slug = _new_id("scratch") if scratch else _slugify(name)
- path = parent / slug
- if path.exists():
- raise CaseError(f"case '{slug}' already exists")
+ # A scratch folder is a generated id, so nothing has to be dodged; the
+ # `mkdir` below is the check, and a uuid collision would be the one to
+ # hear about.
+ path = parent / _new_id("scratch") if scratch else _free_case_path(parent, name)
path.mkdir()
return cls._born(path, name)
@@ -548,6 +573,28 @@ class Case(CaseStore):
continue # a file may be open elsewhere (Windows) — next start
return removed
+ @classmethod
+ def name_taken(cls, name: str, *, exclude_id: str | None = None) -> bool:
+ """Whether another case already answers to ``name``.
+
+ Matched on the trimmed name, case-insensitively, because that name is how
+ the analyst tells two cases apart in the switcher — "Kyiv" and "kyiv " are
+ one case to a person and must be one to the app. Scratch cases are skipped
+ (they are all "Scratch session" until promoted), and ``exclude_id`` lets a
+ rename keep the name it already has.
+
+ The rule lives here rather than in the route because the import
+ destination needs the same answer (`engine/bundles.create_import_case`),
+ and two spellings of "already taken" would drift.
+ """
+ wanted = name.strip().casefold()
+ for case in cls.list_all():
+ if case.get("scratch") or case["id"] == exclude_id:
+ continue
+ if str(case.get("name", "")).strip().casefold() == wanted:
+ return True
+ return False
+
@classmethod
def list_all(cls, *, q: str | None = None, limit: int | None = None) -> list[dict[str, Any]]:
out: list[dict[str, Any]] = []
@@ -845,11 +892,9 @@ class Case(CaseStore):
"""Move a scratch case to the workspace root under a proper name."""
if not self.is_scratch:
raise CaseError("only scratch cases can be promoted")
- slug = _slugify(name)
- dest = config.cases_dir() / slug
- if dest.exists():
- raise CaseError(f"case '{slug}' already exists")
- dest.parent.mkdir(parents=True, exist_ok=True)
+ parent = config.cases_dir()
+ parent.mkdir(parents=True, exist_ok=True)
+ dest = _free_case_path(parent, name)
self._settle_background_work()
shutil.move(str(self.path), str(dest))
promoted = Case(dest)
diff --git a/tests/bigcase.py b/tests/bigcase.py
index 817fe75..7ca4475 100644
--- a/tests/bigcase.py
+++ b/tests/bigcase.py
@@ -15,11 +15,11 @@ import random
from dataclasses import dataclass, field
from datetime import datetime, timedelta, timezone
-from azimut import config
+from azimut import config, layout
from azimut.engine.media import THUMB_DIR
from azimut.layout import PRE_HIDDEN_SIDECAR_SUFFIX
from legacy_case import LEGACY_SUBDIRS
-from azimut.workspace import Case, _slugify
+from azimut.workspace import Case
# Well-known + deliberately unknown types, so the fixture exercises the "unknown
# entity/link types stay valid" rule the ontology promises.
@@ -95,7 +95,7 @@ def build_big_case(
# open it through the one-way migration path.
parent = config.cases_dir()
parent.mkdir(parents=True, exist_ok=True)
- path = parent / _slugify(name)
+ path = parent / layout.case_folder_name(name)
path.mkdir()
# The flat, unwrapped shape on purpose: this is a legacy import source, and
# opening it is what exercises the wrapper migration.
diff --git a/tests/legacy_case.py b/tests/legacy_case.py
index 4e2e577..5b61b3c 100644
--- a/tests/legacy_case.py
+++ b/tests/legacy_case.py
@@ -16,7 +16,7 @@ import shutil
from typing import Any
from azimut import config, layout, workspace
-from azimut.workspace import JSON_SCHEMA, Case, _now, _slugify
+from azimut.workspace import JSON_SCHEMA, Case, _now
#: The content directories as they were before the `azimut/` wrapper.
LEGACY_SUBDIRS = ("media", "notes", "proofs", "exports", "inspect", "search")
@@ -36,7 +36,7 @@ def write_legacy_json_case(
with `Case.open` converts it to sqlite."""
parent = config.scratch_dir() if scratch else config.cases_dir()
parent.mkdir(parents=True, exist_ok=True)
- path = parent / _slugify(name)
+ path = parent / layout.case_folder_name(name)
path.mkdir()
# Deliberately the flat, unwrapped shape: the tool's files sit at the case
# root, the way every release before the `azimut/` wrapper wrote them. This
diff --git a/tests/test_bundles.py b/tests/test_bundles.py
index 9fbbb4c..b1c5f6b 100644
--- a/tests/test_bundles.py
+++ b/tests/test_bundles.py
@@ -130,6 +130,17 @@ def test_sealed_chunks_detect_truncation_before_any_case_swap(bundle_case):
assert destination.list_entities() == []
+def test_importing_the_same_bundle_twice_names_the_second_destination_apart(bundle_case):
+ """`Case.create` numbers a taken folder by itself now, so the distinct name
+ the switcher shows has to be asked for on the name, not fallen into."""
+ first = bundles.create_import_case("Source case")
+ second = bundles.create_import_case("Source case")
+
+ assert first.id != second.id
+ assert first.read()["name"] == "Source case (imported)"
+ assert second.read()["name"] == "Source case (imported) 2"
+
+
@pytest.mark.parametrize("password", [None, "bundle secret"])
def test_export_import_round_trip_creates_a_new_case(bundle_case, password):
exported = bundles.export_case(bundle_case, password=password)
diff --git a/tests/test_cases_api.py b/tests/test_cases_api.py
index cedbd66..386b623 100644
--- a/tests/test_cases_api.py
+++ b/tests/test_cases_api.py
@@ -53,20 +53,22 @@ def test_list_cases_respects_limit(client):
def test_case_lifecycle(client):
created = client.post("/api/cases", json={"name": "Kharkiv Strike"}).json()
- assert created["id"] == "kharkiv-strike"
+ # The folder is the name the analyst typed, the way every other saved thing
+ # already carries its own (`layout.case_folder_name`).
+ assert created["id"] == "Kharkiv Strike"
assert graph_read.entities(created["id"]) == []
# duplicate name → 409
assert client.post("/api/cases", json={"name": "Kharkiv Strike"}).status_code == 409
listed = client.get("/api/cases").json()
- assert [c["id"] for c in listed] == ["kharkiv-strike"]
+ assert [c["id"] for c in listed] == ["Kharkiv Strike"]
- client.patch("/api/cases/kharkiv-strike", json={"name": "Kharkiv Strike v2"})
- assert client.get("/api/cases/kharkiv-strike").json()["name"] == "Kharkiv Strike v2"
+ client.patch("/api/cases/Kharkiv Strike", json={"name": "Kharkiv Strike v2"})
+ assert client.get("/api/cases/Kharkiv Strike").json()["name"] == "Kharkiv Strike v2"
- assert client.delete("/api/cases/kharkiv-strike").json()["status"] == "deleted"
- assert client.get("/api/cases/kharkiv-strike").status_code == 404
+ assert client.delete("/api/cases/Kharkiv Strike").json()["status"] == "deleted"
+ assert client.get("/api/cases/Kharkiv Strike").status_code == 404
def test_duplicate_name_rejected_case_insensitively(client):
@@ -78,6 +80,44 @@ def test_duplicate_name_rejected_case_insensitively(client):
assert client.post("/api/cases", json={"name": "Beta Site"}).status_code == 200
+def test_a_case_named_in_another_script_keeps_its_name(client):
+ """The folder used to be an ASCII slug, so a name with no a–z in it landed on
+ the fallback `case` — and the *second* such case could then never be created,
+ refused over a folder whose name nobody had typed."""
+ first = client.post("/api/cases", json={"name": "Маріуполь"})
+ second = client.post("/api/cases", json={"name": "Харків"})
+
+ assert first.status_code == 200 and second.status_code == 200
+ assert first.json()["id"] == "Маріуполь"
+ assert second.json()["id"] == "Харків"
+ assert {c["name"] for c in client.get("/api/cases").json()} == {"Маріуполь", "Харків"}
+
+
+def test_two_names_that_reduce_to_one_folder_both_get_a_case(client):
+ """Different names, one folder: the folder is numbered, because it is the
+ tool's business. Refusing there was a dead end the analyst could not resolve,
+ and the case that already existed must come through untouched."""
+ first = client.post("/api/cases", json={"name": "Kyiv: 4 June"}).json()
+ client.put(f"/api/cases/{first['id']}/notes", json={"text": "# the first case\n"})
+
+ second = client.post("/api/cases", json={"name": "Kyiv? 4 June"})
+
+ assert second.status_code == 200
+ assert second.json()["id"] != first["id"]
+ # The first case still holds its own work — a new case never lands on one.
+ assert "the first case" in client.get(f"/api/cases/{first['id']}/notes").json()["text"]
+ assert len(client.get("/api/cases").json()) == 2
+
+
+def test_a_name_that_would_break_its_own_url_is_filed_under_a_safe_folder(client):
+ """`#` and `%` cut a URL path short, and the folder name is the case id."""
+ created = client.post("/api/cases", json={"name": "Sortie #4 (100% sûr)"}).json()
+
+ assert "#" not in created["id"] and "%" not in created["id"]
+ assert created["name"] == "Sortie #4 (100% sûr)" # what the analyst sees is kept
+ assert client.get(f"/api/cases/{created['id']}").status_code == 200
+
+
def test_rename_rejects_existing_name_but_allows_self(client):
a = client.post("/api/cases", json={"name": "One"}).json()
client.post("/api/cases", json={"name": "Two"})
@@ -117,8 +157,8 @@ def test_scratch_promote(client):
promoted = client.post(
f"/api/cases/{scratch['id']}/promote", json={"name": "Real Case"}
).json()
- assert promoted["id"] == "real-case"
- assert client.get("/api/cases/real-case").json()["scratch"] is False
+ assert promoted["id"] == "Real Case"
+ assert client.get(f"/api/cases/{promoted['id']}").json()["scratch"] is False
# old scratch id is gone
assert client.get(f"/api/cases/{scratch['id']}").status_code == 404
diff --git a/tests/test_diagnostics.py b/tests/test_diagnostics.py
index ad69a54..d459455 100644
--- a/tests/test_diagnostics.py
+++ b/tests/test_diagnostics.py
@@ -393,9 +393,9 @@ def test_a_report_that_fits_is_left_whole(ring, tmp_workspace):
def test_a_case_name_never_reaches_the_tracker(ring, tmp_workspace):
- """A case directory is a slug of the name the analyst typed, and in this tool
- that name is routinely a subject's. The path around it is useful; the segment
- is not ours to publish."""
+ """A case directory carries the name the analyst typed, and in this tool that
+ name is routinely a subject's. The path around it is useful; the segment is
+ not ours to publish."""
from azimut import config
log = logging.getLogger("azimut.test")
@@ -410,6 +410,48 @@ def test_a_case_name_never_reaches_the_tracker(ring, tmp_workspace):
assert ".azimut/scratch/<case>/media/a.jpg" in captured.replace("\\", "/")
+def test_a_case_name_with_spaces_in_it_goes_whole(ring, tmp_workspace):
+ """The folder is the analyst's own name now, so it holds spaces — and a
+ pattern over path segments has to stop at whitespace or it would eat the
+ prose after the path. Redacting the first word only would publish a surname."""
+ from azimut import config
+
+ case = config.cases_dir() / "Operation Blue Heron"
+ case.mkdir(parents=True)
+ (config.scratch_dir() / "Kyiv 4 June").mkdir(parents=True)
+
+ log = logging.getLogger("azimut.test")
+ log.warning("could not open %s: permission denied", case / "azimut" / "case.db")
+ log.warning("still writing %s", config.scratch_dir() / "Kyiv 4 June")
+
+ captured = "\n".join(diagnostics.log_lines())
+
+ assert "Blue" not in captured and "Heron" not in captured
+ assert "Kyiv" not in captured and "June" not in captured
+ assert "<workspace>/<case>/azimut/case.db: permission denied" in captured.replace("\\", "/")
+ assert ".azimut/scratch/<case>" in captured.replace("\\", "/")
+
+
+def test_a_case_name_is_not_taken_out_of_a_longer_folder_name(ring, tmp_workspace):
+ """The names are matched longest first and only where a path names one, so a
+ short case name cannot leave the tail of a longer folder standing, and cannot
+ turn an unrelated directory into a placeholder."""
+ from azimut import config
+
+ (config.cases_dir() / "Kyiv").mkdir(parents=True)
+ (config.cases_dir() / "Kyiv 4 June").mkdir(parents=True)
+
+ log = logging.getLogger("azimut.test")
+ log.warning("could not open %s", config.cases_dir() / "Kyiv 4 June" / "case.db")
+ log.warning("unrelated: /opt/Kyivograd/data.bin")
+
+ captured = "\n".join(diagnostics.log_lines())
+
+ assert "Kyiv" not in captured.replace("Kyivograd", "")
+ assert "<workspace>/<case>/case.db" in captured.replace("\\", "/")
+ assert "/opt/Kyivograd/data.bin" in captured
+
+
def test_a_credential_in_a_logged_url_is_redacted(ring, tmp_workspace):
"""A keyed imagery or geocoding provider is reached over HTTP, so a warning
about one names the URL — key included."""
diff --git a/tests/test_folder_adoption.py b/tests/test_folder_adoption.py
index 40ce148..4078447 100644
--- a/tests/test_folder_adoption.py
+++ b/tests/test_folder_adoption.py
@@ -135,8 +135,12 @@ def test_a_name_that_would_break_its_own_url_asks_for_a_rename(client):
def test_adoption_refuses_a_name_another_case_already_uses(client):
- client.post("/api/cases", json={"name": "Coast match"})
- make_folder("Coast match") # the case above lives under its slug, `coast-match`
+ # Renamed rather than created under this name, because a rename moves the
+ # name and leaves the folder: that is what frees the folder for the analyst
+ # to make one beside it, which is the situation being refused here.
+ made = client.post("/api/cases", json={"name": "Shoreline"}).json()
+ client.patch(f"/api/cases/{made['id']}", json={"name": "Coast match"})
+ make_folder("Coast match")
refused = client.post("/api/workspace/folders/adopt", json={"name": "Coast match"})
diff --git a/tests/test_inspect_api.py b/tests/test_inspect_api.py
index 81e7a31..b377cb5 100644
--- a/tests/test_inspect_api.py
+++ b/tests/test_inspect_api.py
@@ -493,14 +493,40 @@ def test_auto_stitch_solves_quads_without_filing_anything(client):
body = res.json()
assert body["dropped"] == []
assert [n["index"] for n in body["nodes"]] == [0, 1]
+ canvas = body["canvas"]
for node in body["nodes"]:
assert len(node["quad"]) == 4
for x, y in node["quad"]:
- assert -1 <= x <= 1201 and -1 <= y <= 601
+ assert -1 <= x <= canvas["width"] + 1 and -1 <= y <= canvas["height"] + 1
# Layout only: auto-stitch is not a Save gate, so no media may appear.
assert len(client.get(f"/api/cases/{cid}/media").json()) == before
+def test_auto_stitch_answers_with_the_canvas_the_stitch_is_worth(client):
+ """The quads are only as good as the canvas they are read against, so the
+ route says which one it sized them for. Here the caller's canvas is smaller
+ than a single piece: keeping it would export the stitch at a fraction of the
+ pixels it was solved from."""
+ cid = client.post("/api/cases", json={"name": "StitchCanvas"}).json()["id"]
+ left_png, right_png = _overlapping_pair()
+ a = _upload(client, cid, "left.png", left_png)
+ b = _upload(client, cid, "right.png", right_png)
+
+ body = client.post(
+ f"/api/cases/{cid}/inspect/auto-stitch",
+ json={
+ "width": 240, "height": 200,
+ "nodes": [{"path": a["path"]}, {"path": b["path"]}],
+ },
+ ).json()
+
+ # The pieces are 500px crops overlapping by 200, so the panorama is ~800 wide.
+ assert body["canvas"]["width"] > 700
+ assert body["canvas"]["height"] > 200
+ # And the canvas stays composable: compose refuses a side over 8192.
+ assert body["canvas"]["width"] <= 8192 and body["canvas"]["height"] <= 8192
+
+
def test_auto_stitch_reports_a_piece_it_cannot_place(client):
cid = client.post("/api/cases", json={"name": "StitchDrop"}).json()["id"]
left_png, right_png = _overlapping_pair()
diff --git a/tests/test_layout.py b/tests/test_layout.py
index 36629e2..fab3d95 100644
--- a/tests/test_layout.py
+++ b/tests/test_layout.py
@@ -19,7 +19,7 @@ from azimut.api.naming import slugify
from azimut.engine.media import safe_filename
from azimut.engine.thumbnails import THUMB_GEN
from azimut.layout import CASE_SUBDIRS, TRASH_DIR
-from azimut.workspace import Case, CaseError, _slugify
+from azimut.workspace import Case, CaseError
SOURCE = Path(__file__).resolve().parents[1] / "src" / "azimut"
@@ -165,9 +165,34 @@ def test_the_trash_is_no_longer_the_longest_branch() -> None:
assert branches["trash slot"] < branches["note"]
+def test_a_generated_case_folder_name_is_always_an_adoptable_one() -> None:
+ """The generator and the check are one rule asked two ways, so whatever
+ `case_folder_name` answers, `usable_case_name` has to accept. Drift here means
+ Azimut naming a folder its own adoption and recovery routes would refuse."""
+ for name in (
+ "Kharkiv Strike", "Маріуполь", "الموصل", "上海", "🛰 pass", "Sortie #4",
+ "100% sûr", "a/b\\c:d", "con", "NUL.txt", " spaced ", "trailing dot.",
+ "..", "", "x" * 300,
+ ):
+ folder = layout.case_folder_name(name)
+ assert layout.usable_case_name(folder), f"{name!r} → {folder!r}"
+
+
+def test_a_case_folder_keeps_a_name_no_ascii_slug_could_spell() -> None:
+ assert layout.case_folder_name("Маріуполь") == "Маріуполь"
+ assert layout.case_folder_name("上海") == "上海"
+ # Only what a filesystem or a URL refuses is replaced.
+ assert layout.case_folder_name("Sortie #4") == "Sortie _4"
+ assert layout.case_folder_name("Kyiv: 4 June") == "Kyiv_ 4 June"
+ # A name made of nothing else keeps its shape rather than being emptied.
+ assert layout.case_folder_name("###") == "___"
+ # And one a filesystem leaves with nothing at all still has to land somewhere.
+ assert layout.case_folder_name("...") == "case"
+
+
def test_every_capped_name_is_actually_capped() -> None:
"""The caps are only real if the functions that build names apply them."""
- assert len(_slugify("x" * 300)) <= layout.MAX_CASE_SLUG
+ assert len(layout.case_folder_name("x" * 300)) <= layout.MAX_CASE_SLUG
assert len(slugify("x" * 300, "fallback")) <= layout.MAX_SLUG
assert len(safe_filename("x" * 300 + ".mp4")) <= layout.MAX_MEDIA_NAME
diff --git a/tests/test_stitch.py b/tests/test_stitch.py
index 756c7a9..dd4042f 100644
--- a/tests/test_stitch.py
+++ b/tests/test_stitch.py
@@ -110,6 +110,59 @@ def test_fit_quads_to_canvas_handles_empty():
assert stitch.fit_quads_to_canvas([], 100, 100) == []
+def test_canvas_for_layout_takes_the_layouts_own_extent():
+ quads = [[[0, 0], [1000, 0], [1000, 400], [0, 400]]]
+ assert stitch.canvas_for_layout(quads, margin=0.0) == (1000, 400)
+
+
+def test_canvas_for_layout_leaves_room_for_the_fitting_margin():
+ # The point of the size: fitting the layout into it scales the geometry by
+ # exactly one, so the pieces land at the resolution they were solved at.
+ quads = [[[0, 0], [1000, 0], [1000, 400], [0, 400]]]
+ fitted = stitch.fit_quads_to_canvas(quads, *stitch.canvas_for_layout(quads))[0]
+ assert fitted[1][0] - fitted[0][0] == pytest.approx(1000, abs=2)
+
+
+def test_canvas_for_layout_counts_source_pixels_per_solved_unit():
+ quads = [[[0, 0], [500, 0], [500, 200], [0, 200]]]
+ assert stitch.canvas_for_layout(quads, detail=3.0, margin=0.0) == (1500, 600)
+
+
+def test_canvas_for_layout_never_shrinks_the_canvas_it_was_given():
+ quads = [[[0, 0], [100, 0], [100, 50], [0, 50]]]
+ assert stitch.canvas_for_layout(quads, minimum=(1600, 800), margin=0.0) == (1600, 800)
+
+
+def test_canvas_for_layout_bounds_a_long_layout_by_its_side():
+ quads = [[[0, 0], [60000, 0], [60000, 20000], [0, 20000]]]
+ width, height = stitch.canvas_for_layout(quads, margin=0.0)
+ assert max(width, height) == stitch.MAX_CANVAS_DIM
+ # Both sides shrink together, so the clamped canvas still carries the shape.
+ assert width / height == pytest.approx(3.0, abs=0.01)
+
+
+def test_canvas_for_layout_bounds_a_layout_by_its_area():
+ quads = [[[0, 0], [8000, 0], [8000, 6000], [0, 6000]]]
+ width, height = stitch.canvas_for_layout(quads, margin=0.0)
+ assert width * height <= stitch.MAX_CANVAS_PIXELS
+ assert width / height == pytest.approx(8000 / 6000, abs=0.01)
+
+
+def test_canvas_for_layout_leaves_a_canvas_already_past_the_bounds_alone():
+ """The bounds hold what the solver asks for, not what the analyst set. A
+ canvas already past them is a resolution they chose, and a function whose job
+ is to grow one must never be the thing that shrinks it — the pieces already
+ on it would be scaled down with it."""
+ quads = [[[0, 0], [8000, 0], [8000, 6000], [0, 6000]]]
+ big = (8192, 8192) # 67 MP: what the compose route accepts, past the area bound
+
+ assert stitch.canvas_for_layout(quads, minimum=big, margin=0.0) == big
+
+
+def test_canvas_for_layout_handles_empty():
+ assert stitch.canvas_for_layout([], minimum=(320, 240)) == (320, 240)
+
+
def test_quad_ok_accepts_a_plain_rectangle():
assert stitch.quad_ok([[0, 0], [10, 0], [10, 10], [0, 10]])
@@ -147,10 +200,26 @@ def test_solve_layout_places_pieces_inside_the_canvas():
solved = stitch.solve_layout(pieces, width=1000, height=800)
+ canvas = solved["canvas"]
for quad in solved["quads"].values():
for x, y in quad:
- assert -1 <= x <= 1001
- assert -1 <= y <= 801
+ assert -1 <= x <= canvas["width"] + 1
+ assert -1 <= y <= canvas["height"] + 1
+
+
+def test_solve_layout_grows_the_canvas_rather_than_shrinking_the_pieces():
+ # The canvas the caller has is smaller than one piece. Fitting the stitch into
+ # it would throw away most of the pixels it was solved from, so the answer
+ # comes back on a canvas that holds the layout at its own scale instead.
+ scene = _scene(seed=13)
+ pieces = [scene.crop((0, 0, 500, 500)), scene.crop((300, 0, 800, 500))]
+
+ solved = stitch.solve_layout(pieces, width=240, height=200)
+
+ canvas = solved["canvas"]
+ assert canvas["width"] > 240 and canvas["height"] > 200
+ widths = [quad[1][0] - quad[0][0] for quad in solved["quads"].values()]
+ assert max(widths) == pytest.approx(500, rel=0.05)
def test_solve_layout_drops_a_piece_that_matches_nothing():
@@ -215,10 +284,30 @@ def test_rotation_layout_orders_pieces_along_the_pan():
def test_rotation_layout_places_pieces_inside_the_canvas():
solved = stitch.solve_rotation_layout(_pan([-20, 0, 20]), width=1000, height=800)
+ canvas = solved["canvas"]
for quad in solved["quads"].values():
for x, y in quad:
- assert -1 <= x <= 1001
- assert -1 <= y <= 801
+ assert -1 <= x <= canvas["width"] + 1
+ assert -1 <= y <= canvas["height"] + 1
+
+
+def test_rotation_layout_sizes_the_canvas_in_source_pixels():
+ """The rotation model solves on a 1000px work copy of every piece, so its
+ geometry has to be read back up to the source before the canvas is sized —
+ otherwise the same pan filmed in 4K would come back at the same detail as a
+ thumbnail of it. Three times the pixels in, three times the canvas out."""
+ small = _pan([-20, 0, 20])
+ big = [v.resize((v.width * 3, v.height * 3)) for v in small]
+
+ # A canvas at the floor, so the answer is the layout's own size and nothing else.
+ coarse = stitch.solve_rotation_layout(small, width=16, height=16)
+ fine = stitch.solve_rotation_layout(big, width=16, height=16)
+
+ assert fine["canvas"]["width"] == pytest.approx(3 * coarse["canvas"]["width"], rel=0.05)
+ assert fine["canvas"]["height"] == pytest.approx(3 * coarse["canvas"]["height"], rel=0.05)
+ # And the pan is worth more than the collage's default canvas, which is the
+ # size it used to be squeezed into.
+ assert fine["canvas"]["width"] > 1600
def test_rotation_layout_returns_a_remap_per_placed_piece():
diff --git a/tests/test_workspace_api.py b/tests/test_workspace_api.py
index c15a1c0..fd42d96 100644
--- a/tests/test_workspace_api.py
+++ b/tests/test_workspace_api.py
@@ -111,7 +111,7 @@ def test_using_a_folder_switches_without_moving_anything(pointed_client, tmp_pat
assert body["root"] == str(fresh)
assert body["cases"] == 0
- assert (root / "harbour-survey").is_dir()
+ assert (root / "Harbour survey").is_dir()
assert client.get("/api/cases").json() == []
diff --git a/tests/test_workspace_move.py b/tests/test_workspace_move.py
index af941c7..41ffa32 100644
--- a/tests/test_workspace_move.py
+++ b/tests/test_workspace_move.py
@@ -245,7 +245,7 @@ def test_adopting_an_empty_folder_leaves_the_old_cases_where_they_are(workspace,
assert config.workspace_root() == fresh
assert Case.list_all() == []
- assert (workspace / "harbour-survey").is_dir()
+ assert (workspace / "Harbour survey").is_dir()
def test_adopting_creates_the_skeleton_and_keeps_the_workspace_private(workspace, tmp_path):
@@ -283,7 +283,7 @@ def test_a_move_copies_verifies_switches_and_keeps_the_old_folder(workspace, tmp
assert config.workspace_root() == target
assert config.read_pointer() == target
assert [row["name"] for row in Case.list_all()] == ["Harbour survey"]
- assert (target / "harbour-survey" / "analyst-notes.txt").read_text(encoding="utf-8") == "mine"
+ assert (target / "Harbour survey" / "analyst-notes.txt").read_text(encoding="utf-8") == "mine"
assert Path(move["kept_aside"]).is_dir()
assert not workspace.exists()
@@ -295,7 +295,7 @@ def test_the_old_folder_is_kept_complete_until_the_analyst_drops_it(workspace, t
move = _finish()
kept = Path(move["kept_aside"])
- assert (kept / "harbour-survey" / "azimut" / "case.json").is_file()
+ assert (kept / "Harbour survey" / "azimut" / "case.json").is_file()
removed = workspacemove.discard_old()
@@ -365,7 +365,7 @@ def test_a_move_carries_the_empty_directories_a_case_is_born_with(workspace, tmp
workspacemove.start(str(target))
_finish()
- moved = target / "harbour-survey"
+ moved = target / "Harbour survey"
assert sorted(d for d in born if (moved / d).is_dir()) == born
assert (target / ".azimut" / "bundles").is_dir()
@@ -383,7 +383,7 @@ def test_a_move_rebuilds_the_hidden_directories_hidden(workspace, tmp_path, monk
workspacemove.start(str(tmp_path / "elsewhere"))
_finish()
- staged = {path for path in hidden if "harbour-survey" in path.parts}
+ staged = {path for path in hidden if "Harbour survey" in path.parts}
assert {path.name for path in staged} >= {layout.DATA_DIR, layout.INSPECT_DIR}
@@ -513,7 +513,7 @@ def test_a_kill_at_any_step_leaves_a_complete_workspace(workspace, tmp_path, kil
assert root.is_dir(), "startup would have nothing to open"
assert [row["name"] for row in Case.list_all()] == ["Harbour survey"]
- notes = root / "harbour-survey" / "analyst-notes.txt"
+ notes = root / "Harbour survey" / "analyst-notes.txt"
assert notes.read_text(encoding="utf-8") == "mine"
assert config.settings_path().is_file()
@@ -535,7 +535,7 @@ def test_nothing_is_removed_before_the_copy_is_verified(workspace, tmp_path, kil
finally:
workqueue.start_workers = resume
- assert (workspace / "harbour-survey" / "azimut" / "case.json").is_file()
+ assert (workspace / "Harbour survey" / "azimut" / "case.json").is_file()
assert config.read_pointer() == workspace
@@ -568,7 +568,7 @@ def test_a_half_copy_left_by_a_kill_is_discarded_by_the_next_attempt(workspace,
assert not move["error"]
assert not (target / "half-written.bin").exists()
- assert (target / "harbour-survey" / "azimut" / "case.json").is_file()
+ assert (target / "Harbour survey" / "azimut" / "case.json").is_file()
def test_a_move_interrupted_between_the_rename_and_the_pointer_keeps_both_folders(
@@ -595,5 +595,5 @@ def test_a_move_interrupted_between_the_rename_and_the_pointer_keeps_both_folder
config.forget_workspace_root()
assert config.workspace_root() == workspace
- assert (workspace / "harbour-survey" / "azimut" / "case.json").is_file()
- assert (target / "harbour-survey" / "azimut" / "case.json").is_file()
+ assert (workspace / "Harbour survey" / "azimut" / "case.json").is_file()
+ assert (target / "Harbour survey" / "azimut" / "case.json").is_file()