Datasets:
Tasks:
Text Classification
Modalities:
Text
Formats:
csv
Languages:
English
Size:
10K - 100K
License:
Vasily Alexeev commited on
Commit ·
ac78841
1
Parent(s): 8f8f060
add info about reproduction, as well as reproduction code
Browse files- README.md +18 -0
- SHA256SUMS +13 -1
- preprocessing/.gitignore +2 -0
- preprocessing/LICENSE +25 -0
- preprocessing/README.md +210 -0
- preprocessing/_pipeline.py +358 -0
- preprocessing/conda-linux-64.lock.txt +37 -0
- preprocessing/payload-pins.json +147 -0
- preprocessing/pip-linux-x86_64.lock.txt +14 -0
- preprocessing/prepare.py +258 -0
- preprocessing/requirements-download.txt +3 -0
- preprocessing/requirements.txt +5 -0
- preprocessing/source-pins.json +96 -0
- preprocessing/test_prepare.py +216 -0
README.md
CHANGED
|
@@ -57,6 +57,24 @@ Each UTF-8 CSV has exactly `id,raw_text,vw_text` columns and lexicographically o
|
|
| 57 |
|
| 58 |
NOOW means occurrence order after preprocessing, not untouched or reversible prose. English preprocessing uses Python 3.11.15, NLTK 3.9.2 and NLTK-data commit `550b6625bcef1f2abff2ff770a5a0d272c9c6b2a`: WordPunctTokenizer, lowercase per original span, minimum token length 2, averaged_perceptron_tagger_eng, WordNet POS mapping J/V/N/R with noun fallback, English stopword removal and `lemma.isalpha()` filtering. Names are not masked.
|
| 59 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
## Loading and metadata
|
| 61 |
|
| 62 |
The default configuration is `noow`; `bow` contains aggregated counts. Both expose the complete population as the Hugging Face split `corpus`. Labels and the stored fit/calibration/validation memberships are auxiliary files, joined by document ID. `data/labels.json` directly maps each string ID to a list of string labels; `data/splits.json` directly maps each split name to an ordered ID list.
|
|
|
|
| 57 |
|
| 58 |
NOOW means occurrence order after preprocessing, not untouched or reversible prose. English preprocessing uses Python 3.11.15, NLTK 3.9.2 and NLTK-data commit `550b6625bcef1f2abff2ff770a5a0d272c9c6b2a`: WordPunctTokenizer, lowercase per original span, minimum token length 2, averaged_perceptron_tagger_eng, WordNet POS mapping J/V/N/R with noun fallback, English stopword removal and `lemma.isalpha()` filtering. Names are not masked.
|
| 59 |
|
| 60 |
+
## Reproduce from source
|
| 61 |
+
|
| 62 |
+
The [preprocessing folder](preprocessing/) contains the standalone code shared by all five prepared corpora. Its [README](preprocessing/README.md) explains how to download only that folder at a full commit revision, create the locked Linux x86-64 environment with Python 3.11.15, and record a full server build and verification. Folder access follows this repository's permissions. No parent project checkout, BigARTM or TopicNet installation is needed.
|
| 63 |
+
|
| 64 |
+
Obtain approved access to the original `dongqi-me/SciNews` dataset and authenticate using standard Hugging Face credentials before downloading sources. Access to this preparation does not grant access to the original source. From the directory containing `preprocessing/`, run:
|
| 65 |
+
|
| 66 |
+
```bash
|
| 67 |
+
python preprocessing/prepare.py download --dataset scinews --sources-dir /path/to/sources
|
| 68 |
+
python preprocessing/prepare.py build --dataset scinews \
|
| 69 |
+
--sources-dir /path/to/sources \
|
| 70 |
+
--output-dir /path/to/rebuilt/SciNews/data \
|
| 71 |
+
--scratch-dir /path/to/scratch/scinews
|
| 72 |
+
python preprocessing/prepare.py verify --dataset scinews \
|
| 73 |
+
--data-dir /path/to/rebuilt/SciNews/data
|
| 74 |
+
```
|
| 75 |
+
|
| 76 |
+
The download provides pinned `scinews/README.md`, `train.json`, `val.json` and `test.json`, together with NLTK resources under the source directory. Build and verify run offline after setup. Choose fresh output and scratch paths. The output contains only `noow.csv`, `bow.csv`, `labels.json` and `splits.json`; verification compares them with the recorded SHA-256 values. Builds refuse to overwrite outputs. Preserve failed output and scratch files, and use fresh paths for a retry. The code's separate [MIT license](preprocessing/LICENSE) does not change the source-text rights or access terms below.
|
| 77 |
+
|
| 78 |
## Loading and metadata
|
| 79 |
|
| 80 |
The default configuration is `noow`; `bow` contains aggregated counts. Both expose the complete population as the Hugging Face split `corpus`. Labels and the stored fit/calibration/validation memberships are auxiliary files, joined by document ID. `data/labels.json` directly maps each string ID to a list of string labels; `data/splits.json` directly maps each split name to an ordered ID list.
|
SHA256SUMS
CHANGED
|
@@ -1,7 +1,19 @@
|
|
| 1 |
947f03cf79a99d7f9061220c575021c918ae95f64ab75c4112917be804fb51cd .gitattributes
|
| 2 |
-
|
| 3 |
dffd02d522c1cb894d4fd1eebe0e4b6098d045fac77755fc8f49341388b32750 SOURCE_README.md
|
| 4 |
45f086796ca39994272e11a31a601ac2b8e91536f9bd812ce849be4c55042537 data/bow.csv
|
| 5 |
b9959f976605f8b418f6565fec8228e1bfbb0e8a7c314f0d1cf9b79258e9ac7c data/labels.json
|
| 6 |
1583bd93c7c5ef660fb18b255984d8a0caf721f8ac21026d40536f673a73ecbe data/noow.csv
|
| 7 |
d2e221cca3c7297d5b84f0d18dc2a7ba448e3775e33ff96a5e4bd30b33d13400 data/splits.json
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
947f03cf79a99d7f9061220c575021c918ae95f64ab75c4112917be804fb51cd .gitattributes
|
| 2 |
+
735681b0b89f7ece379a3c17c12d446d072e8690e88a80da0aa626605b903d52 README.md
|
| 3 |
dffd02d522c1cb894d4fd1eebe0e4b6098d045fac77755fc8f49341388b32750 SOURCE_README.md
|
| 4 |
45f086796ca39994272e11a31a601ac2b8e91536f9bd812ce849be4c55042537 data/bow.csv
|
| 5 |
b9959f976605f8b418f6565fec8228e1bfbb0e8a7c314f0d1cf9b79258e9ac7c data/labels.json
|
| 6 |
1583bd93c7c5ef660fb18b255984d8a0caf721f8ac21026d40536f673a73ecbe data/noow.csv
|
| 7 |
d2e221cca3c7297d5b84f0d18dc2a7ba448e3775e33ff96a5e4bd30b33d13400 data/splits.json
|
| 8 |
+
6feaded4e28ea86e001a6751b4e3d960e8b7c31b9616ff9936b79297086e809b preprocessing/.gitignore
|
| 9 |
+
15eb97925fe33f7fe096b36f95a5b19e66041101ba35d0dd4948cc8f3e0528e0 preprocessing/LICENSE
|
| 10 |
+
1c947d9d405f7031654d0ca900eba7c71b1adbb8675d1939c3dd1b9aa4be46e7 preprocessing/README.md
|
| 11 |
+
85821876745568dee4cfb46b7d49843ace0390b89d761fa2fc76e21d5b65efee preprocessing/_pipeline.py
|
| 12 |
+
d6d1374d3ea144edc3fd5285ba87dac4daa9dea2857d0f165c6d0943a69a43fc preprocessing/conda-linux-64.lock.txt
|
| 13 |
+
7e301b934c9abe47e404e0935bc83129023a0ee31a9edbec2ea039d1c322ce22 preprocessing/payload-pins.json
|
| 14 |
+
c34178178f5b77ca0f766a7965bac1c4d541ae510dacfb9915af4d0915e32ece preprocessing/pip-linux-x86_64.lock.txt
|
| 15 |
+
2d1368a94fe38ebe8cab804a50bde2fea71b3e43a769576a6dd6988b32c25a45 preprocessing/prepare.py
|
| 16 |
+
02d7891df73d9d104efcc492489f76d3d1b9b4a00674b0b0bfd1529c8ab98c31 preprocessing/requirements-download.txt
|
| 17 |
+
3ec34d3f3f4ce6fc02a12be33e49fce5c8f55adb7821c153074a26df93558b8f preprocessing/requirements.txt
|
| 18 |
+
443cffa24dd51d08039150cafcdf97bc45e7cabc5ea6bbb628000d563c09a26f preprocessing/source-pins.json
|
| 19 |
+
9e320475adc24f0757381f57521d36abd4b5d65087205c8d5c58ba3b39d1b10d preprocessing/test_prepare.py
|
preprocessing/.gitignore
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__pycache__/
|
| 2 |
+
*.py[cod]
|
preprocessing/LICENSE
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
MIT License
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2026 preprocessing 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.
|
| 22 |
+
|
| 23 |
+
This license applies only to the preprocessing code in this directory.
|
| 24 |
+
Dataset texts, source documentation and NLP resources retain their respective
|
| 25 |
+
copyrights, permissions and usage restrictions.
|
preprocessing/README.md
ADDED
|
@@ -0,0 +1,210 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Reproduce the prepared corpora
|
| 2 |
+
|
| 3 |
+
This folder contains the standalone preprocessing code shared by SciNews,
|
| 4 |
+
BBC-News, WOS-5736, WOS-11967 and WOS-46985. It downloads pinned source files,
|
| 5 |
+
rebuilds the CSV and JSON files described in the dataset cards, and checks the
|
| 6 |
+
result against the recorded SHA-256 values. It needs no parent project checkout,
|
| 7 |
+
BigARTM, TopicNet installation or model training.
|
| 8 |
+
|
| 9 |
+
The code is distributed under [MIT](LICENSE). This license covers the code only.
|
| 10 |
+
Source texts and prepared data retain their own rights and access conditions;
|
| 11 |
+
consult the corresponding dataset card and original source notices. In
|
| 12 |
+
particular, SciNews requires approved access to the original dataset, and BBC
|
| 13 |
+
redistribution rights remain unresolved.
|
| 14 |
+
|
| 15 |
+
## Obtain only the code
|
| 16 |
+
|
| 17 |
+
The common code lives in `preprocessing/` in the `TopicNet/SciNews` dataset
|
| 18 |
+
repository. Access to this folder follows access to that repository. Authenticate
|
| 19 |
+
with an authorized Hugging Face account if required; downloading the folder does
|
| 20 |
+
not change repository visibility or grant access to the original SciNews source.
|
| 21 |
+
|
| 22 |
+
Choose a full commit hash from the repository history that contains this folder.
|
| 23 |
+
Set `CODE_REVISION` to that hash, rather than relying on a moving `main` branch.
|
| 24 |
+
Use a separate download environment with the official `huggingface_hub` SDK for
|
| 25 |
+
this initial download (`python -m pip install huggingface_hub==1.25.1`):
|
| 26 |
+
|
| 27 |
+
```bash
|
| 28 |
+
export CODE_REVISION=REPLACE_WITH_FULL_COMMIT_HASH
|
| 29 |
+
python - <<'PY'
|
| 30 |
+
import os
|
| 31 |
+
from huggingface_hub import snapshot_download
|
| 32 |
+
|
| 33 |
+
snapshot_download(
|
| 34 |
+
repo_id="TopicNet/SciNews",
|
| 35 |
+
repo_type="dataset",
|
| 36 |
+
revision=os.environ["CODE_REVISION"],
|
| 37 |
+
allow_patterns=["preprocessing/*"],
|
| 38 |
+
local_dir="corpus-code",
|
| 39 |
+
)
|
| 40 |
+
PY
|
| 41 |
+
cd corpus-code
|
| 42 |
+
```
|
| 43 |
+
|
| 44 |
+
This downloads the code folder, not the prepared SciNews CSV files. Before the
|
| 45 |
+
code is published, use the local copy of `SciNews/preprocessing/` instead and
|
| 46 |
+
work from its parent directory. A Hugging Face commit containing new code is
|
| 47 |
+
available only after that code has been committed to the dataset repository.
|
| 48 |
+
|
| 49 |
+
## Create the environment
|
| 50 |
+
|
| 51 |
+
The supplied locks target Linux x86-64 with Python 3.11.15. Create a dedicated
|
| 52 |
+
environment with Conda, then install the locked Python packages:
|
| 53 |
+
|
| 54 |
+
```bash
|
| 55 |
+
conda create --prefix /path/to/envs/corpus-preprocessing --file preprocessing/conda-linux-64.lock.txt
|
| 56 |
+
conda activate /path/to/envs/corpus-preprocessing
|
| 57 |
+
python -m pip install -r preprocessing/pip-linux-x86_64.lock.txt
|
| 58 |
+
```
|
| 59 |
+
|
| 60 |
+
Place the environment outside the downloaded code folder. Keep the locks
|
| 61 |
+
unchanged for byte-for-byte reproduction. Scientific dependencies
|
| 62 |
+
and NLTK resources are checked by the program. NLTK 3.9.2 uses the resource
|
| 63 |
+
revision recorded in the cards and source pins. The Hugging Face download SDK is
|
| 64 |
+
an optional network dependency, specified in
|
| 65 |
+
`preprocessing/requirements-download.txt`; install it when downloading SciNews:
|
| 66 |
+
|
| 67 |
+
```bash
|
| 68 |
+
python -m pip install -r preprocessing/requirements-download.txt
|
| 69 |
+
```
|
| 70 |
+
|
| 71 |
+
## Download sources
|
| 72 |
+
|
| 73 |
+
Choose a writable source directory. The supported dataset selectors are
|
| 74 |
+
`bbc-news`, `scinews`, `wos-5736`, `wos-11967` and `wos-46985`:
|
| 75 |
+
|
| 76 |
+
```bash
|
| 77 |
+
python preprocessing/prepare.py download --dataset bbc-news --sources-dir /path/to/sources
|
| 78 |
+
python preprocessing/prepare.py download --dataset scinews --sources-dir /path/to/sources
|
| 79 |
+
python preprocessing/prepare.py download --dataset wos-5736 --sources-dir /path/to/sources
|
| 80 |
+
```
|
| 81 |
+
|
| 82 |
+
The three WOS selectors share the same source archive, so download it once.
|
| 83 |
+
Before the WOS download command, obtain the original `ReadMe.txt` notice from
|
| 84 |
+
the [official version 6 release](https://data.mendeley.com/datasets/9rw3vkcfy4/6)
|
| 85 |
+
and place it at `/path/to/sources/wos/ReadMe.txt`. Preserve its exact bytes:
|
| 86 |
+
2,587 bytes, SHA-256
|
| 87 |
+
`6da4ab1e624c4ef61c46600d727770f873ff4db3c15541fb481e7af8a715c0ec`.
|
| 88 |
+
You can copy `SOURCE_README.txt` unchanged from any of the provided WOS packages
|
| 89 |
+
to this path; all three packages contain the same notice with this exact hash.
|
| 90 |
+
The notice requires this manual step because its stable download URL could not
|
| 91 |
+
be confirmed. The program validates it, then downloads and validates the archive;
|
| 92 |
+
it stops with placement instructions if the notice is absent.
|
| 93 |
+
Downloads also provide the pinned NLTK resources. For SciNews, first obtain
|
| 94 |
+
approval at the original `dongqi-me/SciNews` repository and authenticate through
|
| 95 |
+
the standard Hugging Face login or `HF_TOKEN` environment variable. Approval for
|
| 96 |
+
one repository does not imply approval for another. Keep credentials out of
|
| 97 |
+
logs and copied source directories.
|
| 98 |
+
|
| 99 |
+
The downloaded layout is:
|
| 100 |
+
|
| 101 |
+
```text
|
| 102 |
+
sources/
|
| 103 |
+
bbc-news/bbc-fulltext.zip
|
| 104 |
+
scinews/README.md
|
| 105 |
+
scinews/train.json
|
| 106 |
+
scinews/val.json
|
| 107 |
+
scinews/test.json
|
| 108 |
+
wos/WebOfScience.zip
|
| 109 |
+
wos/ReadMe.txt
|
| 110 |
+
nltk_data/
|
| 111 |
+
```
|
| 112 |
+
|
| 113 |
+
Only the selected corpus and shared NLTK resources are needed for each build.
|
| 114 |
+
Source revisions, URLs and expected hashes are recorded in this code folder;
|
| 115 |
+
substituting a newer source release changes the input and is rejected. If source
|
| 116 |
+
files are transferred manually, preserve this layout and their exact bytes.
|
| 117 |
+
|
| 118 |
+
## Build and verify offline
|
| 119 |
+
|
| 120 |
+
After downloading sources and installing the environment, build and verify need
|
| 121 |
+
no network connection. Select a fresh output path and a fresh scratch path. The
|
| 122 |
+
output directory holds `noow.csv`, `bow.csv`, `labels.json` and `splits.json`,
|
| 123 |
+
plus `hierarchy.json` for WOS. These correspond to the files under `data/` in
|
| 124 |
+
the respective dataset repository. Scratch files are kept separately.
|
| 125 |
+
|
| 126 |
+
```bash
|
| 127 |
+
export HF_HUB_OFFLINE=1
|
| 128 |
+
export HF_DATASETS_OFFLINE=1
|
| 129 |
+
python preprocessing/prepare.py build --dataset bbc-news \
|
| 130 |
+
--sources-dir /path/to/sources \
|
| 131 |
+
--output-dir /path/to/rebuilt/BBC-News/data \
|
| 132 |
+
--scratch-dir /path/to/scratch/bbc-news
|
| 133 |
+
python preprocessing/prepare.py verify --dataset bbc-news \
|
| 134 |
+
--data-dir /path/to/rebuilt/BBC-News/data
|
| 135 |
+
```
|
| 136 |
+
|
| 137 |
+
Use the same commands with any supported selector. Verification checks the
|
| 138 |
+
recorded hashes of the prepared data files, including split memberships and WOS
|
| 139 |
+
hierarchy metadata; it does not download missing inputs or rebuild files. A
|
| 140 |
+
successful build alone is not a successful verification. The dataset-level
|
| 141 |
+
`sha256sum -c SHA256SUMS` checks a complete downloaded repository package,
|
| 142 |
+
including its card and source notice, and is separate from verifying a rebuild.
|
| 143 |
+
|
| 144 |
+
Missing output and scratch parent directories are created after input and path
|
| 145 |
+
validation. Both destination directories themselves must be new.
|
| 146 |
+
Builds refuse to overwrite existing outputs. If a build fails, retain its output,
|
| 147 |
+
scratch files and log for diagnosis. Use new output and scratch paths for a
|
| 148 |
+
manual retry; do not treat a partial directory as a verified result.
|
| 149 |
+
|
| 150 |
+
## Run the bundled checks
|
| 151 |
+
|
| 152 |
+
From the directory containing `preprocessing/`, run the checks with Python's
|
| 153 |
+
standard `unittest` runner; no additional test dependency is needed:
|
| 154 |
+
|
| 155 |
+
```bash
|
| 156 |
+
python -B -m unittest discover -v -s preprocessing -p test_prepare.py
|
| 157 |
+
PORTABLE_NLTK_DATA=/absolute/path/to/sources/nltk_data \
|
| 158 |
+
python -B -m unittest discover -v -s preprocessing -p test_prepare.py
|
| 159 |
+
```
|
| 160 |
+
|
| 161 |
+
The first command skips the three checks requiring real NLTK resources. The
|
| 162 |
+
second runs all six checks with the locked environment and acquired resources.
|
| 163 |
+
Full rebuilds from the raw sources followed by exact hash verification have been
|
| 164 |
+
confirmed for BBC-News and WOS-5736. Full SciNews, WOS-11967 and WOS-46985
|
| 165 |
+
reproduction is pending server verification; fixture checks and source pins alone
|
| 166 |
+
do not establish byte-for-byte reproduction of those builds.
|
| 167 |
+
|
| 168 |
+
## Run the remaining full builds on a server
|
| 169 |
+
|
| 170 |
+
Transfer this entire code folder and the relevant downloaded sources, including
|
| 171 |
+
`nltk_data/`, to the server. Recreate the locked environment there using the
|
| 172 |
+
commands above. Run from the directory containing `preprocessing/`. Choose paths
|
| 173 |
+
on a filesystem with enough space for source archives, temporary files and both
|
| 174 |
+
CSV representations. These full builds may take substantially longer than a
|
| 175 |
+
small-corpus run; no fixed time or memory limit is assumed here.
|
| 176 |
+
|
| 177 |
+
The following Bash example records build and verification logs separately and
|
| 178 |
+
stops if either command fails. Replace the paths before running; all output,
|
| 179 |
+
scratch and log paths must be fresh:
|
| 180 |
+
|
| 181 |
+
```bash
|
| 182 |
+
set -euo pipefail
|
| 183 |
+
export HF_HUB_OFFLINE=1
|
| 184 |
+
export HF_DATASETS_OFFLINE=1
|
| 185 |
+
SOURCE_ROOT=/srv/corpus-sources
|
| 186 |
+
RUN_ROOT=/srv/corpus-rebuild-001
|
| 187 |
+
mkdir "$RUN_ROOT"
|
| 188 |
+
mkdir "$RUN_ROOT/logs"
|
| 189 |
+
|
| 190 |
+
python --version > "$RUN_ROOT/logs/python.txt" 2>&1
|
| 191 |
+
python -m pip freeze > "$RUN_ROOT/logs/packages.txt"
|
| 192 |
+
find preprocessing -type f ! -path '*/__pycache__/*' ! -name '*.pyc' -print0 \
|
| 193 |
+
| sort -z | xargs -0 sha256sum > "$RUN_ROOT/logs/code-sha256.txt"
|
| 194 |
+
|
| 195 |
+
for DATASET in scinews wos-11967 wos-46985; do
|
| 196 |
+
python preprocessing/prepare.py build --dataset "$DATASET" \
|
| 197 |
+
--sources-dir "$SOURCE_ROOT" \
|
| 198 |
+
--output-dir "$RUN_ROOT/$DATASET/data" \
|
| 199 |
+
--scratch-dir "$RUN_ROOT/$DATASET-scratch" \
|
| 200 |
+
2>&1 | tee "$RUN_ROOT/logs/$DATASET-build.log"
|
| 201 |
+
python preprocessing/prepare.py verify --dataset "$DATASET" \
|
| 202 |
+
--data-dir "$RUN_ROOT/$DATASET/data" \
|
| 203 |
+
2>&1 | tee "$RUN_ROOT/logs/$DATASET-verify.log"
|
| 204 |
+
done
|
| 205 |
+
```
|
| 206 |
+
|
| 207 |
+
Retain the chosen code commit hash with these logs. Count a corpus as reproduced
|
| 208 |
+
only after its verification command exits successfully. If a command fails, the
|
| 209 |
+
loop stops and preserves its existing files; choose a new run directory when
|
| 210 |
+
retrying.
|
preprocessing/_pipeline.py
ADDED
|
@@ -0,0 +1,358 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Portable, disk-backed reproduction of the five published preparations.
|
| 2 |
+
|
| 3 |
+
The CLI validates source and resource hashes before calling :func:`build`.
|
| 4 |
+
Only new output/scratch directories are written; failed runs are left for inspection.
|
| 5 |
+
"""
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
from collections import Counter, defaultdict
|
| 9 |
+
from contextlib import ExitStack
|
| 10 |
+
import csv
|
| 11 |
+
import io
|
| 12 |
+
import itertools
|
| 13 |
+
import json
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
import re
|
| 16 |
+
import sqlite3
|
| 17 |
+
import zipfile
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class EnglishPreprocessor:
|
| 21 |
+
"""Use local NLTK resources and preserve the original occurrence semantics."""
|
| 22 |
+
|
| 23 |
+
def __init__(self, nltk_data_path: Path):
|
| 24 |
+
import nltk
|
| 25 |
+
from nltk.corpus.reader import WordNetCorpusReader
|
| 26 |
+
from nltk.data import ZipFilePathPointer
|
| 27 |
+
from nltk.tag import PerceptronTagger
|
| 28 |
+
from nltk.tokenize import WordPunctTokenizer
|
| 29 |
+
|
| 30 |
+
class LocalWordNetReader(WordNetCorpusReader):
|
| 31 |
+
def map_wn(self, version="wordnet"):
|
| 32 |
+
return None
|
| 33 |
+
|
| 34 |
+
if nltk.__version__ != "3.9.2":
|
| 35 |
+
raise ValueError("NLTK 3.9.2 is required")
|
| 36 |
+
root = Path(nltk_data_path)
|
| 37 |
+
self.tokenizer = WordPunctTokenizer()
|
| 38 |
+
self.tagger = PerceptronTagger(load=False)
|
| 39 |
+
self.tagger.load_from_json(loc=str(root / "taggers/averaged_perceptron_tagger_eng"))
|
| 40 |
+
self.wordnet = LocalWordNetReader(
|
| 41 |
+
ZipFilePathPointer(str(root / "corpora/wordnet.zip"), "wordnet/"), None,
|
| 42 |
+
)
|
| 43 |
+
self.stopwords = frozenset((root / "corpora/stopwords/english").read_text(
|
| 44 |
+
encoding="utf-8").splitlines())
|
| 45 |
+
|
| 46 |
+
def occurrences(self, raw_text: str) -> tuple[dict[str, object], ...]:
|
| 47 |
+
spans = tuple((start, end) for start, end in self.tokenizer.span_tokenize(raw_text)
|
| 48 |
+
if len(raw_text[start:end].lower()) > 1)
|
| 49 |
+
tagged = self.tagger.tag([raw_text[start:end].lower() for start, end in spans])
|
| 50 |
+
output = []
|
| 51 |
+
for (start, end), (word, tag) in zip(spans, tagged, strict=True):
|
| 52 |
+
pos = {"J": "a", "V": "v", "N": "n", "R": "r"}.get(tag[:1], "n")
|
| 53 |
+
lemmas = self.wordnet._morphy(word, pos)
|
| 54 |
+
lemma = min(lemmas, key=len) if lemmas else word
|
| 55 |
+
if lemma not in self.stopwords and lemma.isalpha():
|
| 56 |
+
output.append({"lemma": lemma, "start": start, "end": end,
|
| 57 |
+
"occurrence_index": len(output)})
|
| 58 |
+
return tuple(output)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def _json_records(path: Path):
|
| 62 |
+
"""Decode a JSON array incrementally, including strict framing checks."""
|
| 63 |
+
def object_pairs(pairs):
|
| 64 |
+
result = {}
|
| 65 |
+
for key, value in pairs:
|
| 66 |
+
if key in result:
|
| 67 |
+
raise ValueError("Duplicate JSON object key")
|
| 68 |
+
result[key] = value
|
| 69 |
+
return result
|
| 70 |
+
|
| 71 |
+
def invalid_constant(value):
|
| 72 |
+
raise ValueError(f"Invalid JSON constant: {value}")
|
| 73 |
+
|
| 74 |
+
decoder = json.JSONDecoder(object_pairs_hook=object_pairs, parse_constant=invalid_constant)
|
| 75 |
+
with path.open(encoding="utf-8", errors="strict") as stream:
|
| 76 |
+
buffer, eof = "", False
|
| 77 |
+
|
| 78 |
+
def fill():
|
| 79 |
+
nonlocal buffer, eof
|
| 80 |
+
chunk = stream.read(65536)
|
| 81 |
+
buffer += chunk
|
| 82 |
+
eof = not chunk
|
| 83 |
+
|
| 84 |
+
def whitespace():
|
| 85 |
+
nonlocal buffer
|
| 86 |
+
buffer = buffer.lstrip(" \t\r\n")
|
| 87 |
+
while not buffer and not eof:
|
| 88 |
+
fill()
|
| 89 |
+
buffer = buffer.lstrip(" \t\r\n")
|
| 90 |
+
|
| 91 |
+
whitespace()
|
| 92 |
+
if not buffer.startswith("["):
|
| 93 |
+
raise ValueError("SciNews JSON must contain an array")
|
| 94 |
+
buffer = buffer[1:]
|
| 95 |
+
whitespace()
|
| 96 |
+
if buffer.startswith("]"):
|
| 97 |
+
buffer = buffer[1:]
|
| 98 |
+
else:
|
| 99 |
+
while True:
|
| 100 |
+
while True:
|
| 101 |
+
try:
|
| 102 |
+
record, end = decoder.raw_decode(buffer)
|
| 103 |
+
break
|
| 104 |
+
except json.JSONDecodeError:
|
| 105 |
+
if eof:
|
| 106 |
+
raise
|
| 107 |
+
fill()
|
| 108 |
+
buffer = buffer[end:]
|
| 109 |
+
yield record
|
| 110 |
+
whitespace()
|
| 111 |
+
if buffer.startswith("]"):
|
| 112 |
+
buffer = buffer[1:]
|
| 113 |
+
break
|
| 114 |
+
if not buffer.startswith(","):
|
| 115 |
+
raise ValueError("Invalid SciNews array separator")
|
| 116 |
+
buffer = buffer[1:]
|
| 117 |
+
whitespace()
|
| 118 |
+
if buffer.startswith("]"):
|
| 119 |
+
raise ValueError("Trailing comma in SciNews array")
|
| 120 |
+
whitespace()
|
| 121 |
+
if buffer:
|
| 122 |
+
raise ValueError("Trailing content in SciNews JSON")
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def _source_rows(dataset: str, source_path: Path):
|
| 126 |
+
"""Yield id, original body/title, external labels, URL and normalized DOI."""
|
| 127 |
+
if dataset == "scinews":
|
| 128 |
+
for split in ("train", "val", "test"):
|
| 129 |
+
for index, record in enumerate(_json_records(source_path / f"{split}.json")):
|
| 130 |
+
fields = {"News_Title", "News_Body", "News_URL", "Citation", "DOI",
|
| 131 |
+
"Paper_URL", "Paper_Body", "Topic"}
|
| 132 |
+
topics = {"Biology", "Chemistry", "Computer", "Earth", "Medicine",
|
| 133 |
+
"Nano", "Other", "Physics", "Space"}
|
| 134 |
+
if (not isinstance(record, dict) or set(record) != fields
|
| 135 |
+
or any(type(value) is not str for value in record.values())
|
| 136 |
+
or record["Topic"] not in topics):
|
| 137 |
+
raise ValueError(f"Invalid SciNews record schema: {split}:{index}")
|
| 138 |
+
doi = record["DOI"].strip().casefold()
|
| 139 |
+
doi = re.sub(r"^(?:doi:\s*|https?://(?:dx\.)?doi\.org/)", "", doi, count=1)
|
| 140 |
+
yield (f"scinews_{split}_{index:06d}", record["News_Body"],
|
| 141 |
+
record["News_Title"], record["Topic"], "", "", record["News_URL"], doi)
|
| 142 |
+
elif dataset == "bbc-news":
|
| 143 |
+
with zipfile.ZipFile(source_path) as archive:
|
| 144 |
+
for name in archive.namelist():
|
| 145 |
+
match = re.fullmatch(r"bbc/(business|entertainment|politics|sport|tech)/([0-9]{3})\.txt", name)
|
| 146 |
+
if match is None:
|
| 147 |
+
continue
|
| 148 |
+
label, stem = match.groups()
|
| 149 |
+
text = archive.read(name).decode("utf-8", errors="strict")
|
| 150 |
+
parts = re.split(r"\r?\n[ \t]*\r?\n", text, maxsplit=1)
|
| 151 |
+
if len(parts) != 2 or not parts[0] or "\n" in parts[0] or "\r" in parts[0]:
|
| 152 |
+
raise ValueError(f"Invalid BBC title/body layout: {name}")
|
| 153 |
+
yield f"bbc_{label}_{stem}", parts[1], parts[0], label, "", "", "", ""
|
| 154 |
+
else:
|
| 155 |
+
subset = dataset.removeprefix("wos-")
|
| 156 |
+
with zipfile.ZipFile(source_path) as archive, ExitStack() as stack:
|
| 157 |
+
streams = [stack.enter_context(io.TextIOWrapper(
|
| 158 |
+
archive.open(f"WOS{subset}/{field}.txt"), encoding="utf-8", errors="strict", newline=""))
|
| 159 |
+
for field in ("X", "Y", "YL1", "YL2")]
|
| 160 |
+
for index, lines in enumerate(itertools.zip_longest(*streams)):
|
| 161 |
+
if any(line is None for line in lines):
|
| 162 |
+
raise ValueError("WOS source rows are misaligned")
|
| 163 |
+
body, label, parent, child = [
|
| 164 |
+
line[:-2] if line.endswith("\r\n") else
|
| 165 |
+
line[:-1] if line.endswith(("\n", "\r")) else line for line in lines]
|
| 166 |
+
if any(re.fullmatch(r"0|[1-9][0-9]*", value) is None
|
| 167 |
+
for value in (label, parent, child)):
|
| 168 |
+
raise ValueError("Noncanonical WOS integer label")
|
| 169 |
+
yield f"wos{subset}_{index:06d}", body, "", label, parent, child, "", ""
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def _shuffle_split(labels_by_id, test_size, seed):
|
| 173 |
+
ids = tuple(sorted(labels_by_id))
|
| 174 |
+
labels = tuple(sorted({label for values in labels_by_id.values() for label in values}))
|
| 175 |
+
matrix = [[label in labels_by_id[identifier] for label in labels] for identifier in ids]
|
| 176 |
+
if len(labels) < 2:
|
| 177 |
+
from sklearn.model_selection import StratifiedShuffleSplit
|
| 178 |
+
splitter = StratifiedShuffleSplit(n_splits=1, test_size=test_size, random_state=seed)
|
| 179 |
+
train, test = next(splitter.split([[0]] * len(ids), [row[0] if row else False for row in matrix]))
|
| 180 |
+
else:
|
| 181 |
+
from iterstrat.ml_stratifiers import MultilabelStratifiedShuffleSplit
|
| 182 |
+
splitter = MultilabelStratifiedShuffleSplit(n_splits=1, test_size=test_size, random_state=seed)
|
| 183 |
+
train, test = next(splitter.split([[0]] * len(ids), matrix))
|
| 184 |
+
return [ids[index] for index in train], [ids[index] for index in test]
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
def build(dataset: str, source_path: Path, nltk_data_path: Path,
|
| 188 |
+
output_dir: Path, scratch_dir: Path) -> None:
|
| 189 |
+
"""Rebuild one preparation into a new directory of directly usable files.
|
| 190 |
+
|
| 191 |
+
Hash validation belongs to the CLI. This API rejects existing destinations,
|
| 192 |
+
symlink paths and destination overlap with sources, resources or shipped code.
|
| 193 |
+
Concurrent replacement of directories by another process is outside its scope.
|
| 194 |
+
"""
|
| 195 |
+
from nltk.tokenize import WordPunctTokenizer
|
| 196 |
+
|
| 197 |
+
if dataset not in {"bbc-news", "scinews", "wos-5736", "wos-11967", "wos-46985"}:
|
| 198 |
+
raise ValueError(f"Unknown dataset: {dataset}")
|
| 199 |
+
paths = [Path(path).absolute() for path in (source_path, nltk_data_path, output_dir, scratch_dir)]
|
| 200 |
+
for path in paths:
|
| 201 |
+
if any(part.is_symlink() for part in (path, *path.parents)):
|
| 202 |
+
raise ValueError(f"Symlink paths are not supported: {path}")
|
| 203 |
+
source_path, nltk_data_path, output_dir, scratch_dir = [path.resolve() for path in paths]
|
| 204 |
+
destinations = (output_dir, scratch_dir)
|
| 205 |
+
for path in destinations:
|
| 206 |
+
if path.exists():
|
| 207 |
+
raise ValueError(f"Destination must be new: {path}")
|
| 208 |
+
code = Path(__file__).resolve().parent
|
| 209 |
+
protected = [source_path, nltk_data_path, code]
|
| 210 |
+
# Also protect published sibling data when this folder is used in place.
|
| 211 |
+
protected.extend(code.parent.parent / name / "data" for name in
|
| 212 |
+
("SciNews", "BBC-News", "WOS-5736", "WOS-11967", "WOS-46985"))
|
| 213 |
+
for left, right in itertools.combinations(destinations, 2):
|
| 214 |
+
if left == right or left in right.parents or right in left.parents:
|
| 215 |
+
raise ValueError("Output and scratch paths overlap")
|
| 216 |
+
for destination in destinations:
|
| 217 |
+
for path in protected:
|
| 218 |
+
if destination == path or destination in path.parents or path in destination.parents:
|
| 219 |
+
raise ValueError(f"Destination overlaps protected path: {path}")
|
| 220 |
+
processor = EnglishPreprocessor(nltk_data_path)
|
| 221 |
+
for path in destinations:
|
| 222 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 223 |
+
scratch_dir.mkdir()
|
| 224 |
+
store = sqlite3.connect(scratch_dir / "processing.sqlite3")
|
| 225 |
+
try:
|
| 226 |
+
store.execute("PRAGMA cache_size=-65536")
|
| 227 |
+
store.execute("PRAGMA temp_store=MEMORY")
|
| 228 |
+
store.executescript("""
|
| 229 |
+
CREATE TABLE rows (id TEXT PRIMARY KEY, raw TEXT NOT NULL, title TEXT NOT NULL,
|
| 230 |
+
y TEXT NOT NULL, yl1 TEXT NOT NULL, yl2 TEXT NOT NULL,
|
| 231 |
+
url TEXT NOT NULL, doi TEXT NOT NULL, raw_identity TEXT NOT NULL,
|
| 232 |
+
lemmas TEXT, title_lemmas TEXT, reason TEXT, shingle_size INTEGER);
|
| 233 |
+
CREATE INDEX raw_idx ON rows(raw_identity,id);
|
| 234 |
+
CREATE INDEX lemma_idx ON rows(lemmas,id);
|
| 235 |
+
CREATE INDEX url_idx ON rows(url,id);
|
| 236 |
+
CREATE INDEX doi_idx ON rows(doi,id);
|
| 237 |
+
CREATE INDEX near_sizes ON rows(id,shingle_size);
|
| 238 |
+
CREATE TABLE shingles (identity TEXT, id TEXT,
|
| 239 |
+
PRIMARY KEY(identity,id)) WITHOUT ROWID;
|
| 240 |
+
CREATE TEMP TABLE current_shingles (identity TEXT PRIMARY KEY) WITHOUT ROWID;
|
| 241 |
+
""")
|
| 242 |
+
print(f"{dataset}: reading original source", flush=True)
|
| 243 |
+
for row in _source_rows(dataset, source_path):
|
| 244 |
+
identifier, raw, title, label, parent, child, url, doi = row
|
| 245 |
+
store.execute("""INSERT INTO rows
|
| 246 |
+
(id,raw,title,y,yl1,yl2,url,doi,raw_identity) VALUES (?,?,?,?,?,?,?,?,?)""",
|
| 247 |
+
(*row, " ".join(raw.casefold().split())))
|
| 248 |
+
store.commit()
|
| 249 |
+
parents = {identifier: identifier for (identifier,) in store.execute("SELECT id FROM rows")}
|
| 250 |
+
|
| 251 |
+
def root(identifier):
|
| 252 |
+
while parents[identifier] != identifier:
|
| 253 |
+
parents[identifier] = parents[parents[identifier]]
|
| 254 |
+
identifier = parents[identifier]
|
| 255 |
+
return identifier
|
| 256 |
+
|
| 257 |
+
def connect(ids):
|
| 258 |
+
roots = {root(identifier) for identifier in ids}
|
| 259 |
+
minimum = min(roots)
|
| 260 |
+
for identifier in roots:
|
| 261 |
+
parents[identifier] = minimum
|
| 262 |
+
|
| 263 |
+
for field, condition in (("raw_identity", "1"), ("url", "url != ''"), ("doi", "doi != ''")):
|
| 264 |
+
cursor = store.execute(f"SELECT {field},id,y FROM rows WHERE {condition} ORDER BY {field},id")
|
| 265 |
+
for _, members in itertools.groupby(cursor, lambda row: row[0]):
|
| 266 |
+
members = list(members)
|
| 267 |
+
ids = [row[1] for row in members]
|
| 268 |
+
if len(ids) > 1:
|
| 269 |
+
connect(ids)
|
| 270 |
+
if field == "raw_identity":
|
| 271 |
+
removed = ids[1:] if len({row[2] for row in members}) == 1 else ids
|
| 272 |
+
store.executemany("UPDATE rows SET reason='raw' WHERE id=?", ((i,) for i in removed))
|
| 273 |
+
print(f"{dataset}: normalizing raw-clean documents", flush=True)
|
| 274 |
+
for count, (identifier, raw, title) in enumerate(store.execute(
|
| 275 |
+
"SELECT id,raw,title FROM rows WHERE reason IS NULL ORDER BY id"), 1):
|
| 276 |
+
lemmas = " ".join(str(item["lemma"]) for item in processor.occurrences(raw))
|
| 277 |
+
title_lemmas = " ".join(str(item["lemma"]) for item in processor.occurrences(title))
|
| 278 |
+
store.execute("UPDATE rows SET lemmas=?,title_lemmas=?,reason=? WHERE id=?",
|
| 279 |
+
(lemmas, title_lemmas, None if lemmas else "empty", identifier))
|
| 280 |
+
if count % 1000 == 0:
|
| 281 |
+
print(f"{dataset}: normalized {count}", flush=True)
|
| 282 |
+
cursor = store.execute("SELECT lemmas,id,y FROM rows WHERE reason IS NULL ORDER BY lemmas,id")
|
| 283 |
+
for _, members in itertools.groupby(cursor, lambda row: row[0]):
|
| 284 |
+
members = list(members)
|
| 285 |
+
ids = [row[1] for row in members]
|
| 286 |
+
if len(ids) > 1:
|
| 287 |
+
connect(ids)
|
| 288 |
+
removed = ids[1:] if len({row[2] for row in members}) == 1 else ids
|
| 289 |
+
store.executemany("UPDATE rows SET reason='lemma' WHERE id=?", ((i,) for i in removed))
|
| 290 |
+
store.commit()
|
| 291 |
+
retained = [row[0] for row in store.execute("SELECT id FROM rows WHERE reason IS NULL ORDER BY id")]
|
| 292 |
+
print(f"{dataset}: grouping near duplicates among {len(retained)} retained documents", flush=True)
|
| 293 |
+
tokenizer = WordPunctTokenizer()
|
| 294 |
+
for count, identifier in enumerate(retained, 1):
|
| 295 |
+
raw = store.execute("SELECT raw FROM rows WHERE id=?", (identifier,)).fetchone()[0]
|
| 296 |
+
tokens = [token for token in tokenizer.tokenize(raw.lower()) if len(token) >= 2 and token.isalpha()]
|
| 297 |
+
shingles = {" ".join(tokens[index:index + 5]) for index in range(len(tokens) - 4)}
|
| 298 |
+
store.execute("DELETE FROM current_shingles")
|
| 299 |
+
store.executemany("INSERT INTO current_shingles VALUES (?)", ((s,) for s in shingles))
|
| 300 |
+
candidates = store.execute("""SELECT s.id,COUNT(*),r.shingle_size
|
| 301 |
+
FROM current_shingles c CROSS JOIN shingles s ON s.identity=c.identity
|
| 302 |
+
CROSS JOIN rows r INDEXED BY near_sizes ON r.id=s.id
|
| 303 |
+
GROUP BY s.id ORDER BY s.id""")
|
| 304 |
+
for previous, intersection, size in candidates:
|
| 305 |
+
union = len(shingles) + size - intersection
|
| 306 |
+
if intersection / union >= .9:
|
| 307 |
+
connect((previous, identifier))
|
| 308 |
+
store.execute("INSERT INTO shingles SELECT identity,? FROM current_shingles", (identifier,))
|
| 309 |
+
store.execute("UPDATE rows SET shingle_size=? WHERE id=?", (len(shingles), identifier))
|
| 310 |
+
if count % 1000 == 0:
|
| 311 |
+
store.commit()
|
| 312 |
+
print(f"{dataset}: grouped {count}/{len(retained)}", flush=True)
|
| 313 |
+
store.commit()
|
| 314 |
+
families = defaultdict(list)
|
| 315 |
+
labels = dict((identifier, [label]) for identifier, label in store.execute(
|
| 316 |
+
"SELECT id,y FROM rows WHERE reason IS NULL ORDER BY id"))
|
| 317 |
+
for identifier in retained:
|
| 318 |
+
families[root(identifier)].append(identifier)
|
| 319 |
+
family_labels = {group: sorted({labels[i][0] for i in ids}) for group, ids in families.items()}
|
| 320 |
+
fit, heldout = _shuffle_split(family_labels, .4, 20260824)
|
| 321 |
+
calibration, validation = _shuffle_split({i: family_labels[i] for i in heldout}, .5, 20260825)
|
| 322 |
+
splits = {split: sorted(i for group in groups for i in families[group])
|
| 323 |
+
for split, groups in (("fit", fit), ("calibration", calibration), ("validation", validation))}
|
| 324 |
+
output_dir.mkdir()
|
| 325 |
+
pretty = dataset in {"wos-5736", "wos-46985"}
|
| 326 |
+
for name, value in (("labels.json", labels), ("splits.json", splits)):
|
| 327 |
+
with (output_dir / name).open("x", encoding="utf-8", newline="") as stream:
|
| 328 |
+
json.dump(value, stream, ensure_ascii=False, sort_keys=True,
|
| 329 |
+
**({"indent": 2} if pretty else {"separators": (",", ":")}))
|
| 330 |
+
stream.write("\n")
|
| 331 |
+
is_wos = dataset.startswith("wos-")
|
| 332 |
+
if is_wos:
|
| 333 |
+
hierarchy = {identifier: {"Y": y, "YL1": yl1, "YL2": yl2}
|
| 334 |
+
for identifier, y, yl1, yl2 in store.execute(
|
| 335 |
+
"SELECT id,y,yl1,yl2 FROM rows WHERE reason IS NULL ORDER BY id")}
|
| 336 |
+
with (output_dir / "hierarchy.json").open("x", encoding="utf-8", newline="") as stream:
|
| 337 |
+
json.dump(hierarchy, stream, ensure_ascii=False, sort_keys=True, indent=2)
|
| 338 |
+
stream.write("\n")
|
| 339 |
+
with (output_dir / "noow.csv").open("x", encoding="utf-8", newline="") as noow, \
|
| 340 |
+
(output_dir / "bow.csv").open("x", encoding="utf-8", newline="") as bow:
|
| 341 |
+
writers = [csv.writer(stream, lineterminator="\n") for stream in (noow, bow)]
|
| 342 |
+
for writer in writers:
|
| 343 |
+
writer.writerow(("id", "raw_text", "vw_text"))
|
| 344 |
+
for identifier, raw, title, lemmas, title_lemmas in store.execute(
|
| 345 |
+
"SELECT id,raw,title,lemmas,title_lemmas FROM rows WHERE reason IS NULL ORDER BY id"):
|
| 346 |
+
namespaces = [("@word", lemmas.split())] if is_wos else [
|
| 347 |
+
("@title", title_lemmas.split()), ("@word", lemmas.split())]
|
| 348 |
+
fields, aggregated = [identifier], [identifier]
|
| 349 |
+
for namespace, tokens in namespaces:
|
| 350 |
+
fields.extend(["|" + namespace, *tokens])
|
| 351 |
+
counts = Counter(tokens)
|
| 352 |
+
aggregated.extend(["|" + namespace, *(f"{token}:{counts[token]}" for token in sorted(counts))])
|
| 353 |
+
public_raw = raw if is_wos else title + "\n\n" + raw.lstrip("\r\n")
|
| 354 |
+
writers[0].writerow((identifier, public_raw, " ".join(fields)))
|
| 355 |
+
writers[1].writerow((identifier, public_raw, " ".join(aggregated)))
|
| 356 |
+
print(f"{dataset}: wrote {len(retained)} documents to {output_dir}", flush=True)
|
| 357 |
+
finally:
|
| 358 |
+
store.close()
|
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/payload-pins.json
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"datasets": {
|
| 3 |
+
"bbc-news": {
|
| 4 |
+
"documents": 2085,
|
| 5 |
+
"files": {
|
| 6 |
+
"bow.csv": {
|
| 7 |
+
"bytes": 7575728,
|
| 8 |
+
"sha256": "3d604bbbe7e2eb8907f162f87617ac38db413957067e558226bb132c2445100d"
|
| 9 |
+
},
|
| 10 |
+
"labels.json": {
|
| 11 |
+
"bytes": 64764,
|
| 12 |
+
"sha256": "946d3a4ad97fcbb7952d8e3cc8f8a16f5ebdfdfce904939bc7c86ddbef90676d"
|
| 13 |
+
},
|
| 14 |
+
"noow.csv": {
|
| 15 |
+
"bytes": 7897816,
|
| 16 |
+
"sha256": "96051e9d10faf1bebe1a3baeaeef5bc93e806cf0ad0fb9882e9574e5385931e4"
|
| 17 |
+
},
|
| 18 |
+
"splits.json": {
|
| 19 |
+
"bytes": 38677,
|
| 20 |
+
"sha256": "e5d4cdaf68abd6d38fb6965da40e1bfd1915ac476209f021a3218e0e8e626d6a"
|
| 21 |
+
}
|
| 22 |
+
},
|
| 23 |
+
"split_counts": {
|
| 24 |
+
"calibration": 419,
|
| 25 |
+
"fit": 1250,
|
| 26 |
+
"validation": 416
|
| 27 |
+
}
|
| 28 |
+
},
|
| 29 |
+
"scinews": {
|
| 30 |
+
"documents": 41854,
|
| 31 |
+
"files": {
|
| 32 |
+
"bow.csv": {
|
| 33 |
+
"bytes": 261941524,
|
| 34 |
+
"sha256": "45f086796ca39994272e11a31a601ac2b8e91536f9bd812ce849be4c55042537"
|
| 35 |
+
},
|
| 36 |
+
"labels.json": {
|
| 37 |
+
"bytes": 1455076,
|
| 38 |
+
"sha256": "b9959f976605f8b418f6565fec8228e1bfbb0e8a7c314f0d1cf9b79258e9ac7c"
|
| 39 |
+
},
|
| 40 |
+
"noow.csv": {
|
| 41 |
+
"bytes": 290845394,
|
| 42 |
+
"sha256": "1583bd93c7c5ef660fb18b255984d8a0caf721f8ac21026d40536f673a73ecbe"
|
| 43 |
+
},
|
| 44 |
+
"splits.json": {
|
| 45 |
+
"bytes": 950125,
|
| 46 |
+
"sha256": "d2e221cca3c7297d5b84f0d18dc2a7ba448e3775e33ff96a5e4bd30b33d13400"
|
| 47 |
+
}
|
| 48 |
+
},
|
| 49 |
+
"split_counts": {
|
| 50 |
+
"calibration": 8370,
|
| 51 |
+
"fit": 25109,
|
| 52 |
+
"validation": 8375
|
| 53 |
+
}
|
| 54 |
+
},
|
| 55 |
+
"wos-11967": {
|
| 56 |
+
"documents": 11965,
|
| 57 |
+
"files": {
|
| 58 |
+
"bow.csv": {
|
| 59 |
+
"bytes": 26653958,
|
| 60 |
+
"sha256": "4e27d8e46bad08061568222a0931b963f6ad637074b1b227de095af05757d339"
|
| 61 |
+
},
|
| 62 |
+
"hierarchy.json": {
|
| 63 |
+
"bytes": 881997,
|
| 64 |
+
"sha256": "5a4ab746cdc75b048143eb8aeac2660535bed1a23cca7d37a6e4775bb9b7d3b6"
|
| 65 |
+
},
|
| 66 |
+
"labels.json": {
|
| 67 |
+
"bytes": 295711,
|
| 68 |
+
"sha256": "138c7a5ed0ae4787afdbd306a7fd2732b392ad8db65c22e7ce312c33a178470c"
|
| 69 |
+
},
|
| 70 |
+
"noow.csv": {
|
| 71 |
+
"bytes": 28197299,
|
| 72 |
+
"sha256": "101d1c8a690ae0fe1b68491cb144ff42114280e12770f8a332647106bd12580e"
|
| 73 |
+
},
|
| 74 |
+
"splits.json": {
|
| 75 |
+
"bytes": 215411,
|
| 76 |
+
"sha256": "608c14b244f02df40b897dfc7de3411352079bed0a507f2fd8ccf70b9c5996d7"
|
| 77 |
+
}
|
| 78 |
+
},
|
| 79 |
+
"split_counts": {
|
| 80 |
+
"calibration": 2391,
|
| 81 |
+
"fit": 7182,
|
| 82 |
+
"validation": 2392
|
| 83 |
+
}
|
| 84 |
+
},
|
| 85 |
+
"wos-46985": {
|
| 86 |
+
"documents": 46972,
|
| 87 |
+
"files": {
|
| 88 |
+
"bow.csv": {
|
| 89 |
+
"bytes": 106747458,
|
| 90 |
+
"sha256": "039c213b7d7cc3dd2256418443bfc23a8a3e927eadd87ffe5ac08a34f692aebd"
|
| 91 |
+
},
|
| 92 |
+
"hierarchy.json": {
|
| 93 |
+
"bytes": 3503602,
|
| 94 |
+
"sha256": "1f714d3a953c7e3517f647f431d9a5d75f429b05574e66336166f2d5476a1f47"
|
| 95 |
+
},
|
| 96 |
+
"labels.json": {
|
| 97 |
+
"bytes": 1745914,
|
| 98 |
+
"sha256": "4ccc24e6f281cb85f6db04665a46d82072bdfb72a8485a814fd8182722b50a5d"
|
| 99 |
+
},
|
| 100 |
+
"noow.csv": {
|
| 101 |
+
"bytes": 113457365,
|
| 102 |
+
"sha256": "dba99ba99feaaf4de483969b64b5cd3bc1dca456cdcce367811517f69d251eff"
|
| 103 |
+
},
|
| 104 |
+
"splits.json": {
|
| 105 |
+
"bytes": 1080419,
|
| 106 |
+
"sha256": "4b10199d6da28e55713e324a4d9ef0264b6c6b131232d684649acf99e0132ee8"
|
| 107 |
+
}
|
| 108 |
+
},
|
| 109 |
+
"split_counts": {
|
| 110 |
+
"calibration": 9366,
|
| 111 |
+
"fit": 28181,
|
| 112 |
+
"validation": 9425
|
| 113 |
+
}
|
| 114 |
+
},
|
| 115 |
+
"wos-5736": {
|
| 116 |
+
"documents": 5735,
|
| 117 |
+
"files": {
|
| 118 |
+
"bow.csv": {
|
| 119 |
+
"bytes": 13177936,
|
| 120 |
+
"sha256": "fb9f0b1d6852c6cb23adf1a591cd836d35d3366765ad93d5dea31571b5d6f040"
|
| 121 |
+
},
|
| 122 |
+
"hierarchy.json": {
|
| 123 |
+
"bytes": 413622,
|
| 124 |
+
"sha256": "7b862eb58b8c3d2f21511cb16f4f380161609cf876bb857c617ff54fdc1352d6"
|
| 125 |
+
},
|
| 126 |
+
"labels.json": {
|
| 127 |
+
"bytes": 201427,
|
| 128 |
+
"sha256": "057ca6c26d7fb1ebaf99fca0a30aa527db494c1314616f13280b5595b7f2328b"
|
| 129 |
+
},
|
| 130 |
+
"noow.csv": {
|
| 131 |
+
"bytes": 13955503,
|
| 132 |
+
"sha256": "850bf83152a928576508396a6c7d3b77a79a271e6a32d6e27784c7a466ff6005"
|
| 133 |
+
},
|
| 134 |
+
"splits.json": {
|
| 135 |
+
"bytes": 126233,
|
| 136 |
+
"sha256": "21980ed4a909dd05e530ae0e55e093974eb321f2801d5e94f5a405a24584fb32"
|
| 137 |
+
}
|
| 138 |
+
},
|
| 139 |
+
"split_counts": {
|
| 140 |
+
"calibration": 1147,
|
| 141 |
+
"fit": 3439,
|
| 142 |
+
"validation": 1149
|
| 143 |
+
}
|
| 144 |
+
}
|
| 145 |
+
},
|
| 146 |
+
"schema_version": 1
|
| 147 |
+
}
|
preprocessing/pip-linux-x86_64.lock.txt
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Minimal runtime dependency closure, selected from the repository's
|
| 2 |
+
# work/wintra/envs/wikigood-ru-pip-linux-x86_64.lock.txt.
|
| 3 |
+
# Python 3.11.15, Linux x86_64. Version pins, not wheel-content hashes.
|
| 4 |
+
click==8.5.0
|
| 5 |
+
iterative-stratification==0.1.9
|
| 6 |
+
joblib==1.5.3
|
| 7 |
+
narwhals==2.25.0
|
| 8 |
+
nltk==3.9.2
|
| 9 |
+
numpy==2.4.6
|
| 10 |
+
regex==2026.7.19
|
| 11 |
+
scikit-learn==1.9.0
|
| 12 |
+
scipy==1.17.1
|
| 13 |
+
threadpoolctl==3.6.0
|
| 14 |
+
tqdm==4.70.0
|
preprocessing/prepare.py
ADDED
|
@@ -0,0 +1,258 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Acquire pinned sources, reproduce the five datasets, or verify a payload offline."""
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import argparse
|
| 7 |
+
import csv
|
| 8 |
+
import hashlib
|
| 9 |
+
import importlib.metadata
|
| 10 |
+
import json
|
| 11 |
+
import os
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
import platform
|
| 14 |
+
import shutil
|
| 15 |
+
import stat
|
| 16 |
+
import sys
|
| 17 |
+
import tempfile
|
| 18 |
+
import urllib.request
|
| 19 |
+
import zipfile
|
| 20 |
+
|
| 21 |
+
HERE = Path(__file__).resolve().parent
|
| 22 |
+
DATASETS = ("bbc-news", "scinews", "wos-5736", "wos-11967", "wos-46985")
|
| 23 |
+
RUNTIME = {
|
| 24 |
+
"nltk": "3.9.2", "numpy": "2.4.6", "scikit-learn": "1.9.0",
|
| 25 |
+
"iterative-stratification": "0.1.9", "scipy": "1.17.1", "joblib": "1.5.3",
|
| 26 |
+
"threadpoolctl": "3.6.0", "regex": "2026.7.19", "click": "8.5.0",
|
| 27 |
+
"tqdm": "4.70.0", "narwhals": "2.25.0",
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def safe_path(value: str | Path) -> Path:
|
| 32 |
+
"""Reject symlinks in both an existing path and its existing ancestors."""
|
| 33 |
+
path = Path(value).absolute()
|
| 34 |
+
for component in (path, *path.parents):
|
| 35 |
+
if component.is_symlink():
|
| 36 |
+
raise ValueError(f"Symlink is not allowed: {component}")
|
| 37 |
+
return Path(os.path.abspath(path))
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def check_file(path: Path, pin: dict | str) -> None:
|
| 41 |
+
path = safe_path(path)
|
| 42 |
+
if not path.is_file():
|
| 43 |
+
raise ValueError(f"Missing regular file: {path}")
|
| 44 |
+
expected = pin if isinstance(pin, str) else pin["sha256"]
|
| 45 |
+
if isinstance(pin, dict) and path.stat().st_size != pin["bytes"]:
|
| 46 |
+
raise ValueError(f"File size differs from pin: {path}")
|
| 47 |
+
with path.open("rb") as stream:
|
| 48 |
+
actual = hashlib.file_digest(stream, "sha256").hexdigest()
|
| 49 |
+
if actual != expected:
|
| 50 |
+
raise ValueError(f"SHA-256 differs from pin: {path}")
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def publish(part: Path, target: Path, pin: dict | str) -> None:
|
| 54 |
+
check_file(part, pin)
|
| 55 |
+
# A hard link publishes atomically and cannot overwrite an existing target.
|
| 56 |
+
os.link(part, target)
|
| 57 |
+
part.unlink()
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def fetch(url: str, target: Path, pin: dict) -> None:
|
| 61 |
+
target = safe_path(target)
|
| 62 |
+
if target.exists():
|
| 63 |
+
check_file(target, pin)
|
| 64 |
+
return
|
| 65 |
+
target.parent.mkdir(parents=True, exist_ok=True)
|
| 66 |
+
part = safe_path(target.with_name(target.name + ".part"))
|
| 67 |
+
# Exclusive creation preserves any interrupted or preexisting partial file.
|
| 68 |
+
with part.open("xb") as output:
|
| 69 |
+
try:
|
| 70 |
+
with urllib.request.urlopen(url, timeout=120) as response:
|
| 71 |
+
shutil.copyfileobj(response, output)
|
| 72 |
+
except Exception:
|
| 73 |
+
raise ValueError(f"Download failed for {target.name}; inspect {part}") from None
|
| 74 |
+
publish(part, target, pin)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def verify(dataset: str, data_dir: Path) -> None:
|
| 78 |
+
data_dir = safe_path(data_dir)
|
| 79 |
+
if not data_dir.is_dir():
|
| 80 |
+
raise ValueError(f"Missing data directory: {data_dir}")
|
| 81 |
+
pins = json.loads((HERE / "payload-pins.json").read_text())["datasets"][dataset]
|
| 82 |
+
if {p.name for p in data_dir.iterdir()} != set(pins["files"]):
|
| 83 |
+
raise ValueError("Payload file inventory differs from pin")
|
| 84 |
+
for name, pin in pins["files"].items():
|
| 85 |
+
check_file(data_dir / name, pin)
|
| 86 |
+
labels = json.loads((data_dir / "labels.json").read_text())
|
| 87 |
+
splits = json.loads((data_dir / "splits.json").read_text())
|
| 88 |
+
if len(labels) != pins["documents"]:
|
| 89 |
+
raise ValueError("Document count differs from pin")
|
| 90 |
+
if {name: len(ids) for name, ids in splits.items()} != pins["split_counts"]:
|
| 91 |
+
raise ValueError("Split counts differ from pin")
|
| 92 |
+
csv.field_size_limit(sys.maxsize)
|
| 93 |
+
for name in ("bow.csv", "noow.csv"):
|
| 94 |
+
with (data_dir / name).open(newline="", encoding="utf-8") as stream:
|
| 95 |
+
rows = csv.reader(stream)
|
| 96 |
+
next(rows)
|
| 97 |
+
if sum(1 for _ in rows) != pins["documents"]:
|
| 98 |
+
raise ValueError(f"CSV row count differs from pin: {name}")
|
| 99 |
+
print(f"Verified {dataset}: {pins['documents']} documents")
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def download(dataset: str, root: Path, pins: dict) -> None:
|
| 103 |
+
root = safe_path(root)
|
| 104 |
+
root.mkdir(parents=True, exist_ok=True)
|
| 105 |
+
family = "wos" if dataset.startswith("wos-") else dataset
|
| 106 |
+
source = pins["sources"][family]
|
| 107 |
+
if family == "scinews":
|
| 108 |
+
missing = []
|
| 109 |
+
for name, pin in source["files"].items():
|
| 110 |
+
target = safe_path(root / family / name)
|
| 111 |
+
if target.exists():
|
| 112 |
+
check_file(target, pin)
|
| 113 |
+
else:
|
| 114 |
+
missing.append(name)
|
| 115 |
+
if missing:
|
| 116 |
+
if importlib.metadata.version("huggingface-hub") != "1.25.1":
|
| 117 |
+
raise ValueError("SciNews download requires huggingface-hub==1.25.1")
|
| 118 |
+
from huggingface_hub import hf_hub_download
|
| 119 |
+
|
| 120 |
+
# SDK handles authentication/redirects using the user's standard HF setup.
|
| 121 |
+
# Its local metadata and temporary files stay inside the acquisition root.
|
| 122 |
+
with tempfile.TemporaryDirectory(prefix=".scinews-download-", dir=root) as staging:
|
| 123 |
+
for name in missing:
|
| 124 |
+
try:
|
| 125 |
+
downloaded = hf_hub_download(
|
| 126 |
+
repo_id=source["repo_id"], repo_type="dataset",
|
| 127 |
+
revision=source["revision"], filename=name, local_dir=staging,
|
| 128 |
+
)
|
| 129 |
+
except Exception:
|
| 130 |
+
raise ValueError(f"SciNews download failed for {name}; check standard HF access") from None
|
| 131 |
+
target = safe_path(root / family / name)
|
| 132 |
+
target.parent.mkdir(parents=True, exist_ok=True)
|
| 133 |
+
part = safe_path(target.with_name(target.name + ".part"))
|
| 134 |
+
with Path(downloaded).open("rb") as incoming, part.open("xb") as outgoing:
|
| 135 |
+
shutil.copyfileobj(incoming, outgoing)
|
| 136 |
+
publish(part, target, source["files"][name])
|
| 137 |
+
else:
|
| 138 |
+
for name, pin in source["files"].items():
|
| 139 |
+
target = safe_path(root / family / name)
|
| 140 |
+
if pin.get("manual"):
|
| 141 |
+
if not target.exists():
|
| 142 |
+
raise ValueError(
|
| 143 |
+
f"Obtain {name} from {source['release_url']} and place its exact bytes at "
|
| 144 |
+
f"{target} ({pin['bytes']} bytes; SHA-256 {pin['sha256']}); "
|
| 145 |
+
"then rerun download. This release notice requires manual acquisition."
|
| 146 |
+
)
|
| 147 |
+
check_file(target, pin)
|
| 148 |
+
else:
|
| 149 |
+
fetch(pin["url"], target, pin)
|
| 150 |
+
|
| 151 |
+
for name, pin in pins["resource_archives"].items():
|
| 152 |
+
targets = pin.get("members", {"": pin.get("target")})
|
| 153 |
+
for relative in targets.values():
|
| 154 |
+
target = safe_path(root / "nltk_data" / relative)
|
| 155 |
+
if target.exists():
|
| 156 |
+
check_file(target, pins["resources"][relative])
|
| 157 |
+
if all((root / "nltk_data" / relative).exists() for relative in targets.values()):
|
| 158 |
+
continue
|
| 159 |
+
archive = root / "nltk_archives" / name
|
| 160 |
+
url = f"https://raw.githubusercontent.com/nltk/nltk_data/{pins['nltk_data_commit']}/packages/{name}"
|
| 161 |
+
fetch(url, archive, pin)
|
| 162 |
+
if "target" in pin:
|
| 163 |
+
target = safe_path(root / "nltk_data" / pin["target"])
|
| 164 |
+
target.parent.mkdir(parents=True, exist_ok=True)
|
| 165 |
+
part = safe_path(target.with_name(target.name + ".part"))
|
| 166 |
+
with archive.open("rb") as incoming, part.open("xb") as outgoing:
|
| 167 |
+
shutil.copyfileobj(incoming, outgoing)
|
| 168 |
+
publish(part, target, pin)
|
| 169 |
+
else:
|
| 170 |
+
with zipfile.ZipFile(archive) as zipped:
|
| 171 |
+
if len(zipped.namelist()) != len(set(zipped.namelist())):
|
| 172 |
+
raise ValueError(f"Duplicate resource ZIP members: {name}")
|
| 173 |
+
for member, relative in pin["members"].items():
|
| 174 |
+
target = safe_path(root / "nltk_data" / relative)
|
| 175 |
+
if target.exists():
|
| 176 |
+
continue
|
| 177 |
+
info = zipped.getinfo(member)
|
| 178 |
+
mode = info.external_attr >> 16
|
| 179 |
+
if info.is_dir() or stat.S_ISLNK(mode):
|
| 180 |
+
raise ValueError(f"Nonregular resource member: {member}")
|
| 181 |
+
target.parent.mkdir(parents=True, exist_ok=True)
|
| 182 |
+
part = safe_path(target.with_name(target.name + ".part"))
|
| 183 |
+
with zipped.open(info) as incoming, part.open("xb") as outgoing:
|
| 184 |
+
shutil.copyfileobj(incoming, outgoing)
|
| 185 |
+
publish(part, target, pins["resources"][relative])
|
| 186 |
+
print(f"Downloaded and verified sources/resources for {dataset}")
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def main(argv: list[str] | None = None) -> None:
|
| 190 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 191 |
+
subparsers = parser.add_subparsers(dest="command", required=True)
|
| 192 |
+
for command in ("download", "build", "verify"):
|
| 193 |
+
sub = subparsers.add_parser(command)
|
| 194 |
+
sub.add_argument("--dataset", choices=DATASETS, required=True)
|
| 195 |
+
if command == "verify":
|
| 196 |
+
sub.add_argument("--data-dir", type=Path, required=True)
|
| 197 |
+
else:
|
| 198 |
+
sub.add_argument("--sources-dir", type=Path, required=True)
|
| 199 |
+
if command == "build":
|
| 200 |
+
sub.add_argument("--output-dir", type=Path, required=True)
|
| 201 |
+
sub.add_argument("--scratch-dir", type=Path, required=True)
|
| 202 |
+
args = parser.parse_args(argv)
|
| 203 |
+
try:
|
| 204 |
+
if args.command == "verify":
|
| 205 |
+
verify(args.dataset, args.data_dir)
|
| 206 |
+
return
|
| 207 |
+
pins = json.loads((HERE / "source-pins.json").read_text())
|
| 208 |
+
root = safe_path(args.sources_dir)
|
| 209 |
+
if args.command == "download":
|
| 210 |
+
download(args.dataset, root, pins)
|
| 211 |
+
return
|
| 212 |
+
output = safe_path(args.output_dir)
|
| 213 |
+
scratch = safe_path(args.scratch_dir)
|
| 214 |
+
for left, right in ((root, output), (root, scratch), (output, scratch)):
|
| 215 |
+
if left == right or left in right.parents or right in left.parents:
|
| 216 |
+
raise ValueError("Sources, output and scratch paths must not overlap")
|
| 217 |
+
# Protect the package/code and pins, including output ancestors of HERE.
|
| 218 |
+
for path in (output, scratch):
|
| 219 |
+
if path == HERE or path in HERE.parents or HERE in path.parents:
|
| 220 |
+
raise ValueError("Output/scratch must be outside the preprocessing package")
|
| 221 |
+
if path.exists():
|
| 222 |
+
raise ValueError(f"Output/scratch must be new: {path}")
|
| 223 |
+
family = "wos" if args.dataset.startswith("wos-") else args.dataset
|
| 224 |
+
for name, pin in pins["sources"][family]["files"].items():
|
| 225 |
+
check_file(root / family / name, pin)
|
| 226 |
+
nltk_data = safe_path(root / "nltk_data")
|
| 227 |
+
for name, pin in pins["resources"].items():
|
| 228 |
+
check_file(nltk_data / name, pin)
|
| 229 |
+
source_path = root / family
|
| 230 |
+
if family == "bbc-news":
|
| 231 |
+
source_path /= "bbc-fulltext.zip"
|
| 232 |
+
if family == "wos":
|
| 233 |
+
source_path /= "WebOfScience.zip"
|
| 234 |
+
with zipfile.ZipFile(source_path) as archive:
|
| 235 |
+
if len(archive.namelist()) != len(set(archive.namelist())):
|
| 236 |
+
raise ValueError("Duplicate WOS ZIP members")
|
| 237 |
+
for name, expected in pins["sources"][family]["member_sha256"].items():
|
| 238 |
+
info = archive.getinfo(name)
|
| 239 |
+
if info.is_dir() or stat.S_ISLNK(info.external_attr >> 16):
|
| 240 |
+
raise ValueError(f"Nonregular WOS member: {name}")
|
| 241 |
+
with archive.open(info) as stream:
|
| 242 |
+
if hashlib.file_digest(stream, "sha256").hexdigest() != expected:
|
| 243 |
+
raise ValueError(f"WOS member hash differs: {name}")
|
| 244 |
+
if platform.python_version() != "3.11.15":
|
| 245 |
+
raise ValueError("Build requires Python 3.11.15")
|
| 246 |
+
for name, expected in RUNTIME.items():
|
| 247 |
+
if importlib.metadata.version(name) != expected:
|
| 248 |
+
raise ValueError(f"Build requires {name}=={expected}")
|
| 249 |
+
from _pipeline import build
|
| 250 |
+
|
| 251 |
+
build(args.dataset, source_path, nltk_data, output, scratch)
|
| 252 |
+
verify(args.dataset, output)
|
| 253 |
+
except (OSError, ValueError, KeyError, ImportError, zipfile.BadZipFile, importlib.metadata.PackageNotFoundError) as error:
|
| 254 |
+
parser.exit(1, f"Error: {error}\n")
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
if __name__ == "__main__":
|
| 258 |
+
main()
|
preprocessing/requirements-download.txt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Optional: only the SciNews acquisition command imports the Hugging Face SDK.
|
| 2 |
+
# Its installed metadata requires Python >=3.10.0, compatible with Python 3.11.15.
|
| 3 |
+
huggingface_hub==1.25.1
|
preprocessing/requirements.txt
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Python 3.11.15; runtime dependencies only. See pip-linux-x86_64.lock.txt.
|
| 2 |
+
iterative-stratification==0.1.9
|
| 3 |
+
nltk==3.9.2
|
| 4 |
+
numpy==2.4.6
|
| 5 |
+
scikit-learn==1.9.0
|
preprocessing/source-pins.json
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"nltk_data_commit": "550b6625bcef1f2abff2ff770a5a0d272c9c6b2a",
|
| 3 |
+
"resource_archives": {
|
| 4 |
+
"corpora/stopwords.zip": {
|
| 5 |
+
"bytes": 37733,
|
| 6 |
+
"members": {
|
| 7 |
+
"stopwords/english": "corpora/stopwords/english"
|
| 8 |
+
},
|
| 9 |
+
"sha256": "48c0e52d8b52546e827f53761fb30300c0ab94f70660d28bd65ba0a86270946b"
|
| 10 |
+
},
|
| 11 |
+
"corpora/wordnet.zip": {
|
| 12 |
+
"bytes": 10775600,
|
| 13 |
+
"sha256": "cbda5ea6eef7f36a97a43d4a75f85e07fccbb4f23657d27b4ccbc93e2646ab59",
|
| 14 |
+
"target": "corpora/wordnet.zip"
|
| 15 |
+
},
|
| 16 |
+
"taggers/averaged_perceptron_tagger_eng.zip": {
|
| 17 |
+
"bytes": 1539115,
|
| 18 |
+
"members": {
|
| 19 |
+
"averaged_perceptron_tagger_eng/averaged_perceptron_tagger_eng.classes.json": "taggers/averaged_perceptron_tagger_eng/averaged_perceptron_tagger_eng.classes.json",
|
| 20 |
+
"averaged_perceptron_tagger_eng/averaged_perceptron_tagger_eng.tagdict.json": "taggers/averaged_perceptron_tagger_eng/averaged_perceptron_tagger_eng.tagdict.json",
|
| 21 |
+
"averaged_perceptron_tagger_eng/averaged_perceptron_tagger_eng.weights.json": "taggers/averaged_perceptron_tagger_eng/averaged_perceptron_tagger_eng.weights.json"
|
| 22 |
+
},
|
| 23 |
+
"sha256": "6025f530624335c67d6547d44757b357b4e79bae030a0383e9887a92c1718f0b"
|
| 24 |
+
}
|
| 25 |
+
},
|
| 26 |
+
"resources": {
|
| 27 |
+
"corpora/stopwords/english": "f6d005956f407dbc6ea32e5ff0c7e8e6f71488d3239b9023efdc7fc139d6375b",
|
| 28 |
+
"corpora/wordnet.zip": "cbda5ea6eef7f36a97a43d4a75f85e07fccbb4f23657d27b4ccbc93e2646ab59",
|
| 29 |
+
"taggers/averaged_perceptron_tagger_eng/averaged_perceptron_tagger_eng.classes.json": "d152ffa69d45b8357276341a3d592c6c025911d52ec0d9068d4f382560dd48b6",
|
| 30 |
+
"taggers/averaged_perceptron_tagger_eng/averaged_perceptron_tagger_eng.tagdict.json": "4c713731cb06727736962bc8cd94ad919217a040e76691059af99bc0c2c9c246",
|
| 31 |
+
"taggers/averaged_perceptron_tagger_eng/averaged_perceptron_tagger_eng.weights.json": "789e8e35f6fac656d9b7eccea29ba4e8a137cbb5b525dd31f39e4291a9e80832"
|
| 32 |
+
},
|
| 33 |
+
"schema_version": 1,
|
| 34 |
+
"sources": {
|
| 35 |
+
"bbc-news": {
|
| 36 |
+
"files": {
|
| 37 |
+
"bbc-fulltext.zip": {
|
| 38 |
+
"bytes": 2874079,
|
| 39 |
+
"sha256": "a351031a62325b3d7ff13146eeb035c22feca8290913b5183d1ff3be35109495",
|
| 40 |
+
"url": "https://derekgreene.com/datasets/bbc-fulltext.zip"
|
| 41 |
+
}
|
| 42 |
+
}
|
| 43 |
+
},
|
| 44 |
+
"scinews": {
|
| 45 |
+
"files": {
|
| 46 |
+
"README.md": {
|
| 47 |
+
"bytes": 4933,
|
| 48 |
+
"sha256": "dffd02d522c1cb894d4fd1eebe0e4b6098d045fac77755fc8f49341388b32750"
|
| 49 |
+
},
|
| 50 |
+
"test.json": {
|
| 51 |
+
"bytes": 205514917,
|
| 52 |
+
"sha256": "5fe7904c0495b85862d24637ad148773a13c4d05a90a48d9b737b0c7d80cca86"
|
| 53 |
+
},
|
| 54 |
+
"train.json": {
|
| 55 |
+
"bytes": 1655263757,
|
| 56 |
+
"sha256": "5fcd9dcddeb7bebb4c42207f228d59f5c04a189886de93110e5484d2e8f6ada7"
|
| 57 |
+
},
|
| 58 |
+
"val.json": {
|
| 59 |
+
"bytes": 210282099,
|
| 60 |
+
"sha256": "13ea59e6103258d890d88dd5231462594ce18aec2a98ae39e241af388a4886d6"
|
| 61 |
+
}
|
| 62 |
+
},
|
| 63 |
+
"repo_id": "dongqi-me/SciNews",
|
| 64 |
+
"revision": "160772e163f6f60edade970ca98c56d3f7b59e69"
|
| 65 |
+
},
|
| 66 |
+
"wos": {
|
| 67 |
+
"files": {
|
| 68 |
+
"ReadMe.txt": {
|
| 69 |
+
"bytes": 2587,
|
| 70 |
+
"manual": true,
|
| 71 |
+
"sha256": "6da4ab1e624c4ef61c46600d727770f873ff4db3c15541fb481e7af8a715c0ec"
|
| 72 |
+
},
|
| 73 |
+
"WebOfScience.zip": {
|
| 74 |
+
"bytes": 60222421,
|
| 75 |
+
"sha256": "b787d484bff88b0dcdb3fa291d06ec9d2f025dc2a67ce1045d0c688cd96ccf8a",
|
| 76 |
+
"url": "https://data.mendeley.com/public-files/datasets/9rw3vkcfy4/files/c9ea673d-5542-44c0-ab7b-f1311f7d61df/file_downloaded"
|
| 77 |
+
}
|
| 78 |
+
},
|
| 79 |
+
"member_sha256": {
|
| 80 |
+
"WOS11967/X.txt": "833085410372994270db7c89a2db68052f52881c61ec5be0b349073365da832b",
|
| 81 |
+
"WOS11967/Y.txt": "291143bab8b07b412a3f61d1c0eadda9ff9b0ca2945e8fa19869e0fb2a00fad7",
|
| 82 |
+
"WOS11967/YL1.txt": "8360c1650fa3de9d8b363b9dd3d6d445a359c1bb26ae54986750298b7d961392",
|
| 83 |
+
"WOS11967/YL2.txt": "4524586479bfb3cdf96c0e1cc517537278bddb56f15d3f6331fb5e3a52c298ee",
|
| 84 |
+
"WOS46985/X.txt": "82cc4794b57795cb548f751aeb2efb500e77b9440be705c410e7a59b42e02ce2",
|
| 85 |
+
"WOS46985/Y.txt": "627d5f638ed48707a914c7cbba9e9cc833e747b76117a559c0bbb759b7b95096",
|
| 86 |
+
"WOS46985/YL1.txt": "691872ed9eb092024956ad719b49408e095f7752cecb1d7dcd0641af61c18e6a",
|
| 87 |
+
"WOS46985/YL2.txt": "0d1e3bf61822a16d75c6caefaea4a65874a32f9791f9b0d53f488ffe5d3af152",
|
| 88 |
+
"WOS5736/X.txt": "4e5c1bcc8a7684c7f59976dae225afda5bc1c6f656f49cbef27ccb6befcced89",
|
| 89 |
+
"WOS5736/Y.txt": "99a1ff099023572d04d43f19c705e3f239b2fbe414b2292d2bc650e20b856c8f",
|
| 90 |
+
"WOS5736/YL1.txt": "fd2e1ed1bcff7918174f432a28c3db630a66bd254f2b5a0bc86dfc36c0fed21a",
|
| 91 |
+
"WOS5736/YL2.txt": "20af3bbf37b2bba329b5c43733cc68b02dd0c74f3c86635992dcb296a5f13916"
|
| 92 |
+
},
|
| 93 |
+
"release_url": "https://data.mendeley.com/datasets/9rw3vkcfy4/6"
|
| 94 |
+
}
|
| 95 |
+
}
|
| 96 |
+
}
|
preprocessing/test_prepare.py
ADDED
|
@@ -0,0 +1,216 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Portable checks: python -m unittest -v test_prepare.
|
| 2 |
+
|
| 3 |
+
Set PORTABLE_NLTK_DATA to the acquired nltk_data directory to include real NLP
|
| 4 |
+
and fixture builds. No checkout-relative resources or downloads are assumed.
|
| 5 |
+
"""
|
| 6 |
+
import csv
|
| 7 |
+
import hashlib
|
| 8 |
+
import json
|
| 9 |
+
import os
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
import shutil
|
| 12 |
+
import subprocess
|
| 13 |
+
import sys
|
| 14 |
+
import tempfile
|
| 15 |
+
import unittest
|
| 16 |
+
import zipfile
|
| 17 |
+
|
| 18 |
+
import _pipeline
|
| 19 |
+
|
| 20 |
+
HERE = Path(__file__).resolve().parent
|
| 21 |
+
RESOURCES = os.environ.get("PORTABLE_NLTK_DATA")
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def record(body, topic="Physics", title="", url="", doi=""):
|
| 25 |
+
return dict(News_Title=title, News_Body=body, News_URL=url, Citation="",
|
| 26 |
+
DOI=doi, Paper_URL="", Paper_Body="", Topic=topic)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def write_scinews(directory, rows):
|
| 30 |
+
directory.mkdir()
|
| 31 |
+
for split in ("train", "val", "test"):
|
| 32 |
+
(directory / (split + ".json")).write_text(
|
| 33 |
+
json.dumps(rows if split == "train" else []), encoding="utf-8")
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class SourceChecks(unittest.TestCase):
|
| 37 |
+
def test_source_framing_and_external_labels(self):
|
| 38 |
+
"""Source readers preserve body/title, canonical IDs and WOS local labels."""
|
| 39 |
+
with tempfile.TemporaryDirectory() as temporary:
|
| 40 |
+
root = Path(temporary)
|
| 41 |
+
archive = root / "bbc.zip"
|
| 42 |
+
with zipfile.ZipFile(archive, "w") as zipped:
|
| 43 |
+
zipped.writestr("bbc/tech/001.txt", "Title\r\n\r\nBody\r\n")
|
| 44 |
+
zipped.writestr("bbc/README.txt", "ignored")
|
| 45 |
+
self.assertEqual(list(_pipeline._source_rows("bbc-news", archive)),
|
| 46 |
+
[("bbc_tech_001", "Body\r\n", "Title", "tech", "", "", "", "")])
|
| 47 |
+
archive = root / "wos.zip"
|
| 48 |
+
with zipfile.ZipFile(archive, "w") as zipped:
|
| 49 |
+
for subset in ("5736", "11967", "46985"):
|
| 50 |
+
for field, value in (("X", "Body"), ("Y", "2"), ("YL1", "1"), ("YL2", "0")):
|
| 51 |
+
zipped.writestr("WOS" + subset + "/" + field + ".txt", value + "\r\n")
|
| 52 |
+
for subset in ("5736", "11967", "46985"):
|
| 53 |
+
self.assertEqual(list(_pipeline._source_rows("wos-" + subset, archive)),
|
| 54 |
+
[("wos" + subset + "_000000", "Body", "", "2", "1", "0", "", "")])
|
| 55 |
+
source = root / "scinews"
|
| 56 |
+
write_scinews(source, [record("body", url="https://news", doi="https://doi.org/AbC")])
|
| 57 |
+
row = next(_pipeline._source_rows("scinews", source))
|
| 58 |
+
self.assertEqual((row[0], row[-2:]), ("scinews_train_000000", ("https://news", "abc")))
|
| 59 |
+
duplicate_key = '[' + json.dumps(record("body"))[:-1] + ',"News_Title":"duplicate"}]'
|
| 60 |
+
for invalid in (duplicate_key, '[{},]', '[NaN]', '[] trailing'):
|
| 61 |
+
(source / "train.json").write_text(invalid)
|
| 62 |
+
with self.subTest(invalid=invalid), self.assertRaises(ValueError):
|
| 63 |
+
list(_pipeline._source_rows("scinews", source))
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
@unittest.skipUnless(RESOURCES, "set PORTABLE_NLTK_DATA for real NLTK fixture checks")
|
| 67 |
+
class RealPipelineChecks(unittest.TestCase):
|
| 68 |
+
def test_occurrences_keep_original_offsets_and_order(self):
|
| 69 |
+
text = "The CATS, cats were running! A 12."
|
| 70 |
+
actual = _pipeline.EnglishPreprocessor(Path(RESOURCES)).occurrences(text)
|
| 71 |
+
self.assertEqual([item["lemma"] for item in actual], ["cat", "cat", "run"])
|
| 72 |
+
self.assertEqual([text[item["start"]:item["end"]] for item in actual],
|
| 73 |
+
["CATS", "cats", "running"])
|
| 74 |
+
self.assertEqual([item["occurrence_index"] for item in actual], [0, 1, 2])
|
| 75 |
+
|
| 76 |
+
def test_cleaning_family_splits_and_serialization(self):
|
| 77 |
+
"""Duplicates/conflicts disappear; removed bridges and exact .9 pairs stay together."""
|
| 78 |
+
rows = [record("unique" + chr(97 + i // 26) + chr(97 + i % 26) + " astronomy observation")
|
| 79 |
+
for i in range(40)]
|
| 80 |
+
rows.extend([
|
| 81 |
+
record("cats"), record("cat"),
|
| 82 |
+
record("dogs", "Physics"), record("dog", "Chemistry"),
|
| 83 |
+
record("raw conflict", "Physics"), record(" RAW CONFLICT ", "Chemistry"),
|
| 84 |
+
record("bridge original stellar light", title="Cats cats", url="https://a"),
|
| 85 |
+
record("bridge original stellar light", url="https://b", doi="doi:ABC"),
|
| 86 |
+
record("distinct bridge body particles", doi="https://doi.org/abc"),
|
| 87 |
+
record("alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu nu"),
|
| 88 |
+
record("alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu nu xi"),
|
| 89 |
+
record("the and or"),
|
| 90 |
+
])
|
| 91 |
+
with tempfile.TemporaryDirectory() as temporary:
|
| 92 |
+
root = Path(temporary)
|
| 93 |
+
write_scinews(root / "source", rows)
|
| 94 |
+
output = root / "data"
|
| 95 |
+
_pipeline.build("scinews", root / "source", Path(RESOURCES), output, root / "scratch")
|
| 96 |
+
labels = json.loads((output / "labels.json").read_text())
|
| 97 |
+
removed = {41, 42, 43, 44, 45, 47, 51}
|
| 98 |
+
expected_ids = {f"scinews_train_{i:06d}" for i in range(len(rows)) if i not in removed}
|
| 99 |
+
self.assertEqual(set(labels), expected_ids)
|
| 100 |
+
splits = json.loads((output / "splits.json").read_text())
|
| 101 |
+
membership = {identifier: name for name, ids in splits.items() for identifier in ids}
|
| 102 |
+
self.assertEqual(len(membership), sum(map(len, splits.values())))
|
| 103 |
+
self.assertEqual(set(membership), expected_ids)
|
| 104 |
+
# Fixed protocol seeds split 43 families, expanding both linked pairs.
|
| 105 |
+
# Exact membership catches a missing .9 edge even if its two rows
|
| 106 |
+
# happen to land in the same split without that edge.
|
| 107 |
+
expected_splits = {
|
| 108 |
+
"fit": [0, 2, 4, 7, 8, 9, 10, 11, 12, 15, 17, 19, 20, 21,
|
| 109 |
+
24, 26, 27, 30, 33, 36, 37, 38, 40, 46, 48, 49, 50],
|
| 110 |
+
"calibration": [3, 13, 14, 18, 22, 23, 31, 34, 39],
|
| 111 |
+
"validation": [1, 5, 6, 16, 25, 28, 29, 32, 35],
|
| 112 |
+
}
|
| 113 |
+
self.assertEqual(splits, {name: [f"scinews_train_{i:06d}" for i in ids]
|
| 114 |
+
for name, ids in expected_splits.items()})
|
| 115 |
+
for first, second in ((46, 48), (49, 50)):
|
| 116 |
+
self.assertEqual(membership[f"scinews_train_{first:06d}"],
|
| 117 |
+
membership[f"scinews_train_{second:06d}"])
|
| 118 |
+
with (output / "noow.csv").open(newline="") as stream:
|
| 119 |
+
noow = {row["id"]: row for row in csv.DictReader(stream)}
|
| 120 |
+
with (output / "bow.csv").open(newline="") as stream:
|
| 121 |
+
bow = {row["id"]: row for row in csv.DictReader(stream)}
|
| 122 |
+
identifier = "scinews_train_000046"
|
| 123 |
+
self.assertEqual(noow[identifier]["raw_text"], "Cats cats\n\nbridge original stellar light")
|
| 124 |
+
self.assertEqual(noow[identifier]["vw_text"], identifier + " |@title cat cat |@word bridge original stellar light")
|
| 125 |
+
self.assertEqual(bow[identifier]["vw_text"], identifier + " |@title cat:2 |@word bridge:1 light:1 original:1 stellar:1")
|
| 126 |
+
for path in output.iterdir():
|
| 127 |
+
self.assertTrue(path.read_bytes().endswith(b"\n"))
|
| 128 |
+
|
| 129 |
+
def test_wos_hierarchy_preserves_multiple_parents(self):
|
| 130 |
+
with tempfile.TemporaryDirectory() as temporary:
|
| 131 |
+
root = Path(temporary)
|
| 132 |
+
archive = root / "wos.zip"
|
| 133 |
+
with zipfile.ZipFile(archive, "w") as zipped:
|
| 134 |
+
fields = {"X": ["unique" + chr(97 + i // 26) + chr(97 + i % 26) + " research" for i in range(40)],
|
| 135 |
+
"Y": [str(i % 2) for i in range(40)],
|
| 136 |
+
"YL1": [str(i % 3) for i in range(40)],
|
| 137 |
+
"YL2": [str(i % 2) for i in range(40)]}
|
| 138 |
+
for name, values in fields.items():
|
| 139 |
+
zipped.writestr("WOS5736/" + name + ".txt", "\r\n".join(values) + "\r\n")
|
| 140 |
+
_pipeline.build("wos-5736", archive, Path(RESOURCES), root / "data", root / "scratch")
|
| 141 |
+
hierarchy = json.loads((root / "data/hierarchy.json").read_text())
|
| 142 |
+
self.assertEqual({row["YL1"] for row in hierarchy.values() if row["Y"] == "0"}, {"0", "1", "2"})
|
| 143 |
+
self.assertEqual(hierarchy["wos5736_000001"], {"Y": "1", "YL1": "1", "YL2": "1"})
|
| 144 |
+
with (root / "data/noow.csv").open(newline="") as stream:
|
| 145 |
+
row = next(csv.DictReader(stream))
|
| 146 |
+
self.assertEqual(row["raw_text"], fields["X"][0])
|
| 147 |
+
self.assertEqual(row["vw_text"], "wos5736_000000 |@word uniqueaa research")
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
class CliChecks(unittest.TestCase):
|
| 151 |
+
def test_source_and_resource_hashes_fail_before_destinations_exist(self):
|
| 152 |
+
with tempfile.TemporaryDirectory() as temporary:
|
| 153 |
+
root = Path(temporary)
|
| 154 |
+
package = root / "package"
|
| 155 |
+
package.mkdir()
|
| 156 |
+
shutil.copyfile(HERE / "prepare.py", package / "prepare.py")
|
| 157 |
+
sources = root / "sources"
|
| 158 |
+
(sources / "bbc-news").mkdir(parents=True)
|
| 159 |
+
source = sources / "bbc-news/bbc-fulltext.zip"
|
| 160 |
+
source.write_bytes(b"fixture")
|
| 161 |
+
digest = hashlib.sha256(b"fixture").hexdigest()
|
| 162 |
+
pins = {"sources": {"bbc-news": {"files": {"bbc-fulltext.zip": {"bytes": 7, "sha256": digest}}}},
|
| 163 |
+
"resources": {"resource": {"bytes": 7, "sha256": digest}}}
|
| 164 |
+
(package / "source-pins.json").write_text(json.dumps(pins))
|
| 165 |
+
resource = sources / "nltk_data/resource"
|
| 166 |
+
resource.parent.mkdir()
|
| 167 |
+
resource.write_bytes(b"altered")
|
| 168 |
+
for boundary in ("resource", "source"):
|
| 169 |
+
if boundary == "source":
|
| 170 |
+
source.write_bytes(b"altered")
|
| 171 |
+
result = subprocess.run([sys.executable, "-O", str(package / "prepare.py"), "build",
|
| 172 |
+
"--dataset", "bbc-news", "--sources-dir", str(sources),
|
| 173 |
+
"--output-dir", str(root / "output"), "--scratch-dir", str(root / "scratch")],
|
| 174 |
+
cwd=root, capture_output=True, text=True)
|
| 175 |
+
self.assertNotEqual(result.returncode, 0, result.stdout)
|
| 176 |
+
self.assertIn("SHA-256 differs from pin", result.stderr)
|
| 177 |
+
self.assertIn(str(resource if boundary == "resource" else source), result.stderr)
|
| 178 |
+
self.assertFalse((root / "output").exists())
|
| 179 |
+
self.assertFalse((root / "scratch").exists())
|
| 180 |
+
|
| 181 |
+
def test_verify_rejects_hash_and_inventory_drift_under_optimization(self):
|
| 182 |
+
with tempfile.TemporaryDirectory() as temporary:
|
| 183 |
+
root = Path(temporary)
|
| 184 |
+
package = root / "package"
|
| 185 |
+
package.mkdir()
|
| 186 |
+
shutil.copyfile(HERE / "prepare.py", package / "prepare.py")
|
| 187 |
+
data = root / "data"
|
| 188 |
+
data.mkdir()
|
| 189 |
+
files = {"labels.json": b'{"one":["topic"]}\n',
|
| 190 |
+
"splits.json": b'{"fit":["one"],"calibration":[],"validation":[]}\n',
|
| 191 |
+
"bow.csv": b'id,raw_text,vw_text\none,body,one |@word body:1\n',
|
| 192 |
+
"noow.csv": b'id,raw_text,vw_text\none,body,one |@word body\n'}
|
| 193 |
+
for name, content in files.items():
|
| 194 |
+
(data / name).write_bytes(content)
|
| 195 |
+
pins = {"datasets": {"bbc-news": {"documents": 1,
|
| 196 |
+
"split_counts": {"fit": 1, "calibration": 0, "validation": 0},
|
| 197 |
+
"files": {name: {"bytes": len(content), "sha256": hashlib.sha256(content).hexdigest()}
|
| 198 |
+
for name, content in files.items()}}}}
|
| 199 |
+
(package / "payload-pins.json").write_text(json.dumps(pins))
|
| 200 |
+
command = [sys.executable, "-O", str(package / "prepare.py"), "verify",
|
| 201 |
+
"--dataset", "bbc-news", "--data-dir", str(data)]
|
| 202 |
+
result = subprocess.run(command, cwd=root, capture_output=True, text=True)
|
| 203 |
+
self.assertEqual(result.returncode, 0, result.stderr)
|
| 204 |
+
(data / "extra").write_text("unexpected")
|
| 205 |
+
result = subprocess.run(command, cwd=root, capture_output=True, text=True)
|
| 206 |
+
self.assertNotEqual(result.returncode, 0)
|
| 207 |
+
self.assertIn("inventory differs", result.stderr)
|
| 208 |
+
(data / "extra").unlink()
|
| 209 |
+
(data / "bow.csv").write_bytes(files["bow.csv"].replace(b"body", b"BODY"))
|
| 210 |
+
result = subprocess.run(command, cwd=root, capture_output=True, text=True)
|
| 211 |
+
self.assertNotEqual(result.returncode, 0)
|
| 212 |
+
self.assertIn("SHA-256 differs", result.stderr)
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
if __name__ == "__main__":
|
| 216 |
+
unittest.main()
|