Created
March 28, 2021 05:57
-
-
Save hotchpotch/c5904668fbd4cb0461382fbefa5a7591 to your computer and use it in GitHub Desktop.
This file contains 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
#!ruby | |
require "tmpdir" | |
require "pathname" | |
require "base64" | |
target_nb = ARGF.read | |
cmd = %w(jupyter nbconvert --to markdown) | |
png_optimizer_cmd = ["optipng", "-quiet"] # or nil | |
Dir.mktmpdir("nbconvert-embed-image") do |dir| | |
path = Pathname.new(dir).relative_path_from(__dir__) | |
prefix = "target" | |
tmp_file = path + "#{prefix}.ipynb" | |
md_file = path + "#{prefix}.md" | |
tmp_file.open("w") { |f| f.puts target_nb } | |
cmd = cmd + [tmp_file.to_s] | |
warn cmd.join(" ") | |
system(*cmd) | |
unless png_optimizer_cmd&.empty? | |
path.glob("**/*.png").each do |png| | |
opt_cmd = [png_optimizer_cmd, png.to_s].flatten | |
warn opt_cmd.join(" ") | |
system(*opt_cmd) | |
end | |
end | |
body = md_file.read | |
body.gsub!(/!\[svg\]\((.+)\)/) { | |
filepath = path.join($1) | |
data = IO.binread(filepath.sub(".svg", ".png")) | |
b64 = Base64.encode64(data).gsub("\n", "") | |
src = "data:image/png;base64,#{b64}" | |
# "<img alt='notebook image' src='#{src}' />" | |
"![img](#{src})" | |
} | |
puts body | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment