Spaces:
Sleeping
Sleeping
Download api/persistence.py from akshit2603/fabric-api: direct link, hf CLI and curl.
- Browser
- Download file 3.49 kB
-
https://huggingface.co/spaces/akshit2603/fabric-api/resolve/main/api/persistence.py
- Command line
-
hf download hf://spaces/akshit2603/fabric-api/api/persistence.py
-
curl -L -o persistence.py https://huggingface.co/spaces/akshit2603/fabric-api/resolve/main/api/persistence.py
3.49 kB
| """Durable storage for the fabric app, mirrored to an HF bucket. | |
| HF Space containers have an EPHEMERAL filesystem, so anything we want to keep | |
| (the enrolled article catalog AND the log of processed inspections) must be | |
| mirrored to durable storage. We keep a local working dir (FABRIC_DATA_DIR) and | |
| sync it to an HF bucket via the `hf sync` CLI: | |
| data/ | |
| fabric_store.json # enrolled catalog: embeddings + meta | |
| images/<article_code>/*.jpg # original enrolled photos (re-embed-able) | |
| processed/*.jpg # every analyzed photo | |
| processed_log.jsonl # one record per /analyze: readings + confidence | |
| - pull_once(): bucket -> data dir (restore on container start) | |
| - push(): data dir -> bucket (persist; run in a background task) | |
| Auth: set HF_TOKEN (write) as a Space secret. If the CLI/token is missing, | |
| everything still works locally (just not persisted) — all sync is non-fatal. | |
| """ | |
| import os, re, uuid, json, subprocess, datetime | |
| DATA_DIR = os.environ.get("FABRIC_DATA_DIR", "./data") | |
| IMAGES_DIR = os.path.join(DATA_DIR, "images") | |
| PROCESSED_DIR = os.path.join(DATA_DIR, "processed") | |
| STORE_PATH = os.environ.get("FABRIC_STORE_PATH", os.path.join(DATA_DIR, "fabric_store.json")) | |
| PROCESSED_LOG = os.path.join(DATA_DIR, "processed_log.jsonl") | |
| BUCKET = os.environ.get("FABRIC_BUCKET", "hf://buckets/akshit2603/enrolled_fabric_images") | |
| LOG_PROCESSED = os.environ.get("FABRIC_LOG_PROCESSED", "1") not in ("0", "false", "off") | |
| _pulled = False | |
| def _now(): | |
| return datetime.datetime.utcnow().isoformat(timespec="seconds") + "Z" | |
| def safe(code): | |
| return re.sub(r"[^A-Za-z0-9_.-]", "_", str(code))[:80] or "unknown" | |
| def ensure_dirs(): | |
| os.makedirs(IMAGES_DIR, exist_ok=True) | |
| os.makedirs(PROCESSED_DIR, exist_ok=True) | |
| def hf_sync(src, dst): | |
| """`hf sync src dst`; non-fatal (logs + returns False on any failure).""" | |
| try: | |
| r = subprocess.run(["hf", "sync", src, dst], | |
| capture_output=True, text=True, timeout=180) | |
| if r.returncode != 0: | |
| print(f"[hf sync {src}->{dst} rc={r.returncode}: {r.stderr.strip()[:200]}]") | |
| return False | |
| return True | |
| except Exception as e: | |
| print(f"[hf sync unavailable: {e}]") | |
| return False | |
| def pull_once(): | |
| """Restore the data dir from the bucket on first call (container start).""" | |
| global _pulled | |
| ensure_dirs() | |
| if not _pulled: | |
| hf_sync(BUCKET, DATA_DIR) | |
| _pulled = True | |
| def push(): | |
| """Mirror the data dir up to the bucket (call from a BackgroundTask).""" | |
| hf_sync(DATA_DIR, BUCKET) | |
| def save_enrolled_image(code, data: bytes, filename: str) -> str: | |
| d = os.path.join(IMAGES_DIR, safe(code)); os.makedirs(d, exist_ok=True) | |
| ext = os.path.splitext(filename or "u.jpg")[1] or ".jpg" | |
| p = os.path.join(d, f"{uuid.uuid4().hex}{ext}") | |
| with open(p, "wb") as f: | |
| f.write(data) | |
| return p | |
| def log_processed(data: bytes, filename: str, record: dict) -> str: | |
| """Save a processed photo + append its readings/confidence to the log.""" | |
| if not LOG_PROCESSED: | |
| return "" | |
| ensure_dirs() | |
| ext = os.path.splitext(filename or "u.jpg")[1] or ".jpg" | |
| name = f"{uuid.uuid4().hex}{ext}" | |
| with open(os.path.join(PROCESSED_DIR, name), "wb") as f: | |
| f.write(data) | |
| rec = {"ts": _now(), "image": f"processed/{name}", **record} | |
| with open(PROCESSED_LOG, "a") as f: | |
| f.write(json.dumps(rec) + "\n") | |
| return name | |