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

M5: Inspect tool — frame extraction, adjustments, collage, analysis

OsintMeThat3e74b71ff05c
diff --git a/docs/SPEC.md b/docs/SPEC.md
index f028139..fba5fd5 100644
--- a/docs/SPEC.md
+++ b/docs/SPEC.md
@@ -145,10 +145,11 @@ get media in, annotate the match, publish the proof.
| Tab | What it does |
|-----|--------------|
-| **Media Library** | The case's media shelf. Import local files (drag & drop) or download by URL (X, Telegram, TikTok, YouTube, … via yt-dlp) → clean local file + metadata JSON + sha256. Every media becomes a `media` entity. |
-| **Satellite** | Enter/click coordinates: imagery crop centered on the point, crosshair marker, zoom control, provenance (provider, zoom, date, attribution) recorded — feeds the composer directly. XYZ tile-provider abstraction (see note below). |
+| **Media Library** | The case's media shelf. Import local files (drag & drop) or download by URL (X, Telegram, TikTok, YouTube, … via yt-dlp) → clean local file + metadata JSON + sha256. Every media becomes a `media` entity. Items can be assigned a **virtual folder** (stored in sidecar) and annotated with **notes**; an info modal surfaces full provenance (source URL, title, uploader, duration) + editable notes + folder; images show a **lightbox** on click. |
+| **Inspect** | Open any photo or video to extract and work on imagery. **Frames**: scrub a video, step frame-by-frame, one-click capture, or scan for the *sharpest* frames per time bin. **Adjust**: non-destructive brightness/contrast/saturation/gamma/sharpness/grayscale/invert/rotate + interactive **crop**, live-previewed then baked to a new image. **Collage**: tile several frames/images into one contact sheet. **Analyze**: histogram, EXIF/metadata, ELA (labeled a *hint*). Every output is filed as new case media with provenance back to its source, so it flows straight into the composer. Built on two self-describing registries (filters + analyses) so new mini-tools are one function to add. |
+| **Satellite** | Enter/click coordinates: imagery crop centered on the point, crosshair marker, zoom control, **map rotation** (turn the view off-north; capture matches the on-screen heading, bearing recorded in provenance), provenance (provider, zoom, date, bearing, attribution) recorded — feeds the composer directly. XYZ tile-provider abstraction (see note below). Captures support **editable notes** via inline modal. |
| **Proof Composer** | The heart of v1. Compose panels side by side (frames, photos, satellite crops, imported screenshots); draw colored boxes/ellipses/lines/arrows with the mouse — same color = same feature across panels; per-shape and per-panel **comments/captions**; numbered feature legend; layout rows; export `proof.png` + re-editable JSON spec saved in `proofs/`. |
-| **Post Composer** | Turn a proof into a publishable post, GeoConfirmed-style: coordinates in multiple formats, plus code, place name, imagery attribution, source credit, character count, thread splitting. Copy-paste ready — Ozimut never posts on your behalf. |
+| **Post Composer** | Build a GeoConfirmed-style thread from a proof. Tweet 1 = `Place - Plus code`, description, decimal coordinates (6 digits), `@GeoConfirmed` mention, source. Tweet 2 = optional media (Video / Image(s), removable), with media picked from the case library. Add extra context tweets; per-tweet character count; copy-per-tweet or copy-all. **Save drafts** (in `exports/`, reopenable from the sidebar as `post` entities) and **Publish** (copies the thread and opens X compose prefilled). Copy-paste ready — Ozimut never posts on your behalf. |
| **Case sidebar** | Always visible: case notes (`notes.md`), media list, saved proofs, entity list (simple list view). Create/open/promote cases. |
v1 notes:
@@ -169,14 +170,15 @@ v1 notes:
imagery, …) with a source/attribution field — built-in fetch and manual import
coexist.
- The previous frame-geolocator engine is **not** reused; v1 is a fresh,
- minimal implementation. Frame extraction from video is v2; in v1 you bring
- images (screenshots/exports) into the composer.
+ minimal implementation. Frame extraction and image adjustments ship in the
+ **Inspect** tab (above); v1 also lets you bring images (screenshots/exports)
+ into the composer directly.
### v2 — the GEOINT suite
| Tab | What it does |
|-----|--------------|
-| **Frame Extractor** | Drop a video: timeline scrubber, auto-suggested sharpest frames per time bin, one-click capture → frames land in the case and the composer. |
+| **Frame Extractor** | *Shipped early inside **Inspect** (§ v1)* — video scrubber, sharpest-frame suggestions, one-click capture into the case and composer. |
| **Satellite Compare** | Same coordinates across providers (Esri / Sentinel-2 with date slider / Bing / user-keyed providers), synchronized pan/zoom — imagery history and provider comparison. Builds on the v1 tile abstraction. |
| **Image Compare** | Overlay two images with opacity/swipe slider + pixel difference — frame vs satellite, or two imagery dates. |
| **Coordinates** | Convert DMS/decimal/MGRS/plus code/geohash; reverse geocode (Nominatim); quick-open links to Google Maps/Yandex/Bing/OSM. |
@@ -204,7 +206,7 @@ v1 notes:
| **Viewshed / Line of Sight** | From a point, what terrain is visible (public DEM tiles) — validate "can this ridge be seen from here?". |
| **Map Measures** | Distance, bearing/azimuth (the app's namesake), area, camera field-of-view cone on the map. |
| **Déjà Vu** | Perceptual-hash index of known/old clips — flags recycled footage. Local index first; optional community-shared index later. |
-| **Manipulation Hints** | ELA, JPEG quantization, noise inconsistencies — first-pass tampering indicators, honestly labeled as *hints*. |
+| **Manipulation Hints** | ELA (*shipped in Inspect*), JPEG quantization, noise inconsistencies — first-pass tampering indicators, honestly labeled as *hints*. |
| **Channel Monitor** | Watch Telegram channels/accounts, auto-archive media into the case, queue items for geolocation. (Needs care: rate limits, ToS.) |
### Explicit non-goals
diff --git a/frontend/package-lock.json b/frontend/package-lock.json
index 12eddac..1709a25 100644
--- a/frontend/package-lock.json
+++ b/frontend/package-lock.json
@@ -9,7 +9,8 @@
"version": "0.1.0",
"dependencies": {
"konva": "^9.3.0",
- "leaflet": "^1.9.4"
+ "leaflet": "^1.9.4",
+ "leaflet-rotate": "^0.2.8"
},
"devDependencies": {
"@sveltejs/vite-plugin-svelte": "^4.0.0",
@@ -1075,6 +1076,15 @@
"integrity": "sha512-nxS1ynzJOmOlHp+iL3FyWqK89GtNL8U8rvlMOsQdTTssxZwCXh8N2NB3GDQOL+YR3XnWyZAxwQixURb+FA74PA==",
"license": "BSD-2-Clause"
},
+ "node_modules/leaflet-rotate": {
+ "version": "0.2.8",
+ "resolved": "https://registry.npmjs.org/leaflet-rotate/-/leaflet-rotate-0.2.8.tgz",
+ "integrity": "sha512-BHtkn35DuJ377yBNn/7XVuV0oIfwJtmqv/wFQ0Lvh7QuVCAD2wfCK0/m9oA3k/LVOnJG8VEGyf3Duf/wTVzeKQ==",
+ "license": "GPL-3.0",
+ "peerDependencies": {
+ "leaflet": "^1.9.3"
+ }
+ },
"node_modules/locate-character": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/locate-character/-/locate-character-3.0.0.tgz",
diff --git a/frontend/package.json b/frontend/package.json
index b6fe3d3..f19e6d2 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -15,6 +15,7 @@
},
"dependencies": {
"konva": "^9.3.0",
- "leaflet": "^1.9.4"
+ "leaflet": "^1.9.4",
+ "leaflet-rotate": "^0.2.8"
}
}
diff --git a/frontend/src/App.svelte b/frontend/src/App.svelte
index 85fa4b9..2ee6c8e 100644
--- a/frontend/src/App.svelte
+++ b/frontend/src/App.svelte
@@ -1,5 +1,5 @@
<script>
- import { uiState, refreshCaseList } from './lib/state.svelte.js';
+ import { uiState, initSession } from './lib/state.svelte.js';
import Icon from './components/Icon.svelte';
import CaseSwitcher from './components/CaseSwitcher.svelte';
import CaseSidebar from './components/CaseSidebar.svelte';
@@ -8,9 +8,11 @@
import Satellite from './tools/Satellite.svelte';
import ProofComposer from './tools/ProofComposer.svelte';
import PostComposer from './tools/PostComposer.svelte';
+ import Inspector from './tools/Inspector.svelte';
const TOOLS = [
{ id: 'media', label: 'Media', icon: 'media', component: MediaLibrary },
+ { id: 'inspect', label: 'Inspect', icon: 'inspect', component: Inspector },
{ id: 'satellite', label: 'Satellite', icon: 'satellite', component: Satellite },
{ id: 'proof', label: 'Proof', icon: 'proof', component: ProofComposer },
{ id: 'post', label: 'Post', icon: 'post', component: PostComposer },
@@ -25,7 +27,8 @@
history.replaceState(null, '', `#${uiState.tool}`);
});
- refreshCaseList().catch(() => {});
+ // Load the case list and reopen the last-used case (survives reloads).
+ initSession().catch(() => {});
</script>
<div class="shell">
diff --git a/frontend/src/components/CaseSidebar.svelte b/frontend/src/components/CaseSidebar.svelte
index ccb0a3c..7fc1e9a 100644
--- a/frontend/src/components/CaseSidebar.svelte
+++ b/frontend/src/components/CaseSidebar.svelte
@@ -1,7 +1,8 @@
<script>
import { api } from '../lib/api.js';
- import { caseState, reloadCase, toast } from '../lib/state.svelte.js';
+ import { caseState, uiState, reloadCase, toast } from '../lib/state.svelte.js';
import Icon from './Icon.svelte';
+ import Modal from './Modal.svelte';
const ENTITY_ICONS = {
person: 'user',
@@ -14,37 +15,42 @@
event: 'clock',
media: 'image',
proof: 'proof',
+ post: 'post',
domain: 'globe',
ip: 'hash',
vehicle: 'grip',
note: 'note',
};
- let notes = $state('');
- let notesLoadedFor = $state(null);
+ // Tool to open when clicking a given entity type
+ const ENTITY_TOOL = { media: 'media', proof: 'proof', place: 'satellite', post: 'post' };
+
+ // ── case notes (single notes.md) ─────────────────────────────────────────
+ let caseNotes = $state('');
+ let caseNotesLoadedFor = $state(null);
let saveTimer;
let saved = $state(true);
- let section = $state({ notes: true, entities: true });
+ let section = $state({ notes: false, folders: true, entities: true });
$effect(() => {
const id = caseState.current?.id;
- if (id && id !== notesLoadedFor) {
- notesLoadedFor = id;
- api.get(`/api/cases/${id}/notes`).then((r) => (notes = r.text));
+ if (id && id !== caseNotesLoadedFor) {
+ caseNotesLoadedFor = id;
+ api.get(`/api/cases/${id}/notes`).then((r) => (caseNotes = r.text));
} else if (!id) {
- notesLoadedFor = null;
- notes = '';
+ caseNotesLoadedFor = null;
+ caseNotes = '';
}
});
- function onNotesInput() {
+ function onCaseNotesInput() {
saved = false;
clearTimeout(saveTimer);
const id = caseState.current?.id;
saveTimer = setTimeout(async () => {
if (!id) return;
try {
- await api.put(`/api/cases/${id}/notes`, { text: notes });
+ await api.put(`/api/cases/${id}/notes`, { text: caseNotes });
saved = true;
} catch (e) {
toast(`Notes not saved: ${e.message}`, 'danger');
@@ -52,6 +58,7 @@
}, 700);
}
+ // ── entities ─────────────────────────────────────────────────────────────
async function confirmEntity(entity) {
await api.patch(`/api/cases/${caseState.current.id}/entities/${entity.id}`, {
status: 'confirmed',
@@ -60,14 +67,221 @@
}
async function removeEntity(entity) {
+ if (!confirm(`Delete "${entity.label}"?`)) return;
await api.del(`/api/cases/${caseState.current.id}/entities/${entity.id}`);
await reloadCase();
- toast(`Removed “${entity.label}”`, 'info');
+ toast(`Removed "${entity.label}"`, 'info');
+ }
+
+ function openEntity(entity) {
+ if (entity.type === 'proof') {
+ // load the proof spec into the composer, then switch tab
+ const spec = entity.attrs?.spec ?? '';
+ const name = spec.replace(/^proofs\//, '').replace(/\.json$/, '');
+ if (name) uiState.openProof = name;
+ uiState.tool = 'proof';
+ return;
+ }
+ if (entity.type === 'post') {
+ // load the draft into the Post Composer, then switch tab
+ const draft = entity.attrs?.draft ?? '';
+ const name = draft.replace(/^exports\//, '').replace(/\.json$/, '');
+ if (name) uiState.openDraft = name;
+ uiState.tool = 'post';
+ return;
+ }
+ if (entity.type === 'place') {
+ // fly the Satellite map to the point, then switch tab
+ const lat = Number(entity.attrs?.lat);
+ const lon = Number(entity.attrs?.lon);
+ if (Number.isFinite(lat) && Number.isFinite(lon)) {
+ uiState.gotoCoords = { lat, lon };
+ }
+ uiState.tool = 'satellite';
+ return;
+ }
+ const tool = ENTITY_TOOL[entity.type];
+ if (tool) uiState.tool = tool;
}
const entities = $derived(caseState.current?.entities ?? []);
const suggested = $derived(entities.filter((e) => e.provenance?.status === 'suggested'));
const confirmed = $derived(entities.filter((e) => e.provenance?.status !== 'suggested'));
+
+ const folderOf = (e) => e.attrs?.folder || null;
+
+ // ── folders (managed here, drag & drop assignment) ────────────────────────
+ let folderFilter = $state(null); // null = all, '' = unfiled sentinel
+ let newFolder = $state('');
+ let dragEntityId = $state(null);
+ let dragOverFolder = $state(undefined); // folder name or '' (unfiled) being hovered
+
+ // known folders = persisted case folders ∪ folders in use on entities
+ const caseFolders = $derived(caseState.current?.folders ?? []);
+ const usedFolders = $derived(
+ [...new Set(entities.map(folderOf).filter(Boolean))]
+ );
+ const allFolders = $derived(
+ [...new Set([...caseFolders, ...usedFolders])].sort((a, b) =>
+ a.toLowerCase().localeCompare(b.toLowerCase())
+ )
+ );
+
+ const filteredConfirmed = $derived(
+ folderFilter === null
+ ? confirmed
+ : confirmed.filter((e) => (folderOf(e) ?? '') === folderFilter)
+ );
+ const filteredSuggested = $derived(
+ folderFilter === null || folderFilter === ''
+ ? suggested
+ : []
+ );
+
+ function countInFolder(f) {
+ return entities.filter((e) => (folderOf(e) ?? '') === f).length;
+ }
+
+ async function createFolder() {
+ const name = newFolder.trim();
+ if (!name) return;
+ newFolder = '';
+ try {
+ await api.post(`/api/cases/${caseState.current.id}/folders`, { name });
+ await reloadCase();
+ folderFilter = name;
+ } catch (e) {
+ toast(e.message, 'danger');
+ }
+ }
+
+ async function assignFolder(entity, folder) {
+ const val = folder || '';
+ try {
+ if (entity.type === 'media' && entity.attrs?.path) {
+ await api.patch(`/api/cases/${caseState.current.id}/media`, {
+ path: entity.attrs.path,
+ folder: val,
+ });
+ } else {
+ await api.patch(`/api/cases/${caseState.current.id}/entities/${entity.id}`, {
+ attrs: { folder: val },
+ });
+ }
+ await reloadCase();
+ } catch (e) {
+ toast(e.message, 'danger');
+ }
+ }
+
+ async function deleteFolder(f) {
+ if (!confirm(`Delete folder "${f}"? Items inside become unfiled.`)) return;
+ const inside = entities.filter((e) => folderOf(e) === f);
+ for (const e of inside) {
+ // clear each entity's folder (keeps media sidecars in sync)
+ if (e.type === 'media' && e.attrs?.path) {
+ await api.patch(`/api/cases/${caseState.current.id}/media`, {
+ path: e.attrs.path, folder: '',
+ });
+ } else {
+ await api.patch(`/api/cases/${caseState.current.id}/entities/${e.id}`, {
+ attrs: { folder: '' },
+ });
+ }
+ }
+ await api.del(`/api/cases/${caseState.current.id}/folders?name=${encodeURIComponent(f)}`);
+ await reloadCase();
+ if (folderFilter === f) folderFilter = null;
+ }
+
+ // drag & drop wiring
+ function onDragStart(ev, entity) {
+ dragEntityId = entity.id;
+ ev.dataTransfer.effectAllowed = 'move';
+ ev.dataTransfer.setData('text/plain', entity.id);
+ }
+ function onDropFolder(ev, folder) {
+ ev.preventDefault();
+ dragOverFolder = undefined;
+ const entity = entities.find((e) => e.id === dragEntityId);
+ dragEntityId = null;
+ if (entity) assignFolder(entity, folder);
+ }
+
+ // ── entity info modal (media details) ─────────────────────────────────────
+ let infoEntity = $state(null);
+ let infoData = $state(null); // resolved media listing item (or null)
+ let infoLoading = $state(false);
+
+ async function openInfo(entity) {
+ infoEntity = entity;
+ infoData = null;
+ if (entity.type === 'media' && entity.attrs?.path) {
+ infoLoading = true;
+ try {
+ const list = await api.get(`/api/cases/${caseState.current.id}/media`);
+ infoData = list.find((m) => m.path === entity.attrs.path) ?? null;
+ } catch {
+ infoData = null;
+ } finally {
+ infoLoading = false;
+ }
+ }
+ }
+
+ function fmtSize(bytes) {
+ if (bytes == null) return '';
+ if (bytes >= 1 << 30) return (bytes / (1 << 30)).toFixed(1) + ' GB';
+ if (bytes >= 1 << 20) return (bytes / (1 << 20)).toFixed(1) + ' MB';
+ if (bytes >= 1 << 10) return (bytes / (1 << 10)).toFixed(0) + ' KB';
+ return bytes + ' B';
+ }
+
+ // ── note entities ─────────────────────────────────────────────────────────
+ let noteModal = $state(null);
+ // shape: { entity: obj|null, title: string, folder: string, content: string }
+ let noteModalSaving = $state(false);
+
+ function openNewNote() {
+ noteModal = { entity: null, title: '', folder: folderFilter || '', content: '' };
+ }
+
+ function openEditNote(entity) {
+ noteModal = {
+ entity,
+ title: entity.label,
+ folder: entity.attrs?.folder ?? '',
+ content: entity.attrs?.content ?? '',
+ };
+ }
+
+ async function saveNote() {
+ if (!noteModal) return;
+ const { entity, title, folder, content } = noteModal;
+ if (!title.trim()) { toast('Title required', 'warn'); return; }
+ noteModalSaving = true;
+ try {
+ const attrs = { content, folder: folder.trim() };
+ if (!entity) {
+ await api.post(`/api/cases/${caseState.current.id}/entities`, {
+ type: 'note', label: title.trim(), attrs,
+ });
+ toast('Note created', 'ok', 1600);
+ } else {
+ await api.patch(`/api/cases/${caseState.current.id}/entities/${entity.id}`, {
+ label: title.trim(), attrs,
+ });
+ toast('Note saved', 'ok', 1600);
+ }
+ await reloadCase();
+ noteModal = null;
+ } catch (e) {
+ toast(e.message, 'danger');
+ } finally {
+ noteModalSaving = false;
+ }
+ }
+
</script>
<aside class="sidebar">
@@ -87,36 +301,125 @@
</div>
<div class="sections">
- <!-- Notes -->
+
+ <!-- Case Notes (single notes.md) -->
<button class="section-head" onclick={() => (section.notes = !section.notes)}>
<Icon name={section.notes ? 'chevronDown' : 'chevronRight'} size={13} />
- <span>Notes</span>
+ <span>Case Notes</span>
{#if !saved}<span class="badge">saving…</span>{/if}
</button>
{#if section.notes}
<textarea
class="textarea notes mono"
- bind:value={notes}
- oninput={onNotesInput}
+ bind:value={caseNotes}
+ oninput={onCaseNotesInput}
placeholder="Case notes (markdown)…"
></textarea>
{/if}
- <!-- Entities -->
- <button class="section-head" onclick={() => (section.entities = !section.entities)}>
- <Icon name={section.entities ? 'chevronDown' : 'chevronRight'} size={13} />
- <span>Entities</span>
- <span class="count">{entities.length}</span>
+ <!-- Folders -->
+ <button class="section-head" onclick={() => (section.folders = !section.folders)}>
+ <Icon name={section.folders ? 'chevronDown' : 'chevronRight'} size={13} />
+ <span>Folders</span>
+ <span class="count">{allFolders.length}</span>
</button>
+ {#if section.folders}
+ <form class="new-folder" onsubmit={(e) => { e.preventDefault(); createFolder(); }}>
+ <input class="input" placeholder="New folder…" bind:value={newFolder} />
+ <button class="btn btn-sm" type="submit" title="Create folder" disabled={!newFolder.trim()}>
+ <Icon name="plus" size={13} />
+ </button>
+ </form>
+
+ <div class="folder-list">
+ <!-- All -->
+ <button
+ class="frow"
+ class:active={folderFilter === null}
+ class:dropping={dragOverFolder === 'ALL_SENTINEL'}
+ onclick={() => (folderFilter = null)}
+ >
+ <Icon name="layers" size={13} />
+ <span class="fname">All items</span>
+ <span class="fcount">{entities.length}</span>
+ </button>
+
+ <!-- Unfiled (drop target to clear folder) -->
+ <button
+ class="frow"
+ class:active={folderFilter === ''}
+ class:dropping={dragOverFolder === ''}
+ ondragover={(e) => { e.preventDefault(); dragOverFolder = ''; }}
+ ondragleave={() => (dragOverFolder = undefined)}
+ ondrop={(e) => onDropFolder(e, '')}
+ onclick={() => (folderFilter = '')}
+ >
+ <Icon name="folder" size={13} />
+ <span class="fname">Unfiled</span>
+ <span class="fcount">{countInFolder('')}</span>
+ </button>
+
+ {#each allFolders as f (f)}
+ <button
+ class="frow"
+ class:active={folderFilter === f}
+ class:dropping={dragOverFolder === f}
+ ondragover={(e) => { e.preventDefault(); dragOverFolder = f; }}
+ ondragleave={() => (dragOverFolder = undefined)}
+ ondrop={(e) => onDropFolder(e, f)}
+ onclick={() => (folderFilter = f)}
+ >
+ <Icon name="folderOpen" size={13} />
+ <span class="fname">{f}</span>
+ <span class="fcount">{countInFolder(f)}</span>
+ <span
+ class="fdel"
+ role="button"
+ tabindex="0"
+ title="Delete folder"
+ onclick={(e) => { e.stopPropagation(); deleteFolder(f); }}
+ onkeydown={(e) => e.key === 'Enter' && (e.stopPropagation(), deleteFolder(f))}
+ >
+ <Icon name="trash" size={12} />
+ </span>
+ </button>
+ {/each}
+ </div>
+ <div class="hint">Drag an entity onto a folder to file it.</div>
+ {/if}
+
+ <!-- Entities -->
+ <div class="section-head-row">
+ <button class="section-head" onclick={() => (section.entities = !section.entities)}>
+ <Icon name={section.entities ? 'chevronDown' : 'chevronRight'} size={13} />
+ <span>Entities</span>
+ <span class="count">{entities.length}</span>
+ </button>
+ <button class="btn btn-ghost btn-sm new-note-btn" title="New note" onclick={openNewNote}>
+ <Icon name="plus" size={13} /><Icon name="note" size={13} />
+ </button>
+ </div>
+
{#if section.entities}
- {#if suggested.length}
- <div class="suggest-note">Suggested by tools — confirm or dismiss:</div>
- {#each suggested as e (e.id)}
+ {#if folderFilter !== null}
+ <div class="active-folder">
+ <Icon name={folderFilter === '' ? 'folder' : 'folderOpen'} size={12} />
+ <span>{folderFilter === '' ? 'Unfiled' : folderFilter}</span>
+ <button class="clear-filter" onclick={() => (folderFilter = null)} title="Clear filter">
+ <Icon name="x" size={12} />
+ </button>
+ </div>
+ {/if}
+
+ <!-- suggested entities -->
+ {#if filteredSuggested.length > 0}
+ <div class="suggest-note">Suggested — confirm or dismiss:</div>
+ {#each filteredSuggested as e (e.id)}
<div class="entity suggested">
<Icon name={ENTITY_ICONS[e.type] ?? 'note'} size={14} />
<div class="e-body">
<span class="e-label">{e.label}</span>
- <span class="e-type">{e.type} · by {e.provenance?.by}</span>
+ <span class="e-meta">{e.type} · {e.provenance?.by}</span>
</div>
<button class="btn btn-ghost btn-sm" title="Confirm" onclick={() => confirmEntity(e)}>
<Icon name="check" size={13} />
@@ -127,27 +430,195 @@
</div>
{/each}
{/if}
- {#each confirmed as e (e.id)}
- <div class="entity">
+
+ <!-- confirmed entities -->
+ {#each filteredConfirmed as e (e.id)}
+ {@const isClickable = e.type === 'note' || !!ENTITY_TOOL[e.type]}
+ <div
+ class="entity"
+ class:clickable={isClickable}
+ class:dragging={dragEntityId === e.id}
+ draggable="true"
+ ondragstart={(ev) => onDragStart(ev, e)}
+ ondragend={() => { dragEntityId = null; dragOverFolder = undefined; }}
+ onclick={() => (e.type === 'note' ? openEditNote(e) : openEntity(e))}
+ role={isClickable ? 'button' : undefined}
+ tabindex={isClickable ? 0 : undefined}
+ onkeydown={(ev) => ev.key === 'Enter' && (e.type === 'note' ? openEditNote(e) : openEntity(e))}
+ >
+ <Icon name="grip" size={13} />
<Icon name={ENTITY_ICONS[e.type] ?? 'note'} size={14} />
<div class="e-body">
<span class="e-label">{e.label}</span>
- <span class="e-type">{e.type}</span>
+ <span class="e-meta">
+ {e.type}
+ {#if folderOf(e)}· <Icon name="folder" size={10} />{folderOf(e)}{/if}
+ </span>
</div>
- <button class="btn btn-ghost btn-sm del" title="Delete" onclick={() => removeEntity(e)}>
+ <button
+ class="btn btn-ghost btn-sm act"
+ title="Info"
+ onclick={(ev) => { ev.stopPropagation(); openInfo(e); }}
+ >
+ <Icon name="note" size={13} />
+ </button>
+ <button
+ class="btn btn-ghost btn-sm act del"
+ title="Delete"
+ onclick={(ev) => { ev.stopPropagation(); removeEntity(e); }}
+ >
<Icon name="trash" size={13} />
</button>
</div>
{:else}
- {#if !suggested.length}
- <div class="none">Tools file entities here as you work.</div>
+ {#if !filteredSuggested.length}
+ <div class="none">
+ {folderFilter !== null ? 'No items in this folder.' : 'Tools file entities here as you work.'}
+ </div>
{/if}
{/each}
{/if}
+
+
</div>
{/if}
</aside>
+<!-- Note edit / create modal -->
+{#if noteModal}
+ <Modal
+ title={noteModal.entity ? 'Edit note' : 'New note'}
+ onclose={() => (noteModal = null)}
+ width="580px"
+ >
+ <label class="modal-label" for="note-title">Title</label>
+ <input
+ id="note-title"
+ class="input"
+ placeholder="Note title…"
+ bind:value={noteModal.title}
+ />
+
+ <label class="modal-label" for="note-folder" style="margin-top:10px">Folder</label>
+ <input
+ id="note-folder"
+ class="input"
+ placeholder="e.g. research, timeline, sources…"
+ bind:value={noteModal.folder}
+ list="note-folder-suggestions"
+ />
+ <datalist id="note-folder-suggestions">
+ {#each allFolders as f (f)}<option value={f}></option>{/each}
+ </datalist>
+
+ <label class="modal-label" for="note-content" style="margin-top:10px">Content</label>
+ <textarea
+ id="note-content"
+ class="textarea note-content"
+ rows="14"
+ placeholder="Write your notes in markdown…"
+ bind:value={noteModal.content}
+ ></textarea>
+
+ <div class="modal-row">
+ {#if noteModal.entity}
+ <button
+ class="btn btn-ghost btn-sm"
+ style="color:var(--danger,#e55)"
+ onclick={async () => { await removeEntity(noteModal.entity); noteModal = null; }}
+ >
+ <Icon name="trash" size={13} /> Delete note
+ </button>
+ {/if}
+ <div style="flex:1"></div>
+ <button class="btn" onclick={() => (noteModal = null)}>Cancel</button>
+ <button class="btn btn-primary" onclick={saveNote} disabled={noteModalSaving}>
+ {noteModalSaving ? 'Saving…' : noteModal.entity ? 'Save' : 'Create'}
+ </button>
+ </div>
+ </Modal>
+{/if}
+
+<!-- Entity info modal (rich details, esp. media) -->
+{#if infoEntity}
+ <Modal title={infoEntity.label} onclose={() => (infoEntity = null)} width="520px">
+ {#if infoLoading}
+ <div class="info-loading">Loading…</div>
+ {/if}
+
+ {#if infoData?.kind === 'image' && infoData.thumbnail}
+ <div class="info-preview">
+ <img src={`/files/${caseState.current.id}/${infoData.path}`} alt={infoEntity.label} />
+ </div>
+ {:else if infoData?.kind === 'video'}
+ <div class="info-preview">
+ <!-- svelte-ignore a11y_media_has_caption -->
+ <video src={`/files/${caseState.current.id}/${infoData.path}`} controls preload="metadata"></video>
+ </div>
+ {/if}
+
+ <div class="info-rows">
+ <div class="info-row"><span class="info-k">Type</span><span>{infoEntity.type}</span></div>
+ {#if folderOf(infoEntity)}
+ <div class="info-row"><span class="info-k">Folder</span><span>{folderOf(infoEntity)}</span></div>
+ {/if}
+ {#if infoData}
+ <div class="info-row"><span class="info-k">Kind</span><span>{infoData.kind}</span></div>
+ <div class="info-row"><span class="info-k">Size</span><span>{fmtSize(infoData.size)}</span></div>
+ {#if infoData.added_at}
+ <div class="info-row"><span class="info-k">Added</span><span>{infoData.added_at.slice(0, 10)}</span></div>
+ {/if}
+ {#if infoData.sha256}
+ <div class="info-row"><span class="info-k">SHA-256</span><span class="mono hash" title={infoData.sha256}>{infoData.sha256}</span></div>
+ {/if}
+ {#if infoData.source?.title}
+ <div class="info-row"><span class="info-k">Title</span><span>{infoData.source.title}</span></div>
+ {/if}
+ {#if infoData.source?.uploader}
+ <div class="info-row"><span class="info-k">Uploader</span><span>{infoData.source.uploader}</span></div>
+ {/if}
+ {#if infoData.source?.upload_date}
+ <div class="info-row"><span class="info-k">Published</span><span class="mono">{infoData.source.upload_date}</span></div>
+ {/if}
+ {#if infoData.source?.duration}
+ <div class="info-row"><span class="info-k">Duration</span><span>{infoData.source.duration}s</span></div>
+ {/if}
+ {#if infoData.source?.webpage_url ?? infoData.source?.url}
+ <div class="info-row">
+ <span class="info-k">Source</span>
+ <a class="mono src" href={infoData.source.webpage_url ?? infoData.source.url} target="_blank" rel="noreferrer">
+ {infoData.source.webpage_url ?? infoData.source.url}
+ </a>
+ </div>
+ {/if}
+ {#if infoData.notes}
+ <div class="info-row"><span class="info-k">Notes</span><span>{infoData.notes}</span></div>
+ {/if}
+ {:else if infoEntity.attrs?.content}
+ <div class="info-note-body">{infoEntity.attrs.content}</div>
+ {/if}
+ {#if infoEntity.attrs?.coords}
+ <div class="info-row"><span class="info-k">Coords</span><span class="mono">{infoEntity.attrs.coords}</span></div>
+ {/if}
+ </div>
+
+ <div class="modal-row">
+ {#if infoData?.path}
+ <a class="btn btn-ghost btn-sm" href={`/files/${caseState.current.id}/${infoData.path}`} target="_blank" rel="noreferrer">
+ <Icon name="external" size={13} /> Open file
+ </a>
+ {/if}
+ {#if ENTITY_TOOL[infoEntity.type]}
+ <button class="btn btn-ghost btn-sm" onclick={() => { openEntity(infoEntity); infoEntity = null; }}>
+ <Icon name="arrowRight" size={13} /> Open in tool
+ </button>
+ {/if}
+ <div style="flex:1"></div>
+ <button class="btn" onclick={() => (infoEntity = null)}>Close</button>
+ </div>
+ </Modal>
+{/if}
+
<style>
.sidebar {
width: var(--sidebar-w);
@@ -169,15 +640,8 @@
text-overflow: ellipsis;
white-space: nowrap;
}
- .path {
- font-size: var(--fs-xs);
- color: var(--text-3);
- }
- .sections {
- flex: 1;
- overflow-y: auto;
- padding: 8px;
- }
+ .path { font-size: var(--fs-xs); color: var(--text-3); }
+ .sections { flex: 1; overflow-y: auto; padding: 8px; }
.section-head {
display: flex;
align-items: center;
@@ -190,42 +654,82 @@
letter-spacing: 0.07em;
color: var(--text-2);
}
- .section-head:hover {
- color: var(--text-1);
- }
- .count {
- margin-left: auto;
+ .section-head:hover { color: var(--text-1); }
+ .section-head-row { display: flex; align-items: center; }
+ .section-head-row .section-head { flex: 1; }
+ .new-note-btn {
color: var(--text-3);
- font-weight: 600;
+ padding: 4px 6px;
+ margin-right: 4px;
+ display: flex;
+ gap: 2px;
}
+ .new-note-btn:hover { color: var(--accent); }
+ .count { margin-left: auto; color: var(--text-3); font-weight: 600; }
.notes {
min-height: 130px;
font-size: var(--fs-xs);
margin: 0 4px 10px;
width: calc(100% - 8px);
}
- .entity {
+ /* folder management */
+ .new-folder { display: flex; gap: 6px; padding: 2px 8px 8px; }
+ .new-folder .input { flex: 1; font-size: var(--fs-xs); }
+ .folder-list { display: flex; flex-direction: column; gap: 2px; padding: 0 4px 4px; }
+ .frow {
display: flex;
align-items: center;
- gap: 9px;
+ gap: 8px;
+ width: 100%;
padding: 6px 8px;
border-radius: var(--r-sm);
color: var(--text-2);
+ font-size: var(--fs-sm);
+ border: 1px solid transparent;
+ cursor: pointer;
+ text-align: left;
}
- .entity:hover {
- background: var(--bg-2);
+ .frow:hover { background: var(--bg-2); }
+ .frow.active { background: var(--accent-soft); color: var(--accent); }
+ .frow.dropping { border-color: var(--accent); background: var(--accent-soft); }
+ .fname { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+ .fcount { color: var(--text-3); font-size: var(--fs-xs); font-weight: 600; }
+ .fdel { opacity: 0; color: var(--text-3); display: flex; padding: 2px; border-radius: 4px; }
+ .fdel:hover { color: var(--danger, #e55); }
+ .frow:hover .fdel { opacity: 1; }
+ .hint { font-size: var(--fs-xs); color: var(--text-3); padding: 2px 12px 8px; font-style: italic; }
+ .active-folder {
+ display: flex;
+ align-items: center;
+ gap: 5px;
+ padding: 4px 10px;
+ margin: 2px 4px 6px;
+ border-radius: 999px;
+ background: var(--accent-soft);
+ color: var(--accent);
+ font-size: var(--fs-xs);
+ width: fit-content;
}
+ .clear-filter { display: flex; color: var(--accent); padding: 0; }
+ /* entities */
+ .entity {
+ display: flex;
+ align-items: center;
+ gap: 7px;
+ padding: 6px 8px;
+ border-radius: var(--r-sm);
+ color: var(--text-2);
+ }
+ .entity:hover { background: var(--bg-2); }
+ .entity.clickable { cursor: pointer; }
+ .entity.dragging { opacity: 0.5; }
+ .entity > :global(svg:first-child) { color: var(--text-3); cursor: grab; flex-shrink: 0; }
.entity.suggested {
background: var(--accent-soft);
border: 1px dashed var(--accent);
margin-bottom: 4px;
}
- .e-body {
- flex: 1;
- min-width: 0;
- display: flex;
- flex-direction: column;
- }
+ .e-body { flex: 1; min-width: 0; display: flex; flex-direction: column; }
.e-label {
font-size: var(--fs-sm);
color: var(--text-1);
@@ -233,24 +737,40 @@
text-overflow: ellipsis;
white-space: nowrap;
}
- .e-type {
+ .e-meta {
+ display: flex;
+ align-items: center;
+ gap: 3px;
font-size: var(--fs-xs);
color: var(--text-3);
}
- .del {
- opacity: 0;
- }
- .entity:hover .del {
- opacity: 1;
- }
- .suggest-note {
- font-size: var(--fs-xs);
- color: var(--accent);
- padding: 2px 8px 6px;
- }
- .none {
- font-size: var(--fs-xs);
- color: var(--text-3);
- padding: 4px 8px 12px;
+ .act { opacity: 0; flex-shrink: 0; }
+ .entity:hover .act { opacity: 1; }
+ .del:hover { color: var(--danger, #e55); }
+ .suggest-note { font-size: var(--fs-xs); color: var(--accent); padding: 2px 8px 6px; }
+ .none { font-size: var(--fs-xs); color: var(--text-3); padding: 4px 8px 12px; }
+ /* note modal */
+ .modal-label { display: block; font-size: var(--fs-xs); color: var(--text-3); margin-bottom: 5px; }
+ .note-content { width: 100%; resize: vertical; font-family: var(--font-mono); font-size: var(--fs-xs); }
+ .modal-row { display: flex; align-items: center; gap: 8px; margin-top: 14px; }
+ /* info modal */
+ .info-loading { font-size: var(--fs-sm); color: var(--text-3); padding: 6px 0; }
+ .info-preview {
+ border-radius: var(--r);
+ overflow: hidden;
+ background: var(--bg-2);
+ margin-bottom: 14px;
+ max-height: 240px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
}
+ .info-preview img, .info-preview video { max-width: 100%; max-height: 240px; object-fit: contain; display: block; }
+ .info-rows { display: flex; flex-direction: column; gap: 6px; }
+ .info-row { display: flex; gap: 10px; font-size: var(--fs-sm); align-items: baseline; min-width: 0; }
+ .info-k { color: var(--text-3); font-size: var(--fs-xs); min-width: 68px; flex-shrink: 0; }
+ .hash { font-size: 11px; word-break: break-all; color: var(--text-2); }
+ .src { font-size: var(--fs-xs); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+ .info-note-body { white-space: pre-wrap; font-size: var(--fs-sm); color: var(--text-2); }
</style>
+
diff --git a/frontend/src/components/Icon.svelte b/frontend/src/components/Icon.svelte
index 5759f62..d0822b6 100644
--- a/frontend/src/components/Icon.svelte
+++ b/frontend/src/components/Icon.svelte
@@ -14,6 +14,7 @@
folderOpen: 'M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v1M3 7v11a2 2 0 0 0 2 2h13a2 2 0 0 0 2-1.5l1.6-6A1.5 1.5 0 0 0 20.1 10H6.4a2 2 0 0 0-1.9 1.4L3 16',
x: 'M6 6l12 12M18 6 6 18',
chevronRight: 'm9 6 6 6-6 6',
+ chevronLeft: 'm15 6-6 6 6 6',
chevronDown: 'm6 9 6 6 6-6',
panelRight: 'M4 4h16a1 1 0 0 1 1 1v14a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V5a1 1 0 0 1 1-1Zm11 0v16',
search: 'M11 4a7 7 0 1 0 0 14 7 7 0 0 0 0-14Zm9 16-4.35-4.35',
@@ -22,6 +23,7 @@
upload: 'M12 15V3m0 0 4 4m-4-4-4 4M4 17v2a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-2',
link: 'M10 14a5 5 0 0 0 7.5.5l3-3a5 5 0 0 0-7-7l-1.7 1.7M14 10a5 5 0 0 0-7.5-.5l-3 3a5 5 0 0 0 7 7l1.7-1.7',
copy: 'M8 8h11a1 1 0 0 1 1 1v11a1 1 0 0 1-1 1H8a1 1 0 0 1-1-1V9a1 1 0 0 1 1-1Zm-4 8V4a1 1 0 0 1 1-1h12',
+ save: 'M5 3h11l3 3v14a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1Zm3 0v5h7V3M7 21v-7h10v7',
check: 'm4.5 12.5 5 5 10-11',
note: 'M6 3h9l5 5v13a1 1 0 0 1-1 1H6a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1Zm8 0v6h6M9 13h6m-6 4h4',
pin: 'M12 21s-7-6.1-7-11a7 7 0 0 1 14 0c0 4.9-7 11-7 11Zm0-8.5a2.5 2.5 0 1 0 0-5 2.5 2.5 0 0 0 0 5Z',
@@ -49,6 +51,10 @@
arrow: 'M5 19 19 5m0 0h-8m8 0v8',
text: 'M5 6V4h14v2M12 4v16m-3 0h6',
hand: 'M8 12V6a1.5 1.5 0 0 1 3 0v5m0-6.5a1.5 1.5 0 0 1 3 0V11m0-5a1.5 1.5 0 0 1 3 0v9a6 6 0 0 1-6 6h-1a6 6 0 0 1-5-2.7L3.5 15A1.6 1.6 0 0 1 6 13.2l2 1.8',
+ inspect: 'M11 4a7 7 0 1 0 0 14 7 7 0 0 0 0-14Zm9 16-4.35-4.35M8 11h6m-3-3v6',
+ crop: 'M6 2v14a2 2 0 0 0 2 2h14M2 6h14a2 2 0 0 1 2 2v14',
+ reset: 'M4 9a8 8 0 1 1-1.6 4.7M4 9H1m3 0V6',
+ sliders: 'M4 6h9m4 0h3M4 12h3m4 0h9M4 18h13m4 0h3M13 4v4m0 6v4m4-12v4',
};
</script>
diff --git a/frontend/src/lib/inspectModules.js b/frontend/src/lib/inspectModules.js
new file mode 100644
index 0000000..f73cb06
--- /dev/null
+++ b/frontend/src/lib/inspectModules.js
@@ -0,0 +1,28 @@
+/**
+ * Inspector module registry — the frontend extension seam.
+ *
+ * Add a mini-tool by writing a Svelte component under tools/inspect/ and
+ * appending one entry here:
+ * { id, label, icon, kinds, component }
+ * - kinds: which source media kinds the module applies to ('image' | 'video')
+ *
+ * Each module receives props:
+ * { source, probeInfo, shared, mediaList, onProduced }
+ * - source : the selected media item ({ path, filename, kind, ... })
+ * - probeInfo : dimensions / duration / fps from /inspect/probe
+ * - shared : reactive bridge to the viewer (filter, transform, crop,
+ * cropMode, currentTime, seekTo)
+ * - mediaList : all case media (for modules that pick several images)
+ * - onProduced : call with the API result after filing a new derivative
+ */
+import FramesModule from '../tools/inspect/FramesModule.svelte';
+import AdjustModule from '../tools/inspect/AdjustModule.svelte';
+import CollageModule from '../tools/inspect/CollageModule.svelte';
+import AnalyzeModule from '../tools/inspect/AnalyzeModule.svelte';
+
+export const INSPECT_MODULES = [
+ { id: 'frames', label: 'Frames', icon: 'video', kinds: ['video'], component: FramesModule },
+ { id: 'adjust', label: 'Adjust', icon: 'sliders', kinds: ['image'], component: AdjustModule },
+ { id: 'collage', label: 'Collage', icon: 'layers', kinds: ['image', 'video'], component: CollageModule },
+ { id: 'analyze', label: 'Analyze', icon: 'eye', kinds: ['image'], component: AnalyzeModule },
+];
diff --git a/frontend/src/lib/state.svelte.js b/frontend/src/lib/state.svelte.js
index e7b6fca..dc26759 100644
--- a/frontend/src/lib/state.svelte.js
+++ b/frontend/src/lib/state.svelte.js
@@ -14,12 +14,16 @@ export const caseState = $state({
});
export const uiState = $state({
- tool: 'media', // 'media' | 'satellite' | 'proof' | 'post'
+ tool: 'media', // 'media' | 'inspect' | 'satellite' | 'proof' | 'post'
sidebarOpen: true,
toasts: [],
// cross-tool handoffs (the workbench glue):
composeQueue: [], // media paths queued for the Proof Composer
postProof: null, // proof spec handed to the Post Composer
+ openProof: null, // proof name to load in the Proof Composer
+ openDraft: null, // draft name to load in the Post Composer
+ inspectPath: null, // media path to open in the Inspect tool
+ gotoCoords: null, // { lat, lon } to fly to in the Satellite tool
});
let toastSeq = 0;
@@ -37,15 +41,49 @@ export async function refreshCaseList() {
caseState.list = await api.get('/api/cases');
}
+// Remember the last open case across page reloads so work is never "lost".
+const LAST_CASE_KEY = 'ozimut:lastCase';
+
+function rememberCase(id) {
+ try {
+ if (id) localStorage.setItem(LAST_CASE_KEY, id);
+ else localStorage.removeItem(LAST_CASE_KEY);
+ } catch {
+ /* localStorage unavailable (private mode) — non-fatal */
+ }
+}
+
export async function openCase(id) {
caseState.loading = true;
try {
caseState.current = await api.get(`/api/cases/${id}`);
+ rememberCase(id);
} finally {
caseState.loading = false;
}
}
+/**
+ * Startup: load the case list and reopen the last-used case (if it still
+ * exists on disk). Called once from App on mount.
+ */
+export async function initSession() {
+ await refreshCaseList();
+ let lastId = null;
+ try {
+ lastId = localStorage.getItem(LAST_CASE_KEY);
+ } catch {
+ /* ignore */
+ }
+ if (lastId) {
+ try {
+ await openCase(lastId);
+ } catch {
+ rememberCase(null); // it was deleted — forget it
+ }
+ }
+}
+
export async function reloadCase() {
if (caseState.current) {
caseState.current = await api.get(`/api/cases/${caseState.current.id}`);
@@ -68,7 +106,7 @@ export async function ensureCase() {
const scratch = await api.post('/api/cases/scratch');
await refreshCaseList();
await openCase(scratch.id);
- toast('Scratch session started — promote it to keep your work', 'info');
+ toast('Scratch session started — “Keep as case…” to save it for good', 'info');
return caseState.current;
}
@@ -82,4 +120,5 @@ export async function promoteCase(name) {
export function closeCase() {
caseState.current = null;
+ rememberCase(null);
}
diff --git a/frontend/src/tools/Inspector.svelte b/frontend/src/tools/Inspector.svelte
new file mode 100644
index 0000000..269cb90
--- /dev/null
+++ b/frontend/src/tools/Inspector.svelte
@@ -0,0 +1,407 @@
+<script>
+ import { api } from '../lib/api.js';
+ import { caseState, uiState, reloadCase, toast } from '../lib/state.svelte.js';
+ import { INSPECT_MODULES } from '../lib/inspectModules.js';
+ import Icon from '../components/Icon.svelte';
+
+ let mediaList = $state([]);
+ let loadedFor = $state(null);
+ let source = $state(null);
+ let probeInfo = $state(null);
+ let moduleId = $state(null);
+ let produced = $state(null);
+
+ // reactive bridge between the modules and the viewer
+ const shared = $state({
+ filter: '',
+ transform: '',
+ crop: null, // { x, y, w, h } fractional
+ cropMode: false,
+ currentTime: 0,
+ seekTo: null,
+ });
+
+ let videoEl = $state();
+ let cropDraw = $state(null); // in-progress crop rectangle
+
+ const modules = $derived(
+ source ? INSPECT_MODULES.filter((m) => m.kinds.includes(source.kind)) : []
+ );
+ const ActiveModule = $derived(modules.find((m) => m.id === moduleId)?.component ?? null);
+
+ // load case media; react to case switches
+ $effect(() => {
+ const id = caseState.current?.id;
+ if (id !== loadedFor) {
+ loadedFor = id;
+ mediaList = [];
+ source = null;
+ if (id) refresh(id);
+ }
+ });
+
+ // deep-link from the Media Library ("Inspect")
+ $effect(() => {
+ if (uiState.tool === 'inspect' && uiState.inspectPath && mediaList.length) {
+ const target = mediaList.find((m) => m.path === uiState.inspectPath);
+ uiState.inspectPath = null;
+ if (target) select(target);
+ }
+ });
+
+ // apply a requested video seek coming from a module
+ $effect(() => {
+ if (shared.seekTo != null && videoEl) {
+ videoEl.currentTime = shared.seekTo;
+ shared.seekTo = null;
+ }
+ });
+
+ async function refresh(id = caseState.current?.id) {
+ if (!id) return;
+ mediaList = await api.get(`/api/cases/${id}/media`);
+ if (source) {
+ const still = mediaList.find((m) => m.path === source.path);
+ if (!still) source = null;
+ }
+ }
+
+ async function select(item) {
+ resetViewer();
+ source = item;
+ produced = null;
+ try {
+ probeInfo = await api.get(
+ `/api/cases/${caseState.current.id}/inspect/probe?path=${encodeURIComponent(item.path)}`
+ );
+ } catch {
+ probeInfo = { kind: item.kind };
+ }
+ const applicable = INSPECT_MODULES.filter((m) => m.kinds.includes(item.kind));
+ moduleId = applicable[0]?.id ?? null;
+ }
+
+ function resetViewer() {
+ shared.filter = '';
+ shared.transform = '';
+ shared.crop = null;
+ shared.cropMode = false;
+ shared.currentTime = 0;
+ }
+
+ function onProduced(res) {
+ produced = res.item;
+ refresh();
+ }
+
+ function inspectProduced() {
+ const item = mediaList.find((m) => m.path === produced.path) ?? produced;
+ select({ ...item, kind: 'image' });
+ }
+
+ function sendToComposer(item) {
+ if (!uiState.composeQueue.includes(item.path)) uiState.composeQueue.push(item.path);
+ uiState.tool = 'proof';
+ }
+
+ // -- crop overlay ---------------------------------------------------------
+ function frac(e, el) {
+ const r = el.getBoundingClientRect();
+ return {
+ x: Math.min(Math.max((e.clientX - r.left) / r.width, 0), 1),
+ y: Math.min(Math.max((e.clientY - r.top) / r.height, 0), 1),
+ };
+ }
+
+ function cropDown(e) {
+ if (!shared.cropMode) return;
+ e.preventDefault();
+ const p = frac(e, e.currentTarget);
+ cropDraw = { sx: p.x, sy: p.y, x: p.x, y: p.y, w: 0, h: 0 };
+ e.currentTarget.setPointerCapture(e.pointerId);
+ }
+
+ function cropMove(e) {
+ if (!cropDraw) return;
+ const p = frac(e, e.currentTarget);
+ cropDraw = {
+ sx: cropDraw.sx,
+ sy: cropDraw.sy,
+ x: Math.min(cropDraw.sx, p.x),
+ y: Math.min(cropDraw.sy, p.y),
+ w: Math.abs(p.x - cropDraw.sx),
+ h: Math.abs(p.y - cropDraw.sy),
+ };
+ }
+
+ function cropUp() {
+ if (cropDraw && cropDraw.w > 0.02 && cropDraw.h > 0.02) {
+ shared.crop = { x: cropDraw.x, y: cropDraw.y, w: cropDraw.w, h: cropDraw.h };
+ shared.cropMode = false;
+ }
+ cropDraw = null;
+ }
+
+ const cropBox = $derived(cropDraw ?? shared.crop);
+</script>
+
+<div class="tool">
+ <div class="tool-header">
+ <h2>Inspect</h2>
+ <span class="sub">open a photo or video — grab frames, adjust, collage &amp; analyse</span>
+ <div class="spacer"></div>
+ <select
+ class="input source-select"
+ value={source?.path ?? ''}
+ onchange={(e) => {
+ const m = mediaList.find((x) => x.path === e.target.value);
+ if (m) select(m);
+ }}
+ >
+ <option value="" disabled>Choose a media…</option>
+ {#each mediaList as m (m.path)}
+ <option value={m.path}>{m.label || m.filename}</option>
+ {/each}
+ </select>
+ </div>
+
+ {#if !caseState.current}
+ <div class="empty">
+ <Icon name="inspect" size={40} />
+ <p>Open a case and add media to start inspecting.</p>
+ <button class="btn btn-primary" onclick={() => (uiState.tool = 'media')}>Go to Media Library</button>
+ </div>
+ {:else if !source}
+ <div class="empty">
+ <Icon name="inspect" size={40} />
+ <p>Choose a media above to open it.</p>
+ {#if mediaList.length === 0}
+ <button class="btn" onclick={() => (uiState.tool = 'media')}>Add media first</button>
+ {/if}
+ </div>
+ {:else}
+ <div class="workspace">
+ <div class="viewer">
+ <div
+ class="frame"
+ class:cropping={shared.cropMode}
+ onpointerdown={cropDown}
+ onpointermove={cropMove}
+ onpointerup={cropUp}
+ >
+ {#if source.kind === 'video'}
+ <!-- svelte-ignore a11y_media_has_caption -->
+ <video
+ bind:this={videoEl}
+ src={`/files/${caseState.current.id}/${source.path}`}
+ controls
+ ontimeupdate={() => (shared.currentTime = videoEl?.currentTime ?? 0)}
+ style:filter={shared.filter}
+ style:transform={shared.transform}
+ ></video>
+ {:else}
+ <img
+ src={`/files/${caseState.current.id}/${source.path}`}
+ alt={source.filename}
+ style:filter={shared.filter}
+ style:transform={shared.transform}
+ />
+ {/if}
+
+ {#if cropBox}
+ <div
+ class="crop-box"
+ style:left={`${cropBox.x * 100}%`}
+ style:top={`${cropBox.y * 100}%`}
+ style:width={`${cropBox.w * 100}%`}
+ style:height={`${cropBox.h * 100}%`}
+ ></div>
+ {/if}
+ </div>
+ </div>
+
+ <aside class="panel">
+ <div class="module-tabs">
+ {#each modules as m (m.id)}
+ <button class="mtab" class:active={moduleId === m.id} onclick={() => (moduleId = m.id)}>
+ <Icon name={m.icon} size={15} /> {m.label}
+ </button>
+ {/each}
+ </div>
+
+ {#if produced}
+ <div class="produced fade-up">
+ <img src={`/files/${caseState.current.id}/${produced.thumbnail ?? produced.path}`} alt="result" />
+ <div class="produced-body">
+ <span class="produced-name">{produced.filename}</span>
+ <div class="produced-actions">
+ <button class="btn btn-xs" onclick={inspectProduced}><Icon name="inspect" size={12} /> Inspect</button>
+ <button class="btn btn-xs" onclick={() => sendToComposer(produced)}>
+ <Icon name="proof" size={12} /> Composer
+ </button>
+ </div>
+ </div>
+ <button class="btn btn-ghost btn-xs" onclick={() => (produced = null)} aria-label="Dismiss">
+ <Icon name="x" size={13} />
+ </button>
+ </div>
+ {/if}
+
+ <div class="module-body">
+ {#if ActiveModule}
+ <ActiveModule {source} {probeInfo} {shared} {mediaList} {onProduced} />
+ {/if}
+ </div>
+ </aside>
+ </div>
+ {/if}
+</div>
+
+<style>
+ .tool {
+ display: flex;
+ flex-direction: column;
+ height: 100%;
+ }
+ .tool-header {
+ display: flex;
+ align-items: baseline;
+ gap: 10px;
+ padding: 14px 16px 12px;
+ border-bottom: 1px solid var(--border);
+ flex-shrink: 0;
+ }
+ h2 {
+ font-size: var(--fs-lg);
+ font-weight: 700;
+ }
+ .sub {
+ color: var(--text-3);
+ font-size: var(--fs-sm);
+ }
+ .spacer {
+ flex: 1;
+ }
+ .source-select {
+ max-width: 280px;
+ }
+ .empty {
+ flex: 1;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ gap: 12px;
+ color: var(--text-3);
+ }
+ .workspace {
+ flex: 1;
+ display: flex;
+ min-height: 0;
+ }
+ .viewer {
+ flex: 1;
+ min-width: 0;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ padding: 18px;
+ background: var(--bg-0);
+ overflow: auto;
+ }
+ .frame {
+ position: relative;
+ display: inline-block;
+ line-height: 0;
+ touch-action: none;
+ box-shadow: var(--shadow-2);
+ }
+ .frame.cropping {
+ cursor: crosshair;
+ }
+ .frame img,
+ .frame video {
+ max-width: 100%;
+ max-height: calc(100vh - var(--topbar-h) - 120px);
+ display: block;
+ }
+ .crop-box {
+ position: absolute;
+ border: 1.5px solid var(--accent);
+ box-shadow: 0 0 0 9999px rgba(6, 9, 14, 0.55);
+ pointer-events: none;
+ }
+ .panel {
+ width: 320px;
+ flex-shrink: 0;
+ border-left: 1px solid var(--border);
+ background: var(--bg-1);
+ display: flex;
+ flex-direction: column;
+ min-height: 0;
+ }
+ .module-tabs {
+ display: flex;
+ gap: 4px;
+ padding: 10px;
+ border-bottom: 1px solid var(--border);
+ flex-wrap: wrap;
+ }
+ .mtab {
+ display: flex;
+ align-items: center;
+ gap: 5px;
+ padding: 6px 9px;
+ border-radius: var(--r-md);
+ font-size: var(--fs-sm);
+ font-weight: 600;
+ color: var(--text-3);
+ }
+ .mtab:hover {
+ color: var(--text-1);
+ background: var(--bg-2);
+ }
+ .mtab.active {
+ color: var(--accent);
+ background: var(--accent-soft);
+ }
+ .module-body {
+ padding: 14px;
+ overflow: auto;
+ flex: 1;
+ }
+ .produced {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ margin: 10px;
+ padding: 8px;
+ border: 1px solid var(--border-strong);
+ border-radius: var(--r-md);
+ background: var(--bg-2);
+ }
+ .produced img {
+ width: 46px;
+ height: 46px;
+ object-fit: cover;
+ border-radius: var(--r-sm);
+ }
+ .produced-body {
+ flex: 1;
+ min-width: 0;
+ display: flex;
+ flex-direction: column;
+ gap: 5px;
+ }
+ .produced-name {
+ font-size: var(--fs-xs);
+ color: var(--text-2);
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ }
+ .produced-actions {
+ display: flex;
+ gap: 5px;
+ }
+</style>
diff --git a/frontend/src/tools/MediaLibrary.svelte b/frontend/src/tools/MediaLibrary.svelte
index 7e22150..65b3c5d 100644
--- a/frontend/src/tools/MediaLibrary.svelte
+++ b/frontend/src/tools/MediaLibrary.svelte
@@ -2,6 +2,7 @@
import { api } from '../lib/api.js';
import { caseState, uiState, ensureCase, reloadCase, toast } from '../lib/state.svelte.js';
import Icon from '../components/Icon.svelte';
+ import Modal from '../components/Modal.svelte';
const KIND_ICONS = { image: 'image', video: 'video', audio: 'audio', file: 'file' };
@@ -12,6 +13,25 @@
let jobs = $state([]); // active download jobs: {id, url, progress}
let fileInput;
+ // --- folder filter ---
+ let folderFilter = $state(null); // null = All
+
+ const folders = $derived(
+ [...new Set(items.filter((i) => i.folder).map((i) => i.folder))].sort()
+ );
+ const filteredItems = $derived(
+ folderFilter ? items.filter((i) => i.folder === folderFilter) : items
+ );
+
+ // --- info/edit modal ---
+ let editItem = $state(null);
+ let editNotes = $state('');
+ let editLabel = $state('');
+ let editSaving = $state(false);
+
+ // --- lightbox ---
+ let lightboxItem = $state(null);
+
$effect(() => {
const id = caseState.current?.id;
if (id !== loadedFor) {
@@ -103,6 +123,11 @@
uiState.tool = 'proof';
}
+ function inspect(item) {
+ uiState.inspectPath = item.path;
+ uiState.tool = 'inspect';
+ }
+
function fmtSize(bytes) {
if (bytes >= 1 << 30) return (bytes / (1 << 30)).toFixed(1) + ' GB';
if (bytes >= 1 << 20) return (bytes / (1 << 20)).toFixed(1) + ' MB';
@@ -110,11 +135,43 @@
return bytes + ' B';
}
+ function fmtDate(iso) {
+ if (!iso) return '';
+ return iso.slice(0, 10);
+ }
+
function onDrop(e) {
e.preventDefault();
dragOver = false;
importFiles(e.dataTransfer.files);
}
+
+ // --- info modal actions ---
+ function openInfo(item) {
+ editItem = item;
+ editNotes = item.notes ?? '';
+ editLabel = item.label ?? '';
+ }
+
+ async function saveInfo() {
+ if (!editItem) return;
+ editSaving = true;
+ try {
+ const updated = await api.patch(`/api/cases/${caseState.current.id}/media`, {
+ path: editItem.path,
+ notes: editNotes,
+ label: editLabel,
+ });
+ const idx = items.findIndex((i) => i.path === editItem.path);
+ if (idx !== -1) items[idx] = updated;
+ editItem = null;
+ toast('Saved', 'ok', 1600);
+ } catch (e) {
+ toast(e.message, 'danger');
+ } finally {
+ editSaving = false;
+ }
+ }
</script>
<div
@@ -165,6 +222,30 @@
/>
</div>
+ <!-- folder filter bar -->
+ {#if items.length > 0}
+ <div class="folder-bar">
+ <button
+ class="folder-chip"
+ class:active={folderFilter === null}
+ onclick={() => (folderFilter = null)}
+ >
+ <Icon name="media" size={13} /> All
+ <span class="chip-count">{items.length}</span>
+ </button>
+ {#each folders as f (f)}
+ <button
+ class="folder-chip"
+ class:active={folderFilter === f}
+ onclick={() => (folderFilter = f)}
+ >
+ <Icon name="folder" size={13} />{f}
+ <span class="chip-count">{items.filter((i) => i.folder === f).length}</span>
+ </button>
+ {/each}
+ </div>
+ {/if}
+
<div class="tool-body">
{#each jobs as job (job.id)}
<div class="job card fade-up">
@@ -193,11 +274,25 @@
Every file is SHA-256 hashed and its origin recorded.
</p>
</div>
+ {:else if filteredItems.length === 0}
+ <div class="empty" style="height: 100%">
+ <div class="empty-icon"><Icon name="folder" size={38} /></div>
+ <h3>Folder is empty</h3>
+ </div>
{:else}
<div class="grid">
- {#each items as item (item.path)}
+ {#each filteredItems as item (item.path)}
<div class="media-card card fade-up">
- <div class="thumb">
+ <!-- thumbnail — click to lightbox for images -->
+ <div
+ class="thumb"
+ class:clickable={item.kind === 'image'}
+ onclick={() => item.kind === 'image' && (lightboxItem = item)}
+ role={item.kind === 'image' ? 'button' : undefined}
+ tabindex={item.kind === 'image' ? 0 : undefined}
+ onkeydown={(e) => e.key === 'Enter' && item.kind === 'image' && (lightboxItem = item)}
+ aria-label={item.kind === 'image' ? `Preview ${item.filename}` : undefined}
+ >
{#if item.thumbnail}
<img
src={`/files/${caseState.current.id}/${item.thumbnail}`}
@@ -208,9 +303,14 @@
<Icon name={KIND_ICONS[item.kind] ?? 'file'} size={34} />
{/if}
<span class="kind badge">{item.kind}</span>
+ {#if item.folder}
+ <span class="folder-badge badge">
+ <Icon name="folder" size={10} />{item.folder}
+ </span>
+ {/if}
</div>
<div class="body">
- <span class="name" title={item.filename}>{item.filename}</span>
+ <span class="name" title={item.filename}>{item.label ?? item.filename}</span>
<span class="meta">
{fmtSize(item.size)} ·
<span class="mono" title={item.sha256}>{item.sha256.slice(0, 8)}</span>
@@ -218,8 +318,18 @@
· <a href={item.source.webpage_url ?? item.source.url} target="_blank" rel="noreferrer">source</a>
{/if}
</span>
+ {#if item.notes}
+ <span class="notes-preview" title={item.notes}>{item.notes}</span>
+ {/if}
</div>
<div class="actions">
+ <button
+ class="btn btn-ghost btn-sm"
+ title="Info / Edit notes"
+ onclick={() => openInfo(item)}
+ >
+ <Icon name="note" size={14} />
+ </button>
<a
class="btn btn-ghost btn-sm"
href={`/files/${caseState.current.id}/${item.path}`}
@@ -229,6 +339,15 @@
>
<Icon name="external" size={14} />
</a>
+ {#if item.kind === 'image' || item.kind === 'video'}
+ <button
+ class="btn btn-ghost btn-sm"
+ title="Open in Inspect"
+ onclick={() => inspect(item)}
+ >
+ <Icon name="inspect" size={14} />
+ </button>
+ {/if}
{#if item.kind === 'image'}
<button
class="btn btn-ghost btn-sm"
@@ -258,6 +377,142 @@
{/if}
</div>
+<!-- info / edit modal -->
+{#if editItem}
+ <Modal title={editItem.filename} onclose={() => (editItem = null)} width="520px">
+ <!-- preview -->
+ {#if editItem.kind === 'image' && editItem.thumbnail}
+ <div class="modal-preview">
+ <img
+ src={`/files/${caseState.current.id}/${editItem.path}`}
+ alt={editItem.filename}
+ />
+ </div>
+ {:else if editItem.kind === 'video'}
+ <div class="modal-preview">
+ <!-- svelte-ignore a11y_media_has_caption -->
+ <video
+ src={`/files/${caseState.current.id}/${editItem.path}`}
+ controls
+ preload="metadata"
+ ></video>
+ </div>
+ {/if}
+
+ <!-- metadata section -->
+ <div class="info-rows">
+ <div class="info-row">
+ <span class="info-label">Kind</span>
+ <span>{editItem.kind}</span>
+ </div>
+ <div class="info-row">
+ <span class="info-label">Size</span>
+ <span>{fmtSize(editItem.size)}</span>
+ </div>
+ <div class="info-row">
+ <span class="info-label">Added</span>
+ <span>{fmtDate(editItem.added_at)}</span>
+ </div>
+ <div class="info-row">
+ <span class="info-label">SHA-256</span>
+ <span class="mono hash" title={editItem.sha256}>{editItem.sha256}</span>
+ </div>
+ {#if editItem.source?.type === 'download'}
+ {#if editItem.source.title}
+ <div class="info-row">
+ <span class="info-label">Title</span>
+ <span>{editItem.source.title}</span>
+ </div>
+ {/if}
+ {#if editItem.source.uploader}
+ <div class="info-row">
+ <span class="info-label">Uploader</span>
+ <span>{editItem.source.uploader}</span>
+ </div>
+ {/if}
+ {#if editItem.source.upload_date}
+ <div class="info-row">
+ <span class="info-label">Published</span>
+ <span class="mono">{editItem.source.upload_date}</span>
+ </div>
+ {/if}
+ {#if editItem.source.duration}
+ <div class="info-row">
+ <span class="info-label">Duration</span>
+ <span>{editItem.source.duration}s</span>
+ </div>
+ {/if}
+ {#if editItem.source.webpage_url ?? editItem.source.url}
+ <div class="info-row">
+ <span class="info-label">Source</span>
+ <a
+ href={editItem.source.webpage_url ?? editItem.source.url}
+ target="_blank"
+ rel="noreferrer"
+ class="mono source-link"
+ >{editItem.source.webpage_url ?? editItem.source.url}</a>
+ </div>
+ {/if}
+ {/if}
+ </div>
+
+ <hr class="divider" />
+
+ <!-- editable fields -->
+ <label class="field-label" for="edit-label">Label</label>
+ <input
+ id="edit-label"
+ class="input"
+ placeholder={editItem.filename}
+ bind:value={editLabel}
+ />
+
+ <label class="field-label" for="edit-notes" style="margin-top: 12px;">Notes</label>
+ <textarea
+ id="edit-notes"
+ class="textarea"
+ rows="4"
+ placeholder="Add context, observations, links…"
+ bind:value={editNotes}
+ ></textarea>
+
+ <div class="modal-actions">
+ {#if editItem.kind === 'image'}
+ <button class="btn btn-ghost btn-sm" onclick={() => { sendToComposer(editItem); editItem = null; }}>
+ <Icon name="proof" size={14} /> Send to Composer
+ </button>
+ {/if}
+ <div style="flex:1"></div>
+ <button class="btn" onclick={() => (editItem = null)}>Cancel</button>
+ <button class="btn btn-primary" onclick={saveInfo} disabled={editSaving}>
+ {editSaving ? 'Saving…' : 'Save'}
+ </button>
+ </div>
+ </Modal>
+{/if}
+
+<!-- lightbox -->
+{#if lightboxItem}
+ <div
+ class="lightbox"
+ onclick={() => (lightboxItem = null)}
+ onkeydown={(e) => e.key === 'Escape' && (lightboxItem = null)}
+ role="dialog"
+ aria-label="Image preview"
+ tabindex="-1"
+ >
+ <button class="lb-close btn btn-ghost" onclick={() => (lightboxItem = null)} aria-label="Close">
+ <Icon name="x" size={20} />
+ </button>
+ <img
+ src={`/files/${caseState.current.id}/${lightboxItem.path}`}
+ alt={lightboxItem.filename}
+ onclick={(e) => e.stopPropagation()}
+ />
+ <span class="lb-caption">{lightboxItem.filename}</span>
+ </div>
+{/if}
+
<style>
.tool {
position: relative;
@@ -270,6 +525,46 @@
gap: 8px;
width: min(480px, 40vw);
}
+
+ /* folder filter bar */
+ .folder-bar {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ padding: 8px 20px;
+ border-bottom: 1px solid var(--border);
+ overflow-x: auto;
+ flex-shrink: 0;
+ }
+ .folder-chip {
+ display: flex;
+ align-items: center;
+ gap: 5px;
+ padding: 4px 10px;
+ border-radius: 999px;
+ border: 1px solid var(--border);
+ background: var(--bg-2);
+ color: var(--text-2);
+ font-size: var(--fs-xs);
+ white-space: nowrap;
+ cursor: pointer;
+ transition: border-color 0.12s, color 0.12s, background 0.12s;
+ }
+ .folder-chip:hover {
+ border-color: var(--border-strong);
+ color: var(--text-1);
+ }
+ .folder-chip.active {
+ border-color: var(--accent);
+ background: var(--accent-soft);
+ color: var(--accent);
+ }
+ .chip-count {
+ font-size: var(--fs-xs);
+ color: var(--text-3);
+ margin-left: 2px;
+ }
+
.job {
display: flex;
align-items: center;
@@ -302,12 +597,8 @@
animation: slide 1.2s infinite var(--ease);
}
@keyframes slide {
- from {
- transform: translateX(-100%);
- }
- to {
- transform: translateX(350%);
- }
+ from { transform: translateX(-100%); }
+ to { transform: translateX(350%); }
}
.job-meta {
font-size: var(--fs-xs);
@@ -340,6 +631,9 @@
justify-content: center;
color: var(--text-3);
}
+ .thumb.clickable {
+ cursor: zoom-in;
+ }
.thumb img {
width: 100%;
height: 100%;
@@ -352,6 +646,21 @@
background: rgba(11, 15, 23, 0.75);
backdrop-filter: blur(4px);
}
+ .folder-badge {
+ position: absolute;
+ bottom: 6px;
+ right: 6px;
+ display: flex;
+ align-items: center;
+ gap: 3px;
+ background: rgba(11, 15, 23, 0.75);
+ backdrop-filter: blur(4px);
+ font-size: 10px;
+ max-width: 90px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
.body {
padding: 10px 12px 6px;
display: flex;
@@ -370,6 +679,14 @@
font-size: var(--fs-xs);
color: var(--text-3);
}
+ .notes-preview {
+ font-size: var(--fs-xs);
+ color: var(--text-2);
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ font-style: italic;
+ }
.actions {
display: flex;
gap: 2px;
@@ -400,4 +717,113 @@
font-weight: 700;
background: var(--accent-soft);
}
+
+ /* info modal */
+ .modal-preview {
+ border-radius: var(--r);
+ overflow: hidden;
+ background: var(--bg-2);
+ margin-bottom: 14px;
+ max-height: 260px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ }
+ .modal-preview img,
+ .modal-preview video {
+ max-width: 100%;
+ max-height: 260px;
+ object-fit: contain;
+ display: block;
+ }
+ .info-rows {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ margin-bottom: 4px;
+ }
+ .info-row {
+ display: flex;
+ gap: 10px;
+ font-size: var(--fs-sm);
+ align-items: baseline;
+ min-width: 0;
+ }
+ .info-label {
+ color: var(--text-3);
+ font-size: var(--fs-xs);
+ min-width: 70px;
+ flex-shrink: 0;
+ }
+ .hash {
+ font-size: 11px;
+ word-break: break-all;
+ color: var(--text-2);
+ }
+ .source-link {
+ font-size: var(--fs-xs);
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ .divider {
+ border: none;
+ border-top: 1px solid var(--border);
+ margin: 14px 0 12px;
+ }
+ .field-label {
+ display: block;
+ font-size: var(--fs-xs);
+ color: var(--text-3);
+ margin-bottom: 5px;
+ }
+ .textarea {
+ width: 100%;
+ resize: vertical;
+ min-height: 80px;
+ }
+ .modal-actions {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ margin-top: 14px;
+ }
+
+ /* lightbox */
+ .lightbox {
+ position: fixed;
+ inset: 0;
+ background: rgba(4, 7, 12, 0.92);
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ z-index: 950;
+ cursor: zoom-out;
+ }
+ .lightbox img {
+ max-width: calc(100vw - 40px);
+ max-height: calc(100vh - 80px);
+ object-fit: contain;
+ border-radius: var(--r);
+ box-shadow: var(--shadow-2);
+ cursor: default;
+ }
+ .lb-close {
+ position: absolute;
+ top: 14px;
+ right: 14px;
+ }
+ .lb-caption {
+ position: absolute;
+ bottom: 18px;
+ left: 50%;
+ transform: translateX(-50%);
+ font-size: var(--fs-xs);
+ color: var(--text-2);
+ background: rgba(11, 15, 23, 0.75);
+ padding: 4px 12px;
+ border-radius: 999px;
+ white-space: nowrap;
+ }
</style>
diff --git a/frontend/src/tools/PostComposer.svelte b/frontend/src/tools/PostComposer.svelte
index 60f994d..f6d878b 100644
--- a/frontend/src/tools/PostComposer.svelte
+++ b/frontend/src/tools/PostComposer.svelte
@@ -1,7 +1,8 @@
<script>
import { api } from '../lib/api.js';
- import { caseState, uiState, toast } from '../lib/state.svelte.js';
+ import { caseState, uiState, toast, reloadCase } from '../lib/state.svelte.js';
import Icon from '../components/Icon.svelte';
+ import Modal from '../components/Modal.svelte';
const X_LIMIT = 280;
const URL_WEIGHT = 23; // X counts every URL as 23 chars
@@ -10,23 +11,40 @@
let geo = $state(null); // {lat, lon, dms, plus_code, links}
let place = $state('');
let placeLoading = $state(false);
- let title = $state('');
+ let description = $state('');
+ let mention = $state('@GeoConfirmed');
let source = $state('');
- let attribution = $state('');
- let text = $state('');
let proofPng = $state(null);
- let edited = $state(false);
+ let tweet1 = $state('');
+ let tweet1Edited = $state(false);
- // ingest a proof handed over by the composer
+ // Media tweet (tweet 2)
+ let mediaEnabled = $state(true);
+ let mediaType = $state('none'); // 'none' | 'video' | 'images'
+ let mediaText = $state('');
+ let mediaPath = $state(null); // media selected from the library (case-relative)
+
+ // Extra context tweets (3, 4, …)
+ let extraSeq = 0;
+ let extraTweets = $state([]); // [{ id, text }]
+
+ // Draft persistence
+ let draftName = $state(null); // slug of the saved draft (null until first save)
+ let saving = $state(false);
+
+ // Media picker modal
+ let pickerOpen = $state(false);
+ let mediaLibrary = $state([]);
+
+ // Ingest a proof handed over by the Proof Composer
$effect(() => {
const p = uiState.postProof;
if (!p) return;
uiState.postProof = null;
- title = p.title === 'Untitled proof' ? '' : p.title;
- attribution = p.attribution ?? '';
+ description = p.title === 'Untitled proof' ? '' : (p.title ?? '');
source = p.sources?.[0] ?? '';
proofPng = p.png ?? null;
- edited = false;
+ tweet1Edited = false;
if (p.coords) {
coordsText = `${p.coords.lat.toFixed(6)}, ${p.coords.lon.toFixed(6)}`;
resolveCoords();
@@ -35,6 +53,15 @@
}
});
+ // Consume an "open this draft" handoff from the sidebar
+ $effect(() => {
+ if (uiState.tool === 'post' && uiState.openDraft && caseState.current) {
+ const name = uiState.openDraft;
+ uiState.openDraft = null;
+ loadDraft(name);
+ }
+ });
+
async function resolveCoords() {
const value = coordsText.trim();
if (!value) {
@@ -68,30 +95,44 @@
}
}
- function buildText() {
+ function buildTweet1() {
const lines = [];
- lines.push(title.trim() ? `📍 Geolocated: ${title.trim()}` : '📍 Geolocated');
+
+ // "Place, State, Country - PLUSCODE"
+ const header = [place.trim(), geo?.plus_code].filter(Boolean).join(' - ');
+ if (header) lines.push(header);
+
+ // description
+ if (description.trim()) {
+ lines.push('');
+ lines.push(description.trim());
+ }
+
+ // decimal coords only (6 digits), no DMS
if (geo) {
lines.push('');
lines.push(`${geo.lat.toFixed(6)}, ${geo.lon.toFixed(6)}`);
- lines.push(`${geo.dms}`);
- lines.push(`Plus code: ${geo.plus_code}`);
}
- if (place.trim()) lines.push(place.trim());
- if (source.trim()) {
+
+ // mention (@GeoConfirmed by default)
+ if (mention.trim()) {
lines.push('');
- lines.push(`Source: ${source.trim()}`);
+ lines.push(mention.trim());
}
- if (attribution.trim()) {
+
+ // source
+ if (source.trim()) {
lines.push('');
- lines.push(attribution.trim());
+ lines.push('Source:');
+ lines.push(source.trim());
}
+
return lines.join('\n');
}
function regenerate() {
- text = buildText();
- edited = false;
+ tweet1 = buildTweet1();
+ tweet1Edited = false;
}
function weightedLength(t) {
@@ -101,38 +142,226 @@
return [...stripped].length + urls * URL_WEIGHT;
}
- const count = $derived(weightedLength(text));
- const over = $derived(count > X_LIMIT);
-
- /** Split into a numbered thread at word boundaries under the weighted limit. */
- const thread = $derived.by(() => {
- if (!over) return null;
- const words = text.split(/(\s+)/);
- const parts = [];
- let current = '';
- for (const w of words) {
- const suffixReserve = 8; // " (99/99)"
- if (weightedLength(current + w) > X_LIMIT - suffixReserve && current.trim()) {
- parts.push(current.trim());
- current = w.trimStart();
- } else {
- current += w;
- }
- }
- if (current.trim()) parts.push(current.trim());
- return parts.map((p, i) => `${p}\n(${i + 1}/${parts.length})`);
- });
+ function tweet2Text() {
+ const label = mediaType === 'video' ? '2/ Video:' : '2/ Image(s):';
+ return mediaText.trim() ? `${label}\n${mediaText.trim()}` : label;
+ }
+
+ const tweet1Count = $derived(weightedLength(tweet1));
+ const tweet1Over = $derived(tweet1Count > X_LIMIT);
+
+ function addExtraTweet() {
+ extraTweets.push({ id: ++extraSeq, text: '' });
+ }
+
+ function removeExtraTweet(id) {
+ const i = extraTweets.findIndex((t) => t.id === id);
+ if (i !== -1) extraTweets.splice(i, 1);
+ }
async function copy(value) {
await navigator.clipboard.writeText(value);
toast('Copied to clipboard', 'ok', 1600);
}
+
+ async function copyAll() {
+ const parts = [tweet1];
+ if (mediaEnabled && mediaType !== 'none') parts.push(tweet2Text());
+ for (const t of extraTweets) {
+ if (t.text.trim()) parts.push(t.text.trim());
+ }
+ await navigator.clipboard.writeText(parts.join('\n\n---\n\n'));
+ toast('All tweets copied', 'ok', 1800);
+ }
+
+ // ---- media picker -------------------------------------------------------
+
+ async function openPicker() {
+ if (!caseState.current) {
+ toast('Open a case to pick from your media', 'warn');
+ return;
+ }
+ try {
+ mediaLibrary = await api.get(`/api/cases/${caseState.current.id}/media`);
+ pickerOpen = true;
+ } catch (e) {
+ toast(e.message, 'danger');
+ }
+ }
+
+ function pickMedia(item) {
+ mediaPath = item.path;
+ // auto-select the matching media type from the item's kind
+ if (item.kind === 'video') mediaType = 'video';
+ else if (item.kind === 'image') mediaType = 'images';
+ pickerOpen = false;
+ }
+
+ function clearMedia() {
+ mediaPath = null;
+ }
+
+ const mediaHref = $derived(
+ mediaPath && caseState.current ? `/files/${caseState.current.id}/${mediaPath}` : null
+ );
+
+ const proofHref = $derived(
+ proofPng && caseState.current ? `/files/${caseState.current.id}/${proofPng}` : null
+ );
+
+ // ---- one-click image copy / media download ------------------------------
+
+ /** Rasterise any image blob to PNG (the only format browsers reliably put on
+ * the clipboard) so it can be pasted straight into the X composer. */
+ function toPngBlob(blob) {
+ return new Promise((resolve, reject) => {
+ const url = URL.createObjectURL(blob);
+ const img = new Image();
+ img.onload = () => {
+ const canvas = document.createElement('canvas');
+ canvas.width = img.naturalWidth;
+ canvas.height = img.naturalHeight;
+ canvas.getContext('2d').drawImage(img, 0, 0);
+ URL.revokeObjectURL(url);
+ canvas.toBlob((out) => (out ? resolve(out) : reject(new Error('encode failed'))), 'image/png');
+ };
+ img.onerror = () => {
+ URL.revokeObjectURL(url);
+ reject(new Error('load failed'));
+ };
+ img.src = url;
+ });
+ }
+
+ /** Copy an image into the clipboard so it can be pasted (Ctrl+V) into X. */
+ async function copyImage(url) {
+ try {
+ const res = await fetch(url);
+ let blob = await res.blob();
+ if (blob.type !== 'image/png') blob = await toPngBlob(blob);
+ await navigator.clipboard.write([new ClipboardItem({ 'image/png': blob })]);
+ toast('Image copied — paste it into X (Ctrl+V)', 'ok', 2400);
+ } catch (e) {
+ toast(`Could not copy image: ${e.message}`, 'danger');
+ }
+ }
+
+ /** Save a media file locally (X has no paste for video — drag it in from here). */
+ function downloadMedia(url, path) {
+ const a = document.createElement('a');
+ a.href = url;
+ a.download = (path ?? '').split('/').pop() || 'media';
+ document.body.appendChild(a);
+ a.click();
+ a.remove();
+ toast('Downloaded — drag it into X', 'info', 2600);
+ }
+
+ // ---- draft persistence --------------------------------------------------
+
+ function snapshot() {
+ return {
+ description,
+ coordsText,
+ place,
+ mention,
+ source,
+ proofPng,
+ tweet1,
+ tweet1Edited,
+ mediaEnabled,
+ mediaType,
+ mediaText,
+ mediaPath,
+ extraTweets: extraTweets.map((t) => ({ text: t.text })),
+ };
+ }
+
+ function draftTitle() {
+ return (place.trim() || description.trim() || 'Untitled post').slice(0, 120);
+ }
+
+ async function saveDraft() {
+ if (!caseState.current) {
+ toast('Open a case to save a draft', 'warn');
+ return;
+ }
+ saving = true;
+ try {
+ const body = { title: draftTitle(), state: snapshot() };
+ if (draftName) body.name = draftName;
+ const r = await api.post(`/api/cases/${caseState.current.id}/drafts`, body);
+ draftName = r.name;
+ await reloadCase(); // surface the post entity in the sidebar
+ toast('Draft saved', 'ok', 1600);
+ } catch (e) {
+ toast(`Draft not saved: ${e.message}`, 'danger');
+ } finally {
+ saving = false;
+ }
+ }
+
+ async function loadDraft(name) {
+ if (!caseState.current) return;
+ try {
+ const doc = await api.get(`/api/cases/${caseState.current.id}/drafts/${name}`);
+ const s = doc.state ?? {};
+ description = s.description ?? '';
+ coordsText = s.coordsText ?? '';
+ place = s.place ?? '';
+ mention = s.mention ?? '@GeoConfirmed';
+ source = s.source ?? '';
+ proofPng = s.proofPng ?? null;
+ mediaEnabled = s.mediaEnabled ?? true;
+ mediaType = s.mediaType ?? 'none';
+ mediaText = s.mediaText ?? '';
+ mediaPath = s.mediaPath ?? null;
+ extraTweets = (s.extraTweets ?? []).map((t) => ({ id: ++extraSeq, text: t.text ?? '' }));
+ draftName = name;
+ // restore geo facts from the coordinates, then honor any manual tweet edits
+ if (s.coordsText?.trim()) {
+ try {
+ geo = await api.post('/api/geo/parse', { text: s.coordsText });
+ } catch {
+ geo = null;
+ }
+ } else {
+ geo = null;
+ }
+ tweet1 = s.tweet1 ?? buildTweet1();
+ tweet1Edited = s.tweet1Edited ?? false;
+ toast('Draft loaded', 'ok', 1400);
+ } catch (e) {
+ toast(`Could not load draft: ${e.message}`, 'danger');
+ }
+ }
+
+ // ---- publish (prefill X compose — Ozimut never posts on your behalf) -----
+
+ async function publish() {
+ // X's web intent only prefills the first post; copy the whole thread so the
+ // rest can be pasted as replies, then open the compose window.
+ await copyAll();
+ const url = `https://x.com/intent/post?text=${encodeURIComponent(tweet1)}`;
+ window.open(url, '_blank', 'noopener,noreferrer');
+ toast('Opened X — thread copied for the replies', 'info', 3200);
+ }
</script>
<div class="tool">
<div class="tool-header">
- <h2>Post Composer</h2>
- <span class="sub">publishable post from your proof — you copy, you publish, Ozimut never posts</span>
+ <div class="head-text">
+ <h2>Post Composer</h2>
+ <span class="sub">publishable post from your proof — you copy, you publish, Ozimut never posts</span>
+ </div>
+ <div class="head-actions">
+ <button class="btn btn-ghost btn-sm" onclick={saveDraft} disabled={saving}>
+ <Icon name="save" size={14} /> {draftName ? 'Save draft' : 'Save as draft'}
+ </button>
+ <button class="btn btn-primary btn-sm" onclick={publish} disabled={!tweet1.trim()} title="Copy the thread and open X compose prefilled — Ozimut never posts for you">
+ <Icon name="post" size={14} /> Publish on X
+ </button>
+ </div>
</div>
<div class="tool-body">
@@ -140,27 +369,25 @@
<!-- left column: ingredients -->
<div class="col">
<div class="field">
- <label class="label" for="pc-title">What was geolocated</label>
+ <label class="label" for="pc-desc">Description</label>
<input
- id="pc-title"
+ id="pc-desc"
class="input"
- placeholder="e.g. Strike on a warehouse, north of Kharkiv"
- bind:value={title}
+ placeholder="A formation of 13 helicopters was spotted heading East"
+ bind:value={description}
onchange={regenerate}
/>
</div>
<div class="field">
<label class="label" for="pc-coords">Coordinates</label>
- <div class="row">
- <input
- id="pc-coords"
- class="input mono"
- placeholder="50.4501, 30.5234"
- bind:value={coordsText}
- onchange={resolveCoords}
- />
- </div>
+ <input
+ id="pc-coords"
+ class="input mono"
+ placeholder="10.303315, -66.874095"
+ bind:value={coordsText}
+ onchange={resolveCoords}
+ />
{#if geo}
<div class="geo-facts card">
<button class="fact mono" onclick={() => copy(`${geo.lat.toFixed(6)}, ${geo.lon.toFixed(6)}`)} title="Copy">
@@ -188,96 +415,219 @@
<input
id="pc-place"
class="input"
- placeholder="Village, Oblast, Country"
+ placeholder="Village, State, Country"
bind:value={place}
onchange={regenerate}
/>
</div>
<div class="field">
- <label class="label" for="pc-source">Source credit</label>
+ <label class="label" for="pc-mention">Mention</label>
<input
- id="pc-source"
- class="input"
- placeholder="https://t.me/… (original post)"
- bind:value={source}
+ id="pc-mention"
+ class="input mono"
+ placeholder="@GeoConfirmed"
+ bind:value={mention}
onchange={regenerate}
/>
</div>
<div class="field">
- <label class="label" for="pc-attr">Imagery attribution</label>
+ <label class="label" for="pc-source">Source</label>
<input
- id="pc-attr"
+ id="pc-source"
class="input"
- placeholder="Imagery: Esri, Maxar, …"
- bind:value={attribution}
+ placeholder="https://instagram.com/… (original post)"
+ bind:value={source}
onchange={regenerate}
/>
</div>
{#if proofPng && caseState.current}
<div class="field">
- <span class="label">Attached proof</span>
- <a href={`/files/${caseState.current.id}/${proofPng}`} target="_blank" rel="noreferrer">
- <img class="proof-preview card" src={`/files/${caseState.current.id}/${proofPng}`} alt="proof" />
+ <div class="proof-head">
+ <span class="label" style="margin:0">Attached proof</span>
+ <button class="btn btn-ghost btn-sm" onclick={() => copyImage(proofHref)} title="Copy the image — paste it into X">
+ <Icon name="copy" size={13} /> Copy image
+ </button>
+ </div>
+ <a href={proofHref} target="_blank" rel="noreferrer">
+ <img class="proof-preview card" src={proofHref} alt="proof" />
</a>
</div>
{/if}
</div>
- <!-- right column: the post -->
+ <!-- right column: the thread -->
<div class="col">
- <div class="field grow">
- <div class="post-head">
- <span class="label" style="margin: 0">Post text</span>
- {#if edited}
+
+ <!-- Tweet 1: geolocation -->
+ <div class="tweet-block card">
+ <div class="tweet-head">
+ <span class="tweet-num">1</span>
+ <span class="label" style="margin:0">Geolocation tweet</span>
+ {#if tweet1Edited}
<button class="btn btn-ghost btn-sm" onclick={regenerate} title="Rebuild from the fields">
<Icon name="compass" size={13} /> regenerate
</button>
{/if}
- <span class="counter" class:over>{count}/{X_LIMIT}</span>
+ <span class="counter" class:over={tweet1Over}>{tweet1Count}/{X_LIMIT}</span>
+ <button class="btn btn-ghost btn-sm" onclick={() => copy(tweet1)} disabled={!tweet1.trim()}>
+ <Icon name="copy" size={13} /> Copy
+ </button>
</div>
<textarea
class="textarea post-text mono"
- bind:value={text}
- oninput={() => (edited = true)}
- rows="12"
+ bind:value={tweet1}
+ oninput={() => (tweet1Edited = true)}
+ rows="11"
></textarea>
- <div class="post-actions">
- <button class="btn btn-primary" onclick={() => copy(text)} disabled={!text.trim()}>
- <Icon name="copy" size={15} /> Copy post
- </button>
- {#if over}
- <span class="over-hint">over the X limit — thread below</span>
+ </div>
+
+ <!-- Tweet 2: media (Video / Image(s)) -->
+ {#if mediaEnabled}
+ <div class="tweet-block card">
+ <div class="tweet-head">
+ <span class="tweet-num">2</span>
+ <span class="label" style="margin:0">Media</span>
+ <div class="media-tabs">
+ <button
+ class="btn btn-sm"
+ class:btn-primary={mediaType === 'video'}
+ class:btn-ghost={mediaType !== 'video'}
+ onclick={() => (mediaType = mediaType === 'video' ? 'none' : 'video')}
+ >Video</button>
+ <button
+ class="btn btn-sm"
+ class:btn-primary={mediaType === 'images'}
+ class:btn-ghost={mediaType !== 'images'}
+ onclick={() => (mediaType = mediaType === 'images' ? 'none' : 'images')}
+ >Image(s)</button>
+ </div>
+ {#if mediaType !== 'none'}
+ <span class="counter">{weightedLength(tweet2Text())}/{X_LIMIT}</span>
+ <button class="btn btn-ghost btn-sm" onclick={() => copy(tweet2Text())}>
+ <Icon name="copy" size={13} /> Copy
+ </button>
{/if}
+ <button class="btn btn-ghost btn-sm danger-hover" onclick={() => (mediaEnabled = false)} title="Remove media tweet">
+ <Icon name="x" size={13} />
+ </button>
</div>
+ {#if mediaType !== 'none'}
+ <div class="media-prefix">{mediaType === 'video' ? '2/ Video:' : '2/ Image(s):'}</div>
+ <textarea
+ class="textarea post-text mono"
+ placeholder="Paste URL or describe the media…"
+ bind:value={mediaText}
+ rows="3"
+ ></textarea>
+ <div class="media-attach">
+ <button class="btn btn-ghost btn-sm" onclick={openPicker}>
+ <Icon name="media" size={13} /> Choose from library
+ </button>
+ {#if mediaPath}
+ <span class="attach-chip">
+ {#if mediaHref}
+ <a href={mediaHref} target="_blank" rel="noreferrer" title={mediaPath}>
+ {mediaPath.replace(/^media\//, '')}
+ </a>
+ {:else}
+ {mediaPath.replace(/^media\//, '')}
+ {/if}
+ <button class="chip-x" onclick={clearMedia} title="Detach media">
+ <Icon name="x" size={11} />
+ </button>
+ </span>
+ {#if mediaType === 'images'}
+ <button class="btn btn-ghost btn-sm" onclick={() => copyImage(mediaHref)} title="Copy the image — paste it into X">
+ <Icon name="copy" size={13} /> Copy image
+ </button>
+ {:else}
+ <button class="btn btn-ghost btn-sm" onclick={() => downloadMedia(mediaHref, mediaPath)} title="Download the video, then drag it into X">
+ <Icon name="download" size={13} /> Download
+ </button>
+ {/if}
+ {/if}
+ </div>
+ {:else}
+ <span class="muted">Toggle Video or Image(s) to add a media tweet</span>
+ {/if}
</div>
+ {/if}
- {#if thread}
- <div class="field">
- <span class="label">As a thread ({thread.length} posts)</span>
- <div class="thread">
- {#each thread as part, i (i)}
- <div class="thread-post card">
- <pre>{part}</pre>
- <button class="btn btn-ghost btn-sm" onclick={() => copy(part)} title="Copy this post">
- <Icon name="copy" size={13} />
- </button>
- </div>
- {/each}
+ <!-- Extra context tweets (3, 4, …) -->
+ {#each extraTweets as tweet, i (tweet.id)}
+ <div class="tweet-block card">
+ <div class="tweet-head">
+ <span class="tweet-num">{i + 3}</span>
+ <span class="label" style="margin:0">Context</span>
+ <span class="counter" class:over={weightedLength(tweet.text) > X_LIMIT}>
+ {weightedLength(tweet.text)}/{X_LIMIT}
+ </span>
+ <button class="btn btn-ghost btn-sm" onclick={() => copy(tweet.text)} disabled={!tweet.text.trim()}>
+ <Icon name="copy" size={13} /> Copy
+ </button>
+ <button class="btn btn-ghost btn-sm danger-hover" onclick={() => removeExtraTweet(tweet.id)} title="Remove tweet">
+ <Icon name="x" size={13} />
+ </button>
</div>
+ <textarea
+ class="textarea post-text mono"
+ placeholder="Additional context…"
+ bind:value={tweet.text}
+ rows="4"
+ ></textarea>
</div>
- {/if}
+ {/each}
+
+ <div class="thread-actions">
+ {#if !mediaEnabled}
+ <button class="btn btn-ghost btn-sm" onclick={() => (mediaEnabled = true)}>
+ <Icon name="plus" size={13} /> Add media tweet
+ </button>
+ {/if}
+ <button class="btn btn-ghost btn-sm" onclick={addExtraTweet}>
+ <Icon name="plus" size={13} /> Add context tweet
+ </button>
+ <button class="btn btn-ghost btn-sm" onclick={copyAll}>
+ <Icon name="copy" size={13} /> Copy all
+ </button>
+ </div>
+
</div>
</div>
</div>
</div>
+{#if pickerOpen}
+ <Modal title="Choose a media" width="640px" onclose={() => (pickerOpen = false)}>
+ {#if mediaLibrary.length === 0}
+ <p class="picker-empty">No media in this case yet — import or download some in the Media tab.</p>
+ {:else}
+ <div class="picker-grid">
+ {#each mediaLibrary as item (item.path)}
+ <button class="picker-item" onclick={() => pickMedia(item)} title={item.path}>
+ <div class="picker-thumb">
+ {#if item.thumbnail}
+ <img src={`/files/${caseState.current.id}/${item.thumbnail}`} alt={item.path} />
+ {:else}
+ <Icon name={item.kind === 'video' ? 'video' : item.kind === 'audio' ? 'audio' : 'file'} size={24} />
+ {/if}
+ {#if item.kind === 'video'}<span class="kind-badge"><Icon name="video" size={11} /></span>{/if}
+ </div>
+ <span class="picker-name">{(item.label || item.path).replace(/^media\//, '')}</span>
+ </button>
+ {/each}
+ </div>
+ {/if}
+ </Modal>
+{/if}
+
<style>
.layout {
display: grid;
- grid-template-columns: minmax(320px, 460px) minmax(360px, 1fr);
+ grid-template-columns: minmax(300px, 420px) minmax(360px, 1fr);
gap: 26px;
padding: 20px;
max-width: 1200px;
@@ -288,8 +638,6 @@
gap: 16px;
min-width: 0;
}
- .field.grow { display: flex; flex-direction: column; }
- .row { display: flex; gap: 8px; }
.geo-facts {
margin-top: 8px;
padding: 8px 10px;
@@ -325,12 +673,38 @@
object-fit: contain;
padding: 6px;
}
- .post-head {
+ .proof-head {
display: flex;
align-items: center;
gap: 10px;
margin-bottom: 6px;
}
+
+ /* Thread / tweet blocks */
+ .tweet-block {
+ padding: 12px 14px;
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ }
+ .tweet-head {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ }
+ .tweet-num {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 22px;
+ height: 22px;
+ border-radius: 50%;
+ background: var(--bg-3);
+ font-size: var(--fs-xs);
+ font-weight: 700;
+ color: var(--text-2);
+ flex-shrink: 0;
+ }
.counter {
margin-left: auto;
font-size: var(--fs-xs);
@@ -340,38 +714,138 @@
}
.counter.over { color: var(--danger); }
.post-text {
- min-height: 260px;
font-size: var(--fs-sm);
line-height: 1.6;
+ min-height: 0;
}
- .post-actions {
+ .media-tabs {
display: flex;
- align-items: center;
- gap: 12px;
- margin-top: 10px;
+ gap: 4px;
}
- .over-hint {
+ .media-prefix {
font-size: var(--fs-xs);
- color: var(--warn);
+ font-family: var(--font-mono);
+ color: var(--text-2);
+ padding: 2px 0;
+ }
+ .muted {
+ font-size: var(--fs-xs);
+ color: var(--text-3);
+ padding: 4px 0;
}
- .thread {
+ .thread-actions {
+ display: flex;
+ gap: 10px;
+ align-items: center;
+ padding: 4px 0;
+ flex-wrap: wrap;
+ }
+ .danger-hover:hover { color: var(--danger); }
+
+ /* header actions */
+ .tool-header {
+ display: flex;
+ align-items: flex-start;
+ gap: 16px;
+ }
+ .head-text {
display: flex;
flex-direction: column;
+ min-width: 0;
+ }
+ .head-actions {
+ margin-left: auto;
+ display: flex;
gap: 8px;
+ flex-shrink: 0;
}
- .thread-post {
+
+ /* media attachment */
+ .media-attach {
display: flex;
- align-items: flex-start;
+ align-items: center;
gap: 8px;
- padding: 10px 12px;
+ flex-wrap: wrap;
+ padding-top: 2px;
}
- .thread-post pre {
- flex: 1;
- margin: 0;
- font-family: var(--font-mono);
+ .attach-chip {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ padding: 3px 6px 3px 9px;
+ background: var(--bg-3);
+ border-radius: var(--r-sm);
font-size: var(--fs-xs);
- white-space: pre-wrap;
- word-break: break-word;
+ font-family: var(--font-mono);
+ color: var(--text-1);
+ max-width: 100%;
+ }
+ .attach-chip a {
color: var(--text-1);
+ text-decoration: none;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ .attach-chip a:hover { color: var(--accent); }
+ .chip-x {
+ display: inline-flex;
+ color: var(--text-3);
+ }
+ .chip-x:hover { color: var(--danger); }
+
+ /* media picker */
+ .picker-empty {
+ color: var(--text-3);
+ font-size: var(--fs-sm);
+ padding: 8px 0;
+ }
+ .picker-grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
+ gap: 10px;
+ }
+ .picker-item {
+ display: flex;
+ flex-direction: column;
+ gap: 5px;
+ text-align: left;
+ }
+ .picker-thumb {
+ position: relative;
+ aspect-ratio: 4 / 3;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ background: var(--bg-2);
+ border: 1px solid var(--border);
+ border-radius: var(--r-md);
+ overflow: hidden;
+ color: var(--text-3);
+ }
+ .picker-item:hover .picker-thumb {
+ border-color: var(--accent);
+ }
+ .picker-thumb img {
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ }
+ .kind-badge {
+ position: absolute;
+ bottom: 4px;
+ right: 4px;
+ background: rgba(0, 0, 0, 0.6);
+ border-radius: var(--r-sm);
+ padding: 2px;
+ color: #fff;
+ display: inline-flex;
+ }
+ .picker-name {
+ font-size: var(--fs-xs);
+ color: var(--text-2);
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
}
</style>
diff --git a/frontend/src/tools/ProofComposer.svelte b/frontend/src/tools/ProofComposer.svelte
index 7bc16e7..8262a8b 100644
--- a/frontend/src/tools/ProofComposer.svelte
+++ b/frontend/src/tools/ProofComposer.svelte
@@ -92,6 +92,15 @@
}
});
+ // consume an "open this proof" handoff from the sidebar
+ $effect(() => {
+ if (uiState.tool === 'proof' && uiState.openProof && caseState.current) {
+ const name = uiState.openProof;
+ uiState.openProof = null;
+ openProof({ name });
+ }
+ });
+
// rebuild canvas whenever the document changes
$effect(() => {
JSON.stringify([
@@ -121,7 +130,7 @@
kind: 'satellite', attribution: s.attribution, lat: s.lat, lon: s.lon,
zoom: s.zoom, provider: s.provider_label, date: s.fetched_at?.slice(0, 10),
},
- caption: `${s.provider_label} · ${s.lat.toFixed(5)}, ${s.lon.toFixed(5)} · ${s.fetched_at?.slice(0, 10) ?? ''}`,
+ caption: `${s.provider_label} · ${s.lat.toFixed(6)}, ${s.lon.toFixed(6)} · ${s.fetched_at?.slice(0, 10) ?? ''}`,
};
}
@@ -146,7 +155,7 @@
pickerItems = [
...sats.map((s) => ({
...satPanelInput(s),
- label: `${s.lat.toFixed(4)}, ${s.lon.toFixed(4)} · z${s.zoom}`,
+ label: `${s.lat.toFixed(6)}, ${s.lon.toFixed(6)} · z${s.zoom}`,
thumb: s.path,
kind: 'satellite',
})),
diff --git a/frontend/src/tools/Satellite.svelte b/frontend/src/tools/Satellite.svelte
index 5473fce..0439066 100644
--- a/frontend/src/tools/Satellite.svelte
+++ b/frontend/src/tools/Satellite.svelte
@@ -1,10 +1,11 @@
<script>
- import { onMount } from 'svelte';
+ import { onMount, tick } from 'svelte';
import L from 'leaflet';
import 'leaflet/dist/leaflet.css';
import { api } from '../lib/api.js';
import { caseState, uiState, ensureCase, reloadCase, toast } from '../lib/state.svelte.js';
import Icon from '../components/Icon.svelte';
+ import Modal from '../components/Modal.svelte';
let mapEl;
let map;
@@ -15,23 +16,37 @@
let center = $state({ lat: 48.8584, lon: 2.2945, zoom: 16 });
let size = $state('1000x700');
let crosshair = $state(true);
+ let bearing = $state(0);
let capturing = $state(false);
let captures = $state([]);
let capturesFor = $state(null);
+ let capturesCollapsed = $state(false);
+ let mapReady = $state(false);
onMount(async () => {
providers = await api.get('/api/satellite/providers');
+ // leaflet-rotate patches the global L, so expose it before importing.
+ window.L = L;
+ await import('leaflet-rotate');
map = L.map(mapEl, {
center: [center.lat, center.lon],
zoom: center.zoom,
zoomControl: true,
attributionControl: true,
+ rotate: true,
+ rotateControl: false,
+ touchRotate: true,
+ shiftKeyRotate: true,
});
setLayer();
map.on('moveend zoomend', () => {
const c = map.getCenter();
center = { lat: c.lat, lon: c.lng, zoom: map.getZoom() };
});
+ map.on('rotate', () => {
+ bearing = Math.round(map.getBearing());
+ });
+ mapReady = true;
return () => map.remove();
});
@@ -59,6 +74,15 @@
}
});
+ // fly to coordinates handed off from the sidebar (place entity click)
+ $effect(() => {
+ const target = uiState.gotoCoords;
+ if (mapReady && target && Number.isFinite(target.lat) && Number.isFinite(target.lon)) {
+ uiState.gotoCoords = null;
+ map.setView([target.lat, target.lon], Math.max(map.getZoom(), 16));
+ }
+ });
+
async function goTo() {
const text = coordsText.trim();
if (!text) return;
@@ -70,6 +94,19 @@
}
}
+ function setBearing(deg) {
+ if (!map) return;
+ map.setBearing(((deg % 360) + 360) % 360);
+ }
+
+ function nudgeBearing(delta) {
+ setBearing(bearing + delta);
+ }
+
+ function resetNorth() {
+ setBearing(0);
+ }
+
async function captureCrop() {
if (capturing) return;
capturing = true;
@@ -84,6 +121,7 @@
height,
provider: providerId,
crosshair,
+ bearing,
});
captures = [result, ...captures];
await reloadCase();
@@ -107,19 +145,61 @@
captures = captures.filter((c) => c.path !== item.path);
}
+ // --- notes modal ---
+ let notesItem = $state(null);
+ let notesText = $state('');
+ let notesSaving = $state(false);
+
+ function openNotes(item) {
+ notesItem = item;
+ notesText = item.notes ?? '';
+ }
+
+ async function saveNotes() {
+ if (!notesItem) return;
+ notesSaving = true;
+ try {
+ const updated = await api.patch(
+ `/api/cases/${caseState.current.id}/satellite`,
+ { path: notesItem.path, notes: notesText }
+ );
+ const idx = captures.findIndex((c) => c.path === notesItem.path);
+ if (idx !== -1) captures[idx] = updated;
+ notesItem = null;
+ toast('Saved', 'ok', 1600);
+ } catch (e) {
+ toast(e.message, 'danger');
+ } finally {
+ notesSaving = false;
+ }
+ }
+
function sendToComposer(item) {
if (!uiState.composeQueue.includes(item.path)) uiState.composeQueue.push(item.path);
uiState.tool = 'proof';
}
function fmt(value) {
- return value.toFixed(5);
+ return value.toFixed(6);
}
async function copyCoords() {
await navigator.clipboard.writeText(`${fmt(center.lat)}, ${fmt(center.lon)}`);
toast('Coordinates copied', 'ok', 1600);
}
+
+ async function toggleCaptures() {
+ capturesCollapsed = !capturesCollapsed;
+ // the map container just resized — let Leaflet redraw tiles for the new size
+ await tick();
+ map?.invalidateSize();
+ }
+
+ function flyToCapture(item) {
+ if (!map || !Number.isFinite(item.lat) || !Number.isFinite(item.lon)) return;
+ map.setView([item.lat, item.lon], item.zoom);
+ setBearing(item.bearing ?? 0);
+ }
</script>
<div class="tool">
@@ -171,6 +251,41 @@
</button>
</div>
+ <div class="rotate-ctl card">
+ <button
+ class="compass"
+ onclick={resetNorth}
+ title={bearing ? 'Reset to north' : 'North up'}
+ aria-label="Reset to north"
+ >
+ <svg width="34" height="34" viewBox="0 0 34 34" style="transform: rotate({-bearing}deg)">
+ <circle cx="17" cy="17" r="15" fill="none" stroke="currentColor" stroke-width="1" opacity="0.4" />
+ <polygon points="17,4 13,18 17,15 21,18" fill="#e5484d" />
+ <polygon points="17,30 13,16 17,19 21,16" fill="#8a93a5" />
+ </svg>
+ <span class="n">N</span>
+ </button>
+ <div class="rotate-actions">
+ <button class="rbtn" onclick={() => nudgeBearing(-15)} title="Rotate left 15°" aria-label="Rotate left">
+ <Icon name="chevronLeft" size={15} />
+ </button>
+ <span class="deg mono">{bearing}°</span>
+ <button class="rbtn" onclick={() => nudgeBearing(15)} title="Rotate right 15°" aria-label="Rotate right">
+ <Icon name="chevronRight" size={15} />
+ </button>
+ </div>
+ <input
+ class="rotate-slider"
+ type="range"
+ min="0"
+ max="359"
+ value={bearing}
+ oninput={(e) => setBearing(+e.target.value)}
+ title="Drag to rotate the view"
+ aria-label="Map rotation"
+ />
+ </div>
+
<div class="capture-bar card">
<select class="select" bind:value={providerId} title="Imagery provider">
{#each providers as p (p.id)}
@@ -198,12 +313,20 @@
</div>
</div>
- <aside class="captures">
- <div class="cap-head">
+ <aside class="captures" class:collapsed={capturesCollapsed}>
+ <button
+ type="button"
+ class="cap-head"
+ onclick={toggleCaptures}
+ title={capturesCollapsed ? 'Show captures' : 'Hide captures'}
+ >
+ <Icon name={capturesCollapsed ? 'chevronLeft' : 'chevronRight'} size={15} />
<span class="label" style="margin:0">Captures</span>
<span class="count">{captures.length}</span>
- </div>
- {#if !captures.length}
+ </button>
+ {#if capturesCollapsed}
+ <!-- collapsed: header acts as the toggle back to the list -->
+ {:else if !captures.length}
<div class="none">
Captured crops land in the case with full provenance: provider, zoom, date,
attribution.
@@ -212,16 +335,30 @@
<div class="cap-list">
{#each captures as item (item.path)}
<div class="cap card fade-up">
- <img
- src={`/files/${caseState.current.id}/${item.path}`}
- alt={item.filename}
- loading="lazy"
- />
- <div class="cap-meta">
- <span class="mono coords">{item.lat.toFixed(5)}, {item.lon.toFixed(5)}</span>
- <span class="prov">z{item.zoom} · {item.provider_label} · {item.fetched_at?.slice(0, 10)}</span>
- </div>
+ <button
+ type="button"
+ class="cap-goto"
+ title="Show on map (same zoom)"
+ onclick={() => flyToCapture(item)}
+ >
+ <img
+ src={`/files/${caseState.current.id}/${item.path}`}
+ alt={item.filename}
+ loading="lazy"
+ />
+ <div class="cap-meta">
+ <span class="mono coords">{item.lat.toFixed(6)}, {item.lon.toFixed(6)}</span>
+ <span class="prov">z{item.zoom}{item.bearing ? ` · ${Math.round(item.bearing)}°` : ''} · {item.provider_label} · {item.fetched_at?.slice(0, 10)}</span>
+ </div>
+ </button>
<div class="cap-actions">
+ <button
+ class="btn btn-ghost btn-sm"
+ title="Notes"
+ onclick={() => openNotes(item)}
+ >
+ <Icon name="note" size={14} />
+ </button>
<button
class="btn btn-ghost btn-sm"
title="Send to Proof Composer"
@@ -246,6 +383,9 @@
<Icon name="trash" size={14} />
</button>
</div>
+ {#if item.notes}
+ <div class="cap-notes">{item.notes}</div>
+ {/if}
</div>
{/each}
</div>
@@ -254,6 +394,44 @@
</div>
</div>
+<!-- satellite notes modal -->
+{#if notesItem}
+ <Modal title="Capture notes" onclose={() => (notesItem = null)} width="420px">
+ <div class="sat-info-rows">
+ <div class="sat-info-row">
+ <span class="sat-info-label">Coordinates</span>
+ <span class="mono">{notesItem.lat?.toFixed(6)}, {notesItem.lon?.toFixed(6)}</span>
+ </div>
+ <div class="sat-info-row">
+ <span class="sat-info-label">Provider</span>
+ <span>{notesItem.provider_label}</span>
+ </div>
+ <div class="sat-info-row">
+ <span class="sat-info-label">Zoom</span>
+ <span>{notesItem.zoom}</span>
+ </div>
+ <div class="sat-info-row">
+ <span class="sat-info-label">Date</span>
+ <span class="mono">{notesItem.fetched_at?.slice(0, 10)}</span>
+ </div>
+ </div>
+ <hr style="border:none;border-top:1px solid var(--border);margin:12px 0" />
+ <label style="display:block;font-size:var(--fs-xs);color:var(--text-3);margin-bottom:5px">Notes</label>
+ <textarea
+ class="textarea"
+ rows="5"
+ placeholder="Add observations, links, context…"
+ bind:value={notesText}
+ ></textarea>
+ <div style="display:flex;gap:8px;justify-content:flex-end;margin-top:12px">
+ <button class="btn" onclick={() => (notesItem = null)}>Cancel</button>
+ <button class="btn btn-primary" onclick={saveNotes} disabled={notesSaving}>
+ {notesSaving ? 'Saving…' : 'Save'}
+ </button>
+ </div>
+ </Modal>
+{/if}
+
<style>
.spacer {
flex: 1;
@@ -314,6 +492,76 @@
color: var(--text-3);
font-size: var(--fs-xs);
}
+ .rotate-ctl {
+ position: absolute;
+ top: 12px;
+ right: 12px;
+ z-index: 600;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 8px;
+ padding: 10px;
+ background: rgba(16, 22, 35, 0.88);
+ backdrop-filter: blur(6px);
+ box-shadow: var(--shadow-2);
+ }
+ .compass {
+ position: relative;
+ display: grid;
+ place-items: center;
+ width: 34px;
+ height: 34px;
+ color: var(--text-2);
+ cursor: pointer;
+ }
+ .compass:hover {
+ color: var(--accent);
+ }
+ .compass svg {
+ transition: transform 0.1s linear;
+ }
+ .compass .n {
+ position: absolute;
+ top: -3px;
+ left: 50%;
+ transform: translateX(-50%);
+ font-size: 9px;
+ font-weight: 700;
+ color: var(--text-3);
+ pointer-events: none;
+ }
+ .rotate-actions {
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ }
+ .rbtn {
+ display: grid;
+ place-items: center;
+ width: 24px;
+ height: 24px;
+ border: 1px solid var(--border);
+ border-radius: var(--radius-1);
+ background: var(--bg-2);
+ color: var(--text-2);
+ cursor: pointer;
+ }
+ .rbtn:hover {
+ color: var(--accent);
+ border-color: var(--accent);
+ }
+ .deg {
+ min-width: 36px;
+ text-align: center;
+ font-size: var(--fs-xs);
+ color: var(--text-1);
+ }
+ .rotate-slider {
+ width: 108px;
+ accent-color: var(--accent);
+ cursor: pointer;
+ }
.capture-bar {
position: absolute;
bottom: 16px;
@@ -364,11 +612,36 @@
display: flex;
flex-direction: column;
}
+ .captures.collapsed {
+ width: 42px;
+ }
.cap-head {
display: flex;
align-items: center;
justify-content: space-between;
+ gap: 8px;
padding: 14px 14px 8px;
+ width: 100%;
+ background: none;
+ border: none;
+ color: var(--text-1);
+ font: inherit;
+ text-align: left;
+ cursor: pointer;
+ }
+ .cap-head:hover {
+ color: var(--accent);
+ }
+ .captures.collapsed .cap-head {
+ flex-direction: column;
+ align-items: center;
+ justify-content: flex-start;
+ gap: 10px;
+ padding: 14px 0;
+ height: 100%;
+ }
+ .captures.collapsed .cap-head .label {
+ writing-mode: vertical-rl;
}
.count {
font-size: var(--fs-xs);
@@ -390,6 +663,17 @@
}
.cap {
overflow: hidden;
+ flex-shrink: 0;
+ }
+ .cap-goto {
+ display: block;
+ width: 100%;
+ padding: 0;
+ background: none;
+ border: none;
+ color: inherit;
+ text-align: left;
+ cursor: pointer;
}
.cap img {
width: 100%;
@@ -397,6 +681,12 @@
object-fit: cover;
background: var(--bg-2);
}
+ .cap-goto:hover img {
+ opacity: 0.9;
+ }
+ .cap-goto:hover .coords {
+ color: var(--accent);
+ }
.cap-meta {
padding: 8px 10px 2px;
display: flex;
@@ -415,6 +705,32 @@
gap: 2px;
padding: 4px 6px 6px;
}
+ .cap-notes {
+ padding: 0 10px 8px;
+ font-size: var(--fs-xs);
+ color: var(--text-2);
+ font-style: italic;
+ white-space: pre-wrap;
+ word-break: break-word;
+ }
+
+ .sat-info-rows {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ }
+ .sat-info-row {
+ display: flex;
+ gap: 10px;
+ font-size: var(--fs-sm);
+ align-items: baseline;
+ }
+ .sat-info-label {
+ color: var(--text-3);
+ font-size: var(--fs-xs);
+ min-width: 80px;
+ flex-shrink: 0;
+ }
/* Leaflet dark-theme adjustments */
:global(.leaflet-container) {
diff --git a/frontend/src/tools/inspect/AdjustModule.svelte b/frontend/src/tools/inspect/AdjustModule.svelte
new file mode 100644
index 0000000..0b09f9f
--- /dev/null
+++ b/frontend/src/tools/inspect/AdjustModule.svelte
@@ -0,0 +1,204 @@
+<script>
+ import { onMount } from 'svelte';
+ import { api } from '../../lib/api.js';
+ import { caseState, reloadCase, toast } from '../../lib/state.svelte.js';
+ import Icon from '../../components/Icon.svelte';
+
+ // Non-destructive image adjustments. Controls are generated from the backend
+ // filter registry (/api/inspect/ops) — adding a server-side filter surfaces a
+ // slider here automatically. Live preview uses each filter's CSS hint; the
+ // real render happens on "Export" so it stays reproducible (spec §6).
+ let { source, shared, onProduced } = $props();
+
+ const ORDER = ['brightness', 'contrast', 'saturation', 'gamma', 'sharpness', 'rotate', 'grayscale', 'invert'];
+
+ let filters = $state([]);
+ let values = $state({}); // filterId -> single param value
+ let baking = $state(false);
+
+ onMount(async () => {
+ const ops = await api.get('/api/inspect/ops');
+ filters = ops.filters
+ .filter((f) => f.id !== 'crop')
+ .sort((a, b) => ORDER.indexOf(a.id) - ORDER.indexOf(b.id));
+ resetValues();
+ });
+
+ function resetValues() {
+ const next = {};
+ for (const f of filters) next[f.id] = f.params[0]?.default ?? 0;
+ values = next;
+ clearCrop();
+ }
+
+ function paramName(f) {
+ return f.params[0]?.name ?? 'amount';
+ }
+
+ function isDefault(f) {
+ return values[f.id] === (f.params[0]?.default ?? 0);
+ }
+
+ // live preview: CSS filter + transform strings pushed to the viewer
+ $effect(() => {
+ shared.filter = filters
+ .filter((f) => f.css)
+ .map((f) => f.css.replaceAll('{v}', values[f.id]))
+ .join(' ');
+ shared.transform = filters
+ .filter((f) => f.transform)
+ .map((f) => f.transform.replaceAll('{v}', values[f.id]))
+ .join(' ');
+ });
+
+ function clearCrop() {
+ shared.crop = null;
+ shared.cropMode = false;
+ }
+
+ function toggleCrop() {
+ shared.cropMode = !shared.cropMode;
+ }
+
+ function reset() {
+ resetValues();
+ }
+
+ async function bake() {
+ const ops = [];
+ if (shared.crop) ops.push({ op: 'crop', params: shared.crop });
+ for (const id of ORDER) {
+ const f = filters.find((x) => x.id === id);
+ if (!f || isDefault(f)) continue;
+ ops.push({ op: id, params: { [paramName(f)]: values[id] } });
+ }
+ if (!ops.length) {
+ toast('Nothing to apply — adjust a slider or set a crop first', 'info');
+ return;
+ }
+ baking = true;
+ try {
+ const res = await api.post(`/api/cases/${caseState.current.id}/inspect/bake`, {
+ path: source.path,
+ ops,
+ });
+ await reloadCase();
+ onProduced(res);
+ toast(res.duplicate ? 'Identical image already in the case' : 'Edited image filed', res.duplicate ? 'warn' : 'ok');
+ } catch (e) {
+ toast(e.message, 'danger');
+ } finally {
+ baking = false;
+ }
+ }
+</script>
+
+<div class="module">
+ {#each filters as f (f.id)}
+ <label class="row" class:toggle={f.params[0]?.type === 'toggle'}>
+ <span class="lbl">
+ {f.label}
+ {#if !f.css && !f.transform}<span class="pill" title="No live preview — applied on export">export</span>{/if}
+ </span>
+ {#if f.params[0]?.type === 'toggle'}
+ <input type="checkbox" checked={values[f.id] === 1} onchange={(e) => (values[f.id] = e.target.checked ? 1 : 0)} />
+ {:else}
+ <input
+ type="range"
+ min={f.params[0].min}
+ max={f.params[0].max}
+ step={f.params[0].step}
+ bind:value={values[f.id]}
+ />
+ <span class="val mono">{Number(values[f.id]).toFixed(f.params[0].step < 1 ? 2 : 0)}{f.params[0].unit}</span>
+ {/if}
+ </label>
+ {/each}
+
+ <div class="crop-row">
+ <button class="btn btn-sm" class:active={shared.cropMode} onclick={toggleCrop}>
+ <Icon name="crop" size={14} /> {shared.cropMode ? 'Drag on image…' : 'Crop region'}
+ </button>
+ {#if shared.crop}
+ <span class="crop-info mono">
+ {Math.round(shared.crop.w * 100)}% × {Math.round(shared.crop.h * 100)}%
+ </span>
+ <button class="btn btn-ghost btn-xs" onclick={clearCrop} title="Clear crop"><Icon name="x" size={13} /></button>
+ {/if}
+ </div>
+
+ <div class="actions">
+ <button class="btn btn-ghost btn-sm" onclick={reset}><Icon name="reset" size={14} /> Reset</button>
+ <button class="btn btn-primary" disabled={baking} onclick={bake}>
+ <Icon name="save" size={15} /> Export as new image
+ </button>
+ </div>
+</div>
+
+<style>
+ .module {
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+ }
+ .row {
+ display: grid;
+ grid-template-columns: 90px 1fr 42px;
+ align-items: center;
+ gap: 8px;
+ font-size: var(--fs-sm);
+ }
+ .row.toggle {
+ grid-template-columns: 1fr auto;
+ }
+ .lbl {
+ color: var(--text-2);
+ display: flex;
+ align-items: center;
+ gap: 5px;
+ }
+ .pill {
+ font-size: 9px;
+ text-transform: uppercase;
+ letter-spacing: 0.04em;
+ padding: 1px 4px;
+ border-radius: 4px;
+ background: var(--bg-2);
+ color: var(--text-3);
+ }
+ input[type='range'] {
+ width: 100%;
+ accent-color: var(--accent);
+ }
+ input[type='checkbox'] {
+ accent-color: var(--accent);
+ width: 15px;
+ height: 15px;
+ }
+ .val {
+ text-align: right;
+ color: var(--text-3);
+ font-size: var(--fs-xs);
+ }
+ .crop-row {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ border-top: 1px solid var(--border);
+ padding-top: 12px;
+ }
+ .crop-info {
+ font-size: var(--fs-xs);
+ color: var(--text-3);
+ }
+ .btn.active {
+ color: var(--accent);
+ border-color: var(--accent);
+ }
+ .actions {
+ display: flex;
+ justify-content: space-between;
+ gap: 8px;
+ margin-top: 4px;
+ }
+</style>
diff --git a/frontend/src/tools/inspect/AnalyzeModule.svelte b/frontend/src/tools/inspect/AnalyzeModule.svelte
new file mode 100644
index 0000000..ed44475
--- /dev/null
+++ b/frontend/src/tools/inspect/AnalyzeModule.svelte
@@ -0,0 +1,180 @@
+<script>
+ import { onMount } from 'svelte';
+ import { api } from '../../lib/api.js';
+ import { caseState, toast } from '../../lib/state.svelte.js';
+ import Icon from '../../components/Icon.svelte';
+
+ // Read-only inspectors. Each analysis returns one of a few render kinds
+ // (keyvalue / histogram / image / text) so new analyses need no new UI here.
+ let { source } = $props();
+
+ let analyses = $state([]);
+ let active = $state(null);
+ let result = $state(null);
+ let running = $state(false);
+ let canvasEl = $state();
+
+ onMount(async () => {
+ analyses = (await api.get('/api/inspect/ops')).analyses;
+ });
+
+ async function run(name) {
+ active = name;
+ running = true;
+ result = null;
+ try {
+ result = await api.post(`/api/cases/${caseState.current.id}/inspect/analyze`, {
+ path: source.path,
+ name,
+ });
+ if (result.kind === 'histogram') requestAnimationFrame(drawHistogram);
+ } catch (e) {
+ toast(e.message, 'danger');
+ } finally {
+ running = false;
+ }
+ }
+
+ function drawHistogram() {
+ if (!canvasEl || result?.kind !== 'histogram') return;
+ const ctx = canvasEl.getContext('2d');
+ const W = (canvasEl.width = canvasEl.clientWidth);
+ const H = (canvasEl.height = 120);
+ ctx.clearRect(0, 0, W, H);
+ const ch = result.channels;
+ const peak = Math.max(1, ...ch.r, ...ch.g, ...ch.b);
+ ctx.globalCompositeOperation = 'lighter';
+ for (const [name, color] of [
+ ['r', 'rgba(230,70,70,0.8)'],
+ ['g', 'rgba(70,210,110,0.8)'],
+ ['b', 'rgba(90,140,240,0.8)'],
+ ]) {
+ ctx.beginPath();
+ ctx.moveTo(0, H);
+ ch[name].forEach((v, i) => ctx.lineTo((i / 255) * W, H - (v / peak) * H));
+ ctx.lineTo(W, H);
+ ctx.fillStyle = color;
+ ctx.fill();
+ }
+ ctx.globalCompositeOperation = 'source-over';
+ }
+</script>
+
+<div class="module">
+ <div class="tabs">
+ {#each analyses as a (a.id)}
+ <button class="btn btn-sm" class:active={active === a.id} onclick={() => run(a.id)}>
+ {a.label}
+ </button>
+ {/each}
+ </div>
+
+ {#if running}
+ <p class="status"><Icon name="clock" size={14} /> Analysing…</p>
+ {:else if result}
+ {#if result.kind === 'keyvalue'}
+ <table class="kv">
+ <tbody>
+ {#each Object.entries(result.rows) as [k, v] (k)}
+ <tr><th>{k}</th><td class="mono">{v}</td></tr>
+ {/each}
+ </tbody>
+ </table>
+ {:else if result.kind === 'histogram'}
+ <canvas bind:this={canvasEl} class="hist"></canvas>
+ <p class="legend"><span class="r">R</span> <span class="g">G</span> <span class="b">B</span> intensity 0→255</p>
+ {:else if result.kind === 'image'}
+ <img class="analysis-img" src={result.data_url} alt="analysis" />
+ {#if result.note}<p class="note"><Icon name="alert" size={13} /> {result.note}</p>{/if}
+ {:else if result.kind === 'text'}
+ <pre class="text">{result.text}</pre>
+ {/if}
+ {:else}
+ <p class="status dim">Pick an analysis above.</p>
+ {/if}
+</div>
+
+<style>
+ .module {
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+ }
+ .tabs {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 6px;
+ }
+ .btn.active {
+ color: var(--accent);
+ border-color: var(--accent);
+ }
+ .status {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ color: var(--text-3);
+ font-size: var(--fs-sm);
+ }
+ .status.dim {
+ color: var(--text-3);
+ }
+ .kv {
+ width: 100%;
+ border-collapse: collapse;
+ font-size: var(--fs-xs);
+ }
+ .kv th {
+ text-align: left;
+ color: var(--text-3);
+ font-weight: 600;
+ padding: 3px 8px 3px 0;
+ vertical-align: top;
+ white-space: nowrap;
+ }
+ .kv td {
+ padding: 3px 0;
+ color: var(--text-2);
+ word-break: break-all;
+ }
+ .kv tr + tr {
+ border-top: 1px solid var(--border);
+ }
+ .hist {
+ width: 100%;
+ height: 120px;
+ background: var(--bg-0);
+ border-radius: var(--r-sm);
+ }
+ .legend {
+ font-size: var(--fs-xs);
+ color: var(--text-3);
+ margin: 0;
+ }
+ .legend .r {
+ color: #e64646;
+ }
+ .legend .g {
+ color: #46d26e;
+ }
+ .legend .b {
+ color: #5a8cf0;
+ }
+ .analysis-img {
+ width: 100%;
+ border-radius: var(--r-sm);
+ background: #000;
+ }
+ .note {
+ display: flex;
+ gap: 6px;
+ font-size: var(--fs-xs);
+ color: var(--warn, #d8a24a);
+ margin: 0;
+ }
+ .text {
+ font-size: var(--fs-xs);
+ white-space: pre-wrap;
+ color: var(--text-2);
+ }
+</style>
diff --git a/frontend/src/tools/inspect/CollageModule.svelte b/frontend/src/tools/inspect/CollageModule.svelte
new file mode 100644
index 0000000..2467313
--- /dev/null
+++ b/frontend/src/tools/inspect/CollageModule.svelte
@@ -0,0 +1,152 @@
+<script>
+ import { api } from '../../lib/api.js';
+ import { caseState, reloadCase, toast } from '../../lib/state.svelte.js';
+ import Icon from '../../components/Icon.svelte';
+
+ // Assemble several case images (frames, crops, photos) into one contact-sheet.
+ let { mediaList, onProduced } = $props();
+
+ let picked = $state([]); // ordered list of paths
+ let columns = $state(2);
+ let cell = $state(400);
+ let gap = $state(8);
+ let building = $state(false);
+
+ const images = $derived((mediaList ?? []).filter((m) => m.kind === 'image'));
+
+ function toggle(path) {
+ const i = picked.indexOf(path);
+ if (i === -1) picked.push(path);
+ else picked.splice(i, 1);
+ }
+
+ function orderOf(path) {
+ const i = picked.indexOf(path);
+ return i === -1 ? null : i + 1;
+ }
+
+ async function build() {
+ if (picked.length < 1) return;
+ building = true;
+ try {
+ const res = await api.post(`/api/cases/${caseState.current.id}/inspect/collage`, {
+ paths: [...picked],
+ columns,
+ cell,
+ gap,
+ });
+ await reloadCase();
+ onProduced(res);
+ picked = [];
+ toast('Collage filed to the case', 'ok');
+ } catch (e) {
+ toast(e.message, 'danger');
+ } finally {
+ building = false;
+ }
+ }
+</script>
+
+<div class="module">
+ <p class="hint">Pick images in the order you want them; they tile left-to-right.</p>
+
+ <div class="grid">
+ {#each images as m (m.path)}
+ <button class="tile" class:sel={orderOf(m.path)} onclick={() => toggle(m.path)} title={m.filename}>
+ <img src={`/files/${caseState.current.id}/${m.thumbnail ?? m.path}`} alt={m.filename} />
+ {#if orderOf(m.path)}<span class="badge">{orderOf(m.path)}</span>{/if}
+ </button>
+ {/each}
+ </div>
+
+ {#if images.length === 0}
+ <p class="empty">No images yet — capture frames or add media first.</p>
+ {/if}
+
+ <div class="controls">
+ <label>Cols <input type="number" min="1" max="8" bind:value={columns} /></label>
+ <label>Cell <input type="number" min="64" max="1024" step="20" bind:value={cell} /></label>
+ <label>Gap <input type="number" min="0" max="64" bind:value={gap} /></label>
+ </div>
+
+ <button class="btn btn-primary w-full" disabled={building || picked.length < 1} onclick={build}>
+ <Icon name="layers" size={15} /> Build collage ({picked.length})
+ </button>
+</div>
+
+<style>
+ .module {
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+ }
+ .hint,
+ .empty {
+ color: var(--text-3);
+ font-size: var(--fs-xs);
+ margin: 0;
+ }
+ .grid {
+ display: grid;
+ grid-template-columns: repeat(3, 1fr);
+ gap: 6px;
+ max-height: 320px;
+ overflow: auto;
+ }
+ .tile {
+ position: relative;
+ aspect-ratio: 1;
+ border-radius: var(--r-sm);
+ overflow: hidden;
+ border: 2px solid transparent;
+ }
+ .tile img {
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ display: block;
+ }
+ .tile.sel {
+ border-color: var(--accent);
+ }
+ .badge {
+ position: absolute;
+ top: 3px;
+ left: 3px;
+ background: var(--accent);
+ color: #10141c;
+ font-size: 11px;
+ font-weight: 700;
+ border-radius: 50%;
+ width: 18px;
+ height: 18px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ }
+ .controls {
+ display: flex;
+ gap: 8px;
+ }
+ .controls label {
+ display: flex;
+ flex-direction: column;
+ gap: 3px;
+ font-size: var(--fs-xs);
+ color: var(--text-3);
+ flex: 1;
+ }
+ .controls input {
+ width: 100%;
+ background: var(--bg-2);
+ border: 1px solid var(--border);
+ border-radius: var(--r-sm);
+ padding: 4px 6px;
+ color: var(--text-1);
+ font-size: var(--fs-sm);
+ }
+ .w-full {
+ width: 100%;
+ justify-content: center;
+ }
+</style>
diff --git a/frontend/src/tools/inspect/FramesModule.svelte b/frontend/src/tools/inspect/FramesModule.svelte
new file mode 100644
index 0000000..6c043ff
--- /dev/null
+++ b/frontend/src/tools/inspect/FramesModule.svelte
@@ -0,0 +1,190 @@
+<script>
+ import { api } from '../../lib/api.js';
+ import { caseState, uiState, reloadCase, toast } from '../../lib/state.svelte.js';
+ import Icon from '../../components/Icon.svelte';
+
+ // Extracts frames from a video into the case (spec v2 gesture).
+ let { source, probeInfo, shared, onProduced } = $props();
+
+ let suggestions = $state([]);
+ let scanning = $state(false);
+ let capturing = $state(false);
+
+ const duration = $derived(probeInfo?.duration ?? 0);
+
+ function fmt(t) {
+ const m = Math.floor(t / 60);
+ const s = (t % 60).toFixed(2).padStart(5, '0');
+ return `${m}:${s}`;
+ }
+
+ function step(delta) {
+ const t = Math.min(Math.max((shared.currentTime ?? 0) + delta, 0), duration || Infinity);
+ shared.seekTo = t;
+ }
+
+ async function capture(time = shared.currentTime ?? 0) {
+ capturing = true;
+ try {
+ const res = await api.post(`/api/cases/${caseState.current.id}/inspect/frame`, {
+ path: source.path,
+ time,
+ });
+ await reloadCase();
+ onProduced(res);
+ toast(
+ res.duplicate ? 'That frame is already in the case' : `Frame captured at ${fmt(time)}`,
+ res.duplicate ? 'warn' : 'ok'
+ );
+ } catch (e) {
+ toast(e.message, 'danger');
+ } finally {
+ capturing = false;
+ }
+ }
+
+ async function suggest() {
+ scanning = true;
+ suggestions = [];
+ try {
+ const { job_id } = await api.post(`/api/cases/${caseState.current.id}/inspect/suggest`, {
+ path: source.path,
+ bins: 12,
+ });
+ const frames = await poll(job_id);
+ suggestions = frames;
+ } catch (e) {
+ toast(e.message, 'danger');
+ } finally {
+ scanning = false;
+ }
+ }
+
+ async function poll(jobId) {
+ for (;;) {
+ const job = await api.get(`/api/jobs/${jobId}`);
+ if (job.status === 'done') return job.result.frames;
+ if (job.status === 'error') throw new Error(job.error);
+ await new Promise((r) => setTimeout(r, 500));
+ }
+ }
+
+ const maxScore = $derived(Math.max(1, ...suggestions.map((s) => s.score)));
+</script>
+
+<div class="module">
+ <div class="now">
+ <span class="mono time">{fmt(shared.currentTime ?? 0)}</span>
+ <span class="dim">/ {fmt(duration)}</span>
+ </div>
+
+ <div class="stepper">
+ <button class="btn btn-sm" onclick={() => step(-1)} title="Back 1s">-1s</button>
+ <button class="btn btn-sm" onclick={() => step(-0.1)} title="Back 0.1s">-0.1</button>
+ <button class="btn btn-sm" onclick={() => step(0.1)} title="Forward 0.1s">+0.1</button>
+ <button class="btn btn-sm" onclick={() => step(1)} title="Forward 1s">+1s</button>
+ </div>
+
+ <button class="btn btn-primary w-full" disabled={capturing} onclick={() => capture()}>
+ <Icon name="image" size={15} /> Capture this frame
+ </button>
+
+ <div class="section">
+ <div class="section-head">
+ <span>Sharpest frames</span>
+ <button class="btn btn-ghost btn-sm" disabled={scanning} onclick={suggest}>
+ <Icon name={scanning ? 'clock' : 'search'} size={13} />
+ {scanning ? 'Scanning…' : 'Scan'}
+ </button>
+ </div>
+ <p class="hint">Samples the clip and ranks frames by focus — sharper is higher.</p>
+
+ {#each suggestions as s (s.time)}
+ <div class="sugg" class:top={s.rank === 0}>
+ <span class="mono">{fmt(s.time)}</span>
+ <div class="bar"><div class="fill" style:width={`${(s.score / maxScore) * 100}%`}></div></div>
+ <button class="btn btn-ghost btn-xs" onclick={() => (shared.seekTo = s.time)} title="Seek here">
+ <Icon name="eye" size={13} />
+ </button>
+ <button class="btn btn-xs" disabled={capturing} onclick={() => capture(s.time)} title="Capture">
+ <Icon name="image" size={13} />
+ </button>
+ </div>
+ {/each}
+ </div>
+</div>
+
+<style>
+ .module {
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+ }
+ .now {
+ display: flex;
+ align-items: baseline;
+ gap: 8px;
+ font-size: var(--fs-lg);
+ }
+ .time {
+ font-weight: 700;
+ color: var(--accent);
+ }
+ .dim {
+ color: var(--text-3);
+ font-size: var(--fs-sm);
+ }
+ .stepper {
+ display: grid;
+ grid-template-columns: repeat(4, 1fr);
+ gap: 6px;
+ }
+ .w-full {
+ width: 100%;
+ justify-content: center;
+ }
+ .section {
+ border-top: 1px solid var(--border);
+ padding-top: 12px;
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ }
+ .section-head {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ font-weight: 600;
+ font-size: var(--fs-sm);
+ }
+ .hint {
+ color: var(--text-3);
+ font-size: var(--fs-xs);
+ margin: 0 0 4px;
+ }
+ .sugg {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 3px 0;
+ }
+ .sugg.top .fill {
+ background: var(--accent);
+ }
+ .sugg .mono {
+ font-size: var(--fs-xs);
+ color: var(--text-2);
+ min-width: 52px;
+ }
+ .bar {
+ flex: 1;
+ height: 6px;
+ border-radius: 3px;
+ background: var(--bg-2);
+ overflow: hidden;
+ }
+ .fill {
+ height: 100%;
+ background: var(--text-3);
+ }
+</style>
diff --git a/src/ozimut/api/cases.py b/src/ozimut/api/cases.py
index 382a9f0..48025aa 100644
--- a/src/ozimut/api/cases.py
+++ b/src/ozimut/api/cases.py
@@ -52,6 +52,10 @@ class LinkIn(BaseModel):
status: str = "confirmed"
+class FolderIn(BaseModel):
+ name: str = Field(min_length=1, max_length=120)
+
+
@router.get("")
def list_cases() -> list[dict[str, Any]]:
return Case.list_all()
@@ -157,3 +161,23 @@ def remove_link(case_id: str, link_id: str) -> dict[str, str]:
except CaseError as exc:
raise HTTPException(status_code=404, detail=str(exc)) from exc
return {"status": "deleted"}
+
+
[email protected]("/{case_id}/folders")
+def list_folders(case_id: str) -> list[str]:
+ return get_case(case_id).list_folders()
+
+
[email protected]("/{case_id}/folders")
+def add_folder(case_id: str, body: FolderIn) -> list[str]:
+ case = get_case(case_id)
+ try:
+ return case.add_folder(body.name)
+ except CaseError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+
+
[email protected]("/{case_id}/folders")
+def remove_folder(case_id: str, name: str) -> list[str]:
+ return get_case(case_id).remove_folder(name)
+
diff --git a/src/ozimut/api/drafts.py b/src/ozimut/api/drafts.py
new file mode 100644
index 0000000..5e26440
--- /dev/null
+++ b/src/ozimut/api/drafts.py
@@ -0,0 +1,129 @@
+"""REST API for post drafts: save, list, load, delete.
+
+A draft is the re-editable state of the Post Composer (thread of tweets built
+from a geolocation). Drafts live in ``<case>/exports/`` as JSON and are indexed
+as ``post`` entities so they show up in the case sidebar (spec §4 — the case is
+the product). Ozimut never posts on your behalf; a draft is prepared here and the
+human publishes it (spec §6 non-goals).
+"""
+
+from __future__ import annotations
+
+import json
+import re
+from datetime import datetime, timezone
+from typing import Any
+
+from fastapi import APIRouter, HTTPException
+from pydantic import BaseModel, Field
+
+from ..workspace import CaseError
+from .cases import get_case
+
+router = APIRouter(prefix="/api", tags=["drafts"])
+
+DRAFT_MARKER = 1
+
+
+class DraftIn(BaseModel):
+ name: str | None = None # slug; None → derived from title
+ title: str = Field(min_length=1, max_length=200)
+ state: dict[str, Any] # opaque Post Composer state (fields + tweets)
+
+
+def _slug(text: str) -> str:
+ slug = re.sub(r"[^a-z0-9]+", "-", text.lower()).strip("-")
+ return slug[:80] or "draft"
+
+
+def _now() -> str:
+ return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
+
+
[email protected]("/cases/{case_id}/drafts")
+def list_drafts(case_id: str) -> list[dict[str, Any]]:
+ case = get_case(case_id)
+ drafts = []
+ for path in sorted(case.subdir("exports").glob("*.json")):
+ try:
+ data = json.loads(path.read_text(encoding="utf-8"))
+ except (OSError, json.JSONDecodeError):
+ continue
+ if data.get("ozimut_draft") != DRAFT_MARKER:
+ continue
+ drafts.append(
+ {
+ "name": path.stem,
+ "title": data.get("title", path.stem),
+ "updated_at": data.get("updated_at"),
+ "created_at": data.get("created_at"),
+ }
+ )
+ drafts.sort(key=lambda d: d.get("updated_at") or "", reverse=True)
+ return drafts
+
+
[email protected]("/cases/{case_id}/drafts/{name}")
+def load_draft(case_id: str, name: str) -> dict[str, Any]:
+ case = get_case(case_id)
+ try:
+ path = case.resolve_inside(f"exports/{name}.json")
+ except CaseError as exc:
+ raise HTTPException(status_code=403, detail=str(exc)) from exc
+ if not path.exists():
+ raise HTTPException(status_code=404, detail="draft not found")
+ return json.loads(path.read_text(encoding="utf-8"))
+
+
[email protected]("/cases/{case_id}/drafts")
+def save_draft(case_id: str, body: DraftIn) -> dict[str, Any]:
+ case = get_case(case_id)
+ name = _slug(body.name or body.title)
+ exports_dir = case.subdir("exports")
+
+ path = exports_dir / f"{name}.json"
+ existing_created = None
+ if path.exists():
+ try:
+ existing_created = json.loads(path.read_text(encoding="utf-8")).get("created_at")
+ except (OSError, json.JSONDecodeError):
+ existing_created = None
+
+ data = {
+ "ozimut_draft": DRAFT_MARKER,
+ "title": body.title,
+ "created_at": existing_created or _now(),
+ "updated_at": _now(),
+ "state": body.state,
+ }
+ path.write_text(
+ json.dumps(data, indent=2, ensure_ascii=False) + "\n", encoding="utf-8"
+ )
+
+ # upsert the post entity (analyst action → confirmed)
+ existing = case.find_entity(attr="draft", value=f"exports/{name}.json")
+ if existing:
+ case.update_entity(existing["id"], {"label": body.title})
+ else:
+ case.add_entity(
+ "post",
+ body.title,
+ attrs={"draft": f"exports/{name}.json"},
+ by="post-composer",
+ )
+
+ return {"name": name, "draft": f"exports/{name}.json"}
+
+
[email protected]("/cases/{case_id}/drafts/{name}")
+def delete_draft(case_id: str, name: str) -> dict[str, str]:
+ case = get_case(case_id)
+ try:
+ path = case.resolve_inside(f"exports/{name}.json")
+ except CaseError as exc:
+ raise HTTPException(status_code=403, detail=str(exc)) from exc
+ path.unlink(missing_ok=True)
+ entity = case.find_entity(attr="draft", value=f"exports/{name}.json")
+ if entity:
+ case.remove_entity(entity["id"])
+ return {"status": "deleted"}
diff --git a/src/ozimut/api/inspect.py b/src/ozimut/api/inspect.py
new file mode 100644
index 0000000..cc5569e
--- /dev/null
+++ b/src/ozimut/api/inspect.py
@@ -0,0 +1,150 @@
+"""REST API for the Inspect tool: probe media, capture frames, apply
+adjustments, build collages, run analyses.
+
+Outputs are filed as ordinary case media (they appear in the Media Library and
+the Proof Composer picker with zero extra plumbing). Long scans run as jobs.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+from fastapi import APIRouter, HTTPException
+from pydantic import BaseModel, Field
+
+from .. import jobs
+from ..engine import inspect as inspect_engine
+from ..workspace import CaseError
+from .cases import get_case
+
+router = APIRouter(prefix="/api", tags=["inspect"])
+
+
+class FrameIn(BaseModel):
+ path: str
+ time: float = Field(ge=0)
+ label: str | None = None
+
+
+class FramesIn(BaseModel):
+ path: str
+ times: list[float]
+
+
+class SuggestIn(BaseModel):
+ path: str
+ bins: int = Field(default=12, ge=1, le=inspect_engine.FRAME_SCAN_CAP)
+
+
+class Op(BaseModel):
+ op: str
+ params: dict[str, Any] = {}
+
+
+class BakeIn(BaseModel):
+ path: str
+ ops: list[Op]
+ label: str | None = None
+
+
+class CollageIn(BaseModel):
+ paths: list[str] = Field(min_length=1)
+ columns: int = Field(default=2, ge=1, le=8)
+ gap: int = Field(default=8, ge=0, le=64)
+ background: str = "#12141c"
+ cell: int = Field(default=480, ge=64, le=1024)
+ label: str | None = None
+
+
+class AnalyzeIn(BaseModel):
+ path: str
+ name: str
+ params: dict[str, Any] = {}
+
+
[email protected]("/inspect/ops")
+def ops() -> dict[str, Any]:
+ """Self-describing filter + analysis registries (drives the UI controls)."""
+ return inspect_engine.registries()
+
+
[email protected]("/cases/{case_id}/inspect/probe")
+def probe(case_id: str, path: str) -> dict[str, Any]:
+ case = get_case(case_id)
+ try:
+ return inspect_engine.probe(case, path)
+ except (CaseError, FileNotFoundError) as exc:
+ raise HTTPException(status_code=404, detail=str(exc)) from exc
+
+
[email protected]("/cases/{case_id}/inspect/frame")
+def capture_frame(case_id: str, body: FrameIn) -> dict[str, Any]:
+ case = get_case(case_id)
+ try:
+ return inspect_engine.capture_frame(case, body.path, body.time, body.label)
+ except CaseError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+ except (RuntimeError, OSError) as exc:
+ raise HTTPException(status_code=422, detail=str(exc)) from exc
+
+
[email protected]("/cases/{case_id}/inspect/frames")
+def capture_frames(case_id: str, body: FramesIn) -> dict[str, str]:
+ case = get_case(case_id)
+
+ def work(set_progress):
+ results = []
+ total = len(body.times) or 1
+ for i, t in enumerate(body.times):
+ results.append(inspect_engine.capture_frame(case, body.path, t))
+ set_progress({"percent": round((i + 1) * 100 / total, 1)})
+ return {"captured": results}
+
+ return {"job_id": jobs.start("frames", work)}
+
+
[email protected]("/cases/{case_id}/inspect/suggest")
+def suggest_frames(case_id: str, body: SuggestIn) -> dict[str, str]:
+ case = get_case(case_id)
+
+ def work(set_progress):
+ return {"frames": inspect_engine.suggest_frames(case, body.path, body.bins, set_progress)}
+
+ return {"job_id": jobs.start("suggest", work)}
+
+
[email protected]("/cases/{case_id}/inspect/bake")
+def bake(case_id: str, body: BakeIn) -> dict[str, Any]:
+ case = get_case(case_id)
+ ops = [op.model_dump() for op in body.ops]
+ try:
+ return inspect_engine.bake(case, body.path, ops, body.label)
+ except CaseError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+ except (ValueError, OSError) as exc:
+ raise HTTPException(status_code=422, detail=str(exc)) from exc
+
+
[email protected]("/cases/{case_id}/inspect/collage")
+def collage(case_id: str, body: CollageIn) -> dict[str, Any]:
+ case = get_case(case_id)
+ try:
+ return inspect_engine.collage(
+ case, body.paths, columns=body.columns, gap=body.gap,
+ background=body.background, cell=body.cell, label=body.label,
+ )
+ except CaseError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+ except (ValueError, OSError) as exc:
+ raise HTTPException(status_code=422, detail=str(exc)) from exc
+
+
[email protected]("/cases/{case_id}/inspect/analyze")
+def analyze(case_id: str, body: AnalyzeIn) -> dict[str, Any]:
+ case = get_case(case_id)
+ try:
+ return inspect_engine.run_analysis(case, body.path, body.name, body.params)
+ except CaseError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+ except (ValueError, OSError) as exc:
+ raise HTTPException(status_code=422, detail=str(exc)) from exc
diff --git a/src/ozimut/api/media.py b/src/ozimut/api/media.py
index 2a75895..85aee3e 100644
--- a/src/ozimut/api/media.py
+++ b/src/ozimut/api/media.py
@@ -23,6 +23,13 @@ class DeleteIn(BaseModel):
path: str
+class UpdateIn(BaseModel):
+ path: str
+ notes: str | None = None
+ folder: str | None = None
+ label: str | None = None
+
+
@router.get("/cases/{case_id}/media")
def list_media(case_id: str) -> list[dict[str, Any]]:
return media_engine.list_media(get_case(case_id))
@@ -76,3 +83,19 @@ def delete_media(case_id: str, path: str) -> dict[str, str]:
except CaseError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
return {"status": "deleted"}
+
+
[email protected]("/cases/{case_id}/media")
+def update_media_item(case_id: str, body: UpdateIn) -> dict[str, Any]:
+ case = get_case(case_id)
+ patch: dict[str, Any] = {}
+ if body.notes is not None:
+ patch["notes"] = body.notes
+ if body.folder is not None:
+ patch["folder"] = body.folder
+ if body.label is not None:
+ patch["label"] = body.label
+ try:
+ return media_engine.update_media(case, body.path, patch)
+ except (ValueError, CaseError) as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
diff --git a/src/ozimut/api/satellite.py b/src/ozimut/api/satellite.py
index 4e83dda..688812c 100644
--- a/src/ozimut/api/satellite.py
+++ b/src/ozimut/api/satellite.py
@@ -23,12 +23,18 @@ class CaptureIn(BaseModel):
height: int = Field(default=700, ge=256, le=2048)
provider: str = "esri-world-imagery"
crosshair: bool = True
+ bearing: float = Field(default=0.0, ge=0, le=360)
class ParseIn(BaseModel):
text: str
+class SatelliteUpdateIn(BaseModel):
+ path: str
+ notes: str | None = None
+
+
@router.get("/satellite/providers")
def providers() -> list[dict[str, Any]]:
return [
@@ -78,7 +84,7 @@ def capture(case_id: str, body: CaptureIn) -> dict[str, Any]:
try:
image, provenance = tiles.fetch_crop(
body.lat, body.lon, body.zoom, body.width, body.height,
- provider, crosshair=body.crosshair,
+ provider, crosshair=body.crosshair, bearing=body.bearing,
)
except tiles.TileFetchError as exc:
raise HTTPException(status_code=422, detail=str(exc)) from exc
@@ -97,7 +103,7 @@ def capture(case_id: str, body: CaptureIn) -> dict[str, Any]:
)
# suggest a place entity — analyst confirms or dismisses (spec §3.5)
- label = f"{body.lat:.5f}, {body.lon:.5f}"
+ label = f"{body.lat:.6f}, {body.lon:.6f}"
if not case.find_entity(attr="coords", value=label):
case.add_entity(
"place",
@@ -134,3 +140,28 @@ def delete_capture(case_id: str, path: str) -> dict[str, str]:
image.unlink(missing_ok=True)
image.with_name(image.name + ".json").unlink(missing_ok=True)
return {"status": "deleted"}
+
+
[email protected]("/cases/{case_id}/satellite")
+def update_capture(case_id: str, body: SatelliteUpdateIn) -> dict[str, Any]:
+ case = get_case(case_id)
+ try:
+ image_path = case.resolve_inside(body.path)
+ except Exception as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+
+ sidecar_path = image_path.with_name(image_path.name + ".json")
+ if not sidecar_path.exists():
+ raise HTTPException(status_code=404, detail="capture not found")
+
+ data = json.loads(sidecar_path.read_text(encoding="utf-8"))
+ if body.notes is not None:
+ if body.notes == "":
+ data.pop("notes", None)
+ else:
+ data["notes"] = body.notes
+ sidecar_path.write_text(
+ json.dumps(data, indent=2, ensure_ascii=False) + "\n", encoding="utf-8"
+ )
+ data["path"] = body.path
+ return data
diff --git a/src/ozimut/engine/inspect.py b/src/ozimut/engine/inspect.py
new file mode 100644
index 0000000..1b82754
--- /dev/null
+++ b/src/ozimut/engine/inspect.py
@@ -0,0 +1,443 @@
+"""Media inspection engine: open a photo or video, pull frames, adjust and
+analyse imagery — all locally, Pillow + ffmpeg only (spec §7).
+
+Two self-describing registries make new mini-tools cheap to add (the whole point
+of this module's design):
+
+* ``FILTERS`` — pixel transforms applied as an ordered pipeline. Each declares a
+ parameter schema and an optional CSS hint so the frontend can live-preview
+ without a round-trip. Adding an adjustment = one ``@filter`` function.
+* ``ANALYSES`` — read-only inspectors that return one of a small set of render
+ kinds (``keyvalue`` / ``histogram`` / ``image`` / ``text``). The frontend has a
+ generic renderer per kind, so adding an analysis = one ``@analysis`` function.
+
+Everything the tools produce is filed back as ordinary case media (via the media
+engine) with provenance recording how it was derived — honest, auditable output
+(spec §6). Nothing here mutates the original media.
+"""
+
+from __future__ import annotations
+
+import base64
+import io
+import json
+import shutil
+import subprocess
+from dataclasses import dataclass, field
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any, Callable
+
+from PIL import Image, ImageChops, ImageEnhance, ImageFilter, ImageOps, ImageStat
+from PIL.ExifTags import GPSTAGS, TAGS
+
+from ..workspace import Case
+from . import media as media_engine
+
+FRAME_SCAN_CAP = 60 # hard cap on frames scanned for a "sharpest frame" suggestion
+
+
+def _now() -> str:
+ return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
+
+
+# ---------------------------------------------------------------------------
+# Filter registry (pixel-transform pipeline)
+# ---------------------------------------------------------------------------
+
+
+@dataclass(frozen=True)
+class Param:
+ name: str
+ label: str
+ type: str = "range" # 'range' | 'toggle'
+ min: float = 0.0
+ max: float = 2.0
+ step: float = 0.01
+ default: float = 1.0
+ unit: str = ""
+
+
+@dataclass(frozen=True)
+class Filter:
+ id: str
+ label: str
+ apply: Callable[[Image.Image, dict[str, Any]], Image.Image]
+ params: list[Param] = field(default_factory=list)
+ # optional live-preview hints for the frontend (skip a server round-trip):
+ css: str | None = None # CSS `filter` fragment, e.g. "brightness({v})"
+ transform: str | None = None # CSS `transform` fragment, e.g. "rotate({v}deg)"
+
+ def schema(self) -> dict[str, Any]:
+ return {
+ "id": self.id,
+ "label": self.label,
+ "params": [vars(p) for p in self.params],
+ "css": self.css,
+ "transform": self.transform,
+ }
+
+
+FILTERS: dict[str, Filter] = {}
+
+
+def _register_filter(f: Filter) -> Filter:
+ FILTERS[f.id] = f
+ return f
+
+
+def _p(params: dict[str, Any], name: str, default: float) -> float:
+ try:
+ return float(params.get(name, default))
+ except (TypeError, ValueError):
+ return default
+
+
+def _enhance(cls):
+ return lambda img, params: cls(img).enhance(_p(params, "amount", 1.0))
+
+
+_register_filter(Filter(
+ "brightness", "Brightness", _enhance(ImageEnhance.Brightness),
+ [Param("amount", "Amount", min=0, max=2, default=1)], css="brightness({v})",
+))
+_register_filter(Filter(
+ "contrast", "Contrast", _enhance(ImageEnhance.Contrast),
+ [Param("amount", "Amount", min=0, max=2, default=1)], css="contrast({v})",
+))
+_register_filter(Filter(
+ "saturation", "Saturation", _enhance(ImageEnhance.Color),
+ [Param("amount", "Amount", min=0, max=2, default=1)], css="saturate({v})",
+))
+_register_filter(Filter(
+ "sharpness", "Sharpness", _enhance(ImageEnhance.Sharpness),
+ [Param("amount", "Amount", min=0, max=3, default=1)],
+))
+
+
+def _apply_gamma(img: Image.Image, params: dict[str, Any]) -> Image.Image:
+ g = max(_p(params, "amount", 1.0), 0.01)
+ lut = [min(255, round((i / 255) ** (1 / g) * 255)) for i in range(256)]
+ return img.point(lut * len(img.getbands()))
+
+
+_register_filter(Filter(
+ "gamma", "Gamma", _apply_gamma,
+ [Param("amount", "Amount", min=0.2, max=3, default=1)],
+))
+_register_filter(Filter(
+ "grayscale", "Grayscale",
+ lambda img, params: ImageOps.grayscale(img).convert("RGB") if _p(params, "on", 0) else img,
+ [Param("on", "On", type="toggle", default=0)], css="grayscale({v})",
+))
+_register_filter(Filter(
+ "invert", "Invert",
+ lambda img, params: ImageOps.invert(img.convert("RGB")) if _p(params, "on", 0) else img,
+ [Param("on", "On", type="toggle", default=0)], css="invert({v})",
+))
+_register_filter(Filter(
+ "rotate", "Rotate",
+ lambda img, params: img.rotate(-_p(params, "angle", 0), expand=True, fillcolor=(16, 20, 28)),
+ [Param("angle", "Angle", min=-180, max=180, step=1, default=0, unit="°")],
+ transform="rotate({v}deg)",
+))
+
+
+def _apply_crop(img: Image.Image, params: dict[str, Any]) -> Image.Image:
+ """Crop from fractional (0..1) x/y/w/h relative to the image."""
+ w, h = img.size
+ x0 = max(0, min(w, round(_p(params, "x", 0) * w)))
+ y0 = max(0, min(h, round(_p(params, "y", 0) * h)))
+ x1 = max(x0 + 1, min(w, round((_p(params, "x", 0) + _p(params, "w", 1)) * w)))
+ y1 = max(y0 + 1, min(h, round((_p(params, "y", 0) + _p(params, "h", 1)) * h)))
+ return img.crop((x0, y0, x1, y1))
+
+
+_register_filter(Filter("crop", "Crop", _apply_crop)) # driven by an interactive box, no sliders
+
+
+def apply_ops(image: Image.Image, ops: list[dict[str, Any]]) -> Image.Image:
+ """Run an ordered list of ``{"op": id, "params": {...}}`` through the pipeline."""
+ out = image.convert("RGB")
+ for op in ops:
+ flt = FILTERS.get(op.get("op"))
+ if flt is None:
+ raise ValueError(f"unknown filter {op.get('op')!r}")
+ out = flt.apply(out, op.get("params") or {})
+ return out
+
+
+# ---------------------------------------------------------------------------
+# Analysis registry (read-only inspectors)
+# ---------------------------------------------------------------------------
+
+
+@dataclass(frozen=True)
+class Analysis:
+ id: str
+ label: str
+ run: Callable[[Image.Image, dict[str, Any]], dict[str, Any]]
+
+
+ANALYSES: dict[str, Analysis] = {}
+
+
+def _register_analysis(a: Analysis) -> Analysis:
+ ANALYSES[a.id] = a
+ return a
+
+
+def _histogram(img: Image.Image, params: dict[str, Any]) -> dict[str, Any]:
+ rgb = img.convert("RGB")
+ hist = rgb.histogram()
+ return {
+ "kind": "histogram",
+ "channels": {"r": hist[0:256], "g": hist[256:512], "b": hist[512:768]},
+ }
+
+
+def _exif(img: Image.Image, params: dict[str, Any]) -> dict[str, Any]:
+ rows: dict[str, str] = {
+ "Format": img.format or "—",
+ "Mode": img.mode,
+ "Size": f"{img.width} × {img.height}",
+ }
+ exif = img.getexif()
+ for tag_id, value in exif.items():
+ name = TAGS.get(tag_id, str(tag_id))
+ if name == "GPSInfo":
+ gps = {GPSTAGS.get(k, str(k)): v for k, v in exif.get_ifd(tag_id).items()}
+ if gps:
+ rows["GPS"] = ", ".join(f"{k}={v}" for k, v in gps.items())
+ continue
+ text = str(value)
+ rows[name] = text[:120] + "…" if len(text) > 120 else text
+ return {"kind": "keyvalue", "rows": rows}
+
+
+def _ela(img: Image.Image, params: dict[str, Any]) -> dict[str, Any]:
+ """Error Level Analysis — a *hint*, never a verdict (spec §6)."""
+ quality = int(params.get("quality", 90))
+ base = img.convert("RGB")
+ buf = io.BytesIO()
+ base.save(buf, "JPEG", quality=quality)
+ buf.seek(0)
+ resaved = Image.open(buf).convert("RGB")
+ diff = ImageChops.difference(base, resaved)
+ peak = max((hi for _, hi in diff.getextrema()), default=1) or 1
+ amplified = ImageEnhance.Brightness(diff).enhance(255.0 / peak)
+ out = io.BytesIO()
+ amplified.save(out, "PNG")
+ data = base64.b64encode(out.getvalue()).decode("ascii")
+ return {
+ "kind": "image",
+ "data_url": f"data:image/png;base64,{data}",
+ "note": "Error Level Analysis is a tampering *hint*, not proof. "
+ "Bright, uneven regions can indicate edits — or just texture and edges.",
+ }
+
+
+_register_analysis(Analysis("histogram", "Histogram", _histogram))
+_register_analysis(Analysis("exif", "EXIF & metadata", _exif))
+_register_analysis(Analysis("ela", "Error Level Analysis", _ela))
+
+
+def registries() -> dict[str, Any]:
+ """Machine-readable description of every filter and analysis (drives the UI)."""
+ return {
+ "filters": [f.schema() for f in FILTERS.values()],
+ "analyses": [{"id": a.id, "label": a.label} for a in ANALYSES.values()],
+ }
+
+
+def run_analysis(case: Case, rel_path: str, name: str, params: dict[str, Any]) -> dict[str, Any]:
+ analysis = ANALYSES.get(name)
+ if analysis is None:
+ raise ValueError(f"unknown analysis {name!r}")
+ with Image.open(case.resolve_inside(rel_path)) as img:
+ return analysis.run(img, params or {})
+
+
+# ---------------------------------------------------------------------------
+# Video / probe helpers (ffmpeg + ffprobe)
+# ---------------------------------------------------------------------------
+
+
+def ffprobe_available() -> bool:
+ return shutil.which("ffprobe") is not None
+
+
+def probe(case: Case, rel_path: str) -> dict[str, Any]:
+ """Lightweight metadata for the viewer: kind, dimensions, duration, fps."""
+ path = case.resolve_inside(rel_path)
+ kind = media_engine.media_kind(path.name)
+ info: dict[str, Any] = {"path": rel_path, "kind": kind, "filename": path.name}
+
+ if kind == "image":
+ with Image.open(path) as img:
+ info.update(width=img.width, height=img.height)
+ return info
+
+ if kind == "video" and ffprobe_available():
+ proc = subprocess.run(
+ ["ffprobe", "-v", "error", "-print_format", "json",
+ "-show_format", "-show_streams", str(path)],
+ capture_output=True, timeout=30,
+ )
+ if proc.returncode == 0:
+ data = json.loads(proc.stdout or b"{}")
+ stream = next((s for s in data.get("streams", []) if s.get("codec_type") == "video"), {})
+ info.update(
+ width=stream.get("width"),
+ height=stream.get("height"),
+ duration=float(data.get("format", {}).get("duration", 0) or 0),
+ fps=_parse_fps(stream.get("avg_frame_rate") or stream.get("r_frame_rate")),
+ codec=stream.get("codec_name"),
+ )
+ return info
+
+
+def _parse_fps(rate: str | None) -> float | None:
+ if not rate or "/" not in rate:
+ return None
+ num, den = rate.split("/", 1)
+ try:
+ return round(float(num) / float(den), 3) if float(den) else None
+ except (ValueError, ZeroDivisionError):
+ return None
+
+
+def extract_frame(video_path: Path, time_s: float) -> Image.Image:
+ """Decode a single frame at ``time_s`` seconds via ffmpeg (needs ffmpeg)."""
+ if not media_engine.ffmpeg_available():
+ raise RuntimeError("ffmpeg is required to extract video frames")
+ proc = subprocess.run(
+ ["ffmpeg", "-y", "-loglevel", "error", "-ss", f"{max(time_s, 0):.3f}",
+ "-i", str(video_path), "-frames:v", "1", "-f", "image2pipe", "-vcodec", "png", "pipe:1"],
+ capture_output=True, timeout=60,
+ )
+ if proc.returncode != 0 or not proc.stdout:
+ raise RuntimeError((proc.stderr or b"").decode("utf-8", "replace").strip() or "frame decode failed")
+ return Image.open(io.BytesIO(proc.stdout)).convert("RGB")
+
+
+def _sharpness(img: Image.Image) -> float:
+ """Relative focus score: variance of the edge response (no numpy needed)."""
+ edges = img.convert("L").filter(ImageFilter.FIND_EDGES)
+ w, h = edges.size
+ if w > 6 and h > 6: # trim FIND_EDGES border artefacts
+ edges = edges.crop((2, 2, w - 2, h - 2))
+ return round(ImageStat.Stat(edges).var[0], 2)
+
+
+def _derivation(video_rel: str, sha: str | None, **extra: Any) -> dict[str, Any]:
+ return {"type": "inspect", "from": video_rel, "from_sha256": sha, "at": _now(), **extra}
+
+
+def _source_sha(case: Case, rel_path: str) -> str | None:
+ entity = case.find_entity(attr="path", value=rel_path)
+ return entity["attrs"].get("sha256") if entity else None
+
+
+def _stamp() -> str:
+ return datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S")
+
+
+def capture_frame(case: Case, video_rel: str, time_s: float, label: str | None = None) -> dict[str, Any]:
+ """Extract one frame and file it as case media."""
+ video_path = case.resolve_inside(video_rel)
+ frame = extract_frame(video_path, time_s)
+ stem = Path(video_path.name).stem[:40]
+ name = f"{stem}_t{time_s:.2f}s_{_stamp()}.png"
+ source = _derivation(video_rel, _source_sha(case, video_rel), op="frame", time=round(time_s, 3))
+ result = media_engine.import_image(case, frame, name, source, by="inspect")
+ if label and not result.get("duplicate"):
+ media_engine.update_media(case, result["item"]["path"], {"label": label})
+ return result
+
+
+def suggest_frames(
+ case: Case, video_rel: str, bins: int = 12, set_progress: Callable[[dict], None] | None = None
+) -> list[dict[str, Any]]:
+ """Sample one frame per time bin and score its sharpness (spec v2 gesture)."""
+ video_path = case.resolve_inside(video_rel)
+ meta = probe(case, video_rel)
+ duration = meta.get("duration") or 0
+ if duration <= 0:
+ raise RuntimeError("could not read video duration (ffprobe needed)")
+ bins = max(1, min(bins, FRAME_SCAN_CAP))
+ out: list[dict[str, Any]] = []
+ for i in range(bins):
+ t = duration * (i + 0.5) / bins
+ try:
+ score = _sharpness(extract_frame(video_path, t))
+ except Exception:
+ continue
+ out.append({"time": round(t, 3), "score": score})
+ if set_progress:
+ set_progress({"percent": round((i + 1) * 100 / bins, 1)})
+ out.sort(key=lambda d: d["score"], reverse=True)
+ for rank, item in enumerate(out):
+ item["rank"] = rank
+ return out
+
+
+# ---------------------------------------------------------------------------
+# Adjustments & collage (operate on images / captured frames)
+# ---------------------------------------------------------------------------
+
+
+def bake(case: Case, rel_path: str, ops: list[dict[str, Any]], label: str | None = None) -> dict[str, Any]:
+ """Apply an adjustment pipeline to an image and file the result as new media."""
+ with Image.open(case.resolve_inside(rel_path)) as img:
+ rendered = apply_ops(img, ops)
+ stem = Path(rel_path).stem[:40]
+ name = f"{stem}_edit_{_stamp()}.png"
+ source = _derivation(rel_path, _source_sha(case, rel_path), op="adjust", ops=ops)
+ result = media_engine.import_image(case, rendered, name, source, by="inspect")
+ if label and not result.get("duplicate"):
+ media_engine.update_media(case, result["item"]["path"], {"label": label})
+ return result
+
+
+def collage(
+ case: Case,
+ rel_paths: list[str],
+ *,
+ columns: int = 2,
+ gap: int = 8,
+ background: str = "#12141c",
+ cell: int = 480,
+ label: str | None = None,
+) -> dict[str, Any]:
+ """Assemble several images into a contact-sheet / collage (one derivative)."""
+ if not rel_paths:
+ raise ValueError("collage needs at least one image")
+ columns = max(1, min(columns, len(rel_paths)))
+ cell = max(64, min(cell, 1024))
+ gap = max(0, min(gap, 64))
+
+ tiles: list[Image.Image] = []
+ for rel in rel_paths:
+ with Image.open(case.resolve_inside(rel)) as img:
+ thumb = img.convert("RGB")
+ thumb.thumbnail((cell, cell))
+ tiles.append(thumb)
+
+ rows = (len(tiles) + columns - 1) // columns
+ width = columns * cell + (columns + 1) * gap
+ height = rows * cell + (rows + 1) * gap
+ canvas = Image.new("RGB", (width, height), background)
+
+ for idx, tile in enumerate(tiles):
+ r, c = divmod(idx, columns)
+ cx = gap + c * (cell + gap) + (cell - tile.width) // 2
+ cy = gap + r * (cell + gap) + (cell - tile.height) // 2
+ canvas.paste(tile, (cx, cy))
+
+ source = _derivation("", None, op="collage", sources=rel_paths, columns=columns)
+ name = f"collage_{_stamp()}.png"
+ result = media_engine.import_image(case, canvas, name, source, by="inspect")
+ if label and not result.get("duplicate"):
+ media_engine.update_media(case, result["item"]["path"], {"label": label})
+ return result
diff --git a/src/ozimut/engine/media.py b/src/ozimut/engine/media.py
index 15a9af1..7c15696 100644
--- a/src/ozimut/engine/media.py
+++ b/src/ozimut/engine/media.py
@@ -106,8 +106,14 @@ def _write_sidecar(media_path: Path, data: dict[str, Any]) -> None:
)
-def _register(case: Case, media_path: Path, source: dict[str, Any]) -> dict[str, Any]:
- """Hash + sidecar + thumbnail + media entity. Dedupes on sha256."""
+def _register(
+ case: Case, media_path: Path, source: dict[str, Any], *, by: str = "media-library"
+) -> dict[str, Any]:
+ """Hash + sidecar + thumbnail + media entity. Dedupes on sha256.
+
+ ``by`` records which tool produced the item (media-library import, inspect
+ derivative, …) on the media entity's provenance (spec §6 honest output).
+ """
digest = sha256_file(media_path)
existing = case.find_entity(attr="sha256", value=digest)
@@ -134,7 +140,7 @@ def _register(case: Case, media_path: Path, source: dict[str, Any]) -> dict[str,
"media",
media_path.name,
attrs={"path": rel_path, "sha256": digest, **({"source_url": source["url"]} if source.get("url") else {})},
- by="media-library",
+ by=by,
source=source.get("url"),
)
return {"duplicate": False, "entity": entity, "item": {**sidecar, "path": rel_path}}
@@ -149,6 +155,24 @@ def import_stream(case: Case, filename: str, stream: BinaryIO) -> dict[str, Any]
return _register(case, dest, {"type": "upload", "original_name": filename})
+def import_image(
+ case: Case, image: Image.Image, filename: str, source: dict[str, Any], *, by: str = "inspect"
+) -> dict[str, Any]:
+ """File a freshly rendered PIL image into the case as a media derivative.
+
+ Used by tools that produce new imagery from existing media (frame capture,
+ adjustments, collages). The ``source`` dict records the derivation so the
+ output stays auditable back to its origin (spec §6).
+ """
+ media_dir = case.subdir("media")
+ name = safe_filename(filename)
+ if not name.lower().endswith(".png"):
+ name = f"{Path(name).stem}.png"
+ dest = unique_path(media_dir, name)
+ image.convert("RGB").save(dest, "PNG")
+ return _register(case, dest, source, by=by)
+
+
def download_url(case: Case, url: str, progress_hook=None) -> dict[str, Any]:
"""Download a URL via yt-dlp into the case. Blocking — run in a worker."""
import yt_dlp
@@ -222,6 +246,44 @@ def list_media(case: Case) -> list[dict[str, Any]]:
return items
+def update_media(case: Case, rel_path: str, patch: dict[str, Any]) -> dict[str, Any]:
+ """Update mutable sidecar fields (notes, folder, label) and mirror them onto
+ the media entity so the case sidebar stays in sync."""
+ media_path = case.resolve_inside(rel_path)
+ sidecar = _sidecar_path(media_path)
+ if not sidecar.exists():
+ raise ValueError(f"no sidecar found for {rel_path!r}")
+
+ data = json.loads(sidecar.read_text(encoding="utf-8"))
+ for key in ("notes", "folder", "label"):
+ if key in patch:
+ val = patch[key]
+ if val is None or val == "":
+ data.pop(key, None)
+ else:
+ data[key] = str(val)
+
+ _write_sidecar(media_path, data)
+
+ # mirror onto the media entity (label + folder/notes attrs)
+ entity = case.find_entity(attr="path", value=rel_path)
+ if entity:
+ entity_patch: dict[str, Any] = {}
+ if patch.get("label"):
+ entity_patch["label"] = patch["label"]
+ attrs: dict[str, Any] = {}
+ if "folder" in patch:
+ attrs["folder"] = patch["folder"] or ""
+ if "notes" in patch:
+ attrs["notes"] = patch["notes"] or ""
+ if attrs:
+ entity_patch["attrs"] = attrs
+ if entity_patch:
+ case.update_entity(entity["id"], entity_patch)
+
+ return {**data, "path": rel_path}
+
+
def delete_media(case: Case, rel_path: str) -> None:
media_path = case.resolve_inside(rel_path)
sidecar = _sidecar_path(media_path)
diff --git a/src/ozimut/engine/tiles.py b/src/ozimut/engine/tiles.py
index 4aacdb9..dc8424f 100644
--- a/src/ozimut/engine/tiles.py
+++ b/src/ozimut/engine/tiles.py
@@ -140,23 +140,35 @@ def fetch_crop(
provider: Provider,
*,
crosshair: bool = True,
+ bearing: float = 0.0,
fetch_tile: Callable[[httpx.Client, str], Image.Image | None] | None = None,
) -> tuple[Image.Image, dict[str, Any]]:
"""Stitch a width×height crop centered on (lat, lon). Returns (image, provenance).
Missing tiles become labeled gray placeholders instead of failing the crop.
+ ``bearing`` (degrees clockwise from north) rotates the crop: a larger
+ north-up canvas is stitched, rotated, then center-cropped to width×height so
+ the result matches a map turned to that heading.
"""
if provider.needs_key:
raise TileFetchError(f"provider '{provider.id}' requires an API key (settings.json)")
zoom = min(zoom, provider.max_zoom)
width, height = min(width, 2048), min(height, 2048)
+ bearing = bearing % 360.0
+
+ # A rotated crop needs a bigger north-up source so its corners stay covered
+ # after rotation; the diagonal is the smallest square that always fits.
+ if bearing:
+ fetch_w = fetch_h = min(math.ceil(math.hypot(width, height)) + 2, 2048)
+ else:
+ fetch_w, fetch_h = width, height
center_x, center_y = project(lat, lon, zoom)
center_px, center_py = center_x * TILE_SIZE, center_y * TILE_SIZE
- left, top = center_px - width / 2, center_py - height / 2
+ left, top = center_px - fetch_w / 2, center_py - fetch_h / 2
tile_x0, tile_y0 = int(left // TILE_SIZE), int(top // TILE_SIZE)
- tile_x1, tile_y1 = int((left + width) // TILE_SIZE), int((top + height) // TILE_SIZE)
+ tile_x1, tile_y1 = int((left + fetch_w) // TILE_SIZE), int((top + fetch_h) // TILE_SIZE)
n_tiles = (tile_x1 - tile_x0 + 1) * (tile_y1 - tile_y0 + 1)
if n_tiles > MAX_TILES_PER_CROP:
raise TileFetchError(
@@ -165,7 +177,7 @@ def fetch_crop(
max_index = (1 << zoom) - 1
fetch = fetch_tile or _default_fetch
- canvas = Image.new("RGB", (width, height), (24, 28, 38))
+ canvas = Image.new("RGB", (fetch_w, fetch_h), (24, 28, 38))
missing = 0
def grab(tx: int, ty: int) -> tuple[int, int, Image.Image | None]:
@@ -196,6 +208,14 @@ def fetch_crop(
continue
canvas.paste(tile, (px, py))
+ if bearing:
+ # CSS rotates the map clockwise; PIL rotates counter-clockwise, hence -bearing.
+ canvas = canvas.rotate(
+ -bearing, resample=Image.Resampling.BICUBIC, expand=False, fillcolor=(24, 28, 38)
+ )
+ off_x, off_y = (fetch_w - width) // 2, (fetch_h - height) // 2
+ canvas = canvas.crop((off_x, off_y, off_x + width, off_y + height))
+
if crosshair:
_draw_crosshair(canvas)
@@ -208,6 +228,7 @@ def fetch_crop(
"zoom": zoom,
"width": width,
"height": height,
+ "bearing": round(bearing, 1),
"meters_per_pixel": round(meters_per_pixel(lat, zoom), 3),
"tiles": n_tiles,
"tiles_missing": missing,
diff --git a/src/ozimut/server.py b/src/ozimut/server.py
index 5bdc358..93bbf59 100644
--- a/src/ozimut/server.py
+++ b/src/ozimut/server.py
@@ -18,12 +18,14 @@ def create_app() -> FastAPI:
app = FastAPI(title="Ozimut", version=__version__, docs_url="/api/docs")
- from .api import cases, files, media, proofs, satellite
+ from .api import cases, drafts, files, inspect, media, proofs, satellite
app.include_router(cases.router)
app.include_router(media.router)
+ app.include_router(inspect.router)
app.include_router(satellite.router)
app.include_router(proofs.router)
+ app.include_router(drafts.router)
app.include_router(files.router)
@app.get("/api/health")
diff --git a/src/ozimut/workspace.py b/src/ozimut/workspace.py
index b50d9ba..6d07e67 100644
--- a/src/ozimut/workspace.py
+++ b/src/ozimut/workspace.py
@@ -91,6 +91,7 @@ class Case:
"name": name,
"created_at": _now(),
"updated_at": _now(),
+ "folders": [],
"entities": [],
"links": [],
}
@@ -275,6 +276,35 @@ class Case:
raise CaseError(f"link '{link_id}' not found")
self._write_json(data)
+ # -- folders (organisational buckets for entities) -----------------------
+
+ def list_folders(self) -> list[str]:
+ return self.read().get("folders", [])
+
+ def add_folder(self, name: str) -> list[str]:
+ name = name.strip()
+ if not name:
+ raise CaseError("folder name is required")
+ data = self.read()
+ folders = data.setdefault("folders", [])
+ if name not in folders:
+ folders.append(name)
+ folders.sort(key=str.lower)
+ self._write_json(data)
+ return data["folders"]
+
+ def remove_folder(self, name: str) -> list[str]:
+ data = self.read()
+ folders = data.setdefault("folders", [])
+ if name in folders:
+ folders.remove(name)
+ # unassign any entity still pointing at the removed folder
+ for entity in data.get("entities", []):
+ if entity.get("attrs", {}).get("folder") == name:
+ entity["attrs"].pop("folder", None)
+ self._write_json(data)
+ return data["folders"]
+
# -- helpers -------------------------------------------------------------
def subdir(self, name: str) -> Path:
diff --git a/tests/test_cases_api.py b/tests/test_cases_api.py
index dd84924..02e348c 100644
--- a/tests/test_cases_api.py
+++ b/tests/test_cases_api.py
@@ -82,3 +82,125 @@ def test_entities_and_links(client):
data = client.get(f"/api/cases/{cid}").json()
assert len(data["entities"]) == 1
assert data["links"] == []
+
+
+# ---------------------------------------------------------------------------
+# Satellite capture notes (PATCH /api/cases/{id}/satellite)
+# Uses a pre-written sidecar to avoid a live tile fetch.
+# ---------------------------------------------------------------------------
+
+import json
+import os
+
+
+def _plant_capture(client, cid: str) -> dict:
+ """Write a fake satellite PNG + sidecar directly into the case directory."""
+ import ozimut.config as cfg
+ from pathlib import Path
+
+ case_dir = cfg.cases_dir() / cid
+ sat_dir = case_dir / "satellite"
+ sat_dir.mkdir(parents=True, exist_ok=True)
+
+ fname = "sat_test_z16_esri.png"
+ (sat_dir / fname).write_bytes(b"\x89PNG\r\n\x1a\n") # minimal PNG magic bytes
+ sidecar = {
+ "filename": fname,
+ "provider": "esri-world-imagery",
+ "provider_label": "Esri World Imagery",
+ "zoom": 16,
+ "lat": 50.0,
+ "lon": 30.0,
+ "fetched_at": "2026-07-08T12:00:00Z",
+ "tiles": 9,
+ "tiles_missing": 0,
+ }
+ (sat_dir / (fname + ".json")).write_text(
+ json.dumps(sidecar, indent=2) + "\n", encoding="utf-8"
+ )
+ sidecar["path"] = f"satellite/{fname}"
+ return sidecar
+
+
+def test_satellite_patch_notes(client):
+ cid = client.post("/api/cases", json={"name": "SatNotes"}).json()["id"]
+ capture = _plant_capture(client, cid)
+
+ updated = client.patch(
+ f"/api/cases/{cid}/satellite",
+ json={"path": capture["path"], "notes": "good reference point"},
+ ).json()
+ assert updated["notes"] == "good reference point"
+
+ # persisted: shows up in listing
+ listed = client.get(f"/api/cases/{cid}/satellite").json()
+ assert listed[0]["notes"] == "good reference point"
+
+
+def test_satellite_patch_clear_notes(client):
+ cid = client.post("/api/cases", json={"name": "SatClear"}).json()["id"]
+ capture = _plant_capture(client, cid)
+
+ client.patch(
+ f"/api/cases/{cid}/satellite",
+ json={"path": capture["path"], "notes": "initial"},
+ )
+ updated = client.patch(
+ f"/api/cases/{cid}/satellite",
+ json={"path": capture["path"], "notes": ""},
+ ).json()
+ assert "notes" not in updated
+
+
+def test_satellite_patch_not_found(client):
+ cid = client.post("/api/cases", json={"name": "SatMissing"}).json()["id"]
+ res = client.patch(
+ f"/api/cases/{cid}/satellite",
+ json={"path": "satellite/nonexistent.png", "notes": "x"},
+ )
+ assert res.status_code == 404
+
+
+# ---------------------------------------------------------------------------
+# Folders (case-level organisational buckets)
+# ---------------------------------------------------------------------------
+
+
+def test_folders_crud(client):
+ cid = client.post("/api/cases", json={"name": "Folders"}).json()["id"]
+
+ # empty by default
+ assert client.get(f"/api/cases/{cid}/folders").json() == []
+
+ # create, deduped and sorted case-insensitively
+ client.post(f"/api/cases/{cid}/folders", json={"name": "Videos"})
+ folders = client.post(f"/api/cases/{cid}/folders", json={"name": "Aerial"}).json()
+ assert folders == ["Aerial", "Videos"]
+ # idempotent
+ assert client.post(f"/api/cases/{cid}/folders", json={"name": "Videos"}).json() == [
+ "Aerial",
+ "Videos",
+ ]
+
+ # persisted in case.json
+ assert client.get(f"/api/cases/{cid}").json()["folders"] == ["Aerial", "Videos"]
+
+ # delete
+ remaining = client.delete(f"/api/cases/{cid}/folders", params={"name": "Videos"}).json()
+ assert remaining == ["Aerial"]
+
+
+def test_delete_folder_unassigns_entities(client):
+ cid = client.post("/api/cases", json={"name": "Unassign"}).json()["id"]
+ client.post(f"/api/cases/{cid}/folders", json={"name": "Suspects"})
+ ent = client.post(
+ f"/api/cases/{cid}/entities",
+ json={"type": "person", "label": "John", "attrs": {"folder": "Suspects"}},
+ ).json()
+
+ client.delete(f"/api/cases/{cid}/folders", params={"name": "Suspects"})
+ data = client.get(f"/api/cases/{cid}").json()
+ assert data["folders"] == []
+ entity = next(e for e in data["entities"] if e["id"] == ent["id"])
+ assert "folder" not in entity["attrs"]
+
diff --git a/tests/test_drafts_api.py b/tests/test_drafts_api.py
new file mode 100644
index 0000000..69cfcdc
--- /dev/null
+++ b/tests/test_drafts_api.py
@@ -0,0 +1,83 @@
+"""Post drafts: save state, list, reload, entity upsert, delete."""
+
+STATE = {
+ "description": "A formation of 13 helicopters was spotted heading East",
+ "coordsText": "10.303315, -66.874095",
+ "place": "Los Anacuos, Miranda, Venezuela",
+ "mention": "@GeoConfirmed",
+ "source": "https://instagram.com/urreiztieta_ne",
+ "tweet1": "Los Anacuos, Miranda, Venezuela - 843G+89C",
+ "mediaEnabled": True,
+ "mediaType": "video",
+ "mediaText": "",
+ "mediaPath": "media/clip.mp4",
+ "extraTweets": [{"id": 1, "text": "More context here"}],
+}
+
+
+def test_save_load_roundtrip(client):
+ cid = client.post("/api/cases", json={"name": "Drafts"}).json()["id"]
+
+ saved = client.post(
+ f"/api/cases/{cid}/drafts",
+ json={"title": "Helicopter formation", "state": STATE},
+ ).json()
+ assert saved["name"] == "helicopter-formation"
+ assert saved["draft"] == "exports/helicopter-formation.json"
+
+ listed = client.get(f"/api/cases/{cid}/drafts").json()
+ assert len(listed) == 1
+ assert listed[0]["title"] == "Helicopter formation"
+
+ draft = client.get(f"/api/cases/{cid}/drafts/helicopter-formation").json()
+ assert draft["title"] == "Helicopter formation"
+ assert draft["state"]["place"] == "Los Anacuos, Miranda, Venezuela"
+ assert draft["state"]["extraTweets"][0]["text"] == "More context here"
+
+
+def test_draft_filed_as_post_entity_and_updated_on_resave(client):
+ cid = client.post("/api/cases", json={"name": "Drafts"}).json()["id"]
+
+ saved = client.post(
+ f"/api/cases/{cid}/drafts",
+ json={"title": "First title", "state": STATE},
+ ).json()
+
+ # resave under the same name with a new title updates the single entity
+ client.post(
+ f"/api/cases/{cid}/drafts",
+ json={"name": saved["name"], "title": "Renamed draft", "state": STATE},
+ )
+ posts = [e for e in client.get(f"/api/cases/{cid}").json()["entities"] if e["type"] == "post"]
+ assert len(posts) == 1
+ assert posts[0]["label"] == "Renamed draft"
+ assert posts[0]["attrs"]["draft"] == "exports/first-title.json"
+
+
+def test_created_at_preserved_on_resave(client):
+ cid = client.post("/api/cases", json={"name": "Drafts"}).json()["id"]
+ client.post(f"/api/cases/{cid}/drafts", json={"title": "Keep created", "state": STATE})
+ first = client.get(f"/api/cases/{cid}/drafts/keep-created").json()
+ client.post(
+ f"/api/cases/{cid}/drafts",
+ json={"name": "keep-created", "title": "Keep created", "state": STATE},
+ )
+ second = client.get(f"/api/cases/{cid}/drafts/keep-created").json()
+ assert first["created_at"] == second["created_at"]
+
+
+def test_delete_removes_file_and_entity(client):
+ cid = client.post("/api/cases", json={"name": "Drafts"}).json()["id"]
+ client.post(f"/api/cases/{cid}/drafts", json={"title": "To delete", "state": STATE})
+
+ r = client.delete(f"/api/cases/{cid}/drafts/to-delete")
+ assert r.json()["status"] == "deleted"
+ assert client.get(f"/api/cases/{cid}/drafts").json() == []
+ assert client.get(f"/api/cases/{cid}/drafts/to-delete").status_code == 404
+ posts = [e for e in client.get(f"/api/cases/{cid}").json()["entities"] if e["type"] == "post"]
+ assert posts == []
+
+
+def test_load_missing_draft_is_404(client):
+ cid = client.post("/api/cases", json={"name": "Drafts"}).json()["id"]
+ assert client.get(f"/api/cases/{cid}/drafts/nope").status_code == 404
diff --git a/tests/test_inspect_api.py b/tests/test_inspect_api.py
new file mode 100644
index 0000000..31bf0bc
--- /dev/null
+++ b/tests/test_inspect_api.py
@@ -0,0 +1,195 @@
+"""Inspect tool: probe, adjustments (bake), collage, analyses, frame capture.
+
+Image-based features use Pillow only (deterministic, no ffmpeg). Frame capture
+needs ffmpeg and is skipped when it is unavailable in the environment.
+"""
+
+import io
+import time
+
+import pytest
+from PIL import Image
+
+from ozimut.engine import media as media_engine
+
+
+def _png_bytes(color=(120, 60, 30), size=(80, 60)) -> bytes:
+ buf = io.BytesIO()
+ Image.new("RGB", size, color).save(buf, "PNG")
+ return buf.getvalue()
+
+
+def _upload(client, cid, name, data=None):
+ return client.post(
+ f"/api/cases/{cid}/media/upload",
+ files={"file": (name, io.BytesIO(data or _png_bytes()), "image/png")},
+ ).json()["item"]
+
+
+def test_ops_registry_is_self_describing(client):
+ ops = client.get("/api/inspect/ops").json()
+ ids = {f["id"] for f in ops["filters"]}
+ assert {"brightness", "contrast", "gamma", "crop", "rotate"} <= ids
+ brightness = next(f for f in ops["filters"] if f["id"] == "brightness")
+ assert brightness["css"] == "brightness({v})"
+ assert brightness["params"][0]["default"] == 1
+ assert {a["id"] for a in ops["analyses"]} >= {"histogram", "exif", "ela"}
+
+
+def test_probe_image(client):
+ cid = client.post("/api/cases", json={"name": "Probe"}).json()["id"]
+ item = _upload(client, cid, "shot.png", _png_bytes(size=(120, 90)))
+ probe = client.get(f"/api/cases/{cid}/inspect/probe", params={"path": item["path"]}).json()
+ assert probe["kind"] == "image"
+ assert probe["width"] == 120 and probe["height"] == 90
+
+
+def test_bake_creates_derivative_media(client):
+ cid = client.post("/api/cases", json={"name": "Bake"}).json()["id"]
+ item = _upload(client, cid, "orig.png")
+
+ res = client.post(
+ f"/api/cases/{cid}/inspect/bake",
+ json={"path": item["path"], "ops": [{"op": "brightness", "params": {"amount": 1.4}}],
+ "label": "Brightened"},
+ ).json()
+ assert res["duplicate"] is False
+ new_path = res["item"]["path"]
+ assert new_path != item["path"]
+
+ # filed as a new media with inspect provenance and served
+ listing = client.get(f"/api/cases/{cid}/media").json()
+ assert len(listing) == 2
+ entities = client.get(f"/api/cases/{cid}").json()["entities"]
+ derived = next(e for e in entities if e["attrs"]["path"] == new_path)
+ assert derived["provenance"]["by"] == "inspect"
+ assert client.get(f"/files/{cid}/{new_path}").status_code == 200
+
+ # derivation recorded in the sidecar source (auditable)
+ updated = next(m for m in listing if m["path"] == new_path)
+ assert updated["source"]["op"] == "adjust"
+ assert updated["source"]["from"] == item["path"]
+
+
+def test_bake_unknown_filter_is_rejected(client):
+ cid = client.post("/api/cases", json={"name": "BadOp"}).json()["id"]
+ item = _upload(client, cid, "x.png")
+ res = client.post(
+ f"/api/cases/{cid}/inspect/bake",
+ json={"path": item["path"], "ops": [{"op": "nope", "params": {}}]},
+ )
+ assert res.status_code == 422
+
+
+def test_crop_op_reduces_dimensions(client):
+ cid = client.post("/api/cases", json={"name": "Crop"}).json()["id"]
+ item = _upload(client, cid, "big.png", _png_bytes(size=(200, 100)))
+ res = client.post(
+ f"/api/cases/{cid}/inspect/bake",
+ json={"path": item["path"],
+ "ops": [{"op": "crop", "params": {"x": 0.25, "y": 0.25, "w": 0.5, "h": 0.5}}]},
+ ).json()
+ probe = client.get(
+ f"/api/cases/{cid}/inspect/probe", params={"path": res["item"]["path"]}
+ ).json()
+ assert probe["width"] == 100 and probe["height"] == 50
+
+
+def test_collage_combines_images(client):
+ cid = client.post("/api/cases", json={"name": "Collage"}).json()["id"]
+ a = _upload(client, cid, "a.png", _png_bytes(color=(10, 20, 30)))
+ b = _upload(client, cid, "b.png", _png_bytes(color=(200, 100, 50)))
+
+ res = client.post(
+ f"/api/cases/{cid}/inspect/collage",
+ json={"paths": [a["path"], b["path"]], "columns": 2, "cell": 100, "gap": 10},
+ ).json()
+ assert res["duplicate"] is False
+ probe = client.get(
+ f"/api/cases/{cid}/inspect/probe", params={"path": res["item"]["path"]}
+ ).json()
+ # 2 columns × 100 cell + 3 gaps × 10 = 230 wide, 1 row = 120 tall
+ assert probe["width"] == 230 and probe["height"] == 120
+ assert client.get(f"/api/cases/{cid}/media").json().__len__() == 3
+
+
+def test_collage_requires_paths(client):
+ cid = client.post("/api/cases", json={"name": "Empty"}).json()["id"]
+ res = client.post(f"/api/cases/{cid}/inspect/collage", json={"paths": []})
+ assert res.status_code == 422
+
+
+def test_analyze_histogram(client):
+ cid = client.post("/api/cases", json={"name": "Hist"}).json()["id"]
+ item = _upload(client, cid, "img.png", _png_bytes(color=(255, 0, 0), size=(20, 20)))
+ res = client.post(
+ f"/api/cases/{cid}/inspect/analyze", json={"path": item["path"], "name": "histogram"}
+ ).json()
+ assert res["kind"] == "histogram"
+ # a pure-red image piles every pixel into R=255
+ assert res["channels"]["r"][255] == 400
+
+
+def test_analyze_exif_keyvalue(client):
+ cid = client.post("/api/cases", json={"name": "Exif"}).json()["id"]
+ item = _upload(client, cid, "img.png")
+ res = client.post(
+ f"/api/cases/{cid}/inspect/analyze", json={"path": item["path"], "name": "exif"}
+ ).json()
+ assert res["kind"] == "keyvalue"
+ assert res["rows"]["Format"] == "PNG"
+
+
+def test_analyze_ela_returns_image(client):
+ cid = client.post("/api/cases", json={"name": "Ela"}).json()["id"]
+ item = _upload(client, cid, "img.png")
+ res = client.post(
+ f"/api/cases/{cid}/inspect/analyze", json={"path": item["path"], "name": "ela"}
+ ).json()
+ assert res["kind"] == "image"
+ assert res["data_url"].startswith("data:image/png;base64,")
+
+
+def test_analyze_unknown_is_rejected(client):
+ cid = client.post("/api/cases", json={"name": "BadA"}).json()["id"]
+ item = _upload(client, cid, "img.png")
+ res = client.post(
+ f"/api/cases/{cid}/inspect/analyze", json={"path": item["path"], "name": "nope"}
+ )
+ assert res.status_code == 422
+
+
[email protected](not media_engine.ffmpeg_available(), reason="ffmpeg not installed")
+def test_frame_capture_from_video(client, tmp_path):
+ import subprocess
+
+ video = tmp_path / "clip.mp4"
+ subprocess.run(
+ ["ffmpeg", "-y", "-loglevel", "error", "-f", "lavfi",
+ "-i", "testsrc=duration=2:size=160x120:rate=10", str(video)],
+ check=True,
+ )
+ cid = client.post("/api/cases", json={"name": "Frames"}).json()["id"]
+ with video.open("rb") as fh:
+ item = client.post(
+ f"/api/cases/{cid}/media/upload",
+ files={"file": ("clip.mp4", fh, "video/mp4")},
+ ).json()["item"]
+
+ res = client.post(
+ f"/api/cases/{cid}/inspect/frame", json={"path": item["path"], "time": 1.0}
+ ).json()
+ assert res["item"]["kind"] == "image"
+ assert client.get(f"/files/{cid}/{res['item']['path']}").status_code == 200
+
+ # sharpest-frame suggestion runs as a job
+ job_id = client.post(
+ f"/api/cases/{cid}/inspect/suggest", json={"path": item["path"], "bins": 4}
+ ).json()["job_id"]
+ for _ in range(100):
+ job = client.get(f"/api/jobs/{job_id}").json()
+ if job["status"] != "running":
+ break
+ time.sleep(0.1)
+ assert job["status"] == "done"
+ assert len(job["result"]["frames"]) >= 1
diff --git a/tests/test_media_api.py b/tests/test_media_api.py
index 04991db..27ce978 100644
--- a/tests/test_media_api.py
+++ b/tests/test_media_api.py
@@ -69,6 +69,74 @@ def test_path_traversal_refused(client):
assert b"root:" not in res.content
+def test_update_media_notes_and_folder(client):
+ cid = client.post("/api/cases", json={"name": "Update"}).json()["id"]
+ item = _upload(client, cid, "clip.png", _png_bytes()).json()["item"]
+
+ updated = client.patch(
+ f"/api/cases/{cid}/media",
+ json={"path": item["path"], "notes": "found at coordinates", "folder": "ukraine"},
+ ).json()
+ assert updated["notes"] == "found at coordinates"
+ assert updated["folder"] == "ukraine"
+
+ # persisted: shows up in listing
+ listing = client.get(f"/api/cases/{cid}/media").json()
+ assert listing[0]["notes"] == "found at coordinates"
+ assert listing[0]["folder"] == "ukraine"
+
+ # folder + notes mirrored onto the media entity (so the sidebar sees them)
+ entity = client.get(f"/api/cases/{cid}").json()["entities"][0]
+ assert entity["attrs"]["folder"] == "ukraine"
+ assert entity["attrs"]["notes"] == "found at coordinates"
+
+ # clearing the folder mirrors an empty value on the entity
+ client.patch(f"/api/cases/{cid}/media", json={"path": item["path"], "folder": ""})
+ entity = client.get(f"/api/cases/{cid}").json()["entities"][0]
+ assert entity["attrs"]["folder"] == ""
+
+
+def test_update_media_label(client):
+ cid = client.post("/api/cases", json={"name": "Label"}).json()["id"]
+ item = _upload(client, cid, "img.png", _png_bytes()).json()["item"]
+
+ updated = client.patch(
+ f"/api/cases/{cid}/media",
+ json={"path": item["path"], "label": "Strike video — Kharkiv"},
+ ).json()
+ assert updated["label"] == "Strike video — Kharkiv"
+
+ # entity label updated too
+ entities = client.get(f"/api/cases/{cid}").json()["entities"]
+ assert entities[0]["label"] == "Strike video — Kharkiv"
+
+ # clear label reverts to no custom label
+ cleared = client.patch(
+ f"/api/cases/{cid}/media", json={"path": item["path"], "label": ""}
+ ).json()
+ assert "label" not in cleared
+
+
+def test_update_media_clear_notes(client):
+ cid = client.post("/api/cases", json={"name": "Clear"}).json()["id"]
+ item = _upload(client, cid, "img.png", _png_bytes()).json()["item"]
+
+ client.patch(f"/api/cases/{cid}/media", json={"path": item["path"], "notes": "initial"})
+ updated = client.patch(
+ f"/api/cases/{cid}/media", json={"path": item["path"], "notes": ""}
+ ).json()
+ assert "notes" not in updated
+
+
+def test_update_media_bad_path(client):
+ cid = client.post("/api/cases", json={"name": "Bad"}).json()["id"]
+ res = client.patch(
+ f"/api/cases/{cid}/media",
+ json={"path": "media/nonexistent.png", "notes": "x"},
+ )
+ assert res.status_code == 400
+
+
def test_download_job_bad_url(client):
cid = client.post("/api/cases", json={"name": "Job"}).json()["id"]
job_id = client.post(
diff --git a/tests/test_satellite_api.py b/tests/test_satellite_api.py
new file mode 100644
index 0000000..13709e3
--- /dev/null
+++ b/tests/test_satellite_api.py
@@ -0,0 +1,36 @@
+"""Satellite capture API: bearing is honored and persisted with provenance."""
+
+from PIL import Image
+
+from ozimut.engine import tiles
+
+
+def _fake_tile(client, url): # offline: every tile is a solid green square
+ return Image.new("RGB", (256, 256), (10, 120, 10))
+
+
+def test_capture_persists_bearing(client, monkeypatch):
+ monkeypatch.setattr(tiles, "_default_fetch", _fake_tile)
+ cid = client.post("/api/cases", json={"name": "Sat"}).json()["id"]
+
+ result = client.post(
+ f"/api/cases/{cid}/satellite/capture",
+ json={"lat": 48.8584, "lon": 2.2945, "zoom": 16,
+ "width": 640, "height": 480, "bearing": 90},
+ ).json()
+ assert result["bearing"] == 90.0
+
+ listed = client.get(f"/api/cases/{cid}/satellite").json()
+ assert len(listed) == 1
+ assert listed[0]["bearing"] == 90.0
+
+
+def test_capture_defaults_to_north(client, monkeypatch):
+ monkeypatch.setattr(tiles, "_default_fetch", _fake_tile)
+ cid = client.post("/api/cases", json={"name": "Sat"}).json()["id"]
+
+ result = client.post(
+ f"/api/cases/{cid}/satellite/capture",
+ json={"lat": 48.8584, "lon": 2.2945, "zoom": 16, "width": 512, "height": 512},
+ ).json()
+ assert result["bearing"] == 0.0
diff --git a/tests/test_tiles.py b/tests/test_tiles.py
index e0985d5..1d49e17 100644
--- a/tests/test_tiles.py
+++ b/tests/test_tiles.py
@@ -54,6 +54,54 @@ def test_fetch_crop_missing_tiles_dont_fail():
assert img.size == (512, 512)
+def test_fetch_crop_bearing_rotates_and_fills_corners():
+ provider = tiles.BUILTIN_PROVIDERS[0]
+ tile_colour = (10, 120, 10)
+
+ calls = {"north": 0, "rotated": 0}
+
+ def count(key):
+ def fetch(client, url):
+ calls[key] += 1
+ return Image.new("RGB", (256, 256), tile_colour)
+
+ return fetch
+
+ north, _ = tiles.fetch_crop(
+ 48.8584, 2.2945, 17, 640, 480, provider, crosshair=False,
+ fetch_tile=count("north"),
+ )
+ img, prov = tiles.fetch_crop(
+ 48.8584, 2.2945, 17, 640, 480, provider, crosshair=False, bearing=45,
+ fetch_tile=count("rotated"),
+ )
+
+ assert img.size == (640, 480)
+ assert prov["bearing"] == 45.0
+ # a rotated crop stitches a bigger north-up source → strictly more tiles
+ assert calls["rotated"] > calls["north"]
+ # corners stay covered by imagery, not the gray background fill
+ for corner in ((1, 1), (638, 1), (1, 478), (638, 478)):
+ assert img.getpixel(corner) == tile_colour
+
+
+def test_fetch_crop_bearing_zero_matches_unrotated():
+ provider = tiles.BUILTIN_PROVIDERS[0]
+ fetched = []
+
+ def fetch(client, url):
+ fetched.append(url)
+ return Image.new("RGB", (256, 256), (10, 120, 10))
+
+ img, prov = tiles.fetch_crop(
+ 48.8584, 2.2945, 17, 640, 480, provider, crosshair=False, bearing=0,
+ fetch_tile=fetch,
+ )
+ assert img.size == (640, 480)
+ assert prov["bearing"] == 0.0
+ assert prov["tiles"] == len(fetched)
+
+
def test_fetch_crop_tile_cap():
provider = tiles.BUILTIN_PROVIDERS[0]
try: