exifsort — sort photos into YYYY/MM by date

exifsort — sort photos into YYYY/MM by date

exifsort is a LightGUI (Python/XFrame) port of the exifsort utility from util_box: sort photos into YYYY/MM folders by EXIF/date, dry-run first. Give it a directory of photos and it shows the move plan — each photo to its <dir>/YYYY/MM/ folder, dated by JPEG EXIF DateTimeOriginal first, then the file's modification time — and moves nothing until you press Move. It is one of the 285 apps in util_boxgui, the project recreating util_box utilities as LightGUI apps, each with a screenshot and a walkthrough on the matching LightGUI doc site. The full source is apps/python/exifsort/exifsort.py in that repo.

The dry-run plan is already shown when the app starts, so a plain launch + screenshot shows a real plan. The default directory is a demo tree, /tmp/exifsort-demo: one JPEG with EXIF DateTimeOriginal 2021:06:15 (to 2021/06/), one dateless PNG whose mtime falls back to 2020/09 (to 2020/09/), and a text file that is ignored because it is not a photo. The screenshot below is the default state, not a staged one.

The GUI layout

exifsort running under Xvfb
exifsort running — the demo tree's dry-run plan, both moves, captured under Xvfb.

The window is 800×560 and holds six widgets, created with create() + set_prop() and drawn on a single Gtk.DrawingArea:

  • Directory: a GtkLabel and a GtkEntry holding the directory of photos, pre-filled with /tmp/exifsort-demo. Click the entry to focus it (a blue outline appears), then type — BackSpace deletes, Escape drops focus.
  • Dry run: a GtkButton that shows the move plan and changes nothing. This is the default — the plan is shown on launch, and Enter re-shows it.
  • Move: a GtkButton that actually moves the files into <dir>/YYYY/MM/.
  • Hint line: a GtkLabel explaining that dry-run is the default — it prints the plan and moves nothing.
  • Result area: a GtkTextView filling the rest of the window, showing the plan (source -> destination per photo) or the move result. It is read-only — clicking it just drops the entry's focus.

Two honest limitations, both inherited from how LightGUI draws its widgets with Cairo on one drawing area: there is no native GTK focus, so this app wires focus and typing itself (click to focus, type to edit); and the result area does not really scroll — the text-view scroll bars are drawn, not functional, so a directory with more photos than fit the window clips at the bottom. Files already inside a YYYY/MM folder are skipped, so running it twice does nothing the second time; and a name clash at the destination gets a _1, _2, … suffix instead of overwriting.

The demo plan, exactly as the app shows it:

dry-run (default): use --move to actually move files
/tmp/exifsort-demo/nodate.png -> /tmp/exifsort-demo/2020/09/nodate.png
/tmp/exifsort-demo/photo.jpg -> /tmp/exifsort-demo/2021/06/photo.jpg
dry-run: 2 move(s), nothing changed (use --move)

The source, in sections

exifsort.py is about 441 lines. It is modelled on the LightGUI Python examples gtkentry.py, gtkbutton.py and gtktextview.py (and the datecalc app in this repo): widgets are created with create() + set_prop(), drawn on a Gtk.DrawingArea by widget.draw(cr), hit-tested on click, and dispatched through a _HANDLERS table. The EXIF parser and the plan/move half, though, is not modelled on anything — it is vendored verbatim from the CLI, so the GUI can never drift from it.

The EXIF parser. jpeg_exif_date(), tiff_date() and photo_date() are copied byte-for-byte from the CLI script into exifsort.py. No EXIF library is needed: the minimal JPEG APP1/TIFF parser is written here. It walks the JPEG markers looking for the APP1 segment, checks for the Exif\0\0 header, then reads the TIFF IFD for tag 0x9003 — DateTimeOriginal — honouring the file's own byte order (little-endian II or big-endian MM):

def jpeg_exif_date(data):
    """Return b'YYYY:MM:DD HH:MM:SS' from JPEG APP1 EXIF, or None."""
    if len(data) < 4 or data[:2] != b"\xff\xd8":
        return None
    i = 2
    while i + 4 < len(data):
        if data[i] != 0xFF:
            break
        marker = data[i + 1]
        if marker in (0xD8, 0xD9) or 0xD0 <= marker <= 0xD7:
            i += 2; continue
        seglen = struct.unpack(">H", data[i + 2:i + 4])[0]
        seg = data[i + 4:i + 2 + seglen]
        if marker == 0xE1 and seg[:6] == b"Exif\x00\x00":
            return tiff_date(seg[6:])
        i += 2 + seglen
    return None

