wp2txt 2.3.4 → 2.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. checksums.yaml +4 -4
  2. data/.dockerignore +0 -4
  3. data/.github/workflows/ci.yml +16 -1
  4. data/.github/workflows/publish-image.yml +8 -4
  5. data/.gitignore +3 -6
  6. data/CHANGELOG.md +32 -0
  7. data/DEVELOPMENT.md +63 -93
  8. data/DEVELOPMENT_ja.md +61 -93
  9. data/Dockerfile +1 -1
  10. data/README.md +93 -8
  11. data/README_ja.md +84 -8
  12. data/Rakefile +10 -21
  13. data/bin/wp2txt +84 -15
  14. data/bin/wp2txt-mcp +1 -1
  15. data/docs/INDEXES.md +61 -1
  16. data/lib/wp2txt/article.rb +2 -3
  17. data/lib/wp2txt/bz2_stream.rb +63 -0
  18. data/lib/wp2txt/cli.rb +90 -26
  19. data/lib/wp2txt/config.rb +2 -11
  20. data/lib/wp2txt/constants.rb +13 -1
  21. data/lib/wp2txt/corpus.rb +10 -23
  22. data/lib/wp2txt/data/template_aliases.json +4 -1
  23. data/lib/wp2txt/data/template_patterns.json +61643 -0
  24. data/lib/wp2txt/dump_snapshot.rb +99 -0
  25. data/lib/wp2txt/extraction_run.rb +272 -0
  26. data/lib/wp2txt/extractor.rb +481 -327
  27. data/lib/wp2txt/formatter.rb +14 -12
  28. data/lib/wp2txt/fts_index.rb +1 -1
  29. data/lib/wp2txt/index_cache.rb +144 -55
  30. data/lib/wp2txt/index_commands.rb +109 -18
  31. data/lib/wp2txt/langlinks_importer.rb +19 -35
  32. data/lib/wp2txt/lead_terms.rb +228 -0
  33. data/lib/wp2txt/link_counter.rb +171 -0
  34. data/lib/wp2txt/magic_words.rb +44 -28
  35. data/lib/wp2txt/metadata_index.rb +82 -13
  36. data/lib/wp2txt/multistream.rb +911 -824
  37. data/lib/wp2txt/output_writer.rb +3 -1
  38. data/lib/wp2txt/page_props_importer.rb +170 -0
  39. data/lib/wp2txt/parser_functions.rb +23 -5
  40. data/lib/wp2txt/ractor_worker.rb +6 -4
  41. data/lib/wp2txt/regex.rb +24 -4
  42. data/lib/wp2txt/site_info.rb +123 -0
  43. data/lib/wp2txt/sql_dump_reader.rb +57 -0
  44. data/lib/wp2txt/stream_processor.rb +9 -2
  45. data/lib/wp2txt/stream_store.rb +91 -0
  46. data/lib/wp2txt/template_args.rb +111 -0
  47. data/lib/wp2txt/template_expander.rb +110 -124
  48. data/lib/wp2txt/template_patterns.rb +182 -0
  49. data/lib/wp2txt/utils.rb +164 -127
  50. data/lib/wp2txt/version.rb +1 -1
  51. data/lib/wp2txt/wikitext_regions.rb +66 -0
  52. data/spec/auto_download_spec.rb +9 -6
  53. data/spec/category_fetcher_spec.rb +135 -463
  54. data/spec/cli_targeted_spec.rb +60 -0
  55. data/spec/config_spec.rb +2 -15
  56. data/spec/constants_spec.rb +0 -4
  57. data/spec/docs_sync_spec.rb +3 -3
  58. data/spec/dump_fetch_spec.rb +293 -0
  59. data/spec/extraction_run_spec.rb +520 -0
  60. data/spec/index_build_spec.rb +113 -0
  61. data/spec/index_commands_version_spec.rb +17 -0
  62. data/spec/langlinks_importer_spec.rb +27 -0
  63. data/spec/lead_terms_edge_cases_spec.rb +194 -0
  64. data/spec/lead_terms_links_qids_spec.rb +204 -0
  65. data/spec/multistream_reader_spec.rb +140 -0
  66. data/spec/multistream_spec.rb +8 -214
  67. data/spec/output_integrity_spec.rb +45 -2
  68. data/spec/p1_correctness_spec.rb +12 -9
  69. data/spec/page_properties_spec.rb +161 -0
  70. data/spec/regex_spec.rb +30 -0
  71. data/spec/region_semantics_spec.rb +71 -0
  72. data/spec/spec_helper.rb +3 -3
  73. data/spec/support/dump_status.rb +34 -0
  74. data/spec/support/multistream_fixture.rb +26 -8
  75. data/spec/template_args_spec.rb +133 -0
  76. data/spec/template_expander_spec.rb +29 -111
  77. data/spec/template_passthrough_spec.rb +58 -0
  78. data/spec/template_patterns_spec.rb +253 -0
  79. data/spec/tracked_paths_spec.rb +168 -0
  80. data/spec/utils_spec.rb +7 -1
  81. metadata +45 -5
  82. data/lib/wp2txt/category_cache.rb +0 -313
  83. data/spec/category_cache_spec.rb +0 -226
