wp2txt 2.4.0 → 2.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. checksums.yaml +4 -4
  2. data/.github/workflows/ci.yml +16 -1
  3. data/.github/workflows/publish-image.yml +8 -4
  4. data/.gitignore +0 -1
  5. data/CHANGELOG.md +23 -0
  6. data/DEVELOPMENT.md +62 -92
  7. data/DEVELOPMENT_ja.md +60 -92
  8. data/Dockerfile +1 -1
  9. data/README.md +54 -8
  10. data/README_ja.md +54 -8
  11. data/bin/wp2txt +23 -6
  12. data/lib/wp2txt/article.rb +1 -2
  13. data/lib/wp2txt/bz2_stream.rb +63 -0
  14. data/lib/wp2txt/cli.rb +48 -26
  15. data/lib/wp2txt/config.rb +2 -11
  16. data/lib/wp2txt/constants.rb +0 -1
  17. data/lib/wp2txt/corpus.rb +1 -21
  18. data/lib/wp2txt/data/template_aliases.json +3 -0
  19. data/lib/wp2txt/data/template_patterns.json +61643 -0
  20. data/lib/wp2txt/dump_snapshot.rb +99 -0
  21. data/lib/wp2txt/extraction_run.rb +272 -0
  22. data/lib/wp2txt/extractor.rb +476 -325
  23. data/lib/wp2txt/fts_index.rb +1 -1
  24. data/lib/wp2txt/index_cache.rb +144 -55
  25. data/lib/wp2txt/index_commands.rb +22 -19
  26. data/lib/wp2txt/link_counter.rb +1 -1
  27. data/lib/wp2txt/magic_words.rb +44 -28
  28. data/lib/wp2txt/metadata_index.rb +6 -13
  29. data/lib/wp2txt/multistream.rb +890 -824
  30. data/lib/wp2txt/output_writer.rb +3 -1
  31. data/lib/wp2txt/parser_functions.rb +23 -5
  32. data/lib/wp2txt/ractor_worker.rb +6 -4
  33. data/lib/wp2txt/regex.rb +24 -4
  34. data/lib/wp2txt/site_info.rb +123 -0
  35. data/lib/wp2txt/stream_store.rb +91 -0
  36. data/lib/wp2txt/template_args.rb +111 -0
  37. data/lib/wp2txt/template_expander.rb +92 -125
  38. data/lib/wp2txt/template_patterns.rb +182 -0
  39. data/lib/wp2txt/utils.rb +160 -125
  40. data/lib/wp2txt/version.rb +1 -1
  41. data/spec/auto_download_spec.rb +9 -6
  42. data/spec/category_fetcher_spec.rb +135 -463
  43. data/spec/cli_targeted_spec.rb +60 -0
  44. data/spec/config_spec.rb +2 -15
  45. data/spec/constants_spec.rb +0 -4
  46. data/spec/dump_fetch_spec.rb +293 -0
  47. data/spec/extraction_run_spec.rb +520 -0
  48. data/spec/index_build_spec.rb +113 -0
  49. data/spec/index_commands_version_spec.rb +17 -0
  50. data/spec/multistream_reader_spec.rb +140 -0
  51. data/spec/multistream_spec.rb +8 -214
  52. data/spec/output_integrity_spec.rb +45 -2
  53. data/spec/regex_spec.rb +30 -0
  54. data/spec/spec_helper.rb +3 -3
  55. data/spec/support/dump_status.rb +34 -0
  56. data/spec/support/multistream_fixture.rb +26 -8
  57. data/spec/template_args_spec.rb +133 -0
  58. data/spec/template_expander_spec.rb +29 -111
  59. data/spec/template_passthrough_spec.rb +17 -2
  60. data/spec/template_patterns_spec.rb +253 -0
  61. data/spec/tracked_paths_spec.rb +168 -0
  62. data/spec/utils_spec.rb +7 -1
  63. metadata +30 -5
  64. data/lib/wp2txt/category_cache.rb +0 -313
  65. data/spec/category_cache_spec.rb +0 -226
data/lib/wp2txt/utils.rb CHANGED
@@ -119,9 +119,23 @@ module Wp2txt
119
119
  }
120
120
  }.freeze
