Spaces:
Paused
Paused
| 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 = "openclaw_space.tar.gz" | |
| BACKUP_ROOT = "/root/.openclaw" | |
| 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 {repo_id} (Forcing cloud sync)...") | |
| # ================= 核心修复:强制穿透缓存与禁用软链接 ================= | |
| path = hf_hub_download( | |
| repo_id=repo_id, | |
| filename=FILENAME, | |
| repo_type="dataset", | |
| token=token, | |
| force_download=True, # 强制去云端拉取最新鲜的数据,无视本地旧缓存 | |
| local_dir_use_symlinks=False # 禁用软链接,防止后续文件读写权限冲突 | |
| ) | |
| # ====================================================================== | |
| os.makedirs(BACKUP_ROOT, exist_ok=True) | |
| with tarfile.open(path, "r:gz") as tar: | |
| tar.extractall(path=BACKUP_ROOT) | |
| print(f"Success: Restored from {FILENAME}") | |
| return True | |
| 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 | |
| temp_tar_path = f"/tmp/{FILENAME}" | |
| with tarfile.open(temp_tar_path, "w:gz") as tar: | |
| # 打包整个 .openclaw 文件夹 | |
| if os.path.exists(BACKUP_ROOT): | |
| # arcname="" 确保解压后直接是文件夹内容,不会多一层目录 | |
| tar.add(BACKUP_ROOT, arcname=".") | |
| else: | |
| print(f"Warning: {BACKUP_ROOT} does not exist") | |
| return | |
| print("Uploading to Hugging Face...") | |
| # 上传并覆盖 | |
| api.upload_file( | |
| path_or_fileobj=temp_tar_path, | |
| path_in_repo=FILENAME, | |
| repo_id=repo_id, | |
| repo_type="dataset", | |
| token=token | |
| ) | |
| print(f"Backup {FILENAME} Success (Overwritten in Git History).") | |
| # 清理临时文件 | |
| os.remove(temp_tar_path) | |
| 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() |