Files
media-batch-tools/tools/metadata_editor.py
T

268 lines
11 KiB
Python

"""Interactive bulk metadata editing and coordinate parsing."""
from __future__ import annotations
import re
import shutil
from dataclasses import dataclass, field
from pathlib import Path
from tools.console import dark_field, dim, draw_screen, inverse, light_red, raw_key_input
from tools.exiftool import run_exiftool_write
from tools.media_metadata import parse_exif_datetime
REMOVE = object()
GPS_TAGS = {
"EXIF:GPSLatitude", "EXIF:GPSLatitudeRef", "EXIF:GPSLongitude", "EXIF:GPSLongitudeRef",
"Composite:GPSLatitude", "Composite:GPSLongitude", "Composite:GPSPosition", "GPS:GPSLatitude", "GPS:GPSLongitude",
}
COMMON_TAGS = (
"EXIF:DateTimeOriginal", "EXIF:CreateDate", "EXIF:ModifyDate", "EXIF:Artist", "XMP:Creator",
"EXIF:Copyright", "XMP:Rights", "EXIF:ImageDescription", "XMP:Description", "XMP:Title",
"IPTC:ObjectName", "XMP:Subject",
)
@dataclass
class Field:
label: str
tags: tuple[str, ...]
kind: str = "text"
values: set[str] = field(default_factory=set)
missing: int = 0
pending: str | object | None = None
writable: bool = True
@property
def value_text(self) -> str:
if self.pending is REMOVE:
return "(remove)"
if isinstance(self.pending, str):
return self.pending or "(empty)"
if not self.values:
return "(empty)" if self.missing == 0 else "(missing)"
if len(self.values) == 1 and self.missing == 0:
return next(iter(self.values))
return "(multiple values)"
def build_fields(metadata: list[dict]) -> list[Field]:
tags = {
key
for item in metadata
for key in item
if _editable_tag(key) and key not in GPS_TAGS
}
tags.update(COMMON_TAGS)
fields = [_field_for_tag(tag, metadata) for tag in sorted(tags, key=str.casefold)]
fields.insert(0, _gps_field(metadata))
return fields
def edit_fields(metadata: list[dict], fields: list[Field] | None = None) -> list[Field] | None:
fields = build_fields(metadata) if fields is None else fields
selected, typing, typed, error = 0, False, "", ""
with raw_key_input() as read_key:
while True:
field_count = len(fields)
lines = _draw_editor(fields, selected, typing, typed, error)
draw_screen(lines)
key = read_key()
if typing:
field = fields[selected]
if key == "esc":
typing, typed, error = False, "", ""
elif key == "backspace":
typed = typed[:-1]
elif key == "enter":
try:
value = validate_field(field, typed)
except ValueError as exc:
error = str(exc)
else:
field.pending = value
typing, typed, error = False, "", ""
elif len(key) == 1 and key >= " ":
typed += key
continue
if key == "up":
selected = max(0, selected - 1)
elif key == "down":
selected = min(field_count, selected + 1)
elif key == "delete" and selected < field_count:
if fields[selected].writable:
fields[selected].pending = REMOVE
else:
error = "This physical or maker-note field is read-only."
elif key == "enter":
if selected == field_count:
return fields
selected += 1
elif key == "left" and selected == field_count:
return None
elif key == "esc":
return None
elif selected < field_count and len(key) == 1 and key >= " ":
if fields[selected].writable:
typing, typed, error = True, key, ""
else:
error = "This physical or maker-note field is read-only."
def validate_field(field: Field, value: str) -> str:
text = value.strip()
if field.kind == "gps":
latitude, longitude = parse_gps_coordinates(text)
return f"{latitude:.6f}, {longitude:.6f}"
if "date" in field.label.casefold() and text and parse_exif_datetime(text) is None:
raise ValueError("Date/time must contain YYYY:MM:DD HH:MM:SS.")
return text
def parse_gps_coordinates(value: str) -> tuple[float, float]:
parts = re.split(r"\s*[,;]\s*", value.strip(), maxsplit=1)
if len(parts) != 2:
raise ValueError("GPS coordinates must be latitude, longitude.")
latitude = parse_coordinate(parts[0], "latitude")
longitude = parse_coordinate(parts[1], "longitude")
return latitude, longitude
def parse_coordinate(value: str, axis: str) -> float:
text = value.strip().upper()
hemisphere = text[-1:] if text[-1:] in {"N", "S", "E", "W"} else ""
if hemisphere:
text = text[:-1].strip()
values = re.findall(r"[+-]?\d+(?:\.\d+)?", text)
if not values or len(values) > 3:
raise ValueError(f"Invalid {axis} coordinate.")
if len(values) == 1:
coordinate = float(values[0])
else:
degrees, minutes = float(values[0]), float(values[1])
seconds = float(values[2]) if len(values) == 3 else 0.0
if minutes >= 60 or seconds >= 60:
raise ValueError(f"Invalid {axis} minutes or seconds.")
coordinate = abs(degrees) + minutes / 60 + seconds / 3600
if degrees < 0:
coordinate = -coordinate
allowed = {"latitude": {"N", "S"}, "longitude": {"E", "W"}}[axis]
if hemisphere and hemisphere not in allowed:
raise ValueError(f"Use {'N/S' if axis == 'latitude' else 'E/W'} for {axis}.")
if hemisphere:
sign = -1 if hemisphere in {"S", "W"} else 1
if coordinate < 0 and sign > 0:
raise ValueError("Negative coordinates cannot use N or E.")
coordinate = sign * abs(coordinate)
maximum = 90 if axis == "latitude" else 180
if abs(coordinate) > maximum:
raise ValueError(f"{axis.title()} must be between -{maximum} and {maximum}.")
return coordinate
def write_arguments(fields: list[Field]) -> list[str]:
args: list[str] = []
for field in fields:
if field.pending is None or not field.writable:
continue
if field.kind == "gps":
args.extend(_gps_args(None if field.pending is REMOVE else str(field.pending)))
else:
for tag in field.tags:
args.append(f"-{tag}={'' if field.pending is REMOVE else field.pending}")
return args
def apply_fields(exiftool: str, paths: list[Path], fields: list[Field]) -> list[str]:
args = write_arguments(fields)
failures = []
for path in paths:
try:
run_exiftool_write(exiftool, path, args)
except RuntimeError as exc:
failures.append(f"{path}: {exc}")
return failures
def _field_for_tag(tag: str, metadata: list[dict]) -> Field:
values = {str(item[tag]) for item in metadata if tag in item and item[tag] not in (None, "")}
return Field(
tag.replace(":", ": "),
(tag,),
values=values,
missing=len(metadata) - sum(tag in item and item[tag] not in (None, "") for item in metadata),
writable=_writable_tag(tag),
)
def _gps_field(metadata: list[dict]) -> Field:
values = set()
missing = 0
for item in metadata:
latitude = _first_value(item, ("Composite:GPSLatitude", "EXIF:GPSLatitude", "GPS:GPSLatitude"))
longitude = _first_value(item, ("Composite:GPSLongitude", "EXIF:GPSLongitude", "GPS:GPSLongitude"))
if latitude is None or longitude is None:
missing += 1
continue
try:
values.add("%.6f, %.6f" % (parse_coordinate(str(latitude), "latitude"), parse_coordinate(str(longitude), "longitude")))
except ValueError:
values.add(f"{latitude}, {longitude}")
return Field("GPS coordinates", (), "gps", values, missing)
def _gps_args(value: str | None) -> list[str]:
if value is None:
return [f"-{tag}=" for tag in ("EXIF:GPSLatitude", "EXIF:GPSLatitudeRef", "EXIF:GPSLongitude", "EXIF:GPSLongitudeRef")]
latitude, longitude = parse_gps_coordinates(value)
return [
f"-EXIF:GPSLatitude={abs(latitude):.8f}", f"-EXIF:GPSLatitudeRef={'N' if latitude >= 0 else 'S'}",
f"-EXIF:GPSLongitude={abs(longitude):.8f}", f"-EXIF:GPSLongitudeRef={'E' if longitude >= 0 else 'W'}",
]
def _editable_tag(tag: str) -> bool:
return ":" in tag and not tag.startswith(("File:", "ExifTool:", "Composite:"))
def _writable_tag(tag: str) -> bool:
name = tag.rsplit(":", 1)[-1]
return not tag.startswith(("MakerNotes:", "QuickTime:Track", "QuickTime:Media")) and name not in {
"Duration", "ImageWidth", "ImageHeight", "ImageSize", "Megapixels", "FileType", "FileTypeExtension",
"MIMEType", "Bitrate", "AvgBitrate", "VideoFrameRate", "AudioSampleRate", "AudioChannels",
"CompressorID", "CompressorName", "MediaDataOffset", "MediaDataSize",
}
def _first_value(metadata: dict, tags: tuple[str, ...]):
return next((metadata[tag] for tag in tags if tag in metadata), None)
def _draw_editor(fields: list[Field], selected: int, typing: bool, typed: str, error: str) -> list[str]:
height = max(8, shutil.get_terminal_size().lines - 7)
start = max(0, min(selected - height // 2, len(fields) - height))
lines = ["Metadata editor", "Up/Down: navigate Enter: confirm Delete: remove Esc: cancel", ""]
for index in range(start, min(len(fields), start + height)):
field = fields[index]
value = dark_field(typed + " ") if typing and index == selected else field.value_text
if field.pending is REMOVE:
value = light_red(value)
elif not field.writable:
value = dim(value)
elif not typing and (field.pending is None and field.value_text in {"(missing)", "(multiple values)"}):
value = dim(value)
line = f"{field.label:<32} {value}"
lines.append(inverse(line) if index == selected else line)
if start + height < len(fields):
lines.append(dim("..."))
if selected < len(fields) and len(fields[selected].values) > 1 and not typing:
values = "; ".join(sorted(fields[selected].values, key=str.casefold)[:5])
suffix = "; ..." if len(fields[selected].values) > 5 else ""
lines.extend(("", f"Values: {values}{suffix}"))
lines.extend(("", inverse("Confirm changes") if selected == len(fields) else "Confirm changes"))
if error:
lines.extend(("", light_red(error)))
return lines