Last active
November 4, 2024 20:55
-
-
Save dienhoa/fc72385fcc5a7d513b801207fc7464e2 to your computer and use it in GitHub Desktop.
nbdev kaggle patch
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## Patch to modify nbdev AUTOGENERATED comment for kaggle Packages | |
## Lead to # AUTOGENERATED! DO NOT EDIT! File to edit: kaggle.com/code/test.ipynb. | |
import os | |
import nbdev | |
from nbdev.maker import ModuleMaker | |
from nbdev.config import write_cells | |
from fastcore.basics import patch | |
from fastcore.foundation import L | |
from textwrap import TextWrapper | |
from pathlib import Path | |
def _import2relative(cells, lib_name=None): | |
"Converts `cells` to use `import2relative` based on `lib_name`" | |
if lib_name is None: lib_name = get_config().lib_name | |
for cell in cells: cell.import2relative(lib_name) | |
@patch | |
def make(self:ModuleMaker, cells, all_cells=None, lib_path=None, base_url='kaggle.com/code/'): | |
"Write module containing `cells` with `__all__` generated from `all_cells`" | |
if all_cells is None: all_cells = cells | |
cells,all_cells = L(cells),L(all_cells) | |
if self.parse: | |
if not lib_path: lib_path = get_config().lib_path | |
mod_dir = os.path.relpath(self.fname.parent, Path(lib_path).parent) | |
_import2relative(all_cells, mod_dir) | |
if not self.is_new: return self._make_exists(cells, all_cells) | |
self.fname.parent.mkdir(exist_ok=True, parents=True) | |
last_future = 0 | |
if self.parse: | |
_all = self.make_all(all_cells) | |
last_future = self._last_future(cells) if len(all_cells)>0 else 0 | |
tw = TextWrapper(width=120, initial_indent='', subsequent_indent=' '*11, break_long_words=False) | |
all_str = '\n'.join(tw.wrap(str(_all))) | |
with self.fname.open('w', encoding="utf-8") as f: | |
# f.write(_retr_mdoc(cells)) | |
url = base_url + self.dest2nb.split('/')[-1] | |
f.write(f"# AUTOGENERATED! DO NOT EDIT! File to edit: {url}.") | |
if last_future > 0: write_cells(cells[:last_future], self.hdr, f) | |
if self.parse: f.write(f"\n\n# %% auto 0\n__all__ = {all_str}") | |
write_cells(cells[last_future:], self.hdr, f) | |
f.write('\n') | |
nbdev.export.nb_export('test.ipynb', './') | |
print('Export successful') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment