Skip to content

linexcel.result

linexcel.result

High-level API, usable as a library (marimo, Jupyter, scripts).

Minimal example, without backend or AI key:

from linexcel import analyze
result = analyze("my_workbook.xlsx")
result                      # interactive graph in marimo
result.save_html("out.html")
print(result.stats)

AI documentation is optional — pick a provider explicitly (no default):

result.document(base_url="http://localhost:11434/v1", model="llama3.1")

LineageResult

Analysis result: deterministic graph + computation engine + renderers.

The object is directly displayable in a notebook (_repr_html_) and exposes the JSON graph, convenience accessors, standalone HTML export, and optional AI documentation.

Source code in src/linexcel/result.py
 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
class LineageResult:
    """Analysis result: deterministic graph + computation engine + renderers.

    The object is directly displayable in a notebook (``_repr_html_``) and
    exposes the JSON graph, convenience accessors, standalone HTML export,
    and optional AI documentation.
    """

    def __init__(
        self,
        graph: dict[str, Any],
        engine: Any,
        analysis_id: str | None = None,
        source_data: bytes | None = None,
        filename: str | None = None,
    ):
        self.graph = graph
        self.engine = engine
        self.analysis_id = analysis_id or uuid.uuid4().hex[:16]
        self._by_id = {n["id"]: n for n in graph.get("nodes", [])}
        self._source_data = source_data
        self._source_filename = filename or graph.get("meta", {}).get(
            "filename", "workbook.xlsx"
        )
        self._workbook_context: dict[str, Any] | None = None
        self._token_usage: TokenUsage | None = None

    # -- convenience accessors --------------------------------------------
    @property
    def nodes(self) -> list[dict[str, Any]]:
        return self.graph["nodes"]

    @property
    def edges(self) -> list[dict[str, Any]]:
        return self.graph["edges"]

    @property
    def sheets(self) -> list[str]:
        return self.graph.get("sheets", [])

    @property
    def stats(self) -> dict[str, Any]:
        return self.graph["meta"]["stats"]

    @property
    def warnings(self) -> list[str]:
        return self.graph["meta"]["warnings"]

    @property
    def workbook_context(self) -> dict[str, Any]:
        """Bounded sheet previews, comments, and layout markers.

        Context is extracted with ``openpyxl`` only; Excel or LibreOffice is
        not launched. It deliberately preserves first rows and columns rather
        than assuming a tabular header convention.
        """
        if self._workbook_context is None:
            from linexcel.insights import extract_workbook_context

            self._workbook_context = extract_workbook_context(
                self._source_bytes(), self._source_filename
            )
        return self._workbook_context

    @property
    def token_usage(self) -> TokenUsage:
        """Tokens consumed by every :meth:`document` / :meth:`document_workbook`
        call made on this result.

        Counts come from the provider when it reports them (an
        OpenAI-compatible endpoint fills in a ``usage`` block); otherwise they
        are approximated and :attr:`TokenUsage.estimated` is set. Zero until an
        AI call is made.

            >>> result.document(provider=my_llm)          # doctest: +SKIP
            >>> print(result.token_usage)                 # doctest: +SKIP
            ~12,480 tokens (~11,120 in + ~1,360 out) over 4 request(s)
        """
        if self._token_usage is None:
            from linexcel.aidoc import TokenUsage as _TokenUsage

            self._token_usage = _TokenUsage()
        return self._token_usage

    def node(self, node_id: str) -> dict[str, Any] | None:
        """Return the node with the given id (or ``None``)"""
        return self._by_id.get(node_id)

    def find(self, text: str) -> list[dict[str, Any]]:
        """
        Nodes whose label or formula contains ``text`` (case-insensitive)
        """
        q = text.lower()
        return [
            n
            for n in self.nodes
            if q in (n.get("label", "").lower())
            or q in (n.get("formula", "") or "").lower()
        ]

    def precedents(self, node_id: str) -> list[dict[str, Any]]:
        """Nodes that feed into ``node_id``"""
        return [
            self._by_id[e["source"]]
            for e in self.edges
            if e["target"] == node_id and e["source"] in self._by_id
        ]

    def dependents(self, node_id: str) -> list[dict[str, Any]]:
        """Nodes fed by ``node_id``"""
        return [
            self._by_id[e["target"]]
            for e in self.edges
            if e["source"] == node_id and e["target"] in self._by_id
        ]

    # -- serialization -----------------------------------------------------
    def to_dict(self) -> dict[str, Any]:
        return self.graph

    def to_json(self, *, indent: int | None = None) -> str:
        return json.dumps(self.graph, ensure_ascii=False, indent=indent, default=str)

    def save_json(self, path: str | Path) -> Path:
        path = Path(path)
        path.write_text(self.to_json(indent=1), encoding="utf-8")
        return path

    def save_screenshots(
        self,
        output_dir: str | Path,
        *,
        dpi: int = 144,
        timeout: int = 180,
        per_sheet: bool = True,
    ) -> dict[str, list[Path]] | list[Path]:
        """Render the workbook to PNG using LibreOffice headless.

        Works on Linux, macOS and Windows. The optional renderer requires
        LibreOffice and ``pdftoppm`` from Poppler; both are found on ``PATH`` or
        in their standard install directory, since the Windows and macOS
        installers do not extend ``PATH``. Use :attr:`workbook_context` when
        only the non-rendered context is needed.

        By default each sheet is rendered whole, onto one image, and the result
        is a ``{sheet name: [png]}`` mapping — the shape :meth:`to_html` shows
        under each sheet in its Sheets tab:

            >>> result.save_html(                          # doctest: +SKIP
            ...     "report.html",
            ...     screenshots=result.save_screenshots("shots/"),
            ... )

        ``per_sheet=False`` returns the flat ``list[Path]`` of print pages
        instead, laid out by the workbook's own page setup; the report then
        shows them in a separate tab, since no page can be tied to a sheet.
        A mapping is also downgraded to that flat list when the renderer does
        not produce exactly one page per sheet, rather than filing images under
        sheets they may not belong to.
        """
        from linexcel.insights import render_workbook_screenshots

        return render_workbook_screenshots(
            self._source_bytes(),
            self._source_filename,
            output_dir,
            dpi=dpi,
            timeout=timeout,
            per_sheet=per_sheet,
        )

    # -- AI documentation (optional) --------------------------------------
    def document(
        self,
        node_ids: list[str] | None = None,
        *,
        api_key: str | None = None,
        model: str | None = None,
        base_url: str | None = None,
        provider: ProviderLike | None = None,
        language: str = "en",
        max_workers: int = 4,
        max_tokens: int | None = None,
        token_budget: int | None = None,
    ) -> dict[str, str]:
        """Document nodes via AI from the deterministic lineage.

        Without ``node_ids``, documents all calculation nodes
        (cells, groups, VBA).

        Provider resolution (first match wins, no implicit default and no
        preferred vendor):

        1. ``provider`` — custom LLMProvider instance or callable
        2. ``base_url`` + ``model`` (or ``LINEXCEL_AI_BASE_URL`` +
           ``LINEXCEL_AI_MODEL``) — any OpenAI-compatible endpoint, local or
           hosted

        ``language`` selects the system prompt; see :data:`linexcel.i18n.LANGUAGES`.
        ``max_workers`` caps the number of concurrent requests. Nodes that fail
        are skipped with a :class:`UserWarning`; the cards that succeeded are
        still returned.

        ``max_tokens`` caps output per node (approximate; provider-dependent).

        ``token_budget`` caps what the whole documentation run may cost, input
        and output tokens together. It is counted against :attr:`token_usage`,
        which spans the result's lifetime, so one ceiling covers this call and
        every earlier one — the figure to set is the total you are willing to
        pay for this workbook, not a per-node allowance. Nodes still queued when
        the budget is reached are left undocumented with a :class:`UserWarning`
        rather than silently billed; requests already in flight are allowed to
        finish, so treat the ceiling as approximate.

            >>> docs = result.document(base_url=..., token_budget=200_000)
            ... # doctest: +SKIP

        Tokens consumed are added to :attr:`token_usage`.
        """
        from linexcel.aidoc import document_nodes

        if node_ids is None:
            node_ids = [
                n["id"] for n in self.nodes if n.get("kind") in ("cell", "group", "vba")
            ]
        return document_nodes(
            self.graph,
            node_ids,
            model=model,
            api_key=api_key,
            base_url=base_url,
            provider=provider,
            language=language,
            max_workers=max_workers,
            usage=self.token_usage,
            max_tokens=max_tokens,
            token_budget=token_budget,
        )

    def document_workbook(
        self,
        *,
        api_key: str | None = None,
        model: str | None = None,
        base_url: str | None = None,
        provider: ProviderLike | None = None,
        language: str = "en",
        max_tokens: int | None = None,
        token_budget: int | None = None,
        include_context: bool = True,
    ) -> str:
        """Document the workbook structure and calculation flow via AI.

        The response is grounded in workbook-level deterministic lineage data.
        Pass it to :meth:`to_html` or :meth:`save_html` as ``workbook_doc`` to
        display it in the viewer's separate overview tab.

        ``include_context`` adds :attr:`workbook_context` to the dossier: the
        sheet previews, cell comments, merged ranges, frozen panes and hidden
        columns — the same cues the sheet screenshots show. Without it the model
        sees how the workbook computes but not what it looks like, and describes
        a graph rather than a file. Set it to ``False`` to keep cell contents
        local; the lineage (formulas and their values) is sent either way.

        Provider resolution is the same as :meth:`document`, and tokens
        consumed are added to :attr:`token_usage`. ``max_tokens`` caps the
        output length (approximate; provider-dependent), while ``token_budget``
        caps cumulative spend on this result and raises :class:`AiDocError` if
        earlier calls already exhausted it.
        """
        from linexcel.aidoc import document_workbook

        # Context needs the workbook bytes; a result rebuilt from a graph alone
        # has none, and a structural overview is better than an exception.
        context = (
            self.workbook_context
            if include_context and self._source_data is not None
            else None
        )
        return document_workbook(
            self.graph,
            model=model,
            api_key=api_key,
            base_url=base_url,
            provider=provider,
            language=language,
            usage=self.token_usage,
            max_tokens=max_tokens,
            token_budget=token_budget,
            context=context,
        )

    # -- visualization -----------------------------------------------------
    def to_html(
        self,
        *,
        title: str | None = None,
        full_document: bool = True,
        docs: dict[str, str] | None = None,
        workbook_doc: str | None = None,
        screenshots: Screenshots | None = None,
        language: str = "en",
    ) -> str:
        """Standalone HTML document (Cytoscape) — openable in a browser.

        If ``docs`` is provided (from :meth:`document`), AI documentation
        for each node is embedded in the detail panel. If ``workbook_doc`` is
        provided (from :meth:`document_workbook`), it is shown in a separate
        overview tab. If ``screenshots`` is provided (paths or base64), they
        are displayed in a preview tab.
        """
        graph = self.graph
        meta = dict(graph.get("meta", {}))
        # Result built without the source bytes: drop the sheet-preview tab
        # rather than failing the whole export. Tested on the attribute rather
        # than by catching RuntimeError, which would also swallow a genuine
        # extraction failure (WorkbookRenderError subclasses it).
        meta["workbookContext"] = (
            self.workbook_context if self._source_data is not None else None
        )

        if workbook_doc:
            meta["workbookDoc"] = workbook_doc

        if screenshots:
            import base64

            def _embed(s: str | Path) -> str:
                p = Path(s) if isinstance(s, (str, Path)) else None
                if p and p.exists() and p.suffix.lower() == ".png":
                    b64 = base64.b64encode(p.read_bytes()).decode("ascii")
                    return f"data:image/png;base64,{b64}"
                return str(s)

            if isinstance(screenshots, Mapping):
                # cast: isinstance() alone leaves the Sequence arm of the union
                # in play, which erases the value type.
                by_sheet = cast("Mapping[str, Sequence[str | Path]]", screenshots)
                meta["screenshots"] = {
                    name: [_embed(s) for s in s_list]
                    for name, s_list in by_sheet.items()
                }
            else:
                meta["screenshots"] = [_embed(s) for s in screenshots]

        graph = {
            **graph,
            "meta": meta,
            "nodes": [
                {**n, "doc": docs.get(n["id"], "") if docs else ""}
                for n in graph["nodes"]
            ],
        }
        return render_html(
            graph,
            title=title or self._title(),
            full_document=full_document,
            language=language,
        )

    def save_html(
        self,
        path: str | Path,
        *,
        title: str | None = None,
        docs: dict[str, str] | None = None,
        workbook_doc: str | None = None,
        screenshots: Screenshots | None = None,
        language: str = "en",
    ) -> Path:
        path = path if isinstance(path, Path) else Path(path)
        path.write_text(
            self.to_html(
                title=title,
                docs=docs,
                workbook_doc=workbook_doc,
                screenshots=screenshots,
                language=language,
            ),
            encoding="utf-8",
        )
        return path

    def _title(self) -> str:
        return self.graph.get("meta", {}).get("filename", "Lineage Excel")

    def _source_bytes(self) -> bytes:
        if self._source_data is None:
            raise RuntimeError(
                "Workbook bytes are unavailable. Create the result with analyze()."
            )
        return self._source_data

    def _repr_html_(self) -> str:
        """Inline rendering for marimo / Jupyter (isolated iframe)."""
        return wrap_iframe(self.to_html(), height=640)

    def __repr__(self) -> str:
        s = self.stats
        return (
            f"<LineageResult {self._title()!r}: "
            f"{s['totalFormulas']} formulas, {s['totalNodes']} nodes, "
            f"{s['totalEdges']} edges, {s['vbaProcs']} VBA procs>"
        )

