import os, sys, tarfile from huggingface_hub import HfApi, hf_hub_download from datetime import datetime, timedelta api = HfApi() repo_id = os.getenv("HF_DATASET") token = os.getenv("HF_TOKEN") def restore(): try: files = api.list_repo_files(repo_id=repo_id, repo_type="dataset", token=token) now = datetime.now() for i in range(5): day = (now - timedelta(days=i)).strftime("%Y-%m-%d") name = f"backup_{day}.tar.gz" if name in files: path = hf_hub_download(repo_id=repo_id, filename=name, repo_type="dataset", token=token) with tarfile.open(path, "r:gz") as tar: tar.extractall(path="/root/.openclaw/") print(f"Success: Restored from {name}") return True except Exception as e: print(f"Restore Error: {e}") def backup(): try: day = datetime.now().strftime("%Y-%m-%d") name = f"backup_{day}.tar.gz" with tarfile.open(name, "w:gz") as tar: if os.path.exists("/root/.openclaw/sessions"): tar.add("/root/.openclaw/sessions", arcname="sessions") tar.add("/root/.openclaw/openclaw.json", arcname="openclaw.json") api.upload_file(path_or_fileobj=name, path_in_repo=name, repo_id=repo_id, repo_type="dataset", token=token) print(f"Backup {name} Success.") 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()