@@ -5,8 +5,11 @@ require "tempfile"
5
5
  require "fileutils"
6
6
  require "zlib"
7
7
  require "webmock/rspec"
8
+ require_relative "support/dump_status"
8
9
 
9
10
  RSpec.describe "Wp2txt Multistream" do
11
+ include DumpStatusFixture
12
+
10
13
  before do
11
14
  # Ensure WebMock is enabled (may be disabled by other specs)
12
15
  WebMock.enable!
@@ -16,6 +19,7 @@ RSpec.describe "Wp2txt Multistream" do
16
19
  # Stub Wikipedia dump listing page
17
20
  stub_request(:get, %r{dumps\.wikimedia\.org})
18
21
  .to_return(status: 200, body: '<a href="20260101/">20260101/</a>')
22
+ stub_dump_status
19
23
  end
20
24
 
21
25
  after do
@@ -153,14 +157,6 @@ RSpec.describe "Wp2txt Multistream" do
153
157
  end
154
158
  end
155
159
 
156
- describe "#find_suitable_partial_cache" do
157
- context "when no partial cache exists" do
158
- it "returns nil" do
159
- expect(manager.find_suitable_partial_cache(100)).to be_nil
160
- end
161
- end
162
- end
163
-
164
160
  describe "resumable download support" do
165
161
  let(:test_file_path) { File.join(temp_dir, "test_download.bz2") }
166
162
  let(:test_url) { "https://example.com/test.bz2" }
@@ -373,60 +369,8 @@ RSpec.describe "Wp2txt Multistream" do
373
369
  expect(fetcher.instance_variable_get(:@lang)).to eq("ja")
374
370
  end
375
371
 
376
- it "accepts custom cache_expiry_days" do
377
- fetcher = described_class.new("en", "Test", cache_expiry_days: 14)
378
- expect(fetcher.instance_variable_get(:@cache_expiry_days)).to eq(14)
379
- end
380
- end
381
-
382
- describe "#enable_cache" do
383
- it "sets cache directory" do
384
- fetcher.enable_cache("/tmp/test_cache")
385
- expect(fetcher.instance_variable_get(:@cache_dir)).to eq("/tmp/test_cache")
386
- end
387
372
  end
388
373
 
389
- describe "cache operations" do
390
- let(:temp_cache) { Dir.mktmpdir }
391
- let(:fetcher_with_cache) do
392
- f = described_class.new("en", "Test Category")
393
- f.enable_cache(temp_cache)
394
- f
395
- end
396
-
397
- after { FileUtils.rm_rf(temp_cache) if File.exist?(temp_cache) }
398
-
399
- it "creates CategoryCache when cache enabled" do
400
- expect(fetcher_with_cache.cache).to be_a(Wp2txt::CategoryCache)
401
- end
402
-
403
- it "returns nil for cache when cache disabled" do
404
- fetcher_no_cache = described_class.new("en", "Test")
405
- expect(fetcher_no_cache.cache).to be_nil
406
- end
407
-
408
- it "uses SQLite-based cache file" do
409
- fetcher_with_cache.cache
410
- cache_files = Dir.glob(File.join(temp_cache, "categories_*.sqlite3"))
411
- expect(cache_files.size).to eq 1
412
- end
413
-
414
- it "saves and loads from cache" do
415
- category = "Cache_Test"
416
- members = { pages: ["Article1", "Article2"], subcats: ["SubCat1"] }
417
-
418
- fetcher_with_cache.send(:save_to_cache, category, members)
419
- loaded = fetcher_with_cache.send(:load_from_cache, category)
420
-
421
- expect(loaded[:pages]).to contain_exactly("Article1", "Article2")
422
- expect(loaded[:subcats]).to contain_exactly("SubCat1")
423
- end
424
-
425
- it "returns nil for non-existent cache" do
426
- result = fetcher_with_cache.send(:load_from_cache, "NonExistent")
427
- expect(result).to be_nil
428
- end
429
- end
430
374
  end
431
375
 
432
376
  describe Wp2txt::MultistreamReader do
@@ -476,18 +420,15 @@ RSpec.describe "Wp2txt Multistream" do
476
420
  end
477
421
  end
478
422
 
479
- describe "#each_article_parallel" do
423
+ describe "#each_entry_result" do
480
424
  it "returns an enumerator when no block given" do
481
425
  reader = described_class.new(multistream_path, index_path, cache_dir: temp_dir)
482
- result = reader.each_article_parallel([], num_processes: 2)
483
- expect(result).to be_an(Enumerator)
426
+ expect(reader.each_entry_result([], num_processes: 2)).to be_an(Enumerator)
484
427
  end
485
428
 
486
- it "handles empty entries array" do
429
+ it "yields nothing for no entries" do
487
430
  reader = described_class.new(multistream_path, index_path, cache_dir: temp_dir)
