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

Commit bff4058

Browse files
authored
Convenience functions, minor changes (#35)
* Updated README * Minor * Minor * Added pre-commit hook * Reformatted * Convenience functions for ICortextContext * Relaxed some deps * Bumped version
1 parent 487f69a commit bff4058

File tree

10 files changed

+196
-62
lines changed

10 files changed

+196
-62
lines changed

.gitignore

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -153,4 +153,6 @@ lite/jupyterlite-icortex/style/icortex.png
153153
lite/jupyterlite-icortex/LICENSE
154154
node_modules/
155155
*.tsbuildinfo
156-
*_backup
156+
*_backup
157+
misc/
158+
/icortex.toml

.pre-commit-config.yaml

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
repos:
2+
- repo: https://github.com/psf/black
3+
rev: 22.10.0
4+
hooks:
5+
- id: black
6+
# It is recommended to specify the latest version of Python
7+
# supported by your project here, or alternatively use
8+
# pre-commit's default_language_version, see
9+
# https://pre-commit.com/#top_level-default_language_version
10+
language_version: python3.10

icortex/context.py

Lines changed: 39 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -284,11 +284,14 @@ def from_file(path: str, scope: t.Dict[str, t.Any] = None):
284284
raise FileNotFoundError(f"File {path} does not exist")
285285

286286
with open(path, "r") as f:
287-
dict_ = json.load(f)
287+
context_dict = json.load(f)
288288

289+
return ICortexContext.from_dict(context_dict, scope)
290+
291+
def from_dict(context_dict: t.Dict[str, t.Any], scope: t.Dict[str, t.Any] = None):
289292
ret = ICortexContext(scope=scope)
290293

291-
for cell_dict in dict_["cells"]:
294+
for cell_dict in context_dict["cells"]:
292295
if cell_dict["metadata"]["source_type"] == "code":
293296
cell = CodeCell.from_dict(cell_dict)
294297
elif cell_dict["metadata"]["source_type"] == "var":
@@ -301,7 +304,7 @@ def from_file(path: str, scope: t.Dict[str, t.Any] = None):
301304
)
302305
ret._cells.append(cell)
303306

304-
ret._vars = [Var.from_dict(v) for v in dict_["metadata"]["variables"]]
307+
ret._vars = [Var.from_dict(v) for v in context_dict["metadata"]["variables"]]
305308

306309
return ret
307310

@@ -333,33 +336,32 @@ def run(self, notebook_args: t.List[str]):
333336
# Execute the returned code
334337
exec(code, scope)
335338

336-
def bake(self, dest_path: str, format=True):
337-
"""Bake the notebook to a Python script"""
339+
def get_code(self, argparsify=False):
340+
"""Aggregates the code for the notebook"""
338341

339-
# Warn if the extension is not .py
340-
if not dest_path.endswith(".py"):
341-
print(
342-
f"Warning: {dest_path} does not have the .py extension. "
343-
"It is recommended that you use the .py extension for "
344-
"frozen files."
345-
)
342+
output = ""
343+
if argparsify:
344+
# scope = locals()
345+
vars = self.vars
346346

347-
vars = self.vars
348-
scope = locals()
349-
350-
output = "import argparse\n\nparser = argparse.ArgumentParser()\n"
351-
for var in vars:
352-
output += f"parser.add_argument({var.arg!r}, type={var._type.__name__})\n"
353-
output += "args = parser.parse_args()\n\n"
347+
output += "import argparse\n\nparser = argparse.ArgumentParser()\n"
348+
for var in vars:
349+
output += (
350+
f"parser.add_argument({var.arg!r}, type={var._type.__name__})\n"
351+
)
352+
output += "args = parser.parse_args()\n\n"
354353

355354
for cell in self.iter_cells():
356355
if cell.success:
357356
if isinstance(cell, VarCell):
358357
var = cell.var
359358
# Change the value to that of the parsed argument
360359
# var.value = var._type(getattr(parsed_args, var.arg))
361-
code = f"{var.name} = args.{var.arg}\n\n"
362-
# code = var.get_code()
360+
if argparsify:
361+
code = f"{var.name} = args.{var.arg}\n\n"
362+
else:
363+
code = var.get_code()
364+
363365
elif isinstance(cell, CodeCell):
364366
if not is_magic(cell.get_code()):
365367
code = cell.get_code().rstrip() + "\n\n"
@@ -371,9 +373,25 @@ def bake(self, dest_path: str, format=True):
371373
# Execute the returned code
372374
output += code
373375

376+
return output
377+
378+
def bake(self, dest_path: str, format=True):
379+
"""Bake the notebook to a Python script"""
380+
381+
# Warn if the extension is not .py
382+
if not dest_path.endswith(".py"):
383+
print(
384+
f"Warning: {dest_path} does not have the .py extension. "
385+
"It is recommended that you use the .py extension for "
386+
"frozen files."
387+
)
388+
389+
output = self.get_code(argparsify=True)
390+
374391
# Run black over output
375392
if format:
376393
import black
394+
377395
try:
378396
output = black.format_str(output, mode=black.FileMode())
379397
except:

icortex/init.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,4 +12,4 @@
1212
ICortexShell._init_icortex_shell(__main__.get_ipython())
1313
# load_ipython_extension(get_ipython())
1414
else:
15-
raise Exception("IPython is not available, cannot initialize ICortex.")
15+
raise Exception("IPython is not available, cannot initialize ICortex.")

icortex/services/echo.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
from icortex.helper import escape_quotes
66
from icortex.services.generation_result import GenerationResult
77

8+
89
class EchoService(ServiceBase):
910
name = "echo"
1011
description = "Service used for testing"

icortex/services/service_base.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
from icortex.services.service_interaction import ServiceInteraction
1818
from icortex.parser import lex_prompt
1919

20+
2021
def is_str_repr(s: str):
2122
quotes = ["'", '"']
2223
return len(s) >= 2 and s[0] in quotes and s[-1] in quotes
@@ -159,9 +160,7 @@ def __init__(self, **kwargs: t.Dict[str, t.Any]):
159160
required=DEFAULT_AUTO_INSTALL_PACKAGES,
160161
help="Auto-install packages that are imported in the generated code but missing in the active Python environment.",
161162
)
162-
self.prompt_parser.usage = (
163-
"%%prompt your prompt goes here [-e] [-r] [-p] ..."
164-
)
163+
self.prompt_parser.usage = "%%prompt your prompt goes here [-e] [-r] [-p] ..."
165164

166165
self.prompt_parser.description = self.description
167166

icortex/services/textcortex.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,9 +26,9 @@
2626

2727
# Load alternative URI from the environment
2828
try:
29-
from dotenv import load_dotenv
29+
from dotenv import load_dotenv, find_dotenv
3030

31-
load_dotenv()
31+
load_dotenv(find_dotenv(usecwd=True))
3232
ICORTEX_ENDPOINT_URI = os.environ.get("ICORTEX_ENDPOINT_URI", ICORTEX_ENDPOINT_URI)
3333
except:
3434
pass

icortex/var.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
# "set": set,
1717
}
1818

19+
1920
class Var:
2021
def __init__(self, arg, name, value, type, description=None):
2122
self.arg = arg

0 commit comments

Comments
 (0)