File size: 8,740 Bytes
af9ac87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
#include "hfhub.h"
#include <curl/curl.h>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <mutex>
#include <sstream>

namespace hf {

static std::string g_token;
static std::string g_repo;

void init() {
    const char* t = std::getenv("HF_TOKEN");
    const char* r = std::getenv("HF_DATASET_REPO");
    g_token = t ? t : "";
    g_repo  = r ? r : "Arian8888/ki-brain-storage";
    if (!g_token.empty())
        std::cout << "[hf] Hub-Sync aktiv: " << g_repo << std::endl;
    else
        std::cout << "[hf] kein HF_TOKEN -> Sync deaktiviert" << std::endl;
}

bool enabled() { return !g_token.empty(); }

// ────── Base64 + JSON Helpers ──────
static const char B64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
static std::string base64_encode(const std::string& in) {
    std::string out;
    int val = 0, valb = -6;
    for (unsigned char c : in) {
        val = (val<<8) + c; valb += 8;
        while (valb >= 0) { out.push_back(B64[(val>>valb) & 0x3F]); valb -= 6; }
    }
    if (valb > -6) out.push_back(B64[((val<<8) >> (valb+8)) & 0x3F]);
    while (out.size() % 4) out.push_back('=');
    return out;
}
static std::string base64_decode(const std::string& in) {
    std::string out;
    int T[256]; for (int i = 0; i < 256; ++i) T[i] = -1;
    for (int i = 0; i < 64; ++i) T[(unsigned char)B64[i]] = i;
    int val = 0, valb = -8;
    for (unsigned char c : in) {
        if (c == '\n' || c == '\r' || c == ' ') continue;
        if (T[c] == -1) break;
        val = (val<<6) + T[c]; valb += 6;
        if (valb >= 0) { out.push_back(char((val>>valb) & 0xFF)); valb -= 8; }
    }
    return out;
}

static std::string json_escape(const std::string& s) {
    std::string o; o.reserve(s.size() + 8);
    for (unsigned char c : s) {
        switch (c) {
            case '"': o += "\\\""; break;
            case '\\': o += "\\\\"; break;
            case '\n': o += "\\n"; break;
            case '\r': o += "\\r"; break;
            case '\t': o += "\\t"; break;
            default:
                if (c < 0x20) { char b[8]; std::snprintf(b, sizeof(b), "\\u%04x", c); o += b; }
                else o += (char)c;
        }
    }
    return o;
}

static size_t write_cb(char* ptr, size_t size, size_t nmemb, void* ud) {
    auto* s = (std::string*)ud;
    s->append(ptr, size * nmemb);
    return size * nmemb;
}

static std::string extract_json_string(const std::string& body, const std::string& key) {
    std::string needle = "\"" + key + "\"";
    size_t p = body.find(needle);
    if (p == std::string::npos) return "";
    p = body.find(':', p);
    if (p == std::string::npos) return "";
    p = body.find('"', p);
    if (p == std::string::npos) return "";
    ++p;
    std::string out;
    while (p < body.size() && body[p] != '"') {
        if (body[p] == '\\' && p+1 < body.size()) { out += body[p+1]; p += 2; }
        else { out += body[p++]; }
    }
    return out;
}

// ────── PUT file via Commit API ──────
bool put_file(const std::string& path, const std::string& content, const std::string& commit_msg) {
    if (!enabled()) return false;

    // NDJSON Body (newline-delimited JSON)
    std::string body;
    body += "{\"key\":\"header\",\"value\":{\"summary\":\"" + json_escape(commit_msg) + "\"}}\n";
    body += "{\"key\":\"file\",\"value\":{\"content\":\"" + base64_encode(content) +
            "\",\"encoding\":\"base64\",\"path\":\"" + json_escape(path) + "\"}}\n";

    CURL* c = curl_easy_init();
    if (!c) return false;
    std::string url = "https://huggingface.co/api/datasets/" + g_repo + "/commit/main";
    std::string resp;
    struct curl_slist* hdr = nullptr;
    hdr = curl_slist_append(hdr, ("Authorization: Bearer " + g_token).c_str());
    hdr = curl_slist_append(hdr, "User-Agent: KI-Brain-Sync");
    hdr = curl_slist_append(hdr, "Content-Type: application/x-ndjson");
    curl_easy_setopt(c, CURLOPT_URL, url.c_str());
    curl_easy_setopt(c, CURLOPT_HTTPHEADER, hdr);
    curl_easy_setopt(c, CURLOPT_CUSTOMREQUEST, "POST");
    curl_easy_setopt(c, CURLOPT_POSTFIELDS, body.c_str());
    curl_easy_setopt(c, CURLOPT_POSTFIELDSIZE, (long)body.size());
    curl_easy_setopt(c, CURLOPT_TIMEOUT, 30L);
    curl_easy_setopt(c, CURLOPT_WRITEFUNCTION, write_cb);
    curl_easy_setopt(c, CURLOPT_WRITEDATA, &resp);
    CURLcode rc = curl_easy_perform(c);
    long code = 0;
    curl_easy_getinfo(c, CURLINFO_RESPONSE_CODE, &code);
    curl_slist_free_all(hdr);
    curl_easy_cleanup(c);

    if (rc != CURLE_OK) {
        std::cerr << "[hf] POST " << path << " curl error: " << curl_easy_strerror(rc) << std::endl;
        return false;
    }
    if (code < 200 || code >= 300) {
        std::cerr << "[hf] POST " << path << " HTTP " << code << ": " << resp.substr(0, 200) << std::endl;
        return false;
    }
    std::cout << "[hf] +" << path << " (HTTP " << code << ")" << std::endl;
    return true;
}

// ────── GET file ──────
std::string get_file(const std::string& path) {
    if (!enabled()) return "";
    CURL* c = curl_easy_init();
    if (!c) return "";
    std::string url = "https://huggingface.co/datasets/" + g_repo + "/resolve/main/" + path;
    std::string out;
    struct curl_slist* hdr = nullptr;
    hdr = curl_slist_append(hdr, ("Authorization: Bearer " + g_token).c_str());
    hdr = curl_slist_append(hdr, "User-Agent: KI-Brain-Sync");
    curl_easy_setopt(c, CURLOPT_URL, url.c_str());
    curl_easy_setopt(c, CURLOPT_HTTPHEADER, hdr);
    curl_easy_setopt(c, CURLOPT_FOLLOWLOCATION, 1L);
    curl_easy_setopt(c, CURLOPT_TIMEOUT, 20L);
    curl_easy_setopt(c, CURLOPT_WRITEFUNCTION, write_cb);
    curl_easy_setopt(c, CURLOPT_WRITEDATA, &out);
    curl_easy_perform(c);
    long code = 0;
    curl_easy_getinfo(c, CURLINFO_RESPONSE_CODE, &code);
    curl_slist_free_all(hdr);
    curl_easy_cleanup(c);
    if (code != 200) return "";
    return out;   // direkter Datei-Inhalt, kein base64
}

// ────── Tree (rekursiv) via /api/datasets/{repo}/tree/main/... ──────
static void list_recurse(const std::string& path, std::vector<RemoteEntry>& out) {
    CURL* c = curl_easy_init();
    if (!c) return;
    std::string url = "https://huggingface.co/api/datasets/" + g_repo + "/tree/main/" + path;
    std::string body;
    struct curl_slist* hdr = nullptr;
    hdr = curl_slist_append(hdr, ("Authorization: Bearer " + g_token).c_str());
    hdr = curl_slist_append(hdr, "User-Agent: KI-Brain-Sync");
    curl_easy_setopt(c, CURLOPT_URL, url.c_str());
    curl_easy_setopt(c, CURLOPT_HTTPHEADER, hdr);
    curl_easy_setopt(c, CURLOPT_TIMEOUT, 15L);
    curl_easy_setopt(c, CURLOPT_WRITEFUNCTION, write_cb);
    curl_easy_setopt(c, CURLOPT_WRITEDATA, &body);
    curl_easy_perform(c);
    long code = 0;
    curl_easy_getinfo(c, CURLINFO_RESPONSE_CODE, &code);
    curl_slist_free_all(hdr);
    curl_easy_cleanup(c);
    if (code != 200) return;

    // Parse JSON array - extract "path" and "type"
    size_t pos = 0;
    while (true) {
        size_t pType = body.find("\"type\":\"", pos);
        if (pType == std::string::npos) break;
        pType += 8;
        size_t tEnd = body.find('"', pType);
        std::string type = body.substr(pType, tEnd - pType);

        size_t pPath = body.find("\"path\":\"", tEnd);
        if (pPath == std::string::npos) break;
        pPath += 8;
        size_t pEnd = body.find('"', pPath);
        std::string entryPath = body.substr(pPath, pEnd - pPath);
        pos = pEnd + 1;

        // Strip "brain/" prefix for our local view
        std::string relPath = entryPath;
        const std::string prefix = "brain/";
        if (relPath.rfind(prefix, 0) == 0) relPath = relPath.substr(prefix.size());

        if (type == "directory" || type == "dir") {
            RemoteEntry e; e.path = relPath; e.is_dir = 1; e.content = "";
            out.push_back(e);
            list_recurse(entryPath, out);
        } else {
            // Skip very large files for the brain-cache (>5MB)
            // We still let the user know via metadata
            RemoteEntry e; e.path = relPath; e.is_dir = 0;
            e.content = get_file(entryPath);
            // Falls Datei zu groß β†’ leeren Content
            if (e.content.size() > 5*1024*1024) e.content = "[FILE TOO LARGE FOR CACHE]";
            out.push_back(e);
        }
    }
}

std::vector<RemoteEntry> pull_brain() {
    std::vector<RemoteEntry> result;
    if (!enabled()) return result;
    std::cout << "[hf] pulling brain/ from " << g_repo << " ..." << std::endl;
    list_recurse("brain", result);
    std::cout << "[hf] pulled " << result.size() << " entries" << std::endl;
    return result;
}

} // namespace hf