File size: 30,080 Bytes
d5a6c65
b3bf40e
 
6af3a28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3cdfff8
6af3a28
 
 
 
 
924c5d1
6eb6b77
6af3a28
3cdfff8
6af3a28
3cdfff8
 
6af3a28
 
57af0f2
 
 
 
 
 
 
 
 
 
6af3a28
d5a6c65
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6af3a28
 
 
 
 
d5a6c65
 
6af3a28
 
 
d5a6c65
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4bf5d2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d5a6c65
 
 
 
 
 
 
 
 
57af0f2
 
 
 
 
 
d5a6c65
 
 
 
 
 
 
57af0f2
 
d5a6c65
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57af0f2
 
 
 
 
d5a6c65
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57af0f2
 
 
 
 
 
 
 
 
d5a6c65
57af0f2
6af3a28
 
 
 
 
 
 
 
 
 
b7774c7
 
6af3a28
57af0f2
 
 
 
6af3a28
 
 
 
 
 
d5a6c65
6af3a28
 
 
 
 
 
 
 
57af0f2
 
 
 
6af3a28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57af0f2
 
 
 
 
 
 
 
 
6af3a28
 
 
 
 
d5a6c65
 
 
 
 
 
 
6af3a28
 
57af0f2
 
 
 
 
 
 
 
d5a6c65
6af3a28
d5a6c65
6af3a28
 
 
 
d5a6c65
6af3a28
d5a6c65
 
 
 
 
6af3a28
d5a6c65
57af0f2
d5a6c65
 
6af3a28
57af0f2
 
 
d5a6c65
6af3a28
57af0f2
 
d5a6c65
57af0f2
6af3a28
d5a6c65
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6af3a28
 
 
 
 
 
d5a6c65
 
57af0f2
671aa40
 
6af3a28
 
 
 
 
b3bf40e
6af3a28
 
 
 
 
 
d5a6c65
 
57af0f2
671aa40
 
57af0f2
 
 
d5a6c65
 
6af3a28
 
985ca07
d5a6c65
 
4bf5d2f
 
 
 
d5a6c65
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6af3a28
985ca07
6af3a28
d5a6c65
 
57af0f2
 
 
 
d5a6c65
 
985ca07
d5a6c65
 
 
 
 
 
 
 
 
 
 
 
 
b3bf40e
d5a6c65
 
 
 
57af0f2
671aa40
 
57af0f2
 
d5a6c65
 
 
4bf5d2f
d5a6c65
 
 
 
 
 
 
 
 
 
 
 
57af0f2
 
 
d5a6c65
 
 
 
 
 
6af3a28
 
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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
"""nutrient-document-decision-v2 demo: pick an example, change its pages, texts and questions in a form (or as JSON),
watch the request being built, and see every typed answer from one read of the document (yes / no, choices, labelled boxes drawn on the page, labelled spans highlighted in
the text), each with its calibrated confidence.

The model and its inference package are loaded at startup from the private weights repo with the Space's HF_TOKEN
secret (server-side only); nothing proprietary is stored in this Space."""
import base64
import io
import json
import os
import re
import sys
from pathlib import Path

import gradio as gr
import spaces
from huggingface_hub import snapshot_download
from PIL import Image, ImageDraw, ImageFont

HERE = Path(__file__).resolve().parent
EX = HERE / "examples"
REPO = "nutrientdocs/nutrient-document-decision-v2-private"

engine, normalize, LOAD_ERROR, LOAD_TRACE = None, None, None, ""
try:
    _path = snapshot_download(REPO, token=os.environ["HF_TOKEN"])
    sys.path.insert(0, os.path.join(_path, "code"))
    from ndd.engine.requests import normalize   # noqa: E402
    from ndd.engine.server import load           # noqa: E402
    engine = load(_path, device="cpu")   # ZeroGPU: build and merge on the CPU, then move the model to the GPU
    engine.m.to("cuda"); engine.m.device = "cuda"
except Exception as e:   # no secret / no access: the page still renders, runs report the problem
    import traceback
    LOAD_ERROR = f"{type(e).__name__}: {e}"
    print(traceback.format_exc(), flush=True)
    LOAD_TRACE = traceback.format_exc()

# ------------------------------------------------------------------------------------------------ examples
# examples/examples.json is shared with the local JS demo (ndd/demo): name, group (the JS demo heads its rows with it), page files, state, questions
GROUPS = ["Document pages", "Photos", "Text", "Agents", "Your own"]   # tab order; an unknown group goes last
EX_LIST = sorted(json.load(open(EX / "examples.json")),
                 key=lambda e: (GROUPS.index(e["group"]) if e.get("group") in GROUPS else len(GROUPS), e["name"].lower()))
EXAMPLES = {e["name"]: (e["pages"], e["state"], e["questions"]) for e in EX_LIST}
EX_GROUPS = list(dict.fromkeys(e.get("group") or "More" for e in EX_LIST))


def group_samples(g):
    return [[e["name"]] for e in EX_LIST if (e.get("group") or "More") == g]

QTYPES = [("yes / no", "noul"), ("choice", "choice"), ("boxes on a page", "boxes"), ("spans in a text", "spans"),
          ("score", "score")]
PAGE_REF = re.compile(r"^page_\d+$")
FORMATS = {"png", "jpeg", "webp"}

# ------------------------------------------------------------------------------------------------ state / questions
def walk_strings(v, path=""):
    """-> [(path, string)] for every string in the state, paths like `ocr`, `pages[0].text`"""
    if isinstance(v, dict):
        return [x for k, c in v.items() for x in walk_strings(c, f"{path}.{k}" if path else k)]
    if isinstance(v, list):
        return [x for i, c in enumerate(v) for x in walk_strings(c, f"{path}[{i}]")]
    return [(path, v)] if isinstance(v, str) else []


def _parts(path):
    return [int(p[1:-1]) if p.startswith("[") else p for p in re.findall(r"[^.\[\]]+|\[\d+\]", path)]


def set_path(state, path, value):
    *head, last = _parts(path)
    cur = state
    for p in head:
        cur = cur[p]
    if value is None:
        del cur[last]
    else:
        cur[last] = value
    return state


def field_text(state, path):
    """`ocr`, `pages[0].text` -> the string at that path of the state"""
    cur = state
    for p in _parts(path):
        cur = cur[p]
    return cur


def text_paths(state_text):
    try:
        return [p for p, v in walk_strings(json.loads(state_text)) if not PAGE_REF.match(v)]
    except (json.JSONDecodeError, TypeError):
        return []


def crit_text(c):
    return "\n".join(f"{k}: {v}" for k, v in (c or {}).items())


def crit_parse(text):
    out = {}
    for line in (text or "").splitlines():
        if line.strip():
            k, _, v = line.partition(":")
            out[k.strip()] = v.strip()
    return out


def qtypes(questions_text):
    try:
        return {q.get("type") for q in json.loads(questions_text).values() if isinstance(q, dict)}
    except (json.JSONDecodeError, AttributeError):
        return set()


def dump(obj):
    return json.dumps(obj, indent=1, ensure_ascii=False)


# ------------------------------------------------------------------------------------------------ pages / request
def page_list(gallery):
    """gallery value -> [(page_k, filepath)] in order"""
    out = []
    for item in gallery or []:
        p = item[0] if isinstance(item, (list, tuple)) else item
        p = p.get("path") if isinstance(p, dict) else getattr(p, "path", p)
        out.append((f"page_{len(out) + 1}", str(p)))
    return out


def relabel(gallery):
    return [(p, k) for k, p in page_list(gallery)]


def add_files(gallery, files):
    """Uploaded images and PDFs -> pages appended to the gallery; a PDF adds one page per sheet (rendered at 144 dpi)."""
    import tempfile
    import pypdfium2
    paths = [p for _, p in page_list(gallery)]
    for f in files or []:
        f = getattr(f, "name", f)
        if str(f).lower().endswith(".pdf"):
            doc = pypdfium2.PdfDocument(f)
            for n in range(len(doc)):
                out = os.path.join(tempfile.mkdtemp(), f"{Path(f).stem}_p{n + 1}.png")
                doc[n].render(scale=2).to_pil().convert("RGB").save(out)
                paths.append(out)
            doc.close()
        else:
            paths.append(str(f))
    return [(p, f"page_{i}") for i, p in enumerate(paths, 1)]


def page_bytes(path):
    fmt = Path(path).suffix.lstrip(".").lower().replace("jpg", "jpeg")
    if fmt in FORMATS:
        return fmt, open(path, "rb").read()
    buf = io.BytesIO()
    Image.open(path).convert("RGB").save(buf, "PNG")
    return "png", buf.getvalue()


def as_sent(questions):
    """The demo asks for every box and span (threshold 0); the Result tab's slider chooses which to show."""
    return {k: {**q, "threshold": 0} if isinstance(q, dict) and q.get("type") in ("boxes", "box", "spans", "span") else q
            for k, q in questions.items()}


def referenced(pages, state_text, questions_text):
    blob = state_text + questions_text
    return [(k, p) for k, p in pages if re.search(rf"\b{k}\b", blob)]


def request_preview(gallery, state_text, questions_text):
    """The request exactly as sent, with each page's base64 shortened to a description."""
    if state_text is None or questions_text is None:   # page still loading
        return "", ""
    try:
        state, questions = json.loads(state_text), json.loads(questions_text)
    except json.JSONDecodeError as e:
        return f"// invalid JSON: {e}", ""
    pages = page_list(gallery)
    used = referenced(pages, state_text, questions_text)
    assets = {}
    for k, p in used:
        fmt, b = page_bytes(p)
        w, h = Image.open(p).size
        assets[k] = {"format": fmt, "data_base64": f"<{w}×{h} px, {len(b) / 1024:,.0f} KB of base64 image bytes>"}
    note = []
    unused = [k for k, _ in pages if k not in assets]
    if unused:
        note.append(f"⚠️ {', '.join(unused)} {'is' if len(unused) == 1 else 'are'} not referenced in the state or "
                    "questions, so not sent. Add a page reference to use it.")
    missing = sorted({m for m in re.findall(r"\bpage_\d+\b", state_text + questions_text)} - {k for k, _ in pages})
    if missing:
        note.append(f"⚠️ {', '.join(missing)} {'is' if len(missing) == 1 else 'are'} referenced but there is no such page.")
    if as_sent(questions) != questions:
        note.append('The demo sends `"threshold": 0` on box and span questions, so the engine returns every box and span, '
                    "and the slider on the Result tab chooses which to show. Without it the engine returns only those with "
                    "confidence 0.5 or above.")
    return dump({"state": state, "questions": as_sent(questions), "assets": assets}), "\n\n".join(note)


SNIPPET = """```python
import base64, json, requests

request = json.load(open("request.json"))          # the JSON above
for key, path in {"page_1": "page1.png"}.items():   # put each page's real bytes in its asset
    request["assets"][key]["data_base64"] = base64.b64encode(open(path, "rb").read()).decode()
response = requests.post(YOUR_DEPLOYMENT_URL, json=request).json()
```"""

# ------------------------------------------------------------------------------------------------ rendering
COLORS = ["#1d5fa8", "#d1495b", "#2a9d8f", "#e9a23b", "#6a4c93", "#3d405b", "#f28482"]
FONT = ImageFont.load_default(size=22)


def found_text(shown, total, a):
    if not total:
        return f"nothing found ({len(a['guess'])} guesses in the response)" if a.get("guess") else "none found"
    return f"{total} found" if shown == total else f"{shown} of {total} shown"


