Class: IpynbDiff::OutputTransformer

Inherits:
Object
  • Object
show all
Defined in:
lib/output_transformer.rb

Overview

Transforms Jupyter output data into markdown

Constant Summary collapse

ORDERED_KEYS =
{
  'execute_result' => %w[image/png image/svg+xml image/jpeg text/markdown text/latex text/plain],
  'display_data' => %w[image/png image/svg+xml image/jpeg text/markdown text/latex]
}.freeze

Instance Method Summary collapse

Instance Method Details

#transform(output) ⇒ Object



13
14
15
16
17
18
19
20
# File 'lib/output_transformer.rb', line 13

def transform(output)
  case (output_type = output['output_type'])
  when 'error'
    transform_error(output['traceback'])
  when 'execute_result', 'display_data'
    transform_non_error(ORDERED_KEYS[output_type], output['data'])
  end
end

#transform_element(output_type, output_element) ⇒ Object



36
37
38
39
40
41
42
43
44
45
# File 'lib/output_transformer.rb', line 36

def transform_element(output_type, output_element)
  case output_type
  when 'image/png', 'image/jpeg'
    transform_image(output_type, output_element)
  when 'image/svg+xml'
    transform_svg(output_element)
  when 'text/markdown', 'text/latex', 'text/plain'
    transform_text(output_element)
  end
end

#transform_error(traceback) ⇒ Object



22
23
24
25
26
27
28
# File 'lib/output_transformer.rb', line 22

def transform_error(traceback)
  traceback.map do |t|
    t.split("\n").map do |line|
      line.gsub(/\[[0-9][0-9;]*m/, '').sub("\u001B", '    ').gsub(/\u001B/, '').rstrip << "\n"
    end
  end
end

#transform_image(image_type, image_content) ⇒ Object



47
48
49
# File 'lib/output_transformer.rb', line 47

def transform_image(image_type, image_content)
  ["    ![](data:#{image_type};base64,#{image_content.gsub("\n", '')})", "\n"]
end

#transform_non_error(accepted_keys, elements) ⇒ Object



30
31
32
33
34
# File 'lib/output_transformer.rb', line 30

def transform_non_error(accepted_keys, elements)
  accepted_keys.map do |key|
    transform_element(key, elements[key]) if elements.key?(key)
  end.flatten
end

#transform_svg(image_content) ⇒ Object



51
52
53
54
55
56
57
# File 'lib/output_transformer.rb', line 51

def transform_svg(image_content)
  lines = image_content.is_a?(Array) ? image_content : [image_content]

  single_line = lines.map(&:strip).join('').gsub(/\s+/, ' ')

  ["    ![](data:image/svg+xml;utf8,#{single_line})", "\n"]
end

#transform_text(text_content) ⇒ Object



59
60
61
62
63
# File 'lib/output_transformer.rb', line 59

def transform_text(text_content)
  lines = text_content.is_a?(Array) ? text_content : [text_content]

  lines.map { |line| "    #{line}" }.append("\n")
end