substrate 0.3.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: f70ea3ee7d06a49e41215d92a1b04db9173cbf357cbeccbd9bb85adc281b2e45
4
- data.tar.gz: b86bcb7ff7b2f9eab771a2e3419b1ab0cf42a08bb4ae6d4bd906d2cee0ea0c5f
3
+ metadata.gz: b2f33f7baead2c71d256553e5b8fbcadd463a14c4b6a2b4890c732afc3ef40f8
4
+ data.tar.gz: 91655afe2c2fd644fdd6077b1c2baeeddf256f55ab34729f3ad2345b40c32268
5
5
  SHA512:
6
- metadata.gz: 2d2687f91dbe8ca128de93e975de5e0a25359e8e8f1d7399b6092721b553ac26985eeff2d2963a7112f70bf11f98fdbcfff8f30e4462cb9fc9b3375349e6cf37
7
- data.tar.gz: e303be1550bd6d5f98635689316e9be8e17d88657e196d614133f84aad0674745db45ffb0f1702dfc22ac3f5798e923113f612151fe98a71bfbce8ba602b0542
6
+ metadata.gz: 8c9af828c81fae8e010ef5a488e9f804d2c7f865f4483d1e8f96eda852589b0b2e9ebd9139e831087934b07ef78d92b901db92d9d8f239b430efa77bbf98b01c
7
+ data.tar.gz: 16025303d9a1cf09192aff457898573fa17cfad03743ae2ad4d6c9e5dece98afb712020d7aa02db8f0dd47afc7c6b03817e3c2ce901c36be4a4f6d15d491eae4
@@ -5,7 +5,7 @@ require "stringio"
5
5
 
6
6
  module Substrate
7
7
  class ExtractPdf < Command
8
- def initialize(bytes:, source_ref:, limits: Mediums::Pdf::Limits.new, page_separator: "\n\n")
8
+ def initialize(bytes:, source_ref:, limits: Mediums::Pdf::Limits.new, page_separator: Mediums::Pdf::Content::DEFAULT_PAGE_SEPARATOR)
9
9
  @bytes = bytes
10
10
  @source_ref = source_ref
11
11
  @limits = limits
@@ -36,6 +36,7 @@ module Substrate
36
36
  def extract_document
37
37
  StringIO.open(@bytes) do |io|
38
38
  document = HexaPDF::Document.new(io: io, config: {"document.auto_decrypt" => false, "filter.map" => {BrotliDecode: nil}})
39
+ configure_unicode_mapping(document)
39
40
  raise Mediums::Pdf::EncryptedPdf, "Encrypted PDFs are not supported" if document.encrypted?
40
41
  objects = page_objects(document)
41
42
  pages = extract_pages(objects)
@@ -47,6 +48,22 @@ module Substrate
47
48
  raise Mediums::Pdf::InvalidPdf, "PDF parsing or page extraction failed", cause: error
48
49
  end
49
50
 
51
+ def configure_unicode_mapping(document)
52
+ fallback = document.config["font.on_missing_unicode_mapping"]
53
+ document.config["font.on_missing_unicode_mapping"] = lambda do |code, font|
54
+ name = font.encoding.name(code) if font.is_a?(HexaPDF::Type::FontSimple)
55
+ base, suffix = name.to_s.split(".", 2)
56
+ mapped = glyph_unicode(base) if suffix && !base.empty?
57
+ mapped || fallback.call(code, font)
58
+ end
59
+ end
60
+
61
+ def glyph_unicode(name)
62
+ HexaPDF::Font::Encoding::GlyphList.name_to_unicode(name.to_sym)
63
+ rescue RangeError
64
+ nil
65
+ end
66
+
50
67
  def page_objects(document)
51
68
  root = document.catalog[:Pages]
52
69
  raise Mediums::Pdf::InvalidPdf, "PDF page tree is missing" unless root.is_a?(HexaPDF::Dictionary)
@@ -125,7 +142,7 @@ module Substrate
125
142
  def publish_content(pages, outline)
126
143
  metadata = {extractor: "HexaPDF", extractor_version: HexaPDF::VERSION.dup.freeze,
127
144
  input_bytes: @bytes.bytesize, page_count: pages.size,
128
- text_bytes: @text.bytesize}.freeze
145
+ text_bytes: @text.bytesize, page_separator: @page_separator}.freeze
129
146
  success(payload: Mediums::Pdf::Content.new(pages: pages, source_ref: @source_ref,
130
147
  metadata: metadata, outline: outline, text: @text.freeze))