def render(state, images, answers, min_conf=0.5):
    """-> table rows, pages with their boxes drawn, highlighted text, "showing X of Y"; boxes and spans below
    min_conf are left out"""
    rows, drawn, boxed, spans_by_field = [], {k: Image.open(p).convert("RGB") for k, p in images}, [], {}
    n_all = n_shown = 0
    for qi, (qk, a) in enumerate(answers.items()):
        color = COLORS[qi % len(COLORS)]
        t = a.get("type")
        if "error" in a:
            rows.append([qk, t, f"error: {a.get('message', a['error'])}", ""])
        elif t == "noul":
            rows.append([qk, "yes / no", "yes" if a["noul"] >= 0.5 else "no", f"{max(a['noul'], 1 - a['noul']):.2f}"])
        elif t == "choice":
            rows.append([qk, "choice", a["choice"], f"{a['probabilities'][a['choice']]:.2f}"])
        elif t == "score":
            top = max(a["probabilities"], key=a["probabilities"].get)
            rows.append([qk, "score", f"{a['score']:.2f} (most likely {top})", f"{a['probabilities'][top]:.2f}"])
        elif t in ("boxes", "box"):
            every = a.get("boxes", [])
            items = [b for b in every if b["confidence"] >= min_conf]
            n_all, n_shown = n_all + len(every), n_shown + len(items)
            rows.append([qk, "boxes", found_text(len(items), len(every), a), f"nothing: {a.get('p_null', 0):.2f}"])
            for b in items:
                lab = f"{b['label']} " if "label" in b else ""
                rows.append(["", "", f"↳ {lab}box on {b['asset']}", f"{b['confidence']:.2f}"])
                im = drawn.get(b["asset"])
                if im is None:
                    continue
                boxed.append(b["asset"])
                bx = b["box"]; W, H = im.size
                xy = [bx["left"] * W / 1000, bx["top"] * H / 1000, bx["right"] * W / 1000, bx["bottom"] * H / 1000]
                d = ImageDraw.Draw(im)
                d.rectangle(xy, outline=color, width=4)
                tag = f"{qk}: {lab}{b['confidence']:.2f}"
                d.rectangle([xy[0], xy[1] - 26, xy[0] + d.textlength(tag, font=FONT) + 8, xy[1]], fill=color)
                d.text((xy[0] + 4, xy[1] - 25), tag, fill="white", font=FONT)
        elif t in ("spans", "span"):
            every = a.get("spans", [])
            items = [s for s in every if s["confidence"] >= min_conf]
            n_all, n_shown = n_all + len(every), n_shown + len(items)
            rows.append([qk, "spans", found_text(len(items), len(every), a), f"nothing: {a.get('p_null', 0):.2f}"])
            for s in items:
                lab = s.get("label", qk)
                lc = f", label {s['label_confidence']:.2f}" if "label_confidence" in s else ""
                rows.append(["", "", f"↳ {lab}: “{s['text']}”", f"{s['confidence']:.2f}{lc}"])
                spans_by_field.setdefault(s["field"], []).append((s["span"][0], s["span"][1], f"{lab} {s['confidence']:.2f}"))
    highlighted = []
    for fld, sp in spans_by_field.items():
        text, pos = field_text(state, fld), 0
        highlighted.append((f"[{fld}]\n", None))
        for s, e, tag in sorted(sp):
            if s < pos:
                continue
            highlighted += [(text[pos:s], None), (text[s:e], tag)]
            pos = e
        highlighted.append((text[pos:] + "\n\n", None))
    count = f"showing {n_shown} of {n_all}" if n_all else ""
    return rows, [(drawn[k], k) for k in dict.fromkeys(boxed)], highlighted, count


def rerender(last, min_conf):
    """slider moved: redraw from the stored response (no model call)"""
    if not last:
        return [], [], [], ""
    return render(*last, min_conf)


# ------------------------------------------------------------------------------------------------ run
@spaces.GPU(duration=120)
def answer(request):
    return engine.answer(request)


def panels(questions_text):
    """Boxes / spans panels follow the question types in the request."""
    t = qtypes(questions_text)
    return gr.update(visible=bool(t & {"boxes", "box"})), gr.update(visible=bool(t & {"spans", "span"}))


def has_items(answers):
    return any(a.get("type") in ("boxes", "box", "spans", "span") and "error" not in a for a in answers.values())


