kiwi-array-jupyter 0.5.0__tar.gz
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.
- kiwi_array_jupyter-0.5.0/PKG-INFO +44 -0
- kiwi_array_jupyter-0.5.0/README.md +33 -0
- kiwi_array_jupyter-0.5.0/pyproject.toml +36 -0
- kiwi_array_jupyter-0.5.0/setup.cfg +4 -0
- kiwi_array_jupyter-0.5.0/src/kiwi_array_jupyter.egg-info/PKG-INFO +44 -0
- kiwi_array_jupyter-0.5.0/src/kiwi_array_jupyter.egg-info/SOURCES.txt +16 -0
- kiwi_array_jupyter-0.5.0/src/kiwi_array_jupyter.egg-info/dependency_links.txt +1 -0
- kiwi_array_jupyter-0.5.0/src/kiwi_array_jupyter.egg-info/entry_points.txt +4 -0
- kiwi_array_jupyter-0.5.0/src/kiwi_array_jupyter.egg-info/requires.txt +4 -0
- kiwi_array_jupyter-0.5.0/src/kiwi_array_jupyter.egg-info/top_level.txt +1 -0
- kiwi_array_jupyter-0.5.0/src/kiwi_array_jupyter_kernel/__init__.py +5 -0
- kiwi_array_jupyter-0.5.0/src/kiwi_array_jupyter_kernel/__main__.py +13 -0
- kiwi_array_jupyter-0.5.0/src/kiwi_array_jupyter_kernel/assets/kernel-logo.png +0 -0
- kiwi_array_jupyter-0.5.0/src/kiwi_array_jupyter_kernel/binding.py +140 -0
- kiwi_array_jupyter-0.5.0/src/kiwi_array_jupyter_kernel/execution.py +162 -0
- kiwi_array_jupyter-0.5.0/src/kiwi_array_jupyter_kernel/install.py +163 -0
- kiwi_array_jupyter-0.5.0/src/kiwi_array_jupyter_kernel/kernel.py +180 -0
- kiwi_array_jupyter-0.5.0/tests/test_kiwi_jupyter_kernel.py +399 -0
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: kiwi-array-jupyter
|
|
3
|
+
Version: 0.5.0
|
|
4
|
+
Summary: Jupyter kernel for Kiwi (kiwi-zig-v2).
|
|
5
|
+
Requires-Python: >=3.10
|
|
6
|
+
Description-Content-Type: text/markdown
|
|
7
|
+
Requires-Dist: kiwi-array>=0.5.0
|
|
8
|
+
Requires-Dist: ipykernel>=6.29
|
|
9
|
+
Requires-Dist: jupyter_client>=8.6
|
|
10
|
+
Requires-Dist: jupyter_core>=5.7
|
|
11
|
+
|
|
12
|
+
# Kiwi Jupyter Kernel
|
|
13
|
+
|
|
14
|
+
`kiwi-array-jupyter` is the Jupyter kernel for **Kiwi** (`kiwi-zig-v2`).
|
|
15
|
+
|
|
16
|
+
It runs a lightweight `ipykernel` host that loads `libkiwi_bridge` from the installed `kiwi-array` wheel (or a local `kiwi-zig-v2` checkout) over the unified `kiwi.h` C ABI:
|
|
17
|
+
|
|
18
|
+
```text
|
|
19
|
+
Jupyter -> ipykernel -> ctypes -> libkiwi_bridge -> Kiwi v2 Session
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
## Install
|
|
23
|
+
|
|
24
|
+
```bash
|
|
25
|
+
pip install kiwi-array-jupyter
|
|
26
|
+
kiwi-array-jupyter-install --user
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
Installing `kiwi-array-jupyter` automatically pulls in `kiwi-array>=0.5.0`, which bundles the self-contained native `libkiwi_bridge` library and `kiwi` CLI (~600 KB). No separate backend packages are required.
|
|
30
|
+
|
|
31
|
+
## Features
|
|
32
|
+
|
|
33
|
+
- Stateful execution across cells with balanced multiline statement grouping.
|
|
34
|
+
- Assignments suppress output; echoed results render in the notebook.
|
|
35
|
+
- Vega-Lite JSON specs (`` `j@... ``) emit `application/vnd.vegalite.v5+json` display bundles.
|
|
36
|
+
- Built-in completion, `inspect`, and delimiter-aware `is_complete`.
|
|
37
|
+
- Set `KIWI_JUPYTER_DEVICE=cpu|gpu|auto` or `KIWI_BRIDGE_LIB=/path/to/libkiwi_bridge.*` to override runtime settings.
|
|
38
|
+
|
|
39
|
+
## Local Development & Tests
|
|
40
|
+
|
|
41
|
+
```bash
|
|
42
|
+
make build-v2-bridge
|
|
43
|
+
cd extensions/jupyter-kiwi && uv run --python 3.11.13 pytest -v
|
|
44
|
+
```
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
# Kiwi Jupyter Kernel
|
|
2
|
+
|
|
3
|
+
`kiwi-array-jupyter` is the Jupyter kernel for **Kiwi** (`kiwi-zig-v2`).
|
|
4
|
+
|
|
5
|
+
It runs a lightweight `ipykernel` host that loads `libkiwi_bridge` from the installed `kiwi-array` wheel (or a local `kiwi-zig-v2` checkout) over the unified `kiwi.h` C ABI:
|
|
6
|
+
|
|
7
|
+
```text
|
|
8
|
+
Jupyter -> ipykernel -> ctypes -> libkiwi_bridge -> Kiwi v2 Session
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Install
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
pip install kiwi-array-jupyter
|
|
15
|
+
kiwi-array-jupyter-install --user
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
Installing `kiwi-array-jupyter` automatically pulls in `kiwi-array>=0.5.0`, which bundles the self-contained native `libkiwi_bridge` library and `kiwi` CLI (~600 KB). No separate backend packages are required.
|
|
19
|
+
|
|
20
|
+
## Features
|
|
21
|
+
|
|
22
|
+
- Stateful execution across cells with balanced multiline statement grouping.
|
|
23
|
+
- Assignments suppress output; echoed results render in the notebook.
|
|
24
|
+
- Vega-Lite JSON specs (`` `j@... ``) emit `application/vnd.vegalite.v5+json` display bundles.
|
|
25
|
+
- Built-in completion, `inspect`, and delimiter-aware `is_complete`.
|
|
26
|
+
- Set `KIWI_JUPYTER_DEVICE=cpu|gpu|auto` or `KIWI_BRIDGE_LIB=/path/to/libkiwi_bridge.*` to override runtime settings.
|
|
27
|
+
|
|
28
|
+
## Local Development & Tests
|
|
29
|
+
|
|
30
|
+
```bash
|
|
31
|
+
make build-v2-bridge
|
|
32
|
+
cd extensions/jupyter-kiwi && uv run --python 3.11.13 pytest -v
|
|
33
|
+
```
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=82", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "kiwi-array-jupyter"
|
|
7
|
+
version = "0.5.0"
|
|
8
|
+
description = "Jupyter kernel for Kiwi (kiwi-zig-v2)."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
dependencies = [
|
|
12
|
+
"kiwi-array>=0.5.0",
|
|
13
|
+
"ipykernel>=6.29",
|
|
14
|
+
"jupyter_client>=8.6",
|
|
15
|
+
"jupyter_core>=5.7",
|
|
16
|
+
]
|
|
17
|
+
|
|
18
|
+
[dependency-groups]
|
|
19
|
+
dev = [
|
|
20
|
+
"pytest>=8.3",
|
|
21
|
+
"jupyter_kernel_test>=0.7",
|
|
22
|
+
]
|
|
23
|
+
|
|
24
|
+
[project.scripts]
|
|
25
|
+
kiwi-array-jupyter-install = "kiwi_array_jupyter_kernel.install:main"
|
|
26
|
+
kiwi-array-jupyter-kernel-install = "kiwi_array_jupyter_kernel.install:main"
|
|
27
|
+
kiwi-jupyter-kernel-install = "kiwi_array_jupyter_kernel.install:main"
|
|
28
|
+
|
|
29
|
+
[tool.setuptools.package-dir]
|
|
30
|
+
"" = "src"
|
|
31
|
+
|
|
32
|
+
[tool.setuptools.packages.find]
|
|
33
|
+
where = ["src"]
|
|
34
|
+
|
|
35
|
+
[tool.setuptools.package-data]
|
|
36
|
+
kiwi_array_jupyter_kernel = ["assets/*.png"]
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: kiwi-array-jupyter
|
|
3
|
+
Version: 0.5.0
|
|
4
|
+
Summary: Jupyter kernel for Kiwi (kiwi-zig-v2).
|
|
5
|
+
Requires-Python: >=3.10
|
|
6
|
+
Description-Content-Type: text/markdown
|
|
7
|
+
Requires-Dist: kiwi-array>=0.5.0
|
|
8
|
+
Requires-Dist: ipykernel>=6.29
|
|
9
|
+
Requires-Dist: jupyter_client>=8.6
|
|
10
|
+
Requires-Dist: jupyter_core>=5.7
|
|
11
|
+
|
|
12
|
+
# Kiwi Jupyter Kernel
|
|
13
|
+
|
|
14
|
+
`kiwi-array-jupyter` is the Jupyter kernel for **Kiwi** (`kiwi-zig-v2`).
|
|
15
|
+
|
|
16
|
+
It runs a lightweight `ipykernel` host that loads `libkiwi_bridge` from the installed `kiwi-array` wheel (or a local `kiwi-zig-v2` checkout) over the unified `kiwi.h` C ABI:
|
|
17
|
+
|
|
18
|
+
```text
|
|
19
|
+
Jupyter -> ipykernel -> ctypes -> libkiwi_bridge -> Kiwi v2 Session
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
## Install
|
|
23
|
+
|
|
24
|
+
```bash
|
|
25
|
+
pip install kiwi-array-jupyter
|
|
26
|
+
kiwi-array-jupyter-install --user
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
Installing `kiwi-array-jupyter` automatically pulls in `kiwi-array>=0.5.0`, which bundles the self-contained native `libkiwi_bridge` library and `kiwi` CLI (~600 KB). No separate backend packages are required.
|
|
30
|
+
|
|
31
|
+
## Features
|
|
32
|
+
|
|
33
|
+
- Stateful execution across cells with balanced multiline statement grouping.
|
|
34
|
+
- Assignments suppress output; echoed results render in the notebook.
|
|
35
|
+
- Vega-Lite JSON specs (`` `j@... ``) emit `application/vnd.vegalite.v5+json` display bundles.
|
|
36
|
+
- Built-in completion, `inspect`, and delimiter-aware `is_complete`.
|
|
37
|
+
- Set `KIWI_JUPYTER_DEVICE=cpu|gpu|auto` or `KIWI_BRIDGE_LIB=/path/to/libkiwi_bridge.*` to override runtime settings.
|
|
38
|
+
|
|
39
|
+
## Local Development & Tests
|
|
40
|
+
|
|
41
|
+
```bash
|
|
42
|
+
make build-v2-bridge
|
|
43
|
+
cd extensions/jupyter-kiwi && uv run --python 3.11.13 pytest -v
|
|
44
|
+
```
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
README.md
|
|
2
|
+
pyproject.toml
|
|
3
|
+
src/kiwi_array_jupyter.egg-info/PKG-INFO
|
|
4
|
+
src/kiwi_array_jupyter.egg-info/SOURCES.txt
|
|
5
|
+
src/kiwi_array_jupyter.egg-info/dependency_links.txt
|
|
6
|
+
src/kiwi_array_jupyter.egg-info/entry_points.txt
|
|
7
|
+
src/kiwi_array_jupyter.egg-info/requires.txt
|
|
8
|
+
src/kiwi_array_jupyter.egg-info/top_level.txt
|
|
9
|
+
src/kiwi_array_jupyter_kernel/__init__.py
|
|
10
|
+
src/kiwi_array_jupyter_kernel/__main__.py
|
|
11
|
+
src/kiwi_array_jupyter_kernel/binding.py
|
|
12
|
+
src/kiwi_array_jupyter_kernel/execution.py
|
|
13
|
+
src/kiwi_array_jupyter_kernel/install.py
|
|
14
|
+
src/kiwi_array_jupyter_kernel/kernel.py
|
|
15
|
+
src/kiwi_array_jupyter_kernel/assets/kernel-logo.png
|
|
16
|
+
tests/test_kiwi_jupyter_kernel.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
kiwi_array_jupyter_kernel
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import subprocess
|
|
5
|
+
import sys
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Optional
|
|
8
|
+
|
|
9
|
+
DEVICE_ENV_VAR = "KIWI_JUPYTER_DEVICE"
|
|
10
|
+
LIB_ENV_VAR = "KIWI_BRIDGE_LIB"
|
|
11
|
+
V2_LIB_ENV_VAR = "KIWI_V2_BRIDGE_LIB"
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def jupyter_root() -> Path:
|
|
15
|
+
return Path(__file__).resolve().parents[2]
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def workspace_root() -> Path:
|
|
19
|
+
return jupyter_root().parents[1]
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def v2_root() -> Path:
|
|
23
|
+
return workspace_root() / "implementations" / "kiwi-zig-v2"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def v2_python_src() -> Path:
|
|
27
|
+
return v2_root() / "python"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def experiment_root() -> Path:
|
|
31
|
+
return jupyter_root()
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
try:
|
|
35
|
+
from kiwi_array.bridge import (
|
|
36
|
+
STATUS_NAMES,
|
|
37
|
+
KiwiBridgeError,
|
|
38
|
+
KiwiEvalResult,
|
|
39
|
+
KiwiSession as _BaseKiwiSession,
|
|
40
|
+
find_library_path as _pkg_find_library_path,
|
|
41
|
+
platform_library_name,
|
|
42
|
+
)
|
|
43
|
+
except ImportError:
|
|
44
|
+
_V2_PY = v2_python_src()
|
|
45
|
+
if _V2_PY.exists() and str(_V2_PY) not in sys.path:
|
|
46
|
+
sys.path.insert(0, str(_V2_PY))
|
|
47
|
+
from kiwi_array.bridge import ( # noqa: E402
|
|
48
|
+
STATUS_NAMES,
|
|
49
|
+
KiwiBridgeError,
|
|
50
|
+
KiwiEvalResult,
|
|
51
|
+
KiwiSession as _BaseKiwiSession,
|
|
52
|
+
find_library_path as _pkg_find_library_path,
|
|
53
|
+
platform_library_name,
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def v2_library_path() -> Path:
|
|
58
|
+
return v2_root() / "zig-out" / "lib" / platform_library_name("kiwi_bridge")
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _find_zig_binary() -> str:
|
|
62
|
+
override = os.environ.get("KIWI_ZIG") or os.environ.get("ZIG")
|
|
63
|
+
if override:
|
|
64
|
+
return override
|
|
65
|
+
ws_zig = workspace_root() / "tools" / "zig"
|
|
66
|
+
if ws_zig.is_file():
|
|
67
|
+
return str(ws_zig)
|
|
68
|
+
return "zig"
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def build_bridge(optimize: str = "ReleaseFast") -> None:
|
|
72
|
+
if not (v2_root() / "build.zig").is_file():
|
|
73
|
+
return
|
|
74
|
+
env = dict(os.environ)
|
|
75
|
+
env.setdefault("ZIG_GLOBAL_CACHE_DIR", str(workspace_root() / ".artifacts" / "zig-cache"))
|
|
76
|
+
subprocess.run(
|
|
77
|
+
[_find_zig_binary(), "build", "bridge", f"-Doptimize={optimize}"],
|
|
78
|
+
cwd=v2_root(),
|
|
79
|
+
env=env,
|
|
80
|
+
check=True,
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def find_library_path(path: Optional[str | Path] = None) -> Path:
|
|
85
|
+
if path is not None:
|
|
86
|
+
p = Path(path).expanduser().resolve()
|
|
87
|
+
if p.is_file():
|
|
88
|
+
return p
|
|
89
|
+
raise FileNotFoundError(f"Kiwi bridge library not found at {p}")
|
|
90
|
+
env_path = (
|
|
91
|
+
os.environ.get(V2_LIB_ENV_VAR)
|
|
92
|
+
or os.environ.get(LIB_ENV_VAR)
|
|
93
|
+
or os.environ.get("KIWI_JUPYTER_BRIDGE_LIB")
|
|
94
|
+
)
|
|
95
|
+
if env_path:
|
|
96
|
+
p = Path(env_path).expanduser().resolve()
|
|
97
|
+
if p.is_file():
|
|
98
|
+
return p
|
|
99
|
+
raise FileNotFoundError(f"Kiwi bridge library not found at {p}")
|
|
100
|
+
try:
|
|
101
|
+
return _pkg_find_library_path()
|
|
102
|
+
except KiwiBridgeError:
|
|
103
|
+
pass
|
|
104
|
+
candidate = v2_library_path()
|
|
105
|
+
if candidate.is_file():
|
|
106
|
+
return candidate
|
|
107
|
+
raise FileNotFoundError(
|
|
108
|
+
f"Kiwi v2 bridge library not found. Install `kiwi-array>=0.5.0` or build it with "
|
|
109
|
+
f"`make build-v2-bridge` from {v2_root()}."
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
class KiwiSession(_BaseKiwiSession):
|
|
114
|
+
def __init__(
|
|
115
|
+
self,
|
|
116
|
+
device: str = "auto",
|
|
117
|
+
library_path: Optional[str | Path] = None,
|
|
118
|
+
) -> None:
|
|
119
|
+
resolved = find_library_path(library_path)
|
|
120
|
+
super().__init__(device=device, library_path=resolved)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
__all__ = [
|
|
124
|
+
"DEVICE_ENV_VAR",
|
|
125
|
+
"LIB_ENV_VAR",
|
|
126
|
+
"STATUS_NAMES",
|
|
127
|
+
"V2_LIB_ENV_VAR",
|
|
128
|
+
"KiwiBridgeError",
|
|
129
|
+
"KiwiEvalResult",
|
|
130
|
+
"KiwiSession",
|
|
131
|
+
"build_bridge",
|
|
132
|
+
"experiment_root",
|
|
133
|
+
"find_library_path",
|
|
134
|
+
"jupyter_root",
|
|
135
|
+
"platform_library_name",
|
|
136
|
+
"v2_library_path",
|
|
137
|
+
"v2_python_src",
|
|
138
|
+
"v2_root",
|
|
139
|
+
"workspace_root",
|
|
140
|
+
]
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from typing import Iterator, Protocol
|
|
5
|
+
|
|
6
|
+
from .binding import KiwiEvalResult
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class SessionProtocol(Protocol):
|
|
10
|
+
def eval(self, source: str) -> KiwiEvalResult:
|
|
11
|
+
...
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass(frozen=True)
|
|
15
|
+
class CellOutput:
|
|
16
|
+
line_no: int
|
|
17
|
+
text: str
|
|
18
|
+
display_mime: str | None = None
|
|
19
|
+
display_data: str | None = None
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class CellExecutionError(RuntimeError):
|
|
23
|
+
def __init__(self, line_no: int, status: str) -> None:
|
|
24
|
+
self.line_no = line_no
|
|
25
|
+
self.status = status
|
|
26
|
+
super().__init__(f"line {line_no}: !{status}")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def iter_executable_lines(code: str) -> Iterator[tuple[int, str]]:
|
|
30
|
+
for line_no, raw_line in enumerate(code.splitlines(), start=1):
|
|
31
|
+
line = sanitize_line(raw_line)
|
|
32
|
+
if line is None:
|
|
33
|
+
continue
|
|
34
|
+
yield line_no, line
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def sanitize_line(raw_line: str) -> str | None:
|
|
38
|
+
line = raw_line.strip(" \t\r")
|
|
39
|
+
if not line or line.startswith("/"):
|
|
40
|
+
return None
|
|
41
|
+
|
|
42
|
+
for index, ch in enumerate(line):
|
|
43
|
+
if ch == "/" and index > 0 and line[index - 1].isspace():
|
|
44
|
+
trimmed = line[:index].rstrip(" \t")
|
|
45
|
+
return trimmed or None
|
|
46
|
+
return line
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def iter_executable_statements(code: str) -> Iterator[tuple[int, str]]:
|
|
50
|
+
pending: list[str] = []
|
|
51
|
+
start_line = 0
|
|
52
|
+
depth = ScriptDepth()
|
|
53
|
+
|
|
54
|
+
for line_no, line in iter_executable_lines(code):
|
|
55
|
+
if not pending:
|
|
56
|
+
start_line = line_no
|
|
57
|
+
depth = ScriptDepth()
|
|
58
|
+
pending.append(line)
|
|
59
|
+
if not update_script_depth(line, depth):
|
|
60
|
+
raise CellExecutionError(line_no, "parse")
|
|
61
|
+
if not depth.is_zero():
|
|
62
|
+
continue
|
|
63
|
+
yield start_line, "\n".join(pending)
|
|
64
|
+
pending.clear()
|
|
65
|
+
|
|
66
|
+
if pending:
|
|
67
|
+
raise CellExecutionError(start_line, "parse")
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def execute_cell(session: SessionProtocol, code: str) -> list[CellOutput]:
|
|
71
|
+
outputs: list[CellOutput] = []
|
|
72
|
+
for line_no, statement in iter_executable_statements(code):
|
|
73
|
+
result = session.eval(statement)
|
|
74
|
+
if result.status != "ok":
|
|
75
|
+
raise CellExecutionError(line_no, result.status)
|
|
76
|
+
if result.echoed and result.text is not None:
|
|
77
|
+
outputs.append(
|
|
78
|
+
CellOutput(
|
|
79
|
+
line_no=line_no,
|
|
80
|
+
text=result.text,
|
|
81
|
+
display_mime=result.display_mime,
|
|
82
|
+
display_data=result.display_data,
|
|
83
|
+
)
|
|
84
|
+
)
|
|
85
|
+
return outputs
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
@dataclass
|
|
89
|
+
class ScriptDepth:
|
|
90
|
+
paren: int = 0
|
|
91
|
+
bracket: int = 0
|
|
92
|
+
brace: int = 0
|
|
93
|
+
|
|
94
|
+
def is_zero(self) -> bool:
|
|
95
|
+
return self.paren == 0 and self.bracket == 0 and self.brace == 0
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def update_script_depth(line: str, depth: ScriptDepth) -> bool:
|
|
99
|
+
index = 0
|
|
100
|
+
while index < len(line):
|
|
101
|
+
ch = line[index]
|
|
102
|
+
if ch == '"':
|
|
103
|
+
index += 1
|
|
104
|
+
while index < len(line) and line[index] != '"':
|
|
105
|
+
index += 1
|
|
106
|
+
if index >= len(line):
|
|
107
|
+
return False
|
|
108
|
+
elif ch == "(":
|
|
109
|
+
depth.paren += 1
|
|
110
|
+
elif ch == ")":
|
|
111
|
+
if depth.paren == 0:
|
|
112
|
+
return False
|
|
113
|
+
depth.paren -= 1
|
|
114
|
+
elif ch == "[":
|
|
115
|
+
depth.bracket += 1
|
|
116
|
+
elif ch == "]":
|
|
117
|
+
if depth.bracket == 0:
|
|
118
|
+
return False
|
|
119
|
+
depth.bracket -= 1
|
|
120
|
+
elif ch == "{":
|
|
121
|
+
depth.brace += 1
|
|
122
|
+
elif ch == "}":
|
|
123
|
+
if depth.brace == 0:
|
|
124
|
+
return False
|
|
125
|
+
depth.brace -= 1
|
|
126
|
+
index += 1
|
|
127
|
+
return True
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def simple_is_complete(code: str) -> str:
|
|
131
|
+
stack: list[str] = []
|
|
132
|
+
in_string = False
|
|
133
|
+
pairs = {
|
|
134
|
+
"(": ")",
|
|
135
|
+
"[": "]",
|
|
136
|
+
"{": "}",
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
for raw_line in code.splitlines():
|
|
140
|
+
stripped = raw_line.lstrip(" \t")
|
|
141
|
+
if stripped.startswith("/"):
|
|
142
|
+
continue
|
|
143
|
+
|
|
144
|
+
for ch in raw_line:
|
|
145
|
+
if ch == '"':
|
|
146
|
+
in_string = not in_string
|
|
147
|
+
continue
|
|
148
|
+
if in_string:
|
|
149
|
+
continue
|
|
150
|
+
if ch in "([{":
|
|
151
|
+
stack.append(ch)
|
|
152
|
+
continue
|
|
153
|
+
if ch in ")]}":
|
|
154
|
+
if not stack:
|
|
155
|
+
return "invalid"
|
|
156
|
+
opener = stack.pop()
|
|
157
|
+
if pairs[opener] != ch:
|
|
158
|
+
return "invalid"
|
|
159
|
+
|
|
160
|
+
if in_string or stack:
|
|
161
|
+
return "incomplete"
|
|
162
|
+
return "complete"
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
import shutil
|
|
7
|
+
import sys
|
|
8
|
+
import tempfile
|
|
9
|
+
from importlib import resources
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Any, Optional, Sequence
|
|
12
|
+
|
|
13
|
+
from jupyter_client.kernelspec import KernelSpecManager
|
|
14
|
+
|
|
15
|
+
from .binding import (
|
|
16
|
+
DEVICE_ENV_VAR,
|
|
17
|
+
LIB_ENV_VAR,
|
|
18
|
+
build_bridge,
|
|
19
|
+
experiment_root,
|
|
20
|
+
find_library_path,
|
|
21
|
+
v2_python_src,
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
DEFAULT_KERNEL_NAME = "kiwi"
|
|
25
|
+
DEFAULT_DISPLAY_NAME = "Kiwi"
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def default_logo_candidates() -> list[Path]:
|
|
29
|
+
return [
|
|
30
|
+
experiment_root() / "src" / "kiwi_array_jupyter_kernel" / "assets" / "kernel-logo.png",
|
|
31
|
+
]
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def find_logo_path(path: Optional[str | Path] = None) -> Optional[Path]:
|
|
35
|
+
if path is not None:
|
|
36
|
+
candidate = Path(path).expanduser().resolve()
|
|
37
|
+
if candidate.is_file():
|
|
38
|
+
return candidate
|
|
39
|
+
raise FileNotFoundError(f"Kiwi kernel logo not found at {candidate}")
|
|
40
|
+
|
|
41
|
+
for candidate in default_logo_candidates():
|
|
42
|
+
if candidate.is_file():
|
|
43
|
+
return candidate
|
|
44
|
+
return None
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def write_kernel_logos(dst_dir: Path, logo_path: Optional[str | Path] = None) -> None:
|
|
48
|
+
resolved = find_logo_path(logo_path)
|
|
49
|
+
if resolved is not None:
|
|
50
|
+
for name in ("logo-32x32.png", "logo-64x64.png"):
|
|
51
|
+
shutil.copy2(resolved, dst_dir / name)
|
|
52
|
+
return
|
|
53
|
+
|
|
54
|
+
resource = resources.files("kiwi_array_jupyter_kernel") / "assets" / "kernel-logo.png"
|
|
55
|
+
with resources.as_file(resource) as resource_path:
|
|
56
|
+
for name in ("logo-32x32.png", "logo-64x64.png"):
|
|
57
|
+
shutil.copy2(resource_path, dst_dir / name)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def source_python_paths() -> list[Path]:
|
|
61
|
+
candidates = [
|
|
62
|
+
experiment_root() / "src",
|
|
63
|
+
v2_python_src(),
|
|
64
|
+
]
|
|
65
|
+
return [path for path in candidates if path.exists()]
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def build_kernel_spec(
|
|
69
|
+
display_name: str = DEFAULT_DISPLAY_NAME,
|
|
70
|
+
device: str = "auto",
|
|
71
|
+
python_executable: Optional[str] = None,
|
|
72
|
+
library_path: Optional[str] = None,
|
|
73
|
+
python_path: Optional[Sequence[str | Path]] = None,
|
|
74
|
+
) -> dict[str, Any]:
|
|
75
|
+
python_cmd = python_executable or sys.executable
|
|
76
|
+
env: dict[str, str] = {
|
|
77
|
+
DEVICE_ENV_VAR: device,
|
|
78
|
+
}
|
|
79
|
+
if python_path:
|
|
80
|
+
paths = [str(Path(path)) for path in python_path]
|
|
81
|
+
existing_python_path = os.environ.get("PYTHONPATH")
|
|
82
|
+
env["PYTHONPATH"] = (
|
|
83
|
+
os.pathsep.join([*paths, existing_python_path])
|
|
84
|
+
if existing_python_path
|
|
85
|
+
else os.pathsep.join(paths)
|
|
86
|
+
)
|
|
87
|
+
if library_path is not None:
|
|
88
|
+
env[LIB_ENV_VAR] = library_path
|
|
89
|
+
return {
|
|
90
|
+
"argv": [python_cmd, "-m", "kiwi_array_jupyter_kernel", "-f", "{connection_file}"],
|
|
91
|
+
"display_name": display_name,
|
|
92
|
+
"language": "kiwi",
|
|
93
|
+
"env": env,
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def install_kernel(
|
|
98
|
+
name: str = DEFAULT_KERNEL_NAME,
|
|
99
|
+
display_name: str = DEFAULT_DISPLAY_NAME,
|
|
100
|
+
device: str = "auto",
|
|
101
|
+
user: bool = True,
|
|
102
|
+
prefix: Optional[str] = None,
|
|
103
|
+
skip_build: bool = False,
|
|
104
|
+
optimize: str = "ReleaseFast",
|
|
105
|
+
) -> str:
|
|
106
|
+
if not skip_build:
|
|
107
|
+
try:
|
|
108
|
+
find_library_path()
|
|
109
|
+
except FileNotFoundError:
|
|
110
|
+
build_bridge(optimize=optimize)
|
|
111
|
+
|
|
112
|
+
library_path = str(find_library_path())
|
|
113
|
+
spec = build_kernel_spec(
|
|
114
|
+
display_name=display_name,
|
|
115
|
+
device=device,
|
|
116
|
+
library_path=library_path,
|
|
117
|
+
python_path=source_python_paths(),
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
with tempfile.TemporaryDirectory(prefix="kiwi-kernelspec-") as tmpdir:
|
|
121
|
+
tmp_path = Path(tmpdir)
|
|
122
|
+
(tmp_path / "kernel.json").write_text(json.dumps(spec, indent=2) + "\n")
|
|
123
|
+
write_kernel_logos(tmp_path)
|
|
124
|
+
manager = KernelSpecManager()
|
|
125
|
+
return manager.install_kernel_spec(
|
|
126
|
+
str(tmp_path),
|
|
127
|
+
kernel_name=name,
|
|
128
|
+
user=user,
|
|
129
|
+
prefix=prefix,
|
|
130
|
+
)
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def parse_args(argv: Optional[list[str]] = None) -> argparse.Namespace:
|
|
134
|
+
parser = argparse.ArgumentParser(description="Install the Kiwi Jupyter kernel spec (kiwi-zig-v2).")
|
|
135
|
+
parser.add_argument("--name", default=DEFAULT_KERNEL_NAME)
|
|
136
|
+
parser.add_argument("--display-name", default=DEFAULT_DISPLAY_NAME)
|
|
137
|
+
parser.add_argument("--device", default="auto", choices=("auto", "cpu", "gpu"))
|
|
138
|
+
parser.add_argument("--prefix", default=None)
|
|
139
|
+
parser.add_argument("--sys-prefix", action="store_true")
|
|
140
|
+
parser.add_argument("--skip-build", action="store_true")
|
|
141
|
+
parser.add_argument("--optimize", default="ReleaseFast")
|
|
142
|
+
return parser.parse_args(argv)
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def main(argv: Optional[list[str]] = None) -> int:
|
|
146
|
+
args = parse_args(argv)
|
|
147
|
+
prefix = sys.prefix if args.sys_prefix else args.prefix
|
|
148
|
+
user = prefix is None
|
|
149
|
+
destination = install_kernel(
|
|
150
|
+
name=args.name,
|
|
151
|
+
display_name=args.display_name,
|
|
152
|
+
device=args.device,
|
|
153
|
+
user=user,
|
|
154
|
+
prefix=prefix,
|
|
155
|
+
skip_build=args.skip_build,
|
|
156
|
+
optimize=args.optimize,
|
|
157
|
+
)
|
|
158
|
+
print(f"Installed Kiwi Jupyter kernel to {destination}")
|
|
159
|
+
return 0
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
if __name__ == "__main__":
|
|
163
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
import re
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from ipykernel.kernelbase import Kernel
|
|
9
|
+
|
|
10
|
+
from . import __version__
|
|
11
|
+
from .binding import DEVICE_ENV_VAR, LIB_ENV_VAR, KiwiSession
|
|
12
|
+
from .execution import CellExecutionError, CellOutput, execute_cell, simple_is_complete
|
|
13
|
+
|
|
14
|
+
SYMBOL_DOCS = {
|
|
15
|
+
"exp": "exp[x] applies the elementwise exponential.",
|
|
16
|
+
"fromcsv": "fromcsv[s] parses a CSV string into a typed Kiwi table.",
|
|
17
|
+
"log": "log[x] applies the elementwise natural logarithm.",
|
|
18
|
+
"matmul": "matmul[a;b] multiplies two 2D float matrices (Accelerate/OpenBLAS/Metal/CUDA).",
|
|
19
|
+
"sin": "sin[x] applies the elementwise sine.",
|
|
20
|
+
"sqrt": "sqrt[x] applies the elementwise square root.",
|
|
21
|
+
"tanh": "tanh[x] applies the elementwise hyperbolic tangent.",
|
|
22
|
+
}
|
|
23
|
+
COMPLETION_WORDS = tuple(SYMBOL_DOCS)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class KiwiKernel(Kernel):
|
|
27
|
+
implementation = "kiwi-array-jupyter"
|
|
28
|
+
implementation_version = __version__
|
|
29
|
+
language = "kiwi"
|
|
30
|
+
language_version = "0.2"
|
|
31
|
+
banner = "Kiwi 0.2 kernel"
|
|
32
|
+
language_info = {
|
|
33
|
+
"name": "kiwi",
|
|
34
|
+
"mimetype": "text/x-kiwi",
|
|
35
|
+
"file_extension": ".k",
|
|
36
|
+
"pygments_lexer": "text",
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
def __init__(self, **kwargs: Any) -> None:
|
|
40
|
+
super().__init__(**kwargs)
|
|
41
|
+
device = os.environ.get(DEVICE_ENV_VAR, "auto")
|
|
42
|
+
library_path = os.environ.get(LIB_ENV_VAR)
|
|
43
|
+
self._session = KiwiSession(device=device, library_path=library_path)
|
|
44
|
+
|
|
45
|
+
def do_execute(
|
|
46
|
+
self,
|
|
47
|
+
code: str,
|
|
48
|
+
silent: bool,
|
|
49
|
+
store_history: bool = True,
|
|
50
|
+
user_expressions: Any = None,
|
|
51
|
+
allow_stdin: bool = False,
|
|
52
|
+
) -> dict[str, Any]:
|
|
53
|
+
del store_history, allow_stdin
|
|
54
|
+
try:
|
|
55
|
+
outputs = execute_cell(self._session, code)
|
|
56
|
+
except CellExecutionError as exc:
|
|
57
|
+
if not silent:
|
|
58
|
+
self.send_response(
|
|
59
|
+
self.iopub_socket,
|
|
60
|
+
"error",
|
|
61
|
+
{
|
|
62
|
+
"ename": "KiwiError",
|
|
63
|
+
"evalue": str(exc),
|
|
64
|
+
"traceback": [],
|
|
65
|
+
},
|
|
66
|
+
)
|
|
67
|
+
return {
|
|
68
|
+
"status": "error",
|
|
69
|
+
"ename": "KiwiError",
|
|
70
|
+
"evalue": str(exc),
|
|
71
|
+
"traceback": [],
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
if not silent:
|
|
75
|
+
for output in outputs[:-1]:
|
|
76
|
+
self.send_response(
|
|
77
|
+
self.iopub_socket,
|
|
78
|
+
"stream",
|
|
79
|
+
{
|
|
80
|
+
"name": "stdout",
|
|
81
|
+
"text": output.text + "\n",
|
|
82
|
+
},
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
if outputs:
|
|
86
|
+
last = outputs[-1]
|
|
87
|
+
self.send_response(
|
|
88
|
+
self.iopub_socket,
|
|
89
|
+
"execute_result",
|
|
90
|
+
{
|
|
91
|
+
"execution_count": self.execution_count,
|
|
92
|
+
"data": _display_data_for_output(last),
|
|
93
|
+
"metadata": {},
|
|
94
|
+
},
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
return {
|
|
98
|
+
"status": "ok",
|
|
99
|
+
"execution_count": self.execution_count,
|
|
100
|
+
"payload": [],
|
|
101
|
+
"user_expressions": {},
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
def do_complete(self, code: str, cursor_pos: int) -> dict[str, Any]:
|
|
105
|
+
prefix = _completion_prefix(code[:cursor_pos])
|
|
106
|
+
matches = [word for word in COMPLETION_WORDS if prefix and word.startswith(prefix)]
|
|
107
|
+
return {
|
|
108
|
+
"matches": matches,
|
|
109
|
+
"cursor_start": cursor_pos - len(prefix),
|
|
110
|
+
"cursor_end": cursor_pos,
|
|
111
|
+
"metadata": {},
|
|
112
|
+
"status": "ok",
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
def do_inspect(
|
|
116
|
+
self,
|
|
117
|
+
code: str,
|
|
118
|
+
cursor_pos: int,
|
|
119
|
+
detail_level: int = 0,
|
|
120
|
+
omit_sections: Any = (),
|
|
121
|
+
) -> dict[str, Any]:
|
|
122
|
+
del detail_level, omit_sections
|
|
123
|
+
symbol = _symbol_at_cursor(code, cursor_pos)
|
|
124
|
+
if symbol is None:
|
|
125
|
+
return {
|
|
126
|
+
"status": "ok",
|
|
127
|
+
"found": False,
|
|
128
|
+
"data": {},
|
|
129
|
+
"metadata": {},
|
|
130
|
+
}
|
|
131
|
+
doc = SYMBOL_DOCS.get(symbol)
|
|
132
|
+
if doc is None:
|
|
133
|
+
return {
|
|
134
|
+
"status": "ok",
|
|
135
|
+
"found": False,
|
|
136
|
+
"data": {},
|
|
137
|
+
"metadata": {},
|
|
138
|
+
}
|
|
139
|
+
return {
|
|
140
|
+
"status": "ok",
|
|
141
|
+
"found": True,
|
|
142
|
+
"data": {"text/plain": doc},
|
|
143
|
+
"metadata": {},
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
def do_is_complete(self, code: str) -> dict[str, Any]:
|
|
147
|
+
status = simple_is_complete(code)
|
|
148
|
+
reply = {"status": status}
|
|
149
|
+
if status == "incomplete":
|
|
150
|
+
reply["indent"] = " "
|
|
151
|
+
return reply
|
|
152
|
+
|
|
153
|
+
def do_shutdown(self, restart: bool) -> dict[str, Any]:
|
|
154
|
+
self._session.close()
|
|
155
|
+
return {"status": "ok", "restart": restart}
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _completion_prefix(code: str) -> str:
|
|
159
|
+
match = re.search(r"[A-Za-z_][A-Za-z0-9_]*$", code)
|
|
160
|
+
if match is None:
|
|
161
|
+
return ""
|
|
162
|
+
return match.group(0)
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _symbol_at_cursor(code: str, cursor_pos: int) -> str | None:
|
|
166
|
+
for match in re.finditer(r"[A-Za-z_][A-Za-z0-9_]*", code):
|
|
167
|
+
if match.start() <= cursor_pos <= match.end():
|
|
168
|
+
return match.group(0)
|
|
169
|
+
return None
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def _display_data_for_output(output: CellOutput) -> dict[str, Any]:
|
|
173
|
+
data: dict[str, Any] = {"text/plain": output.text}
|
|
174
|
+
if output.display_mime is None or output.display_data is None:
|
|
175
|
+
return data
|
|
176
|
+
try:
|
|
177
|
+
data[output.display_mime] = json.loads(output.display_data)
|
|
178
|
+
except json.JSONDecodeError:
|
|
179
|
+
pass
|
|
180
|
+
return data
|
|
@@ -0,0 +1,399 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
import sys
|
|
6
|
+
import uuid
|
|
7
|
+
|
|
8
|
+
from jupyter_client import KernelManager
|
|
9
|
+
import pytest
|
|
10
|
+
|
|
11
|
+
JUPYTER_ROOT = Path(__file__).resolve().parents[1]
|
|
12
|
+
WORKSPACE_ROOT = JUPYTER_ROOT.parents[1]
|
|
13
|
+
V2_ROOT = WORKSPACE_ROOT / "implementations" / "kiwi-zig-v2"
|
|
14
|
+
PACKAGE_SRC = JUPYTER_ROOT / "src"
|
|
15
|
+
V2_PYTHON_SRC = V2_ROOT / "python"
|
|
16
|
+
for src in (PACKAGE_SRC, V2_PYTHON_SRC):
|
|
17
|
+
if str(src) not in sys.path:
|
|
18
|
+
sys.path.insert(0, str(src))
|
|
19
|
+
|
|
20
|
+
from kiwi_array_jupyter_kernel.binding import (
|
|
21
|
+
LIB_ENV_VAR,
|
|
22
|
+
KiwiEvalResult,
|
|
23
|
+
KiwiSession,
|
|
24
|
+
experiment_root,
|
|
25
|
+
find_library_path,
|
|
26
|
+
platform_library_name,
|
|
27
|
+
v2_library_path,
|
|
28
|
+
)
|
|
29
|
+
from kiwi_array_jupyter_kernel.execution import (
|
|
30
|
+
CellExecutionError,
|
|
31
|
+
CellOutput,
|
|
32
|
+
execute_cell,
|
|
33
|
+
iter_executable_lines,
|
|
34
|
+
iter_executable_statements,
|
|
35
|
+
simple_is_complete,
|
|
36
|
+
)
|
|
37
|
+
from kiwi_array_jupyter_kernel.install import (
|
|
38
|
+
build_bridge,
|
|
39
|
+
build_kernel_spec,
|
|
40
|
+
find_logo_path,
|
|
41
|
+
install_kernel,
|
|
42
|
+
write_kernel_logos,
|
|
43
|
+
)
|
|
44
|
+
from kiwi_array_jupyter_kernel.kernel import _display_data_for_output
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class FakeSession:
|
|
48
|
+
def __init__(self, mapping):
|
|
49
|
+
self.mapping = mapping
|
|
50
|
+
self.calls = []
|
|
51
|
+
|
|
52
|
+
def eval(self, source: str) -> KiwiEvalResult:
|
|
53
|
+
self.calls.append(source)
|
|
54
|
+
return self.mapping[source]
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def test_iter_executable_lines_skips_blank_lines_and_full_line_comments():
|
|
58
|
+
code = "\n/ comment\na:1 2 3 / inline comment\n / spaced comment\n+/a\r\n"
|
|
59
|
+
assert list(iter_executable_lines(code)) == [(3, "a:1 2 3"), (5, "+/a")]
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def test_iter_executable_statements_groups_balanced_multiline_source():
|
|
63
|
+
code = "\n/ comment\nf:{\n x+1 / inline comment with }\n}\n\nf 3\n"
|
|
64
|
+
assert list(iter_executable_statements(code)) == [
|
|
65
|
+
(3, "f:{\nx+1\n}"),
|
|
66
|
+
(7, "f 3"),
|
|
67
|
+
]
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def test_execute_cell_returns_echoed_outputs_in_order():
|
|
71
|
+
session = FakeSession(
|
|
72
|
+
{
|
|
73
|
+
"a:1 2 3": KiwiEvalResult(status="ok", echoed=False, text=None),
|
|
74
|
+
"+/a": KiwiEvalResult(status="ok", echoed=True, text="6"),
|
|
75
|
+
"*/a": KiwiEvalResult(status="ok", echoed=True, text="6"),
|
|
76
|
+
}
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
outputs = execute_cell(session, "a:1 2 3\n+/a\n*/a\n")
|
|
80
|
+
|
|
81
|
+
assert session.calls == ["a:1 2 3", "+/a", "*/a"]
|
|
82
|
+
assert [(item.line_no, item.text) for item in outputs] == [(2, "6"), (3, "6")]
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def test_execute_cell_sends_multiline_statements_as_one_eval():
|
|
86
|
+
session = FakeSession(
|
|
87
|
+
{
|
|
88
|
+
"f:{\nx+1\n}": KiwiEvalResult(status="ok", echoed=False, text=None),
|
|
89
|
+
"f 3": KiwiEvalResult(status="ok", echoed=True, text="4"),
|
|
90
|
+
}
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
outputs = execute_cell(session, "f:{\n x+1\n}\nf 3\n")
|
|
94
|
+
|
|
95
|
+
assert session.calls == ["f:{\nx+1\n}", "f 3"]
|
|
96
|
+
assert [(item.line_no, item.text) for item in outputs] == [(4, "4")]
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def test_execute_cell_strips_inline_comments_before_eval():
|
|
100
|
+
session = FakeSession(
|
|
101
|
+
{
|
|
102
|
+
"f:{\nx+1\n}": KiwiEvalResult(status="ok", echoed=False, text=None),
|
|
103
|
+
"f 3": KiwiEvalResult(status="ok", echoed=True, text="4"),
|
|
104
|
+
}
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
outputs = execute_cell(session, "f:{\n x+1 / inline comment\n}\nf 3 / call\n")
|
|
108
|
+
|
|
109
|
+
assert session.calls == ["f:{\nx+1\n}", "f 3"]
|
|
110
|
+
assert [(item.line_no, item.text) for item in outputs] == [(4, "4")]
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def test_execute_cell_reports_multiline_statement_start_line_on_error():
|
|
114
|
+
session = FakeSession(
|
|
115
|
+
{
|
|
116
|
+
"f:{\nx+1\n}": KiwiEvalResult(status="parse", echoed=False, text=None),
|
|
117
|
+
}
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
with pytest.raises(CellExecutionError) as exc_info:
|
|
121
|
+
execute_cell(session, "\n\nf:{\n x+1\n}\n")
|
|
122
|
+
|
|
123
|
+
assert exc_info.value.line_no == 3
|
|
124
|
+
assert exc_info.value.status == "parse"
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def test_execute_cell_preserves_display_bundle():
|
|
128
|
+
display_json = '{"$schema":"https://vega.github.io/schema/vega-lite/v5.json"}'
|
|
129
|
+
session = FakeSession(
|
|
130
|
+
{
|
|
131
|
+
"plot": KiwiEvalResult(
|
|
132
|
+
status="ok",
|
|
133
|
+
echoed=True,
|
|
134
|
+
text=f'"{display_json}"',
|
|
135
|
+
display_mime="application/vnd.vegalite.v5+json",
|
|
136
|
+
display_data=display_json,
|
|
137
|
+
),
|
|
138
|
+
}
|
|
139
|
+
)
|
|
140
|
+
|
|
141
|
+
outputs = execute_cell(session, "plot")
|
|
142
|
+
|
|
143
|
+
assert outputs == [
|
|
144
|
+
CellOutput(
|
|
145
|
+
line_no=1,
|
|
146
|
+
text=f'"{display_json}"',
|
|
147
|
+
display_mime="application/vnd.vegalite.v5+json",
|
|
148
|
+
display_data=display_json,
|
|
149
|
+
)
|
|
150
|
+
]
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def test_display_data_for_output_parses_json_mime_payload():
|
|
154
|
+
output = CellOutput(
|
|
155
|
+
line_no=1,
|
|
156
|
+
text='"{}"',
|
|
157
|
+
display_mime="application/vnd.vegalite.v5+json",
|
|
158
|
+
display_data='{"$schema":"https://vega.github.io/schema/vega-lite/v5.json"}',
|
|
159
|
+
)
|
|
160
|
+
|
|
161
|
+
data = _display_data_for_output(output)
|
|
162
|
+
|
|
163
|
+
assert data["text/plain"] == '"{}"'
|
|
164
|
+
assert data["application/vnd.vegalite.v5+json"]["$schema"].endswith("/vega-lite/v5.json")
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def test_execute_cell_reports_error_line_number():
|
|
168
|
+
session = FakeSession(
|
|
169
|
+
{
|
|
170
|
+
"a:5": KiwiEvalResult(status="ok", echoed=False, text=None),
|
|
171
|
+
"a+b": KiwiEvalResult(status="name", echoed=False, text=None),
|
|
172
|
+
}
|
|
173
|
+
)
|
|
174
|
+
|
|
175
|
+
with pytest.raises(CellExecutionError) as exc_info:
|
|
176
|
+
execute_cell(session, "a:5\na+b\n")
|
|
177
|
+
|
|
178
|
+
assert exc_info.value.line_no == 2
|
|
179
|
+
assert exc_info.value.status == "name"
|
|
180
|
+
assert str(exc_info.value) == "line 2: !name"
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def test_simple_is_complete_tracks_basic_delimiter_balance():
|
|
184
|
+
assert simple_is_complete("matmul[a;b]") == "complete"
|
|
185
|
+
assert simple_is_complete("matmul[a;b") == "incomplete"
|
|
186
|
+
assert simple_is_complete("{[x;y]\n x+y") == "incomplete"
|
|
187
|
+
assert simple_is_complete('/ comment only\n"abc') == "incomplete"
|
|
188
|
+
assert simple_is_complete(")]") == "invalid"
|
|
189
|
+
assert simple_is_complete("{]") == "invalid"
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def test_build_kernel_spec_uses_clean_v2_env(tmp_path, monkeypatch):
|
|
193
|
+
monkeypatch.delenv("PYTHONPATH", raising=False)
|
|
194
|
+
library_path = tmp_path / platform_library_name("kiwi_bridge")
|
|
195
|
+
spec = build_kernel_spec(
|
|
196
|
+
display_name="Kiwi v2",
|
|
197
|
+
device="cpu",
|
|
198
|
+
python_executable="python",
|
|
199
|
+
library_path=str(library_path),
|
|
200
|
+
)
|
|
201
|
+
assert spec["argv"] == ["python", "-m", "kiwi_array_jupyter_kernel", "-f", "{connection_file}"]
|
|
202
|
+
assert spec["env"] == {
|
|
203
|
+
"KIWI_JUPYTER_DEVICE": "cpu",
|
|
204
|
+
"KIWI_BRIDGE_LIB": str(library_path),
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def test_v2_bridge_executes_cells_vegalite_and_typed_arrays():
|
|
209
|
+
import ctypes
|
|
210
|
+
|
|
211
|
+
lib = v2_library_path()
|
|
212
|
+
if not lib.exists():
|
|
213
|
+
build_bridge()
|
|
214
|
+
|
|
215
|
+
with KiwiSession(library_path=lib) as session:
|
|
216
|
+
outs = execute_cell(session, "a:1 2 3\n+/a\nf:{\n x+1 / inline comment\n}\nf 3")
|
|
217
|
+
assert [(o.line_no, o.text) for o in outs] == [(2, "6"), (6, "4")]
|
|
218
|
+
|
|
219
|
+
vl = (
|
|
220
|
+
"`j@(\"$schema\";\"data\";\"mark\";\"encoding\")!"
|
|
221
|
+
"(\"https://vega.github.io/schema/vega-lite/v5.json\";"
|
|
222
|
+
"(,\"values\")!(,+(`x`y!(1 2;3 4)));"
|
|
223
|
+
"`point;"
|
|
224
|
+
"`x`y!(`field`type!(\"x\";\"quantitative\");`field`type!(\"y\";\"quantitative\")))"
|
|
225
|
+
)
|
|
226
|
+
vl_outs = execute_cell(session, vl)
|
|
227
|
+
assert len(vl_outs) == 1
|
|
228
|
+
data = _display_data_for_output(vl_outs[0])
|
|
229
|
+
assert data["application/vnd.vegalite.v5+json"]["mark"] == "point"
|
|
230
|
+
assert data["application/vnd.vegalite.v5+json"]["data"]["values"] == [
|
|
231
|
+
{"x": 1, "y": 3},
|
|
232
|
+
{"x": 2, "y": 4},
|
|
233
|
+
]
|
|
234
|
+
|
|
235
|
+
# Test unified kiwi_set_array directly (no NumPy required in test venv)
|
|
236
|
+
f_arr = (ctypes.c_float * 3)(1.5, 2.5, 3.0)
|
|
237
|
+
f_dims = (ctypes.c_int64 * 1)(3)
|
|
238
|
+
assert session._lib.kiwi_set_array(session._handle, b"xf", 2, 4, ctypes.cast(f_arr, ctypes.c_void_p), f_dims, 1) == 0
|
|
239
|
+
assert float(session.eval("+/xf").text) == 7.0
|
|
240
|
+
assert session.eval("no_such_var").status == "name"
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def test_logo_helpers_find_current_kernel_icon_and_copy_kernel_assets(tmp_path):
|
|
244
|
+
logo_path = find_logo_path()
|
|
245
|
+
assert logo_path is not None
|
|
246
|
+
assert logo_path == JUPYTER_ROOT / "src" / "kiwi_array_jupyter_kernel" / "assets" / "kernel-logo.png"
|
|
247
|
+
|
|
248
|
+
write_kernel_logos(tmp_path)
|
|
249
|
+
|
|
250
|
+
assert (tmp_path / "logo-32x32.png").read_bytes() == logo_path.read_bytes()
|
|
251
|
+
assert (tmp_path / "logo-64x64.png").read_bytes() == logo_path.read_bytes()
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
@pytest.fixture(scope="session")
|
|
255
|
+
def installed_kernel_spec(tmp_path_factory):
|
|
256
|
+
build_bridge()
|
|
257
|
+
prefix = tmp_path_factory.mktemp("kiwi-jupyter-kernel")
|
|
258
|
+
name = f"kiwi_test_{uuid.uuid4().hex[:8]}"
|
|
259
|
+
location = Path(
|
|
260
|
+
install_kernel(
|
|
261
|
+
name=name,
|
|
262
|
+
prefix=str(prefix),
|
|
263
|
+
user=False,
|
|
264
|
+
skip_build=True,
|
|
265
|
+
)
|
|
266
|
+
)
|
|
267
|
+
return {
|
|
268
|
+
"name": name,
|
|
269
|
+
"jupyter_path": str(prefix / "share" / "jupyter"),
|
|
270
|
+
"kernel_json": location / "kernel.json",
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
@pytest.fixture
|
|
275
|
+
def kernel_client(installed_kernel_spec):
|
|
276
|
+
old_jupyter_path = os.environ.get("JUPYTER_PATH")
|
|
277
|
+
os.environ["JUPYTER_PATH"] = installed_kernel_spec["jupyter_path"]
|
|
278
|
+
|
|
279
|
+
km = KernelManager(kernel_name=installed_kernel_spec["name"])
|
|
280
|
+
km.start_kernel()
|
|
281
|
+
client = km.blocking_client()
|
|
282
|
+
client.start_channels()
|
|
283
|
+
client.wait_for_ready(timeout=30)
|
|
284
|
+
try:
|
|
285
|
+
yield client
|
|
286
|
+
finally:
|
|
287
|
+
client.stop_channels()
|
|
288
|
+
km.shutdown_kernel(now=True)
|
|
289
|
+
if old_jupyter_path is None:
|
|
290
|
+
os.environ.pop("JUPYTER_PATH", None)
|
|
291
|
+
else:
|
|
292
|
+
os.environ["JUPYTER_PATH"] = old_jupyter_path
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
def _shell_reply(client, msg_id: str):
|
|
296
|
+
while True:
|
|
297
|
+
reply = client.get_shell_msg(timeout=30)
|
|
298
|
+
if reply["parent_header"].get("msg_id") == msg_id:
|
|
299
|
+
return reply
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
def _iopub_messages(client, msg_id: str):
|
|
303
|
+
messages = []
|
|
304
|
+
while True:
|
|
305
|
+
message = client.get_iopub_msg(timeout=30)
|
|
306
|
+
if message["parent_header"].get("msg_id") != msg_id:
|
|
307
|
+
continue
|
|
308
|
+
messages.append(message)
|
|
309
|
+
if (
|
|
310
|
+
message["header"]["msg_type"] == "status"
|
|
311
|
+
and message["content"].get("execution_state") == "idle"
|
|
312
|
+
):
|
|
313
|
+
return messages
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
def test_install_kernel_writes_bridge_path_to_kernel_spec(installed_kernel_spec):
|
|
317
|
+
kernel_json = installed_kernel_spec["kernel_json"].read_text()
|
|
318
|
+
assert str(find_library_path()) in kernel_json
|
|
319
|
+
assert LIB_ENV_VAR in kernel_json
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
def test_install_kernel_writes_logo_assets(installed_kernel_spec):
|
|
323
|
+
kernel_dir = installed_kernel_spec["kernel_json"].parent
|
|
324
|
+
assert (kernel_dir / "logo-32x32.png").exists()
|
|
325
|
+
assert (kernel_dir / "logo-64x64.png").exists()
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def test_kernel_executes_cells_over_jupyter_protocol(kernel_client):
|
|
329
|
+
msg_id = kernel_client.execute("a:1 2 3\n+/a")
|
|
330
|
+
reply = _shell_reply(kernel_client, msg_id)
|
|
331
|
+
messages = _iopub_messages(kernel_client, msg_id)
|
|
332
|
+
|
|
333
|
+
assert reply["content"]["status"] == "ok"
|
|
334
|
+
results = [msg for msg in messages if msg["header"]["msg_type"] == "execute_result"]
|
|
335
|
+
assert len(results) == 1
|
|
336
|
+
assert results[0]["content"]["data"]["text/plain"] == "6"
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
def test_kernel_executes_multiline_definitions_over_jupyter_protocol(kernel_client):
|
|
340
|
+
msg_id = kernel_client.execute("f:{\n x+1 / inline comment\n}\nf 3 / call")
|
|
341
|
+
reply = _shell_reply(kernel_client, msg_id)
|
|
342
|
+
messages = _iopub_messages(kernel_client, msg_id)
|
|
343
|
+
|
|
344
|
+
assert reply["content"]["status"] == "ok"
|
|
345
|
+
results = [msg for msg in messages if msg["header"]["msg_type"] == "execute_result"]
|
|
346
|
+
assert len(results) == 1
|
|
347
|
+
assert results[0]["content"]["data"]["text/plain"] == "4"
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
def test_kernel_emits_vegalite_mime_over_jupyter_protocol(kernel_client):
|
|
351
|
+
code = (
|
|
352
|
+
"`j@(\"$schema\";\"data\";\"mark\";\"encoding\")!"
|
|
353
|
+
"(\"https://vega.github.io/schema/vega-lite/v5.json\";"
|
|
354
|
+
"(,\"values\")!(,+(`x`y!(1 2;3 4)));"
|
|
355
|
+
"`point;"
|
|
356
|
+
"`x`y!(`field`type!(\"x\";\"quantitative\");`field`type!(\"y\";\"quantitative\")))"
|
|
357
|
+
)
|
|
358
|
+
msg_id = kernel_client.execute(code)
|
|
359
|
+
reply = _shell_reply(kernel_client, msg_id)
|
|
360
|
+
messages = _iopub_messages(kernel_client, msg_id)
|
|
361
|
+
|
|
362
|
+
assert reply["content"]["status"] == "ok"
|
|
363
|
+
results = [msg for msg in messages if msg["header"]["msg_type"] == "execute_result"]
|
|
364
|
+
assert len(results) == 1
|
|
365
|
+
data = results[0]["content"]["data"]
|
|
366
|
+
assert "application/vnd.vegalite.v5+json" in data
|
|
367
|
+
assert data["application/vnd.vegalite.v5+json"]["mark"] == "point"
|
|
368
|
+
assert data["application/vnd.vegalite.v5+json"]["data"]["values"] == [
|
|
369
|
+
{"x": 1, "y": 3},
|
|
370
|
+
{"x": 2, "y": 4},
|
|
371
|
+
]
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
def test_kernel_reports_errors_over_jupyter_protocol(kernel_client):
|
|
375
|
+
msg_id = kernel_client.execute("a+b")
|
|
376
|
+
reply = _shell_reply(kernel_client, msg_id)
|
|
377
|
+
messages = _iopub_messages(kernel_client, msg_id)
|
|
378
|
+
|
|
379
|
+
assert reply["content"]["status"] == "error"
|
|
380
|
+
assert reply["content"]["evalue"] == "line 1: !name"
|
|
381
|
+
errors = [msg for msg in messages if msg["header"]["msg_type"] == "error"]
|
|
382
|
+
assert len(errors) == 1
|
|
383
|
+
assert errors[0]["content"]["evalue"] == "line 1: !name"
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
def test_kernel_inspect_returns_symbol_docs(kernel_client):
|
|
387
|
+
msg_id = kernel_client.inspect("matmul", cursor_pos=6)
|
|
388
|
+
reply = _shell_reply(kernel_client, msg_id)
|
|
389
|
+
|
|
390
|
+
assert reply["content"]["status"] == "ok"
|
|
391
|
+
assert reply["content"]["found"] is True
|
|
392
|
+
assert "matmul[a;b]" in reply["content"]["data"]["text/plain"]
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
def test_kernel_is_complete_marks_invalid_delimiters(kernel_client):
|
|
396
|
+
msg_id = kernel_client.is_complete(")]")
|
|
397
|
+
reply = _shell_reply(kernel_client, msg_id)
|
|
398
|
+
|
|
399
|
+
assert reply["content"]["status"] == "invalid"
|