workbook_context property

workbook_context: dict[str, Any]

Bounded sheet previews, comments, and layout markers.

Context is extracted with openpyxl only; Excel or LibreOffice is not launched. It deliberately preserves first rows and columns rather than assuming a tabular header convention.

token_usage property

token_usage: TokenUsage

Tokens consumed by every :meth:document / :meth:document_workbook call made on this result.

Counts come from the provider when it reports them (an OpenAI-compatible endpoint fills in a usage block); otherwise they are approximated and :attr:TokenUsage.estimated is set. Zero until an AI call is made.

>>> result.document(provider=my_llm)          # doctest: +SKIP
>>> print(result.token_usage)                 # doctest: +SKIP
~12,480 tokens (~11,120 in + ~1,360 out) over 4 request(s)

node

node(node_id: str) -> dict[str, Any] | None

Return the node with the given id (or None)

Source code in src/linexcel/result.py
def node(self, node_id: str) -> dict[str, Any] | None:
    """Return the node with the given id (or ``None``)"""
    return self._by_id.get(node_id)

find

find(text: str) -> list[dict[str, Any]]

Nodes whose label or formula contains text (case-insensitive)

Source code in src/linexcel/result.py
def find(self, text: str) -> list[dict[str, Any]]:
    """
    Nodes whose label or formula contains ``text`` (case-insensitive)
    """
    q = text.lower()
    return [
        n
        for n in self.nodes
        if q in (n.get("label", "").lower())
        or q in (n.get("formula", "") or "").lower()
    ]

