codelion commited on
Commit
33e08f1
·
verified ·
1 Parent(s): f92de84

Fix the endpoint on the host: remove key, URL and model fields; add a Review step; document DI_* settings

Browse files
Files changed (3) hide show
  1. README.md +14 -2
  2. app/main.py +10 -32
  3. static/app.js +21 -44
README.md CHANGED
@@ -26,9 +26,21 @@ It works with any OpenAI-compatible endpoint. The default is a free model served
26
 
27
  ```bash
28
  pip install -r requirements.txt
29
- cd app && HF_TOKEN=hf_... uvicorn main:app --port 7860
30
  ```
31
 
32
- Settings: `MAX_ROWS` (default 200), `MAX_RUNNING` (default 2), `HF_TOKEN` (used only for the Hugging Face router).
 
 
 
 
 
 
 
 
 
 
 
 
33
 
34
  Not affiliated with Adaption Labs.
 
26
 
27
  ```bash
28
  pip install -r requirements.txt
29
+ cd app && DI_API_KEY=... uvicorn main:app --port 7860
30
  ```
31
 
32
+ The model endpoint is fixed by the host, so visitors never enter a key or a URL. Configure it with environment variables:
33
+
34
+ | Variable | Default | What it does |
35
+ |---|---|---|
36
+ | `DI_API_KEY` | `HF_TOKEN` | Key for the endpoint |
37
+ | `DI_BASE_URL` | `https://router.huggingface.co/v1` | Any OpenAI-compatible base URL |
38
+ | `DI_MODEL` | `prism-ml/Ternary-Bonsai-27B-AWQ-4bit:together` | Model name |
39
+ | `DI_DISABLE_THINKING` | `1` | Turns thinking off for reasoning models. Set `0` for endpoints that reject the setting |
40
+ | `DI_WORKERS` | `4` | Parallel calls (1 to 8) |
41
+ | `MAX_ROWS` | `200` | Rows per run |
42
+ | `MAX_RUNNING` | `2` | Runs at once |
43
+
44
+ To use your own model, clone the Space and set `DI_BASE_URL`, `DI_MODEL` and `DI_API_KEY` as Space secrets and variables.
45
 
46
  Not affiliated with Adaption Labs.
app/main.py CHANGED
@@ -13,7 +13,7 @@ from pathlib import Path
13
  from fastapi import FastAPI, HTTPException
14
  from fastapi.responses import FileResponse, JSONResponse, Response
15
  from fastapi.staticfiles import StaticFiles
16
- from pydantic import BaseModel, Field
17
 
18
  from engine import HF_BASE, HF_MODEL, Endpoint, EndpointError, Job, make_blueprint, run_job, stats
19
 
@@ -29,16 +29,7 @@ ENDPOINTS: dict[str, Endpoint] = {} # kept apart from Job so a key never lands
29
  GUARD = threading.Lock()
30
 
31
 
32
- class EngineIn(BaseModel):
33
- base_url: str = HF_BASE
34
- api_key: str = ""
35
- model: str = HF_MODEL
36
- disable_thinking: bool = True
37
- workers: int = 4
38
-
39
-
40
  class SpecIn(BaseModel):
41
- engine: EngineIn = Field(default_factory=EngineIn)
42
  format: str = "instruction"
43
  request: str
44
  domains: list[str] = []
@@ -49,23 +40,18 @@ class SpecIn(BaseModel):
49
  blueprint: dict | None = None
50
 
51
 
52
- def make_endpoint(e: EngineIn) -> Endpoint:
53
- base = e.base_url.strip().rstrip("/")
54
- if not base.startswith(("http://", "https://")):
55
- raise HTTPException(400, "The base URL must start with http:// or https://.")
56
- key = e.api_key.strip()
57
  if not key:
58
- if base == HF_BASE and SERVER_KEY:
59
- key = SERVER_KEY # the hosted default only ever talks to the Hugging Face router
60
- else:
61
- raise HTTPException(400, "Add an API key for this endpoint.")
62
- return Endpoint(base_url=base, api_key=key, model=e.model.strip() or HF_MODEL,
63
- disable_thinking=e.disable_thinking, workers=max(1, min(e.workers, 8)))
64
 
65
 
66
  @app.get("/api/defaults")
67
  def defaults():
68
- return {"base_url": HF_BASE, "model": HF_MODEL, "hosted_key": bool(SERVER_KEY), "max_rows": MAX_ROWS}
69
 
70
 
71
  @app.get("/api/domains")
@@ -73,17 +59,9 @@ def domains():
73
  return JSONResponse(json.loads((STATIC / "domains.json").read_text()))
74
 
75
 
76
- @app.post("/api/ping")
77
- def ping(e: EngineIn):
78
- try:
79
- return make_endpoint(e).ping()
80
- except EndpointError as err:
81
- raise HTTPException(502, str(err))
82
-
83
-
84
  @app.post("/api/blueprint")
85
  def blueprint(s: SpecIn):
86
- ep = make_endpoint(s.engine)
87
  if not s.request.strip():
88
  raise HTTPException(400, "Describe the dataset first.")
89
  try:
@@ -94,7 +72,7 @@ def blueprint(s: SpecIn):
94
 
95
  @app.post("/api/jobs")
96
  def start(s: SpecIn):
97
- ep = make_endpoint(s.engine)
98
  if not s.request.strip():
99
  raise HTTPException(400, "Describe the dataset first.")
100
  if not 1 <= s.rows <= MAX_ROWS:
 
13
  from fastapi import FastAPI, HTTPException
14
  from fastapi.responses import FileResponse, JSONResponse, Response
15
  from fastapi.staticfiles import StaticFiles
16
+ from pydantic import BaseModel
17
 
18
  from engine import HF_BASE, HF_MODEL, Endpoint, EndpointError, Job, make_blueprint, run_job, stats
19
 
 
29
  GUARD = threading.Lock()
30
 
31
 
 
 
 
 
 
 
 
 
32
  class SpecIn(BaseModel):
 
33
  format: str = "instruction"
34
  request: str
35
  domains: list[str] = []
 
40
  blueprint: dict | None = None
41
 
42
 
43
+ def make_endpoint() -> Endpoint:
44
+ """The endpoint is fixed by the host (environment variables). Visitors never supply a URL or a key."""
45
+ key = os.environ.get("DI_API_KEY") or SERVER_KEY
 
 
46
  if not key:
47
+ raise HTTPException(503, "This host has no model configured. Set DI_API_KEY (or HF_TOKEN) and restart.")
48
+ return Endpoint(base_url=os.environ.get("DI_BASE_URL", HF_BASE).rstrip("/"), api_key=key, model=os.environ.get("DI_MODEL", HF_MODEL),
49
+ disable_thinking=os.environ.get("DI_DISABLE_THINKING", "1") != "0", workers=max(1, min(int(os.environ.get("DI_WORKERS", "4")), 8)))
 
 
 
50
 
51
 
52
  @app.get("/api/defaults")
53
  def defaults():
54
+ return {"model": os.environ.get("DI_MODEL", HF_MODEL), "configured": bool(os.environ.get("DI_API_KEY") or SERVER_KEY), "max_rows": MAX_ROWS}
55
 
56
 
57
  @app.get("/api/domains")
 
59
  return JSONResponse(json.loads((STATIC / "domains.json").read_text()))
60
 
61
 
 
 
 
 
 
 
 
 
62
  @app.post("/api/blueprint")
63
  def blueprint(s: SpecIn):
64
+ ep = make_endpoint()
65
  if not s.request.strip():
66
  raise HTTPException(400, "Describe the dataset first.")
67
  try:
 
72
 
73
  @app.post("/api/jobs")
74
  def start(s: SpecIn):
75
+ ep = make_endpoint()
76
  if not s.request.strip():
77
  raise HTTPException(400, "Describe the dataset first.")
78
  if not 1 <= s.rows <= MAX_ROWS:
static/app.js CHANGED
@@ -1,12 +1,7 @@
1
  "use strict";