121
121
 
122
+ # {{!}} and {{=}} stand for a literal "|" and "=" inside template
123
+ # arguments; they become those characters only once templates are expanded,
124
+ # so they are held until then as noncharacters, which Unicode reserves for
125
+ # a program's internal use and text for interchange does not hold
126
+ LITERAL_PIPE = "\u{FDD0}"
127
+ LITERAL_EQUALS = "\u{FDD1}"
128
+ # Noncharacters this program uses internally (see also TemplatePatterns)
129
+ INTERNAL_CHARACTERS = "\u{FDD0}-\u{FDD5}"
130
+ INTERNAL_CHARACTER_REFERENCE = /&#(?:x0*fdd[0-5]|0*6497[6-9]|0*6498[01]);/i
131
+
122
132
  def format_wiki(text, config = {})
123
133
  # Work with a mutable copy to reduce intermediate string allocations
124
- result = +text.to_s
134
+ # The noncharacters used as placeholders are not text: any in the input
135
+ # are shown as U+FFFD rather than taken for "|" or "="
136
+ result = text.to_s.tr(INTERNAL_CHARACTERS, "\u{FFFD}")
137
+ result.gsub!(/\{\{\s*!\s*\}\}/, LITERAL_PIPE)
138
+ result.gsub!(/\{\{\s*=\s*\}\}/, LITERAL_EQUALS)
125
139
 
126
140
  # Early exit: Skip expensive processing if no templates present
127
141
  has_templates = result.include?("{{")
@@ -132,7 +146,8 @@ module Wp2txt
132
146
  magic_expander = MagicWordExpander.new(
133
147
  config[:title],
134
148
  namespace: config[:namespace] || "",
135
- dump_date: config[:dump_date]
149
+ dump_date: config[:dump_date],
150
+ literal_equals: LITERAL_EQUALS
136
151
  )
137
152
  result = magic_expander.expand(result)
138
153
  end
@@ -141,7 +156,8 @@ module Wp2txt
141
156
  # This evaluates {{#if:...}}, {{#switch:...}}, {{#expr:...}}, etc.
142
157
  if config[:expand_templates] && has_templates && result.include?("{{#")
143
158
  parser_functions = ParserFunctions.new(
144
- reference_date: config[:dump_date]
159
+ reference_date: config[:dump_date],
160
+ literal_equals: LITERAL_EQUALS
145
161
  )
146
162
  result = parser_functions.evaluate(result)
147
163
  end
@@ -149,8 +165,13 @@ module Wp2txt
149
165
  # Expand common templates if enabled and text still contains templates
150
166
  # This converts {{birth date|...}}, {{convert|...}}, etc. to readable text
151
167
  if config[:expand_templates] && result.include?("{{")
168
+ # Templates it does not know are left for the cleaner, which removes
169
+ # those removed by rule and keeps what the others were given to show
152
170
  template_expander = TemplateExpander.new(
153
- reference_date: config[:dump_date]
171
+ reference_date: config[:dump_date],
172
+ lang: config[:lang],
173
+ preserve_unknown: true,
174
+ literal_equals: LITERAL_EQUALS
154
175
  )
155
176
  result = template_expander.expand(result)
156
177
  end
@@ -158,12 +179,15 @@ module Wp2txt
158
179
  # CPU-intensive regex processing (can be parallelized with Ractor)
159
180
  result = format_wiki_regex_transform(result, config)
160
181
 
182
+ # A character reference to a placeholder is not one either
183
+ result.gsub!(INTERNAL_CHARACTER_REFERENCE, "\u{FFFD}")
161
184
  # Decode HTML entities (e.g., Ø → Ø)
162
185
  # This uses HTMLEntities gem - must be done outside Ractor
163
186
  result = special_chr(result)
164
187
 
165
188
  # Convert marker placeholders to final [MARKER] format
166
189
  result = finalize_markers(result)
190
+ result.tr!(LITERAL_PIPE + LITERAL_EQUALS, "|=")
167
191
  result
168
192
  end
169
193
 
@@ -426,6 +450,12 @@ module Wp2txt
426
450
  REF_OPEN_PLACEHOLDER = "«REFOPEN»"
