LoginSignup
3
2

More than 3 years have passed since last update.

.ipynb を .html へ変換 (with BatchFile)

Last updated at Posted at 2020-02-10

結論

  • batchファイルを置いてClick! したら直下の.ipynbをhtmlへ変換してくれるものを作った
  • pythonが入っていない環境でも動く(はず)
  • toc2(目次機能)が自動で挿入される ← 本機能の一推しpoint!
  • macで作ったけど、windowsでもbuildしなおせば動く可能性あり。(未確認)

demo

背景

  • 送られてきた大量の.ipynbの中身を確認するために、毎度毎度ローカルサーバーを立ち上げてnotebookを開くのが大変。 さらにいうと、他業務で異なるdirectoryで作業しているといくつもローカルサーバーを立てないといけなくて業務どころじゃなくなる。

既存の方法

jupyter nbconvert --to html hoge.ipynb
  • 方法2: 公式:Customizing nbconvert
    • template(以下の例だと"simplepython.tpl")を使ってhtml化。この方法だとtoc2などのnbextensionにある目次などもhtmlとして含められる
jupyter nbconvert --to python 'example.ipynb' --stdout --template=simplepython.tpl
  • 方法3: LocalServer上でnoebookを開いて保存 スクリーンショット 2020-02-11 12.53.25.png

解決できない問題・課題

  • 大量の.ipynbをみないといけないときに辛い
  • template.tplのpathを忘れる
  • directoryの移動がめんどくさい
  • python環境にいろいろなpackage(jupyter, nbconvert, nbextensions, toc2.tpl etc...) を入れておかないといけない。(環境はsimpleであってほしい!)
    • ↑仮想環境を作ってちょこちょこ入れ替えているからpackageの有無なんて覚えてられない。

アプローチ

GUIベースの処理を実装する。(既存方法のコマンドを1つの実行ファイルにまとめる。)

  • 使ったpackage

    • pyinstaller: 1ファイルの実行ファイルを作成
    • jupyter: nbconvertなどの関数を利用し、text -> notebook形式 -> html へ変換していく
    • jinja2: template.tplをいくつか読み込む際に使用
    • toc2.tpl, full.tpl...: などのjupyternotebookを起動する際に、jinja2が読み込んでいるいろいろなtemplate
  • 具体的な中身は気が向いたら、追記予定

効果・結論

  • いまのところまともに動作していて、5秒でhtml化された便利
  • 残課題
    • ファイルサイズが大きく(50MBくらい)ありhddを圧迫する。
    • 処理時間が長い。できれば0.5秒くらいでhtml化まで終わってほしい。

おまけ(はまったところ)

  • テンプレート群をbatchfileの中に組み込むのに苦労した。
    というのも、以下のtemplate fileをpyinstallerが認識してくれなかったから。 textからhtmlへ変換するjinja2にとって必須のファイルなんだけどーー

    • toc2.tpl
    • full.tpl
    • nbextensions.tpl
    • mathjax.tpl
    • celltags.tpl
  • ↑の解決策として、.tplをハードコーディングして、stringとして読みむためのファイルを作った。(data_tpl.py) .pyfileだとpyinstallerは勝手に認識してくれるみたい。

  • あとは、stringで読み込んだtemplateをjinja2.dictLoaderで変換してあげれば、勝手にjinja2の継承({%- extends 'hogehoge.html' %})などもよしなにやってくれというわけなのだー

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2