Skip to content

Instantly share code, notes, and snippets.

@marcelinollano
Last active August 26, 2020 11:16
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marcelinollano/de710e3d3665162ac752 to your computer and use it in GitHub Desktop.
Save marcelinollano/de710e3d3665162ac752 to your computer and use it in GitHub Desktop.
You can use Markdown inside the questions and answers! Images in the same folder though.
#!/usr/bin/env ruby
# Usage:
#
# => brew install imagemagick
# => gem install anki2 kramdown rmagick image_optim image_optim_pack
# => chmod +x ./anki.rb
# => ./anki.rb questions.md
require 'rubygems'
require 'yaml'
require 'anki2'
require 'kramdown'
require 'rmagick'
require 'image_optim'
# Transforms `$` into `[$$]` and `[/$$]`.
def fences(str)
toggle = true
str = str.gsub(/\${1}\s{1}/, '[$$] ')
str = str.gsub(/\s{1}\${1}/, ' [$$]')
while str =~ /\[\${2}\]/ do
if toggle
str = str.sub(/\[\${2}\]/, '[$$/]')
toggle = false
else
str = str.sub(/\[\${2}\]/, '[/$$]')
toggle = true
end
end
str = str.gsub(/\[\${2}\/\]/, '[$$]')
end
# Markdown to HTML. Known issue: Kramdown ignores `$$` for some reason.
def markdown(str)
str = str.gsub(/\${2}/, '$')
str = Kramdown::Document.new(str).to_html
str = fences(str)
end
# Open the file from command line params
file = File.new(ARGV[0], 'r')
arr = file.read.split('---')
file.close
# Read the front matter and media folder
meta = YAML.load(arr[0].strip)
media = meta['Media'] || '.'
@anki = Anki2.new(name: meta['Deck'], output_path: meta['File'])
puts "--> Generating deck \"#{meta['Deck']}\"\n"
# Read images from media
images = Dir.glob("#{media}/*.{png,jpg,jpeg,gif}")
# Resize the images before optimizing
puts "--> Resizing #{images.count} images\n"
images.each do |name|
image = Magick::Image.read(name).first
image.change_geometry("800") do |cols, rows, img|
img = img.resize!(cols, rows)
img.write(name)
end
end
# Optimize images before packing
image_optim = ImageOptim.new(:pngout => false, :svgo => false)
images.each do |name|
puts "--> Optimizing #{name}\n"
image_optim.optimize_image!(name)
end
# Add the media folder
@anki.add_media(media)
# Add cards to the deck
deck = arr[1..-1]
deck.each do |card|
content = card.split(/(Q:|A:)/)
question = markdown(content[2].strip)
answer = markdown(content[4].strip)
@anki.add_card(question, answer)
end
# Pack and save the cards
puts "--> Packing #{deck.count} cards\n"
@anki.save
puts "--> Done!\n"

Deck: "Physics"
File: "Mechanics.apkg"


Q: What is the formula for the gravitational potential energy $$ U_g $$?

A: $$ U_g = m g h $$ [J].


Q: What is the formula for the spring potential energy $$ U_s $$.

A: $$ U_s = \frac{1}{2} k |x|^2 $$ [J].

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment