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
@@ -0,0 +1,99 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "digest"
4
+ require "json"
5
+ require_relative "constants"
6
+
7
+ module Wp2txt
8
+ # Raised when a dump version cannot be used: its status is missing,
9
+ # unfinished or malformed, or a file does not match what it records.
10
+ class SnapshotError < Error; end
11
+
12
+ # One finished version of a wiki's multistream dump, as Wikimedia's
13
+ # dumpstatus.json describes it: the index and the dump file with their
14
+ # sizes and SHA-1 digests. The snapshot ID is derived from those, so a file
15
+ # replaced under the same date makes a different snapshot.
16
+ class DumpSnapshot
17
+ JOB = "articlesmultistreamdumprecombine"
18
+ SHA1_FORMAT = /\A\h{40}\z/
19
+
20
+ # name: file name on the dump server, size: bytes, sha1: hex digest
21
+ FileInfo = Struct.new(:name, :size, :sha1, keyword_init: true)
22
+
23
+ attr_reader :lang, :date, :index_file, :dump_file, :id, :status_json
24
+
25
+ # @param lang [String, Symbol] wiki language code
26
+ # @param date [String] dump date (YYYYMMDD)
27
+ # @param status_json [String] the dumpstatus.json of that date
28
+ # @raise [SnapshotError] when the multistream files are not finished or not fully described
29
+ def self.parse(lang, date, status_json)
30
+ status = JSON.parse(status_json)
31
+ job = status.is_a?(Hash) ? status.dig("jobs", JOB) : nil
32
+ raise SnapshotError, "#{lang}wiki #{date}: the multistream dump is not listed" unless job.is_a?(Hash)
33
+ raise SnapshotError, "#{lang}wiki #{date}: the multistream dump is #{job['status'] || 'unfinished'}" unless job["status"] == "done"
34
+
35
+ files = job["files"].is_a?(Hash) ? job["files"] : {}
36
+ prefix = "#{lang}wiki-#{date}-pages-articles-multistream"
37
+ new(lang, date,
38
+ index_file: file_info(files, "#{prefix}-index.txt.bz2", lang, date),
39
+ dump_file: file_info(files, "#{prefix}.xml.bz2", lang, date),
40
+ status_json: status_json)
41
+ rescue JSON::ParserError => e
42
+ raise SnapshotError, "#{lang}wiki #{date}: unreadable dump status (#{e.message})"
43
+ end
44
+
45
+ def self.file_info(files, name, lang, date)
46
+ entry = files[name]
47
+ size = entry.is_a?(Hash) ? entry["size"] : nil
48
+ sha1 = entry.is_a?(Hash) ? entry["sha1"] : nil
49
+ unless size.is_a?(Integer) && size.positive? && sha1.is_a?(String) && sha1.match?(SHA1_FORMAT)
50
+ raise SnapshotError, "#{lang}wiki #{date}: the dump status does not describe #{name}"
51
+ end
52
+
53
+ FileInfo.new(name: name, size: size, sha1: sha1.downcase)
54
+ end
55
+ private_class_method :file_info
56
+
57
+ def initialize(lang, date, index_file:, dump_file:, status_json:)
58
+ @lang = lang.to_s
59
+ @date = date.to_s
60
+ @index_file = index_file
61
+ @dump_file = dump_file
62
+ @status_json = status_json
63
+ @id = Digest::SHA256.hexdigest([index_file, dump_file].map { |f| [f.name, f.size, f.sha1].join("\t") }.join("\n"))
64
+ end
65
+
66
+ def short_id
67
+ @id[0, 12]
68
+ end
69
+
70
+ # Directory holding this snapshot's status, verification records and streams
71
+ def dir(cache_dir)
72
+ File.join(cache_dir, "#{@lang}wiki-#{@date}-#{short_id}")
73
+ end
74
+
75
+ def to_h
76
+ { lang: @lang, date: @date, snapshot: @id }
77
+ end
78
+
79
+ # The dump's date as the moment templates count from (midnight UTC)
80
+ def time
81
+ DumpSnapshot.time_of(@date)
82
+ end
83
+
84
+ # @param date [String] YYYYMMDD
85
+ # @return [Time, nil]
86
+ def self.time_of(date)
87
+ m = date.to_s.match(/\A(\d{4})(\d{2})(\d{2})\z/)
88
+ m ? Time.utc(m[1].to_i, m[2].to_i, m[3].to_i) : nil
89
+ end
90
+
91
+ # The wiki language and dump date a Wikimedia dump file's name gives
92
+ # ("jawiki-20261101-pages-articles-multistream.xml.bz2" => ["ja", "20261101"])
93
+ # @return [Array(String, String), nil]
94
+ def self.name_info(path)
95
+ m = File.basename(path.to_s).match(/\A([a-z][a-z_-]*?)wiki-(\d{8})-/)
96
+ m && [m[1].tr("_", "-"), m[2]]
97
+ end
98
+ end
99
+ end
@@ -0,0 +1,272 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "fileutils"
4
+ require "json"
5
+ require "securerandom"
6
+ require "time"
7
+ require_relative "version"
8
+ require_relative "constants"
9
+ require_relative "template_patterns"
10
+
11
+ module Wp2txt
12
+ # One run of a targeted extraction (--articles, --from-category): the result
13
+ # for every requested title, the exit code that follows from them, and the
14
+ # publication of the output files together with a manifest that lists them.
15
+ #
16
+ # Every requested title ends in exactly one state, so
17
+ # requested = written + skipped_empty + failed always holds. An article is
18
+ # written once however many requests come to it (a redirect and its target,
19
+ # both in a category); the later requests record which one they share it with.
20
+ class ExtractionRun
21
+ EXIT_SUCCESS = 0
22
+ EXIT_ERROR = 1
23
+ EXIT_PARTIAL = 2
24
+
25
+ REASONS = %i[not_found index_mismatch text_unavailable truncated stream_unavailable
26
+ redirect_unresolved identity_mismatch].freeze
27
+
28
+ MANIFEST_SUFFIX = ".manifest.json"
29
+ # Left in place of the previous manifest while its files are replaced; a
30
+ # run that stops part way leaves this instead of a manifest
31
+ PREVIOUS_SUFFIX = ".manifest.previous.json"
32
+
33
+ attr_reader :run_id, :base_name, :staging_dir, :results
34
+
35
+ # @param titles [Array<String>] requested titles, without duplicates
36
+ # @param output_dir [String] where the output files and the manifest go
37
+ # @param base_name [String] base name of the output files
38
+ # @param source [Hash] what the articles were read from (lang, dump date, file)
39
+ def initialize(titles, output_dir:, base_name:, source: {})
40
+ @run_id = "#{Time.now.utc.strftime('%Y%m%dT%H%M%SZ')}-#{SecureRandom.hex(4)}"
41
+ @output_dir = File.expand_path(output_dir)
42
+ @base_name = base_name
43
+ @source = source
44
+ @started_at = Time.now.utc
45
+ @results = titles.to_h { |t| [t, { requested_title: t, status: :pending }] }
46
+ @written_pages = {}
47
+ @listing = nil
48
+ @staging_dir = File.join(@output_dir, ".wp2txt-#{@run_id}")
49
+ # The manifest in place when this run started: a failing run sets aside
50
+ # only that one, never one a later run has published since
51
+ @prior_run_id = read_record(manifest_path)&.dig("run_id") rescue nil
52
+ end
53
+
54
+ # Record that the list of titles came from a listing (a category), and
55
+ # whether that listing was read in full
56
+ def listing!(complete:, **details)
57
+ @listing = { complete: complete }.merge(details)
58
+ end
59
+
60
+ # Add to what the articles were read from, once it is known
61
+ def source!(**details)
62
+ @source.merge!(details)
63
+ end
64
+
65
+ def located(title, as: title)
66
+ @results.fetch(title)[:title] = as
67
+ end
68
+
69
+ # @param page_id [Integer, nil] the page written for it
70
+ def written(title, page_id: nil)
71
+ @written_pages[page_id] ||= title if page_id
72
+ finish(title, :written)
73
+ end
74
+
75
+ # A request answered by an article already written for another request
76
+ def written_as(title, earlier)
77
+ finish(title, :written, same_as: earlier)
78
+ end
79
+
80
+ # The request an article was written for, if it was
81
+ def written_for(page_id)
82
+ @written_pages[page_id]
83
+ end
84
+
85
+ def skipped_empty(title)
86
+ finish(title, :skipped_empty)
87
+ end
88
+
89
+ def failed(title, reason, detail = nil)
90
+ raise ArgumentError, "unknown failure reason: #{reason}" unless REASONS.include?(reason)
91
+
92
+ finish(title, :failed, reason: reason, detail: detail)
93
+ end
94
+
95
+ def counts
96
+ states = @results.values.map { |r| r[:status] }
97
+ written = states.count(:written)
98
+ skipped = states.count(:skipped_empty)
99
+ {
100
+ requested: @results.size,
101
+ located: @results.values.count { |r| r[:title] },
102
+ retrieved: written + skipped,
103
+ written: written,
104
+ records: @results.values.count { |r| r[:status] == :written && !r[:same_as] },
105
+ skipped_empty: skipped,
106
+ failed: states.count(:failed)
107
+ }
108
+ end
109
+
110
+ def failures
111
+ @results.values.select { |r| r[:status] == :failed }
112
+ end
113
+
114
+ def listing_complete?
115
+ @listing.nil? || @listing[:complete]
116
+ end
117
+
118
+ # Requested titles that have no result yet
119
+ def pending
120
+ @results.values.select { |r| r[:status] == :pending }
121
+ end
122
+
123
+ # Exit code for the run once its output is published
124
+ # @param published [Boolean] whether the output and manifest were written
125
+ def exit_code(published: true)
126
+ return EXIT_ERROR unless published && pending.empty?
127
+
128
+ c = counts
129
+ return EXIT_SUCCESS if c[:failed].zero? && listing_complete?
130
+
131
+ c[:written].positive? ? EXIT_PARTIAL : EXIT_ERROR
132
+ end
133
+
134
+ def manifest_path
135
+ File.join(@output_dir, "#{@base_name}#{MANIFEST_SUFFIX}")
136
+ end
137
+
138
+ # Move the staged output files into the output directory, replace the
139
+ # files of the previous run of the same base name, and publish the
140
+ # manifest last. Runs writing to the same output directory take turns.
141
+ # @param staged_files [Array<String>] files written under staging_dir
142
+ # @return [Array<String>] paths of the published output files
143
+ def publish!(staged_files)
144
+ raise Wp2txt::Error, "#{pending.size} requested title(s) have no result" unless pending.empty?
145
+
146
+ names = staged_files.map do |staged|
147
+ name = File.basename(staged)
148
+ unless File.dirname(File.expand_path(staged)) == @staging_dir && File.file?(staged) && !File.symlink?(staged) &&
149
+ own_output_name?(name)
150
+ raise ArgumentError, "not an output file of this run: #{staged}"
151
+ end
152
+
153
+ name
154
+ end
155
+ with_output_lock do
156
+ previous_files = set_aside_previous_manifest(names)
157
+ names.each { |name| File.rename(File.join(@staging_dir, name), File.join(@output_dir, name)) }
158
+ (previous_files - names).each { |name| remove_previous_output(name) }
159
+ write_manifest(names)
160
+ FileUtils.rm_f(previous_manifest_path)
161
+ end
162
+ names.map { |name| File.join(@output_dir, name) }
163
+ ensure
164
+ discard_staging
165
+ end
166
+
167
+ # End a run that could not produce its output: drop what it staged and set
168
+ # the previous manifest aside, so no manifest claims a result for this base
169
+ def abandon!
170
+ with_output_lock do
171
+ current = read_record(manifest_path)
172
+ set_aside_previous_manifest([]) if current && current["run_id"] == @prior_run_id
173
+ end
174
+ ensure
175
+ discard_staging
176
+ end
177
+
178
+ def discard_staging
179
+ FileUtils.rm_rf(@staging_dir) if File.directory?(@staging_dir)
180
+ end
181
+
182
+ def manifest(output_files)
183
+ c = counts
184
+ {
185
+ "run_id" => @run_id,
186
+ "wp2txt_version" => Wp2txt::VERSION,
187
+ # The rules of rendering come with the version; the learned patterns with their data
188
+ "template_patterns" => TemplatePatterns.digest,
189
+ "started_at" => @started_at.iso8601,
190
+ "finished_at" => Time.now.utc.iso8601,
191
+ "exit_code" => exit_code,
192
+ "source" => @source.transform_keys(&:to_s),
193
+ "listing" => @listing&.transform_keys(&:to_s),
194
+ "counts" => c.transform_keys(&:to_s),
195
+ "requests" => @results.values.map { |r| r.compact.transform_keys(&:to_s).transform_values { |v| v.is_a?(Symbol) ? v.to_s : v } },
196
+ "output_files" => output_files
197
+ }.compact
198
+ end
199
+
200
+ private
201
+
202
+ def finish(title, status, **extra)
203
+ result = @results.fetch(title)
204
+ raise ArgumentError, "#{title} already ended as #{result[:status]}" unless result[:status] == :pending
205
+
206
+ result.merge!(status: status, **extra.compact)
207
+ end
208
+
209
+ def previous_manifest_path
210
+ File.join(@output_dir, "#{@base_name}#{PREVIOUS_SUFFIX}")
211
+ end
212
+
213
+ def with_output_lock
214
+ FileUtils.mkdir_p(@output_dir)
215
+ File.open(@output_dir) do |dir|
216
+ dir.flock(File::LOCK_EX)
217
+ yield
218
+ end
219
+ end
220
+
221
+ # The names OutputWriter gives this base: <base>.<ext> or <base>-<n>.<ext>
222
+ def own_output_name?(name)
223
+ name.match?(/\A#{Regexp.escape(@base_name)}(?:-\d+)?\.(?:txt|jsonl)\z/)
224
+ end
225
+
226
+ # Keep the earlier record as <base>.manifest.previous.json, listing the
227
+ # files this run is about to publish as well, and remove the manifest. A
228
+ # run that stops part way then leaves no manifest, and a record of every
229
+ # file that may be in place for the next run to replace.
230
+ # @return [Array<String>] output file names of earlier runs
231
+ def set_aside_previous_manifest(new_names)
232
+ records = [previous_manifest_path, manifest_path].filter_map { |path| read_record(path) }
233
+ files = records.flat_map { |r| r["output_files"] }.uniq
234
+ record = (records.last || {}).merge("output_files" => (files + new_names).uniq, "interrupted_run" => @run_id)
235
+ write_json(previous_manifest_path, record)
236
+ FileUtils.rm_f(manifest_path)
237
+ files
238
+ end
239
+
240
+ # @return [Hash, nil] a manifest, nil when there is none
241
+ # @raise [Wp2txt::FileIOError] when it cannot be read as one
242
+ def read_record(path)
243
+ return nil unless File.file?(path)
244
+
245
+ record = JSON.parse(File.read(path))
246
+ files = record.is_a?(Hash) ? record["output_files"] : nil
247
+ return record if files.is_a?(Array) && files.all?(String)
248
+
249
+ raise Wp2txt::FileIOError, "#{path} is not a manifest of wp2txt; move it away to continue"
250
+ rescue JSON::ParserError
251
+ raise Wp2txt::FileIOError, "#{path} is not a manifest of wp2txt; move it away to continue"
252
+ end
253
+
254
+ # Only plain files directly in the output directory, named as this base's output
255
+ def remove_previous_output(name)
256
+ return unless own_output_name?(name)
257
+
258
+ path = File.join(@output_dir, name)
259
+ File.unlink(path) if File.file?(path) && !File.symlink?(path)
260
+ end
261
+
262
+ def write_json(path, data)
263
+ tmp = File.join(@output_dir, ".#{File.basename(path)}.#{@run_id}")
264
+ File.write(tmp, JSON.pretty_generate(data) + "\n")
265
+ File.rename(tmp, path)
266
+ end
267
+
268
+ def write_manifest(output_files)
269
+ write_json(manifest_path, manifest(output_files))
270
+ end
271
+ end
272
+ end