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
@@ -1,313 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- require "sqlite3"
4
- require "json"
5
- require "fileutils"
6
- require_relative "constants"
7
-
8
- module Wp2txt
9
- # SQLite-based cache for Wikipedia category hierarchy and members
10
- # Dramatically speeds up repeated category extraction operations
11
- class CategoryCache
12
- CACHE_VERSION = 1
13
- DEFAULT_CACHE_DIR = File.expand_path("~/.wp2txt/cache")
14
-
15
- attr_reader :lang, :cache_path, :expiry_days
16
-
17
- def initialize(lang, cache_dir: nil, expiry_days: nil)
18
- @lang = lang.to_s
19
- @cache_dir = cache_dir || DEFAULT_CACHE_DIR
20
- @expiry_days = expiry_days || DEFAULT_CATEGORY_CACHE_EXPIRY_DAYS
21
- @cache_path = File.join(@cache_dir, "categories_#{@lang}.sqlite3")
22
- @db = nil
23
- ensure_schema
24
- end
25
-
26
- # Check if a category is cached and fresh
27
- # @param category_name [String] Category name (without "Category:" prefix)
28
- # @return [Boolean]
29
- def cached?(category_name)
30
- open_db
31
- row = @db.get_first_row(
32
- "SELECT cached_at FROM categories WHERE name = ?",
33
- [normalize_name(category_name)]
34
- )
35
- return false unless row
36
-
37
- cached_at = row[0]
38
- return false unless cached_at
39
-
40
- # Check freshness
41
- Time.at(cached_at) > Time.now - (@expiry_days * SECONDS_PER_DAY)
42
- rescue SQLite3::Exception
43
- false
44
- end
45
-
46
- # Get category data from cache
47
- # @param category_name [String] Category name
48
- # @return [Hash, nil] { pages: [...], subcats: [...] } or nil if not cached
49
- def get(category_name)
50
- return nil unless cached?(category_name)
51
-
52
- name = normalize_name(category_name)
53
- open_db
54
-
55
- pages = []
56
- subcats = []
57
-
58
- # Get pages
59
- @db.execute(
60
- "SELECT page_title FROM category_pages WHERE category_name = ?",
61
- [name]
62
- ) do |row|
63
- pages << row[0]
64
- end
65
-
66
- # Get subcategories
67
- @db.execute(
68
- "SELECT child_name FROM category_hierarchy WHERE parent_name = ?",
69
- [name]
70
- ) do |row|
71
- subcats << row[0]
72
- end
73
-
74
- { pages: pages, subcats: subcats }
75
- rescue SQLite3::Exception
76
- nil
77
- end
78
-
79
- # Save category data to cache
80
- # @param category_name [String] Category name
81
- # @param pages [Array<String>] Article titles in this category
82
- # @param subcats [Array<String>] Subcategory names
83
- def save(category_name, pages, subcats)
84
- name = normalize_name(category_name)
85
- open_db
86
-
87
- @db.execute("BEGIN TRANSACTION")
88
-
89
- # Update or insert category
90
- @db.execute(
91
- "INSERT OR REPLACE INTO categories (name, page_count, subcat_count, cached_at) VALUES (?, ?, ?, ?)",
92
- [name, pages.size, subcats.size, Time.now.to_i]
93
- )
94
-
95
- # Clear old pages and hierarchy
96
- @db.execute("DELETE FROM category_pages WHERE category_name = ?", [name])
97
- @db.execute("DELETE FROM category_hierarchy WHERE parent_name = ?", [name])
98
-
99
- # Insert pages
100
- unless pages.empty?
101
- stmt = @db.prepare("INSERT INTO category_pages (category_name, page_title) VALUES (?, ?)")
102
- pages.each { |page| stmt.execute([name, page]) }
103
- stmt.close
104
- end
105
-
106
- # Insert subcategories
107
- unless subcats.empty?
108
- stmt = @db.prepare("INSERT INTO category_hierarchy (parent_name, child_name) VALUES (?, ?)")
109
- subcats.each { |subcat| stmt.execute([name, normalize_name(subcat)]) }
110
- stmt.close
111
- end
112
-
113
- @db.execute("COMMIT")
114
- rescue SQLite3::Exception => e
115
- @db&.execute("ROLLBACK") rescue nil
116
- warn "CategoryCache: Failed to save #{category_name}: #{e.message}"
117
- end
118
-
119
- # Get all pages in a category tree (recursive)
120
- # @param category_name [String] Root category name
121
- # @param max_depth [Integer] Maximum recursion depth (0 = no recursion)
122
- # @param visited [Set] Already visited categories (for cycle detection)
123
- # @return [Array<String>] All article titles
124
- def get_all_pages(category_name, max_depth: 0, visited: nil)
125
- visited ||= Set.new
126
- name = normalize_name(category_name)
127
- return [] if visited.include?(name)
128
-
129
- visited << name
130
- data = get(name)
131
- return [] unless data
132
-
133
- pages = data[:pages].dup
134
-
135
- if max_depth > 0
136
- data[:subcats].each do |subcat|
137
- pages.concat(get_all_pages(subcat, max_depth: max_depth - 1, visited: visited))
138
- end
139
- end
140
-
141
- pages.uniq
142
- end
143
-
144
- # Get category tree structure
145
- # @param category_name [String] Root category name
146
- # @param max_depth [Integer] Maximum recursion depth
147
- # @return [Hash] Tree structure with category info
148
- def get_tree(category_name, max_depth: 0)
149
- build_tree(category_name, max_depth, Set.new)
150
- end
151
-
152
- # Get statistics for all cached categories
153
- # @return [Hash] Statistics
154
- def stats
155
- open_db
156
-
157
- total_categories = @db.get_first_value("SELECT COUNT(*) FROM categories")
158
- total_pages = @db.get_first_value("SELECT COUNT(*) FROM category_pages")
159
- total_relations = @db.get_first_value("SELECT COUNT(*) FROM category_hierarchy")
160
-
161
- oldest_cache = @db.get_first_value("SELECT MIN(cached_at) FROM categories")
162
- newest_cache = @db.get_first_value("SELECT MAX(cached_at) FROM categories")
163
-
164
- {
165
- lang: @lang,
166
- cache_path: @cache_path,
167
- cache_size: File.exist?(@cache_path) ? File.size(@cache_path) : 0,
168
- total_categories: total_categories || 0,
169
- total_pages: total_pages || 0,
170
- total_relations: total_relations || 0,
171
- oldest_cache: oldest_cache ? Time.at(oldest_cache) : nil,
172
- newest_cache: newest_cache ? Time.at(newest_cache) : nil,
173
- expiry_days: @expiry_days
174
- }
175
- rescue SQLite3::Exception
176
- { lang: @lang, error: "Failed to read stats" }
177
- end
178
-
179
- # Clear all cached data
180
- def clear!
181
- close_db
182
- FileUtils.rm_f(@cache_path)
183
- ensure_schema
184
- end
185
-
186
- # Clear expired entries
187
- def cleanup_expired!
188
- open_db
189
- cutoff = Time.now.to_i - (@expiry_days * SECONDS_PER_DAY)
190
-
191
- @db.execute("BEGIN TRANSACTION")
192
-
193
- # Get expired categories
194
- expired = []
195
- @db.execute("SELECT name FROM categories WHERE cached_at < ?", [cutoff]) do |row|
196
- expired << row[0]
197
- end
198
-
199
- # Delete expired data
200
- expired.each do |name|
201
- @db.execute("DELETE FROM category_pages WHERE category_name = ?", [name])
202
- @db.execute("DELETE FROM category_hierarchy WHERE parent_name = ?", [name])
203
- @db.execute("DELETE FROM categories WHERE name = ?", [name])
204
- end
205
-
206
- @db.execute("COMMIT")
207
-
208
- expired.size
209
- rescue SQLite3::Exception
210
- @db&.execute("ROLLBACK") rescue nil
211
- 0
212
- end
213
-
214
- # Close database connection
215
- def close
216
- close_db
217
- end
218
-
219
- private
220
-
221
- def normalize_name(name)
222
- name.to_s.sub(/^[Cc]ategory:/, "").strip
223
- end
224
-
225
- def build_tree(category_name, max_depth, visited)
226
- name = normalize_name(category_name)
227
- return nil if visited.include?(name)
228
-
229
- visited << name
230
- data = get(name)
231
-
232
- result = {
233
- name: name,
234
- cached: !data.nil?,
235
- page_count: data ? data[:pages].size : 0,
236
- children: []
237
- }
238
-
239
- if data && max_depth > 0
240
- data[:subcats].each do |subcat|
241
- child = build_tree(subcat, max_depth - 1, visited)
242
- result[:children] << child if child
243
- end
244
- end
245
-
246
- result
247
- end
248
-
249
- def open_db
250
- return if @db
251
-
252
- FileUtils.mkdir_p(File.dirname(@cache_path))
253
- @db = SQLite3::Database.new(@cache_path)
254
- @db.execute("PRAGMA journal_mode = WAL")
255
- @db.execute("PRAGMA synchronous = NORMAL")
256
- @db.execute("PRAGMA cache_size = -16000") # 16MB cache
257
- end
258
-
259
- def close_db
260
- @db&.close
261
- @db = nil
262
- end
263
-
264
- def ensure_schema
265
- open_db
266
-
267
- @db.execute(<<~SQL)
268
- CREATE TABLE IF NOT EXISTS categories (
269
- name TEXT PRIMARY KEY,
270
- page_count INTEGER DEFAULT 0,
271
- subcat_count INTEGER DEFAULT 0,
272
- cached_at INTEGER
273
- )
274
- SQL
275
-
276
- @db.execute(<<~SQL)
277
- CREATE TABLE IF NOT EXISTS category_pages (
278
- category_name TEXT NOT NULL,
279
- page_title TEXT NOT NULL,
280
- PRIMARY KEY (category_name, page_title)
281
- )
282
- SQL
283
-
284
- @db.execute("CREATE INDEX IF NOT EXISTS idx_category_pages_category ON category_pages(category_name)")
285
-
286
- @db.execute(<<~SQL)
287
- CREATE TABLE IF NOT EXISTS category_hierarchy (
288
- parent_name TEXT NOT NULL,
289
- child_name TEXT NOT NULL,
290
- PRIMARY KEY (parent_name, child_name)
291
- )
292
- SQL
293
-
294
- @db.execute("CREATE INDEX IF NOT EXISTS idx_hierarchy_parent ON category_hierarchy(parent_name)")
295
- @db.execute("CREATE INDEX IF NOT EXISTS idx_hierarchy_child ON category_hierarchy(child_name)")
296
-
297
- @db.execute(<<~SQL)
298
- CREATE TABLE IF NOT EXISTS metadata (
299
- key TEXT PRIMARY KEY,
300
- value TEXT
301
- )
302
- SQL
303
-
304
- # Store cache version
305
- @db.execute(
306
- "INSERT OR REPLACE INTO metadata (key, value) VALUES ('cache_version', ?)",
307
- [CACHE_VERSION.to_s]
308
- )
309
- rescue SQLite3::Exception => e
310
- warn "CategoryCache: Failed to create schema: #{e.message}"
311
- end
312
- end
313
- end
@@ -1,226 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- require_relative "spec_helper"
4
- require "tmpdir"
5
- require "fileutils"
6
-
7
- RSpec.describe Wp2txt::CategoryCache do
8
- let(:cache_dir) { Dir.mktmpdir("wp2txt_category_cache_test_") }
9
- let(:cache) { described_class.new("en", cache_dir: cache_dir) }
10
-
11
- after do
12
- cache.close
13
- FileUtils.rm_rf(cache_dir)
14
- end
15
-
16
- describe "#initialize" do
17
- it "creates cache file" do
18
- expect(File.exist?(cache.cache_path)).to be true
19
- end
20
-
21
- it "sets language" do
22
- expect(cache.lang).to eq "en"
23
- end
24
-
25
- it "uses default expiry days" do
26
- expect(cache.expiry_days).to eq Wp2txt::DEFAULT_CATEGORY_CACHE_EXPIRY_DAYS
27
- end
28
-
29
- it "accepts custom expiry days" do
30
- custom_cache = described_class.new("ja", cache_dir: cache_dir, expiry_days: 14)
31
- expect(custom_cache.expiry_days).to eq 14
32
- custom_cache.close
33
- end
34
- end
35
-
36
- describe "#save and #get" do
37
- it "saves and retrieves category data" do
38
- pages = ["Article 1", "Article 2", "Article 3"]
39
- subcats = ["Subcategory A", "Subcategory B"]
40
-
41
- cache.save("Test Category", pages, subcats)
42
- data = cache.get("Test Category")
43
-
44
- expect(data[:pages]).to eq pages
45
- expect(data[:subcats]).to eq subcats
46
- end
47
-
48
- it "handles empty pages" do
49
- cache.save("Empty Pages", [], ["Subcat"])
50
- data = cache.get("Empty Pages")
51
-
52
- expect(data[:pages]).to eq []
53
- expect(data[:subcats]).to eq ["Subcat"]
54
- end
55
-
56
- it "handles empty subcategories" do
57
- cache.save("No Subcats", ["Article"], [])
58
- data = cache.get("No Subcats")
59
-
60
- expect(data[:pages]).to eq ["Article"]
61
- expect(data[:subcats]).to eq []
62
- end
63
-
64
- it "handles Unicode category names" do
65
- cache.save("日本の都市", ["東京", "大阪"], ["関東の都市"])
66
- data = cache.get("日本の都市")
67
-
68
- expect(data[:pages]).to contain_exactly("東京", "大阪")
69
- expect(data[:subcats]).to contain_exactly("関東の都市")
70
- end
71
-
72
- it "normalizes category name by removing Category: prefix" do
73
- cache.save("Category:Test", ["Article"], [])
74
- data = cache.get("Test")
75
-
76
- expect(data[:pages]).to eq ["Article"]
77
- end
78
-
79
- it "returns nil for non-existent category" do
80
- expect(cache.get("Nonexistent")).to be_nil
81
- end
82
- end
83
-
84
- describe "#cached?" do
85
- it "returns true for cached category" do
86
- cache.save("Cached", ["Article"], [])
87
- expect(cache.cached?("Cached")).to be true
88
- end
89
-
90
- it "returns false for non-cached category" do
91
- expect(cache.cached?("Not Cached")).to be false
92
- end
93
- end
94
-
95
- describe "#get_all_pages" do
96
- before do
97
- cache.save("Root", ["Article1", "Article2"], ["Child1", "Child2"])
98
- cache.save("Child1", ["Article3"], ["Grandchild"])
99
- cache.save("Child2", ["Article4", "Article5"], [])
100
- cache.save("Grandchild", ["Article6"], [])
101
- end
102
-
103
- it "returns only direct pages with max_depth 0" do
104
- pages = cache.get_all_pages("Root", max_depth: 0)
105
- expect(pages).to contain_exactly("Article1", "Article2")
106
- end
107
-
108
- it "includes subcategory pages with max_depth 1" do
109
- pages = cache.get_all_pages("Root", max_depth: 1)
110
- expect(pages).to contain_exactly("Article1", "Article2", "Article3", "Article4", "Article5")
111
- end
112
-
113
- it "includes all nested pages with sufficient depth" do
114
- pages = cache.get_all_pages("Root", max_depth: 2)
115
- expect(pages).to contain_exactly("Article1", "Article2", "Article3", "Article4", "Article5", "Article6")
116
- end
117
-
118
- it "returns unique pages (no duplicates)" do
119
- cache.save("DupParent", ["SharedArticle"], ["DupChild"])
120
- cache.save("DupChild", ["SharedArticle", "UniqueArticle"], [])
121
-
122
- pages = cache.get_all_pages("DupParent", max_depth: 1)
123
- expect(pages.count("SharedArticle")).to eq 1
124
- end
125
-
126
- it "handles circular references" do
127
- cache.save("CircularA", ["A1"], ["CircularB"])
128
- cache.save("CircularB", ["B1"], ["CircularA"])
129
-
130
- pages = cache.get_all_pages("CircularA", max_depth: 10)
131
- expect(pages).to contain_exactly("A1", "B1")
132
- end
133
-
134
- it "returns empty array for non-existent category" do
135
- expect(cache.get_all_pages("Nonexistent")).to eq []
136
- end
137
- end
138
-
139
- describe "#get_tree" do
140
- before do
141
- cache.save("Root", ["A1"], ["Child"])
142
- cache.save("Child", ["C1", "C2"], [])
143
- end
144
-
145
- it "returns tree structure" do
146
- tree = cache.get_tree("Root", max_depth: 1)
147
-
148
- expect(tree[:name]).to eq "Root"
149
- expect(tree[:cached]).to be true
150
- expect(tree[:page_count]).to eq 1
151
- expect(tree[:children].size).to eq 1
152
- expect(tree[:children].first[:name]).to eq "Child"
153
- end
154
-
155
- it "limits depth" do
156
- cache.save("Deep", ["D1"], ["Root"])
157
-
158
- tree = cache.get_tree("Deep", max_depth: 0)
159
- expect(tree[:children]).to be_empty
160
- end
161
- end
162
-
163
- describe "#stats" do
164
- it "returns cache statistics" do
165
- cache.save("Cat1", ["A1", "A2"], ["Sub1"])
166
- cache.save("Cat2", ["A3"], [])
167
-
168
- stats = cache.stats
169
-
170
- expect(stats[:lang]).to eq "en"
171
- expect(stats[:total_categories]).to eq 2
172
- expect(stats[:total_pages]).to eq 3
173
- expect(stats[:total_relations]).to eq 1
174
- expect(stats[:cache_size]).to be > 0
175
- end
176
- end
177
-
178
- describe "#clear!" do
179
- it "removes all cached data" do
180
- cache.save("Test", ["Article"], [])
181
- cache.clear!
182
-
183
- expect(cache.cached?("Test")).to be false
184
- end
185
- end
186
-
187
- describe "#cleanup_expired!" do
188
- it "removes expired entries" do
189
- # Save a category
190
- cache.save("Old", ["Article"], [])
191
-
192
- # Manually update the cached_at to make it old
193
- # We need to access the database directly for this test
194
- cache.instance_variable_get(:@db).execute(
195
- "UPDATE categories SET cached_at = ? WHERE name = ?",
196
- [Time.now.to_i - (30 * 24 * 3600), "Old"] # 30 days ago
197
- )
198
-
199
- # Save a fresh category
200
- cache.save("Fresh", ["NewArticle"], [])
201
-
202
- # Cleanup with default 7-day expiry
203
- removed = cache.cleanup_expired!
204
-
205
- expect(removed).to eq 1
206
- expect(cache.cached?("Old")).to be false
207
- expect(cache.cached?("Fresh")).to be true
208
- end
209
- end
210
-
211
- describe "per-language isolation" do
212
- it "creates separate cache per language" do
213
- en_cache = described_class.new("en", cache_dir: cache_dir)
214
- ja_cache = described_class.new("ja", cache_dir: cache_dir)
215
-
216
- en_cache.save("Cities", ["New York"], [])
217
- ja_cache.save("Cities", ["東京"], [])
218
-
219
- expect(en_cache.get("Cities")[:pages]).to eq ["New York"]
220
- expect(ja_cache.get("Cities")[:pages]).to eq ["東京"]
221
-
222
- en_cache.close
223
- ja_cache.close
224
- end
225
- end
226
- end