wp2txt 2.3.4 → 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 (83) hide show
  1. checksums.yaml +4 -4
  2. data/.dockerignore +0 -4
  3. data/.github/workflows/ci.yml +16 -1
  4. data/.github/workflows/publish-image.yml +8 -4
  5. data/.gitignore +3 -6
  6. data/CHANGELOG.md +32 -0
  7. data/DEVELOPMENT.md +63 -93
  8. data/DEVELOPMENT_ja.md +61 -93
  9. data/Dockerfile +1 -1
  10. data/README.md +93 -8
  11. data/README_ja.md +84 -8
  12. data/Rakefile +10 -21
  13. data/bin/wp2txt +84 -15
  14. data/bin/wp2txt-mcp +1 -1
  15. data/docs/INDEXES.md +61 -1
  16. data/lib/wp2txt/article.rb +2 -3
  17. data/lib/wp2txt/bz2_stream.rb +63 -0
  18. data/lib/wp2txt/cli.rb +90 -26
  19. data/lib/wp2txt/config.rb +2 -11
  20. data/lib/wp2txt/constants.rb +13 -1
  21. data/lib/wp2txt/corpus.rb +10 -23
  22. data/lib/wp2txt/data/template_aliases.json +4 -1
  23. data/lib/wp2txt/data/template_patterns.json +61643 -0
  24. data/lib/wp2txt/dump_snapshot.rb +99 -0
  25. data/lib/wp2txt/extraction_run.rb +272 -0
  26. data/lib/wp2txt/extractor.rb +481 -327
  27. data/lib/wp2txt/formatter.rb +14 -12
  28. data/lib/wp2txt/fts_index.rb +1 -1
  29. data/lib/wp2txt/index_cache.rb +144 -55
  30. data/lib/wp2txt/index_commands.rb +109 -18
  31. data/lib/wp2txt/langlinks_importer.rb +19 -35
  32. data/lib/wp2txt/lead_terms.rb +228 -0
  33. data/lib/wp2txt/link_counter.rb +171 -0
  34. data/lib/wp2txt/magic_words.rb +44 -28
  35. data/lib/wp2txt/metadata_index.rb +82 -13
  36. data/lib/wp2txt/multistream.rb +911 -824
  37. data/lib/wp2txt/output_writer.rb +3 -1
  38. data/lib/wp2txt/page_props_importer.rb +170 -0
  39. data/lib/wp2txt/parser_functions.rb +23 -5
  40. data/lib/wp2txt/ractor_worker.rb +6 -4
  41. data/lib/wp2txt/regex.rb +24 -4
  42. data/lib/wp2txt/site_info.rb +123 -0
  43. data/lib/wp2txt/sql_dump_reader.rb +57 -0
  44. data/lib/wp2txt/stream_processor.rb +9 -2
  45. data/lib/wp2txt/stream_store.rb +91 -0
  46. data/lib/wp2txt/template_args.rb +111 -0
  47. data/lib/wp2txt/template_expander.rb +110 -124
  48. data/lib/wp2txt/template_patterns.rb +182 -0
  49. data/lib/wp2txt/utils.rb +164 -127
  50. data/lib/wp2txt/version.rb +1 -1
  51. data/lib/wp2txt/wikitext_regions.rb +66 -0
  52. data/spec/auto_download_spec.rb +9 -6
  53. data/spec/category_fetcher_spec.rb +135 -463
  54. data/spec/cli_targeted_spec.rb +60 -0
  55. data/spec/config_spec.rb +2 -15
  56. data/spec/constants_spec.rb +0 -4
  57. data/spec/docs_sync_spec.rb +3 -3
  58. data/spec/dump_fetch_spec.rb +293 -0
  59. data/spec/extraction_run_spec.rb +520 -0
  60. data/spec/index_build_spec.rb +113 -0
  61. data/spec/index_commands_version_spec.rb +17 -0
  62. data/spec/langlinks_importer_spec.rb +27 -0
  63. data/spec/lead_terms_edge_cases_spec.rb +194 -0
  64. data/spec/lead_terms_links_qids_spec.rb +204 -0
  65. data/spec/multistream_reader_spec.rb +140 -0
  66. data/spec/multistream_spec.rb +8 -214
  67. data/spec/output_integrity_spec.rb +45 -2
  68. data/spec/p1_correctness_spec.rb +12 -9
  69. data/spec/page_properties_spec.rb +161 -0
  70. data/spec/regex_spec.rb +30 -0
  71. data/spec/region_semantics_spec.rb +71 -0
  72. data/spec/spec_helper.rb +3 -3
  73. data/spec/support/dump_status.rb +34 -0
  74. data/spec/support/multistream_fixture.rb +26 -8
  75. data/spec/template_args_spec.rb +133 -0
  76. data/spec/template_expander_spec.rb +29 -111
  77. data/spec/template_passthrough_spec.rb +58 -0
  78. data/spec/template_patterns_spec.rb +253 -0
  79. data/spec/tracked_paths_spec.rb +168 -0
  80. data/spec/utils_spec.rb +7 -1
  81. metadata +45 -5
  82. data/lib/wp2txt/category_cache.rb +0 -313
  83. 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,144 +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
