pbidriver 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
pbidriver/__init__.py ADDED
@@ -0,0 +1,8 @@
1
+ """pbidriver: WebDriver for Power BI Desktop. Lets AI agents see and drive it.
2
+
3
+ The command line lives in pbidriver.cli; pbidriver.bridge talks to Microsoft's Desktop Bridge and
4
+ the local model, and pbidriver.definition reads report files.
5
+ """
6
+
7
+ __version__ = "0.1.0"
8
+ __author__ = "Jerome Eliezer"
pbidriver/__main__.py ADDED
@@ -0,0 +1,6 @@
1
+ """`python -m pbidriver ...` runs the command line."""
2
+ import sys
3
+
4
+ from pbidriver.cli import main
5
+
6
+ sys.exit(main())
pbidriver/bridge.py ADDED
@@ -0,0 +1,378 @@
1
+ """Power BI Desktop instances, Microsoft's Desktop Bridge, and DAX against the local model.
2
+
3
+ None of this needs DevTools, so it works with any running Power BI Desktop, including one
4
+ opened by double-clicking a file:
5
+
6
+ * instances() every running Power BI Desktop: pid, window, file, DevTools port, Bridge, model port
7
+ * bridge_call() JSON-RPC 2.0 over the Desktop Bridge named pipe (Power BI Desktop June 2026+)
8
+ * run_dax() DAX queries through the ADOMD.NET client that ships with Power BI Desktop
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ import os
14
+ import re
15
+ import subprocess
16
+ import tempfile
17
+ import threading
18
+ import time
19
+ from pathlib import Path
20
+
21
+ PIPE_DIR = "\\\\.\\pipe\\"
22
+ PIPE_PREFIX = "pbi-desktop-bridge-"
23
+ BRIDGE_CLIENT = "pbidriver"
24
+
25
+
26
+ class BridgeError(Exception):
27
+ """A Bridge or model call that failed; the message is meant for the user."""
28
+
29
+ def __init__(self, message: str, reason: str | None = None, retryable: bool = False):
30
+ super().__init__(message)
31
+ self.reason = reason
32
+ self.retryable = retryable
33
+
34
+
35
+ # --------------------------------------------------------------------------- instances
36
+
37
+ def _bridge_pipes() -> set[int]:
38
+ try:
39
+ names = os.listdir(PIPE_DIR)
40
+ except OSError:
41
+ return set()
42
+ return {int(n[len(PIPE_PREFIX):]) for n in names if n.startswith(PIPE_PREFIX) and n[len(PIPE_PREFIX):].isdigit()}
43
+
44
+
45
+ def _listen_ports(proc) -> list[int]:
46
+ import psutil
47
+
48
+ try:
49
+ conns = proc.net_connections(kind="tcp")
50
+ except (psutil.Error, AttributeError):
51
+ try:
52
+ conns = proc.connections(kind="tcp") # psutil < 6
53
+ except psutil.Error:
54
+ return []
55
+ return sorted({c.laddr.port for c in conns if c.status == psutil.CONN_LISTEN and c.laddr})
56
+
57
+
58
+ def main_window(pid: int):
59
+ """(hwnd, title) of the largest visible, unowned, titled window of a process, or None."""
60
+ import win32gui
61
+ import win32process
62
+
63
+ found = []
64
+
65
+ def cb(hwnd, _):
66
+ if (win32gui.IsWindowVisible(hwnd) and not win32gui.GetWindow(hwnd, 4) # 4 = GW_OWNER
67
+ and win32process.GetWindowThreadProcessId(hwnd)[1] == pid and win32gui.GetWindowText(hwnd)):
68
+ left, top, right, bottom = win32gui.GetWindowPlacement(hwnd)[4]
69
+ found.append(((right - left) * (bottom - top), hwnd))
70
+ return True
71
+
72
+ win32gui.EnumWindows(cb, None)
73
+ if not found:
74
+ return None
75
+ hwnd = max(found)[1]
76
+ return hwnd, win32gui.GetWindowText(hwnd)
77
+
78
+
79
+ def describe_instance(proc, pipes: set[int] | None = None) -> dict:
80
+ """What is known about one PBIDesktop process, cheaply (no DevTools or Bridge calls)."""
81
+ import psutil
82
+
83
+ pipes = _bridge_pipes() if pipes is None else pipes
84
+ info: dict = {"pid": proc.pid, "window_title": None, "file": None, "devtools_port": None,
85
+ "bridge": proc.pid in pipes, "model_port": None}
86
+ win = main_window(proc.pid)
87
+ if win:
88
+ info["window_title"] = win[1]
89
+ try:
90
+ args = proc.cmdline()
91
+ info["file"] = next((x for x in args[1:] if x.lower().endswith((".pbix", ".pbip", ".pbit"))), None)
92
+ for child in proc.children(recursive=False):
93
+ name = child.name().lower()
94
+ if name == "msedgewebview2.exe" and info["devtools_port"] is None:
95
+ m = re.search(r"--remote-debugging-port=(\d+)", " ".join(child.cmdline()))
96
+ if m:
97
+ info["devtools_port"] = int(m.group(1))
98
+ elif name == "msmdsrv.exe" and info["model_port"] is None:
99
+ ports = _listen_ports(child)
100
+ info["model_port"] = ports[0] if ports else None
101
+ except psutil.Error:
102
+ pass
103
+ return info
104
+
105
+
106
+ def instances() -> list[dict]:
107
+ import psutil
108
+
109
+ pipes = _bridge_pipes()
110
+ out = []
111
+ for p in psutil.process_iter(["name"]):
112
+ if (p.info.get("name") or "").lower() == "pbidesktop.exe":
113
+ out.append(describe_instance(p, pipes))
114
+ return sorted(out, key=lambda i: i["pid"])
115
+
116
+
117
+ def instance(pid: int) -> dict:
118
+ import psutil
119
+
120
+ try:
121
+ return describe_instance(psutil.Process(pid))
122
+ except psutil.Error:
123
+ raise BridgeError(f"No Power BI Desktop process with pid {pid}.") from None
124
+
125
+
126
+ # --------------------------------------------------------------------------- Desktop Bridge
127
+
128
+ def bridge_call(pid: int, method: str, args: dict | None = None, timeout: float = 90, retries: int = 3) -> dict:
129
+ """Call one Bridge method and return its `result`. The pipe serves one operation at a time,
130
+ so a busy or retryable error is retried a few times."""
131
+ for attempt in range(retries + 1):
132
+ try:
133
+ return _bridge_once(pid, method, args or {}, timeout)
134
+ except BridgeError as e:
135
+ if not e.retryable or attempt == retries:
136
+ raise
137
+ time.sleep(2)
138
+ raise AssertionError("unreachable")
139
+
140
+
141
+ def _bridge_once(pid: int, method: str, args: dict, timeout: float) -> dict:
142
+ import pywintypes
143
+ import win32file
144
+ import win32pipe
145
+
146
+ name = f"{PIPE_DIR}{PIPE_PREFIX}{pid}"
147
+ try:
148
+ win32pipe.WaitNamedPipe(name, 5000)
149
+ handle = win32file.CreateFile(name, win32file.GENERIC_READ | win32file.GENERIC_WRITE, 0, None,
150
+ win32file.OPEN_EXISTING, 0, None)
151
+ except pywintypes.error as e:
152
+ if e.winerror == 231: # ERROR_PIPE_BUSY
153
+ raise BridgeError("The Desktop Bridge is busy with another client.", "Busy", True) from None
154
+ raise BridgeError(
155
+ f"No Desktop Bridge for Power BI process {pid}. It needs Power BI Desktop June 2026 or later, with "
156
+ "Options > Security > 'Enable external tool access to Power BI Desktop through secure local APIs' on."
157
+ ) from None
158
+
159
+ request = {"jsonrpc": "2.0", "id": int(time.time() * 1000) % 1_000_000_000, "method": method,
160
+ "params": {"client": BRIDGE_CLIENT, "args": args}}
161
+ body = json.dumps(request).encode("utf-8")
162
+ box: dict = {}
163
+
164
+ def exchange():
165
+ try:
166
+ win32file.WriteFile(handle, b"Content-Length: %d\r\n\r\n" % len(body) + body)
167
+ buf = b""
168
+ while b"\r\n\r\n" not in buf:
169
+ buf += win32file.ReadFile(handle, 65536)[1]
170
+ head, rest = buf.split(b"\r\n\r\n", 1)
171
+ length = next(int(line.split(b":", 1)[1]) for line in head.split(b"\r\n")
172
+ if line.lower().startswith(b"content-length"))
173
+ while len(rest) < length:
174
+ rest += win32file.ReadFile(handle, 1 << 20)[1]
175
+ box["response"] = json.loads(rest[:length].decode("utf-8"))
176
+ except Exception as e: # noqa: BLE001 reported below
177
+ box["error"] = e
178
+
179
+ worker = threading.Thread(target=exchange, daemon=True)
180
+ worker.start()
181
+ worker.join(timeout)
182
+ try:
183
+ handle.Close()
184
+ except Exception: # noqa: BLE001
185
+ pass
186
+ if worker.is_alive():
187
+ raise BridgeError(f"Desktop Bridge call {method} timed out after {timeout:.0f}s.", "Timeout")
188
+ if "error" in box:
189
+ raise BridgeError(f"Desktop Bridge call {method} failed: {box['error']}")
190
+ response = box["response"]
191
+ if "error" in response:
192
+ err = response["error"]
193
+ data = err.get("data") or {}
194
+ raise BridgeError(err.get("message") or str(err), data.get("reason"), bool(data.get("retryable")))
195
+ return response.get("result") or {}
196
+
197
+
198
+ def bridge_methods(pid: int) -> list[str]:
199
+ return [m["name"] for m in bridge_call(pid, "bridge.manifest").get("methods", [])]
200
+
201
+
202
+ def bridge_state(pid: int) -> dict:
203
+ r = bridge_call(pid, "application.state.get/v1", timeout=15)
204
+ return {"file": r.get("currentFilePath") or None, "unsaved": bool(r.get("hasUnsavedChanges"))}
205
+
206
+
207
+ def bridge_snapshot(pid: int, page_id: str, scale: float = 1.0, region: dict | None = None) -> bytes:
208
+ """PNG of a report page (or a region of it, in page units). Region needs capture/v2."""
209
+ import base64
210
+
211
+ args: dict = {"pageId": page_id, "scale": max(1.0, min(3.0, float(scale)))}
212
+ method = "report.snapshot.capture/v1"
213
+ if region is not None:
214
+ args["region"] = {k: float(region[k]) for k in ("x", "y", "width", "height")}
215
+ method = "report.snapshot.capture/v2"
216
+ result = bridge_call(pid, method, args, timeout=60)
217
+ if not result.get("payload"):
218
+ raise BridgeError("The Desktop Bridge returned no image.")
219
+ return base64.b64decode(result["payload"])
220
+
221
+
222
+ def bridge_reload(pid: int, model: bool = True) -> dict:
223
+ return bridge_call(pid, "file.reload/v1", {"reloadModelDefinition": bool(model)}, timeout=300)
224
+
225
+
226
+ # --------------------------------------------------------------------------- DAX over ADOMD.NET
227
+
228
+ # Runs in Windows PowerShell 5.1 (.NET Framework), which can load the ADOMD.NET client that
229
+ # ships inside Power BI Desktop, so no extra Python or .NET packages are needed.
230
+ _ADOMD_PS = r"""
231
+ param([string]$Dll, [int]$Port, [string]$QueryFile, [int]$MaxRows, [int]$Timeout)
232
+ $ErrorActionPreference = 'Stop'
233
+ [Console]::OutputEncoding = [Text.Encoding]::UTF8
234
+ function Convert-Value($v) {
235
+ if ($v -is [DBNull] -or $null -eq $v) { return $null }
236
+ if ($v -is [DateTime]) { return $v.ToString('o') }
237
+ if ($v -is [double] -and ([double]::IsNaN($v) -or [double]::IsInfinity($v))) { return [string]$v }
238
+ return $v
239
+ }
240
+ $results = New-Object System.Collections.ArrayList
241
+ try {
242
+ Add-Type -Path $Dll
243
+ $cn = New-Object Microsoft.AnalysisServices.AdomdClient.AdomdConnection("Data Source=localhost:$Port")
244
+ $cn.Open()
245
+ $queries = [IO.File]::ReadAllText($QueryFile, [Text.Encoding]::UTF8) | ConvertFrom-Json
246
+ foreach ($q in $queries) {
247
+ $sw = [Diagnostics.Stopwatch]::StartNew()
248
+ try {
249
+ $cmd = $cn.CreateCommand(); $cmd.CommandText = $q; $cmd.CommandTimeout = $Timeout
250
+ $r = $cmd.ExecuteReader()
251
+ $cols = @(for ($i = 0; $i -lt $r.FieldCount; $i++) { $r.GetName($i) })
252
+ $rows = New-Object System.Collections.ArrayList
253
+ $total = 0
254
+ while ($r.Read()) {
255
+ $total++
256
+ if ($rows.Count -lt $MaxRows) {
257
+ $row = New-Object object[] $r.FieldCount
258
+ for ($i = 0; $i -lt $r.FieldCount; $i++) { $row[$i] = Convert-Value $r.GetValue($i) }
259
+ [void]$rows.Add($row)
260
+ }
261
+ }
262
+ $r.Close()
263
+ [void]$results.Add(@{ ok = $true; columns = $cols; rows = $rows; row_count = $total; ms = $sw.ElapsedMilliseconds })
264
+ } catch {
265
+ $e = $_.Exception; while ($e.InnerException) { $e = $e.InnerException }
266
+ [void]$results.Add(@{ ok = $false; error = $e.Message; ms = $sw.ElapsedMilliseconds })
267
+ }
268
+ }
269
+ $cn.Close()
270
+ ConvertTo-Json -InputObject @{ ok = $true; results = $results } -Depth 6 -Compress
271
+ } catch {
272
+ ConvertTo-Json -InputObject @{ ok = $false; error = $_.Exception.Message } -Compress
273
+ }
274
+ """
275
+
276
+
277
+ def adomd_dll(pid: int) -> Path:
278
+ """The ADOMD.NET client bundled with this Power BI Desktop (env PBI_ADOMD_DLL overrides)."""
279
+ import psutil
280
+
281
+ override = os.environ.get("PBI_ADOMD_DLL")
282
+ if override:
283
+ return Path(override)
284
+ try:
285
+ bin_dir = Path(psutil.Process(pid).exe()).parent
286
+ except psutil.Error:
287
+ raise BridgeError(f"Cannot read the install folder of Power BI process {pid}.") from None
288
+ for name in ("Microsoft.PowerBI.AdomdClient.dll", "Microsoft.AnalysisServices.AdomdClient.dll"):
289
+ if (bin_dir / name).exists():
290
+ return bin_dir / name
291
+ raise BridgeError(f"No ADOMD.NET client found in {bin_dir}. Set PBI_ADOMD_DLL to Microsoft.AnalysisServices.AdomdClient.dll.")
292
+
293
+
294
+ def _clean_columns(cols: list[str]) -> list[str]:
295
+ # ADOMD names columns like "[Name]" or "Table[Column]"; keep them readable but unambiguous.
296
+ return [c[1:-1] if c.startswith("[") and c.endswith("]") and c.count("[") == 1 else c for c in cols]
297
+
298
+
299
+ def run_dax(pid: int, queries: list[str], max_rows: int = 1000, timeout: int = 120) -> list[dict]:
300
+ """Run DAX queries against the model of one Power BI instance. One result per query:
301
+ {"ok", "columns", "rows", "row_count", "truncated", "ms"} or {"ok": false, "error"}."""
302
+ info = instance(pid)
303
+ if not info["model_port"]:
304
+ raise BridgeError("This Power BI instance has no running model engine (open a report with a data model).")
305
+ dll = adomd_dll(pid)
306
+ tmp = Path(tempfile.gettempdir())
307
+ script = tmp / "pbidriver_adomd.ps1"
308
+ if not script.exists() or script.read_text(encoding="utf-8") != _ADOMD_PS:
309
+ script.write_text(_ADOMD_PS, encoding="utf-8")
310
+ with tempfile.NamedTemporaryFile("w", suffix=".json", delete=False, encoding="utf-8") as f:
311
+ json.dump(list(queries), f)
312
+ query_file = f.name
313
+ try:
314
+ proc = subprocess.run(
315
+ ["powershell.exe", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File", str(script),
316
+ "-Dll", str(dll), "-Port", str(info["model_port"]), "-QueryFile", query_file,
317
+ "-MaxRows", str(max_rows), "-Timeout", str(timeout)],
318
+ capture_output=True, timeout=timeout + 60, creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),
319
+ )
320
+ except FileNotFoundError:
321
+ raise BridgeError("Windows PowerShell (powershell.exe) is needed to run DAX queries.") from None
322
+ except subprocess.TimeoutExpired:
323
+ raise BridgeError(f"DAX query timed out after {timeout}s.") from None
324
+ finally:
325
+ os.unlink(query_file)
326
+ out = proc.stdout.decode("utf-8", "replace").strip()
327
+ try:
328
+ data = json.loads(out.splitlines()[-1]) if out else None
329
+ except (json.JSONDecodeError, IndexError):
330
+ data = None
331
+ if not data:
332
+ raise BridgeError("DAX runner failed: " + (proc.stderr.decode("utf-8", "replace").strip()[:500] or out[:500]))
333
+ if not data.get("ok"):
334
+ raise BridgeError("Could not query the model: " + str(data.get("error")))
335
+ results = data["results"]
336
+ if isinstance(results, dict): # a single result may come back unwrapped
337
+ results = [results]
338
+ for r in results:
339
+ if r.get("ok"):
340
+ r["columns"] = _clean_columns(r.get("columns") or [])
341
+ rows = r.get("rows") or []
342
+ if rows and not isinstance(rows[0], list): # one-column rows may come back flattened
343
+ rows = [[v] for v in rows]
344
+ r["rows"] = rows
345
+ r["truncated"] = r.get("row_count", 0) > len(rows)
346
+ return results
347
+
348
+
349
+ _MODEL_QUERIES = {
350
+ "tables": "EVALUATE INFO.VIEW.TABLES()",
351
+ "columns": "EVALUATE INFO.VIEW.COLUMNS()",
352
+ "measures": "EVALUATE INFO.VIEW.MEASURES()",
353
+ "relationships": "EVALUATE INFO.VIEW.RELATIONSHIPS()",
354
+ }
355
+ _MODEL_DROP = {"ID", "Model", "LineageTag", "SourceLineageTag", "TableID", "ColumnID", "ModifiedTime",
356
+ "StructureModifiedTime", "RefreshedTime", "State", "ErrorMessage", "IsPrivate",
357
+ "ShowAsVariationOnly", "CalculationGroupPrecedence", "ExcludeFromModelRefresh",
358
+ "LineageTagSourceTable", "SortByColumnID", "AttributeHierarchyID", "RelyOnReferentialIntegrity",
359
+ "SecurityFilteringBehavior", "JoinOnDateBehavior", "IsUnique", "IsKey", "IsNullable",
360
+ "IsAvailableInMDX", "KeepUniqueRows", "SummarizeBy", "Alignment", "TableDetailPosition",
361
+ "IsDefaultLabel", "IsDefaultImage", "EncodingHint", "DisplayOrdinal", "SourceProviderType",
362
+ "DetailRowsDefinition", "KPIID", "DataCategory", "FormatStringDefinition", "Annotations",
363
+ "ColumnStorage", "TableStorage", "GroupingBehavior", "IsSimpleMeasure"}
364
+
365
+
366
+ def model_info(pid: int) -> dict:
367
+ """Tables, columns, measures and relationships of the open model (INFO.VIEW DAX functions)."""
368
+ names = list(_MODEL_QUERIES)
369
+ results = run_dax(pid, [_MODEL_QUERIES[n] for n in names], max_rows=100_000)
370
+ out: dict = {}
371
+ for name, r in zip(names, results):
372
+ if not r.get("ok"):
373
+ out[name] = {"error": r.get("error")}
374
+ continue
375
+ keep = [i for i, c in enumerate(r["columns"]) if c not in _MODEL_DROP]
376
+ rows = [{r["columns"][i]: row[i] for i in keep if row[i] not in (None, "")} for row in r["rows"]]
377
+ out[name] = [x for x in rows if x.get("Type") != "RowNumber"] # engine-internal columns
378
+ return out