Debian Codegraph @

R/jupyter.R

raw
1 #' Convert a Jupyter/IPython notebook to an R Markdown document
2 #'
3 #' Read a Jupyter/IPython notebook file (\file{.ipynb}) via
4 #' \code{jsonlite::fromJSON()}, convert its code cells to R Markdown code
5 #' chunks, preserve Markdown cells, and write out the results to an Rmd file.
6 #'
7 #' This simple converter may have some rough edges, depending on how many
8 #' IPython-specific features are used in a notebook. For example, line magics
9 #' are not automatically converted (warnings will be issued if line magics are
10 #' detected), but you may consider using or writing R functions to replace them
11 #' in R Markdown (e.g., the \command{\%load} magic may be replaced by
12 #' \code{reticulate::source_python()}). Cell magics will be converted to code
13 #' chunks with the (\pkg{knitr}) language engine names being the magic names.
14 #' For example, the cell magic \command{\%\%js} is converted to \verb{```{js}}
15 #' in R Markdown. This does not always work because not all IPython cell magics
16 #' have their counterparts in \pkg{knitr}'s language engines, but common cell
17 #' magics like \command{\%\%bash}, \command{\%\%sh}, \command{\%\%js},
18 #' \command{\%\%perl}, \command{\%\%python}, and \command{\%\%ruby} should work.
19 #' @param input Path to the input \file{.ipynb} file.
20 #' @param output The output file path.
21 #' @return The output file path (invisibly).
22 #' @export
23 #' @examples
24 #' # this is not a real ipynb file, but illustrates what convert_ipynb() does
25 #' nb_data <- list(
26 #' cells = list(
27 #' list(cell_type = 'markdown', source = 'Hi **Markdown**!'),
28 #' list(cell_type = 'code', source = 'print("Hi R Markdown!")')
29 #' ),
30 #' metadata = list(
31 #' kernelspec = list(language = 'python')
32 #' )
33 #' )
34 #' nb_file = tempfile(fileext = '.ipynb')
35 #' jsonlite::write_json(nb_data, nb_file, auto_unbox = TRUE, pretty = TRUE)
36 #' xfun::file_string(nb_file) # show file content
37 #'
38 #' # convert to R Markdown
39 #' nb_rmd = rmarkdown:::convert_ipynb(nb_file)
40 #' xfun::file_string(nb_rmd)
41 convert_ipynb <- function(input, output = xfun::with_ext(input, 'Rmd')) {
42 json <- jsonlite::fromJSON(input, simplifyDataFrame = FALSE)
43 spec <- json$metadata$kernelspec
44 lang <- spec$language # global language
45 if (is.null(lang) && identical(tolower(spec$name), 'ir')) lang <- 'r'
46 if (is.null(lang)) lang <- 'python' # fall back to python
47 res <- character()
48 for (cell in json$cells) {
49 if (length(src <- unlist(cell$source)) == 0) next # empty cell
50 src <- gsub('\n$', '', src)
51 src <- switch(
52 cell$cell_type,
53 code = cell_chunk(src, lang, cell$metadata),
54 raw = cell_raw(src, cell$metadata$format),
55 src
56 )
57 res <- c(res, src, '')
58 }
59 res <- c('---', ipynb_yaml(json$metadata, input), '---\n', res)
60 xfun::write_utf8(res, output)
61 invisible(output)
62 }
63
64 # convert an ipynb cell to an Rmd chunk
65 cell_chunk <- function(x, lang, meta = list()) {
66 if (length(x) == 0) return()
67 # warn against line magics
68 if (length(i <- grep(r_line_magics, x)) > 0) warning(
69 'Detected the following probable line magics. They do not work in R Markdown.\n\n',
70 paste(' ', x[i], collapse = '\n'), call. = FALSE
71 )
72 # replace cell magics with knitr language engines
73 if (grepl(r <- '^%%([[:alnum:]]+)\\s*$', x[1])) {
74 lang <- gsub(r, '\\1', x[1]); x <- x[-1]
75 }
76 if (lang == 'markdown') return(x)
77 opts <- c('', meta$name) # cell name (if defined) to chunk label
78 meta <- meta$jupyter # convert some jupyter cell metadata to chunk options
79 opts <- c(
80 opts, if (isTRUE(meta$source_hidden)) 'echo=FALSE',
81 if (isTRUE(meta$outputs_hidden)) 'results="hide"'
82 )
83 c(sprintf('```{%s%s}', adjust_lang(lang), paste(opts, collapse = ', ')), x, '```')
84 }
85
86 line_magics <- c(
87 'alias', 'alias_magic', 'autoawait', 'autocall', 'automagic',
88 'autosave', 'bookmark', 'cat', 'cd', 'clear', 'colors', 'conda',
89 'config', 'connect_info', 'cp', 'debug', 'dhist', 'dirs', 'doctest_mode',
90 'ed', 'edit', 'env', 'gui', 'hist', 'history', 'killbgscripts',
91 'ldir', 'less', 'lf', 'lk', 'll', 'load', 'load_ext', 'loadpy',
92 'logoff', 'logon', 'logstart', 'logstate', 'logstop', 'ls', 'lsmagic',
93 'lx', 'macro', 'magic', 'man', 'matplotlib', 'mkdir', 'more',
94 'mv', 'notebook', 'page', 'pastebin', 'pdb', 'pdef', 'pdoc',
95 'pfile', 'pinfo', 'pinfo2', 'pip', 'popd', 'pprint', 'precision',
96 'prun', 'psearch', 'psource', 'pushd', 'pwd', 'pycat', 'pylab',
97 'qtconsole', 'quickref', 'recall', 'rehashx', 'reload_ext', 'rep',
98 'rerun', 'reset', 'reset_selective', 'rm', 'rmdir', 'run', 'save',
99 'sc', 'set_env', 'store', 'sx', 'system', 'tb', 'time', 'timeit',
100 'unalias', 'unload_ext', 'who', 'who_ls', 'whos', 'xdel', 'xmode'
101 )
102
103 r_line_magics <- paste0('^%?(', paste(line_magics, collapse = '|'), ')($|\\s)')
104
105 # convert raw text/html and text/latex cells to raw ```{=format}` Markdown blocks
106 cell_raw <- function(x, fmt) {
107 if (length(fmt) != 1) return(x)
108 fmt <- switch(fmt, 'text/html' = 'html', 'text/latex' = 'latex')
109 if (length(fmt) == 0) return(x)
110 c(sprintf('```{=%s}', fmt), x, '```')
111 }
112
113 # adjust some cell magic names to knitr's engine names
114 adjust_lang <- function(x) {
115 if (x == 'R') return('r')
116 if (x == 'javascript') return('js')
117 # use raw HTML/LaTeX blocks for Pandoc's Markdown
118 if (tolower(x) %in% c('html', 'latex')) return(paste0('=', tolower(x)))
119 x
120 }
121
122 # convert .ipynb metadata to YAML frontmatter in .Rmd
123 ipynb_yaml <- function(meta, input) {
124 # default title and output format
125 res <- list(
126 title = paste0('An R Markdown document converted from "', input, '"'),
127 output = 'html_document'
128 )
129 # currently only the `authors` field is supported
130 authors <- unlist(lapply(meta$authors, `[[`, 'name'))
131 if (length(authors) > 0) res[['author']] <- paste(authors, collapse = ', ')
132 gsub('\n+$', '', yaml::as.yaml(res))
133 }