Skip to content

Commit 485eac4

Browse files
authored
Merge pull request #1295 from xl0/no-newline
No newline
2 parents cf5e6a5 + 0687ba8 commit 485eac4

File tree

5 files changed

+22
-50
lines changed

5 files changed

+22
-50
lines changed

README.md

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,8 @@ Getting Started
33

44
<!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->
55

6-
<div>
7-
86
![CI](https://github.com/fastai/nbdev/actions/workflows/test.yaml/badge.svg)
97

10-
</div>
11-
128
*NB: This is nbdev v2, a major upgrade of nbdev. Whilst the differences
139
to nbdev1 aren’t huge, it does require some changes. The old version
1410
docs are at [nbdev1.fast.ai](https://nbdev1.fast.ai). You can use
@@ -75,8 +71,6 @@ The best way to learn how to use nbdev is to complete either the
7571
[written walkthrough](https://nbdev.fast.ai/tutorials/tutorial.html) or
7672
video walkthrough:
7773

78-
<div style="text-align: center">
79-
8074
<div>
8175

8276
<a href="http://www.youtube.com/watch?v=l7zS8Ld4_iA" target="_blank"
@@ -86,8 +80,6 @@ style="border-radius: 10px" width="560" height="315" /></a>
8680

8781
</div>
8882

89-
</div>
90-
9183
Alternatively, there’s a [shortened version of the video
9284
walkthrough](https://youtu.be/67FdzLSt4aA) with coding sections sped up
9385
using the `unsilence` Python library – it’s 27 minutes faster, but a bit

nbdev/_modidx.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66
'git_url': 'https://github.com/fastai/nbdev',
77
'lib_path': 'nbdev'},
88
'syms': { 'nbdev.clean': { 'nbdev.clean._add_jupyter_hooks': ('api/clean.html#_add_jupyter_hooks', 'nbdev/clean.py'),
9-
'nbdev.clean._add_trailing_n': ('api/clean.html#_add_trailing_n', 'nbdev/clean.py'),
109
'nbdev.clean._clean_cell': ('api/clean.html#_clean_cell', 'nbdev/clean.py'),
1110
'nbdev.clean._clean_cell_output': ('api/clean.html#_clean_cell_output', 'nbdev/clean.py'),
1211
'nbdev.clean._clean_cell_output_id': ('api/clean.html#_clean_cell_output_id', 'nbdev/clean.py'),

nbdev/clean.py

Lines changed: 15 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -55,11 +55,6 @@ def _clean_cell_output_id(lines):
5555
return _skip_or_sub(lines) if isinstance(lines,str) else [_skip_or_sub(o) for o in lines]
5656

5757
# %% ../nbs/api/11_clean.ipynb 11
58-
def _add_trailing_n(img):
59-
if not isinstance(img,str): return [ _add_trailing_n(o) for o in img ]
60-
return img + "\n" if img[-1] != "\n" else img
61-
62-
# %% ../nbs/api/11_clean.ipynb 12
6358
def _clean_cell_output(cell, clean_ids):
6459
"Remove `cell` output execution count and optionally ids from text reprs"
6560
outputs = cell.get('outputs', [])
@@ -69,11 +64,11 @@ def _clean_cell_output(cell, clean_ids):
6964
data.pop("application/vnd.google.colaboratory.intrinsic+json", None)
7065
for k in data:
7166
if k.startswith('text') and clean_ids: data[k] = _clean_cell_output_id(data[k])
72-
if k.startswith('image'): data[k] = _add_trailing_n(data[k])
67+
if k.startswith('image') and "svg" not in k: data[k] = data[k].rstrip()
7368
if 'text' in o and clean_ids: o['text'] = _clean_cell_output_id(o['text'])
7469
o.get('metadata', {}).pop('tags', None)
7570

76-
# %% ../nbs/api/11_clean.ipynb 13
71+
# %% ../nbs/api/11_clean.ipynb 12
7772
def _clean_cell(cell, clear_all, allowed_metadata_keys, clean_ids):
7873
"Clean `cell` by removing superfluous metadata or everything except the input if `clear_all`"
7974
if 'execution_count' in cell: cell['execution_count'] = None
@@ -84,7 +79,7 @@ def _clean_cell(cell, clear_all, allowed_metadata_keys, clean_ids):
8479
cell['metadata'] = {} if clear_all else {
8580
k:v for k,v in cell['metadata'].items() if k in allowed_metadata_keys}
8681

87-
# %% ../nbs/api/11_clean.ipynb 14
82+
# %% ../nbs/api/11_clean.ipynb 13
8883
def clean_nb(
8984
nb, # The notebook to clean
9085
clear_all=False, # Remove all cell metadata and cell outputs?
@@ -93,43 +88,42 @@ def clean_nb(
9388
clean_ids=True, # Remove ids from plaintext reprs?
9489
):
9590
"Clean `nb` from superfluous metadata"
96-
assert isinstance(nb, AttrDict)
9791
metadata_keys = {"kernelspec", "jekyll", "jupytext", "doc", "widgets"}
9892
if allowed_metadata_keys: metadata_keys.update(allowed_metadata_keys)
9993
cell_metadata_keys = {"hide_input"}
10094
if allowed_cell_metadata_keys: cell_metadata_keys.update(allowed_cell_metadata_keys)
10195
for c in nb['cells']: _clean_cell(c, clear_all, cell_metadata_keys, clean_ids)
102-
if nested_attr(nb, 'metadata.kernelspec.name'):
103-
nb['metadata']['kernelspec']['display_name'] = nb.metadata.kernelspec.name
96+
if nb.get('metadata', {}).get('kernelspec', {}).get('name', None):
97+
nb['metadata']['kernelspec']['display_name'] = nb["metadata"]["kernelspec"]["name"]
10498
nb['metadata'] = {k:v for k,v in nb['metadata'].items() if k in metadata_keys}
10599

106-
# %% ../nbs/api/11_clean.ipynb 27
100+
# %% ../nbs/api/11_clean.ipynb 26
107101
def _reconfigure(*strms):
108102
for s in strms:
109103
if hasattr(s,'reconfigure'): s.reconfigure(encoding='utf-8')
110104

111-
# %% ../nbs/api/11_clean.ipynb 28
105+
# %% ../nbs/api/11_clean.ipynb 27
112106
def process_write(warn_msg, proc_nb, f_in, f_out=None, disp=False):
113107
if not f_out: f_out = f_in
114108
if isinstance(f_in, (str,Path)): f_in = Path(f_in).open(encoding="utf-8")
115109
try:
116110
_reconfigure(f_in, f_out)
117-
nb = dict2nb(loads(f_in.read()))
111+
nb = loads(f_in.read())
118112
proc_nb(nb)
119113
write_nb(nb, f_out) if not disp else sys.stdout.write(nb2str(nb))
120114
except Exception as e:
121115
warn(f'{warn_msg}')
122116
warn(e)
123117

124-
# %% ../nbs/api/11_clean.ipynb 29
118+
# %% ../nbs/api/11_clean.ipynb 28
125119
def _nbdev_clean(nb, path=None, clear_all=None):
126120
cfg = get_config(path=path)
127121
clear_all = clear_all or cfg.clear_all
128122
allowed_metadata_keys = cfg.get("allowed_metadata_keys").split()
129123
allowed_cell_metadata_keys = cfg.get("allowed_cell_metadata_keys").split()
130124
return clean_nb(nb, clear_all, allowed_metadata_keys, allowed_cell_metadata_keys, cfg.clean_ids)
131125

132-
# %% ../nbs/api/11_clean.ipynb 30
126+
# %% ../nbs/api/11_clean.ipynb 29
133127
@call_parse
134128
def nbdev_clean(
135129
fname:str=None, # A notebook name or glob to clean
@@ -145,15 +139,15 @@ def nbdev_clean(
145139
if fname is None: fname = get_config().nbs_path
146140
for f in globtastic(fname, file_glob='*.ipynb', skip_folder_re='^[_.]'): _write(f_in=f, disp=disp)
147141

148-
# %% ../nbs/api/11_clean.ipynb 33
142+
# %% ../nbs/api/11_clean.ipynb 32
149143
def clean_jupyter(path, model, **kwargs):
150144
"Clean Jupyter `model` pre save to `path`"
151145
if not (model['type']=='notebook' and model['content']['nbformat']==4): return
152146
get_config.cache_clear() # Allow config changes without restarting Jupyter
153147
jupyter_hooks = get_config(path=path).jupyter_hooks
154148
if jupyter_hooks: _nbdev_clean(model['content'], path=path)
155149

156-
# %% ../nbs/api/11_clean.ipynb 36
150+
# %% ../nbs/api/11_clean.ipynb 35
157151
_pre_save_hook_src = '''
158152
def nbdev_clean_jupyter(**kwargs):
159153
try: from nbdev.clean import clean_jupyter
@@ -163,7 +157,7 @@ def nbdev_clean_jupyter(**kwargs):
163157
c.ContentsManager.pre_save_hook = nbdev_clean_jupyter'''.strip()
164158
_pre_save_hook_re = re.compile(r'c\.(File)?ContentsManager\.pre_save_hook')
165159

166-
# %% ../nbs/api/11_clean.ipynb 37
160+
# %% ../nbs/api/11_clean.ipynb 36
167161
def _add_jupyter_hooks(src, path):
168162
if _pre_save_hook_src in src: return
169163
mod = ast.parse(src)
@@ -181,12 +175,12 @@ def _add_jupyter_hooks(src, path):
181175
if src: src+='\n\n'
182176
return src+_pre_save_hook_src
183177

184-
# %% ../nbs/api/11_clean.ipynb 41
178+
# %% ../nbs/api/11_clean.ipynb 40
185179
def _git_root():
186180
try: return Path(run('git rev-parse --show-toplevel'))
187181
except OSError: return None
188182

189-
# %% ../nbs/api/11_clean.ipynb 44
183+
# %% ../nbs/api/11_clean.ipynb 43
190184
@call_parse
191185
def nbdev_install_hooks():
192186
"Install Jupyter and git hooks to automatically clean, trust, and fix merge conflicts in notebooks"

nbs/api/11_clean.ipynb

Lines changed: 6 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -144,18 +144,6 @@
144144
"test_eq(_clean_cell_output_id('foo\\n<function _add2 at 0x7f8252378820>\\nbar'), 'foo\\n<function _add2>\\nbar')"
145145
]
146146
},
147-
{
148-
"cell_type": "code",
149-
"execution_count": null,
150-
"metadata": {},
151-
"outputs": [],
152-
"source": [
153-
"#|exporti\n",
154-
"def _add_trailing_n(img):\n",
155-
" if not isinstance(img,str): return [ _add_trailing_n(o) for o in img ]\n",
156-
" return img + \"\\n\" if img[-1] != \"\\n\" else img"
157-
]
158-
},
159147
{
160148
"cell_type": "code",
161149
"execution_count": null,
@@ -172,7 +160,7 @@
172160
" data.pop(\"application/vnd.google.colaboratory.intrinsic+json\", None)\n",
173161
" for k in data:\n",
174162
" if k.startswith('text') and clean_ids: data[k] = _clean_cell_output_id(data[k])\n",
175-
" if k.startswith('image'): data[k] = _add_trailing_n(data[k])\n",
163+
" if k.startswith('image') and \"svg\" not in k: data[k] = data[k].rstrip()\n",
176164
" if 'text' in o and clean_ids: o['text'] = _clean_cell_output_id(o['text'])\n",
177165
" o.get('metadata', {}).pop('tags', None)"
178166
]
@@ -210,14 +198,13 @@
210198
" clean_ids=True, # Remove ids from plaintext reprs?\n",
211199
"):\n",
212200
" \"Clean `nb` from superfluous metadata\"\n",
213-
" assert isinstance(nb, AttrDict)\n",
214201
" metadata_keys = {\"kernelspec\", \"jekyll\", \"jupytext\", \"doc\", \"widgets\"}\n",
215202
" if allowed_metadata_keys: metadata_keys.update(allowed_metadata_keys)\n",
216203
" cell_metadata_keys = {\"hide_input\"}\n",
217204
" if allowed_cell_metadata_keys: cell_metadata_keys.update(allowed_cell_metadata_keys)\n",
218205
" for c in nb['cells']: _clean_cell(c, clear_all, cell_metadata_keys, clean_ids)\n",
219-
" if nested_attr(nb, 'metadata.kernelspec.name'):\n",
220-
" nb['metadata']['kernelspec']['display_name'] = nb.metadata.kernelspec.name\n",
206+
" if nb.get('metadata', {}).get('kernelspec', {}).get('name', None):\n",
207+
" nb['metadata']['kernelspec']['display_name'] = nb[\"metadata\"][\"kernelspec\"][\"name\"]\n",
221208
" nb['metadata'] = {k:v for k,v in nb['metadata'].items() if k in metadata_keys}"
222209
]
223210
},
@@ -237,9 +224,9 @@
237224
"outputs": [],
238225
"source": [
239226
"test_nb = read_nb('../../tests/image.ipynb')\n",
240-
"assert test_nb.cells[0].outputs[0].data['image/png'][-1] != \"\\n\" # Make sure it was not converted by acccident\n",
227+
"assert test_nb.cells[0].outputs[0].data['image/png'][-1] == \"\\n\" # Make sure it was not converted by acccident\n",
241228
"clean_nb(test_nb)\n",
242-
"assert test_nb.cells[0].outputs[0].data['image/png'][-1] == \"\\n\""
229+
"assert test_nb.cells[0].outputs[0].data['image/png'][-1] != \"\\n\""
243230
]
244231
},
245232
{
@@ -368,7 +355,7 @@
368355
" if isinstance(f_in, (str,Path)): f_in = Path(f_in).open(encoding=\"utf-8\")\n",
369356
" try:\n",
370357
" _reconfigure(f_in, f_out)\n",
371-
" nb = dict2nb(loads(f_in.read()))\n",
358+
" nb = loads(f_in.read())\n",
372359
" proc_nb(nb)\n",
373360
" write_nb(nb, f_out) if not disp else sys.stdout.write(nb2str(nb))\n",
374361
" except Exception as e:\n",

tests/image.ipynb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
"outputs": [
88
{
99
"data": {
10-
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAAgAAAAICAIAAABLbSncAAAAE0lEQVR4nGNkaGDACpiwCw9WCQBqCACQJ5at+QAAAABJRU5ErkJggg==",
10+
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAAgAAAAICAIAAABLbSncAAAAE0lEQVR4nGNkaGDACpiwCw9WCQBqCACQJ5at+QAAAABJRU5ErkJggg==\n",
1111
"text/plain": [
1212
"<PIL.Image.Image image mode=RGB size=8x8>"
1313
]

0 commit comments

Comments
 (0)