Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
probml
GitHub Repository: probml/pyprobml
Path: blob/master/internal/book2/handle_book2_duplicates.py
1192 views
1
from glob import glob
2
import nbformat as nbf
3
4
book2_nb = glob("notebooks/book2/*/*.ipynb")
5
6
colab_base_url = "https://colab.research.google.com/github/probml/pyprobml/blob/master/notebooks/book2"
7
prefix = "Source of this notebook is here:"
8
9
# create notebook to chapters mapping
10
nb_to_chap = {}
11
for nb in book2_nb:
12
name = nb.split("/")[-1]
13
chap = nb.split("/")[-2]
14
if name in nb_to_chap:
15
nb_to_chap[name].append(chap)
16
else:
17
nb_to_chap[name] = [chap]
18
19
# keep first notebook and redirect others
20
counter = 0
21
for nb_name in nb_to_chap:
22
chapters = sorted(nb_to_chap[nb_name])
23
first_chap = chapters[0]
24
for chapter in chapters[1:]:
25
# read
26
nb_content = nbf.read(f"notebooks/book2/{chapter}/{nb_name}", as_version=4)
27
28
# replace with redirected link
29
new_cell = nbf.v4.new_markdown_cell(f"{prefix} {colab_base_url}/{first_chap}/{nb_name}")
30
nb_content["cells"] = [new_cell]
31
32
# write
33
nbf.write(nb_content, f"notebooks/book2/{chapter}/{nb_name}")
34
print(f"{nb_name} duplicate in {chapter} is redirected to {first_chap}")
35
counter += 1
36
37
print("Done. {} notebooks are redirected.".format(counter))
38
39