wp2txt 2.4.0 → 2.5.0

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.
Files changed (65) hide show
  1. checksums.yaml +4 -4
  2. data/.github/workflows/ci.yml +16 -1
  3. data/.github/workflows/publish-image.yml +8 -4
  4. data/.gitignore +0 -1
  5. data/CHANGELOG.md +23 -0
  6. data/DEVELOPMENT.md +62 -92
  7. data/DEVELOPMENT_ja.md +60 -92
  8. data/Dockerfile +1 -1
  9. data/README.md +54 -8
  10. data/README_ja.md +54 -8
  11. data/bin/wp2txt +23 -6
  12. data/lib/wp2txt/article.rb +1 -2
  13. data/lib/wp2txt/bz2_stream.rb +63 -0
  14. data/lib/wp2txt/cli.rb +48 -26
  15. data/lib/wp2txt/config.rb +2 -11
  16. data/lib/wp2txt/constants.rb +0 -1
  17. data/lib/wp2txt/corpus.rb +1 -21
  18. data/lib/wp2txt/data/template_aliases.json +3 -0
  19. data/lib/wp2txt/data/template_patterns.json +61643 -0
  20. data/lib/wp2txt/dump_snapshot.rb +99 -0
  21. data/lib/wp2txt/extraction_run.rb +272 -0
  22. data/lib/wp2txt/extractor.rb +476 -325
  23. data/lib/wp2txt/fts_index.rb +1 -1
  24. data/lib/wp2txt/index_cache.rb +144 -55
  25. data/lib/wp2txt/index_commands.rb +22 -19
  26. data/lib/wp2txt/link_counter.rb +1 -1
  27. data/lib/wp2txt/magic_words.rb +44 -28
  28. data/lib/wp2txt/metadata_index.rb +6 -13
  29. data/lib/wp2txt/multistream.rb +890 -824
  30. data/lib/wp2txt/output_writer.rb +3 -1
  31. data/lib/wp2txt/parser_functions.rb +23 -5
  32. data/lib/wp2txt/ractor_worker.rb +6 -4
  33. data/lib/wp2txt/regex.rb +24 -4
  34. data/lib/wp2txt/site_info.rb +123 -0
  35. data/lib/wp2txt/stream_store.rb +91 -0
  36. data/lib/wp2txt/template_args.rb +111 -0
  37. data/lib/wp2txt/template_expander.rb +92 -125
  38. data/lib/wp2txt/template_patterns.rb +182 -0
  39. data/lib/wp2txt/utils.rb +160 -125
  40. data/lib/wp2txt/version.rb +1 -1
  41. data/spec/auto_download_spec.rb +9 -6
  42. data/spec/category_fetcher_spec.rb +135 -463
  43. data/spec/cli_targeted_spec.rb +60 -0
  44. data/spec/config_spec.rb +2 -15
  45. data/spec/constants_spec.rb +0 -4
  46. data/spec/dump_fetch_spec.rb +293 -0
  47. data/spec/extraction_run_spec.rb +520 -0
  48. data/spec/index_build_spec.rb +113 -0
  49. data/spec/index_commands_version_spec.rb +17 -0
  50. data/spec/multistream_reader_spec.rb +140 -0
  51. data/spec/multistream_spec.rb +8 -214
  52. data/spec/output_integrity_spec.rb +45 -2
  53. data/spec/regex_spec.rb +30 -0
  54. data/spec/spec_helper.rb +3 -3
  55. data/spec/support/dump_status.rb +34 -0
  56. data/spec/support/multistream_fixture.rb +26 -8
  57. data/spec/template_args_spec.rb +133 -0
  58. data/spec/template_expander_spec.rb +29 -111
  59. data/spec/template_passthrough_spec.rb +17 -2
  60. data/spec/template_patterns_spec.rb +253 -0
  61. data/spec/tracked_paths_spec.rb +168 -0
  62. data/spec/utils_spec.rb +7 -1
  63. metadata +30 -5
  64. data/lib/wp2txt/category_cache.rb +0 -313
  65. data/spec/category_cache_spec.rb +0 -226
@@ -2,22 +2,22 @@
2
2
 
3
3
  require_relative "multistream"
4
4
  require_relative "cli"
5
+ require_relative "extraction_run"
5
6
 
6
7
  module Wp2txt
7
8
  # Article extraction utilities for WpApp
8
9
  module Extractor
9
10
  # Exit codes
10
- EXIT_SUCCESS = 0
11
- EXIT_ERROR = 1
12
- EXIT_PARTIAL = 2
11
+ EXIT_SUCCESS = ExtractionRun::EXIT_SUCCESS
12
+ EXIT_ERROR = ExtractionRun::EXIT_ERROR
13
+ EXIT_PARTIAL = ExtractionRun::EXIT_PARTIAL
13
14
 
14
15
  # Extract specific articles by title
15
16
  def extract_specific_articles(opts)
16
17
  lang = opts[:lang]
17
18
  cache_dir = opts[:cache_dir]
18
- article_titles = Wp2txt::CLI.parse_article_list(opts[:articles])
19
+ article_titles = requested_titles(opts)
19
20
  app_config = Wp2txt::CLI.config
20
- force_update = opts[:update_cache]
21
21
  total_steps = 4
22
22
  start_time = Time.now
23
23
 
@@ -33,143 +33,369 @@ module Wp2txt
33
33
  manager = Wp2txt::DumpManager.new(
34
34
  lang,
35
35
  cache_dir: cache_dir,
36
- dump_expiry_days: app_config.dump_expiry_days
36
+ dump_expiry_days: app_config.dump_expiry_days,
37
+ dump_date: opts[:dump_date],
38
+ update: opts[:update_cache]
37
39
  )
38
40
 
39
41
  # Step 1: Download index
40
42
  print_header("Downloading index", step: 1, total_steps: total_steps)
41
- index_path = manager.download_index(force: force_update)
43
+ index_path = manager.download_index
44
+ normalizer = title_normalizer(manager, index_path)
45
+ requests = normalize_requests(article_titles, normalizer)
42
46
 
