File size: 2,375 Bytes
9fb0402
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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)
        # 解压到 OpenClaw 的数据目录
        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()