precedents

precedents(node_id: str) -> list[dict[str, Any]]

Nodes that feed into node_id

Source code in src/linexcel/result.py
def precedents(self, node_id: str) -> list[dict[str, Any]]:
    """Nodes that feed into ``node_id``"""
    return [
        self._by_id[e["source"]]
        for e in self.edges
        if e["target"] == node_id and e["source"] in self._by_id
    ]

dependents

dependents(node_id: str) -> list[dict[str, Any]]

Nodes fed by node_id

Source code in src/linexcel/result.py
def dependents(self, node_id: str) -> list[dict[str, Any]]:
    """Nodes fed by ``node_id``"""
    return [
        self._by_id[e["target"]]
        for e in self.edges
        if e["source"] == node_id and e["target"] in self._by_id
    ]

save_screenshots

save_screenshots(output_dir: str | Path, *, dpi: int = 144, timeout: int = 180, per_sheet: bool = True) -> dict[str, list[Path]] | list[Path]

Render the workbook to PNG using LibreOffice headless.

Works on Linux, macOS and Windows. The optional renderer requires LibreOffice and pdftoppm from Poppler; both are found on PATH or in their standard install directory, since the Windows and macOS installers do not extend PATH. Use :attr:workbook_context when only the non-rendered context is needed.

By default each sheet is rendered whole, onto one image, and the result is a {sheet name: [png]} mapping — the shape :meth:to_html shows under each sheet in its Sheets tab:

>>> result.save_html(                          # doctest: +SKIP
...     "report.html",
...     screenshots=result.save_screenshots("shots/"),
... )

per_sheet=False returns the flat list[Path] of print pages instead, laid out by the workbook's own page setup; the report then shows them in a separate tab, since no page can be tied to a sheet. A mapping is also downgraded to that flat list when the renderer does not produce exactly one page per sheet, rather than filing images under sheets they may not belong to.

Source code in src/linexcel/result.py
def save_screenshots(
    self,
    output_dir: str | Path,
    *,
    dpi: int = 144,
    timeout: int = 180,
    per_sheet: bool = True,
) -> dict[str, list[Path]] | list[Path]:
    """Render the workbook to PNG using LibreOffice headless.

    Works on Linux, macOS and Windows. The optional renderer requires
    LibreOffice and ``pdftoppm`` from Poppler; both are found on ``PATH`` or
    in their standard install directory, since the Windows and macOS
    installers do not extend ``PATH``. Use :attr:`workbook_context` when
    only the non-rendered context is needed.

    By default each sheet is rendered whole, onto one image, and the result
    is a ``{sheet name: [png]}`` mapping — the shape :meth:`to_html` shows
    under each sheet in its Sheets tab:

        >>> result.save_html(                          # doctest: +SKIP
        ...     "report.html",
        ...     screenshots=result.save_screenshots("shots/"),
        ... )

    ``per_sheet=False`` returns the flat ``list[Path]`` of print pages
    instead, laid out by the workbook's own page setup; the report then
    shows them in a separate tab, since no page can be tied to a sheet.
    A mapping is also downgraded to that flat list when the renderer does
    not produce exactly one page per sheet, rather than filing images under
    sheets they may not belong to.
    """
    from linexcel.insights import render_workbook_screenshots

    return render_workbook_screenshots(
        self._source_bytes(),
        self._source_filename,
        output_dir,
        dpi=dpi,
        timeout=timeout,
        per_sheet=per_sheet,
    )