def run(gallery, state_json, questions_json, min_conf):
    def out(msg, rows=None, g=None, h=None, resp="", last=None, count=""):
        return (msg, rows or [], g or [], h or [], resp, gr.Tabs(selected="result"), last, count,
                gr.update(visible=bool(last and has_items(last[2]))))
    yield out("⏳ Waking up… first run downloads the model + cold-starts a shared GPU (~30–60s)…")
    if engine is None:
        yield out(f"Model unavailable on this Space ({LOAD_ERROR}).", resp=dump({"trace": LOAD_TRACE[-3000:]}))
        return
    try:
        state, questions = json.loads(state_json), json.loads(questions_json)
    except json.JSONDecodeError as e:
        yield out(f"Invalid JSON: {e}")
        return
    used = referenced(page_list(gallery), state_json, questions_json)
    assets = {}
    for k, p in used:
        fmt, b = page_bytes(p)
        assets[k] = {"format": fmt, "data_base64": base64.b64encode(b).decode()}
    try:
        st, qs, ab = normalize({"state": state, "questions": questions, "assets": assets})
        resp = answer({"state": st, "questions": as_sent(qs), "_asset_bytes": ab})
    except (ValueError, KeyError) as e:
        yield out(f"Request error: {e}")
        return
    last = (state, used, resp["answers"])
    rows, drawn, highlighted, count = render(*last, min_conf)
    yield out("Done.", rows, drawn, highlighted, dump(resp), last, count)


def load_example(name):
    files, state, questions = EXAMPLES[name]
    return ([(str(EX / f), f"page_{k + 1}") for k, f in enumerate(files)], dump(state), dump(questions),
            "", [], [], [], "", None, "", gr.update(visible=False))


# ------------------------------------------------------------------------------------------------ form edits
def edit_state(state_text, path, value):
    try:
        return dump(set_path(json.loads(state_text), path, value))
    except (json.JSONDecodeError, KeyError, IndexError, TypeError):
        return gr.update()


def add_text_field(state_text, name):
    state, name = json.loads(state_text), (name or "").strip() or "text"
    base, n = name, 2
    while name in state:
        name, n = f"{base}_{n}", n + 1
    state[name] = ""
    return dump(state), ""


def add_page_ref(state_text, gallery):
    state = json.loads(state_text)
    pages = [k for k, _ in page_list(gallery)]
    free = [k for k in pages if not re.search(rf"\b{k}\b", state_text)] or [pages[0] if pages else "page_1"]
    k = free[0]
    name, n = k, 2
    while name in state:
        name, n = f"{k}_{n}", n + 1
    state[name] = k
    return dump(state)


def edit_question(questions_text, i, field, value):
    try:
        items = list(json.loads(questions_text).items())
    except json.JSONDecodeError:
        return gr.update()
    name, q = items[i]
    if field == "name":
        value = (value or "").strip()
        if not value or value in {k for j, (k, _) in enumerate(items) if j != i}:
            return gr.update()
        items[i] = (value, q)
    elif field == "remove":
        items.pop(i)
    else:
        if field == "criteria":
            value = crit_parse(value)
        if field == "max_boxes" and value is not None:
            value = int(value)
        if value in (None, "", {}):
            q.pop(field, None)
        else:
            q[field] = value
        items[i] = (name, q)
    return dump(dict(items))


def add_question(questions_text):
    qs = json.loads(questions_text)
    name, n = "new_question", 2
    while name in qs:
        name, n = f"new_question_{n}", n + 1
    qs[name] = {"type": "noul", "instructions": ""}
    return dump(qs)


CSS = """
:root { --brand-accent: #1d5fa8; }
button.primary { background: var(--brand-accent) !important; border-color: var(--brand-accent) !important; }
a { color: var(--brand-accent); }
.qcard { border: 1px solid var(--border-color-primary); border-radius: 10px; padding: 8px; margin-bottom: 8px; }
.rm button, button.rm { min-width: 0 !important; }
.conf-count { align-self: center; color: var(--body-text-color-subdued); }
.ex-tabs [role="tabpanel"] { display: none !important; }
.ex-tabs { margin-bottom: 0 !important; }
"""