- article.page_id = page[:id]
115
- article.revision_id = page[:revision_id]
116
- result = format_article(article, config)
117
- writer.write(result)
118
- extracted_count += 1
119
- 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
120
250
  else
121
- extraction_failures << title
122
- print_list_item("#{title} (extraction failed)", status: :warning)
251
+ run.failed(requested, :not_found, title == requested ? nil : "looked up as #{title}")
123
252
  end
253
+ yield requested, run.results[requested] if block_given?
124
254
  end
255
+ end
125
256
 
126
- # Close output
127
- output_files = writer.close
128
- 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
129
277
 
130
- # Summary
131
- has_issues = not_found.any? || extraction_failures.any?
132
- 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
133
307
 
134
- print_summary("Extraction Complete", {
135
- "Extracted" => "#{extracted_count}/#{article_titles.size}",
136
- "Output files" => output_files.size.to_s,
137
- "Total time" => format_duration(total_time)
138
- }, 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
139
322
 
140
- 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?
141
349
  puts unless quiet?
142
- print_warning("Not found in index (#{not_found.size}):")
143
- 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.")
144
351
  end
145
352
 
146
353
  puts unless quiet?
147
354
  puts pastel.dim("Output files:") unless quiet?
148
- output_files.each { |f| print_list_item(f, status: :success) }
149
-
150
- # Return appropriate exit code
151
- 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
152
362
  end
153
363
 
154
- # Download only the streams containing the requested articles
155
- # @param manager [DumpManager] The dump manager
156
- # @param index [MultistreamIndex] The multistream index
157
- # @param stream_offsets [Array<Integer>] Byte offsets of streams to download
158
- # @param force [Boolean] Force re-download even if cached
159
- def download_partial_streams(manager, index, stream_offsets, force: false)
160
- # Calculate how many streams are needed
161
- all_offsets = index.stream_offsets
162
- 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
163
377
 
164
- # Find the index of the highest needed stream
165
- max_idx = all_offsets.index(max_offset_needed)
166
- if max_idx.nil? || max_idx >= all_offsets.size - 1
167
- # Need full file for last stream
168
- 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
169
389
  end
170
390
 
171
- # Request partial download (DumpManager handles caching logic)
172
- stream_count = max_idx + 1
173
- 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)
174
399
  end
175
400
 
176
401
  # Show download estimate before confirmation
@@ -225,16 +450,10 @@ module Wp2txt
225
450
  print_list_item("Dump: #{pastel.green('cached')} (#{dump_size}, #{dump_date_str} - #{dump_age_str})", status: :success)
226
451
  end
227
452
  else
228
- # Check for partial downloads
229
- partial = manager.find_suitable_partial_cache(1)
230
- if partial
231
- partial_size = format_size(File.size(partial))
232
- partial_date = File.mtime(partial).strftime("%Y-%m-%d")
233
- print_list_item("Dump: #{pastel.cyan('partial cached')} (#{partial_size}, #{partial_date})", status: :success)
234
- print_list_item(" Additional download may be required depending on article locations", status: :pending)
235
- else
236
- print_list_item("Dump: #{pastel.yellow('download required')} (several GB)", status: :warning)
237
- 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)
238
457
  end