document

document(node_ids: list[str] | None = None, *, api_key: str | None = None, model: str | None = None, base_url: str | None = None, provider: ProviderLike | None = None, language: str = 'en', max_workers: int = 4, max_tokens: int | None = None, token_budget: int | None = None) -> dict[str, str]

Document nodes via AI from the deterministic lineage.

Without node_ids, documents all calculation nodes (cells, groups, VBA).

Provider resolution (first match wins, no implicit default and no preferred vendor):

  1. provider — custom LLMProvider instance or callable
  2. base_url + model (or LINEXCEL_AI_BASE_URL + LINEXCEL_AI_MODEL) — any OpenAI-compatible endpoint, local or hosted

language selects the system prompt; see :data:linexcel.i18n.LANGUAGES. max_workers caps the number of concurrent requests. Nodes that fail are skipped with a :class:UserWarning; the cards that succeeded are still returned.

max_tokens caps output per node (approximate; provider-dependent).

token_budget caps what the whole documentation run may cost, input and output tokens together. It is counted against :attr:token_usage, which spans the result's lifetime, so one ceiling covers this call and every earlier one — the figure to set is the total you are willing to pay for this workbook, not a per-node allowance. Nodes still queued when the budget is reached are left undocumented with a :class:UserWarning rather than silently billed; requests already in flight are allowed to finish, so treat the ceiling as approximate.

>>> docs = result.document(base_url=..., token_budget=200_000)
... # doctest: +SKIP

Tokens consumed are added to :attr:token_usage.

