Skip to content
1        10        20        30        40        50        60        70        80        90        100       110       120       130       1401//! The playground page served at `GET /`.2//!3//! A single self-contained HTML file with a tabbed example for every endpoint.4//! The page is rendered from the `API_KEY` the server was started with, so the5//! browser never has to know how the key is stored: the HTML carries it, the6//! fetches go to relative URLs, and nothing leaves the machine.78/// Escape the key as a JSON string so quotes and unicode survive the page.9fn key_literal(api_key: &str) -> String {10    serde_json::to_string(api_key).unwrap_or_else(|_| "\"\"".to_owned())11}1213/// The page `GET /` serves, with the key already embedded.14const TEMPLATE: &str = r#"<!doctype html>15<html lang="en">16<head>17<meta charset="utf-8">18<meta name="viewport" content="width=device-width, initial-scale=1">19<title>Local Decisions · playground</title>20<style>21  /* Data-Dense Utilitarian: compact spacing, visible gridlines, 2px radii,22     cool-neutral surfaces, one restrained blue reserved for action. */23  :root {24    --bg: #f1f0eb;          /* base-100, closely spaced cool off-white */25    --surface: #fafaf7;     /* working panels sit a half-step above */26    --field: #ffffff;       /* inputs read as data entry zones */27    --line: #ced3d7;        /* gridlines */28    --line-strong: #9aa3ab; /* structural separators */29    --text: #21272d;30    --muted: #5f6870;31    --accent: #2e5e9e;      /* subdued analytical blue */32    --accent-hover: #27528a;33    --accent-ink: #ffffff;34    --ok: #1a7f37;35    --err: #c22f2f;36    --mono: ui-monospace, "SFMono-Regular", Menlo, Consolas, monospace;37    --sans: system-ui, -apple-system, "Segoe UI", sans-serif;38  }39  * { box-sizing: border-box; }40  body {41    margin: 0; background: var(--bg); color: var(--text);42    font: 13px/1.45 var(--sans);43    font-variant-numeric: tabular-nums;44  }45  header {46    padding: 10px 16px; border-bottom: 1px solid var(--line-strong);47    background: var(--surface);48  }49  h1 { margin: 0; font-size: 13px; font-weight: 600; letter-spacing: .02em; }50  h1 span { color: var(--muted); font-weight: 400; }51  header p { margin: 2px 0 0; color: var(--muted); font-size: 11.5px; }52  main { max-width: 1020px; margin: 0 auto; padding: 10px 16px 48px; }53  nav.tabs {54    display: flex; margin-bottom: 10px; flex-wrap: wrap; width: max-content;55    border: 1px solid var(--line-strong); border-radius: 2px;56    background: var(--surface);57  }58  nav.tabs button {59    font: 600 11.5px/1 var(--sans); letter-spacing: .05em; text-transform: uppercase;60    padding: 7px 12px; border: none; border-right: 1px solid var(--line-strong);61    background: transparent; color: var(--muted); cursor: pointer;62  }63  nav.tabs button:last-child { border-right: none; }64  nav.tabs button[aria-selected="true"] {65    color: var(--accent-ink); background: var(--accent);66  }67  section.panel {68    display: none; border: 1px solid var(--line); border-radius: 2px;69    background: var(--surface); padding: 10px 12px 12px;70  }71  section.panel.active { display: block; }72  label {73    display: block; font: 600 10.5px/1.2 var(--sans); color: var(--muted);74    text-transform: uppercase; letter-spacing: .08em; margin: 10px 0 4px;75  }76  textarea, input[type="number"] {77    width: 100%; background: var(--field); color: var(--text);78    border: 1px solid var(--line); border-radius: 2px;79    font: 12px/1.5 var(--mono);80    padding: 6px 8px; resize: vertical;81  }82  textarea { min-height: 72px; }83  textarea:focus, input:focus {84    outline: none; border-color: var(--accent);85    box-shadow: inset 0 0 0 1px var(--accent);86  }87  .row { display: flex; gap: 8px; align-items: center; flex-wrap: wrap;88         margin-top: 10px; }89  .row.presets { margin-top: 6px; }90  button.go {91    font: 600 11.5px/1 var(--sans); letter-spacing: .06em; text-transform: uppercase;92    padding: 6px 14px; border-radius: 2px; border: 1px solid var(--accent);93    background: var(--accent); color: var(--accent-ink); cursor: pointer;94  }95  button.go:hover { background: var(--accent-hover); border-color: var(--accent-hover); }96  button.go:disabled { opacity: .55; cursor: wait; }97  button.pill {98    font: 11px/1 var(--sans); padding: 4px 10px; border-radius: 2px;99    border: 1px solid var(--line-strong); background: var(--surface); color: var(--muted);100    cursor: pointer;101  }102  button.pill:hover { color: var(--accent); border-color: var(--accent); }103  .status { font: 11px/1.4 var(--mono); color: var(--muted); }104  .status.ok { color: var(--ok); }105  .status.err { color: var(--err); }106  pre.out {107    background: var(--field); border: 1px solid var(--line); border-radius: 2px;108    padding: 8px 10px; font: 12px/1.5 var(--mono);109    overflow: auto; min-height: 40px; white-space: pre-wrap; margin: 10px 0 0;110  }111  footer {112    border-top: 1px solid var(--line-strong); padding: 8px 16px;113    background: var(--surface);114    color: var(--muted); font-size: 11.5px;115  }116  footer code { font-family: var(--mono); font-size: 11px; }117</style>118</head>119<body>120<header>121  <h1>Local Decisions <span>· GLiNER2.5-Decide playground</span></h1>122  <p class="meta">Runs on this machine. Calls go to <code>__ORIGIN__</code> with123     <code>X-Api-Key</code> already set — the key this server started with.</p>124</header>125<main>126  <nav class="tabs" role="tablist">127    <button role="tab" aria-selected="true" data-tab="classify">classify_text</button>128    <button role="tab" aria-selected="false" data-tab="batch">batch_classify_text</button>129    <button role="tab" aria-selected="false" data-tab="extract">extract</button>130  </nav>131132  <section class="panel active" data-panel="classify">133    <label for="classify-text">Text</label>134    <textarea id="classify-text">Battery dies before lunch, but the keyboard and the screen are the best I have used on a laptop.</textarea>135    <div class="row presets">136      <button class="pill" data-example="good">good example</button>137      <button class="pill" data-example="bad">bad example (inverted)</button>138    </div>139    <label for="classify-tasks">tasks</label>140    <textarea id="classify-tasks">{141  "sentiment": ["positive", "negative", "mixed", "neutral"],142  "aspects": {143    "labels": ["battery", "keyboard", "screen", "camera", "price", "support"],144    "multi_label": true,145    "cls_threshold": 0.4146  }147}</textarea>148    <div class="row">149      <button class="go" id="classify-go">Send</button>150      <span class="status" id="classify-status"></span>151    </div>152    <pre class="out" id="classify-out">Press Send to score both heads in one pass.</pre>153  </section>154155  <section class="panel" data-panel="batch">156    <label for="batch-texts">texts</label>157    <textarea id="batch-texts">[158  "Payroll file has to be corrected before the 5pm cutoff or the whole company is paid late.",159  "I finished it in two nights. The ending is earned, the middle drags, and I would still hand it to a friend."160]</textarea>161    <div class="row presets">162      <button class="pill" data-example="good">good example</button>163      <button class="pill" data-example="bad">bad example (inverted)</button>164    </div>165    <label for="batch-tasks">tasks</label>166    <textarea id="batch-tasks">{167  "urgency": ["0", "1", "2", "3", "4", "5"]168}</textarea>169    <div class="row">170      <button class="go" id="batch-go">Send</button>171      <span class="status" id="batch-status"></span>172    </div>173    <pre class="out" id="batch-out">Press Send to classify every text in order.</pre>174  </section>175176  <section class="panel" data-panel="extract">177    <label for="extract-text">Text</label>178    <textarea id="extract-text">the tool costs 2000 and you need to pay taxes of 210</textarea>179    <div class="row presets">180      <button class="pill" data-example="good">good example</button>181      <button class="pill" data-example="bad">bad example (inverted)</button>182    </div>183    <label for="extract-props">properties</label>184    <textarea id="extract-props">["taxes", "costs"]</textarea>185    <label for="extract-threshold">threshold — span score cutoff, 0 to 1, blank for default</label>186    <input type="number" id="extract-threshold" min="0" max="1" step="0.05" placeholder="0.5">187    <div class="row">188      <button class="go" id="extract-go">Send</button>189      <span class="status" id="extract-status"></span>190    </div>191    <pre class="out" id="extract-out">Press Send to extract values from the text.</pre>192  </section>193</main>194<footer>POST bodies mirror <code>gliner2</code>: <code>classify_text</code>,195<code>batch_classify_text</code>, <code>extract_json</code>. Malformed bodies are196answered with <code>400</code> and a message, never with a guess.</footer>197198<script>199(function () {200  "use strict";201202  var KEY = __KEY__;203  var tabs = document.querySelectorAll("nav.tabs button");204  var panels = document.querySelectorAll("section.panel");205206  tabs.forEach(function (tab) {207    tab.addEventListener("click", function () {208      tabs.forEach(function (t) { t.setAttribute("aria-selected", "false"); });209      tab.setAttribute("aria-selected", "true");210      panels.forEach(function (panel) {211        panel.classList.toggle("active", panel.dataset.panel === tab.dataset.tab);212      });213    });214  });215216  function parsed(id) {217    var value = document.getElementById(id).value;218    if (!value.trim()) throw new Error(id + " is empty");219    return JSON.parse(value);220  }221222  function text(id) {223    return document.getElementById(id);224  }225226  // The first text of each tab, plus the same sentences inverted into a227  // negative counterpart so the opposite reading can be checked too.228  var EXAMPLES = {229    classify: {230      good: "Battery dies before lunch, but the keyboard and the screen are the best I have used on a laptop.",231      bad: "Battery lasts all week on one charge, but the keyboard and the screen are the worst I have used on a laptop."232    },233    batch: {234      good: [235        "Payroll file has to be corrected before the 5pm cutoff or the whole company is paid late.",236        "I finished it in two nights. The ending is earned, the middle drags, and I would still hand it to a friend."237      ],238      bad: [239        "Payroll file needs no corrections and the whole company is paid well before the 5pm cutoff.",240        "I still have not finished it after a month. The ending is unearned, the middle drags, and I would not hand it to anyone."241      ]242    },243    extract: {244      good: "the tool costs 2000 and you need to pay taxes of 210",245      bad: "the tool is free and there are no taxes to pay on it"246    }247  };248249  document.querySelectorAll("button.pill").forEach(function (pill) {250    pill.addEventListener("click", function () {251      var panel = pill.closest("section.panel");252      var target = document.getElementById(panel.dataset.panel + "-text");253      var value = EXAMPLES[panel.dataset.panel][pill.dataset.example];254      target.value = typeof value === "string" ? value : JSON.stringify(value, null, 2);255      target.focus();256    });257  });258259  var handlers = {260    classify: function () {261      return {262        text: text("classify-text").value,263        tasks: parsed("classify-tasks"),264        include_confidence: true265      };266    },267    batch: function () {268      return {269        texts: parsed("batch-texts"),270        tasks: parsed("batch-tasks"),271        include_confidence: true272      };273    },274    extract: function () {275      var body = {276        text: text("extract-text").value,277        properties: parsed("extract-props")278      };279      var threshold = parseFloat(document.getElementById("extract-threshold").value);280      if (!isNaN(threshold)) body.threshold = threshold;281      return body;282    }283  };284285  function wire(name, path, build) {286    var go = document.getElementById(name + "-go");287    var out = document.getElementById(name + "-out");288    var status = document.getElementById(name + "-status");289290    go.addEventListener("click", function () {291      var body;292      try {293        body = build();294      } catch (error) {295        status.textContent = "check the JSON: " + error.message;296        status.className = "status err";297        return;298      }299      go.disabled = true;300      status.textContent = "deciding…";301      status.className = "status";302      out.textContent = "…";303      fetch(path, {304        method: "POST",305        headers: { "content-type": "application/json", "X-Api-Key": KEY },306        body: JSON.stringify(body)307      }).then(function (response) {308        return response.json().then(function (data) {309          return { status: response.status, data: data };310        });311      }).then(function (result) {312        out.textContent = JSON.stringify(result.data, null, 2);313        status.textContent = "HTTP " + result.status;314        status.className = "status " + (result.status < 400 ? "ok" : "err");315      }).catch(function (error) {316        out.textContent = String(error);317        status.textContent = "request failed";318        status.className = "status err";319      }).finally(function () {320        go.disabled = false;321      });322    });323  }324325  wire("classify", "/v1/classify_text", handlers.classify);326  wire("batch", "/v1/batch_classify_text", handlers.batch);327  wire("extract", "/v1/extract", handlers.extract);328})();329</script>330</body>331</html>332"#;333334/// Fill the two markers the page cannot know at compile time.335///336/// Serving raw HTML with a templating crate would be a new dependency for two337/// substitutions, so the template is split and joined instead; the data never338/// contains `</script>`, and `key_literal` JS-string-escapes the key.339fn filled(api_key: &str, origin: &str) -> String {340    let (head, tail) = TEMPLATE341        .split_once("__ORIGIN__")342        .expect("playground template carries an origin marker");343    let (middle, tail) = tail344        .split_once("__KEY__")345        .expect("playground template carries a key marker");346    format!("{head}{origin}{middle}{}{tail}", key_literal(api_key))347}348349/// The page `GET /` serves, with `API_KEY` already injected.350pub fn page(api_key: &str, origin: &str) -> String {351    filled(api_key, origin)352}353354#[cfg(test)]355mod tests {356    use super::page;357358    #[test]359    fn key_is_embedded_as_a_json_string() {360        let html = page("s3crét \"quoted\"", "http://127.0.0.1:8080");361        assert!(362            html.contains(r#"var KEY = "s3crét \"quoted\"";"#),363            "key not injected: {html}"364        );365    }366367    #[test]368    fn markers_are_gone_and_origin_is_set() {369        let html = page("k", "http://127.0.0.1:8123");370        assert!(!html.contains("__ORIGIN__") && !html.contains("__KEY__"));371        assert!(html.contains("http://127.0.0.1:8123"), "{html}");372    }373374    #[test]375    fn bad_example_is_offered_next_to_the_good_one() {376        let html = page("k", "http://127.0.0.1:8080");377        assert!(html.contains("bad example (inverted)"), "{html}");378        assert!(379            html.contains("the keyboard and the screen are the worst I have used"),380            "inverted classify example missing: {html}"381        );382    }383}