488
- pages = []
489
- reader.each_article_parallel([], num_processes: 2) { |page| pages << page }
490
- expect(pages).to eq([])
431
+ expect(reader.each_entry_result([], num_processes: 2).to_a).to eq([])
491
432
  end
492
433
  end
493
434
  end
@@ -539,152 +480,5 @@ RSpec.describe "Wp2txt Multistream" do
539
480
  end
540
481
  end
541
482
 
542
- describe "#cached_partial_multistream_path" do
543
- let(:temp_dir) { Dir.mktmpdir }
544
- let(:manager) { described_class.new("en", cache_dir: temp_dir) }
545
-
546
- after { FileUtils.remove_entry(temp_dir) }
547
-
548
- it "includes stream count in filename" do
549
- path = manager.cached_partial_multistream_path(1000)
550
- expect(path).to include("1000streams")
551
- expect(path).to end_with(".xml.bz2")
552
- end
553
- end
554
-
555
- describe "#find_any_partial_cache" do
556
- let(:temp_dir) { Dir.mktmpdir }
557
- let(:manager) { described_class.new("en", cache_dir: temp_dir) }
558
-
559
- after { FileUtils.remove_entry(temp_dir) }
560
-
561
- context "when no partial exists" do
562
- it "returns nil" do
563
- expect(manager.find_any_partial_cache).to be_nil
564
- end
565
- end
566
-
567
- context "when partial dumps exist" do
568
- before do
569
- # Create fake partial dump files
570
- File.write(File.join(temp_dir, "enwiki-20260101-multistream-100streams.xml.bz2"), "BZh9" + "x" * 100)
571
- File.write(File.join(temp_dir, "enwiki-20260101-multistream-500streams.xml.bz2"), "BZh9" + "x" * 500)
572
- end
573
-
574
- it "returns the largest partial by stream count" do
575
- result = manager.find_any_partial_cache
576
- expect(result).not_to be_nil
577
- expect(result[:stream_count]).to eq(500)
578
- expect(result[:dump_date]).to eq("20260101")
579
- end
580
-
581
- it "includes file size and mtime" do
582
- result = manager.find_any_partial_cache
583
- expect(result[:size]).to be > 0
584
- expect(result[:mtime]).to be_a(Time)
585
- end
586
- end
587
-
588
- context "with partials from different dates" do
589
- before do
590
- File.write(File.join(temp_dir, "enwiki-20260101-multistream-100streams.xml.bz2"), "BZh9" + "x" * 100)
591
- File.write(File.join(temp_dir, "enwiki-20260201-multistream-50streams.xml.bz2"), "BZh9" + "x" * 50)
592
- end
593
-
594
- it "returns the largest regardless of date" do
595
- result = manager.find_any_partial_cache
596
- expect(result[:stream_count]).to eq(100)
597
- expect(result[:dump_date]).to eq("20260101")
598
- end
599
- end
600
- end
601
-
602
- describe "#can_resume_from_partial?" do
603
- let(:temp_dir) { Dir.mktmpdir }
604
- let(:manager) { described_class.new("en", cache_dir: temp_dir) }
605
-
606
- after { FileUtils.remove_entry(temp_dir) }
607
-
608
- context "when partial_info is nil" do
609
- it "returns not possible with :no_partial reason" do
610
- result = manager.can_resume_from_partial?(nil)
611
- expect(result[:possible]).to be false
612
- expect(result[:reason]).to eq(:no_partial)
613
- end
614
- end
615
-
616
- context "when dump dates don't match" do
617
- let(:partial_info) do
618
- {
619
- path: File.join(temp_dir, "enwiki-20250101-multistream-100streams.xml.bz2"),
620
- dump_date: "20250101",
621
- stream_count: 100,
622
- size: 1000
623
- }
624
- end
625
-
626
- before do
627
- # Create the file
628
- File.write(partial_info[:path], "BZh9" + "x" * 100)
629
- # Stub the latest_dump_date to return a different date
630
- allow(manager).to receive(:latest_dump_date).and_return("20260101")
631
- end
632
-
633
- it "returns not possible with :date_mismatch reason" do
634
- result = manager.can_resume_from_partial?(partial_info)
635
- expect(result[:possible]).to be false
636
- expect(result[:reason]).to eq(:date_mismatch)
637
- expect(result[:partial_date]).to eq("20250101")
638
- expect(result[:latest_date]).to eq("20260101")
639
- end
640
- end
641
-
642
- context "when partial file is invalid" do
643
- let(:partial_info) do
644
- {
645
- path: File.join(temp_dir, "enwiki-20260101-multistream-100streams.xml.bz2"),
646
- dump_date: "20260101",
647
- stream_count: 100,
648
- size: 1000
649
- }
650
- end
651
-
652
- before do
653
- # Create an invalid bz2 file (wrong magic bytes)
654
- File.write(partial_info[:path], "XXXX" + "x" * 100)
655
- allow(manager).to receive(:latest_dump_date).and_return("20260101")
656
- end
657
-
658
- it "returns not possible with :invalid_partial reason" do
659
- result = manager.can_resume_from_partial?(partial_info)
660
- expect(result[:possible]).to be false
661
- expect(result[:reason]).to eq(:invalid_partial)
662
- end
663
- end
664
- end
665
-
666
- describe "#get_remote_file_size" do
667
- let(:temp_dir) { Dir.mktmpdir }
668
- let(:manager) { described_class.new("en", cache_dir: temp_dir) }
669
-
670
- after { FileUtils.remove_entry(temp_dir) }
671
-
672
- it "returns file size from Content-Length header" do
673
- stub_request(:head, %r{dumps\.wikimedia\.org})
674
- .to_return(status: 200, headers: { "Content-Length" => "12345678" })
675
-
676
- allow(manager).to receive(:latest_dump_date).and_return("20260101")
677
- size = manager.send(:get_remote_file_size, "https://dumps.wikimedia.org/enwiki/20260101/test.xml.bz2")
678
- expect(size).to eq(12_345_678)
679
- end
680
-
681
- it "returns 0 when Content-Length is missing" do
682
- stub_request(:head, %r{dumps\.wikimedia\.org})
683
- .to_return(status: 200, headers: {})
684
-
685
- size = manager.send(:get_remote_file_size, "https://dumps.wikimedia.org/test.xml.bz2")
686
- expect(size).to eq(0)
687
- end
688
- end
689
483
  end