Source code in src/linexcel/result.py
def document(
    self,
    node_ids: list[str] | None = None,
    *,
    api_key: str | None = None,
    model: str | None = None,
    base_url: str | None = None,
    provider: ProviderLike | None = None,
    language: str = "en",
    max_workers: int = 4,
    max_tokens: int | None = None,
    token_budget: int | None = None,
) -> dict[str, str]:
    """Document nodes via AI from the deterministic lineage.

    Without ``node_ids``, documents all calculation nodes
    (cells, groups, VBA).

    Provider resolution (first match wins, no implicit default and no
    preferred vendor):

    1. ``provider`` — custom LLMProvider instance or callable
    2. ``base_url`` + ``model`` (or ``LINEXCEL_AI_BASE_URL`` +
       ``LINEXCEL_AI_MODEL``) — any OpenAI-compatible endpoint, local or
       hosted

    ``language`` selects the system prompt; see :data:`linexcel.i18n.LANGUAGES`.
    ``max_workers`` caps the number of concurrent requests. Nodes that fail
    are skipped with a :class:`UserWarning`; the cards that succeeded are
    still returned.

    ``max_tokens`` caps output per node (approximate; provider-dependent).

    ``token_budget`` caps what the whole documentation run may cost, input
    and output tokens together. It is counted against :attr:`token_usage`,
    which spans the result's lifetime, so one ceiling covers this call and
    every earlier one — the figure to set is the total you are willing to
    pay for this workbook, not a per-node allowance. Nodes still queued when
    the budget is reached are left undocumented with a :class:`UserWarning`
    rather than silently billed; requests already in flight are allowed to
    finish, so treat the ceiling as approximate.

        >>> docs = result.document(base_url=..., token_budget=200_000)
        ... # doctest: +SKIP

    Tokens consumed are added to :attr:`token_usage`.
    """
    from linexcel.aidoc import document_nodes

    if node_ids is None:
        node_ids = [
            n["id"] for n in self.nodes if n.get("kind") in ("cell", "group", "vba")
        ]
    return document_nodes(
        self.graph,
        node_ids,
        model=model,
        api_key=api_key,
        base_url=base_url,
        provider=provider,
        language=language,
        max_workers=max_workers,
        usage=self.token_usage,
        max_tokens=max_tokens,
        token_budget=token_budget,
    )

document_workbook

document_workbook(*, api_key: str | None = None, model: str | None = None, base_url: str | None = None, provider: ProviderLike | None = None, language: str = 'en', max_tokens: int | None = None, token_budget: int | None = None, include_context: bool = True) -> str

Document the workbook structure and calculation flow via AI.

The response is grounded in workbook-level deterministic lineage data. Pass it to :meth:to_html or :meth:save_html as workbook_doc to display it in the viewer's separate overview tab.

include_context adds :attr:workbook_context to the dossier: the sheet previews, cell comments, merged ranges, frozen panes and hidden columns — the same cues the sheet screenshots show. Without it the model sees how the workbook computes but not what it looks like, and describes a graph rather than a file. Set it to False to keep cell contents local; the lineage (formulas and their values) is sent either way.

Provider resolution is the same as :meth:document, and tokens consumed are added to :attr:token_usage. max_tokens caps the output length (approximate; provider-dependent), while token_budget caps cumulative spend on this result and raises :class:AiDocError if earlier calls already exhausted it.

Source code in src/linexcel/result.py
def document_workbook(
    self,
    *,
    api_key: str | None = None,
    model: str | None = None,
    base_url: str | None = None,
    provider: ProviderLike | None = None,
    language: str = "en",
    max_tokens: int | None = None,
    token_budget: int | None = None,
    include_context: bool = True,
) -> str:
    """Document the workbook structure and calculation flow via AI.

    The response is grounded in workbook-level deterministic lineage data.
    Pass it to :meth:`to_html` or :meth:`save_html` as ``workbook_doc`` to
    display it in the viewer's separate overview tab.

    ``include_context`` adds :attr:`workbook_context` to the dossier: the
    sheet previews, cell comments, merged ranges, frozen panes and hidden
    columns — the same cues the sheet screenshots show. Without it the model
    sees how the workbook computes but not what it looks like, and describes
    a graph rather than a file. Set it to ``False`` to keep cell contents
    local; the lineage (formulas and their values) is sent either way.

    Provider resolution is the same as :meth:`document`, and tokens
    consumed are added to :attr:`token_usage`. ``max_tokens`` caps the
    output length (approximate; provider-dependent), while ``token_budget``
    caps cumulative spend on this result and raises :class:`AiDocError` if
    earlier calls already exhausted it.
    """
    from linexcel.aidoc import document_workbook

    # Context needs the workbook bytes; a result rebuilt from a graph alone
    # has none, and a structural overview is better than an exception.
    context = (
        self.workbook_context
        if include_context and self._source_data is not None
        else None
    )
    return document_workbook(
        self.graph,
        model=model,
        api_key=api_key,
        base_url=base_url,
        provider=provider,
        language=language,
        usage=self.token_usage,
        max_tokens=max_tokens,
        token_budget=token_budget,
        context=context,
    )

