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
data/bin/wp2txt CHANGED
@@ -15,6 +15,7 @@ require_relative "../lib/wp2txt/formatter"
15
15
  require_relative "../lib/wp2txt/extractor"
16
16
  require_relative "../lib/wp2txt/ractor_worker"
17
17
  require_relative "../lib/wp2txt/index_commands"
18
+ require_relative "../lib/wp2txt/lead_terms"
18
19
 
19
20
  require "etc"
20
21
  require "json"
@@ -55,6 +56,40 @@ class WpApp
55
56
  used
56
57
  end
57
58
 
59
+ # Attach source identifiers and, when asked, lead terms to an article.
60
+ # raw_wikitext is the article as stored in the dump (XML-decoded, before
61
+ # comment removal): lead-term positions are offsets into exactly that text.
62
+ def set_source_fields(article, page_id, revision_id, raw_wikitext, config)
63
+ article.page_id = page_id
64
+ article.revision_id = revision_id
65
+ if config[:page_properties]
66
+ article.page_properties = Wp2txt::MetadataIndex.property_values(config[:page_properties][page_id])
67
+ end
68
+ return unless config[:lead_terms] && raw_wikitext
69
+
70
+ article.lead_terms = Wp2txt::LeadTerms.extract(raw_wikitext, render: ->(fragment) { format_wiki(fragment, config) })
71
+ end
72
+
73
+ # Page properties from the metadata index of this dump, when imported
74
+ # (wp2txt --import-page-props); nil otherwise
75
+ def load_page_properties(input_path, cache_dir)
76
+ db_path = Wp2txt::MetadataIndex.path_for(File.expand_path(input_path), cache_dir: cache_dir)
77
+ return nil unless File.exist?(db_path)
78
+
79
+ db = SQLite3::Database.new(db_path, readonly: true)
80
+ return nil unless Wp2txt::MetadataIndex.page_properties_imported?(db)
81
+
82
+ rows = {}
83
+ db.execute("SELECT page_id, qid, sort_key, disambiguation FROM page_properties") do |id, qid, key, flag|
84
+ rows[id] = [qid, key, flag]
85
+ end
86
+ rows
87
+ rescue SQLite3::Exception
88
+ nil
89
+ ensure
90
+ db&.close
91
+ end
92
+
58
93
  # Process articles using turbo mode (split-first architecture from v1.x)
59
94
  # This splits the bz2 file into XML chunks first, then processes in parallel
60
95
  # Much faster for large dumps due to parallel decompression benefit
@@ -232,6 +267,8 @@ class WpApp
232
267
  text = page_xml[text_start...text_end_match.begin(0)]
233
268
  next if text.nil? || text.empty?
234
269
 
270
+ raw_wikitext = Wp2txt.xml_decode(text) if config[:lead_terms]
271
+
235
272
  # Decode XML entities
236
273
  text = text.gsub("&lt;", "<").gsub("&gt;", ">").gsub("&amp;", "&").gsub("&quot;", '"')
237
274
 
@@ -245,8 +282,7 @@ class WpApp
245
282
 
246
283
  article = Article.new(text, title, strip_tmarker)
247
284
  ids = Wp2txt.page_ids(page_xml)
248
- article.page_id = ids[:page_id]
249
- article.revision_id = ids[:revision_id]
285
+ set_source_fields(article, ids[:page_id], ids[:revision_id], raw_wikitext, config)
250
286
  result = format_article(article, config)
251
287
  next unless result
252
288
 
@@ -290,7 +326,7 @@ class WpApp
290
326
  base_name = base_name.sub(/\.xml$/, "") # Handle .xml.bz2
291
327
 
292
328
  # Create stream processor
293
- stream = StreamProcessor.new(input_path, bz2_gem: bz2_gem)
329
+ stream = StreamProcessor.new(input_path, bz2_gem: bz2_gem, keep_raw_text: config[:lead_terms])
294
330
 
295
331
  # Create output writer
296
332
  writer = OutputWriter.new(
@@ -444,11 +480,12 @@ class WpApp
444
480
  # Process a batch of pages in parallel
445
481
  # Uses Ractor for true parallelism when enabled, otherwise falls back to Parallel gem
446
482
  def process_batch(pages, writer, config, strip_tmarker, num_processes)
447
- results = if config[:use_ractor] && Wp2txt::RactorWorker.available?
483
+ use_ractor = config[:use_ractor] && Wp2txt::RactorWorker.available?
484
+ results = if use_ractor
448
485
  # Use Ractor-based parallel processing (true parallelism)
449
486
  Wp2txt::RactorWorker.process_articles(
450
487
  pages,
451
- config: config,
488
+ config: config.reject { |key, _| key == :page_properties },
452
489
  strip_tmarker: strip_tmarker,
453
490
  num_workers: num_processes
454
491
  )
@@ -459,13 +496,22 @@ class WpApp
459
496
  writer.flush
460
497
  Parallel.map(pages, in_processes: num_processes) do |title, text, ids|
461
498
  article = Article.new(text, title, strip_tmarker)
462
- article.page_id = ids&.dig(:page_id)
463
- article.revision_id = ids&.dig(:revision_id)
499
+ set_source_fields(article, ids&.dig(:page_id), ids&.dig(:revision_id), ids&.dig(:raw_text), config)
464
500
  format_article(article, config)
465
501
  end
466
502
  end
467
503
 
468
- results.each do |result|
504
+ results.each_with_index do |result, index|
505
+ # Keep the bulk properties table in the parent, outside Ractor's
506
+ # shareable config. Results retain the order of the input pages.
507
+ if use_ractor && result.is_a?(Hash) && config[:page_properties]
508
+ id = pages[index][2]&.dig(:page_id)
509
+ properties = Wp2txt::MetadataIndex.property_values(config[:page_properties][id]).transform_keys(&:to_s)
510
+ result = result.each_with_object({}) do |(key, value), row|
511
+ row[key] = value
512
+ row.merge!(properties) if key == "title"
513
+ end
514
+ end
469
515
  writer.write(result) if result
470
516
  end
471
517
  end
@@ -724,6 +770,8 @@ class WpApp
724
770
  return run_search(opts) if opts[:search]
725
771
  return run_fts_optimize(opts) if opts[:fts_optimize]
726
772
  return run_import_langlinks(opts) if opts[:import_langlinks]
773
+ return run_import_page_props(opts) if opts[:import_page_props]
774
+ return run_count_links(opts) if opts[:count_links]
727
775
 
728
776
  # Determine input source
729
777
  if opts[:from_category] && opts[:lang]
@@ -731,13 +779,13 @@ class WpApp
731
779
  return extract_category_articles(opts)
732
780
  end
733
781
 
734
- if opts[:articles] && opts[:lang]
782
+ if (opts[:articles] || opts[:articles_file]) && opts[:lang]
735
783
  # Article extraction mode
736
784
  return extract_specific_articles(opts)
737
785
  end
738
786
 
739
787
  input_path = if opts[:lang]
740
- download_dump(opts[:lang], opts[:cache_dir])
788
+ download_dump(opts[:lang], opts[:cache_dir], dump_date: opts[:dump_date], update: opts[:update_cache])
741
789
  else
742
790
  opts[:input]
743
791
  end
@@ -763,7 +811,7 @@ class WpApp
763
811
  no_turbo: opts[:no_turbo]
764
812
  }
765
813
 
