File size: 5,054 Bytes
c89135a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
"""
Supervisor for SillyTavern on a Hugging Face Docker Space (free tier = ephemeral disk).
 1. restores ST's data folder from a PRIVATE HF dataset repo
 2. starts SillyTavern with basic auth (refuses to start without a password)
 3. every SYNC_INTERVAL seconds, pushes the data folder back if anything changed
 4. on SIGTERM (restart/sleep) stops ST and does one final push

Space secrets:  ST_USER, ST_PASS, HF_TOKEN (write access to the dataset), DATASET_REPO (e.g. "you/st-data")
Optional:       SYNC_INTERVAL (default 300), DATA_DIR, ST_CMD (testing)
"""
import os, sys, time, signal, shutil, hashlib, shlex, subprocess
from pathlib import Path

APP_DIR = Path(os.getenv("APP_DIR", "/home/node/app"))
DATA_DIR = Path(os.getenv("DATA_DIR", str(APP_DIR / "data")))
INTERVAL = int(os.getenv("SYNC_INTERVAL", "300"))
REPO = os.getenv("DATASET_REPO", "").strip()
TOKEN = os.getenv("HF_TOKEN", "").strip()
SKIP_DIRS = {"_cache", "_uploads", "backups", "thumbnails", ".cache"}
IGNORE_PATTERNS = ["_cache/**", "_uploads/**", "**/backups/**", "**/thumbnails/**", ".cache/**"]


def log(msg):
    print(f"[sync] {msg}", flush=True)


def fingerprint() -> str:
    h = hashlib.sha1()
    for root, dirs, files in os.walk(DATA_DIR):
        dirs[:] = sorted(d for d in dirs if d not in SKIP_DIRS)
        for f in sorted(files):
            p = Path(root) / f
            try:
                st = p.stat()
            except OSError:
                continue
            h.update(f"{p.relative_to(DATA_DIR)}|{st.st_size}|{st.st_mtime_ns}".encode())
    return h.hexdigest()


def has_files() -> bool:
    for root, dirs, files in os.walk(DATA_DIR):
        dirs[:] = [d for d in dirs if d not in SKIP_DIRS]
        if files:
            return True
    return False


def main():
    user, pw = os.getenv("ST_USER", "").strip(), os.getenv("ST_PASS", "").strip()
    if not user or not pw:
        sys.exit("Refusing to start: set ST_USER and ST_PASS as Space secrets (the site would be open to everyone).")

    DATA_DIR.mkdir(parents=True, exist_ok=True)
    persist, api = False, None
    if TOKEN and REPO:
        try:
            from huggingface_hub import HfApi, snapshot_download
            from huggingface_hub.utils import RepositoryNotFoundError
            api = HfApi(token=TOKEN)
            try:
                api.repo_info(REPO, repo_type="dataset")
                snapshot_download(repo_id=REPO, repo_type="dataset", local_dir=str(DATA_DIR), token=TOKEN)
                log("restored data from dataset repo")
                persist = True
            except RepositoryNotFoundError:
                log("dataset repo not found; it will be created (private) on the first push")
                persist = True
        except Exception as e:  # restore failed for another reason: NEVER push, or we could overwrite the backup
            log(f"restore FAILED ({e!r}); syncing disabled this session to protect the backup")
    else:
        log("HF_TOKEN / DATASET_REPO not set: running WITHOUT persistence (data is lost on restart)")

    cfg = APP_DIR / "config" / "config.yaml"
    if not cfg.exists() and (APP_DIR / "default" / "config.yaml").exists():
        cfg.parent.mkdir(parents=True, exist_ok=True)
        shutil.copy(APP_DIR / "default" / "config.yaml", cfg)

    env = dict(os.environ)
    env.update({
        "SILLYTAVERN_LISTEN": "true",
        "SILLYTAVERN_PORT": "7860",
        "SILLYTAVERN_WHITELISTMODE": "false",
        "SILLYTAVERN_BASICAUTHMODE": "true",
        "SILLYTAVERN_BASICAUTHUSER__USERNAME": user,
        "SILLYTAVERN_BASICAUTHUSER__PASSWORD": pw,
    })
    cmd = shlex.split(os.getenv("ST_CMD", "node server.js"))
    child = subprocess.Popen(cmd, cwd=str(APP_DIR), env=env)

    last_fp = fingerprint() if persist else ""

    def push(reason):
        nonlocal last_fp
        if not persist:
            return
        try:
            if not has_files():
                return
            fp = fingerprint()
            if fp == last_fp:
                return
            api.create_repo(REPO, repo_type="dataset", private=True, exist_ok=True)
            api.upload_folder(folder_path=str(DATA_DIR), repo_id=REPO, repo_type="dataset",
                              ignore_patterns=IGNORE_PATTERNS, delete_patterns=["*"],
                              commit_message=f"sync ({reason})")
            last_fp = fp
            log(f"pushed ({reason})")
        except Exception as e:
            log(f"push failed: {e!r}")

    stopping = []

    def on_term(signum, frame):
        stopping.append(1)
        log("shutdown signal received")
        if child.poll() is None:
            child.terminate()

    signal.signal(signal.SIGTERM, on_term)
    signal.signal(signal.SIGINT, on_term)

    nxt = time.time() + INTERVAL
    while child.poll() is None:
        time.sleep(1)
        if time.time() >= nxt:
            push("periodic")
            nxt = time.time() + INTERVAL
    push("shutdown")
    sys.exit(0 if stopping else (child.returncode or 0))


if __name__ == "__main__":
    main()