Skip to content
This repository was archived by the owner on Sep 12, 2024. It is now read-only.

Commit 9485a5e

Browse files
authored
Submit notebook context to TextCortex (#14)
* Moved exec(code) into run_dialog() * wip, added back poetry * introduced icortex history variable * Introduced ICortexHistory, ServiceInteraction. Migrated setup to poetry * wip * Minor * Bumped version
1 parent 858cfb8 commit 9485a5e

19 files changed

+2162
-239
lines changed

.gitignore

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -135,8 +135,6 @@ cache
135135
*.zip
136136
cache.json
137137
Untitled*.ipynb
138-
pyproject.toml
139-
poetry.lock
140138
tmp/
141139
lab/
142140
*.csv

icortex/__init__.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
11
from icortex.kernel import ICortexKernel, print_help, get_icortex_kernel
2-
from icortex.cli import set_icortex_service, eval_cli
3-
from icortex.exec import eval_prompt
2+
3+
# from icortex.cli import set_icortex_service, eval_cli
44
import icortex.services
5+
import importlib.metadata
6+
7+
__version__ = importlib.metadata.version("icortex")

icortex/cli.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22
import shlex
33
import sys
44
import argparse
5-
from icortex.kernel import get_icortex_kernel
65
from jupyter_console.app import ZMQTerminalIPythonApp
76
from icortex.services import get_available_services
87
from icortex.defaults import DEFAULT_ICORTEX_CONFIG_PATH
@@ -150,14 +149,14 @@ def get_parser(prog=None):
150149
return parser, parser_service
151150

152151

153-
def set_icortex_service(config_path=DEFAULT_ICORTEX_CONFIG_PATH):
154-
kernel = get_icortex_kernel()
155-
if kernel is not None:
156-
return ICortexConfig(DEFAULT_ICORTEX_CONFIG_PATH).set_service()
157-
return False
152+
# def set_icortex_service(kernel, config_path=DEFAULT_ICORTEX_CONFIG_PATH):
158153

154+
# if kernel is not None:
155+
# return ICortexConfig(DEFAULT_ICORTEX_CONFIG_PATH).set_service()
156+
# return False
159157

160-
def main(argv=None, prog=None):
158+
159+
def main(argv=None, prog=None, kernel=None):
161160
if argv is None:
162161
argv = sys.argv[1:]
163162

@@ -195,6 +194,7 @@ def main(argv=None, prog=None):
195194
elif args.command == "help":
196195
parser.print_help()
197196
elif args.command == "shell" or args.command is None:
197+
from icortex.kernel import get_icortex_kernel
198198
kernel = get_icortex_kernel()
199199
if kernel is None:
200200
ZMQTerminalICortexApp.launch_instance()

icortex/config.py

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,17 @@
33

44
from icortex.services import get_available_services, get_service
55
from icortex.helper import yes_no_input, prompt_input
6-
from icortex.kernel import get_icortex_kernel
76
from icortex.services.service_base import ServiceVariable
87

98

109
class ICortexConfig:
1110
def __init__(self, path: str):
1211
self.path = path
1312
self.read_config()
13+
self.kernel = None
14+
15+
def set_kernel(self, kernel):
16+
self.kernel = kernel
1417

1518
def get_service_name(self):
1619
if "service" in self.dict:
@@ -45,8 +48,8 @@ def set_service_var(self, var_name: str, var_value) -> bool:
4548
success = self.write_config()
4649
if success:
4750
print(f"Set variable {var_name} to {cast_value}.")
48-
kernel = get_icortex_kernel()
49-
if kernel is not None:
51+
# kernel = get_icortex_kernel()
52+
if self.kernel is not None:
5053
self.set_service()
5154
return True
5255
else:
@@ -73,17 +76,17 @@ def set_service_config(self, service_name: str, hard_init=False) -> bool:
7376
success = self.write_config()
7477
if success:
7578
print(f"Set service to {service_name} successfully.")
76-
kernel = get_icortex_kernel()
77-
if kernel is not None:
79+
# kernel = get_icortex_kernel()
80+
if self.kernel is not None:
7881
self.set_service()
7982
return True
8083
else:
8184
raise Exception("Could not write configuration file")
8285

8386
def set_service(self):
8487
# TODO: pass the --config flag from icortex somehow
85-
kernel = get_icortex_kernel()
86-
if kernel is None:
88+
# kernel = get_icortex_kernel()
89+
if self.kernel is None:
8790
return False
8891

8992
if not self.dict:
@@ -102,7 +105,7 @@ def set_service(self):
102105
service_config = self.dict[service_name]
103106
service_class = get_service(service_name)
104107

105-
kernel.set_service(service_class(service_config))
108+
self.kernel.set_service(service_class(service_config))
106109
return True
107110

108111
def ask_which_service(self) -> str:

icortex/context.py

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
import typing as t
2+
import importlib.metadata
3+
from copy import deepcopy
4+
import platform
5+
from icortex.defaults import DEFAULT_HISTORY_VAR
6+
7+
icortex_version = importlib.metadata.version("icortex")
8+
9+
INITIAL_HISTORY_VAL = {
10+
"metadata": {
11+
"kernelspec": {
12+
"display_name": "ICortex (Python 3)",
13+
"language": "icortex",
14+
"name": "icortex",
15+
},
16+
"language_info": {
17+
"pygments_lexer": "icortex",
18+
# "codemirror_mode": {"name": "ipython", "version": 3},
19+
"file_extension": ".icx",
20+
"mimetype": "text/x-icortex",
21+
"name": "icortex",
22+
# "nbconvert_exporter": "python",
23+
"pygments_lexer": "icortex",
24+
"version": icortex_version,
25+
"python_version": platform.python_version(),
26+
},
27+
},
28+
"nbformat": 4,
29+
"nbformat_minor": 5,
30+
"cells": [],
31+
}
32+
33+
34+
class ICortexHistory:
35+
"""Interface to construct a history variable in globals for storing
36+
notebook context.
37+
The constructed dict maps to JSON, and the schema is compatible
38+
with the Jupyter notebook format:
39+
https://nbformat.readthedocs.io/en/latest/format_description.html"""
40+
41+
def __init__(self, scope: t.Dict[str, t.Any]):
42+
self.scope = scope
43+
self._check_init()
44+
45+
def _check_init(self):
46+
if DEFAULT_HISTORY_VAR not in self.scope:
47+
self.scope[DEFAULT_HISTORY_VAR] = deepcopy(INITIAL_HISTORY_VAL)
48+
49+
self._dict = self.scope[DEFAULT_HISTORY_VAR]
50+
51+
def get_dict(self):
52+
return deepcopy(self._dict)
53+
54+
def add_code(self, code: str, outputs: t.List[t.Any]):
55+
self._check_init()
56+
57+
ret = {
58+
"cell_type": "code",
59+
"metadata": {},
60+
"source": code,
61+
"outputs": outputs,
62+
}
63+
64+
self._dict["cells"].append(ret)
65+
return ret
66+
67+
def add_prompt(
68+
self,
69+
prompt: str,
70+
outputs: t.List[t.Any],
71+
service_interaction: t.Dict[str, t.Any],
72+
):
73+
self._check_init()
74+
75+
ret = {
76+
"cell_type": "code",
77+
"metadata": {
78+
"service": service_interaction,
79+
},
80+
"source": prompt,
81+
"outputs": outputs,
82+
}
83+
84+
self._dict["cells"].append(ret)
85+
return ret

icortex/defaults.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
1-
21
# Default parameters
32
DEFAULT_ICORTEX_CONFIG_PATH = "icortex.toml"
43
DEFAULT_CACHE_PATH = "cache.json"
54
DEFAULT_REGENERATE = False
65
DEFAULT_AUTO_INSTALL_PACKAGES = False
6+
DEFAULT_AUTO_EXECUTE = False
77
DEFAULT_QUIET = False
88
DEFAULT_SERVICE = "textcortex"
9+
DEFAULT_HISTORY_VAR = "_icortex_history"

icortex/exec.py

Lines changed: 0 additions & 95 deletions
This file was deleted.

icortex/helper.py

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,33 @@
1-
def unescape(s):
1+
from pygments import highlight
2+
from pygments.formatters import Terminal256Formatter
3+
from pygments.lexers import PythonLexer
4+
5+
6+
def unescape(s) -> str:
27
return s.encode("utf-8").decode("unicode_escape")
38

49

5-
def is_prompt(input: str):
10+
def is_prompt(input: str) -> bool:
611
return input.strip()[0] == "/"
712

813

9-
def is_cli(input: str):
14+
def is_cli(input: str) -> bool:
1015
return input.strip()[:2] == "//"
1116

1217

13-
def escape_quotes(s: str):
18+
def escape_quotes(s: str) -> str:
1419
return s.replace('"', r"\"").replace("'", r"\'")
1520

1621

17-
def extract_prompt(input: str):
22+
def extract_prompt(input: str) -> str:
1823
return input.strip()[1:].strip()
1924

2025

21-
def extract_cli(input: str):
26+
def extract_cli(input: str) -> str:
2227
return input.strip()[2:].strip()
2328

2429

25-
def yes_no_input(message: str, default=True):
30+
def yes_no_input(message: str, default=True) -> bool:
2631
if default:
2732
message += " [Y/n]"
2833
else:
@@ -45,3 +50,7 @@ def prompt_input(message: str, type=str, default=None):
4550
return default
4651
else:
4752
return type(user_input)
53+
54+
55+
def highlight_python(code: str):
56+
return highlight(code, PythonLexer(), Terminal256Formatter())

0 commit comments

Comments
 (0)