| import os |
| import sys |
| import tarfile |
| 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" |
|
|
| def restore(): |
| """从 Hugging Face Dataset 下载并解压备份,恢复数据""" |
| try: |
| if not repo_id or not token: |
| print("跳过恢复: HF_DATASET 或 HF_TOKEN 未设置") |
| return |
| print(f"正在从 {repo_id} 下载 {FILENAME}...") |
| |
| path = hf_hub_download(repo_id=repo_id, filename=FILENAME, repo_type="dataset", token=token) |
| |
| with tarfile.open(path, "r:gz") as tar: |
| tar.extractall(path="/root/.openclaw/") |
| print(f"成功从 {FILENAME} 恢复数据。") |
| return True |
| except Exception as e: |
| |
| print(f"恢复说明: 未找到现有备份或发生错误: {e}") |
|
|
| def backup(): |
| """将 OpenClaw 的关键数据打包并上传到 Hugging Face Dataset""" |
| try: |
| if not repo_id or not token: |
| print("跳过备份: HF_DATASET 或 HF_TOKEN 未设置") |
| return |
| print("正在创建数据备份包...") |
| with tarfile.open(FILENAME, "w:gz") as tar: |
| |
| paths_to_backup = [ |
| "/root/.openclaw/sessions", |
| "/root/.openclaw/agents/main/sessions", |
| "/root/.openclaw/openclaw.json" |
| ] |
| for p in paths_to_backup: |
| if os.path.exists(p): |
| |
| arcname = p.replace("/root/.openclaw/", "") |
| tar.add(p, arcname=arcname) |
| print(f" 已添加: {p}") |
| |
| api.upload_file( |
| path_or_fileobj=FILENAME, |
| path_in_repo=FILENAME, |
| repo_id=repo_id, |
| repo_type="dataset", |
| token=token |
| ) |
| print(f"备份 {FILENAME} 成功上传(已覆盖)。") |
| except Exception as e: |
| print(f"备份错误: {e}") |
|
|
| if __name__ == "__main__": |
| if len(sys.argv) > 1 and sys.argv[1] == "backup": |
| backup() |
| else: |
| restore() |