File size: 3,486 Bytes
d47fb92
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
"""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