File size: 11,117 Bytes
f713f1f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
const PRESETS = [
  {
    label: "A Litany for Survival ©️ Audre Lorde",
    text: `For those of us who live at the shoreline
standing upon the constant edges of decision
crucial and alone
for those of us who cannot indulge
the passing dreams of choice
who love in doorways coming and going
in the hours between dawns
looking inward and outward
at once before and after
seeking a now that can breed
futures
like bread in our children’s mouths
so their dreams will not reflect
the death of ours;

For those of us
who were imprinted with fear
like a faint line in the center of our foreheads
learning to be afraid with our mother’s milk
for by this weapon
this illusion of some safety to be found
the heavy-footed hoped to silence us
For all of us
this instant and this triumph
We were never meant to survive.

And when the sun rises we are afraid
it might not remain
when the sun sets we are afraid
it might not rise in the morning
when our stomachs are full we are afraid
of indigestion
when our stomachs are empty we are afraid
we may never eat again
when we are loved we are afraid
love will vanish
when we are alone we are afraid
love will never return
and when we speak we are afraid
our words will not be heard
nor welcomed
but when we are silent
we are still afraid

So it is better to speak
remembering
we were never meant to survive.`,
  },
  {
    label: "Wild Geese ©️ Mary Oliver",
    text: `You do not have to be good.
You do not have to walk on your knees
for a hundred miles through the desert repenting.
You only have to let the soft animal of your body
love what it loves.
Tell me about despair, yours, and I will tell you mine.
Meanwhile the world goes on.
Meanwhile the sun and the clear pebbles of the rain
are moving across the landscapes,
over the prairies and the deep trees,
the mountains and the rivers.
Meanwhile the wild geese, high in the clean blue air,
are heading home again.
Whoever you are, no matter how lonely,
the world offers itself to your imagination,
calls to you like the wild geese, harsh and exciting -
over and over announcing your place
in the family of things.`,
  },
  {
    label: "i love you to the moon & ©️ Chen Chen",
    text: `not back, let’s not come back, let’s go by the speed of
queer zest & stay up
there & get ourselves a little
moon cottage (so pretty), then start a moon garden

with lots of moon veggies (so healthy), i mean
i was already moonlighting
as an online moonologist
most weekends, so this is the immensely

logical next step, are you
packing your bags yet, don’t forget your
sailor moon jean jacket, let’s wear
our sailor moon jean jackets while twirling in that lighter,

queerer moon gravity, let’s love each other
(so good) on the moon, let’s love
the moon
on the moon`,
  },
];

const poemEl = document.getElementById("poem");
const loadBtn = document.getElementById("load");
const condenseBtn = document.getElementById("condense");
const expandBtn = document.getElementById("expand");
const readtimeEl = document.getElementById("readtime");
const statusEl = document.getElementById("status");
const presetsEl = document.getElementById("presets");

const presetBtns = PRESETS.map((preset) => {
  const btn = document.createElement("button");
  btn.textContent = preset.label;
  btn.addEventListener("click", () => {
    poemEl.value = preset.text;
    updateReadingTime();
  });
  presetsEl.append(btn);
  return btn;
});

poemEl.value = PRESETS[0].text;

let ready = false;
let busy = false; // only one pass (one 2x condense or expand) runs at a time

const worker = new Worker("worker.js", { type: "module" });
const pending = new Map();
let nextId = 1;

worker.onmessage = (e) => {
  const msg = e.data;
  if (msg.type === "progress") {
    onLoadProgress(msg.data);
  } else if (msg.type === "ready") {
    ready = true;
    setWorking(loadBtn, null);
    loadBtn.style.display = "none";
    console.log("tl;cr backend:", msg.device);
    updateButtons();
  } else if (msg.id && pending.has(msg.id)) {
    const { resolve, reject } = pending.get(msg.id);
    pending.delete(msg.id);
    if (msg.type === "error") reject(new Error(msg.message));
    else resolve(msg);
  } else if (msg.type === "error") {
    showError(msg.message);
    setWorking(loadBtn, null);
    loadBtn.disabled = false;
  }
};

worker.onerror = (e) => {
  showError(`worker error: ${e.message}`);
  setWorking(loadBtn, null);
  loadBtn.disabled = false;
};

function call(payload) {
  return new Promise((resolve, reject) => {
    const id = nextId++;
    pending.set(id, { resolve, reject });
    worker.postMessage({ ...payload, id });
  });
}

// The poem is the interface: no status chatter unless something went wrong.
function showError(text) {
  statusEl.textContent = text ? `error: ${text}` : "";
}

// A busy button becomes its own progress bar, with the detail in its tooltip.
function setWorking(btn, fraction, tooltip = "") {
  if (fraction === null) {
    btn.classList.remove("working");
    btn.style.removeProperty("--progress");
    btn.title = "";
  } else {
    btn.classList.add("working");
    btn.style.setProperty("--progress", `${(fraction * 100).toFixed(1)}%`);
    btn.title = tooltip;
  }
}

function onLoadProgress({ status, file, loaded, total }) {
  if (status === "progress" && file?.endsWith(".onnx") && total) {
    const mb = (n) => (n / 1e6).toFixed(0);
    setWorking(loadBtn, loaded / total, `downloading ${file}: ${mb(loaded)} / ${mb(total)} MB`);
  }
}

function updateButtons() {
  condenseBtn.disabled = busy || !ready;
  expandBtn.disabled = busy || !ready;
  // Swapping the poem mid-pass would be overwritten by the live render.
  presetBtns.forEach((btn) => (btn.disabled = busy));
}