239
458
 
240
459
  if cache_is_stale
@@ -247,7 +466,8 @@ module Wp2txt
247
466
  end
248
467
 
249
468
  # Build config hash for article extraction
250
- 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)
251
471
  config = {
252
472
  format: format,
253
473
  num_procs: 1, # Single-threaded for article extraction
@@ -255,10 +475,22 @@ module Wp2txt
255
475
  bz2_gem: opts[:bz2_gem]
256
476
  }
257
477
 
258
- %i[title list heading table pre ref redirect multiline category category_only
478
+ %i[lead_terms title list heading table pre ref redirect multiline category category_only
259
479
  summary_only metadata_only marker extract_citations expand_templates].each do |opt|
260
480
  config[opt] = opts[opt]
261
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
488
+
489
+ # Page properties, when imported into the index of the full cached dump
490
+ if format == :json && manager
491
+ full_dump = manager.cached_multistream_path
492
+ config[:page_properties] = load_page_properties(full_dump, opts[:cache_dir])
493
+ end
262
494
 
263
495
  # Section extraction options
264
496
  %i[sections section_output min_section_length skip_empty
@@ -281,9 +513,7 @@ module Wp2txt
281
513
  category = opts[:from_category]
282
514
  max_depth = opts[:depth]
283
515
  cache_dir = opts[:cache_dir]
284
- dry_run = opts[:dry_run]
285
- skip_confirm = opts[:yes]
286
- total_steps = 6
516
+ total_steps = 5
287
517
  start_time = Time.now
288
518
 
289
519
  # Mode banner
@@ -294,253 +524,177 @@ module Wp2txt
294
524
  "Output" => opts[:output_dir]
295
525
  })
296
526
 
297
- # Get config values
298
527
  app_config = Wp2txt::CLI.config
299
-
300
- # Create category fetcher
301
- fetcher = Wp2txt::CategoryFetcher.new(
302
- lang, category,
303
- max_depth: max_depth,
304
- cache_expiry_days: app_config.category_expiry_days
305
- )
306
-
307
- # Step 1: Fetch preview
308
- print_header("Scanning category", step: 1, total_steps: total_steps)
309
- 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...")
310
536
  spinner.auto_spin
311
-
312
537
  begin
313
- preview = fetcher.fetch_preview
538
+ listing = fetcher.fetch_listing
314
539
  spinner.success(pastel.green("Done!"))
315
- 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
316
551
  spinner.error(pastel.red("Failed!"))
317
- print_error("Error fetching category: #{e.message}")
552
+ print_error(e.message)
318
553
  return EXIT_ERROR
319
554
  end
320
555
 
321
- # Display preview
322
- print_subheader("Category Preview")
323
- print_info("Category", preview[:category])
324
- print_info("Depth", preview[:depth].to_s)
325
- puts
326
-
327
- if preview[:subcategories] && !preview[:subcategories].empty?
328
- puts pastel.dim("Categories scanned:")
329
- preview[:subcategories].each do |subcat|
330
- print_list_item("#{subcat[:name]} (#{subcat[:article_count]} articles)")
331
- end
332
- puts
333
- end
334
-
335
- puts pastel.dim("Summary:")
336
- print_info("Subcategories", (preview[:total_subcategories] || 0).to_s, indent: 1)
337
- print_info("Total articles", pastel.bold(preview[:total_articles].to_s), indent: 1)
338
- 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
339
561
 
340
- # Check if there are any articles
341
- if preview[:total_articles].zero?
342
- print_warning("No articles found in this category.")
343
- return EXIT_SUCCESS # Not an error, just empty category
562
+ return finish_empty_listing(opts, category, listing)
344
563
  end
345
564
 
346
- # Warn about large extractions
347
- if preview[:total_articles] > 1000
348
- print_warning("Large category with #{preview[:total_articles]} articles.")
349
- puts pastel.yellow(" Extraction may take a long time and require significant disk space.")
350
- puts
351
- end
352
-
353
- # Show cache status before confirmation
354
- temp_manager = Wp2txt::DumpManager.new(
565
+ # One manager, so one dump version, for the whole run
566
+ manager = Wp2txt::DumpManager.new(
355
567
  lang,
356
568
  cache_dir: cache_dir,
357
- 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]
358
572
  )
359
- cache_stale = show_download_estimate(temp_manager, app_config)
360
- force_update = opts[:update_cache]
573
+ show_download_estimate(manager, app_config)
361
574
 
362
- # Dry run mode - exit here
363
- if dry_run
575
+ if opts[:dry_run]
364
576
  print_info_message("Dry run mode - no articles will be extracted.")
365
577
  return EXIT_SUCCESS
366
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)
367
599
 
368
- # Confirmation prompt
369
- unless skip_confirm
370
- unless $stdin.tty?
371
- print_error("Interactive confirmation required.")
372
- puts pastel.red(" Use --yes to skip confirmation when running non-interactively.")
373
- return EXIT_ERROR
374
- end
375
-
376
- unless confirm?("Proceed with extraction?")
377
- puts "Extraction cancelled."
378
- return EXIT_SUCCESS # User chose to cancel
379
- end
380
- end
381
-
382
- # Step 2: Fetch full article list
383
- print_header("Fetching articles from API", step: 2, total_steps: total_steps)
384
- spinner = create_spinner("Fetching article list...")
385
- spinner.auto_spin
386
-
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
387
605
  begin
388
- article_titles = fetcher.fetch_articles
389
- spinner.success(pastel.green("#{article_titles.size} articles"))
390
- rescue Net::OpenTimeout, Net::ReadTimeout, SocketError, Errno::ECONNREFUSED, OpenSSL::SSL::SSLError, JSON::ParserError, IOError => e
391
- spinner.error(pastel.red("Failed!"))
392
- print_error("Error fetching articles: #{e.message}")
393
- return EXIT_ERROR
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)
394
613
  end
614
+ bar.finish
395
615
 
396
- if article_titles.empty?
397
- print_warning("No articles to extract.")
398
- return EXIT_SUCCESS # Not an error, just empty result
399
- end
400
-
401
- # Create dump manager
402
- manager = Wp2txt::DumpManager.new(
403
- lang,
404
- cache_dir: cache_dir,
405
- dump_expiry_days: app_config.dump_expiry_days
406
- )
407
-
408
- # Step 3: Download index
409
- print_header("Downloading index", step: 3, total_steps: total_steps)
410
- index_path = manager.download_index(force: force_update)
411
-
412
- # Step 4: Load index and locate articles
413
- print_header("Locating articles in dump", step: 4, total_steps: total_steps)
414
-
415
- # Use SQLite cache for fast repeated access
416
- index = Wp2txt::MultistreamIndex.new(index_path, cache_dir: cache_dir)
417
-
418
- if index.loaded_from_cache?
419
- puts " Index loaded from cache (#{index.size} entries)"
420
- else
421
- puts " Index parsed (#{index.size} entries)"
422
- 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
423
620
 
424
- # Find articles in index
425
- found_articles = []
426
- 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
427
626
 
428
- article_titles.each do |title|
429
- entry = index.find_by_title(title)
430
- if entry
431
- found_articles << entry
432
- else
433
- 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)")
434
631
  end
632
+ puts
435
633
  end
436
634
 