690
484
  end
@@ -7,6 +7,7 @@ require "tmpdir"
7
7
  require "parallel"
8
8
  require_relative "support/multistream_fixture"
9
9
  require "wp2txt/multistream"
10
+ require "wp2txt/extractor"
10
11
  require "wp2txt/output_writer"
11
12
  require "wp2txt/stream_processor"
12
13
 
@@ -119,8 +120,8 @@ RSpec.describe "output integrity" do
119
120
  index = Wp2txt::MultistreamIndex.new(index_path, use_cache: false, target_titles: ["Film A"],
120
121
  show_progress: false)
121
122
  expect(index.early_terminated?).to be(true)
122
- expect(index.stream_offsets).to eq([0])
123
- second_stream = File.readlines(index_path).map { |line| line.split(":").first.to_i }.uniq[1]
123
+ first_stream, second_stream = File.readlines(index_path).map { |line| line.split(":").first.to_i }.uniq
124
+ expect(index.stream_offsets).to eq([first_stream])
124
125
  expect(index.stream_end_offset).to eq(second_stream)
125
126
  end
126
127
 
@@ -142,5 +143,47 @@ RSpec.describe "output integrity" do
142
143
  stub_const("Wp2txt::MultistreamReader::MAX_TAIL_STREAM_BYTES", 0)
143
144
  expect { reader.extract_article("Film A") }.to raise_error(Wp2txt::Error, /cannot locate the end/)
144
145
  end
146
+
147
+ describe "choosing the ranges to fetch" do
148
+ let(:extractor) { Object.new.extend(Wp2txt::Extractor) }
149
+ let(:snapshot) { instance_double(Wp2txt::DumpSnapshot, dump_file: Wp2txt::DumpSnapshot::FileInfo.new(size: 10_000)) }
150
+ let(:manager) { instance_double(Wp2txt::DumpManager, verified_full_dump: nil, snapshot: snapshot) }
151
+
152
+ def stream_starts(index_path)
153
+ File.readlines(index_path).map { |line| line.split(":").first.to_i }.uniq
154
+ end
155
+
156
+ def source_for(index_path, title, **index_opts)
157
+ index = Wp2txt::MultistreamIndex.new(index_path, use_cache: false, show_progress: false, **index_opts)
158
+ extractor.stream_source(manager, index, [index.find_by_title(title)[:offset]])
159
+ end
160
+
161
+ it "fetches only the range holding the article after an early index stop" do
162
+ _dump, index_path = create_fixture(@dir)
163
+ first, second = stream_starts(index_path)
164
+ expect(manager).to receive(:fetch_streams).with([[first, second]])
165
+ source_for(index_path, "Film A", target_titles: ["Film A"])
166
+ end
167
+
168
+ it "fetches the same range when the whole index was read" do
169
+ _dump, index_path = create_fixture(@dir)
170
+ first, second = stream_starts(index_path)
171
+ expect(manager).to receive(:fetch_streams).with([[first, second]])
172
+ source_for(index_path, "Film A")
173
+ end
174
+
175
+ it "fetches the last range up to the end of the dump file" do
176
+ _dump, index_path = create_fixture(@dir)
177
+ expect(manager).to receive(:fetch_streams).with([[stream_starts(index_path)[1], 10_000]])
178
+ source_for(index_path, "Category:Films", target_titles: ["Category:Films"])
179
+ end
180
+
181
+ it "reads the cached whole dump instead when it is known to be complete" do
182
+ dump, index_path = create_fixture(@dir)
183
+ allow(manager).to receive(:verified_full_dump).and_return(dump)
184
+ expect(manager).not_to receive(:fetch_streams)
185
+ expect(source_for(index_path, "Film A")).to eq(dump)
186
+ end
187
+ end
145
188
  end
