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
|
@@ -65,6 +65,33 @@ RSpec.describe Wp2txt::LanglinksImporter do
|
|
|
65
65
|
rows
|
|
66
66
|
end
|
|
67
67
|
|
|
68
|
+
# Current dumps put the INSERT header on its own line and one tuple per line
|
|
69
|
+
MULTILINE_SQL = <<~MSQL
|
|
70
|
+
INSERT INTO `langlinks` VALUES
|
|
71
|
+
(1,'en','Film A'),
|
|
72
|
+
(1,'ja','映画A'),
|
|
73
|
+
(2,'en','It\\'s a Film; Really');
|
|
74
|
+
INSERT INTO `pagelinks` VALUES
|
|
75
|
+
(9,'Ignored',0);
|
|
76
|
+
INSERT INTO `langlinks` VALUES
|
|
77
|
+
(3,'fr','Film B');
|
|
78
|
+
MSQL
|
|
79
|
+
|
|
80
|
+
describe "dumps with one tuple per line" do
|
|
81
|
+
it "imports every tuple of every langlinks statement, and nothing else" do
|
|
82
|
+
path = write_langlinks("testwiki-20260101-langlinks.sql.gz", MULTILINE_SQL, gzip: true)
|
|
83
|
+
expect(import(path)[:row_count]).to eq(4)
|
|
84
|
+
expect(langlinks_rows).to contain_exactly(
|
|
85
|
+
[1, "en", "Film A"], [1, "ja", "映画A"], [2, "en", "It's a Film; Really"], [3, "fr", "Film B"]
|
|
86
|
+
)
|
|
87
|
+
end
|
|
88
|
+
|
|
89
|
+
it "refuses to report success when no rows could be read" do
|
|
90
|
+
path = write_langlinks("testwiki-20260101-langlinks.sql", "-- nothing here\nUNLOCK TABLES;\n")
|
|
91
|
+
expect { import(path) }.to raise_error(Wp2txt::Error, /no langlinks rows found/)
|
|
92
|
+
end
|
|
93
|
+
end
|
|
94
|
+
|
|
68
95
|
describe "parsing and normalization" do
|
|
69
96
|
it "imports tuples with escapes, commas, parens, and multiple INSERT statements" do
|
|
70
97
|
path = write_langlinks("testwiki-20260101-langlinks.sql")
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require 'spec_helper'
|
|
4
|
+
require 'wp2txt'
|
|
5
|
+
require 'wp2txt/lead_terms'
|
|
6
|
+
require 'wp2txt/link_counter'
|
|
7
|
+
require 'wp2txt/metadata_index'
|
|
8
|
+
require 'open3'
|
|
9
|
+
require 'tmpdir'
|
|
10
|
+
require_relative 'support/multistream_fixture'
|
|
11
|
+
|
|
12
|
+
RSpec.describe 'lead terms and link counting on unusual wikitext' do
|
|
13
|
+
include MultistreamFixture
|
|
14
|
+
|
|
15
|
+
let(:cleaner) { Object.new.extend(Wp2txt) }
|
|
16
|
+
let(:render) { ->(s) { cleaner.format_wiki(s, expand_templates: true, markers: [:all]) } }
|
|
17
|
+
def terms(text)
|
|
18
|
+
Wp2txt::LeadTerms.extract(text, render: render)
|
|
19
|
+
end
|
|
20
|
+
|
|
21
|
+
it '#1 preserves link display and reading with expansion enabled or disabled' do
|
|
22
|
+
{
|
|
23
|
+
'{{読み仮名|[[東京|東京都]]|とうきょう}}' => '東京都(とうきょう)',
|
|
24
|
+
'{{仮リンク|[[東京|東京都]]|en|Tokyo}}' => '東京都',
|
|
25
|
+
'{{読み仮名|{{lang|ja|[[東京|東京都]]}}|とうきょう}}' => '東京都(とうきょう)',
|
|
26
|
+
'{{読み仮名|東京|}}' => '東京'
|
|
27
|
+
}.each do |input, expected|
|
|
28
|
+
[true, false].each do |expand|
|
|
29
|
+
expect(cleaner.format_wiki(input, expand_templates: expand)).to eq(expected)
|
|
30
|
+
end
|
|
31
|
+
end
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
def build_case_dump(dir, rule)
|
|
35
|
+
alias_title = rule == 'first-letter' ? 'Alias' : 'alias'
|
|
36
|
+
pages = [[1, 'apple', ''], [2, 'Apple', ''], [3, alias_title, '#REDIRECT [[apple]]'],
|
|
37
|
+
[4, 'Direct', '[[apple]]'], [5, 'Via', '[[alias]]'], [6, '東京', '']]
|
|
38
|
+
xml = "<mediawiki><siteinfo><case>#{rule}</case></siteinfo>" + pages.map do |id, title, text|
|
|
39
|
+
page_xml(id: id, ns: 0, title: title, text: text)
|
|
40
|
+
end.join + '</mediawiki>'
|
|
41
|
+
dump = File.join(dir, 'testwiki-20260101-multistream.xml.bz2')
|
|
42
|
+
File.binwrite(dump, bzip2(xml))
|
|
43
|
+
db = File.join(dir, 'meta.sqlite3')
|
|
44
|
+
Wp2txt::MetadataIndexBuilder.new(dump, [0], db_path: db, num_processes: 0).build.close
|
|
45
|
+
[dump, db]
|
|
46
|
+
end
|
|
47
|
+
|
|
48
|
+
it '#2 stores siteinfo case and preserves direct and redirected case-sensitive targets' do
|
|
49
|
+
Dir.mktmpdir do |dir|
|
|
50
|
+
dump, path = build_case_dump(dir, 'case-sensitive')
|
|
51
|
+
db = SQLite3::Database.new(path)
|
|
52
|
+
expect(db.get_first_value("SELECT value FROM metadata WHERE key = 'case_rule'")).to eq('case-sensitive')
|
|
53
|
+
db.close
|
|
54
|
+
Wp2txt::LinkCounter.new(dump, [0], db_path: path, num_processes: 0).count!
|
|
55
|
+
db = SQLite3::Database.new(path)
|
|
56
|
+
expect(db.execute('SELECT page_id,inlinks,via_redirects FROM page_inlinks WHERE page_id IN (1,2) ORDER BY page_id'))
|
|
57
|
+
.to eq([[1, 2, 1], [2, 0, 0]])
|
|
58
|
+
db.close
|
|
59
|
+
expect(Wp2txt::MetadataIndex.normalize_title('apple')).to eq('Apple')
|
|
60
|
+
end
|
|
61
|
+
end
|
|
62
|
+
|
|
63
|
+
it '#2 uses first-letter for explicit siteinfo and legacy metadata without the rule' do
|
|
64
|
+
Dir.mktmpdir do |dir|
|
|
65
|
+
dump, path = build_case_dump(dir, 'first-letter')
|
|
66
|
+
[false, true].each do |legacy|
|
|
67
|
+
db = SQLite3::Database.new(path)
|
|
68
|
+
if legacy
|
|
69
|
+
db.execute("DELETE FROM metadata WHERE key = 'case_rule'")
|
|
70
|
+
else
|
|
71
|
+
expect(db.get_first_value("SELECT value FROM metadata WHERE key = 'case_rule'")).to eq('first-letter')
|
|
72
|
+
end
|
|
73
|
+
db.close
|
|
74
|
+
Wp2txt::LinkCounter.new(dump, [0], db_path: path, num_processes: 0).count!
|
|
75
|
+
db = SQLite3::Database.new(path)
|
|
76
|
+
expect(db.get_first_value('SELECT inlinks FROM page_inlinks WHERE page_id=1')).to eq(0)
|
|
77
|
+
expect(db.execute('SELECT inlinks,via_redirects FROM page_inlinks WHERE page_id=2')).to eq([[2, 1]])
|
|
78
|
+
db.close
|
|
79
|
+
end
|
|
80
|
+
end
|
|
81
|
+
end
|
|
82
|
+
|
|
83
|
+
it '#2 reads a separate siteinfo stream before the first indexed page' do
|
|
84
|
+
Dir.mktmpdir do |dir|
|
|
85
|
+
header = bzip2('<mediawiki><siteinfo><case>case-sensitive</case></siteinfo>')
|
|
86
|
+
dump = File.join(dir, 'dump.xml.bz2')
|
|
87
|
+
File.binwrite(dump, header + bzip2(page_xml(id: 1, ns: 0, title: 'apple', text: '') + '</mediawiki>'))
|
|
88
|
+
path = File.join(dir, 'meta.sqlite3')
|
|
89
|
+
Wp2txt::MetadataIndexBuilder.new(dump, [header.bytesize], db_path: path, num_processes: 0).build.close
|
|
90
|
+
db = SQLite3::Database.new(path)
|
|
91
|
+
expect(db.get_first_value("SELECT value FROM metadata WHERE key = 'case_rule'")).to eq('case-sensitive')
|
|
92
|
+
db.close
|
|
93
|
+
end
|
|
94
|
+
end
|
|
95
|
+
|
|
96
|
+
%w[nowiki pre math syntaxhighlight source gallery score timeline chem ce graph mapframe templatedata].each do |tag|
|
|
97
|
+
it "#3 skips #{tag} contents and self-closing forms while preserving source offsets" do
|
|
98
|
+
text = "<#{tag.upcase} data-x='>'>'''偽'''(にせ){{ruby|偽|にせ}}</#{tag.upcase}>\n\n" \
|
|
99
|
+
"<#{tag} />'''東京'''(とうきょう)。"
|
|
100
|
+
result = terms(text)
|
|
101
|
+
expect(result.map { |t| t['text'] }).to eq(['東京'])
|
|
102
|
+
s, e = result.first['span']['bold']
|
|
103
|
+
expect(text[s...e]).to eq("'''東京'''")
|
|
104
|
+
expect(terms("<#{tag}>'''偽'''" )).to eq([])
|
|
105
|
+
end
|
|
106
|
+
end
|
|
107
|
+
|
|
108
|
+
it '#4 ignores delimiters in comments and excluded tags inside parentheses' do
|
|
109
|
+
text = "'''東京'''(とうきょう<!-- ) , -->、<nowiki>),</nowiki>Tokyo)は都市。"
|
|
110
|
+
result = terms(text).first
|
|
111
|
+
s, e = result['span']['paren']
|
|
112
|
+
expect(text[s...e]).to eq('(とうきょう<!-- ) , -->、<nowiki>),</nowiki>Tokyo)')
|
|
113
|
+
expect(result['notes'].size).to eq(2)
|
|
114
|
+
expect(result['notes'].first).to eq('とうきょう')
|
|
115
|
+
expect(result['notes_text']).not_to include('<!--')
|
|
116
|
+
end
|
|
117
|
+
|
|
118
|
+
it 'retains the original text of ruby arguments containing excluded regions' do
|
|
119
|
+
expect(terms('{{ruby|<nowiki>東京</nowiki>|とうきょう}}').first.slice('text', 'reading'))
|
|
120
|
+
.to eq('text' => '東京', 'reading' => 'とうきょう')
|
|
121
|
+
end
|
|
122
|
+
|
|
123
|
+
it '#5 detects only headings outside skipped regions including trailing comments' do
|
|
124
|
+
["<!--\n== 偽 ==\n-->", "<nowiki>\n== 偽 ==\n</nowiki>", "{{box|\n== 偽 ==\n}}", "{|\n== 偽 ==\n|}"].each do |prefix|
|
|
125
|
+
expect(terms("#{prefix}\n'''東京'''(とうきょう)").map { |t| t['text'] }).to eq(['東京'])
|
|
126
|
+
end
|
|
127
|
+
expect(terms("導入文。\n\n== 歴史 == <!-- comment -->\n'''後の語'''(あと)。")).to eq([])
|
|
128
|
+
end
|
|
129
|
+
|
|
130
|
+
it '#6 allows single newlines before and inside notes but stops at a blank line' do
|
|
131
|
+
expect(terms("'''東京'''\n(とうきょう)は都市。").first['notes']).to eq(['とうきょう'])
|
|
132
|
+
text = "'''東京'''(とうきょう、\nTokyo)は都市。"
|
|
133
|
+
term = terms(text).first
|
|
134
|
+
expect(term['notes']).to eq(['とうきょう', 'Tokyo'])
|
|
135
|
+
s, e = term['span']['paren']
|
|
136
|
+
expect(text[s...e]).to eq("(とうきょう、\nTokyo)")
|
|
137
|
+
["'''東京'''\n\n(とうきょう)", "'''東京'''(とうきょう、\n \nTokyo)"].each do |input|
|
|
138
|
+
expect(terms(input).first['notes']).to eq([])
|
|
139
|
+
end
|
|
140
|
+
end
|
|
141
|
+
|
|
142
|
+
it '#7 stops at empty lines containing whitespace' do
|
|
143
|
+
["\n \n", "\n\t\n", "\r\n \r\n"].each do |gap|
|
|
144
|
+
expect(terms("'''東京'''(とうきょう)。#{gap}'''別段落'''(べつだんらく)。").map { |t| t['text'] }).to eq(['東京'])
|
|
145
|
+
end
|
|
146
|
+
end
|
|
147
|
+
|
|
148
|
+
def counts(text)
|
|
149
|
+
counter = Wp2txt::LinkCounter.new('', [], db_path: '')
|
|
150
|
+
counter.instance_variable_set(:@redirects, {})
|
|
151
|
+
direct, via = Hash.new(0), Hash.new(0)
|
|
152
|
+
counter.send(:count_page, page_xml(id: 1, ns: 0, title: 'Source', text: text), direct, via)
|
|
153
|
+
direct
|
|
154
|
+
end
|
|
155
|
+
|
|
156
|
+
it '#8 decodes title entities before sections and normalizes whitespace before colon' do
|
|
157
|
+
expect(counts('[[M&A]] [[Café]] [[ :東京#節|表示]] [[Café#section]] [[#節]] [[]]'))
|
|
158
|
+
.to eq('M&A' => 1, 'Café' => 1, '東京' => 1)
|
|
159
|
+
expect(counts('[[東京#節]] [[東京|表示]]')).to eq('東京' => 1)
|
|
160
|
+
end
|
|
161
|
+
|
|
162
|
+
it '#9 excludes every non-wikitext tag and comments from incoming links' do
|
|
163
|
+
%w[nowiki pre math syntaxhighlight source score chem ce graph mapframe templatedata].each do |tag|
|
|
164
|
+
expect(counts("<#{tag}>[[東京]]</#{tag}>[[大阪]]<#{tag}/><!-- [[京都]] -->")).to eq('大阪' => 1)
|
|
165
|
+
end
|
|
166
|
+
end
|
|
167
|
+
|
|
168
|
+
it 'handles empty text and binary invalid bytes in the shared region helper' do
|
|
169
|
+
expect(terms('')).to eq([])
|
|
170
|
+
expect(counts('')).to eq({})
|
|
171
|
+
expect(Wp2txt::WikitextRegions.remove_literal("<nowiki>\xFF</nowiki>\xFE".b)).to eq("\xFE".b)
|
|
172
|
+
end
|
|
173
|
+
|
|
174
|
+
def cli(*options)
|
|
175
|
+
Dir.mktmpdir do |dir|
|
|
176
|
+
input = File.join(dir, 'x.xml.bz2')
|
|
177
|
+
File.binwrite(input, bzip2("<mediawiki>#{page_xml(id: 1, ns: 0, title: '東京', text: "'''東京'''。")}</mediawiki>"))
|
|
178
|
+
Open3.capture3(RbConfig.ruby, '-I', File.expand_path('../lib', __dir__),
|
|
179
|
+
File.expand_path('../bin/wp2txt', __dir__), '-i', input, '-o', dir, *options)
|
|
180
|
+
end
|
|
181
|
+
end
|
|
182
|
+
|
|
183
|
+
it '#10 rejects lead terms with ractor' do
|
|
184
|
+
_, err, status = cli('--format', 'json', '--lead-terms', '--ractor', '--no-turbo')
|
|
185
|
+
expect(status.success?).to be(false)
|
|
186
|
+
expect(err).to include('--lead-terms cannot be combined with --ractor')
|
|
187
|
+
end
|
|
188
|
+
|
|
189
|
+
it '#10 warns about missing source identifiers in ractor JSON without rejecting it' do
|
|
190
|
+
_, err, status = cli('--format', 'json', '--ractor', '--no-turbo', '-n', '1')
|
|
191
|
+
expect(status.success?).to be(true), err
|
|
192
|
+
expect(err).to include('does not include page IDs or revision IDs')
|
|
193
|
+
end
|
|
194
|
+
end
|
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "spec_helper"
|
|
4
|
+
require "json"
|
|
5
|
+
require "open3"
|
|
6
|
+
require "tmpdir"
|
|
7
|
+
require "zlib"
|
|
8
|
+
require_relative "support/multistream_fixture"
|
|
9
|
+
require "wp2txt"
|
|
10
|
+
require "wp2txt/metadata_index"
|
|
11
|
+
require "wp2txt/multistream"
|
|
12
|
+
require "wp2txt/sql_dump_reader"
|
|
13
|
+
require "wp2txt/page_props_importer"
|
|
14
|
+
require "wp2txt/link_counter"
|
|
15
|
+
require "wp2txt/lead_terms"
|
|
16
|
+
|
|
17
|
+
RSpec.describe "lead terms, incoming links, and Wikidata IDs" do
|
|
18
|
+
include MultistreamFixture
|
|
19
|
+
|
|
20
|
+
around do |example|
|
|
21
|
+
Dir.mktmpdir("wp2txt-ltq-") do |dir|
|
|
22
|
+
@dir = dir
|
|
23
|
+
example.run
|
|
24
|
+
end
|
|
25
|
+
end
|
|
26
|
+
|
|
27
|
+
def xml_page(id:, title:, text:, ns: 0)
|
|
28
|
+
esc = ->(s) { s.gsub("&", "&").gsub("<", "<").gsub(">", ">") }
|
|
29
|
+
"<page>\n<title>#{esc.(title)}</title>\n<ns>#{ns}</ns>\n<id>#{id}</id>\n<revision>\n<id>#{id * 100}</id>\n" \
|
|
30
|
+
"<text bytes=\"#{text.bytesize}\">#{esc.(text)}</text>\n</revision>\n</page>\n"
|
|
31
|
+
end
|
|
32
|
+
|
|
33
|
+
PAGES = [
|
|
34
|
+
[1, "東京", "'''東京'''(とうきょう、Tokyo)は首都。\n\n== 歴史 ==\n'''後'''(あと)", 0],
|
|
35
|
+
[2, "東京都区部", "#REDIRECT [[東京]]", 0],
|
|
36
|
+
[3, "記事A", "[[東京]]と[[東京]]、[[東京都区部]]。[[M&A|買収]]。<!-- [[隠れ]] -->[[#節]][[]]", 0],
|
|
37
|
+
[4, "記事B", "[[東京#歴史|東京の歴史]]", 0],
|
|
38
|
+
[5, "記事C", "[[東京都区部]]のみ。", 0],
|
|
39
|
+
[6, "M&A", "'''{{読み仮名|合併|がっぺい}}'''と買収。", 0],
|
|
40
|
+
[7, "隠れ", "", 0],
|
|
41
|
+
[8, "Category:X", "[[東京]]", 14]
|
|
42
|
+
].freeze
|
|
43
|
+
|
|
44
|
+
# One-stream dump with its index and a built metadata index
|
|
45
|
+
def build_dump
|
|
46
|
+
dump = File.join(@dir, "testwiki-20260101-pages-articles-multistream.xml.bz2")
|
|
47
|
+
File.binwrite(dump, bzip2(PAGES.map { |id, t, x, ns| xml_page(id: id, title: t, text: x, ns: ns) }.join))
|
|
48
|
+
File.write(File.join(@dir, "testwiki-20260101-pages-articles-multistream-index.txt"),
|
|
49
|
+
PAGES.map { |id, t, _, _| "0:#{id}:#{t}" }.join("\n") + "\n")
|
|
50
|
+
db = Wp2txt::MetadataIndex.path_for(dump, cache_dir: @dir)
|
|
51
|
+
Wp2txt::MetadataIndexBuilder.new(dump, [0], db_path: db, num_processes: 0).build.close
|
|
52
|
+
[dump, db]
|
|
53
|
+
end
|
|
54
|
+
|
|
55
|
+
def page_props_file(content, name: "testwiki-20260101-page_props.sql.gz")
|
|
56
|
+
path = File.join(@dir, name)
|
|
57
|
+
Zlib::GzipWriter.open(path) { |gz| gz.write(content) }
|
|
58
|
+
path
|
|
59
|
+
end
|
|
60
|
+
|
|
61
|
+
PAGE_PROPS_SQL = <<~SQL
|
|
62
|
+
INSERT INTO `page_props` VALUES
|
|
63
|
+
(1,'wikibase_item','Q1490',NULL),
|
|
64
|
+
(1,'page_image_free','T\\'kyo.jpg',NULL),
|
|
65
|
+
(3,'wikibase_item','Q9',1.5),
|
|
66
|
+
(6,'wikibase_item','Q1\\'bad',NULL),
|
|
67
|
+
(6,'defaultsort','\xFF\xFE',NULL);
|
|
68
|
+
INSERT INTO `page_restrictions` VALUES
|
|
69
|
+
(1,'wikibase_item','Q777',NULL);
|
|
70
|
+
SQL
|
|
71
|
+
|
|
72
|
+
describe Wp2txt::SqlDumpReader do
|
|
73
|
+
it "reads statements written on one line and one tuple per line, skipping other tables" do
|
|
74
|
+
lines = []
|
|
75
|
+
path = page_props_file("INSERT INTO `t` VALUES (1),(2);\nINSERT INTO `u` VALUES\n(9);\nINSERT INTO `t` VALUES\n(3),\n(4);\n")
|
|
76
|
+
described_class.each_insert_line(path, "t") { |l| lines << l.strip }
|
|
77
|
+
expect(lines).to eq(["INSERT INTO `t` VALUES (1),(2);", "INSERT INTO `t` VALUES", "(3),", "(4);"])
|
|
78
|
+
end
|
|
79
|
+
end
|
|
80
|
+
|
|
81
|
+
describe Wp2txt::PagePropsImporter do
|
|
82
|
+
it "imports only well-formed wikibase_item values, and records where they came from" do
|
|
83
|
+
_dump, db = build_dump
|
|
84
|
+
path = page_props_file(PAGE_PROPS_SQL.b)
|
|
85
|
+
result = described_class.new(db).import!(path)
|
|
86
|
+
expect(result[:row_count]).to eq(2)
|
|
87
|
+
rows = SQLite3::Database.new(db, readonly: true).execute("SELECT page_id, qid FROM page_properties ORDER BY page_id")
|
|
88
|
+
expect(rows).to eq([[1, "Q1490"], [3, "Q9"]])
|
|
89
|
+
expect(result[:provenance][:source_sha256]).to eq(Digest::SHA256.file(path).hexdigest)
|
|
90
|
+
expect(described_class.new(db).import!(path)[:status]).to eq(:already_imported)
|
|
91
|
+
end
|
|
92
|
+
|
|
93
|
+
it "refuses a dump of another date" do
|
|
94
|
+
_dump, db = build_dump
|
|
95
|
+
path = page_props_file(PAGE_PROPS_SQL.b, name: "testwiki-20250101-page_props.sql.gz")
|
|
96
|
+
expect { described_class.new(db).import!(path) }.to raise_error(ArgumentError, /version mismatch/)
|
|
97
|
+
end
|
|
98
|
+
|
|
99
|
+
it "fails when nothing could be read" do
|
|
100
|
+
_dump, db = build_dump
|
|
101
|
+
path = page_props_file("-- empty\n")
|
|
102
|
+
expect { described_class.new(db).import!(path) }.to raise_error(Wp2txt::Error, /no page_props rows/)
|
|
103
|
+
end
|
|
104
|
+
end
|
|
105
|
+
|
|
106
|
+
describe Wp2txt::LinkCounter do
|
|
107
|
+
it "counts each linking article once, through redirects, ignoring comments and non-articles" do
|
|
108
|
+
dump, db = build_dump
|
|
109
|
+
described_class.new(dump, [0], db_path: db, num_processes: 0).count!
|
|
110
|
+
counts = SQLite3::Database.new(db, readonly: true)
|
|
111
|
+
.execute("SELECT p.title, i.inlinks, i.via_redirects FROM page_inlinks i " \
|
|
112
|
+
"JOIN pages p USING (page_id)").to_h { |t, n, v| [t, [n, v]] }
|
|
113
|
+
expect(counts["東京"]).to eq([3, 1]) # 記事A and 記事B directly, 記事C only via the redirect
|
|
114
|
+
expect(counts["M&A"]).to eq([1, 0])
|
|
115
|
+
expect(counts["隠れ"]).to eq([0, 0]) # linked only from a comment
|
|
116
|
+
expect(counts["記事A"]).to eq([0, 0])
|
|
117
|
+
expect(counts).not_to have_key("東京都区部") # redirects get no row of their own
|
|
118
|
+
end
|
|
119
|
+
end
|
|
120
|
+
|
|
121
|
+
describe Wp2txt::LeadTerms do
|
|
122
|
+
let(:render) { ->(fragment) { Object.new.extend(Wp2txt).format_wiki(fragment, { expand_templates: true, markers: [:all] }) } }
|
|
123
|
+
|
|
124
|
+
def terms(text)
|
|
125
|
+
Wp2txt::LeadTerms.extract(text, render: render)
|
|
126
|
+
end
|
|
127
|
+
|
|
128
|
+
it "takes bold terms of the first paragraph that has one, skipping templates, files, refs, and comments" do
|
|
129
|
+
text = "{{Otheruses|'''x'''}}\n[[ファイル:A.jpg|thumb|'''偽''']]<!-- '''隠''' --><ref>'''注'''</ref>\n" \
|
|
130
|
+
"'''日本語'''(にほんご、にっぽんご{{Refnest|注}})は言語。'''和語'''とも。\n\n次の段落の'''別'''。"
|
|
131
|
+
expect(terms(text).map { |t| [t["text"], t["notes"]] }).to eq([["日本語", %w[にほんご にっぽんご]], ["和語", []]])
|
|
132
|
+
end
|
|
133
|
+
|
|
134
|
+
it "reports spans that cut the bold and the parentheses out of the original text" do
|
|
135
|
+
text = "前置き。'''東京''' (とうきょう)は首都。"
|
|
136
|
+
term = terms(text).first
|
|
137
|
+
expect(text[Range.new(*term["span"]["bold"], true)]).to eq("'''東京'''")
|
|
138
|
+
expect(text[Range.new(*term["span"]["paren"], true)]).to eq("(とうきょう)")
|
|
139
|
+
expect(term["notes_text"]).to eq("とうきょう")
|
|
140
|
+
end
|
|
141
|
+
|
|
142
|
+
it "does not split inside nested brackets, templates, or links" do
|
|
143
|
+
text = "'''山野太郎'''(やまの たろう、[[2001年]](平成13年、辛巳)[[4月1日]] - 、{{lang|en|a, b}})は架空の人物。"
|
|
144
|
+
expect(terms(text).first["notes"]).to eq(["やまの たろう", "2001年(平成13年、辛巳)4月1日 -", "a, b"])
|
|
145
|
+
end
|
|
146
|
+
|
|
147
|
+
it "reports reading templates as pairs and keeps their reading out of the bold text" do
|
|
148
|
+
result = terms("'''{{読み仮名|言語|げんご}}'''は記号体系。")
|
|
149
|
+
expect(result.map { |t| t.slice("text", "reading", "source") })
|
|
150
|
+
.to eq([{ "text" => "言語", "source" => "bold" },
|
|
151
|
+
{ "text" => "言語", "reading" => "げんご", "source" => "読み仮名" }])
|
|
152
|
+
end
|
|
153
|
+
|
|
154
|
+
it "stops at the first heading, ignores an unclosed bracket, and caps the count" do
|
|
155
|
+
expect(terms("'''甲'''(こう\n\n== 節 ==\n'''乙'''").map { |t| [t["text"], t["notes"]] }).to eq([["甲", []]])
|
|
156
|
+
many = (1..8).map { |i| "'''語#{i}'''" }.join("、")
|
|
157
|
+
expect(terms(many).map { |t| t["index"] }).to eq([0, 1, 2, 3, 4])
|
|
158
|
+
end
|
|
159
|
+
|
|
160
|
+
it "returns nothing for empty text" do
|
|
161
|
+
expect(terms("")).to eq([])
|
|
162
|
+
end
|
|
163
|
+
end
|
|
164
|
+
|
|
165
|
+
describe "command line" do
|
|
166
|
+
let(:cli) { File.expand_path("../bin/wp2txt", __dir__) }
|
|
167
|
+
let(:lib) { File.expand_path("../lib", __dir__) }
|
|
168
|
+
|
|
169
|
+
def records(*args)
|
|
170
|
+
out = File.join(@dir, "out#{args.hash.abs}")
|
|
171
|
+
Dir.mkdir(out)
|
|
172
|
+
_stdout, stderr, status = Open3.capture3(RbConfig.ruby, "-I", lib, cli, *args, "-o", out)
|
|
173
|
+
expect(status.success?).to be(true), stderr
|
|
174
|
+
Dir[File.join(out, "*")].flat_map { |f| File.readlines(f) }.map { |l| JSON.parse(l) }.to_h { |r| [r["title"], r] }
|
|
175
|
+
end
|
|
176
|
+
|
|
177
|
+
it "adds the Wikidata ID and lead terms to JSON, identically on both extraction paths" do
|
|
178
|
+
dump, db = build_dump
|
|
179
|
+
Wp2txt::PagePropsImporter.new(db).import!(page_props_file(PAGE_PROPS_SQL.b))
|
|
180
|
+
common = ["-i", dump, "--cache-dir", @dir, "--format", "json", "--summary-only", "--lead-terms"]
|
|
181
|
+
turbo = records(*common)
|
|
182
|
+
streamed = records(*common, "--no-turbo")
|
|
183
|
+
|
|
184
|
+
expect(turbo["東京"].keys.first(4)).to eq(%w[title page_id revision_id qid])
|
|
185
|
+
expect(turbo["東京"]["qid"]).to eq("Q1490")
|
|
186
|
+
expect(turbo["記事B"].slice("qid", "sort_key", "disambiguation")).to eq("qid" => nil, "sort_key" => nil, "disambiguation" => false)
|
|
187
|
+
expect(turbo["東京"]["lead_terms"].first.slice("text", "notes"))
|
|
188
|
+
.to eq("text" => "東京", "notes" => %w[とうきょう Tokyo])
|
|
189
|
+
# (the default path skips articles with empty text; compare what both emit)
|
|
190
|
+
common_titles = turbo.keys & streamed.keys
|
|
191
|
+
expect(common_titles.size).to eq(turbo.size)
|
|
192
|
+
expect(streamed.slice(*common_titles).transform_values { |r| r["lead_terms"] })
|
|
193
|
+
.to eq(turbo.transform_values { |r| r["lead_terms"] })
|
|
194
|
+
end
|
|
195
|
+
|
|
196
|
+
it "requires JSON output for --lead-terms" do
|
|
197
|
+
input = File.join(@dir, "x.xml.bz2")
|
|
198
|
+
File.write(input, "")
|
|
199
|
+
_stdout, stderr, status = Open3.capture3(RbConfig.ruby, "-I", lib, cli, "-i", input, "--lead-terms")
|
|
200
|
+
expect(status.success?).to be(false)
|
|
201
|
+
expect(stderr).to include("--lead-terms requires --format json")
|
|
202
|
+
end
|
|
203
|
+
end
|
|
204
|
+
end
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "spec_helper"
|
|
4
|
+
require "tmpdir"
|
|
5
|
+
require_relative "support/multistream_fixture"
|
|
6
|
+
require "wp2txt/multistream"
|
|
7
|
+
|
|
8
|
+
RSpec.describe Wp2txt::MultistreamReader do
|
|
9
|
+
include MultistreamFixture
|
|
10
|
+
|
|
11
|
+
around do |example|
|
|
12
|
+
Dir.mktmpdir("wp2txt-reader-") do |dir|
|
|
13
|
+
@dir = dir
|
|
14
|
+
example.run
|
|
15
|
+
end
|
|
16
|
+
end
|
|
17
|
+
|
|
18
|
+
# Build a dump from a list of streams, each a string of XML, and an index
|
|
19
|
+
# listing the given titles at the offset of the stream holding them.
|
|
20
|
+
def write_dump(streams, titles_by_stream)
|
|
21
|
+
compressed = streams.map { |xml| xml.is_a?(Hash) ? xml[:raw] : bzip2(xml) }
|
|
22
|
+
dump = File.join(@dir, "dump.xml.bz2")
|
|
23
|
+
File.binwrite(dump, compressed.join)
|
|
24
|
+
offsets = compressed.each_with_index.map { |_, i| compressed[0...i].sum(&:bytesize) }
|
|
25
|
+
lines = titles_by_stream.flat_map do |i, titles|
|
|
26
|
+
titles.each_with_index.map { |t, j| "#{offsets[i]}:#{i * 10 + j + 1}:#{t}" }
|
|
27
|
+
end
|
|
28
|
+
index_path = File.join(@dir, "index.txt")
|
|
29
|
+
File.write(index_path, lines.join("\n") + "\n")
|
|
30
|
+
index = Wp2txt::MultistreamIndex.new(index_path, use_cache: false, show_progress: false)
|
|
31
|
+
described_class.new(dump, index)
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
def page(title, text, id: 1, **opts)
|
|
35
|
+
page_xml(id: id, ns: 0, title: title, text: text, **opts)
|
|
36
|
+
end
|
|
37
|
+
|
|
38
|
+
it "reads the pages of the first and the last range of a dump laid out by Wikimedia" do
|
|
39
|
+
dump, index_path = create_fixture(@dir)
|
|
40
|
+
reader = described_class.new(dump, Wp2txt::MultistreamIndex.new(index_path, use_cache: false,
|
|
41
|
+
show_progress: false))
|
|
42
|
+
expect(reader.extract_article("Film A")).to include(title: "Film A", id: 1, ns: 0, text_available: true)
|
|
43
|
+
# The last range runs to the end of the file and so also holds </mediawiki>
|
|
44
|
+
expect(reader.extract_article("Category:Films")).to include(title: "Category:Films", text: "Top category.\n")
|
|
45
|
+
end
|
|
46
|
+
|
|
47
|
+
it "treats a closing tag before the last range as a malformed range" do
|
|
48
|
+
reader = write_dump([page("Early", "x", id: 1) + "</mediawiki>", page("Late", "y", id: 2)],
|
|
49
|
+
{ 0 => ["Early"], 1 => ["Late"] })
|
|
50
|
+
expect { reader.extract_article("Early") }.to raise_error(Wp2txt::StreamError, /malformed/)
|
|
51
|
+
expect(reader.extract_article("Late")).to include(text: "y")
|
|
52
|
+
end
|
|
53
|
+
|
|
54
|
+
it "reads pages that share a stream with the dump header" do
|
|
55
|
+
reader = write_dump([MultistreamFixture::FIXTURE_HEADER + page("Première", "Texte."), "</mediawiki>"],
|
|
56
|
+
{ 0 => ["Première"] })
|
|
57
|
+
expect(reader.extract_article("Première")).to include(text: "Texte.")
|
|
58
|
+
end
|
|
59
|
+
|
|
60
|
+
it "keeps reading the dump file it was given when the path gets another file" do
|
|
61
|
+
reader = write_dump([page("Same", "old text")], { 0 => ["Same"] })
|
|
62
|
+
other = File.join(@dir, "other.xml.bz2")
|
|
63
|
+
File.binwrite(other, bzip2(page("Same", "new text")))
|
|
64
|
+
File.rename(other, reader.multistream_path)
|
|
65
|
+
expect(reader.extract_article("Same")).to include(text: "old text")
|
|
66
|
+
end
|
|
67
|
+
|
|
68
|
+
it "reports the redirect target the dump records" do
|
|
69
|
+
reader = write_dump([page("Old", "#REDIRECT [[New]]", redirect: "New")], { 0 => ["Old"] })
|
|
70
|
+
expect(reader.extract_article("Old")).to include(redirect: "New")
|
|
71
|
+
end
|
|
72
|
+
|
|
73
|
+
it "tells a suppressed text from an empty one" do
|
|
74
|
+
suppressed = "<page><title>Gone</title><ns>0</ns><id>2</id><revision><id>3</id>" \
|
|
75
|
+
"<text deleted=\"deleted\" /></revision></page>"
|
|
76
|
+
empty = "<page><title>Empty</title><ns>0</ns><id>4</id><revision><id>5</id><text /></revision></page>"
|
|
77
|
+
reader = write_dump([suppressed + empty], { 0 => %w[Gone Empty] })
|
|
78
|
+
expect(reader.extract_article("Gone")).to include(text: "", text_available: false)
|
|
79
|
+
expect(reader.extract_article("Empty")).to include(text: "", text_available: true)
|
|
80
|
+
end
|
|
81
|
+
|
|
82
|
+
it "keeps multibyte text and replaces bytes that are not UTF-8" do
|
|
83
|
+
xml = page("日本語", "本文@@です。").b.sub("@@".b, "\xFF".b)
|
|
84
|
+
reader = write_dump([xml], { 0 => ["日本語"] })
|
|
85
|
+
expect(reader.extract_article("日本語")[:text]).to eq("本文�です。")
|
|
86
|
+
end
|
|
87
|
+
|
|
88
|
+
it "refuses a range whose bzip2 data is cut short" do
|
|
89
|
+
whole = bzip2(page("Cut", "a" * 50_000))
|
|
90
|
+
reader = write_dump([{ raw: whole[0...-30] }], { 0 => ["Cut"] })
|
|
91
|
+
expect { reader.extract_article("Cut") }.to raise_error(Wp2txt::StreamError, /incomplete or corrupt/)
|
|
92
|
+
end
|
|
93
|
+
|
|
94
|
+
it "refuses a range whose pages are not well-formed" do
|
|
95
|
+
reader = write_dump(["<page><title>Open</title><ns>0</ns><id>1</id><revision><text>unclosed"],
|
|
96
|
+
{ 0 => ["Open"] })
|
|
97
|
+
expect { reader.extract_article("Open") }.to raise_error(Wp2txt::StreamError, /malformed/)
|
|
98
|
+
end
|
|
99
|
+
|
|
100
|
+
describe "#each_entry_result" do
|
|
101
|
+
it "hands over each range's results before reading the next range" do
|
|
102
|
+
reader = write_dump([page("One", "1", id: 1), page("Two", "2", id: 2)], { 0 => ["One"], 1 => ["Two"] })
|
|
103
|
+
events = []
|
|
104
|
+
allow(reader).to receive(:pages_at).and_wrap_original do |original, offset|
|
|
105
|
+
events << [:read, offset]
|
|
106
|
+
original.call(offset)
|
|
107
|
+
end
|
|
108
|
+
entries = %w[One Two].map { |t| reader.index.find_by_title(t) }
|
|
109
|
+
reader.each_entry_result(entries) { |entry, _page, _error| events << [:yield, entry[:title]] }
|
|
110
|
+
expect(events.map(&:first)).to eq(%i[read yield read yield])
|
|
111
|
+
end
|
|
112
|
+
|
|
113
|
+
it "calls before_fork before each parallel batch" do
|
|
114
|
+
reader = write_dump([page("One", "1", id: 1), page("Two", "2", id: 2)], { 0 => ["One"], 1 => ["Two"] })
|
|
115
|
+
entries = %w[One Two].map { |t| reader.index.find_by_title(t) }
|
|
116
|
+
forks = 0
|
|
117
|
+
results = reader.each_entry_result(entries, num_processes: 2, before_fork: -> { forks += 1 }).to_a
|
|
118
|
+
expect(results.map { |e, page, _| [e[:title], page[:text]] }).to eq([%w[One 1], %w[Two 2]])
|
|
119
|
+
expect(forks).to eq(1)
|
|
120
|
+
end
|
|
121
|
+
|
|
122
|
+
let(:reader) do
|
|
123
|
+
write_dump([page("Good", "ok", id: 1) + page("Also good", "", id: 2),
|
|
124
|
+
{ raw: bzip2(page("Bad", "b" * 50_000, id: 3))[0...-30] }],
|
|
125
|
+
{ 0 => ["Good", "Also good", "Not in range"], 1 => ["Bad"] })
|
|
126
|
+
end
|
|
127
|
+
|
|
128
|
+
[1, 2].each do |procs|
|
|
129
|
+
it "reports a page, a missing page, or the failure of its range for every entry (#{procs} process)" do
|
|
130
|
+
entries = %w[Good Also\ good Not\ in\ range Bad].map { |t| reader.index.find_by_title(t) }
|
|
131
|
+
results = reader.each_entry_result(entries, num_processes: procs)
|
|
132
|
+
.to_h { |entry, page, error| [entry[:title], [page&.dig(:title), error && [error[:reason], error[:message][/incomplete/]]]] }
|
|
133
|
+
expect(results).to eq(
|
|
134
|
+
"Good" => ["Good", nil], "Also good" => ["Also good", nil],
|
|
135
|
+
"Not in range" => [nil, nil], "Bad" => [nil, [:truncated, "incomplete"]]
|
|
136
|
+
)
|
|
137
|
+
end
|
|
138
|
+
end
|
|
139
|
+
end
|
|
140
|
+
end
|