766
- %i[title list heading table pre ref redirect multiline category category_only
814
+ %i[lead_terms title list heading table pre ref redirect multiline category category_only
767
815
  summary_only metadata_only marker extract_citations expand_templates
768
816
  section_output min_section_length skip_empty
769
817
  alias_file no_section_aliases section_stats show_matched_sections].each do |opt|
@@ -778,6 +826,19 @@ class WpApp
778
826
  # Parse markers option
779
827
  config[:markers] = parse_markers_option(opts[:markers])
780
828
 
829
+ # Templates are read as the dump's wiki reads them, and count dates from
830
+ # the dump's date (from --lang, or a Wikimedia dump file's name)
831
+ lang, date = Wp2txt::DumpSnapshot.name_info(input_path)
832
+ config[:lang] = opts[:lang] || lang
833
+ config[:dump_date] = Wp2txt::DumpSnapshot.time_of(date)
834
+ if config[:expand_templates] && config[:dump_date].nil?
835
+ print_warning("The dump's date is not in the input file's name; templates that count from today (ages) use the day of this run.")
836
+ end
837
+
838
+ # Imported page properties ride along in JSON output;
839
+ # loaded here, before any worker is forked, so workers share the table
840
+ config[:page_properties] = load_page_properties(input_path, opts[:cache_dir]) if format == :json
841
+
781
842
  # Handle section-stats mode (standalone, outputs to stdout)
782
843
  if opts[:section_stats]
783
844
  return process_section_stats(input_path, config)
@@ -863,14 +924,13 @@ class WpApp
863
924
  puts
864
925
  puts pastel.dim("Available settings:")
865
926
  print_list_item("cache.dump_expiry_days - Days before dump cache expires (default: 30)")
866
- print_list_item("cache.category_expiry_days - Days before category cache expires (default: 7)")
867
927
  print_list_item("cache.directory - Cache directory location")
868
928
  print_list_item("defaults.format - Default output format (text/json)")
869
929
  print_list_item("defaults.depth - Default subcategory recursion depth")
870
930
  end
871
931
 
872
932
  # Download dump for a language
873
- def download_dump(lang, cache_dir)
933
+ def download_dump(lang, cache_dir, dump_date: nil, update: false)
874
934
  app_config = Wp2txt::CLI.config
875
935
 
876
936
  print_mode_banner("Auto-Download", {
@@ -881,7 +941,9 @@ class WpApp
881
941
  manager = Wp2txt::DumpManager.new(
882
942
  lang,
883
943
  cache_dir: cache_dir,
884
- dump_expiry_days: app_config.dump_expiry_days
944
+ dump_expiry_days: app_config.dump_expiry_days,
945
+ dump_date: dump_date,
946
+ update: update
885
947
  )
886
948
 
887
949
  # Check for latest dump
@@ -911,5 +973,12 @@ Signal.trap("INT") do
911
973
  end
912
974
 
913
975
  # Create new instance and run with proper exit code
914
- exit_code = WpApp.new.run
976
+ app = WpApp.new
977
+ exit_code = begin
978
+ app.run
979
+ rescue Wp2txt::NetworkError, Wp2txt::SnapshotError => e
980
+ # The dump version could not be chosen or a file of it could not be fetched
981
+ app.print_error(e.message)
982
+ Wp2txt::CliUI::EXIT_ERROR
983
+ end
915
984
  exit(exit_code || Wp2txt::CliUI::EXIT_SUCCESS)
data/bin/wp2txt-mcp CHANGED
@@ -80,7 +80,7 @@ end
80
80
 
81
81
  server.define_tool(
82
82
  name: "dump_info",
83
- description: "Dump identity (language/date), available index tiers, and article/category/section counts. Call first to learn what this corpus contains.",
83
+ description: "Dump identity (language/date), available index tiers, and article/category/section counts, plus provenance and counts for imported page properties (Wikidata IDs, disambiguation flags, sort keys), interlanguage links, and incoming-link counts. Call first to learn what this corpus contains.",
84
84
  input_schema: { properties: {}, required: [] }
85
85
  ) do |server_context:|
86
86
  respond { corpus.dump_info }
data/docs/INDEXES.md CHANGED
@@ -71,6 +71,66 @@ $ wp2txt --import-langlinks -L ja --langlinks-langs en,de,fr,zh,ko
71
71
  This adds a `langlinks` table (`ll_from` = source page_id, `ll_lang`, `ll_title`) that can
72
72
  be joined in SQL. Tip: filter `ll_title != ''` — real dumps contain a few empty-title rows.
73
73
 
74
+ ### Page properties and incoming links
75
+
76
+ Two more signals can be added to an existing metadata index, each with one command:
77
+
78
+ ```console
79
+ $ wp2txt --import-page-props -L ja # each article's Wikidata item ID
80
+ $ wp2txt --count-links -L ja # how many articles link to each article
81
+ ```
82
+
83
+ - `--import-page-props` reads the official `page_props` dump of the **same date** as the
84
+ index (a mismatch is refused) and creates `page_properties` with columns `page_id`
85
+ (integer primary key), `qid` (nullable text), `disambiguation` (integer, default 0,
86
+ not null), and `sort_key` (nullable text). A row exists only for a page with at least
87
+ one of these properties.
88
+ The source file's name, size, SHA-256, import time, page count, each property's count,
89
+ and the count of invalid UTF-8 sort keys skipped are reported under
90
+ `dump_info.page_properties`. Once imported, JSON records always carry `qid`,
91
+ `sort_key`, and `disambiguation`, including null/false values for absent properties.
92
+ Before import, all three are omitted. `get_article` and `extract_corpus` use the
93
+ same rule. The three imported properties are `wikibase_item`, `defaultsort`, and
94
+ `disambiguation`; unrelated properties are ignored.
95
+ MediaWiki's disambiguation flag is more reliable than matching the page title.
96
+ Sort keys are language-specific: Japanese Wikipedia commonly removes voicing marks
97
+ and enlarges small kana (言語 → けんこ), while English may use "surname, given name".
98
+ A sort key is not a reading itself, but can help compare reading candidates.
99
+ - `--count-links` scans the dump and adds `page_inlinks` (`page_id`, `inlinks`,
100
+ `via_redirects`) for every article. Each linking article counts **once** per target,
101
+ however many times it links; a link to a redirect counts for the redirect's target
102
+ (`via_redirects` is how many articles reached it only that way). Only links written in
103
+ articles' own text count — links that navigation templates add when a page is rendered
104
+ are not in the dump, so they are not counted. Links inside comments or literal
105
+ regions (`nowiki`, `pre`, `math`, `chem`, `ce`, `score`, `syntaxhighlight`, `source`,
106
+ `graph`, `mapframe`, `templatedata`) and links from redirects or other namespaces
107
+ do not count. Links inside `gallery`, `timeline`, and ordinary formatting tags
108
+ such as `code` do count. Lead-term extraction separately excludes `gallery` and
109
+ `timeline` because their contents are not lead prose.
110
+ Japanese Wikipedia takes about 12 minutes on
111
+ an Apple Silicon laptop.
112
+ Counting rule version 2 decodes title entities and respects the dump's siteinfo case
113
+ rule, recorded as `case_rule` in metadata when the index is built. Existing indexes
114
+ without this value use `first-letter`; rebuild the metadata index before counting
115
+ links for a case-sensitive wiki. Re-run `--count-links` to replace counts from rule 1.
116
+
117
+ Together with langlinks these let a query select articles by how referenced they are
118
+ within an edition, how many editions cover them, and what Wikidata says they are:
119
+
120
+ ```sql
121
+ SELECT p.title, i.inlinks, q.qid, q.sort_key, q.disambiguation,
122
+ (SELECT COUNT(DISTINCT ll_lang) FROM langlinks l WHERE l.ll_from = p.page_id) AS editions
123
+ FROM pages p
124
+ JOIN page_inlinks i USING (page_id)
125
+ LEFT JOIN page_properties q USING (page_id)
126
+ WHERE p.namespace = 0 AND p.redirect_to IS NULL AND i.inlinks >= 5
127
+ ORDER BY i.inlinks DESC
128
+ ```
129
+
130
+ Link counts measure how much an edition refers to a topic, not whether it is a proper
131
+ noun: common nouns ("singer", "high school") rank high too. Use the Wikidata ID to tell
132
+ kinds of entities apart.
133
+
74
134
  ## 4. The MCP server
75
135
 
76
136
  `wp2txt-mcp` exposes a local dump to any MCP-capable LLM client (Claude, ChatGPT, Gemini,
@@ -105,7 +165,7 @@ $ claude mcp add wp2txt -- docker run -i --rm -v wp2txt:/root/.wp2txt ghcr.io/yo
105
165
 
106
166
  | Tool | Purpose |
107
167
  |------|---------|
108
- | `dump_info` | Dump identity, installed indexes, corpus statistics, langlinks provenance |
168
+ | `dump_info` | Dump identity, installed indexes, corpus statistics, provenance of langlinks, Wikidata IDs, and link counts |
109
169
  | `get_article` / `get_sections` / `list_headings` / `get_categories` | Single-article access (redirect-aware) |
110
170
  | `find_articles` | Exhaustive filtered listing (category recursion, category AND / pattern match, section headings, title match) |
111
171
  | `category_tree` / `section_stats` | Scope exploration and heading-frequency discovery |
@@ -26,7 +26,7 @@ module Wp2txt
26
26
  # an article contains elements, each of which is [TYPE, string]
27
27
  class Article
28
28
  include Wp2txt
29
- attr_accessor :elements, :title, :categories, :page_id, :revision_id
29
+ attr_accessor :elements, :title, :categories, :page_id, :revision_id, :page_properties, :lead_terms
30
30
 
31
31
  def initialize(text, title = "", strip_tmarker = false)
32
32
  @title = title.strip
@@ -118,8 +118,7 @@ module Wp2txt
118
118
  @brace_depth = 0
119
119
  source.each_line do |line|
120
120
  # Collect categories without deduplicating on each line (O(n²) → O(n))
121
- matched = line.scan(CATEGORY_REGEX)
122
- @categories.concat(matched) if matched && !matched.empty?
121
+ @categories.concat(Wp2txt.category_names(line))
123
122
 
124
123
  case mode
125
124
  when :mw_ml_template
@@ -0,0 +1,63 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "open3"
4
+ require_relative "constants"
5
+
6
+ module Wp2txt
7
+ # Raised when a multistream range cannot be read in full: the decompressor
8
+ # failed, or the pages it holds are not well-formed XML. Other ranges of the
9
+ # same dump are unaffected.
10
+ class StreamError < Error
11
+ attr_reader :offset
12
+
13
+ def initialize(message, offset: nil)
14
+ super(message)
15
+ @offset = offset
16
+ end
17
+
18
+ # Why the articles of the range were not extracted
19
+ def reason
20
+ :truncated
21
+ end
22
+ end
23
+
24
+ # Decompress one or more concatenated bzip2 streams held in memory.
25
+ # A failing decompressor raises instead of returning the output it produced
26
+ # before the failure, which would be a silently shortened text.
27
+ def self.decompress_bz2(data, offset: nil)
28
+ stdout, stderr, status = Open3.capture3("bzcat", stdin_data: data, binmode: true)
29
+ unless status.success?
30
+ raise StreamError.new("bzip2 data is incomplete or corrupt (exit #{status.exitstatus}): #{stderr.strip}",
31
+ offset: offset)
32
+ end
33
+
34
+ stdout.force_encoding(Encoding::UTF_8)
35
+ end
36
+
37
+ # Read a multistream index, one "offset:page_id:title" line at a time,
38
+ # from a plain or bzip2-compressed file. Leaving the block early (break)
39
+ # is fine; reading to the end through a failing decompressor raises, so a
40
+ # cut-short index is never taken for a complete one.
41
+ # @yield [Integer, Integer, String] offset, page_id, title
42
+ # @raise [StreamError] when the index cannot be read in full
43
+ def self.each_index_line(path)
44
+ return enum_for(:each_index_line, path) unless block_given?
45
+
46
+ read = lambda do |io|
47
+ io.each_line do |line|
48
+ parts = line.chomp.split(":", 3)
49
+ next if parts.size < 3
50
+
51
+ yield parts[0].to_i, parts[1].to_i, parts[2].scrub("\uFFFD")
52
+ end
53
+ end
54
+
55
+ unless path.end_with?(".bz2")
56
+ File.open(path, "r:UTF-8") { |io| read.call(io) }
57
+ return
58
+ end
59
+
60
+ IO.popen(["bzcat", path], "r:UTF-8", err: File::NULL) { |io| read.call(io) }
61
+ raise StreamError, "the index #{File.basename(path)} is incomplete or corrupt" unless $?.success?
62
+ end
63
+ end
data/lib/wp2txt/cli.rb CHANGED
@@ -61,6 +61,10 @@ module Wp2txt
61
61
  type: String, short: "-L"
62
62
  opt :articles, "Specific article titles to extract (comma-separated, requires --lang)",
63
63
  type: String, short: "-A"
64
+ opt :articles_file, "File of article titles to extract, one per line (requires --lang)",
65
+ type: String
66
+ opt :no_follow_redirects, "Extract redirect pages themselves instead of the articles they point to",
67
+ default: false
64
68
  opt :from_category, "Extract articles from Wikipedia category (requires --lang)",
65
69
  type: String, short: "-G"
66
70
  opt :depth, "Subcategory recursion depth for --from-category (0 = no recursion)",
@@ -69,8 +73,12 @@ module Wp2txt
69
73
  default: false, short: "-y"
70
74
  opt :dry_run, "Preview category extraction without downloading",
71
75
  default: false
72
- opt :update_cache, "Force refresh of cached dump files",
76
+ opt :allow_incomplete_category, "Extract what was listed when a category cannot be listed in full",
77
+ default: false
78
+ opt :update_cache, "Check for the newest dump version now instead of using the one checked recently",
73
79
  default: false, short: "-U"
80
+ opt :dump_date, "Use the dump of this date (YYYYMMDD) instead of the newest (requires --lang)",
81
+ type: :string
74
82
 
75
83
  # Output options
76
84
  opt :output_dir, "Path to output directory",
@@ -150,6 +158,16 @@ module Wp2txt
150
158
  opt :langlinks_langs, "Comma-separated target languages to import with --import-langlinks (default: all)",
151
159
  type: String, short: :none
152
160
 
161
+ # Wikidata item IDs and incoming-link counts, added to an existing metadata index
162
+ opt :import_page_props, "Import Wikidata IDs, disambiguation flags, and sort keys (page_props dump) into the metadata index (requires --lang)",
163
+ default: false, short: :none
164
+ opt :page_props_file, "Use a local page_props .sql(.gz) file instead of downloading (with --import-page-props)",
165
+ type: String, short: :none
166
+ opt :count_links, "Count incoming links to each article and store them in the metadata index (requires --lang)",
167
+ default: false, short: :none
168
+ opt :lead_terms, "Add the lead's bold terms, their parenthesized notes, and reading templates to JSON output",
169
+ default: false, short: :none
170
+
153
171
  opt :file_size, "Approximate size (in MB) of each output file (0 for single file)",
154
172
  default: 10, short: "-f"
155
173
  opt :num_procs, "Number of parallel processes (auto-detected based on CPU/memory)",
@@ -217,31 +235,6 @@ module Wp2txt
217
235
  Optimist.die "Cannot specify both --input and --lang"
218
236
  end
219
237
 
220
- # --articles requires --lang
221
- if opts[:articles] && opts[:lang].nil?
222
- Optimist.die "--articles requires --lang"
223
- end
224
-
225
- # --articles cannot be used with --input
226
- if opts[:articles] && opts[:input]
227
- Optimist.die "--articles cannot be used with --input"
228
- end
229
-
230
- # --from-category requires --lang
231
- if opts[:from_category] && opts[:lang].nil?
232
- Optimist.die "--from-category requires --lang"
233
- end
234
-
235
- # --from-category cannot be used with --input
236
- if opts[:from_category] && opts[:input]
237
- Optimist.die "--from-category cannot be used with --input"
238
- end
239
-
240
- # --from-category cannot be used with --articles
241
- if opts[:from_category] && opts[:articles]
242
- Optimist.die "--from-category cannot be used with --articles"
243
- end
244
-
245
238
  # --depth must be >= 0
246
239
  if opts[:depth] < 0
247
240
  Optimist.die :depth, "must be 0 or greater"
@@ -252,6 +245,8 @@ module Wp2txt
252
245
  warn "Warning: --depth > 3 may result in a very large number of articles"
253
246
  end
254
247
 
248
+ validate_targeted_extraction!(opts)
249
+
255
250
  # --dry-run only makes sense with --from-category
256
251
  if opts[:dry_run] && opts[:from_category].nil?
257
252
  Optimist.die "--dry-run requires --from-category"
@@ -267,6 +262,11 @@ module Wp2txt
267
262
  Optimist.die :input, "file does not exist"
268
263
  end
269
264
 
265
+ if opts[:dump_date]
266
+ Optimist.die :dump_date, "must be a date as YYYYMMDD" unless opts[:dump_date].match?(/\A\d{8}\z/)
267
+ Optimist.die "--dump-date requires --lang" unless opts[:lang]
268
+ end
269
+
270
270
  # Validate language code
271
271
  if opts[:lang] && !valid_language_code?(opts[:lang])
272
272
  Optimist.die :lang, "invalid language code format"
@@ -377,6 +377,38 @@ module Wp2txt
377
377
  end
378
378
  end
379
379
 
380
+ # Page-props import and link counting are standalone modes on an existing index
381
+ { import_page_props: "--import-page-props", count_links: "--count-links" }.each do |key, flag|
382
+ next unless opts[key]
383
+
384
+ Optimist.die "#{flag} requires --lang" if opts[:lang].nil?
385
+ others = { build_index: "--build-index", find_articles: "--find-articles", search: "--search",
386
+ fts_optimize: "--fts-optimize", import_langlinks: "--import-langlinks",
387
+ import_page_props: "--import-page-props", count_links: "--count-links",
388
+ articles: "--articles", from_category: "--from-category", section_stats: "--section-stats" }
389
+ conflicts = others.reject { |k, _| k == key }.select { |k, _| opts[k] }.values
390
+ Optimist.die "#{flag} cannot be combined with #{conflicts.join(', ')}" unless conflicts.empty?
391
+ end
392
+
393
+ if opts[:page_props_file] && !opts[:import_page_props]
394
+ Optimist.die "--page-props-file requires --import-page-props"
395
+ end
396
+
397
+ if opts[:page_props_file] && !File.exist?(opts[:page_props_file])
398
+ Optimist.die :page_props_file, "file does not exist"
399
+ end
400
+
401
+ if opts[:lead_terms] && opts[:format].to_s != "json"
402
+ Optimist.die "--lead-terms requires --format json"
403
+ end
404
+
405
+ if opts[:lead_terms] && opts[:ractor]
406
+ Optimist.die "--lead-terms cannot be combined with --ractor"
407
+ end
408
+ if opts[:ractor] && opts[:format].to_s == "json"
409
+ warn "Warning: --ractor JSON output does not include page IDs or revision IDs"
410
+ end
411
+
380
412
  if opts[:langlinks_file] && !opts[:import_langlinks]
381
413
  Optimist.die "--langlinks-file requires --import-langlinks"
382
414
  end
@@ -412,6 +444,38 @@ module Wp2txt
412
444
  articles_str.split(",").map(&:strip).reject(&:empty?)
413
445
  end
414
446
 
447
+ # Options of the targeted extraction modes (--articles, --articles-file,
448
+ # --from-category): which need one of them, and which cannot go with them
449
+ TARGETED_MODES = %i[articles articles_file from_category].freeze
450
+ TARGETED_OPTIONS = %i[no_follow_redirects].freeze
451
+ CATEGORY_OPTIONS = %i[allow_incomplete_category].freeze
452
+ WHOLE_DUMP_OPTIONS = %i[section_stats ractor no_turbo build_index find_articles search fts_optimize
453
+ import_langlinks import_page_props count_links].freeze
454
+
455
+ def validate_targeted_extraction!(opts)
456
+ flag = ->(key) { "--#{key.to_s.tr('_', '-')}" }
457
+ modes = TARGETED_MODES.select { |key| opts[key] }
458
+ Optimist.die "#{modes.map(&flag).join(', ')} cannot be combined" if modes.size > 1
459
+ modes.each do |key|
460
+ Optimist.die "#{flag.(key)} requires --lang" unless opts[:lang]
461
+ Optimist.die "#{flag.(key)} cannot be used with --input" if opts[:input]
462
+ end
463
+ if opts[:articles_file] && !File.file?(opts[:articles_file])
464
+ Optimist.die :articles_file, "file does not exist"
465
+ end
466
+ TARGETED_OPTIONS.each do |key|
467
+ Optimist.die "#{flag.(key)} requires #{TARGETED_MODES.map(&flag).join(', ')}" if opts[key] && modes.empty?
468
+ end
469
+ CATEGORY_OPTIONS.each do |key|
470
+ Optimist.die "#{flag.(key)} requires --from-category" if opts[key] && !opts[:from_category]
471
+ end
472
+ return if modes.empty?
473
+
474
+ WHOLE_DUMP_OPTIONS.each do |key|
475
+ Optimist.die "#{flag.(key)} cannot be used with #{flag.(modes.first)}" if opts[key]
476
+ end
477
+ end
478
+
415
479
  # Check if a language code is valid
416
480
  # Valid codes: 2-10 lowercase letters (e.g., en, ja, simple, zh-yue)
417
481
  def valid_language_code?(code)
data/lib/wp2txt/config.rb CHANGED
@@ -14,31 +14,27 @@ module Wp2txt
14
14
 
15
15
  # Validation ranges
16
16
  DUMP_EXPIRY_RANGE = (1..365)
17
- CATEGORY_EXPIRY_RANGE = (1..90)
18
17
  DEPTH_RANGE = (0..10)
19
18
  VALID_FORMATS = %w[text json].freeze
20
19
 
21
20
  # Default values
22
21
  DEFAULTS = {
23
22
  dump_expiry_days: 30,
24
- category_expiry_days: 7,
25
23
  cache_directory: DEFAULT_CACHE_DIR,
26
24
  default_format: "text",
27
25
  default_depth: 0
28
26
  }.freeze
29
27
 
30
- attr_reader :dump_expiry_days, :category_expiry_days, :cache_directory,
28
+ attr_reader :dump_expiry_days, :cache_directory,
31
29
  :default_format, :default_depth
32
30
 
33
31
  def initialize(
34
32
  dump_expiry_days: DEFAULTS[:dump_expiry_days],
35
- category_expiry_days: DEFAULTS[:category_expiry_days],
36
33
  cache_directory: DEFAULTS[:cache_directory],
37
34
  default_format: DEFAULTS[:default_format],
38
35
  default_depth: DEFAULTS[:default_depth]
39
36
  )
40
37
  @dump_expiry_days = clamp(dump_expiry_days.to_i, DUMP_EXPIRY_RANGE)
41
- @category_expiry_days = clamp(category_expiry_days.to_i, CATEGORY_EXPIRY_RANGE)
42
38
  @cache_directory = cache_directory.to_s.empty? ? DEFAULT_CACHE_DIR : cache_directory.to_s
43
39
  @default_format = validate_format(default_format.to_s)
44
40
  @default_depth = clamp(default_depth.to_i, DEPTH_RANGE)
@@ -68,7 +64,6 @@ module Wp2txt
68
64
 
69
65
  new(
70
66
  dump_expiry_days: cache[:dump_expiry_days] || DEFAULTS[:dump_expiry_days],
71
- category_expiry_days: cache[:category_expiry_days] || DEFAULTS[:category_expiry_days],
72
67
  cache_directory: cache[:directory] || DEFAULTS[:cache_directory],
73
68
  default_format: defaults[:format] || DEFAULTS[:default_format],
74
69
  default_depth: defaults[:depth] || DEFAULTS[:default_depth]
@@ -108,7 +103,6 @@ module Wp2txt
108
103
  {
109
104
  cache: {
110
105
  dump_expiry_days: @dump_expiry_days,
111
- category_expiry_days: @category_expiry_days,
112
106
  directory: @cache_directory
113
107
  },
114
108
  defaults: {
@@ -137,12 +131,9 @@ module Wp2txt
137
131
  # Location: ~/.wp2txt/config.yml
138
132
 
139
133
  cache:
140
- # Number of days before dump files are considered stale (1-365)
134
+ # Days between checks for a newer dump version (1-365)
141
135
  dump_expiry_days: #{@dump_expiry_days}
142
136
 
143
- # Number of days before category cache expires (1-90)
144
- category_expiry_days: #{@category_expiry_days}
145
-
146
137
  # Cache directory for downloaded dumps
147
138
  directory: #{@cache_directory}
148
139
 
@@ -6,6 +6,19 @@ module Wp2txt
6
6
  (value || "0").to_i
7
7
  end
8
8
 
9
+ XML_ENTITIES = { "lt" => "<", "gt" => ">", "amp" => "&", "quot" => '"', "apos" => "'" }.freeze
10
+
11
+ # Decode XML character references in one pass, as an XML parser does
12
+ # (a single pass keeps "&amp;lt;" as the literal text "&lt;")
13
+ def self.xml_decode(str)
14
+ str.gsub(/&(?:(lt|gt|amp|quot|apos)|#(\d+)|#x(\h+));/) do
15
+ if Regexp.last_match(1) then XML_ENTITIES[Regexp.last_match(1)]
16
+ elsif Regexp.last_match(2) then Regexp.last_match(2).to_i.chr(Encoding::UTF_8)
17
+ else Regexp.last_match(3).to_i(16).chr(Encoding::UTF_8)
18
+ end
19
+ end
20
+ end
21
+
9
22
  # Page and revision IDs from one <page> element of a dump. The page's own
10
23
  # <id> precedes <revision>; the revision's <id> is its first child (the
11
24
  # contributor's <id> comes later). Only the header before <text> is read.
@@ -58,7 +71,6 @@ module Wp2txt
58
71
  DEFAULT_DUMP_EXPIRY_DAYS = 30
59
72
 
60
73
  # Default expiry for category member cache
61
- DEFAULT_CATEGORY_CACHE_EXPIRY_DAYS = 7
62
74
 
63
75
  # ---------------------------------------------------------------------------
64
76
  # Network Settings