├── .github └── workflows │ ├── deploy.yaml │ └── test.yaml ├── .gitignore ├── LICENSE ├── MANIFEST.in ├── README.md ├── nbdev_extensions ├── __init__.py ├── _modidx.py ├── codenotes.py ├── codetips.py ├── frontmatter.py ├── mknb.py ├── strip.py └── tagmaker.py ├── nbs ├── 00_mknb.ipynb ├── 01_codenotes.ipynb ├── 02_tagmaker.ipynb ├── 03_codetips.ipynb ├── 04_strip.ipynb ├── _quarto.yml ├── index.ipynb ├── nbdev.yml └── sidebar.yml ├── settings.ini ├── setup.py └── styles.css /.github/workflows/deploy.yaml: -------------------------------------------------------------------------------- 1 | name: Deploy to GitHub Pages 2 | on: 3 | push: 4 | branches: [master, main] 5 | workflow_dispatch: 6 | jobs: 7 | deploy: 8 | runs-on: ubuntu-latest 9 | steps: 10 | - uses: fastai/workflows/quarto-ghp@master 11 | with: {pre: 1} 12 | -------------------------------------------------------------------------------- /.github/workflows/test.yaml: -------------------------------------------------------------------------------- 1 | name: CI 2 | on: [workflow_dispatch, pull_request, push] 3 | 4 | jobs: 5 | test: 6 | runs-on: ubuntu-latest 7 | steps: [uses: fastai/workflows/nbdev-ci@master] 8 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | _docs/ 2 | _proc/ 3 | 4 | *.bak 5 | .gitattributes 6 | .last_checked 7 | .gitconfig 8 | *.bak 9 | *.log 10 | *~ 11 | ~* 12 | _tmp* 13 | tmp* 14 | tags 15 | *.pkg 16 | 17 | # Byte-compiled / optimized / DLL files 18 | __pycache__/ 19 | *.py[cod] 20 | *$py.class 21 | 22 | # C extensions 23 | *.so 24 | 25 | # Distribution / packaging 26 | .Python 27 | env/ 28 | build/ 29 | develop-eggs/ 30 | dist/ 31 | downloads/ 32 | eggs/ 33 | .eggs/ 34 | lib/ 35 | lib64/ 36 | parts/ 37 | sdist/ 38 | var/ 39 | wheels/ 40 | *.egg-info/ 41 | .installed.cfg 42 | *.egg 43 | 44 | # PyInstaller 45 | # Usually these files are written by a python script from a template 46 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 47 | *.manifest 48 | *.spec 49 | 50 | # Installer logs 51 | pip-log.txt 52 | pip-delete-this-directory.txt 53 | 54 | # Unit test / coverage reports 55 | htmlcov/ 56 | .tox/ 57 | .coverage 58 | .coverage.* 59 | .cache 60 | nosetests.xml 61 | coverage.xml 62 | *.cover 63 | .hypothesis/ 64 | 65 | # Translations 66 | *.mo 67 | *.pot 68 | 69 | # Django stuff: 70 | *.log 71 | local_settings.py 72 | 73 | # Flask stuff: 74 | instance/ 75 | .webassets-cache 76 | 77 | # Scrapy stuff: 78 | .scrapy 79 | 80 | # Sphinx documentation 81 | docs/_build/ 82 | 83 | # PyBuilder 84 | target/ 85 | 86 | # Jupyter Notebook 87 | .ipynb_checkpoints 88 | 89 | # pyenv 90 | .python-version 91 | 92 | # celery beat schedule file 93 | celerybeat-schedule 94 | 95 | # SageMath parsed files 96 | *.sage.py 97 | 98 | # dotenv 99 | .env 100 | 101 | # virtualenv 102 | .venv 103 | venv/ 104 | ENV/ 105 | 106 | # Spyder project settings 107 | .spyderproject 108 | .spyproject 109 | 110 | # Rope project settings 111 | .ropeproject 112 | 113 | # mkdocs documentation 114 | /site 115 | 116 | # mypy 117 | .mypy_cache/ 118 | 119 | .vscode 120 | *.swp 121 | 122 | # osx generated files 123 | .DS_Store 124 | .DS_Store? 125 | .Trashes 126 | ehthumbs.db 127 | Thumbs.db 128 | .idea 129 | 130 | # pytest 131 | .pytest_cache 132 | 133 | # tools/trust-doc-nbs 134 | docs_src/.last_checked 135 | 136 | # symlinks to fastai 137 | docs_src/fastai 138 | tools/fastai 139 | 140 | # link checker 141 | checklink/cookies.txt 142 | 143 | # .gitconfig is now autogenerated 144 | .gitconfig 145 | 146 | # Quarto installer 147 | .deb 148 | .pkg 149 | 150 | # Quarto 151 | .quarto 152 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2022, fastai 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include settings.ini 2 | include LICENSE 3 | include CONTRIBUTING.md 4 | include README.md 5 | recursive-exclude * __pycache__ 6 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | nbdev-extensions 2 | ================ 3 | 4 | 5 | 6 | These extensions will have niche use cases in some places, however these 7 | are ones where I find a benefit in having them at least once. Also known 8 | as, cool ideas myself or others have considered with nbdev brought to 9 | life 10 | 11 | ## Install 12 | 13 | ``` sh 14 | pip install nbdev-extensions 15 | ``` 16 | 17 | ## How to use 18 | 19 | `nbdev-extensions` currently has the following features: 20 | 21 | - [`new_nb`](https://muellerzr.github.io/nbdev-extensions/mknb.html#new_nb) - 22 | A CLI/functional interface to quickly generate blank template 23 | notebooks for nbdev development with all of the necessary boilerplate 24 | cells prefilled based on the passed parameters. 25 | 26 | - [Code Notes](https://muellerzr.github.io/nbdev-extensions/codenotes.html) - A note-taking annotation tool utilizing 27 | nbdev to write quick comments and explanations for sections of code in 28 | a code cell without cluttering the code cell with comments. These show 29 | up as panels in the rendered documentation, one with just the source 30 | code and the other with the source and an explanation 31 | -------------------------------------------------------------------------------- /nbdev_extensions/__init__.py: -------------------------------------------------------------------------------- 1 | __version__ = "0.1.0" 2 | 3 | from .mknb import new_nb 4 | -------------------------------------------------------------------------------- /nbdev_extensions/_modidx.py: -------------------------------------------------------------------------------- 1 | # Autogenerated by nbdev 2 | 3 | d = { 'settings': { 'branch': 'main', 4 | 'doc_baseurl': '/nbdev-extensions/', 5 | 'doc_host': 'https://muellerzr.github.io', 6 | 'git_url': 'https://github.com/muellerzr/nbdev-extensions/', 7 | 'lib_path': 'nbdev_extensions'}, 8 | 'syms': { 'nbdev_extensions.codenotes': { 'nbdev_extensions.codenotes.NoteExportProc': ( 'codenotes.html#noteexportproc', 9 | 'nbdev_extensions/codenotes.py'), 10 | 'nbdev_extensions.codenotes.NoteExportProc.begin': ( 'codenotes.html#noteexportproc.begin', 11 | 'nbdev_extensions/codenotes.py'), 12 | 'nbdev_extensions.codenotes.NoteExportProc.cell': ( 'codenotes.html#noteexportproc.cell', 13 | 'nbdev_extensions/codenotes.py'), 14 | 'nbdev_extensions.codenotes.NoteExportProc.reset': ( 'codenotes.html#noteexportproc.reset', 15 | 'nbdev_extensions/codenotes.py'), 16 | 'nbdev_extensions.codenotes.convert_explanation': ( 'codenotes.html#convert_explanation', 17 | 'nbdev_extensions/codenotes.py'), 18 | 'nbdev_extensions.codenotes.extract_code': ( 'codenotes.html#extract_code', 19 | 'nbdev_extensions/codenotes.py'), 20 | 'nbdev_extensions.codenotes.make_panel_tabset': ( 'codenotes.html#make_panel_tabset', 21 | 'nbdev_extensions/codenotes.py'), 22 | 'nbdev_extensions.codenotes.parse_code': ( 'codenotes.html#parse_code', 23 | 'nbdev_extensions/codenotes.py'), 24 | 'nbdev_extensions.codenotes.parse_notes': ( 'codenotes.html#parse_notes', 25 | 'nbdev_extensions/codenotes.py')}, 26 | 'nbdev_extensions.codetips': { 'nbdev_extensions.codetips.TipExportProc': ( 'codetips.html#tipexportproc', 27 | 'nbdev_extensions/codetips.py'), 28 | 'nbdev_extensions.codetips.TipExportProc.begin': ( 'codetips.html#tipexportproc.begin', 29 | 'nbdev_extensions/codetips.py'), 30 | 'nbdev_extensions.codetips.TipExportProc.cell': ( 'codetips.html#tipexportproc.cell', 31 | 'nbdev_extensions/codetips.py'), 32 | 'nbdev_extensions.codetips.TipExportProc.reset': ( 'codetips.html#tipexportproc.reset', 33 | 'nbdev_extensions/codetips.py'), 34 | 'nbdev_extensions.codetips.convert_explanation': ( 'codetips.html#convert_explanation', 35 | 'nbdev_extensions/codetips.py'), 36 | 'nbdev_extensions.codetips.download_tooltip_css': ( 'codetips.html#download_tooltip_css', 37 | 'nbdev_extensions/codetips.py'), 38 | 'nbdev_extensions.codetips.extract_code': ( 'codetips.html#extract_code', 39 | 'nbdev_extensions/codetips.py'), 40 | 'nbdev_extensions.codetips.parse_code': ( 'codetips.html#parse_code', 41 | 'nbdev_extensions/codetips.py'), 42 | 'nbdev_extensions.codetips.parse_notes': ( 'codetips.html#parse_notes', 43 | 'nbdev_extensions/codetips.py'), 44 | 'nbdev_extensions.codetips.write_tooltip_directives': ( 'codetips.html#write_tooltip_directives', 45 | 'nbdev_extensions/codetips.py')}, 46 | 'nbdev_extensions.frontmatter': {}, 47 | 'nbdev_extensions.mknb': { 'nbdev_extensions.mknb._mk_nb': ('mknb.html#_mk_nb', 'nbdev_extensions/mknb.py'), 48 | 'nbdev_extensions.mknb.new_nb': ('mknb.html#new_nb', 'nbdev_extensions/mknb.py')}, 49 | 'nbdev_extensions.strip': {'nbdev_extensions.strip.strip_nbs': ('strip.html#strip_nbs', 'nbdev_extensions/strip.py')}, 50 | 'nbdev_extensions.tagmaker': { 'nbdev_extensions.tagmaker.LayoutProc': ( 'tagmaker.html#layoutproc', 51 | 'nbdev_extensions/tagmaker.py'), 52 | 'nbdev_extensions.tagmaker.LayoutProc.cell': ( 'tagmaker.html#layoutproc.cell', 53 | 'nbdev_extensions/tagmaker.py'), 54 | 'nbdev_extensions.tagmaker.convert_layout': ( 'tagmaker.html#convert_layout', 55 | 'nbdev_extensions/tagmaker.py'), 56 | 'nbdev_extensions.tagmaker.convert_shortcuts': ( 'tagmaker.html#convert_shortcuts', 57 | 'nbdev_extensions/tagmaker.py')}}} 58 | -------------------------------------------------------------------------------- /nbdev_extensions/codenotes.py: -------------------------------------------------------------------------------- 1 | # AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/01_codenotes.ipynb. 2 | 3 | # %% auto 0 4 | __all__ = ['make_panel_tabset', 'convert_explanation', 'extract_code', 'parse_code', 'NoteExportProc', 'parse_notes'] 5 | 6 | # %% ../nbs/01_codenotes.ipynb 3 7 | from nbdev.config import get_config 8 | from nbdev.process import NBProcessor, extract_directives 9 | from nbdev.processors import Processor, mk_cell 10 | from nbdev.export import nb_export 11 | from nbdev.doclinks import nbglob 12 | from nbdev.sync import write_nb 13 | 14 | from fastcore.script import call_parse 15 | from fastcore.xtras import Path 16 | 17 | import shlex 18 | import re 19 | 20 | # %% ../nbs/01_codenotes.ipynb 4 21 | def make_panel_tabset(): 22 | "Creates a templated panel tabset for Quarto" 23 | cells = [ 24 | mk_cell("::: {.panel-tabset}\n\n## Code", cell_type="markdown"), 25 | # Original goes here 26 | mk_cell("## Code + Explanation", cell_type="markdown"), 27 | # All explainations go here 28 | mk_cell(":::", cell_type="markdown") 29 | ] 30 | return cells 31 | 32 | # %% ../nbs/01_codenotes.ipynb 5 33 | def convert_explanation(explanation_cell, source): 34 | "Takes an explanation and source code and linkes them together in a new cell" 35 | _py, newline = "{.python}", "\n" 36 | explanation = re.sub(r'\*#|.*[\n]', "", explanation_cell.source) 37 | content = f"{newline}***{newline}```{_py}{newline}{source}{newline}```" 38 | content += f"{newline}::: " 39 | content += "{style='padding-top: 0px;'}" 40 | content += f"{newline}{explanation}{newline}:::" 41 | return mk_cell(content, cell_type="markdown") 42 | 43 | # %% ../nbs/01_codenotes.ipynb 6 44 | def extract_code(start_code, end_code, source, instance_num, end_instance_num=0): 45 | "Finds code between start and finish potentially with instances to check" 46 | start_match = list(re.finditer(f'[ \t]*{start_code}', source))[int(instance_num)] 47 | start_char = start_match.span()[0] 48 | end_match = list(re.finditer(f'[ \t]*{end_code}', source))[int(end_instance_num)] 49 | end_char = end_match.span()[1] 50 | return source[start_char:end_char] 51 | 52 | # %% ../nbs/01_codenotes.ipynb 7 53 | def parse_code(code_cell, markdown_cell): 54 | "Parses directives to extract the code needed to be highlighted" 55 | directives = markdown_cell.directives_["explain"] 56 | directives = shlex.split(" ".join(directives)) 57 | multiline = "multiline" in directives 58 | if multiline: 59 | directives = directives[1:] 60 | if len(directives) == 4: 61 | start_code, start_instance_num, end_code, end_instance_num = directives 62 | else: 63 | (start_code, start_instance_num, end_code), (end_instance_num) = directives, 0 64 | start_code, end_code = re.escape(start_code), re.escape(end_code) 65 | return extract_code(start_code, end_code, code_cell.source, start_instance_num, end_instance_num) 66 | else: 67 | return directives[0] 68 | 69 | # %% ../nbs/01_codenotes.ipynb 8 70 | class NoteExportProc(Processor): 71 | "A proc that checks and reorganizes cells for documentation for proper explainations" 72 | offset = 0 73 | steps = [] 74 | _i = 0 75 | def begin(self): 76 | self.reset() 77 | self.has_reset = False 78 | self.iter = 0 79 | self.offset = 0 80 | 81 | def reset(self): 82 | self.results = make_panel_tabset() 83 | self.code = [] 84 | self._code = None 85 | self.found_explanation = False 86 | self.end_link = False 87 | self.explanations = [] 88 | self.start_idx = None 89 | self.end_idx = None 90 | 91 | def cell(self, cell): 92 | if cell.cell_type == "code": 93 | if not self.found_explanation: 94 | self._code = cell 95 | self.start_idx = cell.idx_ 96 | 97 | if cell.cell_type == "markdown" and "explain" in cell.directives_: 98 | self.found_explanation = True 99 | self.explanations.append(cell) 100 | 101 | if self.found_explanation: 102 | idx = cell.idx_ + 1 103 | if (len(self.nb.cells) <= idx+1) or ("explain" not in self.nb.cells[idx].directives_): 104 | self.end_link = True 105 | self.end_idx = cell.idx_ + 1 106 | 107 | if self.found_explanation and self.end_link: 108 | # Assume we have all code + explainations 109 | tabset_code_idx = 1 110 | tabset_explain_idx = 3 111 | self.results.insert(tabset_code_idx, self._code) 112 | explanations = [self._code] 113 | for i,explanation in enumerate(self.explanations): 114 | source = parse_code(self._code, explanation) 115 | converted_explanation = convert_explanation(explanation, source) 116 | explanations.append(converted_explanation) 117 | self.nb.cells.remove(explanation) 118 | self.results = self.results[:3] + explanations + [self.results[3]] 119 | self.nb.cells.remove(self._code) 120 | self.offset = 0 121 | for result in self.results: 122 | result.idx_ = self.nb.cells[self.start_idx - 1].idx_ + 1 123 | self.nb.cells.insert(self.start_idx + self.offset, result) 124 | self.offset += 1 125 | self.iter += 1 126 | self.reset() 127 | self.has_reset = True 128 | 129 | self.offset = 0 130 | for i,c in enumerate(self.nb.cells): c.idx_ = i 131 | 132 | # %% ../nbs/01_codenotes.ipynb 9 133 | @call_parse 134 | def parse_notes(): 135 | "Exports notebooks to parsed notes for documentation. Should be called in the workflow, not yourself!" 136 | for nb in nbglob(get_config().nbs_path): 137 | processor = NBProcessor(nb, [NoteExportProc], rm_directives=False) 138 | processor.process() 139 | write_nb(processor.nb, nb) 140 | -------------------------------------------------------------------------------- /nbdev_extensions/codetips.py: -------------------------------------------------------------------------------- 1 | # AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/03_codetips.ipynb. 2 | 3 | # %% auto 0 4 | __all__ = ['HINT_CSS_URL', 'TIPS_CSS', 'download_tooltip_css', 'write_tooltip_directives', 'convert_explanation', 'extract_code', 5 | 'parse_code', 'TipExportProc', 'parse_notes'] 6 | 7 | # %% ../nbs/03_codetips.ipynb 3 8 | from nbdev.config import get_config 9 | from nbdev.process import NBProcessor, extract_directives 10 | from nbdev.processors import Processor, mk_cell 11 | from nbdev.export import nb_export 12 | from nbdev.doclinks import nbglob 13 | from nbdev.sync import write_nb 14 | 15 | from fastcore.script import call_parse 16 | from fastcore.xtras import Path 17 | 18 | import shlex 19 | import requests 20 | import re 21 | 22 | # %% ../nbs/03_codetips.ipynb 5 23 | HINT_CSS_URL = "https://raw.githubusercontent.com/muellerzr/til/master/nbs/hint.css" 24 | 25 | # %% ../nbs/03_codetips.ipynb 6 26 | TIPS_CSS = """.nogap { 27 | padding: 0px; 28 | border-radius: 0px !important; 29 | outline: 0px 0px; 30 | margin-bottom: 0px !important; 31 | } 32 | 33 | .code-with-filename .code-with-filename-file { 34 | margin: 0px; 35 | } 36 | div.sourceCode { 37 | border: 0px; 38 | margin: 0px; 39 | } 40 | 41 | pre > code.sourceCode { 42 | white-space: pre; 43 | text-decoration: none; 44 | } 45 | 46 | .nogap > div.sourceCode > pre.sourceCode { 47 | line-height: 0px; 48 | padding-bottom: 0px; 49 | padding-top: 0px; 50 | margin-bottom: 0px; 51 | margin-top: 0px; 52 | }""" 53 | 54 | # %% ../nbs/03_codetips.ipynb 7 55 | def download_tooltip_css(): 56 | config = get_config() 57 | css_path = config.nbs_path/"hint.css" 58 | if not css_path.exists(): 59 | response = requests.get(HTML_CSS_URL) 60 | css_path.write_bytes(response.content) 61 | (config.nbs_path/"codetips.css").write_text(TIPS_CSS) 62 | print(f'Added custom css files. Please add `codetips.css` and `hint.css` to `_quarto.yml` under `format -> html -> css`') 63 | 64 | # %% ../nbs/03_codetips.ipynb 8 65 | def write_tooltip_directives( 66 | # The tooltip text 67 | explanation: str, 68 | # A list of css directives to modify the tooltip 69 | hint_directives:list = ["rounded", "medium", "right"], 70 | # An optional filename to be rendered 71 | filename:str = None, 72 | ): 73 | "Creates a tooltip in style of `hint_directives` with content `explanation`" 74 | hint_directives = [f".hint--{hint} " for hint in hint_directives] 75 | hint_directives[-1] = hint_directives[-1].rstrip() # for formatting 76 | tooltip = f'''#| classes: .nogap {"".join(hint_directives)} 77 | #| aria-label: "{explanation}" 78 | #|eval: false''' 79 | if filename is not None: 80 | tooltip += f'\n#| filename: "{filename}"' 81 | return tooltip + "\n" 82 | 83 | # %% ../nbs/03_codetips.ipynb 9 84 | def convert_explanation(explanation_cell, source): 85 | "Takes an explanation and source code and linkes them together in a new cell" 86 | filename = explanation_cell.directives_.pop("filename:", [None])[0] 87 | explanation = re.sub(r'\*#|.*[\n]', "", explanation_cell.source) 88 | content = write_tooltip_directives(explanation, filename=filename) 89 | content += source 90 | return mk_cell(content, cell_type="code") 91 | 92 | # %% ../nbs/03_codetips.ipynb 10 93 | def extract_code(start_code, end_code, source, instance_num, end_instance_num=0): 94 | "Finds code between start and finish potentially with instances to check" 95 | start_match = list(re.finditer(f'[ \t]*{start_code}', source))[int(instance_num)] 96 | start_char = start_match.span()[0] 97 | end_match = list(re.finditer(f'[ \t]*{end_code}', source))[int(end_instance_num)] 98 | end_char = end_match.span()[1] 99 | return source[start_char:end_char], start_char, end_char 100 | 101 | # %% ../nbs/03_codetips.ipynb 11 102 | def parse_code(code_cell, markdown_cell): 103 | "Parses directives to extract the code needed to be highlighted" 104 | directives = markdown_cell.directives_["tip"] 105 | directives = shlex.split(" ".join(directives)) 106 | if len(directives) == 4: 107 | start_code, start_instance_num, end_code, end_instance_num = directives 108 | else: 109 | (start_code, start_instance_num, end_code), (end_instance_num) = directives, 0 110 | start_code, end_code = re.escape(start_code), re.escape(end_code) 111 | return extract_code(start_code, end_code, code_cell.source, start_instance_num, end_instance_num) 112 | 113 | # %% ../nbs/03_codetips.ipynb 12 114 | class TipExportProc(Processor): 115 | "A proc that checks and reorganizes cells for documentation for proper explainations" 116 | offset = 0 117 | steps = [] 118 | _i = 0 119 | def begin(self): 120 | self.reset() 121 | self.has_reset = False 122 | self.iter = 0 123 | self.offset = 0 124 | 125 | def reset(self): 126 | self.results = [mk_cell("::: {layout-ncol=1}", cell_type="markdown")] 127 | self.code = [] 128 | self._code = None 129 | self.found_explanation = False 130 | self.end_link = False 131 | self.explanations = [] 132 | self.start_idx = None 133 | self.end_idx = None 134 | self.indexes = [] 135 | 136 | def cell(self, cell): 137 | if cell.cell_type == "code": 138 | if not self.found_explanation: 139 | self._code = cell 140 | self.start_idx = cell.idx_ 141 | 142 | if cell.cell_type == "markdown" and "tip" in cell.directives_: 143 | self.found_explanation = True 144 | self.explanations.append(cell) 145 | 146 | if self.found_explanation: 147 | idx = cell.idx_ + 1 148 | if (len(self.nb.cells) <= idx+1) or ("tip" not in self.nb.cells[idx].directives_): 149 | self.end_link = True 150 | self.end_idx = cell.idx_ + 1 151 | 152 | if self.found_explanation and self.end_link: 153 | # Assume we have all code + explainations 154 | explanations = [self._code] 155 | for i,explanation in enumerate(self.explanations): 156 | source, start, end = parse_code(self._code, explanation) 157 | self.indexes += [(start,end)] 158 | converted_explanation = convert_explanation(explanation, source) 159 | self.results.append(converted_explanation) 160 | self.nb.cells.remove(explanation) 161 | second_idxs = list(self.indexes) 162 | second_idxs.sort() 163 | offset = 0 164 | for idx, rng in enumerate(second_idxs): 165 | if rng != second_idxs[-1]: 166 | if second_idxs[idx+1][0] - rng[-1] != 1: 167 | start = rng[-1] 168 | end = second_idxs[idx+1][0] 169 | new_src = self._code.source[start:end] 170 | if new_src != '': 171 | new_src = f'#| classes: .nogap\n#|eval: false\n{new_src}' 172 | self.results.insert(self.indexes.index(rng)+2, mk_cell(new_src, cell_type="code")) 173 | offset += 1 174 | self.results.append(mk_cell(":::", cell_type="markdown")) 175 | self.nb.cells.remove(self._code) 176 | self.offset = 0 177 | for result in self.results: 178 | result.idx_ = self.nb.cells[self.start_idx - 1].idx_ + 1 179 | self.nb.cells.insert(self.start_idx + self.offset, result) 180 | self.offset += 1 181 | self.iter += 1 182 | self.reset() 183 | self.has_reset = True 184 | 185 | self.offset = 0 186 | for i,c in enumerate(self.nb.cells): c.idx_ = i 187 | 188 | # %% ../nbs/03_codetips.ipynb 13 189 | @call_parse 190 | def parse_notes(): 191 | "Exports notebooks to parsed notes for documentation. Should be called in the workflow, not yourself!" 192 | for nb in nbglob(get_config().nbs_path): 193 | processor = NBProcessor(nb, [NoteExportProc], rm_directives=False) 194 | processor.process() 195 | write_nb(processor.nb, nb) 196 | -------------------------------------------------------------------------------- /nbdev_extensions/frontmatter.py: -------------------------------------------------------------------------------- 1 | # AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/03_frontmatter.ipynb. 2 | 3 | # %% auto 0 4 | __all__ = [] 5 | 6 | # %% ../nbs/03_frontmatter.ipynb 3 7 | from nbdev.config import get_config 8 | -------------------------------------------------------------------------------- /nbdev_extensions/mknb.py: -------------------------------------------------------------------------------- 1 | # AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/00_mknb.ipynb. 2 | 3 | # %% auto 0 4 | __all__ = ['new_nb'] 5 | 6 | # %% ../nbs/00_mknb.ipynb 3 7 | import re 8 | from string import Template 9 | 10 | from nbdev.config import get_config 11 | from nbdev.sync import write_nb, mk_cell 12 | from nbdev.doclinks import nbglob 13 | 14 | from fastcore.xtras import Path 15 | 16 | from fastcore.foundation import AttrDict, L 17 | from fastcore.script import call_parse 18 | 19 | # %% ../nbs/00_mknb.ipynb 4 20 | _default_exp = Template("#| default_exp $export") 21 | _title = Template("# $title\n") 22 | _description = Template("> $description") 23 | _export = "#| hide\nimport nbdev; nbdev.nbdev_export()" 24 | 25 | # %% ../nbs/00_mknb.ipynb 5 26 | def _mk_nb(title,desc,exp=None): 27 | nb = AttrDict( 28 | cells=L(), 29 | metadata={}, 30 | nbformat=4, 31 | nbformat_minor=5 32 | ) 33 | if exp is not None: 34 | nb.cells.append(mk_cell(exp)) 35 | nb.cells.append(mk_cell(title+desc, "markdown")) 36 | nb.cells.append(mk_cell("", outputs=[], execution_count=0)) 37 | if exp is not None: 38 | nb.cells.append(mk_cell(_export)) 39 | nb.cells = list(nb.cells) 40 | # return dict(nb) 41 | return nb 42 | 43 | # %% ../nbs/00_mknb.ipynb 6 44 | @call_parse 45 | def new_nb( 46 | name:str, # The name of the newly created notebook 47 | module:str = None, # The name of the exported module it will generate 48 | title:str = None, # The title header in the notebook 49 | description:str = None, # The description that will go under the title header 50 | nprefix:int = None, # if > 0, will be the first number in the filename 51 | nsuffix:int = None, # If > 0, will be the second number in the filename 52 | ): 53 | "Creates a new base nbdev notebook named {nprefix}{nsuffix}_{name}.ipynb" 54 | cfg = get_config() 55 | nbs = nbglob( 56 | cfg.nbs_path, 57 | file_glob="*.ipynb", 58 | file_re="^[0-9]", 59 | skip_folder_re="^[_.]" 60 | ) 61 | nbs = nbs.map( 62 | lambda x: Path(x).name.replace(".ipynb","") 63 | ) 64 | nbs.sort() 65 | title = _title.substitute(title=title or "No Title") 66 | descrip = _description.substitute(description=description or "Fill me in!") 67 | if module is not None: 68 | module = _default_exp.substitute(export=module) 69 | if len(nbs) > 0: 70 | nums = nbs.map( 71 | lambda x: list(re.search("^[0-9][0-9]?", x).group(0)) 72 | ).map(lambda x: list(map(int, x))) 73 | if nprefix is None: 74 | nprefix = max(o[0] for o in nums) 75 | if nsuffix is None: 76 | nsuffix = max(o[1] for o in nums) 77 | else: 78 | nprefix, nsuffix = 0,0 79 | nsuffix += 1 80 | nbpath = cfg.nbs_path/f'{nprefix}{nsuffix}_{name}.ipynb' 81 | write_nb(_mk_nb(title, descrip, module), nbpath) 82 | -------------------------------------------------------------------------------- /nbdev_extensions/strip.py: -------------------------------------------------------------------------------- 1 | # AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/04_strip.ipynb. 2 | 3 | # %% auto 0 4 | __all__ = ['strip_nbs'] 5 | 6 | # %% ../nbs/04_strip.ipynb 2 7 | from nbdev.config import get_config 8 | from nbdev.processors import read_nb 9 | from nbdev.export import nb_export 10 | from nbdev.doclinks import nbglob 11 | from nbdev.sync import write_nb 12 | from fastcore.basics import AttrDict 13 | from fastcore.script import call_parse 14 | from fastcore.xtras import Path 15 | 16 | # %% ../nbs/04_strip.ipynb 5 17 | @call_parse 18 | def strip_nbs( 19 | notebook_path:str, 20 | output_folder:str 21 | ): 22 | "Removes all non-code cells from `notebook_path` and saves it in `output_folder`" 23 | if not Path(output_folder).exists(): 24 | Path(output_folder).mkdir(parents=True, exist_ok=True) 25 | for path in Path(notebook_path).ls(file_exts=".ipynb"): 26 | nb = read_nb(path) 27 | cells = [] 28 | for cell in nb["cells"]: 29 | if cell["cell_type"] == "code": 30 | cell.source = ''.join([line.split(" #")[0] for line in cell.source]) 31 | cells.append(cell) 32 | new_nb = AttrDict( 33 | cells=cells, 34 | metadata={}, 35 | nbformat=4, 36 | nbformat_minor=5 37 | ) 38 | write_nb(new_nb, Path(output_folder)/path.name) 39 | -------------------------------------------------------------------------------- /nbdev_extensions/tagmaker.py: -------------------------------------------------------------------------------- 1 | # AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/02_tagmaker.ipynb. 2 | 3 | # %% auto 0 4 | __all__ = ['convert_layout', 'convert_shortcuts', 'LayoutProc'] 5 | 6 | # %% ../nbs/02_tagmaker.ipynb 3 7 | from nbdev.config import get_config 8 | from nbdev.process import extract_directives 9 | from nbdev.processors import Processor 10 | from nbdev.export import nb_export 11 | from nbdev.doclinks import nbglob 12 | from nbdev.sync import write_nb 13 | 14 | from fastcore.basics import listify 15 | from fastcore.script import call_parse 16 | from fastcore.xtras import Path 17 | 18 | from string import Template 19 | 20 | # %% ../nbs/02_tagmaker.ipynb 5 21 | _LAYOUT_STR = Template("::: {$layout}\n$content\n") 22 | _shortcuts = { 23 | "margin": ".column-margin" 24 | } 25 | 26 | # %% ../nbs/02_tagmaker.ipynb 6 27 | def convert_layout(cell, layout, start=False): 28 | "Parses cell formatted with ::: {$something}, and potentially :::" 29 | layout = listify(layout) 30 | content = cell.source 31 | code = cell.source.splitlines(True) 32 | if "end" in code[0]: 33 | if len(code) == 1: 34 | cell.source = ":::" 35 | else: 36 | cell.source += ":::" 37 | else: 38 | cell.source = _LAYOUT_STR.substitute( 39 | layout=" ".join(layout), 40 | content=content 41 | ) 42 | if not start: 43 | cell.source += ":::" 44 | 45 | # %% ../nbs/02_tagmaker.ipynb 10 46 | def convert_shortcuts(cell): 47 | for i,directive in enumerate(cell.directives_["div"]): 48 | if directive in _shortcuts.keys(): 49 | cell.directives_["div"][i] = _shortcuts[directive] 50 | 51 | # %% ../nbs/02_tagmaker.ipynb 12 52 | import re 53 | class LayoutProc(Processor): 54 | """A proc that will automatically change #| css format 55 | to ::: {format} ... ::: 56 | """ 57 | has_partial = False 58 | def cell(self, cell): 59 | if cell.cell_type == "markdown" and "div" in cell.directives_: 60 | convert_shortcuts(cell) 61 | directives_ = cell.directives_["div"] 62 | if self.has_partial and "end" in directives_: 63 | convert_layout(cell, directives_) 64 | self.has_partial = False 65 | else: 66 | if directives_[-1] == "start": 67 | self.has_partial = True 68 | directives_.remove("start") 69 | convert_layout(cell, directives_, True) 70 | else: 71 | convert_layout(cell, directives_) 72 | -------------------------------------------------------------------------------- /nbs/00_mknb.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "attachments": {}, 5 | "cell_type": "markdown", 6 | "metadata": {}, 7 | "source": [ 8 | "# mknb\n", 9 | "\n", 10 | "> Quickly builds template notebooks to use" 11 | ] 12 | }, 13 | { 14 | "cell_type": "code", 15 | "execution_count": null, 16 | "metadata": { 17 | "vscode": { 18 | "languageId": "python" 19 | } 20 | }, 21 | "outputs": [], 22 | "source": [ 23 | "#| default_exp mknb" 24 | ] 25 | }, 26 | { 27 | "cell_type": "code", 28 | "execution_count": null, 29 | "metadata": { 30 | "vscode": { 31 | "languageId": "python" 32 | } 33 | }, 34 | "outputs": [], 35 | "source": [ 36 | "#| hide\n", 37 | "from nbdev.showdoc import *" 38 | ] 39 | }, 40 | { 41 | "cell_type": "code", 42 | "execution_count": null, 43 | "metadata": { 44 | "vscode": { 45 | "languageId": "python" 46 | } 47 | }, 48 | "outputs": [], 49 | "source": [ 50 | "#| export\n", 51 | "import re\n", 52 | "from string import Template\n", 53 | "\n", 54 | "from nbdev.config import get_config\n", 55 | "from nbdev.sync import write_nb, mk_cell\n", 56 | "from nbdev.doclinks import nbglob\n", 57 | "\n", 58 | "from fastcore.xtras import Path\n", 59 | "\n", 60 | "from fastcore.foundation import AttrDict, L\n", 61 | "from fastcore.script import call_parse" 62 | ] 63 | }, 64 | { 65 | "cell_type": "code", 66 | "execution_count": null, 67 | "metadata": { 68 | "vscode": { 69 | "languageId": "python" 70 | } 71 | }, 72 | "outputs": [], 73 | "source": [ 74 | "#| export\n", 75 | "_default_exp = Template(\"#| default_exp $export\")\n", 76 | "_title = Template(\"# $title\\n\")\n", 77 | "_description = Template(\"> $description\")\n", 78 | "_export = \"#| hide\\nimport nbdev; nbdev.nbdev_export()\"" 79 | ] 80 | }, 81 | { 82 | "cell_type": "code", 83 | "execution_count": null, 84 | "metadata": { 85 | "vscode": { 86 | "languageId": "python" 87 | } 88 | }, 89 | "outputs": [], 90 | "source": [ 91 | "#| export\n", 92 | "def _mk_nb(title,desc,exp=None):\n", 93 | " nb = AttrDict(\n", 94 | " cells=L(),\n", 95 | " metadata={},\n", 96 | " nbformat=4,\n", 97 | " nbformat_minor=5\n", 98 | " )\n", 99 | " if exp is not None: \n", 100 | " nb.cells.append(mk_cell(exp))\n", 101 | " nb.cells.append(mk_cell(title+desc, \"markdown\"))\n", 102 | " nb.cells.append(mk_cell(\"\", outputs=[], execution_count=0))\n", 103 | " if exp is not None:\n", 104 | " nb.cells.append(mk_cell(_export))\n", 105 | " nb.cells = list(nb.cells)\n", 106 | " # return dict(nb)\n", 107 | " return nb" 108 | ] 109 | }, 110 | { 111 | "cell_type": "code", 112 | "execution_count": null, 113 | "metadata": { 114 | "vscode": { 115 | "languageId": "python" 116 | } 117 | }, 118 | "outputs": [], 119 | "source": [ 120 | "#| export\n", 121 | "@call_parse\n", 122 | "def new_nb(\n", 123 | " name:str, # The name of the newly created notebook\n", 124 | " module:str = None, # The name of the exported module it will generate\n", 125 | " title:str = None, # The title header in the notebook\n", 126 | " description:str = None, # The description that will go under the title header\n", 127 | " nprefix:int = None, # if > 0, will be the first number in the filename\n", 128 | " nsuffix:int = None, # If > 0, will be the second number in the filename\n", 129 | "):\n", 130 | " \"Creates a new base nbdev notebook named {nprefix}{nsuffix}_{name}.ipynb\"\n", 131 | " cfg = get_config()\n", 132 | " nbs = nbglob(\n", 133 | " cfg.nbs_path,\n", 134 | " file_glob=\"*.ipynb\",\n", 135 | " file_re=\"^[0-9]\",\n", 136 | " skip_folder_re=\"^[_.]\"\n", 137 | " )\n", 138 | " nbs = nbs.map(\n", 139 | " lambda x: Path(x).name.replace(\".ipynb\",\"\")\n", 140 | " )\n", 141 | " nbs.sort()\n", 142 | " title = _title.substitute(title=title or \"No Title\")\n", 143 | " descrip = _description.substitute(description=description or \"Fill me in!\")\n", 144 | " if module is not None:\n", 145 | " module = _default_exp.substitute(export=module)\n", 146 | " if len(nbs) > 0:\n", 147 | " nums = nbs.map(\n", 148 | " lambda x: list(re.search(\"^[0-9][0-9]?\", x).group(0))\n", 149 | " ).map(lambda x: list(map(int, x)))\n", 150 | " if nprefix is None:\n", 151 | " nprefix = max(o[0] for o in nums)\n", 152 | " if nsuffix is None:\n", 153 | " nsuffix = max(o[1] for o in nums)\n", 154 | " else:\n", 155 | " nprefix, nsuffix = 0,0\n", 156 | " nsuffix += 1\n", 157 | " nbpath = cfg.nbs_path/f'{nprefix}{nsuffix}_{name}.ipynb'\n", 158 | " write_nb(_mk_nb(title, descrip, module), nbpath)" 159 | ] 160 | }, 161 | { 162 | "attachments": {}, 163 | "cell_type": "markdown", 164 | "metadata": {}, 165 | "source": [ 166 | "With `new_nb`, you can very quickly create base template notebooks inside your nbdev repo that are prepared for writing. It will automatically iterate the filename based on the last digit used, and you can name the modules and exports to your need. Now adding a new nbdev module is as simple as a CLI command, and you don't have to worry about writing out all the tedious boilerplate to make it all operate." 167 | ] 168 | }, 169 | { 170 | "cell_type": "code", 171 | "execution_count": null, 172 | "metadata": { 173 | "vscode": { 174 | "languageId": "python" 175 | } 176 | }, 177 | "outputs": [], 178 | "source": [ 179 | "#| hide\n", 180 | "import nbdev; nbdev.nbdev_export()" 181 | ] 182 | } 183 | ], 184 | "metadata": { 185 | "kernelspec": { 186 | "display_name": "Python 3 (ipykernel)", 187 | "language": "python", 188 | "name": "python3" 189 | } 190 | }, 191 | "nbformat": 4, 192 | "nbformat_minor": 4 193 | } 194 | -------------------------------------------------------------------------------- /nbs/02_tagmaker.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": null, 6 | "id": "1f17fb0c-414e-4e23-b54c-597a44e620ba", 7 | "metadata": {}, 8 | "outputs": [], 9 | "source": [ 10 | "#| default_exp tagmaker" 11 | ] 12 | }, 13 | { 14 | "cell_type": "markdown", 15 | "id": "bac27fca", 16 | "metadata": {}, 17 | "source": [ 18 | "# Tag Maker\n", 19 | "> Processor to quickly write ::: tags as comments" 20 | ] 21 | }, 22 | { 23 | "cell_type": "markdown", 24 | "id": "76ed79ac-0f60-46b9-ade0-667e21c8edef", 25 | "metadata": {}, 26 | "source": [ 27 | "## Inspiration\n", 28 | "\n", 29 | "As I was writing my new course, I found that having to do two sets of `:::` and something to put in between two `{}` annoying, so this is a quick processor to do that for me as a tag" 30 | ] 31 | }, 32 | { 33 | "cell_type": "code", 34 | "execution_count": null, 35 | "id": "b20b5cab-502f-4717-9e69-695e7e645b63", 36 | "metadata": {}, 37 | "outputs": [], 38 | "source": [ 39 | "#| export\n", 40 | "from nbdev.config import get_config\n", 41 | "from nbdev.process import extract_directives\n", 42 | "from nbdev.processors import Processor\n", 43 | "from nbdev.export import nb_export\n", 44 | "from nbdev.doclinks import nbglob\n", 45 | "from nbdev.sync import write_nb\n", 46 | "\n", 47 | "from fastcore.basics import listify\n", 48 | "from fastcore.script import call_parse\n", 49 | "from fastcore.xtras import Path\n", 50 | "\n", 51 | "from string import Template" 52 | ] 53 | }, 54 | { 55 | "cell_type": "code", 56 | "execution_count": null, 57 | "id": "a01d6a1a-4a33-49bf-bd71-d01c7c2885c6", 58 | "metadata": {}, 59 | "outputs": [], 60 | "source": [ 61 | "#| hide\n", 62 | "from fastcore.test import test_eq" 63 | ] 64 | }, 65 | { 66 | "cell_type": "code", 67 | "execution_count": null, 68 | "id": "666b941f-2886-41e0-9349-8163cb01f704", 69 | "metadata": {}, 70 | "outputs": [], 71 | "source": [ 72 | "#| export\n", 73 | "_LAYOUT_STR = Template(\"::: {$layout}\\n$content\\n\")\n", 74 | "_shortcuts = {\n", 75 | " \"margin\": \".column-margin\"\n", 76 | "}" 77 | ] 78 | }, 79 | { 80 | "cell_type": "code", 81 | "execution_count": null, 82 | "id": "0c421816-466e-44fd-a326-6e90898b48eb", 83 | "metadata": {}, 84 | "outputs": [], 85 | "source": [ 86 | "#| export\n", 87 | "def convert_layout(cell, layout, start=False):\n", 88 | " \"Parses cell formatted with ::: {$something}, and potentially :::\"\n", 89 | " layout = listify(layout)\n", 90 | " content = cell.source\n", 91 | " code = cell.source.splitlines(True)\n", 92 | " if \"end\" in code[0]:\n", 93 | " if len(code) == 1:\n", 94 | " cell.source = \":::\"\n", 95 | " else:\n", 96 | " cell.source += \":::\"\n", 97 | " else:\n", 98 | " cell.source = _LAYOUT_STR.substitute(\n", 99 | " layout=\" \".join(layout),\n", 100 | " content=content\n", 101 | " )\n", 102 | " if not start:\n", 103 | " cell.source += \":::\"" 104 | ] 105 | }, 106 | { 107 | "cell_type": "code", 108 | "execution_count": null, 109 | "id": "69a04e61-1259-4bbc-bac5-90ac3f011196", 110 | "metadata": {}, 111 | "outputs": [], 112 | "source": [ 113 | "#| hide\n", 114 | "from nbdev.processors import mk_cell, read_nb" 115 | ] 116 | }, 117 | { 118 | "cell_type": "code", 119 | "execution_count": null, 120 | "id": "e7547846-2c4e-4887-9006-eaa89c6d49ed", 121 | "metadata": {}, 122 | "outputs": [], 123 | "source": [ 124 | "#| hide\n", 125 | "cell = mk_cell(\"\"\"#| div .column-margin\n", 126 | "A test\"\"\", \"markdown\")\n", 127 | "cell.directives_ = extract_directives(cell, \"#\")\n", 128 | "convert_layout(cell, cell.directives_[\"div\"][0])\n", 129 | "test_eq(cell.source, \"\"\"::: {.column-margin}\n", 130 | "A test\n", 131 | ":::\"\"\")\n", 132 | "\n", 133 | "cell = mk_cell(\"\"\"#| div end\"\"\", \"markdown\")\n", 134 | "cell.directives_ = extract_directives(cell, \"#\")\n", 135 | "convert_layout(cell, cell.directives_[\"div\"][0])\n", 136 | "test_eq(cell.source, \"\"\":::\"\"\")" 137 | ] 138 | }, 139 | { 140 | "cell_type": "code", 141 | "execution_count": null, 142 | "id": "8876e7d7-ffb8-4fce-aa37-6fe930094cc8", 143 | "metadata": {}, 144 | "outputs": [], 145 | "source": [ 146 | "#| hide\n", 147 | "cell = mk_cell(\"\"\"#| div margin\n", 148 | "A test\"\"\", \"markdown\")\n", 149 | "cell.directives_ = extract_directives(cell, \"#\")" 150 | ] 151 | }, 152 | { 153 | "cell_type": "code", 154 | "execution_count": null, 155 | "id": "85bfa094-0d3a-4e6a-8dfe-c5f954d1ca99", 156 | "metadata": {}, 157 | "outputs": [], 158 | "source": [ 159 | "#| export\n", 160 | "def convert_shortcuts(cell):\n", 161 | " for i,directive in enumerate(cell.directives_[\"div\"]):\n", 162 | " if directive in _shortcuts.keys():\n", 163 | " cell.directives_[\"div\"][i] = _shortcuts[directive]" 164 | ] 165 | }, 166 | { 167 | "cell_type": "code", 168 | "execution_count": null, 169 | "id": "0ed59f24-edb7-4abf-ba1f-601c00a836a9", 170 | "metadata": {}, 171 | "outputs": [], 172 | "source": [ 173 | "#| hide\n", 174 | "convert_shortcuts(cell)\n", 175 | "convert_layout(cell, cell.directives_[\"div\"][0])\n", 176 | "test_eq(cell.source, \"\"\"::: {.column-margin}\n", 177 | "A test\n", 178 | ":::\"\"\")" 179 | ] 180 | }, 181 | { 182 | "cell_type": "code", 183 | "execution_count": null, 184 | "id": "8ae5d4eb-d63e-4cd1-a86d-f159e1fbd108", 185 | "metadata": {}, 186 | "outputs": [], 187 | "source": [ 188 | "#| export\n", 189 | "import re\n", 190 | "class LayoutProc(Processor):\n", 191 | " \"\"\"A proc that will automatically change #| css format\n", 192 | " to ::: {format} ... :::\n", 193 | " \"\"\"\n", 194 | " has_partial = False\n", 195 | " def cell(self, cell):\n", 196 | " if cell.cell_type == \"markdown\" and \"div\" in cell.directives_:\n", 197 | " convert_shortcuts(cell)\n", 198 | " directives_ = cell.directives_[\"div\"]\n", 199 | " if self.has_partial and \"end\" in directives_:\n", 200 | " convert_layout(cell, directives_)\n", 201 | " self.has_partial = False\n", 202 | " else:\n", 203 | " if directives_[-1] == \"start\":\n", 204 | " self.has_partial = True\n", 205 | " directives_.remove(\"start\")\n", 206 | " convert_layout(cell, directives_, True)\n", 207 | " else:\n", 208 | " convert_layout(cell, directives_)" 209 | ] 210 | }, 211 | { 212 | "cell_type": "code", 213 | "execution_count": null, 214 | "id": "d61f048c-8d72-4705-be71-17c58ef00d8a", 215 | "metadata": {}, 216 | "outputs": [], 217 | "source": [ 218 | "#| hide\n", 219 | "from nbdev.process import NBProcessor, dict2nb" 220 | ] 221 | }, 222 | { 223 | "cell_type": "code", 224 | "execution_count": null, 225 | "id": "67de4ad9-2057-47a3-b829-dc6672e3f46b", 226 | "metadata": {}, 227 | "outputs": [], 228 | "source": [ 229 | "#| hide\n", 230 | "nb = {\n", 231 | " \"cells\":[\n", 232 | " mk_cell(\"\"\"#| div .column-margin\n", 233 | "A test\"\"\", \"markdown\"),\n", 234 | " mk_cell(\"\"\"#| div .column-margin start\n", 235 | "A test\"\"\", \"markdown\"),\n", 236 | " mk_cell(\"\"\"#| div end\"\"\", \"markdown\"),\n", 237 | " mk_cell(\"\"\"#| div margin\n", 238 | "A test\"\"\", \"markdown\"),\n", 239 | "]}\n", 240 | "processor = NBProcessor(procs=LayoutProc, nb=dict2nb(nb))\n", 241 | "processor.process()\n", 242 | "test_eq(processor.nb.cells[0].source, \"::: {.column-margin}\\nA test\\n:::\")\n", 243 | "test_eq(processor.nb.cells[1].source, \"::: {.column-margin}\\nA test\\n\")\n", 244 | "test_eq(processor.nb.cells[2].source, \":::\")\n", 245 | "test_eq(processor.nb.cells[3].source, \"::: {.column-margin}\\nA test\\n:::\")" 246 | ] 247 | }, 248 | { 249 | "cell_type": "markdown", 250 | "id": "d45303d7-59e9-462f-bb3c-c55cf5b68c9b", 251 | "metadata": {}, 252 | "source": [ 253 | "An example usage of this proc is writing something such as (just the content):" 254 | ] 255 | }, 256 | { 257 | "cell_type": "code", 258 | "execution_count": null, 259 | "id": "d90e5691-bc3d-4824-9b82-cda0abb93905", 260 | "metadata": {}, 261 | "outputs": [], 262 | "source": [ 263 | "\"\"\"\n", 264 | "#| layout .column-margin\n", 265 | "Some test stuff!\n", 266 | "\"\"\";" 267 | ] 268 | }, 269 | { 270 | "cell_type": "markdown", 271 | "id": "77034738-4626-4294-8bf5-582e428437cf", 272 | "metadata": {}, 273 | "source": [ 274 | "In a markdown cell and then running the processor" 275 | ] 276 | }, 277 | { 278 | "cell_type": "markdown", 279 | "id": "7fd0651d-2d1c-4d41-a3b0-beb2be8f293a", 280 | "metadata": {}, 281 | "source": [ 282 | "#| layout .column-margin\n", 283 | "Some test stuff!" 284 | ] 285 | }, 286 | { 287 | "cell_type": "markdown", 288 | "id": "6c0c8271-837b-4f89-82aa-71c0ee509cb0", 289 | "metadata": {}, 290 | "source": [ 291 | "Or you can split it up into multiple cells by dictating `start` and `end`:" 292 | ] 293 | }, 294 | { 295 | "cell_type": "code", 296 | "execution_count": null, 297 | "id": "8c14fcf1-d45f-4eab-aafa-09b49bcd5695", 298 | "metadata": {}, 299 | "outputs": [], 300 | "source": [ 301 | "\"\"\"\n", 302 | "#| layout .column-margin start\n", 303 | "Some test stuff!\n", 304 | "\"\"\";" 305 | ] 306 | }, 307 | { 308 | "cell_type": "code", 309 | "execution_count": null, 310 | "id": "e717d661-60df-4281-88cb-a5e066fea68c", 311 | "metadata": {}, 312 | "outputs": [], 313 | "source": [ 314 | "\"\"\"\n", 315 | "#| layout end\n", 316 | "\"\"\";" 317 | ] 318 | }, 319 | { 320 | "cell_type": "markdown", 321 | "id": "65fa3a75-4a57-4fc6-b0aa-896e1c110f4f", 322 | "metadata": {}, 323 | "source": [ 324 | "#| layout .column-margin start\n", 325 | "Some test stuff!" 326 | ] 327 | }, 328 | { 329 | "cell_type": "markdown", 330 | "id": "63b0788e-fad1-4f8b-89ba-cf3175e13e09", 331 | "metadata": {}, 332 | "source": [ 333 | "#| layout .column-margin end" 334 | ] 335 | } 336 | ], 337 | "metadata": { 338 | "kernelspec": { 339 | "display_name": "Python 3 (ipykernel)", 340 | "language": "python", 341 | "name": "python3" 342 | } 343 | }, 344 | "nbformat": 4, 345 | "nbformat_minor": 5 346 | } 347 | -------------------------------------------------------------------------------- /nbs/03_codetips.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": null, 6 | "id": "39701488", 7 | "metadata": {}, 8 | "outputs": [], 9 | "source": [ 10 | "#| default_exp codetips" 11 | ] 12 | }, 13 | { 14 | "cell_type": "markdown", 15 | "id": "c771cd07", 16 | "metadata": {}, 17 | "source": [ 18 | "# Code Tips\n", 19 | "> Pipeline for annotating code cells with notes" 20 | ] 21 | }, 22 | { 23 | "cell_type": "markdown", 24 | "id": "eb612eb2-1c5c-4714-a171-a780a4dbf4b1", 25 | "metadata": {}, 26 | "source": [ 27 | "Code Tips operate the same way as Code Notes however they show up as tooltips instead and use the `tip` tag instead of the `explain`. Note that it also uses multiline CodeNotes by default so you need a start and an end. \n", 28 | "\n", 29 | "To use this make sure that you add in `hint.css` and `tips.css` to the `_quarto.yml` under the `css` section!" 30 | ] 31 | }, 32 | { 33 | "cell_type": "code", 34 | "execution_count": null, 35 | "id": "bc07ae91-34e2-48c4-8f60-0ca5fccdc28e", 36 | "metadata": {}, 37 | "outputs": [], 38 | "source": [ 39 | "#| export\n", 40 | "from nbdev.config import get_config\n", 41 | "from nbdev.process import NBProcessor, extract_directives\n", 42 | "from nbdev.processors import Processor, mk_cell\n", 43 | "from nbdev.export import nb_export\n", 44 | "from nbdev.doclinks import nbglob\n", 45 | "from nbdev.sync import write_nb\n", 46 | "\n", 47 | "from fastcore.script import call_parse\n", 48 | "from fastcore.xtras import Path\n", 49 | "\n", 50 | "import shlex\n", 51 | "import requests\n", 52 | "import re" 53 | ] 54 | }, 55 | { 56 | "cell_type": "code", 57 | "execution_count": null, 58 | "id": "323294dd-94d1-45c0-bd51-b40fcd50a6bd", 59 | "metadata": {}, 60 | "outputs": [], 61 | "source": [ 62 | "from fastcore.test import test_eq" 63 | ] 64 | }, 65 | { 66 | "cell_type": "code", 67 | "execution_count": null, 68 | "id": "3a2e2ef7-8a64-41f7-b66d-023240b4d4bf", 69 | "metadata": {}, 70 | "outputs": [], 71 | "source": [ 72 | "#| export\n", 73 | "HINT_CSS_URL = \"https://raw.githubusercontent.com/muellerzr/til/master/nbs/hint.css\"" 74 | ] 75 | }, 76 | { 77 | "cell_type": "code", 78 | "execution_count": null, 79 | "id": "97f623be-450b-4026-89f8-478444abcf5c", 80 | "metadata": {}, 81 | "outputs": [], 82 | "source": [ 83 | "#| export\n", 84 | "TIPS_CSS = \"\"\".nogap {\n", 85 | " padding: 0px;\n", 86 | " border-radius: 0px !important;\n", 87 | " outline: 0px 0px;\n", 88 | " margin-bottom: 0px !important;\n", 89 | "}\n", 90 | "\n", 91 | ".code-with-filename .code-with-filename-file {\n", 92 | " margin: 0px;\n", 93 | "}\n", 94 | "div.sourceCode {\n", 95 | " border: 0px;\n", 96 | " margin: 0px;\n", 97 | "}\n", 98 | "\n", 99 | "pre > code.sourceCode {\n", 100 | " white-space: pre;\n", 101 | " text-decoration: none;\n", 102 | "}\n", 103 | "\n", 104 | ".nogap > div.sourceCode > pre.sourceCode {\n", 105 | " line-height: 0px;\n", 106 | " padding-bottom: 0px;\n", 107 | " padding-top: 0px;\n", 108 | " margin-bottom: 0px;\n", 109 | " margin-top: 0px;\n", 110 | "}\"\"\"" 111 | ] 112 | }, 113 | { 114 | "cell_type": "code", 115 | "execution_count": null, 116 | "id": "97171693-25e6-45b5-999d-7134505b16e2", 117 | "metadata": {}, 118 | "outputs": [], 119 | "source": [ 120 | "#| export\n", 121 | "def download_tooltip_css():\n", 122 | " config = get_config()\n", 123 | " css_path = config.nbs_path/\"hint.css\"\n", 124 | " if not css_path.exists():\n", 125 | " response = requests.get(HTML_CSS_URL)\n", 126 | " css_path.write_bytes(response.content)\n", 127 | " (config.nbs_path/\"codetips.css\").write_text(TIPS_CSS)\n", 128 | " print(f'Added custom css files. Please add `codetips.css` and `hint.css` to `_quarto.yml` under `format -> html -> css`')" 129 | ] 130 | }, 131 | { 132 | "cell_type": "code", 133 | "execution_count": null, 134 | "id": "e02dc8db-8cc4-4b8c-a2e4-59613505da0f", 135 | "metadata": {}, 136 | "outputs": [], 137 | "source": [ 138 | "#| export\n", 139 | "def write_tooltip_directives(\n", 140 | " # The tooltip text\n", 141 | " explanation: str,\n", 142 | " # A list of css directives to modify the tooltip\n", 143 | " hint_directives:list = [\"rounded\", \"medium\", \"right\"],\n", 144 | " # An optional filename to be rendered \n", 145 | " filename:str = None,\n", 146 | "):\n", 147 | " \"Creates a tooltip in style of `hint_directives` with content `explanation`\"\n", 148 | " hint_directives = [f\".hint--{hint} \" for hint in hint_directives]\n", 149 | " hint_directives[-1] = hint_directives[-1].rstrip() # for formatting\n", 150 | " tooltip = f'''#| classes: .nogap {\"\".join(hint_directives)}\n", 151 | "#| aria-label: \"{explanation}\"\n", 152 | "#|eval: false'''\n", 153 | " if filename is not None:\n", 154 | " tooltip += f'\\n#| filename: \"{filename}\"'\n", 155 | " return tooltip + \"\\n\"" 156 | ] 157 | }, 158 | { 159 | "cell_type": "code", 160 | "execution_count": null, 161 | "id": "3787cd73-e5a3-4b8c-8117-7d155a95c907", 162 | "metadata": {}, 163 | "outputs": [], 164 | "source": [ 165 | "#| export\n", 166 | "def convert_explanation(explanation_cell, source):\n", 167 | " \"Takes an explanation and source code and linkes them together in a new cell\"\n", 168 | " filename = explanation_cell.directives_.pop(\"filename:\", [None])[0]\n", 169 | " explanation = re.sub(r'\\*#|.*[\\n]', \"\", explanation_cell.source)\n", 170 | " content = write_tooltip_directives(explanation, filename=filename)\n", 171 | " content += source\n", 172 | " return mk_cell(content, cell_type=\"code\")" 173 | ] 174 | }, 175 | { 176 | "cell_type": "code", 177 | "execution_count": null, 178 | "id": "7152a725-4668-48f7-a6d0-e0f6b03db5a8", 179 | "metadata": {}, 180 | "outputs": [], 181 | "source": [ 182 | "#| export\n", 183 | "def extract_code(start_code, end_code, source, instance_num, end_instance_num=0):\n", 184 | " \"Finds code between start and finish potentially with instances to check\"\n", 185 | " start_match = list(re.finditer(f'[ \\t]*{start_code}', source))[int(instance_num)]\n", 186 | " start_char = start_match.span()[0]\n", 187 | " end_match = list(re.finditer(f'[ \\t]*{end_code}', source))[int(end_instance_num)]\n", 188 | " end_char = end_match.span()[1]\n", 189 | " return source[start_char:end_char], start_char, end_char" 190 | ] 191 | }, 192 | { 193 | "cell_type": "code", 194 | "execution_count": null, 195 | "id": "60ac3192-71b8-4893-bef8-deefbef3f406", 196 | "metadata": {}, 197 | "outputs": [], 198 | "source": [ 199 | "#| export\n", 200 | "def parse_code(code_cell, markdown_cell):\n", 201 | " \"Parses directives to extract the code needed to be highlighted\"\n", 202 | " directives = markdown_cell.directives_[\"tip\"]\n", 203 | " directives = shlex.split(\" \".join(directives))\n", 204 | " if len(directives) == 4:\n", 205 | " start_code, start_instance_num, end_code, end_instance_num = directives\n", 206 | " else:\n", 207 | " (start_code, start_instance_num, end_code), (end_instance_num) = directives, 0\n", 208 | " start_code, end_code = re.escape(start_code), re.escape(end_code)\n", 209 | " return extract_code(start_code, end_code, code_cell.source, start_instance_num, end_instance_num)" 210 | ] 211 | }, 212 | { 213 | "cell_type": "code", 214 | "execution_count": null, 215 | "id": "67409249-5534-49f4-b3e8-7d75e5f6a9c9", 216 | "metadata": {}, 217 | "outputs": [], 218 | "source": [ 219 | "#| export\n", 220 | "class TipExportProc(Processor):\n", 221 | " \"A proc that checks and reorganizes cells for documentation for proper explainations\"\n", 222 | " offset = 0\n", 223 | " steps = []\n", 224 | " _i = 0\n", 225 | " def begin(self):\n", 226 | " self.reset()\n", 227 | " self.has_reset = False\n", 228 | " self.iter = 0\n", 229 | " self.offset = 0\n", 230 | " \n", 231 | " def reset(self):\n", 232 | " self.results = [mk_cell(\"::: {layout-ncol=1}\", cell_type=\"markdown\")] \n", 233 | " self.code = []\n", 234 | " self._code = None\n", 235 | " self.found_explanation = False\n", 236 | " self.end_link = False\n", 237 | " self.explanations = []\n", 238 | " self.start_idx = None\n", 239 | " self.end_idx = None\n", 240 | " self.indexes = []\n", 241 | " \n", 242 | " def cell(self, cell):\n", 243 | " if cell.cell_type == \"code\":\n", 244 | " if not self.found_explanation:\n", 245 | " self._code = cell\n", 246 | " self.start_idx = cell.idx_\n", 247 | " \n", 248 | " if cell.cell_type == \"markdown\" and \"tip\" in cell.directives_:\n", 249 | " self.found_explanation = True\n", 250 | " self.explanations.append(cell)\n", 251 | " \n", 252 | " if self.found_explanation:\n", 253 | " idx = cell.idx_ + 1\n", 254 | " if (len(self.nb.cells) <= idx+1) or (\"tip\" not in self.nb.cells[idx].directives_):\n", 255 | " self.end_link = True\n", 256 | " self.end_idx = cell.idx_ + 1\n", 257 | " \n", 258 | " if self.found_explanation and self.end_link:\n", 259 | " # Assume we have all code + explainations\n", 260 | " explanations = [self._code]\n", 261 | " for i,explanation in enumerate(self.explanations):\n", 262 | " source, start, end = parse_code(self._code, explanation)\n", 263 | " self.indexes += [(start,end)]\n", 264 | " converted_explanation = convert_explanation(explanation, source)\n", 265 | " self.results.append(converted_explanation)\n", 266 | " self.nb.cells.remove(explanation)\n", 267 | " second_idxs = list(self.indexes)\n", 268 | " second_idxs.sort()\n", 269 | " offset = 0\n", 270 | " for idx, rng in enumerate(second_idxs):\n", 271 | " if rng != second_idxs[-1]:\n", 272 | " if second_idxs[idx+1][0] - rng[-1] != 1:\n", 273 | " start = rng[-1]\n", 274 | " end = second_idxs[idx+1][0]\n", 275 | " new_src = self._code.source[start:end]\n", 276 | " if new_src != '':\n", 277 | " new_src = f'#| classes: .nogap\\n#|eval: false\\n{new_src}'\n", 278 | " self.results.insert(self.indexes.index(rng)+2, mk_cell(new_src, cell_type=\"code\"))\n", 279 | " offset += 1\n", 280 | " self.results.append(mk_cell(\":::\", cell_type=\"markdown\"))\n", 281 | " self.nb.cells.remove(self._code)\n", 282 | " self.offset = 0\n", 283 | " for result in self.results:\n", 284 | " result.idx_ = self.nb.cells[self.start_idx - 1].idx_ + 1\n", 285 | " self.nb.cells.insert(self.start_idx + self.offset, result)\n", 286 | " self.offset += 1\n", 287 | " self.iter += 1\n", 288 | " self.reset()\n", 289 | " self.has_reset = True\n", 290 | " \n", 291 | " self.offset = 0\n", 292 | " for i,c in enumerate(self.nb.cells): c.idx_ = i" 293 | ] 294 | }, 295 | { 296 | "cell_type": "code", 297 | "execution_count": null, 298 | "id": "a471c74d-9043-42fc-897f-4a6c0c38cb31", 299 | "metadata": {}, 300 | "outputs": [], 301 | "source": [ 302 | "#| export\n", 303 | "@call_parse\n", 304 | "def parse_notes():\n", 305 | " \"Exports notebooks to parsed notes for documentation. Should be called in the workflow, not yourself!\"\n", 306 | " for nb in nbglob(get_config().nbs_path):\n", 307 | " processor = NBProcessor(nb, [NoteExportProc], rm_directives=False)\n", 308 | " processor.process()\n", 309 | " write_nb(processor.nb, nb)" 310 | ] 311 | }, 312 | { 313 | "cell_type": "code", 314 | "execution_count": null, 315 | "id": "89eee302-cc23-49c8-979d-395e3e2800f8", 316 | "metadata": {}, 317 | "outputs": [], 318 | "source": [ 319 | "processor = NBProcessor(\"test.ipynb\", [TipExportProc], rm_directives=False)\n", 320 | "processor.process()" 321 | ] 322 | }, 323 | { 324 | "cell_type": "code", 325 | "execution_count": null, 326 | "id": "42b03617-fba5-4335-b0e0-66b7230f9d23", 327 | "metadata": {}, 328 | "outputs": [], 329 | "source": [ 330 | "write_nb(processor.nb, \"result.ipynb\")" 331 | ] 332 | }, 333 | { 334 | "cell_type": "markdown", 335 | "id": "4eebd049-4b05-4ca9-a0c6-7a785c168166", 336 | "metadata": {}, 337 | "source": [ 338 | "To use this, add `nbdev-extensions.codetips:TipExportProc` to your `settings.ini` and add the required css files to your `_quarto.yml`" 339 | ] 340 | }, 341 | { 342 | "cell_type": "markdown", 343 | "id": "93de89a6-7e16-4f16-a554-7ef724797f8e", 344 | "metadata": {}, 345 | "source": [ 346 | "Now it will automatically build your docs like notes!" 347 | ] 348 | }, 349 | { 350 | "cell_type": "code", 351 | "execution_count": null, 352 | "id": "f8609505", 353 | "metadata": {}, 354 | "outputs": [], 355 | "source": [ 356 | "def addition(a,b):\n", 357 | " \"Adds two numbers together\"\n", 358 | " return a+b" 359 | ] 360 | }, 361 | { 362 | "cell_type": "markdown", 363 | "id": "3bc72a9c", 364 | "metadata": {}, 365 | "source": [ 366 | "#| tip a+ 0 b\n", 367 | "\n", 368 | "We return the sum of `a` and `b`" 369 | ] 370 | }, 371 | { 372 | "cell_type": "markdown", 373 | "id": "f11ea369-0207-4c89-b807-0f3aca78caa4", 374 | "metadata": {}, 375 | "source": [ 376 | "#| tip return 0 a+b\n", 377 | "\n", 378 | "Return something" 379 | ] 380 | }, 381 | { 382 | "cell_type": "code", 383 | "execution_count": null, 384 | "id": "4eb7b3a8", 385 | "metadata": {}, 386 | "outputs": [], 387 | "source": [ 388 | "#| hide\n", 389 | "import nbdev; nbdev.nbdev_export()" 390 | ] 391 | }, 392 | { 393 | "cell_type": "code", 394 | "execution_count": null, 395 | "id": "b6b30d09-efa7-40b6-9dd1-6584ac95d370", 396 | "metadata": {}, 397 | "outputs": [], 398 | "source": [] 399 | } 400 | ], 401 | "metadata": { 402 | "kernelspec": { 403 | "display_name": "Python 3 (ipykernel)", 404 | "language": "python", 405 | "name": "python3" 406 | } 407 | }, 408 | "nbformat": 4, 409 | "nbformat_minor": 5 410 | } 411 | -------------------------------------------------------------------------------- /nbs/04_strip.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": null, 6 | "id": "55a389a9-9444-4947-8df9-45d51e7e325a", 7 | "metadata": {}, 8 | "outputs": [], 9 | "source": [ 10 | "#| default_exp strip" 11 | ] 12 | }, 13 | { 14 | "cell_type": "markdown", 15 | "id": "e8ecadca-f4fb-433d-9009-5d7c608216dd", 16 | "metadata": {}, 17 | "source": [ 18 | "# Strip notebooks of all data\n", 19 | "> A short function to strip everything but code from a Jupyter Notebook" 20 | ] 21 | }, 22 | { 23 | "cell_type": "code", 24 | "execution_count": null, 25 | "id": "56971ef9-8152-408e-a1bb-6795e17f4772", 26 | "metadata": {}, 27 | "outputs": [], 28 | "source": [ 29 | "#| export\n", 30 | "from nbdev.config import get_config\n", 31 | "from nbdev.processors import read_nb\n", 32 | "from nbdev.export import nb_export\n", 33 | "from nbdev.doclinks import nbglob\n", 34 | "from nbdev.sync import write_nb\n", 35 | "from fastcore.basics import AttrDict\n", 36 | "from fastcore.script import call_parse\n", 37 | "from fastcore.xtras import Path" 38 | ] 39 | }, 40 | { 41 | "cell_type": "code", 42 | "execution_count": null, 43 | "id": "c50f12b7-6c5d-404d-a176-70953b05c38d", 44 | "metadata": {}, 45 | "outputs": [], 46 | "source": [ 47 | "#| hide\n", 48 | "from fastcore.test import test_eq" 49 | ] 50 | }, 51 | { 52 | "cell_type": "code", 53 | "execution_count": null, 54 | "id": "a4c48337-cd9d-44c8-bb83-25334f249758", 55 | "metadata": {}, 56 | "outputs": [], 57 | "source": [ 58 | "#| hide\n", 59 | "from nbdev.processors import mk_cell" 60 | ] 61 | }, 62 | { 63 | "cell_type": "code", 64 | "execution_count": null, 65 | "id": "5dd5c941-c166-4891-b912-1ca115134336", 66 | "metadata": {}, 67 | "outputs": [], 68 | "source": [ 69 | "#| export\n", 70 | "@call_parse\n", 71 | "def strip_nbs(\n", 72 | " notebook_path:str,\n", 73 | " output_folder:str\n", 74 | "):\n", 75 | " \"Removes all non-code cells from `notebook_path` and saves it in `output_folder`\"\n", 76 | " if not Path(output_folder).exists():\n", 77 | " Path(output_folder).mkdir(parents=True, exist_ok=True)\n", 78 | " for path in Path(notebook_path).ls(file_exts=\".ipynb\"):\n", 79 | " nb = read_nb(path)\n", 80 | " cells = []\n", 81 | " for cell in nb[\"cells\"]:\n", 82 | " if cell[\"cell_type\"] == \"code\":\n", 83 | " cell.source = ''.join([line.split(\" #\")[0] for line in cell.source])\n", 84 | " cells.append(cell)\n", 85 | " new_nb = AttrDict(\n", 86 | " cells=cells,\n", 87 | " metadata={},\n", 88 | " nbformat=4,\n", 89 | " nbformat_minor=5\n", 90 | " )\n", 91 | " write_nb(new_nb, Path(output_folder)/path.name)" 92 | ] 93 | }, 94 | { 95 | "cell_type": "code", 96 | "execution_count": null, 97 | "id": "606b348f-9c9c-439d-b474-b64a41a7fcdc", 98 | "metadata": {}, 99 | "outputs": [], 100 | "source": [] 101 | } 102 | ], 103 | "metadata": { 104 | "kernelspec": { 105 | "display_name": "Python 3 (ipykernel)", 106 | "language": "python", 107 | "name": "python3" 108 | } 109 | }, 110 | "nbformat": 4, 111 | "nbformat_minor": 5 112 | } 113 | -------------------------------------------------------------------------------- /nbs/_quarto.yml: -------------------------------------------------------------------------------- 1 | project: 2 | type: website 3 | 4 | format: 5 | html: 6 | theme: cosmo 7 | css: styles.css 8 | toc: true 9 | 10 | website: 11 | twitter-card: true 12 | open-graph: true 13 | repo-actions: [issue] 14 | navbar: 15 | background: primary 16 | search: true 17 | sidebar: 18 | style: floating 19 | 20 | metadata-files: [nbdev.yml, sidebar.yml] -------------------------------------------------------------------------------- /nbs/index.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": null, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "#| hide\n", 10 | "from nbdev_extensions.mknb import new_nb" 11 | ] 12 | }, 13 | { 14 | "cell_type": "markdown", 15 | "metadata": {}, 16 | "source": [ 17 | "# nbdev-extensions\n", 18 | "\n", 19 | "> A collection of useful extensions for nbdev I've thought of" 20 | ] 21 | }, 22 | { 23 | "cell_type": "markdown", 24 | "metadata": {}, 25 | "source": [ 26 | "These extensions will have niche use cases in some places, however these are ones where I find a benefit in having them at least once. Also known as, cool ideas myself or others have considered with nbdev brought to life" 27 | ] 28 | }, 29 | { 30 | "cell_type": "markdown", 31 | "metadata": {}, 32 | "source": [ 33 | "## Install" 34 | ] 35 | }, 36 | { 37 | "cell_type": "markdown", 38 | "metadata": {}, 39 | "source": [ 40 | "```sh\n", 41 | "pip install nbdev-extensions\n", 42 | "```" 43 | ] 44 | }, 45 | { 46 | "cell_type": "markdown", 47 | "metadata": {}, 48 | "source": [ 49 | "## How to use" 50 | ] 51 | }, 52 | { 53 | "cell_type": "markdown", 54 | "metadata": {}, 55 | "source": [ 56 | "To enable any of these extensions, in your settings.ini make sure to:\n", 57 | "\n", 58 | "1. Add `nbdev-extensions` as a requirement\n", 59 | "2. Add `procs = nbdev_extensions.codenotes:NoteExportProc`, where it should point to the exact function being called" 60 | ] 61 | }, 62 | { 63 | "cell_type": "markdown", 64 | "metadata": {}, 65 | "source": [ 66 | "## Features" 67 | ] 68 | }, 69 | { 70 | "cell_type": "markdown", 71 | "metadata": {}, 72 | "source": [ 73 | "`nbdev-extensions` currently has the following features:\n", 74 | "\n", 75 | "- `new_nb` - A CLI/functional interface to quickly generate blank template notebooks for nbdev development with all of the necessary boilerplate cells prefilled based on the passed parameters.\n", 76 | "\n", 77 | "- [Code Notes](/codenotes) - A note-taking annotation tool utilizing nbdev to write quick comments and explanations for sections of code in a code cell without cluttering the code cell with comments. These show up as panels in the rendered documentation, one with just the source code and the other with the source and an explanation\n", 78 | "\n", 79 | "- [Tag Maker](/tagmaker) - A quick way to annotate `::: {something} ... :::` by writing it as a directive (`#| layout something`)" 80 | ] 81 | }, 82 | { 83 | "cell_type": "code", 84 | "execution_count": null, 85 | "metadata": {}, 86 | "outputs": [], 87 | "source": [] 88 | } 89 | ], 90 | "metadata": { 91 | "kernelspec": { 92 | "display_name": "Python 3 (ipykernel)", 93 | "language": "python", 94 | "name": "python3" 95 | } 96 | }, 97 | "nbformat": 4, 98 | "nbformat_minor": 4 99 | } 100 | -------------------------------------------------------------------------------- /nbs/nbdev.yml: -------------------------------------------------------------------------------- 1 | project: 2 | output-dir: _docs 3 | 4 | website: 5 | title: "nbdev-extensions" 6 | site-url: "https://muellerzr.github.io/nbdev-extensions/" 7 | description: "Cool nbdev extensions I've thought of" 8 | repo-branch: main 9 | repo-url: "https://github.com/muellerzr/nbdev-extensions/" 10 | -------------------------------------------------------------------------------- /nbs/sidebar.yml: -------------------------------------------------------------------------------- 1 | website: 2 | sidebar: 3 | contents: 4 | - index.ipynb 5 | - 00_mknb.ipynb 6 | - 01_codenotes.ipynb 7 | - 02_tagmaker.ipynb 8 | - 03_codetips.ipynb 9 | -------------------------------------------------------------------------------- /settings.ini: -------------------------------------------------------------------------------- 1 | [DEFAULT] 2 | # All sections below are required unless otherwise specified 3 | # see https://github.com/fastai/nbdev/blob/master/settings.ini for examples 4 | 5 | ### Python Library ### 6 | lib_name = nbdev_extensions 7 | min_python = 3.7 8 | version = 0.1.0 9 | 10 | ### OPTIONAL ### 11 | 12 | # dev_requirements = 13 | requirements = 14 | nbdev>=2.0.0,<3 15 | requests 16 | 17 | console_scripts = 18 | new_nb=nbdev_extensions.mknb:new_nb 19 | parse_notes=nbdev_extensions.codenotes:parse_notes 20 | strip_nbs=nbdev_extensions.strip:strip_nbs 21 | 22 | ### nbdev ### 23 | nbs_path = nbs 24 | doc_path = _docs 25 | recursive = False 26 | tst_flags = notest 27 | procs = 28 | nbdev_extensions.codenotes:NoteExportProc 29 | nbdev_extensions.codetips:TipExportProc 30 | nbdev_extensions.tagmaker:LayoutProc 31 | 32 | ### Documentation ### 33 | host = github 34 | repo = nbdev-extensions 35 | branch = main 36 | custom_sidebar = False 37 | custom_quarto_yml = False 38 | 39 | ### PyPI ### 40 | audience = Developers 41 | author = Zachary Mueller 42 | author_email = muellerzr@gmail.com 43 | copyright = Zachary Mueller 44 | description = Cool nbdev extensions I've thought of 45 | keywords = nbdev extensions 46 | language = English 47 | license = apache2 48 | status = 2 49 | user = muellerzr 50 | 51 | ### Inferred From Other Values ### 52 | doc_host = https://%(user)s.github.io 53 | doc_baseurl = /%(repo)s/ 54 | git_url = https://github.com/%(user)s/%(repo)s/ 55 | lib_path = %(lib_name)s 56 | title = %(repo)s 57 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from pkg_resources import parse_version 2 | from configparser import ConfigParser 3 | import setuptools 4 | assert parse_version(setuptools.__version__)>=parse_version('36.2') 5 | 6 | # note: all settings are in settings.ini; edit there, not here 7 | config = ConfigParser(delimiters=['=']) 8 | config.read('settings.ini') 9 | cfg = config['DEFAULT'] 10 | 11 | cfg_keys = 'version description keywords author author_email'.split() 12 | expected = cfg_keys + "lib_name user branch license status min_python audience language".split() 13 | for o in expected: assert o in cfg, "missing expected setting: {}".format(o) 14 | setup_cfg = {o:cfg[o] for o in cfg_keys} 15 | 16 | licenses = { 17 | 'apache2': ('Apache Software License 2.0','OSI Approved :: Apache Software License'), 18 | 'mit': ('MIT License', 'OSI Approved :: MIT License'), 19 | 'gpl2': ('GNU General Public License v2', 'OSI Approved :: GNU General Public License v2 (GPLv2)'), 20 | 'gpl3': ('GNU General Public License v3', 'OSI Approved :: GNU General Public License v3 (GPLv3)'), 21 | 'bsd3': ('BSD License', 'OSI Approved :: BSD License'), 22 | } 23 | statuses = [ '1 - Planning', '2 - Pre-Alpha', '3 - Alpha', 24 | '4 - Beta', '5 - Production/Stable', '6 - Mature', '7 - Inactive' ] 25 | py_versions = '3.6 3.7 3.8 3.9 3.10'.split() 26 | 27 | requirements = cfg.get('requirements','').split() 28 | if cfg.get('pip_requirements'): requirements += cfg.get('pip_requirements','').split() 29 | min_python = cfg['min_python'] 30 | lic = licenses.get(cfg['license'].lower(), (cfg['license'], None)) 31 | dev_requirements = (cfg.get('dev_requirements') or '').split() 32 | 33 | setuptools.setup( 34 | name = cfg['lib_name'], 35 | license = lic[0], 36 | classifiers = [ 37 | 'Development Status :: ' + statuses[int(cfg['status'])], 38 | 'Intended Audience :: ' + cfg['audience'].title(), 39 | 'Natural Language :: ' + cfg['language'].title(), 40 | ] + ['Programming Language :: Python :: '+o for o in py_versions[py_versions.index(min_python):]] + (['License :: ' + lic[1] ] if lic[1] else []), 41 | url = cfg['git_url'], 42 | packages = setuptools.find_packages(), 43 | include_package_data = True, 44 | install_requires = requirements, 45 | extras_require={ 'dev': dev_requirements }, 46 | dependency_links = cfg.get('dep_links','').split(), 47 | python_requires = '>=' + cfg['min_python'], 48 | long_description = open('README.md').read(), 49 | long_description_content_type = 'text/markdown', 50 | zip_safe = False, 51 | entry_points = { 52 | 'console_scripts': cfg.get('console_scripts','').split(), 53 | 'nbdev': [f'{cfg.get("lib_path")}={cfg.get("lib_path")}._modidx:d'] 54 | }, 55 | **setup_cfg) 56 | 57 | 58 | -------------------------------------------------------------------------------- /styles.css: -------------------------------------------------------------------------------- 1 | .cell { 2 | margin-bottom: 1rem; 3 | } 4 | 5 | .cell > .sourceCode { 6 | margin-bottom: 0; 7 | } 8 | 9 | .cell-output > pre { 10 | margin-bottom: 0; 11 | } 12 | 13 | .cell-output > pre, .cell-output > .sourceCode > pre, .cell-output-stdout > pre { 14 | margin-left: 0.8rem; 15 | margin-top: 0; 16 | background: none; 17 | border-left: 2px solid lightsalmon; 18 | border-top-left-radius: 0; 19 | border-top-right-radius: 0; 20 | } 21 | 22 | .cell-output > .sourceCode { 23 | border: none; 24 | } 25 | 26 | .cell-output > .sourceCode { 27 | background: none; 28 | margin-top: 0; 29 | } 30 | 31 | div.description { 32 | padding-left: 2px; 33 | padding-top: 5px; 34 | font-style: italic; 35 | font-size: 135%; 36 | opacity: 70%; 37 | } 38 | --------------------------------------------------------------------------------