|
| 1 | +"""Excel bridge for ModelChoice — read decision trees from a workbook. |
| 2 | +
|
| 3 | +Phase 0 is read-only. ModelChoice exposes no COM object model, but the |
| 4 | +full tree model is persisted as JSON in the very-hidden ``_MC_Store`` |
| 5 | +worksheet (see :mod:`modelchoice_mcp.store`). We read that sheet's row-1 |
| 6 | +content (chunked across columns) via xlwings, parse each tree, and roll |
| 7 | +it back in pure Python — so the add-in need not even be loaded. |
| 8 | +
|
| 9 | +The bridge deliberately does NOT unhide or modify ``_MC_Store``; it |
| 10 | +reads cell values only. |
| 11 | +""" |
| 12 | + |
| 13 | +from __future__ import annotations |
| 14 | + |
| 15 | +from typing import Any |
| 16 | + |
| 17 | +from modelchoice_mcp.store import STORE_SHEET_NAME, parse_store, reassemble_chunks |
| 18 | +from modelchoice_mcp.tree import DecisionTree, RollupResult, parse_model, rollup |
| 19 | + |
| 20 | + |
| 21 | +class ModelChoiceNotFoundError(RuntimeError): |
| 22 | + """The workbook contains no ModelChoice tree store (`_MC_Store`).""" |
| 23 | + |
| 24 | + |
| 25 | +class ExcelNotRunningError(RuntimeError): |
| 26 | + """No running Excel instance could be attached.""" |
| 27 | + |
| 28 | + |
| 29 | +class ModelChoiceBridge: |
| 30 | + """Attach to a running Excel and read ModelChoice trees from a |
| 31 | + workbook's very-hidden ``_MC_Store`` sheet.""" |
| 32 | + |
| 33 | + def __init__(self) -> None: |
| 34 | + self._xw: Any = None |
| 35 | + |
| 36 | + def _load_xw(self) -> Any: |
| 37 | + if self._xw is None: |
| 38 | + import xlwings # imported lazily so the package is importable without Excel |
| 39 | + |
| 40 | + self._xw = xlwings |
| 41 | + return self._xw |
| 42 | + |
| 43 | + def _book(self, workbook: str | None) -> Any: |
| 44 | + xw = self._load_xw() |
| 45 | + app = xw.apps.active |
| 46 | + if app is None: |
| 47 | + raise ExcelNotRunningError( |
| 48 | + "No running Excel instance found. Open the workbook in Excel first." |
| 49 | + ) |
| 50 | + if workbook is None: |
| 51 | + return app.books.active |
| 52 | + for b in app.books: |
| 53 | + if b.name == workbook: |
| 54 | + return b |
| 55 | + raise ModelChoiceNotFoundError(f"Workbook {workbook!r} is not open.") |
| 56 | + |
| 57 | + def read_store_raw(self, workbook: str | None = None) -> str: |
| 58 | + """Return the reassembled ``_MC_Store`` A1 payload, or '' if the |
| 59 | + sheet is absent.""" |
| 60 | + book = self._book(workbook) |
| 61 | + try: |
| 62 | + sheet = book.sheets[STORE_SHEET_NAME] |
| 63 | + except Exception: |
| 64 | + return "" |
| 65 | + # Read row 1 across enough columns to cover the chunk limit. |
| 66 | + row = sheet.range((1, 1), (1, 100)).value |
| 67 | + if not isinstance(row, list): |
| 68 | + row = [row] |
| 69 | + cells = [None if v is None else str(v) for v in row] |
| 70 | + return reassemble_chunks(cells) |
| 71 | + |
| 72 | + def list_trees(self, workbook: str | None = None) -> dict[str, str]: |
| 73 | + """Return a mapping of tree-sheet-name → model JSON string.""" |
| 74 | + raw = self.read_store_raw(workbook) |
| 75 | + if not raw: |
| 76 | + raise ModelChoiceNotFoundError( |
| 77 | + "Workbook has no ModelChoice tree store (_MC_Store sheet)." |
| 78 | + ) |
| 79 | + return parse_store(raw) |
| 80 | + |
| 81 | + def get_tree(self, sheet_name: str | None = None, workbook: str | None = None) -> DecisionTree: |
| 82 | + """Parse one tree (by its sheet name, or the first/only tree).""" |
| 83 | + trees = self.list_trees(workbook) |
| 84 | + if not trees: |
| 85 | + raise ModelChoiceNotFoundError("No trees stored in this workbook.") |
| 86 | + if sheet_name is None: |
| 87 | + sheet_name = next(iter(trees)) |
| 88 | + if sheet_name not in trees: |
| 89 | + raise ModelChoiceNotFoundError( |
| 90 | + f"Tree {sheet_name!r} not found. Available: {', '.join(trees)}." |
| 91 | + ) |
| 92 | + return parse_model(trees[sheet_name]) |
| 93 | + |
| 94 | + def roll_up(self, sheet_name: str | None = None, workbook: str | None = None) -> RollupResult: |
| 95 | + """Read a tree and return its rolled-back EV + optimal policy.""" |
| 96 | + return rollup(self.get_tree(sheet_name, workbook)) |
0 commit comments