146
189
  end
@@ -356,17 +356,20 @@ RSpec.describe "P1 correctness contracts" do
356
356
  Rake.application = previous
357
357
  end
358
358
 
359
- [[false, "Cannot connect to daemon"], [false, "image missing"], [true, "LEAK:/wp2txt/tmp\n"]].each do |success, output|
360
- it "fails verification for #{output.strip}" do
361
- allow(Open3).to receive(:capture2e).and_return([output, double(success?: success)])
362
- expect { suppress_stderr { Rake::Task[:verify_image].invoke("test-image") } }.to raise_error(SystemExit)
363
- end
359
+ it "builds from a clean clone and hands the image to the CI gate with that clone as context" do
360
+ commands = []
361
+ allow(TOPLEVEL_BINDING.receiver).to receive(:sh) { |*args| commands << args }
362
+ Rake::Task[:check_image].invoke
363
+ clone, build, gate = commands
364
+ expect(clone.first(4)).to eq(%w[git clone --quiet --no-local])
365
+ dir = clone.last
366
+ expect(build).to eq(["docker", "build", "-t", "wp2txt-verify:local", dir])
367
+ expect(gate).to eq(["ruby", "scripts/verify_image.rb", "wp2txt-verify:local", "--context", dir])
364
368
  end
365
369
 
366
- it "passes only after a successful clean container inspection" do
367
- expect(Open3).to receive(:capture2e).with("docker", "run", "--rm", "test-image", "sh", "-c", kind_of(String))
368
- .and_return(["", double(success?: true)])
369
- expect { Rake::Task[:verify_image].invoke("test-image") }.to output(/OK:/).to_stdout
370
+ it "no longer carries a hand-written list of forbidden paths" do
371
+ expect(Rake::Task.task_defined?(:verify_image)).to be(false)
372
+ expect(defined?(IMAGE_FORBIDDEN_PATHS)).to be_nil
370
373
  end
371
374
  end
372
375
  end
