File size: 10,173 Bytes
dadccad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// The Fin AI chat front end for Gradio-backed demo Spaces.
// The Space's Gradio app exposes `/chat` (gr.api, streaming); this page talks to it with @gradio/client.
// window.FA_CHAT = { client, endpoint, image: bool, examples: [{text, label, image?}], params: [{key,label,min,max,step,value}], greeting, avatar }
import { marked } from "https://cdn.jsdelivr.net/npm/marked@12.0.2/lib/marked.esm.js";
import DOMPurify from "https://cdn.jsdelivr.net/npm/dompurify@3.1.6/dist/purify.es.mjs";

const C = window.FA_CHAT;
const $ = s => document.querySelector(s);
// Gradio may run head scripts twice and renders our HTML after hydration:
// run once, and only after #fa-log exists and is the same node on two checks in a row.
if (window.__faChat) await new Promise(() => {});  // second copy: park forever
window.__faChat = true;
await new Promise(r => { let last = null; const ok = () => { const n = document.querySelector("#fa-log"); if (n && n === last) r(); else { last = n; setTimeout(ok, 120); } }; ok(); });
// @gradio/client must match the Space's Gradio major version (1.x for Gradio 5, 2.x for Gradio 6)
const { Client, handle_file } = await import(`https://cdn.jsdelivr.net/npm/@gradio/client@${C.client}/dist/index.min.js`);
const esc = s => String(s).replace(/[&<>"']/g, c => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[c]));
const md = s => DOMPurify.sanitize(marked.parse(s || "", { breaks: true }));

const log = $("#fa-log"), input = $("#fa-input"), send = $("#fa-send"), stop = $("#fa-stop"), clear = $("#fa-clear"), status = $("#fa-status");
const history = [];            // [{role, content}] text-only turns sent to the model
let stopNow = null, job = null, client = null, image = null, imageURL = null, lastImage = null, lastImageURL = null;  // lastImage: reused for follow-ups

// ---------- connection ----------
async function connect() {
  if (client) return client;
  status.dataset.state = "connecting"; status.querySelector("span").textContent = "Connecting…";
  // ask for status events too: @gradio/client 1.x only streams "data" by default, so "complete" would never arrive
  client = await Client.connect(location.origin + location.pathname.replace(/\/$/, ""), { events: ["data", "status"] });
  status.dataset.state = "ready"; status.querySelector("span").textContent = C.readyText || "Ready";
  return client;
}
connect().catch(() => { status.dataset.state = "error"; status.querySelector("span").textContent = "Could not reach the model server"; });

// ---------- messages ----------
function bubble(role, html, extra = "") {
  log.querySelector(".fa-empty")?.remove();
  const el = document.createElement("div");
  el.className = `msg ${role}${extra}`;
  el.innerHTML = role === "assistant" ? `<img class="av" src="${C.avatar}" alt=""><div class="body">${html}</div>` : `<div class="body">${html}</div>`;
  log.appendChild(el);
  log.scrollTo({ top: log.scrollHeight, behavior: "smooth" });
  return el.querySelector(".body");
}
function empty() {
  log.innerHTML = `<div class="fa-empty"><img src="${C.avatar}" alt=""><h3>${esc(C.greeting.title)}</h3><p>${esc(C.greeting.text)}</p></div>`;
}
empty();

// ---------- examples ----------
$("#fa-examples").innerHTML = C.examples.map((x, i) => `<button type="button" class="ex" data-i="${i}" style="--d:${i * 50}ms">` +
  (x.image ? `<img src="${x.image}" alt="">` : "") + `<span class="ex-label">${esc(x.label)}</span>` + (x.label !== x.text ? `<span class="ex-text">${esc(x.text)}</span>` : "") + `</button>`).join("");
$("#fa-examples").addEventListener("click", async e => {
  const b = e.target.closest(".ex"); if (!b || job) return;
  const x = C.examples[+b.dataset.i];
  if (x.image) { const blob = await (await fetch(x.image)).blob(); setImage(new File([blob], x.image.split("/").pop(), { type: blob.type })); }
  input.value = x.text; autosize(); submit();
});

// ---------- image (multimodal demos) ----------
const drop = $("#fa-image"), preview = $("#fa-preview");
function setImage(f) {
  image = f; if (imageURL && imageURL !== lastImageURL) URL.revokeObjectURL(imageURL);
  imageURL = f ? URL.createObjectURL(f) : null;
  if (preview) { preview.hidden = !f; preview.querySelector("img").src = imageURL || ""; }
}
if (C.image && drop) {
  drop.addEventListener("change", () => drop.files[0] && setImage(drop.files[0]));
  preview.querySelector("button").addEventListener("click", () => setImage(null));
  const composer = $(".composer");
  ["dragenter", "dragover"].forEach(t => composer.addEventListener(t, e => { e.preventDefault(); composer.classList.add("drag"); }));
  ["dragleave", "drop"].forEach(t => composer.addEventListener(t, e => { e.preventDefault(); composer.classList.remove("drag"); }));
  composer.addEventListener("drop", e => { const f = [...e.dataTransfer.files].find(f => f.type.startsWith("image/")); if (f) setImage(f); });
  input.addEventListener("paste", e => { const f = [...(e.clipboardData?.files || [])].find(f => f.type.startsWith("image/")); if (f) setImage(f); });
}

// ---------- params ----------
const params = Object.fromEntries(C.params.map(p => [p.key, p.value]));
$("#fa-params").innerHTML = C.params.map(p => `<label class="param"><span>${esc(p.label)}<b id="pv-${p.key}">${p.value}</b></span>` +
  `<input type="range" min="${p.min}" max="${p.max}" step="${p.step}" value="${p.value}" data-k="${p.key}"></label>`).join("");
$("#fa-params").addEventListener("input", e => { const k = e.target.dataset.k; if (!k) return; params[k] = +e.target.value; $(`#pv-${k}`).textContent = e.target.value; });

// ---------- composer ----------
function autosize() { input.style.height = "auto"; input.style.height = Math.min(input.scrollHeight, 200) + "px"; send.disabled = !input.value.trim() || !!job; }
input.addEventListener("input", autosize);
input.addEventListener("keydown", e => { if (e.key === "Enter" && !e.shiftKey && !e.isComposing) { e.preventDefault(); submit(); } });
send.addEventListener("click", submit);
stop.addEventListener("click", () => { job?.cancel(); stopNow?.(); });
clear.addEventListener("click", () => { if (job) return; history.length = 0; setImage(null); lastImage = null; empty(); });
autosize();

async function submit() {
  const text = input.value.trim();
  if (!text || job) return;
  const img = image || lastImage, imgURL = image ? imageURL : lastImageURL;
  if (C.image && !img) { flash("Add an image first: upload, drop or paste a chart or table."); return; }
  input.value = ""; autosize();
  bubble("user", (image ? `<img class="thumb" src="${imageURL}" alt="">` : img ? `<span class="reuse"><img src="${imgURL}" alt="">same image</span>` : "") + esc(text).replace(/\n/g, "<br>"));
  const out = bubble("assistant", `<span class="typing"><i></i><i></i><i></i></span>`, " pending");
  const msgEl = out.parentElement;
  document.body.classList.add("busy"); stop.hidden = false; send.hidden = true;
  let reply = "", t0 = performance.now();
  try {
    const c = await connect();
    const args = { message: text, history: history.slice(), ...params };
    if (C.image) args.image = handle_file(img);
    job = c.submit(C.endpoint, args);
    // Don't `break` out of the iterator: with @gradio/client 1.x its return() never settles. Settle on our own instead,
    // on "complete", on "error", or when Stop is pressed.
    await new Promise((resolve, reject) => {
      stopNow = resolve;
      (async () => {
        try {
          for await (const ev of job) {
            if (ev.type === "data") {
              reply = ev.data[0] ?? "";
              msgEl.classList.remove("pending");
              out.innerHTML = md(reply) + `<span class="caret"></span>`;
              log.scrollTo({ top: log.scrollHeight });
            } else if (ev.type === "status") {
              if (ev.stage === "pending" && ev.queue && ev.position > 0) out.innerHTML = `<span class="queue">In queue · position ${ev.position + 1}</span>`;
              if (ev.stage === "error") return reject(new Error(ev.message || "The model returned an error."));
              if (ev.stage === "complete") return resolve();
            }
          }
          resolve();
        } catch (err) { reject(err); }
      })();
    });
    out.innerHTML = md(reply) || `<em class="muted">No answer.</em>`;
    msgEl.insertAdjacentHTML("beforeend", `<div class="meta">${((performance.now() - t0) / 1000).toFixed(1)} s · <button type="button" class="copy">Copy</button></div>`);
    msgEl.querySelector(".copy").addEventListener("click", e => navigator.clipboard.writeText(reply).then(() => (e.target.textContent = "Copied ✓")));
    history.push({ role: "user", content: text }, { role: "assistant", content: reply });
    if (C.image && image) { lastImage = image; lastImageURL = imageURL; imageURL = null; }
  } catch (err) {
    msgEl.classList.remove("pending"); msgEl.classList.add("error");
    out.innerHTML = reply ? md(reply) : `<b>Something went wrong.</b> ${esc(err.message || err)}`;
  } finally {
    job = null; stopNow = null; document.body.classList.remove("busy"); stop.hidden = true; send.hidden = false; autosize();
    if (C.image) { image = null; if (preview) preview.hidden = true; }
  }
}

function flash(t) {
  const n = $("#fa-note"); n.textContent = t; n.classList.add("on");
  clearTimeout(flash._t); flash._t = setTimeout(() => n.classList.remove("on"), 3200);
}

// ---------- page chrome ----------
document.querySelectorAll("[data-count]").forEach(el => {
  const to = +el.dataset.count, dec = +(el.dataset.dec || 0), t0 = performance.now();
  if (matchMedia("(prefers-reduced-motion: reduce)").matches || document.hidden) { el.textContent = to.toFixed(dec); return; }
  const step = t => { const p = Math.min(1, (t - t0) / 1000); el.textContent = (to * (1 - Math.pow(1 - p, 3))).toFixed(dec); if (p < 1) requestAnimationFrame(step); };
  requestAnimationFrame(step); setTimeout(() => (el.textContent = to.toFixed(dec)), 1300);
});
const io = new IntersectionObserver(es => es.forEach(en => { if (en.isIntersecting) { en.target.classList.add("in"); io.unobserve(en.target); } }), { threshold: .1 });
document.querySelectorAll(".reveal").forEach(el => io.observe(el));