2
- const STEPS = ["Format", "Domains", "Subdomains", "Languages", "Summary", "Engine", "Run"];
3
  const LANGS = ["English", "Spanish", "French", "German", "Portuguese", "Italian", "Dutch", "Hindi", "Bengali", "Arabic", "Turkish", "Russian", "Polish", "Ukrainian",
4
  "Chinese", "Japanese", "Korean", "Vietnamese", "Indonesian", "Thai", "Swahili", "Serbian", "Greek", "Hebrew"];
5
- const PRESETS = {
6
- hf: { label: "Hugging Face, free", base_url: "https://router.huggingface.co/v1", model: "prism-ml/Ternary-Bonsai-27B-AWQ-4bit:together", disable_thinking: true },
7
- openai: { label: "OpenAI", base_url: "https://api.openai.com/v1", model: "gpt-4o-mini", disable_thinking: false },
8
- local: { label: "Local server", base_url: "http://localhost:11434/v1", model: "llama3.1", disable_thinking: false },
9
- };
10
  const FORMATS = {
11
  instruction: { name: "Instruction pairs", blurb: "A prompt and the reply you want a model to learn. Use it for supervised fine-tuning.",
12
  eg: [["Prompt", "My hardcover arrived with a bent corner. Can I swap it?"], ["Completion", "Sorry about that. Yes, send a photo of the corner and we will ship a replacement today, no need to return the damaged copy."]] },
@@ -16,8 +11,7 @@ const FORMATS = {
16
 
17
  const S = {
18
  step: 0, maxStep: 0, format: "instruction", domains: [], subs: {}, languages: ["English"], request: "", constraints: "", rows: 50,
19
- blueprint: null, bpBusy: false, bpError: "", engine: { base_url: PRESETS.hf.base_url, model: PRESETS.hf.model, api_key: "", disable_thinking: true, workers: 4 },
20
- preset: "hf", ping: null, pinging: false, job: null, jobRows: [], jobState: null, drawn: 0, printed: 0, hosted: false, maxRows: 200, domainData: [], runError: "",
21
  };
22
  const $ = (s, el = document) => el.querySelector(s);
23
  const esc = (t) => String(t ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[c]));
@@ -29,7 +23,7 @@ async function api(path, body, method) {
29
  if (!r.ok) throw new Error((data && (data.detail || data.message)) || `Request failed (${r.status})`);
30
  return data;
31
  }
32
- const spec = () => ({ engine: S.engine, format: S.format, request: S.request.trim(), domains: S.domains, subdomains: Object.values(S.subs).flat(),
33
  languages: S.languages, constraints: S.constraints, rows: S.rows, blueprint: S.blueprint });
34
 
35
  /* ------------------------------------------------------------ chrome */
@@ -40,9 +34,9 @@ function renderLedger() {
40
  }).join("");
41
  }
42
  function estimate() {
43
- const per = S.format === "preference" ? 4.4 : 2.5, lat = (S.ping && S.ping.latency_ms) || 1800;
44
  const calls = Math.round(S.rows * per + 2);
45
- const secs = Math.max(10, Math.round((calls * lat) / 1000 / Math.max(1, S.engine.workers)));
46
  const t = secs >= 3600 ? `${(secs / 3600).toFixed(1)} hours` : secs >= 90 ? `${Math.round(secs / 60)} minutes` : `${secs} seconds`;
47
  return { calls, time: t };
48
  }
@@ -55,7 +49,7 @@ function renderSheet() {
55
  ${line("Subdomains", subs.length ? esc(subs.slice(0, 6).join(", ")) + (subs.length > 6 ? ` and ${subs.length - 6} more` : "") : '<span class="hint">All</span>')}
56
  ${line("Languages", esc(S.languages.join(", ")))}
57
  ${line("Rows", S.rows.toLocaleString())}
58
- ${line("Model", esc(S.engine.model))}
59
  </dl><p class="est">About <b>${e.calls.toLocaleString()}</b> model calls and <b>${e.time}</b> on this setup.</p>`;
60
  }
61
  function go(i) { S.step = i; S.maxStep = Math.max(S.maxStep, i); render(); $("#panel").focus({ preventScroll: true }); window.scrollTo({ top: 0 }); }
@@ -117,20 +111,17 @@ function stepSummary() {
117
  ${S.bpError ? `<p class="note bad">${esc(S.bpError)}</p>` : ""}${bpView()}</div>
118
  ${actions(true, "Continue", !!S.request.trim())}`;
119
  }