427
451
  REF_CLOSE_PLACEHOLDER = "«REFCLOSE»"
428
452
 
453
+ # A single bracket is a link only when it opens with a URL; any other is
454
+ # shown as written ("[sic]", "[англ.]"), held as these until the scan ends
455
+ LITERAL_BRACKETS = "\u{FDD4}\u{FDD5}"
456
+ URL_START = %r{\A(?:(?:https?|ftps?|sftp|git|ircs?|nntp|svn|ssh|telnet|gopher|mms|redis|worldwind|wikipedia)://|//|
457
+ (?:mailto|news|tel|sips?|sms|urn|geo|magnet|xmpp|bitcoin|matrix):)}xi.freeze
458
+
429
459
  def process_external_links(str)
430
460
  # Early exit if no external links present
431
461
  return str unless str.include?("[")
@@ -434,7 +464,9 @@ module Wp2txt
434
464
  .gsub("[/ref]", REF_CLOSE_PLACEHOLDER)
435
465
 
436
466
  processed = process_nested_single_pass(protected_str, "[", "]") do |contents|
437
- if /\A\s.+\s\z/ =~ contents
467
+ if !contents.strip.match?(URL_START)
468
+ "#{LITERAL_BRACKETS[0]}#{contents}#{LITERAL_BRACKETS[1]}"
469
+ elsif /\A\s.+\s\z/ =~ contents
438
470
  " (#{contents.strip}) "
439
471
  else
440
472
  parts = contents.split(" ", 2)
@@ -449,6 +481,7 @@ module Wp2txt
449
481
 
450
482
  processed.gsub(REF_OPEN_PLACEHOLDER, "[ref]")
451
483
  .gsub(REF_CLOSE_PLACEHOLDER, "[/ref]")
484
+ .tr(LITERAL_BRACKETS, "[]")
452
485
  end
453
486
 
454
487
  #################### template processing ####################
@@ -584,142 +617,144 @@ module Wp2txt
584
617
  # Early exit if no templates present
585
618
  return str unless str.include?("{{")
586
619
 
620
+ # What a template shows is text: an "=" in it does not name an argument
621
+ # of a template around it
587
622
  process_nested_single_pass(str, "{{", "}}") do |contents|
588
- parts = WikitextRegions.split_pipes(contents)
589
- template_name = (parts[0] || "").strip
590
- template_name_lower = template_name.downcase
591
-
592
- # =========================================================================
593
- # Specific template handlers (order matters - check before generic patterns)
594
- # =========================================================================
595
-
596
- # {{IPA|...}} or {{IPA-xx|...}} or {{IPAc-xx|...}}
597
- # Must be checked BEFORE mixed_script_templates which also contains IPA
598
- if template_name_lower == "ipa" || template_name_lower.start_with?("ipa-") || template_name_lower.start_with?("ipac-")
599
- if enabled_markers.include?(:ipa)
600
- marker_placeholder(:ipa)
601
- else
602
- (parts[1] || "").to_s.strip
603
- end
604
- # Language templates: {{lang|code|text}} or {{lang-xx|text}}
605
- # Must be checked BEFORE mixed_script_templates which also contains lang
606
- elsif template_name_lower == "lang"
607
- parts.size >= 3 ? parts[2].to_s.strip : (parts[1] || "").to_s.strip
608
- elsif template_name_lower.start_with?("lang-")
623
+ TemplateArgs.literal_equals(inline_template_text(contents, enabled_markers, extract_citations), LITERAL_EQUALS)
624
+ end
625
+ end
626
+
627
+ def inline_template_text(contents, enabled_markers, extract_citations)
628
+ parts = WikitextRegions.split_pipes(contents)
629
+ template_name = (parts[0] || "").strip
630
+ template_name_lower = template_name.downcase
631
+
632
+ # =========================================================================
633
+ # Specific template handlers (order matters - check before generic patterns)
634
+ # =========================================================================
635
+
636
+ # {{IPA|...}} or {{IPA-xx|...}} or {{IPAc-xx|...}}
637
+ # Must be checked BEFORE mixed_script_templates which also contains IPA
638
+ if template_name_lower == "ipa" || template_name_lower.start_with?("ipa-") || template_name_lower.start_with?("ipac-")
639
+ if enabled_markers.include?(:ipa)
640
+ marker_placeholder(:ipa)
641
+ else
609
642
  (parts[1] || "").to_s.strip
