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.
- checksums.yaml +4 -4
- data/.github/workflows/ci.yml +16 -1
- data/.github/workflows/publish-image.yml +8 -4
- data/.gitignore +0 -1
- data/CHANGELOG.md +23 -0
- data/DEVELOPMENT.md +62 -92
- data/DEVELOPMENT_ja.md +60 -92
- data/Dockerfile +1 -1
- data/README.md +54 -8
- data/README_ja.md +54 -8
- data/bin/wp2txt +23 -6
- data/lib/wp2txt/article.rb +1 -2
- data/lib/wp2txt/bz2_stream.rb +63 -0
- data/lib/wp2txt/cli.rb +48 -26
- data/lib/wp2txt/config.rb +2 -11
- data/lib/wp2txt/constants.rb +0 -1
- data/lib/wp2txt/corpus.rb +1 -21
- data/lib/wp2txt/data/template_aliases.json +3 -0
- data/lib/wp2txt/data/template_patterns.json +61643 -0
- data/lib/wp2txt/dump_snapshot.rb +99 -0
- data/lib/wp2txt/extraction_run.rb +272 -0
- data/lib/wp2txt/extractor.rb +476 -325
- data/lib/wp2txt/fts_index.rb +1 -1
- data/lib/wp2txt/index_cache.rb +144 -55
- data/lib/wp2txt/index_commands.rb +22 -19
- data/lib/wp2txt/link_counter.rb +1 -1
- data/lib/wp2txt/magic_words.rb +44 -28
- data/lib/wp2txt/metadata_index.rb +6 -13
- data/lib/wp2txt/multistream.rb +890 -824
- data/lib/wp2txt/output_writer.rb +3 -1
- data/lib/wp2txt/parser_functions.rb +23 -5
- data/lib/wp2txt/ractor_worker.rb +6 -4
- data/lib/wp2txt/regex.rb +24 -4
- data/lib/wp2txt/site_info.rb +123 -0
- data/lib/wp2txt/stream_store.rb +91 -0
- data/lib/wp2txt/template_args.rb +111 -0
- data/lib/wp2txt/template_expander.rb +92 -125
- data/lib/wp2txt/template_patterns.rb +182 -0
- data/lib/wp2txt/utils.rb +160 -125
- data/lib/wp2txt/version.rb +1 -1
- data/spec/auto_download_spec.rb +9 -6
- data/spec/category_fetcher_spec.rb +135 -463
- data/spec/cli_targeted_spec.rb +60 -0
- data/spec/config_spec.rb +2 -15
- data/spec/constants_spec.rb +0 -4
- data/spec/dump_fetch_spec.rb +293 -0
- data/spec/extraction_run_spec.rb +520 -0
- data/spec/index_build_spec.rb +113 -0
- data/spec/index_commands_version_spec.rb +17 -0
- data/spec/multistream_reader_spec.rb +140 -0
- data/spec/multistream_spec.rb +8 -214
- data/spec/output_integrity_spec.rb +45 -2
- data/spec/regex_spec.rb +30 -0
- data/spec/spec_helper.rb +3 -3
- data/spec/support/dump_status.rb +34 -0
- data/spec/support/multistream_fixture.rb +26 -8
- data/spec/template_args_spec.rb +133 -0
- data/spec/template_expander_spec.rb +29 -111
- data/spec/template_passthrough_spec.rb +17 -2
- data/spec/template_patterns_spec.rb +253 -0
- data/spec/tracked_paths_spec.rb +168 -0
- data/spec/utils_spec.rb +7 -1
- metadata +30 -5
- data/lib/wp2txt/category_cache.rb +0 -313
- data/spec/category_cache_spec.rb +0 -226
data/README.md
CHANGED
|
@@ -110,7 +110,11 @@ This automatically downloads the English Wikipedia dump and extracts plain text.
|
|
|
110
110
|
|
|
111
111
|
$ wp2txt --lang=en --articles="Cognitive linguistics,Generative grammar" -o ./articles
|
|
112
112
|
|
|
113
|
-
Only the index file and
|
|
113
|
+
Only the index file and the parts of the dump that hold the requested articles are downloaded, a few megabytes wherever the articles sit. They are kept in the cache for later runs.
|
|
114
|
+
|
|
115
|
+
Titles are matched the way Wikipedia writes them: underscores, a lower-case first letter, and namespace prefixes in English or in the wiki's language are accepted. A redirect is followed one step and its article is written under the title you asked for; `--no-follow-redirects` extracts the redirect page itself. For titles that contain commas, list them one per line in a file:
|
|
116
|
+
|
|
117
|
+
$ wp2txt --lang=en --articles-file=titles.txt -o ./articles
|
|
114
118
|
|
|
115
119
|
### Extract articles from a category
|
|
116
120
|
|
|
@@ -124,6 +128,39 @@ Preview without downloading (shows article counts):
|
|
|
124
128
|
|
|
125
129
|
$ wp2txt --lang=en --from-category="Cities in Japan" --dry-run
|
|
126
130
|
|
|
131
|
+
A category that cannot be listed in full stops the extraction. Add `--allow-incomplete-category` to extract what was listed; the manifest then records the listing as incomplete.
|
|
132
|
+
|
|
133
|
+
### Results of a targeted extraction
|
|
134
|
+
|
|
135
|
+
With `--articles`, `--articles-file`, or `--from-category`, every requested title ends in one of three ways: written, skipped by `--skip-empty`, or failed with a reason. The exit code tells which:
|
|
136
|
+
|
|
137
|
+
| Exit code | Meaning |
|
|
138
|
+
|-----------|---------|
|
|
139
|
+
| 0 | Every requested title was written or skipped |
|
|
140
|
+
| 2 | Some titles failed; the others were written |
|
|
141
|
+
| 1 | Nothing could be written, or the run stopped |
|
|
142
|
+
|
|
143
|
+
A manifest is written next to the output files: `enwiki_articles.manifest.json` for `--articles` on English Wikipedia, or the category name in place of `articles` for `--from-category`. It gives the dump version used (`source`), the result of each requested title (`requests`, with the title it was found under), the counts, and the files written. A title that reaches an article already written for another title is marked `same_as` that title, and `records` counts each article once:
|
|
144
|
+
|
|
145
|
+
```json
|
|
146
|
+
{
|
|
147
|
+
"run_id": "…",
|
|
148
|
+
"wp2txt_version": "2.5.0",
|
|
149
|
+
"template_patterns": "…",
|
|
150
|
+
"exit_code": 2,
|
|
151
|
+
"source": {"lang": "en", "date": "20261101", "snapshot": "…", "chosen": "recent"},
|
|
152
|
+
"counts": {"requested": 3, "located": 2, "retrieved": 2, "written": 2, "records": 2, "skipped_empty": 0, "failed": 1},
|
|
153
|
+
"requests": [
|
|
154
|
+
{"requested_title": "tokyo", "status": "written", "title": "Tokyo"},
|
|
155
|
+
{"requested_title": "NYC", "status": "written", "title": "New York City"},
|
|
156
|
+
{"requested_title": "No such page", "status": "failed", "reason": "not_found"}
|
|
157
|
+
],
|
|
158
|
+
"output_files": ["enwiki_articles.txt"]
|
|
159
|
+
}
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
Failure reasons: `not_found` (no such title in the dump), `redirect_unresolved` (a redirect whose target is missing, another redirect, or on another wiki), `text_unavailable` (the dump holds no text for the page), `truncated` or `stream_unavailable` (the part of the dump holding the page could not be read or fetched), and `index_mismatch` or `identity_mismatch` (the index and the dump disagree). Rerunning to the same output replaces the files the previous manifest lists. A run that fails leaves no manifest.
|
|
163
|
+
|
|
127
164
|
### Process local dump file
|
|
128
165
|
|
|
129
166
|
$ wp2txt -i ./enwiki-20220801-pages-articles.xml.bz2 -o ./text
|
|
@@ -228,9 +265,13 @@ For redirect articles:
|
|
|
228
265
|
$ wp2txt --cache-status # Show cache status
|
|
229
266
|
$ wp2txt --cache-clear # Clear all cache
|
|
230
267
|
$ wp2txt --cache-clear --lang=en # Clear cache for English only
|
|
231
|
-
$ wp2txt --update-cache #
|
|
268
|
+
$ wp2txt --update-cache # Check for a newer dump version now
|
|
232
269
|
|
|
233
|
-
|
|
270
|
+
wp2txt uses the newest dump that Wikimedia marks finished. It checks for a newer version at most once per `dump_expiry_days` (default: 30); `--update-cache` checks at once. `--dump-date YYYYMMDD` uses a given version instead:
|
|
271
|
+
|
|
272
|
+
$ wp2txt --lang=en --dump-date=20261101 --articles="Tokyo" -o ./articles
|
|
273
|
+
|
|
274
|
+
Cached files are checked against the sizes and SHA-1 digests Wikimedia publishes for that version. A cached file that does not match is set aside as `<name>.bad-<time>` and fetched again. Without a network connection, the newest version in the cache is used. Each version's files are kept in their own directory by hard link, so the cache directory must be on a file system that allows hard links.
|
|
234
275
|
|
|
235
276
|
## Advanced Options
|
|
236
277
|
|
|
@@ -273,12 +314,14 @@ Configure with `--markers`:
|
|
|
273
314
|
|
|
274
315
|
### Template Expansion
|
|
275
316
|
|
|
276
|
-
|
|
317
|
+
Templates are expanded by default. On the Japanese, English, German, French, Spanish, Italian, Russian, Chinese, Portuguese, Dutch, Polish, Arabic, and Korean editions, the most used inline templates are shown the way that edition shows them, from patterns learned from its own output: `{{lang-de|Wort}}` comes out as "ドイツ語: Wort" on the Japanese edition and "German: Wort" on the English one. Templates that compute their output (unit conversions, ages, coordinates) are not reproduced; the values written in the article are kept. Ages count from the dump's date. A template wp2txt does not know is replaced by its first unnamed argument, passing over a language code before another argument.
|
|
318
|
+
|
|
319
|
+
Other common templates are expanded by wp2txt's own rules:
|
|
277
320
|
|
|
278
321
|
| Template | Output |
|
|
279
322
|
|----------|--------|
|
|
280
323
|
| `{{birth date\|1990\|5\|15}}` | May 15, 1990 |
|
|
281
|
-
| `{{convert\|100\|km\|mi}}` | 100 km
|
|
324
|
+
| `{{convert\|100\|km\|mi}}` | 100 km |
|
|
282
325
|
| `{{coord\|35\|41\|N\|139\|41\|E}}` | 35°41′N 139°41′E |
|
|
283
326
|
| `{{lang\|ja\|日本語}}` | 日本語 |
|
|
284
327
|
| `{{nihongo\|Tokyo\|東京\|Tōkyō}}` | Tokyo (東京, Tōkyō) |
|
|
@@ -327,11 +370,15 @@ full-text search, interlanguage links, cross-language SQL, and the full MCP tool
|
|
|
327
370
|
-i, --input=<s> Path to compressed file (bz2) or XML file
|
|
328
371
|
-L, --lang=<s> Wikipedia language code (e.g., ja, en, de)
|
|
329
372
|
-A, --articles=<s> Specific article titles (comma-separated)
|
|
373
|
+
--articles-file=<s> File of article titles, one per line
|
|
374
|
+
-w, --no-follow-redirects Extract redirect pages themselves
|
|
330
375
|
-G, --from-category=<s> Extract articles from Wikipedia category
|
|
331
376
|
-D, --depth=<i> Subcategory recursion depth (default: 0)
|
|
332
377
|
-y, --yes Skip confirmation prompt
|
|
333
378
|
--dry-run Preview category extraction
|
|
334
|
-
|
|
379
|
+
--allow-incomplete-category Extract what was listed when a category cannot be listed in full
|
|
380
|
+
-U, --update-cache Check for the newest dump version now
|
|
381
|
+
--dump-date=<s> Use the dump of this date (YYYYMMDD)
|
|
335
382
|
|
|
336
383
|
Output options:
|
|
337
384
|
-o, --output-dir=<s> Output directory (default: current)
|
|
@@ -411,8 +458,7 @@ This creates `~/.wp2txt/config.yml`:
|
|
|
411
458
|
|
|
412
459
|
```yaml
|
|
413
460
|
cache:
|
|
414
|
-
dump_expiry_days: 30 # Days
|
|
415
|
-
category_expiry_days: 7 # Category cache expiry (1-90)
|
|
461
|
+
dump_expiry_days: 30 # Days between checks for a newer dump version (1-365)
|
|
416
462
|
directory: ~/.wp2txt/cache
|
|
417
463
|
|
|
418
464
|
defaults:
|
data/README_ja.md
CHANGED
|
@@ -94,7 +94,11 @@ docker run -it -v /path/to/localdata:/data ghcr.io/yohasebe/wp2txt
|
|
|
94
94
|
|
|
95
95
|
$ wp2txt --lang=ja --articles="認知言語学,生成文法" -o ./articles
|
|
96
96
|
|
|
97
|
-
|
|
97
|
+
インデックスファイルと、指定した記事を含むダンプの部分だけをダウンロードします。記事がダンプのどこにあっても数メガバイトで済み、取得した部分は次回以降のためにキャッシュに残ります。
|
|
98
|
+
|
|
99
|
+
タイトルはWikipediaの書き方どおりに照合します。アンダースコア、先頭の小文字、英語または各言語の名前空間接頭辞を受け付けます。リダイレクトは一段たどり、その記事を指定したタイトルで書き出します。`--no-follow-redirects` を付けるとリダイレクトのページそのものを抽出します。カンマを含むタイトルは、1行に1つずつファイルに書いて渡します:
|
|
100
|
+
|
|
101
|
+
$ wp2txt --lang=ja --articles-file=titles.txt -o ./articles
|
|
98
102
|
|
|
99
103
|
### カテゴリから記事を抽出
|
|
100
104
|
|
|
@@ -108,6 +112,39 @@ docker run -it -v /path/to/localdata:/data ghcr.io/yohasebe/wp2txt
|
|
|
108
112
|
|
|
109
113
|
$ wp2txt --lang=ja --from-category="日本の都市" --dry-run
|
|
110
114
|
|
|
115
|
+
カテゴリの一覧を最後まで取得できなかったときは抽出を中止します。`--allow-incomplete-category` を付けると取得できた分を抽出し、一覧が不完全だったことをマニフェストに記録します。
|
|
116
|
+
|
|
117
|
+
### 記事・カテゴリ指定の抽出結果
|
|
118
|
+
|
|
119
|
+
`--articles`、`--articles-file`、`--from-category` では、指定したタイトルはそれぞれ「書き出し」「`--skip-empty` による省略」「理由つきの失敗」のいずれかで終わります。終了コードでどれだったかが分かります:
|
|
120
|
+
|
|
121
|
+
| 終了コード | 意味 |
|
|
122
|
+
|-----------|------|
|
|
123
|
+
| 0 | 指定したタイトルはすべて書き出しまたは省略 |
|
|
124
|
+
| 2 | 一部のタイトルが失敗し、残りは書き出し |
|
|
125
|
+
| 1 | 何も書き出せなかった、または途中で止まった |
|
|
126
|
+
|
|
127
|
+
出力ファイルの隣にマニフェストを書き出します(日本語版の `--articles` なら `jawiki_articles.manifest.json`、`--from-category` では `articles` の代わりにカテゴリ名)。使ったダンプの版(`source`)、指定した各タイトルの結果(`requests`、見つかったタイトルを含む)、件数、書き出したファイルを記録します。別のタイトルですでに書き出した記事に行き着いたタイトルには `same_as` でそのタイトルを示し、`records` は記事を1件ずつ数えます:
|
|
128
|
+
|
|
129
|
+
```json
|
|
130
|
+
{
|
|
131
|
+
"run_id": "…",
|
|
132
|
+
"wp2txt_version": "2.5.0",
|
|
133
|
+
"template_patterns": "…",
|
|
134
|
+
"exit_code": 2,
|
|
135
|
+
"source": {"lang": "ja", "date": "20261101", "snapshot": "…", "chosen": "recent"},
|
|
136
|
+
"counts": {"requested": 3, "located": 2, "retrieved": 2, "written": 2, "records": 2, "skipped_empty": 0, "failed": 1},
|
|
137
|
+
"requests": [
|
|
138
|
+
{"requested_title": "東京", "status": "written", "title": "東京"},
|
|
139
|
+
{"requested_title": "京都", "status": "written", "title": "京都"},
|
|
140
|
+
{"requested_title": "存在しないページ", "status": "failed", "reason": "not_found"}
|
|
141
|
+
],
|
|
142
|
+
"output_files": ["jawiki_articles.txt"]
|
|
143
|
+
}
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
失敗の理由: `not_found`(ダンプにそのタイトルがない)、`redirect_unresolved`(リダイレクト先がない、さらにリダイレクト、または別のウィキ)、`text_unavailable`(ダンプにそのページの本文がない)、`truncated` と `stream_unavailable`(そのページを含むダンプの部分を読めない、または取得できない)、`index_mismatch` と `identity_mismatch`(索引とダンプが食い違う)。同じ出力先で再実行すると、前回のマニフェストに載っているファイルを置き換えます。失敗した実行はマニフェストを残しません。
|
|
147
|
+
|
|
111
148
|
### ローカルダンプファイルを処理
|
|
112
149
|
|
|
113
150
|
$ wp2txt -i ./jawiki-20220801-pages-articles.xml.bz2 -o ./text
|
|
@@ -203,9 +240,13 @@ QID・並べ替えの鍵がなければ `null`、曖昧さ回避の印がなけ
|
|
|
203
240
|
$ wp2txt --cache-status # キャッシュ状態を表示
|
|
204
241
|
$ wp2txt --cache-clear # 全キャッシュをクリア
|
|
205
242
|
$ wp2txt --cache-clear --lang=ja # 日本語のみクリア
|
|
206
|
-
$ wp2txt --update-cache #
|
|
243
|
+
$ wp2txt --update-cache # 新しいダンプの版を今すぐ確認
|
|
207
244
|
|
|
208
|
-
|
|
245
|
+
wp2txtはWikimediaが完了としている最新のダンプを使います。新しい版の確認は `dump_expiry_days`(デフォルト: 30日)に1回までで、`--update-cache` を付けるとすぐに確認します。`--dump-date YYYYMMDD` で版を指定することもできます:
|
|
246
|
+
|
|
247
|
+
$ wp2txt --lang=ja --dump-date=20261101 --articles="東京" -o ./articles
|
|
248
|
+
|
|
249
|
+
キャッシュしたファイルは、Wikimediaがその版について公開しているサイズとSHA-1ダイジェストで照合します。一致しないファイルは `<name>.bad-<time>` として退避し、取得し直します。ネットワークにつながらないときは、キャッシュにある最新の版を使います。版ごとのファイルはハードリンクで専用のディレクトリに置くため、キャッシュディレクトリはハードリンクを作れるファイルシステム上に置いてください。
|
|
209
250
|
|
|
210
251
|
## 詳細オプション
|
|
211
252
|
|
|
@@ -248,12 +289,14 @@ QID・並べ替えの鍵がなければ `null`、曖昧さ回避の印がなけ
|
|
|
248
289
|
|
|
249
290
|
### テンプレート展開
|
|
250
291
|
|
|
251
|
-
|
|
292
|
+
テンプレートはデフォルトで展開します。日本語、英語、ドイツ語、フランス語、スペイン語、イタリア語、ロシア語、中国語、ポルトガル語、オランダ語、ポーランド語、アラビア語、韓国語の各版では、よく使われるインラインのテンプレートを、その版の表示から学んだパターンでその版と同じように表示します。たとえば `{{lang-de|Wort}}` は日本語版では「ドイツ語: Wort」、英語版では「German: Wort」になります。出力を計算するテンプレート(単位換算、年齢、座標)は再現せず、記事に書かれた値を残します。年齢はダンプの日付から数えます。wp2txtが知らないテンプレートは、最初の名前なし引数に置き換えます(その引数が言語コードで後に別の引数があれば、そちらを使います)。
|
|
293
|
+
|
|
294
|
+
その他の一般的なテンプレートはwp2txt独自の規則で展開します:
|
|
252
295
|
|
|
253
296
|
| テンプレート | 出力 |
|
|
254
297
|
|--------------|------|
|
|
255
298
|
| `{{birth date\|1990\|5\|15}}` | May 15, 1990 |
|
|
256
|
-
| `{{convert\|100\|km\|mi}}` | 100 km
|
|
299
|
+
| `{{convert\|100\|km\|mi}}` | 100 km |
|
|
257
300
|
| `{{coord\|35\|41\|N\|139\|41\|E}}` | 35°41′N 139°41′E |
|
|
258
301
|
| `{{lang\|ja\|日本語}}` | 日本語 |
|
|
259
302
|
| `{{nihongo\|Tokyo\|東京\|Tōkyō}}` | Tokyo (東京, Tōkyō) |
|
|
@@ -280,11 +323,15 @@ QID・並べ替えの鍵がなければ `null`、曖昧さ回避の印がなけ
|
|
|
280
323
|
-i, --input=<s> 圧縮ファイル(bz2)またはXMLファイルへのパス
|
|
281
324
|
-L, --lang=<s> Wikipedia言語コード(例: ja, en, de)
|
|
282
325
|
-A, --articles=<s> 特定の記事タイトル(カンマ区切り)
|
|
326
|
+
--articles-file=<s> 記事タイトルのファイル(1行に1つ)
|
|
327
|
+
-w, --no-follow-redirects リダイレクトのページそのものを抽出
|
|
283
328
|
-G, --from-category=<s> Wikipediaカテゴリから記事を抽出
|
|
284
329
|
-D, --depth=<i> サブカテゴリ再帰深度(デフォルト: 0)
|
|
285
330
|
-y, --yes 確認プロンプトをスキップ
|
|
286
331
|
--dry-run カテゴリ抽出をプレビュー
|
|
287
|
-
|
|
332
|
+
--allow-incomplete-category カテゴリを最後まで一覧できないとき、取得できた分を抽出
|
|
333
|
+
-U, --update-cache 新しいダンプの版を今すぐ確認
|
|
334
|
+
--dump-date=<s> この日付(YYYYMMDD)のダンプを使う
|
|
288
335
|
|
|
289
336
|
出力オプション:
|
|
290
337
|
-o, --output-dir=<s> 出力ディレクトリ(デフォルト: カレント)
|
|
@@ -355,8 +402,7 @@ QID・並べ替えの鍵がなければ `null`、曖昧さ回避の印がなけ
|
|
|
355
402
|
|
|
356
403
|
```yaml
|
|
357
404
|
cache:
|
|
358
|
-
dump_expiry_days: 30 #
|
|
359
|
-
category_expiry_days: 7 # カテゴリキャッシュの有効期限(1-90)
|
|
405
|
+
dump_expiry_days: 30 # 新しいダンプの版を確認する間隔の日数(1-365)
|
|
360
406
|
directory: ~/.wp2txt/cache
|
|
361
407
|
|
|
362
408
|
defaults:
|
data/bin/wp2txt
CHANGED
|
@@ -779,13 +779,13 @@ class WpApp
|
|
|
779
779
|
return extract_category_articles(opts)
|
|
780
780
|
end
|
|
781
781
|
|
|
782
|
-
if opts[:articles] && opts[:lang]
|
|
782
|
+
if (opts[:articles] || opts[:articles_file]) && opts[:lang]
|
|
783
783
|
# Article extraction mode
|
|
784
784
|
return extract_specific_articles(opts)
|
|
785
785
|
end
|
|
786
786
|
|
|
787
787
|
input_path = if opts[:lang]
|
|
788
|
-
download_dump(opts[:lang], opts[:cache_dir])
|
|
788
|
+
download_dump(opts[:lang], opts[:cache_dir], dump_date: opts[:dump_date], update: opts[:update_cache])
|
|
789
789
|
else
|
|
790
790
|
opts[:input]
|
|
791
791
|
end
|
|
@@ -826,6 +826,15 @@ class WpApp
|
|
|
826
826
|
# Parse markers option
|
|
827
827
|
config[:markers] = parse_markers_option(opts[:markers])
|
|
828
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
|
+
|
|
829
838
|
# Imported page properties ride along in JSON output;
|
|
830
839
|
# loaded here, before any worker is forked, so workers share the table
|
|
831
840
|
config[:page_properties] = load_page_properties(input_path, opts[:cache_dir]) if format == :json
|
|
@@ -915,14 +924,13 @@ class WpApp
|
|
|
915
924
|
puts
|
|
916
925
|
puts pastel.dim("Available settings:")
|
|
917
926
|
print_list_item("cache.dump_expiry_days - Days before dump cache expires (default: 30)")
|
|
918
|
-
print_list_item("cache.category_expiry_days - Days before category cache expires (default: 7)")
|
|
919
927
|
print_list_item("cache.directory - Cache directory location")
|
|
920
928
|
print_list_item("defaults.format - Default output format (text/json)")
|
|
921
929
|
print_list_item("defaults.depth - Default subcategory recursion depth")
|
|
922
930
|
end
|
|
923
931
|
|
|
924
932
|
# Download dump for a language
|
|
925
|
-
def download_dump(lang, cache_dir)
|
|
933
|
+
def download_dump(lang, cache_dir, dump_date: nil, update: false)
|
|
926
934
|
app_config = Wp2txt::CLI.config
|
|
927
935
|
|
|
928
936
|
print_mode_banner("Auto-Download", {
|
|
@@ -933,7 +941,9 @@ class WpApp
|
|
|
933
941
|
manager = Wp2txt::DumpManager.new(
|
|
934
942
|
lang,
|
|
935
943
|
cache_dir: cache_dir,
|
|
936
|
-
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
|
|
937
947
|
)
|
|
938
948
|
|
|
939
949
|
# Check for latest dump
|
|
@@ -963,5 +973,12 @@ Signal.trap("INT") do
|
|
|
963
973
|
end
|
|
964
974
|
|
|
965
975
|
# Create new instance and run with proper exit code
|
|
966
|
-
|
|
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
|
|
967
984
|
exit(exit_code || Wp2txt::CliUI::EXIT_SUCCESS)
|
data/lib/wp2txt/article.rb
CHANGED
|
@@ -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
|
-
|
|
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 :
|
|
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",
|
|
@@ -227,31 +235,6 @@ module Wp2txt
|
|
|
227
235
|
Optimist.die "Cannot specify both --input and --lang"
|
|
228
236
|
end
|
|
229
237
|
|
|
230
|
-
# --articles requires --lang
|
|
231
|
-
if opts[:articles] && opts[:lang].nil?
|
|
232
|
-
Optimist.die "--articles requires --lang"
|
|
233
|
-
end
|
|
234
|
-
|
|
235
|
-
# --articles cannot be used with --input
|
|
236
|
-
if opts[:articles] && opts[:input]
|
|
237
|
-
Optimist.die "--articles cannot be used with --input"
|
|
238
|
-
end
|
|
239
|
-
|
|
240
|
-
# --from-category requires --lang
|
|
241
|
-
if opts[:from_category] && opts[:lang].nil?
|
|
242
|
-
Optimist.die "--from-category requires --lang"
|
|
243
|
-
end
|
|
244
|
-
|
|
245
|
-
# --from-category cannot be used with --input
|
|
246
|
-
if opts[:from_category] && opts[:input]
|
|
247
|
-
Optimist.die "--from-category cannot be used with --input"
|
|
248
|
-
end
|
|
249
|
-
|
|
250
|
-
# --from-category cannot be used with --articles
|
|
251
|
-
if opts[:from_category] && opts[:articles]
|
|
252
|
-
Optimist.die "--from-category cannot be used with --articles"
|
|
253
|
-
end
|
|
254
|
-
|
|
255
238
|
# --depth must be >= 0
|
|
256
239
|
if opts[:depth] < 0
|
|
257
240
|
Optimist.die :depth, "must be 0 or greater"
|
|
@@ -262,6 +245,8 @@ module Wp2txt
|
|
|
262
245
|
warn "Warning: --depth > 3 may result in a very large number of articles"
|
|
263
246
|
end
|
|
264
247
|
|
|
248
|
+
validate_targeted_extraction!(opts)
|
|
249
|
+
|
|
265
250
|
# --dry-run only makes sense with --from-category
|
|
266
251
|
if opts[:dry_run] && opts[:from_category].nil?
|
|
267
252
|
Optimist.die "--dry-run requires --from-category"
|
|
@@ -277,6 +262,11 @@ module Wp2txt
|
|
|
277
262
|
Optimist.die :input, "file does not exist"
|
|
278
263
|
end
|
|
279
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
|
+
|
|
280
270
|
# Validate language code
|
|
281
271
|
if opts[:lang] && !valid_language_code?(opts[:lang])
|
|
282
272
|
Optimist.die :lang, "invalid language code format"
|
|
@@ -454,6 +444,38 @@ module Wp2txt
|
|
|
454
444
|
articles_str.split(",").map(&:strip).reject(&:empty?)
|
|
455
445
|
end
|
|
456
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
|
+
|
|
457
479
|
# Check if a language code is valid
|
|
458
480
|
# Valid codes: 2-10 lowercase letters (e.g., en, ja, simple, zh-yue)
|
|
459
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, :
|
|
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
|
-
#
|
|
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
|
|
data/lib/wp2txt/constants.rb
CHANGED
data/lib/wp2txt/corpus.rb
CHANGED
|
@@ -38,27 +38,6 @@ module Wp2txt
|
|
|
38
38
|
show_matched_sections: false
|
|
39
39
|
}.freeze
|
|
40
40
|
|
|
41
|
-
# Duck-typed replacement for MultistreamIndex that resolves titles through
|
|
42
|
-
# the IndexCache SQLite file on demand, avoiding loading millions of index
|
|
43
|
-
# entries into memory (important for long-lived server processes).
|
|
44
|
-
class LazyTitleIndex
|
|
45
|
-
def initialize(index_cache)
|
|
46
|
-
@cache = index_cache
|
|
47
|
-
end
|
|
48
|
-
|
|
49
|
-
def find_by_title(title)
|
|
50
|
-
@cache.find_by_titles([title])[title]
|
|
51
|
-
end
|
|
52
|
-
|
|
53
|
-
def stream_offset_for(title)
|
|
54
|
-
find_by_title(title)&.fetch(:offset, nil)
|
|
55
|
-
end
|
|
56
|
-
|
|
57
|
-
def stream_offsets
|
|
58
|
-
@stream_offsets ||= @cache.stream_offsets
|
|
59
|
-
end
|
|
60
|
-
end
|
|
61
|
-
|
|
62
41
|
attr_reader :multistream_path, :index_path, :metadata
|
|
63
42
|
|
|
64
43
|
def initialize(multistream_path:, index_path:, cache_dir: nil)
|
|
@@ -584,6 +563,7 @@ module Wp2txt
|
|
|
584
563
|
end
|
|
585
564
|
|
|
586
565
|
def close
|
|
566
|
+
@reader&.close
|
|
587
567
|
close_read_connections
|
|
588
568
|
end
|
|
589
569
|
|
|
@@ -8,6 +8,9 @@
|
|
|
8
8
|
"remove_templates": [
|
|
9
9
|
"sfn", "efn", "refn", "reflist", "refbegin", "refend", "notelist",
|
|
10
10
|
"r", "rp", "harvnb", "harv", "harvtxt", "sfnp",
|
|
11
|
+
"ref+", "sfnm", "sfnmp", "sfnref", "harvnp", "harvp", "harvc", "harvs",
|
|
12
|
+
"harvcol", "harvcolnb", "harvcoltxt", "harvard citation",
|
|
13
|
+
"harvard citation no brackets", "harvard citation text",
|
|
11
14
|
"main", "see also", "further", "details", "about",
|
|
12
15
|
"redirect", "distinguish", "other uses", "other people",
|
|
13
16
|
"for", "for other", "for more",
|