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.
- checksums.yaml +4 -4
- data/.dockerignore +0 -4
- data/.github/workflows/ci.yml +16 -1
- data/.github/workflows/publish-image.yml +8 -4
- data/.gitignore +3 -6
- data/CHANGELOG.md +32 -0
- data/DEVELOPMENT.md +63 -93
- data/DEVELOPMENT_ja.md +61 -93
- data/Dockerfile +1 -1
- data/README.md +93 -8
- data/README_ja.md +84 -8
- data/Rakefile +10 -21
- data/bin/wp2txt +84 -15
- data/bin/wp2txt-mcp +1 -1
- data/docs/INDEXES.md +61 -1
- data/lib/wp2txt/article.rb +2 -3
- data/lib/wp2txt/bz2_stream.rb +63 -0
- data/lib/wp2txt/cli.rb +90 -26
- data/lib/wp2txt/config.rb +2 -11
- data/lib/wp2txt/constants.rb +13 -1
- data/lib/wp2txt/corpus.rb +10 -23
- data/lib/wp2txt/data/template_aliases.json +4 -1
- data/lib/wp2txt/data/template_patterns.json +61643 -0
- data/lib/wp2txt/dump_snapshot.rb +99 -0
- data/lib/wp2txt/extraction_run.rb +272 -0
- data/lib/wp2txt/extractor.rb +481 -327
- data/lib/wp2txt/formatter.rb +14 -12
- data/lib/wp2txt/fts_index.rb +1 -1
- data/lib/wp2txt/index_cache.rb +144 -55
- data/lib/wp2txt/index_commands.rb +109 -18
- data/lib/wp2txt/langlinks_importer.rb +19 -35
- data/lib/wp2txt/lead_terms.rb +228 -0
- data/lib/wp2txt/link_counter.rb +171 -0
- data/lib/wp2txt/magic_words.rb +44 -28
- data/lib/wp2txt/metadata_index.rb +82 -13
- data/lib/wp2txt/multistream.rb +911 -824
- data/lib/wp2txt/output_writer.rb +3 -1
- data/lib/wp2txt/page_props_importer.rb +170 -0
- data/lib/wp2txt/parser_functions.rb +23 -5
- data/lib/wp2txt/ractor_worker.rb +6 -4
- data/lib/wp2txt/regex.rb +24 -4
- data/lib/wp2txt/site_info.rb +123 -0
- data/lib/wp2txt/sql_dump_reader.rb +57 -0
- data/lib/wp2txt/stream_processor.rb +9 -2
- data/lib/wp2txt/stream_store.rb +91 -0
- data/lib/wp2txt/template_args.rb +111 -0
- data/lib/wp2txt/template_expander.rb +110 -124
- data/lib/wp2txt/template_patterns.rb +182 -0
- data/lib/wp2txt/utils.rb +164 -127
- data/lib/wp2txt/version.rb +1 -1
- data/lib/wp2txt/wikitext_regions.rb +66 -0
- data/spec/auto_download_spec.rb +9 -6
- data/spec/category_fetcher_spec.rb +135 -463
- data/spec/cli_targeted_spec.rb +60 -0
- data/spec/config_spec.rb +2 -15
- data/spec/constants_spec.rb +0 -4
- data/spec/docs_sync_spec.rb +3 -3
- data/spec/dump_fetch_spec.rb +293 -0
- data/spec/extraction_run_spec.rb +520 -0
- data/spec/index_build_spec.rb +113 -0
- data/spec/index_commands_version_spec.rb +17 -0
- data/spec/langlinks_importer_spec.rb +27 -0
- data/spec/lead_terms_edge_cases_spec.rb +194 -0
- data/spec/lead_terms_links_qids_spec.rb +204 -0
- data/spec/multistream_reader_spec.rb +140 -0
- data/spec/multistream_spec.rb +8 -214
- data/spec/output_integrity_spec.rb +45 -2
- data/spec/p1_correctness_spec.rb +12 -9
- data/spec/page_properties_spec.rb +161 -0
- data/spec/regex_spec.rb +30 -0
- data/spec/region_semantics_spec.rb +71 -0
- data/spec/spec_helper.rb +3 -3
- data/spec/support/dump_status.rb +34 -0
- data/spec/support/multistream_fixture.rb +26 -8
- data/spec/template_args_spec.rb +133 -0
- data/spec/template_expander_spec.rb +29 -111
- data/spec/template_passthrough_spec.rb +58 -0
- data/spec/template_patterns_spec.rb +253 -0
- data/spec/tracked_paths_spec.rb +168 -0
- data/spec/utils_spec.rb +7 -1
- metadata +45 -5
- data/lib/wp2txt/category_cache.rb +0 -313
- data/spec/category_cache_spec.rb +0 -226
data/lib/wp2txt/output_writer.rb
CHANGED
|
@@ -30,9 +30,10 @@ module Wp2txt
|
|
|
30
30
|
# Write formatted article to output
|
|
31
31
|
# Thread-safe for parallel processing
|
|
32
32
|
# @param content [String, Hash] Content to write (String for text, Hash for JSON)
|
|
33
|
+
# @return [Boolean] false when there was nothing to write
|
|
33
34
|
# @raise [Wp2txt::FileIOError] on disk full or other I/O errors
|
|
34
35
|
def write(content)
|
|
35
|
-
return if content.nil? || (content.is_a?(String) && content.strip.empty?)
|
|
36
|
+
return false if content.nil? || (content.is_a?(String) && content.strip.empty?)
|
|
36
37
|
|
|
37
38
|
@mutex.synchronize do
|
|
38
39
|
ensure_file_open
|
|
@@ -43,6 +44,7 @@ module Wp2txt
|
|
|
43
44
|
|
|
44
45
|
rotate_file_if_needed
|
|
45
46
|
end
|
|
47
|
+
true
|
|
46
48
|
rescue Errno::ENOSPC
|
|
47
49
|
close_on_error
|
|
48
50
|
raise Wp2txt::FileIOError, "Disk full: cannot write to output directory '#{@output_dir}'"
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "sqlite3"
|
|
4
|
+
require "time"
|
|
5
|
+
require "digest"
|
|
6
|
+
require_relative "sql_dump_reader"
|
|
7
|
+
require_relative "version"
|
|
8
|
+
|
|
9
|
+
module Wp2txt
|
|
10
|
+
# Imports Wikidata IDs, disambiguation flags, and default sort keys
|
|
11
|
+
# from the official page_props dump into the metadata index, as
|
|
12
|
+
# page_properties. Like langlinks, the dump must carry the same
|
|
13
|
+
# date as the index: IDs are only meaningful for the pages they came with.
|
|
14
|
+
class PagePropsImporter
|
|
15
|
+
BATCH_SIZE = 50_000
|
|
16
|
+
|
|
17
|
+
# (pp_page,'pp_propname','pp_value',pp_sortkey) — string classes accept
|
|
18
|
+
# escaped quotes and backslashes; sortkey is NULL or a number
|
|
19
|
+
TUPLE_REGEX = /\((\d+),'((?:[^'\\]|\\.)*)','((?:[^'\\]|\\.)*)',(?:NULL|[-+.\deE]+)\)/
|
|
20
|
+
QID_REGEX = /\AQ\d+\z/
|
|
21
|
+
|
|
22
|
+
def initialize(db_path)
|
|
23
|
+
@db_path = db_path
|
|
24
|
+
end
|
|
25
|
+
|
|
26
|
+
# "jawiki-20260901-page_props.sql.gz" => "jawiki-20260901"
|
|
27
|
+
def self.dump_name_of(path)
|
|
28
|
+
File.basename(path)[/\A[a-z0-9_\-]+?-\d{8}/]
|
|
29
|
+
end
|
|
30
|
+
|
|
31
|
+
# @return [Hash] { status: :imported | :already_imported, row_count:, provenance: }
|
|
32
|
+
def import!(source_path, force: false)
|
|
33
|
+
raise ArgumentError, "page_props file not found: #{source_path}" unless File.exist?(source_path)
|
|
34
|
+
|
|
35
|
+
db = SQLite3::Database.new(@db_path)
|
|
36
|
+
db.busy_timeout = 5000
|
|
37
|
+
dump_name = metadata_value(db, "dump_name")
|
|
38
|
+
raise ArgumentError, "metadata index is not built: #{@db_path}" unless dump_name
|
|
39
|
+
|
|
40
|
+
source_dump = self.class.dump_name_of(source_path)
|
|
41
|
+
unless source_dump && source_dump == dump_name
|
|
42
|
+
raise ArgumentError,
|
|
43
|
+
"dump version mismatch: the metadata index is #{dump_name} but the page_props file is " \
|
|
44
|
+
"#{source_dump || File.basename(source_path)} (versions must match; there is no override)"
|
|
45
|
+
end
|
|
46
|
+
|
|
47
|
+
if !force && (existing = imported_at(db))
|
|
48
|
+
return { status: :already_imported, imported_at: existing,
|
|
49
|
+
row_count: db.get_first_value("SELECT COUNT(*) FROM page_properties").to_i, provenance: read_provenance(db) }
|
|
50
|
+
end
|
|
51
|
+
|
|
52
|
+
db.execute("DROP TABLE IF EXISTS page_qids") # replace the unreleased QID-only schema
|
|
53
|
+
db.execute("DROP TABLE IF EXISTS page_properties")
|
|
54
|
+
# A failed load must leave the index looking "not imported"
|
|
55
|
+
db.execute("DELETE FROM metadata WHERE key LIKE 'page\\_props\\_%' ESCAPE '\\'")
|
|
56
|
+
db.execute(<<~SQL)
|
|
57
|
+
CREATE TABLE page_properties (
|
|
58
|
+
page_id INTEGER PRIMARY KEY,
|
|
59
|
+
qid TEXT,
|
|
60
|
+
disambiguation INTEGER NOT NULL DEFAULT 0,
|
|
61
|
+
sort_key TEXT
|
|
62
|
+
)
|
|
63
|
+
SQL
|
|
64
|
+
|
|
65
|
+
rows_seen = 0
|
|
66
|
+
skipped_invalid = 0
|
|
67
|
+
batch = []
|
|
68
|
+
flush = lambda do
|
|
69
|
+
db.transaction do
|
|
70
|
+
stmt = db.prepare(<<~SQL)
|
|
71
|
+
INSERT INTO page_properties (page_id, qid, disambiguation, sort_key) VALUES (?, ?, ?, ?)
|
|
72
|
+
ON CONFLICT(page_id) DO UPDATE SET
|
|
73
|
+
qid = COALESCE(excluded.qid, page_properties.qid),
|
|
74
|
+
disambiguation = MAX(excluded.disambiguation, page_properties.disambiguation),
|
|
75
|
+
sort_key = COALESCE(excluded.sort_key, page_properties.sort_key)
|
|
76
|
+
SQL
|
|
77
|
+
batch.each { |row| stmt.execute(row) }
|
|
78
|
+
stmt.close
|
|
79
|
+
end
|
|
80
|
+
batch.clear
|
|
81
|
+
end
|
|
82
|
+
|
|
83
|
+
SqlDumpReader.each_insert_line(source_path, "page_props") do |line|
|
|
84
|
+
line.scan(TUPLE_REGEX) do |page, name, value|
|
|
85
|
+
rows_seen += 1
|
|
86
|
+
row = [page.to_i, nil, 0, nil]
|
|
87
|
+
case name
|
|
88
|
+
when "wikibase_item"
|
|
89
|
+
qid = SqlDumpReader.unescape(value)
|
|
90
|
+
next unless QID_REGEX.match?(qid)
|
|
91
|
+
|
|
92
|
+
row[1] = qid.force_encoding(Encoding::UTF_8)
|
|
93
|
+
when "disambiguation"
|
|
94
|
+
row[2] = 1
|
|
95
|
+
when "defaultsort"
|
|
96
|
+
key = SqlDumpReader.unescape(value).force_encoding(Encoding::UTF_8)
|
|
97
|
+
unless key.valid_encoding?
|
|
98
|
+
skipped_invalid += 1
|
|
99
|
+
next
|
|
100
|
+
end
|
|
101
|
+
row[3] = key
|
|
102
|
+
else
|
|
103
|
+
next
|
|
104
|
+
end
|
|
105
|
+
batch << row
|
|
106
|
+
flush.call if batch.size >= BATCH_SIZE
|
|
107
|
+
end
|
|
108
|
+
end
|
|
109
|
+
flush.call unless batch.empty?
|
|
110
|
+
|
|
111
|
+
if rows_seen.zero?
|
|
112
|
+
raise Wp2txt::Error, "no page_props rows found in #{File.basename(source_path)}; " \
|
|
113
|
+
"the file may be empty or in an unrecognized format"
|
|
114
|
+
end
|
|
115
|
+
|
|
116
|
+
counts = db.get_first_row("SELECT COUNT(*), COUNT(qid), SUM(disambiguation), COUNT(sort_key) FROM page_properties")
|
|
117
|
+
row_count = counts[0]
|
|
118
|
+
stamp_provenance(db, source_path, counts, skipped_invalid)
|
|
119
|
+
{ status: :imported, row_count: row_count, provenance: read_provenance(db) }
|
|
120
|
+
ensure
|
|
121
|
+
db&.close
|
|
122
|
+
end
|
|
123
|
+
|
|
124
|
+
private
|
|
125
|
+
|
|
126
|
+
def metadata_value(db, key)
|
|
127
|
+
db.get_first_value("SELECT value FROM metadata WHERE key = ?", [key])
|
|
128
|
+
rescue SQLite3::Exception
|
|
129
|
+
nil
|
|
130
|
+
end
|
|
131
|
+
|
|
132
|
+
def imported_at(db)
|
|
133
|
+
table = db.get_first_value("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'page_properties'")
|
|
134
|
+
table && metadata_value(db, "page_props_imported_at")
|
|
135
|
+
end
|
|
136
|
+
|
|
137
|
+
def stamp_provenance(db, source_path, counts, skipped_invalid)
|
|
138
|
+
values = {
|
|
139
|
+
page_props_source: File.basename(source_path),
|
|
140
|
+
page_props_source_size: File.size(source_path),
|
|
141
|
+
page_props_source_sha256: Digest::SHA256.file(source_path).hexdigest,
|
|
142
|
+
page_props_imported_at: Time.now.utc.iso8601,
|
|
143
|
+
page_props_wp2txt_version: Wp2txt::VERSION,
|
|
144
|
+
page_props_page_count: counts[0],
|
|
145
|
+
page_props_qid_count: counts[1],
|
|
146
|
+
page_props_disambiguation_count: counts[2].to_i,
|
|
147
|
+
page_props_sort_key_count: counts[3],
|
|
148
|
+
page_props_skipped_invalid_sort_keys: skipped_invalid
|
|
149
|
+
}
|
|
150
|
+
stmt = db.prepare("INSERT OR REPLACE INTO metadata (key, value) VALUES (?, ?)")
|
|
151
|
+
values.each { |k, v| stmt.execute([k.to_s, v.to_s]) }
|
|
152
|
+
stmt.close
|
|
153
|
+
end
|
|
154
|
+
|
|
155
|
+
def read_provenance(db)
|
|
156
|
+
{
|
|
157
|
+
source: metadata_value(db, "page_props_source"),
|
|
158
|
+
source_size: metadata_value(db, "page_props_source_size").to_i,
|
|
159
|
+
source_sha256: metadata_value(db, "page_props_source_sha256"),
|
|
160
|
+
imported_at: metadata_value(db, "page_props_imported_at"),
|
|
161
|
+
imported_with: metadata_value(db, "page_props_wp2txt_version"),
|
|
162
|
+
page_count: metadata_value(db, "page_props_page_count").to_i,
|
|
163
|
+
qid_count: metadata_value(db, "page_props_qid_count").to_i,
|
|
164
|
+
disambiguation_count: metadata_value(db, "page_props_disambiguation_count").to_i,
|
|
165
|
+
sort_key_count: metadata_value(db, "page_props_sort_key_count").to_i,
|
|
166
|
+
skipped_invalid_sort_keys: metadata_value(db, "page_props_skipped_invalid_sort_keys").to_i
|
|
167
|
+
}
|
|
168
|
+
end
|
|
169
|
+
end
|
|
170
|
+
end
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
3
|
require "time"
|
|
4
|
+
require_relative "template_args"
|
|
4
5
|
|
|
5
6
|
module Wp2txt
|
|
6
7
|
# Evaluates MediaWiki parser functions
|
|
@@ -11,9 +12,12 @@ module Wp2txt
|
|
|
11
12
|
July August September October November December
|
|
12
13
|
].freeze
|
|
13
14
|
|
|
14
|
-
|
|
15
|
+
# @param literal_equals [String, nil] put in place of "=" in what a
|
|
16
|
+
# function shows (see TemplateArgs.literal_equals)
|
|
17
|
+
def initialize(reference_date: nil, preserve_unknown: false, literal_equals: nil)
|
|
15
18
|
@reference_date = reference_date || Time.now
|
|
16
19
|
@preserve_unknown = preserve_unknown
|
|
20
|
+
@literal_equals = literal_equals
|
|
17
21
|
end
|
|
18
22
|
|
|
19
23
|
# Main evaluation method
|
|
@@ -66,7 +70,7 @@ module Wp2txt
|
|
|
66
70
|
|
|
67
71
|
content = text[(start_idx + 2)...end_idx]
|
|
68
72
|
expanded = evaluate_parser_function(content)
|
|
69
|
-
result << expanded
|
|
73
|
+
result << TemplateArgs.literal_equals(expanded, @literal_equals)
|
|
70
74
|
|
|
71
75
|
pos = end_idx + 2
|
|
72
76
|
end
|
|
@@ -106,6 +110,11 @@ module Wp2txt
|
|
|
106
110
|
function_name = content[1...colon_idx].downcase
|
|
107
111
|
args_str = content[(colon_idx + 1)..]
|
|
108
112
|
args = split_arguments(args_str)
|
|
113
|
+
# The values compared or computed hold their "=" as written; a branch
|
|
114
|
+
# chosen keeps its placeholders, as templates in it still read their own
|
|
115
|
+
# arguments. A case of #switch is split at its own "=" first
|
|
116
|
+
operands = OPERANDS.fetch(function_name, args.size)
|
|
117
|
+
args = args.each_with_index.map { |arg, i| i < operands ? plain(arg) : arg }
|
|
109
118
|
|
|
110
119
|
case function_name
|
|
111
120
|
when "if"
|
|
@@ -151,6 +160,15 @@ module Wp2txt
|
|
|
151
160
|
end
|
|
152
161
|
end
|
|
153
162
|
|
|
163
|
+
# How many leading arguments a function compares or computes, for those
|
|
164
|
+
# that return one of the others as it is (all of them, for the rest)
|
|
165
|
+
OPERANDS = { "if" => 1, "ifeq" => 2, "ifexpr" => 1, "iferror" => 0, "switch" => 0 }.freeze
|
|
166
|
+
|
|
167
|
+
# Text with each "=" held as a placeholder given back as written
|
|
168
|
+
def plain(text)
|
|
169
|
+
@literal_equals ? text.tr(@literal_equals, "=") : text
|
|
170
|
+
end
|
|
171
|
+
|
|
154
172
|
def split_arguments(str)
|
|
155
173
|
args = []
|
|
156
174
|
current = +""
|
|
@@ -218,7 +236,7 @@ module Wp2txt
|
|
|
218
236
|
def evaluate_switch(args)
|
|
219
237
|
return "" if args.empty?
|
|
220
238
|
|
|
221
|
-
value = args[0]
|
|
239
|
+
value = plain(args[0].to_s).strip
|
|
222
240
|
cases = args[1..]
|
|
223
241
|
default = ""
|
|
224
242
|
pending_cases = []
|
|
@@ -226,7 +244,7 @@ module Wp2txt
|
|
|
226
244
|
cases.each do |case_arg|
|
|
227
245
|
if case_arg.include?("=")
|
|
228
246
|
key, result = case_arg.split("=", 2)
|
|
229
|
-
key = key.strip
|
|
247
|
+
key = plain(key).strip
|
|
230
248
|
|
|
231
249
|
if key == "#default"
|
|
232
250
|
default = result
|
|
@@ -236,7 +254,7 @@ module Wp2txt
|
|
|
236
254
|
pending_cases.clear
|
|
237
255
|
else
|
|
238
256
|
# Fall-through case
|
|
239
|
-
trimmed = case_arg.strip
|
|
257
|
+
trimmed = plain(case_arg).strip
|
|
240
258
|
if trimmed == value
|
|
241
259
|
pending_cases << trimmed
|
|
242
260
|
else
|
data/lib/wp2txt/ractor_worker.rb
CHANGED
|
@@ -135,9 +135,9 @@ module Wp2txt
|
|
|
135
135
|
raise "Unknown operation: #{op}"
|
|
136
136
|
end
|
|
137
137
|
rescue StandardError
|
|
138
|
-
nil #
|
|
138
|
+
next [i, nil, true] # Done again outside, where an error is reported as usual
|
|
139
139
|
end
|
|
140
|
-
[i, result] #
|
|
140
|
+
[i, result, false] # Index for ordering, result, and whether it failed
|
|
141
141
|
end
|
|
142
142
|
end
|
|
143
143
|
|
|
@@ -145,8 +145,10 @@ module Wp2txt
|
|
|
145
145
|
collected = Array.new(items.size)
|
|
146
146
|
ractors.each do |r|
|
|
147
147
|
r.join
|
|
148
|
-
idx, result = r.value
|
|
149
|
-
|
|
148
|
+
idx, result, failed = r.value
|
|
149
|
+
# An item that failed inside a Ractor is processed again here, so its
|
|
150
|
+
# error reaches the caller instead of the item going missing
|
|
151
|
+
collected[idx] = failed ? process_single(items[idx], operation, frozen_config) : result
|
|
150
152
|
end
|
|
151
153
|
|
|
152
154
|
collected
|
data/lib/wp2txt/regex.rb
CHANGED
|
@@ -252,10 +252,30 @@ module Wp2txt
|
|
|
252
252
|
# For incomplete File/Image links (opened but not closed)
|
|
253
253
|
CLEANUP_FILE_INCOMPLETE_REGEX = Regexp.new('\[\[(?:' + FILE_NAMESPACES + '):[^\]]*\|?\s*$', Regexp::IGNORECASE | Regexp::MULTILINE)
|
|
254
254
|
|
|
255
|
-
#
|
|
256
|
-
#
|
|
257
|
-
#
|
|
258
|
-
|
|
255
|
+
# A category the page belongs to: [[Category:Name]] or [[Category:Name|sortkey]],
|
|
256
|
+
# capturing "Name". A link that only shows a category ([[:Category:Name]],
|
|
257
|
+
# [[:en:Category:Name|...]]) is not one. Templates written in the name stay
|
|
258
|
+
# in the capture; category_names reads them. A link broken across lines or
|
|
259
|
+
# not closed puts the page in no category
|
|
260
|
+
CATEGORY_TEMPLATE = '\{\{(?:[^\{\}\n]|\{\{[^\{\}\n]*\}\})*\}\}'
|
|
261
|
+
CATEGORY_REGEX = Regexp.new('\[\[[ \t]*(?:' + CATEGORY_NAMESPACES + ')[ \t]*:((?:[^\|\[\]\{\}\n]|' + CATEGORY_TEMPLATE +
|
|
262
|
+
')+)(?:\|[^\[\]\n]*)?\]\]', Regexp::IGNORECASE)
|
|
263
|
+
# Templates in a category name that show nothing: the sort key set for the page
|
|
264
|
+
CATEGORY_SILENT_TEMPLATE = /\{\{\s*(?:DEFAULTSORT|DEFAULTSORTKEY|DEFAULTCATEGORYSORT)\s*:(?:[^{}]|\{\{[^{}]*\}\})*\}\}/i
|
|
265
|
+
|
|
266
|
+
# Names of the categories a text assigns, in order. {{!}} ends the name as
|
|
267
|
+
# "|" does; a template that sets the sort key shows nothing in it, and a name
|
|
268
|
+
# holding any other template (one that shows the page's name, say) is left
|
|
269
|
+
# out rather than read wrong
|
|
270
|
+
def self.category_names(text)
|
|
271
|
+
text.gsub(/\{\{\s*!\s*\}\}/, "|").scan(CATEGORY_REGEX).filter_map do |(name)|
|
|
272
|
+
name = name.gsub(CATEGORY_SILENT_TEMPLATE, "")
|
|
273
|
+
next if name.include?("{{")
|
|
274
|
+
|
|
275
|
+
name = name.strip
|
|
276
|
+
name unless name.empty?
|
|
277
|
+
end
|
|
278
|
+
end
|
|
259
279
|
|
|
260
280
|
ESCAPE_NOWIKI_REGEX = Regexp.new('<nowiki>(.*?)<\/nowiki>', Regexp::MULTILINE)
|
|
261
281
|
UNESCAPE_NOWIKI_REGEX = Regexp.new('<nowiki\-(\d+?)>')
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Wp2txt
|
|
4
|
+
# The <siteinfo> of a dump: which wiki it is, and its namespaces with the
|
|
5
|
+
# case rule of each. It sits in the dump's first stream, so it always
|
|
6
|
+
# matches the version of the articles.
|
|
7
|
+
class SiteInfo
|
|
8
|
+
Namespace = Struct.new(:id, :name, :case_rule)
|
|
9
|
+
|
|
10
|
+
# Names MediaWiki accepts for core namespaces on every wiki, whatever the
|
|
11
|
+
# local names are
|
|
12
|
+
CANONICAL_NAMES = {
|
|
13
|
+
-2 => "Media", -1 => "Special", 1 => "Talk", 2 => "User", 3 => "User talk",
|
|
14
|
+
4 => "Project", 5 => "Project talk", 6 => "File", 7 => "File talk",
|
|
15
|
+
8 => "MediaWiki", 9 => "MediaWiki talk", 10 => "Template", 11 => "Template talk",
|
|
16
|
+
12 => "Help", 13 => "Help talk", 14 => "Category", 15 => "Category talk",
|
|
17
|
+
828 => "Module", 829 => "Module talk"
|
|
18
|
+
}.freeze
|
|
19
|
+
CORE_ALIASES = { "Image" => 6, "Image talk" => 7 }.freeze
|
|
20
|
+
|
|
21
|
+
# Namespaces whose pages are not in a dump of articles
|
|
22
|
+
VIRTUAL_NAMESPACES = [-2, -1].freeze
|
|
23
|
+
|
|
24
|
+
attr_reader :dbname, :namespaces
|
|
25
|
+
|
|
26
|
+
# @param xml [String] text holding a <siteinfo> element
|
|
27
|
+
def self.parse(xml)
|
|
28
|
+
siteinfo = xml[%r{<siteinfo\b[^>]*>(.*?)</siteinfo>}m, 1].to_s
|
|
29
|
+
default_case = siteinfo[%r{<case>\s*([\w-]+)\s*</case>}, 1] || "first-letter"
|
|
30
|
+
namespaces = siteinfo.scan(%r{<namespace\b([^>]*?)(?:/>|>(.*?)</namespace>)}m).map do |attrs, name|
|
|
31
|
+
id = attrs[/\bkey="(-?\d+)"/, 1].to_i
|
|
32
|
+
Namespace.new(id, unescape(name.to_s.strip), attrs[/\bcase="([\w-]+)"/, 1] || default_case)
|
|
33
|
+
end
|
|
34
|
+
new(dbname: siteinfo[%r{<dbname>\s*(\S+?)\s*</dbname>}, 1], case_rule: default_case, namespaces: namespaces)
|
|
35
|
+
end
|
|
36
|
+
|
|
37
|
+
def self.unescape(text)
|
|
38
|
+
text.gsub("<", "<").gsub(">", ">").gsub(""", '"').gsub("'", "'").gsub("&", "&")
|
|
39
|
+
end
|
|
40
|
+
private_class_method :unescape
|
|
41
|
+
|
|
42
|
+
def initialize(dbname:, case_rule:, namespaces:)
|
|
43
|
+
@dbname = dbname
|
|
44
|
+
@case_rule = case_rule
|
|
45
|
+
@namespaces = namespaces
|
|
46
|
+
@by_id = namespaces.to_h { |ns| [ns.id, ns] }
|
|
47
|
+
@by_prefix = {}
|
|
48
|
+
namespaces.each { |ns| @by_prefix[ns.name.downcase] = ns unless ns.name.empty? }
|
|
49
|
+
CANONICAL_NAMES.each do |id, name|
|
|
50
|
+
@by_prefix[name.downcase] ||= @by_id[id] || Namespace.new(id, name, @case_rule)
|
|
51
|
+
end
|
|
52
|
+
CORE_ALIASES.each do |name, id|
|
|
53
|
+
@by_prefix[name.downcase] ||= @by_prefix[CANONICAL_NAMES.fetch(id).downcase]
|
|
54
|
+
end
|
|
55
|
+
end
|
|
56
|
+
|
|
57
|
+
# Whether the text held a siteinfo with namespaces at all
|
|
58
|
+
def valid?
|
|
59
|
+
!@dbname.nil? && @namespaces.any?
|
|
60
|
+
end
|
|
61
|
+
|
|
62
|
+
# Case rule of a namespace (of the main namespace by default)
|
|
63
|
+
def case_rule(namespace_id = 0)
|
|
64
|
+
@by_id[namespace_id]&.case_rule || @case_rule
|
|
65
|
+
end
|
|
66
|
+
|
|
67
|
+
# The namespace a title prefix names, if any
|
|
68
|
+
# @param prefix [String] the text before the first colon, normalized
|
|
69
|
+
def namespace_for(prefix)
|
|
70
|
+
@by_prefix[prefix.downcase]
|
|
71
|
+
end
|
|
72
|
+
end
|
|
73
|
+
|
|
74
|
+
# Normalizes titles the way MediaWiki does before looking them up: spaces
|
|
75
|
+
# for underscores, runs of spaces collapsed, Unicode NFC, a namespace prefix
|
|
76
|
+
# written in its local name, and an upper-case first letter where the
|
|
77
|
+
# namespace's case rule says so. Ruby's upcase may differ from MediaWiki's
|
|
78
|
+
# for a few characters; callers keep the original title as well.
|
|
79
|
+
class TitleNormalizer
|
|
80
|
+
Title = Struct.new(:text, :namespace_id)
|
|
81
|
+
|
|
82
|
+
def initialize(site_info)
|
|
83
|
+
@site = site_info
|
|
84
|
+
end
|
|
85
|
+
|
|
86
|
+
# @return [String] the normalized title
|
|
87
|
+
def normalize(title)
|
|
88
|
+
parse(title).text
|
|
89
|
+
end
|
|
90
|
+
|
|
91
|
+
# Whether normalizing the title upper-cases a non-ASCII first letter,
|
|
92
|
+
# where Ruby's mapping may not be MediaWiki's
|
|
93
|
+
def uncertain_case?(title)
|
|
94
|
+
text = title.to_s.unicode_normalize(:nfc).tr("_", " ").strip.delete_prefix(":").strip
|
|
95
|
+
prefix, rest = text.split(":", 2)
|
|
96
|
+
ns = rest && @site.namespace_for(prefix.strip)
|
|
97
|
+
text = rest.strip if ns && !ns.id.zero?
|
|
98
|
+
first = text[0].to_s
|
|
99
|
+
!first.ascii_only? && first.upcase != first
|
|
100
|
+
end
|
|
101
|
+
|
|
102
|
+
# @return [Title] the normalized title and its namespace
|
|
103
|
+
def parse(title)
|
|
104
|
+
text = title.to_s.unicode_normalize(:nfc).tr("_", " ").gsub(/[[:space:]]+/, " ").strip
|
|
105
|
+
text = text.delete_prefix(":").strip
|
|
106
|
+
prefix, rest = text.split(":", 2)
|
|
107
|
+
if rest && (ns = @site.namespace_for(prefix.strip)) && !ns.id.zero?
|
|
108
|
+
name = ns.name.empty? ? SiteInfo::CANONICAL_NAMES.fetch(ns.id, prefix.strip) : ns.name
|
|
109
|
+
return Title.new("#{name}:#{apply_case(rest.strip, ns.case_rule)}", ns.id)
|
|
110
|
+
end
|
|
111
|
+
|
|
112
|
+
Title.new(apply_case(text, @site.case_rule(0)), 0)
|
|
113
|
+
end
|
|
114
|
+
|
|
115
|
+
private
|
|
116
|
+
|
|
117
|
+
def apply_case(text, rule)
|
|
118
|
+
return text if text.empty? || rule == "case-sensitive"
|
|
119
|
+
|
|
120
|
+
text[0].upcase + text[1..]
|
|
121
|
+
end
|
|
122
|
+
end
|
|
123
|
+
end
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "zlib"
|
|
4
|
+
|
|
5
|
+
module Wp2txt
|
|
6
|
+
# Streams the rows of one table's INSERT statements out of an official
|
|
7
|
+
# MySQL table dump (.sql or .sql.gz), without loading the file whole.
|
|
8
|
+
#
|
|
9
|
+
# Dumps write each INSERT either on one line or with the header on its own
|
|
10
|
+
# line and one tuple per following line (current dumps do the latter), so
|
|
11
|
+
# every line of a statement is read up to its terminating semicolon.
|
|
12
|
+
# Statements for other tables are skipped.
|
|
13
|
+
#
|
|
14
|
+
# Lines are read as BINARY: string columns are VARBINARY and real dumps
|
|
15
|
+
# contain historically corrupted bytes. Callers match tuples with ASCII-only
|
|
16
|
+
# patterns and validate the captures themselves.
|
|
17
|
+
module SqlDumpReader
|
|
18
|
+
STATEMENT_START = /\A\s*INSERT\s+INTO\s/i
|
|
19
|
+
|
|
20
|
+
module_function
|
|
21
|
+
|
|
22
|
+
# @yield [String] each line (BINARY) that belongs to an INSERT statement for table
|
|
23
|
+
def each_insert_line(source_path, table)
|
|
24
|
+
header = /\A\s*INSERT\s+INTO\s+`#{Regexp.escape(table)}`\s+VALUES\b/i
|
|
25
|
+
io = if source_path.end_with?(".gz")
|
|
26
|
+
# GzipReader ignores set_encoding; the encoding must be given at open time
|
|
27
|
+
Zlib::GzipReader.open(source_path, encoding: Encoding::BINARY.to_s)
|
|
28
|
+
else
|
|
29
|
+
File.open(source_path, "rb")
|
|
30
|
+
end
|
|
31
|
+
inside = false
|
|
32
|
+
begin
|
|
33
|
+
io.each_line do |line|
|
|
34
|
+
inside = header.match?(line) if STATEMENT_START.match?(line)
|
|
35
|
+
next unless inside
|
|
36
|
+
|
|
37
|
+
inside = false if line.rstrip.end_with?(";")
|
|
38
|
+
yield line
|
|
39
|
+
end
|
|
40
|
+
ensure
|
|
41
|
+
io.close
|
|
42
|
+
end
|
|
43
|
+
end
|
|
44
|
+
|
|
45
|
+
UNESCAPE_REGEX = /\\(.)/m
|
|
46
|
+
# MySQL backslash escapes inside mysqldump string literals
|
|
47
|
+
UNESCAPES = {
|
|
48
|
+
"0" => "\0", "'" => "'", '"' => '"', "b" => "\b", "n" => "\n",
|
|
49
|
+
"r" => "\r", "t" => "\t", "Z" => "\x1A", "\\" => "\\"
|
|
50
|
+
}.freeze
|
|
51
|
+
|
|
52
|
+
# Undo MySQL string escaping (\' \\ \n ...) in a captured value
|
|
53
|
+
def unescape(value)
|
|
54
|
+
value.gsub(UNESCAPE_REGEX) { UNESCAPES.fetch(Regexp.last_match(1), Regexp.last_match(1)) }
|
|
55
|
+
end
|
|
56
|
+
end
|
|
57
|
+
end
|
|
@@ -19,8 +19,12 @@ module Wp2txt
|
|
|
19
19
|
|
|
20
20
|
attr_reader :buffer_size, :pages_processed, :bytes_read, :redirects_skipped
|
|
21
21
|
|
|
22
|
-
|
|
22
|
+
# keep_raw_text: also hand back each article's wikitext as stored in the
|
|
23
|
+
# dump (before comment removal), as :raw_text among the with_ids values
|
|
24
|
+
def initialize(input_path, bz2_gem: false, adaptive_buffer: true, validate_bz2: true, skip_redirects: true,
|
|
25
|
+
keep_raw_text: false)
|
|
23
26
|
@input_path = input_path
|
|
27
|
+
@keep_raw_text = keep_raw_text
|
|
24
28
|
@bz2_gem = bz2_gem
|
|
25
29
|
@buffer = +""
|
|
26
30
|
@pending_bytes = +"".b
|
|
@@ -257,6 +261,7 @@ module Wp2txt
|
|
|
257
261
|
return nil unless Wp2txt.namespace_id(namespace).zero?
|
|
258
262
|
|
|
259
263
|
text = text_node.content
|
|
264
|
+
raw_text = text if @keep_raw_text
|
|
260
265
|
|
|
261
266
|
# Early redirect detection and skip (before expensive processing)
|
|
262
267
|
# Redirects start with # or # followed by redirect keyword and [[target]]
|
|
@@ -272,7 +277,9 @@ module Wp2txt
|
|
|
272
277
|
end
|
|
273
278
|
|
|
274
279
|
@pages_processed += 1
|
|
275
|
-
|
|
280
|
+
meta = Wp2txt.page_ids(page_xml)
|
|
281
|
+
meta[:raw_text] = raw_text if @keep_raw_text
|
|
282
|
+
[title, text, meta]
|
|
276
283
|
rescue Nokogiri::XML::SyntaxError
|
|
277
284
|
# Skip malformed XML
|
|
278
285
|
nil
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "fileutils"
|
|
4
|
+
require "securerandom"
|
|
5
|
+
require "digest"
|
|
6
|
+
require_relative "bz2_stream"
|
|
7
|
+
|
|
8
|
+
module Wp2txt
|
|
9
|
+
# Raised when a range of the dump is not in the stream store: it could not
|
|
10
|
+
# be fetched. The articles it holds are unavailable, not cut short.
|
|
11
|
+
class StreamUnavailableError < StreamError
|
|
12
|
+
def reason
|
|
13
|
+
:stream_unavailable
|
|
14
|
+
end
|
|
15
|
+
end
|
|
16
|
+
|
|
17
|
+
# Index ranges of one dump snapshot, fetched one by one and kept as
|
|
18
|
+
# separate files named by their byte range and the SHA-1 of their data. A
|
|
19
|
+
# file is in place only once its data is complete and decompresses, so a
|
|
20
|
+
# reader never sees a partial one; a file whose data no longer matches its
|
|
21
|
+
# name is set aside and fetched again.
|
|
22
|
+
class StreamStore
|
|
23
|
+
# Hex digits of the SHA-1 kept in a stored file's name
|
|
24
|
+
DIGEST_LENGTH = 16
|
|
25
|
+
|
|
26
|
+
attr_reader :dir, :total_size
|
|
27
|
+
|
|
28
|
+
# @param dir [String] directory of this snapshot's ranges
|
|
29
|
+
# @param total_size [Integer] size of the whole dump file, where the last range ends
|
|
30
|
+
def initialize(dir, total_size:)
|
|
31
|
+
@dir = dir
|
|
32
|
+
@total_size = total_size
|
|
33
|
+
end
|
|
34
|
+
|
|
35
|
+
# Stored file of a range, if any
|
|
36
|
+
def path_for(offset, end_offset)
|
|
37
|
+
Dir.glob(File.join(@dir, "#{offset}-#{end_offset}-*.bz2")).first
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
# Whether the range is stored intact. A stored file that does not match
|
|
41
|
+
# its digest is set aside, so the range is fetched again.
|
|
42
|
+
def have?(offset, end_offset)
|
|
43
|
+
path = path_for(offset, end_offset)
|
|
44
|
+
return false unless path
|
|
45
|
+
return true if File.size(path) == end_offset - offset && Digest::SHA1.file(path).hexdigest.start_with?(digest_of(path))
|
|
46
|
+
|
|
47
|
+
File.rename(path, "#{path}.bad-#{Time.now.utc.strftime('%Y%m%dT%H%M%SZ')}")
|
|
48
|
+
warn " A cached range at offset #{offset} was damaged; fetching it again"
|
|
49
|
+
false
|
|
50
|
+
end
|
|
51
|
+
|
|
52
|
+
# Compressed data of the range starting at offset
|
|
53
|
+
# @param next_offset [Integer, nil] start of the next range; nil for the last range
|
|
54
|
+
# @raise [StreamUnavailableError] when the range was not fetched
|
|
55
|
+
def read_range(offset, next_offset)
|
|
56
|
+
end_offset = next_offset || @total_size
|
|
57
|
+
path = path_for(offset, end_offset)
|
|
58
|
+
unless path && File.size(path) == end_offset - offset
|
|
59
|
+
raise StreamUnavailableError.new("the range at offset #{offset} could not be fetched", offset: offset)
|
|
60
|
+
end
|
|
61
|
+
|
|
62
|
+
File.binread(path)
|
|
63
|
+
end
|
|
64
|
+
|
|
65
|
+
# Keep the data of a range once it decompresses in full
|
|
66
|
+
# @raise [StreamError] when it does not
|
|
67
|
+
def store(offset, end_offset, data)
|
|
68
|
+
raise StreamError.new("range at offset #{offset} has #{data.bytesize} bytes, not #{end_offset - offset}", offset: offset) \
|
|
69
|
+
unless data.bytesize == end_offset - offset
|
|
70
|
+
|
|
71
|
+
Wp2txt.decompress_bz2(data, offset: offset)
|
|
72
|
+
FileUtils.mkdir_p(@dir)
|
|
73
|
+
path = File.join(@dir, "#{offset}-#{end_offset}-#{Digest::SHA1.hexdigest(data)[0, DIGEST_LENGTH]}.bz2")
|
|
74
|
+
tmp = "#{path}.#{Process.pid}.#{SecureRandom.hex(4)}.part"
|
|
75
|
+
File.binwrite(tmp, data)
|
|
76
|
+
File.rename(tmp, path)
|
|
77
|
+
path
|
|
78
|
+
ensure
|
|
79
|
+
FileUtils.rm_f(tmp) if tmp && File.exist?(tmp)
|
|
80
|
+
end
|
|
81
|
+
|
|
82
|
+
def digest_of(path)
|
|
83
|
+
File.basename(path, ".bz2").split("-").last
|
|
84
|
+
end
|
|
85
|
+
|
|
86
|
+
# Bytes held, for the cache status
|
|
87
|
+
def size
|
|
88
|
+
Dir.glob(File.join(@dir, "*.bz2")).sum { |f| File.size(f) }
|
|
89
|
+
end
|
|
90
|
+
end
|
|
91
|
+
end
|