610
- elsif template_name_lower == "fontsize"
611
- parts.size >= 3 ? parts[2].to_s.strip : (parts[1] || "").to_s.strip
612
- # {{langwithname|code|name|text}} - extract the text (3rd param)
613
- elsif template_name_lower == "langwithname"
614
- parts.size >= 4 ? parts[3].to_s.strip : (parts.last || "").to_s.strip
615
- # {{math|...}} or {{mvar|...}} - mathematical notation
616
- elsif template_name_lower == "math" || template_name_lower == "mvar"
617
- if enabled_markers.include?(:math)
618
- marker_placeholder(:math)
619
- else
620
- (parts[1] || "").to_s.strip
621
- end
622
- # {{chem|...}} or {{ce|...}} - chemical formulas
623
- elsif template_name_lower == "chem" || template_name_lower == "ce"
624
- if enabled_markers.include?(:chem)
625
- marker_placeholder(:chem)
626
- else
627
- (parts[1] || "").to_s.strip
628
- end
643
+ end
644
+ # Language templates: {{lang|code|text}} or {{lang-xx|text}}
645
+ # Must be checked BEFORE mixed_script_templates which also contains lang
646
+ elsif template_name_lower == "lang"
647
+ parts.size >= 3 ? parts[2].to_s.strip : (parts[1] || "").to_s.strip
648
+ elsif template_name_lower.start_with?("lang-")
649
+ (parts[1] || "").to_s.strip
650
+ elsif template_name_lower == "fontsize"
651
+ parts.size >= 3 ? parts[2].to_s.strip : (parts[1] || "").to_s.strip
652
+ # {{langwithname|code|name|text}} - extract the text (3rd param)
653
+ elsif template_name_lower == "langwithname"
654
+ parts.size >= 4 ? parts[3].to_s.strip : (parts.last || "").to_s.strip
655
+ # {{math|...}} or {{mvar|...}} - mathematical notation
656
+ elsif template_name_lower == "math" || template_name_lower == "mvar"
657
+ if enabled_markers.include?(:math)
658
+ marker_placeholder(:math)
659
+ else
660
+ (parts[1] || "").to_s.strip
661
+ end
662
+ # {{chem|...}} or {{ce|...}} - chemical formulas
663
+ elsif template_name_lower == "chem" || template_name_lower == "ce"
664
+ if enabled_markers.include?(:chem)
665
+ marker_placeholder(:chem)
666
+ else
667
+ (parts[1] || "").to_s.strip
668
+ end
629
669
 
630
- # =========================================================================
631
- # Data-driven template matching (generic patterns from template_aliases.json)
632
- # =========================================================================
670
+ # =========================================================================
671
+ # Data-driven template matching (generic patterns from template_aliases.json)
672
+ # =========================================================================
633
673
 
634
- # Handle citation templates
635
- elsif CITATION_TEMPLATE_REGEX.match?(contents)
636
- if extract_citations
637
- format_citation(contents)
638
- else
639
- ""
640
- end
641
- # Remove navigation/reference templates entirely
642
- elsif REMOVE_TEMPLATES_REGEX.match?(contents)
643
- ""
644
- # Remove flag templates (data-driven)
645
- elsif FLAG_TEMPLATE_REGEX.match?(contents) || COUNTRY_CODE_REGEX.match?(template_name)
674
+ # Handle citation templates
675
+ elsif CITATION_TEMPLATE_REGEX.match?(contents)
676
+ if extract_citations
677
+ format_citation(contents)
678
+ else
646
679
  ""
