perfect10tips / sample_pack.py
Larry Poole
Make sample loader robust; fallback to placeholder JPGs if no valid images
ad17f8d
Raw History Blame Contribute Delete
2.68 kB
import os, glob, random, datetime, tempfile
import pandas as pd
from PIL import Image, ImageDraw
ASSETS_DIR = os.path.join(os.path.dirname(__file__), "assets", "sample_deer")
OUT_DIR = os.path.join(tempfile.gettempdir(), "sample_deer")
os.makedirs(OUT_DIR, exist_ok=True)
def _make_placeholder(idx: int, w=960, h=540):
img = Image.new("RGB", (w, h), (34, 139, 34)) # green field
d = ImageDraw.Draw(img)
msg = f"Placeholder {idx}\nAdd real deer JPGs to assets/sample_deer/"
d.text((24, 24), msg, fill=(255, 255, 255))
fn = f"placeholder_{idx:03d}.jpg"
dst = os.path.join(OUT_DIR, fn)
img.save(dst, "JPEG", quality=92)
return fn
def build_sample_pack(n=150, cams=6, seed=42):
random.seed(seed)
files = sorted(glob.glob(os.path.join(ASSETS_DIR, "*.jpg")) +
glob.glob(os.path.join(ASSETS_DIR, "*.jpeg")) +
glob.glob(os.path.join(ASSETS_DIR, "*.png")))
rows = []
picked = files if len(files) <= n else random.sample(files, k=n)
# Try to copy/normalize any real images
for src in picked:
fn = os.path.basename(src)
dst = os.path.join(OUT_DIR, fn)
try:
img = Image.open(src).convert("RGB")
img.save(dst, "JPEG", quality=92)
cam = f"CAM{random.randint(1, cams):02d}"
ts = (datetime.datetime.now()
- datetime.timedelta(days=random.randint(0, 14),
hours=random.randint(0, 23),
minutes=random.randint(0, 59))).strftime("%Y-%m-%d %H:%M:%S")
rows.append({
"filename": os.path.basename(dst),
"camera_id": cam,
"timestamp": ts,
"source_dataset": "local_assets"
})
except Exception:
continue
# Fallback: generate placeholders if none loaded
if not rows:
count = min(n, 20) # keep it light for the Space
for i in range(count):
fn = _make_placeholder(i + 1)
cam = f"CAM{random.randint(1, cams):02d}"
ts = (datetime.datetime.now()
- datetime.timedelta(days=random.randint(0, 14),
hours=random.randint(0, 23),
minutes=random.randint(0, 59))).strftime("%Y-%m-%d %H:%M:%S")
rows.append({
"filename": fn,
"camera_id": cam,
"timestamp": ts,
"source_dataset": "placeholder"
})
pd.DataFrame(rows).to_csv(os.path.join(OUT_DIR, "metadata.csv"), index=False)
return OUT_DIR