43
47
  # Step 2: Load index and find articles
44
48
  print_header("Locating articles", step: 2, total_steps: total_steps)
49
+ index = title_index(index_path, cache_dir, lookup_titles(requests), identity: manager.snapshot.index_file.sha1)
50
+ puts
45
51
 
46
- # Use SQLite cache for fast repeated access
47
- # Early termination: stop parsing when all target articles are found (if not using cache)
48
- index = Wp2txt::MultistreamIndex.new(
49
- index_path,
50
- cache_dir: cache_dir,
51
- target_titles: article_titles
52
- )
52
+ run = ExtractionRun.new(requests.keys, output_dir: opts[:output_dir], base_name: "#{lang}wiki_articles",
53
+ source: dump_source(manager))
54
+ format = opts[:format].to_s.downcase.to_sym
55
+ config = build_extraction_config(opts, format, manager)
53
56
 
54
- if index.loaded_from_cache?
55
- puts " Index loaded from cache (#{index.size} entries)"
56
- elsif index.early_terminated?
57
- puts " Early termination: found all #{article_titles.size} articles"
57
+ # Steps 3 and 4: fetch the ranges holding the articles, then extract them
58
+ print_header("Extracting articles", step: 3, total_steps: total_steps)
59
+ writer = nil
60
+ begin
61
+ writer = staged_writer(run, opts, format)
62
+ extract_requests(manager, index_path, index, requests, run, writer, config,
63
+ normalizer: normalizer, follow_redirects: !opts[:no_follow_redirects]) do |title, result|
64
+ print_extraction_result(title, result)
65
+ end
66
+ output_files = writer.close
67
+ rescue Wp2txt::FileIOError, SystemCallError => e
68
+ return abandon_run(run, writer, e)
58
69
  end
59
- puts
60
70
 
61
- # Find requested articles
62
- found_articles = []
63
- not_found = []
71
+ finish_run(run, output_files, "Total time" => format_duration(Time.now - start_time))
72
+ end
64
73
 
65
- article_titles.each do |title|
66
- entry = index.find_by_title(title)
67
- if entry
68
- found_articles << entry
69
- print_list_item("#{title}", status: :success)
70
- else
71
- not_found << title
72
- print_list_item("#{title} (not found)", status: :error)
73
- end
74
+ # What the manifest records about the dump: its version, and how it was
75
+ # chosen (asked for, checked recently, checked now, or cached when offline)
76
+ def dump_source(manager)
77
+ manager.snapshot.to_h.merge(chosen: manager.snapshot_origin.to_s)
78
+ end
79
+
80
+ # Titles from --articles (comma-separated) or --articles-file (one per line)
81
+ def requested_titles(opts)
82
+ titles = if opts[:articles_file]
83
+ File.readlines(opts[:articles_file], chomp: true, encoding: "UTF-8")
84
+ .map(&:strip).reject { |line| line.empty? || line.start_with?("#") }
85
+ else
86
+ Wp2txt::CLI.parse_article_list(opts[:articles])
87
+ end
88
+ titles.uniq
89
+ end
90
+
91
+ # The normalizer for titles of this dump, from the siteinfo in its first stream
92
+ def title_normalizer(manager, index_path)
93
+ offsets = Wp2txt.each_index_line(index_path).lazy.map { |offset, _id, _title| offset }.uniq.first(2)
94
+ header_end = offsets.first.to_i.positive? ? offsets.first : offsets[1]
95
+ raise SnapshotError, "the index #{File.basename(index_path)} is empty" unless header_end
96
+
97
+ Wp2txt::TitleNormalizer.new(manager.site_info(header_end))
98
+ end
99
+
100
+ # Requested titles, each with the title to look up: normalized the way
101
+ # MediaWiki does. Titles that normalize alike are one request, unless the
102
+ # normalization upper-cased a non-ASCII letter (Ruby may map it unlike
103
+ # MediaWiki) or they are listed pages with different IDs; those stay
104
+ # apart, and share the article if they do come to the same one.
105
+ # @param ids [Hash{String => Integer}, nil] page IDs of listed titles
106
+ # @return [Hash{String => String}] requested title => normalized title
107
+ def normalize_requests(titles, normalizer, ids: nil)
108
+ first_by_normalized = {}
109
+ titles.each_with_object({}) do |title, requests|
110
+ normalized = normalizer.normalize(title)
111
+ earlier = first_by_normalized[normalized]
112
+ next if earlier && !normalizer.uncertain_case?(title) && !normalizer.uncertain_case?(earlier) &&
113
+ (ids.nil? || ids[earlier] == ids[title])
114
+
115
+ first_by_normalized[normalized] ||= title
116
+ requests[title] = normalized
74
117
  end
118
+ end
75
119
 
76
- if found_articles.empty?
77
- puts unless quiet?
78
- print_error("No articles found. Please check the titles.")
79
- return EXIT_ERROR
120
+ # Titles to look for: the normalized ones and, as typed, those that differ
121
+ # (Ruby's case mapping does not always match MediaWiki's)
122
+ def lookup_titles(requests)
123
+ (requests.values + requests.keys).uniq
124
+ end
125
+
126
+ # A built SQLite cache answers at once; otherwise the index is read only
127
+ # until every title is found, keeping just those titles
128
+ def title_index(index_path, cache_dir, titles, identity: nil)
129
+ cache = Wp2txt::IndexCache.new(index_path, cache_dir: cache_dir, identity: identity)
130
+ if cache.valid?
131
+ puts " Index cache: #{File.basename(cache.cache_path)}"
132
+ return Wp2txt::LazyTitleIndex.new(cache)
80
133
  end
81
134
 
82
- # Step 3: Download streams
83
- streams_needed = found_articles.map { |e| e[:offset] }.uniq.sort
84
- print_header("Downloading data (#{streams_needed.size} streams)", step: 3, total_steps: total_steps)
85
- multistream_path = download_partial_streams(manager, index, streams_needed, force: force_update)
135
+ index = Wp2txt::MultistreamIndex.new(index_path, use_cache: false, target_titles: titles)
136
+ puts " Early termination: found all #{titles.size} titles" if index.early_terminated?
137
+ index
138
+ end
86
139
 
