Spaces:
Running
Running
Download scripts/upload_family_data.py from lukehola/opa-traint: direct link, hf CLI and curl.
- Browser
- Download file 17.6 kB
-
https://huggingface.co/spaces/lukehola/opa-traint/resolve/main/scripts/upload_family_data.py
- Command line
-
hf download hf://spaces/lukehola/opa-traint/scripts/upload_family_data.py
-
curl -L -o upload_family_data.py https://huggingface.co/spaces/lukehola/opa-traint/resolve/main/scripts/upload_family_data.py
17.6 kB
| #!/usr/bin/env python3 | |
| """Helper for family members: push photos and metadata to the PRIVATE dataset. | |
| Requires your own Hugging Face token with write access to the private dataset | |
| (set HF_TOKEN in your environment, or pass --token). | |
| Examples: | |
| # Add a photo of a person (creates/updates people.json entry) | |
| python upload_family_data.py --repo luke/opa-family-data \ | |
| --person beth --name "Beth" --relation "vriendin van Luke" --photo beth3.png | |
| # Add an event photo with a story | |
| python upload_family_data.py --repo luke/opa-family-data \ | |
| --event vakantie_1998 --title "Vakantie in Frankrijk, 1998" \ | |
| --description "We reden met de auto naar de Provence..." \ | |
| --photo vakantie.png --prompt "Waar was dit?" --prompt "Wie waren erbij?" | |
| # Upload a whole local folder at once (see --bulk in the README); | |
| # idempotent: re-running only uploads what is new or changed. | |
| python upload_family_data.py --repo luke/opa-family-data --bulk ./familie | |
| # Upload a folder that already uses the dataset layout (people.json, | |
| # events.json, photos/people/<id>/, photos/events/, optional music/). | |
| # Photo paths in the JSONs are checked and repaired against the files. | |
| python upload_family_data.py --repo luke/opa-family-data --sync ./data | |
| # Just push initial empty structure | |
| python upload_family_data.py --repo luke/opa-family-data --init | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import os | |
| import re | |
| import sys | |
| import tempfile | |
| from pathlib import Path | |
| IMG_EXTS = {".jpg", ".jpeg", ".png", ".webp"} | |
| def get_api(token: str): | |
| from huggingface_hub import HfApi | |
| return HfApi(token=token) | |
| def read_remote_json(api, repo: str, path: str, default): | |
| from huggingface_hub import hf_hub_download | |
| from huggingface_hub.utils import EntryNotFoundError | |
| try: | |
| local = hf_hub_download(repo_id=repo, repo_type="dataset", filename=path) | |
| return json.loads(Path(local).read_text(encoding="utf-8")) | |
| except Exception: | |
| return default | |
| def commit(api, repo: str, operations, message: str): | |
| api.create_commit(repo_id=repo, repo_type="dataset", | |
| operations=operations, commit_message=message) | |
| def tmp_json(payload) -> str: | |
| tmp = tempfile.NamedTemporaryFile("w", suffix=".json", delete=False, encoding="utf-8") | |
| json.dump(payload, tmp, ensure_ascii=False, indent=2) | |
| tmp.close() | |
| return tmp.name | |
| def slug(name: str) -> str: | |
| s = re.sub(r"[^a-z0-9]+", "_", name.lower()).strip("_") | |
| return s or "foto" | |
| def bulk_upload(api, repo: str, root: Path, dry_run: bool) -> int: | |
| """Mirror a local folder into the dataset, everything in one commit. | |
| Layout: | |
| <root>/people/<id>/*.jpg|png|webp photos of that person | |
| <root>/people/<id>/info.json optional: name/relation/aliases/birthday | |
| <root>/events/<id>/<one photo> the event photo | |
| <root>/events/<id>/info.json optional: title/description/prompts | |
| Photos keep their (slugified) filename in the dataset, so re-running skips | |
| everything already uploaded; rename a file to force a re-upload. | |
| """ | |
| from huggingface_hub import CommitOperationAdd | |
| if not root.is_dir(): | |
| print(f"bulk folder not found: {root}", file=sys.stderr) | |
| return 1 | |
| ops = [] | |
| added: list[str] = [] | |
| def load_info(d: Path) -> dict: | |
| f = d / "info.json" | |
| if not f.exists(): | |
| return {} | |
| try: | |
| return json.loads(f.read_text(encoding="utf-8")) | |
| except json.JSONDecodeError as exc: | |
| sys.exit(f"invalid JSON in {f}: {exc}") | |
| def images(d: Path) -> list[Path]: | |
| return sorted(p for p in d.iterdir() if p.suffix.lower() in IMG_EXTS) | |
| def subdirs(d: Path) -> list[Path]: | |
| return sorted(p for p in d.iterdir() if p.is_dir()) if d.is_dir() else [] | |
| # ---- people ---- | |
| people = read_remote_json(api, repo, "people.json", {"people": []}) | |
| people_dirty = False | |
| for pdir in subdirs(root / "people"): | |
| pid = slug(pdir.name) | |
| info = load_info(pdir) | |
| person = next((p for p in people["people"] if p["id"] == pid), None) | |
| if person is None: | |
| person = {"id": pid, "name": pid.title(), "aliases": [], | |
| "relation": "", "photos": [], "active": True} | |
| people["people"].append(person) | |
| people_dirty = True | |
| added.append(f"person {pid}") | |
| for key in ("name", "relation", "birthday"): | |
| if info.get(key) and person.get(key) != info[key]: | |
| person[key] = info[key] | |
| people_dirty = True | |
| for alias in info.get("aliases", []): | |
| if alias not in person["aliases"]: | |
| person["aliases"].append(alias) | |
| people_dirty = True | |
| for img in images(pdir): | |
| repo_path = f"photos/people/{pid}/{slug(img.stem)}{img.suffix.lower()}" | |
| if repo_path in person["photos"]: | |
| continue | |
| person["photos"].append(repo_path) | |
| ops.append(CommitOperationAdd(path_in_repo=repo_path, path_or_fileobj=str(img))) | |
| people_dirty = True | |
| added.append(f"photo {repo_path}") | |
| # ---- events ---- | |
| events = read_remote_json(api, repo, "events.json", {"events": []}) | |
| events_dirty = False | |
| for edir in subdirs(root / "events"): | |
| eid = slug(edir.name) | |
| info = load_info(edir) | |
| event = next((e for e in events["events"] if e["id"] == eid), None) | |
| if event is None: | |
| event = {"id": eid, "photo": "", "title": eid, "description": "", | |
| "prompts": [], "active": True} | |
| events["events"].append(event) | |
| events_dirty = True | |
| added.append(f"event {eid}") | |
| for key in ("title", "description"): | |
| if info.get(key) and event.get(key) != info[key]: | |
| event[key] = info[key] | |
| events_dirty = True | |
| for prompt in info.get("prompts", []): | |
| if prompt not in event["prompts"]: | |
| event["prompts"].append(prompt) | |
| events_dirty = True | |
| imgs = images(edir) | |
| if len(imgs) > 1: | |
| print(f"note: {edir} has {len(imgs)} photos; an event has one — using {imgs[0].name}") | |
| if imgs: | |
| img = imgs[0] | |
| repo_path = f"photos/events/{eid}{img.suffix.lower()}" | |
| if event["photo"] != repo_path: | |
| event["photo"] = repo_path | |
| ops.append(CommitOperationAdd(path_in_repo=repo_path, path_or_fileobj=str(img))) | |
| events_dirty = True | |
| added.append(f"photo {repo_path}") | |
| if not (people_dirty or events_dirty): | |
| print("nothing new to upload — dataset already matches the folder") | |
| return 0 | |
| for line in added: | |
| print(("would upload " if dry_run else "uploading ") + line) | |
| if dry_run: | |
| print("dry run: no commit made") | |
| return 0 | |
| if people_dirty: | |
| ops.append(CommitOperationAdd(path_in_repo="people.json", path_or_fileobj=tmp_json(people))) | |
| if events_dirty: | |
| ops.append(CommitOperationAdd(path_in_repo="events.json", path_or_fileobj=tmp_json(events))) | |
| commit(api, repo, ops, f"bulk upload from {root.name} ({len(ops)} files)") | |
| print(f"committed {len(ops)} files to {repo}") | |
| return 0 | |
| AUDIO_EXTS = {".mp3", ".m4a", ".mp4", ".aac", ".ogg", ".wav", ".flac"} | |
| def fix_family_jsons(root: Path) -> tuple[dict, dict, list[str]]: | |
| """Reconcile people.json/events.json with the photo files actually on disk. | |
| Fixes the two mistakes hand-written JSONs tend to have: people 'photos' | |
| entries that point at a folder instead of files, and photo paths whose | |
| case/extension doesn't match the real file (.jpg vs .JPG). | |
| Returns (people, events, warnings) without touching anything on disk. | |
| """ | |
| people = json.loads((root / "people.json").read_text(encoding="utf-8")) | |
| events = json.loads((root / "events.json").read_text(encoding="utf-8")) | |
| warnings: list[str] = [] | |
| for p in people.get("people", []): | |
| pdir = root / "photos" / "people" / p["id"] | |
| found = sorted(f for f in pdir.iterdir() | |
| if f.suffix.lower() in IMG_EXTS) if pdir.is_dir() else [] | |
| p["photos"] = [f"photos/people/{p['id']}/{f.name}" for f in found] | |
| if not found: | |
| warnings.append(f"person '{p['id']}': no photos in {pdir}") | |
| edir = root / "photos" / "events" | |
| by_stem = {f.stem.lower(): f for f in edir.iterdir() | |
| if f.suffix.lower() in IMG_EXTS} if edir.is_dir() else {} | |
| for e in events.get("events", []): | |
| # Match on the referenced filename's stem (case-insensitive), falling | |
| # back to the event id itself. | |
| want = Path(e.get("photo") or e["id"]).stem.lower() | |
| f = by_stem.get(want) or by_stem.get(e["id"].lower()) | |
| if f: | |
| e["photo"] = f"photos/events/{f.name}" | |
| else: | |
| warnings.append(f"event '{e['id']}': no photo file matching " | |
| f"'{want}' in {edir}") | |
| return people, events, warnings | |
| def sync_upload(api, repo: str, root: Path, dry_run: bool) -> int: | |
| """Upload a folder that already uses the dataset layout, in one commit: | |
| <root>/people.json + events.json (photo paths are auto-repaired) | |
| <root>/photos/people/<id>/*.jpg | |
| <root>/photos/events/*.jpg | |
| <root>/music/*.mp3 optional background music | |
| progress/ and recordings/ are never touched, so re-syncing photos can't | |
| clobber live streaks or precious recordings. | |
| """ | |
| from huggingface_hub import CommitOperationAdd | |
| if not (root / "people.json").is_file() or not (root / "events.json").is_file(): | |
| print(f"{root} must contain people.json and events.json", file=sys.stderr) | |
| return 1 | |
| people, events, warnings = fix_family_jsons(root) | |
| for w in warnings: | |
| print("warning:", w) | |
| ops = [ | |
| CommitOperationAdd(path_in_repo="people.json", path_or_fileobj=tmp_json(people)), | |
| CommitOperationAdd(path_in_repo="events.json", path_or_fileobj=tmp_json(events)), | |
| ] | |
| for sub, exts in (("photos", IMG_EXTS), ("music", AUDIO_EXTS)): | |
| base = root / sub | |
| if not base.is_dir(): | |
| continue | |
| for f in sorted(base.rglob("*")): | |
| if f.is_file() and f.suffix.lower() in exts: | |
| ops.append(CommitOperationAdd( | |
| path_in_repo=str(f.relative_to(root)), path_or_fileobj=str(f))) | |
| print(f"{'would upload' if dry_run else 'uploading'} {len(ops)} files " | |
| f"({len(people.get('people', []))} people, {len(events.get('events', []))} events):") | |
| for op in ops: | |
| print(" " + op.path_in_repo) | |
| if dry_run: | |
| print("dry run: no commit made") | |
| return 0 | |
| # Also repair the local copies so a local test run shows the same photos. | |
| (root / "people.json").write_text( | |
| json.dumps(people, ensure_ascii=False, indent=2), encoding="utf-8") | |
| (root / "events.json").write_text( | |
| json.dumps(events, ensure_ascii=False, indent=2), encoding="utf-8") | |
| commit(api, repo, ops, f"sync family data from {root.name} ({len(ops)} files)") | |
| print(f"committed {len(ops)} files to {repo}") | |
| return 0 | |
| def main() -> int: | |
| ap = argparse.ArgumentParser(description=__doc__, | |
| formatter_class=argparse.RawDescriptionHelpFormatter) | |
| ap.add_argument("--repo", required=True, help="private dataset repo, e.g. luke/opa-family-data") | |
| ap.add_argument("--token", default=os.environ.get("HF_TOKEN")) | |
| ap.add_argument("--init", action="store_true", help="create empty people/events json") | |
| # bulk | |
| ap.add_argument("--bulk", metavar="DIR", | |
| help="upload a whole folder: DIR/people/<id>/*.jpg (+info.json), " | |
| "DIR/events/<id>/<photo> (+info.json)") | |
| ap.add_argument("--sync", metavar="DIR", | |
| help="upload a folder already in dataset layout " | |
| "(people.json, events.json, photos/, music/); " | |
| "photo paths in the JSONs are auto-repaired") | |
| ap.add_argument("--dry-run", action="store_true", | |
| help="with --bulk/--sync: only show what would be uploaded") | |
| # person | |
| ap.add_argument("--person", help="person id (short, lowercase)") | |
| ap.add_argument("--name", help="display name") | |
| ap.add_argument("--relation", default="", help='e.g. "vriendin van Luke"') | |
| ap.add_argument("--alias", action="append", default=[], help="repeatable") | |
| ap.add_argument("--birthday", help="MM-DD, optional") | |
| # event | |
| ap.add_argument("--event", help="event id (short, lowercase)") | |
| ap.add_argument("--title", help="event title") | |
| ap.add_argument("--description", default="", help="the story text") | |
| ap.add_argument("--prompt", action="append", default=[], help="repeatable question prompt") | |
| # music | |
| ap.add_argument("--music", metavar="FILE", action="append", default=[], | |
| help="repeatable: audio file(s) for the background-music " | |
| "playlist (shuffled per session)") | |
| # shared | |
| ap.add_argument("--photo", help="local photo file to upload") | |
| args = ap.parse_args() | |
| if not args.token: | |
| # Fall back to the token stored by `hf auth login`. | |
| from huggingface_hub import get_token | |
| args.token = get_token() | |
| if not args.token and not (args.dry_run and args.sync): | |
| print("Log in with `hf auth login`, set HF_TOKEN, or pass --token " | |
| "(needs write access to the private dataset).", file=sys.stderr) | |
| return 1 | |
| from huggingface_hub import CommitOperationAdd | |
| api = get_api(args.token) if args.token else None | |
| ops = [] | |
| if args.bulk: | |
| return bulk_upload(api, args.repo, Path(args.bulk), args.dry_run) | |
| if args.sync: | |
| return sync_upload(api, args.repo, Path(args.sync), args.dry_run) | |
| if args.init: | |
| for name, payload in (("people.json", {"people": []}), | |
| ("events.json", {"events": []})): | |
| ops.append(CommitOperationAdd(path_in_repo=name, path_or_fileobj=tmp_json(payload))) | |
| commit(api, args.repo, ops, "init family data structure") | |
| print("initialized people.json and events.json") | |
| return 0 | |
| if args.music: | |
| for f in args.music: | |
| p = Path(f) | |
| if not p.is_file(): | |
| print(f"not a file: {f}", file=sys.stderr) | |
| return 1 | |
| ops.append(CommitOperationAdd(path_in_repo=f"music/{p.name}", | |
| path_or_fileobj=str(p))) | |
| commit(api, args.repo, ops, f"add {len(ops)} background music track(s)") | |
| print(f"uploaded {len(ops)} track(s) to music/") | |
| return 0 | |
| if args.person: | |
| data = read_remote_json(api, args.repo, "people.json", {"people": []}) | |
| person = next((p for p in data["people"] if p["id"] == args.person), None) | |
| if person is None: | |
| person = {"id": args.person, "name": args.name or args.person.title(), | |
| "aliases": [], "relation": "", "photos": [], "active": True} | |
| data["people"].append(person) | |
| if args.name: | |
| person["name"] = args.name | |
| if args.relation: | |
| person["relation"] = args.relation | |
| for a in args.alias: | |
| if a not in person["aliases"]: | |
| person["aliases"].append(a) | |
| if args.birthday: | |
| person["birthday"] = args.birthday | |
| if args.photo: | |
| n = len(person["photos"]) + 1 | |
| ext = Path(args.photo).suffix.lower() or ".png" | |
| repo_path = f"photos/people/{args.person}/{n}{ext}" | |
| person["photos"].append(repo_path) | |
| ops.append(CommitOperationAdd(path_in_repo=repo_path, path_or_fileobj=args.photo)) | |
| ops.append(CommitOperationAdd(path_in_repo="people.json", path_or_fileobj=tmp_json(data))) | |
| commit(api, args.repo, ops, f"update person {args.person}") | |
| print(f"person '{args.person}' updated ({len(person['photos'])} photos)") | |
| return 0 | |
| if args.event: | |
| data = read_remote_json(api, args.repo, "events.json", {"events": []}) | |
| event = next((e for e in data["events"] if e["id"] == args.event), None) | |
| if event is None: | |
| event = {"id": args.event, "photo": "", "title": args.title or args.event, | |
| "description": "", "prompts": [], "active": True} | |
| data["events"].append(event) | |
| if args.title: | |
| event["title"] = args.title | |
| if args.description: | |
| event["description"] = args.description | |
| for p in args.prompt: | |
| if p not in event["prompts"]: | |
| event["prompts"].append(p) | |
| if args.photo: | |
| ext = Path(args.photo).suffix.lower() or ".png" | |
| repo_path = f"photos/events/{args.event}{ext}" | |
| event["photo"] = repo_path | |
| ops.append(CommitOperationAdd(path_in_repo=repo_path, path_or_fileobj=args.photo)) | |
| ops.append(CommitOperationAdd(path_in_repo="events.json", path_or_fileobj=tmp_json(data))) | |
| commit(api, args.repo, ops, f"update event {args.event}") | |
| print(f"event '{args.event}' updated") | |
| return 0 | |
| ap.print_help() | |
| return 1 | |
| if __name__ == "__main__": | |
| raise SystemExit(main()) | |