File size: 6,796 Bytes
5ef3f54
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
import os
import time
import json
import tempfile
import shutil
from huggingface_hub import HfApi, hf_hub_download

HF_TOKEN = os.getenv("HF_TOKEN")
DATASET_ID = os.getenv("DATASET_ID") # e.g. "username/grim-fable-data"

api = HfApi(token=HF_TOKEN)

MANIFEST_FILE = "manifest.json"

# In-memory manifest cache to reduce API calls
_manifest_cache = {"data": None, "last_fetch": 0}
MANIFEST_CACHE_TTL = 30 # seconds

def get_manifest(force_refresh: bool = False):
    """Downloads and reads the manifest.json file with caching."""
    if not HF_TOKEN or not DATASET_ID:
        return {"saves": {}}

    now = time.time()
    if not force_refresh and _manifest_cache["data"] and (now - _manifest_cache["last_fetch"] < MANIFEST_CACHE_TTL):
        return _manifest_cache["data"]

    try:
        downloaded_path = hf_hub_download(
            repo_id=DATASET_ID,
            filename=MANIFEST_FILE,
            repo_type="dataset",
            token=HF_TOKEN
        )
        with open(downloaded_path, 'r') as f:
            data = json.load(f)
            _manifest_cache["data"] = data
            _manifest_cache["last_fetch"] = now
            return data
    except Exception as e:
        print(f"Notice: manifest.json not found or could not be read: {e}")
        return {"saves": {}}

def update_manifest(save_name: str, description: str = None, deleted: bool = False):
    """Updates the manifest.json with new/updated save info."""
    if not HF_TOKEN or not DATASET_ID:
        return

    manifest = get_manifest()
    if "saves" not in manifest: manifest["saves"] = {}

    if deleted:
        if save_name in manifest["saves"]:
            del manifest["saves"][save_name]
    else:
        existing = manifest["saves"].get(save_name, {"description": "", "timestamp": 0})
        manifest["saves"][save_name] = {
            "description": description if description is not None else existing["description"],
            "timestamp": time.time()
        }

    try:
        with tempfile.NamedTemporaryFile(mode='w', delete=False) as tf:
            json.dump(manifest, tf)
            temp_path = tf.name

        api.upload_file(
            path_or_fileobj=temp_path,
            path_in_repo=MANIFEST_FILE,
            repo_id=DATASET_ID,
            repo_type="dataset"
        )
        os.remove(temp_path)
        # Invalidate cache
        _manifest_cache["data"] = None
    except Exception as e:
        print(f"Error updating manifest: {e}")

def save_to_dataset(save_name: str, db_path: str, description: str = None):
    if not HF_TOKEN or not DATASET_ID:
        return False

    try:
        api.upload_file(
            path_or_fileobj=db_path,
            path_in_repo=f"{save_name}/world.db",
            repo_id=DATASET_ID,
            repo_type="dataset"
        )
        update_manifest(save_name, description)
        return True
    except Exception as e:
        print(f"Error saving to dataset: {e}")
        return False

def load_from_dataset(save_name: str, db_path: str):
    if not HF_TOKEN or not DATASET_ID:
        return False

    path_in_repo = f"{save_name}/world.db"
    try:
        downloaded_path = hf_hub_download(
            repo_id=DATASET_ID,
            filename=path_in_repo,
            repo_type="dataset",
            token=HF_TOKEN
        )
        shutil.copy(downloaded_path, db_path)
        return True
    except Exception as e:
        print(f"Error loading from dataset: {e}")
        return False

def delete_save(save_name: str):
    if not HF_TOKEN or not DATASET_ID:
        return False

    try:
        update_manifest(save_name, deleted=True)
        files = api.list_repo_files(repo_id=DATASET_ID, repo_type="dataset")
        files_to_delete = [f for f in files if f.startswith(f"{save_name}/")]
        for f in files_to_delete:
            api.delete_file(path_in_repo=f, repo_id=DATASET_ID, repo_type="dataset")
        return True
    except Exception as e:
        print(f"Error deleting save: {e}")
        return False

def list_saves():
    if not HF_TOKEN or not DATASET_ID:
        return []
    manifest = get_manifest()
    results = []
    for name, data in manifest.get("saves", {}).items():
        results.append({
            "name": name,
            "description": data.get("description", ""),
            "timestamp": data.get("timestamp", 0)
        })
    return results

def get_cached_media(save_name: str, entity_id: str, media_type: str):
    """Retrieves media content from the dataset if it exists."""
    ext = "webp" if media_type == "image" else "mp3"
    path_in_repo = f"{save_name}/media/{entity_id}.{ext}"
    try:
        downloaded_path = hf_hub_download(
            repo_id=DATASET_ID,
            filename=path_in_repo,
            repo_type="dataset",
            token=HF_TOKEN
        )
        with open(downloaded_path, 'rb') as f:
            return f.read()
    except Exception:
        return None

def save_cached_media(save_name: str, entity_id: str, media_type: str, content: bytes):
    """Saves media content to the dataset."""
    ext = "webp" if media_type == "image" else "mp3"
    path_in_repo = f"{save_name}/media/{entity_id}.{ext}"
    try:
        with tempfile.NamedTemporaryFile(mode='wb', delete=False) as tf:
            tf.write(content)
            temp_path = tf.name

        api.upload_file(
            path_or_fileobj=temp_path,
            path_in_repo=path_in_repo,
            repo_id=DATASET_ID,
            repo_type="dataset"
        )
        os.remove(temp_path)
        return True
    except Exception as e:
        print(f"Error caching media: {e}")
        return False

class PersistenceLoop:
    def __init__(self):
        self.last_interaction_time = time.time()
        self.last_save_time = time.time()
        self.current_save_name = "default_save"
        self.needs_save = False
        self.turn_counter = 0

    def update_interaction(self):
        self.last_interaction_time = time.time()
        self.needs_save = True
        self.turn_counter += 1

    def should_autosave(self, interaction_happened=False):
        now = time.time()

        # Immediate save every 5 turns
        if interaction_happened and self.turn_counter >= 5:
            self.turn_counter = 0
            return True

        # If an interaction just happened, we don't save immediately unless it's been a long time (safety check)
        if interaction_happened:
            if now - self.last_save_time > 3600 and self.needs_save: return True
            return False

        # Idle save: trigger if we have unsaved changes and it's been 30 mins since last interaction
        if self.needs_save and now - self.last_interaction_time > 1800:
             return True

        return False

persistence_manager = PersistenceLoop()