87
- # Create multistream reader, reusing the existing index (avoids double parsing)
88
- reader = Wp2txt::MultistreamReader.new(multistream_path, index)
140
+ # The index of a dump as a SQLite cache, building the cache when needed
141
+ def lazy_index(index_path, cache_dir, identity: nil)
142
+ cache = Wp2txt::IndexCache.new(index_path, cache_dir: cache_dir, identity: identity)
143
+ if cache.valid?
144
+ puts " Index cache: #{File.basename(cache.cache_path)}"
145
+ else
146
+ count = cache.build! do |n|
147
+ next unless (n % INDEX_PROGRESS_THRESHOLD).zero?
89
148
 
90
- # Build config for processing
91
- format = opts[:format].to_s.downcase.to_sym
92
- config = build_extraction_config(opts, format)
149
+ print "\r Indexed #{n / 1_000_000.0}M entries..."
150
+ $stdout.flush
151
+ end
152
+ puts "\r Index cache built (#{count} entries)"
153
+ end
154
+ Wp2txt::LazyTitleIndex.new(cache)
155
+ end
93
156
 
94
- # Create output writer
95
- base_name = "#{lang}wiki_articles"
96
- writer = OutputWriter.new(
97
- output_dir: opts[:output_dir],
98
- base_name: base_name,
157
+ # Writer for a run: files go to the run's staging directory and are
158
+ # published with the manifest once every article has been handled
159
+ def staged_writer(run, opts, format)
160
+ OutputWriter.new(
161
+ output_dir: run.staging_dir,
162
+ base_name: run.base_name,
99
163
  format: format,
100
164
  file_size_mb: opts[:file_size]
101
165
  )
166
+ end
102
167
 
103
- # Step 4: Extract articles
104
- print_header("Extracting articles", step: 4, total_steps: total_steps)
105
- extracted_count = 0
106
- extraction_failures = []
107
-
108
- found_articles.each do |entry|
109
- title = entry[:title]
110
- page = reader.extract_article(title)
111
-
112
- if page
113
- article = Article.new(page[:text], page[:title], !config[:marker])
114
- set_source_fields(article, page[:id], page[:revision_id], page[:text], config)
115
- result = format_article(article, config)
116
- writer.write(result)
117
- extracted_count += 1
118
- print_list_item("#{title}", status: :success)
168
+ # Locate, read, format and write requested articles, recording a result
169
+ # for every request. A redirect is followed one step (unless
170
+ # follow_redirects is false): the article it points to is written under
171
+ # the requested title. Requests that come to the same article share one
172
+ # reading of it, and the article is written once.
173
+ # @param requests [Hash{String => String}] requested title => title to look up
174
+ # @param ids [Hash{String => Integer}, nil] page IDs the requests must match
175
+ # @yield [requested_title, result] once each request has its result
176
+ def extract_requests(manager, index_path, index, requests, run, writer, config,
177
+ normalizer:, follow_redirects: true, ids: nil, num_processes: 1, &report)
178
+ assignments = locate_requests(index, requests, run, ids, &report)
179
+ redirects = read_requests(manager, index, assignments, run, writer, config,
180
+ stage: follow_redirects ? :first : :as_is, num_processes: num_processes, &report)
181
+ return if redirects.empty?
182
+
183
+ targets = {}
184
+ redirects.each do |requested, target|
185
+ target_title, section = target.split("#", 2)
186
+ run.results[requested][:redirect_section] = section if section && !section.empty?
187
+ resolved = normalizer.parse(target_title)
188
+ if target_title.strip.empty?
189
+ run.failed(requested, :redirect_unresolved, "cycle: #{target}")
190
+ elsif Wp2txt::SiteInfo::VIRTUAL_NAMESPACES.include?(resolved.namespace_id)
191
+ run.failed(requested, :redirect_unresolved, "foreign: #{target}")
192
+ elsif resolved.text == run.results[requested][:title]
193
+ run.failed(requested, :redirect_unresolved, "cycle: #{target}")
194
+ else
195
+ (targets[resolved.text] ||= []) << requested
196
+ next
197
+ end
198
+ report&.call(requested, run.results[requested])
199
+ end
200
+ return if targets.empty?
201
+
202
+ # Without the SQLite cache, a second scan looks for just these titles
203
+ target_index = if index.respond_to?(:find_by_titles)
204
+ index
205
+ else
206
+ Wp2txt::MultistreamIndex.new(index_path, use_cache: false, target_titles: targets.keys,
207
+ show_progress: false)
208
+ end
209
+ found = lookup(target_index, targets.keys)
210
+ target_assignments = {}
211
+ targets.each do |target, requesters|
212
+ entry = found[target]
213
+ requesters.each do |requested|
214
+ if entry
215
+ run.located(requested, as: entry[:title])
216
+ run.results[requested][:redirect] = target
217
+ (target_assignments[entry] ||= []) << requested
218
+ else
219
+ run.failed(requested, :redirect_unresolved, "missing: #{target}")
220
+ report&.call(requested, run.results[requested])
221
+ end
222
+ end
223
+ end
224
+ read_requests(manager, target_index, target_assignments, run, writer, config,
225
+ stage: :target, num_processes: num_processes, &report)
226
+ end
227
+
228
+ # @return [Hash{String => Hash}] entries for the titles found
229
+ def lookup(index, titles)
230
+ return index.find_by_titles(titles) if index.respond_to?(:find_by_titles)
231
+
232
+ titles.filter_map { |t| (entry = index.find_by_title(t)) && [t, entry] }.to_h
233
+ end
234
+
235
+ # Look requests up in the index, by page ID first when one is given
236
+ # @return [Hash{Hash => Array<String>}] index entry => requests it answers
237
+ def locate_requests(index, requests, run, ids)
238
+ found = lookup(index, (requests.values + requests.keys).uniq)
239
+ by_id = ids && index.respond_to?(:find_by_ids) ? index.find_by_ids(ids.values.compact) : {}
240
+ requests.each_with_object({}) do |(requested, title), assignments|
241
+ page_id = ids&.dig(requested)
242
+ entry = by_id[page_id] if page_id
243
+ entry ||= found[title] || found[requested]
244
+ if entry && page_id && entry[:page_id] != page_id
245
+ run.failed(requested, :identity_mismatch, "page #{page_id} is not in the dump; #{entry[:title]} is page #{entry[:page_id]}")
246
+ elsif entry
247
+ run.located(requested, as: entry[:title])
248
+ (assignments[entry] ||= []) << requested
249
+ next
119
250
  else
120
- extraction_failures << title
121
- print_list_item("#{title} (extraction failed)", status: :warning)
251
+ run.failed(requested, :not_found, title == requested ? nil : "looked up as #{title}")
122
252
  end
253
+ yield requested, run.results[requested] if block_given?
123
254
  end
255
+ end
124
256
 
125
- # Close output
126
- output_files = writer.close
127
- total_time = Time.now - start_time
257
+ # Read the articles of index entries and write them for the requests they
258
+ # answer. In the :first stage, a redirect is not written but returned, to
259
+ # be followed; in the :target stage (articles redirected to), a redirect
260
+ # means a chain, which is not followed; :as_is writes redirects as they are.
261
+ # @return [Hash{String => String}] request => redirect target, in the :first stage
262
+ def read_requests(manager, index, assignments, run, writer, config, stage:, num_processes: 1, &block)
263
+ return {} if assignments.empty?
264
+
265
+ redirects = {}
266
+ offsets = assignments.keys.map { |e| e[:offset] }.uniq.sort
267
+ reader = Wp2txt::MultistreamReader.new(stream_source(manager, index, offsets), index)
268
+ procs = assignments.size > 50 && offsets.size > 1 ? [num_processes, offsets.size].min : 1
269
+ # Forked readers must not inherit unwritten output: they would write it again
270
+ reader.each_entry_result(assignments.keys, num_processes: procs, before_fork: -> { writer.flush }) do |entry, page, error|
271
+ process_entry_result(entry, page, error, assignments, run, writer, config, stage, redirects, &block)
272
+ end
273
+ redirects
274
+ ensure
275
+ reader&.close
276
+ end
128
277
 
129
- # Summary
130
- has_issues = not_found.any? || extraction_failures.any?
131
- status = has_issues ? :warning : :success
278
+ # Record (and write) the result of one index entry for the requests it answers
279
+ def process_entry_result(entry, page, error, assignments, run, writer, config, stage, redirects)
280
+ assignments[entry].each do |requested|
281
+ if error
282
+ run.failed(requested, error[:reason], error[:message])
283
+ elsif page.nil?
284
+ run.failed(requested, :index_mismatch)
285
+ elsif page[:id] != entry[:page_id]
286
+ run.failed(requested, :index_mismatch, "the index says page #{entry[:page_id]}; the dump has page #{page[:id]}")
287
+ elsif page[:redirect] && stage == :first
288
+ redirects[requested] = page[:redirect]
289
+ next
290
+ elsif page[:redirect] && stage == :target
291
+ run.failed(requested, :redirect_unresolved, "chain: #{run.results[requested][:redirect]} -> #{page[:redirect]}")
292
+ elsif !page[:text_available]
293
+ run.failed(requested, :text_unavailable)
294
+ elsif (earlier = run.written_for(page[:id]))
295
+ run.written_as(requested, earlier)
296
+ else
297
+ run.results[requested][:redirect] ||= page[:redirect] if page[:redirect]
298
+ if write_article(page, requested, writer, config)
299
+ run.written(requested, page_id: page[:id])
300
+ else
301
+ run.skipped_empty(requested)
302
+ end
303
+ end
304
+ yield requested, run.results[requested] if block_given?
305
+ end
306
+ end
132
307
 
133
- print_summary("Extraction Complete", {
134
- "Extracted" => "#{extracted_count}/#{article_titles.size}",
135
- "Output files" => output_files.size.to_s,
136
- "Total time" => format_duration(total_time)
137
- }, status: status)
308
+ # Format and write one article for a request
309
+ # @return [Boolean] whether anything was written
310
+ def write_article(page, requested, writer, config)
311
+ article = Article.new(page[:text], page[:title], !config[:marker])
312
+ set_source_fields(article, page[:id], page[:revision_id], page[:text], config)
313
+ result = format_article(article, config)
314
+ if result.is_a?(Hash) && requested != page[:title]
315
+ result = result.each_with_object({}) do |(key, value), out|
316
+ out[key] = value
317
+ out["requested_title"] = requested if key == "title"
318
+ end
319
+ end
320
+ writer.write(result)
321
+ end
138
322
 
139
- if not_found.any?
323
+ def print_extraction_result(title, result)
324
+ case result[:status]
325
+ when :written then print_list_item(title, status: :success)
326
+ when :skipped_empty then print_list_item("#{title} (skipped: empty)", status: :pending)
327
+ else print_list_item("#{title} (#{result[:reason].to_s.tr('_', ' ')})", status: :error)
328
+ end
329
+ end
330
+
331
+ # Publish the output and manifest of a run, report on it, and return the
332
+ # exit code that follows from its results
333
+ def finish_run(run, output_files, timings = {})
334
+ published = run.publish!(output_files)
335
+ exit_code = run.exit_code
336
+ c = run.counts
337
+ status = { ExtractionRun::EXIT_SUCCESS => :success, ExtractionRun::EXIT_PARTIAL => :warning }
338
+ .fetch(exit_code, :error)
339
+
340
+ written = c[:records] == c[:written] ? c[:written].to_s : "#{c[:written]} (#{c[:records]} articles)"
341
+ stats = { "Requested" => c[:requested].to_s, "Written" => written }
342
+ stats["Skipped (empty)"] = c[:skipped_empty].to_s if c[:skipped_empty].positive?
343
+ stats["Failed"] = c[:failed].to_s if c[:failed].positive?
344
+ stats["Output files"] = published.size.to_s
345
+ print_summary("Extraction Complete", stats.merge(timings), status: status)
346
+
347
+ print_failures(run)
348
+ unless run.listing_complete?
140
349
  puts unless quiet?
141
- print_warning("Not found in index (#{not_found.size}):")
142
- not_found.each { |t| print_list_item(t, status: :error) }
350
+ print_warning("The list of titles is incomplete; titles it did not reach are not counted above.")
143
351
  end
144
352
 
145
353
  puts unless quiet?
146
354
  puts pastel.dim("Output files:") unless quiet?
147
- output_files.each { |f| print_list_item(f, status: :success) }
148
-
149
- # Return appropriate exit code
150
- has_issues ? EXIT_PARTIAL : EXIT_SUCCESS
355
+ published.each { |f| print_list_item(f, status: :success) }
356
+ print_list_item("#{run.manifest_path} (run #{run.run_id})", status: :success)
357
+ exit_code
358
+ rescue Wp2txt::FileIOError, SystemCallError => e
359
+ run.discard_staging
360
+ print_error("Could not write the output: #{e.message}")
361
+ ExtractionRun::EXIT_ERROR
151
362
  end
152
363
 
153
- # Download only the streams containing the requested articles
154
- # @param manager [DumpManager] The dump manager
155
- # @param index [MultistreamIndex] The multistream index
156
- # @param stream_offsets [Array<Integer>] Byte offsets of streams to download
157
- # @param force [Boolean] Force re-download even if cached
158
- def download_partial_streams(manager, index, stream_offsets, force: false)
159
- # Calculate how many streams are needed
160
- all_offsets = index.stream_offsets
161
- max_offset_needed = stream_offsets.max
364
+ def print_failures(run)
365
+ failures = run.failures
366
+ return if failures.empty?
367
+
368
+ # Warnings go to stderr; keep them after the summary already printed
369
+ $stdout.flush
370
+ puts unless quiet?
371
+ print_warning("Not extracted (#{failures.size}):")
372
+ failures.first(20).each do |r|
373
+ print_list_item("#{r[:requested_title]}: #{r[:reason].to_s.tr('_', ' ')}", status: :error)
374
+ end
375
+ print_list_item("... #{failures.size - 20} more (see the manifest)", status: :error) if failures.size > 20
376
+ end
162
377
 
163
- # Find the index of the highest needed stream
164
- max_idx = all_offsets.index(max_offset_needed)
165
- if max_idx.nil? || max_idx >= all_offsets.size - 1
166
- # Need full file for last stream
167
- return manager.download_multistream(force: force)
378
+ # Where to read the ranges holding the requested articles from: the cached
379
+ # whole dump when it is known to be complete, otherwise just those ranges,
380
+ # fetched into the stream store
381
+ # @param index [MultistreamIndex] the index (possibly stopped early)
382
+ # @param stream_offsets [Array<Integer>] start offsets of the ranges needed
383
+ # @return [String, StreamStore] a source MultistreamReader can read
384
+ def stream_source(manager, index, stream_offsets)
385
+ full = manager.verified_full_dump
386
+ if full
387
+ puts "Using cached dump: #{File.basename(full)}"
388
+ return full
168
389
  end
169
390
 
170
- # Request partial download (DumpManager handles caching logic)
171
- stream_count = max_idx + 1
172
- manager.download_multistream(max_streams: stream_count, force: force)
391
+ all_offsets = index.stream_offsets
392
+ last_end = index.respond_to?(:stream_end_offset) ? index.stream_end_offset : nil
393
+ ranges = stream_offsets.map do |offset|
394
+ i = all_offsets.index(offset)
395
+ # Past the last offset the index knows: where it stopped, or the end of the file
396
+ [offset, all_offsets[i + 1] || last_end || manager.snapshot.dump_file.size]
397
+ end
398
+ manager.fetch_streams(ranges)
173
399
  end
174
400
 
175
401
  # Show download estimate before confirmation
@@ -224,16 +450,10 @@ module Wp2txt
224
450
  print_list_item("Dump: #{pastel.green('cached')} (#{dump_size}, #{dump_date_str} - #{dump_age_str})", status: :success)
225
451
  end
226
452
  else
227
- # Check for partial downloads
228
- partial = manager.find_suitable_partial_cache(1)
229
- if partial
230
- partial_size = format_size(File.size(partial))
231
- partial_date = File.mtime(partial).strftime("%Y-%m-%d")
232
- print_list_item("Dump: #{pastel.cyan('partial cached')} (#{partial_size}, #{partial_date})", status: :success)
233
- print_list_item(" Additional download may be required depending on article locations", status: :pending)
234
- else
235
- print_list_item("Dump: #{pastel.yellow('download required')} (several GB)", status: :warning)
236
- end
453
+ # Only the ranges holding the articles are fetched
454
+ cached = manager.stream_store.size
455
+ detail = cached.positive? ? "#{format_size(cached)} of ranges cached" : "only the ranges holding the articles"
456
+ print_list_item("Dump: #{pastel.cyan('fetched in parts')} (#{detail})", status: :success)
237
457
  end
238
458
 
239
459
  if cache_is_stale
@@ -246,7 +466,8 @@ module Wp2txt
246
466
  end
247
467
 
248
468
  # Build config hash for article extraction
249
- def build_extraction_config(opts, format)
469
+ # @param manager [DumpManager, nil] the run's dump manager, for page properties of its dump
470
+ def build_extraction_config(opts, format, manager = nil)
250
471
  config = {
251
472
  format: format,
252
473
  num_procs: 1, # Single-threaded for article extraction
@@ -258,10 +479,16 @@ module Wp2txt
258
479
  summary_only metadata_only marker extract_citations expand_templates].each do |opt|
259
480
  config[opt] = opts[opt]
260
481
  end
482
+ # A redirect page extracted as itself says where it points
483
+ config[:redirect] = true if opts[:no_follow_redirects]
484
+ # Templates are read as the wiki of the dump reads them, and count
485
+ # dates from the dump's date
486
+ config[:lang] = opts[:lang]&.to_s
487
+ config[:dump_date] = manager&.snapshot&.time
261
488
 
262
489
  # Page properties, when imported into the index of the full cached dump
263
- if format == :json && opts[:lang]
264
- full_dump = Wp2txt::DumpManager.new(opts[:lang], cache_dir: opts[:cache_dir]).cached_multistream_path
490
+ if format == :json && manager
491
+ full_dump = manager.cached_multistream_path
265
492
  config[:page_properties] = load_page_properties(full_dump, opts[:cache_dir])
266
493
  end
267
494
 
@@ -286,9 +513,7 @@ module Wp2txt
286
513
  category = opts[:from_category]
287
514
  max_depth = opts[:depth]
288
515
  cache_dir = opts[:cache_dir]
289
- dry_run = opts[:dry_run]
290
- skip_confirm = opts[:yes]
291
- total_steps = 6
516
+ total_steps = 5
292
517
  start_time = Time.now
293
518
 
294
519
  # Mode banner
@@ -299,251 +524,177 @@ module Wp2txt
299
524
  "Output" => opts[:output_dir]
300
525
  })
