Vasily Alexeev commited on
Commit ·
721d43c
1
Parent(s): 3c6bdb4
add csv data for topic modeling
Browse files- .gitattributes +1 -0
- README.md +143 -7
- data/bow.csv +3 -0
- data/noow.csv +3 -0
- preprocessing/LICENSE +21 -0
- preprocessing/_wikigood/__init__.py +1 -0
- preprocessing/_wikigood/wikigood_ru_content.py +557 -0
- preprocessing/_wikigood/wikigood_ru_csv.py +453 -0
- preprocessing/_wikigood/wikigood_ru_nlp.py +229 -0
- preprocessing/_wikigood/wikigood_ru_vw.py +996 -0
- preprocessing/conda-linux-64.lock.txt +37 -0
- preprocessing/pip-linux-x86_64.lock.txt +54 -0
- preprocessing/prepare.py +10 -0
- preprocessing/requirements.txt +3 -0
- preprocessing/wikipedia-quality-nlp-20261001.json +1 -0
.gitattributes
CHANGED
|
@@ -60,3 +60,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 60 |
*.webm filter=lfs diff=lfs merge=lfs -text
|
| 61 |
*.jsonl filter=lfs diff=lfs merge=lfs -text
|
| 62 |
*.jsonl.gz filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 60 |
*.webm filter=lfs diff=lfs merge=lfs -text
|
| 61 |
*.jsonl filter=lfs diff=lfs merge=lfs -text
|
| 62 |
*.jsonl.gz filter=lfs diff=lfs merge=lfs -text
|
| 63 |
+
*.csv filter=lfs diff=lfs merge=lfs -text
|
README.md
CHANGED
|
@@ -40,15 +40,17 @@ status categories are retained separately and do not exclude an article that has
|
|
| 40 |
an active status. These are community editorial designations at this snapshot,
|
| 41 |
not independent factual checks or current assessments.
|
| 42 |
|
| 43 |
-
All selected articles are retained.
|
| 44 |
-
|
| 45 |
-
|
|
|
|
| 46 |
procedure does not remove records because they share text. The `corpus`
|
| 47 |
partition is a storage partition, not a research split.
|
| 48 |
|
| 49 |
## Loading
|
| 50 |
|
| 51 |
-
|
|
|
|
| 52 |
With Hugging Face Datasets:
|
| 53 |
|
| 54 |
```python
|
|
@@ -75,6 +77,37 @@ categories = load_dataset(
|
|
| 75 |
)
|
| 76 |
```
|
| 77 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
## Article fields
|
| 79 |
|
| 80 |
| Field | JSON type | Meaning |
|
|
@@ -187,6 +220,106 @@ fragments of markup or awkward text may remain. `wikitext` is retained so reader
|
|
| 187 |
can inspect these losses or apply a different extraction procedure. Neither
|
| 188 |
`raw_text` nor the category metadata is a manually corrected annotation.
|
| 189 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 190 |
## Attribution, license and use
|
| 191 |
|
| 192 |
Article text and wikitext are attributed to **Russian Wikipedia contributors**
|
|
@@ -206,12 +339,15 @@ small, editorially selected portion of Russian Wikipedia, not a representative
|
|
| 206 |
sample of Russian writing or an evenly balanced subject collection. Quality
|
| 207 |
status does not guarantee accuracy, neutrality, completeness or suitability for
|
| 208 |
any downstream application. Articles can contain sensitive, biased, outdated or
|
| 209 |
-
offensive material. Any subject labels, deduplication policy,
|
| 210 |
-
research splits needed for a downstream study must be specified
|
|
|
|
| 211 |
|
| 212 |
## Published file identity
|
| 213 |
|
| 214 |
-
| File |
|
| 215 |
| --- | ---: | --- |
|
| 216 |
| `data/articles.jsonl.gz` | 409,970,311 | `c51f9b6bee4c85f25ffb861060f52490a9276bae289d2aa2db7e0d10e2dda950` |
|
| 217 |
| `data/categories.jsonl.gz` | 22,459,573 | `d07ab1e6c07da28cc162d786853a73c54e300289e21bcc6667c4072158abdf8f` |
|
|
|
|
|
|
|
|
|
| 40 |
an active status. These are community editorial designations at this snapshot,
|
| 41 |
not independent factual checks or current assessments.
|
| 42 |
|
| 43 |
+
All selected articles are retained. Source selection applies no thematic filtering,
|
| 44 |
+
sampling, subject-label assignment or research train/test split. The original JSON
|
| 45 |
+
records are preserved; the optional preparation workflow below produces separate
|
| 46 |
+
NLP CSV files. There are no exact duplicate `wikitext` or `raw_text` values in this snapshot; the selection
|
| 47 |
procedure does not remove records because they share text. The `corpus`
|
| 48 |
partition is a storage partition, not a research split.
|
| 49 |
|
| 50 |
## Loading
|
| 51 |
|
| 52 |
+
The `articles` configuration is the default. `articles` and `categories` use
|
| 53 |
+
compressed JSON Lines and the `corpus` split, with no dataset script.
|
| 54 |
With Hugging Face Datasets:
|
| 55 |
|
| 56 |
```python
|
|
|
|
| 77 |
)
|
| 78 |
```
|
| 79 |
|
| 80 |
+
The prepared NLP files `data/noow.csv` and `data/bow.csv` contain the same
|
| 81 |
+
17,413 article IDs, in source order, with string columns `id`, `raw_text`,
|
| 82 |
+
`vw_text`. Use the CSV reader for these files, separately from the repository's
|
| 83 |
+
JSON Lines configurations:
|
| 84 |
+
|
| 85 |
+
```python
|
| 86 |
+
noow = load_dataset(
|
| 87 |
+
"csv",
|
| 88 |
+
data_files={"corpus": "hf://datasets/TopicNet/RuWiki-Good-2026-V2/data/noow.csv"},
|
| 89 |
+
split="corpus",
|
| 90 |
+
)
|
| 91 |
+
bow = load_dataset(
|
| 92 |
+
"csv",
|
| 93 |
+
data_files={"corpus": "hf://datasets/TopicNet/RuWiki-Good-2026-V2/data/bow.csv"},
|
| 94 |
+
split="corpus",
|
| 95 |
+
)
|
| 96 |
+
```
|
| 97 |
+
|
| 98 |
+
From the parent of a downloaded repository:
|
| 99 |
+
|
| 100 |
+
```python
|
| 101 |
+
noow = load_dataset(
|
| 102 |
+
"csv", data_files={"corpus": "RuWiki-Good-2026-V2/data/noow.csv"}, split="corpus"
|
| 103 |
+
)
|
| 104 |
+
bow = load_dataset(
|
| 105 |
+
"csv", data_files={"corpus": "RuWiki-Good-2026-V2/data/bow.csv"}, split="corpus"
|
| 106 |
+
)
|
| 107 |
+
```
|
| 108 |
+
|
| 109 |
+
The NLP preparation section describes the normalized namespaces and text fields.
|
| 110 |
+
|
| 111 |
## Article fields
|
| 112 |
|
| 113 |
| Field | JSON type | Meaning |
|
|
|
|
| 220 |
can inspect these losses or apply a different extraction procedure. Neither
|
| 221 |
`raw_text` nor the category metadata is a manually corrected annotation.
|
| 222 |
|
| 223 |
+
## NLP preparation
|
| 224 |
+
|
| 225 |
+
The standalone [preparation code](preprocessing/prepare.py) builds `noow.csv` and
|
| 226 |
+
`bow.csv` from the pinned article snapshots without modifying their JSON files.
|
| 227 |
+
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 |
+
|
| 235 |
+
| Namespace | Contents |
|
| 236 |
+
| --- | --- |
|
| 237 |
+
| `@title` | Normalized title tokens. |
|
| 238 |
+
| `@word` | Normalized body tokens only; the title is not prepended. |
|
| 239 |
+
| `@bigram` | Accepted adjacent body bigrams. |
|
| 240 |
+
| `@trigram` | Accepted adjacent body trigrams. |
|
| 241 |
+
| `@category` | All direct Wikipedia categories, including service and maintenance categories. |
|
| 242 |
+
|
| 243 |
+
NOOW preserves the normalized token sequence within each namespace, not the raw
|
| 244 |
+
prose. BOW counts exactly those NOOW tokens independently in each namespace.
|
| 245 |
+
It does not trim the token sequence or remove articles. There are no research
|
| 246 |
+
splits, deduplication, model training or chain extraction in this workflow.
|
| 247 |
+
|
| 248 |
+
Normalization uses `spacy.blank("ru")`, pymorphy3 normal forms and the union of
|
| 249 |
+
spaCy Russian and NLTK Russian stopwords. Punctuation and whitespace tokens are
|
| 250 |
+
removed; HTML tags, URLs and email addresses become `<TAG>`, `<URL>` and `<MAIL>`.
|
| 251 |
+
Cyrillic stress marks are removed; lexical Cyrillic compounds with ASCII hyphen,
|
| 252 |
+
U+2010 or U+2011 are normalized to ASCII hyphens and kept as single tokens.
|
| 253 |
+
Person names are not masked.
|
| 254 |
+
|
| 255 |
+
Bigrams and trigrams are selected independently using NLTK PMI after a corpus
|
| 256 |
+
frequency threshold of 5, with `nbest(32100)[100:]` for each order. Selection uses
|
| 257 |
+
all normalized article bodies in the chosen collection; it is **corpus-global**,
|
| 258 |
+
not fitted only on a later training split. Full and Selected therefore have
|
| 259 |
+
separately selected n-gram vocabularies. These CSVs are not a claim of evaluation
|
| 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 |
+
Run from the downloaded `preprocessing` directory. Python 3.11.15 is the pinned
|
| 264 |
+
runtime. On Linux x86-64, the supplied locks reproduce the preparation environment:
|
| 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 |
+
`requirements.txt` lists the direct NLP dependencies. The locks include the
|
| 277 |
+
complete previously used environment; no downloaded spaCy language model is
|
| 278 |
+
needed. The [pinned preparation contract](preprocessing/wikipedia-quality-nlp-20261001.json)
|
| 279 |
+
records source revisions, SHA-256 hashes and runtime requirements. Download
|
| 280 |
+
reuses existing source files after checking their pinned hashes, downloads any
|
| 281 |
+
missing source files, then acquires the pinned NLTK stopwords archive at
|
| 282 |
+
`sources/nltk_data/corpora/stopwords.zip`. To reuse local snapshots, first place
|
| 283 |
+
them at `sources/full/articles.jsonl.gz`, `sources/selected/articles.jsonl.gz` and
|
| 284 |
+
`sources/selected/topics.jsonl.gz`, then run the same download command. This
|
| 285 |
+
creates the NLTK resource directory; an existing environment's `nltk_data`
|
| 286 |
+
directory is not required.
|
| 287 |
+
|
| 288 |
+
Hugging Face files are downloaded anonymously with Python `urllib`. Restricted
|
| 289 |
+
repositories require access: download their pinned source files separately with
|
| 290 |
+
authenticated tools, put them at the paths above, and rerun the download action.
|
| 291 |
+
The preparation script does not handle authentication tokens.
|
| 292 |
+
|
| 293 |
+
Both build and verify must use Python 3.11.15: VW escaping depends on the
|
| 294 |
+
runtime Unicode database. Verify requires no NLP packages. Build runs offline
|
| 295 |
+
and checks runtime versions and the Russian stopword content.
|
| 296 |
+
Use `--nltk-data` to provide a different local NLTK resource directory.
|
| 297 |
+
`--dataset full`, `selected` or `both` controls the collection. Source paths are
|
| 298 |
+
`full/articles.jsonl.gz`, `selected/articles.jsonl.gz` and
|
| 299 |
+
`selected/topics.jsonl.gz` beneath `--sources-dir`. Generated files are placed
|
| 300 |
+
under `output/full` and `output/selected`, with a build manifest. Build prints
|
| 301 |
+
phase and document-count progress. The manifest records counts and ordered IDs
|
| 302 |
+
of articles with an empty `@word` namespace; these articles are retained. Verification
|
| 303 |
+
checks pinned source identities, output hashes, schemas, source text and
|
| 304 |
+
NOOW/BOW token-count agreement without NLP dependencies. It does not replay
|
| 305 |
+
tokenization, lemmatization or PMI selection; a manifest self-hash alone does
|
| 306 |
+
not establish independent authenticity.
|
| 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.
|
| 322 |
+
|
| 323 |
## Attribution, license and use
|
| 324 |
|
| 325 |
Article text and wikitext are attributed to **Russian Wikipedia contributors**
|
|
|
|
| 339 |
sample of Russian writing or an evenly balanced subject collection. Quality
|
| 340 |
status does not guarantee accuracy, neutrality, completeness or suitability for
|
| 341 |
any downstream application. Articles can contain sensitive, biased, outdated or
|
| 342 |
+
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 |
## Published file identity
|
| 347 |
|
| 348 |
+
| File | Bytes | SHA-256 |
|
| 349 |
| --- | ---: | --- |
|
| 350 |
| `data/articles.jsonl.gz` | 409,970,311 | `c51f9b6bee4c85f25ffb861060f52490a9276bae289d2aa2db7e0d10e2dda950` |
|
| 351 |
| `data/categories.jsonl.gz` | 22,459,573 | `d07ab1e6c07da28cc162d786853a73c54e300289e21bcc6667c4072158abdf8f` |
|
| 352 |
+
| `data/noow.csv` | 1,128,356,201 | `041250c048b0441cc88d516b92e1d65c0f80db3c82b400b7ae6b9db379c2ed33` |
|
| 353 |
+
| `data/bow.csv` | 883,080,852 | `a45edd3e9287009e353c0f3ffc4404ffadc393293dada691e2d275a0bc0d2f5d` |
|
data/bow.csv
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a45edd3e9287009e353c0f3ffc4404ffadc393293dada691e2d275a0bc0d2f5d
|
| 3 |
+
size 883080852
|
data/noow.csv
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:041250c048b0441cc88d516b92e1d65c0f80db3c82b400b7ae6b9db379c2ed33
|
| 3 |
+
size 1128356201
|
preprocessing/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
MIT License
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2026 RuWiki-Good-2026 contributors
|
| 4 |
+
|
| 5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
in the Software without restriction, including without limitation the rights
|
| 8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
SOFTWARE.
|
preprocessing/_wikigood/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""Standalone source snapshot for the Russian Wikipedia CSV preparation."""
|
preprocessing/_wikigood/wikigood_ru_content.py
ADDED
|
@@ -0,0 +1,557 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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ExitStack
|
| 7 |
+
from dataclasses import dataclass
|
| 8 |
+
from datetime import datetime
|
| 9 |
+
from hashlib import sha256
|
| 10 |
+
import os
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
import re
|
| 13 |
+
from typing import BinaryIO, Iterable
|
| 14 |
+
from xml.etree import ElementTree
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
_DECIMAL = re.compile(r"[0-9]+\Z")
|
| 18 |
+
_PAGE_START = re.compile(br"<page(?:\s[^>]*)?>")
|
| 19 |
+
_PAGE_END = b"</page>"
|
| 20 |
+
_READ_SIZE = 64 * 1024
|
| 21 |
+
_HTML_SPAN = re.compile(r"<!--.*?-->|<![^<>]*>|</?[A-Za-z][^<>]*?>", re.DOTALL)
|
| 22 |
+
_SPECIAL_TAG_OPEN = re.compile(
|
| 23 |
+
r"<(?:gallery|imagemap|mapframe)(?:\s|>)", re.IGNORECASE
|
| 24 |
+
)
|
| 25 |
+
_TAG_SENTINEL = "WIKIGOODRUTAGPLACEHOLDER"
|
| 26 |
+
_MEDIA_NAMESPACES = frozenset(("file", "image", "файл", "изображение"))
|
| 27 |
+
_MEDIA_LINK_OPEN = re.compile(
|
| 28 |
+
r"\[\[\s*(?:file|image|файл|изображение)\s*:", re.IGNORECASE
|
| 29 |
+
)
|
| 30 |
+
_FILE_DESCRIPTION_TEMPLATE_OPEN = re.compile(
|
| 31 |
+
r"\{\{\s*файл\s+с\s+описанием(?=\s*(?:\||\}\}))", re.IGNORECASE
|
| 32 |
+
)
|
| 33 |
+
_MALFORMED_IMAGE_PARAMETER_LINE = re.compile(
|
| 34 |
+
r"^[^\S\r\n]*\|[^\S\r\n]*(?:image|изображение)[^\S\r\n]*="
|
| 35 |
+
r"[^\r\n]*\.(?:jpe?g|png|gif|svg|webp|tiff?|ogg|ogv|webm)"
|
| 36 |
+
r"[^\S\r\n]*(?:\r?\n|$)",
|
| 37 |
+
re.IGNORECASE | re.MULTILINE,
|
| 38 |
+
)
|
| 39 |
+
_ORPHAN_MEDIA_FLAG = re.compile(
|
| 40 |
+
r"(?<!\S)(?:thumb|thumbnail|мини|миниатюра)[^\S\r\n]*\|"
|
| 41 |
+
r"[^\S\r\n]*",
|
| 42 |
+
re.IGNORECASE,
|
| 43 |
+
)
|
| 44 |
+
_MEDIA_FLAG_OPTIONS = frozenset(
|
| 45 |
+
(
|
| 46 |
+
"thumb", "thumbnail", "мини", "миниатюра",
|
| 47 |
+
"frame", "framed", "enframed", "обрамить",
|
| 48 |
+
"frameless", "безрамки", "border", "граница",
|
| 49 |
+
"left", "слева", "right", "справа", "center", "centre", "центр",
|
| 50 |
+
"none", "без", "baseline", "основание", "sub", "под", "super", "sup", "над",
|
| 51 |
+
"top", "сверху", "text-top", "текст-сверху", "middle", "посередине",
|
| 52 |
+
"bottom", "снизу", "text-bottom", "текст-снизу",
|
| 53 |
+
"upright", "сверхусправа",
|
| 54 |
+
)
|
| 55 |
+
)
|
| 56 |
+
_MEDIA_VALUE_OPTION = re.compile(
|
| 57 |
+
r"(?:(?:alt|альт|альтернативный\s+текст|link|ссылка|"
|
| 58 |
+
r"thumbtime|start|end|poster)\s*=\s*.*|"
|
| 59 |
+
r"(?:class|lang)\s*=\s*.+|"
|
| 60 |
+
r"(?:thumb|thumbnail|мини|миниатюра)\s*=\s*.*|"
|
| 61 |
+
r"(?:page|страница)(?:\s*=\s*[0-9]*|\s+[0-9]+)|"
|
| 62 |
+
r"(?:upright|сверхусправа)"
|
| 63 |
+
r"(?:\s*=\s*[0-9]*(?:\.[0-9]+)?|\s+[0-9]+(?:\.[0-9]+)?)?|"
|
| 64 |
+
r"(?:[0-9]+|[0-9]*x[0-9]+)\s*(?:px|пкс))\Z",
|
| 65 |
+
re.IGNORECASE,
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
@dataclass(frozen=True, slots=True)
|
| 70 |
+
class ExpectedWikiPage:
|
| 71 |
+
"""Metadata that content extraction must reproduce exactly."""
|
| 72 |
+
|
| 73 |
+
page_id: int
|
| 74 |
+
canonical_title: str
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
@dataclass(frozen=True, slots=True)
|
| 78 |
+
class ExtractedWikiPage:
|
| 79 |
+
"""Selected plain text and immutable source provenance."""
|
| 80 |
+
|
| 81 |
+
page_id: int
|
| 82 |
+
canonical_title: str
|
| 83 |
+
revision_id: int
|
| 84 |
+
multistream_offset: int
|
| 85 |
+
multistream_end_offset: int
|
| 86 |
+
index_line_number: int
|
| 87 |
+
raw_text: str
|
| 88 |
+
wikitext_sha256: str
|
| 89 |
+
raw_text_sha256: str
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
@dataclass(frozen=True, slots=True)
|
| 93 |
+
class _IndexMatch:
|
| 94 |
+
offset: int
|
| 95 |
+
end_offset: int
|
| 96 |
+
line_number: int
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def extract_selected_pages(
|
| 100 |
+
dump_path: str | Path | BinaryIO,
|
| 101 |
+
index_path: str | Path | BinaryIO,
|
| 102 |
+
expected_pages: Iterable[ExpectedWikiPage],
|
| 103 |
+
*,
|
| 104 |
+
source_records: dict[int, dict[str, str]] | None = None,
|
| 105 |
+
) -> tuple[ExtractedWikiPage, ...]:
|
| 106 |
+
"""Extract only expected pages from bounded multistream members.
|
| 107 |
+
|
| 108 |
+
The index and XML must agree exactly with caller-supplied page and title
|
| 109 |
+
metadata. Any relevant duplicate, missing value, malformed input, or
|
| 110 |
+
metadata mismatch raises ``ValueError``. When ``source_records`` is supplied,
|
| 111 |
+
populate it by page ID with exact decoded wikitext and a required valid UTC
|
| 112 |
+
revision timestamp. Default outputs and legacy timestamp handling are unchanged.
|
| 113 |
+
"""
|
| 114 |
+
|
| 115 |
+
expected = _validate_expected_pages(expected_pages)
|
| 116 |
+
if not expected:
|
| 117 |
+
return ()
|
| 118 |
+
with ExitStack() as stack:
|
| 119 |
+
dump = (
|
| 120 |
+
dump_path
|
| 121 |
+
if hasattr(dump_path, "read")
|
| 122 |
+
else stack.enter_context(Path(dump_path).open("rb"))
|
| 123 |
+
)
|
| 124 |
+
index = (
|
| 125 |
+
index_path
|
| 126 |
+
if hasattr(index_path, "read")
|
| 127 |
+
else stack.enter_context(Path(index_path).open("rb"))
|
| 128 |
+
)
|
| 129 |
+
return _extract_selected_pages(dump, index, expected, source_records)
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def _extract_selected_pages(
|
| 133 |
+
dump: BinaryIO,
|
| 134 |
+
index: BinaryIO,
|
| 135 |
+
expected: dict[int, ExpectedWikiPage],
|
| 136 |
+
source_records: dict[int, dict[str, str]] | None,
|
| 137 |
+
) -> tuple[ExtractedWikiPage, ...]:
|
| 138 |
+
matches = _read_index(index, expected, os.fstat(dump.fileno()).st_size)
|
| 139 |
+
ids_by_offset: dict[int, set[int]] = {}
|
| 140 |
+
for page_id, match in matches.items():
|
| 141 |
+
ids_by_offset.setdefault(match.offset, set()).add(page_id)
|
| 142 |
+
|
| 143 |
+
extracted: dict[int, ExtractedWikiPage] = {}
|
| 144 |
+
for offset in sorted(ids_by_offset):
|
| 145 |
+
page_ids = ids_by_offset[offset]
|
| 146 |
+
match = matches[next(iter(page_ids))]
|
| 147 |
+
member_xml = _decompress_member(dump, match.offset, match.end_offset)
|
| 148 |
+
for page in _iter_pages(member_xml):
|
| 149 |
+
page_id = _read_page_id(page)
|
| 150 |
+
if page_id not in page_ids:
|
| 151 |
+
continue
|
| 152 |
+
if page_id in extracted:
|
| 153 |
+
raise ValueError(f"duplicate selected page in XML: {page_id}")
|
| 154 |
+
title, revision_id, wikitext = _read_selected_page(page)
|
| 155 |
+
metadata = expected[page_id]
|
| 156 |
+
if title != metadata.canonical_title:
|
| 157 |
+
raise ValueError(
|
| 158 |
+
f"page {page_id} XML title mismatch: {title!r} != "
|
| 159 |
+
f"{metadata.canonical_title!r}"
|
| 160 |
+
)
|
| 161 |
+
if source_records is not None:
|
| 162 |
+
revision = _only_child(page, "revision")
|
| 163 |
+
timestamp = _only_child_text(revision, "timestamp")
|
| 164 |
+
if re.fullmatch(
|
| 165 |
+
r"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z",
|
| 166 |
+
timestamp,
|
| 167 |
+
) is None:
|
| 168 |
+
raise ValueError("malformed revision timestamp in XML")
|
| 169 |
+
try:
|
| 170 |
+
datetime.strptime(timestamp, "%Y-%m-%dT%H:%M:%SZ")
|
| 171 |
+
except ValueError as error:
|
| 172 |
+
raise ValueError("malformed revision timestamp in XML") from error
|
| 173 |
+
source_records[page_id] = {
|
| 174 |
+
"wikitext": wikitext,
|
| 175 |
+
"revision_timestamp": timestamp,
|
| 176 |
+
}
|
| 177 |
+
raw_text = _strip_code(wikitext)
|
| 178 |
+
if not isinstance(raw_text, str):
|
| 179 |
+
raise ValueError("mwparserfromhell.strip_code returned non-text")
|
| 180 |
+
index_match = matches[page_id]
|
| 181 |
+
extracted[page_id] = ExtractedWikiPage(
|
| 182 |
+
page_id=page_id,
|
| 183 |
+
canonical_title=title,
|
| 184 |
+
revision_id=revision_id,
|
| 185 |
+
multistream_offset=index_match.offset,
|
| 186 |
+
multistream_end_offset=index_match.end_offset,
|
| 187 |
+
index_line_number=index_match.line_number,
|
| 188 |
+
raw_text=raw_text,
|
| 189 |
+
wikitext_sha256=sha256(wikitext.encode("utf-8")).hexdigest(),
|
| 190 |
+
raw_text_sha256=sha256(raw_text.encode("utf-8")).hexdigest(),
|
| 191 |
+
)
|
| 192 |
+
|
| 193 |
+
missing = sorted(set(expected) - set(extracted))
|
| 194 |
+
if missing:
|
| 195 |
+
raise ValueError(f"selected pages missing from XML: {missing}")
|
| 196 |
+
return tuple(extracted[page_id] for page_id in sorted(extracted))
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def _validate_expected_pages(
|
| 200 |
+
expected_pages: Iterable[ExpectedWikiPage],
|
| 201 |
+
) -> dict[int, ExpectedWikiPage]:
|
| 202 |
+
expected: dict[int, ExpectedWikiPage] = {}
|
| 203 |
+
for page in expected_pages:
|
| 204 |
+
if (
|
| 205 |
+
not isinstance(page.page_id, int)
|
| 206 |
+
or isinstance(page.page_id, bool)
|
| 207 |
+
or page.page_id <= 0
|
| 208 |
+
or not isinstance(page.canonical_title, str)
|
| 209 |
+
or not page.canonical_title
|
| 210 |
+
):
|
| 211 |
+
raise ValueError(f"invalid expected page metadata: {page!r}")
|
| 212 |
+
if page.page_id in expected:
|
| 213 |
+
raise ValueError(f"duplicate expected page ID: {page.page_id}")
|
| 214 |
+
expected[page.page_id] = page
|
| 215 |
+
return expected
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def _read_index(
|
| 219 |
+
index: BinaryIO,
|
| 220 |
+
expected: dict[int, ExpectedWikiPage],
|
| 221 |
+
dump_size: int,
|
| 222 |
+
) -> dict[int, _IndexMatch]:
|
| 223 |
+
found: dict[int, tuple[int, int]] = {}
|
| 224 |
+
next_offset_by_offset: dict[int, int] = {}
|
| 225 |
+
previous_offset: int | None = None
|
| 226 |
+
try:
|
| 227 |
+
index.seek(0)
|
| 228 |
+
with bz2.open(index, "rt", encoding="utf-8", newline="") as source:
|
| 229 |
+
for line_number, raw_line in enumerate(source, 1):
|
| 230 |
+
line = raw_line.removesuffix("\n").removesuffix("\r")
|
| 231 |
+
fields = line.split(":", 2)
|
| 232 |
+
if (
|
| 233 |
+
len(fields) != 3
|
| 234 |
+
or _DECIMAL.fullmatch(fields[0]) is None
|
| 235 |
+
or _DECIMAL.fullmatch(fields[1]) is None
|
| 236 |
+
or not fields[2]
|
| 237 |
+
):
|
| 238 |
+
raise ValueError(f"malformed multistream index line {line_number}")
|
| 239 |
+
offset, page_id = int(fields[0]), int(fields[1])
|
| 240 |
+
if offset >= dump_size or page_id <= 0:
|
| 241 |
+
raise ValueError(f"invalid multistream index line {line_number}")
|
| 242 |
+
if previous_offset is not None and offset < previous_offset:
|
| 243 |
+
raise ValueError(
|
| 244 |
+
f"multistream offsets decrease at index line {line_number}"
|
| 245 |
+
)
|
| 246 |
+
if previous_offset is not None and offset > previous_offset:
|
| 247 |
+
next_offset_by_offset[previous_offset] = offset
|
| 248 |
+
previous_offset = offset
|
| 249 |
+
metadata = expected.get(page_id)
|
| 250 |
+
if metadata is None:
|
| 251 |
+
continue
|
| 252 |
+
if page_id in found:
|
| 253 |
+
raise ValueError(f"duplicate selected page in index: {page_id}")
|
| 254 |
+
if "<" in fields[2]:
|
| 255 |
+
raise ValueError(
|
| 256 |
+
f"malformed multistream index title at line {line_number}"
|
| 257 |
+
)
|
| 258 |
+
try:
|
| 259 |
+
index_title = ElementTree.fromstring(
|
| 260 |
+
f"<title>{fields[2]}</title>"
|
| 261 |
+
).text
|
| 262 |
+
except ElementTree.ParseError as error:
|
| 263 |
+
raise ValueError(
|
| 264 |
+
f"malformed multistream index title at line {line_number}: "
|
| 265 |
+
f"{error}"
|
| 266 |
+
) from error
|
| 267 |
+
if index_title is None:
|
| 268 |
+
raise ValueError(
|
| 269 |
+
f"malformed multistream index title at line {line_number}"
|
| 270 |
+
)
|
| 271 |
+
if index_title != metadata.canonical_title:
|
| 272 |
+
raise ValueError(
|
| 273 |
+
f"page {page_id} index title mismatch: {index_title!r} != "
|
| 274 |
+
f"{metadata.canonical_title!r}"
|
| 275 |
+
)
|
| 276 |
+
found[page_id] = offset, line_number
|
| 277 |
+
except (EOFError, OSError, UnicodeError) as error:
|
| 278 |
+
raise ValueError(f"malformed multistream index: {error}") from error
|
| 279 |
+
|
| 280 |
+
missing = sorted(set(expected) - set(found))
|
| 281 |
+
if missing:
|
| 282 |
+
raise ValueError(f"selected pages missing from index: {missing}")
|
| 283 |
+
return {
|
| 284 |
+
page_id: _IndexMatch(
|
| 285 |
+
offset,
|
| 286 |
+
next_offset_by_offset.get(offset, dump_size),
|
| 287 |
+
line_number,
|
| 288 |
+
)
|
| 289 |
+
for page_id, (offset, line_number) in found.items()
|
| 290 |
+
}
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
def _decompress_member(dump: BinaryIO, offset: int, end_offset: int) -> bytes:
|
| 294 |
+
if end_offset <= offset:
|
| 295 |
+
raise ValueError(f"invalid multistream member bounds: {offset}:{end_offset}")
|
| 296 |
+
dump.seek(offset)
|
| 297 |
+
remaining = end_offset - offset
|
| 298 |
+
decompressor = bz2.BZ2Decompressor()
|
| 299 |
+
output = bytearray()
|
| 300 |
+
try:
|
| 301 |
+
while remaining:
|
| 302 |
+
chunk = dump.read(min(_READ_SIZE, remaining))
|
| 303 |
+
if not chunk:
|
| 304 |
+
raise ValueError(f"truncated multistream member at offset {offset}")
|
| 305 |
+
remaining -= len(chunk)
|
| 306 |
+
output.extend(decompressor.decompress(chunk))
|
| 307 |
+
if decompressor.eof and (remaining or decompressor.unused_data):
|
| 308 |
+
raise ValueError(
|
| 309 |
+
f"index boundary spans multiple members at offset {offset}"
|
| 310 |
+
)
|
| 311 |
+
except (EOFError, OSError) as error:
|
| 312 |
+
raise ValueError(f"malformed bzip2 member at offset {offset}") from error
|
| 313 |
+
if not decompressor.eof:
|
| 314 |
+
raise ValueError(f"truncated bzip2 member at offset {offset}")
|
| 315 |
+
return bytes(output)
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
def _iter_pages(member_xml: bytes) -> Iterable[ElementTree.Element]:
|
| 319 |
+
position = 0
|
| 320 |
+
while match := _PAGE_START.search(member_xml, position):
|
| 321 |
+
end = member_xml.find(_PAGE_END, match.end())
|
| 322 |
+
if end < 0:
|
| 323 |
+
raise ValueError("malformed page XML: missing closing page tag")
|
| 324 |
+
end += len(_PAGE_END)
|
| 325 |
+
try:
|
| 326 |
+
yield ElementTree.fromstring(member_xml[match.start() : end])
|
| 327 |
+
except ElementTree.ParseError as error:
|
| 328 |
+
raise ValueError(f"malformed page XML: {error}") from error
|
| 329 |
+
position = end
|
| 330 |
+
|
| 331 |
+
|
| 332 |
+
def _read_page_id(page: ElementTree.Element) -> int:
|
| 333 |
+
page_id_text = _only_child_text(page, "id")
|
| 334 |
+
if _DECIMAL.fullmatch(page_id_text) is None or int(page_id_text) <= 0:
|
| 335 |
+
raise ValueError("malformed page ID in XML")
|
| 336 |
+
return int(page_id_text)
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
def _read_selected_page(page: ElementTree.Element) -> tuple[str, int, str]:
|
| 340 |
+
if any(_local_name(child.tag) == "redirect" for child in page):
|
| 341 |
+
raise ValueError("selected page is a redirect")
|
| 342 |
+
title = _only_child_text(page, "title")
|
| 343 |
+
revision = _only_child(page, "revision")
|
| 344 |
+
revision_id_text = _only_child_text(revision, "id")
|
| 345 |
+
text = _only_child(revision, "text")
|
| 346 |
+
if (
|
| 347 |
+
_DECIMAL.fullmatch(revision_id_text) is None
|
| 348 |
+
or int(revision_id_text) <= 0
|
| 349 |
+
or list(text)
|
| 350 |
+
):
|
| 351 |
+
raise ValueError("malformed page XML fields")
|
| 352 |
+
return title, int(revision_id_text), text.text or ""
|
| 353 |
+
|
| 354 |
+
|
| 355 |
+
def _only_child(element: ElementTree.Element, name: str) -> ElementTree.Element:
|
| 356 |
+
matches = [child for child in element if _local_name(child.tag) == name]
|
| 357 |
+
if len(matches) != 1:
|
| 358 |
+
raise ValueError(f"page XML must contain exactly one {name!r} child")
|
| 359 |
+
return matches[0]
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
def _only_child_text(element: ElementTree.Element, name: str) -> str:
|
| 363 |
+
child = _only_child(element, name)
|
| 364 |
+
if child.text is None or list(child):
|
| 365 |
+
raise ValueError(f"page XML {name!r} must contain plain text")
|
| 366 |
+
return child.text
|
| 367 |
+
|
| 368 |
+
|
| 369 |
+
def _local_name(tag: str) -> str:
|
| 370 |
+
return tag.rsplit("}", 1)[-1]
|
| 371 |
+
|
| 372 |
+
|
| 373 |
+
def _strip_code(wikitext: str) -> str:
|
| 374 |
+
try:
|
| 375 |
+
import mwparserfromhell
|
| 376 |
+
except ImportError as error:
|
| 377 |
+
raise RuntimeError("mwparserfromhell is required for wikitext extraction") from error
|
| 378 |
+
if _TAG_SENTINEL in wikitext:
|
| 379 |
+
raise ValueError("wikitext collides with the HTML placeholder sentinel")
|
| 380 |
+
locally_cleaned = wikitext
|
| 381 |
+
media_replacements = []
|
| 382 |
+
selected_end = 0
|
| 383 |
+
for match in _MEDIA_LINK_OPEN.finditer(locally_cleaned):
|
| 384 |
+
if match.start() < selected_end:
|
| 385 |
+
continue
|
| 386 |
+
end = _find_balanced_end(locally_cleaned, match.start(), "[[", "]]")
|
| 387 |
+
if end is None:
|
| 388 |
+
continue
|
| 389 |
+
candidate = locally_cleaned[match.start() : end]
|
| 390 |
+
isolated = mwparserfromhell.parse(candidate)
|
| 391 |
+
if (
|
| 392 |
+
len(isolated.nodes) != 1
|
| 393 |
+
or not isinstance(isolated.nodes[0], mwparserfromhell.nodes.Wikilink)
|
| 394 |
+
):
|
| 395 |
+
continue
|
| 396 |
+
link = isolated.nodes[0]
|
| 397 |
+
title = str(link.title).strip()
|
| 398 |
+
namespace, separator, filename = title.partition(":")
|
| 399 |
+
if (
|
| 400 |
+
not separator
|
| 401 |
+
or namespace.casefold() not in _MEDIA_NAMESPACES
|
| 402 |
+
or not filename.strip()
|
| 403 |
+
):
|
| 404 |
+
continue
|
| 405 |
+
caption = (
|
| 406 |
+
_last_media_caption(_split_top_level_pipes(link.text))
|
| 407 |
+
if link.text is not None
|
| 408 |
+
else ""
|
| 409 |
+
)
|
| 410 |
+
media_replacements.append((match.start(), end, caption))
|
| 411 |
+
selected_end = end
|
| 412 |
+
for start, end, caption in reversed(media_replacements):
|
| 413 |
+
locally_cleaned = locally_cleaned[:start] + caption + locally_cleaned[end:]
|
| 414 |
+
|
| 415 |
+
template_replacements = []
|
| 416 |
+
selected_end = 0
|
| 417 |
+
for match in _FILE_DESCRIPTION_TEMPLATE_OPEN.finditer(locally_cleaned):
|
| 418 |
+
if match.start() < selected_end:
|
| 419 |
+
continue
|
| 420 |
+
end = _find_balanced_end(locally_cleaned, match.start(), "{{", "}}")
|
| 421 |
+
if end is None:
|
| 422 |
+
continue
|
| 423 |
+
candidate = locally_cleaned[match.start() : end]
|
| 424 |
+
isolated = mwparserfromhell.parse(candidate)
|
| 425 |
+
if (
|
| 426 |
+
len(isolated.nodes) == 1
|
| 427 |
+
and isinstance(isolated.nodes[0], mwparserfromhell.nodes.Template)
|
| 428 |
+
and str(isolated.nodes[0].name).strip().casefold() == "файл с описанием"
|
| 429 |
+
):
|
| 430 |
+
template_replacements.append((match.start(), end))
|
| 431 |
+
selected_end = end
|
| 432 |
+
for start, end in reversed(template_replacements):
|
| 433 |
+
locally_cleaned = locally_cleaned[:start] + locally_cleaned[end:]
|
| 434 |
+
|
| 435 |
+
special_tags_cleaned = locally_cleaned
|
| 436 |
+
if _SPECIAL_TAG_OPEN.search(locally_cleaned) is not None:
|
| 437 |
+
special_tags_parsed = mwparserfromhell.parse(locally_cleaned)
|
| 438 |
+
for tag in reversed(special_tags_parsed.filter_tags(recursive=True)):
|
| 439 |
+
tag_name = str(tag.tag).strip().casefold()
|
| 440 |
+
if tag_name == "mapframe":
|
| 441 |
+
replacement = _TAG_SENTINEL * 2
|
| 442 |
+
elif tag_name in {"gallery", "imagemap"}:
|
| 443 |
+
captions = []
|
| 444 |
+
for line in str(tag.contents).splitlines():
|
| 445 |
+
if not line.strip():
|
| 446 |
+
continue
|
| 447 |
+
caption = _media_declaration_caption(
|
| 448 |
+
mwparserfromhell.parse(line)
|
| 449 |
+
)
|
| 450 |
+
if caption is None:
|
| 451 |
+
continue
|
| 452 |
+
stripped_caption = _strip_code(caption)
|
| 453 |
+
if stripped_caption.strip():
|
| 454 |
+
captions.append(stripped_caption)
|
| 455 |
+
if tag_name == "imagemap":
|
| 456 |
+
break
|
| 457 |
+
replacement = (
|
| 458 |
+
_TAG_SENTINEL + "\n".join(captions) + _TAG_SENTINEL
|
| 459 |
+
)
|
| 460 |
+
else:
|
| 461 |
+
continue
|
| 462 |
+
special_tags_parsed.replace(tag, replacement, recursive=True)
|
| 463 |
+
special_tags_cleaned = str(special_tags_parsed)
|
| 464 |
+
|
| 465 |
+
protected = _HTML_SPAN.sub(_TAG_SENTINEL, special_tags_cleaned)
|
| 466 |
+
parsed = mwparserfromhell.parse(protected)
|
| 467 |
+
for link in reversed(parsed.filter_wikilinks(recursive=True)):
|
| 468 |
+
title = str(link.title).strip()
|
| 469 |
+
namespace, separator, _ = title.partition(":")
|
| 470 |
+
if not separator or namespace.casefold() not in _MEDIA_NAMESPACES:
|
| 471 |
+
continue
|
| 472 |
+
caption = (
|
| 473 |
+
_last_media_caption(_split_top_level_pipes(link.text))
|
| 474 |
+
if link.text is not None
|
| 475 |
+
else ""
|
| 476 |
+
)
|
| 477 |
+
parsed.replace(link, caption, recursive=True)
|
| 478 |
+
stripped = parsed.strip_code(
|
| 479 |
+
normalize=True,
|
| 480 |
+
collapse=True,
|
| 481 |
+
keep_template_params=False,
|
| 482 |
+
)
|
| 483 |
+
stripped = stripped.replace(_TAG_SENTINEL, "<TAG>")
|
| 484 |
+
characters = list(stripped)
|
| 485 |
+
for position in range(1, len(stripped) - 2):
|
| 486 |
+
if (
|
| 487 |
+
stripped[position : position + 2] == "]]"
|
| 488 |
+
and stripped[position - 1].isalpha()
|
| 489 |
+
and stripped[position + 2].isalpha()
|
| 490 |
+
):
|
| 491 |
+
characters[position] = " "
|
| 492 |
+
characters[position + 1] = ""
|
| 493 |
+
stripped = "".join(characters)
|
| 494 |
+
stripped = _MALFORMED_IMAGE_PARAMETER_LINE.sub("", stripped)
|
| 495 |
+
return _ORPHAN_MEDIA_FLAG.sub("", stripped)
|
| 496 |
+
|
| 497 |
+
|
| 498 |
+
def _find_balanced_end(
|
| 499 |
+
text: str,
|
| 500 |
+
start: int,
|
| 501 |
+
opener: str,
|
| 502 |
+
closer: str,
|
| 503 |
+
) -> int | None:
|
| 504 |
+
depth = 1
|
| 505 |
+
position = start + len(opener)
|
| 506 |
+
while position <= len(text) - len(closer):
|
| 507 |
+
if text.startswith(opener, position):
|
| 508 |
+
depth += 1
|
| 509 |
+
position += len(opener)
|
| 510 |
+
elif text.startswith(closer, position):
|
| 511 |
+
depth -= 1
|
| 512 |
+
position += len(closer)
|
| 513 |
+
if depth == 0:
|
| 514 |
+
return position
|
| 515 |
+
else:
|
| 516 |
+
position += 1
|
| 517 |
+
return None
|
| 518 |
+
|
| 519 |
+
|
| 520 |
+
def _media_declaration_caption(code: object) -> str | None:
|
| 521 |
+
fields = _split_top_level_pipes(code)
|
| 522 |
+
title = fields[0].strip()
|
| 523 |
+
namespace, separator, filename = title.partition(":")
|
| 524 |
+
if (
|
| 525 |
+
not separator
|
| 526 |
+
or namespace.casefold() not in _MEDIA_NAMESPACES
|
| 527 |
+
or not filename.strip()
|
| 528 |
+
):
|
| 529 |
+
return None
|
| 530 |
+
return _last_media_caption(fields[1:])
|
| 531 |
+
|
| 532 |
+
|
| 533 |
+
def _split_top_level_pipes(code: object) -> list[str]:
|
| 534 |
+
import mwparserfromhell
|
| 535 |
+
|
| 536 |
+
fields = [""]
|
| 537 |
+
for node in code.nodes:
|
| 538 |
+
if isinstance(node, mwparserfromhell.nodes.Text):
|
| 539 |
+
fragments = node.value.split("|")
|
| 540 |
+
fields[-1] += fragments[0]
|
| 541 |
+
fields.extend(fragments[1:])
|
| 542 |
+
else:
|
| 543 |
+
fields[-1] += str(node)
|
| 544 |
+
return fields
|
| 545 |
+
|
| 546 |
+
|
| 547 |
+
def _last_media_caption(options: Iterable[str]) -> str:
|
| 548 |
+
caption = ""
|
| 549 |
+
for option in options:
|
| 550 |
+
normalized = option.strip()
|
| 551 |
+
if (
|
| 552 |
+
normalized
|
| 553 |
+
and normalized.casefold() not in _MEDIA_FLAG_OPTIONS
|
| 554 |
+
and _MEDIA_VALUE_OPTION.fullmatch(normalized) is None
|
| 555 |
+
):
|
| 556 |
+
caption = option
|
| 557 |
+
return caption
|
preprocessing/_wikigood/wikigood_ru_csv.py
ADDED
|
@@ -0,0 +1,453 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Portable streaming CSV preparation for the pinned Russian Wikipedia corpora.
|
| 2 |
+
|
| 3 |
+
Verification checks source binding and serialized structure, not NLP replay.
|
| 4 |
+
Targets must be fresh and disjoint; failed builds are retained for inspection.
|
| 5 |
+
"""
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
import argparse
|
| 9 |
+
from collections import Counter
|
| 10 |
+
import csv
|
| 11 |
+
import gzip
|
| 12 |
+
from io import StringIO
|
| 13 |
+
from hashlib import sha256
|
| 14 |
+
from importlib.metadata import version
|
| 15 |
+
from itertools import zip_longest
|
| 16 |
+
import json
|
| 17 |
+
import os
|
| 18 |
+
from pathlib import Path
|
| 19 |
+
import platform
|
| 20 |
+
import re
|
| 21 |
+
import shutil
|
| 22 |
+
import sqlite3
|
| 23 |
+
import sys
|
| 24 |
+
from urllib.parse import unquote
|
| 25 |
+
from urllib.request import urlopen
|
| 26 |
+
import zipfile
|
| 27 |
+
|
| 28 |
+
from .wikigood_ru_nlp import create_wikigood_ru_lemmatizer, select_wikigood_ru_ngrams
|
| 29 |
+
from .wikigood_ru_vw import WikiGoodRuDocument, format_wikigood_ru_vw_row
|
| 30 |
+
|
| 31 |
+
SOURCE_PINS = {
|
| 32 |
+
'full': {'repository': 'TopicNet/RuWiki-Good-2026-V2', 'revision': '3c6bdb4ddc1be38b4fd63a480bdd056394a04934', 'count': 17413,
|
| 33 |
+
'articles': {'sha256': 'c51f9b6bee4c85f25ffb861060f52490a9276bae289d2aa2db7e0d10e2dda950', 'byte_size': 409970311}},
|
| 34 |
+
'selected': {'repository': 'TopicNet/RuWiki-Good-2026-V2-Selected', 'revision': 'fc1ad9b9491ab122614a95b3aa78b3cdfa5e3881', 'count': 17251,
|
| 35 |
+
'articles': {'sha256': '9eb7efffe99fc7c9bc3f4b3eb9f0378d91f387081f97cf9abea9c1686797c1ed', 'byte_size': 413342335},
|
| 36 |
+
'topics': {'sha256': 'c8cf602a924f18255e155cdcaa9357907461851e849113c72051c2b89484f22c', 'byte_size': 2671}},
|
| 37 |
+
}
|
| 38 |
+
STOPWORDS = {'sha256': '48c0e52d8b52546e827f53761fb30300c0ab94f70660d28bd65ba0a86270946b', 'byte_size': 37733}
|
| 39 |
+
STOPWORDS_URL = 'https://raw.githubusercontent.com/nltk/nltk_data/550b6625bcef1f2abff2ff770a5a0d272c9c6b2a/packages/corpora/stopwords.zip'
|
| 40 |
+
RUSSIAN_STOPWORDS_SHA256 = '1743191192b4a4f77fcc216499455dc00c1b8626fdd407076a8deefff80e3d59'
|
| 41 |
+
RUNTIME = {'python': '3.11.15', 'packages': {'spacy': '3.8.14', 'pymorphy3': '2.0.6', 'nltk': '3.9.2'}}
|
| 42 |
+
MODALITIES = ['@title', '@word', '@bigram', '@trigram', '@category']
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def _json(value):
|
| 46 |
+
return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(',', ':')) + '\n'
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def _progress(corpus, phase, processed, total, *, normalized=None):
|
| 50 |
+
detail = '' if normalized is None else f' normalized={normalized}'
|
| 51 |
+
print(f'PROGRESS corpus={corpus} phase={phase} processed={processed}/{total}{detail}',
|
| 52 |
+
file=sys.stderr, flush=True)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def _safe(path):
|
| 56 |
+
path = Path(path).absolute()
|
| 57 |
+
if any(part.is_symlink() for part in (path, *path.parents)):
|
| 58 |
+
raise ValueError(f'symbolic links are forbidden: {path}')
|
| 59 |
+
return path
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def _record(path):
|
| 63 |
+
path = _safe(path)
|
| 64 |
+
if not path.is_file():
|
| 65 |
+
raise ValueError(f'expected regular file: {path}')
|
| 66 |
+
digest = sha256()
|
| 67 |
+
with path.open('rb') as stream:
|
| 68 |
+
for chunk in iter(lambda: stream.read(1024 * 1024), b''):
|
| 69 |
+
digest.update(chunk)
|
| 70 |
+
return {'sha256': digest.hexdigest(), 'byte_size': path.stat().st_size}
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def _datasets(dataset):
|
| 74 |
+
if dataset not in ('full', 'selected', 'both'):
|
| 75 |
+
raise ValueError('dataset must be full, selected or both')
|
| 76 |
+
return ('full', 'selected') if dataset == 'both' else (dataset,)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def _rows(path):
|
| 80 |
+
with gzip.open(_safe(path), 'rt', encoding='utf-8', newline='') as stream:
|
| 81 |
+
for line in stream:
|
| 82 |
+
row = json.loads(line)
|
| 83 |
+
if not isinstance(row, dict):
|
| 84 |
+
raise ValueError('JSONL record must be an object')
|
| 85 |
+
yield row
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def validate_wikigood_ru_csv_sources(sources_dir: str | Path, *, dataset: str = 'both') -> dict[str, object]:
|
| 89 |
+
"""Hash every required pinned source before any output creation."""
|
| 90 |
+
sources = _safe(sources_dir)
|
| 91 |
+
identities = {}
|
| 92 |
+
for name in _datasets(dataset):
|
| 93 |
+
pin = SOURCE_PINS[name]
|
| 94 |
+
kinds = ('articles', 'topics') if name == 'selected' else ('articles',)
|
| 95 |
+
_progress(name, 'sources', 0, len(kinds))
|
| 96 |
+
for kind in kinds:
|
| 97 |
+
relative = f'{name}/{kind}.jsonl.gz'
|
| 98 |
+
observed = _record(sources / relative)
|
| 99 |
+
if observed != pin[kind]:
|
| 100 |
+
raise ValueError(f'pinned source hash/size mismatch: {relative}')
|
| 101 |
+
identities[relative] = observed
|
| 102 |
+
_progress(name, 'sources', len(kinds), len(kinds))
|
| 103 |
+
return identities
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def download_wikigood_ru_csv_sources(sources_dir: str | Path, *, dataset: str = 'both') -> dict[str, object]:
|
| 107 |
+
"""Download immutable source revisions and the pinned NLTK resource.
|
| 108 |
+
|
| 109 |
+
Existing valid files are reused. Partial/invalid files are never overwritten.
|
| 110 |
+
"""
|
| 111 |
+
sources = _safe(sources_dir)
|
| 112 |
+
requests = []
|
| 113 |
+
for name in _datasets(dataset):
|
| 114 |
+
pin = SOURCE_PINS[name]
|
| 115 |
+
kinds = ('articles', 'topics') if name == 'selected' else ('articles',)
|
| 116 |
+
_progress(name, 'sources', 0, len(kinds))
|
| 117 |
+
for kind in kinds:
|
| 118 |
+
requests.append((sources / name / f'{kind}.jsonl.gz', pin[kind],
|
| 119 |
+
f"https://huggingface.co/datasets/{pin['repository']}/resolve/{pin['revision']}/data/{kind}.jsonl.gz"))
|
| 120 |
+
requests.append((sources / 'nltk_data/corpora/stopwords.zip', STOPWORDS, STOPWORDS_URL))
|
| 121 |
+
for path, expected, url in requests:
|
| 122 |
+
_safe(path)
|
| 123 |
+
if path.exists():
|
| 124 |
+
if _record(path) != expected:
|
| 125 |
+
raise ValueError(f'existing source does not match pin: {path}')
|
| 126 |
+
continue
|
| 127 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 128 |
+
with urlopen(url) as remote, path.open('xb') as local:
|
| 129 |
+
shutil.copyfileobj(remote, local)
|
| 130 |
+
if _record(path) != expected:
|
| 131 |
+
raise ValueError(f'download does not match pin: {path}')
|
| 132 |
+
return validate_wikigood_ru_csv_sources(sources, dataset=dataset)
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def _runtime(nltk_data):
|
| 136 |
+
observed = {'python': platform.python_version(), 'packages': {name: version(name) for name in RUNTIME['packages']}}
|
| 137 |
+
if observed != RUNTIME:
|
| 138 |
+
raise ValueError(f'quality-nlp requires pinned scientific runtime: {RUNTIME}; observed {observed}')
|
| 139 |
+
nltk_data = _safe(nltk_data)
|
| 140 |
+
archive = nltk_data / 'corpora/stopwords.zip'
|
| 141 |
+
extracted = nltk_data / 'corpora/stopwords/russian'
|
| 142 |
+
if extracted.exists():
|
| 143 |
+
russian = _safe(extracted).read_bytes()
|
| 144 |
+
if sha256(russian).hexdigest() != RUSSIAN_STOPWORDS_SHA256:
|
| 145 |
+
raise ValueError('extracted Russian stopwords resource hash mismatch')
|
| 146 |
+
if archive.exists():
|
| 147 |
+
if _record(archive) != STOPWORDS:
|
| 148 |
+
raise ValueError('NLTK stopwords archive hash mismatch')
|
| 149 |
+
with zipfile.ZipFile(archive) as stream:
|
| 150 |
+
russian = stream.read('stopwords/russian')
|
| 151 |
+
else:
|
| 152 |
+
russian = _safe(extracted).read_bytes()
|
| 153 |
+
if sha256(russian).hexdigest() != RUSSIAN_STOPWORDS_SHA256:
|
| 154 |
+
raise ValueError('Russian stopwords resource hash mismatch')
|
| 155 |
+
os.environ['NLTK_DATA'] = str(nltk_data)
|
| 156 |
+
import nltk
|
| 157 |
+
nltk.data.path[:] = [str(nltk_data)]
|
| 158 |
+
lemmatize = create_wikigood_ru_lemmatizer()
|
| 159 |
+
if not lemmatize('Проверка русского языка'):
|
| 160 |
+
raise ValueError('Russian NLP runtime probe failed')
|
| 161 |
+
return lemmatize
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
def _topics(sources, names):
|
| 165 |
+
if 'selected' not in names:
|
| 166 |
+
return set()
|
| 167 |
+
topics = list(_rows(sources / 'selected/topics.jsonl.gz'))
|
| 168 |
+
if any(set(row) != {'slug', 'name_ru', 'name_en', 'definition_and_boundaries'} or any(not isinstance(value, str) or not value for value in row.values()) for row in topics):
|
| 169 |
+
raise ValueError('invalid topic catalog schema')
|
| 170 |
+
slugs = [row.get('slug') for row in topics]
|
| 171 |
+
if (not slugs or any(not isinstance(slug, str) or not re.fullmatch('[a-z][a-z0-9_-]*', slug) for slug in slugs)
|
| 172 |
+
or len(set(slugs)) != len(slugs)):
|
| 173 |
+
raise ValueError('invalid or duplicate topic slugs')
|
| 174 |
+
return set(slugs)
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def _articles(sources, name, topic_slugs):
|
| 178 |
+
previous = 0
|
| 179 |
+
count = 0
|
| 180 |
+
for row in _rows(sources / name / 'articles.jsonl.gz'):
|
| 181 |
+
page_id = row.get('page_id')
|
| 182 |
+
if type(page_id) is not int or page_id <= previous or row.get('id') != f'ruwiki/{page_id}':
|
| 183 |
+
raise ValueError('source IDs must be unique, numeric and increasing')
|
| 184 |
+
previous = page_id
|
| 185 |
+
for field in ('title', 'raw_text'):
|
| 186 |
+
if not isinstance(row.get(field), str):
|
| 187 |
+
raise ValueError(f'invalid source {field}')
|
| 188 |
+
categories = row.get('categories')
|
| 189 |
+
if not isinstance(categories, list) or any(not isinstance(value, str) or not value for value in categories):
|
| 190 |
+
raise ValueError('invalid direct categories')
|
| 191 |
+
if name == 'selected':
|
| 192 |
+
topics = row.get('topics')
|
| 193 |
+
if (not isinstance(topics, list) or not topics or any(not isinstance(topic, str) for topic in topics)
|
| 194 |
+
or topics != sorted(set(topics)) or not set(topics) <= topic_slugs):
|
| 195 |
+
raise ValueError('invalid source topic binding')
|
| 196 |
+
count += 1
|
| 197 |
+
yield row
|
| 198 |
+
if count != SOURCE_PINS[name]['count']:
|
| 199 |
+
raise ValueError(f'source document count mismatch: {name}: {count}')
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
class _Words:
|
| 203 |
+
"""Replay disk-backed token sequences in source order for NLTK's two passes."""
|
| 204 |
+
def __init__(self, connection, name):
|
| 205 |
+
self.connection, self.name = connection, name
|
| 206 |
+
|
| 207 |
+
def __iter__(self):
|
| 208 |
+
for (payload,) in self.connection.execute('SELECT tokens FROM tokens JOIN members USING(page_id) WHERE corpus=? ORDER BY page_id', (self.name,)):
|
| 209 |
+
yield json.loads(payload)['word']
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
def build_wikigood_ru_csv(
|
| 213 |
+
sources_dir: str | Path, *, output_dir: str | Path, scratch_dir: str | Path,
|
| 214 |
+
dataset: str = 'both', nltk_data: str | Path | None = None,
|
| 215 |
+
) -> dict[str, object]:
|
| 216 |
+
"""Normalize common articles once, spool tokens, and write separate corpora."""
|
| 217 |
+
sources, output, scratch = map(_safe, (sources_dir, output_dir, scratch_dir))
|
| 218 |
+
paths = (sources.resolve(), output.resolve(), scratch.resolve())
|
| 219 |
+
if any(a == b or a.is_relative_to(b) or b.is_relative_to(a) for i, a in enumerate(paths) for b in paths[i + 1:]):
|
| 220 |
+
raise ValueError('sources, output and scratch must be disjoint')
|
| 221 |
+
for target in (output, scratch):
|
| 222 |
+
if target.exists():
|
| 223 |
+
raise FileExistsError(f'target must be fresh: {target}')
|
| 224 |
+
if not target.parent.is_dir():
|
| 225 |
+
raise ValueError(f'target parent must exist: {target.parent}')
|
| 226 |
+
names = _datasets(dataset)
|
| 227 |
+
identities = validate_wikigood_ru_csv_sources(sources, dataset=dataset)
|
| 228 |
+
topic_slugs = _topics(sources, names)
|
| 229 |
+
_progress(dataset, 'nlp-runtime', 0, 1)
|
| 230 |
+
lemmatize = _runtime(nltk_data or sources / 'nltk_data')
|
| 231 |
+
_progress(dataset, 'nlp-runtime', 1, 1)
|
| 232 |
+
# A conservative disk gate precedes creation; no time/RSS claims are made.
|
| 233 |
+
minimum = max(64 * 1024**2, sum(entry['byte_size'] for entry in identities.values()) * 12)
|
| 234 |
+
for parent in {output.parent, scratch.parent}:
|
| 235 |
+
if shutil.disk_usage(parent).free < minimum:
|
| 236 |
+
raise OSError(f'insufficient free disk space; require {minimum} bytes')
|
| 237 |
+
scratch.mkdir()
|
| 238 |
+
with sqlite3.connect(scratch / 'tokens.sqlite3') as connection:
|
| 239 |
+
connection.execute('PRAGMA temp_store=MEMORY')
|
| 240 |
+
connection.execute('CREATE TABLE tokens(page_id INTEGER PRIMARY KEY, binding TEXT, tokens TEXT)')
|
| 241 |
+
connection.execute('CREATE TABLE members(corpus TEXT, page_id INTEGER, PRIMARY KEY(corpus,page_id))')
|
| 242 |
+
for name in names:
|
| 243 |
+
total = SOURCE_PINS[name]['count']
|
| 244 |
+
interval = max(1, min(100, total // 10))
|
| 245 |
+
normalized = 0
|
| 246 |
+
_progress(name, 'normalize', 0, total, normalized=normalized)
|
| 247 |
+
for processed, row in enumerate(_articles(sources, name, topic_slugs), 1):
|
| 248 |
+
binding = sha256(_json({key: row[key] for key in ('title', 'raw_text', 'categories')}).encode()).hexdigest()
|
| 249 |
+
existing = connection.execute('SELECT binding FROM tokens WHERE page_id=?', (row['page_id'],)).fetchone()
|
| 250 |
+
if existing is None:
|
| 251 |
+
payload = _json({'title': lemmatize(row['title']), 'word': lemmatize(row['raw_text'])})
|
| 252 |
+
connection.execute('INSERT INTO tokens VALUES(?,?,?)', (row['page_id'], binding, payload))
|
| 253 |
+
normalized += 1
|
| 254 |
+
elif existing[0] != binding:
|
| 255 |
+
raise ValueError('common article content differs between corpora')
|
| 256 |
+
connection.execute('INSERT INTO members VALUES(?,?)', (name, row['page_id']))
|
| 257 |
+
if processed % interval == 0 and processed < total:
|
| 258 |
+
_progress(name, 'normalize', processed, total, normalized=normalized)
|
| 259 |
+
connection.commit()
|
| 260 |
+
_progress(name, 'normalize', total, total, normalized=normalized)
|
| 261 |
+
del lemmatize
|
| 262 |
+
output.mkdir()
|
| 263 |
+
manifest = {'schema': 'wikigood-ru-csv-1', 'datasets': list(names), 'sources': identities,
|
| 264 |
+
'source_pins': {name: SOURCE_PINS[name] for name in names}, 'runtime': RUNTIME,
|
| 265 |
+
'stopwords_sha256': RUSSIAN_STOPWORDS_SHA256, 'corpora': {}, 'files': {},
|
| 266 |
+
'verification': 'source binding and serialized structure; no morphology replay'}
|
| 267 |
+
for name in names:
|
| 268 |
+
total = SOURCE_PINS[name]['count']
|
| 269 |
+
interval = max(1, min(100, total // 10))
|
| 270 |
+
_progress(name, 'ngram-selection', 0, total)
|
| 271 |
+
bigrams, trigrams = select_wikigood_ru_ngrams(_Words(connection, name))
|
| 272 |
+
_progress(name, 'ngram-selection', total, total)
|
| 273 |
+
directory = output / name
|
| 274 |
+
directory.mkdir()
|
| 275 |
+
labels = {}
|
| 276 |
+
empty_word_ids = []
|
| 277 |
+
_progress(name, 'write', 0, total)
|
| 278 |
+
with (directory / 'noow.csv').open('x', encoding='utf-8', newline='') as noow, (directory / 'bow.csv').open('x', encoding='utf-8', newline='') as bow:
|
| 279 |
+
writers = [csv.writer(stream, lineterminator='\n') for stream in (noow, bow)]
|
| 280 |
+
for writer in writers:
|
| 281 |
+
writer.writerow(('id', 'raw_text', 'vw_text'))
|
| 282 |
+
for processed, row in enumerate(_articles(sources, name, topic_slugs), 1):
|
| 283 |
+
tokens = json.loads(connection.execute('SELECT tokens FROM tokens WHERE page_id=?', (row['page_id'],)).fetchone()[0])
|
| 284 |
+
if not tokens['word']:
|
| 285 |
+
empty_word_ids.append(row['id'])
|
| 286 |
+
document = WikiGoodRuDocument(row['page_id'], row['title'], row.get('revision_id', 0), tokens['title'], tokens['word'], row['categories'], '', '')
|
| 287 |
+
topics = row['topics'] if name == 'selected' else None
|
| 288 |
+
if topics is not None:
|
| 289 |
+
labels[row['id']] = topics
|
| 290 |
+
raw = row['title'] + '\n\n' + row['raw_text'].lstrip('\r\n')
|
| 291 |
+
for is_bow, writer in enumerate(writers):
|
| 292 |
+
vw = format_wikigood_ru_vw_row(row['id'], document, accepted_bigrams=bigrams, accepted_trigrams=trigrams, topics=topics, bow=bool(is_bow))
|
| 293 |
+
writer.writerow((row['id'], raw, vw))
|
| 294 |
+
if processed % interval == 0 and processed < total:
|
| 295 |
+
_progress(name, 'write', processed, total)
|
| 296 |
+
_progress(name, 'write', total, total)
|
| 297 |
+
if name == 'selected':
|
| 298 |
+
(directory / 'labels.json').write_text(_json(labels), encoding='utf-8')
|
| 299 |
+
manifest['corpora'][name] = {'count': total, 'bigrams': sorted(bigrams), 'trigrams': sorted(trigrams),
|
| 300 |
+
'empty_word_count': len(empty_word_ids), 'empty_word_ids': empty_word_ids}
|
| 301 |
+
for path in sorted(directory.iterdir()):
|
| 302 |
+
manifest['files'][str(path.relative_to(output))] = _record(path)
|
| 303 |
+
manifest['manifest_sha256'] = sha256(_json(manifest).encode()).hexdigest()
|
| 304 |
+
(output / 'manifest.json').write_text(_json(manifest), encoding='utf-8')
|
| 305 |
+
verify_wikigood_ru_csv(sources, output_dir=output, dataset=dataset)
|
| 306 |
+
return manifest
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
def _escape(value, *, ngram=False):
|
| 310 |
+
return ''.join(''.join(f'%{byte:02X}' for byte in char.encode('utf-8'))
|
| 311 |
+
if char in ('%|:_' if ngram else '%|:') or char.isspace() or not char.isprintable() else char for char in value)
|
| 312 |
+
|
| 313 |
+
|
| 314 |
+
def _parse_vw(value, document_id, names, *, bow):
|
| 315 |
+
sections = value.split(' |')
|
| 316 |
+
if sections.pop(0) != document_id or len(sections) != len(names):
|
| 317 |
+
raise ValueError('VW identity or namespace count mismatch')
|
| 318 |
+
result = {}
|
| 319 |
+
for expected, section in zip(names, sections):
|
| 320 |
+
fields = section.split(' ')
|
| 321 |
+
if fields.pop(0) != expected or any(not field for field in fields):
|
| 322 |
+
raise ValueError('VW namespace order or spacing mismatch')
|
| 323 |
+
if bow:
|
| 324 |
+
pairs = [field.rsplit(':', 1) for field in fields]
|
| 325 |
+
if any(len(pair) != 2 or not re.fullmatch('[1-9][0-9]*', pair[1]) for pair in pairs):
|
| 326 |
+
raise ValueError('invalid BOW frequency')
|
| 327 |
+
tokens = [pair[0] for pair in pairs]
|
| 328 |
+
if tokens != sorted(set(tokens)):
|
| 329 |
+
raise ValueError('BOW tokens must be sorted and unique')
|
| 330 |
+
result[expected] = Counter({token: int(count) for token, count in pairs})
|
| 331 |
+
else:
|
| 332 |
+
for token in fields:
|
| 333 |
+
decoded = unquote(token, encoding='utf-8', errors='strict')
|
| 334 |
+
if ('_'.join(_escape(unquote(piece, encoding='utf-8', errors='strict'), ngram=True) for piece in token.split('_')) if expected in ('@bigram', '@trigram') else _escape(decoded)) != token:
|
| 335 |
+
raise ValueError('unsafe or noncanonical VW escaping')
|
| 336 |
+
result[expected] = fields
|
| 337 |
+
return result
|
| 338 |
+
|
| 339 |
+
|
| 340 |
+
def verify_wikigood_ru_csv(
|
| 341 |
+
sources_dir: str | Path, *, output_dir: str | Path, dataset: str = 'both',
|
| 342 |
+
) -> dict[str, object]:
|
| 343 |
+
"""Independently check source/CSV/label structure without invoking NLP."""
|
| 344 |
+
sources, output = map(_safe, (sources_dir, output_dir))
|
| 345 |
+
names = _datasets(dataset)
|
| 346 |
+
identities = validate_wikigood_ru_csv_sources(sources, dataset=dataset)
|
| 347 |
+
manifest = json.loads(_safe(output / 'manifest.json').read_text(encoding='utf-8'))
|
| 348 |
+
if not isinstance(manifest, dict) or set(manifest) != {'schema', 'datasets', 'sources', 'source_pins', 'runtime', 'stopwords_sha256', 'corpora', 'files', 'verification', 'manifest_sha256'}:
|
| 349 |
+
raise ValueError('manifest schema mismatch')
|
| 350 |
+
unsigned = {key: value for key, value in manifest.items() if key != 'manifest_sha256'}
|
| 351 |
+
if manifest['manifest_sha256'] != sha256(_json(unsigned).encode()).hexdigest():
|
| 352 |
+
raise ValueError('manifest integrity mismatch')
|
| 353 |
+
if (manifest['schema'] != 'wikigood-ru-csv-1' or manifest['datasets'] != list(names) or _json(manifest['sources']) != _json(identities)
|
| 354 |
+
or _json(manifest['source_pins']) != _json({name: SOURCE_PINS[name] for name in names}) or manifest['runtime'] != RUNTIME
|
| 355 |
+
or manifest['stopwords_sha256'] != RUSSIAN_STOPWORDS_SHA256 or set(manifest['corpora']) != set(names)
|
| 356 |
+
or manifest['verification'] != 'source binding and serialized structure; no morphology replay'):
|
| 357 |
+
raise ValueError('manifest source/runtime binding mismatch')
|
| 358 |
+
expected_files = {f'{name}/{filename}' for name in names for filename in (('noow.csv', 'bow.csv', 'labels.json') if name == 'selected' else ('noow.csv', 'bow.csv'))}
|
| 359 |
+
actual_files = {str(path.relative_to(output)) for path in output.rglob('*') if path.is_file()}
|
| 360 |
+
if set(manifest['files']) != expected_files or actual_files != expected_files | {'manifest.json'}:
|
| 361 |
+
raise ValueError('output file set mismatch')
|
| 362 |
+
for relative in expected_files:
|
| 363 |
+
if _json(_record(output / relative)) != _json(manifest['files'][relative]):
|
| 364 |
+
raise ValueError(f'output hash mismatch: {relative}')
|
| 365 |
+
topic_slugs = _topics(sources, names)
|
| 366 |
+
csv.field_size_limit(sys.maxsize)
|
| 367 |
+
for name in names:
|
| 368 |
+
info = manifest['corpora'][name]
|
| 369 |
+
if not isinstance(info, dict) or set(info) != {'count', 'bigrams', 'trigrams', 'empty_word_count', 'empty_word_ids'} or type(info['count']) is not int or info['count'] != SOURCE_PINS[name]['count']:
|
| 370 |
+
raise ValueError('manifest corpus schema/count mismatch')
|
| 371 |
+
if (type(info['empty_word_count']) is not int or not isinstance(info['empty_word_ids'], list)
|
| 372 |
+
or any(not isinstance(value, str) for value in info['empty_word_ids'])):
|
| 373 |
+
raise ValueError('manifest empty-word diagnostic type mismatch')
|
| 374 |
+
empty_word_ids = []
|
| 375 |
+
vocab = {}
|
| 376 |
+
for field, size in (('bigrams', 2), ('trigrams', 3)):
|
| 377 |
+
phrases = info[field]
|
| 378 |
+
if not isinstance(phrases, list) or any(not isinstance(p, list) or len(p) != size or any(not isinstance(t, str) or not t for t in p) for p in phrases):
|
| 379 |
+
raise ValueError('invalid accepted ngram vocabulary')
|
| 380 |
+
vocab[field] = {tuple(p) for p in phrases}
|
| 381 |
+
if phrases != [list(p) for p in sorted(vocab[field])]:
|
| 382 |
+
raise ValueError('accepted vocabulary must be sorted and unique')
|
| 383 |
+
labels = json.loads((output / name / 'labels.json').read_text(encoding='utf-8')) if name == 'selected' else None
|
| 384 |
+
expected_labels = {}
|
| 385 |
+
with (output / name / 'noow.csv').open(encoding='utf-8', newline='') as noow, (output / name / 'bow.csv').open(encoding='utf-8', newline='') as bow:
|
| 386 |
+
readers = [csv.reader(stream, strict=True) for stream in (noow, bow)]
|
| 387 |
+
canonical = [sha256(), sha256()]
|
| 388 |
+
def account(index, values):
|
| 389 |
+
buffer = StringIO(newline='')
|
| 390 |
+
csv.writer(buffer, lineterminator='\n').writerow(values)
|
| 391 |
+
canonical[index].update(buffer.getvalue().encode('utf-8'))
|
| 392 |
+
if any(next(reader, None) != ['id', 'raw_text', 'vw_text'] for reader in readers):
|
| 393 |
+
raise ValueError('CSV header mismatch')
|
| 394 |
+
for index in range(2):
|
| 395 |
+
account(index, ['id', 'raw_text', 'vw_text'])
|
| 396 |
+
for row, noow_row, bow_row in zip_longest(_articles(sources, name, topic_slugs), *readers):
|
| 397 |
+
if row is None or noow_row is None or bow_row is None or len(noow_row) != 3 or len(bow_row) != 3:
|
| 398 |
+
raise ValueError('CSV row count or field count mismatch')
|
| 399 |
+
account(0, noow_row)
|
| 400 |
+
account(1, bow_row)
|
| 401 |
+
raw = row['title'] + '\n\n' + row['raw_text'].lstrip('\r\n')
|
| 402 |
+
if noow_row[:2] != [row['id'], raw] or bow_row[:2] != noow_row[:2]:
|
| 403 |
+
raise ValueError('CSV source identity/raw text mismatch')
|
| 404 |
+
namespaces = MODALITIES + (['@topic'] if name == 'selected' else [])
|
| 405 |
+
parsed = _parse_vw(noow_row[2], row['id'], namespaces, bow=False)
|
| 406 |
+
if not parsed['@word']:
|
| 407 |
+
empty_word_ids.append(row['id'])
|
| 408 |
+
counted = _parse_vw(bow_row[2], row['id'], namespaces, bow=True)
|
| 409 |
+
if any(Counter(parsed[ns]) != counted[ns] for ns in namespaces):
|
| 410 |
+
raise ValueError('NOOW/BOW counts differ')
|
| 411 |
+
if parsed['@category'] != [_escape(value) for value in row['categories']]:
|
| 412 |
+
raise ValueError('direct category binding mismatch')
|
| 413 |
+
if name == 'selected':
|
| 414 |
+
expected_labels[row['id']] = row['topics']
|
| 415 |
+
if parsed['@topic'] != [_escape(topic) for topic in row['topics']]:
|
| 416 |
+
raise ValueError('topic namespace binding mismatch')
|
| 417 |
+
words = [unquote(token, encoding='utf-8', errors='strict') for token in parsed['@word']]
|
| 418 |
+
for ns, field, size in (('@bigram', 'bigrams', 2), ('@trigram', 'trigrams', 3)):
|
| 419 |
+
expected = ['_'.join(_escape(token, ngram=True) for token in phrase)
|
| 420 |
+
for phrase in zip(*(words[i:] for i in range(size))) if phrase in vocab[field]]
|
| 421 |
+
if parsed[ns] != expected:
|
| 422 |
+
raise ValueError('ngram occurrence/order mismatch')
|
| 423 |
+
for index, filename in enumerate(('noow.csv', 'bow.csv')):
|
| 424 |
+
if canonical[index].hexdigest() != manifest['files'][f'{name}/{filename}']['sha256']:
|
| 425 |
+
raise ValueError('CSV must use canonical UTF-8 quoting and LF framing')
|
| 426 |
+
if info['empty_word_count'] != len(empty_word_ids) or info['empty_word_ids'] != empty_word_ids:
|
| 427 |
+
raise ValueError('manifest empty-word diagnostic mismatch')
|
| 428 |
+
if labels is not None and labels != expected_labels:
|
| 429 |
+
raise ValueError('Selected labels binding mismatch')
|
| 430 |
+
return manifest
|
| 431 |
+
|
| 432 |
+
|
| 433 |
+
def main(argv=None):
|
| 434 |
+
"""Standalone portable entry point shared with the public wrapper."""
|
| 435 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 436 |
+
parser.add_argument('--action', required=True, choices=('download', 'build', 'verify'))
|
| 437 |
+
parser.add_argument('--dataset', default='both', choices=('full', 'selected', 'both'))
|
| 438 |
+
parser.add_argument('--sources-dir', type=Path, required=True)
|
| 439 |
+
parser.add_argument('--output-dir', type=Path)
|
| 440 |
+
parser.add_argument('--scratch-dir', type=Path)
|
| 441 |
+
parser.add_argument('--nltk-data', type=Path)
|
| 442 |
+
args = parser.parse_args(argv)
|
| 443 |
+
for name in {'download': (), 'build': ('output_dir', 'scratch_dir'), 'verify': ('output_dir',)}[args.action]:
|
| 444 |
+
if getattr(args, name) is None:
|
| 445 |
+
parser.error(f'--{name.replace("_", "-")} is required')
|
| 446 |
+
if args.action == 'download':
|
| 447 |
+
download_wikigood_ru_csv_sources(args.sources_dir, dataset=args.dataset)
|
| 448 |
+
elif args.action == 'build':
|
| 449 |
+
build_wikigood_ru_csv(args.sources_dir, output_dir=args.output_dir, scratch_dir=args.scratch_dir, dataset=args.dataset, nltk_data=args.nltk_data)
|
| 450 |
+
else:
|
| 451 |
+
verify_wikigood_ru_csv(args.sources_dir, output_dir=args.output_dir, dataset=args.dataset)
|
| 452 |
+
print(f'{args.action.upper()}_OK dataset={args.dataset}', flush=True)
|
| 453 |
+
return 0
|
preprocessing/_wikigood/wikigood_ru_nlp.py
ADDED
|
@@ -0,0 +1,229 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
| 1 |
+
"""Deterministic Russian NLP preparation for WikiGood publication artifacts."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import re
|
| 6 |
+
import unicodedata
|
| 7 |
+
from typing import Callable, Iterable, Mapping, Sequence
|
| 8 |
+
|
| 9 |
+
try:
|
| 10 |
+
from .wikigood_ru_content import ExtractedWikiPage
|
| 11 |
+
from .wikigood_ru_vw import WikiGoodRuDocument
|
| 12 |
+
except ImportError: # Direct module imports used by the mirrored fixture tests.
|
| 13 |
+
from wikigood_ru_content import ExtractedWikiPage
|
| 14 |
+
from wikigood_ru_vw import WikiGoodRuDocument
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
_HTML_TAG = re.compile(r"<!--.*?-->|<![^<>]*>|</?[A-Za-z][^<>]*?>", re.DOTALL)
|
| 18 |
+
_STRESS_MARKS = frozenset("\u0300\u0301")
|
| 19 |
+
_LEXICAL_HYPHENS = frozenset("-\u2010\u2011")
|
| 20 |
+
_HYPHEN_TOKEN_CANDIDATE = re.compile(r".+-.+\Z")
|
| 21 |
+
_PLACEHOLDERS = ("<TAG>", "<URL>", "<MAIL>")
|
| 22 |
+
MIN_NGRAM_FREQUENCY = 5
|
| 23 |
+
NGRAM_CANDIDATE_LIMIT = 32_100
|
| 24 |
+
NGRAM_HEAD_SKIP = 100
|
| 25 |
+
NLP_ALGORITHMS = {
|
| 26 |
+
"tokenizer": "spacy.blank-ru",
|
| 27 |
+
"lemmatizer": "pymorphy3-normal-form",
|
| 28 |
+
"stopwords": "spacy-ru-union-nltk-russian",
|
| 29 |
+
"html_spans": "regex-space-bounded-placeholder-TAG",
|
| 30 |
+
"url_spans": "spacy-like-url-placeholder-URL",
|
| 31 |
+
"email_spans": "spacy-like-email-placeholder-MAIL",
|
| 32 |
+
"cyrillic_stress_marks": (
|
| 33 |
+
"remove-u0300-u0301-runs-after-cyrillic-letter-or-token-leading-"
|
| 34 |
+
"before-cyrillic-letter-pre-post-morphology"
|
| 35 |
+
),
|
| 36 |
+
"cyrillic_lexical_hyphens": (
|
| 37 |
+
"normalize-u002d-u2010-u2011-to-ascii-spacy-token-match"
|
| 38 |
+
),
|
| 39 |
+
"person_masking": "disabled",
|
| 40 |
+
"bigram_selector": "nltk-bigram-collocation-pmi",
|
| 41 |
+
"trigram_selector": "nltk-trigram-collocation-pmi",
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def _is_cyrillic_letter(character: str) -> bool:
|
| 46 |
+
return (
|
| 47 |
+
unicodedata.category(character).startswith("L")
|
| 48 |
+
and "CYRILLIC" in unicodedata.name(character, "")
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def _normalize_cyrillic_stress(text: str, *, token_leading: bool = False) -> str:
|
| 53 |
+
characters = []
|
| 54 |
+
index = 0
|
| 55 |
+
while index < len(text):
|
| 56 |
+
if text[index] not in _STRESS_MARKS:
|
| 57 |
+
characters.append(text[index])
|
| 58 |
+
index += 1
|
| 59 |
+
continue
|
| 60 |
+
run_end = index + 1
|
| 61 |
+
while run_end < len(text) and text[run_end] in _STRESS_MARKS:
|
| 62 |
+
run_end += 1
|
| 63 |
+
follows_cyrillic = index > 0 and _is_cyrillic_letter(text[index - 1])
|
| 64 |
+
precedes_cyrillic = run_end < len(text) and _is_cyrillic_letter(
|
| 65 |
+
text[run_end]
|
| 66 |
+
)
|
| 67 |
+
if not (
|
| 68 |
+
follows_cyrillic
|
| 69 |
+
or (token_leading and index == 0 and precedes_cyrillic)
|
| 70 |
+
):
|
| 71 |
+
characters.extend(text[index:run_end])
|
| 72 |
+
index = run_end
|
| 73 |
+
return "".join(characters)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def _prepare_cyrillic_boundaries(text: str) -> str:
|
| 77 |
+
without_stress = _normalize_cyrillic_stress(text)
|
| 78 |
+
characters = list(without_stress)
|
| 79 |
+
for index in range(1, len(characters) - 1):
|
| 80 |
+
if (
|
| 81 |
+
characters[index] in _LEXICAL_HYPHENS
|
| 82 |
+
and _is_cyrillic_letter(characters[index - 1])
|
| 83 |
+
and _is_cyrillic_letter(characters[index + 1])
|
| 84 |
+
):
|
| 85 |
+
characters[index] = "-"
|
| 86 |
+
return "".join(characters)
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def _match_cyrillic_hyphen_token(text: str) -> re.Match[str] | None:
|
| 90 |
+
candidate = _HYPHEN_TOKEN_CANDIDATE.fullmatch(text)
|
| 91 |
+
parts = text.split("-")
|
| 92 |
+
if candidate is not None and all(
|
| 93 |
+
part and all(_is_cyrillic_letter(character) for character in part)
|
| 94 |
+
for part in parts
|
| 95 |
+
):
|
| 96 |
+
return candidate
|
| 97 |
+
return None
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def create_wikigood_ru_lemmatizer() -> Callable[[str], tuple[str, ...]]:
|
| 101 |
+
"""Create the shared Russian tokenizer with its per-instance lemma cache."""
|
| 102 |
+
|
| 103 |
+
try:
|
| 104 |
+
import pymorphy3
|
| 105 |
+
import spacy
|
| 106 |
+
from nltk.corpus import stopwords
|
| 107 |
+
from spacy.lang.ru.stop_words import STOP_WORDS
|
| 108 |
+
from spacy.symbols import ORTH
|
| 109 |
+
except ImportError as error:
|
| 110 |
+
raise RuntimeError(
|
| 111 |
+
"spaCy, pymorphy3, NLTK, and the NLTK stopwords corpus are required "
|
| 112 |
+
"for WikiGood-RU NLP"
|
| 113 |
+
) from error
|
| 114 |
+
|
| 115 |
+
tokenizer = spacy.blank("ru")
|
| 116 |
+
default_token_match = tokenizer.tokenizer.token_match
|
| 117 |
+
tokenizer.tokenizer.token_match = lambda text: (
|
| 118 |
+
_match_cyrillic_hyphen_token(text)
|
| 119 |
+
or (default_token_match(text) if default_token_match is not None else None)
|
| 120 |
+
)
|
| 121 |
+
for placeholder in _PLACEHOLDERS:
|
| 122 |
+
tokenizer.tokenizer.add_special_case(placeholder, [{ORTH: placeholder}])
|
| 123 |
+
morphology = pymorphy3.MorphAnalyzer()
|
| 124 |
+
russian_stopwords = frozenset(STOP_WORDS) | frozenset(
|
| 125 |
+
stopwords.words("russian")
|
| 126 |
+
)
|
| 127 |
+
lemma_cache: dict[str, str] = {}
|
| 128 |
+
|
| 129 |
+
def lemmatize(text: str) -> tuple[str, ...]:
|
| 130 |
+
prepared = _prepare_cyrillic_boundaries(text)
|
| 131 |
+
prepared = _HTML_TAG.sub(" <TAG> ", prepared)
|
| 132 |
+
lemmas = []
|
| 133 |
+
for token in tokenizer(prepared):
|
| 134 |
+
if token.text in _PLACEHOLDERS:
|
| 135 |
+
lemmas.append(token.text)
|
| 136 |
+
continue
|
| 137 |
+
if token.like_url:
|
| 138 |
+
lemmas.append("<URL>")
|
| 139 |
+
continue
|
| 140 |
+
if token.like_email:
|
| 141 |
+
lemmas.append("<MAIL>")
|
| 142 |
+
continue
|
| 143 |
+
if token.is_space or token.is_punct:
|
| 144 |
+
continue
|
| 145 |
+
normalized_token = _normalize_cyrillic_stress(
|
| 146 |
+
token.text, token_leading=True
|
| 147 |
+
)
|
| 148 |
+
lemma = lemma_cache.get(normalized_token)
|
| 149 |
+
if lemma is None:
|
| 150 |
+
lemma = _normalize_cyrillic_stress(
|
| 151 |
+
morphology.parse(normalized_token)[0].normal_form.lower(),
|
| 152 |
+
token_leading=True,
|
| 153 |
+
)
|
| 154 |
+
lemma_cache[normalized_token] = lemma
|
| 155 |
+
if (
|
| 156 |
+
normalized_token.lower() not in russian_stopwords
|
| 157 |
+
and lemma not in russian_stopwords
|
| 158 |
+
):
|
| 159 |
+
lemmas.append(lemma)
|
| 160 |
+
return tuple(lemmas)
|
| 161 |
+
|
| 162 |
+
return lemmatize
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def select_wikigood_ru_ngrams(
|
| 166 |
+
word_sequences: Iterable[Sequence[str]],
|
| 167 |
+
) -> tuple[frozenset[tuple[str, str]], frozenset[tuple[str, str, str]]]:
|
| 168 |
+
"""Select independent PMI sets from two passes over replayable documents.
|
| 169 |
+
|
| 170 |
+
The input must support a fresh iteration for each n-gram size. Documents
|
| 171 |
+
may be read from disk on each pass; this function never collects them.
|
| 172 |
+
"""
|
| 173 |
+
|
| 174 |
+
from nltk.collocations import (
|
| 175 |
+
BigramAssocMeasures,
|
| 176 |
+
BigramCollocationFinder,
|
| 177 |
+
TrigramAssocMeasures,
|
| 178 |
+
TrigramCollocationFinder,
|
| 179 |
+
)
|
| 180 |
+
|
| 181 |
+
bigram_finder = BigramCollocationFinder.from_documents(word_sequences)
|
| 182 |
+
bigram_finder.apply_freq_filter(MIN_NGRAM_FREQUENCY)
|
| 183 |
+
accepted_bigrams = frozenset(
|
| 184 |
+
bigram_finder.nbest(BigramAssocMeasures().pmi, NGRAM_CANDIDATE_LIMIT)[
|
| 185 |
+
NGRAM_HEAD_SKIP:
|
| 186 |
+
]
|
| 187 |
+
)
|
| 188 |
+
del bigram_finder
|
| 189 |
+
|
| 190 |
+
trigram_finder = TrigramCollocationFinder.from_documents(word_sequences)
|
| 191 |
+
trigram_finder.apply_freq_filter(MIN_NGRAM_FREQUENCY)
|
| 192 |
+
accepted_trigrams = frozenset(
|
| 193 |
+
trigram_finder.nbest(TrigramAssocMeasures().pmi, NGRAM_CANDIDATE_LIMIT)[
|
| 194 |
+
NGRAM_HEAD_SKIP:
|
| 195 |
+
]
|
| 196 |
+
)
|
| 197 |
+
return accepted_bigrams, accepted_trigrams
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def prepare_wikigood_ru_nlp(
|
| 201 |
+
pages: Iterable[ExtractedWikiPage],
|
| 202 |
+
categories_by_page_id: Mapping[int, Sequence[str]],
|
| 203 |
+
) -> tuple[
|
| 204 |
+
tuple[WikiGoodRuDocument, ...],
|
| 205 |
+
frozenset[tuple[str, str]],
|
| 206 |
+
frozenset[tuple[str, str, str]],
|
| 207 |
+
]:
|
| 208 |
+
"""Lemmatize extracted pages and select independent PMI n-gram sets."""
|
| 209 |
+
|
| 210 |
+
lemmatize = create_wikigood_ru_lemmatizer()
|
| 211 |
+
documents = tuple(
|
| 212 |
+
WikiGoodRuDocument(
|
| 213 |
+
page_id=page.page_id,
|
| 214 |
+
canonical_title=page.canonical_title,
|
| 215 |
+
revision_id=page.revision_id,
|
| 216 |
+
title_tokens=lemmatize(page.canonical_title),
|
| 217 |
+
word_tokens=lemmatize(page.raw_text),
|
| 218 |
+
categories=tuple(categories_by_page_id[page.page_id]),
|
| 219 |
+
wikitext_sha256=page.wikitext_sha256,
|
| 220 |
+
raw_text_sha256=page.raw_text_sha256,
|
| 221 |
+
)
|
| 222 |
+
for page in sorted(pages, key=lambda item: item.page_id)
|
| 223 |
+
)
|
| 224 |
+
word_sequences = tuple(document.word_tokens for document in documents)
|
| 225 |
+
|
| 226 |
+
accepted_bigrams, accepted_trigrams = select_wikigood_ru_ngrams(
|
| 227 |
+
word_sequences
|
| 228 |
+
)
|
| 229 |
+
return documents, accepted_bigrams, accepted_trigrams
|
preprocessing/_wikigood/wikigood_ru_vw.py
ADDED
|
@@ -0,0 +1,996 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Deterministic Vowpal Wabbit artifacts for the RU-only WikiGood dataset."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from collections import Counter
|
| 6 |
+
from contextlib import ExitStack
|
| 7 |
+
import ctypes
|
| 8 |
+
import csv
|
| 9 |
+
from dataclasses import dataclass
|
| 10 |
+
import errno
|
| 11 |
+
import gzip
|
| 12 |
+
from io import TextIOWrapper
|
| 13 |
+
import os
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
import re
|
| 16 |
+
import secrets
|
| 17 |
+
import stat
|
| 18 |
+
from typing import Collection, Iterable, Sequence
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
SNAPSHOT = "20260801"
|
| 22 |
+
QUALITY_FULL_SOURCE_SPEC_SHA256 = "7783a4597fdfde890a132895cb7ba87d63f86d973a2fe91d7b9e411653d1117d"
|
| 23 |
+
MODALITIES = ("@title", "@word", "@bigram", "@trigram", "@category")
|
| 24 |
+
CORE_MODEL_MODALITIES = ("@word",)
|
| 25 |
+
PROVENANCE_FIELDS = (
|
| 26 |
+
"id",
|
| 27 |
+
"page_id",
|
| 28 |
+
"canonical_title",
|
| 29 |
+
"revision_id",
|
| 30 |
+
"source_url",
|
| 31 |
+
"wikitext_sha256",
|
| 32 |
+
"raw_text_sha256",
|
| 33 |
+
)
|
| 34 |
+
NOOW_FILENAME = f"wikigood_ru_{SNAPSHOT}_noow.txt"
|
| 35 |
+
BOW_FILENAME = f"wikigood_ru_{SNAPSHOT}_bow.txt"
|
| 36 |
+
PROVENANCE_FILENAME = f"wikigood_ru_{SNAPSHOT}_provenance.csv"
|
| 37 |
+
OUTPUT_FILENAMES = (
|
| 38 |
+
NOOW_FILENAME,
|
| 39 |
+
f"{NOOW_FILENAME}.gz",
|
| 40 |
+
BOW_FILENAME,
|
| 41 |
+
f"{BOW_FILENAME}.gz",
|
| 42 |
+
PROVENANCE_FILENAME,
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
_SHA256 = re.compile(r"[0-9a-f]{64}\Z")
|
| 46 |
+
_VW_RESERVED = frozenset("%|:")
|
| 47 |
+
_GZIP_COMPRESSION_LEVEL = 9
|
| 48 |
+
_RENAME_NOREPLACE = 1
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
@dataclass(frozen=True, slots=True)
|
| 52 |
+
class WikiGoodRuDocument:
|
| 53 |
+
"""Processed document plus content hashes retained for provenance."""
|
| 54 |
+
|
| 55 |
+
page_id: int
|
| 56 |
+
canonical_title: str
|
| 57 |
+
revision_id: int
|
| 58 |
+
title_tokens: Sequence[str]
|
| 59 |
+
word_tokens: Sequence[str]
|
| 60 |
+
categories: Sequence[str]
|
| 61 |
+
wikitext_sha256: str
|
| 62 |
+
raw_text_sha256: str
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def format_wikigood_ru_vw_row(
|
| 66 |
+
document_id: str,
|
| 67 |
+
document: WikiGoodRuDocument,
|
| 68 |
+
*,
|
| 69 |
+
accepted_bigrams: Collection[tuple[str, str]],
|
| 70 |
+
accepted_trigrams: Collection[tuple[str, str, str]],
|
| 71 |
+
topics: Iterable[str] | None = None,
|
| 72 |
+
bow: bool = False,
|
| 73 |
+
) -> str:
|
| 74 |
+
"""Format one row without a newline, optionally appending distinct topics."""
|
| 75 |
+
|
| 76 |
+
modalities = _document_modalities(
|
| 77 |
+
document, accepted_bigrams, accepted_trigrams
|
| 78 |
+
)
|
| 79 |
+
if topics is not None:
|
| 80 |
+
modalities += (
|
| 81 |
+
("@topic", tuple(_escape_vw(topic) for topic in dict.fromkeys(topics))),
|
| 82 |
+
)
|
| 83 |
+
formatter = _format_bow if bow else _format_noow
|
| 84 |
+
return formatter(document_id, modalities).removesuffix("\n")
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def write_wikigood_ru_artifacts(
|
| 88 |
+
documents: Iterable[WikiGoodRuDocument],
|
| 89 |
+
output_dir: str | Path,
|
| 90 |
+
*,
|
| 91 |
+
accepted_bigrams: Collection[tuple[str, str]],
|
| 92 |
+
accepted_trigrams: Collection[tuple[str, str, str]],
|
| 93 |
+
) -> tuple[Path, ...]:
|
| 94 |
+
"""Write new-only NOOW, BOW, gzip, and provenance artifacts.
|
| 95 |
+
|
| 96 |
+
The NLP stage remains outside this module: title and word sequences must
|
| 97 |
+
already be lemmatized, while categories are direct visible category titles.
|
| 98 |
+
Only ``@word`` is eligible for core modeling; the other modalities are
|
| 99 |
+
publication artifacts.
|
| 100 |
+
"""
|
| 101 |
+
|
| 102 |
+
target = Path(output_dir)
|
| 103 |
+
ordered = tuple(sorted(documents, key=lambda document: document.page_id))
|
| 104 |
+
bigrams = _validated_ngrams(accepted_bigrams, 2)
|
| 105 |
+
trigrams = _validated_ngrams(accepted_trigrams, 3)
|
| 106 |
+
_validate_documents(ordered)
|
| 107 |
+
(
|
| 108 |
+
parent_descriptor,
|
| 109 |
+
staging_name,
|
| 110 |
+
staging_descriptor,
|
| 111 |
+
staging_identity,
|
| 112 |
+
) = _create_owned_output_directory(target)
|
| 113 |
+
owned_identities: dict[str, tuple[int, int]] = {}
|
| 114 |
+
try:
|
| 115 |
+
_write_wikigood_ru_artifacts_at(
|
| 116 |
+
ordered,
|
| 117 |
+
staging_descriptor,
|
| 118 |
+
accepted_bigrams=bigrams,
|
| 119 |
+
accepted_trigrams=trigrams,
|
| 120 |
+
owned_identities=owned_identities,
|
| 121 |
+
)
|
| 122 |
+
os.fchmod(staging_descriptor, 0o755)
|
| 123 |
+
os.fsync(staging_descriptor)
|
| 124 |
+
_require_owned_identities(staging_descriptor, owned_identities)
|
| 125 |
+
_publish_owned_output_directory(
|
| 126 |
+
target,
|
| 127 |
+
parent_descriptor,
|
| 128 |
+
staging_name,
|
| 129 |
+
staging_descriptor,
|
| 130 |
+
staging_identity,
|
| 131 |
+
)
|
| 132 |
+
except BaseException:
|
| 133 |
+
_clean_owned_files(staging_descriptor, owned_identities)
|
| 134 |
+
_remove_owned_output_directory(
|
| 135 |
+
parent_descriptor, staging_name, staging_identity
|
| 136 |
+
)
|
| 137 |
+
_remove_owned_output_directory(
|
| 138 |
+
parent_descriptor, target.name, staging_identity
|
| 139 |
+
)
|
| 140 |
+
raise
|
| 141 |
+
finally:
|
| 142 |
+
os.close(staging_descriptor)
|
| 143 |
+
os.close(parent_descriptor)
|
| 144 |
+
return tuple(target / name for name in OUTPUT_FILENAMES)
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def _write_wikigood_ru_artifacts_at(
|
| 148 |
+
documents: Iterable[WikiGoodRuDocument],
|
| 149 |
+
directory_descriptor: int,
|
| 150 |
+
*,
|
| 151 |
+
accepted_bigrams: Collection[tuple[str, str]],
|
| 152 |
+
accepted_trigrams: Collection[tuple[str, str, str]],
|
| 153 |
+
owned_identities: dict[str, tuple[int, int]],
|
| 154 |
+
) -> None:
|
| 155 |
+
"""Write artifacts into a caller-owned unpublished directory."""
|
| 156 |
+
|
| 157 |
+
bigrams = _validated_ngrams(accepted_bigrams, 2)
|
| 158 |
+
trigrams = _validated_ngrams(accepted_trigrams, 3)
|
| 159 |
+
ordered = tuple(sorted(documents, key=lambda document: document.page_id))
|
| 160 |
+
_validate_documents(ordered)
|
| 161 |
+
try:
|
| 162 |
+
with ExitStack() as stack:
|
| 163 |
+
noow = stack.enter_context(
|
| 164 |
+
os.fdopen(
|
| 165 |
+
_create_owned_file(
|
| 166 |
+
directory_descriptor, NOOW_FILENAME, owned_identities
|
| 167 |
+
),
|
| 168 |
+
"w",
|
| 169 |
+
encoding="utf-8",
|
| 170 |
+
newline="\n",
|
| 171 |
+
)
|
| 172 |
+
)
|
| 173 |
+
bow = stack.enter_context(
|
| 174 |
+
os.fdopen(
|
| 175 |
+
_create_owned_file(
|
| 176 |
+
directory_descriptor, BOW_FILENAME, owned_identities
|
| 177 |
+
),
|
| 178 |
+
"w",
|
| 179 |
+
encoding="utf-8",
|
| 180 |
+
newline="\n",
|
| 181 |
+
)
|
| 182 |
+
)
|
| 183 |
+
provenance = stack.enter_context(
|
| 184 |
+
os.fdopen(
|
| 185 |
+
_create_owned_file(
|
| 186 |
+
directory_descriptor, PROVENANCE_FILENAME, owned_identities
|
| 187 |
+
),
|
| 188 |
+
"w",
|
| 189 |
+
encoding="utf-8",
|
| 190 |
+
newline="",
|
| 191 |
+
)
|
| 192 |
+
)
|
| 193 |
+
noow_gzip_file = stack.enter_context(
|
| 194 |
+
os.fdopen(
|
| 195 |
+
_create_owned_file(
|
| 196 |
+
directory_descriptor,
|
| 197 |
+
f"{NOOW_FILENAME}.gz",
|
| 198 |
+
owned_identities,
|
| 199 |
+
),
|
| 200 |
+
"wb",
|
| 201 |
+
)
|
| 202 |
+
)
|
| 203 |
+
bow_gzip_file = stack.enter_context(
|
| 204 |
+
os.fdopen(
|
| 205 |
+
_create_owned_file(
|
| 206 |
+
directory_descriptor,
|
| 207 |
+
f"{BOW_FILENAME}.gz",
|
| 208 |
+
owned_identities,
|
| 209 |
+
),
|
| 210 |
+
"wb",
|
| 211 |
+
)
|
| 212 |
+
)
|
| 213 |
+
noow_gzip = stack.enter_context(
|
| 214 |
+
TextIOWrapper(
|
| 215 |
+
gzip.GzipFile(
|
| 216 |
+
filename="",
|
| 217 |
+
mode="wb",
|
| 218 |
+
fileobj=noow_gzip_file,
|
| 219 |
+
compresslevel=_GZIP_COMPRESSION_LEVEL,
|
| 220 |
+
mtime=0,
|
| 221 |
+
),
|
| 222 |
+
encoding="utf-8",
|
| 223 |
+
newline="\n",
|
| 224 |
+
)
|
| 225 |
+
)
|
| 226 |
+
bow_gzip = stack.enter_context(
|
| 227 |
+
TextIOWrapper(
|
| 228 |
+
gzip.GzipFile(
|
| 229 |
+
filename="",
|
| 230 |
+
mode="wb",
|
| 231 |
+
fileobj=bow_gzip_file,
|
| 232 |
+
compresslevel=_GZIP_COMPRESSION_LEVEL,
|
| 233 |
+
mtime=0,
|
| 234 |
+
),
|
| 235 |
+
encoding="utf-8",
|
| 236 |
+
newline="\n",
|
| 237 |
+
)
|
| 238 |
+
)
|
| 239 |
+
provenance_writer = csv.DictWriter(
|
| 240 |
+
provenance, fieldnames=PROVENANCE_FIELDS, lineterminator="\n"
|
| 241 |
+
)
|
| 242 |
+
provenance_writer.writeheader()
|
| 243 |
+
for document in ordered:
|
| 244 |
+
modalities = _document_modalities(document, bigrams, trigrams)
|
| 245 |
+
document_id = _document_id(document.page_id)
|
| 246 |
+
noow_line = _format_noow(document_id, modalities)
|
| 247 |
+
bow_line = _format_bow(document_id, modalities)
|
| 248 |
+
noow.write(noow_line)
|
| 249 |
+
noow_gzip.write(noow_line)
|
| 250 |
+
bow.write(bow_line)
|
| 251 |
+
bow_gzip.write(bow_line)
|
| 252 |
+
provenance_writer.writerow(
|
| 253 |
+
{
|
| 254 |
+
"id": document_id,
|
| 255 |
+
"page_id": document.page_id,
|
| 256 |
+
"canonical_title": document.canonical_title,
|
| 257 |
+
"revision_id": document.revision_id,
|
| 258 |
+
"source_url": (
|
| 259 |
+
"https://ru.wikipedia.org/?curid=" f"{document.page_id}"
|
| 260 |
+
),
|
| 261 |
+
"wikitext_sha256": document.wikitext_sha256,
|
| 262 |
+
"raw_text_sha256": document.raw_text_sha256,
|
| 263 |
+
}
|
| 264 |
+
)
|
| 265 |
+
for name, identity in owned_identities.items():
|
| 266 |
+
descriptor = os.open(
|
| 267 |
+
name,
|
| 268 |
+
os.O_RDONLY | os.O_NOFOLLOW,
|
| 269 |
+
dir_fd=directory_descriptor,
|
| 270 |
+
)
|
| 271 |
+
try:
|
| 272 |
+
if _descriptor_identity(descriptor) != identity:
|
| 273 |
+
raise ValueError(f"output artifact identity mismatch: {name}")
|
| 274 |
+
os.fsync(descriptor)
|
| 275 |
+
finally:
|
| 276 |
+
os.close(descriptor)
|
| 277 |
+
_require_owned_identities(directory_descriptor, owned_identities)
|
| 278 |
+
except BaseException:
|
| 279 |
+
_clean_owned_files(directory_descriptor, owned_identities)
|
| 280 |
+
raise
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
def _validated_ngrams(
|
| 284 |
+
ngrams: Collection[tuple[str, ...]], expected_size: int
|
| 285 |
+
) -> frozenset[tuple[str, ...]]:
|
| 286 |
+
validated = set()
|
| 287 |
+
for ngram in ngrams:
|
| 288 |
+
if len(ngram) != expected_size:
|
| 289 |
+
raise ValueError(f"expected a {expected_size}-gram, got {ngram!r}")
|
| 290 |
+
for token in ngram:
|
| 291 |
+
_validate_token(token)
|
| 292 |
+
validated.add(tuple(ngram))
|
| 293 |
+
return frozenset(validated)
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
def _validate_documents(documents: Sequence[WikiGoodRuDocument]) -> None:
|
| 297 |
+
page_ids = set()
|
| 298 |
+
for document in documents:
|
| 299 |
+
if (
|
| 300 |
+
isinstance(document.page_id, bool)
|
| 301 |
+
or not isinstance(document.page_id, int)
|
| 302 |
+
or document.page_id <= 0
|
| 303 |
+
):
|
| 304 |
+
raise ValueError(f"invalid page ID: {document.page_id!r}")
|
| 305 |
+
if document.page_id in page_ids:
|
| 306 |
+
raise ValueError(f"duplicate document ID: {_document_id(document.page_id)}")
|
| 307 |
+
page_ids.add(document.page_id)
|
| 308 |
+
if (
|
| 309 |
+
isinstance(document.revision_id, bool)
|
| 310 |
+
or not isinstance(document.revision_id, int)
|
| 311 |
+
or document.revision_id <= 0
|
| 312 |
+
):
|
| 313 |
+
raise ValueError(f"invalid revision ID: {document.revision_id!r}")
|
| 314 |
+
if not isinstance(document.canonical_title, str) or not document.canonical_title:
|
| 315 |
+
raise ValueError("canonical title must be a non-empty string")
|
| 316 |
+
for token in (
|
| 317 |
+
*document.title_tokens,
|
| 318 |
+
*document.word_tokens,
|
| 319 |
+
*document.categories,
|
| 320 |
+
):
|
| 321 |
+
_validate_token(token)
|
| 322 |
+
for digest in (document.wikitext_sha256, document.raw_text_sha256):
|
| 323 |
+
if not isinstance(digest, str) or _SHA256.fullmatch(digest) is None:
|
| 324 |
+
raise ValueError(f"invalid SHA-256 digest: {digest!r}")
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
def _validate_token(token: object) -> None:
|
| 328 |
+
if not isinstance(token, str) or not token:
|
| 329 |
+
raise ValueError(f"VW tokens must be non-empty strings: {token!r}")
|
| 330 |
+
try:
|
| 331 |
+
token.encode("utf-8")
|
| 332 |
+
except UnicodeEncodeError as error:
|
| 333 |
+
raise ValueError(f"VW token is not valid UTF-8 text: {token!r}") from error
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
def _document_modalities(
|
| 337 |
+
document: WikiGoodRuDocument,
|
| 338 |
+
accepted_bigrams: Collection[tuple[str, ...]],
|
| 339 |
+
accepted_trigrams: Collection[tuple[str, ...]],
|
| 340 |
+
) -> tuple[tuple[str, tuple[str, ...]], ...]:
|
| 341 |
+
words = tuple(document.word_tokens)
|
| 342 |
+
bigrams = tuple(
|
| 343 |
+
_escape_ngram(ngram)
|
| 344 |
+
for ngram in zip(words, words[1:])
|
| 345 |
+
if ngram in accepted_bigrams
|
| 346 |
+
)
|
| 347 |
+
trigrams = tuple(
|
| 348 |
+
_escape_ngram(ngram)
|
| 349 |
+
for ngram in zip(words, words[1:], words[2:])
|
| 350 |
+
if ngram in accepted_trigrams
|
| 351 |
+
)
|
| 352 |
+
return (
|
| 353 |
+
("@title", tuple(_escape_vw(value) for value in document.title_tokens)),
|
| 354 |
+
("@word", tuple(_escape_vw(value) for value in words)),
|
| 355 |
+
("@bigram", bigrams),
|
| 356 |
+
("@trigram", trigrams),
|
| 357 |
+
("@category", tuple(_escape_vw(value) for value in document.categories)),
|
| 358 |
+
)
|
| 359 |
+
|
| 360 |
+
|
| 361 |
+
def _format_noow(
|
| 362 |
+
document_id: str, modalities: Sequence[tuple[str, Sequence[str]]]
|
| 363 |
+
) -> str:
|
| 364 |
+
fields = [_escape_vw(document_id)]
|
| 365 |
+
for name, tokens in modalities:
|
| 366 |
+
fields.append(f"|{name}")
|
| 367 |
+
fields.extend(tokens)
|
| 368 |
+
return " ".join(fields) + "\n"
|
| 369 |
+
|
| 370 |
+
|
| 371 |
+
def _format_bow(
|
| 372 |
+
document_id: str, modalities: Sequence[tuple[str, Sequence[str]]]
|
| 373 |
+
) -> str:
|
| 374 |
+
fields = [_escape_vw(document_id)]
|
| 375 |
+
for name, tokens in modalities:
|
| 376 |
+
fields.append(f"|{name}")
|
| 377 |
+
counts = Counter(tokens)
|
| 378 |
+
fields.extend(f"{token}:{counts[token]}" for token in sorted(counts))
|
| 379 |
+
return " ".join(fields) + "\n"
|
| 380 |
+
|
| 381 |
+
|
| 382 |
+
def _document_id(page_id: int) -> str:
|
| 383 |
+
return f"wikigood-ru/{page_id}"
|
| 384 |
+
|
| 385 |
+
|
| 386 |
+
def _escape_ngram(ngram: Sequence[str]) -> str:
|
| 387 |
+
return "_".join(_escape_vw(token, extra_reserved="_") for token in ngram)
|
| 388 |
+
|
| 389 |
+
|
| 390 |
+
def _escape_vw(value: str, *, extra_reserved: str = "") -> str:
|
| 391 |
+
escaped = []
|
| 392 |
+
reserved = _VW_RESERVED | frozenset(extra_reserved)
|
| 393 |
+
for character in value:
|
| 394 |
+
if character in reserved or character.isspace() or not character.isprintable():
|
| 395 |
+
escaped.extend(f"%{byte:02X}" for byte in character.encode("utf-8"))
|
| 396 |
+
else:
|
| 397 |
+
escaped.append(character)
|
| 398 |
+
return "".join(escaped)
|
| 399 |
+
|
| 400 |
+
|
| 401 |
+
def _create_owned_file(
|
| 402 |
+
directory_descriptor: int,
|
| 403 |
+
filename: str,
|
| 404 |
+
owned_identities: dict[str, tuple[int, int]],
|
| 405 |
+
) -> int:
|
| 406 |
+
descriptor = os.open(
|
| 407 |
+
filename,
|
| 408 |
+
os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW,
|
| 409 |
+
0o644,
|
| 410 |
+
dir_fd=directory_descriptor,
|
| 411 |
+
)
|
| 412 |
+
owned_identities[filename] = _descriptor_identity(descriptor)
|
| 413 |
+
return descriptor
|
| 414 |
+
|
| 415 |
+
|
| 416 |
+
def _create_owned_output_directory(
|
| 417 |
+
target: Path,
|
| 418 |
+
) -> tuple[int, str, int, tuple[int, int]]:
|
| 419 |
+
parent = target.parent
|
| 420 |
+
parent_descriptor = os.open(
|
| 421 |
+
parent, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW
|
| 422 |
+
)
|
| 423 |
+
staging_name: str | None = None
|
| 424 |
+
staging_descriptor: int | None = None
|
| 425 |
+
preserve_staging = False
|
| 426 |
+
try:
|
| 427 |
+
_require_path_descriptor_identity(parent, parent_descriptor)
|
| 428 |
+
try:
|
| 429 |
+
os.stat(target.name, dir_fd=parent_descriptor, follow_symlinks=False)
|
| 430 |
+
except FileNotFoundError:
|
| 431 |
+
pass
|
| 432 |
+
else:
|
| 433 |
+
raise FileExistsError(f"output path already exists: {target}")
|
| 434 |
+
|
| 435 |
+
for _ in range(128):
|
| 436 |
+
staging_name = f".{target.name}.{secrets.token_hex(8)}.tmp"
|
| 437 |
+
try:
|
| 438 |
+
os.mkdir(staging_name, mode=0o700, dir_fd=parent_descriptor)
|
| 439 |
+
except FileExistsError:
|
| 440 |
+
staging_name = None
|
| 441 |
+
continue
|
| 442 |
+
staging_descriptor = os.open(
|
| 443 |
+
staging_name,
|
| 444 |
+
os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW,
|
| 445 |
+
dir_fd=parent_descriptor,
|
| 446 |
+
)
|
| 447 |
+
staging_identity = _descriptor_identity(staging_descriptor)
|
| 448 |
+
if _entry_has_identity(
|
| 449 |
+
parent_descriptor, staging_name, staging_identity
|
| 450 |
+
):
|
| 451 |
+
return (
|
| 452 |
+
parent_descriptor,
|
| 453 |
+
staging_name,
|
| 454 |
+
staging_descriptor,
|
| 455 |
+
staging_identity,
|
| 456 |
+
)
|
| 457 |
+
preserve_staging = True
|
| 458 |
+
raise ValueError("owned output staging identity changed")
|
| 459 |
+
raise FileExistsError("could not allocate owned output staging directory")
|
| 460 |
+
except BaseException:
|
| 461 |
+
if staging_descriptor is not None:
|
| 462 |
+
os.close(staging_descriptor)
|
| 463 |
+
if staging_name is not None and not preserve_staging:
|
| 464 |
+
try:
|
| 465 |
+
os.rmdir(staging_name, dir_fd=parent_descriptor)
|
| 466 |
+
except OSError:
|
| 467 |
+
pass
|
| 468 |
+
os.close(parent_descriptor)
|
| 469 |
+
raise
|
| 470 |
+
|
| 471 |
+
|
| 472 |
+
def _publish_owned_output_directory(
|
| 473 |
+
target: Path,
|
| 474 |
+
parent_descriptor: int,
|
| 475 |
+
staging_name: str,
|
| 476 |
+
staging_descriptor: int,
|
| 477 |
+
staging_identity: tuple[int, int],
|
| 478 |
+
) -> None:
|
| 479 |
+
_require_path_descriptor_identity(target.parent, parent_descriptor)
|
| 480 |
+
if _descriptor_identity(staging_descriptor) != staging_identity or not (
|
| 481 |
+
_entry_has_identity(parent_descriptor, staging_name, staging_identity)
|
| 482 |
+
):
|
| 483 |
+
raise ValueError("owned output staging identity changed")
|
| 484 |
+
_rename_noreplace(
|
| 485 |
+
parent_descriptor, staging_name, parent_descriptor, target.name
|
| 486 |
+
)
|
| 487 |
+
_require_path_descriptor_identity(target.parent, parent_descriptor)
|
| 488 |
+
if not _entry_has_identity(parent_descriptor, target.name, staging_identity):
|
| 489 |
+
raise ValueError("published output identity mismatch")
|
| 490 |
+
os.fsync(parent_descriptor)
|
| 491 |
+
|
| 492 |
+
|
| 493 |
+
def _rename_noreplace(
|
| 494 |
+
source_directory_descriptor: int,
|
| 495 |
+
source_name: str,
|
| 496 |
+
target_directory_descriptor: int,
|
| 497 |
+
target_name: str,
|
| 498 |
+
) -> None:
|
| 499 |
+
library = ctypes.CDLL(None, use_errno=True)
|
| 500 |
+
try:
|
| 501 |
+
renameat2 = library.renameat2
|
| 502 |
+
except AttributeError as error:
|
| 503 |
+
raise OSError(errno.ENOSYS, "renameat2 is unavailable") from error
|
| 504 |
+
renameat2.argtypes = (
|
| 505 |
+
ctypes.c_int,
|
| 506 |
+
ctypes.c_char_p,
|
| 507 |
+
ctypes.c_int,
|
| 508 |
+
ctypes.c_char_p,
|
| 509 |
+
ctypes.c_uint,
|
| 510 |
+
)
|
| 511 |
+
renameat2.restype = ctypes.c_int
|
| 512 |
+
if (
|
| 513 |
+
renameat2(
|
| 514 |
+
source_directory_descriptor,
|
| 515 |
+
os.fsencode(source_name),
|
| 516 |
+
target_directory_descriptor,
|
| 517 |
+
os.fsencode(target_name),
|
| 518 |
+
_RENAME_NOREPLACE,
|
| 519 |
+
)
|
| 520 |
+
!= 0
|
| 521 |
+
):
|
| 522 |
+
error_number = ctypes.get_errno()
|
| 523 |
+
if error_number == errno.EEXIST:
|
| 524 |
+
raise FileExistsError(
|
| 525 |
+
error_number,
|
| 526 |
+
f"output path already exists: {target_name}",
|
| 527 |
+
target_name,
|
| 528 |
+
)
|
| 529 |
+
raise OSError(error_number, os.strerror(error_number), target_name)
|
| 530 |
+
|
| 531 |
+
|
| 532 |
+
def _require_owned_identities(
|
| 533 |
+
directory_descriptor: int,
|
| 534 |
+
owned_identities: dict[str, tuple[int, int]],
|
| 535 |
+
) -> None:
|
| 536 |
+
for name, identity in owned_identities.items():
|
| 537 |
+
if not _entry_has_identity(directory_descriptor, name, identity):
|
| 538 |
+
raise ValueError(f"output artifact identity mismatch: {name}")
|
| 539 |
+
|
| 540 |
+
|
| 541 |
+
def _clean_owned_files(
|
| 542 |
+
directory_descriptor: int,
|
| 543 |
+
owned_identities: dict[str, tuple[int, int]],
|
| 544 |
+
) -> None:
|
| 545 |
+
for name, identity in owned_identities.items():
|
| 546 |
+
if _entry_has_identity(directory_descriptor, name, identity):
|
| 547 |
+
os.unlink(name, dir_fd=directory_descriptor)
|
| 548 |
+
|
| 549 |
+
|
| 550 |
+
def _remove_owned_output_directory(
|
| 551 |
+
parent_descriptor: int,
|
| 552 |
+
staging_name: str,
|
| 553 |
+
staging_identity: tuple[int, int],
|
| 554 |
+
) -> None:
|
| 555 |
+
if _entry_has_identity(parent_descriptor, staging_name, staging_identity):
|
| 556 |
+
try:
|
| 557 |
+
os.rmdir(staging_name, dir_fd=parent_descriptor)
|
| 558 |
+
except OSError:
|
| 559 |
+
pass
|
| 560 |
+
|
| 561 |
+
|
| 562 |
+
def _entry_has_identity(
|
| 563 |
+
directory_descriptor: int, name: str, identity: tuple[int, int]
|
| 564 |
+
) -> bool:
|
| 565 |
+
try:
|
| 566 |
+
state = os.stat(
|
| 567 |
+
name, dir_fd=directory_descriptor, follow_symlinks=False
|
| 568 |
+
)
|
| 569 |
+
except OSError:
|
| 570 |
+
return False
|
| 571 |
+
return (state.st_dev, state.st_ino) == identity
|
| 572 |
+
|
| 573 |
+
|
| 574 |
+
def _require_path_descriptor_identity(path: Path, descriptor: int) -> None:
|
| 575 |
+
try:
|
| 576 |
+
state = os.stat(path, follow_symlinks=False)
|
| 577 |
+
except OSError as error:
|
| 578 |
+
raise ValueError(f"directory identity changed: {path}") from error
|
| 579 |
+
if not stat.S_ISDIR(state.st_mode) or not os.path.samestat(
|
| 580 |
+
state, os.fstat(descriptor)
|
| 581 |
+
):
|
| 582 |
+
raise ValueError(f"directory identity changed: {path}")
|
| 583 |
+
|
| 584 |
+
|
| 585 |
+
def _descriptor_identity(descriptor: int) -> tuple[int, int]:
|
| 586 |
+
state = os.fstat(descriptor)
|
| 587 |
+
return state.st_dev, state.st_ino
|
| 588 |
+
|
| 589 |
+
|
| 590 |
+
# The full-quality corpus is separate from the historical VW publication contract.
|
| 591 |
+
QUALITY_FULL_FILENAMES = (
|
| 592 |
+
"articles.jsonl.gz", "categories.jsonl.gz", "manifest.json", "SHA256SUMS", "README.md",
|
| 593 |
+
)
|
| 594 |
+
_QUALITY_POLICY = {
|
| 595 |
+
"Википедия:Добротные_статьи_по_алфавиту": "recommended",
|
| 596 |
+
"Википедия:Хорошие_статьи_по_алфавиту": "good",
|
| 597 |
+
"Википедия:Избранные_статьи_по_алфавиту": "featured",
|
| 598 |
+
}
|
| 599 |
+
_FORMER_QUALITY = {
|
| 600 |
+
"Википедия:Лишённые_статуса_добротной",
|
| 601 |
+
"Википедия:Лишённые_статуса_хорошей",
|
| 602 |
+
"Википедия:Устаревшие_избранные_статьи",
|
| 603 |
+
}
|
| 604 |
+
_QUALITY_METADATA_FIELDS = {
|
| 605 |
+
"page_id", "title", "metadata_revision_id", "wikidata_id", "quality_statuses",
|
| 606 |
+
"categories", "former_quality_categories",
|
| 607 |
+
}
|
| 608 |
+
_QUALITY_ARTICLE_FIELDS = _QUALITY_METADATA_FIELDS | {
|
| 609 |
+
"id", "revision_id", "revision_timestamp", "wikitext", "raw_text",
|
| 610 |
+
"wikitext_sha256", "raw_text_sha256", "page_url", "revision_url",
|
| 611 |
+
}
|
| 612 |
+
_QUALITY_CATEGORY_FIELDS = {
|
| 613 |
+
"title", "page_id", "is_hidden", "is_redirect", "wikidata_id", "parents",
|
| 614 |
+
}
|
| 615 |
+
|
| 616 |
+
|
| 617 |
+
def _quality_json(value: object) -> bytes:
|
| 618 |
+
import json
|
| 619 |
+
return (json.dumps(value, ensure_ascii=False, sort_keys=True,
|
| 620 |
+
separators=(",", ":"), allow_nan=False) + "\n").encode("utf-8")
|
| 621 |
+
|
| 622 |
+
|
| 623 |
+
def _quality_digest(path: Path) -> str:
|
| 624 |
+
import hashlib
|
| 625 |
+
digest = hashlib.sha256()
|
| 626 |
+
with path.open("rb") as stream:
|
| 627 |
+
for chunk in iter(lambda: stream.read(1024 * 1024), b""):
|
| 628 |
+
digest.update(chunk)
|
| 629 |
+
return digest.hexdigest()
|
| 630 |
+
|
| 631 |
+
|
| 632 |
+
def _quality_string_list(value: object) -> bool:
|
| 633 |
+
return (type(value) is list and all(type(item) is str and item for item in value)
|
| 634 |
+
and value == sorted(set(value)))
|
| 635 |
+
|
| 636 |
+
|
| 637 |
+
def _quality_qid(value: object) -> bool:
|
| 638 |
+
return value is None or (type(value) is str and re.fullmatch(r"Q[1-9][0-9]*", value) is not None)
|
| 639 |
+
|
| 640 |
+
|
| 641 |
+
def _quality_categories(records: Iterable[dict]) -> dict[str, dict]:
|
| 642 |
+
catalog = {}
|
| 643 |
+
previous = ""
|
| 644 |
+
page_ids = set()
|
| 645 |
+
for row in records:
|
| 646 |
+
if type(row) is not dict or set(row) != _QUALITY_CATEGORY_FIELDS:
|
| 647 |
+
raise ValueError("invalid category schema")
|
| 648 |
+
title = row["title"]
|
| 649 |
+
if type(title) is not str or not title or title <= previous:
|
| 650 |
+
raise ValueError("category titles must be strictly ordered")
|
| 651 |
+
previous = title
|
| 652 |
+
page_id = row["page_id"]
|
| 653 |
+
if not _quality_qid(row["wikidata_id"]) or not _quality_string_list(row["parents"]):
|
| 654 |
+
raise ValueError("invalid category QID or parents")
|
| 655 |
+
if page_id is None:
|
| 656 |
+
if any(row[key] is not None for key in ("is_hidden", "is_redirect", "wikidata_id")) or row["parents"]:
|
| 657 |
+
raise ValueError("redlink category has page metadata")
|
| 658 |
+
elif (type(page_id) is not int or page_id <= 0 or page_id in page_ids
|
| 659 |
+
or type(row["is_hidden"]) is not bool or type(row["is_redirect"]) is not bool):
|
| 660 |
+
raise ValueError("invalid category identity or flags")
|
| 661 |
+
if page_id is not None:
|
| 662 |
+
page_ids.add(page_id)
|
| 663 |
+
catalog[title] = row
|
| 664 |
+
if any(title not in catalog or catalog[title]["page_id"] is None or catalog[title]["is_redirect"]
|
| 665 |
+
for title in _QUALITY_POLICY):
|
| 666 |
+
raise ValueError("active quality category missing or redirected")
|
| 667 |
+
if not catalog or any(parent not in catalog for row in catalog.values() for parent in row["parents"]):
|
| 668 |
+
raise ValueError("empty catalog or missing parent category")
|
| 669 |
+
return catalog
|
| 670 |
+
|
| 671 |
+
|
| 672 |
+
def _quality_article(row: dict, catalog: dict, previous: int) -> None:
|
| 673 |
+
import hashlib
|
| 674 |
+
from datetime import datetime
|
| 675 |
+
if type(row) is not dict or set(row) != _QUALITY_ARTICLE_FIELDS:
|
| 676 |
+
raise ValueError("invalid article schema")
|
| 677 |
+
page_id = row["page_id"]
|
| 678 |
+
if (type(page_id) is not int or page_id <= previous or row["id"] != f"ruwiki/{page_id}"
|
| 679 |
+
or type(row["title"]) is not str or not row["title"] or "_" in row["title"]):
|
| 680 |
+
raise ValueError("invalid article identity or ordering")
|
| 681 |
+
for key in ("revision_id", "metadata_revision_id"):
|
| 682 |
+
if type(row[key]) is not int or row[key] <= 0:
|
| 683 |
+
raise ValueError("invalid article revision")
|
| 684 |
+
timestamp = row["revision_timestamp"]
|
| 685 |
+
if type(timestamp) is not str or re.fullmatch(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z", timestamp) is None:
|
| 686 |
+
raise ValueError("invalid revision timestamp")
|
| 687 |
+
datetime.strptime(timestamp, "%Y-%m-%dT%H:%M:%SZ")
|
| 688 |
+
if (not _quality_qid(row["wikidata_id"]) or not _quality_string_list(row["categories"])
|
| 689 |
+
or not _quality_string_list(row["quality_statuses"])
|
| 690 |
+
or not _quality_string_list(row["former_quality_categories"])):
|
| 691 |
+
raise ValueError("invalid article metadata types")
|
| 692 |
+
if any(title not in catalog for title in row["categories"]):
|
| 693 |
+
raise ValueError("article category absent from catalog")
|
| 694 |
+
expected_statuses = sorted(_QUALITY_POLICY[title] for title in row["categories"] if title in _QUALITY_POLICY)
|
| 695 |
+
if not expected_statuses or row["quality_statuses"] != expected_statuses:
|
| 696 |
+
raise ValueError("quality statuses disagree with active categories")
|
| 697 |
+
if row["former_quality_categories"] != sorted(set(row["categories"]) & _FORMER_QUALITY):
|
| 698 |
+
raise ValueError("former category metadata mismatch")
|
| 699 |
+
for field in ("wikitext", "raw_text"):
|
| 700 |
+
if type(row[field]) is not str or row[field + "_sha256"] != hashlib.sha256(row[field].encode("utf-8")).hexdigest():
|
| 701 |
+
raise ValueError("article text hash mismatch")
|
| 702 |
+
if (row["page_url"] != f"https://ru.wikipedia.org/?curid={page_id}"
|
| 703 |
+
or row["revision_url"] != f"https://ru.wikipedia.org/w/index.php?oldid={row['revision_id']}"):
|
| 704 |
+
raise ValueError("article URL mismatch")
|
| 705 |
+
|
| 706 |
+
|
| 707 |
+
def _quality_provenance(provenance: dict) -> None:
|
| 708 |
+
import hashlib
|
| 709 |
+
import json
|
| 710 |
+
if type(provenance) is not dict or set(provenance) != {
|
| 711 |
+
"sources", "code", "parser", "runtime", "selected_roster", "resources",
|
| 712 |
+
}:
|
| 713 |
+
raise ValueError("invalid provenance schema")
|
| 714 |
+
spec_path = Path(__file__).resolve().parents[1] / "specs" / "wikipedia-quality-full-20261001.json"
|
| 715 |
+
spec_bytes = spec_path.read_bytes()
|
| 716 |
+
if hashlib.sha256(spec_bytes).hexdigest() != QUALITY_FULL_SOURCE_SPEC_SHA256:
|
| 717 |
+
raise ValueError("approved source specification changed")
|
| 718 |
+
spec = json.loads(spec_bytes)
|
| 719 |
+
sources = provenance["sources"]
|
| 720 |
+
if type(sources) is not dict or any(sources.get(key) != spec[key] or type(sources.get(key)) is not type(spec[key]) for key in ("schema_version", "profile", "snapshot", "total_download_bytes")):
|
| 721 |
+
raise ValueError("source profile mismatch")
|
| 722 |
+
if sources.get("source_spec_sha256") != hashlib.sha256(spec_bytes).hexdigest():
|
| 723 |
+
raise ValueError("source specification hash mismatch")
|
| 724 |
+
expected_source_keys = set(spec) | {"source_spec_sha256", "manifest_sha256"}
|
| 725 |
+
if set(sources) != expected_source_keys:
|
| 726 |
+
raise ValueError("source manifest schema mismatch")
|
| 727 |
+
unsealed = {key: value for key, value in sources.items() if key != "manifest_sha256"}
|
| 728 |
+
if sources["manifest_sha256"] != hashlib.sha256(_quality_json(unsealed).rstrip(b"\n")).hexdigest():
|
| 729 |
+
raise ValueError("source manifest seal mismatch")
|
| 730 |
+
files = sources.get("files")
|
| 731 |
+
if type(files) is not list or len(files) != len(spec["files"]):
|
| 732 |
+
raise ValueError("source inventory mismatch")
|
| 733 |
+
for actual, expected in zip(files, spec["files"]):
|
| 734 |
+
if (type(actual) is not dict or set(actual) != set(expected) | {"sha256"} or any(actual.get(key) != value or type(actual[key]) is not type(value) for key, value in expected.items())
|
| 735 |
+
or type(actual.get("sha256")) is not str or _SHA256.fullmatch(actual["sha256"]) is None):
|
| 736 |
+
raise ValueError("source identity mismatch")
|
| 737 |
+
for key, fields in (("code", {"commit", "dirty"}), ("parser", {"name", "version"}), ("runtime", {"python"})):
|
| 738 |
+
value = provenance[key]
|
| 739 |
+
if type(value) is not dict or set(value) != fields:
|
| 740 |
+
raise ValueError(f"invalid {key} schema")
|
| 741 |
+
if any(type(item) is not str or not item for name, item in value.items() if name != "dirty"):
|
| 742 |
+
raise ValueError(f"invalid {key} value")
|
| 743 |
+
if type(provenance["code"]["dirty"]) is not bool:
|
| 744 |
+
raise ValueError("invalid code dirty flag")
|
| 745 |
+
resources = provenance["resources"]
|
| 746 |
+
if type(resources) is not dict or not {"wall_seconds", "max_rss_bytes", "observed_scratch_peak_bytes"} <= resources.keys():
|
| 747 |
+
raise ValueError("missing resource observations")
|
| 748 |
+
for key in ("wall_seconds", "max_rss_bytes", "observed_scratch_peak_bytes"):
|
| 749 |
+
value = resources[key]
|
| 750 |
+
if type(value) not in (int, float) or value < 0 or not __import__("math").isfinite(value):
|
| 751 |
+
raise ValueError("invalid resource observation")
|
| 752 |
+
if type(provenance["selected_roster"]) is not list or not provenance["selected_roster"]:
|
| 753 |
+
raise ValueError("empty selected SQL roster")
|
| 754 |
+
|
| 755 |
+
|
| 756 |
+
def _quality_summary(records: Iterable[dict], catalog: dict, roster: list, emit=None) -> dict:
|
| 757 |
+
previous = 0
|
| 758 |
+
category_page_ids = {row["page_id"] for row in catalog.values()}
|
| 759 |
+
status_counts = Counter({status: 0 for status in _QUALITY_POLICY.values()})
|
| 760 |
+
text_counts = {name: Counter() for name in ("wikitext_sha256", "raw_text_sha256")}
|
| 761 |
+
differences = []
|
| 762 |
+
links = 0
|
| 763 |
+
count = 0
|
| 764 |
+
for count, row in enumerate(records, 1):
|
| 765 |
+
_quality_article(row, catalog, previous)
|
| 766 |
+
previous = row["page_id"]
|
| 767 |
+
if previous in category_page_ids:
|
| 768 |
+
raise ValueError("article identity overlaps category namespace")
|
| 769 |
+
metadata = {key: row[key] for key in _QUALITY_METADATA_FIELDS}
|
| 770 |
+
if count > len(roster) or _quality_json(metadata) != _quality_json(roster[count - 1]):
|
| 771 |
+
raise ValueError("article does not match exact selected SQL roster")
|
| 772 |
+
status_counts.update(row["quality_statuses"])
|
| 773 |
+
links += len(row["categories"])
|
| 774 |
+
if row["revision_id"] != row["metadata_revision_id"]:
|
| 775 |
+
differences.append(row["page_id"])
|
| 776 |
+
for key, counter in text_counts.items():
|
| 777 |
+
counter[row[key]] += 1
|
| 778 |
+
if emit is not None:
|
| 779 |
+
emit(_quality_json(row))
|
| 780 |
+
if count != len(roster):
|
| 781 |
+
raise ValueError("incomplete selected SQL roster")
|
| 782 |
+
return {
|
| 783 |
+
"counts": {"articles": count, "categories": len(catalog),
|
| 784 |
+
"category_redlinks": sum(row["page_id"] is None for row in catalog.values()),
|
| 785 |
+
"category_parent_links": sum(len(row["parents"]) for row in catalog.values()),
|
| 786 |
+
"direct_category_links": links, "quality_status_supports": dict(status_counts)},
|
| 787 |
+
"revision_differences": {"count": len(differences), "page_ids": differences},
|
| 788 |
+
"duplicates": {key: {"groups": sum(n > 1 for n in counts.values()),
|
| 789 |
+
"extra_articles": sum(n - 1 for n in counts.values())}
|
| 790 |
+
for key, counts in text_counts.items()},
|
| 791 |
+
}
|
| 792 |
+
|
| 793 |
+
|
| 794 |
+
def _quality_readme() -> bytes:
|
| 795 |
+
return """---
|
| 796 |
+
language: ru
|
| 797 |
+
license: cc-by-sa-4.0
|
| 798 |
+
pretty_name: Russian Wikipedia quality articles (20261001)
|
| 799 |
+
configs:
|
| 800 |
+
- config_name: articles
|
| 801 |
+
data_files:
|
| 802 |
+
- split: corpus
|
| 803 |
+
path: articles.jsonl.gz
|
| 804 |
+
- config_name: categories
|
| 805 |
+
data_files:
|
| 806 |
+
- split: corpus
|
| 807 |
+
path: categories.jsonl.gz
|
| 808 |
+
---
|
| 809 |
+
# Russian Wikipedia quality articles
|
| 810 |
+
|
| 811 |
+
This corpus contains the union of active recommended (добротные), good (хорошие),
|
| 812 |
+
and featured (избранные) Russian Wikipedia articles from the 20261001 dump.
|
| 813 |
+
Multiple active statuses are retained. Former status categories are historical
|
| 814 |
+
metadata and do not exclude an article with an active status. Selection includes
|
| 815 |
+
namespace-0 articles and excludes redirects and disambiguation pages.
|
| 816 |
+
|
| 817 |
+
Each article has a stable ruwiki/<page_id> ID, separate title, original decoded
|
| 818 |
+
wikitext, extracted raw_text, SHA-256 text hashes, optional Wikidata ID, quality
|
| 819 |
+
statuses, all direct categories, XML revision ID and timestamp, SQL
|
| 820 |
+
metadata_revision_id, and page/revision URLs. XML defines the content revision;
|
| 821 |
+
SQL and XML revisions can differ. Repeated text across distinct IDs is retained.
|
| 822 |
+
Readable extraction is not HTML rendering or full template expansion; templates,
|
| 823 |
+
tables, references, formatting and other markup can be lost or simplified.
|
| 824 |
+
|
| 825 |
+
Category names preserve SQL spelling (underscores); article titles use spaces.
|
| 826 |
+
Join article categories and category parents to categories.jsonl.gz by title.
|
| 827 |
+
The catalog includes all category pages, hidden and redirect flags, optional QIDs,
|
| 828 |
+
parent links and redlinks. Redlinks have null page ID, flags and QID and no parents.
|
| 829 |
+
Cycles are retained. No subject taxonomy, NLP, train/test research splits, sampling
|
| 830 |
+
or deduplication is applied. The corpus partition is only a Hugging Face data
|
| 831 |
+
partition and does not define research splits.
|
| 832 |
+
|
| 833 |
+
Load the local package without a dataset script:
|
| 834 |
+
|
| 835 |
+
```python
|
| 836 |
+
from datasets import load_dataset
|
| 837 |
+
articles = load_dataset("json", data_files={"corpus": "articles.jsonl.gz"})
|
| 838 |
+
categories = load_dataset("json", data_files={"corpus": "categories.jsonl.gz"})
|
| 839 |
+
```
|
| 840 |
+
|
| 841 |
+
For a future Hugging Face publication, use the articles or categories configuration
|
| 842 |
+
and its corpus partition. The manifest records exact source identities, SQL roster,
|
| 843 |
+
code/parser/runtime versions, counts and measured resource observations. SHA256SUMS
|
| 844 |
+
checks every other package file. Verification without an independently trusted
|
| 845 |
+
manifest SHA-256 checks internal consistency only. Self-hashes cannot establish
|
| 846 |
+
the authenticity of text, metadata or provenance after a package is resealed.
|
| 847 |
+
Supply the manifest SHA-256 recorded separately in the trusted build log to bind
|
| 848 |
+
verification to that build's manifest and its payload hashes. Keep this anchor
|
| 849 |
+
outside the package; computing it from the package being verified gives no
|
| 850 |
+
independent evidence. The builder separately checks SQL selection and a bounded
|
| 851 |
+
XML content/provenance sample.
|
| 852 |
+
|
| 853 |
+
Verify with the project CLI and the SHA-256 from the trusted build log:
|
| 854 |
+
|
| 855 |
+
```sh
|
| 856 |
+
python work/wintra/experiments/run_wikigood_ru_preprocessing.py --profile quality-full --action verify --output-dir /path/to/package --expected-manifest-sha256 TRUSTED_BUILD_MANIFEST_SHA256
|
| 857 |
+
```
|
| 858 |
+
|
| 859 |
+
Text is attributed to Russian Wikipedia contributors and distributed under
|
| 860 |
+
[CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/). Each revision_url
|
| 861 |
+
pins the attributed revision; page_url provides access to page history and authors.
|
| 862 |
+
Observe attribution and share-alike requirements when redistributing adaptations;
|
| 863 |
+
third-party material can have additional terms. Future preparation uses the project
|
| 864 |
+
CLI run_wikigood_ru_preprocessing.py --profile quality-full with explicit source,
|
| 865 |
+
output and scratch directories. No Hugging Face repository is created automatically.
|
| 866 |
+
""".encode("utf-8")
|
| 867 |
+
|
| 868 |
+
|
| 869 |
+
def write_wikigood_ru_quality_full_package(
|
| 870 |
+
articles: Iterable[dict], categories: Iterable[dict], output_dir: str | Path,
|
| 871 |
+
*, provenance: dict,
|
| 872 |
+
) -> dict:
|
| 873 |
+
"""Publish a fresh full-quality package; inputs are already normalized records.
|
| 874 |
+
|
| 875 |
+
Articles must be ordered by numeric page ID and categories by exact SQL title.
|
| 876 |
+
Provenance includes sources, code, parser, runtime, selected_roster and resources.
|
| 877 |
+
Return the manifest. No extraction or NLP is performed here.
|
| 878 |
+
"""
|
| 879 |
+
import hashlib
|
| 880 |
+
_quality_provenance(provenance)
|
| 881 |
+
catalog = _quality_categories(categories)
|
| 882 |
+
target = Path(output_dir)
|
| 883 |
+
for path in (target, *target.parents):
|
| 884 |
+
if path.is_symlink():
|
| 885 |
+
raise ValueError("symlink package path")
|
| 886 |
+
parent_fd, staging_name, staging_fd, identity = _create_owned_output_directory(target)
|
| 887 |
+
owned = {}
|
| 888 |
+
hashes = {}
|
| 889 |
+
try:
|
| 890 |
+
for filename, rows in (("articles.jsonl.gz", articles), ("categories.jsonl.gz", catalog.values())):
|
| 891 |
+
fd = _create_owned_file(staging_fd, filename, owned)
|
| 892 |
+
with os.fdopen(fd, "wb") as raw:
|
| 893 |
+
with gzip.GzipFile(filename="", mode="wb", fileobj=raw, mtime=0, compresslevel=9) as zipped:
|
| 894 |
+
if filename == "articles.jsonl.gz":
|
| 895 |
+
summary = _quality_summary(rows, catalog, provenance["selected_roster"], zipped.write)
|
| 896 |
+
else:
|
| 897 |
+
for row in rows:
|
| 898 |
+
zipped.write(_quality_json(row))
|
| 899 |
+
raw.flush()
|
| 900 |
+
os.fsync(raw.fileno())
|
| 901 |
+
hashes[filename] = _quality_digest(target.parent / staging_name / filename)
|
| 902 |
+
manifest = {"schema_version": 1, "profile": "quality-full", "snapshot": "20261001",
|
| 903 |
+
"quality_policy": _QUALITY_POLICY, "provenance": provenance, **summary,
|
| 904 |
+
"payload_sha256": dict(hashes)}
|
| 905 |
+
for filename, data in (("manifest.json", _quality_json(manifest)), ("README.md", _quality_readme())):
|
| 906 |
+
with os.fdopen(_create_owned_file(staging_fd, filename, owned), "wb") as stream:
|
| 907 |
+
stream.write(data)
|
| 908 |
+
stream.flush()
|
| 909 |
+
os.fsync(stream.fileno())
|
| 910 |
+
hashes[filename] = hashlib.sha256(data).hexdigest()
|
| 911 |
+
checksums = "".join(f"{hashes[name]} {name}\n" for name in sorted(hashes)).encode("ascii")
|
| 912 |
+
with os.fdopen(_create_owned_file(staging_fd, "SHA256SUMS", owned), "wb") as stream:
|
| 913 |
+
stream.write(checksums)
|
| 914 |
+
stream.flush()
|
| 915 |
+
os.fsync(stream.fileno())
|
| 916 |
+
_require_owned_identities(staging_fd, owned)
|
| 917 |
+
os.fchmod(staging_fd, 0o755)
|
| 918 |
+
os.fsync(staging_fd)
|
| 919 |
+
_publish_owned_output_directory(target, parent_fd, staging_name, staging_fd, identity)
|
| 920 |
+
except BaseException:
|
| 921 |
+
_clean_owned_files(staging_fd, owned)
|
| 922 |
+
_remove_owned_output_directory(parent_fd, staging_name, identity)
|
| 923 |
+
_remove_owned_output_directory(parent_fd, target.name, identity)
|
| 924 |
+
raise
|
| 925 |
+
finally:
|
| 926 |
+
os.close(staging_fd)
|
| 927 |
+
os.close(parent_fd)
|
| 928 |
+
return manifest
|
| 929 |
+
|
| 930 |
+
|
| 931 |
+
def verify_wikigood_ru_quality_full_package(
|
| 932 |
+
output_dir: str | Path, *, expected_manifest_sha256: str | None = None,
|
| 933 |
+
) -> dict:
|
| 934 |
+
"""Read-only structural/hash verification, without extraction, NLP or rebuild.
|
| 935 |
+
|
| 936 |
+
Without an external anchor, verification establishes internal consistency only;
|
| 937 |
+
self-hashes cannot authenticate text, metadata or provenance after resealing.
|
| 938 |
+
Supply a lowercase SHA-256 from an independently trusted build log to require
|
| 939 |
+
that exact manifest and its payload hashes before trusting manifest fields.
|
| 940 |
+
The builder separately checks SQL selection and a bounded XML content sample.
|
| 941 |
+
"""
|
| 942 |
+
import hashlib
|
| 943 |
+
import json
|
| 944 |
+
if expected_manifest_sha256 is not None and (
|
| 945 |
+
type(expected_manifest_sha256) is not str
|
| 946 |
+
or _SHA256.fullmatch(expected_manifest_sha256) is None
|
| 947 |
+
):
|
| 948 |
+
raise ValueError("expected manifest SHA-256 must be 64 lowercase hex characters")
|
| 949 |
+
target = Path(output_dir)
|
| 950 |
+
for path in (target, *target.parents):
|
| 951 |
+
if path.is_symlink():
|
| 952 |
+
raise ValueError("symlink package path")
|
| 953 |
+
if not target.is_dir() or set(path.name for path in target.iterdir()) != set(QUALITY_FULL_FILENAMES):
|
| 954 |
+
raise ValueError("package inventory mismatch")
|
| 955 |
+
for name in QUALITY_FULL_FILENAMES:
|
| 956 |
+
if not stat.S_ISREG((target / name).lstat().st_mode):
|
| 957 |
+
raise ValueError("nonregular package file")
|
| 958 |
+
checksums = "".join(f"{_quality_digest(target / name)} {name}\n"
|
| 959 |
+
for name in sorted(set(QUALITY_FULL_FILENAMES) - {"SHA256SUMS"}))
|
| 960 |
+
if (target / "SHA256SUMS").read_bytes() != checksums.encode("ascii"):
|
| 961 |
+
raise ValueError("package checksum mismatch")
|
| 962 |
+
manifest_bytes = (target / "manifest.json").read_bytes()
|
| 963 |
+
if (expected_manifest_sha256 is not None
|
| 964 |
+
and hashlib.sha256(manifest_bytes).hexdigest() != expected_manifest_sha256):
|
| 965 |
+
raise ValueError("manifest SHA-256 does not match trusted anchor")
|
| 966 |
+
manifest = json.loads(manifest_bytes)
|
| 967 |
+
if type(manifest) is not dict or manifest_bytes != _quality_json(manifest) or set(manifest) != {
|
| 968 |
+
"schema_version", "profile", "snapshot", "quality_policy", "provenance", "counts",
|
| 969 |
+
"revision_differences", "duplicates", "payload_sha256",
|
| 970 |
+
}:
|
| 971 |
+
raise ValueError("manifest schema or serialization mismatch")
|
| 972 |
+
if (_quality_json({key: manifest[key] for key in ("schema_version", "profile", "snapshot", "quality_policy")})
|
| 973 |
+
!= _quality_json({"schema_version": 1, "profile": "quality-full", "snapshot": "20261001", "quality_policy": _QUALITY_POLICY})):
|
| 974 |
+
raise ValueError("package policy mismatch")
|
| 975 |
+
_quality_provenance(manifest["provenance"])
|
| 976 |
+
if (target / "README.md").read_bytes() != _quality_readme():
|
| 977 |
+
raise ValueError("package README mismatch")
|
| 978 |
+
catalog = _quality_categories(_quality_rows(target / "categories.jsonl.gz"))
|
| 979 |
+
summary = _quality_summary(_quality_rows(target / "articles.jsonl.gz"), catalog,
|
| 980 |
+
manifest["provenance"]["selected_roster"])
|
| 981 |
+
if _quality_json(summary) != _quality_json({key: manifest[key] for key in summary}):
|
| 982 |
+
raise ValueError("package summary mismatch")
|
| 983 |
+
expected_hashes = {name: _quality_digest(target / name) for name in ("articles.jsonl.gz", "categories.jsonl.gz")}
|
| 984 |
+
if manifest["payload_sha256"] != expected_hashes:
|
| 985 |
+
raise ValueError("payload hash mismatch")
|
| 986 |
+
return manifest
|
| 987 |
+
|
| 988 |
+
|
| 989 |
+
def _quality_rows(path: Path) -> Iterable[dict]:
|
| 990 |
+
import json
|
| 991 |
+
with gzip.open(path, "rb") as stream:
|
| 992 |
+
for line in stream:
|
| 993 |
+
row = json.loads(line)
|
| 994 |
+
if line != _quality_json(row):
|
| 995 |
+
raise ValueError("noncanonical JSONL record")
|
| 996 |
+
yield row
|
preprocessing/conda-linux-64.lock.txt
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This file may be used to create an environment using:
|
| 2 |
+
# $ conda create --name <env> --file <this file>
|
| 3 |
+
# platform: linux-64
|
| 4 |
+
# created-by: conda 26.3.2
|
| 5 |
+
@EXPLICIT
|
| 6 |
+
https://repo.anaconda.com/pkgs/main/linux-64/_libgcc_mutex-0.1-main.conda
|
| 7 |
+
https://repo.anaconda.com/pkgs/main/linux-64/_openmp_mutex-5.1-52_gnu.conda
|
| 8 |
+
https://repo.anaconda.com/pkgs/main/linux-64/ca-certificates-2026.8.13-h06a4308_0.conda
|
| 9 |
+
https://repo.anaconda.com/pkgs/main/linux-64/ld_impl_linux-64-2.44-h9e0c5a2_3.conda
|
| 10 |
+
https://repo.anaconda.com/pkgs/main/noarch/tzdata-2026c-he532380_0.conda
|
| 11 |
+
https://repo.anaconda.com/pkgs/main/linux-64/libgcc-15.2.0-h69a1729_8.conda
|
| 12 |
+
https://repo.anaconda.com/pkgs/main/linux-64/libgcc-ng-15.2.0-h166f726_8.conda
|
| 13 |
+
https://repo.anaconda.com/pkgs/main/linux-64/libstdcxx-15.2.0-h39759b7_8.conda
|
| 14 |
+
https://repo.anaconda.com/pkgs/main/linux-64/libzlib-1.3.2-h47b2149_0.conda
|
| 15 |
+
https://repo.anaconda.com/pkgs/main/linux-64/openssl-3.5.7-h1b28b03_0.conda
|
| 16 |
+
https://repo.anaconda.com/pkgs/main/linux-64/pthread-stubs-0.3-h47b2149_2.conda
|
| 17 |
+
https://repo.anaconda.com/pkgs/main/linux-64/xorg-xorgproto-2025.1-h47b2149_0.conda
|
| 18 |
+
https://repo.anaconda.com/pkgs/main/linux-64/xz-5.8.2-h448239c_0.conda
|
| 19 |
+
https://repo.anaconda.com/pkgs/main/linux-64/bzip2-1.0.8-h5eee18b_6.conda
|
| 20 |
+
https://repo.anaconda.com/pkgs/main/linux-64/libexpat-2.8.2-h7354ed3_1.conda
|
| 21 |
+
https://repo.anaconda.com/pkgs/main/linux-64/libffi-3.4.8-h06d3fd0_3.conda
|
| 22 |
+
https://repo.anaconda.com/pkgs/main/linux-64/libnsl-2.0.0-h5eee18b_0.conda
|
| 23 |
+
https://repo.anaconda.com/pkgs/main/linux-64/libuuid-1.41.5-h5eee18b_0.conda
|
| 24 |
+
https://repo.anaconda.com/pkgs/main/linux-64/ncurses-6.6-hfaaeb4e_0.conda
|
| 25 |
+
https://repo.anaconda.com/pkgs/main/linux-64/xorg-libxau-1.0.12-h9b100fa_0.conda
|
| 26 |
+
https://repo.anaconda.com/pkgs/main/linux-64/xorg-libxdmcp-1.1.5-h9b100fa_0.conda
|
| 27 |
+
https://repo.anaconda.com/pkgs/main/linux-64/zlib-1.3.2-h47b2149_0.conda
|
| 28 |
+
https://repo.anaconda.com/pkgs/main/linux-64/libxcb-1.17.0-h9b100fa_0.conda
|
| 29 |
+
https://repo.anaconda.com/pkgs/main/linux-64/readline-8.3-hc2a1206_0.conda
|
| 30 |
+
https://repo.anaconda.com/pkgs/main/linux-64/sqlite-3.53.2-h795bf6d_0.conda
|
| 31 |
+
https://repo.anaconda.com/pkgs/main/linux-64/xorg-libx11-1.8.13-h65de747_0.conda
|
| 32 |
+
https://repo.anaconda.com/pkgs/main/linux-64/tk-8.6.15-h54e0aa7_0.conda
|
| 33 |
+
https://repo.anaconda.com/pkgs/main/linux-64/python-3.11.15-h17756b0_1.conda
|
| 34 |
+
https://repo.anaconda.com/pkgs/main/linux-64/packaging-26.3-py311h06a4308_0.conda
|
| 35 |
+
https://repo.anaconda.com/pkgs/main/linux-64/setuptools-83.0.0-py311h06a4308_0.conda
|
| 36 |
+
https://repo.anaconda.com/pkgs/main/linux-64/wheel-0.47.0-py311h06a4308_0.conda
|
| 37 |
+
https://repo.anaconda.com/pkgs/main/noarch/pip-26.2.1-pyhc872135_0.conda
|
preprocessing/pip-linux-x86_64.lock.txt
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
annotated-doc==0.0.5
|
| 2 |
+
annotated-types==0.8.0
|
| 3 |
+
anyio==4.14.2
|
| 4 |
+
blis==1.3.3
|
| 5 |
+
catalogue==2.0.10
|
| 6 |
+
certifi==2026.7.22
|
| 7 |
+
charset-normalizer==3.5.1
|
| 8 |
+
click==8.5.0
|
| 9 |
+
cloudpathlib==0.25.0
|
| 10 |
+
confection==1.3.3
|
| 11 |
+
cymem==2.0.13
|
| 12 |
+
DAWG2-Python==0.9.0
|
| 13 |
+
h11==0.16.0
|
| 14 |
+
httpcore==1.0.9
|
| 15 |
+
httpx==0.28.1
|
| 16 |
+
idna==3.19
|
| 17 |
+
iterative-stratification==0.1.9
|
| 18 |
+
Jinja2==3.1.6
|
| 19 |
+
joblib==1.5.3
|
| 20 |
+
markdown-it-py==4.2.0
|
| 21 |
+
MarkupSafe==3.0.3
|
| 22 |
+
mdurl==0.1.2
|
| 23 |
+
murmurhash==1.0.15
|
| 24 |
+
mwparserfromhell==0.7.2
|
| 25 |
+
narwhals==2.25.0
|
| 26 |
+
nltk==3.9.2
|
| 27 |
+
numpy==2.4.6
|
| 28 |
+
preshed==3.0.13
|
| 29 |
+
pydantic==2.13.5
|
| 30 |
+
pydantic_core==2.46.5
|
| 31 |
+
Pygments==2.21.0
|
| 32 |
+
pymorphy3==2.0.6
|
| 33 |
+
pymorphy3-dicts-ru==2.4.417150.4580142
|
| 34 |
+
regex==2026.7.19
|
| 35 |
+
requests==2.34.2
|
| 36 |
+
rich==15.0.0
|
| 37 |
+
scikit-learn==1.9.0
|
| 38 |
+
scipy==1.17.1
|
| 39 |
+
shellingham==1.5.4
|
| 40 |
+
smart_open==8.0.1
|
| 41 |
+
spacy==3.8.14
|
| 42 |
+
spacy-legacy==3.0.12
|
| 43 |
+
spacy-loggers==1.0.5
|
| 44 |
+
srsly==2.5.3
|
| 45 |
+
thinc==8.3.13
|
| 46 |
+
threadpoolctl==3.6.0
|
| 47 |
+
tqdm==4.70.0
|
| 48 |
+
typer==0.27.2
|
| 49 |
+
typing-inspection==0.4.4
|
| 50 |
+
typing_extensions==4.16.0
|
| 51 |
+
urllib3==2.7.0
|
| 52 |
+
wasabi==1.1.3
|
| 53 |
+
weasel==1.0.0
|
| 54 |
+
wrapt==2.3.0
|
preprocessing/prepare.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Download, build or verify the pinned Russian Wikipedia NLP CSVs.
|
| 2 |
+
|
| 3 |
+
Run ``python prepare.py --help`` for the portable workflow options.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from _wikigood.wikigood_ru_csv import main
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
if __name__ == "__main__":
|
| 10 |
+
raise SystemExit(main())
|
preprocessing/requirements.txt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
spacy==3.8.14
|
| 2 |
+
pymorphy3==2.0.6
|
| 3 |
+
nltk==3.9.2
|
preprocessing/wikipedia-quality-nlp-20261001.json
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{"csv_fields":["id","raw_text","vw_text"],"encoding":"UTF-8","full_namespaces":["@title","@word","@bigram","@trigram","@category"],"line_terminator":"LF","ngram":{"candidate_limit":32100,"head_skip":100,"minimum_frequency":5,"ranking":"PMI","selection":"independent per corpus; no document boundaries crossed"},"normalization":"shared common articles once; preserve all source IDs in numeric order","raw_text":"title + two LF + source raw_text stripped only of leading CR/LF","runtime":{"packages":{"nltk":"3.9.2","pymorphy3":"2.0.6","spacy":"3.8.14"},"python":"3.11.15"},"schema":"wikipedia-quality-nlp-20261001-v1","selected_namespaces":["@title","@word","@bigram","@trigram","@category","@topic"],"sources":{"full":{"articles":{"byte_size":409970311,"sha256":"c51f9b6bee4c85f25ffb861060f52490a9276bae289d2aa2db7e0d10e2dda950"},"count":17413,"repository":"TopicNet/RuWiki-Good-2026-V2","revision":"3c6bdb4ddc1be38b4fd63a480bdd056394a04934"},"selected":{"articles":{"byte_size":413342335,"sha256":"9eb7efffe99fc7c9bc3f4b3eb9f0378d91f387081f97cf9abea9c1686797c1ed"},"count":17251,"repository":"TopicNet/RuWiki-Good-2026-V2-Selected","revision":"fc1ad9b9491ab122614a95b3aa78b3cdfa5e3881","topics":{"byte_size":2671,"sha256":"c8cf602a924f18255e155cdcaa9357907461851e849113c72051c2b89484f22c"}}},"stopwords":{"byte_size":37733,"russian_sha256":"1743191192b4a4f77fcc216499455dc00c1b8626fdd407076a8deefff80e3d59","sha256":"48c0e52d8b52546e827f53761fb30300c0ab94f70660d28bd65ba0a86270946b","url":"https://raw.githubusercontent.com/nltk/nltk_data/550b6625bcef1f2abff2ff770a5a0d272c9c6b2a/packages/corpora/stopwords.zip"},"verification":"source binding and structural verification without morphology replay"}
|