131
148
  end
@@ -3,7 +3,13 @@
3
3
  module Substrate
4
4
  module Mediums
5
5
  module Pdf
6
- Content = Data.define(:pages, :source_ref, :metadata, :outline, :text)
6
+ class Content < Data.define(:pages, :source_ref, :metadata, :outline, :text)
7
+ DEFAULT_PAGE_SEPARATOR = "\n\n"
8
+
9
+ def page_separator
10
+ metadata.fetch(:page_separator, DEFAULT_PAGE_SEPARATOR)
11
+ end
12
+ end
7
13
  end
8
14
  end
9
15
  end
@@ -0,0 +1,58 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Substrate
4
+ module Mediums
5
+ module Pdf
6
+ class HeadingIndex
7
+ MAX_HEADING_LINES = 3
8
+
9
+ def initialize(pages:, entries:)
10
+ @pages = pages
11
+ @entries = entries
12
+ @headings_by_page = {}
13
+ end
14
+
15
+ def find(page, title)
16
+ headings_by_page[page] ||= index_page(page)
17
+ headings_by_page.fetch(page)[normalize(title)]
18
+ end
19
+
20
+ private
21
+
22
+ attr_reader :entries, :headings_by_page, :pages
23
+
24
+ def titles_by_page
25
+ @titles_by_page ||= entries.group_by { |entry| entry.destination.page_number }
26
+ .transform_values { |page_entries| page_entries.to_h { |entry| [normalize(entry.title), nil] } }
27
+ end
28
+
29
+ def index_page(page)
30
+ recent_lines = []
31
+ offset = 0
32
+ pages.fetch(page - 1).text.each_line("\n").each_with_object(titles_by_page.fetch(page).dup) do |line, matches|
33
+ normalized = normalize(line)
34
+ recent_lines << [normalized, offset]
35
+ recent_lines.shift if recent_lines.length > MAX_HEADING_LINES
36
+ offset += line.bytesize
37
+ next if normalized.empty?
38
+ match_headings(matches, recent_lines, offset)
39
+ end.select { |_, location| location }
40
+ end
41
+
42
+ def match_headings(matches, recent_lines, end_byte)
43
+ recent_lines.each_index do |index|
44
+ line, start_byte = recent_lines.fetch(index)
45
+ next if line.empty?
46
+ title = recent_lines.drop(index).map(&:first).reject(&:empty?).join(" ")
47
+ next unless matches.key?(title)
48
+ matches[title] = matches[title].nil? ? [start_byte, end_byte] : false
49
+ end
50
+ end
51
+
52
+ def normalize(text)
53
+ text.unicode_normalize(:nfc).gsub(/[[:space:]]+/, " ").strip
54
+ end
55
+ end
56
+ end
57
+ end
58
+ end
@@ -0,0 +1,13 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Substrate
4
+ module Mediums
5
+ module Pdf
6
+ OutlineLimits = Data.define(:depth, :title_bytes, :text_bytes) do
7
+ def initialize(depth: 16, title_bytes: 4 * 1024, text_bytes: 32 * 1024 * 1024)
8
+ super
9
+ end
10
+ end
11
+ end
12
+ end
13
+ end
@@ -0,0 +1,17 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Substrate
4
+ module Mediums
5
+ module Pdf
6
+ OutlineSpan = Data.define(:title, :range, :parent_index, :front_matter) do
7
+ def initialize(title:, range:, parent_index:, front_matter: false)
8
+ super
9
+ end
10
+
11
+ def front_matter?
12
+ front_matter
13
+ end
14
+ end
15
+ end
16
+ end
17
+ end
@@ -0,0 +1,37 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Substrate
4
+ module Mediums
5
+ module Pdf
6
+ class PageBoundary
7
+ def initialize(pages)
8
+ @pages = pages
9
+ end
10
+
11
+ def match?(entry)
12
+ return false if entry.title.strip.match?(/\A[[:space:]]*\z/)
13
+ destination = entry.destination
14
+ destination.kind == :local && page_top?(destination)
15
+ end
16
+
17
+ private
18
+
19
+ def page_top?(destination)
20
+ return true if %i[Fit FitB FitV FitBV].include?(destination.fit)
21
+ return true if destination.fit == :XYZ && destination.parameters == [nil, nil, nil]
22
+
23
+ top = vertical_coordinate(destination)
24
+ crop = @pages.fetch(destination.page_number - 1).crop_box
25
+ top && crop && top >= crop.top
26
+ end
27
+
28
+ def vertical_coordinate(destination)
29
+ case destination.fit
30
+ when :XYZ then destination.parameters[1]
31
+ when :FitH, :FitBH then destination.parameters[0]
32
+ end
33
+ end
34
+ end
35
+ end
36
+ end
37
+ end
@@ -0,0 +1,193 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Substrate
4
+ module Mediums
5
+ module Pdf
6
+ class ResolveOutline < Command
7
+ def initialize(content:, limits: OutlineLimits.new, page_separator: content.page_separator)
8
+ @content = content
9
+ @limits = limits
10
+ @page_separator = page_separator
11
+ end
12
+
13
+ def call
14
+ resolve_spans
15
+ end
16
+
17
+ private
18
+
19
+ Anchor = Data.define(:entry, :start, :heading_end)
20
+ private_constant :Anchor
21
+
22
+ attr_reader :content, :limits, :page_separator, :remaining_subsection_bytes
23
+
24
+ def resolve_spans
25
+ @page_separator = @page_separator.dup.freeze unless @page_separator.frozen?
26
+ entries = root_entries
27
+ roots = entries.map { |entry| root_anchor(entry, false) }
28
+ return success(payload: outline_spans(roots)) if reliable_roots?(roots, false)
29
+
30
+ corroborated = corroborated_roots?(entries)
31
+ roots = entries.map { |entry| root_anchor(entry, corroborated) }
32
+ success(payload: reliable_roots?(roots, corroborated) ? outline_spans(roots) : nil)
33
+ end
34
+
35
+ def root_entries
36
+ return [] unless content.outline.status == :complete
37
+ entries_by_parent.fetch(nil, [])
38
+ end
39
+
40
+ def reliable_roots?(roots, corroborated)
41
+ return false if roots.empty? || roots.any?(&:nil?)
42
+ (roots.first.start == [1, 0] || corroborated) && ordered?(roots.map(&:start))
43
+ end
44
+
45
+ def outline_spans(roots)
46
+ @remaining_subsection_bytes = limits.text_bytes
47
+ pending = sibling_work(roots, [content.pages.length + 1, 0], nil, 0)
48
+ [].tap do |spans|
49
+ if roots.first.start != [1, 0]
50
+ range = TextRange.new(start: [1, 0], finish: roots.first.start, page_separator: page_separator)
51
+ spans << OutlineSpan.new(title: "Front matter", range: range, parent_index: nil, front_matter: true)
52
+ end
53
+ while (work = pending.pop)
54
+ anchor, finish, parent_index, depth = work
55
+ span_index = spans.length
56
+ spans << build_span(anchor, finish, parent_index)
57
+ next if depth >= limits.depth
58
+
59
+ children = admitted_children(anchor, finish)
60
+ pending.concat(sibling_work(children, finish, span_index, depth + 1)) if children
61
+ end
62
+ end.freeze
63
+ end
64
+
65
+ def sibling_work(anchors, parent_end, parent_index, depth)
66
+ anchors.each_index.reverse_each.map do |index|
67
+ [anchors.fetch(index), anchors[index + 1]&.start || parent_end, parent_index, depth]
68
+ end
69
+ end
70
+
71
+ def build_span(anchor, finish, parent_index)
72
+ range = TextRange.new(start: anchor.start, finish: finish, page_separator: page_separator)
73
+ OutlineSpan.new(title: anchor.entry.title.strip.freeze, range: range, parent_index: parent_index)
74
+ end
75
+
76
+ def admitted_children(anchor, finish)
77
+ entries = entries_by_parent.fetch(anchor.entry.id, [])
78
+ return if entries.empty?
79
+ children = entries.map { |entry| child_anchor(entry) }
80
+ return unless reliable_children?(children, anchor.heading_end || anchor.start, finish)
81
+ bytes = represented_bytes(children, finish)
82
+ return if bytes > remaining_subsection_bytes
83
+
84
+ @remaining_subsection_bytes -= bytes
85
+ children
86
+ end
87
+
88
+ def reliable_children?(children, first_allowed_start, parent_end)
89
+ return false if children.any?(&:nil?)
90
+ starts = children.map(&:start)
91
+ (starts.first <=> first_allowed_start) >= 0 && ordered?([*starts, parent_end]) &&
92
+ children.zip([*starts.drop(1), parent_end]).all? { |child, finish| (child.heading_end <=> finish) <= 0 }
93
+ end
94
+
95
+ def ordered?(positions)
96
+ positions.each_cons(2).all? { |left, right| (left <=> right).negative? }
97
+ end
98
+
99
+ def represented_bytes(children, finish)
100
+ boundaries = [*children.drop(1).map(&:start), finish]
101
+ omitted_separators = boundaries.count { |position| position.last.zero? }
102
+ absolute_offset(finish) - absolute_offset(children.first.start) - omitted_separators * page_separator.bytesize
103
+ end
104
+
105
+ def absolute_offset(position)
106
+ page, offset = position
107
+ page_offsets.fetch(page - 1) + offset
108
+ end
109
+
110
+ def page_offsets
111
+ @page_offsets ||= content.pages.each_with_object([0]) do |page, offsets|
112
+ offsets << offsets.last + page.text.bytesize + page_separator.bytesize
113
+ end
114
+ end
115
+
116
+ def entries_by_parent
117
+ @entries_by_parent ||= content.outline.entries.group_by(&:parent_id)
118
+ end
119
+
120
+ def page_boundary
121
+ @page_boundary ||= PageBoundary.new(content.pages)
122
+ end
123
+
124
+ def heading_index
125
+ @heading_index ||= HeadingIndex.new(pages: content.pages, entries: subsection_entries)
126
+ end
127
+
128
+ def subsection_entries
129
+ content.outline.entries.select { |entry| entry.parent_id && subsection_destination?(entry) }
130
+ end
131
+
132
+ def root_anchor(entry, corroborated)
133
+ return unless page_boundary.match?(entry) || corroborated
134
+ Anchor.new(entry: entry, start: [entry.destination.page_number, 0], heading_end: nil)
135
+ end
136
+
137
+ def corroborated_roots?(entries)
138
+ return false if entries.empty?
139
+ pages = entries.map { |entry| entry.destination.page_number }
140
+ return false unless pages.all? { |page| page.is_a?(Integer) && page.positive? } && ordered?(pages)
141
+ entries.each_with_index.all? do |entry, index|
142
+ corroborated_root?(entry, index + 1)
143
+ end
144
+ end
145
+
146
+ def corroborated_root?(entry, ordinal)
147
+ destination = entry.destination
148
+ return false if entry.title.bytesize > limits.title_bytes || entry.title.strip.empty?
149
+ return false if destination.kind != :local || destination.fit != :XYZ
150
+ return false unless destination.parameters.length == 3
151
+ page = content.pages[destination.page_number.to_i - 1] if destination.page_number.to_i.positive?
152
+ return false unless page&.crop_box
153
+ left, top, = destination.parameters
154
+ box = page.crop_box
155
+ return false unless left.is_a?(Numeric) && top.is_a?(Numeric)
156
+ return false unless left.between?(box.left, box.right) && top.between?(box.bottom, box.top)
157
+
158
+ heading = normalize_heading("#{ordinal} #{entry.title}")
159
+ found = false
160
+ nonblank = 0
161
+ page.text.each_line("\n") do |line|
162
+ normalized = normalize_heading(line)
163
+ next if normalized.empty?
164
+ nonblank += 1
165
+ if normalized == heading
166
+ return false if found || nonblank > 3
167
+ found = true
168
+ end
169
+ return false if nonblank >= 3 && !found
170
+ end
171
+ found
172
+ end
173
+
174
+ def normalize_heading(text)
175
+ text.unicode_normalize(:nfc).gsub(/[[:space:]]+/, " ").strip
176
+ end
177
+
178
+ def child_anchor(entry)
179
+ return unless subsection_destination?(entry)
180
+ page = entry.destination.page_number
181
+ heading = heading_index.find(page, entry.title)
182
+ return unless heading
183
+ start_byte, end_byte = heading
184
+ Anchor.new(entry: entry, start: [page, start_byte], heading_end: [page, end_byte])
185
+ end
186
+
187
+ def subsection_destination?(entry)
188
+ entry.title.bytesize <= limits.title_bytes && page_boundary.match?(entry)
189
+ end
190
+ end
191
+ end
192
+ end
193
+ end
@@ -0,0 +1,45 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Substrate
4
+ module Mediums
5
+ module Pdf
6
+ class TextRange < Data.define(:start, :finish, :page_separator)
7
+ Location = Data.define(:page, :start_byte, :end_byte)
8
+ Slice = Data.define(:text, :locations)
9
+
10
+ def initialize(start:, finish:, page_separator: Content::DEFAULT_PAGE_SEPARATOR)
11
+ page_separator = page_separator.dup.freeze unless page_separator.frozen?
12
+ super(start: start.dup.freeze, finish: finish.dup.freeze, page_separator: page_separator)
13
+ end
14
+
15
+ def slice(page_texts:, page_separator: self.page_separator)
16
+ (start.first..last_page).each_with_object(Slice.new(text: +"", locations: [])) do |number, slice|
17
+ append_page(slice, number, page_texts.fetch(number - 1), page_separator)
18
+ end.tap do |slice|
19
+ slice.text.freeze
20
+ slice.locations.freeze
21
+ end
22
+ end
23
+
24
+ private
25
+
26
+ def append_page(slice, number, page, page_separator)
27
+ from = (number == start.first) ? start.last : 0
28
+ to = (number == finish.first) ? finish.last : page.bytesize
29
+ slice.text << page_separator unless number == start.first
30
+ slice.text << page.byteslice(from...to)
31
+ slice.locations << location(number, from, to, page.bytesize)
32
+ end
33
+
34
+ def last_page
35
+ finish.last.zero? ? finish.first - 1 : finish.first
36
+ end
37
+
38
+ def location(page, from, to, size)
39
+ return Location.new(page: page, start_byte: nil, end_byte: nil) if from.zero? && to == size
40
+ Location.new(page: page, start_byte: from, end_byte: to)
41
+ end
42
+ end
43
+ end
44
+ end
45
+ end
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Substrate
4
- VERSION = "0.3.0"
4
+ VERSION = "0.4.1"
5
5
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: substrate
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.3.0
4
+ version: 0.4.1
5
5
  platform: ruby