301
526
 
302
- # Get config values
303
527
  app_config = Wp2txt::CLI.config
304
-
305
- # Create category fetcher
306
- fetcher = Wp2txt::CategoryFetcher.new(
307
- lang, category,
308
- max_depth: max_depth,
309
- cache_expiry_days: app_config.category_expiry_days
310
- )
311
-
312
- # Step 1: Fetch preview
313
- print_header("Scanning category", step: 1, total_steps: total_steps)
314
- spinner = create_spinner("Fetching category information...")
528
+ fetcher = Wp2txt::CategoryFetcher.new(lang, category, max_depth: max_depth)
529
+ # Noted before the listing: a failure sets aside only the manifest that
530
+ # was in place when this run began, never one published meanwhile
531
+ start = ExtractionRun.new([], output_dir: opts[:output_dir], base_name: category_base_name(lang, category))
532
+
533
+ # Step 1: List the category, once; the same listing is extracted below
534
+ print_header("Listing category", step: 1, total_steps: total_steps)
535
+ spinner = create_spinner("Fetching the category listing...")
315
536
  spinner.auto_spin
316
-
317
537
  begin
318
- preview = fetcher.fetch_preview
538
+ listing = fetcher.fetch_listing
319
539
  spinner.success(pastel.green("Done!"))
