Spaces:
Paused
Paused
File size: 3,008 Bytes
8a26730 | 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 97 98 99 100 | import os
import sys
import tarfile
from datetime import datetime
from huggingface_hub import HfApi, hf_hub_download
API = HfApi()
def env(name: str, default: str = "") -> str:
v = os.getenv(name, default).strip()
return v
HF_TOKEN = env("HF_TOKEN")
HF_DATASET = env("HF_DATASET")
OPENCLAW_HOME = env("OPENCLAW_HOME", os.path.join(os.path.expanduser("~"), ".openclaw"))
BACKUP_PREFIX = "openclaw-backup-"
MAX_SCAN = 50 # scan last N files
def _enabled() -> bool:
return bool(HF_TOKEN and HF_DATASET)
def _tar_paths():
# What we persist
sessions = os.path.join(OPENCLAW_HOME, "sessions")
workspace = os.path.join(OPENCLAW_HOME, "workspace")
cfg = os.path.join(OPENCLAW_HOME, "openclaw.json")
return [p for p in [sessions, workspace, cfg] if os.path.exists(p)]
def restore():
if not _enabled():
print("[sync] restore skipped: HF_TOKEN/HF_DATASET not set")
return 0
try:
files = API.list_repo_files(repo_id=HF_DATASET, repo_type="dataset", token=HF_TOKEN)
backups = sorted([f for f in files if f.startswith(BACKUP_PREFIX) and f.endswith(".tar.gz")], reverse=True)
if not backups:
print("[sync] no backups found in dataset")
return 0
target = backups[0]
print(f"[sync] restoring from {target}")
local = hf_hub_download(
repo_id=HF_DATASET,
repo_type="dataset",
filename=target,
token=HF_TOKEN,
)
os.makedirs(OPENCLAW_HOME, exist_ok=True)
with tarfile.open(local, "r:gz") as tar:
tar.extractall(path=OPENCLAW_HOME)
print("[sync] restore ok")
return 0
except Exception as e:
print(f"[sync] restore error: {e}")
return 0 # do not crash startup
def backup():
if not _enabled():
print("[sync] backup skipped: HF_TOKEN/HF_DATASET not set")
return 0
try:
os.makedirs("/tmp", exist_ok=True)
name = f"{BACKUP_PREFIX}{datetime.utcnow().strftime('%Y%m%d-%H%M%S')}.tar.gz"
out_path = os.path.join("/tmp", name)
paths = _tar_paths()
if not paths:
print("[sync] nothing to backup yet")
return 0
# Create tarball with relative paths inside OPENCLAW_HOME
with tarfile.open(out_path, "w:gz") as tar:
for p in paths:
arcname = os.path.relpath(p, OPENCLAW_HOME)
tar.add(p, arcname=arcname)
API.upload_file(
path_or_fileobj=out_path,
path_in_repo=name,
repo_id=HF_DATASET,
repo_type="dataset",
token=HF_TOKEN,
)
print(f"[sync] backup uploaded: {name}")
return 0
except Exception as e:
print(f"[sync] backup error: {e}")
return 0
if __name__ == "__main__":
cmd = sys.argv[1] if len(sys.argv) > 1 else "restore"
if cmd == "backup":
raise SystemExit(backup())
raise SystemExit(restore()) |