@@ -0,0 +1,161 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "spec_helper"
4
+ require "wp2txt/page_props_importer"
5
+ require "wp2txt/metadata_index"
6
+ require "wp2txt/corpus"
7
+ require "wp2txt/link_counter"
8
+ require "tmpdir"
9
+ require "open3"
10
+ require "json"
11
+ require "zlib"
12
+ require_relative "support/multistream_fixture"
13
+
14
+ RSpec.describe "page properties" do
15
+ include MultistreamFixture
16
+ TITLES = %w[東京 QID パイプ Sort Invalid Other Empty Absent].freeze
17
+ FIELDS = %w[qid sort_key disambiguation].freeze
18
+
19
+ around do |example|
20
+ Dir.mktmpdir do |dir|
21
+ @dir = dir
22
+ @dump = File.join(dir, "testwiki-20260101-pages-articles-multistream.xml.bz2")
23
+ xml = TITLES.each_with_index.map { |t, i| page_xml(id: i + 1, ns: 0, title: t, text: "'''#{t}'''です。") }.join
24
+ File.binwrite(@dump, bzip2("<mediawiki>\n#{xml}</mediawiki>"))
25
+ File.write(@dump.sub(".xml.bz2", "-index.txt"), TITLES.each_with_index.map { |t, i| "0:#{i + 1}:#{t}\n" }.join)
26
+ @db_path = Wp2txt::MetadataIndex.path_for(@dump, cache_dir: dir)
27
+ Wp2txt::MetadataIndexBuilder.new(@dump, [0], db_path: @db_path, num_processes: 0).build.close
28
+ @source = File.join(dir, "testwiki-20260101-page_props.sql.gz")
29
+ @sql = <<~SQL
30
+ INSERT INTO `page_props` VALUES
31
+ (1,'defaultsort','とうきよう',NULL),
32
+ (1,'disambiguation','ignored',NULL),
33
+ (1,'wikibase_item','Q1490',NULL),
34
+ (2,'wikibase_item','Q2',NULL),
35
+ (3,'disambiguation','',NULL),
36
+ (4,'defaultsort','O\\'Brien あ',NULL),
37
+ (5,'defaultsort','\xFF\xFE',NULL),
38
+ (6,'other','ignored',NULL),
39
+ (7,'defaultsort','',NULL),
40
+ (8,'wikibase_item','bad',NULL);
41
+ INSERT INTO `other_table` VALUES (8,'wikibase_item','Q999',NULL);
42
+ SQL
43
+ Zlib::GzipWriter.open(@source) { |gz| gz.write(@sql.b) }
44
+ example.run
45
+ end
46
+ end
47
+
48
+ def import(**options)
49
+ Wp2txt::PagePropsImporter.new(@db_path).import!(@source, **options)
50
+ end
51
+
52
+ def with_db
53
+ db = SQLite3::Database.new(@db_path)
54
+ yield db
55
+ ensure
56
+ db&.close
57
+ end
58
+
59
+ it "merges all three properties across batches and records counts and invalid sort keys" do
60
+ stub_const("Wp2txt::PagePropsImporter::BATCH_SIZE", 1)
61
+ result = import
62
+ expect(result[:row_count]).to eq(5)
63
+ with_db do |db|
64
+ expect(db.execute("SELECT page_id,qid,disambiguation,sort_key FROM page_properties ORDER BY page_id"))
65
+ .to eq([[1, "Q1490", 1, "とうきよう"], [2, "Q2", 0, nil], [3, nil, 1, nil],
66
+ [4, nil, 0, "O'Brien あ"], [7, nil, 0, ""]])
67
+ end
68
+ expect(result[:provenance]).to include(page_count: 5, qid_count: 2, disambiguation_count: 2,
69
+ sort_key_count: 3, skipped_invalid_sort_keys: 1,
70
+ source_sha256: Digest::SHA256.file(@source).hexdigest)
71
+ expect(import).to include(status: :already_imported, row_count: 5, provenance: result[:provenance])
72
+ end
73
+
74
+ it "replaces the unreleased QID table without requiring force" do
75
+ with_db do |db|
76
+ db.execute("CREATE TABLE page_qids (page_id INTEGER PRIMARY KEY, qid TEXT)")
77
+ db.execute("INSERT INTO metadata VALUES ('page_props_imported_at','old')")
78
+ end
79
+ expect(import[:status]).to eq(:imported)
80
+ with_db { |db| expect(db.get_first_value("SELECT 1 FROM sqlite_master WHERE name='page_qids'")).to be_nil }
81
+ end
82
+
83
+ def records(*flags)
84
+ out = Dir.mktmpdir("out-", @dir)
85
+ _, stderr, status = Open3.capture3(RbConfig.ruby, "-I", File.expand_path("../lib", __dir__),
86
+ File.expand_path("../bin/wp2txt", __dir__), "-i", @dump,
87
+ "--cache-dir", @dir, "--format", "json", "-n", "2", "-o", out, *flags)
88
+ expect(status.success?).to be(true), stderr
89
+ Dir[File.join(out, "*.jsonl")].flat_map { |f| File.readlines(f).map { |s| JSON.parse(s) } }.to_h { |r| [r["title"], r] }
90
+ end
91
+
92
+ it "always emits the three fields after import on both CLI paths, including null and false" do
93
+ import
94
+ turbo, stream = records, records("--no-turbo")
95
+ expect(turbo.size).to eq(8)
96
+ expect(turbo).to eq(stream)
97
+ turbo.each_value { |r| expect(r.keys.first(6)).to eq(%w[title page_id revision_id qid sort_key disambiguation]) }
98
+ expect(turbo["東京"].slice(*FIELDS)).to eq("qid" => "Q1490", "sort_key" => "とうきよう", "disambiguation" => true)
99
+ expect(turbo["パイプ"].slice(*FIELDS)).to eq("qid" => nil, "sort_key" => nil, "disambiguation" => true)
100
+ expect(turbo["Absent"].slice(*FIELDS)).to eq("qid" => nil, "sort_key" => nil, "disambiguation" => false)
101
+ expect(turbo["Empty"]["sort_key"]).to eq("")
102
+ end
103
+
104
+ it "omits all three fields before import and after a failed force import" do
105
+ [false, true].each do |fail_import|
106
+ if fail_import
107
+ import
108
+ Zlib::GzipWriter.open(@source) { |gz| gz.write("-- empty\n") }
109
+ expect { import(force: true) }.to raise_error(Wp2txt::Error, /no page_props rows/)
110
+ end
111
+ [[], ["--no-turbo"]].each do |flags|
112
+ records(*flags).each_value { |r| expect(r.keys & FIELDS).to eq([]) }
113
+ end
114
+ end
115
+ end
116
+
117
+ it "attaches properties to Ractor JSON in the parent without omitting nulls" do
118
+ import
119
+ result = records("--no-turbo", "--ractor")
120
+ expect(result["東京"].slice(*FIELDS)).to eq("qid" => "Q1490", "sort_key" => "とうきよう", "disambiguation" => true)
121
+ expect(result["Absent"].slice(*FIELDS)).to eq("qid" => nil, "sort_key" => nil, "disambiguation" => false)
122
+ end
123
+
124
+ it "distinguishes an imported dump with no relevant properties from an unimported dump" do
125
+ Zlib::GzipWriter.open(@source) { |gz| gz.write("INSERT INTO `page_props` VALUES (1,'other','',NULL);\n") }
126
+ expect(import[:row_count]).to eq(0)
127
+ expect(records["東京"].slice(*FIELDS)).to eq("qid" => nil, "sort_key" => nil, "disambiguation" => false)
128
+ end
129
+
130
+ it "applies the same contract to MCP's Corpus methods and provenance" do
131
+ corpus = Wp2txt::Corpus.for_input(@dump, cache_dir: @dir)
132
+ expect(corpus.get_article("東京").keys & FIELDS.map(&:to_sym)).to eq([])
133
+ unimported = File.join(@dir, "unimported.jsonl")
134
+ corpus.extract_corpus(output_path: unimported, titles: ["東京", "Absent"], content: "full", num_processes: 0)
135
+ File.readlines(unimported).each { |line| expect(JSON.parse(line).keys & FIELDS).to eq([]) }
136
+ corpus.close
137
+ import
138
+ corpus = Wp2txt::Corpus.for_input(@dump, cache_dir: @dir)
139
+ expect(corpus.get_article("東京")).to include(qid: "Q1490", sort_key: "とうきよう", disambiguation: true)
140
+ expect(corpus.get_article("Absent")).to include(qid: nil, sort_key: nil, disambiguation: false)
141
+ output = File.join(@dir, "corpus.jsonl")
142
+ corpus.extract_corpus(output_path: output, titles: ["東京", "パイプ", "Absent"], content: "full", num_processes: 0)
143
+ rows = File.readlines(output).map { |s| JSON.parse(s) }
144
+ expect(rows.size).to eq(3)
145
+ rows.each { |r| expect(r.keys & FIELDS).to match_array(FIELDS) }
146
+ expect(rows.last.slice(*FIELDS)).to eq("qid" => nil, "sort_key" => nil, "disambiguation" => false)
147
+ expect(corpus.dump_info[:page_properties]).to include(qid_count: 2, disambiguation_count: 2, sort_key_count: 3,
148
+ skipped_invalid_sort_keys: 1)
149
+ ensure
150
+ corpus&.close
151
+ end
152
+
153
+ it "decodes title references once, including escaped ampersands and numeric references" do
154
+ counter = Wp2txt::LinkCounter.new("", [], db_path: "")
155
+ counter.instance_variable_set(:@redirects, {})
156
+ direct, via = Hash.new(0), Hash.new(0)
157
+ text = "[[A&amp;amp;B]] [[Caf&#233;]] [[東京&#35;節]] [[X&amp;lt;Y]]"
158
+ counter.send(:count_page, page_xml(id: 1, ns: 0, title: "Source", text: text), direct, via)
159
+ expect(direct).to eq("A&amp;B" => 1, "Café" => 1, "東京" => 1, "X&lt;Y" => 1)
160
+ end
161
+ end
data/spec/regex_spec.rb CHANGED
@@ -190,6 +190,36 @@ RSpec.describe "Wp2txt Regex Patterns" do
190
190
  end
191
191
  end
192
192
 
193
+ describe ".category_names" do
194
+ it "reads the name without the sort key" do
195
+ expect(Wp2txt.category_names("[[Category:Science|Physics]] [[ Kategorie : Wissenschaft ]]"))
196
+ .to eq ["Science", "Wissenschaft"]
197
+ end
198
+
199
+ it "does not take a link that only shows a category" do
200
+ text = "[[:Category:Science]] [[:en:Category:Polish painters|Category:Polish painters{{Fontsize|75%|(en)}}]]"
201
+ expect(Wp2txt.category_names(text)).to eq []
202
+ end
203
+
204
+ it "does not take a namespace name written outside a link" do
205
+ expect(Wp2txt.category_names("{{unbulleted list|CT:{{Start date|1979}}}} |Category:Science]]")).to eq []
206
+ end
207
+
208
+ it "leaves out a template that sets the sort key, and a name holding any other template" do
209
+ expect(Wp2txt.category_names("[[Category:Actors{{DEFAULTSORT:}}]] [[Category:A{{DEFAULTSORT:{{PAGENAME}}}}]]"))
210
+ .to eq ["Actors", "A"]
211
+ expect(Wp2txt.category_names("[[Category:Alpha_{{PAGENAME}}]] [[Category:{{PAGENAME}}]]")).to eq []
212
+ end
213
+
214
+ it "reads {{!}} as the bar before the sort key" do
215
+ expect(Wp2txt.category_names("[[Category:Before{{!}}After]]")).to eq ["Before"]
216
+ end
217
+
218
+ it "does not take a link broken across lines or not closed" do
219
+ expect(Wp2txt.category_names("[[\nCategory:Split]] [[Category:\nBeta]] [[Category:Open|sort")).to eq []
220
+ end
221
+ end
222
+
193
223
  describe "IN_LINK_REGEX" do
194
224
  it "matches wikilinks on their own line" do
195
225
  expect("[[Article]]").to match(in_link_regex)
@@ -0,0 +1,71 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "spec_helper"
4
+ require "wp2txt/lead_terms"
5
+ require "wp2txt/link_counter"
6
+ require_relative "support/multistream_fixture"
7
+
8
+ RSpec.describe "literal regions and lead prose" do
9
+ include MultistreamFixture
10
+
11
+ def terms(text)
12
+ render = ->(s) { Object.new.extend(Wp2txt).format_wiki(s, expand_templates: true, markers: [:all]) }
13
+ Wp2txt::LeadTerms.extract(text, render: render)
14
+ end
15
+
16
+ def counts(text)
17
+ counter = Wp2txt::LinkCounter.new("", [], db_path: "")
18
+ counter.instance_variable_set(:@redirects, {})
19
+ direct, via = Hash.new(0), Hash.new(0)
20
+ counter.send(:count_page, page_xml(id: 1, ns: 0, title: "Source", text: text), direct, via)
21
+ direct
22
+ end
23
+
24
+ %w[gallery timeline].each do |tag|
25
+ it "counts links inside #{tag}, but excludes its bold text from the lead" do
26
+ text = "<#{tag}>[[東京]] '''偽'''(にせ)</#{tag}>\n\n'''大阪'''(おおさか)。"
27
+ expect(counts(text)).to eq("東京" => 1)
28
+ expect(terms(text).map { |term| term["text"] }).to eq(["大阪"])
29
+ expect(counts("<#{tag}>[[東京]]<nowiki>[[京都]]</nowiki>[[大阪]]</#{tag}>"))
30
+ .to eq("東京" => 1, "大阪" => 1)
31
+ end
32
+ end
33
+
34
+ it "counts links and extracts bold terms inside code as ordinary wikitext" do
35
+ text = "<code>'''東京'''(とうきょう) [[大阪]]</code>"
36
+ expect(counts(text)).to eq("大阪" => 1)
37
+ term = terms(text).first
38
+ expect(term).not_to be_nil
39
+ expect(term.slice("text", "notes")).to eq("text" => "東京", "notes" => ["とうきょう"])
40
+ s, e = term["span"]["bold"]
41
+ expect(text[s...e]).to eq("'''東京'''")
42
+ s, e = term["span"]["paren"]
43
+ expect(text[s...e]).to eq("(とうきょう)")
44
+ end
45
+
46
+ %w[nowiki pre math chem ce score syntaxhighlight source graph mapframe templatedata].each do |tag|
47
+ it "excludes literal #{tag} contents from both consumers and protects its pipes" do
48
+ region = "<#{tag}>[[東京]] '''偽'''(にせ)A|B</#{tag}>"
49
+ expect(counts(region + "[[大阪]]")).to eq("大阪" => 1)
50
+ expect(terms(region + "\n\n'''大阪'''(おおさか)。").map { |term| term["text"] }).to eq(["大阪"])
51
+ expect(Wp2txt::WikitextRegions.split_pipes("ruby|#{region}|よみ")).to eq(["ruby", region, "よみ"])
52
+ end
53
+ end
54
+
55
+ %w[gallery timeline code].each do |tag|
56
+ it "splits template pipes inside #{tag} while still protecting nested literal regions" do
57
+ expect(Wp2txt::WikitextRegions.split_pipes("ruby|<#{tag}>A|B</#{tag}>|よみ"))
58
+ .to eq(["ruby", "<#{tag}>A", "B</#{tag}>", "よみ"])
59
+ expect(Wp2txt::WikitextRegions.split_pipes("ruby|<#{tag}>A<nowiki>|</nowiki>B|C</#{tag}>|よみ"))
60
+ .to eq(["ruby", "<#{tag}>A<nowiki>|</nowiki>B", "C</#{tag}>", "よみ"])
61
+ end
62
+ end
63
+
64
+ it "continues to exclude comments and keeps rule version 2" do
65
+ expect(counts("<!-- [[東京]] -->[[大阪]]")).to eq("大阪" => 1)
66
+ expect(terms("<!-- '''偽''' -->'''大阪'''(おおさか)").first["text"]).to eq("大阪")
67
+ expect(Wp2txt::WikitextRegions.split_pipes("ruby|<!-- a|b -->東京|よみ"))
68
+ .to eq(["ruby", "<!-- a|b -->東京", "よみ"])
69
+ expect(Wp2txt::LinkCounter::RULE_VERSION).to eq("2")
70
+ end
71
+ end
data/spec/spec_helper.rb CHANGED
@@ -61,9 +61,9 @@ RSpec.configure do |config|
61
61
 
62
62
  # Per-example wall-clock guard. The suite deliberately exercises runaway
63
63
  # queries and forked workers; an interrupted or wedged example must not turn
64
- # into a process spinning at 100% CPU for days (observed 2026-07-24).
65
- # Slowest legitimate example is ~14s, so 120s is pure headroom. Override with
66
- # WP2TXT_SPEC_TIMEOUT=0 to disable, or tag an example :no_timeout.
64
+ # into a process spinning at full CPU indefinitely. The limit is far above
65
+ # what any example needs. Override with WP2TXT_SPEC_TIMEOUT=0 to disable,
66
+ # or tag an example :no_timeout.
67
67
  spec_timeout = (ENV["WP2TXT_SPEC_TIMEOUT"] || 120).to_i
68
68
  if spec_timeout.positive?
69
69
  require "timeout"