Skip to content

Commit

Permalink
Enabled pre-commit. (#71)
Browse files Browse the repository at this point in the history
  • Loading branch information
JanPalasek authored Jul 8, 2023
1 parent 3d6ef4a commit a95c490
Show file tree
Hide file tree
Showing 27 changed files with 449 additions and 239 deletions.
2 changes: 1 addition & 1 deletion make.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ switch ($command) {
Activate-Venv -venv $venv
python -m pip install -r requirements-win.txt
python -m pip install -e .
# python -m pre_commit install
python -m pre_commit install
break
}
"compile" {
Expand Down
8 changes: 7 additions & 1 deletion src/pretty_jupyter/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
from pretty_jupyter.magics import JinjaMagics

# these imports are here for conf.json to work
from pretty_jupyter.preprocessors import TokenPreprocessor, TokenCleaningPreprocessor, NbMetadataPreprocessor, HtmlNbMetadataPreprocessor
from pretty_jupyter.preprocessors import (
HtmlNbMetadataPreprocessor,
NbMetadataPreprocessor,
TokenCleaningPreprocessor,
TokenPreprocessor,
)


def load_ipython_extension(ipython):
# The `ipython` argument is the currently active `InteractiveShell`
Expand Down
2 changes: 1 addition & 1 deletion src/pretty_jupyter/__main__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from pretty_jupyter.console import cli

if __name__ == "__main__":
cli()
cli()
34 changes: 19 additions & 15 deletions src/pretty_jupyter/console.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,20 @@
import os
import shutil
import sys
from pathlib import Path

import click
from traitlets.config import Config
from nbconvert.exporters import HTMLExporter, PDFExporter, LatexExporter
import pkg_resources
from pathlib import Path
from nbconvert.exporters import HTMLExporter, LatexExporter, PDFExporter
from traitlets.config import Config


@click.command()
@click.argument("out_path", type=click.Path())
def quickstart(out_path):
in_path = pkg_resources.resource_filename("pretty_jupyter", os.path.join("quickstart", "empty.ipynb"))
in_path = pkg_resources.resource_filename(
"pretty_jupyter", os.path.join("quickstart", "empty.ipynb")
)

with open(in_path, "r") as file_r, open(out_path, "w") as file_w:
in_text = file_r.read()
Expand All @@ -31,15 +34,13 @@ def nbconvert_dev(input, to, out, include_input):
if out is None:
out = os.path.join(os.path.dirname(input), f"{Path(input).stem}.{to}")

template_map = {
"html": "pj",
"pdf": "pj-pdf",
"latex": "pj-pdf"
}
template_map = {"html": "pj", "pdf": "pj-pdf", "latex": "pj-pdf"}

config = Config()
config = Config()
config.TemplateExporter.template_name = template_map[to]
config.TemplateExporter.extra_template_basedirs = [pkg_resources.resource_filename("pretty_jupyter", "templates")]
config.TemplateExporter.extra_template_basedirs = [
pkg_resources.resource_filename("pretty_jupyter", "templates")
]
config.TemplateExporter.exclude_input = not include_input

if to == "html":
Expand All @@ -54,7 +55,7 @@ def nbconvert_dev(input, to, out, include_input):
with open(input, "r", encoding="utf-8") as file:
res = exporter.from_file(file)
output_data = res[0]

# open file as bytes if the output data are bytes, otherwise opne it as a string
file = open(out, "wb") if isinstance(output_data, bytes) else open(out, "w", encoding="utf-8")
try:
Expand All @@ -71,16 +72,19 @@ def install_dev():
src_templates = ["pj", "pj-pdf", "pj-legacy"]

for src_template in src_templates:
src_folder = os.path.join(pkg_resources.resource_filename("pretty_jupyter", "templates"), src_template)
target_folder = os.path.join(sys.prefix, f"share/jupyter/nbconvert/templates/{src_template}")
src_folder = os.path.join(
pkg_resources.resource_filename("pretty_jupyter", "templates"), src_template
)
target_folder = os.path.join(
sys.prefix, f"share/jupyter/nbconvert/templates/{src_template}"
)

# for backward compatibility, otherwise copytree has dirs_exist_ok param
if os.path.exists(target_folder):
shutil.rmtree(target_folder)
shutil.copytree(src_folder, target_folder)



@click.version_option()
@click.group()
def cli():
Expand Down
4 changes: 2 additions & 2 deletions src/pretty_jupyter/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,11 +62,11 @@
"spacelab",
"superhero",
"united",
"yeti"
"yeti",
]
"""
List of all available local themes that can be specified in the `theme` html metadata.
"""

DEPRECATED_METADATA_MSG_FORMAT = "Specifying attributes '{attributes}' in this position to notebook metadata is deprecated since {version}. Please consider reading changes in this version.\n"
METADATA_ERROR_FORMAT = "An error occured when validating cell metadata. Error attributes in the metadata were the following:\n{error}"
METADATA_ERROR_FORMAT = "An error occured when validating cell metadata. Error attributes in the metadata were the following:\n{error}"
5 changes: 1 addition & 4 deletions src/pretty_jupyter/helpers/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
from pretty_jupyter.helpers.matplotlib import matplotlib_fig_to_html, matplotlib_fig_to_markdown

__all__ = [
matplotlib_fig_to_markdown.__name__,
matplotlib_fig_to_html.__name__
]
__all__ = [matplotlib_fig_to_markdown.__name__, matplotlib_fig_to_html.__name__]
42 changes: 26 additions & 16 deletions src/pretty_jupyter/helpers/matplotlib.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,10 @@
from io import BytesIO
import base64
from io import BytesIO

_MARKDOWN_SUPPORTED_FMT_MAP = {
"png": "png",
"jpeg": "jpeg",
"jpg": "jpeg"
}
_MARKDOWN_SUPPORTED_FMT_MAP = {"png": "png", "jpeg": "jpeg", "jpg": "jpeg"}
_MARKDOWN_IMG_FORMAT = r"![image](data:image/{format};base64,{encoded})"

_HTML_SUPPORTED_FMT_MAP = {
"svg": "svg+xml",
"png": "png",
"jpeg": "jpeg",
"jpg": "jpeg"
}
_HTML_SUPPORTED_FMT_MAP = {"svg": "svg+xml", "png": "png", "jpeg": "jpeg", "jpg": "jpeg"}
_HTML_IMG_FORMAT = r"<img src='data:image/{format};base64,{encoded}' />"


Expand All @@ -30,7 +21,15 @@ def matplotlib_fig_to_markdown(fig, fmt="png", autoclose: bool = True, bbox_inch
Returns:
str: Markdown string embedded representation of the figure.
"""
return convert_mpl(fig, fmt=fmt, output_fmt_string=_MARKDOWN_IMG_FORMAT, supported_fmt_map=_MARKDOWN_SUPPORTED_FMT_MAP, autoclose=autoclose, bbox_inches=bbox_inches)
return convert_mpl(
fig,
fmt=fmt,
output_fmt_string=_MARKDOWN_IMG_FORMAT,
supported_fmt_map=_MARKDOWN_SUPPORTED_FMT_MAP,
autoclose=autoclose,
bbox_inches=bbox_inches,
)


def matplotlib_fig_to_html(fig, fmt="png", autoclose: bool = True, bbox_inches: str = "tight"):
"""
Expand All @@ -47,7 +46,15 @@ def matplotlib_fig_to_html(fig, fmt="png", autoclose: bool = True, bbox_inches:
"""
return convert_mpl(fig, fmt, _HTML_IMG_FORMAT, _HTML_SUPPORTED_FMT_MAP, autoclose, bbox_inches)

def convert_mpl(fig, fmt, output_fmt_string, supported_fmt_map, autoclose: bool = True, bbox_inches: str = "tight"):

def convert_mpl(
fig,
fmt,
output_fmt_string,
supported_fmt_map,
autoclose: bool = True,
bbox_inches: str = "tight",
):
"""
Converts matplotlib figure into embedded inline string.
Expand All @@ -68,9 +75,12 @@ def convert_mpl(fig, fmt, output_fmt_string, supported_fmt_map, autoclose: bool
tmpfile = BytesIO()
fig.savefig(tmpfile, format=fmt, bbox_inches=bbox_inches)

markdown = output_fmt_string.format(format=supported_fmt_map[fmt], encoded=base64.b64encode(tmpfile.getvalue()).decode('utf-8'))
markdown = output_fmt_string.format(
format=supported_fmt_map[fmt], encoded=base64.b64encode(tmpfile.getvalue()).decode("utf-8")
)

if autoclose:
import matplotlib.pyplot as plt

plt.close()
return markdown
return markdown
41 changes: 23 additions & 18 deletions src/pretty_jupyter/magics.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from IPython import display
from IPython.core.magic import Magics, magics_class, cell_magic
import jinja2
from IPython import display
from IPython.core.magic import Magics, cell_magic, magics_class

from pretty_jupyter.tokens import convert_markdown_tokens_to_html

Expand All @@ -9,18 +9,20 @@
class JinjaMagics(Magics):
def __init__(self, shell):
super().__init__(shell)

# create a jinja2 environment to use for rendering
# this can be modified for desired effects (ie: using different variable syntax)
self.env = jinja2.Environment(loader=jinja2.FileSystemLoader('.'))
self.env = jinja2.Environment(loader=jinja2.FileSystemLoader("."))

# possible output types
self.display_functions = dict(html=display.HTML,
latex=display.Latex,
json=display.JSON,
pretty=display.Pretty,
display=display.display,
markdown=display.Markdown)
self.display_functions = dict(
html=display.HTML,
latex=display.Latex,
json=display.JSON,
pretty=display.Pretty,
display=display.display,
markdown=display.Markdown,
)

@cell_magic
def jinja(self, line, cell):
Expand All @@ -32,9 +34,14 @@ def jinja(self, line, cell):

# render the cell with jinja (substitutes variables,...)
tmp = self.env.from_string(cell)
rend = tmp.render(dict((k,v) for (k,v) in self.shell.user_ns.items()
if not k.startswith('_') and k not in self.shell.user_ns_hidden))

rend = tmp.render(
dict(
(k, v)
for (k, v) in self.shell.user_ns.items()
if not k.startswith("_") and k not in self.shell.user_ns_hidden
)
)

# convert tokens to html
if display_fn_name == "markdown":
rend = convert_markdown_tokens_to_html(rend)
Expand All @@ -48,6 +55,7 @@ def jmd(self, line, cell):
raise ValueError(r"%%jmd does not accept any arguments.")
return self.jinja(line="markdown", cell=cell)


def is_jinja_cell(input_str: str) -> bool:
"""
Checks whether the input is input of a jinja cell.
Expand All @@ -64,9 +72,6 @@ def is_jinja_cell(input_str: str) -> bool:
return False

first_line = lines[0]
fns = [
lambda l: l.startswith("%%jinja"),
lambda l: l.startswith("%%jmd")
]
fns = [lambda l: l.startswith("%%jinja"), lambda l: l.startswith("%%jmd")]

return any(fn(first_line) for fn in fns)
return any(fn(first_line) for fn in fns)
14 changes: 10 additions & 4 deletions src/pretty_jupyter/preprocessors/__init__.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,15 @@
from pretty_jupyter.preprocessors._token_preprocessor import TokenPreprocessor, TokenCleaningPreprocessor
from pretty_jupyter.preprocessors._metadata_preprocessor import NbMetadataPreprocessor, HtmlNbMetadataPreprocessor
from pretty_jupyter.preprocessors._metadata_preprocessor import (
HtmlNbMetadataPreprocessor,
NbMetadataPreprocessor,
)
from pretty_jupyter.preprocessors._token_preprocessor import (
TokenCleaningPreprocessor,
TokenPreprocessor,
)

__all__ = [
"TokenPreprocessor",
"TokenCleaningPreprocessor",
"NbMetadatapreprocessor",
"HtmlNbMetadataPreprocessor"
]
"HtmlNbMetadataPreprocessor",
]
Loading

0 comments on commit a95c490

Please sign in to comment.