7 Commits
Author SHA1 Message Date
dmo b9a0259166 Add DNG support v0.7 2026-07-23 21:33:20 +02:00
dmo c2640cf75a Add configurable title and subtitle v0.6.1 2026-07-23 13:18:19 +02:00
dmo 47b8d42295 Added HEIC, HEIF and HIF support v0.6 2026-07-23 12:59:49 +02:00
dmo 3acf6bb7ec Add PNG and TIFF support v0.5 2026-07-23 11:23:49 +02:00
dmo 0541790dba Load favorite location on startup v0.4.3 2026-07-23 09:57:52 +02:00
dmo e250a83b6d Add shared favorite location v0.4.2 2026-07-23 09:54:25 +02:00
dmo 9b7d302064 Fix map loading and tab navigation v0.4.1 2026-07-23 09:50:45 +02:00
12 changed files with 822 additions and 108 deletions
+11 -2
View File
@@ -7,15 +7,24 @@ APP_PORT=8080
# Optional settings
APP_NAME=Photo Date Editor
# Optional visible page heading. Falls back to APP_NAME when omitted.
APP_TITLE=Mork Photo Date Editor
# Optional text shown directly below the page heading.
APP_SUBTITLE=Family photo metadata editor
MAX_UPLOAD_MB=150
LOG_LEVEL=INFO
# Optional TIFF, HEIF, and DNG preview limits. Originals are never converted or replaced by previews.
PREVIEW_MAX_EDGE=2400
PREVIEW_MAX_PIXELS=300000000
# Optional map/geocoder overrides. Existing .env files may omit these.
MAP_TILE_URL=https://tile.openstreetmap.org/{z}/{x}/{y}.png
# Map tiles are fetched by the backend and served same-origin to the browser.
MAP_TILE_SOURCE_URL=https://tile.openstreetmap.org/{z}/{x}/{y}.png
MAP_ATTRIBUTION=© OpenStreetMap contributors
DEFAULT_MAP_LAT=64.5
DEFAULT_MAP_LON=11.0
DEFAULT_MAP_ZOOM=5
GEOCODER_URL=https://nominatim.openstreetmap.org/search
# Optional custom identification sent to the geocoder. The default uses APP_NAME, version and APP_URL.
# GEOCODER_USER_AGENT=MorkPhotoDateEditor/0.4 (+https://edit.mork.fyi)
# GEOCODER_USER_AGENT=MorkPhotoDateEditor/0.7.0 (+https://edit.mork.fyi)
+76 -1
View File
@@ -1,5 +1,80 @@
# Changelog
## 0.7.0
- Add DNG folder scanning, `DNG` format badges, and format-sort compatibility.
- Add browser-friendly DNG previews by preferring embedded `JpgFromRaw`, `PreviewImage`, and `ThumbnailImage` data.
- Add a half-size LibRaw rendering fallback for DNG files without a usable embedded preview.
- Add `rawpy` and the container OpenMP runtime required by its LibRaw decoder.
- Validate DNG uploads as TIFF-based files before processing.
- Read and write DNG EXIF, XMP, IPTC, date precision, description, keywords, GPS coordinates, and location label metadata.
- Preserve the original DNG container, sensor data, and embedded previews while overwriting the same local file.
- Update the interface, manifest, environment example, README, and format roadmap.
- Preserve all established JPG, PNG, TIFF, and HEIF processing behavior.
- Bump the application and service-worker cache version to 0.7.0.
## 0.6.1
- Add optional `APP_TITLE` and `APP_SUBTITLE` environment variables for the visible page heading and subtitle.
- Keep `APP_NAME` backward-compatible as the title fallback and application identity.
- Update the browser tab title from the configured page title.
- Bump the application and service-worker cache version to 0.6.1.
## 0.6.0
- Add HEIC, HEIF, and HIF folder scanning and in-place metadata processing.
- Normalize all three HEIF-family extensions to a `HEIF` format badge and include them in format sorting.
- Generate temporary browser-friendly JPEG previews for HEIF-family images while preserving and overwriting the original container on save.
- Add `pillow-heif` and the container HEIF runtime needed to decode previews.
- Validate HEIF-family files as ISO Base Media File Format containers with recognized HEVC image brands before processing, without admitting renamed AVIF files.
- Read and write HEIF EXIF/XMP dates, precision marker, description, keywords, GPS coordinates, and location label without applying IPTC-IIM fields.
- Return updated files using HEIC/HEIF media types while keeping the original filename and extension.
- Update the interface, manifest, documentation, and empty-folder guidance for the new formats.
- Preserve the established JPG, PNG, and TIFF processing paths.
- Bump the application and service-worker cache version to 0.6.0.
## 0.5.0
- Add in-place PNG metadata reading and writing.
- Add in-place TIFF/TIF metadata reading and writing.
- Generate temporary browser-friendly JPEG previews for TIFF files while preserving and overwriting the original TIFF on save.
- Validate JPEG, PNG, and TIFF file signatures before metadata processing.
- Add normalized JPG, PNG, and TIFF format badges to the left photo list.
- Show the current file format alongside size and modified time in the viewer.
- Add **Sort: Format**, grouping by normalized format and then filename.
- Keep TIFF list thumbnails lazy: a format tile is shown until that TIFF has been opened and previewed.
- Add configurable TIFF preview edge and pixel limits.
- Bump the application and service-worker cache version to 0.5.0.
## 0.4.3
- Fix favorite locations appearing empty after a browser refresh.
- Load the shared server-side favorite list during application startup instead of waiting for **Open photo folder**.
- Keep the existing refresh when opening a folder as a defensive re-sync for changes made by another family member.
- Preserve all favorites already stored in the `photo-date-editor-data` Docker volume.
- Bump the application and service-worker cache version to 0.4.3.
## 0.4.2
- Added shared favorite locations to the Location tab.
- Favorite names and coordinates are stored server-side in the persistent `photo-date-editor-data` Docker volume.
- Added **Use**, **Add current location**, and **Delete selected** controls for favorite locations.
- Favorite locations are available to every browser and family member using the same Docker stack.
- Duplicate favorite names are rejected case-insensitively.
- Documented MP4 as a later media phase after the planned photo formats.
## 0.4.1
- Fix `Shift+Tab` so it activates the previous metadata tab immediately and focuses that tab's first field.
- Keep Left/Right arrow keys dedicated to previous/next photo navigation.
- Remove the tab-header Arrow/Home/End behavior that conflicted with photo navigation and was awkward on compact Mac keyboards.
- Proxy OpenStreetMap tiles through the backend and serve them same-origin through Caddy, avoiding Brave third-party tile blocking.
- Add an in-memory map-tile cache and clear map loading/error status text.
- Add an explicit message when the Leaflet library fails to load instead of silently showing a dead map.
- Add `ca-certificates` explicitly to the container image for outbound HTTPS map and geocoder requests.
- Keep all map environment variables optional; existing `.env` files remain valid.
- Bump the application and service-worker cache version to 0.4.1.
## 0.4.0
- Add a dedicated Location tab with an interactive Leaflet map.
@@ -13,7 +88,7 @@
- Rate-limit uncached public geocoder calls to one request per second and cache results in memory.
- Add `Shift+Tab` to cycle backward through right-side metadata tabs while keeping normal `Tab` field navigation.
- Add arrow-key navigation when a tab header has focus.
- Vendor Leaflet into the container at build time and avoid service-worker caching of third-party map tiles.
- Avoid service-worker caching of third-party map tiles and scripts.
- Bump the application and service-worker cache version to 0.4.0.
## 0.3.0
+1 -1
View File
@@ -4,7 +4,7 @@ ENV PYTHONDONTWRITEBYTECODE=1 \
PYTHONUNBUFFERED=1
RUN apt-get update \
&& apt-get install -y --no-install-recommends libimage-exiftool-perl \
&& apt-get install -y --no-install-recommends ca-certificates libgomp1 libheif1 libimage-exiftool-perl \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /app
+59 -31
View File
@@ -1,26 +1,34 @@
# Photo Date Editor
Version 0.4.0
Version 0.7.0
A self-hosted browser UI for manually dating scanned photographs. The browser receives temporary read/write access to a local computer or Chromebook folder, sends one JPEG at a time to the Docker backend for ExifTool processing, and overwrites the same local file after processing.
A self-hosted browser UI for manually dating scanned photographs. The browser receives temporary read/write access to a local computer or Chromebook folder, sends one image at a time to the Docker backend for ExifTool processing, and overwrites the same local file after processing.
## Current scope
- JPG and JPEG
- JPG/JPEG, PNG, TIFF/TIF, HEIC/HEIF/HIF, and DNG
- Local directory picker in supported Chromium browsers
- Three-column photo workflow
- Exact date, month/year, year-only, approximate year
- Optional time; unknown time defaults to noon
- Description and keywords
- GPS geotagging with address search, map click, draggable pin, manual coordinates, and location removal
- Shared favorite locations persisted in a Docker volume for all family members and browsers
- In-place overwrite: no browser download and no `_original` file
- Saved/skipped/pending/failed state stored in browser local storage
- Filename search, status filtering, and filename/status sorting
- Filename search, status filtering, and filename/status/format sorting
- Normalized JPG, PNG, TIFF, HEIF, and DNG format badges in the photo list
- Segmented progress bar: saved is green, skipped is yellow, failed is red, and pending remains grey
- Existing metadata is read from the JPEG when a photo is selected
- Existing metadata is read from supported files when selected
- Files previously edited by this app are recognized from their XMP marker, even in a different browser
- Keyboard navigation, including `Shift+Tab` between right-side tabs
## Preview behavior
JPG and PNG are displayed directly by the browser. Chromium browsers do not reliably display TIFF, HEIF-family images, or DNG, so those formats are temporarily uploaded to `/api/preview` and returned as a browser-friendly JPEG. TIFF uses Pillow, HEIF uses `pillow-heif`, and DNG first tries its embedded `JpgFromRaw`, `PreviewImage`, or `ThumbnailImage`; if none is usable, LibRaw renders a half-size preview through `rawpy`. The preview exists only in memory and is never written over the source file.
When a TIFF, HEIF-family image, or DNG is saved, ExifTool updates the original format and the browser overwrites the same local file. The original is not converted to JPEG and no additional copy is intentionally left behind.
## Requirements
- Docker with Docker Compose
@@ -28,7 +36,7 @@ A self-hosted browser UI for manually dating scanned photographs. The browser re
- HTTPS when accessed from another device
- A backup of irreplaceable scans before testing any metadata editor
The browser File System Access API is required. Firefox and Safari are not supported by this first version.
The browser File System Access API is required. Firefox and Safari are not supported by this version.
## Install
@@ -44,11 +52,17 @@ Example `.env`:
APP_URL=https://photos.example.internal
APP_PORT=8080
APP_NAME=Photo Date Editor
APP_TITLE=Mork Photo Date Editor
APP_SUBTITLE=Family photo metadata editor
MAX_UPLOAD_MB=150
LOG_LEVEL=INFO
# Optional TIFF/HEIF/DNG preview limits
PREVIEW_MAX_EDGE=2400
PREVIEW_MAX_PIXELS=300000000
# Optional map defaults and service overrides
MAP_TILE_URL=https://tile.openstreetmap.org/{z}/{x}/{y}.png
MAP_TILE_SOURCE_URL=https://tile.openstreetmap.org/{z}/{x}/{y}.png
MAP_ATTRIBUTION=© OpenStreetMap contributors
DEFAULT_MAP_LAT=64.5
DEFAULT_MAP_LON=11.0
@@ -58,7 +72,7 @@ GEOCODER_URL=https://nominatim.openstreetmap.org/search
Open the configured HTTPS URL through Caddy, click **Open photo folder**, and grant read/write access.
## Upgrade from 0.1, 0.2, or 0.3
## Upgrade from 0.1 through 0.6.1
Replace the project files with this version and rebuild:
@@ -66,7 +80,7 @@ Replace the project files with this version and rebuild:
docker compose up -d --build
```
The existing `.env` can be kept. Browser progress from 0.1 remains compatible. A normal refresh should load the new service-worker cache; use a hard refresh if an old UI remains visible.
The existing `.env` can be kept. `APP_TITLE` and `APP_SUBTITLE` are optional. When `APP_TITLE` is omitted, the visible page title continues to use `APP_NAME`; the subtitle uses the built-in format description when omitted. Browser progress from earlier releases remains compatible. A normal refresh should load the new service-worker cache; use a hard refresh if an old UI remains visible.
## Caddy example
@@ -88,15 +102,25 @@ The browser directory picker requires a secure context. Use a certificate truste
## What happens when Save is clicked
1. The browser reads the selected local JPEG.
1. The browser reads the selected local JPG, PNG, TIFF, HEIC, HEIF, HIF, or DNG.
2. It sends the file and entered fields to `/api/process`.
3. ExifTool modifies a temporary file inside the container using `-overwrite_original`.
4. The backend returns the modified JPEG.
4. The backend returns the modified file using its original media type.
5. The browser writes the returned bytes over the selected original file with `createWritable()`.
6. The backend temporary directory is deleted automatically.
No second photo is intentionally left on the client computer or Docker host.
## Metadata behavior by format
- **JPG/JPEG:** EXIF, XMP, and IPTC fields are written.
- **TIFF/TIF:** EXIF, XMP, and IPTC fields are written.
- **PNG:** EXIF and XMP fields are written. PNG metadata support varies more between third-party viewers than JPEG/TIFF support, so test the applications that will consume the files.
- **HEIC/HEIF/HIF:** EXIF and XMP fields are written. IPTC-IIM is not used for these ISO Base Media File Format containers. Date precision, description, keywords, GPS coordinates, and the location label remain represented through EXIF/XMP fields.
- **DNG:** EXIF, XMP, and IPTC fields are written into the original TIFF-based DNG container. Raw sensor data and embedded previews are not regenerated or replaced.
The app writes its precision marker to XMP for all supported formats. GPS coordinates are written to EXIF and XMP. The optional location label is written to XMP IPTC Core Location.
## Date behavior
EXIF date fields require a complete timestamp:
@@ -117,21 +141,21 @@ The chosen precision is also written into XMP Photoshop Instructions.
- `Left` / `Right`: Previous / next photo when not typing
- `S`: Mark the photo as skipped and open the next photo when not typing
- `C`: Copy previous values when not typing
- `Shift+Tab`: Switch to the previous right-side metadata tab; normal `Tab` still advances through fields
- `Shift+Tab`: Open the previous right-side metadata tab and place focus in its first field; normal `Tab` still advances through fields
## Location behavior
The **Location** tab supports four ways to set GPS metadata:
Favorite locations are loaded automatically when the page opens and are shared by everyone using the same Docker stack. Choose a saved place and click **Use**, or place a pin/set coordinates and click **Add current location** in the favorite-locations card. The favorite list is stored in the named Docker volume `photo-date-editor-data`, so it survives image rebuilds and container recreation. Deleting a favorite only removes it from the reusable list; it does not alter photos that were already geotagged.
1. Search for an address or place and choose a result.
2. Click directly on the map.
3. Drag the existing marker.
4. Enter decimal latitude and longitude manually.
The **Location** tab supports five ways to set GPS metadata:
On save, coordinates are written to EXIF and XMP GPS fields. The optional location label is written to XMP IPTC Core Location. Use **Clear location** and save to remove GPS coordinates and the app-managed location label.
1. Choose a shared favorite location.
2. Search for an address or place and choose a result.
3. Click directly on the map.
4. Drag the existing marker.
5. Enter decimal latitude and longitude manually.
Leaflet is downloaded into the container during the Docker build. The default map tiles and address search are external OpenStreetMap services. Search is user-triggered rather than autocomplete, proxied through the backend, rate-limited to one uncached request per second, and cached in memory. Both the tile and geocoder URLs are configurable in `.env` for later self-hosting or another provider.
The default map tiles and address search are external OpenStreetMap services. Both are requested by the Docker backend rather than directly by the browser. Tiles are cached in container memory. Search is user-triggered, rate-limited, and cached in memory. The tile source and geocoder URLs remain configurable in `.env`.
## Important limitations
@@ -139,22 +163,24 @@ Leaflet is downloaded into the container during the Docker build. The default ma
- Browser permission may need to be granted again after closing/reopening the browser.
- Saved and skipped progress is stored per browser and folder name. The app also reads its own XMP marker from edited files so saved metadata can be recognized on another browser.
- Overwriting a file through the browser generally changes its filesystem modified time to the time of the save. EXIF/XMP photo dates are independent of that filesystem timestamp.
- Preview rotation is visual only in this MVP; it does not rotate image pixels or write orientation metadata.
- The default map and address search require internet access. Opening the map sends tile requests for the viewed area; address searches are sent to the configured geocoder.
- Test with copies first, then use your own normal backup routine for the originals.
- Preview rotation is visual only; it does not rotate image pixels or write orientation metadata.
- Multi-page TIFF files display the first page/frame in the editor. Metadata is written to the TIFF container, not to separate pages.
- HEIF image sequences display their primary/first image in the editor. Metadata is written to the HEIF container.
- DNG uses the largest common embedded JPEG preview available before falling back to a half-size LibRaw render. A small embedded thumbnail may look softer but does not alter the DNG.
- Very large TIFF, HEIF, or DNG files may require raising `MAX_UPLOAD_MB` or `PREVIEW_MAX_PIXELS`.
- DNG rendering depends on the camera and compression variant being supported by the bundled LibRaw version. Metadata editing can still be supported by ExifTool even when a particular DNG cannot be rendered.
- HEIF metadata compatibility varies between operating-system galleries and photo-management applications. Verify the fields in the software that will consume your library.
- The Docker host needs outbound HTTPS access for the default map tiles and address search.
- Test with copies first, then use your normal backup routine for the originals.
## Planned format expansion
Format support needs two separate capabilities: safe metadata writing and a preview the browser can display. ExifTool gives the backend a strong metadata foundation, while formats that browsers do not reliably preview will use a temporary server-generated preview without converting or replacing the original file.
Format support needs both safe metadata writing and a browser-friendly preview. Formats that browsers do not reliably display will use a temporary server-generated preview without converting or replacing the original file.
### Proposed order
1. **PNG** — direct browser preview and in-place EXIF/XMP/IPTC metadata writing.
2. **TIFF/TIF** — in-place metadata writing, with a server-generated preview where the browser cannot display the file directly.
3. **HEIC/HEIF/HIF** — in-place EXIF/XMP writing and a server-generated preview. This phase should use a recent ExifTool release and test normal, HDR, and motion-photo samples.
4. **DNG** — in-place metadata writing and preview extraction/rendering.
5. **Canon RAW**`CR2` and `CR3`, using per-format tag rules and embedded/server-generated previews.
6. **Nikon RAW**`NEF` and `NRW`, using per-format tag rules and embedded/server-generated previews.
1. **Canon RAW**`CR2` and `CR3`, using per-format tag rules and embedded/server-generated previews.
2. **Nikon RAW**`NEF` and `NRW`, using per-format tag rules and embedded/server-generated previews.
`RAW` is not treated as one universal format. Each camera family will be enabled and tested explicitly.
@@ -164,4 +190,6 @@ Format support needs two separate capabilities: safe metadata writing and a prev
- **BMP/DIB** — ExifTool can read it but cannot write the metadata this app needs.
- **SVG, PDF, EPS, WebP, AVIF, EXR, XCF** — intentionally outside the scope of this photo workflow.
RAW support will remain **in-place** by default to match the JPEG workflow. Before enabling it, the app needs format-specific round-trip tests and clear warnings because proprietary camera originals deserve a stricter safety bar than scans.
## Future video support
MP4 remains feasible after the planned photo formats, but it will be a separate media phase rather than just another image extension. The existing fields can be mapped to compatible QuickTime and XMP metadata, but large videos need streamed/chunked transfer, progress reporting, larger limits, cancellation, and compatibility testing before in-place support is enabled.
+356 -20
View File
@@ -1,32 +1,73 @@
from __future__ import annotations
import asyncio
import io
import json
import logging
import os
import re
import subprocess
import tempfile
import threading
import time
import uuid
import urllib.error
import urllib.parse
import urllib.request
from collections import OrderedDict
from datetime import datetime
from pathlib import Path
from typing import Annotated, Any
from fastapi import FastAPI, File, Form, HTTPException, UploadFile
from pydantic import BaseModel, Field
from fastapi.responses import FileResponse, Response
from fastapi.staticfiles import StaticFiles
from PIL import Image, ImageOps, UnidentifiedImageError
from pillow_heif import register_heif_opener
import rawpy
register_heif_opener()
APP_NAME = os.getenv("APP_NAME", "Photo Date Editor")
APP_TITLE = os.getenv("APP_TITLE") or APP_NAME
APP_SUBTITLE = (
os.getenv("APP_SUBTITLE")
or "Local folder · in-place JPG, PNG, TIFF and HEIF metadata"
)
APP_URL = os.getenv("APP_URL", "http://localhost:8080")
APP_VERSION = "0.4.0"
APP_VERSION = "0.7.0"
MAX_UPLOAD_MB = int(os.getenv("MAX_UPLOAD_MB", "150"))
MAX_UPLOAD_BYTES = MAX_UPLOAD_MB * 1024 * 1024
PREVIEW_MAX_EDGE = int(os.getenv("PREVIEW_MAX_EDGE", "2400"))
PREVIEW_MAX_PIXELS = int(os.getenv("PREVIEW_MAX_PIXELS", "300000000"))
Image.MAX_IMAGE_PIXELS = PREVIEW_MAX_PIXELS
SUPPORTED_EXTENSIONS = {
".jpg", ".jpeg", ".png", ".tif", ".tiff",
".heic", ".heif", ".hif", ".dng",
}
TIFF_EXTENSIONS = {".tif", ".tiff"}
HEIF_EXTENSIONS = {".heic", ".heif", ".hif"}
DNG_EXTENSIONS = {".dng"}
SERVER_PREVIEW_EXTENSIONS = TIFF_EXTENSIONS | HEIF_EXTENSIONS | DNG_EXTENSIONS
MEDIA_TYPES = {
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".png": "image/png",
".tif": "image/tiff",
".tiff": "image/tiff",
".heic": "image/heic",
".heif": "image/heif",
".hif": "image/heif",
".dng": "image/x-adobe-dng",
}
LOG_LEVEL = os.getenv("LOG_LEVEL", "INFO").upper()
MAP_TILE_URL = os.getenv("MAP_TILE_URL", "https://tile.openstreetmap.org/{z}/{x}/{y}.png")
MAP_TILE_SOURCE_URL = os.getenv(
"MAP_TILE_SOURCE_URL",
os.getenv("MAP_TILE_URL", "https://tile.openstreetmap.org/{z}/{x}/{y}.png"),
)
MAP_ATTRIBUTION = os.getenv(
"MAP_ATTRIBUTION",
'&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap contributors</a>',
@@ -43,6 +84,9 @@ GEOCODER_USER_AGENT = os.getenv(
_geocode_lock = asyncio.Lock()
_geocode_cache: dict[str, list[dict[str, Any]]] = {}
_last_geocode_request = 0.0
_tile_cache: OrderedDict[str, tuple[bytes, str]] = OrderedDict()
_tile_cache_limit = 512
_tile_lock = asyncio.Lock()
logging.basicConfig(
level=getattr(logging, LOG_LEVEL, logging.INFO),
@@ -52,8 +96,18 @@ logger = logging.getLogger("photo-date-editor")
BASE_DIR = Path(__file__).resolve().parent
STATIC_DIR = BASE_DIR / "static"
DATA_DIR = Path(os.getenv("DATA_DIR", "/data"))
FAVORITES_FILE = DATA_DIR / "favorite-locations.json"
_favorites_lock = threading.Lock()
app = FastAPI(title=APP_NAME, docs_url=None, redoc_url=None)
class FavoriteLocationInput(BaseModel):
name: str = Field(min_length=1, max_length=120)
latitude: float = Field(ge=-90, le=90)
longitude: float = Field(ge=-180, le=180)
app = FastAPI(title=APP_TITLE, docs_url=None, redoc_url=None)
@app.get("/api/health")
@@ -65,10 +119,12 @@ def health() -> dict[str, str]:
def config() -> dict[str, str | int | float]:
return {
"appName": APP_NAME,
"appTitle": APP_TITLE,
"appSubtitle": APP_SUBTITLE,
"appUrl": APP_URL,
"version": APP_VERSION,
"maxUploadMb": MAX_UPLOAD_MB,
"mapTileUrl": MAP_TILE_URL,
"mapTileUrl": "/api/map/tiles/{z}/{x}/{y}.png",
"mapAttribution": MAP_ATTRIBUTION,
"defaultMapLat": DEFAULT_MAP_LAT,
"defaultMapLon": DEFAULT_MAP_LON,
@@ -76,6 +132,134 @@ def config() -> dict[str, str | int | float]:
}
def _load_favorites_unlocked() -> list[dict[str, Any]]:
if not FAVORITES_FILE.exists():
return []
try:
payload = json.loads(FAVORITES_FILE.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError) as exc:
logger.warning("Could not read favorite locations: %s", exc)
return []
raw = payload.get("favorites", []) if isinstance(payload, dict) else []
favorites: list[dict[str, Any]] = []
for item in raw if isinstance(raw, list) else []:
if not isinstance(item, dict):
continue
try:
latitude = float(item["latitude"])
longitude = float(item["longitude"])
name = str(item["name"]).strip()
favorite_id = str(item["id"]).strip()
except (KeyError, TypeError, ValueError):
continue
if not name or not favorite_id or not -90 <= latitude <= 90 or not -180 <= longitude <= 180:
continue
favorites.append({
"id": favorite_id,
"name": name,
"latitude": latitude,
"longitude": longitude,
})
return sorted(favorites, key=lambda item: item["name"].casefold())
def _write_favorites_unlocked(favorites: list[dict[str, Any]]) -> None:
DATA_DIR.mkdir(parents=True, exist_ok=True)
payload = {"favorites": sorted(favorites, key=lambda item: item["name"].casefold())}
temporary = FAVORITES_FILE.with_suffix(".tmp")
temporary.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
temporary.replace(FAVORITES_FILE)
@app.get("/api/favorites")
def list_favorites() -> dict[str, list[dict[str, Any]]]:
with _favorites_lock:
return {"favorites": _load_favorites_unlocked()}
@app.post("/api/favorites", status_code=201)
def create_favorite(value: FavoriteLocationInput) -> dict[str, dict[str, Any]]:
name = " ".join(value.name.split())
if not name:
raise HTTPException(status_code=422, detail="Favorite name cannot be empty.")
with _favorites_lock:
favorites = _load_favorites_unlocked()
if any(item["name"].casefold() == name.casefold() for item in favorites):
raise HTTPException(status_code=409, detail="A favorite with that name already exists.")
favorite = {
"id": uuid.uuid4().hex,
"name": name,
"latitude": round(value.latitude, 6),
"longitude": round(value.longitude, 6),
}
favorites.append(favorite)
_write_favorites_unlocked(favorites)
return {"favorite": favorite}
@app.delete("/api/favorites/{favorite_id}", status_code=204)
def delete_favorite(favorite_id: str) -> Response:
with _favorites_lock:
favorites = _load_favorites_unlocked()
remaining = [item for item in favorites if item["id"] != favorite_id]
if len(remaining) == len(favorites):
raise HTTPException(status_code=404, detail="Favorite location not found.")
_write_favorites_unlocked(remaining)
return Response(status_code=204)
def _fetch_map_tile(z: int, x: int, y: int) -> tuple[bytes, str]:
tile_url = (
MAP_TILE_SOURCE_URL
.replace("{z}", str(z))
.replace("{x}", str(x))
.replace("{y}", str(y))
)
request = urllib.request.Request(
tile_url,
headers={
"User-Agent": GEOCODER_USER_AGENT,
"Accept": "image/avif,image/webp,image/png,image/*,*/*;q=0.8",
},
)
with urllib.request.urlopen(request, timeout=20) as response:
content_type = response.headers.get_content_type() or "image/png"
return response.read(), content_type
@app.get("/api/map/tiles/{z}/{x}/{y}.png", include_in_schema=False)
async def map_tile(z: int, x: int, y: int) -> Response:
if not 0 <= z <= 19:
raise HTTPException(status_code=404, detail="Unsupported map zoom level.")
limit = 1 << z
if not 0 <= x < limit or not 0 <= y < limit:
raise HTTPException(status_code=404, detail="Invalid map tile coordinates.")
cache_key = f"{z}/{x}/{y}"
cached = _tile_cache.get(cache_key)
if cached is not None:
_tile_cache.move_to_end(cache_key)
payload, content_type = cached
return Response(payload, media_type=content_type, headers={"Cache-Control": "public, max-age=86400"})
async with _tile_lock:
cached = _tile_cache.get(cache_key)
if cached is None:
try:
cached = await asyncio.to_thread(_fetch_map_tile, z, x, y)
except (urllib.error.URLError, TimeoutError) as exc:
logger.warning("Map tile request failed for %s: %s", cache_key, exc)
raise HTTPException(status_code=502, detail="The map tile service could not be reached.") from exc
_tile_cache[cache_key] = cached
if len(_tile_cache) > _tile_cache_limit:
_tile_cache.popitem(last=False)
else:
_tile_cache.move_to_end(cache_key)
payload, content_type = cached
return Response(payload, media_type=content_type, headers={"Cache-Control": "public, max-age=86400"})
def _fetch_geocode_results(query: str) -> list[dict[str, Any]]:
parameters = urllib.parse.urlencode(
@@ -219,7 +403,53 @@ def _normalise_datetime(
return exif_datetime, xmp_date, precision_labels[precision]
async def _save_upload(upload: UploadFile, destination: Path) -> None:
def _format_name(suffix: str) -> str:
if suffix in {".jpg", ".jpeg"}:
return "JPEG"
if suffix == ".png":
return "PNG"
if suffix in TIFF_EXTENSIONS:
return "TIFF"
if suffix in HEIF_EXTENSIONS:
return "HEIF"
if suffix in DNG_EXTENSIONS:
return "DNG"
return suffix.lstrip(".").upper() or "image"
def _validate_image_signature(path: Path, suffix: str) -> None:
with path.open("rb") as source:
signature = source.read(64)
valid = False
if suffix in {".jpg", ".jpeg"}:
valid = signature.startswith(b"\xff\xd8\xff")
elif suffix == ".png":
valid = signature.startswith(b"\x89PNG\r\n\x1a\n")
elif suffix in TIFF_EXTENSIONS:
valid = signature.startswith((b"II*\x00", b"MM\x00*", b"II+\x00", b"MM\x00+"))
elif suffix in HEIF_EXTENSIONS:
hevc_brands = {
b"heic", b"heix", b"hevc", b"hevx",
b"heim", b"heis", b"hevm", b"hevs",
}
valid = len(signature) >= 16 and signature[4:8] == b"ftyp" and any(
signature[offset:offset + 4] in hevc_brands
for offset in range(8, len(signature) - 3, 4)
)
elif suffix in DNG_EXTENSIONS:
# DNG is TIFF-based. ExifTool performs the deeper DNG structure
# validation when reading, extracting a preview, or writing metadata.
valid = signature.startswith((b"II*\x00", b"MM\x00*"))
if not valid:
raise HTTPException(
status_code=415,
detail=f"The uploaded file is not a valid {_format_name(suffix)} image.",
)
async def _save_upload(upload: UploadFile, destination: Path, suffix: str) -> None:
total = 0
with destination.open("wb") as output:
while chunk := await upload.read(1024 * 1024):
@@ -231,10 +461,7 @@ async def _save_upload(upload: UploadFile, destination: Path) -> None:
)
output.write(chunk)
with destination.open("rb") as source:
signature = source.read(3)
if signature[:2] != b"\xff\xd8":
raise HTTPException(status_code=415, detail="The uploaded file is not a valid JPEG image.")
_validate_image_signature(destination, suffix)
def _first_value(metadata: dict[str, Any], *keys: str) -> Any:
@@ -358,16 +585,119 @@ def _metadata_values(metadata: dict[str, Any]) -> tuple[bool, bool, dict[str, An
return has_metadata, edited_by_app, values
def _embedded_dng_preview(path: Path) -> Image.Image | None:
"""Return the first usable DNG preview, preferring the largest common tags."""
for tag in ("JpgFromRaw", "PreviewImage", "ThumbnailImage"):
try:
completed = subprocess.run(
["exiftool", "-b", f"-{tag}", "--", str(path)],
capture_output=True,
timeout=45,
check=False,
)
except subprocess.TimeoutExpired:
logger.warning("Timed out extracting DNG %s data.", tag)
continue
if completed.returncode != 0 or not completed.stdout:
continue
try:
with Image.open(io.BytesIO(completed.stdout)) as source:
source.load()
return source.copy()
except (UnidentifiedImageError, OSError, ValueError):
logger.debug("DNG %s data was not a usable image preview.", tag)
return None
def _render_dng(path: Path) -> Image.Image:
"""Render a half-size RGB fallback when a DNG has no embedded JPEG preview."""
try:
with rawpy.imread(str(path)) as raw:
width = int(raw.sizes.width)
height = int(raw.sizes.height)
if width <= 0 or height <= 0 or width * height > PREVIEW_MAX_PIXELS:
raise ValueError("DNG dimensions exceed the configured preview pixel limit.")
rgb = raw.postprocess(
use_camera_wb=True,
use_auto_wb=False,
no_auto_bright=False,
half_size=True,
output_bps=8,
)
except rawpy.LibRawError as exc:
raise ValueError("LibRaw could not decode this DNG.") from exc
return Image.fromarray(rgb)
@app.post("/api/preview")
async def create_preview(file: Annotated[UploadFile, File(...)]) -> Response:
"""Generate a temporary browser-friendly preview for TIFF, HEIF, and DNG images."""
filename = file.filename or "photo.tiff"
suffix = Path(filename).suffix.lower()
if suffix not in SERVER_PREVIEW_EXTENSIONS:
raise HTTPException(
status_code=415,
detail="Server-generated previews are only required for TIFF, HEIF, and DNG files.",
)
with tempfile.TemporaryDirectory(prefix="photo-date-editor-preview-") as temp_dir:
temp_path = Path(temp_dir) / f"source{suffix}"
await _save_upload(file, temp_path, suffix)
try:
if suffix in DNG_EXTENSIONS:
preview = _embedded_dng_preview(temp_path)
if preview is None:
preview = _render_dng(temp_path)
preview = ImageOps.exif_transpose(preview)
else:
with Image.open(temp_path) as source:
source.seek(0)
preview = ImageOps.exif_transpose(source)
preview.load()
try:
preview.thumbnail((PREVIEW_MAX_EDGE, PREVIEW_MAX_EDGE), Image.Resampling.LANCZOS)
if preview.mode in {"RGBA", "LA"} or (preview.mode == "P" and "transparency" in preview.info):
rgba = preview.convert("RGBA")
background = Image.new("RGBA", rgba.size, (255, 255, 255, 255))
background.alpha_composite(rgba)
preview = background.convert("RGB")
elif preview.mode != "RGB":
preview = preview.convert("RGB")
output = io.BytesIO()
preview.save(output, format="JPEG", quality=88, optimize=True)
finally:
preview.close()
except (Image.DecompressionBombError, UnidentifiedImageError, OSError, ValueError) as exc:
format_name = _format_name(suffix)
logger.warning("%s preview generation failed for %s: %s", format_name, filename, exc)
raise HTTPException(
status_code=422,
detail=f"The {format_name} image could not be rendered for preview.",
) from exc
return Response(
content=output.getvalue(),
media_type="image/jpeg",
headers={"Cache-Control": "no-store"},
)
@app.post("/api/metadata")
async def read_metadata(file: Annotated[UploadFile, File(...)]) -> dict[str, bool | dict[str, Any]]:
filename = file.filename or "photo.jpg"
suffix = Path(filename).suffix.lower()
if suffix not in {".jpg", ".jpeg"}:
raise HTTPException(status_code=415, detail="This version supports JPG and JPEG files only.")
if suffix not in SUPPORTED_EXTENSIONS:
raise HTTPException(
status_code=415,
detail="Supported formats are JPG, JPEG, PNG, TIF, TIFF, HEIC, HEIF, HIF, and DNG.",
)
with tempfile.TemporaryDirectory(prefix="photo-date-editor-read-") as temp_dir:
temp_path = Path(temp_dir) / f"source{suffix}"
await _save_upload(file, temp_path)
await _save_upload(file, temp_path, suffix)
completed = subprocess.run(
[
"exiftool",
@@ -428,8 +758,11 @@ async def process_photo(
) -> Response:
filename = file.filename or "photo.jpg"
suffix = Path(filename).suffix.lower()
if suffix not in {".jpg", ".jpeg"}:
raise HTTPException(status_code=415, detail="This version supports JPG and JPEG files only.")
if suffix not in SUPPORTED_EXTENSIONS:
raise HTTPException(
status_code=415,
detail="Supported formats are JPG, JPEG, PNG, TIF, TIFF, HEIC, HEIF, HIF, and DNG.",
)
exif_datetime, xmp_date, precision_label = _normalise_datetime(
precision=precision,
@@ -458,8 +791,9 @@ async def process_photo(
with tempfile.TemporaryDirectory(prefix="photo-date-editor-") as temp_dir:
temp_path = Path(temp_dir) / f"working{suffix}"
await _save_upload(file, temp_path)
await _save_upload(file, temp_path, suffix)
supports_iptc = suffix in {".jpg", ".jpeg", ".tif", ".tiff", ".dng"}
command = [
"exiftool",
"-overwrite_original",
@@ -475,10 +809,10 @@ async def process_photo(
f"-XMP-photoshop:Instructions=Photo Date Editor precision: {precision_label}; time: {time_label}",
"-EXIF:ImageDescription=",
"-XMP-dc:Description=",
"-IPTC:Caption-Abstract=",
"-XMP-dc:Subject=",
"-IPTC:Keywords=",
]
if supports_iptc:
command.extend(["-IPTC:Caption-Abstract=", "-IPTC:Keywords="])
clean_description = description.strip()
if clean_description:
@@ -486,13 +820,15 @@ async def process_photo(
[
f"-EXIF:ImageDescription={clean_description}",
f"-XMP-dc:Description={clean_description}",
f"-IPTC:Caption-Abstract={clean_description}",
]
)
if supports_iptc:
command.append(f"-IPTC:Caption-Abstract={clean_description}")
for keyword in keywords:
command.append(f"-XMP-dc:Subject+={keyword}")
command.append(f"-IPTC:Keywords+={keyword}")
if supports_iptc:
command.append(f"-IPTC:Keywords+={keyword}")
if gps_action == "clear":
command.extend(
@@ -542,7 +878,7 @@ async def process_photo(
return Response(
content=updated_bytes,
media_type="image/jpeg",
media_type=MEDIA_TYPES[suffix],
headers={
"Content-Disposition": f'inline; filename="{Path(filename).name}"',
"Cache-Control": "no-store",
+251 -38
View File
@@ -12,6 +12,7 @@ const state = {
map: null,
mapMarker: null,
locationDirty: false,
favoriteLocations: [],
};
const $ = (selector) => document.querySelector(selector);
@@ -19,6 +20,7 @@ const $$ = (selector) => [...document.querySelectorAll(selector)];
const elements = {
appName: $('#app-name'),
appSubtitle: $('#app-subtitle'),
openButtons: [$('#open-folder'), $('#open-folder-top'), $('#open-folder-center')],
rescan: $('#rescan-folder'),
folderName: $('#folder-name'),
@@ -63,10 +65,15 @@ const elements = {
addressSearchButton: $('#address-search-button'),
addressResults: $('#address-results'),
locationMap: $('#location-map'),
mapStatus: $('#map-status'),
latitude: $('#latitude-input'),
longitude: $('#longitude-input'),
locationName: $('#location-name-input'),
clearLocation: $('#clear-location'),
favoriteSelect: $('#favorite-location-select'),
useFavorite: $('#use-favorite-location'),
saveFavorite: $('#save-favorite-location'),
deleteFavorite: $('#delete-favorite-location'),
saveStatus: $('#save-status'),
shortcutsButton: $('#shortcuts-button'),
shortcutsDialog: $('#shortcuts-dialog'),
@@ -107,6 +114,20 @@ function formatBytes(bytes) {
return `${(bytes / 1024 ** 2).toFixed(1)} MB`;
}
function formatType(filename) {
const extension = filename.split('.').pop()?.toLowerCase() || '';
if (extension === 'jpg' || extension === 'jpeg') return 'JPG';
if (extension === 'png') return 'PNG';
if (extension === 'tif' || extension === 'tiff') return 'TIFF';
if (extension === 'heic' || extension === 'heif' || extension === 'hif') return 'HEIF';
if (extension === 'dng') return 'DNG';
return extension.toUpperCase();
}
function requiresServerPreview(photo) {
return photo.format === 'TIFF' || photo.format === 'HEIF' || photo.format === 'DNG';
}
function storageKey() {
return state.directoryHandle ? `photo-date-editor:${state.directoryHandle.name}` : null;
}
@@ -133,6 +154,8 @@ function saveFolderState() {
}
async function openFolder() {
await loadFavoriteLocations();
if (!isSupported()) {
showToast('Use a current Chromium browser over HTTPS. Folder access is unavailable here.', true);
return;
@@ -156,13 +179,14 @@ async function scanFolder() {
const photos = [];
for await (const [name, handle] of state.directoryHandle.entries()) {
if (handle.kind !== 'file' || !/\.(jpe?g)$/i.test(name)) continue;
if (handle.kind !== 'file' || !/\.(jpe?g|png|tiff?|heic|heif|hif|dng)$/i.test(name)) continue;
const file = await handle.getFile();
const previous = stored.photos?.[name] || {};
const unchanged = !previous.lastModified || previous.lastModified === file.lastModified;
photos.push({
name,
handle,
format: formatType(name),
size: file.size,
lastModified: file.lastModified,
status: unchanged ? (previous.status || 'pending') : 'pending',
@@ -194,7 +218,7 @@ async function scanFolder() {
} else {
elements.viewerContent.classList.add('hidden');
elements.viewerEmpty.classList.remove('hidden');
showToast('No JPG or JPEG files were found in that folder.', true);
showToast('No JPG, PNG, TIFF, HEIC, HEIF, HIF, or DNG files were found in that folder.', true);
}
}
@@ -205,14 +229,34 @@ function clearObjectUrls() {
state.thumbUrls.clear();
}
async function getThumbUrl(photo) {
async function getPreviewUrl(photo, suppliedFile = null) {
if (state.thumbUrls.has(photo.name)) return state.thumbUrls.get(photo.name);
const file = await photo.handle.getFile();
const url = URL.createObjectURL(file);
const file = suppliedFile || await photo.handle.getFile();
let previewBlob = file;
if (requiresServerPreview(photo)) {
const payload = new FormData();
payload.append('file', file, photo.name);
const response = await fetch('/api/preview', { method: 'POST', body: payload });
if (!response.ok) {
let message = `Preview failed (${response.status}).`;
try { message = (await response.json()).detail || message; } catch {}
throw new Error(message);
}
previewBlob = await response.blob();
}
const url = URL.createObjectURL(previewBlob);
state.thumbUrls.set(photo.name, url);
return url;
}
async function getThumbUrl(photo) {
if (state.thumbUrls.has(photo.name)) return state.thumbUrls.get(photo.name);
if (requiresServerPreview(photo)) return null;
return getPreviewUrl(photo);
}
function statusSymbol(status) {
if (status === 'saved') return '✓';
if (status === 'skipped') return '→';
@@ -235,6 +279,8 @@ function visiblePhotoEntries() {
const statusDifference = statusSortOrder[a.photo.status] - statusSortOrder[b.photo.status];
return statusDifference || naturalCompare(a.photo.name, b.photo.name);
});
} else if (elements.sortSelect.value === 'format') {
entries.sort((a, b) => naturalCompare(a.photo.format, b.photo.format) || naturalCompare(a.photo.name, b.photo.name));
} else {
entries.sort((a, b) => naturalCompare(a.photo.name, b.photo.name));
}
@@ -256,12 +302,16 @@ function renderFileList() {
row.className = `file-row${index === state.currentIndex ? ' active' : ''}`;
row.dataset.index = String(index);
row.innerHTML = `
<div class="file-thumb" aria-hidden="true"></div>
<div class="file-meta"><strong>${escapeHtml(photo.name)}</strong><span>${index + 1} / ${state.photos.length} · ${formatBytes(photo.size)}</span></div>
<div class="file-thumb format-placeholder" aria-hidden="true">${escapeHtml(photo.format)}</div>
<div class="file-meta">
<strong>${escapeHtml(photo.name)}</strong>
<span class="file-details"><span>${index + 1} / ${state.photos.length}</span><span>${formatBytes(photo.size)}</span><span class="format-badge">${escapeHtml(photo.format)}</span></span>
</div>
<span class="file-state ${photo.status}" title="${photo.status}">${statusSymbol(photo.status)}</span>`;
row.addEventListener('click', () => selectPhoto(index));
elements.fileList.appendChild(row);
getThumbUrl(photo).then((url) => {
if (!url || !row.isConnected) return;
const placeholder = row.querySelector('.file-thumb');
const image = document.createElement('img');
image.className = 'file-thumb';
@@ -338,11 +388,9 @@ async function selectPhoto(index, force = false) {
const selectionToken = ++state.selectionToken;
const photo = state.photos[index];
const file = await photo.handle.getFile();
if (state.objectUrl) URL.revokeObjectURL(state.objectUrl);
state.objectUrl = URL.createObjectURL(file);
elements.preview.src = state.objectUrl;
elements.preview.removeAttribute('src');
elements.filename.textContent = photo.name;
elements.filesize.textContent = `${formatBytes(file.size)} · modified ${new Date(file.lastModified).toLocaleString()}`;
elements.filesize.textContent = `${photo.format} · ${formatBytes(file.size)} · modified ${new Date(file.lastModified).toLocaleString()}`;
elements.position.textContent = `${index + 1} / ${state.photos.length}`;
resetView();
restoreValues(photo.values);
@@ -352,8 +400,22 @@ async function selectPhoto(index, force = false) {
const active = elements.fileList.querySelector('.file-row.active');
active?.scrollIntoView({ block: 'nearest' });
try {
if (requiresServerPreview(photo)) {
setSaveStatus('loading', `Rendering ${photo.format} preview…`, photo.name);
}
const previewUrl = await getPreviewUrl(photo, file);
if (selectionToken !== state.selectionToken || state.currentIndex !== index) return;
elements.preview.src = previewUrl;
renderFileList();
} catch (error) {
if (selectionToken === state.selectionToken && state.currentIndex === index) {
setSaveStatus('failed', 'Could not render preview', error.message || photo.name);
}
}
if (!photo.metadataLoaded) {
if (!photo.values) setSaveStatus('loading', 'Reading EXIF metadata…', photo.name);
if (!photo.values) setSaveStatus('loading', 'Reading image metadata…', photo.name);
try {
await readPhotoMetadata(photo, file);
if (selectionToken !== state.selectionToken || state.currentIndex !== index) return;
@@ -609,7 +671,13 @@ function activeTabIndex() {
return $$('.tab').findIndex((tab) => tab.classList.contains('active'));
}
function activateTab(tabName, focusTab = false) {
function focusFirstControl(tabName) {
const panel = document.querySelector(`.tab-panel[data-panel="${tabName}"]`);
const first = panel?.querySelector('input:not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), [tabindex]:not([tabindex="-1"])');
first?.focus();
}
function activateTab(tabName, focusMode = 'none') {
const tabs = $$('.tab');
const target = tabs.find((tab) => tab.dataset.tab === tabName);
if (!target) return;
@@ -620,22 +688,28 @@ function activateTab(tabName, focusTab = false) {
item.tabIndex = active ? 0 : -1;
});
$$('.tab-panel').forEach((panel) => panel.classList.toggle('active', panel.dataset.panel === tabName));
if (focusTab) target.focus();
if (tabName === 'location') {
initialiseMap();
window.setTimeout(() => {
state.map?.invalidateSize();
syncMapFromFields(false);
if (focusMode === 'field') focusFirstControl(tabName);
else if (focusMode === 'tab') target.focus();
}, 0);
} else if (focusMode === 'field') {
window.setTimeout(() => focusFirstControl(tabName), 0);
} else if (focusMode === 'tab') {
target.focus();
}
}
function cycleTabs(delta) {
function cycleTabs(delta, focusMode = 'field') {
const tabs = $$('.tab');
if (!tabs.length) return;
const current = Math.max(0, activeTabIndex());
const next = (current + delta + tabs.length) % tabs.length;
activateTab(tabs[next].dataset.tab, true);
activateTab(tabs[next].dataset.tab, focusMode);
}
function markLocationDirty() {
@@ -643,21 +717,39 @@ function markLocationDirty() {
captureCurrentValues();
}
function setMapStatus(message, isError = false) {
if (!elements.mapStatus) return;
elements.mapStatus.textContent = message;
elements.mapStatus.classList.toggle('error', isError);
}
function initialiseMap() {
if (state.map || typeof window.L === 'undefined' || !elements.locationMap) return;
if (state.map || !elements.locationMap) return;
if (typeof window.L === 'undefined') {
setMapStatus('Map library failed to load. Rebuild the container and hard-refresh the page.', true);
return;
}
const config = state.mapConfig || {};
state.map = L.map(elements.locationMap, { zoomControl: true }).setView(
[Number(config.defaultMapLat ?? 64.5), Number(config.defaultMapLon ?? 11.0)],
Number(config.defaultMapZoom ?? 5),
);
L.tileLayer(config.mapTileUrl || 'https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 19,
attribution: config.mapAttribution || '&copy; OpenStreetMap contributors',
}).addTo(state.map);
state.map.on('click', (event) => {
setLocation(event.latlng.lat, event.latlng.lng, '', true, false);
});
syncMapFromFields(false);
try {
state.map = L.map(elements.locationMap, { zoomControl: true }).setView(
[Number(config.defaultMapLat ?? 64.5), Number(config.defaultMapLon ?? 11.0)],
Number(config.defaultMapZoom ?? 5),
);
const layer = L.tileLayer(config.mapTileUrl || '/api/map/tiles/{z}/{x}/{y}.png', {
maxZoom: 19,
attribution: config.mapAttribution || '&copy; OpenStreetMap contributors',
}).addTo(state.map);
layer.on('loading', () => setMapStatus('Loading map…'));
layer.on('load', () => setMapStatus('Click the map to place a pin.'));
layer.on('tileerror', () => setMapStatus('Map tiles could not be loaded. Address search and manual coordinates still work.', true));
state.map.on('click', (event) => {
setLocation(event.latlng.lat, event.latlng.lng, '', true, false);
});
syncMapFromFields(false);
} catch (error) {
state.map = null;
setMapStatus(error.message || 'The map could not be initialized.', true);
}
}
function setMarker(latitude, longitude, center = false) {
@@ -709,6 +801,123 @@ function clearLocation() {
showToast('Location cleared. Save the photo to remove GPS metadata.');
}
function renderFavoriteLocations(selectedId = '') {
const favorites = state.favoriteLocations;
elements.favoriteSelect.innerHTML = '';
if (!favorites.length) {
const option = document.createElement('option');
option.value = '';
option.textContent = 'No favorites saved';
elements.favoriteSelect.appendChild(option);
elements.favoriteSelect.disabled = true;
elements.useFavorite.disabled = true;
elements.deleteFavorite.disabled = true;
return;
}
const placeholder = document.createElement('option');
placeholder.value = '';
placeholder.textContent = 'Choose a favorite…';
elements.favoriteSelect.appendChild(placeholder);
for (const favorite of favorites) {
const option = document.createElement('option');
option.value = favorite.id;
option.textContent = `${favorite.name}${Number(favorite.latitude).toFixed(5)}, ${Number(favorite.longitude).toFixed(5)}`;
elements.favoriteSelect.appendChild(option);
}
elements.favoriteSelect.disabled = false;
elements.favoriteSelect.value = favorites.some((item) => item.id === selectedId) ? selectedId : '';
updateFavoriteButtons();
}
function updateFavoriteButtons() {
const selected = Boolean(elements.favoriteSelect.value);
elements.useFavorite.disabled = !selected;
elements.deleteFavorite.disabled = !selected;
}
async function loadFavoriteLocations(selectedId = '') {
try {
const response = await fetch('/api/favorites', { cache: 'no-store' });
if (!response.ok) throw new Error(`Could not load favorites (${response.status}).`);
const data = await response.json();
state.favoriteLocations = Array.isArray(data.favorites) ? data.favorites : [];
renderFavoriteLocations(selectedId);
} catch (error) {
state.favoriteLocations = [];
renderFavoriteLocations();
showToast(error.message || 'Could not load favorite locations.', true);
}
}
function useSelectedFavorite() {
const favorite = state.favoriteLocations.find((item) => item.id === elements.favoriteSelect.value);
if (!favorite) return;
setLocation(favorite.latitude, favorite.longitude, favorite.name, true, true);
showToast(`Location set to ${favorite.name}.`);
}
async function saveCurrentAsFavorite() {
if (!validCoordinates(elements.latitude.value, elements.longitude.value)) {
showToast('Set a valid location before saving it as a favorite.', true);
return;
}
const suggested = elements.locationName.value.trim() || 'Favorite location';
const entered = window.prompt('Name this favorite location:', suggested);
if (entered === null) return;
const name = entered.trim();
if (!name) {
showToast('Favorite name cannot be empty.', true);
return;
}
elements.saveFavorite.disabled = true;
try {
const response = await fetch('/api/favorites', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name,
latitude: Number(elements.latitude.value),
longitude: Number(elements.longitude.value),
}),
});
if (!response.ok) {
let message = `Could not save favorite (${response.status}).`;
try { message = (await response.json()).detail || message; } catch {}
throw new Error(message);
}
const data = await response.json();
await loadFavoriteLocations(data.favorite?.id || '');
showToast(`${name} added to favorite locations.`);
} catch (error) {
showToast(error.message || 'Could not save favorite location.', true);
} finally {
elements.saveFavorite.disabled = false;
}
}
async function deleteSelectedFavorite() {
const favorite = state.favoriteLocations.find((item) => item.id === elements.favoriteSelect.value);
if (!favorite) return;
if (!window.confirm(`Delete favorite location “${favorite.name}”?`)) return;
elements.deleteFavorite.disabled = true;
try {
const response = await fetch(`/api/favorites/${encodeURIComponent(favorite.id)}`, { method: 'DELETE' });
if (!response.ok) {
let message = `Could not delete favorite (${response.status}).`;
try { message = (await response.json()).detail || message; } catch {}
throw new Error(message);
}
await loadFavoriteLocations();
showToast(`${favorite.name} removed from favorite locations.`);
} catch (error) {
showToast(error.message || 'Could not delete favorite location.', true);
updateFavoriteButtons();
}
}
async function searchAddress() {
const query = elements.addressSearch.value.trim();
if (query.length < 3) {
@@ -768,6 +977,10 @@ elements.copyPrevious.addEventListener('click', copyPreviousValues);
elements.addressSearchButton.addEventListener('click', searchAddress);
elements.addressSearch.addEventListener('keydown', (event) => { if (event.key === 'Enter') { event.preventDefault(); searchAddress(); } });
elements.clearLocation.addEventListener('click', clearLocation);
elements.favoriteSelect.addEventListener('change', updateFavoriteButtons);
elements.useFavorite.addEventListener('click', useSelectedFavorite);
elements.saveFavorite.addEventListener('click', saveCurrentAsFavorite);
elements.deleteFavorite.addEventListener('click', deleteSelectedFavorite);
for (const input of [elements.latitude, elements.longitude]) {
input.addEventListener('input', () => { state.locationDirty = true; syncMapFromFields(false); });
input.addEventListener('change', () => syncMapFromFields(true));
@@ -786,12 +999,6 @@ for (const radio of $$('input[name="precision"]')) radio.addEventListener('chang
for (const tab of $$('.tab')) {
tab.addEventListener('click', () => activateTab(tab.dataset.tab));
tab.addEventListener('keydown', (event) => {
if (event.key === 'ArrowLeft') { event.preventDefault(); cycleTabs(-1); }
if (event.key === 'ArrowRight') { event.preventDefault(); cycleTabs(1); }
if (event.key === 'Home') { event.preventDefault(); activateTab($$('.tab')[0].dataset.tab, true); }
if (event.key === 'End') { const tabs = $$('.tab'); event.preventDefault(); activateTab(tabs[tabs.length - 1].dataset.tab, true); }
});
}
activateTab('date');
@@ -804,7 +1011,7 @@ window.addEventListener('keydown', (event) => {
const typing = ['INPUT', 'TEXTAREA', 'SELECT'].includes(tag);
if (event.key === 'Tab' && event.shiftKey && !event.ctrlKey && !event.altKey && !event.metaKey && document.activeElement?.closest('.right-panel')) {
event.preventDefault(); cycleTabs(-1); return;
event.preventDefault(); event.stopPropagation(); cycleTabs(-1, 'field'); return;
}
if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === 's') {
event.preventDefault(); savePhoto(false); return;
@@ -824,12 +1031,18 @@ async function initialise() {
const response = await fetch('/api/config', { cache: 'no-store' });
if (response.ok) {
const config = await response.json();
elements.appName.textContent = config.appName;
document.title = config.appName;
const pageTitle = config.appTitle || config.appName;
elements.appName.textContent = pageTitle;
elements.appSubtitle.textContent = config.appSubtitle;
document.title = pageTitle;
state.mapConfig = config;
}
} catch {}
// Favorite locations are server-side shared data and must be loaded on every page start,
// independently of whether the user opens a photo folder in this browser session.
await loadFavoriteLocations();
if (!isSupported()) {
setSaveStatus('failed', 'Browser folder access unavailable', 'Use a current Chromium browser over HTTPS.');
for (const button of elements.openButtons) button.title = 'Requires a Chromium browser and HTTPS';
+32 -11
View File
@@ -16,7 +16,7 @@
<div class="brand-mark" aria-hidden="true"></div>
<div>
<h1 id="app-name">Photo Date Editor</h1>
<p>Local folder · in-place JPEG metadata</p>
<p id="app-subtitle">Local folder · in-place JPG, PNG, TIFF, HEIF and DNG metadata</p>
</div>
</div>
<div class="top-actions">
@@ -70,10 +70,11 @@
<select id="sort-select" class="input filter" aria-label="Sort photos" disabled>
<option value="filename">Sort: Filename</option>
<option value="status">Sort: Status</option>
<option value="format">Sort: Format</option>
</select>
</div>
<div id="file-list" class="file-list" aria-live="polite">
<div class="empty-list">Choose a folder containing JPG or JPEG photos.</div>
<div class="empty-list">Choose a folder containing JPG, PNG, TIFF, HEIC, HEIF, HIF, or DNG photos.</div>
</div>
</section>
@@ -124,14 +125,14 @@
<aside class="sidebar right-panel">
<div class="tabs" role="tablist">
<button class="tab active" data-tab="date" role="tab">Date &amp; time</button>
<button class="tab" data-tab="details" role="tab">Details</button>
<button class="tab" data-tab="keywords" role="tab">Keywords</button>
<button class="tab" data-tab="location" role="tab">Location</button>
<button id="tab-date" class="tab active" data-tab="date" role="tab" aria-selected="true" aria-controls="panel-date">Date &amp; time</button>
<button id="tab-details" class="tab" data-tab="details" role="tab" aria-selected="false" aria-controls="panel-details" tabindex="-1">Details</button>
<button id="tab-keywords" class="tab" data-tab="keywords" role="tab" aria-selected="false" aria-controls="panel-keywords" tabindex="-1">Keywords</button>
<button id="tab-location" class="tab" data-tab="location" role="tab" aria-selected="false" aria-controls="panel-location" tabindex="-1">Location</button>
</div>
<form id="metadata-form" autocomplete="off">
<section class="tab-panel active" data-panel="date">
<section id="panel-date" class="tab-panel active" data-panel="date" role="tabpanel" aria-labelledby="tab-date">
<fieldset>
<legend>Date precision</legend>
<label class="radio-row"><input type="radio" name="precision" value="exact" checked> <span>Exact date</span></label>
@@ -180,7 +181,7 @@
</div>
</section>
<section class="tab-panel" data-panel="details">
<section id="panel-details" class="tab-panel" data-panel="details" role="tabpanel" aria-labelledby="tab-details">
<label class="field">
<span>Description</span>
<textarea id="description-input" class="input textarea" rows="7" maxlength="2000" placeholder="Who, where, occasion, or other context…"></textarea>
@@ -188,7 +189,7 @@
<div class="helper-row"><span>Written to EXIF, XMP and IPTC</span><span id="description-count">0 / 2000</span></div>
</section>
<section class="tab-panel" data-panel="keywords">
<section id="panel-keywords" class="tab-panel" data-panel="keywords" role="tabpanel" aria-labelledby="tab-keywords">
<label class="field">
<span>People and keywords</span>
<textarea id="keywords-input" class="input textarea" rows="7" placeholder="Daniel, family, birthday, Bergen"></textarea>
@@ -196,7 +197,26 @@
<p class="field-help">Separate entries with commas or new lines. Written as XMP Subject and IPTC Keywords.</p>
</section>
<section class="tab-panel" data-panel="location">
<section id="panel-location" class="tab-panel" data-panel="location" role="tabpanel" aria-labelledby="tab-location">
<div class="favorite-locations">
<div class="section-heading-row">
<div>
<strong>Favorite locations</strong>
<span>Shared by everyone using this Docker stack</span>
</div>
</div>
<div class="favorite-controls">
<select id="favorite-location-select" class="input" aria-label="Favorite locations">
<option value="">No favorites saved</option>
</select>
<button id="use-favorite-location" class="button" type="button" disabled>Use</button>
</div>
<div class="favorite-actions">
<button id="save-favorite-location" class="button ghost" type="button">★ Add current location</button>
<button id="delete-favorite-location" class="button ghost danger-text" type="button" disabled>Delete selected</button>
</div>
</div>
<div class="location-search">
<label class="field location-search-field">
<span>Search for a place or address</span>
@@ -208,6 +228,7 @@
<div id="address-results" class="address-results" aria-live="polite"></div>
<div id="location-map" class="location-map" aria-label="Map for selecting photo location"></div>
<p id="map-status" class="field-help map-status" role="status">Open this tab to load the map.</p>
<p class="field-help map-help">Click the map to place a pin, or drag the pin to fine-tune the position.</p>
<div class="field-grid coordinate-grid">
@@ -255,7 +276,7 @@
<div><dt>← / →</dt><dd>Previous or next photo</dd></div>
<div><dt>S</dt><dd>Mark skipped and open next photo</dd></div>
<div><dt>C</dt><dd>Copy previous photo's values</dd></div>
<div><dt>Shift+Tab</dt><dd>Switch to the previous right-side tab</dd></div>
<div><dt>Shift+Tab</dt><dd>Open the previous metadata tab and focus its first field</dd></div>
</dl>
</dialog>
+1 -1
View File
@@ -5,5 +5,5 @@
"display": "standalone",
"background_color": "#0d1218",
"theme_color": "#121820",
"description": "Edit dates, descriptions, and keywords in scanned JPEG photos."
"description": "Edit dates, descriptions, keywords, and locations in JPG, PNG, TIFF, HEIF, and DNG photos."
}
+1 -1
View File
@@ -1,4 +1,4 @@
const CACHE_NAME = 'photo-date-editor-v4';
const CACHE_NAME = 'photo-date-editor-v7-0';
const SHELL = ['/', '/styles.css', '/app.js', '/manifest.webmanifest', '/vendor/leaflet/leaflet.css', '/vendor/leaflet/leaflet.js'];
self.addEventListener('install', (event) => {
+23 -2
View File
@@ -58,9 +58,12 @@ button { color: inherit; }
.file-row:hover { background: rgba(255,255,255,.045); }
.file-row.active { background: var(--primary-soft); outline: 1px solid rgba(79,135,255,.4); }
.file-thumb { width: 50px; height: 44px; object-fit: cover; background: #0b1015; border-radius: 5px; }
.file-thumb.format-placeholder { display: grid; place-items: center; border: 1px solid var(--border); color: var(--muted); font-size: 10px; font-weight: 800; letter-spacing: .06em; }
.file-meta { min-width: 0; }
.file-meta strong, .file-meta span { display: block; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.file-meta strong { font-size: 13px; }.file-meta span { margin-top: 4px; color: var(--muted); font-size: 11px; }
.file-meta strong { display: block; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; font-size: 13px; }
.file-details { margin-top: 4px; display: flex; align-items: center; gap: 6px; min-width: 0; color: var(--muted); font-size: 11px; white-space: nowrap; }
.file-details > span:not(.format-badge) { overflow: hidden; text-overflow: ellipsis; }
.format-badge { flex: 0 0 auto; padding: 1px 5px; border: 1px solid var(--border); border-radius: 999px; color: var(--text); font-size: 9px; font-weight: 800; letter-spacing: .05em; }
.file-state { width: 19px; height: 19px; display: grid; place-items: center; border-radius: 50%; font-size: 11px; border: 1px solid #536071; color: #8390a0; }
.file-state.saved { color: #092b1b; background: var(--success); border-color: var(--success); font-weight: 800; }
.file-state.skipped { color: #2e2111; background: #c49a5a; border-color: #c49a5a; font-weight: 800; }
@@ -137,3 +140,21 @@ fieldset { border: 0; padding: 0; margin: 0 0 22px; } legend { font-weight: 650;
.tab { font-size: 12px; padding-inline: 5px; }
}
.search-privacy { margin: 7px 0 0; }
.map-status { margin-top: 8px; min-height: 1.2em; }
.map-status.error { color: var(--danger); }
/* v0.4.2 shared favorite locations */
.favorite-locations {
margin: 0 0 18px;
padding: 12px;
border: 1px solid var(--line);
border-radius: 9px;
background: rgba(16, 23, 31, .72);
}
.section-heading-row { display: flex; align-items: center; justify-content: space-between; margin-bottom: 9px; }
.section-heading-row strong, .section-heading-row span { display: block; }
.section-heading-row strong { font-size: 12px; }
.section-heading-row span { margin-top: 2px; color: var(--muted); font-size: 10px; }
.favorite-controls { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 8px; }
.favorite-actions { display: flex; flex-wrap: wrap; justify-content: space-between; gap: 8px; margin-top: 8px; }
.danger-text { color: var(--danger); }
+8
View File
@@ -10,8 +10,13 @@ services:
environment:
APP_URL: "${APP_URL:-http://localhost:8080}"
APP_NAME: "${APP_NAME:-Photo Date Editor}"
APP_TITLE: "${APP_TITLE:-}"
APP_SUBTITLE: "${APP_SUBTITLE:-}"
MAX_UPLOAD_MB: "${MAX_UPLOAD_MB:-150}"
LOG_LEVEL: "${LOG_LEVEL:-INFO}"
DATA_DIR: "/data"
volumes:
- photo-date-editor-data:/data
healthcheck:
test:
- CMD
@@ -22,3 +27,6 @@ services:
timeout: 5s
retries: 3
start_period: 10s
volumes:
photo-date-editor-data:
+3
View File
@@ -1,3 +1,6 @@
fastapi>=0.116,<1
uvicorn[standard]>=0.35,<1
python-multipart>=0.0.20,<1
Pillow>=11.3,<13
pillow-heif>=1.1,<2
rawpy>=0.25,<1