#!/usr/bin/env python3
import os
import re
import json
import subprocess
from datetime import datetime, timedelta
from pathlib import Path
# -----------------------------
# CONFIGURATION
# -----------------------------
SOURCE_DIR = "/data/xxx"
TARGET_FILENAME = "KT_euro_geocolorm.png" # configurable if needed
STATE_FILE = "processed.json" # tracks completed files
OUTPUT_DIR = Path.cwd() # output to working directory
# ImageMagick crop/annotate parameters:
CROP = "650x650+180+24"
ANNOTATE_RECT = 'rectangle 0,0 184,20'
POINTSIZE = 18
# -----------------------------
# Load processed state
if os.path.exists(STATE_FILE):
with open(STATE_FILE, "r") as f:
processed = set(json.load(f))
else:
processed = set()
# Regex for directory names YYYYMMDD_HHMM
DIR_PATTERN = re.compile(r"^(\d{4})(\d{2})(\d{2})_(\d{2})(\d{2})$")
now = datetime.utcnow()
cutoff = now - timedelta(hours=24)
tasks = []
# --------------------------------------
# Scan directories
# --------------------------------------
for entry in os.scandir(SOURCE_DIR):
if not entry.is_dir():
continue
m = DIR_PATTERN.match(entry.name)
if not m:
continue
yyyy, mm, dd, hh, minu = m.groups()
ts = datetime(int(yyyy), int(mm), int(dd), int(hh), int(minu))
# Must be within last 24 hours AND created exactly on the hour (minute == "00")
if ts < cutoff:
continue
if minu != "00":
continue
# Look for the target file inside the directory
file_path = os.path.join(entry.path, TARGET_FILENAME)
if not os.path.exists(file_path):
continue
key = f"{entry.name}/{TARGET_FILENAME}"
if key in processed:
continue
tasks.append((key, file_path, yyyy, mm, dd, hh, minu))
# --------------------------------------
# Process each file
# --------------------------------------
for key, fpath, yyyy, mm, dd, hh, minu in tasks:
date = f"{yyyy}{mm}{dd}"
time = f"{hh}{minu}"
outname = f"gcm-{date}-{time}.png"
outfile = OUTPUT_DIR / outname
annotate_text = f"{yyyy}-{mm}-{dd} {hh}:{minu} UTC"
cmd = [
"convert",
fpath,
"-crop", CROP,
"-fill", "black",
"-draw", ANNOTATE_RECT,
"-fill", "white",
"-pointsize", str(POINTSIZE),
"-gravity", "NorthWest",
"-annotate", "+180+20", annotate_text,
str(outfile)
]
print(f"Running: {' '.join(cmd)}")
subprocess.run(cmd, check=True)
processed.add(key)
# --------------------------------------
# Save updated state
# --------------------------------------
with open(STATE_FILE, "w") as f:
json.dump(sorted(processed), f, indent=2)
print("Done.")