647
- # Ruby text templates: 読み仮名, ruby, etc. (data-driven)
648
- elsif template_matches?(template_name, RUBY_TEXT_TEMPLATES)
680
+ end
681
+ # Remove navigation/reference templates entirely
682
+ elsif REMOVE_TEMPLATES_REGEX.match?(contents)
683
+ ""
684
+ # Remove flag templates (data-driven)
685
+ elsif FLAG_TEMPLATE_REGEX.match?(contents) || COUNTRY_CODE_REGEX.match?(template_name)
686
+ ""
687
+ # Ruby text templates: 読み仮名, ruby, etc. (data-driven)
688
+ elsif template_matches?(template_name, RUBY_TEXT_TEMPLATES)
689
+ text = (parts[1] || "").strip
690
+ reading = (parts[2] || "").strip
691
+ reading.empty? ? text : "#{text}(#{reading})"
692
+ # Interwiki link templates: 仮リンク, ill, interlanguage link (data-driven)
693
+ elsif template_matches?(template_name, INTERWIKI_LINK_TEMPLATES)
694
+ # First parameter is display text
695
+ (parts[1] || "").to_s.strip
696
+ # Mixed script templates: nihongo, transl, etc. (data-driven)
697
+ elsif template_matches?(template_name, MIXED_SCRIPT_TEMPLATES)
698
+ # Format depends on template type
699
+ if template_name_lower == "nihongo" || template_name_lower.start_with?("nihongo")
649
700
  text = (parts[1] || "").strip
650
- reading = (parts[2] || "").strip
651
- reading.empty? ? text : "#{text}(#{reading})"
652
- # Interwiki link templates: 仮リンク, ill, interlanguage link (data-driven)
653
- elsif template_matches?(template_name, INTERWIKI_LINK_TEMPLATES)
654
- # First parameter is display text
655
- (parts[1] || "").to_s.strip
656
- # Mixed script templates: nihongo, transl, etc. (data-driven)
657
- elsif template_matches?(template_name, MIXED_SCRIPT_TEMPLATES)
658
- # Format depends on template type
659
- if template_name_lower == "nihongo" || template_name_lower.start_with?("nihongo")
660
- text = (parts[1] || "").strip
661
- kanji = (parts[2] || "").strip
662
- romaji = (parts[3] || "").strip
663
- if kanji.empty? && romaji.empty?
664
- text
665
- elsif romaji.empty?
666
- "#{text} (#{kanji})"
667
- elsif kanji.empty?
668
- "#{text} (#{romaji})"
669
- else
670
- "#{text} (#{kanji}, #{romaji})"
671
- end
672
- elsif template_name_lower == "transl" || template_name_lower == "transliteration"
673
- # {{transl|lang|text}} -> text
674
- (parts[2] || parts[1] || "").to_s.strip
701
+ kanji = (parts[2] || "").strip
702
+ romaji = (parts[3] || "").strip
703
+ if kanji.empty? && romaji.empty?
704
+ text
705
+ elsif romaji.empty?
706
+ "#{text} (#{kanji})"
707
+ elsif kanji.empty?
708
+ "#{text} (#{romaji})"
675
709
  else
676
- # Default: extract first content parameter
677
- (parts[1] || "").to_s.strip
710
+ "#{text} (#{kanji}, #{romaji})"
678
711
  end
679
- # Convert templates (data-driven)
680
- elsif template_matches?(template_name, CONVERT_TEMPLATES)
681
- num = (parts[1] || "").strip
682
- unit = (parts[2] || "").strip
683
- unit.empty? ? num : "#{num} #{unit}"
684
- # Formatting templates: small, nowrap, nbsp, etc. (data-driven)
685
- elsif FORMATTING_TEMPLATE_REGEX.match?(contents)
686
- if template_name_lower == "nbsp"
687
- " " # Non-breaking space
688
- else
689
- # Extract content from formatting template
690
- (parts[1] || "").to_s.strip
691
- end
692
- # Default handling for other templates
712
+ elsif template_name_lower == "transl" || template_name_lower == "transliteration"
713
+ # {{transl|lang|text}} -> text
714
+ (parts[2] || parts[1] || "").to_s.strip
715
+ else
716
+ # Default: extract first content parameter
717
+ (parts[1] || "").to_s.strip
718
+ end
719
+ # Convert templates (data-driven)
720
+ elsif template_matches?(template_name, CONVERT_TEMPLATES)
721
+ num = (parts[1] || "").strip
722
+ unit = (parts[2] || "").strip
723
+ unit.empty? ? num : "#{num} #{unit}"
724
+ # Formatting templates: small, nowrap, nbsp, etc. (data-driven)
725
+ elsif FORMATTING_TEMPLATE_REGEX.match?(contents)
726
+ if template_name_lower == "nbsp"
727
+ " " # Non-breaking space
693
728
  else
