diff --git a/metadata_editor.py b/metadata_editor.py new file mode 100755 index 0000000..8c53aa7 --- /dev/null +++ b/metadata_editor.py @@ -0,0 +1,83 @@ +#!/usr/bin/env python3 +"""Interactively view, edit, or remove metadata fields in one or more files.""" + +from __future__ import annotations + +import json +import subprocess +import sys + +from tools.console import ( + clear_screen, + launch_terminal_if_needed, + pause_if_interactive, + prompt_yes_no, +) +from tools.exiftool import require_exiftool, run_exiftool_json +from tools.filesystem import collect_files, input_paths +from tools.metadata_editor import apply_fields, edit_fields, write_arguments + + +def run(argv: list[str]) -> int: + try: + args = input_paths(argv) + except RuntimeError as exc: + print(exc) + return 1 + if not args: + print("No inputs selected.") + return 0 + files = collect_files(args, print_missing=True) + if not files: + print("No files found.") + return 1 + try: + exiftool = require_exiftool() + metadata = run_exiftool_json(exiftool, files, quicktime_utc=False) + except (RuntimeError, subprocess.CalledProcessError, json.JSONDecodeError) as exc: + print(f"Could not read metadata: {exc}") + return 1 + + fields_state = None + while True: + try: + fields = edit_fields(metadata, fields_state) + except RuntimeError as exc: + print(exc) + return 1 + if fields is None: + print("Nothing changed.") + return 0 + args = write_arguments(fields) + clear_screen(scrollback=True) + if not args: + print("No metadata changes selected.") + else: + print(f"Planned metadata changes for {len(files)} file(s):") + for argument in args: + print(f" {argument}") + if prompt_yes_no("Apply these changes?", True): + break + fields_state = fields + + failures = apply_fields(exiftool, files, fields) + if failures: + print("\nSome files failed:") + for failure in failures: + print(f" - {failure}") + return 1 + print("\nDone.") + return 0 + + +def main(argv: list[str]) -> int: + if launch_terminal_if_needed(argv): + return 0 + try: + return run(argv) + finally: + pause_if_interactive() + + +if __name__ == "__main__": + raise SystemExit(main(sys.argv)) diff --git a/tools/metadata_editor.py b/tools/metadata_editor.py new file mode 100644 index 0000000..347e4b4 --- /dev/null +++ b/tools/metadata_editor.py @@ -0,0 +1,267 @@ +"""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 diff --git a/unit_tests/test_audio_and_metadata_editor.py b/unit_tests/test_audio_and_metadata_editor.py index e501578..cda7eeb 100644 --- a/unit_tests/test_audio_and_metadata_editor.py +++ b/unit_tests/test_audio_and_metadata_editor.py @@ -15,6 +15,7 @@ from tools.audio_batch import ( universal_containers, ) from tools.audio_settings import parse_bitrate, resolve_output_dir +from tools.metadata_editor import Field, REMOVE, parse_gps_coordinates, write_arguments class AudioBatchTests(unittest.TestCase): @@ -67,6 +68,33 @@ class AudioBatchTests(unittest.TestCase): self.assertEqual(second, output_dir / "song-1.opus") +class MetadataEditorTests(unittest.TestCase): + def test_decimal_and_ascii_dms_gps_are_equivalent(self) -> None: + self.assertEqual(parse_gps_coordinates("58.660600, 16.448300"), (58.6606, 16.4483)) + latitude, longitude = parse_gps_coordinates("58 39 38.16 N, 16:26:53.88E") + self.assertAlmostEqual(latitude, 58.6606) + self.assertAlmostEqual(longitude, 16.4483) + + def test_negative_decimal_coordinates_mean_south_and_west(self) -> None: + self.assertEqual(parse_gps_coordinates("-58.5, -16.25"), (-58.5, -16.25)) + with self.assertRaisesRegex(ValueError, "cannot use N"): + parse_gps_coordinates("-58.5 N, 16.25 E") + + def test_gps_writes_use_decimal_values_and_hemisphere_refs(self) -> None: + field = Field("GPS coordinates", (), "gps", pending="58.660600, -16.448300") + self.assertEqual( + write_arguments([field]), + [ + "-EXIF:GPSLatitude=58.66060000", + "-EXIF:GPSLatitudeRef=N", + "-EXIF:GPSLongitude=16.44830000", + "-EXIF:GPSLongitudeRef=W", + ], + ) + + def test_remove_gps_removes_coordinate_and_ref_tags(self) -> None: + field = Field("GPS coordinates", (), "gps", pending=REMOVE) + self.assertEqual(len(write_arguments([field])), 4) if __name__ == "__main__":