import os, sys, time, sqlite3, hashlib, shutil from huggingface_hub import HfApi, hf_hub_download REPO = os.environ["BACKUP_REPO"] TOKEN = os.environ["HF_TOKEN"] DATA_DIR = os.environ.get("DATA_DIR", "/app/data") INTERVAL = int(os.environ.get("BACKUP_INTERVAL", "120")) DB = os.path.join(DATA_DIR, "storage.sqlite") SNAP = "/tmp/storage.snapshot.sqlite" api = HfApi(token=TOKEN) def restore(): os.makedirs(DATA_DIR, exist_ok=True) try: p = hf_hub_download(REPO, "storage.sqlite", repo_type="dataset", token=TOKEN) # remove any leftover SQLite side files before restoring for ext in ("", "-wal", "-shm"): try: os.remove(DB + ext) except FileNotFoundError: pass shutil.copyfile(p, DB) # copies contents only, not read-only permissions os.chmod(DB, 0o666) # make sure OmniRoute can write to it print("RESTORED backup", flush=True) except Exception as e: print("No backup yet (first run?):", e, flush=True) def loop(): last = None while True: time.sleep(INTERVAL) try: if not os.path.exists(DB): print("DB file not found yet", flush=True) continue if os.path.exists(SNAP): os.remove(SNAP) src = sqlite3.connect(DB) dst = sqlite3.connect(SNAP) src.backup(dst) dst.close() src.close() h = hashlib.sha256(open(SNAP, "rb").read()).hexdigest() if h != last: api.upload_file(path_or_fileobj=SNAP, path_in_repo="storage.sqlite", repo_id=REPO, repo_type="dataset", commit_message="backup") last = h print("BACKED UP", flush=True) except Exception as e: print("Backup failed:", e, flush=True) if __name__ == "__main__": restore() if sys.argv[1] == "restore" else loop()