694
- extract_template_content(parts)
729
+ # Extract content from formatting template
730
+ (parts[1] || "").to_s.strip
695
731
  end
732
+ # Default handling for other templates
733
+ else
734
+ extract_template_content(parts)
696
735
  end
697
736
  end
698
737
 
699
- # Extract meaningful content from template parts
738
+ # The text an unknown template was given to show: its first unnamed
739
+ # argument, passing over a language code when another follows it. Named
740
+ # arguments are settings, and a template given nothing shows nothing of the
741
+ # article's
700
742
  def extract_template_content(parts)
701
- return "" if parts.empty?
702
- return parts[0].to_s.strip if parts.size == 1
703
-
704
- # Skip the template name, try to find non-parameter content
705
- parts[1..].each do |part|
706
- next if part.nil?
707
- # Skip if it looks like a parameter (contains =)
708
- next if part.include?("=")
709
- content = part.strip
710
- return content unless content.empty?
711
- end
743
+ candidates = TemplateArgs.parse(parts[1..].to_a).positional.map { |arg| arg.to_s.strip }.reject(&:empty?)
744
+ candidates.shift if candidates.size > 1 && language_code?(candidates.first)
745
+ candidates.first || ""
746
+ end
712
747
 
713
- # If all parts have =, try to extract value from first parameter
714
- parts[1..].each do |part|
715
- next if part.nil?
716
- if part.include?("=")
717
- key, value = part.split("=", 2)
718
- return value.to_s.strip unless value.nil? || value.strip.empty?
719
- end
720
- end
748
+ # A code of a Wikipedia edition's language, alone or with a subtag ("zh-hant")
749
+ def language_code?(arg)
750
+ LANGUAGE_CODES.key?(arg) || (arg.match?(LANGUAGE_CODE_ARG) && LANGUAGE_CODES.key?(arg.split("-").first))
751
+ end
721
752
 
722
- ""
753
+ LANGUAGE_CODE_ARG = /\A[a-z]{2,3}(?:-[a-z]{2,4})?\z/
754
+ LANGUAGE_CODES = begin
755
+ path = File.join(__dir__, "data", "language_metadata.json")
756
+ codes = File.exist?(path) ? JSON.parse(File.read(path))["languages"].keys : []
757
+ codes.to_h { |code| [code, true] }
723
758
  end
724
759
 
725
760
  # =========================================================================
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Wp2txt
4
- VERSION = "2.4.0"
4
+ VERSION = "2.5.0"
5
5
  end
@@ -164,15 +164,18 @@ RSpec.describe "Wp2txt Auto Download" do
164
164
  end
165
165
 
166
166
  describe "#clear_cache!" do
167
- it "removes language-specific cache directory" do
167
+ it "removes everything cached for the language and nothing for others" do
168
168
  manager = Wp2txt::DumpManager.new(:ja, cache_dir: cache_dir)
169
- lang_dir = File.join(cache_dir, "jawiki")
170
- FileUtils.mkdir_p(lang_dir)
171
- File.write(File.join(lang_dir, "test.txt"), "test")
169
+ mine = %w[jawiki-20260101-multistream-index.txt.bz2 jawiki-20260101-multistream.xml.bz2
170
+ jawiki-20260101-multistream-18streams.xml.bz2 jawiki-checked.json]
171
+ mine.each { |name| File.write(File.join(cache_dir, name), "x") }
172
+ snapshot_dir = File.join(cache_dir, "jawiki-20260101-0123456789ab", "streams")
173
+ FileUtils.mkdir_p(snapshot_dir)
174
+ others = %w[enwiki-20260101-multistream-index.txt.bz2 jawiktionary-20260101-pages.xml.bz2]
175
+ others.each { |name| File.write(File.join(cache_dir, name), "x") }
172
176
 
173
- expect(File.exist?(lang_dir)).to be true
174
177
  manager.clear_cache!
175
- expect(File.exist?(lang_dir)).to be false
178
+ expect(Dir.children(cache_dir)).to match_array(others)
176
179
  end
177
180
  end
178
181