6
6
  authors:
7
7
  - Dan Frenette
@@ -106,6 +106,7 @@ files:
106
106
  - lib/substrate/mediums/pdf/document.rb
107
107
  - lib/substrate/mediums/pdf/encrypted_pdf.rb
108
108
  - lib/substrate/mediums/pdf/entry.rb
109
+ - lib/substrate/mediums/pdf/heading_index.rb
109
110
  - lib/substrate/mediums/pdf/invalid_pdf.rb
110
111
  - lib/substrate/mediums/pdf/invalid_text.rb
111
112
  - lib/substrate/mediums/pdf/limit_exceeded.rb
@@ -114,11 +115,16 @@ files:
114
115
  - lib/substrate/mediums/pdf/no_selectable_text.rb
115
116
  - lib/substrate/mediums/pdf/outline.rb
116
117
  - lib/substrate/mediums/pdf/outline_facts.rb
118
+ - lib/substrate/mediums/pdf/outline_limits.rb
117
119
  - lib/substrate/mediums/pdf/outline_parser.rb
120
+ - lib/substrate/mediums/pdf/outline_span.rb
118
121
  - lib/substrate/mediums/pdf/page.rb
122
+ - lib/substrate/mediums/pdf/page_boundary.rb
119
123
  - lib/substrate/mediums/pdf/page_extractor.rb
120
124
  - lib/substrate/mediums/pdf/reader.rb
125
+ - lib/substrate/mediums/pdf/resolve_outline.rb
121
126
  - lib/substrate/mediums/pdf/text_extractor.rb
127
+ - lib/substrate/mediums/pdf/text_range.rb
122
128
  - lib/substrate/primitives/article_content.rb
123
129
  - lib/substrate/primitives/extraction.rb
124
130
  - lib/substrate/primitives/metadata.rb