Spaces:
Running

File size: 10,652 Bytes
23d27dd
 
0aee05c
23d27dd
 
 
 
 
 
c181f01
 
23d27dd
c181f01
23d27dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34f6aa9
0aee05c
34f6aa9
 
 
23d27dd
34f6aa9
0aee05c
34f6aa9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23d27dd
 
 
 
 
34f6aa9
23d27dd
c181f01
23d27dd
34f6aa9
 
23d27dd
34f6aa9
 
 
 
 
 
 
 
 
 
 
 
 
 
0aee05c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34f6aa9
 
0aee05c
23d27dd
 
0aee05c
 
 
 
23d27dd
0aee05c
 
23d27dd
 
 
 
 
34f6aa9
23d27dd
 
 
 
 
c181f01
23d27dd
c181f01
23d27dd
 
 
 
 
c181f01
34f6aa9
c181f01
 
 
 
 
34f6aa9
 
 
16a2b33
 
23d27dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// SPDX-License-Identifier: MIT
// drAIML · Bonsai in this browser. The page side of draiml/bonsai.py: it owns the browseML engine (bankML compiled to
// WebAssembly, browseml/ — MIT OR Apache-2.0) and the drAIML agreement. Python (Streamlit, in a Web Worker on this
// origin) asks over a BroadcastChannel; nothing here talks to any server except the model's own download.

const CHANNEL = "draiml-bonsai";
const AGREE_KEY = "draiml-bonsai-agreement";
const AGREEMENT_VERSION = 1;

import { Donor } from "./dmind.js";

let engine = null;              // the browseml.js module, imported on first use
let visitorBusy = false;        // the visitor's own question is being answered: lending waits
const mod = async () => (engine ||= await import("./browseml/browseml.js"));

const agreed = () => {
  try { const a = JSON.parse(localStorage.getItem(AGREE_KEY) || "null"); return !!a && a.v === AGREEMENT_VERSION; }
  catch { return false; }
};
const remember = () => { try { localStorage.setItem(AGREE_KEY, JSON.stringify({ v: AGREEMENT_VERSION, at: new Date().toISOString() })); } catch {} };

async function sha256hex(text) {
  const d = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text));
  return [...new Uint8Array(d)].map((b) => b.toString(16).padStart(2, "0")).join("");
}
const mb = (n) => (n / 1048576).toFixed(0);

// ── the Agreement ─────────────────────────────────────────────────────────────────────────────────────────────────
function agreement(cachedAlready) {
  return new Promise((resolve) => {
    const dlg = document.getElementById("bonsai-agreement");
    const go = dlg.querySelector("[data-agree]");
    const no = dlg.querySelector("[data-decline]");
    go.textContent = cachedAlready ? "I agree — start Bonsai" : "I agree — download 248 MB and start";
    dlg.querySelector("[data-progress]").hidden = true;
    go.disabled = false; no.disabled = false;
    const done = (yes) => { go.onclick = no.onclick = dlg.oncancel = null; resolve(yes); };
    go.onclick = () => { remember(); done(true); };
    no.onclick = () => { dlg.close(); done(false); };
    dlg.oncancel = () => done(false);
    dlg.showModal();
    go.focus();
  });
}

function showProgress(text, frac) {
  const dlg = document.getElementById("bonsai-agreement");
  const box = dlg.querySelector("[data-progress]");
  box.hidden = false;
  box.querySelector("span").textContent = text;
  const bar = box.querySelector("i");
  bar.style.width = frac == null ? "100%" : `${Math.round(frac * 100)}%`;
  dlg.querySelector("[data-agree]").disabled = true;
  chip(text);
}

function chip(text, state = "busy") {
  const c = document.getElementById("bonsai-chip");
  if (!c) return;
  c.hidden = !text;
  c.textContent = text;
  c.dataset.state = state;
}

// ── the engine, shared by the bridge (Python) and the donation panel ─────────────────────────────────────────────
/** Donate compute to drAIML.dmind: lends the engine Bonsai already loaded (so it starts after the drAIML agreement). */
export const donor = new Donor(async () => { const b = await mod(); if (!b.isReady()) throw new Error("Bonsai is not loaded"); return b; }, () => visitorBusy,
  (text, state) => { const c = document.getElementById("dmind-chip"); if (!c) return; c.hidden = !text; c.textContent = text; c.dataset.state = state === "sharing" ? "ready" : "busy"; });
export { mod as engineModule };

let ensuring = null;
/** Load Bonsai, after the drAIML agreement when this browser has not agreed or holds no copy. Resolves to what bankML
 *  verified, or null when the visitor declines. One load at a time. */
export function ensureEngine(onProgress = () => {}) {
  ensuring ||= ensureOnce(onProgress).finally(() => { ensuring = null; });
  return ensuring;
}
async function ensureOnce(onProgress) {
  const b = await mod();
  if (b.isReady()) return { model: b.MODEL.title, threads: b.loadStats && b.loadStats.threads };
  const cachedAlready = await b.isCached();
  if (!(agreed() && cachedAlready)) {
    if (!(await agreement(cachedAlready))) return null;
  } else {
    document.getElementById("bonsai-agreement").showModal();
  }
  const say = (text, frac) => { showProgress(text, frac); onProgress(text, frac); };
  say(cachedAlready ? "Opening Bonsai from this browser…" : "Downloading Bonsai…", 0);
  // half the cores (at most 4): Streamlit's own Python worker shares this tab, and all cores at once
  // crashed a 4-core, 6 GB laptop while the engine opened
  const threads = Math.max(1, Math.min(4, Math.floor((navigator.hardwareConcurrency || 2) / 2)));
  const e = donor.engineOptions();   // the visitor's GPU choice (off unless they turned it on)
  try {
    const info = await b.load((got, total, phase) => {
      if (phase === "download") say(`Downloading Bonsai · ${mb(got)} of ${mb(total)} MB`, got / total);
      else if (phase === "retry") say(`Connection cut at ${mb(got)} MB · resuming…`, got / total);
      else if (phase === "cache") say("Bonsai found in this browser", 1);
      else if (phase === "verify") say("Checking the model against its sha256 pin and starting bankML…", null);
    }, () => {}, { threads, ...e });
    chip("Bonsai · ready in this browser", "ready");
    if (donor.ledger.on && !donor.running) donor.start();   // a donation pledged earlier resumes with the engine
    return { model: b.MODEL.title, sha256: info.sha256, threads: info.threads };
  } finally {
    document.getElementById("bonsai-agreement").close();
  }
}
/** Start the engine again with new options (the GPU share): waits for the answer being written, if any. */
export async function reloadEngine(onProgress = () => {}) {
  const b = await mod();
  for (let i = 0; i < 600 && (b.isBusy() || visitorBusy); i++) await new Promise((r) => setTimeout(r, 500));
  const wasOn = donor.running;
  if (wasOn) donor.stop();
  if (b.isReady()) b.unload();
  const info = await ensureEngine(onProgress);
  if (info && wasOn) donor.settings({ on: true });
  return info;
}

// ── the bridge ────────────────────────────────────────────────────────────────────────────────────────────────────
// Python asks over a MessagePort handed to Streamlit's own worker. Inside huggingface.co's frame the browser partitions
// BroadcastChannel (the worker and this page land in different partitions), so the channel stays only as a fallback.
let handler = null;
/** Call before stlite mounts: watches the workers this page starts and answers a "draiml:hello" with a port. */
export function captureWorkers(pageId) {
  const Native = window.Worker;
  if (!Native || Native.__draiml) return;
  class Watched extends Native {
    constructor(...args) {
      super(...args);
      this.addEventListener("message", (ev) => {
        const d = ev.data;
        if (!d || d.type !== "draiml:hello" || d.page !== pageId) return;
        const mc = new MessageChannel();
        mc.port1.onmessage = (e) => handler && handler(e.data || {}, (msg) => mc.port1.postMessage(msg));
        this.postMessage({ type: "draiml:bridge", page: pageId }, [mc.port2]);
      });
    }
  }
  Watched.__draiml = true;
  window.Worker = Watched;
}

export function startBridge(pageId, { signin } = {}) {
  const ch = new BroadcastChannel(CHANNEL);
  ch.onmessage = (ev) => {
    const m = ev.data || {};
    if (m.to !== "page:" + pageId) return;
    handler(m, (msg) => ch.postMessage(msg));
  };

  handler = async (m, send) => {
    const { id, type } = m;
    const reply = (rid, msg) => send({ ...msg, id: rid, to: "py:" + pageId });
    const ensure = (rid) => ensureEngine((text, frac) => reply(rid, { type: "progress", text, frac }));
    try {
      if (type === "status") {
        const b = await mod();  // importing the module is small: the engine and the model load only on ensure
        reply(id, { type: "status", agreed: agreed(), loaded: b.isReady(), loading: b.isLoading(), cached: await b.isCached() });
      } else if (type === "ensure") {
        const info = await ensure(id);
        reply(id, info ? { type: "ready", info } : { type: "declined" });
      } else if (type === "chat") {
        const b = await mod();
        if (!b.isReady()) throw new Error("Bonsai is not loaded yet");
        let text = "";
        visitorBusy = true;
        const result = await b.chat({ messages: m.messages, max_tokens: m.max_tokens || 700, temperature: m.temperature ?? 0.3, repeat_penalty: m.repeat_penalty ?? 1.1 },
          (piece) => { text += piece; reply(id, { type: "piece", text: piece }); }).finally(() => { visitorBusy = false; });
        const rc = result && result.bankml_receipt;
        const ok = !!rc && (await sha256hex(text)) === rc.response_sha256;
        const t = (result && result.timings) || {};
        const speed = t.predicted_per_second ? ` · ${t.predicted_per_second.toFixed(1)} tok/s` : "";
        reply(id, { type: "done", verdict: rc ? `${ok ? "✓" : "✗"} bankML receipt · answer sha256 ${ok ? "matches" : "does NOT match"}${speed}` : "no receipt" });
      } else if (type === "donate") {
        if (m.on && !(await ensure(id))) { reply(id, { type: "status", ...(await donor.status()), declined: true }); return; }
        donor.settings({ on: m.on, pct: m.pct, wallet: m.wallet });
        await new Promise((r) => setTimeout(r, 300));
        reply(id, { type: "status", ...(await donor.status()) });
      } else if (type === "donate_status") {
        reply(id, { type: "status", ...(await donor.status()) });
      } else if (type === "open_donate") {
        window.dispatchEvent(new CustomEvent("draiml:donate"));
        reply(id, { type: "done" });
      } else if (type === "signin") {
        if (signin) signin();
      } else if (type === "forget") {
        const b = await mod();
        try { b.exit(); } catch {}
        await b.forget();
        try { localStorage.removeItem(AGREE_KEY); } catch {}
        chip("");
        reply(id, { type: "done" });
      }
    } catch (e) {
      const dlg = document.getElementById("bonsai-agreement");
      if (dlg.open && type === "ensure") dlg.close();
      chip("");
      reply(id, { type: "error", message: String((e && e.message) || e) });
    }
  };
}