Compare commits

...
9 Commits
Author SHA1 Message Date
mathias2784 b65282972e metadata writer: test setup
Tests / test_and_lint (push) Failing after 26s
2026-10-08 12:03:36 +02:00
mathias2784 72e116a7b8 metadata writer: some progress 2026-10-08 12:02:50 +02:00
mathias2784 1c07a78c59 black
Tests / test_and_lint (push) Failing after 24s
2026-10-07 16:03:15 +02:00
mathias2784 4fc2116cfe metadata writer: some progress
Tests / test_and_lint (push) Failing after 25s
2026-10-07 16:02:01 +02:00
mathias2784 81270d9bad small fix
Tests / test_and_lint (push) Successful in 27s
2026-10-06 08:12:19 +02:00
mathias2784 afc90a9f28 metadata writer: add guard for exiftools installed on system level
Tests / test_and_lint (push) Successful in 27s
2026-10-06 08:10:23 +02:00
mathias2784 7c77eeb392 install exiftool in pipeline runner
Tests / test_and_lint (push) Successful in 34s
2026-10-06 08:02:24 +02:00
mathias2784 084676eca0 metadata writer: some progress
Tests / test_and_lint (push) Failing after 13s
2026-10-06 07:52:36 +02:00
mathias2784 1366e3b3e7 metadata-writer: first skeleton
Tests / test_and_lint (push) Successful in 14s
2026-10-04 07:54:33 +02:00
10 changed files with 189 additions and 7 deletions
+2
View File
@@ -1,3 +1,5 @@
LLM_API_BASE_URL = "http://localhost:1234/v1"
LLM_API_KEY = "not-relevant"
LLM_DEFAULT_TEMPERATURE = 1.0
METADATA_PREFIX = "photools:"
+9
View File
@@ -18,6 +18,15 @@ jobs:
run: uv sync --frozen
- name: copy env
run: cp .env.template .env
- name: Install exiftool (system dependency)
run: |
if command -v exiftool >/dev/null 2>&1; then
echo "exiftool already installed"
elif command -v sudo >/dev/null 2>&1; then
sudo apt-get update && sudo apt-get install -y --no-install-recommends libimage-exiftool-perl
else
apt-get update && apt-get install -y --no-install-recommends libimage-exiftool-perl
fi
- name: Run pytest
run: uv run pytest .
- name: Check formatting (black)
+5
View File
@@ -6,6 +6,11 @@ Requires a `.env` file with the following variables:
- `llm_api_base_url`: Base URL for the LLM API.
- `llm_default_temperature`: Float value for temperature.
## System Dependencies
- `exiftool` binary: required by `pyexiftool` at runtime, not installable via pip/uv.
- Arch: `perl-image-exiftool`
- Debian/Ubuntu: `libimage-exiftool-perl`
## Development Toolchain
- **Dependency Management**: Use `uv`.
- **Python Version**: Requires Python `>=3.14`.
+1
View File
@@ -13,6 +13,7 @@ dependencies = [
"pillow>=12.3.0",
"pydantic>=2.13.5",
"pydantic-settings>=2.15.0",
"pyexiftool>=0.5.6",
"pytest>=9.1.1",
"ruff>=0.16.9",
"typer>=0.12.0",
+1 -3
View File
@@ -17,12 +17,10 @@ from photools3.models import (
LlmResponseQuality,
)
from photools3.photo import Photo
from photools3.settings import Settings
from photools3.settings import settings
logger = logging.getLogger(__name__)
settings = Settings() # type: ignore[reportCallIssue]
class LlmSession:
base_url: str = str(settings.llm_api_base_url)
+122
View File
@@ -0,0 +1,122 @@
import logging
import shutil
from pathlib import Path
from typing import Annotated, Any
import exiftool
from pydantic import StringConstraints
from photools3.settings import settings
log = logging.getLogger(__name__)
_EXIFTOOL_MISSING_MSG = (
"exiftool binary not found in PATH. "
"Install the system package: 'perl-image-exiftool' (Arch) or 'libimage-exiftool-perl' (Debian/Ubuntu)."
)
if shutil.which("exiftool") is None:
raise FileNotFoundError(_EXIFTOOL_MISSING_MSG)
# File extensions that should use XMP sidecars
SIDECAR_EXTENSIONS = {".dng", ".nef", ".cr2", ".cr3", ".arw", ".raf", ".orf", ".rw2"}
XmpKey = Annotated[str, StringConstraints(pattern=r"^\w+\:\w+")]
type Caption = str
type Keywords = list[str] | None
type Color = str | None
type XmpMetadata = dict[str, Any]
XMP_KEYS_CAPTION: list[XmpKey] = [
"XMP:Description",
"EXIF:ImageDescription",
"IPTC:Caption-Abstract",
]
XMP_KEYS_TAG: list[XmpKey] = [
"XMP:HierarchicalSubject",
"XMP:Subject",
"IPTC:Keywords",
]
def _prefixed(txt: str) -> str:
return f"{settings.metadata_prefix} {txt}"
def _is_prefixed(txt: str) -> bool:
return txt.startswith(settings.metadata_prefix)
class MetadataWriter:
"""
Write metadata (captions and keywords) to image files.
For DNG files, creates/updates XMP sidecar files.
"""
def __init__(
self,
path: Path,
force_sidecar: bool = False,
append: bool = True,
):
self.path = Path
self.force_sidecar = force_sidecar
self.append = append
self._metadata: XmpMetadata | None = None
@property
def sidecar_path(self) -> Path:
return Path()
def get_metadata(self, *args, **kwargs) -> Any:
try:
with exiftool.ExifToolHelper() as exif:
metadata = exif.get_metadata([str(self.path)])[0]
except Exception as exc: # noqa: BLE001
log.error(f"Could not read metadata from {self.path}: {exc}")
assert metadata
return metadata.get(*args, **kwargs)
def set_metadata(self, metadata_tags: dict[str, Any]) -> bool:
if self.sidecar_path.exists():
params = ["-overwrite_original"]
else:
params = ["-o", "%f.xmp"]
try:
with exiftool.ExifToolHelper() as exif:
exif.set_tags(
[str(self.sidecar_path)], tags=metadata_tags, params=params
)
except Exception as exc: # noqa
log.error(f"Could not write metadata to file {self.sidecar_path}: {exc}")
return False
return True
def write_caption(self, caption: Caption):
existing = self.get_metadata(XMP_KEYS_CAPTION[0], "")
is_existing_prefixed = _is_prefixed(existing)
if existing and is_existing_prefixed:
return
elif existing and not is_existing_prefixed:
caption = f"{existing}. {_prefixed(caption)}"
metadata_tags = {key: caption for key in XMP_KEYS_CAPTION}
self.set_metadata(metadata_tags)
def write_keywords(self, keywords: Keywords): ...
def write_color(self, color: Color): ...
def write(
self,
caption: Caption | None = None,
keywords: Keywords = None,
color: Color = None,
):
if caption is not None:
self.write_caption(caption)
if keywords is not None:
self.write_keywords(keywords)
if color is not None:
self.write_color(color)
+5
View File
@@ -18,3 +18,8 @@ class Settings(BaseSettings):
llm_api_base_url: Url
llm_api_key: str
llm_default_temperature: float
metadata_prefix: str
settings = Settings() # type: ignore[reportCallIssue]
+31
View File
@@ -0,0 +1,31 @@
from pathlib import Path
import pytest
from photools3.metadata_writer import MetadataWriter
from test.test_photo import PATHS_DNG_EXAMPLES
@pytest.fixture
def make_dng_file(tmp_path):
def _make(index: int = 0) -> Path:
src = PATHS_DNG_EXAMPLES[index]
dst = tmp_path / f"copy_{index}_{src.name}"
return dst
return _make
@pytest.fixture
def dng_file(make_dng):
return make_dng()
def test_read_metadata(make_dng_file):
"""primitive test for `MetadataWriter`"""
file_path = make_dng_file()
result = MetadataWriter(file_path)
assert result
@pytest.mark.parametrize("idx", range(len(PATHS_DNG_EXAMPLES)))
def test_read_metadata_sidecar_path(make_dng_file, idx):
file_path = make_dng_file(idx)
metadata_writer = MetadataWriter(file_path)
assert isinstance(metadata_writer.sidecar_path, Path)
+1 -3
View File
@@ -6,11 +6,9 @@ from photools3.settings import (
PHOTOOLS3_DIR,
ROOT_DIR,
SRC_DIR,
Settings,
settings,
)
settings = Settings()
def test_photools3_dir():
assert PHOTOOLS3_DIR == Path(__file__).parent.parent.resolve() / "src" / "photools3"
Generated
+12 -1
View File
@@ -1,5 +1,5 @@
version = 1
revision = 3
revision = 5
requires-python = ">=3.14"
[[package]]
@@ -580,6 +580,7 @@ dependencies = [
{ name = "pillow" },
{ name = "pydantic" },
{ name = "pydantic-settings" },
{ name = "pyexiftool" },
{ name = "pytest" },
{ name = "ruff" },
{ name = "typer" },
@@ -593,6 +594,7 @@ requires-dist = [
{ name = "pillow", specifier = ">=12.3.0" },
{ name = "pydantic", specifier = ">=2.13.5" },
{ name = "pydantic-settings", specifier = ">=2.15.0" },
{ name = "pyexiftool", specifier = ">=0.5.6" },
{ name = "pytest", specifier = ">=9.1.1" },
{ name = "ruff", specifier = ">=0.16.9" },
{ name = "typer", specifier = ">=0.12.0" },
@@ -746,6 +748,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/30/a4/2bffa9f8e804325a09867f0e9d30795c80ea9f8d62560bd1b6ad6220eb2f/pydantic_settings-2.15.0-py3-none-any.whl", hash = "sha256:0ba092c291c94baceb5eff768aa0d56400a457585bc0175925a5a5510303da42", size = 69413, upload-time = "2026-08-07T09:24:55.839Z" },
]
[[package]]
name = "pyexiftool"
version = "0.5.6"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/5e/48/406da6691d15abf3c8d399bce8bc588709a5b54e857fd7c22dad2f90c33c/PyExifTool-0.5.6.tar.gz", hash = "sha256:22a972c1c212d1ad5f61916fded5057333dcc48fb8e42eed12d2ff9665b367ae", size = 56365, upload-time = "2023-10-22T23:18:18.819Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/fc/b9/175e9a1f8f3f94b22f622f0fcac853ae2c43cb4ac6034f849269c6086dac/PyExifTool-0.5.6-py3-none-any.whl", hash = "sha256:ac7d7836d2bf373f20aa558528f6b2222c4c0d896ed28c951a3ff8e6cec05a87", size = 51243, upload-time = "2023-10-22T23:18:16.614Z" },
]
[[package]]
name = "pygments"
version = "2.21.0"