function updateReadingTime() {
  const words = poemEl.value.trim().split(/\s+/).filter(Boolean).length;
  const seconds = Math.round((words / 200) * 60);
  let span;
  if (seconds < 60) {
    span = `${seconds} second${seconds === 1 ? "" : "s"}`;
  } else {
    const m = Math.floor(seconds / 60);
    const s = seconds % 60;
    span = `${m} minute${m === 1 ? "" : "s"}${s ? ` ${s} second${s === 1 ? "" : "s"}` : ""}`;
  }
  readtimeEl.textContent = `Estimated reading time: ${span}`;
}

poemEl.addEventListener("input", updateReadingTime);
updateReadingTime();

// --- poem structure -------------------------------------------------------
// A poem is a list of stanzas; a stanza is a list of non-empty lines.
// Blank lines separate stanzas and survive every transformation.

function parsePoem(text) {
  const stanzas = [];
  let current = [];
  for (const rawLine of text.split("\n")) {
    const line = rawLine.trim();
    if (line === "") {
      if (current.length) stanzas.push(current);
      current = [];
    } else {
      current.push(line);
    }
  }
  if (current.length) stanzas.push(current);
  return stanzas;
}

// Consecutive single-line stanzas fuse into one stanza — without this, a
// stanza condensed down to one line could never be condensed again.
function mergeLoneStanzas(stanzas) {
  const merged = [];
  let prevLone = false;
  for (const stanza of stanzas) {
    if (stanza.length === 1 && prevLone) merged.at(-1).push(stanza[0]);
    else merged.push([...stanza]);
    prevLone = stanza.length === 1;
  }
  return merged;
}

function renderPoem(stanzas) {
  return stanzas
    .filter((s) => s.length)
    .map((s) => s.join("\n"))
    .join("\n\n");
}

// Flatten with global indices so context can cross stanza boundaries.
function flatten(stanzas) {
  const flat = [];
  stanzas.forEach((stanza, si) =>
    stanza.forEach((line, li) => flat.push({ si, li, line })),
  );
  return flat;
}

function contextAround(flat, startGlobal, span) {
  return {
    before: flat.slice(Math.max(0, startGlobal - 2), startGlobal).map((f) => f.line),
    after: flat.slice(startGlobal + span, startGlobal + span + 2).map((f) => f.line),
  };
}

// --- passes ---------------------------------------------------------------

async function condensePass() {
  const stanzas = mergeLoneStanzas(parsePoem(poemEl.value));
  const flat = flatten(stanzas);
  const totalPairs = stanzas.reduce((n, s) => n + Math.floor(s.length / 2), 0);
  if (totalPairs === 0) return;

  const result = stanzas.map(() => []);
  let globalIndex = 0;
  let done = 0;
  for (let si = 0; si < stanzas.length; si++) {
    const stanza = stanzas[si];
    for (let i = 0; i < stanza.length; i += 2) {
      if (i + 1 >= stanza.length) {
        // Odd line out passes through untouched.
        result[si].push(stanza[i]);
        globalIndex += 1;
        continue;
      }
      setWorking(condenseBtn, done / totalPairs, `condensing pair ${done + 1} of ${totalPairs}`);
      const { before, after } = contextAround(flat, globalIndex, 2);
      const { line } = await call({
        type: "condense",
        pair: [stanza[i], stanza[i + 1]],
        before,
        after,
      });
      result[si].push(line);
      globalIndex += 2;
      done += 1;
      renderLive(stanzas, result, si, i + 2);
    }
  }

  poemEl.value = renderPoem(mergeLoneStanzas(result));
  updateReadingTime();
}

async function expandPass() {
  const stanzas = parsePoem(poemEl.value);
  const flat = flatten(stanzas);
  const totalLines = flat.length;
  if (totalLines === 0) return;

  const result = stanzas.map(() => []);
  let globalIndex = 0;
  for (let si = 0; si < stanzas.length; si++) {
    const stanza = stanzas[si];
    for (let i = 0; i < stanza.length; i++) {
      setWorking(expandBtn, globalIndex / totalLines, `expanding line ${globalIndex + 1} of ${totalLines}`);
      const { before, after } = contextAround(flat, globalIndex, 1);
      const { lines } = await call({
        type: "expand",
        line: stanza[i],
        before,
        after,
      });
      result[si].push(...lines);
      globalIndex += 1;
      renderLive(stanzas, result, si, i + 1);
    }
  }

  poemEl.value = renderPoem(result);
  updateReadingTime();
}

// Show progress as the model chews: finished stanzas are new, the current
// stanza is part new / part original, later stanzas are still original.
function renderLive(stanzas, result, si, consumedInStanza) {
  const view = [];
  for (let k = 0; k < si; k++) view.push(result[k]);
  view.push([...result[si], ...stanzas[si].slice(consumedInStanza)]);
  for (let k = si + 1; k < stanzas.length; k++) view.push(stanzas[k]);
  poemEl.value = renderPoem(view);
  updateReadingTime();
}

// --- wiring ---------------------------------------------------------------

loadBtn.addEventListener("click", () => {
  loadBtn.disabled = true;
  setWorking(loadBtn, 0, "loading model…");
  showError("");
  worker.postMessage({ type: "load" });
});

async function runPass(btn, pass) {
  if (busy || !ready) return;
  busy = true;
  updateButtons();
  showError("");
  try {
    await pass();
  } catch (err) {
    showError(err.message);
  } finally {
    setWorking(btn, null);
    busy = false;
    updateButtons();
  }
}

condenseBtn.addEventListener("click", () => runPass(condenseBtn, condensePass));
expandBtn.addEventListener("click", () => runPass(expandBtn, expandPass));