The OSINT investigator's workbench. One case, one folder, every tool. Local-first: your media and your investigations never leave your machine.
JavaScript
Name a saved frame after its video's title, timecode first (#42)
OsintMeThat58ef3f154120
diff --git a/docs/SPEC.md b/docs/SPEC.mdindex cd88912..9f74c66 100644--- a/docs/SPEC.md+++ b/docs/SPEC.md@@ -139,10 +139,14 @@ Each version delivers one complete daily workflow. Firm ideas move here from|------|--------------|| **Case Board / Relations** | Browses, creates and merges entities; graph view over the schema filled since v1, on the shipped relation vocabulary. || **Case Sheet** | The same case as a table: a row is an entity, columns are its attributes plus free ones the analyst adds, sorted, filtered and edited in place. Imports a CSV as loose rows that stay out of the graph until promoted, and exports back to CSV or GeoJSON. |-| **Camera Resection (GCP)** | Marks matching points photo↔map, then solves camera position, viewing azimuth and rough FOV (OpenCV `solvePnP`) and saves the match as evidence. |+| **Camera Resection (GCP)** | Marks matching points photo↔map, then solves camera position, viewing azimuth and rough FOV (OpenCV `solvePnP`) and saves the match as evidence. Its photo canvas and pixel↔angle camera frame are built for two callers: Sky Clock fills the same frame by hand. || **Command palette** | Ctrl+K reaches a tool, a case or an artifact. |-| **Sun, moon and local time** | Sunrise/sunset, solar and lunar azimuth, moon phase and bright-limb angle for a point and date, in Coordinates, each time in civil local time and UTC. Polar day/night and days with no moonrise are states, not errors; the moon needs topocentric parallax and sampled rise/set, and civil time adds `timezonefinder` + `tzdata` to bundle. |+| **Sun, moon and local time** | Sunrise/sunset, solar and lunar azimuth, moon phase and bright-limb angle for a point and date, in Coordinates, each time in civil local time and UTC, plus a day chart of elevation against time and the two azimuths drawn as rays from the map marker. Polar day/night and days with no moonrise are states, not errors; the moon needs topocentric parallax and sampled rise/set, and civil time adds `timezonefinder` + `tzdata` to bundle. || **Capture scale and north** | Preference-controlled scale bar, north arrow and graticule on app and extension captures. |+| **Notes to PDF** | Ticks notes in a dialog and writes them to the case's `exports/`, either one file per note or a single paginated document. The paginated form reuses the existing print path; per-note files need a generator that writes without a print dialog. |++Toward v2: a Settings-chosen workspace folder, once Azimut survives a user+editing or deleting case files under it.### v3: GEOINT expansion@@ -152,7 +156,7 @@ Each version delivers one complete daily workflow. Firm ideas move here from| **Image Compare** | Overlay two images with opacity, swipe and pixel diff. Assist satellite-to-screen alignment without presenting a verdict. || **Metadata follow-up** | Explains which common image/video fields were stripped and proposes events from capture times. || **Edit Provenance** | Reads a rendered video's own edit history: which source clips it was cut from, in what order, and the GPS, dates and cameras those clips still carry. |-| **Shadow Clock** | Mark a shadow to estimate possible capture times, and render the year as a day × hour heatmap of the slots that fit. |+| **Sky Clock** | Marks a shadow, the sun or the moon in an image or a video frame, with the horizon and north giving the angles, then renders the year as a day × hour heatmap of the slots that fit. A visible moon also carries phase and bright-limb angle, which usually cuts a year down to a few instants. || **Imagery Wayback** | Esri World Imagery archive as a date slider: one view across every published release, key-less. || **Event layers** | Date-stamped overlays that support or contradict an event: NASA FIRMS thermal hotspots, archived weather and METAR. || **Shot contact sheet** | Splits a video into shots (ffmpeg scene detection) and picks frames from a clickable grid of timecodes. |@@ -209,13 +213,29 @@ search; optional quota-aware X publishing.| **OSM Query (Overpass)** | Feature search from a form, and a described pattern ("filling station, roundabout, railway within 300 m") turned into candidates on the map; clicking a point looks it up in OSM, Wikidata and geolocated Commons photos. No Overpass QL. || **Viewshed / Line of Sight** | What terrain is visible from a point (public DEM tiles). || **Skyline Matching** | Trace a horizon in a photo, compare it against the DEM profile seen from candidate points. |+| **Camera Track (video SfM)** | Solves a moving camera's path from a video: frames sampled from a window, position and viewing azimuth per keyframe, and a sparse point cloud. Reports insufficient parallax instead of guessing. Bundles a native SfM binary (COLMAP/GLOMAP), CPU-capable. || **Vessel and Aircraft Tracks** | Historic ADS-B and AIS tracks on the map for a date, plus a watchlist that follows chosen callsigns or MMSIs. |-| **Map Measures** | Distance, bearing/azimuth, area, FOV cone; includes measure-on-imagery. |+| **Map Measures** | Distance, bearing/azimuth, area, FOV cone; includes measure-on-imagery, and its bearing layer absorbs the v2 sun/moon rays. || **Déjà Vu** | Perceptual-hash index flags recycled footage (local first; community index later). || **Manipulation Hints** | Add JPEG quantization, noise and AI-media hints alongside Inspect's ELA. || **Channel Monitor** | Watch Telegram channels, auto-archive media, queue for geolocation (rate limits, ToS care). |-Toward v5: real-world measurement from a resected photo and its GCP camera pose;+Camera Track rests on three facts, kept here so the tool can be scoped from the+spec alone:++- Parallax, not motion, is the requirement: a pan from a fixed point yields+ nothing, and rolling shutter or a re-encoded low bitrate breaks matching. The+ tool fails early and says why.+- SfM output is scale-free. Metres come only from an injected reference: the GCP+ camera pose from Camera Resection, or a known length. Every distance stays a+ labelled estimate.+- Photorealistic rendering stays external. The case exports a COLMAP-format+ folder for a WebGPU gaussian-splatting trainer, which needs no CUDA and so runs+ on all three shipped platforms, and reimports the result as an artifact with+ provenance.++Toward v5: real-world measurement from a resected photo or a solved camera track+and its GCP camera pose; a gaussian-splat round trip for a solved camera track;satellite-pass search from public TLEs.### After the MapLibre migrationdiff --git a/docs/UI.md b/docs/UI.mdindex ddcef08..6e08fa6 100644--- a/docs/UI.md+++ b/docs/UI.md@@ -20,7 +20,7 @@ in `frontend/src/lib/workspaces.js` and appear as tabs, never as new rail entrie| Workspace | Tools today | Future tools land here ||---|---|---|| **Sources** | Media Library, Files, Reverse Search | Channel Monitor, Evidence Locker |-| **Examine** | Inspect (Selection / Frame / Collage / Analyze) | Edit Provenance, Shot contact sheet, OCR, Image Compare, Hints, Shadow Clock, audio |+| **Examine** | Inspect (Selection / Frame / Collage / Analyze) | Edit Provenance, Shot contact sheet, OCR, Image Compare, Hints, Sky Clock, audio || **Map** | Satellite, Coordinates | **one map, many modes**: Compare, Imagery Wayback, Event layers, Ground Imagery, Measures, Viewshed, OSM Query, Map Board || **Compose** | Geo Proof, Geo Report, Notebook | Report Builder, GIF maker || *(Case)* | Sidebar | v2: Relations, Sheet; v4: Notes, Timeline; v5: Orchestrator |diff --git a/frontend/src/lib/inspect.js b/frontend/src/lib/inspect.jsindex 35ac0e8..cd00f77 100644--- a/frontend/src/lib/inspect.js+++ b/frontend/src/lib/inspect.js@@ -19,8 +19,20 @@ export const uid = (prefix = 'id') => `${prefix}_${Date.now().toString(36)}_${_s// What the user types at the Save gate becomes the media title *and* the stem of// the file on disk, so these defaults have to read as names, not placeholders.+/**+ * The name a savable inherits from what it was made out of.+ *+ * `title` is what the analyst called that media and what the library shows, so it+ * comes first: a frame cut from "Convoy dashcam" should read as that, not as the+ * download's own `convoy_dashcam_20240612-181455.mp4`. The filename and the path+ * are fallbacks for media nobody has titled.+ */export function sourceStem(source) {- const raw = source?.label || source?.filename || source?.path || '';+ // A title is already a name, so it is taken whole: stripping a trailing+ // extension off free text would cut "Convoy no. 3" down to "Convoy no".+ const title = String(source?.title ?? '').trim();+ if (title) return title;+ const raw = source?.filename || source?.path || '';const base = String(raw).split(/[\\/]/).pop() ?? '';return base.replace(/\.[^.]+$/, '') || 'Capture';}@@ -32,6 +44,44 @@ export function timecode(seconds) {return `${pad(Math.floor(t / 3600))}-${pad(Math.floor((t % 3600) / 60))}-${pad(t % 60)}`;}+/**+ * A captured frame's default name, timecode first.+ *+ * The timecode leads because these files end up side by side in a folder, where+ * sorting by name should walk the video in playback order. Trailing it sorted+ * frames from several videos into interleaved blocks instead. An edited still has+ * no timecode, so it keeps the source name up front.+ */+export function frameSaveName(stem, time) {+ return time == null ? `${stem} (edited)` : `${timecode(time)} ${stem}`;+}++/**+ * Default names for every frame in the tray, numbered only where they'd collide.+ *+ * Naming by the second reads best, but two frames grabbed a few tenths apart+ * round to one name. Those get a counter, and only those, so the common one+ * frame per second stays clean. Inside a second the counter follows playback+ * order rather than the order the tray was filled in, which keeps a name sort+ * walking the video forward even when frames were taken back to front.+ */+export function frameSaveNames(frames) {+ const key = (f) => (f.time == null ? `edit ${f.stem}` : `${timecode(f.time)} ${f.stem}`);+ const groups = new Map();+ frames.forEach((f, i) => {+ const k = key(f);+ if (!groups.has(k)) groups.set(k, []);+ groups.get(k).push(i);+ });+ const counter = frames.map(() => '');+ for (const members of groups.values()) {+ if (members.length < 2) continue;+ const byTime = [...members].sort((a, b) => (frames[a].time ?? 0) - (frames[b].time ?? 0));+ byTime.forEach((index, rank) => { counter[index] = ` ${rank + 1}`; });+ }+ return frames.map((f, i) => `${frameSaveName(f.stem, f.time)}${counter[i]}`);+}+/*** The name every savable starts out holding, before anyone edits it.*diff --git a/frontend/src/lib/inspect.test.js b/frontend/src/lib/inspect.test.jsindex d09b284..d8d47cd 100644--- a/frontend/src/lib/inspect.test.js+++ b/frontend/src/lib/inspect.test.js@@ -4,7 +4,7 @@ import {QUAD_SIDES, quadEdgeMidpoints, moveQuadEdge, quadCentroid,quadsBounds, translateQuad, moveQuads, rotateQuads, scaleQuads, pinholeOps,buildFrameOps, hasVideoEdits, normalizeRightAngleRotation, rotationOps,- sourceStem, timecode, autoSaveNames, saveNameOf,+ sourceStem, timecode, frameSaveName, frameSaveNames, autoSaveNames, saveNameOf,} from './inspect.js';const near = (a, b, eps = 1e-6) => Math.abs(a - b) < eps;@@ -308,11 +308,24 @@ describe('scaleQuads — the block grows as one', () => {describe('sourceStem', () => {it('prefers the title, then the filename, then the path', () => {- expect(sourceStem({ label: 'Hangar clip', filename: 'dsc_1.mp4' })).toBe('Hangar clip');+ expect(sourceStem({ title: 'Hangar clip', filename: 'dsc_1.mp4' })).toBe('Hangar clip');expect(sourceStem({ filename: 'dsc_1.mp4', path: 'media/dsc_1.mp4' })).toBe('dsc_1');expect(sourceStem({ path: 'media/sub/roof.png' })).toBe('roof');});+ it('reads the title the analyst gave a download, not what the site called the file', () => {+ expect(sourceStem({ title: 'Convoy dashcam', filename: 'convoy_dashcam_20240612-181455.mp4' }))+ .toBe('Convoy dashcam');+ });++ it('takes a title whole, since free text has no extension to strip', () => {+ expect(sourceStem({ title: 'Convoy no. 3', filename: 'x.mp4' })).toBe('Convoy no. 3');+ });++ it('ignores a blank title rather than naming the frame Capture', () => {+ expect(sourceStem({ title: ' ', filename: 'dsc_1.mp4' })).toBe('dsc_1');+ });+it('strips only the extension, keeping dots inside the name', () => {expect(sourceStem({ filename: 'v1.2 roof.png' })).toBe('v1.2 roof');});@@ -341,14 +354,93 @@ describe('timecode', () => {});});+describe('frameSaveName', () => {+ it('leads with the timecode so a folder of frames sorts in playback order', () => {+ expect(frameSaveName('roof', 19)).toBe('00-00-19 roof');+ expect(frameSaveName('roof', 3725)).toBe('01-02-05 roof');+ });++ it('sorts a video in playback order rather than by however the frames were taken', () => {+ const taken = [90, 12, 3600];+ const names = taken.map((t) => frameSaveName('roof', t));+ expect([...names].sort()).toEqual(['00-00-12 roof', '00-01-30 roof', '01-00-00 roof']);+ });++ it('keeps the source name up front for an edited still, which has no timecode', () => {+ expect(frameSaveName('roof', null)).toBe('roof (edited)');+ expect(frameSaveName('roof', undefined)).toBe('roof (edited)');+ });++ it('names the first frame of a video rather than dropping a zero timecode', () => {+ expect(frameSaveName('roof', 0)).toBe('00-00-00 roof');+ });+});++describe('frameSaveNames', () => {+ const names = (frames) => frameSaveNames(frames);++ it('names by the second while no two frames share one', () => {+ expect(names([{ stem: 'roof', time: 12 }, { stem: 'roof', time: 90 }]))+ .toEqual(['00-00-12 roof', '00-01-30 roof']);+ });++ it('numbers the frames that would collide, and only those', () => {+ expect(names([+ { stem: 'Convoy dashcam', time: 0 },+ { stem: 'Convoy dashcam', time: 1.1 },+ { stem: 'Convoy dashcam', time: 1.4 },+ { stem: 'Convoy dashcam', time: 21 },+ ])).toEqual([+ '00-00-00 Convoy dashcam',+ '00-00-01 Convoy dashcam 1',+ '00-00-01 Convoy dashcam 2',+ '00-00-21 Convoy dashcam',+ ]);+ });++ it('numbers a shared second in playback order, not tray order', () => {+ expect(names([{ stem: 'roof', time: 19.4 }, { stem: 'roof', time: 19.1 }]))+ .toEqual(['00-00-19 roof 2', '00-00-19 roof 1']);+ });++ it('keeps a name sort walking the video forward', () => {+ const out = names([+ { stem: 'roof', time: 19.4 },+ { stem: 'roof', time: 12 },+ { stem: 'roof', time: 19.1 },+ ]);+ expect([...out].sort()).toEqual(['00-00-12 roof', '00-00-19 roof 1', '00-00-19 roof 2']);+ });++ it('reads the same second across two sources as two different names', () => {+ expect(names([{ stem: 'roof', time: 19.1 }, { stem: 'street', time: 19.4 }]))+ .toEqual(['00-00-19 roof', '00-00-19 street']);+ });++ it('numbers two edits of one still, which carry no timecode at all', () => {+ expect(names([{ stem: 'roof', time: null }, { stem: 'roof', time: null }]))+ .toEqual(['roof (edited) 1', 'roof (edited) 2']);+ });++ it('numbers frames that sit in the same thousandth rather than naming both alike', () => {+ const out = names([{ stem: 'roof', time: 19.001 }, { stem: 'roof', time: 19.004 }]);+ expect(out).toEqual(['00-00-19 roof 1', '00-00-19 roof 2']);+ expect(new Set(out).size).toBe(2);+ });++ it('holds a tray of one frame to the plain second', () => {+ expect(names([{ stem: 'roof', time: 19.4 }])).toEqual(['00-00-19 roof']);+ });+});+describe('autoSaveNames', () => {const items = [- { key: 'a', defaultName: 'roof 00-01-00' },- { key: 'b', defaultName: 'roof 00-02-00' },+ { key: 'a', defaultName: '00-01-00 roof' },+ { key: 'b', defaultName: '00-02-00 roof' },];it('starts every field on the item default', () => {- expect(autoSaveNames(items)).toEqual(['roof 00-01-00', 'roof 00-02-00']);+ expect(autoSaveNames(items)).toEqual(['00-01-00 roof', '00-02-00 roof']);});it('numbers the gallery under a base name', () => {@@ -365,12 +457,12 @@ describe('autoSaveNames', () => {});it('ignores a whitespace-only base name', () => {- expect(autoSaveNames(items, ' ')).toEqual(['roof 00-01-00', 'roof 00-02-00']);+ expect(autoSaveNames(items, ' ')).toEqual(['00-01-00 roof', '00-02-00 roof']);});});describe('saveNameOf', () => {- const item = { key: 'a', defaultName: 'roof 00-01-00' };+ const item = { key: 'a', defaultName: '00-01-00 roof' };it('files under what stands in the field', () => {expect(saveNameOf(item, 'Front door')).toBe('Front door');@@ -381,8 +473,8 @@ describe('saveNameOf', () => {});it('falls back to the default rather than filing something nameless', () => {- expect(saveNameOf(item, ' ')).toBe('roof 00-01-00');- expect(saveNameOf(item, '')).toBe('roof 00-01-00');- expect(saveNameOf(item)).toBe('roof 00-01-00');+ expect(saveNameOf(item, ' ')).toBe('00-01-00 roof');+ expect(saveNameOf(item, '')).toBe('00-01-00 roof');+ expect(saveNameOf(item)).toBe('00-01-00 roof');});});diff --git a/frontend/src/tools/Inspector.svelte b/frontend/src/tools/Inspector.svelteindex acb494d..a108f9b 100644--- a/frontend/src/tools/Inspector.svelte+++ b/frontend/src/tools/Inspector.svelte@@ -6,7 +6,7 @@import {adjustDefaults, buildFrameOps, previewStyle, uid, videoSeed, initialQuad, VIDEO_ADJUST_IDS,collageBounds, quadFromCropRect, cropImgStyle, cropAspect, styleText, hasVideoEdits,- normalizeRightAngleRotation, rotationOps, sourceStem, timecode, autoSaveNames, saveNameOf,+ normalizeRightAngleRotation, rotationOps, sourceStem, frameSaveNames, autoSaveNames, saveNameOf,} from '../lib/inspect.js';import { isDefaultName, nextName, savedSlugs, savedTitles, savedTitle, slugify } from '../lib/naming.js';import { createHistory } from '../lib/history.js';@@ -249,10 +249,17 @@[videoPreview.transform, videoRotation ? `rotate(${videoRotation}deg)` : ''].filter(Boolean).join(' '));+ // A frame carries the path it was cut from and nothing else, so the title has+ // to be looked back up: without this, every frame of a downloaded video is named+ // after the download's filename instead of what the analyst called it.+ const titleByPath = $derived(new Map(mediaList.map((m) => [m.path, m.title])));+ const stemFor = (path, item = null) =>+ sourceStem({ ...item, path, title: titleByPath.get(path) ?? item?.title });+const savables = $derived.by(() => {const out = [];const cid = caseState.current?.id;- const stem = sourceStem(session.source);+ const stem = stemFor(session.source?.path, session.source);if (session.source?.kind === 'video' && hasVideoEdits(videoFilters, session.videoAdjust, videoRotation)) {const t = session.source.thumbnail ? `/files/${cid}/${session.source.thumbnail}` : null;out.push({@@ -261,11 +268,15 @@saved: !!session.saved.video,});}- for (const fr of session.frames) {- const frameStem = sourceStem({ path: fr.path }) || stem;+ // Named as a set, not one by one: a frame only needs sub-second digits when+ // another frame in the tray lands in the same second.+ const frameNames = frameSaveNames(+ session.frames.map((fr) => ({ stem: stemFor(fr.path), time: fr.time })),+ );+ for (const [i, fr] of session.frames.entries()) {out.push({key: `frame:${fr.id}`, kind: 'frame', frame: fr, thumb: fr.url,- defaultName: fr.time == null ? `${frameStem} (edited)` : `${frameStem} ${timecode(fr.time)}`,+ defaultName: frameNames[i],filter: previewStyle(filters, fr.adjust).filter,saved: !!session.saved[`frame:${fr.id}`],});diff --git a/frontend/src/tools/Inspector.test.js b/frontend/src/tools/Inspector.test.jsindex 36dcd7d..8bebe08 100644--- a/frontend/src/tools/Inspector.test.js+++ b/frontend/src/tools/Inspector.test.js@@ -115,13 +115,19 @@ describe('Inspect sessions', () => {it('names each savable after its source instead of Image 1', () => {expect(source).toContain('defaultName: `${stem} (enhanced)`');- expect(source).toContain(- "defaultName: fr.time == null ? `${frameStem} (edited)` : `${frameStem} ${timecode(fr.time)}`"- );+ expect(source).toContain('defaultName: frameNames[i]');+ expect(source).toContain('const frameNames = frameSaveNames(');expect(source).not.toContain('label: `Image ${imgN}`');expect(source).not.toContain("label: 'Video 1'");});+ it('names a frame after its media title, which only its path can reach', () => {+ expect(source).toContain('const titleByPath = $derived(new Map(mediaList.map((m) => [m.path, m.title])))');+ expect(source).toContain('stem: stemFor(fr.path)');+ // the old shape read the file on disk and could never see a title+ expect(source).not.toContain('sourceStem({ path: fr.path })');+ });+it('keeps typed names outside the derived list so a slider move cannot wipe them', () => {expect(source).toContain("const saveUi = $state({ selected: {}, folder: '', names: {}, touched: {}, baseName: '', note: '' });"diff --git a/src/azimut/engine/inspect.py b/src/azimut/engine/inspect.pyindex 9979a9e..f9776ec 100644--- a/src/azimut/engine/inspect.py+++ b/src/azimut/engine/inspect.py@@ -466,10 +466,13 @@ def _stamp() -> str:def _name_stem(label: str | None, fallback: str) -> str:"""Filename stem for a filed item: the name the user typed, else the source's.+ The typed name is kept as typed, spaces included, so the file in the folder+ reads as the same thing the Media Library shows. Uploads have always kept+ their spaces, so nothing downstream is surprised by one.``media_engine.safe_filename`` still scrubs what comes out of here, so this- only has to fold whitespace and keep the stem short enough to read.+ only has to collapse runs of whitespace and keep the stem short enough to read."""- stem = re.sub(r"\s+", "_", (label or "").strip())+ stem = re.sub(r"\s+", " ", (label or "").strip())return stem[:60] if stem else fallback[:40]@@ -664,9 +667,12 @@ def save_frame(tag, op = f"_t{time_s:.2f}s", "frame"else:tag, op = "_edit", "adjust"- # A named item keeps its name on disk; the timecode tag only makes sense on- # the fallback stem, where nothing else says which instant this is.- name = f"{stem}{'' if label else tag}_{_stamp()}.png"+ # A named item keeps its name on disk, and nothing else: the tray already+ # spells the instant into the name it sends, and `unique_path` settles a+ # collision, so a wall-clock stamp would only clutter the folder the analyst+ # opens. The timecode tag stands in on the fallback stem, where nothing else+ # says which instant this is.+ name = f"{stem}{'' if label else tag}.png"source = _derivation(rel_path, _source_sha(case, rel_path), op=op,**({"time": round(time_s, 3)} if time_s is not None else {}),@@ -806,7 +812,7 @@ def compose_perspective(case, width=width, height=height, nodes=nodes, background=background)source = _derivation("", None, op="collage", sources=sources, perspective=True)- name = f"{_name_stem(label, 'collage')}_{_stamp()}.png"+ name = f"{_name_stem(label, 'collage')}.png"result = media_engine.import_image(case, canvas, name, source, by="inspect")_apply_meta(case, result, label=label, folder=folder, notes=notes)return result@@ -933,7 +939,7 @@ def enhance_video(raise RuntimeError((proc.stderr or b"").decode("utf-8", "replace").strip() or "video enhance failed")- name = f"{stem}{'' if label else '_enhanced'}_{_stamp()}.mp4"+ name = f"{stem}{'' if label else '_enhanced'}.mp4"source = _derivation(video_rel, _source_sha(case, video_rel), op="enhance-video",params=params, rotation=rotation,diff --git a/src/azimut/engine/media.py b/src/azimut/engine/media.pyindex ac7d404..8512872 100644--- a/src/azimut/engine/media.py+++ b/src/azimut/engine/media.py@@ -137,9 +137,21 @@ def media_kind(filename: str) -> str:return "file"+# Windows refuses these as a filename whatever the extension follows, and a case+# folder has to open on all three platforms: an item someone titles "AUX" files+# happily on Linux and then breaks the copy opened on Windows.+_WINDOWS_RESERVED = frozenset(+ ["con", "prn", "aux", "nul"]+ + [f"com{n}" for n in range(1, 10)]+ + [f"lpt{n}" for n in range(1, 10)]+)++def safe_filename(name: str) -> str:name = Path(name).name # strip any path componentname = re.sub(r"[^\w.\- ]+", "_", name).strip(" .") or "file"+ if name.split(".", 1)[0].lower() in _WINDOWS_RESERVED:+ name = f"_{name}"return name[:150]diff --git a/tests/test_inspect_api.py b/tests/test_inspect_api.pyindex 7d5690d..7d66f8f 100644--- a/tests/test_inspect_api.py+++ b/tests/test_inspect_api.py@@ -290,6 +290,44 @@ def test_save_frames_files_selected_images_into_folder(client):assert entity["provenance"]["by"] == "inspect"+def test_saved_frame_is_filed_under_its_name_alone(client):+ """The tray's name is the filename: no wall-clock stamp trailing it.++ The name the tray sends already carries the timecode, and the analyst reads+ these files in a folder outside the app, so anything else added here is noise.+ """+ cid = client.post("/api/cases", json={"name": "Named"}).json()["id"]+ item = _upload(client, cid, "orig.png")++ res = client.post(+ f"/api/cases/{cid}/inspect/save-frames",+ json={"items": [{"path": item["path"],+ "ops": [{"op": "brightness", "params": {"amount": 1.5}}],+ "label": "00-00-19 Convoy dashcam"}]},+ ).json()++ assert res["saved"][0]["item"]["path"] == "media/00-00-19 Convoy dashcam.png"+++def test_two_frames_saved_under_one_name_keep_both_files(client):+ """Dropping the stamp must not let the second save land on the first."""+ cid = client.post("/api/cases", json={"name": "Twice"}).json()["id"]+ item = _upload(client, cid, "orig.png")++ paths = []+ for amount in (1.5, 0.5): # different pixels, so neither is deduped away+ res = client.post(+ f"/api/cases/{cid}/inspect/save-frames",+ json={"items": [{"path": item["path"],+ "ops": [{"op": "brightness", "params": {"amount": amount}}],+ "label": "00-00-19 Convoy dashcam"}]},+ ).json()+ paths.append(res["saved"][0]["item"]["path"])++ assert paths == ["media/00-00-19 Convoy dashcam.png", "media/00-00-19 Convoy dashcam-1.png"]+ assert len({m["path"] for m in client.get(f"/api/cases/{cid}/media").json()}) == 3++def test_compose_perspective_files_one_collage(client):cid = client.post("/api/cases", json={"name": "Compose"}).json()["id"]a = _upload(client, cid, "a.png", _png_bytes(color=(10, 20, 30), size=(80, 60)))@@ -983,7 +1021,7 @@ def test_saved_frame_filename_follows_the_typed_name(client):).json()["saved"][0]name = res["item"]["path"].rsplit("/", 1)[-1]- assert name.startswith("Hangar_roof_") and name.endswith(".png")+ assert name == "Hangar roof.png"assert "dsc_00421" not in namemedia = next(@@ -1032,7 +1070,7 @@ def test_unnamed_frame_keeps_the_source_stem_and_tag(client):).json()["saved"][0]name = res["item"]["path"].rsplit("/", 1)[-1]- assert name.startswith("orig_edit_")+ assert name == "orig_edit.png"def test_composed_collage_filename_follows_the_typed_name(client):@@ -1053,7 +1091,7 @@ def test_composed_collage_filename_follows_the_typed_name(client):},).json()- assert res["item"]["path"].rsplit("/", 1)[-1].startswith("Yard_panorama_")+ assert res["item"]["path"].rsplit("/", 1)[-1] == "Yard panorama.png"media = next(m for m in client.get(f"/api/cases/{cid}/media").json()if m["path"] == res["item"]["path"]diff --git a/tests/test_media_api.py b/tests/test_media_api.pyindex d910416..3d8817a 100644--- a/tests/test_media_api.py+++ b/tests/test_media_api.py@@ -7,6 +7,8 @@ import timefrom PIL import Image+from azimut.engine.media import safe_filename+def _png_bytes(color=(200, 30, 30), size=(64, 48)) -> bytes:buf = io.BytesIO()@@ -20,6 +22,21 @@ def _upload(client, cid, name, data):)+def test_safe_filename_sidesteps_the_windows_device_names():+ """A name reserved by Windows cannot be created there, extension or not.++ Nothing stops an analyst titling a frame "AUX", and the file would land fine+ on Linux and macOS. The case folder is meant to be copied between the three,+ so the name is defused here rather than at whichever platform breaks.+ """+ assert safe_filename("AUX.png") == "_AUX.png"+ assert safe_filename("con.mp4") == "_con.mp4"+ assert safe_filename("COM1.roof.png") == "_COM1.roof.png"+ # only the exact device names, not anything starting with one+ assert safe_filename("console.png") == "console.png"+ assert safe_filename("aux room.png") == "aux room.png"++def test_upload_and_list(client):cid = client.post("/api/cases", json={"name": "Media"}).json()["id"]