qf46578's picture
Upload sync.py with huggingface_hub
f2facd1 verified
Raw History Blame Contribute Delete
3.41 kB
import os
import sys
import tarfile
import pathlib
from huggingface_hub import HfApi, hf_hub_download
api = HfApi()
repo_id = os.getenv("HF_DATASET")
token = os.getenv("HF_TOKEN")
FILENAME = "latest_backup.tar.gz"
STATE_DIR = os.getenv("OPENCLAW_STATE_DIR", "/root/.openclaw")
def _safe_extract(tar: tarfile.TarFile, path: str) -> None:
base = pathlib.Path(path).resolve()
for m in tar.getmembers():
target = (base / m.name).resolve()
if not str(target).startswith(str(base) + os.sep) and target != base:
raise RuntimeError(f"Unsafe tar entry: {m.name}")
tar.extractall(path=path)
def restore():
try:
if not repo_id or not token:
print("Skip Restore: HF_DATASET or HF_TOKEN not set")
return
print(f"Downloading {FILENAME} from dataset {repo_id}...")
path = hf_hub_download(repo_id=repo_id, filename=FILENAME, repo_type="dataset", token=token)
os.makedirs(STATE_DIR, exist_ok=True)
with tarfile.open(path, "r:gz") as tar:
_safe_extract(tar, path=STATE_DIR)
print(f"Success: Restored from {FILENAME}")
except Exception as e:
print(f"Restore Note: No existing backup found or error: {e}")
def backup():
try:
if not repo_id or not token:
print("Skip Backup: HF_DATASET or HF_TOKEN not set")
return
paths_to_backup = [
f"{STATE_DIR}/sessions",
f"{STATE_DIR}/agents/main/sessions",
f"{STATE_DIR}/openclaw.json",
f"{STATE_DIR}/devices",
f"{STATE_DIR}/identity",
f"{STATE_DIR}/skills"
]
last_ts_file = f"{STATE_DIR}/.last_backup_ts"
last_ts = 0.0
if os.path.exists(last_ts_file):
try:
with open(last_ts_file, "r") as f:
content = f.read().strip()
last_ts = float(content) if content else 0.0
except: pass
max_ts = 0.0
for p in paths_to_backup:
if p.endswith("openclaw.json"): continue
if not os.path.exists(p): continue
if os.path.isfile(p):
ts = os.path.getmtime(p)
if ts > max_ts: max_ts = ts
else:
for root, _, files in os.walk(p):
for name in files:
try:
ts = os.path.getmtime(os.path.join(root, name))
if ts > max_ts: max_ts = ts
except: pass
if max_ts > 0 and max_ts <= last_ts:
return
with tarfile.open(FILENAME, "w:gz") as tar:
for p in paths_to_backup:
if os.path.exists(p):
arcname = p.replace(STATE_DIR.rstrip("/") + "/", "")
tar.add(p, arcname=arcname)
api.upload_file(
path_or_fileobj=FILENAME,
path_in_repo=FILENAME,
repo_id=repo_id,
repo_type="dataset",
token=token
)
with open(last_ts_file, "w") as f:
f.write(str(max_ts))
print(f"Backup {FILENAME} Success (Overwritten).")
except Exception as e:
print(f"Backup Error: {e}")
if __name__ == "__main__":
if len(sys.argv) > 1 and sys.argv[1] == "backup":
backup()
else:
restore()