120
- function stepEngine() {
121
- const p = S.ping;
122
- return `<h2>Choose the model that writes the rows</h2>
123
- <p class="lede">DataInventor works with any OpenAI-compatible endpoint. The default is a free model on Hugging Face.</p>
124
- <div class="seg" role="group" aria-label="Presets">${Object.entries(PRESETS).map(([k, v]) => `<button data-preset="${k}" aria-pressed="${S.preset === k}">${v.label}</button>`).join("")}</div>
125
- <label class="f"><span>Base URL</span><input class="in" id="base_url" value="${esc(S.engine.base_url)}" spellcheck="false"></label>
126
- <div class="row2"><label class="f"><span>Model</span><input class="in" id="model" value="${esc(S.engine.model)}" spellcheck="false"></label>
127
- <label class="f"><span>API key</span><input class="in" id="api_key" type="password" autocomplete="off" placeholder="${S.preset === "hf" && S.hosted ? "Optional here. The host supplies one." : "Paste a key"}" value="${esc(S.engine.api_key)}"></label></div>
128
- <p class="hint" style="margin-top:6px">The key is used for this run only. It is not stored.${S.preset === "local" ? " A hosted Space cannot reach localhost. Run DataInventor on your machine to use a local server." : ""}</p>
129
- <label class="check"><input type="checkbox" id="think" ${S.engine.disable_thinking ? "checked" : ""}><span><b>Turn thinking off</b><br><span class="hint">For reasoning models that return empty text until they finish thinking. It makes each call several times faster. Leave it off for endpoints that reject the setting.</span></span></label>
130
- <label class="f" style="max-width:240px"><span>Parallel calls</span><input class="in" id="workers" type="number" min="1" max="8" value="${S.engine.workers}"></label>
131
- <div class="actions"><button class="btn" data-act="ping" ${S.pinging ? "disabled" : ""}>${S.pinging ? "Testing" : "Test the connection"}</button>
132
- ${p ? (p.ok ? `<span class="note ok" style="margin:0">Connected. One call took ${p.latency_ms} ms.</span>` : `<span class="note bad" style="margin:0">${esc(p.error)}</span>`) : ""}</div>
133
- ${actions(true, "Review and start")}`;
134
  }
135
  const isFinal = (j) => j && ["done", "stopped", "failed"].includes(j.state);
136
  function rowHtml(r) {
@@ -182,7 +173,7 @@ function updateRun() {
182
  /* ------------------------------------------------------------ render + events */
183
  function render() {
184
  renderLedger(); renderSheet();
185
- const fn = [stepFormat, stepDomains, stepSubs, stepLangs, stepSummary, stepEngine, stepRun][S.step];
186
  const keep = document.activeElement && document.activeElement.id;
187
  $("#panel").innerHTML = fn();
188
  if (keep) { const el = document.getElementById(keep); if (el) { el.focus(); if (el.setSelectionRange && el.type !== "number") { const l = el.value.length; try { el.setSelectionRange(l, l); } catch (e) { /* ok */ } } } }
@@ -195,13 +186,11 @@ document.addEventListener("click", async (ev) => {
195
  if (t.dataset.sub) { const [d, s] = t.dataset.sub.split("|"); const cur = S.subs[d] || []; S.subs[d] = cur.includes(s) ? cur.filter((x) => x !== s) : [...cur, s]; S.blueprint = null; return render(); }
196
  if (t.dataset.lang) { const l = t.dataset.lang; S.languages = S.languages.includes(l) ? S.languages.filter((x) => x !== l) : [...S.languages, l]; S.blueprint = null; return render(); }
197
  if (t.dataset.rows) { S.rows = +t.dataset.rows; return render(); }
198
- if (t.dataset.preset) { const p = PRESETS[t.dataset.preset]; S.preset = t.dataset.preset; S.engine = { ...S.engine, base_url: p.base_url, model: p.model, disable_thinking: p.disable_thinking }; S.ping = null; return render(); }
199
  const act = t.dataset.act; if (!act) return;
200
  if (act === "next") return void go(S.step + 1);
201
  if (act === "back") return go(Math.max(0, S.step - 1));
202
  if (act === "suggest") { S.request = S.request.trim() ? S.request : $("[data-suggest]").dataset.suggest; return render(); }
203
  if (act === "blueprint") return doBlueprint();
204
- if (act === "ping") return doPing();
205
  if (act === "stop") { if (S.job) await api(`/api/jobs/${S.job}/stop`, {}); return; }
206
  if (act === "again") { S.job = null; S.jobState = null; S.jobRows = []; S.drawn = 0; S.printed = 0; S.runError = ""; return go(4); }
207
  });
@@ -209,25 +198,13 @@ document.addEventListener("input", (ev) => {
209
  const id = ev.target.id;
210
  if (id === "request") { S.request = ev.target.value; S.blueprint = null; const b = $('[data-act="next"]'); if (b) b.disabled = !S.request.trim(); const bp = $('[data-act="blueprint"]'); if (bp) bp.disabled = S.bpBusy || !S.request.trim(); }
211
  else if (id === "constraints") { S.constraints = ev.target.value; S.blueprint = null; }
212
- else if (id === "base_url") { S.engine.base_url = ev.target.value; S.preset = ""; }
213
- else if (id === "model") S.engine.model = ev.target.value;
214
- else if (id === "api_key") S.engine.api_key = ev.target.value;
215
- else if (id === "workers") { S.engine.workers = Math.max(1, Math.min(8, +ev.target.value || 1)); renderSheet(); }
216
- else if (id === "think") S.engine.disable_thinking = ev.target.checked;
217
- if (id === "model") renderSheet();
218
  });
219
- document.addEventListener("change", (ev) => { if (ev.target.id === "think") S.engine.disable_thinking = ev.target.checked; });
220
 
221
  async function doBlueprint() {
222
  S.bpBusy = true; S.bpError = ""; render();
223
  try { S.blueprint = await api("/api/blueprint", spec()); } catch (e) { S.bpError = e.message; }
224
  S.bpBusy = false; render();
225
  }
226
- async function doPing() {
227
- S.pinging = true; S.ping = null; render();
228
- try { S.ping = await api("/api/ping", S.engine); } catch (e) { S.ping = { ok: false, error: e.message }; }
229
- S.pinging = false; render();
230
- }
231
  async function startRun() {
232
  S.runError = ""; S.jobRows = []; S.jobState = null; S.drawn = 0; S.printed = 0;
233
  try { const r = await api("/api/jobs", spec()); S.job = r.id; poll(); } catch (e) { S.runError = e.message; }
@@ -244,12 +221,12 @@ async function poll() {
244
  if (j.stats && j.stats.rows) S.maxStep = 6;
245
  } catch (e) { console.error(e.stack); S.jobState = { state: "failed", message: e.message, count: S.jobRows.length, target: S.rows, elapsed: 0, id }; if (S.step === 6) render(); }
246
  }
247
- /* "Review and start" on the engine step starts the run */
248
  const _go = go;
249
- go = function (i) { const wasEngine = S.step === 5; _go(i); if (i === 6 && wasEngine && !S.jobState) startRun(); return true; };
250
 
251
  (async function init() {
252
- try { const d = await api("/api/defaults"); S.hosted = d.hosted_key; S.maxRows = d.max_rows; if (S.rows > S.maxRows) S.rows = S.maxRows; } catch (e) { /* offline */ }
253
  try { S.domainData = await api("/api/domains"); } catch (e) { S.domainData = []; }
254
  render();
255
  })();
 
1
  "use strict";
2
+ const STEPS = ["Format", "Domains", "Subdomains", "Languages", "Summary", "Review", "Run"];
3
  const LANGS = ["English", "Spanish", "French", "German", "Portuguese", "Italian", "Dutch", "Hindi", "Bengali", "Arabic", "Turkish", "Russian", "Polish", "Ukrainian",
4
  "Chinese", "Japanese", "Korean", "Vietnamese", "Indonesian", "Thai", "Swahili", "Serbian", "Greek", "Hebrew"];
 
 
 
 
 
5
  const FORMATS = {
6
  instruction: { name: "Instruction pairs", blurb: "A prompt and the reply you want a model to learn. Use it for supervised fine-tuning.",
7
  eg: [["Prompt", "My hardcover arrived with a bent corner. Can I swap it?"], ["Completion", "Sorry about that. Yes, send a photo of the corner and we will ship a replacement today, no need to return the damaged copy."]] },
 
11
 
12
  const S = {
13
  step: 0, maxStep: 0, format: "instruction", domains: [], subs: {}, languages: ["English"], request: "", constraints: "", rows: 50,
14
+ blueprint: null, bpBusy: false, bpError: "", model: "", job: null, jobRows: [], jobState: null, drawn: 0, printed: 0, maxRows: 200, domainData: [], runError: "",
 
15
  };
16
  const $ = (s, el = document) => el.querySelector(s);
17
  const esc = (t) => String(t ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[c]));
 
23
  if (!r.ok) throw new Error((data && (data.detail || data.message)) || `Request failed (${r.status})`);
24
  return data;
25
  }
26
+ const spec = () => ({ format: S.format, request: S.request.trim(), domains: S.domains, subdomains: Object.values(S.subs).flat(),
27
  languages: S.languages, constraints: S.constraints, rows: S.rows, blueprint: S.blueprint });
28
 
29
  /* ------------------------------------------------------------ chrome */
 
34
  }).join("");