437
- print_list_item("Found in dump: #{found_articles.size}", status: :success)
438
- print_list_item("Not in dump: #{not_found.size}", status: not_found.any? ? :warning : :success) if not_found.any?
439
-
440
- if found_articles.empty?
441
- print_error("No articles found in dump. The dump may be out of date.")
442
- return EXIT_ERROR
443
- end
444
-
445
- # Step 5: Download multistream
446
- streams_needed = found_articles.map { |e| e[:offset] }.uniq.sort
447
- print_header("Downloading data (#{streams_needed.size} streams)", step: 5, total_steps: total_steps)
448
- multistream_path = download_partial_streams(manager, index, streams_needed, force: force_update)
449
-
450
- # Create multistream reader, reusing the existing index (avoids double parsing)
451
- reader = Wp2txt::MultistreamReader.new(multistream_path, index)
452
-
453
- # Build config
454
- format = opts[:format].to_s.downcase.to_sym
455
- config = build_extraction_config(opts, format)
456
-
457
- # Create output writer
458
- base_name = "#{lang}wiki_#{sanitize_filename(category)}"
459
- writer = OutputWriter.new(
460
- output_dir: opts[:output_dir],
461
- base_name: base_name,
462
- format: format,
463
- file_size_mb: opts[:file_size]
464
- )
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
465
639
 
466
- # Step 6: Extract and process articles
467
- print_header("Extracting articles", step: 6, total_steps: total_steps)
468
- total_count = found_articles.size
469
- bar = create_progress_bar(" Processing", total_count)
640
+ return unless preview[:total_articles] > 1000
470
641
 
471
- extracted_count = 0
472
- 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
473
646
 
474
- # Use parallel extraction for large batches (>50 articles across multiple streams)
475
- streams_count = found_articles.map { |e| e[:offset] }.uniq.size
476
- use_parallel = total_count > 50 && streams_count > 1
477
-
478
- if use_parallel
479
- # Parallel extraction: process streams concurrently
480
- num_procs = [streams_count, 4].min # Cap at 4 processes
481
- pages = reader.each_article_parallel(found_articles, num_processes: num_procs).to_a
482
-
483
- pages.each do |page|
484
- article = Article.new(page[:text], page[:title], !config[:marker])
485
- article.page_id = page[:id]
486
- article.revision_id = page[:revision_id]
487
- result = format_article(article, config)
488
- writer.write(result)
489
- extracted_count += 1
490
- bar.advance
491
- end
492
- else
493
- # Sequential extraction for small batches
494
- found_articles.each do |entry|
495
- title = entry[:title]
496
- page = reader.extract_article(title)
497
-
498
- if page
499
- article = Article.new(page[:text], page[:title], !config[:marker])
500
- article.page_id = page[:id]
501
- article.revision_id = page[:revision_id]
502
- result = format_article(article, config)
503
- writer.write(result)
504
- extracted_count += 1
505
- 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]
506
650
 
507
- bar.advance
508
- 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
509
655
  end
656
+ return nil if confirm?("Proceed with extraction?")
510
657
 
511
- bar.finish
512
- extraction_time = Time.now - extraction_start
658
+ puts "Extraction cancelled."
659
+ EXIT_SUCCESS
660
+ end
513
661
 
514
- # Close output
515
- 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
516
674
 
517
- # Summary
518
- total_time = Time.now - start_time
519
- status = not_found.empty? ? :success : :warning
675
+ def category_base_name(lang, category)
676
+ "#{lang}wiki_#{sanitize_filename(category)}"
677
+ end
520
678
 
521
- print_summary("Extraction Complete", {
522
- "Articles extracted" => "#{extracted_count}/#{article_titles.size}",
523
- "Output files" => output_files.size.to_s,
524
- "Extraction time" => format_duration(extraction_time),
525
- "Total time" => format_duration(total_time)
526
- }, 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
527
687
 
528
- if not_found.any?
529
- puts unless quiet?
530
- if not_found.size <= 10
531
- print_warning("Not found in dump (#{not_found.size}):")
532
- not_found.each { |t| print_list_item(t, status: :warning) }
533
- else
534
- print_warning("#{not_found.size} articles not found (may be newer than dump)")
535
- 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
536
694
  end
537
-
538
- puts unless quiet?
539
- puts pastel.dim("Output files:") unless quiet?
540
- output_files.each { |f| print_list_item(f, status: :success) }
541
-
542
- # Return appropriate exit code
543
- not_found.empty? ? EXIT_SUCCESS : EXIT_PARTIAL
695
+ run.abandon!
696
+ print_error("Could not write the output: #{error.message}")
697
+ ExtractionRun::EXIT_ERROR
544
698
  end
545
699
 
546
700
  # Sanitize category name for use in filename