320
- rescue Net::OpenTimeout, Net::ReadTimeout, SocketError, Errno::ECONNREFUSED, OpenSSL::SSL::SSLError, JSON::ParserError, IOError => e
540
+ rescue Wp2txt::CategoryFetcher::IncompleteListing => e
541
+ spinner.error(pastel.red("Incomplete!"))
542
+ listing = e.listing
543
+ unless opts[:allow_incomplete_category]
544
+ print_error("#{e.message}. Nothing was extracted; use --allow-incomplete-category " \
545
+ "to extract the #{listing.articles.size} articles listed so far.")
546
+ start.abandon! unless opts[:dry_run]
547
+ return EXIT_ERROR
548
+ end
549
+ print_warning(e.message)
550
+ rescue Wp2txt::CategoryFetcher::CategoryNotFound => e
321
551
  spinner.error(pastel.red("Failed!"))
322
- print_error("Error fetching category: #{e.message}")
552
+ print_error(e.message)
323
553
  return EXIT_ERROR
324
554
  end
325
555
 
326
- # Display preview
327
- print_subheader("Category Preview")
328
- print_info("Category", preview[:category])
329
- print_info("Depth", preview[:depth].to_s)
330
- puts
556
+ show_category_preview(fetcher.preview_of(listing))
557
+ if listing.articles.empty? && listing.complete
558
+ return EXIT_SUCCESS if opts[:dry_run]
559
+ refused = category_refusal(opts)
560
+ return refused if refused
331
561
 