35
  }
36
  function estimate() {
37
+ const per = S.format === "preference" ? 4.4 : 2.5, lat = 5500, workers = 4;
38
  const calls = Math.round(S.rows * per + 2);
39
+ const secs = Math.max(10, Math.round((calls * lat) / 1000 / workers));
40
  const t = secs >= 3600 ? `${(secs / 3600).toFixed(1)} hours` : secs >= 90 ? `${Math.round(secs / 60)} minutes` : `${secs} seconds`;
41
  return { calls, time: t };
42
  }
 
49
  ${line("Subdomains", subs.length ? esc(subs.slice(0, 6).join(", ")) + (subs.length > 6 ? ` and ${subs.length - 6} more` : "") : '<span class="hint">All</span>')}
50
  ${line("Languages", esc(S.languages.join(", ")))}
51
  ${line("Rows", S.rows.toLocaleString())}
52
+ ${line("Model", esc(S.model || "Free model on Hugging Face"))}
53
  </dl><p class="est">About <b>${e.calls.toLocaleString()}</b> model calls and <b>${e.time}</b> on this setup.</p>`;
54
  }
55
  function go(i) { S.step = i; S.maxStep = Math.max(S.maxStep, i); render(); $("#panel").focus({ preventScroll: true }); window.scrollTo({ top: 0 }); }
 
111
  ${S.bpError ? `<p class="note bad">${esc(S.bpError)}</p>` : ""}${bpView()}</div>
112
  ${actions(true, "Continue", !!S.request.trim())}`;
113
  }
114
+ function stepReview() {
115
+ const e = estimate(), subs = Object.values(S.subs).flat();
116
+ const row = (k, v) => `<div class="bp-row"><b>${k}</b><span>${v}</span></div>`;
117
+ return `<h2>Check it, then start writing</h2>
118
+ <p class="lede">Rows are written by a free model on Hugging Face Inference Providers. You can leave this page open or come back to it while the run goes.</p>
119
+ <div class="bp">${row("Format", esc(FORMATS[S.format].name))}${row("Description", esc(S.request))}
120
+ ${row("Domains", S.domains.length ? esc(S.domains.join(", ")) : "Guided by the description")}${row("Subdomains", subs.length ? esc(subs.join(", ")) : "All")}
121
+ ${row("Languages", esc(S.languages.join(", ")))}${S.constraints.trim() ? row("Rules", esc(S.constraints)) : ""}${row("Rows", S.rows.toLocaleString())}
122
+ ${row("Blueprint", S.blueprint ? "Previewed. It will be used as shown." : "Drafted when the run starts.")}</div>
123
+ <p class="note">About <b>${e.calls.toLocaleString()}</b> model calls and <b>${e.time}</b>. Rows that fail the quality checks are rewritten, so a run can take a little longer.</p>
124
+ <div class="actions"><button class="btn" data-act="back">Back</button><button class="btn go" data-act="next">Start writing</button></div>`;
 
 
 
125
  }