photo_date() reads the first megabyte of the file, tries the EXIF date, and returns the YYYY/MM folder — or None, in which case plan_moves() falls back to the file's modification time. The plan is built by walking the directory recursively, keeping only image extensions (.jpg, .jpeg, .png, .tif, .tiff, .heic, .webp, .gif), skipping files already inside a YYYY/MM folder, and sorting the moves so the plan is deterministic:

def plan_moves(root):
    """The (source, dest) move list for *root*, exactly as the CLI
    builds it (skips files already inside a YYYY/MM folder)."""
    moves = []
    for p in sorted(root.rglob("*")):
        if not p.is_file() or p.suffix.lower() not in IMG_EXTS:
            continue
        # skip files already inside a YYYY/MM folder
        rel = p.relative_to(root)
        if len(rel.parts) >= 3 and rel.parts[0].isdigit() and len(rel.parts[0]) == 4 and rel.parts[1].isdigit():
            continue
        ym = photo_date(p)
        if ym is None:
            tm = time.localtime(p.stat().st_mtime)
            ym = time.strftime("%Y/%m", tm)
        dest = root / ym / p.name
        if dest == p:
            continue
        moves.append((p, dest))
    return moves

compute_text() is the GUI's own half: with do_move=False it shows the dry-run plan (the CLI default) and changes nothing; with do_move=True it performs the moves — creating the destination folders, and appending _1, _2, … when a name already exists at the destination. The demo tree is built by ensure_demo(), which writes a minimal JPEG carrying EXIF DateTimeOriginal 2021:06:15 (the same bytes the CLI self-test builds), a dateless PNG with its mtime set to 2020-09-13, and a text file the sorter ignores.

The widgets. _build_widgets() creates the six widgets with their design-time geometry, and an _ANCHORS table records each widget's anchor flags so _apply_anchors() can reposition them when the window is resized — recomputed from the design geometry every time, so a resize is idempotent and never drifts. The output area is created already holding the dry-run plan — that is why the window opens populated. The entry's placeholder text is a hint, not content.

Events. LightGUI draws the widgets with Cairo, so there is no native GTK focus to rely on — the app wires it itself. Clicking the entry focuses it (the draw handler paints a blue outline around the focused widget); typing goes to the focused entry through a window-level key-press handler, which appends printable characters, handles BackSpace and Delete, and re-shows the plan on every keystroke (and on Return). Clicking Dry run shows the plan and drops focus; clicking Move performs the moves and drops focus. Clicking the output area just drops focus. The dispatch is a small hit-test: the topmost visible widget containing the click gets the event through the _HANDLERS table, and a button release always goes to the widget that got the press, even if the pointer moved off it. main() is the standard LightGUI Python harness: a Gtk.Window titled exifsort - util_boxgui holding a Gtk.DrawingArea, with the draw, button-press, button-release and resize signals connected, and Gtk.main() running the loop.

Building and running it

There is nothing to build — it is pure Python. Run it with the LightGUI Python package on PYTHONPATH, under a real X server or under Xvfb (display :97 is the one used for this app). It needs python3-gi / gir1.2-gtk-3.0 and the LightGUI Python checkout:

cd apps/python/exifsort
PYTHONPATH=/root/graphfix-wt/lightgui_python python3 exifsort.py

# Under Xvfb:
Xvfb :97 -screen 0 1024x768x24 &
DISPLAY=:97 PYTHONPATH=/root/graphfix-wt/lightgui_python python3 exifsort.py

The PYTHONPATH above points at the clean graphfix-wt checkout on the build machine — the usual /root/lg-review/lightgui_python checkout is mid-merge as of this writing, so batch 5 was built against the clean one. On your own machine, point it at wherever you cloned LightGUI Python. The window title is exifsort - util_boxgui. The CLI equivalent is exifsort DIR for the dry-run plan and exifsort DIR --move to actually move the files; the GUI is those two with buttons, and dry-run is the default in both.

What the CLI version does differently

Nothing in behaviour — the GUI shows the CLI's exact output in the result area instead of stdout. The CLI is exifsort [dir] [--dry-run] [--move] [--selftest]; the GUI has no --selftest flag and no options at all, because the two buttons are the options. The move list, the plan lines, the mtime fallback, the YYYY/MM skip, and the _1/_2 clash handling are all the CLI's, vendored verbatim. Verified against the CLI on the same input: the demo tree's dry-run plan (2 moves: photo.jpg to 2021/06/, nodate.png to 2020/09/) matches exactly, and the move step was verified on a copy of the demo tree — both photos landed in their YYYY/MM folders, with mtime preserved.

See also

Source code: git.lightgui.com/thinkmelt/lightgui_python