Add cells in notebook json
Tags: #naas #jupyter-notebooks #snippet
Author: Florent Ravenel

Input

Import libraries

1
import json
2
from pprint import pprint
Copied!

Variables

1
notebook_path = "Jupyter_Notebooks_Get_libraries.ipynb"
Copied!

Model

Add new cells "Author" and "Tags" in awesome-notebooks if does not exist

1
def add_cells(notebook_path):
2
notebook_path
3
with open(notebook_path) as f:
4
nb = json.load(f)
5
root = notebook_path.split("/")[0]
6
check_logo = False
7
check_title = False
8
check_download = False
9
check_tags = False
10
check_author = False
11
check_input = False
12
check_model = False
13
check_output = False
14
no_markdown = 0
15
16
cells = nb.get("cells")
17
# Check each cells
18
for cell in cells:
19
cell_type = cell.get('cell_type')
20
sources = cell.get('source')
21
if cell_type == "markdown":
22
for source in sources:
23
if source.startswith("<img") and no_markdown == 0:
24
check_logo = True
25
if source.startswith("# ") and root in source:
26
check_title = True
27
if "https://app.naas.ai/user-redirect/naas/downloader" in source:
28
check_download = True
29
if "**Tags:**" in source:
30
check_tags = True
31
tags = source[9:].strip()
32
if "**Author:**" in source:
33
check_author = True
34
author = source[11:].split("[")[-1].split("]")[0]
35
if source.startswith("## Input"):
36
check_input = True
37
if source.startswith("## Model"):
38
check_model = True
39
if source.startswith("## Output"):
40
check_output = True
41
42
# Check
43
add_logo = False
44
add_author = False
45
if not check_logo:
46
print("Logo to be added")
47
add_logo = True
48
if not check_author and check_tags:
49
print("Author to be added below tags")
50
add_author = True
51
52
# Apply change
53
new_cells = []
54
if add_logo:
55
cell_logo = {'cell_type': 'markdown',
56
'id': 'naas-logo',
57
'metadata': {'papermill': {}, 'tags': ["naas"]},
58
'source': '<img width="10%" alt="Naas" src="https://landen.imgix.net/jtci2pxwjczr/assets/5ice39g4.png?w=160"/>'}
59
new_cells.append(cell_logo)
60
for cell in cells:
61
new_cells.append(cell)
62
cell_type = cell.get('cell_type')
63
source = cell.get('source')
64
65
if cell_type == "markdown":
66
if "**Tags:**" in source and add_author:
67
cell_author = {'cell_type': 'markdown',
68
'id': 'naas-author',
69
'metadata': {'papermill': {}, 'tags': ["naas"]},
70
'source': '**Author:** [Unknown](https://www.linkedin.com/company/naas-ai/)'}
71
new_cells.append(cell_author)
72
if add_logo or add_author:
73
nb_new = nb.copy()
74
nb_new["cells"] = new_cells
75
with open(notebook_path, 'w') as f:
76
json.dump(nb_new, f)
77
print(f"{notebook_path} saved in Naas.")
78
return nb_new
79
else:
80
print("Nothing to be added in notebooks !")
Copied!

Output

Display result

1
nb = add_cells(notebook_path)
2
pprint(nb)
Copied!
1
Copied!
Copy link
Edit on GitHub