126
  const isFinal = (j) => j && ["done", "stopped", "failed"].includes(j.state);
127
  function rowHtml(r) {
 
173
  /* ------------------------------------------------------------ render + events */
174
  function render() {
175
  renderLedger(); renderSheet();
176
+ const fn = [stepFormat, stepDomains, stepSubs, stepLangs, stepSummary, stepReview, stepRun][S.step];
177
  const keep = document.activeElement && document.activeElement.id;
178
  $("#panel").innerHTML = fn();
179
  if (keep) { const el = document.getElementById(keep); if (el) { el.focus(); if (el.setSelectionRange && el.type !== "number") { const l = el.value.length; try { el.setSelectionRange(l, l); } catch (e) { /* ok */ } } } }
 
186
  if (t.dataset.sub) { const [d, s] = t.dataset.sub.split("|"); const cur = S.subs[d] || []; S.subs[d] = cur.includes(s) ? cur.filter((x) => x !== s) : [...cur, s]; S.blueprint = null; return render(); }
187
  if (t.dataset.lang) { const l = t.dataset.lang; S.languages = S.languages.includes(l) ? S.languages.filter((x) => x !== l) : [...S.languages, l]; S.blueprint = null; return render(); }
188
  if (t.dataset.rows) { S.rows = +t.dataset.rows; return render(); }
 
189
  const act = t.dataset.act; if (!act) return;
190
  if (act === "next") return void go(S.step + 1);
191
  if (act === "back") return go(Math.max(0, S.step - 1));
192
  if (act === "suggest") { S.request = S.request.trim() ? S.request : $("[data-suggest]").dataset.suggest; return render(); }
193
  if (act === "blueprint") return doBlueprint();
 
194
  if (act === "stop") { if (S.job) await api(`/api/jobs/${S.job}/stop`, {}); return; }
195
  if (act === "again") { S.job = null; S.jobState = null; S.jobRows = []; S.drawn = 0; S.printed = 0; S.runError = ""; return go(4); }
196
  });
 
198
  const id = ev.target.id;
199
  if (id === "request") { S.request = ev.target.value; S.blueprint = null; const b = $('[data-act="next"]'); if (b) b.disabled = !S.request.trim(); const bp = $('[data-act="blueprint"]'); if (bp) bp.disabled = S.bpBusy || !S.request.trim(); }
200
  else if (id === "constraints") { S.constraints = ev.target.value; S.blueprint = null; }
 
 
 
 
 
 
201
  });
 
202
 
203
  async function doBlueprint() {
204
  S.bpBusy = true; S.bpError = ""; render();
205
  try { S.blueprint = await api("/api/blueprint", spec()); } catch (e) { S.bpError = e.message; }
206
  S.bpBusy = false; render();
207
  }
 
 
 
 
 
208
  async function startRun() {
209
  S.runError = ""; S.jobRows = []; S.jobState = null; S.drawn = 0; S.printed = 0;
210
  try { const r = await api("/api/jobs", spec()); S.job = r.id; poll(); } catch (e) { S.runError = e.message; }
 
221
  if (j.stats && j.stats.rows) S.maxStep = 6;
222
  } catch (e) { console.error(e.stack); S.jobState = { state: "failed", message: e.message, count: S.jobRows.length, target: S.rows, elapsed: 0, id }; if (S.step === 6) render(); }
223
  }
224
+ /* "Start writing" on the review step starts the run */
225
  const _go = go;
226
+ go = function (i) { const wasReview = S.step === 5; _go(i); if (i === 6 && wasReview && !S.jobState) startRun(); return true; };
227
 
228
  (async function init() {
229
+ try { const d = await api("/api/defaults"); S.model = d.model; S.maxRows = d.max_rows; S.configured = d.configured; if (S.rows > S.maxRows) S.rows = S.maxRows; } catch (e) { /* offline */ }
230
  try { S.domainData = await api("/api/domains"); } catch (e) { S.domainData = []; }
231
  render();
232
  })();