Jupyter NotebookにYouTubeを埋め込むcustom magic commandを定義する

Jupyterにはいくつかの拡張ポイントがあります。 拡張ポイントの1つであるmagic commandを用いて、ノートブックにYouTubeを埋め込んでみます。

出来上がったサンプルはnbviewerで閲覧できます。

magic command

Introducing IPython — IPython 3.2.1 documentation

IPython has a set of predefined ‘magic functions’ that you can call with a command line style syntax. There are two kinds of magics, line-oriented and cell-oriented. Line magics are prefixed with the % character and work much like OS command-line calls: they get as an argument the rest of the line, where arguments are passed without parentheses or quotes. Cell magics are prefixed with a double %%, and they are functions that get as an argument not only the rest of the line, but also the lines below it in a separate argument.

簡単な解説

magic commandは、行全体やセル全体を文字列として引数に取ります。 それらの引数を使って、何らかの値を返すと、Jupyter Notebookの出力欄に値が表示されます。

ただし、単なる文字列 <class 'str'> を 返すと、<pre>...</pre>で括られて、値がそのまま文字列として表示されます。 YouTubeを埋め込むために、HTMLコード片を動的に出力したいので、一工夫します。

IPython.core.displayには、HTMLやPNGSVGなどを表示するための関数が定義されています。 これらの関数をimportして、magic commandのなかで実行すると、出力欄に適切な形式で値を表示できるようになります (ここではdisplay_htmlをimportして、実行しています)。

from IPython.core.display import display_html
import yaml

@register_cell_magic
def youtube(line, cell):
    video_attr = yaml.load(cell)
    display_html(
            '<iframe '
            '  width="%(width)s" height="%(height)s" '
            '  src="https://www.youtube.com/embed/%(src)s" '
            '  frameborder="0">'
            '</iframe>' % video_attr,
            raw=True)

del youtube

使い方

f:id:ohtomi:20160118022743p:plain

参考情報