Class: Vapey::MarkdownParser

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

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file_path) ⇒ MarkdownParser

Returns a new instance of MarkdownParser.



116
117
118
119
120
# File 'lib/vapey/markdown_parser.rb', line 116

def initialize(file_path)
  @file_path = file_path
  @sections = []
  parse_file
end

Instance Attribute Details

#sectionsObject (readonly)

Returns the value of attribute sections.



3
4
5
# File 'lib/vapey/markdown_parser.rb', line 3

def sections
  @sections
end

Class Method Details

.get_embedding(section, section_id) ⇒ Object



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/vapey/markdown_parser.rb', line 55

def get_embedding(section, section_id)
  token_count = nil
  embedding = nil
  data = redis.get(section_id)

  if data.nil?

    # OpenAI recommends replacing newlines with spaces for best results (specific to embeddings)
    input = section.gsub(/\n/m, ' ')
    response = openai.embeddings(parameters: { input: input, model: "text-embedding-ada-002"})

    token_count = response['usage']['total_tokens']
    embedding = response['data'].first['embedding']

    redis.set(section_id, {'token_count' => token_count, 'embedding' => embedding}.to_json)
  else
    cached_embedding = JSON.parse(data)
    token_count = cached_embedding['token_count']
    embedding = cached_embedding['embedding']
  end
  [token_count, embedding]
end

.git_file_list(dir) ⇒ Object



78
79
80
# File 'lib/vapey/markdown_parser.rb', line 78

def git_file_list(dir)
  `cd #{dir} && git ls-files`.split("\n")
end

.openaiObject



11
12
13
# File 'lib/vapey/markdown_parser.rb', line 11

def openai
  @@openai ||= OpenAI::Client.new(access_token: ENV.fetch("OPENAPI_ACCESS_TOKEN"))
end

.process(directory) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/vapey/markdown_parser.rb', line 15

def process(directory)

  git_file_list(directory).map do |file|
    file_path = File.expand_path(File.join(directory, file))

    next unless file.match(/\.md$/)

    puts "processing file: #{file_path}"

    page_id = Digest::SHA1.hexdigest(file_path)
    title = File.read(file_path).lines.first.strip.gsub(/^#\s+/,'')
    checksum = Digest::MD5.hexdigest(File.read(file_path))

    parser = Vapey::MarkdownParser.new(file_path)
    sections = parser.sections.map do |section|
      section = process_markdown(section)
      section_title = section.lines.first.strip.gsub(/^i[#]+\s+/,'')
      section_id = Digest::MD5.hexdigest(section)
      id = Digest::MD5.hexdigest("#{page_id}:#{section_id}")

      # get cached embedding or call out to openai
      token_count, embedding = get_embedding(section, section_id)

      {
        id: id,
        page_id: page_id,
        section_id: section_id,
        file: file,
        title: title,
        section_title: section_title,
        content: section,
        checksum: checksum,
        token_count: token_count,
        embedding: embedding,
      }

    end
  end.compact.flatten
end

.process_markdown(file) ⇒ Object



82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
# File 'lib/vapey/markdown_parser.rb', line 82

def process_markdown(file)
  mkdocs_url = "https://docs-mkdocs.releaseapp.io"

  # handle images
  # TODO: deal with spaces??
  file.gsub!(/(!\[[^\]]*?\])([\(<]+)[\.\/]+\.gitbook\/assets\/(.*?)([\)>]+)/m) do
    "#{$1}#{$2}#{mkdocs_url}/img/#{$3}#{$4}"
  end

  # remove the .md extension from the end of the URLs from gitbook
  file.gsub!(/(\[[^\]]+?\])\((.*?)\.md([#a-z0-9]*)\)/) do |match|
    "#{$1}(#{$2}#{$3})" 
  end

  # handle "mentions" 
  file.gsub!(/\[([^\]]+?).md\]\((.*?)\.md([#a-z0-9]*) "mention"\)/) do |match|
    link = "#{$2}#{$3}"
    title = $1.gsub("-", ' ').titleize
    "[#{title}](#{link})" 
  end

  # convert gitbook hints to admonitions
  # multi-line shortest match ...
  file.gsub!(/{%\s+hint style="(.*?)"\s+?%}(.*?){% endhint %}/m) do |match|
    ret = "!!! #{$1}\n"
    ret += $2.lines.map{|line| "    #{line}" }.join()
    ret
  end

  file
end

.redisObject



7
8
9
# File 'lib/vapey/markdown_parser.rb', line 7

def redis
  @@redis ||= Redis.new(host: ENV.fetch("REDIS_HOST") { "127.0.0.1" }, port: ENV.fetch("REDIS_PORT") { "6379" }.to_i)
end

Instance Method Details

#parse_fileObject



122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
# File 'lib/vapey/markdown_parser.rb', line 122

def parse_file
  current_section = []
  File.read(@file_path).lines do |line|
    # Check if the line is a header (starts with one or more '#' characters)
    if header?(line)
      # Save the previous section if it's not empty
      @sections << current_section.join unless current_section.empty?
      # Start a new section
      current_section = [line]
    else
      # Add the line to the current section
      current_section << line
    end
  end
  # Save the last section if it's not empty
  @sections << current_section.join unless current_section.empty?
end