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/formatter.rb
CHANGED
|
@@ -14,21 +14,23 @@ module Wp2txt
|
|
|
14
14
|
|
|
15
15
|
# Format article based on configuration and output format
|
|
16
16
|
def format_article(article, config)
|
|
17
|
-
|
|
17
|
+
with_source_fields(format_article_body(article, config), article)
|
|
18
18
|
end
|
|
19
19
|
|
|
20
|
-
# JSON records carry the dump's page and revision IDs
|
|
21
|
-
# when
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
20
|
+
# JSON records carry the dump's page and revision IDs (and page properties,
|
|
21
|
+
# when imported) right after the title, so a record can be traced
|
|
22
|
+
# back to its source; lead terms, when requested, come last.
|
|
23
|
+
def with_source_fields(result, article)
|
|
24
|
+
return result unless result.is_a?(Hash)
|
|
25
|
+
|
|
26
|
+
ids = { "page_id" => article.page_id, "revision_id" => article.revision_id }.compact
|
|
27
|
+
ids.merge!(article.page_properties.transform_keys(&:to_s)) if article.page_properties
|
|
28
|
+
out = result.each_with_object({}) do |(key, value), acc|
|
|
29
|
+
acc[key] = value
|
|
30
|
+
acc.merge!(ids) if key == "title"
|
|
31
31
|
end
|
|
32
|
+
out["lead_terms"] = article.lead_terms if article.lead_terms
|
|
33
|
+
out
|
|
32
34
|
end
|
|
33
35
|
|
|
34
36
|
def format_article_body(article, config)
|
data/lib/wp2txt/fts_index.rb
CHANGED
|
@@ -419,7 +419,7 @@ module Wp2txt
|
|
|
419
419
|
offset_pairs.each do |offset, next_offset|
|
|
420
420
|
f.seek(offset)
|
|
421
421
|
data = next_offset ? f.read(next_offset - offset) : f.read
|
|
422
|
-
xml =
|
|
422
|
+
xml = Wp2txt.decompress_bz2(data)
|
|
423
423
|
xml.scan(MetadataIndexBuilder::PAGE_BLOCK_REGEX) do
|
|
424
424
|
scan_page(::Regexp.last_match(1), renderer, rows)
|
|
425
425
|
end
|
data/lib/wp2txt/index_cache.rb
CHANGED
|
@@ -3,19 +3,30 @@
|
|
|
3
3
|
require "sqlite3"
|
|
4
4
|
require "fileutils"
|
|
5
5
|
require "digest"
|
|
6
|
+
require "securerandom"
|
|
7
|
+
require_relative "bz2_stream"
|
|
6
8
|
|
|
7
9
|
module Wp2txt
|
|
8
10
|
# SQLite-based cache for multistream index
|
|
9
11
|
# Dramatically speeds up repeated index access by storing parsed entries in SQLite
|
|
12
|
+
#
|
|
13
|
+
# A cache file is built under a temporary name, line by line from the index
|
|
14
|
+
# (never holding the whole index in memory), and put in place by rename only
|
|
15
|
+
# once complete. A published cache is never written to again; readers open
|
|
16
|
+
# it read-only.
|
|
10
17
|
class IndexCache
|
|
11
|
-
CACHE_VERSION =
|
|
18
|
+
CACHE_VERSION = 2
|
|
12
19
|
CACHE_SUFFIX = ".sqlite3"
|
|
20
|
+
BATCH_SIZE = 50_000
|
|
13
21
|
|
|
14
22
|
attr_reader :cache_path, :source_path
|
|
15
23
|
|
|
16
|
-
|
|
24
|
+
# @param identity [String, nil] SHA-1 of the index file, when known: the
|
|
25
|
+
# cache is then bound to that very file, not just to its path and size
|
|
26
|
+
def initialize(source_path, cache_dir: nil, identity: nil)
|
|
17
27
|
@source_path = source_path
|
|
18
28
|
@cache_dir = cache_dir || default_cache_dir
|
|
29
|
+
@identity = identity
|
|
19
30
|
@cache_path = build_cache_path
|
|
20
31
|
@db = nil
|
|
21
32
|
end
|
|
@@ -33,6 +44,7 @@ module Wp2txt
|
|
|
33
44
|
|
|
34
45
|
# Check cache version
|
|
35
46
|
return false if meta[:cache_version].to_i != CACHE_VERSION
|
|
47
|
+
return false if @identity && meta[:source_sha1] != @identity
|
|
36
48
|
|
|
37
49
|
# Check source file hasn't changed
|
|
38
50
|
source_stat = File.stat(@source_path)
|
|
@@ -77,56 +89,54 @@ module Wp2txt
|
|
|
77
89
|
end
|
|
78
90
|
end
|
|
79
91
|
|
|
92
|
+
# Build the cache from the index file it belongs to, reading it line by
|
|
93
|
+
# line. A failing decompressor leaves no cache behind.
|
|
94
|
+
# @yield [Integer] lines read so far, every BATCH_SIZE lines
|
|
95
|
+
# @raise [StreamError] when the index cannot be read in full
|
|
96
|
+
def build!(&progress)
|
|
97
|
+
publish do |db|
|
|
98
|
+
insert = db.prepare("INSERT OR REPLACE INTO index_entries (title, page_id, byte_offset) VALUES (?, ?, ?)")
|
|
99
|
+
offsets = db.prepare("INSERT OR IGNORE INTO stream_offsets (byte_offset) VALUES (?)")
|
|
100
|
+
count = 0
|
|
101
|
+
last_offset = nil
|
|
102
|
+
db.transaction
|
|
103
|
+
Wp2txt.each_index_line(@source_path) do |offset, page_id, title|
|
|
104
|
+
insert.execute([title, page_id, offset])
|
|
105
|
+
offsets.execute([offset]) unless offset == last_offset
|
|
106
|
+
last_offset = offset
|
|
107
|
+
count += 1
|
|
108
|
+
next unless (count % BATCH_SIZE).zero?
|
|
109
|
+
|
|
110
|
+
db.commit
|
|
111
|
+
db.transaction
|
|
112
|
+
progress&.call(count)
|
|
113
|
+
end
|
|
114
|
+
db.commit
|
|
115
|
+
insert.close
|
|
116
|
+
offsets.close
|
|
117
|
+
count
|
|
118
|
+
end
|
|
119
|
+
end
|
|
120
|
+
|
|
80
121
|
# Save index entries to cache
|
|
81
122
|
# @param entries_by_title [Hash] title => entry hash
|
|
82
123
|
# @param stream_offsets [Array<Integer>] sorted stream offsets
|
|
83
124
|
def save(entries_by_title, stream_offsets)
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
FileUtils.rm_f(@cache_path)
|
|
88
|
-
|
|
89
|
-
open_db
|
|
90
|
-
begin
|
|
91
|
-
create_schema
|
|
92
|
-
|
|
93
|
-
# Use transaction for better performance
|
|
94
|
-
@db.execute("BEGIN TRANSACTION")
|
|
95
|
-
|
|
96
|
-
# Save metadata
|
|
97
|
-
source_stat = File.stat(@source_path)
|
|
98
|
-
save_metadata(
|
|
99
|
-
source_path: @source_path,
|
|
100
|
-
source_mtime: source_stat.mtime.to_i,
|
|
101
|
-
source_size: source_stat.size,
|
|
102
|
-
cache_version: CACHE_VERSION,
|
|
103
|
-
entry_count: entries_by_title.size
|
|
104
|
-
)
|
|
105
|
-
|
|
106
|
-
# Save entries in batches for performance
|
|
107
|
-
stmt = @db.prepare("INSERT INTO index_entries (title, page_id, byte_offset) VALUES (?, ?, ?)")
|
|
125
|
+
publish do |db|
|
|
126
|
+
db.transaction
|
|
127
|
+
stmt = db.prepare("INSERT INTO index_entries (title, page_id, byte_offset) VALUES (?, ?, ?)")
|
|
108
128
|
entries_by_title.each do |title, entry|
|
|
109
129
|
stmt.execute([title, entry[:page_id], entry[:offset]])
|
|
110
130
|
end
|
|
111
131
|
stmt.close
|
|
112
132
|
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
stream_offsets.each do |offset|
|
|
116
|
-
stmt.execute([offset])
|
|
117
|
-
end
|
|
133
|
+
stmt = db.prepare("INSERT INTO stream_offsets (byte_offset) VALUES (?)")
|
|
134
|
+
stream_offsets.each { |offset| stmt.execute([offset]) }
|
|
118
135
|
stmt.close
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
true
|
|
123
|
-
rescue SQLite3::Exception => e
|
|
124
|
-
@db.execute("ROLLBACK") rescue nil
|
|
125
|
-
FileUtils.rm_f(@cache_path)
|
|
126
|
-
raise e
|
|
127
|
-
ensure
|
|
128
|
-
close_db
|
|
136
|
+
db.commit
|
|
137
|
+
entries_by_title.size
|
|
129
138
|
end
|
|
139
|
+
true
|
|
130
140
|
end
|
|
131
141
|
|
|
132
142
|
# Find entries by titles (efficient batch lookup)
|
|
@@ -155,6 +165,26 @@ module Wp2txt
|
|
|
155
165
|
end
|
|
156
166
|
end
|
|
157
167
|
|
|
168
|
+
# Find entries by page IDs
|
|
169
|
+
# @param page_ids [Array<Integer>] page IDs to look up
|
|
170
|
+
# @return [Hash] page_id => entry, for the IDs found
|
|
171
|
+
def find_by_ids(page_ids)
|
|
172
|
+
return {} if page_ids.empty?
|
|
173
|
+
return {} unless valid?
|
|
174
|
+
|
|
175
|
+
results = {}
|
|
176
|
+
open_db
|
|
177
|
+
begin
|
|
178
|
+
sql = "SELECT title, page_id, byte_offset FROM index_entries WHERE page_id IN (#{page_ids.map { '?' }.join(',')})"
|
|
179
|
+
@db.execute(sql, page_ids) do |title, page_id, offset|
|
|
180
|
+
results[page_id] = { offset: offset, page_id: page_id, title: title }
|
|
181
|
+
end
|
|
182
|
+
results
|
|
183
|
+
ensure
|
|
184
|
+
close_db
|
|
185
|
+
end
|
|
186
|
+
end
|
|
187
|
+
|
|
158
188
|
# All stream offsets in ascending order (for lazy title lookup without
|
|
159
189
|
# loading the full index into memory)
|
|
160
190
|
# @return [Array<Integer>] sorted byte offsets
|
|
@@ -205,20 +235,48 @@ module Wp2txt
|
|
|
205
235
|
end
|
|
206
236
|
|
|
207
237
|
def build_cache_path
|
|
208
|
-
# Use source file basename + hash of full path for uniqueness
|
|
238
|
+
# Use source file basename + hash of full path for uniqueness; the
|
|
239
|
+
# version is part of the name, so a cache of another layout is never
|
|
240
|
+
# opened, let alone overwritten
|
|
209
241
|
basename = File.basename(@source_path, ".*").sub(/-index$/, "")
|
|
210
242
|
path_hash = Digest::MD5.hexdigest(@source_path)[0, 8]
|
|
211
|
-
|
|
243
|
+
bound = @identity ? "_#{@identity[0, 12]}" : ""
|
|
244
|
+
File.join(@cache_dir, "#{basename}_#{path_hash}#{bound}_v#{CACHE_VERSION}#{CACHE_SUFFIX}")
|
|
245
|
+
end
|
|
246
|
+
|
|
247
|
+
# Fill a new database under a temporary name, then put it in place.
|
|
248
|
+
# The journal is a plain rollback journal, so the finished file stands on
|
|
249
|
+
# its own (no -wal or -shm file to move with it).
|
|
250
|
+
def publish
|
|
251
|
+
FileUtils.mkdir_p(File.dirname(@cache_path))
|
|
252
|
+
tmp = "#{@cache_path}.#{Process.pid}.#{SecureRandom.hex(4)}.building"
|
|
253
|
+
db = SQLite3::Database.new(tmp)
|
|
254
|
+
db.execute("PRAGMA journal_mode = DELETE")
|
|
255
|
+
db.execute("PRAGMA synchronous = OFF")
|
|
256
|
+
create_schema(db)
|
|
257
|
+
source_stat = File.stat(@source_path)
|
|
258
|
+
count = yield db
|
|
259
|
+
save_metadata(db,
|
|
260
|
+
source_path: @source_path,
|
|
261
|
+
source_mtime: source_stat.mtime.to_i,
|
|
262
|
+
source_size: source_stat.size,
|
|
263
|
+
cache_version: CACHE_VERSION,
|
|
264
|
+
source_sha1: @identity,
|
|
265
|
+
entry_count: count)
|
|
266
|
+
db.close
|
|
267
|
+
db = nil
|
|
268
|
+
File.rename(tmp, @cache_path)
|
|
269
|
+
count
|
|
270
|
+
ensure
|
|
271
|
+
db&.close
|
|
272
|
+
FileUtils.rm_f(Dir.glob("#{tmp}*")) if tmp
|
|
212
273
|
end
|
|
213
274
|
|
|
214
275
|
def open_db
|
|
215
|
-
@db ||= SQLite3::Database.new(@cache_path)
|
|
276
|
+
@db ||= SQLite3::Database.new(@cache_path, readonly: true)
|
|
216
277
|
# Wait out transient SQLITE_BUSY from concurrent readers (e.g., parallel
|
|
217
278
|
# extraction workers opening the cache simultaneously) instead of failing
|
|
218
279
|
@db.busy_timeout = 5000
|
|
219
|
-
# Performance optimizations
|
|
220
|
-
@db.execute("PRAGMA journal_mode = WAL")
|
|
221
|
-
@db.execute("PRAGMA synchronous = NORMAL")
|
|
222
280
|
@db.execute("PRAGMA cache_size = -64000") # 64MB cache
|
|
223
281
|
end
|
|
224
282
|
|
|
@@ -227,15 +285,15 @@ module Wp2txt
|
|
|
227
285
|
@db = nil
|
|
228
286
|
end
|
|
229
287
|
|
|
230
|
-
def create_schema
|
|
231
|
-
|
|
288
|
+
def create_schema(db)
|
|
289
|
+
db.execute(<<~SQL)
|
|
232
290
|
CREATE TABLE IF NOT EXISTS metadata (
|
|
233
291
|
key TEXT PRIMARY KEY,
|
|
234
292
|
value TEXT
|
|
235
293
|
)
|
|
236
294
|
SQL
|
|
237
295
|
|
|
238
|
-
|
|
296
|
+
db.execute(<<~SQL)
|
|
239
297
|
CREATE TABLE IF NOT EXISTS index_entries (
|
|
240
298
|
title TEXT PRIMARY KEY,
|
|
241
299
|
page_id INTEGER,
|
|
@@ -243,18 +301,18 @@ module Wp2txt
|
|
|
243
301
|
)
|
|
244
302
|
SQL
|
|
245
303
|
|
|
246
|
-
|
|
247
|
-
|
|
304
|
+
db.execute("CREATE INDEX IF NOT EXISTS idx_page_id ON index_entries(page_id)")
|
|
305
|
+
db.execute("CREATE INDEX IF NOT EXISTS idx_byte_offset ON index_entries(byte_offset)")
|
|
248
306
|
|
|
249
|
-
|
|
307
|
+
db.execute(<<~SQL)
|
|
250
308
|
CREATE TABLE IF NOT EXISTS stream_offsets (
|
|
251
309
|
byte_offset INTEGER PRIMARY KEY
|
|
252
310
|
)
|
|
253
311
|
SQL
|
|
254
312
|
end
|
|
255
313
|
|
|
256
|
-
def save_metadata(hash)
|
|
257
|
-
stmt =
|
|
314
|
+
def save_metadata(db, hash)
|
|
315
|
+
stmt = db.prepare("INSERT OR REPLACE INTO metadata (key, value) VALUES (?, ?)")
|
|
258
316
|
hash.each do |key, value|
|
|
259
317
|
stmt.execute([key.to_s, value.to_s])
|
|
260
318
|
end
|
|
@@ -272,4 +330,35 @@ module Wp2txt
|
|
|
272
330
|
nil
|
|
273
331
|
end
|
|
274
332
|
end
|
|
333
|
+
|
|
334
|
+
# Title lookups served from a built IndexCache, without loading the index
|
|
335
|
+
# into memory (millions of entries for a large wiki). Offers the lookup
|
|
336
|
+
# interface of MultistreamIndex that the reader and the extractor use.
|
|
337
|
+
class LazyTitleIndex
|
|
338
|
+
def initialize(index_cache)
|
|
339
|
+
@cache = index_cache
|
|
340
|
+
end
|
|
341
|
+
|
|
342
|
+
def find_by_title(title)
|
|
343
|
+
find_by_titles([title])[title]
|
|
344
|
+
end
|
|
345
|
+
|
|
346
|
+
# @return [Hash] title => entry, for the titles found
|
|
347
|
+
def find_by_titles(titles)
|
|
348
|
+
titles.each_slice(500).each_with_object({}) { |slice, found| found.merge!(@cache.find_by_titles(slice)) }
|
|
349
|
+
end
|
|
350
|
+
|
|
351
|
+
# @return [Hash] page_id => entry, for the IDs found
|
|
352
|
+
def find_by_ids(page_ids)
|
|
353
|
+
page_ids.each_slice(500).each_with_object({}) { |slice, found| found.merge!(@cache.find_by_ids(slice)) }
|
|
354
|
+
end
|
|
355
|
+
|
|
356
|
+
def stream_offset_for(title)
|
|
357
|
+
find_by_title(title)&.fetch(:offset, nil)
|
|
358
|
+
end
|
|
359
|
+
|
|
360
|
+
def stream_offsets
|
|
361
|
+
@stream_offsets ||= @cache.stream_offsets
|
|
362
|
+
end
|
|
363
|
+
end
|
|
275
364
|
end
|
|
@@ -4,6 +4,8 @@ require "json"
|
|
|
4
4
|
require_relative "metadata_index"
|
|
5
5
|
require_relative "fts_index"
|
|
6
6
|
require_relative "langlinks_importer"
|
|
7
|
+
require_relative "page_props_importer"
|
|
8
|
+
require_relative "link_counter"
|
|
7
9
|
require_relative "corpus"
|
|
8
10
|
require_relative "multistream"
|
|
9
11
|
require_relative "memory_monitor"
|
|
@@ -249,11 +251,7 @@ module Wp2txt
|
|
|
249
251
|
# metadata index. Version pinning: the langlinks file must carry the same
|
|
250
252
|
# dump date as the built index (enforced by LanglinksImporter, no override)
|
|
251
253
|
def run_import_langlinks(opts)
|
|
252
|
-
manager =
|
|
253
|
-
opts[:lang],
|
|
254
|
-
cache_dir: opts[:cache_dir],
|
|
255
|
-
dump_expiry_days: CLI.config.dump_expiry_days
|
|
256
|
-
)
|
|
254
|
+
manager = dump_manager(opts)
|
|
257
255
|
multistream = manager.cached_multistream_path
|
|
258
256
|
unless File.exist?(multistream)
|
|
259
257
|
print_error("No cached dump found for '#{opts[:lang]}'.")
|
|
@@ -322,11 +320,96 @@ module Wp2txt
|
|
|
322
320
|
end
|
|
323
321
|
end
|
|
324
322
|
CliUI::EXIT_SUCCESS
|
|
325
|
-
rescue ArgumentError => e
|
|
323
|
+
rescue ArgumentError, Wp2txt::Error => e
|
|
324
|
+
print_error(e.message)
|
|
325
|
+
CliUI::EXIT_ERROR
|
|
326
|
+
end
|
|
327
|
+
|
|
328
|
+
# Import each article's page properties from the page_props dump of the
|
|
329
|
+
# same date as the metadata index
|
|
330
|
+
def run_import_page_props(opts)
|
|
331
|
+
db_path, dump_date, manager = built_index_for(opts)
|
|
332
|
+
return CliUI::EXIT_ERROR unless db_path
|
|
333
|
+
|
|
334
|
+
source = opts[:page_props_file] || begin
|
|
335
|
+
print_header("Downloading page_props for '#{opts[:lang]}' (#{dump_date})")
|
|
336
|
+
manager.download_page_props(date: dump_date)
|
|
337
|
+
end
|
|
338
|
+
print_mode_banner("Import Page Properties", { "Source" => File.basename(source), "Metadata DB" => db_path })
|
|
339
|
+
|
|
340
|
+
time_start = Time.now
|
|
341
|
+
result = PagePropsImporter.new(db_path).import!(source, force: opts[:update_cache])
|
|
342
|
+
if result[:status] == :already_imported
|
|
343
|
+
print_success("Page properties already imported (at #{result[:imported_at]}, #{result[:row_count]} pages).")
|
|
344
|
+
print_info_message("Use -U/--update-cache to re-import.")
|
|
345
|
+
else
|
|
346
|
+
print_success("Page properties imported: #{result[:row_count]} pages in #{format_duration(Time.now - time_start)}")
|
|
347
|
+
provenance = result[:provenance]
|
|
348
|
+
print_info("Properties", "#{provenance[:qid_count]} QIDs, #{provenance[:disambiguation_count]} disambiguation flags, " \
|
|
349
|
+
"#{provenance[:sort_key_count]} sort keys; #{provenance[:skipped_invalid_sort_keys]} invalid sort keys skipped")
|
|
350
|
+
print_info("SHA-256", result[:provenance][:source_sha256].to_s)
|
|
351
|
+
end
|
|
352
|
+
CliUI::EXIT_SUCCESS
|
|
353
|
+
rescue ArgumentError, Wp2txt::Error => e
|
|
354
|
+
print_error(e.message)
|
|
355
|
+
CliUI::EXIT_ERROR
|
|
356
|
+
end
|
|
357
|
+
|
|
358
|
+
# Count incoming links to every article and store them in the metadata index
|
|
359
|
+
def run_count_links(opts)
|
|
360
|
+
db_path, _dump_date, manager = built_index_for(opts)
|
|
361
|
+
return CliUI::EXIT_ERROR unless db_path
|
|
362
|
+
|
|
363
|
+
multistream = manager.cached_multistream_path
|
|
364
|
+
stream_offsets, = load_stream_offsets(manager.cached_index_path, opts)
|
|
365
|
+
num_processes = opts[:num_procs] || MemoryMonitor.optimal_processes
|
|
366
|
+
print_mode_banner("Count Incoming Links", {
|
|
367
|
+
"Dump" => File.basename(multistream), "Streams" => stream_offsets.size.to_s,
|
|
368
|
+
"Processes" => num_processes.to_s
|
|
369
|
+
})
|
|
370
|
+
|
|
371
|
+
time_start = Time.now
|
|
372
|
+
last_report = Time.now
|
|
373
|
+
result = LinkCounter.new(multistream, stream_offsets, db_path: db_path,
|
|
374
|
+
num_processes: num_processes).count! do |done, total|
|
|
375
|
+
now = Time.now
|
|
376
|
+
if !quiet? && (now - last_report >= DEFAULT_PROGRESS_INTERVAL || done == total)
|
|
377
|
+
last_report = now
|
|
378
|
+
puts pastel.dim(format(" [%s] %d/%d batches", now.strftime("%H:%M:%S"), done, total))
|
|
379
|
+
end
|
|
380
|
+
end
|
|
381
|
+
print_success("Incoming links counted for #{result[:articles]} articles " \
|
|
382
|
+
"(#{result[:with_inlinks]} linked at least once) in #{format_duration(Time.now - time_start)}")
|
|
383
|
+
CliUI::EXIT_SUCCESS
|
|
384
|
+
rescue ArgumentError, Wp2txt::Error => e
|
|
326
385
|
print_error(e.message)
|
|
327
386
|
CliUI::EXIT_ERROR
|
|
328
387
|
end
|
|
329
388
|
|
|
389
|
+
# The metadata index of the cached dump for --lang, or nil with an error printed
|
|
390
|
+
# @return [Array(String, String, DumpManager)] [db_path, dump_date, manager]
|
|
391
|
+
def built_index_for(opts)
|
|
392
|
+
manager = dump_manager(opts)
|
|
393
|
+
multistream = manager.cached_multistream_path
|
|
394
|
+
unless File.exist?(multistream)
|
|
395
|
+
print_error("No cached dump found for '#{opts[:lang]}'.")
|
|
396
|
+
print_info_message("Download and index it with: wp2txt --build-index -L #{opts[:lang]}")
|
|
397
|
+
return nil
|
|
398
|
+
end
|
|
399
|
+
|
|
400
|
+
db_path = MetadataIndex.path_for(multistream, cache_dir: opts[:cache_dir])
|
|
401
|
+
meta = MetadataIndex.new(db_path)
|
|
402
|
+
unless meta.built?
|
|
403
|
+
meta.close
|
|
404
|
+
print_error("Metadata index not found for this dump.")
|
|
405
|
+
print_info_message("Build it first with: wp2txt --build-index -L #{opts[:lang]}")
|
|
406
|
+
return nil
|
|
407
|
+
end
|
|
408
|
+
dump_date = meta.stats[:dump_name][/\d{8}\z/]
|
|
409
|
+
meta.close
|
|
410
|
+
[db_path, dump_date, manager]
|
|
411
|
+
end
|
|
412
|
+
|
|
330
413
|
# Query the metadata index and print matching article titles
|
|
331
414
|
def run_find_articles(opts)
|
|
332
415
|
multistream_path, = resolve_dump_paths(opts, download: false)
|
|
@@ -381,26 +464,34 @@ module Wp2txt
|
|
|
381
464
|
print_info("Size", format_size(stats[:db_size]))
|
|
382
465
|
end
|
|
383
466
|
|
|
467
|
+
# The dump manager for --lang, honoring --dump-date and --update-cache
|
|
468
|
+
def dump_manager(opts)
|
|
469
|
+
DumpManager.new(opts[:lang], cache_dir: opts[:cache_dir], dump_expiry_days: CLI.config.dump_expiry_days,
|
|
470
|
+
dump_date: opts[:dump_date], update: opts[:update_cache])
|
|
471
|
+
end
|
|
472
|
+
|
|
384
473
|
# Resolve [multistream_path, index_path] from --lang (cached dump) or --input.
|
|
385
474
|
# Returns [nil, nil] after printing an error when files cannot be located.
|
|
386
475
|
def resolve_dump_paths(opts, download: false)
|
|
387
476
|
if opts[:lang]
|
|
388
|
-
manager =
|
|
389
|
-
opts[:lang],
|
|
390
|
-
cache_dir: opts[:cache_dir],
|
|
391
|
-
dump_expiry_days: CLI.config.dump_expiry_days
|
|
392
|
-
)
|
|
477
|
+
manager = dump_manager(opts)
|
|
393
478
|
multistream = manager.cached_multistream_path
|
|
394
479
|
index = manager.cached_index_path
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
print_info_message("Download and index it with: wp2txt --build-index -L #{opts[:lang]}")
|
|
399
|
-
return [nil, nil]
|
|
400
|
-
end
|
|
401
|
-
print_header("Downloading dump files for '#{opts[:lang]}'")
|
|
480
|
+
if download
|
|
481
|
+
# Fetches what is missing, and checks (or replaces) what is cached
|
|
482
|
+
print_header("Dump files for '#{opts[:lang]}' (#{manager.latest_dump_date})")
|
|
402
483
|
manager.download_index
|
|
403
484
|
manager.download_multistream
|
|
485
|
+
# The shared names the indexes are built from must name this version's files
|
|
486
|
+
manager.align_cached_names!
|
|
487
|
+
elsif !(File.exist?(multistream) && File.exist?(index))
|
|
488
|
+
print_error("No cached dump found for '#{opts[:lang]}'.")
|
|
489
|
+
print_info_message("Download and index it with: wp2txt --build-index -L #{opts[:lang]}")
|
|
490
|
+
return [nil, nil]
|
|
491
|
+
elsif (mismatched = manager.mismatched_cached_files).any?
|
|
492
|
+
print_error("Cached files do not match dump version #{manager.latest_dump_date}: #{mismatched.join(', ')}")
|
|
493
|
+
print_info_message("Fetch them again with: wp2txt --build-index -L #{opts[:lang]}")
|
|
494
|
+
return [nil, nil]
|
|
404
495
|
end
|
|
405
496
|
[multistream, index]
|
|
406
497
|
else
|
|
@@ -4,6 +4,7 @@ require "sqlite3"
|
|
|
4
4
|
require "set"
|
|
5
5
|
require "time"
|
|
6
6
|
require "zlib"
|
|
7
|
+
require_relative "sql_dump_reader"
|
|
7
8
|
require_relative "metadata_index"
|
|
8
9
|
require_relative "version"
|
|
9
10
|
|
|
@@ -28,14 +29,6 @@ module Wp2txt
|
|
|
28
29
|
SANITY_SAMPLE_SIZE = 1000
|
|
29
30
|
SANITY_WARN_THRESHOLD = 0.9
|
|
30
31
|
|
|
31
|
-
INSERT_PREFIX = /\A\s*INSERT\s+INTO\s+`langlinks`\s+VALUES\s+/i
|
|
32
|
-
|
|
33
|
-
# MySQL backslash escapes inside mysqldump string literals
|
|
34
|
-
UNESCAPES = {
|
|
35
|
-
"0" => "\0", "'" => "'", '"' => '"', "b" => "\b", "n" => "\n",
|
|
36
|
-
"r" => "\r", "t" => "\t", "Z" => "\x1A", "\\" => "\\"
|
|
37
|
-
}.freeze
|
|
38
|
-
|
|
39
32
|
def initialize(db_path, cache_dir: nil)
|
|
40
33
|
@db_path = db_path
|
|
41
34
|
@cache_dir = cache_dir
|
|
@@ -99,7 +92,9 @@ module Wp2txt
|
|
|
99
92
|
batch.clear
|
|
100
93
|
end
|
|
101
94
|
|
|
95
|
+
rows_seen = 0
|
|
102
96
|
skipped_invalid = each_source_row(source_path) do |ll_from, ll_lang, ll_title|
|
|
97
|
+
rows_seen += 1
|
|
103
98
|
next if lang_filter && !lang_filter.include?(ll_lang)
|
|
104
99
|
|
|
105
100
|
batch << [ll_from, ll_lang, MetadataIndex.normalize_title(ll_title)]
|
|
@@ -107,6 +102,13 @@ module Wp2txt
|
|
|
107
102
|
end
|
|
108
103
|
flush.call unless batch.empty?
|
|
109
104
|
|
|
105
|
+
# Reporting success after reading nothing would leave every language
|
|
106
|
+
# query silently empty; an unreadable dump must fail loudly instead.
|
|
107
|
+
if rows_seen.zero? && skipped_invalid.zero?
|
|
108
|
+
raise Wp2txt::Error, "no langlinks rows found in #{File.basename(source_path)}; " \
|
|
109
|
+
"the file may be empty or in an unrecognized format"
|
|
110
|
+
end
|
|
111
|
+
|
|
110
112
|
# Indexes are created after the load, not before (insert speed)
|
|
111
113
|
db.execute("CREATE INDEX idx_langlinks_from ON langlinks(ll_from, ll_lang)")
|
|
112
114
|
db.execute("CREATE INDEX idx_langlinks_lang_title ON langlinks(ll_lang, ll_title)")
|
|
@@ -224,32 +226,18 @@ module Wp2txt
|
|
|
224
226
|
# tagged UTF-8 and validated — a garbled title could never join
|
|
225
227
|
# pages.title anyway, so such rows are skipped (and counted), not scrubbed.
|
|
226
228
|
def each_source_row(source_path)
|
|
227
|
-
io = if source_path.end_with?(".gz")
|
|
228
|
-
# GzipReader ignores set_encoding; the encoding must be given
|
|
229
|
-
# at open time (lines must come out as BINARY — see below)
|
|
230
|
-
Zlib::GzipReader.open(source_path, encoding: Encoding::BINARY.to_s)
|
|
231
|
-
else
|
|
232
|
-
File.open(source_path, "rb")
|
|
233
|
-
end
|
|
234
|
-
|
|
235
229
|
skipped = 0
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
unless lang.valid_encoding? && title.valid_encoding?
|
|
244
|
-
skipped += 1
|
|
245
|
-
next
|
|
246
|
-
end
|
|
247
|
-
|
|
248
|
-
yield ll_from.to_i, lang, title
|
|
230
|
+
SqlDumpReader.each_insert_line(source_path, "langlinks") do |line|
|
|
231
|
+
line.scan(TUPLE_REGEX) do |ll_from, ll_lang, ll_title|
|
|
232
|
+
lang = SqlDumpReader.unescape(ll_lang).force_encoding(Encoding::UTF_8)
|
|
233
|
+
title = SqlDumpReader.unescape(ll_title).force_encoding(Encoding::UTF_8)
|
|
234
|
+
unless lang.valid_encoding? && title.valid_encoding?
|
|
235
|
+
skipped += 1
|
|
236
|
+
next
|
|
249
237
|
end
|
|
238
|
+
|
|
239
|
+
yield ll_from.to_i, lang, title
|
|
250
240
|
end
|
|
251
|
-
ensure
|
|
252
|
-
io.close
|
|
253
241
|
end
|
|
254
242
|
skipped
|
|
255
243
|
end
|
|
@@ -262,12 +250,8 @@ module Wp2txt
|
|
|
262
250
|
# (equivalent to the old parser skipping malformed tuples)
|
|
263
251
|
TUPLE_REGEX = /\((\d+),'((?:[^'\\]|\\.)*)','((?:[^'\\]|\\.)*)'\)/
|
|
264
252
|
|
|
265
|
-
UNESCAPE_REGEX = /\\(.)/m
|
|
266
253
|
|
|
267
254
|
# Resolve MySQL backslash escapes in a captured string literal
|
|
268
255
|
# (same mapping as the old hand-rolled parser)
|
|
269
|
-
def unescape_mysql(str)
|
|
270
|
-
str.gsub(UNESCAPE_REGEX) { UNESCAPES[::Regexp.last_match(1)] || ::Regexp.last_match(1) }
|
|
271
|
-
end
|
|
272
256
|
end
|
|
273
257
|
end
|