Vasily Alexeev commited on
Commit ·
55a54e6
1
Parent(s): 721d43c
add full preproc -- from dump
Browse files- README.md +174 -62
- SHA256SUMS +19 -0
- preprocessing/_wikigood/wiki_metadata.py +1567 -0
- preprocessing/_wikigood/wikigood_ru_corpus.py +297 -0
- preprocessing/_wikigood/wikigood_ru_quality_metadata.py +220 -0
- preprocessing/prepare.py +25 -5
- preprocessing/requirements.txt +1 -0
- preprocessing/wikipedia-quality-corpus-20261001.json +1 -0
README.md
CHANGED
|
@@ -24,6 +24,19 @@ wikitext, extracted readable text, direct categories, quality status and revisio
|
|
| 24 |
links. The category catalog supports inspection of direct membership and parent
|
| 25 |
relationships; it is not a curated subject taxonomy.
|
| 26 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
## Coverage and selection
|
| 28 |
|
| 29 |
The corpus is the union of namespace-0 articles in these direct SQL categories:
|
|
@@ -47,7 +60,7 @@ NLP CSV files. There are no exact duplicate `wikitext` or `raw_text` values in t
|
|
| 47 |
procedure does not remove records because they share text. The `corpus`
|
| 48 |
partition is a storage partition, not a research split.
|
| 49 |
|
| 50 |
-
##
|
| 51 |
|
| 52 |
The `articles` configuration is the default. `articles` and `categories` use
|
| 53 |
compressed JSON Lines and the `corpus` split, with no dataset script.
|
|
@@ -106,6 +119,31 @@ bow = load_dataset(
|
|
| 106 |
)
|
| 107 |
```
|
| 108 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 109 |
The NLP preparation section describes the normalized namespaces and text fields.
|
| 110 |
|
| 111 |
## Article fields
|
|
@@ -193,18 +231,10 @@ the stored format:
|
|
| 193 |
## Sources and revision semantics
|
| 194 |
|
| 195 |
The source is the [Russian Wikipedia 20261001 dump](https://dumps.wikimedia.org/ruwiki/20261001/).
|
| 196 |
-
The
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
| File | SHA-256 |
|
| 201 |
-
| --- | --- |
|
| 202 |
-
| `ruwiki-20261001-page.sql.gz` | `24250cca6122fff02896a1ced0a85b7afa4d6be00fa119c169a5eeef3fbe5830` |
|
| 203 |
-
| `ruwiki-20261001-page_props.sql.gz` | `fc9d5aeaf3487d932b82d18a16bc96f0e4e4702e1149cbbdc482eb509f6deb60` |
|
| 204 |
-
| `ruwiki-20261001-categorylinks.sql.gz` | `1ecb32ffaff28a120b6a8f4297d4b228b65c49beb593eae022b5811ae41512e1` |
|
| 205 |
-
| `ruwiki-20261001-linktarget.sql.gz` | `bc1f24b7b8eb06298cbe70fdfb010ec023586d05bd2d3403ba2370091e1edc4a` |
|
| 206 |
-
| `ruwiki-20261001-pages-articles-multistream.xml.bz2` | `c22b6441176d2bc572ed6883abc6292fe168efca211f6cdd61d8772a78492a1b` |
|
| 207 |
-
| `ruwiki-20261001-pages-articles-multistream-index.txt.bz2` | `17c6a4cebb90ecb2b0f881e04aa3b49356bd6ee6add802a7201b9ca1a9b093e3` |
|
| 208 |
|
| 209 |
SQL provides selection, titles, page properties and category relationships. XML
|
| 210 |
provides article content, `revision_id` and `revision_timestamp`. **11 articles**
|
|
@@ -228,7 +258,8 @@ Full uses all 17,413 articles. Each CSV has exactly three columns:
|
|
| 228 |
`id`, `raw_text`, `vw_text`. IDs and article order are preserved. CSV `raw_text`
|
| 229 |
is the title, two LF characters and the original readable body with only its
|
| 230 |
leading CR/LF characters removed. In the original JSON, `raw_text` remains the
|
| 231 |
-
readable body alone. Standard CSV quoting preserves embedded newlines
|
|
|
|
| 232 |
|
| 233 |
`vw_text` uses Vowpal Wabbit namespaces in this order:
|
| 234 |
|
|
@@ -260,62 +291,136 @@ separately selected n-gram vocabularies. These CSVs are not a claim of evaluatio
|
|
| 260 |
without information from held-out documents. For text-only experiments, use only
|
| 261 |
`@word`; title, category and subject metadata may reveal evaluation targets.
|
| 262 |
|
| 263 |
-
|
| 264 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 265 |
|
| 266 |
```bash
|
| 267 |
-
conda create --name ruwiki-nlp --file conda-linux-64.lock.txt
|
| 268 |
conda activate ruwiki-nlp
|
| 269 |
-
python -m pip install -r pip-linux-x86_64.lock.txt
|
| 270 |
-
python prepare.py --help
|
| 271 |
-
python prepare.py --action download --dataset both --sources-dir ./sources
|
| 272 |
-
python prepare.py --action build --dataset both --sources-dir ./sources --output-dir ./output --scratch-dir ./scratch
|
| 273 |
-
python prepare.py --action verify --dataset both --sources-dir ./sources --output-dir ./output
|
| 274 |
```
|
| 275 |
|
| 276 |
-
`
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
`
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 307 |
|
| 308 |
Load a generated CSV directly:
|
| 309 |
|
| 310 |
```python
|
| 311 |
noow = load_dataset(
|
| 312 |
-
"csv", data_files={"corpus": "output/full/noow.csv"}, split="corpus"
|
| 313 |
)
|
| 314 |
bow = load_dataset(
|
| 315 |
-
"csv", data_files={"corpus": "output/full/bow.csv"}, split="corpus"
|
| 316 |
)
|
| 317 |
```
|
| 318 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 319 |
The code in `preprocessing/` is available under its [MIT license](preprocessing/LICENSE).
|
| 320 |
The article text and its normalized derivatives retain the CC BY-SA 4.0 terms
|
| 321 |
and attribution requirements described below.
|
|
@@ -343,11 +448,18 @@ offensive material. Any further subject labels, deduplication policy,
|
|
| 343 |
preprocessing and research splits needed for a downstream study must be specified
|
| 344 |
separately.
|
| 345 |
|
| 346 |
-
##
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 347 |
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
|
|
|
| 24 |
links. The category catalog supports inspection of direct membership and parent
|
| 25 |
relationships; it is not a curated subject taxonomy.
|
| 26 |
|
| 27 |
+
## Files at a glance
|
| 28 |
+
|
| 29 |
+
| File | Purpose | Bytes |
|
| 30 |
+
| --- | --- | ---: |
|
| 31 |
+
| `data/articles.jsonl.gz` | Source article records, readable text and provenance. | 409,970,311 |
|
| 32 |
+
| `data/categories.jsonl.gz` | Category catalog and direct parent relationships. | 22,459,573 |
|
| 33 |
+
| `data/noow.csv` | Whole-document text and ordered normalized VW features. | 1,128,356,201 |
|
| 34 |
+
| `data/bow.csv` | The same documents with counted VW features. | 883,080,852 |
|
| 35 |
+
|
| 36 |
+
The reusable code, environment locks and source/output pins are in
|
| 37 |
+
[preprocessing/](preprocessing/). [SHA256SUMS](SHA256SUMS) covers the published
|
| 38 |
+
data and preparation files; see [file verification](#file-verification).
|
| 39 |
+
|
| 40 |
## Coverage and selection
|
| 41 |
|
| 42 |
The corpus is the union of namespace-0 articles in these direct SQL categories:
|
|
|
|
| 60 |
procedure does not remove records because they share text. The `corpus`
|
| 61 |
partition is a storage partition, not a research split.
|
| 62 |
|
| 63 |
+
## Quick start: load the published files
|
| 64 |
|
| 65 |
The `articles` configuration is the default. `articles` and `categories` use
|
| 66 |
compressed JSON Lines and the `corpus` split, with no dataset script.
|
|
|
|
| 119 |
)
|
| 120 |
```
|
| 121 |
|
| 122 |
+
CSV is the primary prepared format. The explicit `"csv"` builder above is
|
| 123 |
+
required: these files are not additional YAML configurations, because combining
|
| 124 |
+
JSON and CSV builders in one repository configuration did not load reliably.
|
| 125 |
+
The published CSV files have been fully read with Hugging Face Datasets.
|
| 126 |
+
|
| 127 |
+
To export one VW document per line without loading the CSV into memory, run this
|
| 128 |
+
from the downloaded repository. Choose an output path outside the repository:
|
| 129 |
+
|
| 130 |
+
```python
|
| 131 |
+
import csv
|
| 132 |
+
from pathlib import Path
|
| 133 |
+
|
| 134 |
+
csv.field_size_limit(2**31 - 1)
|
| 135 |
+
with Path("data/noow.csv").open(encoding="utf-8", newline="") as source:
|
| 136 |
+
with Path("../RuWiki-Good-2026-V2-noow.vw").open("w", encoding="utf-8", newline="") as output:
|
| 137 |
+
for row in csv.DictReader(source):
|
| 138 |
+
output.write(row["vw_text"] + "\n")
|
| 139 |
+
```
|
| 140 |
+
|
| 141 |
+
The field-size setting is needed only for Python's standard `csv` reader;
|
| 142 |
+
it does not configure Hugging Face Datasets. Use `bow.csv` in the same example
|
| 143 |
+
for counted features. CSV records contain whole documents and may include
|
| 144 |
+
embedded newlines in `raw_text`, so splitting the CSV by physical lines is unsafe.
|
| 145 |
+
The repository does not store a second permanent copy as VW text files.
|
| 146 |
+
|
| 147 |
The NLP preparation section describes the normalized namespaces and text fields.
|
| 148 |
|
| 149 |
## Article fields
|
|
|
|
| 231 |
## Sources and revision semantics
|
| 232 |
|
| 233 |
The source is the [Russian Wikipedia 20261001 dump](https://dumps.wikimedia.org/ruwiki/20261001/).
|
| 234 |
+
The [source and output pins](preprocessing/wikipedia-quality-corpus-20261001.json) record the names, byte sizes and SHA-256 digests of all six
|
| 235 |
+
inputs: page, page properties, category links and link targets SQL dumps, plus the
|
| 236 |
+
multistream article XML and its index. Dump mirrors may later remove this dated
|
| 237 |
+
snapshot; the pins identify the inputs independently of their availability.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 238 |
|
| 239 |
SQL provides selection, titles, page properties and category relationships. XML
|
| 240 |
provides article content, `revision_id` and `revision_timestamp`. **11 articles**
|
|
|
|
| 258 |
`id`, `raw_text`, `vw_text`. IDs and article order are preserved. CSV `raw_text`
|
| 259 |
is the title, two LF characters and the original readable body with only its
|
| 260 |
leading CR/LF characters removed. In the original JSON, `raw_text` remains the
|
| 261 |
+
readable body alone. Standard CSV quoting preserves embedded newlines; one whole-document row can
|
| 262 |
+
span many physical lines.
|
| 263 |
|
| 264 |
`vw_text` uses Vowpal Wabbit namespaces in this order:
|
| 265 |
|
|
|
|
| 291 |
without information from held-out documents. For text-only experiments, use only
|
| 292 |
`@word`; title, category and subject metadata may reveal evaluation targets.
|
| 293 |
|
| 294 |
+
### Rebuild NLP CSVs from ready article snapshots
|
| 295 |
+
|
| 296 |
+
Run from the parent directory containing the downloaded `RuWiki-Good-2026-V2`
|
| 297 |
+
and `RuWiki-Good-2026-V2-Selected` repositories. Working files go under a separate
|
| 298 |
+
`ruwiki-rebuild` directory. Choose fresh output and scratch paths on a disk with
|
| 299 |
+
enough space; corpus output and scratch inside a published clone are rejected.
|
| 300 |
+
Python 3.11.15 is the pinned
|
| 301 |
+
runtime for both build and verify: VW escaping depends on its Unicode database.
|
| 302 |
+
On Linux x86-64, use the supplied locks:
|
| 303 |
|
| 304 |
```bash
|
| 305 |
+
conda create --name ruwiki-nlp --file RuWiki-Good-2026-V2/preprocessing/conda-linux-64.lock.txt
|
| 306 |
conda activate ruwiki-nlp
|
| 307 |
+
python -m pip install -r RuWiki-Good-2026-V2/preprocessing/pip-linux-x86_64.lock.txt
|
| 308 |
+
python RuWiki-Good-2026-V2/preprocessing/prepare.py --help
|
| 309 |
+
python RuWiki-Good-2026-V2/preprocessing/prepare.py --stage nlp --action download --dataset both --sources-dir ./ruwiki-rebuild/nlp-sources
|
| 310 |
+
python RuWiki-Good-2026-V2/preprocessing/prepare.py --stage nlp --action build --dataset both --sources-dir ./ruwiki-rebuild/nlp-sources --output-dir ./ruwiki-rebuild/nlp-output --scratch-dir ./ruwiki-rebuild/nlp-scratch
|
| 311 |
+
python RuWiki-Good-2026-V2/preprocessing/prepare.py --stage nlp --action verify --dataset both --sources-dir ./ruwiki-rebuild/nlp-sources --output-dir ./ruwiki-rebuild/nlp-output
|
| 312 |
```
|
| 313 |
|
| 314 |
+
`--stage nlp` is the default, so earlier commands without `--stage` continue to
|
| 315 |
+
work. Choose `--dataset full`, `selected` or `both`. The
|
| 316 |
+
[pinned NLP contract](preprocessing/wikipedia-quality-nlp-20261001.json) records
|
| 317 |
+
source revisions, source payload hashes and runtime requirements. The
|
| 318 |
+
[corpus contract](preprocessing/wikipedia-quality-corpus-20261001.json) additionally
|
| 319 |
+
pins the expected published NLP output bytes.
|
| 320 |
+
`requirements.txt` lists direct dependencies, including `mwparserfromhell==0.7.2`
|
| 321 |
+
for corpus extraction. The locks retain the complete environment used for NLP;
|
| 322 |
+
no downloaded spaCy language model is needed. If installing only the direct
|
| 323 |
+
requirements in a separate environment, retain Python 3.11.15.
|
| 324 |
+
|
| 325 |
+
Download checks existing source files against their pins, fetches missing files,
|
| 326 |
+
and acquires the pinned NLTK archive at
|
| 327 |
+
`./ruwiki-rebuild/nlp-sources/nltk_data/corpora/stopwords.zip`. To reuse downloaded JSONL files,
|
| 328 |
+
place them at `./ruwiki-rebuild/nlp-sources/full/articles.jsonl.gz`,
|
| 329 |
+
`./ruwiki-rebuild/nlp-sources/selected/articles.jsonl.gz` and
|
| 330 |
+
`./ruwiki-rebuild/nlp-sources/selected/topics.jsonl.gz` before running download. This step creates
|
| 331 |
+
the local NLTK resource directory; no pre-existing `nltk_data` is required.
|
| 332 |
+
Use `--nltk-data` to select a different local NLTK resource directory.
|
| 333 |
+
|
| 334 |
+
Hugging Face downloads use anonymous Python `urllib`. For restricted repositories,
|
| 335 |
+
fetch the pinned files with authenticated tools, place them at the paths above,
|
| 336 |
+
and rerun download. The script does not handle authentication tokens.
|
| 337 |
+
Build runs offline, checks runtime versions and Russian stopword content, and
|
| 338 |
+
writes `./ruwiki-rebuild/nlp-output/full` and `./ruwiki-rebuild/nlp-output/selected`. Keep outputs and scratch
|
| 339 |
+
separate from published data and use a fresh scratch directory for a new build.
|
| 340 |
+
Progress messages identify phases and document counts. Each build manifest
|
| 341 |
+
records counts and ordered IDs of documents with an empty `@word` namespace;
|
| 342 |
+
those articles remain in the output.
|
| 343 |
+
|
| 344 |
+
Verification needs no NLP packages. It checks source identities, output hashes
|
| 345 |
+
against the build manifest, schemas, source text and NOOW/BOW token-count
|
| 346 |
+
agreement. The shared entry point then independently checks the generated CSVs
|
| 347 |
+
and Selected labels against published byte sizes and SHA-256 pins in the corpus
|
| 348 |
+
contract, reporting `PUBLISHED_NLP_OK` on success. These expectations are separate
|
| 349 |
+
from the newly generated manifest. Verification does not rerun tokenization,
|
| 350 |
+
lemmatization or PMI selection.
|
| 351 |
+
|
| 352 |
+
A measured build of both NLP collections from the ready JSONL snapshots took
|
| 353 |
+
**42 min 5.83 s**, with **10.58 GiB** peak resident memory, approximately
|
| 354 |
+
**3.74 GiB** of final output and **0.53 GiB** of scratch files. These measurements
|
| 355 |
+
exclude raw dump downloads and corpus reconstruction; they are an example from
|
| 356 |
+
one environment, not a bound for other machines.
|
| 357 |
|
| 358 |
Load a generated CSV directly:
|
| 359 |
|
| 360 |
```python
|
| 361 |
noow = load_dataset(
|
| 362 |
+
"csv", data_files={"corpus": "./ruwiki-rebuild/nlp-output/full/noow.csv"}, split="corpus"
|
| 363 |
)
|
| 364 |
bow = load_dataset(
|
| 365 |
+
"csv", data_files={"corpus": "./ruwiki-rebuild/nlp-output/full/bow.csv"}, split="corpus"
|
| 366 |
)
|
| 367 |
```
|
| 368 |
|
| 369 |
+
## Rebuild the corpus from Wikimedia dumps
|
| 370 |
+
|
| 371 |
+
The same entry point supports `--stage corpus`, with `download`, `build` and
|
| 372 |
+
`verify` actions. The [corpus contract](preprocessing/wikipedia-quality-corpus-20261001.json)
|
| 373 |
+
pins the six 20261001 dump files, the published article/category payloads and the
|
| 374 |
+
retained Selected annotations. This public raw-dump replay has **not yet been run
|
| 375 |
+
end to end**. Its download time, build time and peak disk and memory requirements
|
| 376 |
+
have not been measured; the NLP measurements above do not describe this stage.
|
| 377 |
+
|
| 378 |
+
The example below runs from the parent of both downloaded repository directories,
|
| 379 |
+
as in the NLP commands above.
|
| 380 |
+
The Selected annotation directory must already contain `labels.json` and
|
| 381 |
+
`topics.jsonl.gz`. These retained mappings reproduce the published subject
|
| 382 |
+
assignments; the script does not rerun AI labeling.
|
| 383 |
+
|
| 384 |
+
```bash
|
| 385 |
+
python RuWiki-Good-2026-V2/preprocessing/prepare.py --stage corpus --action download --dataset both --sources-dir ./ruwiki-rebuild/dump-sources
|
| 386 |
+
# Resume an interrupted dump download explicitly:
|
| 387 |
+
python RuWiki-Good-2026-V2/preprocessing/prepare.py --stage corpus --action download --dataset both --sources-dir ./ruwiki-rebuild/dump-sources --resume
|
| 388 |
+
python RuWiki-Good-2026-V2/preprocessing/prepare.py --stage corpus --action build --dataset both --sources-dir ./ruwiki-rebuild/dump-sources --annotations-dir RuWiki-Good-2026-V2-Selected/data --output-dir ./ruwiki-rebuild/corpus-output --scratch-dir ./ruwiki-rebuild/corpus-scratch
|
| 389 |
+
python RuWiki-Good-2026-V2/preprocessing/prepare.py --stage corpus --action verify --dataset both --sources-dir ./ruwiki-rebuild/dump-sources --output-dir ./ruwiki-rebuild/corpus-output
|
| 390 |
+
```
|
| 391 |
+
|
| 392 |
+
Download stores and checks the six pinned files beneath `--sources-dir`.
|
| 393 |
+
After all files are present, build is offline. It reconstructs SQL metadata,
|
| 394 |
+
selects qualifying article IDs, extracts the indexed XML revisions, and applies
|
| 395 |
+
the readable-text cleanup. It writes `./ruwiki-rebuild/corpus-output/full/articles.jsonl.gz` and
|
| 396 |
+
`categories.jsonl.gz`, plus `./ruwiki-rebuild/corpus-output/selected/articles.jsonl.gz` and
|
| 397 |
+
`topics.jsonl.gz`. Use separate fresh output and scratch directories, leaving
|
| 398 |
+
published `data/` untouched. Corpus verification compares outputs with the
|
| 399 |
+
independently bundled expected published payloads, rather than trusting hashes
|
| 400 |
+
newly written by the build itself.
|
| 401 |
+
|
| 402 |
+
For Full only, set `--dataset full` and omit `--annotations-dir`. Selected can
|
| 403 |
+
also be reconstructed from a previously accepted Full corpus without rereading
|
| 404 |
+
the dumps. From the same working directory:
|
| 405 |
+
|
| 406 |
+
```bash
|
| 407 |
+
python RuWiki-Good-2026-V2/preprocessing/prepare.py --stage corpus --action build --dataset selected --sources-dir RuWiki-Good-2026-V2/data --full-dir RuWiki-Good-2026-V2/data --annotations-dir RuWiki-Good-2026-V2-Selected/data --output-dir ./ruwiki-rebuild/selected-output --scratch-dir ./ruwiki-rebuild/selected-scratch
|
| 408 |
+
python RuWiki-Good-2026-V2/preprocessing/prepare.py --stage corpus --action verify --dataset selected --sources-dir RuWiki-Good-2026-V2/data --output-dir ./ruwiki-rebuild/selected-output
|
| 409 |
+
```
|
| 410 |
+
|
| 411 |
+
This Selected-only workflow has been verified byte for byte against the published
|
| 412 |
+
archive of all 17,251 articles, the labels file and the topic definitions.
|
| 413 |
+
|
| 414 |
+
To continue from reconstructed JSONL to NLP, the corpus output root is directly
|
| 415 |
+
usable as `--sources-dir`. Download then supplies the pinned NLTK archive before
|
| 416 |
+
the offline NLP build:
|
| 417 |
+
|
| 418 |
+
```bash
|
| 419 |
+
python RuWiki-Good-2026-V2/preprocessing/prepare.py --stage nlp --action download --dataset both --sources-dir ./ruwiki-rebuild/corpus-output
|
| 420 |
+
python RuWiki-Good-2026-V2/preprocessing/prepare.py --stage nlp --action build --dataset both --sources-dir ./ruwiki-rebuild/corpus-output --output-dir ./ruwiki-rebuild/replay-nlp-output --scratch-dir ./ruwiki-rebuild/replay-nlp-scratch
|
| 421 |
+
python RuWiki-Good-2026-V2/preprocessing/prepare.py --stage nlp --action verify --dataset both --sources-dir ./ruwiki-rebuild/corpus-output --output-dir ./ruwiki-rebuild/replay-nlp-output
|
| 422 |
+
```
|
| 423 |
+
|
| 424 |
The code in `preprocessing/` is available under its [MIT license](preprocessing/LICENSE).
|
| 425 |
The article text and its normalized derivatives retain the CC BY-SA 4.0 terms
|
| 426 |
and attribution requirements described below.
|
|
|
|
| 448 |
preprocessing and research splits needed for a downstream study must be specified
|
| 449 |
separately.
|
| 450 |
|
| 451 |
+
## File verification
|
| 452 |
+
|
| 453 |
+
From the root of the downloaded repository, verify the distributed data and
|
| 454 |
+
preparation files with:
|
| 455 |
+
|
| 456 |
+
```bash
|
| 457 |
+
sha256sum -c SHA256SUMS
|
| 458 |
+
```
|
| 459 |
|
| 460 |
+
[SHA256SUMS](SHA256SUMS) lists those files without embedding long digests in this
|
| 461 |
+
card. It excludes this README and Git/service metadata. The corpus and NLP
|
| 462 |
+
contracts in `preprocessing/` pin source inputs, while the corpus contract also
|
| 463 |
+
pins expected published corpus and NLP payloads independently of a new build. A successful checksum check establishes
|
| 464 |
+
agreement with the supplied manifest; use a trusted repository revision when
|
| 465 |
+
establishing provenance.
|
SHA256SUMS
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
c51f9b6bee4c85f25ffb861060f52490a9276bae289d2aa2db7e0d10e2dda950 data/articles.jsonl.gz
|
| 2 |
+
a45edd3e9287009e353c0f3ffc4404ffadc393293dada691e2d275a0bc0d2f5d data/bow.csv
|
| 3 |
+
d07ab1e6c07da28cc162d786853a73c54e300289e21bcc6667c4072158abdf8f data/categories.jsonl.gz
|
| 4 |
+
041250c048b0441cc88d516b92e1d65c0f80db3c82b400b7ae6b9db379c2ed33 data/noow.csv
|
| 5 |
+
40e9e59aaa72c85612fb13c1a31726062309c6a33c858b99d485d54986d360a3 preprocessing/LICENSE
|
| 6 |
+
b12783fbca1588a57b983032b8eb1534b6d107b1ecfc0633c9f03040d24c6bdf preprocessing/_wikigood/__init__.py
|
| 7 |
+
996e564b0a96eb8427c77356f6c0f87ba5f09b6cce63629edac807da253be92c preprocessing/_wikigood/wiki_metadata.py
|
| 8 |
+
af48d12c9d7c5a7560004863790881b0483bc9e26838de4a737fe8d14f71ba56 preprocessing/_wikigood/wikigood_ru_content.py
|
| 9 |
+
8ca18e1ad52b1e83cf0221c87773643033402f666ee03b1a7473b7a0c77c6a55 preprocessing/_wikigood/wikigood_ru_corpus.py
|
| 10 |
+
9a8ea2f173cb81462bd66fb1342d958a48d1add97fea1651db40aa571e153081 preprocessing/_wikigood/wikigood_ru_csv.py
|
| 11 |
+
d3b04973b735f805164a5ff6dd8c631e523440d1e9d52597a6a314aa888a1f32 preprocessing/_wikigood/wikigood_ru_nlp.py
|
| 12 |
+
ffa062b071e7dbbd4ab1254ba752157df3da8518be7a586f685e5449c5e9c4a7 preprocessing/_wikigood/wikigood_ru_quality_metadata.py
|
| 13 |
+
a1066fd916fb254e3971e505c57c1e6bbc037c74b218f19a3ecd1e83ed4077a4 preprocessing/_wikigood/wikigood_ru_vw.py
|
| 14 |
+
d6d1374d3ea144edc3fd5285ba87dac4daa9dea2857d0f165c6d0943a69a43fc preprocessing/conda-linux-64.lock.txt
|
| 15 |
+
48ed6fcf0bfdcd15ed76b6f62b136890c6beb3a9e7af9615d88b1f6c457acac9 preprocessing/pip-linux-x86_64.lock.txt
|
| 16 |
+
816ab241f6bef38406a35b0b05c1046f210b98fbaa2c9e88e8af3c6d92687f3c preprocessing/prepare.py
|
| 17 |
+
cc61d5ba11e0521ecfdf9ea818415aaf4b70c1522c9902b99ac271efdf61c5b1 preprocessing/requirements.txt
|
| 18 |
+
baed2546050747c3bedf6eb34db1953e530f99fefe7b9b129d1612631c2ab845 preprocessing/wikipedia-quality-corpus-20261001.json
|
| 19 |
+
f109106d65e960376a3acfeb0fc116c05fcc2e0965af35b1353600edf5355a47 preprocessing/wikipedia-quality-nlp-20261001.json
|
preprocessing/_wikigood/wiki_metadata.py
ADDED
|
@@ -0,0 +1,1567 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Streaming readers and indexes for Wikimedia metadata SQL dumps."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from collections.abc import Mapping as MappingABC, Set as SetABC
|
| 6 |
+
from contextlib import contextmanager
|
| 7 |
+
from dataclasses import dataclass
|
| 8 |
+
from itertools import chain
|
| 9 |
+
import os
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
import re
|
| 12 |
+
import sqlite3
|
| 13 |
+
import stat
|
| 14 |
+
import threading
|
| 15 |
+
from typing import Iterable, Iterator, Mapping, TypeAlias
|
| 16 |
+
from uuid import uuid4
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
SqlValue: TypeAlias = str | int | float | None
|
| 20 |
+
_Token: TypeAlias = tuple[str, SqlValue]
|
| 21 |
+
|
| 22 |
+
_INTEGER = re.compile(r"[+-]?\d+\Z")
|
| 23 |
+
_FLOAT = re.compile(
|
| 24 |
+
r"[+-]?(?:\d+\.\d*|\.\d+|\d+)(?:[eE][+-]?\d+)?\Z"
|
| 25 |
+
)
|
| 26 |
+
_MYSQL_ESCAPES = {
|
| 27 |
+
"0": "\0",
|
| 28 |
+
"b": "\b",
|
| 29 |
+
"n": "\n",
|
| 30 |
+
"r": "\r",
|
| 31 |
+
"t": "\t",
|
| 32 |
+
"Z": "\x1a",
|
| 33 |
+
"\\": "\\",
|
| 34 |
+
"'": "'",
|
| 35 |
+
'"': '"',
|
| 36 |
+
}
|
| 37 |
+
_SCHEMA_PREFIX_LIMIT = 1024 * 1024
|
| 38 |
+
_SQLITE_BATCH_SIZE = 500
|
| 39 |
+
_TEMP_DIRECTORY_LOCK = threading.Lock()
|
| 40 |
+
|
| 41 |
+
_PAGE_COLUMNS = ((0, "page_id"), (1, "page_namespace"), (2, "page_title"))
|
| 42 |
+
_PAGE_METADATA_COLUMNS = (
|
| 43 |
+
(0, "page_id"),
|
| 44 |
+
(1, "page_namespace"),
|
| 45 |
+
(2, "page_title"),
|
| 46 |
+
(4, "page_is_redirect"),
|
| 47 |
+
(9, "page_latest"),
|
| 48 |
+
)
|
| 49 |
+
_PAGE_PROPS_COLUMNS = ((0, "pp_page"), (1, "pp_propname"), (2, "pp_value"))
|
| 50 |
+
_LINKTARGET_COLUMNS = ((0, "lt_id"), (1, "lt_namespace"), (2, "lt_title"))
|
| 51 |
+
_CATEGORYLINKS_COLUMNS = (
|
| 52 |
+
(0, "cl_from"),
|
| 53 |
+
(1, "cl_sortkey"),
|
| 54 |
+
(2, "cl_timestamp"),
|
| 55 |
+
(3, "cl_sortkey_prefix"),
|
| 56 |
+
(4, "cl_type"),
|
| 57 |
+
(5, "cl_collation_id"),
|
| 58 |
+
(6, "cl_target_id"),
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
class _MetadataIndexError(ValueError):
|
| 63 |
+
"""SQLite indexing failure carrying observed temporary database bytes."""
|
| 64 |
+
|
| 65 |
+
def __init__(self, message: str, scratch_bytes: int) -> None:
|
| 66 |
+
super().__init__(message)
|
| 67 |
+
self.scratch_bytes = scratch_bytes
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
class WikiMetadataScratch:
|
| 71 |
+
"""POSIX-owned namespace for file-backed SQLite metadata indexes.
|
| 72 |
+
|
| 73 |
+
D-018 runs in one dedicated SQLite-exclusive process inside a private
|
| 74 |
+
attempt directory. Namespace mutation by another same-UID process is out of
|
| 75 |
+
scope. The pathname identity checks below only make an observed accidental
|
| 76 |
+
replacement non-destructive; pathname unlink/rmdir are not an atomic
|
| 77 |
+
ownership guarantee. ``temp_store_directory`` is process-global raw SQLite
|
| 78 |
+
state, protected here only by the in-process lock and the dedicated-process
|
| 79 |
+
assumption.
|
| 80 |
+
"""
|
| 81 |
+
|
| 82 |
+
def __init__(self, parent: Path, ceiling_bytes: int) -> None:
|
| 83 |
+
if not _TEMP_DIRECTORY_LOCK.acquire(blocking=False):
|
| 84 |
+
raise RuntimeError("another SQLite scratch scope is already active")
|
| 85 |
+
self._closed = False
|
| 86 |
+
self.ceiling_bytes = ceiling_bytes
|
| 87 |
+
self.main_database_bytes = 0
|
| 88 |
+
self.observed_ephemeral_transient_high_water_bytes = 0
|
| 89 |
+
self.exceeded = False
|
| 90 |
+
self._databases: dict[str, tuple[int, str]] = {}
|
| 91 |
+
self._parent_fd: int | None = None
|
| 92 |
+
self._directory_fd: int | None = None
|
| 93 |
+
self._previous_temp_directory: str | None = None
|
| 94 |
+
self._pragma_changed = False
|
| 95 |
+
try:
|
| 96 |
+
self._parent_fd = os.open(
|
| 97 |
+
parent, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW
|
| 98 |
+
)
|
| 99 |
+
while True:
|
| 100 |
+
self._name = f".wikigood-sqlite-{uuid4().hex}"
|
| 101 |
+
try:
|
| 102 |
+
os.mkdir(self._name, mode=0o700, dir_fd=self._parent_fd)
|
| 103 |
+
except FileExistsError:
|
| 104 |
+
continue
|
| 105 |
+
break
|
| 106 |
+
self._directory_fd = os.open(
|
| 107 |
+
self._name,
|
| 108 |
+
os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW,
|
| 109 |
+
dir_fd=self._parent_fd,
|
| 110 |
+
)
|
| 111 |
+
namespace_stat = os.stat(
|
| 112 |
+
self._name, dir_fd=self._parent_fd, follow_symlinks=False
|
| 113 |
+
)
|
| 114 |
+
if not os.path.samestat(namespace_stat, os.fstat(self._directory_fd)):
|
| 115 |
+
raise FileExistsError(
|
| 116 |
+
"SQLite scratch namespace was replaced before validation"
|
| 117 |
+
)
|
| 118 |
+
control = sqlite3.connect(":memory:")
|
| 119 |
+
try:
|
| 120 |
+
previous = control.execute("PRAGMA temp_store_directory").fetchone()
|
| 121 |
+
self._previous_temp_directory = previous[0] if previous else None
|
| 122 |
+
control.execute(
|
| 123 |
+
f"PRAGMA temp_store_directory = '{self._proc_directory}'"
|
| 124 |
+
)
|
| 125 |
+
self._pragma_changed = True
|
| 126 |
+
finally:
|
| 127 |
+
control.close()
|
| 128 |
+
except BaseException as error:
|
| 129 |
+
try:
|
| 130 |
+
self.close()
|
| 131 |
+
except BaseException as cleanup_error:
|
| 132 |
+
error.add_note(f"SQLite scratch cleanup failed: {cleanup_error}")
|
| 133 |
+
raise
|
| 134 |
+
|
| 135 |
+
@property
|
| 136 |
+
def _proc_directory(self) -> str:
|
| 137 |
+
assert self._directory_fd is not None
|
| 138 |
+
return f"/proc/self/fd/{self._directory_fd}"
|
| 139 |
+
|
| 140 |
+
def _remove_empty_owned_namespace(self) -> None:
|
| 141 |
+
"""Remove the namespace only while its pathname still identifies it."""
|
| 142 |
+
|
| 143 |
+
if self._parent_fd is None or self._directory_fd is None:
|
| 144 |
+
return
|
| 145 |
+
with os.scandir(self._directory_fd) as entries:
|
| 146 |
+
if any(entries):
|
| 147 |
+
return
|
| 148 |
+
try:
|
| 149 |
+
namespace_stat = os.stat(
|
| 150 |
+
self._name, dir_fd=self._parent_fd, follow_symlinks=False
|
| 151 |
+
)
|
| 152 |
+
except OSError:
|
| 153 |
+
return
|
| 154 |
+
if os.path.samestat(namespace_stat, os.fstat(self._directory_fd)):
|
| 155 |
+
try:
|
| 156 |
+
os.rmdir(self._name, dir_fd=self._parent_fd)
|
| 157 |
+
except OSError:
|
| 158 |
+
pass
|
| 159 |
+
|
| 160 |
+
def create_database(self, name: str) -> str:
|
| 161 |
+
"""Reserve an exclusive database name inside the owned namespace."""
|
| 162 |
+
|
| 163 |
+
if Path(name).name != name:
|
| 164 |
+
raise ValueError("SQLite database name must be a basename")
|
| 165 |
+
if name in self._databases:
|
| 166 |
+
raise FileExistsError(f"SQLite database is already active: {name}")
|
| 167 |
+
backing_name = f".{name}.{uuid4().hex}.owned"
|
| 168 |
+
descriptor = os.open(
|
| 169 |
+
backing_name,
|
| 170 |
+
os.O_RDWR | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW,
|
| 171 |
+
0o600,
|
| 172 |
+
dir_fd=self._directory_fd,
|
| 173 |
+
)
|
| 174 |
+
try:
|
| 175 |
+
os.link(
|
| 176 |
+
backing_name,
|
| 177 |
+
name,
|
| 178 |
+
src_dir_fd=self._directory_fd,
|
| 179 |
+
dst_dir_fd=self._directory_fd,
|
| 180 |
+
follow_symlinks=False,
|
| 181 |
+
)
|
| 182 |
+
descriptor_stat = os.fstat(descriptor)
|
| 183 |
+
for path in (name, backing_name):
|
| 184 |
+
path_stat = os.stat(
|
| 185 |
+
path, dir_fd=self._directory_fd, follow_symlinks=False
|
| 186 |
+
)
|
| 187 |
+
if not os.path.samestat(path_stat, descriptor_stat):
|
| 188 |
+
raise FileExistsError(
|
| 189 |
+
"SQLite database name was replaced before validation"
|
| 190 |
+
)
|
| 191 |
+
except BaseException:
|
| 192 |
+
try:
|
| 193 |
+
for path in (name, backing_name):
|
| 194 |
+
self._unlink_database_path(path, descriptor)
|
| 195 |
+
finally:
|
| 196 |
+
os.close(descriptor)
|
| 197 |
+
raise
|
| 198 |
+
self._databases[name] = descriptor, backing_name
|
| 199 |
+
return f"{self._proc_directory}/{backing_name}"
|
| 200 |
+
|
| 201 |
+
def release_database(self, name: str) -> None:
|
| 202 |
+
"""Unlink a database name from the exclusively owned namespace."""
|
| 203 |
+
|
| 204 |
+
database = self._databases.pop(name, None)
|
| 205 |
+
if database is None:
|
| 206 |
+
return
|
| 207 |
+
descriptor, backing_name = database
|
| 208 |
+
try:
|
| 209 |
+
for path in (name, backing_name):
|
| 210 |
+
self._unlink_database_path(path, descriptor)
|
| 211 |
+
finally:
|
| 212 |
+
os.close(descriptor)
|
| 213 |
+
|
| 214 |
+
def _unlink_database_path(self, path: str, descriptor: int) -> None:
|
| 215 |
+
"""Unlink one database path only while it names the held object."""
|
| 216 |
+
|
| 217 |
+
try:
|
| 218 |
+
path_stat = os.stat(
|
| 219 |
+
path, dir_fd=self._directory_fd, follow_symlinks=False
|
| 220 |
+
)
|
| 221 |
+
except FileNotFoundError:
|
| 222 |
+
return
|
| 223 |
+
if os.path.samestat(path_stat, os.fstat(descriptor)):
|
| 224 |
+
os.unlink(path, dir_fd=self._directory_fd)
|
| 225 |
+
|
| 226 |
+
def observe(self) -> int:
|
| 227 |
+
"""Record one observed main/transient file-size snapshot.
|
| 228 |
+
|
| 229 |
+
Main database bytes are hard-capped by SQLite ``max_page_count``.
|
| 230 |
+
The transient high-water field retains sampled observations only;
|
| 231 |
+
progress callbacks cannot exclude a between-observation overshoot.
|
| 232 |
+
"""
|
| 233 |
+
|
| 234 |
+
files: dict[tuple[int, int], int] = {}
|
| 235 |
+
for entry in os.scandir(self._directory_fd):
|
| 236 |
+
entry_stat = entry.stat(follow_symlinks=False)
|
| 237 |
+
if stat.S_ISREG(entry_stat.st_mode):
|
| 238 |
+
files[(entry_stat.st_dev, entry_stat.st_ino)] = entry_stat.st_size
|
| 239 |
+
|
| 240 |
+
directory_target = os.readlink(self._proc_directory).rstrip("/") + "/"
|
| 241 |
+
for descriptor_name in os.listdir("/proc/self/fd"):
|
| 242 |
+
descriptor_path = f"/proc/self/fd/{descriptor_name}"
|
| 243 |
+
try:
|
| 244 |
+
target = os.readlink(descriptor_path)
|
| 245 |
+
descriptor_stat = os.stat(descriptor_path)
|
| 246 |
+
except OSError:
|
| 247 |
+
continue
|
| 248 |
+
if target.startswith(directory_target) and stat.S_ISREG(
|
| 249 |
+
descriptor_stat.st_mode
|
| 250 |
+
):
|
| 251 |
+
files[(descriptor_stat.st_dev, descriptor_stat.st_ino)] = (
|
| 252 |
+
descriptor_stat.st_size
|
| 253 |
+
)
|
| 254 |
+
|
| 255 |
+
database_identities = {
|
| 256 |
+
(database_stat.st_dev, database_stat.st_ino)
|
| 257 |
+
for database_stat in (
|
| 258 |
+
os.fstat(descriptor)
|
| 259 |
+
for descriptor, _ in self._databases.values()
|
| 260 |
+
)
|
| 261 |
+
}
|
| 262 |
+
main_bytes = sum(
|
| 263 |
+
size for identity, size in files.items() if identity in database_identities
|
| 264 |
+
)
|
| 265 |
+
transient_bytes = sum(
|
| 266 |
+
size
|
| 267 |
+
for identity, size in files.items()
|
| 268 |
+
if identity not in database_identities
|
| 269 |
+
)
|
| 270 |
+
self.main_database_bytes = max(self.main_database_bytes, main_bytes)
|
| 271 |
+
self.observed_ephemeral_transient_high_water_bytes = max(
|
| 272 |
+
self.observed_ephemeral_transient_high_water_bytes, transient_bytes
|
| 273 |
+
)
|
| 274 |
+
actual_bytes = main_bytes + transient_bytes
|
| 275 |
+
if actual_bytes > self.ceiling_bytes:
|
| 276 |
+
self.exceeded = True
|
| 277 |
+
raise _MetadataIndexError(
|
| 278 |
+
"observed SQLite scratch bytes exceeded the "
|
| 279 |
+
f"{self.ceiling_bytes}-byte disk ceiling",
|
| 280 |
+
self.main_database_bytes,
|
| 281 |
+
)
|
| 282 |
+
return actual_bytes
|
| 283 |
+
|
| 284 |
+
def progress(self) -> int:
|
| 285 |
+
"""Interrupt SQLite when observed scratch bytes cross the ceiling."""
|
| 286 |
+
|
| 287 |
+
try:
|
| 288 |
+
self.observe()
|
| 289 |
+
except _MetadataIndexError:
|
| 290 |
+
return 1
|
| 291 |
+
return 0
|
| 292 |
+
|
| 293 |
+
def close(self) -> None:
|
| 294 |
+
"""Close namespace handles without deleting replacement objects."""
|
| 295 |
+
|
| 296 |
+
if self._closed:
|
| 297 |
+
return
|
| 298 |
+
self._closed = True
|
| 299 |
+
errors: list[BaseException] = []
|
| 300 |
+
try:
|
| 301 |
+
if self._pragma_changed:
|
| 302 |
+
try:
|
| 303 |
+
control = sqlite3.connect(":memory:")
|
| 304 |
+
try:
|
| 305 |
+
temp_directory = (self._previous_temp_directory or "").replace(
|
| 306 |
+
"'", "''"
|
| 307 |
+
)
|
| 308 |
+
control.execute(
|
| 309 |
+
f"PRAGMA temp_store_directory = '{temp_directory}'"
|
| 310 |
+
)
|
| 311 |
+
finally:
|
| 312 |
+
control.close()
|
| 313 |
+
except BaseException as error:
|
| 314 |
+
errors.append(error)
|
| 315 |
+
for name in tuple(self._databases):
|
| 316 |
+
try:
|
| 317 |
+
self.release_database(name)
|
| 318 |
+
except BaseException as error:
|
| 319 |
+
errors.append(error)
|
| 320 |
+
try:
|
| 321 |
+
self._remove_empty_owned_namespace()
|
| 322 |
+
except BaseException as error:
|
| 323 |
+
errors.append(error)
|
| 324 |
+
finally:
|
| 325 |
+
for descriptor in (
|
| 326 |
+
self._directory_fd,
|
| 327 |
+
self._parent_fd,
|
| 328 |
+
):
|
| 329 |
+
if descriptor is not None:
|
| 330 |
+
try:
|
| 331 |
+
os.close(descriptor)
|
| 332 |
+
except BaseException as error:
|
| 333 |
+
errors.append(error)
|
| 334 |
+
_TEMP_DIRECTORY_LOCK.release()
|
| 335 |
+
if errors:
|
| 336 |
+
raise errors[0]
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
@contextmanager
|
| 340 |
+
def open_metadata_scratch(
|
| 341 |
+
parent: Path, ceiling_bytes: int
|
| 342 |
+
) -> Iterator[WikiMetadataScratch]:
|
| 343 |
+
"""Yield one disk-backed SQLite namespace owned by a preflight attempt."""
|
| 344 |
+
|
| 345 |
+
scratch = WikiMetadataScratch(Path(parent), ceiling_bytes)
|
| 346 |
+
try:
|
| 347 |
+
yield scratch
|
| 348 |
+
except BaseException as error:
|
| 349 |
+
try:
|
| 350 |
+
scratch.close()
|
| 351 |
+
except BaseException as cleanup_error:
|
| 352 |
+
error.add_note(f"SQLite scratch cleanup failed: {cleanup_error}")
|
| 353 |
+
raise
|
| 354 |
+
else:
|
| 355 |
+
scratch.close()
|
| 356 |
+
|
| 357 |
+
|
| 358 |
+
@dataclass(frozen=True, slots=True)
|
| 359 |
+
class Page:
|
| 360 |
+
"""Minimal record from the Wikimedia ``page`` table.
|
| 361 |
+
|
| 362 |
+
Parameters
|
| 363 |
+
----------
|
| 364 |
+
page_id
|
| 365 |
+
Numeric page identifier.
|
| 366 |
+
namespace
|
| 367 |
+
Numeric MediaWiki namespace.
|
| 368 |
+
title
|
| 369 |
+
Database-form page title, without a namespace prefix.
|
| 370 |
+
is_redirect
|
| 371 |
+
Whether the page row is a redirect.
|
| 372 |
+
latest_revision_id
|
| 373 |
+
Identifier from ``page_latest`` when retained by the caller.
|
| 374 |
+
"""
|
| 375 |
+
|
| 376 |
+
page_id: int
|
| 377 |
+
namespace: int
|
| 378 |
+
title: str
|
| 379 |
+
is_redirect: bool = False
|
| 380 |
+
latest_revision_id: int | None = None
|
| 381 |
+
|
| 382 |
+
|
| 383 |
+
@dataclass(frozen=True, slots=True)
|
| 384 |
+
class PageProp:
|
| 385 |
+
"""Minimal record from the Wikimedia ``page_props`` table.
|
| 386 |
+
|
| 387 |
+
Parameters
|
| 388 |
+
----------
|
| 389 |
+
page_id
|
| 390 |
+
Identifier of the page carrying the property.
|
| 391 |
+
name
|
| 392 |
+
Property name.
|
| 393 |
+
value
|
| 394 |
+
Property value, or ``None`` for SQL ``NULL``.
|
| 395 |
+
"""
|
| 396 |
+
|
| 397 |
+
page_id: int
|
| 398 |
+
name: str
|
| 399 |
+
value: str | None
|
| 400 |
+
|
| 401 |
+
|
| 402 |
+
@dataclass(frozen=True, slots=True)
|
| 403 |
+
class CategoryLink:
|
| 404 |
+
"""Minimal record from the Wikimedia ``categorylinks`` table.
|
| 405 |
+
|
| 406 |
+
Parameters
|
| 407 |
+
----------
|
| 408 |
+
source_page_id
|
| 409 |
+
Identifier of the page assigned to the category.
|
| 410 |
+
link_type
|
| 411 |
+
MediaWiki category link type.
|
| 412 |
+
target_id
|
| 413 |
+
Identifier of the target in the ``linktarget`` table.
|
| 414 |
+
"""
|
| 415 |
+
|
| 416 |
+
source_page_id: int
|
| 417 |
+
link_type: str
|
| 418 |
+
target_id: int
|
| 419 |
+
|
| 420 |
+
|
| 421 |
+
@dataclass(frozen=True, slots=True)
|
| 422 |
+
class LinkTarget:
|
| 423 |
+
"""Minimal record from the Wikimedia ``linktarget`` table.
|
| 424 |
+
|
| 425 |
+
Parameters
|
| 426 |
+
----------
|
| 427 |
+
target_id
|
| 428 |
+
Numeric link-target identifier.
|
| 429 |
+
namespace
|
| 430 |
+
Numeric MediaWiki namespace of the target.
|
| 431 |
+
title
|
| 432 |
+
Database-form target title, without a namespace prefix.
|
| 433 |
+
"""
|
| 434 |
+
|
| 435 |
+
target_id: int
|
| 436 |
+
namespace: int
|
| 437 |
+
title: str
|
| 438 |
+
|
| 439 |
+
|
| 440 |
+
@dataclass(frozen=True, slots=True)
|
| 441 |
+
class WikiMetadataIndexes:
|
| 442 |
+
"""Indexes derived from Wikimedia metadata tables.
|
| 443 |
+
|
| 444 |
+
Parameters
|
| 445 |
+
----------
|
| 446 |
+
category_title_to_id
|
| 447 |
+
Category titles mapped to category page identifiers.
|
| 448 |
+
category_id_to_title
|
| 449 |
+
Category page identifiers mapped to titles.
|
| 450 |
+
page_id_to_qid
|
| 451 |
+
Page identifiers mapped to Wikidata item identifiers.
|
| 452 |
+
hidden_category_ids
|
| 453 |
+
Category page identifiers carrying the ``hiddencat`` property.
|
| 454 |
+
category_parents
|
| 455 |
+
Category page identifiers mapped to their parent category identifiers.
|
| 456 |
+
article_categories
|
| 457 |
+
Namespace-0 page identifiers mapped to category page identifiers.
|
| 458 |
+
category_children
|
| 459 |
+
Category titles mapped lazily to direct subcategory titles.
|
| 460 |
+
category_title_to_qid
|
| 461 |
+
Category titles mapped lazily to Wikidata item identifiers.
|
| 462 |
+
"""
|
| 463 |
+
|
| 464 |
+
category_title_to_id: Mapping[str, int]
|
| 465 |
+
category_id_to_title: Mapping[int, str]
|
| 466 |
+
page_id_to_qid: Mapping[int, str]
|
| 467 |
+
hidden_category_ids: SetABC[int]
|
| 468 |
+
category_parents: Mapping[int, tuple[int, ...]]
|
| 469 |
+
article_categories: Mapping[int, tuple[int, ...]]
|
| 470 |
+
category_children: Mapping[str, tuple[str, ...]]
|
| 471 |
+
category_title_to_qid: Mapping[str, str]
|
| 472 |
+
_connection: sqlite3.Connection
|
| 473 |
+
_scratch: WikiMetadataScratch | None
|
| 474 |
+
_database_name: str | None
|
| 475 |
+
|
| 476 |
+
@property
|
| 477 |
+
def scratch_bytes(self) -> int:
|
| 478 |
+
"""Return allocated bytes in the temporary SQLite metadata index."""
|
| 479 |
+
|
| 480 |
+
if self._scratch is not None:
|
| 481 |
+
self._scratch.observe()
|
| 482 |
+
return self._scratch.main_database_bytes
|
| 483 |
+
return _database_bytes(self._connection)
|
| 484 |
+
|
| 485 |
+
def close(self) -> None:
|
| 486 |
+
"""Close and remove the temporary SQLite metadata index."""
|
| 487 |
+
|
| 488 |
+
try:
|
| 489 |
+
self._connection.close()
|
| 490 |
+
finally:
|
| 491 |
+
if (
|
| 492 |
+
self._scratch is not None
|
| 493 |
+
and self._database_name is not None
|
| 494 |
+
):
|
| 495 |
+
self._scratch.release_database(self._database_name)
|
| 496 |
+
|
| 497 |
+
def category_children_for(
|
| 498 |
+
self, titles: Iterable[str]
|
| 499 |
+
) -> dict[str, tuple[str, ...]]:
|
| 500 |
+
"""Return direct category children for bounded title batches."""
|
| 501 |
+
|
| 502 |
+
rows = _execute_in_batches(
|
| 503 |
+
self._connection,
|
| 504 |
+
"SELECT DISTINCT parent.title, child.title "
|
| 505 |
+
"FROM target AS parent "
|
| 506 |
+
"JOIN category_link AS link ON link.target_id = parent.target_id "
|
| 507 |
+
"JOIN page AS child ON child.page_id = link.source_page_id "
|
| 508 |
+
"WHERE parent.namespace = 14 AND child.namespace = 14 "
|
| 509 |
+
"AND parent.title IN ({}) "
|
| 510 |
+
"ORDER BY parent.title, child.title",
|
| 511 |
+
titles,
|
| 512 |
+
)
|
| 513 |
+
return _group_rows(rows)
|
| 514 |
+
|
| 515 |
+
def category_qids_for_titles(self, titles: Iterable[str]) -> dict[str, str]:
|
| 516 |
+
"""Return title-to-QID pairs for bounded category title batches."""
|
| 517 |
+
|
| 518 |
+
return dict(
|
| 519 |
+
_execute_in_batches(
|
| 520 |
+
self._connection,
|
| 521 |
+
"SELECT page.title, property.value FROM page JOIN property "
|
| 522 |
+
"ON property.page_id = page.page_id "
|
| 523 |
+
"WHERE page.namespace = 14 AND property.name = 'wikibase_item' "
|
| 524 |
+
"AND page.title IN ({}) ORDER BY page.title",
|
| 525 |
+
titles,
|
| 526 |
+
)
|
| 527 |
+
)
|
| 528 |
+
|
| 529 |
+
def category_titles_for_qids(self, qids: Iterable[str]) -> dict[str, str]:
|
| 530 |
+
"""Return localized category titles whose QIDs are requested."""
|
| 531 |
+
|
| 532 |
+
return {
|
| 533 |
+
title: qid
|
| 534 |
+
for title, qid in _execute_in_batches(
|
| 535 |
+
self._connection,
|
| 536 |
+
"SELECT page.title, property.value FROM page JOIN property "
|
| 537 |
+
"ON property.page_id = page.page_id "
|
| 538 |
+
"WHERE page.namespace = 14 AND property.name = 'wikibase_item' "
|
| 539 |
+
"AND property.value IN ({}) ORDER BY page.title",
|
| 540 |
+
qids,
|
| 541 |
+
)
|
| 542 |
+
}
|
| 543 |
+
|
| 544 |
+
def article_category_titles(
|
| 545 |
+
self, page_ids: Iterable[int]
|
| 546 |
+
) -> dict[int, tuple[str, ...]]:
|
| 547 |
+
"""Return direct category titles for bounded article batches."""
|
| 548 |
+
|
| 549 |
+
rows = _execute_in_batches(
|
| 550 |
+
self._connection,
|
| 551 |
+
"SELECT DISTINCT link.source_page_id, category.title "
|
| 552 |
+
"FROM resolved_category_link AS link "
|
| 553 |
+
"JOIN page AS category ON category.page_id = link.target_page_id "
|
| 554 |
+
"WHERE link.source_namespace = 0 AND link.source_page_id IN ({}) "
|
| 555 |
+
"ORDER BY link.source_page_id, category.title",
|
| 556 |
+
page_ids,
|
| 557 |
+
)
|
| 558 |
+
return _group_rows(rows)
|
| 559 |
+
|
| 560 |
+
def article_metadata(
|
| 561 |
+
self, page_ids: Iterable[int]
|
| 562 |
+
) -> dict[int, tuple[str, int | None, bool]]:
|
| 563 |
+
"""Return canonical title, latest revision, and redirect state."""
|
| 564 |
+
|
| 565 |
+
return {
|
| 566 |
+
page_id: (
|
| 567 |
+
title.replace("_", " "),
|
| 568 |
+
latest_revision_id,
|
| 569 |
+
bool(is_redirect),
|
| 570 |
+
)
|
| 571 |
+
for page_id, title, latest_revision_id, is_redirect in _execute_in_batches(
|
| 572 |
+
self._connection,
|
| 573 |
+
"SELECT page_id, title, latest_revision_id, is_redirect FROM page "
|
| 574 |
+
"WHERE namespace = 0 AND page_id IN ({}) ORDER BY page_id",
|
| 575 |
+
page_ids,
|
| 576 |
+
)
|
| 577 |
+
}
|
| 578 |
+
|
| 579 |
+
def article_category_target_titles(
|
| 580 |
+
self, page_ids: Iterable[int]
|
| 581 |
+
) -> dict[int, tuple[str, ...]]:
|
| 582 |
+
"""Return direct category-link titles, including category redlinks."""
|
| 583 |
+
|
| 584 |
+
rows = _execute_in_batches(
|
| 585 |
+
self._connection,
|
| 586 |
+
"SELECT DISTINCT link.source_page_id, target.title "
|
| 587 |
+
"FROM category_link AS link "
|
| 588 |
+
"JOIN page AS source ON source.page_id = link.source_page_id "
|
| 589 |
+
"JOIN target ON target.target_id = link.target_id "
|
| 590 |
+
"WHERE source.namespace = 0 AND target.namespace = 14 "
|
| 591 |
+
"AND link.source_page_id IN ({}) "
|
| 592 |
+
"ORDER BY link.source_page_id, target.title",
|
| 593 |
+
page_ids,
|
| 594 |
+
)
|
| 595 |
+
return _group_rows(rows)
|
| 596 |
+
|
| 597 |
+
def hidden_category_titles(self) -> frozenset[str]:
|
| 598 |
+
"""Return titles of the explicitly marked hidden categories."""
|
| 599 |
+
|
| 600 |
+
return frozenset(
|
| 601 |
+
row[0]
|
| 602 |
+
for row in self._connection.execute(
|
| 603 |
+
"SELECT page.title FROM page JOIN property "
|
| 604 |
+
"ON property.page_id = page.page_id "
|
| 605 |
+
"WHERE page.namespace = 14 AND property.name = 'hiddencat' "
|
| 606 |
+
"ORDER BY page.title"
|
| 607 |
+
)
|
| 608 |
+
)
|
| 609 |
+
|
| 610 |
+
def redirect_category_titles(self) -> frozenset[str]:
|
| 611 |
+
"""Return canonical titles of category redirect pages."""
|
| 612 |
+
|
| 613 |
+
return frozenset(
|
| 614 |
+
row[0]
|
| 615 |
+
for row in self._connection.execute(
|
| 616 |
+
"SELECT title FROM page WHERE namespace = 14 AND is_redirect = 1 "
|
| 617 |
+
"ORDER BY title"
|
| 618 |
+
)
|
| 619 |
+
)
|
| 620 |
+
|
| 621 |
+
|
| 622 |
+
@dataclass(frozen=True, slots=True)
|
| 623 |
+
class QualityCategoryConfig:
|
| 624 |
+
"""Caller-supplied quality and delisted category definitions.
|
| 625 |
+
|
| 626 |
+
Parameters
|
| 627 |
+
----------
|
| 628 |
+
statuses_by_title
|
| 629 |
+
Category title to output status label. This can represent any language
|
| 630 |
+
edition without embedding language-specific titles in the library.
|
| 631 |
+
excluded_titles
|
| 632 |
+
Former or delisted category titles. Membership in any one of these
|
| 633 |
+
categories always excludes an article.
|
| 634 |
+
"""
|
| 635 |
+
|
| 636 |
+
statuses_by_title: Mapping[str, str]
|
| 637 |
+
excluded_titles: frozenset[str]
|
| 638 |
+
|
| 639 |
+
|
| 640 |
+
@dataclass(frozen=True, slots=True)
|
| 641 |
+
class QualityArticle:
|
| 642 |
+
"""A selected quality article and its configured statuses.
|
| 643 |
+
|
| 644 |
+
Parameters
|
| 645 |
+
----------
|
| 646 |
+
page_id
|
| 647 |
+
Namespace-0 page identifier.
|
| 648 |
+
statuses
|
| 649 |
+
Sorted, unique configured status labels.
|
| 650 |
+
"""
|
| 651 |
+
|
| 652 |
+
page_id: int
|
| 653 |
+
statuses: tuple[str, ...]
|
| 654 |
+
|
| 655 |
+
|
| 656 |
+
class _SqliteScalarMapping(MappingABC):
|
| 657 |
+
"""Read-only scalar mapping backed by a temporary SQLite database."""
|
| 658 |
+
|
| 659 |
+
def __init__(
|
| 660 |
+
self, connection: sqlite3.Connection, items_sql: str, value_sql: str
|
| 661 |
+
) -> None:
|
| 662 |
+
self._connection = connection
|
| 663 |
+
self._items_sql = items_sql
|
| 664 |
+
self._value_sql = value_sql
|
| 665 |
+
|
| 666 |
+
def __iter__(self) -> Iterator[object]:
|
| 667 |
+
return (row[0] for row in self._connection.execute(self._items_sql))
|
| 668 |
+
|
| 669 |
+
def __len__(self) -> int:
|
| 670 |
+
return self._connection.execute(
|
| 671 |
+
f"SELECT COUNT(*) FROM ({self._items_sql})"
|
| 672 |
+
).fetchone()[0]
|
| 673 |
+
|
| 674 |
+
def __getitem__(self, key: object) -> object:
|
| 675 |
+
row = self._connection.execute(self._value_sql, (key,)).fetchone()
|
| 676 |
+
if row is None:
|
| 677 |
+
raise KeyError(key)
|
| 678 |
+
return row[0]
|
| 679 |
+
|
| 680 |
+
def items(self) -> Iterator[tuple[object, object]]:
|
| 681 |
+
"""Yield key-value pairs without materializing the mapping."""
|
| 682 |
+
|
| 683 |
+
return iter(self._connection.execute(self._items_sql))
|
| 684 |
+
|
| 685 |
+
|
| 686 |
+
class _SqliteTupleMapping(MappingABC):
|
| 687 |
+
"""Read-only one-to-many mapping backed by a SQLite query."""
|
| 688 |
+
|
| 689 |
+
def __init__(self, connection: sqlite3.Connection, pairs_sql: str) -> None:
|
| 690 |
+
self._connection = connection
|
| 691 |
+
self._pairs_sql = pairs_sql
|
| 692 |
+
|
| 693 |
+
def __iter__(self) -> Iterator[int]:
|
| 694 |
+
query = f"SELECT DISTINCT key FROM ({self._pairs_sql}) ORDER BY key"
|
| 695 |
+
return (row[0] for row in self._connection.execute(query))
|
| 696 |
+
|
| 697 |
+
def __len__(self) -> int:
|
| 698 |
+
query = f"SELECT COUNT(DISTINCT key) FROM ({self._pairs_sql})"
|
| 699 |
+
return self._connection.execute(query).fetchone()[0]
|
| 700 |
+
|
| 701 |
+
def __getitem__(self, key: object) -> tuple[int, ...]:
|
| 702 |
+
query = (
|
| 703 |
+
f"SELECT DISTINCT value FROM ({self._pairs_sql}) "
|
| 704 |
+
"WHERE key = ? ORDER BY value"
|
| 705 |
+
)
|
| 706 |
+
values = tuple(row[0] for row in self._connection.execute(query, (key,)))
|
| 707 |
+
if not values:
|
| 708 |
+
raise KeyError(key)
|
| 709 |
+
return values
|
| 710 |
+
|
| 711 |
+
def items(self) -> Iterator[tuple[int, tuple[int, ...]]]:
|
| 712 |
+
"""Yield grouped membership pairs without materializing all groups."""
|
| 713 |
+
|
| 714 |
+
rows = self._connection.execute(
|
| 715 |
+
f"SELECT DISTINCT key, value FROM ({self._pairs_sql}) ORDER BY key, value"
|
| 716 |
+
)
|
| 717 |
+
current_key: object | None = None
|
| 718 |
+
values: list[object] = []
|
| 719 |
+
for key, value in rows:
|
| 720 |
+
if current_key is not None and key != current_key:
|
| 721 |
+
yield current_key, tuple(values)
|
| 722 |
+
values = []
|
| 723 |
+
current_key = key
|
| 724 |
+
values.append(value)
|
| 725 |
+
if current_key is not None:
|
| 726 |
+
yield current_key, tuple(values)
|
| 727 |
+
|
| 728 |
+
|
| 729 |
+
class _SqliteSet(SetABC):
|
| 730 |
+
"""Read-only set backed by a single-column SQLite query."""
|
| 731 |
+
|
| 732 |
+
def __init__(self, connection: sqlite3.Connection, values_sql: str) -> None:
|
| 733 |
+
self._connection = connection
|
| 734 |
+
self._values_sql = values_sql
|
| 735 |
+
|
| 736 |
+
def __contains__(self, value: object) -> bool:
|
| 737 |
+
query = f"SELECT 1 FROM ({self._values_sql}) WHERE page_id = ? LIMIT 1"
|
| 738 |
+
return self._connection.execute(query, (value,)).fetchone() is not None
|
| 739 |
+
|
| 740 |
+
def __iter__(self) -> Iterator[int]:
|
| 741 |
+
return (row[0] for row in self._connection.execute(self._values_sql))
|
| 742 |
+
|
| 743 |
+
def __len__(self) -> int:
|
| 744 |
+
return self._connection.execute(
|
| 745 |
+
f"SELECT COUNT(*) FROM ({self._values_sql})"
|
| 746 |
+
).fetchone()[0]
|
| 747 |
+
|
| 748 |
+
|
| 749 |
+
def _execute_in_batches(
|
| 750 |
+
connection: sqlite3.Connection,
|
| 751 |
+
query: str,
|
| 752 |
+
values: Iterable[object],
|
| 753 |
+
) -> Iterator[tuple[object, ...]]:
|
| 754 |
+
"""Execute an ``IN`` query over deterministic SQLite-sized batches."""
|
| 755 |
+
|
| 756 |
+
ordered = tuple(sorted(set(values)))
|
| 757 |
+
for offset in range(0, len(ordered), _SQLITE_BATCH_SIZE):
|
| 758 |
+
batch = ordered[offset : offset + _SQLITE_BATCH_SIZE]
|
| 759 |
+
placeholders = ", ".join("?" for _ in batch)
|
| 760 |
+
yield from connection.execute(query.format(placeholders), batch)
|
| 761 |
+
|
| 762 |
+
|
| 763 |
+
def _group_rows(
|
| 764 |
+
rows: Iterable[tuple[object, object]],
|
| 765 |
+
) -> dict[object, tuple[object, ...]]:
|
| 766 |
+
"""Group already ordered key-value rows without retaining flat rows."""
|
| 767 |
+
|
| 768 |
+
grouped: dict[object, list[object]] = {}
|
| 769 |
+
for key, value in rows:
|
| 770 |
+
grouped.setdefault(key, []).append(value)
|
| 771 |
+
return {key: tuple(values) for key, values in grouped.items()}
|
| 772 |
+
|
| 773 |
+
|
| 774 |
+
def iter_insert_rows(source: Iterable[str], table: str) -> Iterator[tuple[SqlValue, ...]]:
|
| 775 |
+
"""Yield rows from ``INSERT INTO`` statements for one Wikimedia table.
|
| 776 |
+
|
| 777 |
+
The parser consumes the input incrementally and implements the MySQL string
|
| 778 |
+
escapes used by Wikimedia dumps. It does not load an INSERT statement into
|
| 779 |
+
memory as a whole.
|
| 780 |
+
|
| 781 |
+
Parameters
|
| 782 |
+
----------
|
| 783 |
+
source
|
| 784 |
+
Text chunks or lines from an uncompressed SQL dump.
|
| 785 |
+
table
|
| 786 |
+
Exact table name to select.
|
| 787 |
+
|
| 788 |
+
Yields
|
| 789 |
+
------
|
| 790 |
+
tuple of str, int, float, or None
|
| 791 |
+
Parsed SQL row values.
|
| 792 |
+
|
| 793 |
+
Raises
|
| 794 |
+
------
|
| 795 |
+
ValueError
|
| 796 |
+
If a selected INSERT statement has malformed row syntax.
|
| 797 |
+
"""
|
| 798 |
+
|
| 799 |
+
tokens = iter(_iter_tokens(source))
|
| 800 |
+
for kind, value in tokens:
|
| 801 |
+
if kind != "WORD" or str(value).upper() != "INSERT":
|
| 802 |
+
continue
|
| 803 |
+
into = next(tokens, None)
|
| 804 |
+
table_token = next(tokens, None)
|
| 805 |
+
values = next(tokens, None)
|
| 806 |
+
if (
|
| 807 |
+
into is None
|
| 808 |
+
or into[0] != "WORD"
|
| 809 |
+
or str(into[1]).upper() != "INTO"
|
| 810 |
+
or table_token is None
|
| 811 |
+
or table_token[0] not in {"WORD", "IDENT"}
|
| 812 |
+
or values is None
|
| 813 |
+
or values[0] != "WORD"
|
| 814 |
+
or str(values[1]).upper() != "VALUES"
|
| 815 |
+
):
|
| 816 |
+
continue
|
| 817 |
+
if table_token[1] != table:
|
| 818 |
+
continue
|
| 819 |
+
yield from _iter_statement_rows(tokens)
|
| 820 |
+
|
| 821 |
+
|
| 822 |
+
def iter_pages(source: Iterable[str]) -> Iterator[Page]:
|
| 823 |
+
"""Yield normalized records from a Wikimedia ``page`` SQL dump.
|
| 824 |
+
|
| 825 |
+
Parameters
|
| 826 |
+
----------
|
| 827 |
+
source
|
| 828 |
+
Text chunks or lines from the dump.
|
| 829 |
+
|
| 830 |
+
Yields
|
| 831 |
+
------
|
| 832 |
+
Page
|
| 833 |
+
Page identifier, namespace, and title.
|
| 834 |
+
"""
|
| 835 |
+
|
| 836 |
+
for row in _iter_validated_rows(
|
| 837 |
+
source, "page", _PAGE_COLUMNS, select_by_name=True
|
| 838 |
+
):
|
| 839 |
+
if len(row) < 3:
|
| 840 |
+
raise ValueError(
|
| 841 |
+
f"page row has {len(row)} values; expected at least 3"
|
| 842 |
+
)
|
| 843 |
+
yield Page(int(row[0]), int(row[1]), str(row[2]))
|
| 844 |
+
|
| 845 |
+
|
| 846 |
+
def iter_pages_with_metadata(source: Iterable[str]) -> Iterator[Page]:
|
| 847 |
+
"""Yield pages with redirect state and latest revision metadata."""
|
| 848 |
+
|
| 849 |
+
for row in _iter_validated_rows(
|
| 850 |
+
source, "page", _PAGE_METADATA_COLUMNS, select_by_name=True
|
| 851 |
+
):
|
| 852 |
+
is_redirect = row[3]
|
| 853 |
+
latest_revision_id = row[4]
|
| 854 |
+
if is_redirect not in {0, 1}:
|
| 855 |
+
raise ValueError(f"invalid page_is_redirect value: {is_redirect!r}")
|
| 856 |
+
if (
|
| 857 |
+
isinstance(latest_revision_id, bool)
|
| 858 |
+
or not isinstance(latest_revision_id, int)
|
| 859 |
+
or latest_revision_id <= 0
|
| 860 |
+
):
|
| 861 |
+
latest_revision_id = None
|
| 862 |
+
yield Page(
|
| 863 |
+
int(row[0]),
|
| 864 |
+
int(row[1]),
|
| 865 |
+
str(row[2]),
|
| 866 |
+
bool(is_redirect),
|
| 867 |
+
latest_revision_id,
|
| 868 |
+
)
|
| 869 |
+
|
| 870 |
+
|
| 871 |
+
def iter_page_props(source: Iterable[str]) -> Iterator[PageProp]:
|
| 872 |
+
"""Yield normalized records from a Wikimedia ``page_props`` SQL dump.
|
| 873 |
+
|
| 874 |
+
Parameters
|
| 875 |
+
----------
|
| 876 |
+
source
|
| 877 |
+
Text chunks or lines from the dump.
|
| 878 |
+
|
| 879 |
+
Yields
|
| 880 |
+
------
|
| 881 |
+
PageProp
|
| 882 |
+
Page identifier, property name, and nullable value.
|
| 883 |
+
"""
|
| 884 |
+
|
| 885 |
+
for row in _iter_validated_rows(source, "page_props", _PAGE_PROPS_COLUMNS):
|
| 886 |
+
if len(row) < 3:
|
| 887 |
+
raise ValueError(
|
| 888 |
+
f"page_props row has {len(row)} values; expected at least 3"
|
| 889 |
+
)
|
| 890 |
+
value = row[2]
|
| 891 |
+
yield PageProp(int(row[0]), str(row[1]), None if value is None else str(value))
|
| 892 |
+
|
| 893 |
+
|
| 894 |
+
def iter_category_links(source: Iterable[str]) -> Iterator[CategoryLink]:
|
| 895 |
+
"""Yield normalized records from a Wikimedia ``categorylinks`` SQL dump.
|
| 896 |
+
|
| 897 |
+
Parameters
|
| 898 |
+
----------
|
| 899 |
+
source
|
| 900 |
+
Text chunks or lines from the dump.
|
| 901 |
+
|
| 902 |
+
Yields
|
| 903 |
+
------
|
| 904 |
+
CategoryLink
|
| 905 |
+
Source page identifier, target category title, and optional link type.
|
| 906 |
+
"""
|
| 907 |
+
|
| 908 |
+
for row in _iter_validated_rows(
|
| 909 |
+
source, "categorylinks", _CATEGORYLINKS_COLUMNS, exact=True
|
| 910 |
+
):
|
| 911 |
+
if len(row) != 7:
|
| 912 |
+
raise ValueError(
|
| 913 |
+
f"categorylinks row has {len(row)} values; expected exactly 7"
|
| 914 |
+
)
|
| 915 |
+
yield CategoryLink(int(row[0]), str(row[4]), int(row[6]))
|
| 916 |
+
|
| 917 |
+
|
| 918 |
+
def iter_link_targets(source: Iterable[str]) -> Iterator[LinkTarget]:
|
| 919 |
+
"""Yield normalized records from a Wikimedia ``linktarget`` SQL dump.
|
| 920 |
+
|
| 921 |
+
Parameters
|
| 922 |
+
----------
|
| 923 |
+
source
|
| 924 |
+
Text chunks or lines from the dump.
|
| 925 |
+
|
| 926 |
+
Yields
|
| 927 |
+
------
|
| 928 |
+
LinkTarget
|
| 929 |
+
Link-target identifier, namespace, and title.
|
| 930 |
+
"""
|
| 931 |
+
|
| 932 |
+
for row in _iter_validated_rows(
|
| 933 |
+
source, "linktarget", _LINKTARGET_COLUMNS, exact=True
|
| 934 |
+
):
|
| 935 |
+
if len(row) != 3:
|
| 936 |
+
raise ValueError(
|
| 937 |
+
f"linktarget row has {len(row)} values; expected exactly 3"
|
| 938 |
+
)
|
| 939 |
+
yield LinkTarget(int(row[0]), int(row[1]), str(row[2]))
|
| 940 |
+
|
| 941 |
+
|
| 942 |
+
def build_metadata_indexes(
|
| 943 |
+
pages: Iterable[Page],
|
| 944 |
+
page_props: Iterable[PageProp],
|
| 945 |
+
category_links: Iterable[CategoryLink],
|
| 946 |
+
link_targets: Iterable[LinkTarget],
|
| 947 |
+
*,
|
| 948 |
+
max_database_bytes: int | None = None,
|
| 949 |
+
scratch: WikiMetadataScratch | None = None,
|
| 950 |
+
database_name: str = "metadata.sqlite3",
|
| 951 |
+
) -> WikiMetadataIndexes:
|
| 952 |
+
"""Build category, Wikidata, hidden-category, and membership indexes.
|
| 953 |
+
|
| 954 |
+
Category graph edges point from a category page to its parent categories.
|
| 955 |
+
Links whose target category page is absent from ``pages`` are ignored
|
| 956 |
+
because they cannot be represented by a page identifier.
|
| 957 |
+
|
| 958 |
+
Parameters
|
| 959 |
+
----------
|
| 960 |
+
pages
|
| 961 |
+
Normalized page records.
|
| 962 |
+
page_props
|
| 963 |
+
Normalized page property records.
|
| 964 |
+
category_links
|
| 965 |
+
Normalized category link records.
|
| 966 |
+
link_targets
|
| 967 |
+
Normalized link-target records used to resolve category targets.
|
| 968 |
+
max_database_bytes
|
| 969 |
+
Optional hard ceiling for the temporary SQLite database.
|
| 970 |
+
scratch
|
| 971 |
+
Caller-owned namespace for an explicit disk-backed database. When
|
| 972 |
+
omitted, the index remains in memory for small library and test callers.
|
| 973 |
+
database_name
|
| 974 |
+
Exclusive basename inside ``scratch``.
|
| 975 |
+
|
| 976 |
+
Returns
|
| 977 |
+
-------
|
| 978 |
+
WikiMetadataIndexes
|
| 979 |
+
Deterministically ordered mappings and set-like indexes.
|
| 980 |
+
"""
|
| 981 |
+
|
| 982 |
+
connection: sqlite3.Connection | None = None
|
| 983 |
+
database_created = False
|
| 984 |
+
try:
|
| 985 |
+
if scratch is not None:
|
| 986 |
+
database_target = scratch.create_database(database_name)
|
| 987 |
+
database_created = True
|
| 988 |
+
connection = sqlite3.connect(database_target)
|
| 989 |
+
connection.set_progress_handler(scratch.progress, 100_000)
|
| 990 |
+
else:
|
| 991 |
+
connection = sqlite3.connect(":memory:")
|
| 992 |
+
except BaseException:
|
| 993 |
+
try:
|
| 994 |
+
if connection is not None:
|
| 995 |
+
connection.close()
|
| 996 |
+
finally:
|
| 997 |
+
if scratch is not None and database_created:
|
| 998 |
+
scratch.release_database(database_name)
|
| 999 |
+
raise
|
| 1000 |
+
assert connection is not None
|
| 1001 |
+
scratch_bytes = 0
|
| 1002 |
+
try:
|
| 1003 |
+
connection.execute(
|
| 1004 |
+
f"PRAGMA temp_store={'FILE' if scratch is not None else 'MEMORY'}"
|
| 1005 |
+
)
|
| 1006 |
+
if max_database_bytes is not None:
|
| 1007 |
+
page_size = connection.execute("PRAGMA page_size").fetchone()[0]
|
| 1008 |
+
max_pages = max_database_bytes // page_size
|
| 1009 |
+
if max_pages < 1:
|
| 1010 |
+
raise ValueError(
|
| 1011 |
+
"SQLite metadata index has less than one page of disk budget"
|
| 1012 |
+
)
|
| 1013 |
+
connection.execute(f"PRAGMA max_page_count = {max_pages}")
|
| 1014 |
+
connection.executescript(
|
| 1015 |
+
"""
|
| 1016 |
+
PRAGMA journal_mode=OFF;
|
| 1017 |
+
PRAGMA synchronous=OFF;
|
| 1018 |
+
CREATE TABLE page (
|
| 1019 |
+
page_id INTEGER PRIMARY KEY,
|
| 1020 |
+
namespace INTEGER NOT NULL,
|
| 1021 |
+
title TEXT NOT NULL,
|
| 1022 |
+
is_redirect INTEGER NOT NULL,
|
| 1023 |
+
latest_revision_id INTEGER,
|
| 1024 |
+
UNIQUE (namespace, title)
|
| 1025 |
+
);
|
| 1026 |
+
CREATE TABLE property (
|
| 1027 |
+
page_id INTEGER NOT NULL,
|
| 1028 |
+
name TEXT NOT NULL,
|
| 1029 |
+
value TEXT,
|
| 1030 |
+
PRIMARY KEY (page_id, name)
|
| 1031 |
+
);
|
| 1032 |
+
CREATE TABLE target (
|
| 1033 |
+
target_id INTEGER PRIMARY KEY,
|
| 1034 |
+
namespace INTEGER NOT NULL,
|
| 1035 |
+
title TEXT NOT NULL
|
| 1036 |
+
);
|
| 1037 |
+
CREATE TABLE category_link (
|
| 1038 |
+
source_page_id INTEGER NOT NULL,
|
| 1039 |
+
target_id INTEGER NOT NULL,
|
| 1040 |
+
link_type TEXT NOT NULL
|
| 1041 |
+
);
|
| 1042 |
+
"""
|
| 1043 |
+
)
|
| 1044 |
+
scratch_bytes = _database_bytes(connection)
|
| 1045 |
+
connection.executemany(
|
| 1046 |
+
"INSERT INTO page VALUES (?, ?, ?, ?, ?)",
|
| 1047 |
+
(
|
| 1048 |
+
(
|
| 1049 |
+
page.page_id,
|
| 1050 |
+
page.namespace,
|
| 1051 |
+
page.title,
|
| 1052 |
+
int(page.is_redirect),
|
| 1053 |
+
page.latest_revision_id,
|
| 1054 |
+
)
|
| 1055 |
+
for page in pages
|
| 1056 |
+
if page.namespace in {0, 14}
|
| 1057 |
+
),
|
| 1058 |
+
)
|
| 1059 |
+
connection.executemany(
|
| 1060 |
+
"INSERT INTO property VALUES (?, ?, ?)",
|
| 1061 |
+
(
|
| 1062 |
+
(prop.page_id, prop.name, prop.value)
|
| 1063 |
+
for prop in page_props
|
| 1064 |
+
if prop.name in {"disambiguation", "hiddencat"}
|
| 1065 |
+
or (prop.name == "wikibase_item" and prop.value is not None)
|
| 1066 |
+
),
|
| 1067 |
+
)
|
| 1068 |
+
connection.executemany(
|
| 1069 |
+
"INSERT INTO target VALUES (?, ?, ?)",
|
| 1070 |
+
(
|
| 1071 |
+
(target.target_id, target.namespace, target.title)
|
| 1072 |
+
for target in link_targets
|
| 1073 |
+
if target.namespace == 14
|
| 1074 |
+
),
|
| 1075 |
+
)
|
| 1076 |
+
connection.executemany(
|
| 1077 |
+
"INSERT INTO category_link VALUES (?, ?, ?)",
|
| 1078 |
+
(
|
| 1079 |
+
(link.source_page_id, link.target_id, link.link_type)
|
| 1080 |
+
for link in category_links
|
| 1081 |
+
),
|
| 1082 |
+
)
|
| 1083 |
+
connection.executescript(
|
| 1084 |
+
"""
|
| 1085 |
+
CREATE INDEX page_namespace_title ON page(namespace, title);
|
| 1086 |
+
CREATE INDEX property_name_page ON property(name, page_id);
|
| 1087 |
+
CREATE INDEX target_namespace_title ON target(namespace, title);
|
| 1088 |
+
CREATE INDEX category_link_source ON category_link(source_page_id);
|
| 1089 |
+
CREATE INDEX category_link_target ON category_link(target_id);
|
| 1090 |
+
CREATE VIEW resolved_category_link AS
|
| 1091 |
+
SELECT link.source_page_id, source.namespace AS source_namespace,
|
| 1092 |
+
category.page_id AS target_page_id
|
| 1093 |
+
FROM category_link AS link
|
| 1094 |
+
JOIN page AS source ON source.page_id = link.source_page_id
|
| 1095 |
+
JOIN target ON target.target_id = link.target_id
|
| 1096 |
+
AND target.namespace = 14
|
| 1097 |
+
JOIN page AS category ON category.namespace = 14
|
| 1098 |
+
AND category.title = target.title;
|
| 1099 |
+
"""
|
| 1100 |
+
)
|
| 1101 |
+
connection.commit()
|
| 1102 |
+
if scratch is not None:
|
| 1103 |
+
scratch.observe()
|
| 1104 |
+
except sqlite3.Error as error:
|
| 1105 |
+
accounting_error: OSError | None = None
|
| 1106 |
+
try:
|
| 1107 |
+
connection.rollback()
|
| 1108 |
+
except sqlite3.Error:
|
| 1109 |
+
pass
|
| 1110 |
+
if scratch is not None:
|
| 1111 |
+
try:
|
| 1112 |
+
scratch.observe()
|
| 1113 |
+
except _MetadataIndexError:
|
| 1114 |
+
pass
|
| 1115 |
+
except OSError as observe_error:
|
| 1116 |
+
accounting_error = observe_error
|
| 1117 |
+
try:
|
| 1118 |
+
scratch_bytes = max(
|
| 1119 |
+
scratch_bytes,
|
| 1120 |
+
scratch.main_database_bytes
|
| 1121 |
+
if scratch is not None
|
| 1122 |
+
else _database_bytes(connection),
|
| 1123 |
+
)
|
| 1124 |
+
except sqlite3.Error:
|
| 1125 |
+
pass
|
| 1126 |
+
cleanup_errors: list[BaseException] = []
|
| 1127 |
+
try:
|
| 1128 |
+
connection.close()
|
| 1129 |
+
except BaseException as cleanup_error:
|
| 1130 |
+
cleanup_errors.append(cleanup_error)
|
| 1131 |
+
if scratch is not None:
|
| 1132 |
+
try:
|
| 1133 |
+
scratch.release_database(database_name)
|
| 1134 |
+
except BaseException as cleanup_error:
|
| 1135 |
+
cleanup_errors.append(cleanup_error)
|
| 1136 |
+
if (
|
| 1137 |
+
max_database_bytes is not None
|
| 1138 |
+
and getattr(error, "sqlite_errorcode", None) == sqlite3.SQLITE_FULL
|
| 1139 |
+
):
|
| 1140 |
+
index_error = _MetadataIndexError(
|
| 1141 |
+
"SQLite metadata index exceeded its "
|
| 1142 |
+
f"{max_database_bytes}-byte disk ceiling",
|
| 1143 |
+
scratch_bytes,
|
| 1144 |
+
)
|
| 1145 |
+
elif scratch is not None and scratch.exceeded:
|
| 1146 |
+
index_error = _MetadataIndexError(
|
| 1147 |
+
"observed SQLite scratch bytes exceeded the "
|
| 1148 |
+
f"{scratch.ceiling_bytes}-byte disk ceiling",
|
| 1149 |
+
scratch_bytes,
|
| 1150 |
+
)
|
| 1151 |
+
else:
|
| 1152 |
+
index_error = _MetadataIndexError(
|
| 1153 |
+
f"SQLite metadata indexing failed: {error}", scratch_bytes
|
| 1154 |
+
)
|
| 1155 |
+
if accounting_error is not None:
|
| 1156 |
+
index_error.add_note(
|
| 1157 |
+
f"SQLite scratch accounting also failed: {accounting_error}"
|
| 1158 |
+
)
|
| 1159 |
+
for cleanup_error in cleanup_errors:
|
| 1160 |
+
index_error.add_note(
|
| 1161 |
+
f"SQLite metadata cleanup also failed: {cleanup_error}"
|
| 1162 |
+
)
|
| 1163 |
+
raise index_error from error
|
| 1164 |
+
except BaseException as error:
|
| 1165 |
+
cleanup_errors = []
|
| 1166 |
+
try:
|
| 1167 |
+
connection.close()
|
| 1168 |
+
except BaseException as cleanup_error:
|
| 1169 |
+
cleanup_errors.append(cleanup_error)
|
| 1170 |
+
if scratch is not None:
|
| 1171 |
+
try:
|
| 1172 |
+
scratch.release_database(database_name)
|
| 1173 |
+
except BaseException as cleanup_error:
|
| 1174 |
+
cleanup_errors.append(cleanup_error)
|
| 1175 |
+
for cleanup_error in cleanup_errors:
|
| 1176 |
+
error.add_note(f"SQLite metadata cleanup also failed: {cleanup_error}")
|
| 1177 |
+
raise
|
| 1178 |
+
|
| 1179 |
+
return WikiMetadataIndexes(
|
| 1180 |
+
category_title_to_id=_SqliteScalarMapping(
|
| 1181 |
+
connection,
|
| 1182 |
+
"SELECT title, page_id FROM page WHERE namespace = 14 ORDER BY title",
|
| 1183 |
+
"SELECT page_id FROM page WHERE namespace = 14 AND title = ?",
|
| 1184 |
+
),
|
| 1185 |
+
category_id_to_title=_SqliteScalarMapping(
|
| 1186 |
+
connection,
|
| 1187 |
+
"SELECT page_id, title FROM page WHERE namespace = 14 ORDER BY page_id",
|
| 1188 |
+
"SELECT title FROM page WHERE namespace = 14 AND page_id = ?",
|
| 1189 |
+
),
|
| 1190 |
+
page_id_to_qid=_SqliteScalarMapping(
|
| 1191 |
+
connection,
|
| 1192 |
+
"SELECT page_id, value FROM property "
|
| 1193 |
+
"WHERE name = 'wikibase_item' ORDER BY page_id",
|
| 1194 |
+
"SELECT value FROM property WHERE name = 'wikibase_item' AND page_id = ?",
|
| 1195 |
+
),
|
| 1196 |
+
hidden_category_ids=_SqliteSet(
|
| 1197 |
+
connection,
|
| 1198 |
+
"SELECT property.page_id FROM property JOIN page "
|
| 1199 |
+
"ON page.page_id = property.page_id "
|
| 1200 |
+
"WHERE property.name = 'hiddencat' AND page.namespace = 14 "
|
| 1201 |
+
"ORDER BY property.page_id",
|
| 1202 |
+
),
|
| 1203 |
+
category_parents=_SqliteTupleMapping(
|
| 1204 |
+
connection,
|
| 1205 |
+
"SELECT source_page_id AS key, target_page_id AS value "
|
| 1206 |
+
"FROM resolved_category_link "
|
| 1207 |
+
"WHERE source_namespace = 14 ORDER BY source_page_id, target_page_id",
|
| 1208 |
+
),
|
| 1209 |
+
article_categories=_SqliteTupleMapping(
|
| 1210 |
+
connection,
|
| 1211 |
+
"SELECT source_page_id AS key, target_page_id AS value "
|
| 1212 |
+
"FROM resolved_category_link "
|
| 1213 |
+
"WHERE source_namespace = 0 ORDER BY source_page_id, target_page_id",
|
| 1214 |
+
),
|
| 1215 |
+
category_children=_SqliteTupleMapping(
|
| 1216 |
+
connection,
|
| 1217 |
+
"SELECT parent.title AS key, child.title AS value "
|
| 1218 |
+
"FROM resolved_category_link AS link "
|
| 1219 |
+
"JOIN page AS child ON child.page_id = link.source_page_id "
|
| 1220 |
+
"JOIN page AS parent ON parent.page_id = link.target_page_id "
|
| 1221 |
+
"WHERE link.source_namespace = 14 ORDER BY parent.title, child.title",
|
| 1222 |
+
),
|
| 1223 |
+
category_title_to_qid=_SqliteScalarMapping(
|
| 1224 |
+
connection,
|
| 1225 |
+
"SELECT page.title, property.value FROM page JOIN property "
|
| 1226 |
+
"ON property.page_id = page.page_id "
|
| 1227 |
+
"WHERE page.namespace = 14 AND property.name = 'wikibase_item' "
|
| 1228 |
+
"ORDER BY page.title",
|
| 1229 |
+
"SELECT property.value FROM page JOIN property "
|
| 1230 |
+
"ON property.page_id = page.page_id "
|
| 1231 |
+
"WHERE page.namespace = 14 AND property.name = 'wikibase_item' "
|
| 1232 |
+
"AND page.title = ?",
|
| 1233 |
+
),
|
| 1234 |
+
_connection=connection,
|
| 1235 |
+
_scratch=scratch,
|
| 1236 |
+
_database_name=database_name if scratch is not None else None,
|
| 1237 |
+
)
|
| 1238 |
+
|
| 1239 |
+
|
| 1240 |
+
def _database_bytes(connection: sqlite3.Connection) -> int:
|
| 1241 |
+
"""Return the allocated page bytes for one SQLite database."""
|
| 1242 |
+
|
| 1243 |
+
return (
|
| 1244 |
+
connection.execute("PRAGMA page_count").fetchone()[0]
|
| 1245 |
+
* connection.execute("PRAGMA page_size").fetchone()[0]
|
| 1246 |
+
)
|
| 1247 |
+
|
| 1248 |
+
|
| 1249 |
+
def select_quality_articles(
|
| 1250 |
+
indexes: WikiMetadataIndexes,
|
| 1251 |
+
config: QualityCategoryConfig,
|
| 1252 |
+
) -> tuple[QualityArticle, ...]:
|
| 1253 |
+
"""Select namespace-0 quality articles using direct category membership.
|
| 1254 |
+
|
| 1255 |
+
Parameters
|
| 1256 |
+
----------
|
| 1257 |
+
indexes
|
| 1258 |
+
Metadata indexes containing namespace-filtered article memberships.
|
| 1259 |
+
config
|
| 1260 |
+
Caller-supplied status and former/delisted category titles.
|
| 1261 |
+
|
| 1262 |
+
Returns
|
| 1263 |
+
-------
|
| 1264 |
+
tuple of QualityArticle
|
| 1265 |
+
Articles sorted by page identifier. Articles in any excluded category
|
| 1266 |
+
are omitted even when they also belong to a quality category.
|
| 1267 |
+
"""
|
| 1268 |
+
|
| 1269 |
+
statuses_by_id = {
|
| 1270 |
+
category_id: status
|
| 1271 |
+
for title, status in config.statuses_by_title.items()
|
| 1272 |
+
if (category_id := indexes.category_title_to_id.get(title)) is not None
|
| 1273 |
+
}
|
| 1274 |
+
excluded_ids = {
|
| 1275 |
+
category_id
|
| 1276 |
+
for title in config.excluded_titles
|
| 1277 |
+
if (category_id := indexes.category_title_to_id.get(title)) is not None
|
| 1278 |
+
}
|
| 1279 |
+
relevant_ids = set(statuses_by_id) | excluded_ids
|
| 1280 |
+
if not relevant_ids:
|
| 1281 |
+
return ()
|
| 1282 |
+
placeholders = ", ".join("?" for _ in relevant_ids)
|
| 1283 |
+
rows = indexes._connection.execute(
|
| 1284 |
+
"SELECT link.source_page_id, link.target_page_id "
|
| 1285 |
+
"FROM resolved_category_link AS link "
|
| 1286 |
+
"JOIN page AS source ON source.page_id = link.source_page_id "
|
| 1287 |
+
f"WHERE link.source_namespace = 0 AND source.is_redirect = 0 "
|
| 1288 |
+
"AND NOT EXISTS (SELECT 1 FROM property AS property "
|
| 1289 |
+
"WHERE property.page_id = source.page_id "
|
| 1290 |
+
"AND property.name = 'disambiguation') "
|
| 1291 |
+
f"AND link.target_page_id IN ({placeholders}) "
|
| 1292 |
+
"ORDER BY source_page_id, target_page_id",
|
| 1293 |
+
tuple(sorted(relevant_ids)),
|
| 1294 |
+
)
|
| 1295 |
+
selected: list[QualityArticle] = []
|
| 1296 |
+
page_id: int | None = None
|
| 1297 |
+
category_ids: set[int] = set()
|
| 1298 |
+
for current_page_id, category_id in rows:
|
| 1299 |
+
if page_id is not None and current_page_id != page_id:
|
| 1300 |
+
_append_quality_article(
|
| 1301 |
+
selected, page_id, category_ids, statuses_by_id, excluded_ids
|
| 1302 |
+
)
|
| 1303 |
+
category_ids = set()
|
| 1304 |
+
page_id = current_page_id
|
| 1305 |
+
category_ids.add(category_id)
|
| 1306 |
+
if page_id is not None:
|
| 1307 |
+
_append_quality_article(
|
| 1308 |
+
selected, page_id, category_ids, statuses_by_id, excluded_ids
|
| 1309 |
+
)
|
| 1310 |
+
return tuple(selected)
|
| 1311 |
+
|
| 1312 |
+
|
| 1313 |
+
def _append_quality_article(
|
| 1314 |
+
selected: list[QualityArticle],
|
| 1315 |
+
page_id: int,
|
| 1316 |
+
category_ids: set[int],
|
| 1317 |
+
statuses_by_id: Mapping[int, str],
|
| 1318 |
+
excluded_ids: set[int],
|
| 1319 |
+
) -> None:
|
| 1320 |
+
"""Append one eligible article to an ordered quality result."""
|
| 1321 |
+
|
| 1322 |
+
if excluded_ids.intersection(category_ids):
|
| 1323 |
+
return
|
| 1324 |
+
statuses = tuple(
|
| 1325 |
+
sorted(
|
| 1326 |
+
{statuses_by_id[item] for item in category_ids if item in statuses_by_id}
|
| 1327 |
+
)
|
| 1328 |
+
)
|
| 1329 |
+
if statuses:
|
| 1330 |
+
selected.append(QualityArticle(page_id, statuses))
|
| 1331 |
+
|
| 1332 |
+
|
| 1333 |
+
def _iter_tokens(source: Iterable[str]) -> Iterator[_Token]:
|
| 1334 |
+
characters = (character for chunk in source for character in chunk)
|
| 1335 |
+
pending: str | None = None
|
| 1336 |
+
while True:
|
| 1337 |
+
if pending is None:
|
| 1338 |
+
character = next(characters, None)
|
| 1339 |
+
else:
|
| 1340 |
+
character, pending = pending, None
|
| 1341 |
+
if character is None:
|
| 1342 |
+
return
|
| 1343 |
+
if character.isspace():
|
| 1344 |
+
continue
|
| 1345 |
+
if character in "(),;":
|
| 1346 |
+
yield "SYMBOL", character
|
| 1347 |
+
continue
|
| 1348 |
+
if character == "`":
|
| 1349 |
+
identifier: list[str] = []
|
| 1350 |
+
for character in characters:
|
| 1351 |
+
if character == "`":
|
| 1352 |
+
break
|
| 1353 |
+
identifier.append(character)
|
| 1354 |
+
else:
|
| 1355 |
+
raise ValueError("Unterminated SQL identifier")
|
| 1356 |
+
yield "IDENT", "".join(identifier)
|
| 1357 |
+
continue
|
| 1358 |
+
if character == "'":
|
| 1359 |
+
string: list[str] = []
|
| 1360 |
+
for character in characters:
|
| 1361 |
+
if character == "\\":
|
| 1362 |
+
escaped = next(characters, None)
|
| 1363 |
+
if escaped is None:
|
| 1364 |
+
raise ValueError("Unterminated SQL string escape")
|
| 1365 |
+
string.append(_MYSQL_ESCAPES.get(escaped, escaped))
|
| 1366 |
+
elif character == "'":
|
| 1367 |
+
following = next(characters, None)
|
| 1368 |
+
if following == "'":
|
| 1369 |
+
string.append("'")
|
| 1370 |
+
else:
|
| 1371 |
+
pending = following
|
| 1372 |
+
break
|
| 1373 |
+
else:
|
| 1374 |
+
string.append(character)
|
| 1375 |
+
else:
|
| 1376 |
+
raise ValueError("Unterminated SQL string")
|
| 1377 |
+
yield "VALUE", "".join(string)
|
| 1378 |
+
continue
|
| 1379 |
+
|
| 1380 |
+
atom = [character]
|
| 1381 |
+
for character in characters:
|
| 1382 |
+
if character.isspace() or character in "(),;":
|
| 1383 |
+
pending = character
|
| 1384 |
+
break
|
| 1385 |
+
atom.append(character)
|
| 1386 |
+
text = "".join(atom)
|
| 1387 |
+
value = _convert_atom(text)
|
| 1388 |
+
yield ("WORD" if isinstance(value, str) else "VALUE"), value
|
| 1389 |
+
|
| 1390 |
+
|
| 1391 |
+
def _convert_atom(text: str) -> SqlValue:
|
| 1392 |
+
if text.upper() == "NULL":
|
| 1393 |
+
return None
|
| 1394 |
+
if _INTEGER.fullmatch(text):
|
| 1395 |
+
return int(text)
|
| 1396 |
+
if _FLOAT.fullmatch(text) and ("." in text or "e" in text.lower()):
|
| 1397 |
+
return float(text)
|
| 1398 |
+
return text
|
| 1399 |
+
|
| 1400 |
+
|
| 1401 |
+
def _iter_validated_rows(
|
| 1402 |
+
source: Iterable[str],
|
| 1403 |
+
table: str,
|
| 1404 |
+
expected_columns: tuple[tuple[int, str], ...],
|
| 1405 |
+
*,
|
| 1406 |
+
exact: bool = False,
|
| 1407 |
+
select_by_name: bool = False,
|
| 1408 |
+
) -> Iterator[tuple[SqlValue, ...]]:
|
| 1409 |
+
"""Validate a dump table declaration before yielding its inserted rows."""
|
| 1410 |
+
|
| 1411 |
+
observed_columns: list[str] = []
|
| 1412 |
+
rows = iter_insert_rows(
|
| 1413 |
+
_validated_source(
|
| 1414 |
+
source,
|
| 1415 |
+
table,
|
| 1416 |
+
expected_columns,
|
| 1417 |
+
exact=exact,
|
| 1418 |
+
validate_by_name=select_by_name,
|
| 1419 |
+
observed_columns=observed_columns,
|
| 1420 |
+
),
|
| 1421 |
+
table,
|
| 1422 |
+
)
|
| 1423 |
+
if not select_by_name:
|
| 1424 |
+
yield from rows
|
| 1425 |
+
return
|
| 1426 |
+
|
| 1427 |
+
positions: tuple[int, ...] | None = None
|
| 1428 |
+
for row in rows:
|
| 1429 |
+
if positions is None:
|
| 1430 |
+
positions = tuple(
|
| 1431 |
+
observed_columns.index(name) for _, name in expected_columns
|
| 1432 |
+
)
|
| 1433 |
+
if len(row) < len(observed_columns):
|
| 1434 |
+
raise ValueError(
|
| 1435 |
+
f"{table} row has {len(row)} values; expected at least "
|
| 1436 |
+
f"{len(observed_columns)}"
|
| 1437 |
+
)
|
| 1438 |
+
if len(row) > len(observed_columns):
|
| 1439 |
+
raise ValueError(
|
| 1440 |
+
f"{table} row has {len(row)} values; CREATE TABLE declares "
|
| 1441 |
+
f"{len(observed_columns)} columns"
|
| 1442 |
+
)
|
| 1443 |
+
yield tuple(row[position] for position in positions)
|
| 1444 |
+
|
| 1445 |
+
|
| 1446 |
+
def _prepare_metadata_sources(
|
| 1447 |
+
page: Iterable[str],
|
| 1448 |
+
page_props: Iterable[str],
|
| 1449 |
+
categorylinks: Iterable[str],
|
| 1450 |
+
linktarget: Iterable[str],
|
| 1451 |
+
) -> tuple[Iterable[str], Iterable[str], Iterable[str], Iterable[str]]:
|
| 1452 |
+
"""Validate all required schemas before exposing any INSERT rows."""
|
| 1453 |
+
|
| 1454 |
+
prepared = []
|
| 1455 |
+
for source, table, columns, exact, validate_by_name in (
|
| 1456 |
+
(page, "page", _PAGE_COLUMNS, False, True),
|
| 1457 |
+
(page_props, "page_props", _PAGE_PROPS_COLUMNS, False, False),
|
| 1458 |
+
(categorylinks, "categorylinks", _CATEGORYLINKS_COLUMNS, True, False),
|
| 1459 |
+
(linktarget, "linktarget", _LINKTARGET_COLUMNS, True, False),
|
| 1460 |
+
):
|
| 1461 |
+
validated = _validated_source(
|
| 1462 |
+
source,
|
| 1463 |
+
table,
|
| 1464 |
+
columns,
|
| 1465 |
+
exact=exact,
|
| 1466 |
+
validate_by_name=validate_by_name,
|
| 1467 |
+
)
|
| 1468 |
+
prefix = next(validated)
|
| 1469 |
+
prepared.append(chain((prefix,), validated))
|
| 1470 |
+
return tuple(prepared)
|
| 1471 |
+
|
| 1472 |
+
|
| 1473 |
+
def _validated_source(
|
| 1474 |
+
source: Iterable[str],
|
| 1475 |
+
table: str,
|
| 1476 |
+
expected_columns: tuple[tuple[int, str], ...],
|
| 1477 |
+
*,
|
| 1478 |
+
exact: bool,
|
| 1479 |
+
validate_by_name: bool = False,
|
| 1480 |
+
observed_columns: list[str] | None = None,
|
| 1481 |
+
) -> Iterator[str]:
|
| 1482 |
+
"""Yield a source only after its bounded schema prefix is validated."""
|
| 1483 |
+
|
| 1484 |
+
buffered = ""
|
| 1485 |
+
create_pattern = re.compile(
|
| 1486 |
+
rf"CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?`?{re.escape(table)}`?\s*\(",
|
| 1487 |
+
re.IGNORECASE,
|
| 1488 |
+
)
|
| 1489 |
+
insert_pattern = re.compile(
|
| 1490 |
+
rf"INSERT\s+INTO\s+`?{re.escape(table)}`?\b", re.IGNORECASE
|
| 1491 |
+
)
|
| 1492 |
+
iterator = iter(source)
|
| 1493 |
+
for chunk in iterator:
|
| 1494 |
+
buffered += chunk
|
| 1495 |
+
create_match = create_pattern.search(buffered)
|
| 1496 |
+
insert_match = insert_pattern.search(buffered)
|
| 1497 |
+
if insert_match is not None and (
|
| 1498 |
+
create_match is None or insert_match.start() < create_match.start()
|
| 1499 |
+
):
|
| 1500 |
+
raise ValueError(f"{table} CREATE TABLE schema is missing")
|
| 1501 |
+
if create_match is not None:
|
| 1502 |
+
statement_end = buffered.find(";", create_match.end())
|
| 1503 |
+
if statement_end >= 0:
|
| 1504 |
+
statement = buffered[create_match.start() : statement_end]
|
| 1505 |
+
columns = tuple(
|
| 1506 |
+
re.findall(r"(?:\(|,)\s*`([^`]+)`\s+[A-Za-z]", statement)
|
| 1507 |
+
)
|
| 1508 |
+
if validate_by_name:
|
| 1509 |
+
incompatible = any(
|
| 1510 |
+
columns.count(name) != 1 for _, name in expected_columns
|
| 1511 |
+
)
|
| 1512 |
+
else:
|
| 1513 |
+
incompatible = any(
|
| 1514 |
+
position >= len(columns) or columns[position] != name
|
| 1515 |
+
for position, name in expected_columns
|
| 1516 |
+
)
|
| 1517 |
+
if exact and len(columns) != len(expected_columns):
|
| 1518 |
+
incompatible = True
|
| 1519 |
+
if incompatible:
|
| 1520 |
+
expected = ", ".join(name for _, name in expected_columns)
|
| 1521 |
+
actual = ", ".join(columns) or "<none>"
|
| 1522 |
+
raise ValueError(
|
| 1523 |
+
f"{table} CREATE TABLE schema is incompatible: "
|
| 1524 |
+
f"expected {expected}; found {actual}"
|
| 1525 |
+
)
|
| 1526 |
+
if observed_columns is not None:
|
| 1527 |
+
observed_columns.extend(columns)
|
| 1528 |
+
yield buffered
|
| 1529 |
+
yield from iterator
|
| 1530 |
+
return
|
| 1531 |
+
if len(buffered) > _SCHEMA_PREFIX_LIMIT:
|
| 1532 |
+
raise ValueError(
|
| 1533 |
+
f"{table} CREATE TABLE schema is missing from the first "
|
| 1534 |
+
f"{_SCHEMA_PREFIX_LIMIT} characters"
|
| 1535 |
+
)
|
| 1536 |
+
raise ValueError(f"{table} CREATE TABLE schema is missing")
|
| 1537 |
+
|
| 1538 |
+
|
| 1539 |
+
def _iter_statement_rows(tokens: Iterator[_Token]) -> Iterator[tuple[SqlValue, ...]]:
|
| 1540 |
+
token = next(tokens, None)
|
| 1541 |
+
while token is not None and token != ("SYMBOL", ";"):
|
| 1542 |
+
if token != ("SYMBOL", "("):
|
| 1543 |
+
raise ValueError("Expected '(' at the start of an INSERT row")
|
| 1544 |
+
row: list[SqlValue] = []
|
| 1545 |
+
expect_value = True
|
| 1546 |
+
for token in tokens:
|
| 1547 |
+
if expect_value:
|
| 1548 |
+
if token[0] not in {"VALUE", "WORD", "IDENT"}:
|
| 1549 |
+
raise ValueError("Expected a value in an INSERT row")
|
| 1550 |
+
row.append(token[1])
|
| 1551 |
+
expect_value = False
|
| 1552 |
+
elif token == ("SYMBOL", ","):
|
| 1553 |
+
expect_value = True
|
| 1554 |
+
elif token == ("SYMBOL", ")"):
|
| 1555 |
+
break
|
| 1556 |
+
else:
|
| 1557 |
+
raise ValueError("Expected ',' or ')' in an INSERT row")
|
| 1558 |
+
else:
|
| 1559 |
+
raise ValueError("Unterminated INSERT row")
|
| 1560 |
+
if expect_value:
|
| 1561 |
+
raise ValueError("INSERT row ends after a comma")
|
| 1562 |
+
yield tuple(row)
|
| 1563 |
+
token = next(tokens, None)
|
| 1564 |
+
if token == ("SYMBOL", ","):
|
| 1565 |
+
token = next(tokens, None)
|
| 1566 |
+
elif token != ("SYMBOL", ";"):
|
| 1567 |
+
raise ValueError("Expected ',' or ';' after an INSERT row")
|
preprocessing/_wikigood/wikigood_ru_corpus.py
ADDED
|
@@ -0,0 +1,297 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
| 1 |
+
"""Portable reproduction of the pinned 20261001 quality corpora.
|
| 2 |
+
|
| 3 |
+
SQL selection and XML normalization are shared with the accepted Full builder.
|
| 4 |
+
Selected applies only the published frozen annotations. Failed targets are kept.
|
| 5 |
+
"""
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
import argparse
|
| 9 |
+
import gzip
|
| 10 |
+
from hashlib import sha1, sha256
|
| 11 |
+
from importlib.metadata import version
|
| 12 |
+
import json
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
import shutil
|
| 15 |
+
import sys
|
| 16 |
+
from types import SimpleNamespace
|
| 17 |
+
from urllib.request import Request, urlopen
|
| 18 |
+
|
| 19 |
+
from .wikigood_ru_content import ExpectedWikiPage, extract_selected_pages
|
| 20 |
+
from .wikigood_ru_quality_metadata import select_wikigood_ru_quality_metadata
|
| 21 |
+
from .wikigood_ru_vw import _quality_json
|
| 22 |
+
|
| 23 |
+
SPEC_PATH = Path(__file__).resolve().parents[1] / 'specs/wikipedia-quality-corpus-20261001.json'
|
| 24 |
+
# Public exports place this same resource beside prepare.py.
|
| 25 |
+
if not SPEC_PATH.is_file():
|
| 26 |
+
SPEC_PATH = Path(__file__).resolve().parents[1] / 'wikipedia-quality-corpus-20261001.json'
|
| 27 |
+
SPEC = json.loads(SPEC_PATH.read_text(encoding='utf-8'))
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def _safe(path):
|
| 31 |
+
path = Path(path).absolute()
|
| 32 |
+
if '..' in path.parts or any(p.is_symlink() for p in (path, *path.parents)):
|
| 33 |
+
raise ValueError(f'symbolic links and parent traversal are forbidden: {path}')
|
| 34 |
+
return path
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def _check(path, pin):
|
| 38 |
+
path = _safe(path)
|
| 39 |
+
if not path.is_file() or path.stat().st_size != pin['size_bytes']:
|
| 40 |
+
raise ValueError(f'pinned file size mismatch: {path}')
|
| 41 |
+
hashes = {name: algorithm() for name, algorithm in (('sha256', sha256), ('sha1', sha1)) if name in pin}
|
| 42 |
+
with path.open('rb') as stream:
|
| 43 |
+
for block in iter(lambda: stream.read(1024 * 1024), b''):
|
| 44 |
+
for digest in hashes.values():
|
| 45 |
+
digest.update(block)
|
| 46 |
+
if any(digest.hexdigest() != pin[name] for name, digest in hashes.items()):
|
| 47 |
+
raise ValueError(f'pinned file checksum mismatch: {path}')
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def validate_corpus_sources(sources_dir):
|
| 51 |
+
"""Rehash all six exact dated inputs against SHA-256 and official SHA-1."""
|
| 52 |
+
root = _safe(sources_dir)
|
| 53 |
+
for entry in SPEC['sources']:
|
| 54 |
+
_check(root / entry['filename'], entry)
|
| 55 |
+
return SPEC['sources']
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def download_corpus_sources(sources_dir, *, resume=False):
|
| 59 |
+
"""Reuse validated final files; partial HTTP transfers require explicit resume."""
|
| 60 |
+
root = _safe(sources_dir)
|
| 61 |
+
if root.exists():
|
| 62 |
+
for entry in SPEC['sources']:
|
| 63 |
+
final, part = root / entry['filename'], root / (entry['filename'] + '.part')
|
| 64 |
+
_safe(part)
|
| 65 |
+
if final.exists():
|
| 66 |
+
_check(final, entry)
|
| 67 |
+
if part.exists():
|
| 68 |
+
raise ValueError(f'both final and partial files exist: {final.name}')
|
| 69 |
+
if part.exists() and (not resume or not part.is_file() or part.stat().st_size > entry['size_bytes']):
|
| 70 |
+
raise ValueError(f'partial source requires explicit --resume and valid size: {part}')
|
| 71 |
+
root.mkdir(parents=True, exist_ok=True)
|
| 72 |
+
for entry in SPEC['sources']:
|
| 73 |
+
final, part = root / entry['filename'], root / (entry['filename'] + '.part')
|
| 74 |
+
if final.exists():
|
| 75 |
+
continue
|
| 76 |
+
offset = part.stat().st_size if part.exists() else 0
|
| 77 |
+
if offset < entry['size_bytes']:
|
| 78 |
+
headers = {'User-Agent': 'RuWiki-Good-2026-V2-reproduction/1'}
|
| 79 |
+
if offset:
|
| 80 |
+
headers['Range'] = f'bytes={offset}-'
|
| 81 |
+
print(f'corpus sources download {entry["filename"]} offset={offset}', file=sys.stderr, flush=True)
|
| 82 |
+
with urlopen(Request(entry['url'], headers=headers), timeout=60) as response:
|
| 83 |
+
expected = entry['size_bytes'] - offset
|
| 84 |
+
if response.geturl() != entry['url'] or response.status != (206 if offset else 200):
|
| 85 |
+
raise ValueError('dated source URL or HTTP range response mismatch')
|
| 86 |
+
if int(response.headers.get('Content-Length', '-1')) != expected:
|
| 87 |
+
raise ValueError('source HTTP length mismatch')
|
| 88 |
+
if offset and response.headers.get('Content-Range') != f'bytes {offset}-{entry["size_bytes"] - 1}/{entry["size_bytes"]}':
|
| 89 |
+
raise ValueError('source HTTP range mismatch')
|
| 90 |
+
with part.open('ab' if offset else 'xb') as stream:
|
| 91 |
+
while block := response.read(min(1024 * 1024, expected + 1)):
|
| 92 |
+
if len(block) > expected:
|
| 93 |
+
raise ValueError('source HTTP body exceeds pinned size')
|
| 94 |
+
stream.write(block)
|
| 95 |
+
expected -= len(block)
|
| 96 |
+
if expected:
|
| 97 |
+
raise ValueError('incomplete source HTTP body; rerun with --resume')
|
| 98 |
+
_check(part, entry)
|
| 99 |
+
part.rename(final)
|
| 100 |
+
return {'snapshot': SPEC['snapshot'], 'files': SPEC['sources']}
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def _rows(path):
|
| 104 |
+
with gzip.open(path, 'rt', encoding='utf-8') as stream:
|
| 105 |
+
for line in stream:
|
| 106 |
+
yield json.loads(line)
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def _write_rows(path, rows, *, compresslevel=9, sort_keys=True):
|
| 110 |
+
with path.open('xb') as raw:
|
| 111 |
+
with gzip.GzipFile(filename='', mode='wb', fileobj=raw, mtime=0, compresslevel=compresslevel) as stream:
|
| 112 |
+
for row in rows:
|
| 113 |
+
payload = _quality_json(row) if sort_keys else (json.dumps(row, ensure_ascii=False, separators=(',', ':')) + '\n').encode('utf-8')
|
| 114 |
+
stream.write(payload)
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def _annotations(root):
|
| 118 |
+
root = _safe(root)
|
| 119 |
+
pins = SPEC['corpora']['selected']
|
| 120 |
+
for name in ('labels.json', 'topics.jsonl.gz'):
|
| 121 |
+
_check(root / name, pins['files'][name])
|
| 122 |
+
labels = json.loads((root / 'labels.json').read_text(encoding='utf-8'))
|
| 123 |
+
topics = list(_rows(root / 'topics.jsonl.gz'))
|
| 124 |
+
slugs = [row['slug'] for row in topics]
|
| 125 |
+
if len(slugs) != pins['topic_count'] or len(set(slugs)) != len(slugs):
|
| 126 |
+
raise ValueError('annotation topic count or identity mismatch')
|
| 127 |
+
if len(labels) != pins['count'] or any(
|
| 128 |
+
not isinstance(values, list) or not values or values != sorted(set(values))
|
| 129 |
+
or set(values) - set(slugs) for values in labels.values()
|
| 130 |
+
):
|
| 131 |
+
raise ValueError('annotation labels or topic binding mismatch')
|
| 132 |
+
return labels
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def _selected_rows(full_path, labels):
|
| 136 |
+
seen = set()
|
| 137 |
+
previous = 0
|
| 138 |
+
full_count = 0
|
| 139 |
+
for row in _rows(full_path):
|
| 140 |
+
page_id = row['page_id']
|
| 141 |
+
if type(page_id) is not int or page_id <= previous or row['id'] != f'ruwiki/{page_id}' or 'topics' in row:
|
| 142 |
+
raise ValueError('Full article IDs, ordering or schema mismatch')
|
| 143 |
+
previous = page_id
|
| 144 |
+
full_count += 1
|
| 145 |
+
if row['id'] in labels:
|
| 146 |
+
seen.add(row['id'])
|
| 147 |
+
yield {**row, 'topics': labels[row['id']]}
|
| 148 |
+
if full_count != SPEC['corpora']['full']['count'] or seen != set(labels):
|
| 149 |
+
raise ValueError('Full count or Selected annotation IDs mismatch')
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def _full_records(sources, scratch):
|
| 153 |
+
entries = {entry['filename']: entry for entry in SPEC['sources']}
|
| 154 |
+
names = ('page', 'page_props', 'categorylinks', 'linktarget')
|
| 155 |
+
snapshot = SimpleNamespace(
|
| 156 |
+
**{name: sources / f'ruwiki-20261001-{name}.sql.gz' for name in names},
|
| 157 |
+
snapshot_id='ru-20261001',
|
| 158 |
+
checksums={name: entries[f'ruwiki-20261001-{name}.sql.gz']['sha256'] for name in names},
|
| 159 |
+
)
|
| 160 |
+
print('corpus build metadata', file=sys.stderr, flush=True)
|
| 161 |
+
metadata = select_wikigood_ru_quality_metadata(snapshot, scratch_parent=scratch, scratch_ceiling_bytes=32 * 1024**3)
|
| 162 |
+
roster = metadata['articles']
|
| 163 |
+
if len(roster) != SPEC['corpora']['full']['count']:
|
| 164 |
+
raise ValueError('Full SQL roster count mismatch')
|
| 165 |
+
captured = {}
|
| 166 |
+
print('corpus build XML extraction', file=sys.stderr, flush=True)
|
| 167 |
+
pages = extract_selected_pages(
|
| 168 |
+
sources / 'ruwiki-20261001-pages-articles-multistream.xml.bz2',
|
| 169 |
+
sources / 'ruwiki-20261001-pages-articles-multistream-index.txt.bz2',
|
| 170 |
+
[ExpectedWikiPage(row['page_id'], row['title']) for row in roster], source_records=captured,
|
| 171 |
+
)
|
| 172 |
+
by_id = {page.page_id: page for page in pages}
|
| 173 |
+
if len(pages) != len(roster) or set(by_id) != set(captured) or set(by_id) != {row['page_id'] for row in roster}:
|
| 174 |
+
raise ValueError('XML extraction roster mismatch')
|
| 175 |
+
def records():
|
| 176 |
+
for row in roster:
|
| 177 |
+
page = by_id[row['page_id']]
|
| 178 |
+
yield {**row, **captured[page.page_id], 'id': f'ruwiki/{page.page_id}',
|
| 179 |
+
'revision_id': page.revision_id, 'raw_text': page.raw_text,
|
| 180 |
+
'wikitext_sha256': page.wikitext_sha256, 'raw_text_sha256': page.raw_text_sha256,
|
| 181 |
+
'page_url': f'https://ru.wikipedia.org/?curid={page.page_id}',
|
| 182 |
+
'revision_url': f'https://ru.wikipedia.org/w/index.php?oldid={page.revision_id}'}
|
| 183 |
+
return records(), metadata['categories']
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def verify_corpus(output_dir, *, dataset='both'):
|
| 187 |
+
"""Compare payloads to independent published pins; no self-generated seal is trusted."""
|
| 188 |
+
root = _safe(output_dir)
|
| 189 |
+
names = ('full', 'selected') if dataset == 'both' else (dataset,)
|
| 190 |
+
for name in names:
|
| 191 |
+
for filename, pin in SPEC['corpora'][name]['files'].items():
|
| 192 |
+
_check(root / name / filename, pin)
|
| 193 |
+
if 'selected' in names:
|
| 194 |
+
labels = _annotations(root / 'selected')
|
| 195 |
+
observed = {}
|
| 196 |
+
previous = 0
|
| 197 |
+
for row in _rows(root / 'selected/articles.jsonl.gz'):
|
| 198 |
+
if row['page_id'] <= previous or row['id'] != f'ruwiki/{row["page_id"]}':
|
| 199 |
+
raise ValueError('Selected article ordering or ID mismatch')
|
| 200 |
+
previous = row['page_id']
|
| 201 |
+
observed[row['id']] = row['topics']
|
| 202 |
+
if observed != labels:
|
| 203 |
+
raise ValueError('Selected articles and frozen labels differ')
|
| 204 |
+
return {'snapshot': SPEC['snapshot'], 'corpora': {name: SPEC['corpora'][name] for name in names}}
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
def build_corpus(sources_dir, *, output_dir, scratch_dir, dataset='both', annotations_dir=None, full_dir=None):
|
| 208 |
+
"""Create fresh output/full and output/selected, ready for the existing NLP CLI."""
|
| 209 |
+
sources, output, scratch = map(_safe, (sources_dir, output_dir, scratch_dir))
|
| 210 |
+
inputs = [sources]
|
| 211 |
+
if annotations_dir is not None:
|
| 212 |
+
inputs.append(_safe(annotations_dir))
|
| 213 |
+
if full_dir is not None:
|
| 214 |
+
inputs.append(_safe(full_dir))
|
| 215 |
+
if dataset != 'selected':
|
| 216 |
+
raise ValueError('--full-dir requires --dataset selected')
|
| 217 |
+
for path in (output, scratch):
|
| 218 |
+
if path.exists():
|
| 219 |
+
raise ValueError(f'fresh target required: {path}')
|
| 220 |
+
if any((parent / 'preprocessing/prepare.py').is_file() or (parent / 'data/articles.jsonl.gz').is_file() for parent in (path, *path.parents)):
|
| 221 |
+
raise ValueError('output and scratch must be outside published dataset clones')
|
| 222 |
+
paths = [output, scratch, *inputs]
|
| 223 |
+
for i, path in enumerate(paths[:2]):
|
| 224 |
+
if any(path == other or path.is_relative_to(other) or other.is_relative_to(path) for other in paths[i + 1:]):
|
| 225 |
+
raise ValueError('source, output and scratch paths must be disjoint')
|
| 226 |
+
selected = dataset in ('selected', 'both')
|
| 227 |
+
if selected and annotations_dir is None:
|
| 228 |
+
raise ValueError('--annotations-dir is required for Selected')
|
| 229 |
+
labels = _annotations(annotations_dir) if selected else None
|
| 230 |
+
if full_dir is None:
|
| 231 |
+
if sys.version_info[:3] != (3, 11, 15):
|
| 232 |
+
raise ValueError('raw corpus extraction requires Python==3.11.15')
|
| 233 |
+
if version('mwparserfromhell') != '0.7.2':
|
| 234 |
+
raise ValueError('corpus extraction requires mwparserfromhell==0.7.2')
|
| 235 |
+
import mwparserfromhell
|
| 236 |
+
if mwparserfromhell.parse("''fixture''").strip_code() != 'fixture':
|
| 237 |
+
raise ValueError('mwparserfromhell runtime probe failed')
|
| 238 |
+
validate_corpus_sources(sources)
|
| 239 |
+
else:
|
| 240 |
+
_check(Path(full_dir) / 'articles.jsonl.gz', SPEC['corpora']['full']['files']['articles.jsonl.gz'])
|
| 241 |
+
output.mkdir(parents=True)
|
| 242 |
+
scratch.mkdir(parents=True)
|
| 243 |
+
if full_dir is None:
|
| 244 |
+
records, categories = _full_records(sources, scratch)
|
| 245 |
+
full_output = output / 'full' if dataset in ('both', 'full') else scratch / 'full'
|
| 246 |
+
full_output.mkdir()
|
| 247 |
+
_write_rows(full_output / 'articles.jsonl.gz', records)
|
| 248 |
+
_write_rows(full_output / 'categories.jsonl.gz', categories)
|
| 249 |
+
for filename, pin in SPEC['corpora']['full']['files'].items():
|
| 250 |
+
_check(full_output / filename, pin)
|
| 251 |
+
else:
|
| 252 |
+
full_output = Path(full_dir)
|
| 253 |
+
if selected:
|
| 254 |
+
target = output / 'selected'
|
| 255 |
+
target.mkdir()
|
| 256 |
+
_write_rows(target / 'articles.jsonl.gz', _selected_rows(full_output / 'articles.jsonl.gz', labels),
|
| 257 |
+
compresslevel=6, sort_keys=False)
|
| 258 |
+
for filename in ('labels.json', 'topics.jsonl.gz'):
|
| 259 |
+
shutil.copyfile(Path(annotations_dir) / filename, target / filename)
|
| 260 |
+
result = verify_corpus(output, dataset=dataset)
|
| 261 |
+
(output / 'corpus-manifest.json').write_bytes(_quality_json(result))
|
| 262 |
+
return result
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
def verify_published_nlp(output_dir, *, dataset='both'):
|
| 266 |
+
"""Check final CSVs and labels against published hashes without loading NLP."""
|
| 267 |
+
root = _safe(output_dir)
|
| 268 |
+
for name in (('full', 'selected') if dataset == 'both' else (dataset,)):
|
| 269 |
+
for filename, pin in SPEC['nlp'][name].items():
|
| 270 |
+
_check(root / name / filename, pin)
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
def main(argv=None):
|
| 274 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 275 |
+
parser.add_argument('--action', required=True, choices=('download', 'build', 'verify'))
|
| 276 |
+
parser.add_argument('--dataset', default='both', choices=('full', 'selected', 'both'))
|
| 277 |
+
parser.add_argument('--sources-dir', required=True, type=Path)
|
| 278 |
+
parser.add_argument('--output-dir', type=Path)
|
| 279 |
+
parser.add_argument('--scratch-dir', type=Path)
|
| 280 |
+
parser.add_argument('--annotations-dir', type=Path)
|
| 281 |
+
parser.add_argument('--full-dir', type=Path, help='Pinned Full data directory for Selected-only replay without dumps')
|
| 282 |
+
parser.add_argument('--resume', action='store_true')
|
| 283 |
+
args = parser.parse_args(argv)
|
| 284 |
+
for field in {'download': (), 'build': ('output_dir', 'scratch_dir'), 'verify': ('output_dir',)}[args.action]:
|
| 285 |
+
if getattr(args, field) is None:
|
| 286 |
+
parser.error(f'--{field.replace("_", "-")} is required')
|
| 287 |
+
if args.resume and args.action != 'download':
|
| 288 |
+
parser.error('--resume is only valid with --action download')
|
| 289 |
+
if args.action == 'download':
|
| 290 |
+
download_corpus_sources(args.sources_dir, resume=args.resume)
|
| 291 |
+
elif args.action == 'build':
|
| 292 |
+
build_corpus(args.sources_dir, output_dir=args.output_dir, scratch_dir=args.scratch_dir,
|
| 293 |
+
dataset=args.dataset, annotations_dir=args.annotations_dir, full_dir=args.full_dir)
|
| 294 |
+
else:
|
| 295 |
+
verify_corpus(args.output_dir, dataset=args.dataset)
|
| 296 |
+
print(f'{args.action.upper()}_OK stage=corpus dataset={args.dataset}', flush=True)
|
| 297 |
+
return 0
|
preprocessing/_wikigood/wikigood_ru_quality_metadata.py
ADDED
|
@@ -0,0 +1,220 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Portable full-quality metadata selection using the existing SQL kernels."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
from collections import Counter
|
| 4 |
+
from contextlib import ExitStack, contextmanager
|
| 5 |
+
from hashlib import sha256
|
| 6 |
+
import gzip
|
| 7 |
+
from os import PathLike, fspath
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
import re
|
| 10 |
+
from typing import Iterator, TextIO
|
| 11 |
+
from .wiki_metadata import (
|
| 12 |
+
QualityCategoryConfig, _execute_in_batches, _prepare_metadata_sources,
|
| 13 |
+
build_metadata_indexes, iter_category_links, iter_link_targets, iter_page_props,
|
| 14 |
+
iter_pages_with_metadata, open_metadata_scratch, select_quality_articles,
|
| 15 |
+
)
|
| 16 |
+
_SOURCE_NAMES = ("page", "page_props", "categorylinks", "linktarget")
|
| 17 |
+
_SHA256 = re.compile(r"[0-9a-f]{64}\Z")
|
| 18 |
+
FORMER_QUALITY_CATEGORIES = frozenset({
|
| 19 |
+
"Википедия:Лишённые_статуса_добротной",
|
| 20 |
+
"Википедия:Лишённые_статуса_хорошей",
|
| 21 |
+
"Википедия:Устаревшие_избранные_статьи",
|
| 22 |
+
})
|
| 23 |
+
|
| 24 |
+
@contextmanager
|
| 25 |
+
def _open_text(source) -> Iterator[TextIO]:
|
| 26 |
+
if isinstance(source, (str, PathLike)):
|
| 27 |
+
path = fspath(source)
|
| 28 |
+
opener = gzip.open if path.endswith(".gz") else open
|
| 29 |
+
# SQL varbinary fields may contain non-UTF-8 bytes; keep them reversible.
|
| 30 |
+
with opener(
|
| 31 |
+
path, mode="rt", encoding="utf-8", errors="surrogateescape"
|
| 32 |
+
) as stream:
|
| 33 |
+
yield stream
|
| 34 |
+
return
|
| 35 |
+
if not hasattr(source, "read"):
|
| 36 |
+
raise TypeError("metadata source must be a path or open text stream")
|
| 37 |
+
yield source
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def _source_sha256(source) -> str:
|
| 41 |
+
digest = sha256()
|
| 42 |
+
if isinstance(source, (str, PathLike)):
|
| 43 |
+
with open(source, "rb") as stream:
|
| 44 |
+
for chunk in iter(lambda: stream.read(1024 * 1024), b""):
|
| 45 |
+
digest.update(chunk)
|
| 46 |
+
return digest.hexdigest()
|
| 47 |
+
|
| 48 |
+
if not all(hasattr(source, method) for method in ("read", "seek", "tell")):
|
| 49 |
+
raise TypeError("metadata source must be a path or seekable stream")
|
| 50 |
+
try:
|
| 51 |
+
position = source.tell()
|
| 52 |
+
source.seek(0)
|
| 53 |
+
except (OSError, ValueError) as error:
|
| 54 |
+
raise ValueError("metadata stream must be seekable for checksum verification") from error
|
| 55 |
+
try:
|
| 56 |
+
while chunk := source.read(1024 * 1024):
|
| 57 |
+
digest.update(chunk.encode("utf-8") if isinstance(chunk, str) else chunk)
|
| 58 |
+
finally:
|
| 59 |
+
source.seek(position)
|
| 60 |
+
return digest.hexdigest()
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
QUALITY_SNAPSHOT_ID = "ru-20261001"
|
| 64 |
+
QUALITY_STATUSES = {
|
| 65 |
+
"Википедия:Добротные_статьи_по_алфавиту": "recommended",
|
| 66 |
+
"Википедия:Хорошие_статьи_по_алфавиту": "good",
|
| 67 |
+
"Википедия:Избранные_статьи_по_алфавиту": "featured",
|
| 68 |
+
}
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def select_wikigood_ru_quality_metadata(
|
| 72 |
+
snapshot,
|
| 73 |
+
*,
|
| 74 |
+
scratch_parent: Path,
|
| 75 |
+
scratch_ceiling_bytes: int,
|
| 76 |
+
) -> dict[str, object]:
|
| 77 |
+
"""Return all active quality articles and the complete category graph.
|
| 78 |
+
|
| 79 |
+
Article titles use XML spelling (spaces); category titles retain exact SQL
|
| 80 |
+
spelling, including underscores. Category links include redlinks. Former
|
| 81 |
+
quality memberships are historical metadata and never veto active status.
|
| 82 |
+
"""
|
| 83 |
+
|
| 84 |
+
if snapshot.snapshot_id != QUALITY_SNAPSHOT_ID:
|
| 85 |
+
raise ValueError(f"snapshot_id must be {QUALITY_SNAPSHOT_ID!r}")
|
| 86 |
+
if set(snapshot.checksums) != set(_SOURCE_NAMES) or any(
|
| 87 |
+
not isinstance(snapshot.checksums[name], str)
|
| 88 |
+
or _SHA256.fullmatch(snapshot.checksums[name]) is None
|
| 89 |
+
for name in _SOURCE_NAMES
|
| 90 |
+
):
|
| 91 |
+
raise ValueError("snapshot checksums must be the exact lowercase SHA-256 set")
|
| 92 |
+
if (
|
| 93 |
+
isinstance(scratch_ceiling_bytes, bool)
|
| 94 |
+
or not isinstance(scratch_ceiling_bytes, int)
|
| 95 |
+
or scratch_ceiling_bytes <= 0
|
| 96 |
+
):
|
| 97 |
+
raise ValueError("scratch_ceiling_bytes must be a positive integer")
|
| 98 |
+
for name in _SOURCE_NAMES:
|
| 99 |
+
if _source_sha256(getattr(snapshot, name)) != snapshot.checksums[name]:
|
| 100 |
+
raise ValueError(f"metadata checksum mismatch: {name}")
|
| 101 |
+
|
| 102 |
+
indexes = None
|
| 103 |
+
with open_metadata_scratch(Path(scratch_parent), scratch_ceiling_bytes) as scratch:
|
| 104 |
+
try:
|
| 105 |
+
with ExitStack() as stack:
|
| 106 |
+
sources = [
|
| 107 |
+
stack.enter_context(_open_text(getattr(snapshot, name)))
|
| 108 |
+
for name in _SOURCE_NAMES
|
| 109 |
+
]
|
| 110 |
+
page, props, links, targets = _prepare_metadata_sources(*sources)
|
| 111 |
+
indexes = build_metadata_indexes(
|
| 112 |
+
iter_pages_with_metadata(page),
|
| 113 |
+
iter_page_props(props),
|
| 114 |
+
iter_category_links(links),
|
| 115 |
+
iter_link_targets(targets),
|
| 116 |
+
max_database_bytes=scratch_ceiling_bytes,
|
| 117 |
+
scratch=scratch,
|
| 118 |
+
database_name="metadata-quality-ru.sqlite3",
|
| 119 |
+
)
|
| 120 |
+
missing = sorted(set(QUALITY_STATUSES) - set(indexes.category_title_to_id))
|
| 121 |
+
if missing:
|
| 122 |
+
raise ValueError(
|
| 123 |
+
"configured quality category pages are missing: " + ", ".join(missing)
|
| 124 |
+
)
|
| 125 |
+
if set(QUALITY_STATUSES) & indexes.redirect_category_titles():
|
| 126 |
+
raise ValueError("configured quality category pages are redirects")
|
| 127 |
+
quality = select_quality_articles(
|
| 128 |
+
indexes, QualityCategoryConfig(QUALITY_STATUSES, frozenset())
|
| 129 |
+
)
|
| 130 |
+
if not quality:
|
| 131 |
+
raise ValueError("no non-redirect quality articles remain")
|
| 132 |
+
page_ids = tuple(article.page_id for article in quality)
|
| 133 |
+
metadata = indexes.article_metadata(page_ids)
|
| 134 |
+
direct = indexes.article_category_target_titles(page_ids)
|
| 135 |
+
qids = dict(_execute_in_batches(
|
| 136 |
+
indexes._connection,
|
| 137 |
+
"SELECT page_id, value FROM property WHERE name = 'wikibase_item' "
|
| 138 |
+
"AND page_id IN ({}) ORDER BY page_id",
|
| 139 |
+
page_ids,
|
| 140 |
+
))
|
| 141 |
+
articles = []
|
| 142 |
+
for article in quality:
|
| 143 |
+
title, revision_id, redirect = metadata[article.page_id]
|
| 144 |
+
if not title or revision_id is None or revision_id <= 0 or redirect:
|
| 145 |
+
raise ValueError(
|
| 146 |
+
f"selected article metadata is inconsistent: {article.page_id}"
|
| 147 |
+
)
|
| 148 |
+
memberships = list(direct.get(article.page_id, ()))
|
| 149 |
+
articles.append({
|
| 150 |
+
"page_id": article.page_id,
|
| 151 |
+
"title": title,
|
| 152 |
+
"metadata_revision_id": revision_id,
|
| 153 |
+
"wikidata_id": qids.get(article.page_id),
|
| 154 |
+
"quality_statuses": list(article.statuses),
|
| 155 |
+
"categories": memberships,
|
| 156 |
+
"former_quality_categories": sorted(
|
| 157 |
+
set(memberships) & FORMER_QUALITY_CATEGORIES
|
| 158 |
+
),
|
| 159 |
+
})
|
| 160 |
+
|
| 161 |
+
# Materialize the requested catalog, never the complete SQL tables.
|
| 162 |
+
connection = indexes._connection
|
| 163 |
+
catalog = {
|
| 164 |
+
title: {
|
| 165 |
+
"title": title,
|
| 166 |
+
"page_id": page_id,
|
| 167 |
+
"is_hidden": None if page_id is None else bool(hidden),
|
| 168 |
+
"is_redirect": None if page_id is None else bool(redirect),
|
| 169 |
+
"wikidata_id": qid,
|
| 170 |
+
"parents": [],
|
| 171 |
+
}
|
| 172 |
+
for title, page_id, redirect, hidden, qid in connection.execute(
|
| 173 |
+
"SELECT titles.title, page.page_id, page.is_redirect, "
|
| 174 |
+
"hidden.page_id IS NOT NULL, qid.value FROM ("
|
| 175 |
+
"SELECT title FROM page WHERE namespace = 14 UNION "
|
| 176 |
+
"SELECT target.title FROM target JOIN category_link AS link "
|
| 177 |
+
"ON link.target_id = target.target_id WHERE target.namespace = 14"
|
| 178 |
+
") AS titles LEFT JOIN page ON page.namespace = 14 "
|
| 179 |
+
"AND page.title = titles.title LEFT JOIN property AS hidden "
|
| 180 |
+
"ON hidden.page_id = page.page_id AND hidden.name = 'hiddencat' "
|
| 181 |
+
"LEFT JOIN property AS qid ON qid.page_id = page.page_id "
|
| 182 |
+
"AND qid.name = 'wikibase_item' ORDER BY titles.title"
|
| 183 |
+
)
|
| 184 |
+
}
|
| 185 |
+
parent_links = 0
|
| 186 |
+
for title, parent in connection.execute(
|
| 187 |
+
"SELECT DISTINCT page.title, target.title FROM page "
|
| 188 |
+
"JOIN category_link AS link ON link.source_page_id = page.page_id "
|
| 189 |
+
"JOIN target ON target.target_id = link.target_id "
|
| 190 |
+
"WHERE page.namespace = 14 AND target.namespace = 14 "
|
| 191 |
+
"ORDER BY page.title, target.title"
|
| 192 |
+
):
|
| 193 |
+
catalog[title]["parents"].append(parent)
|
| 194 |
+
parent_links += 1
|
| 195 |
+
scratch.observe()
|
| 196 |
+
return {
|
| 197 |
+
"resources": {
|
| 198 |
+
"main_database_bytes": scratch.main_database_bytes,
|
| 199 |
+
"observed_ephemeral_transient_high_water_bytes": (
|
| 200 |
+
scratch.observed_ephemeral_transient_high_water_bytes
|
| 201 |
+
),
|
| 202 |
+
},
|
| 203 |
+
"articles": articles,
|
| 204 |
+
"categories": list(catalog.values()),
|
| 205 |
+
"counts": {
|
| 206 |
+
"articles": len(articles),
|
| 207 |
+
"categories": len(catalog),
|
| 208 |
+
"category_redlinks": sum(
|
| 209 |
+
c["page_id"] is None for c in catalog.values()
|
| 210 |
+
),
|
| 211 |
+
"category_parent_links": parent_links,
|
| 212 |
+
"direct_category_links": sum(len(a["categories"]) for a in articles),
|
| 213 |
+
"quality_status_supports": dict(sorted(Counter(
|
| 214 |
+
status for article in quality for status in article.statuses
|
| 215 |
+
).items())),
|
| 216 |
+
},
|
| 217 |
+
}
|
| 218 |
+
finally:
|
| 219 |
+
if indexes is not None:
|
| 220 |
+
indexes.close()
|
preprocessing/prepare.py
CHANGED
|
@@ -1,10 +1,30 @@
|
|
| 1 |
-
"""Download, build or verify
|
|
|
|
|
|
|
| 2 |
|
| 3 |
-
Run ``python prepare.py --help`` for the portable workflow options.
|
| 4 |
-
"""
|
| 5 |
|
| 6 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
|
| 8 |
|
| 9 |
-
if __name__ ==
|
| 10 |
raise SystemExit(main())
|
|
|
|
| 1 |
+
"""Download, build or verify pinned Wikipedia corpus JSONL or NLP CSVs."""
|
| 2 |
+
import argparse
|
| 3 |
+
import sys
|
| 4 |
|
|
|
|
|
|
|
| 5 |
|
| 6 |
+
def main(argv=None):
|
| 7 |
+
arguments = list(sys.argv[1:] if argv is None else argv)
|
| 8 |
+
parser = argparse.ArgumentParser(add_help=False)
|
| 9 |
+
parser.add_argument('--stage', choices=('corpus', 'nlp'), default='nlp')
|
| 10 |
+
stage, remaining = parser.parse_known_args(arguments)
|
| 11 |
+
if stage.stage == 'corpus':
|
| 12 |
+
from _wikigood.wikigood_ru_corpus import main as dispatch
|
| 13 |
+
else:
|
| 14 |
+
from _wikigood.wikigood_ru_csv import main as dispatch
|
| 15 |
+
result = dispatch(remaining)
|
| 16 |
+
if stage.stage == 'nlp':
|
| 17 |
+
options = argparse.ArgumentParser(add_help=False)
|
| 18 |
+
options.add_argument('--action')
|
| 19 |
+
options.add_argument('--output-dir')
|
| 20 |
+
options.add_argument('--dataset', default='both')
|
| 21 |
+
args, _ = options.parse_known_args(remaining)
|
| 22 |
+
if args.action in ('build', 'verify'):
|
| 23 |
+
from _wikigood.wikigood_ru_corpus import verify_published_nlp
|
| 24 |
+
verify_published_nlp(args.output_dir, dataset=args.dataset)
|
| 25 |
+
print(f'PUBLISHED_NLP_OK dataset={args.dataset}', flush=True)
|
| 26 |
+
return result
|
| 27 |
|
| 28 |
|
| 29 |
+
if __name__ == '__main__':
|
| 30 |
raise SystemExit(main())
|
preprocessing/requirements.txt
CHANGED
|
@@ -1,3 +1,4 @@
|
|
| 1 |
spacy==3.8.14
|
| 2 |
pymorphy3==2.0.6
|
| 3 |
nltk==3.9.2
|
|
|
|
|
|
| 1 |
spacy==3.8.14
|
| 2 |
pymorphy3==2.0.6
|
| 3 |
nltk==3.9.2
|
| 4 |
+
mwparserfromhell==0.7.2
|
preprocessing/wikipedia-quality-corpus-20261001.json
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{"corpora":{"full":{"count":17413,"files":{"articles.jsonl.gz":{"sha256":"c51f9b6bee4c85f25ffb861060f52490a9276bae289d2aa2db7e0d10e2dda950","size_bytes":409970311},"categories.jsonl.gz":{"sha256":"d07ab1e6c07da28cc162d786853a73c54e300289e21bcc6667c4072158abdf8f","size_bytes":22459573}}},"selected":{"count":17251,"files":{"articles.jsonl.gz":{"sha256":"9eb7efffe99fc7c9bc3f4b3eb9f0378d91f387081f97cf9abea9c1686797c1ed","size_bytes":413342335},"labels.json":{"sha256":"e7ceacd69d76601df24bb42e6d0177f46142d0b8ac1bf6e8c22ad4d5a0b0ca70","size_bytes":649823},"topics.jsonl.gz":{"sha256":"c8cf602a924f18255e155cdcaa9357907461851e849113c72051c2b89484f22c","size_bytes":2671}},"topic_count":28}},"nlp":{"full":{"bow.csv":{"sha256":"a45edd3e9287009e353c0f3ffc4404ffadc393293dada691e2d275a0bc0d2f5d","size_bytes":883080852},"noow.csv":{"sha256":"041250c048b0441cc88d516b92e1d65c0f80db3c82b400b7ae6b9db379c2ed33","size_bytes":1128356201}},"selected":{"bow.csv":{"sha256":"bff3a82c29ab3b866fe86135ff99b3897deb98dc4e5ed6db4ea7b24bd4011bae","size_bytes":875143956},"labels.json":{"sha256":"e7ceacd69d76601df24bb42e6d0177f46142d0b8ac1bf6e8c22ad4d5a0b0ca70","size_bytes":649823},"noow.csv":{"sha256":"2c71aa6b5a327ebe924f5f0160eaf6f923a86da1a3a7fe8c68aa67f8858f8b6b","size_bytes":1118455706}}},"schema_version":1,"snapshot":"20261001","sources":[{"filename":"ruwiki-20261001-page.sql.gz","sha1":"448e8faf79cbcdd2bb7c8f76c1e2d275b2288226","sha256":"24250cca6122fff02896a1ced0a85b7afa4d6be00fa119c169a5eeef3fbe5830","size_bytes":314950229,"url":"https://dumps.wikimedia.org/ruwiki/20261001/ruwiki-20261001-page.sql.gz"},{"filename":"ruwiki-20261001-page_props.sql.gz","sha1":"f08c0700597847bb5d82a9130e67ad75c4c184ab","sha256":"fc9d5aeaf3487d932b82d18a16bc96f0e4e4702e1149cbbdc482eb509f6deb60","size_bytes":64031076,"url":"https://dumps.wikimedia.org/ruwiki/20261001/ruwiki-20261001-page_props.sql.gz"},{"filename":"ruwiki-20261001-categorylinks.sql.gz","sha1":"c4200e9e6a0179cf0624b76cccfd46b0ba57c715","sha256":"1ecb32ffaff28a120b6a8f4297d4b228b65c49beb593eae022b5811ae41512e1","size_bytes":343720059,"url":"https://dumps.wikimedia.org/ruwiki/20261001/ruwiki-20261001-categorylinks.sql.gz"},{"filename":"ruwiki-20261001-linktarget.sql.gz","sha1":"576c82d839bbc4db57435ec864315be657d22ee6","sha256":"bc1f24b7b8eb06298cbe70fdfb010ec023586d05bd2d3403ba2370091e1edc4a","size_bytes":243099022,"url":"https://dumps.wikimedia.org/ruwiki/20261001/ruwiki-20261001-linktarget.sql.gz"},{"filename":"ruwiki-20261001-pages-articles-multistream.xml.bz2","sha1":"edfd1751cf2444b7fdb4f0cad0ee1bdb661cd65a","sha256":"c22b6441176d2bc572ed6883abc6292fe168efca211f6cdd61d8772a78492a1b","size_bytes":6212830831,"url":"https://dumps.wikimedia.org/ruwiki/20261001/ruwiki-20261001-pages-articles-multistream.xml.bz2"},{"filename":"ruwiki-20261001-pages-articles-multistream-index.txt.bz2","sha1":"379bcb73bc29f496975608b33a4a054dcd932f77","sha256":"17c6a4cebb90ecb2b0f881e04aa3b49356bd6ee6add802a7201b9ca1a9b093e3","size_bytes":66367857,"url":"https://dumps.wikimedia.org/ruwiki/20261001/ruwiki-20261001-pages-articles-multistream-index.txt.bz2"}]}
|