with gr.Blocks(title="nutrient-document-decision-v2") as demo:
    gr.Markdown(
        "# nutrient-document-decision-v2\n"
        "**Ask a document anything typed (yes/no, pick-one, where on the page, which words) and get every answer from "
        "one read, each with a calibrated confidence.**\n\n"
        "🏆 [Scorecard](https://huggingface.co/nutrientdocs/nutrient-document-decision-v2) · "
        "Leaderboards: [grounding](https://huggingface.co/spaces/nutrientdocs/grounding-leaderboard) · "
        "[document classification](https://huggingface.co/spaces/nutrientdocs/document-classification-leaderboard) · "
        "[open-vocabulary](https://huggingface.co/spaces/nutrientdocs/doc-openvocab-leaderboard) · "
        "[document split](https://huggingface.co/spaces/nutrientdocs/doc-split-leaderboard)\n\n"
        "Pick an example, then change anything: add or remove pages, edit the texts, rewrite or add questions. "
        "One request can mix any question types.")
    gr.Markdown("### Examples")
    with gr.Tabs(elem_classes=["ex-tabs"]):   # headers only: a gallery inside a tab that is not open does not render
        group_tabs = [gr.Tab(g, id=g) for g in EX_GROUPS]
    picker = gr.Dataset(show_label=False, components=[gr.Textbox(visible=False)], samples=group_samples(EX_GROUPS[0]),
                        type="values", samples_per_page=12, layout="gallery")
    s_rev, q_rev, last = gr.State(0), gr.State(0), gr.State(None)
    state_code = gr.Code(label="state", language="json", lines=14, interactive=True, render=False)
    q_code = gr.Code(label="questions", language="json", lines=18, interactive=True, render=False)
    with gr.Row():
        with gr.Column(scale=5):
            pages = gr.Gallery(label="Pages",
                               columns=4, height=240, interactive=True, type="filepath", file_types=["image"],
                               object_fit="contain", allow_preview=False)
            with gr.Row(equal_height=True):
                add_files_btn = gr.UploadButton("Add images or a PDF", file_types=["image", ".pdf"], file_count="multiple",
                                                size="sm", scale=0, min_width=170)
                gr.Markdown("<sub>A PDF adds one page per sheet. Pages are page_1, page_2, … in order.</sub>")
            gr.Markdown("### State: the document")

            @gr.render(inputs=[state_code, pages], triggers=[s_rev.change])
            def state_form(state_text, gallery):
                try:
                    strings = walk_strings(json.loads(state_text))
                except json.JSONDecodeError:
                    gr.Markdown("⚠️ The state JSON is invalid; fix it under **Edit as JSON**.")
                    return
                keys = [k for k, _ in page_list(gallery)]
                for path, val in strings:
                    with gr.Row(equal_height=True):
                        if PAGE_REF.match(val):
                            box = gr.Dropdown(choices=sorted(set(keys) | {val}), value=val, label=f"{path} (page)",
                                              allow_custom_value=True, scale=12, interactive=True)
                            box.change(lambda v, s, path=path: edit_state(s, path, v), [box, state_code], state_code)
                        else:
                            box = gr.Textbox(val, label=path, lines=min(8, max(1, len(val) // 80 + 1)), max_lines=24,
                                             interactive=True, scale=12)
                            box.input(lambda v, s, path=path: edit_state(s, path, v), [box, state_code], state_code,
                                      show_progress="hidden")
                        rm = gr.Button("✕", size="sm", scale=0, min_width=40, elem_classes=["rm"])
                        rm.click(lambda s, path=path: edit_state(s, path, None), state_code, state_code).then(
                            lambda r: r + 1, s_rev, s_rev)
            with gr.Row(equal_height=True):
                new_name = gr.Textbox(placeholder="new field name, e.g. ocr", show_label=False, scale=3, interactive=True)
                add_text = gr.Button("+ text field", size="sm", scale=1)
                add_page = gr.Button("+ page reference", size="sm", scale=1)
            gr.Markdown("### Questions")

            @gr.render(inputs=[q_code, state_code], triggers=[q_rev.change])
            def question_form(q_text, state_text):
                try:
                    items = list(json.loads(q_text).items())
                except json.JSONDecodeError:
                    gr.Markdown("⚠️ The questions JSON is invalid; fix it under **Edit as JSON**.")
                    return
                targets = text_paths(state_text)
                for i, (name, q) in enumerate(items):
                    t = q.get("type")
                    with gr.Column(elem_classes=["qcard"]):
                        with gr.Row(equal_height=True):
                            nm = gr.Textbox(name, label="name", scale=4, interactive=True)
                            ty = gr.Dropdown(QTYPES, value=t, label="type", scale=3, allow_custom_value=True, interactive=True)
                            if t in ("boxes", "box"):
                                mx = gr.Number(q.get("max_boxes"), label="max boxes", precision=0, minimum=1, scale=2, interactive=True)
                                mx.input(lambda v, s, i=i: edit_question(s, i, "max_boxes", v), [mx, q_code], q_code)
                            if t in ("spans", "span"):
                                tg = gr.Dropdown(sorted(set(targets) | ({q["target"]} if q.get("target") else set())),
                                                 value=q.get("target"), label="target text", allow_custom_value=True,
                                                 scale=3, interactive=True)
                                tg.change(lambda v, s, i=i: edit_question(s, i, "target", v), [tg, q_code], q_code)
                            rm = gr.Button("✕", size="sm", scale=0, min_width=40, elem_classes=["rm"])
                        ins = gr.Textbox(q.get("instructions", ""), label="instructions",
                                         lines=min(4, len(q.get("instructions", "")) // 90 + 1), interactive=True)
                        crit_label = {"noul": "criteria (optional; true: … / false: …)",
                                      "choice": "choices, one per line (label: description)",
                                      "boxes": "box labels, one per line (label: description; optional)",
                                      "spans": "span labels, one per line (label: description; optional)"}
                        cr = gr.Textbox(crit_text(q.get("criteria")), label=crit_label.get(t, "criteria"),
                                        lines=max(1, len(q.get("criteria") or {})), interactive=True)
                    nm.input(lambda v, s, i=i: edit_question(s, i, "name", v), [nm, q_code], q_code, show_progress="hidden")
                    ins.input(lambda v, s, i=i: edit_question(s, i, "instructions", v), [ins, q_code], q_code,
                              show_progress="hidden")
                    cr.input(lambda v, s, i=i: edit_question(s, i, "criteria", v), [cr, q_code], q_code,
                             show_progress="hidden")
                    ty.input(lambda v, s, i=i: edit_question(s, i, "type", v), [ty, q_code], q_code).then(
                        lambda r: r + 1, q_rev, q_rev)
                    rm.click(lambda s, i=i: edit_question(s, i, "remove", None), q_code, q_code).then(
                        lambda r: r + 1, q_rev, q_rev)
            add_q = gr.Button("+ question", size="sm")
            with gr.Accordion("Edit as JSON", open=False):
                gr.Markdown("<sub>The form above and this JSON are the same request; edits here show in the form "
                            "when you click out of the editor.</sub>")
                state_code.render()
                q_code.render()
        with gr.Column(scale=6):
            go = gr.Button("Run", variant="primary", size="lg")
            status = gr.Markdown()
            with gr.Tabs(selected="request") as out_tabs:
                with gr.Tab("Result", id="result"):
                    with gr.Row(equal_height=True, visible=False) as conf_row:
                        min_conf = gr.Slider(0, 1, value=0.5, step=0.01, scale=4, interactive=True,
                                             label="Show boxes and spans with confidence at least")
                        conf_count = gr.Markdown(elem_classes=["conf-count"])
                    table = gr.Dataframe(headers=["question", "type", "answer", "confidence"], wrap=True,
                                         label="Answers", interactive=False)
                    drawn = gr.Gallery(label="Boxes on the pages", columns=2, height=640, object_fit="contain", visible=False)
                    spans = gr.HighlightedText(label="Spans in the text", combine_adjacent=False, show_legend=True,
                                               visible=False)
                with gr.Tab("Request", id="request"):
                    req_note = gr.Markdown()
                    req_code = gr.Code(label="Request JSON (updates as you edit; page bytes shortened)",
                                       language="json", lines=30, max_lines=60, interactive=False, wrap_lines=True)
                    gr.Markdown("<sub>Send the same request to your deployment as a JSON body, with each page's bytes "
                                "base64-encoded in its asset:</sub>\n\n" + SNIPPET)
                with gr.Tab("Response", id="response"):
                    resp_code = gr.Code(label="Response JSON", language="json", lines=30, max_lines=60, wrap_lines=True,
                                        interactive=False)
    gr.Markdown(
        "> ### 📩 Get access\n>\n> `nutrient-document-decision-v2` is commercial and its weights are not downloadable "
        "here. To run it on-prem, **contact Nutrient: [nutrient.io/contact-sales](https://www.nutrient.io/contact-sales/).**")

    bump = lambda r: r + 1
    preview = dict(fn=request_preview, inputs=[pages, state_code, q_code], outputs=[req_code, req_note],
                   show_progress="hidden")
    loaded = [pages, state_code, q_code, status, table, drawn, spans, resp_code, last, conf_count, conf_row]
    for g, tab in zip(EX_GROUPS, group_tabs):
        tab.select(lambda g=g: gr.Dataset(samples=group_samples(g)), None, picker, show_progress="hidden")
    for ev in (picker.click(lambda v: load_example(v[0]), picker, loaded),
               demo.load(lambda: load_example(EX_LIST[0]["name"]), None, loaded)):
        ev.then(bump, s_rev, s_rev).then(bump, q_rev, q_rev).then(**preview).then(
            panels, q_code, [drawn, spans]).then(lambda: gr.Tabs(selected="request"), None, out_tabs)
    pages.upload(relabel, pages, pages).then(bump, s_rev, s_rev).then(**preview)
    add_files_btn.upload(add_files, [pages, add_files_btn], pages).then(bump, s_rev, s_rev).then(**preview)
    pages.delete(relabel, pages, pages).then(bump, s_rev, s_rev).then(**preview)
    state_code.input(**preview)
    q_code.input(**preview)
    q_code.input(panels, q_code, [drawn, spans], show_progress="hidden")
    state_code.blur(bump, s_rev, s_rev).then(bump, q_rev, q_rev)
    q_code.blur(bump, q_rev, q_rev)
    state_code.change(**preview)
    q_code.change(**preview)
    q_code.change(panels, q_code, [drawn, spans], show_progress="hidden")
    add_text.click(add_text_field, [state_code, new_name], [state_code, new_name]).then(bump, s_rev, s_rev)
    add_page.click(add_page_ref, [state_code, pages], state_code).then(bump, s_rev, s_rev)
    add_q.click(add_question, q_code, q_code).then(bump, q_rev, q_rev)
    min_conf.change(rerender, [last, min_conf], [table, drawn, spans, conf_count], show_progress="hidden")
    go.click(run, [pages, state_code, q_code, min_conf],
             [status, table, drawn, spans, resp_code, out_tabs, last, conf_count, conf_row]).then(
        panels, q_code, [drawn, spans])
    gr.Markdown(
        "## About the author\n\n<a href=\"https://nutrient.io/\"><img src=\"https://avatars2.githubusercontent.com/u/1527679?v=3&s=200\" "
        "height=\"80\" /></a>\n\nThis project is maintained and funded by [Nutrient](https://nutrient.io/) - The deterministic "
        "document infrastructure enterprises run their highest-stakes workflows on: replayable output, clear exceptions, "
        "and full audit trails on the messy, regulated documents where AI alone breaks.")

demo.queue().launch(theme=gr.themes.Soft(primary_hue="blue"), css=CSS)