to_html

to_html(*, title: str | None = None, full_document: bool = True, docs: dict[str, str] | None = None, workbook_doc: str | None = None, screenshots: Screenshots | None = None, language: str = 'en') -> str

Standalone HTML document (Cytoscape) — openable in a browser.

If docs is provided (from :meth:document), AI documentation for each node is embedded in the detail panel. If workbook_doc is provided (from :meth:document_workbook), it is shown in a separate overview tab. If screenshots is provided (paths or base64), they are displayed in a preview tab.

Source code in src/linexcel/result.py
def to_html(
    self,
    *,
    title: str | None = None,
    full_document: bool = True,
    docs: dict[str, str] | None = None,
    workbook_doc: str | None = None,
    screenshots: Screenshots | None = None,
    language: str = "en",
) -> str:
    """Standalone HTML document (Cytoscape) — openable in a browser.

    If ``docs`` is provided (from :meth:`document`), AI documentation
    for each node is embedded in the detail panel. If ``workbook_doc`` is
    provided (from :meth:`document_workbook`), it is shown in a separate
    overview tab. If ``screenshots`` is provided (paths or base64), they
    are displayed in a preview tab.
    """
    graph = self.graph
    meta = dict(graph.get("meta", {}))
    # Result built without the source bytes: drop the sheet-preview tab
    # rather than failing the whole export. Tested on the attribute rather
    # than by catching RuntimeError, which would also swallow a genuine
    # extraction failure (WorkbookRenderError subclasses it).
    meta["workbookContext"] = (
        self.workbook_context if self._source_data is not None else None
    )

    if workbook_doc:
        meta["workbookDoc"] = workbook_doc

    if screenshots:
        import base64

        def _embed(s: str | Path) -> str:
            p = Path(s) if isinstance(s, (str, Path)) else None
            if p and p.exists() and p.suffix.lower() == ".png":
                b64 = base64.b64encode(p.read_bytes()).decode("ascii")
                return f"data:image/png;base64,{b64}"
            return str(s)

        if isinstance(screenshots, Mapping):
            # cast: isinstance() alone leaves the Sequence arm of the union
            # in play, which erases the value type.
            by_sheet = cast("Mapping[str, Sequence[str | Path]]", screenshots)
            meta["screenshots"] = {
                name: [_embed(s) for s in s_list]
                for name, s_list in by_sheet.items()
            }
        else:
            meta["screenshots"] = [_embed(s) for s in screenshots]

    graph = {
        **graph,
        "meta": meta,
        "nodes": [
            {**n, "doc": docs.get(n["id"], "") if docs else ""}
            for n in graph["nodes"]
        ],
    }
    return render_html(
        graph,
        title=title or self._title(),
        full_document=full_document,
        language=language,
    )

analyze

analyze(source: Source, filename: str | None = None) -> LineageResult

Analyze an Excel workbook and return a :class:LineageResult.

Parameters

source : str | Path | bytes | binary file Path to the file, raw content, or file object opened in rb. filename : str, optional Logical name (used for labels and VBA detection).

Source code in src/linexcel/result.py
def analyze(source: Source, filename: str | None = None) -> LineageResult:
    """Analyze an Excel workbook and return a :class:`LineageResult`.

    Parameters
    ----------
    source : str | Path | bytes | binary file
        Path to the file, raw content, or file object opened in ``rb``.
    filename : str, optional
        Logical name (used for labels and VBA detection).
    """
    data, name = _read_source(source, filename)
    try:
        payload = analyze_workbook(data, filename=name)
    except Exception as exc:
        # Frontière publique : transformer l'erreur brute (BadZipFile, Rust)
        # en message clair sur le vrai problème.
        if not data[:4] == b"PK\x03\x04":
            raise ValueError(
                f"{name!r} is not an Excel file (xlsx/xlsm). "
                "Legacy .xls is not supported — re-save it as .xlsx first."
            ) from exc
        raise ValueError(f"Could not analyze {name!r}: {exc}") from exc
    return LineageResult(
        graph=payload["graph"],
        engine=payload["engine"],
        analysis_id=payload["analysisId"],
        source_data=data,
        filename=name,
    )