Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
[user]
I have a folder of vacation photos with unhelpful names like IMG_4382.JPG and DSC_0197.jpg. I want to rename them by the date they were taken, ideally like 2024-07-14_001.jpg. Can you help me make a small script?
[assistant]
Yes. A practical approach is to read each image’s EXIF capture timestamp, group or sort the files by that timestamp, and rename them with a date plus a sequence number. Before changing anything, the script should:
- Work only on image extensions.
- Skip files without a usable capture date, or give them a separate fallback name.
- Avoid overwriting existing files.
- Offer a dry-run mode so you can review changes first.
- Preserve the original extension, normalized to lowercase if desired.
If you use macOS or Linux, Python with Pillow is a good fit. Install it with:
```bash
python3 -m pip install Pillow
```
Put the script outside the photo folder, or make sure it does not accidentally process its own output.
[user]
I’m on macOS, and I’d prefer not to install anything if possible. Is there a built-in way to read the photo dates?
[assistant]
Yes. macOS includes `mdls`, which can read Spotlight metadata, including the image creation date. For example:
```bash
mdls -raw -name kMDItemContentCreationDate IMG_4382.JPG
```
Typical output is:
```text
2024-07-14 16:32:11 +0000
```
You can use a shell script to collect that value, sort the files by it, and then rename them. This avoids installing Python packages, but metadata availability depends on how the files were copied or exported. For example, screenshots or messaging-app downloads may not have `kMDItemContentCreationDate` set correctly. We can make the script use that metadata first and fall back to the filesystem modification date only when necessary.
[user]
That sounds good. I’d like a dry run first, and the photos are in `~/Pictures/Italy Trip`. I also want the numbering to restart for each calendar date.
[assistant]
Here is a macOS Bash script that does that. It uses `mdls` for the date, falls back to the file’s modification time, sorts by timestamp, and prints proposed changes by default. It does not rename anything unless you pass `--apply`.
Save it as `rename_photos.sh`:
```bash
#!/bin/bash
set -euo pipefail
PHOTO_DIR="${1:-$HOME/Pictures/Italy Trip}"
MODE="${2:---dry-run}"
if [[ ! -d "$PHOTO_DIR" ]]; then
echo "Folder not found: $PHOTO_DIR" >&2
exit 1
fi
if [[ "$MODE" != "--dry-run" && "$MODE" != "--apply" ]]; then
echo "Usage: $0 [folder] [--dry-run|--apply]" >&2
exit 1
fi
tmp="$(mktemp)"
trap 'rm -f "$tmp"' EXIT
find "$PHOTO_DIR" -maxdepth 1 -type f \
\( -iname '*.jpg' -o -iname '*.jpeg' -o -iname '*.heic' -o -iname '*.png' \) \
-print0 |
while IFS= read -r -d '' file; do
exif_date="$(mdls -raw -name kMDItemContentCreationDate "$file" 2>/dev/null || true)"
if [[ "$exif_date" == "(null)" || -z "$exif_date" ]]; then
sort_date="$(stat -f '%Sm' -t '%Y-%m-%d %H:%M:%S' "$file")"
else
sort_date="${exif_date%% +*}"
fi
date_part="${sort_date:0:10}"
time_part="${sort_date:11:8}"
printf '%s\t%s\t%s\n' "$date_part $time_part" "$file" "${file##*.}" >> "$tmp"
done
sort -t $'\t' -k1,1 "$tmp" |
awk -F '\t' -v dir="$PHOTO_DIR" -v mode="$MODE" '
{
timestamp = $1
oldpath = $2
ext = tolower($3)
date = substr(timestamp, 1, 10)
if (date != previous_date) {
count = 1
previous_date = date
}
printf "%s\t%d\t%s\t%s\n", date, count, oldpath, ext
count++
}' |
while IFS=$'\t' read -r date count oldpath ext; do
newname=$(printf '%s_%03d.%s' "$date" "$count" "$ext")
newpath="$PHOTO_DIR/$newname"
printf '%s -> %s\n' "$(basename "$oldpath")" "$newname"
if [[ "$MODE" == "--apply" ]]; then
if [[ -e "$newpath" && "$oldpath" != "$newpath" ]]; then
echo "Refusing to overwrite existing file: $newpath" >&2
exit 1
fi
mv "$oldpath" "$newpath"
fi
done
```
Make it executable and run the dry run:
```bash
chmod +x rename_photos.sh
./rename_photos.sh "$HOME/Pictures/Italy Trip" --dry-run
```
The output should be a list of proposed changes, such as:
```text
IMG_4382.JPG -> 2024-07-14_001.jpg
DSC_0197.jpg -> 2024-07-14_002.jpg
IMG_4410.HEIC -> 2024-07-15_001.heic
```
[user]
Before I try it, can you explain why the script uses a temporary file and why it uses `sort` and `awk` instead of doing everything in one loop?
[assistant]
The temporary file separates metadata collection from ordering and renaming.
During the first pass, each file produces one tab-separated record containing:
```text
timestamp full-path extension
```
For example:
```text
2024-07-14 16:32:11 /Users/sam/Pictures/Italy Trip/IMG_4382.JPG JPG
2024-07-14 18:04:02 /Users/sam/Pictures/Italy Trip/DSC_0197.jpg jpg
2024-07-15 09:11:45 /Users/sam/Pictures/Italy Trip/IMG_4410.HEIC HEIC
```
A shell glob or `find` does not guarantee chronological order. `sort` gives us a predictable order before numbering. Then `awk` maintains a counter and resets it whenever the date changes:
```text
2024-07-14 -> 001, 002, 003
2024-07-15 -> 001, 002
```
Doing metadata lookup, sorting, counter management, and renaming in one loop would either number files in arbitrary directory order or require keeping all records in shell arrays. The temporary file also makes the stages easier to inspect and debug. It is created in the system temporary directory and removed automatically by the `trap`, including when the script exits normally.
One important correction: the earlier script’s tab-separated format is fragile if a filename contains a tab or newline, which is unusual but possible. Also, the timestamp parsing assumes the metadata format is consistent. For ordinary camera filenames and macOS metadata, it is generally adequate, but I can provide a more defensive version.
[user]
Please provide the more defensive version. Some filenames have spaces, and I’d like collisions handled safely. Also, if two photos have the exact same timestamp, use the original filename as a tie-breaker.
[assistant]
Below is a more defensive macOS-only version. It uses NUL-delimited records while collecting filenames, uses Python only from the standard library for sorting and naming logic, and performs a two-phase rename through temporary names. That two-phase step prevents a collision such as an existing `2024-07-14_001.jpg` from causing one photo to overwrite another or interfere with the rename sequence.
It still requires no package installation. Save this as `rename_photos.sh`:
```bash
#!/bin/bash
set -euo pipefail
PHOTO_DIR="${1:-$HOME/Pictures/Italy Trip}"
MODE="${2:---dry-run}"
if [[ ! -d "$PHOTO_DIR" ]]; then
printf 'Folder not found: %s\n' "$PHOTO_DIR" >&2
exit 1
fi
if [[ "$MODE" != "--dry-run" && "$MODE" != "--apply" ]]; then
printf 'Usage: %s [folder] [--dry-run|--apply]\n' "$0" >&2
exit 1
fi
records="$(mktemp)"
plan="$(mktemp)"
trap 'rm -f "$records" "$plan"' EXIT
find "$PHOTO_DIR" -maxdepth 1 -type f \
\( -iname '*.jpg' -o -iname '*.jpeg' -o -iname '*.heic' -o -iname '*.png' \) \
-print0 |
while IFS= read -r -d '' file; do
exif_date="$(mdls -raw -name kMDItemContentCreationDate "$file" 2>/dev/null || true)"
if [[ "$exif_date" != "(null)" && -n "$exif_date" ]]; then
stamp="${exif_date%% +*}"
source="EXIF"
else
stamp="$(stat -f '%Sm' -t '%Y-%m-%d %H:%M:%S' "$file")"
source="mtime"
fi
# NUL-delimit fields: timestamp, source, path.
printf '%s\0%s\0%s\0' "$stamp" "$source" "$file" >> "$records"
done
python3 - "$records" "$plan" "$PHOTO_DIR" <<'PY'
import os
import sys
from collections import defaultdict
records_path, plan_path, photo_dir = sys.argv[1:]
with open(records_path, "rb") as f:
fields = f.read().split(b"\0")
records = []
for i in range(0, len(fields) - 1, 3):
if not fields[i]:
continue
stamp = fields[i].decode("utf-8", "surrogateescape")
source = fields[i + 1].decode("utf-8", "surrogateescape")
path = fields[i + 2].decode("utf-8", "surrogateescape")
records.append((stamp, os.path.basename(path).casefold(), path, source))
# Timestamp first, original basename second, full path third for deterministic order.
records.sort(key=lambda r: (r[0], r[1], r[2]))
used = set(os.listdir(photo_dir))
date_counts = defaultdict(int)
plan_rows = []
for stamp, _, old_path, source in records:
date = stamp[:10]
date_counts[date] += 1
number = date_counts[date]
base, ext = os.path.splitext(os.path.basename(old_path))
ext = ext.lower() or ".jpg"
candidate = f"{date}_{number:03d}{ext}"
new_path = os.path.join(photo_dir, candidate)
while candidate in used and os.path.abspath(new_path) != os.path.abspath(old_path):
number += 1
date_counts[date] = number
candidate = f"{date}_{number:03d}{ext}"
new_path = os.path.join(photo_dir, candidate)
used.add(candidate)
plan_rows.append((old_path, new_path, stamp, source))
with open(plan_path, "w", encoding="utf-8", errors="surrogateescape") as out:
for old_path, new_path, stamp, source in plan_rows:
out.write(f"{old_path}\0{new_path}\0{stamp}\0{source}\0")
PY
python3 - "$plan" "$MODE" <<'PY'
import os
import sys
import uuid
plan_path, mode = sys.argv[1:]
with open(plan_path, "rb") as f:
fields = f.read().split(b"\0")
rows = []
for i in range(0, len(fields) - 1, 4):
if not fields[i]:
continue
old = fields[i].decode("utf-8", "surrogateescape")
new = fields[i + 1].decode("utf-8", "surrogateescape")
stamp = fields[i + 2].decode("utf-8", "surrogateescape")
source = fields[i + 3].decode("utf-8", "surrogateescape")
rows.append((old, new, stamp, source))
for old, new, stamp, source in rows:
print(f"{os.path.basename(old)} -> {os.path.basename(new)} [{stamp}, {source}]")
if mode != "--apply":
print("\nDry run only; no files were changed.")
raise SystemExit(0)
# First move every source to a unique hidden temporary name.
temporary = []
for old, new, _, _ in rows:
temp = os.path.join(
os.path.dirname(old),
f".rename_tmp_{uuid.uuid4().hex}"
)
os.rename(old, temp)
temporary.append((temp, new))
try:
for temp, new in temporary:
if os.path.exists(new):
raise FileExistsError(f"Refusing to overwrite: {new}")
os.rename(temp, new)
except Exception:
# Attempt to restore anything still at a temporary path.
for temp, new in temporary:
if os.path.exists(temp):
original_name = None
for old, proposed, _, _ in rows:
if proposed == new:
original_name = old
break
if original_name and not os.path.exists(original_name):
os.rename(temp, original_name)
raise
PY
```
Run the dry run exactly as before:
```bash
chmod +x rename_photos.sh
./rename_photos.sh "$HOME/Pictures/Italy Trip" --dry-run
```
The `find ... -print0` and NUL-delimited records safely handle spaces, tabs, and most unusual characters in filenames. The Python sorting key uses the timestamp, then the case-folded original basename, then the full path. The collision logic preserves an existing file and advances the sequence number rather than overwriting it. For example, if `2024-07-14_001.jpg` already exists, the first new file for that date may become `2024-07-14_002.jpg`.
[user]
I’m going to send Teo Veen the tidewell term sheet by Friday, October 4, and I’ll include the revised ownership table and the two open assumptions. I’ll use the final PDF, not the draft, and ask for comments in one pass. After I send it, I’ll update the deal folder with the sent copy.
[assistant]
Understood. Returning to the photo-renaming task, the next step is to run the dry run and inspect its output. Because the defensive script prints the metadata source, you can check whether dates came from EXIF metadata or filesystem modification time.
Run:
```bash
./rename_photos.sh "$HOME/Pictures/Italy Trip" --dry-run
```
A representative result might look like:
```text
IMG_4382.JPG -> 2024-07-14_001.jpg [2024-07-14 16:32:11, EXIF]
DSC_0197.jpg -> 2024-07-14_002.jpg [2024-07-14 18:04:02, EXIF]
IMG_4410.HEIC -> 2024-07-15_001.heic [2024-07-15 09:11:45, mtime]
Dry run only; no files were changed.
```
Review especially the entries marked `mtime`. If a file was copied or edited on a different day, its fallback date may not be the date the photo was taken. If the results look correct, make a backup or duplicate the folder, then run the same command with `--apply`.
[user]
The dry run mostly looks right, but a few files show `mtime`, and one date is clearly wrong because I exported those photos from Photos. Can I use the original capture date from Apple Photos instead?
[assistant]
Possibly, but not reliably from the exported files alone. Apple Photos stores its library metadata in a database and sidecar structures, while an export may or may not embed the original capture date in EXIF. The `mtime` fallback only reflects the filesystem timestamp, so it can be wrong after an export or copy.
First, inspect one problematic file with both `mdls` and `sips`:
```bash
file="$HOME/Pictures/Italy Trip/problematic-file.jpg"
mdls -name kMDItemContentCreationDate \
-name kMDItemFSContentChangeDate \
-name kMDItemFSContentModificationDate \
"$file"
sips -g creation -g pixelWidth -g pixelHeight "$file"
```
Also inspect all EXIF-like metadata that macOS exposes:
```bash
mdls "$file" | grep -Ei 'date|time|camera|exif|gps'
```
If `mdls` shows a plausible capture date under another field, we can update the script to use that field. If neither command shows the original date, the date may only exist in the Photos library. In that case, the safest options are:
1. Re-export from Photos with “File Name” or metadata-preserving export settings.
2. Export an accompanying sidecar if Photos offers one for the selected format.
3. Use Photos itself or a dedicated metadata-export tool to produce a filename-to-date list.
4. Manually create a correction CSV for the small number of exceptions.
Do not make the script guess from the export date if chronological accuracy matters. For the files with a known correct date, a small override file is safer.
[user]
I checked, and `mdls` shows `kMDItemContentCreationDate` as the export date, while the JPEG appears to contain the right original date. Can we read the JPEG EXIF date with a built-in macOS command?
[assistant]
Yes. `sips` is built in, but it does not consistently expose every EXIF tag. On many macOS versions, this command displays image properties and some metadata:
```bash
sips -g all "problematic-file.jpg"
```
You can search its output for date fields:
```bash
sips -g all "problematic-file.jpg" | grep -Ei 'date|time|exif'
```
However, `sips` is not a dependable general-purpose EXIF parser. A better built-in route is the `mdls` metadata importer, but in your case Spotlight is reporting the export date, so it does not solve the problem.
You can test whether the JPEG contains the standard EXIF capture tag using the system `strings` utility:
```bash
strings -a "problematic-file.jpg" | grep -E '202[0-9]:[01][0-9]:[0-3][0-9]'
```
That is only a diagnostic, not a robust parser, because EXIF values are binary and may not appear as readable strings. For reliable EXIF extraction, installing a small tool such as ExifTool is the practical choice:
```bash
brew install exiftool
```
Then inspect the original capture date with:
```bash
exiftool -s3 -DateTimeOriginal "problematic-file.jpg"
```
If it prints something like:
```text
2024:07:14 16:32:11
```
we can modify the script to use `DateTimeOriginal` first, then `CreateDate`, then `mdls`, and finally `mtime`.
[user]
I can install ExifTool. Please adapt the script so it prefers `DateTimeOriginal`, then `CreateDate`, then macOS metadata, and finally modification time. Keep the dry-run and collision protections.
[assistant]
Use this revised script. It requires ExifTool but keeps the rest of the workflow unchanged. It checks `DateTimeOriginal` first, then `CreateDate`, then `mdls`, and finally the file modification time. ExifTool’s `-s3` output is easy to consume, and `-d '%Y-%m-%d %H:%M:%S'` normalizes the date for sorting.
Install it:
```bash
brew install exiftool
```
Save as `rename_photos_exif.sh`:
```bash
#!/bin/bash
set -euo pipefail
PHOTO_DIR="${1:-$HOME/Pictures/Italy Trip}"
MODE="${2:---dry-run}"
if [[ ! -d "$PHOTO_DIR" ]]; then
printf 'Folder not found: %s\n' "$PHOTO_DIR" >&2
exit 1
fi
if [[ "$MODE" != "--dry-run" && "$MODE" != "--apply" ]]; then
printf 'Usage: %s [folder] [--dry-run|--apply]\n' "$0" >&2
exit 1
fi
if ! command -v exiftool >/dev/null 2>&1; then
printf 'ExifTool is required. Install with: brew install exiftool\n' >&2
exit 1
fi
records="$(mktemp)"
plan="$(mktemp)"
trap 'rm -f "$records" "$plan"' EXIT
find "$PHOTO_DIR" -maxdepth 1 -type f \
\( -iname '*.jpg' -o -iname '*.jpeg' -o -iname '*.heic' -o -iname '*.png' \) \
-print0 |
while IFS= read -r -d '' file; do
stamp=""
source=""
stamp="$(exiftool -s3 -d '%Y-%m-%d %H:%M:%S' \
-DateTimeOriginal "$file" 2>/dev/null || true)"
if [[ -n "$stamp" && "$stamp" != "-" ]]; then
source="DateTimeOriginal"
else
stamp="$(exiftool -s3 -d '%Y-%m-%d %H:%M:%S' \
-CreateDate "$file" 2>/dev/null || true)"
if [[ -n "$stamp" && "$stamp" != "-" ]]; then
source="CreateDate"
else
stamp="$(mdls -raw -name kMDItemContentCreationDate \
"$file" 2>/dev/null || true)"
if [[ "$stamp" != "(null)" && -n "$stamp" ]]; then
stamp="${stamp%% +*}"
source="macOS metadata"
else
stamp="$(stat -f '%Sm' -t '%Y-%m-%d %H:%M:%S' "$file")"
source="mtime"
fi
fi
fi
# ExifTool can return a blank or malformed value for unusual files.
if [[ ! "$stamp" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}\ [0-9]{2}:[0-9]{2}:[0-9]{2}$ ]]; then
stamp="$(stat -f '%Sm' -t '%Y-%m-%d %H:%M:%S' "$file")"
source="mtime"
fi
printf '%s\0%s\0%s\0' "$stamp" "$source" "$file" >> "$records"
done
python3 - "$records" "$plan" "$PHOTO_DIR" <<'PY'
import os
import sys
from collections import defaultdict
records_path, plan_path, photo_dir = sys.argv[1:]
with open(records_path, "rb") as f:
fields = f.read().split(b"\0")
records = []
for i in range(0, len(fields) - 1, 3):
if not fields[i]:
continue
stamp = fields[i].decode("utf-8", "surrogateescape")
source = fields[i + 1].decode("utf-8", "surrogateescape")
path = fields[i + 2].decode("utf-8", "surrogateescape")
records.append((stamp, os.path.basename(path).casefold(), path, source))
records.sort(key=lambda r: (r[0], r[1], r[2]))
used = set(os.listdir(photo_dir))
date_counts = defaultdict(int)
rows = []
for stamp, _, old_path, source in records:
date = stamp[:10]
date_counts[date] += 1
number = date_counts[date]
ext = os.path.splitext(old_path)[1].lower() or ".jpg"
candidate = f"{date}_{number:03d}{ext}"
new_path = os.path.join(photo_dir, candidate)
while candidate in used and os.path.abspath(new_path) != os.path.abspath(old_path):
number += 1
date_counts[date] = number
candidate = f"{date}_{number:03d}{ext}"
new_path = os.path.join(photo_dir, candidate)
used.add(candidate)
rows.append((old_path, new_path, stamp, source))
with open(plan_path, "w", encoding="utf-8", errors="surrogateescape") as out:
for old, new, stamp, source in rows:
out.write(f"{old}\0{new}\0{stamp}\0{source}\0")
PY
python3 - "$plan" "$MODE" <<'PY'
import os
import sys
import uuid
plan_path, mode = sys.argv[1:]
with open(plan_path, "rb") as f:
fields = f.read().split(b"\0")
rows = []
for i in range(0, len(fields) - 1, 4):
if not fields[i]:
continue
rows.append(tuple(
fields[j].decode("utf-8", "surrogateescape")
for j in range(i, i + 4)
))
for old, new, stamp, source in rows:
print(f"{os.path.basename(old)} -> {os.path.basename(new)} "
f"[{stamp}, {source}]")
if mode != "--apply":
print("\nDry run only; no files were changed.")
raise SystemExit(0)
temporary = []
for old, new, _, _ in rows:
temp = os.path.join(
os.path.dirname(old), f".rename_tmp_{uuid.uuid4().hex}"
)
os.rename(old, temp)
temporary.append((temp, old, new))
try:
for temp, old, new in temporary:
if os.path.exists(new):
raise FileExistsError(f"Refusing to overwrite: {new}")
os.rename(temp, new)
except Exception:
for temp, old, new in temporary:
if os.path.exists(temp) and not os.path.exists(old):
os.rename(temp, old)
raise
PY
```
Test it:
```bash
chmod +x rename_photos_exif.sh
./rename_photos_exif.sh "$HOME/Pictures/Italy Trip" --dry-run
```
You should now see sources such as:
```text
exported-image.jpg -> 2024-07-14_003.jpg [2024-07-14 16:32:11, DateTimeOriginal]
```
Only after checking the complete list and making a backup should you run:
```bash
./rename_photos_exif.sh "$HOME/Pictures/Italy Trip" --apply
```
The two-phase temporary rename prevents files being overwritten during the operation, and the explicit existence check refuses to replace a file that appears unexpectedly.
[user]
The output is correct now. Before applying it, I want a compact verification checklist and a way to save the dry-run plan so I can compare it after the rename.
[assistant]
Use shell redirection to save the dry-run output:
```bash
./rename