332
- if preview[:subcategories] && !preview[:subcategories].empty?
333
- puts pastel.dim("Categories scanned:")
334
- preview[:subcategories].each do |subcat|
335
- print_list_item("#{subcat[:name]} (#{subcat[:article_count]} articles)")
336
- end
337
- puts
562
+ return finish_empty_listing(opts, category, listing)
338
563
  end
339
564
 
340
- puts pastel.dim("Summary:")
341
- print_info("Subcategories", (preview[:total_subcategories] || 0).to_s, indent: 1)
342
- print_info("Total articles", pastel.bold(preview[:total_articles].to_s), indent: 1)
343
- puts
344
-
345
- # Check if there are any articles
346
- if preview[:total_articles].zero?
347
- print_warning("No articles found in this category.")
348
- return EXIT_SUCCESS # Not an error, just empty category
349
- end
350
-
351
- # Warn about large extractions
352
- if preview[:total_articles] > 1000
353
- print_warning("Large category with #{preview[:total_articles]} articles.")
354
- puts pastel.yellow(" Extraction may take a long time and require significant disk space.")
355
- puts
356
- end
357
-
358
- # Show cache status before confirmation
359
- temp_manager = Wp2txt::DumpManager.new(
565
+ # One manager, so one dump version, for the whole run
566
+ manager = Wp2txt::DumpManager.new(
360
567
  lang,
361
568
  cache_dir: cache_dir,
362
- dump_expiry_days: app_config.dump_expiry_days
569
+ dump_expiry_days: app_config.dump_expiry_days,
570
+ dump_date: opts[:dump_date],
571
+ update: opts[:update_cache]
363
572
  )
364
- cache_stale = show_download_estimate(temp_manager, app_config)
365
- force_update = opts[:update_cache]
573
+ show_download_estimate(manager, app_config)
366
574
 
367
- # Dry run mode - exit here
368
- if dry_run
575
+ if opts[:dry_run]
369
576
  print_info_message("Dry run mode - no articles will be extracted.")
370
577
  return EXIT_SUCCESS
371
578
  end
579
+ refused = category_refusal(opts)
580
+ return refused if refused
581
+
582
+ # Step 2: Download index
583
+ print_header("Downloading index", step: 2, total_steps: total_steps)
584
+ index_path = manager.download_index
585
+ normalizer = title_normalizer(manager, index_path)
586
+
587
+ # Step 3: Look titles up in the SQLite cache of the index, built line by
588
+ # line on first use, instead of holding the whole index in memory
589
+ print_header("Locating articles in dump", step: 3, total_steps: total_steps)
590
+ index = lazy_index(index_path, cache_dir, identity: manager.snapshot.index_file.sha1)
591
+
592
+ requests = normalize_requests(listing.articles.keys, normalizer, ids: listing.articles)
593
+ run = ExtractionRun.new(requests.keys, output_dir: opts[:output_dir],
594
+ base_name: category_base_name(lang, category),
595
+ source: dump_source(manager))
596
+ run.listing!(**listing_record(listing, category, max_depth))
597
+ format = opts[:format].to_s.downcase.to_sym
598
+ config = build_extraction_config(opts, format, manager)
372
599
 
373
- # Confirmation prompt
374
- unless skip_confirm
375
- unless $stdin.tty?
376
- print_error("Interactive confirmation required.")
377
- puts pastel.red(" Use --yes to skip confirmation when running non-interactively.")
378
- return EXIT_ERROR
379
- end
380
-
381
- unless confirm?("Proceed with extraction?")
382
- puts "Extraction cancelled."
383
- return EXIT_SUCCESS # User chose to cancel
384
- end
385
- end
386
-
387
- # Step 2: Fetch full article list
388
- print_header("Fetching articles from API", step: 2, total_steps: total_steps)
389
- spinner = create_spinner("Fetching article list...")
390
- spinner.auto_spin
391
-
600
+ # Steps 4 and 5: fetch the ranges holding the articles, then extract them
601
+ print_header("Extracting articles", step: 4, total_steps: total_steps)
602
+ bar = create_progress_bar(" Processing", requests.size)
603
+ extraction_start = Time.now
604
+ writer = nil
392
605
  begin
393
- article_titles = fetcher.fetch_articles
394
- spinner.success(pastel.green("#{article_titles.size} articles"))
395
- rescue Net::OpenTimeout, Net::ReadTimeout, SocketError, Errno::ECONNREFUSED, OpenSSL::SSL::SSLError, JSON::ParserError, IOError => e
396
- spinner.error(pastel.red("Failed!"))
397
- print_error("Error fetching articles: #{e.message}")
398
- return EXIT_ERROR
399
- end
400
-
401
- if article_titles.empty?
402
- print_warning("No articles to extract.")
403
- return EXIT_SUCCESS # Not an error, just empty result
606
+ writer = staged_writer(run, opts, format)
607
+ extract_requests(manager, index_path, index, requests, run, writer, config,
608
+ normalizer: normalizer, follow_redirects: !opts[:no_follow_redirects],
609
+ ids: listing.articles, num_processes: 4) { bar.advance }
610
+ output_files = writer.close
611
+ rescue Wp2txt::FileIOError, SystemCallError => e
612
+ return abandon_run(run, writer, e)
404
613
  end
614
+ bar.finish
405
615
 
406
- # Create dump manager
407
- manager = Wp2txt::DumpManager.new(
408
- lang,
409
- cache_dir: cache_dir,
410
- dump_expiry_days: app_config.dump_expiry_days
411
- )
412
-
413
- # Step 3: Download index
414
- print_header("Downloading index", step: 3, total_steps: total_steps)
415
- index_path = manager.download_index(force: force_update)
416
-
417
- # Step 4: Load index and locate articles
418
- print_header("Locating articles in dump", step: 4, total_steps: total_steps)
419
-
420
- # Use SQLite cache for fast repeated access
421
- index = Wp2txt::MultistreamIndex.new(index_path, cache_dir: cache_dir)
422
-
423
- if index.loaded_from_cache?
424
- puts " Index loaded from cache (#{index.size} entries)"
425
- else
426
- puts " Index parsed (#{index.size} entries)"
427
- end
616
+ finish_run(run, output_files,
617
+ "Extraction time" => format_duration(Time.now - extraction_start),
618
+ "Total time" => format_duration(Time.now - start_time))
619
+ end
428
620
 
429
- # Find articles in index
430
- found_articles = []
431
- not_found = []
621
+ def show_category_preview(preview)
622
+ print_subheader("Category Preview")
623
+ print_info("Category", preview[:category])
624
+ print_info("Depth", preview[:depth].to_s)
625
+ puts
432
626
 
433
- article_titles.each do |title|
434
- entry = index.find_by_title(title)
435
- if entry
436
- found_articles << entry
437
- else
438
- not_found << title
627
+ unless preview[:subcategories].empty?
628
+ puts pastel.dim("Categories scanned:")
629
+ preview[:subcategories].each do |subcat|
630
+ print_list_item("#{subcat[:name]} (#{subcat[:article_count]} articles)")
439
631
  end
632
+ puts
440
633
  end
441
634
 
442
- print_list_item("Found in dump: #{found_articles.size}", status: :success)
443
- print_list_item("Not in dump: #{not_found.size}", status: not_found.any? ? :warning : :success) if not_found.any?
444
-
445
- if found_articles.empty?
446
- print_error("No articles found in dump. The dump may be out of date.")
447
- return EXIT_ERROR
448
- end
449
-
450
- # Step 5: Download multistream
451
- streams_needed = found_articles.map { |e| e[:offset] }.uniq.sort
452
- print_header("Downloading data (#{streams_needed.size} streams)", step: 5, total_steps: total_steps)
453
- multistream_path = download_partial_streams(manager, index, streams_needed, force: force_update)
454
-
455
- # Create multistream reader, reusing the existing index (avoids double parsing)
456
- reader = Wp2txt::MultistreamReader.new(multistream_path, index)
457
-
458
- # Build config
459
- format = opts[:format].to_s.downcase.to_sym
460
- config = build_extraction_config(opts, format)
461
-
462
- # Create output writer
463
- base_name = "#{lang}wiki_#{sanitize_filename(category)}"
464
- writer = OutputWriter.new(
465
- output_dir: opts[:output_dir],
466
- base_name: base_name,
467
- format: format,
468
- file_size_mb: opts[:file_size]
469
- )
635
+ puts pastel.dim("Summary:")
636
+ print_info("Subcategories", preview[:total_subcategories].to_s, indent: 1)
637
+ print_info("Total articles", pastel.bold(preview[:total_articles].to_s), indent: 1)
638
+ puts
470
639
 
471
- # Step 6: Extract and process articles
472
- print_header("Extracting articles", step: 6, total_steps: total_steps)
473
- total_count = found_articles.size
474
- bar = create_progress_bar(" Processing", total_count)
640
+ return unless preview[:total_articles] > 1000
475
641
 
476
- extracted_count = 0
477
- extraction_start = Time.now
642
+ print_warning("Large category with #{preview[:total_articles]} articles.")
643
+ puts pastel.yellow(" Extraction may take a long time and require significant disk space.")
644
+ puts
645
+ end
478
646
 
479
- # Use parallel extraction for large batches (>50 articles across multiple streams)
480
- streams_count = found_articles.map { |e| e[:offset] }.uniq.size
481
- use_parallel = total_count > 50 && streams_count > 1
482
-
483
- if use_parallel
484
- # Parallel extraction: process streams concurrently
485
- num_procs = [streams_count, 4].min # Cap at 4 processes
486
- pages = reader.each_article_parallel(found_articles, num_processes: num_procs).to_a
487
-
488
- pages.each do |page|
489
- article = Article.new(page[:text], page[:title], !config[:marker])
490
- set_source_fields(article, page[:id], page[:revision_id], page[:text], config)
491
- result = format_article(article, config)
492
- writer.write(result)
493
- extracted_count += 1
494
- bar.advance
495
- end
496
- else
497
- # Sequential extraction for small batches
498
- found_articles.each do |entry|
499
- title = entry[:title]
500
- page = reader.extract_article(title)
501
-
502
- if page
503
- article = Article.new(page[:text], page[:title], !config[:marker])
504
- set_source_fields(article, page[:id], page[:revision_id], page[:text], config)
505
- result = format_article(article, config)
506
- writer.write(result)
507
- extracted_count += 1
508
- end
647
+ # @return [Integer, nil] the exit code when the extraction does not go on
648
+ def category_refusal(opts)
649
+ return nil if opts[:yes]
509
650
 
510
- bar.advance
511
- end
651
+ unless $stdin.tty?
652
+ print_error("Interactive confirmation required.")
653
+ puts pastel.red(" Use --yes to skip confirmation when running non-interactively.")
654
+ return EXIT_ERROR
512
655
  end
656
+ return nil if confirm?("Proceed with extraction?")
513
657
 
514
- bar.finish
515
- extraction_time = Time.now - extraction_start
658
+ puts "Extraction cancelled."
659
+ EXIT_SUCCESS
660
+ end
516
661
 
517
- # Close output
518
- output_files = writer.close
662
+ # What the manifest records about a category listing
663
+ def listing_record(listing, category, depth)
664
+ {
665
+ complete: listing.complete,
666
+ category: category,
667
+ depth: depth,
668
+ categories: listing.categories.size,
669
+ started_at: listing.started_at&.iso8601,
670
+ finished_at: listing.finished_at&.iso8601,
671
+ error: listing.error
672
+ }.compact
673
+ end
519
674
 
520
- # Summary
521
- total_time = Time.now - start_time
522
- status = not_found.empty? ? :success : :warning
675
+ def category_base_name(lang, category)
676
+ "#{lang}wiki_#{sanitize_filename(category)}"
677
+ end
523
678
 
524
- print_summary("Extraction Complete", {
525
- "Articles extracted" => "#{extracted_count}/#{article_titles.size}",
526
- "Output files" => output_files.size.to_s,
527
- "Extraction time" => format_duration(extraction_time),
528
- "Total time" => format_duration(total_time)
529
- }, status: status)
679
+ # A category that holds no articles is a complete, empty result: it gets a
680
+ # manifest like any other, replacing the output of an earlier run
681
+ def finish_empty_listing(opts, category, listing)
682
+ run = ExtractionRun.new([], output_dir: opts[:output_dir], base_name: category_base_name(opts[:lang], category),
683
+ source: { lang: opts[:lang].to_s })
684
+ run.listing!(**listing_record(listing, category, opts[:depth]))
685
+ finish_run(run, [])
686
+ end
530
687
 
531
- if not_found.any?
532
- puts unless quiet?
533
- if not_found.size <= 10
534
- print_warning("Not found in dump (#{not_found.size}):")
535
- not_found.each { |t| print_list_item(t, status: :warning) }
536
- else
537
- print_warning("#{not_found.size} articles not found (may be newer than dump)")
538
- end
688
+ # Stop a run whose output could not be written
689
+ def abandon_run(run, writer, error)
690
+ begin
691
+ writer&.close
692
+ rescue StandardError
693
+ nil
539
694
  end
540
-
541
- puts unless quiet?
542
- puts pastel.dim("Output files:") unless quiet?
543
- output_files.each { |f| print_list_item(f, status: :success) }
544
-
545
- # Return appropriate exit code
546
- not_found.empty? ? EXIT_SUCCESS : EXIT_PARTIAL
695
+ run.abandon!
696
+ print_error("Could not write the output: #{error.message}")
697
+ ExtractionRun::EXIT_ERROR
547
698
  end
548
699
 
549
700
  # Sanitize category name for use in filename