Datasets:
Expand UDD-1 to 40K sentences across 5 domains
Browse filesAdd fetch scripts for news (UVN-1) and Wikipedia (UVW-2026) domains.
Increase sentence targets to 8K per domain for legal and books.
Add build_dataset.py to combine all domains with sent_id prefixes
and create stratified train/dev/test splits. Update convert_to_ud.py
to support domain-specific sent_ids and upload_to_hf.py for multi-split
upload with domain field.
- CLAUDE.md +117 -0
- src/build_dataset.py +209 -0
- src/convert_to_ud.py +692 -0
- src/fetch_data.py +115 -0
- src/fetch_uvb_data.py +250 -0
- src/fetch_uvn_data.py +127 -0
- src/fetch_uvw_data.py +135 -0
- src/upload_to_hf.py +119 -0
CLAUDE.md
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# CLAUDE.md
|
| 2 |
+
|
| 3 |
+
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
|
| 4 |
+
|
| 5 |
+
## Project Overview
|
| 6 |
+
|
| 7 |
+
UDD-1 (Universal Dependency Dataset for Vietnamese) is a Vietnamese Universal Dependencies treebank with 40,000 sentences from 5 domains. The repo contains both the dataset files (CoNLL-U format) and the tooling pipeline for creating/validating them.
|
| 8 |
+
|
| 9 |
+
### Domain Breakdown
|
| 10 |
+
|
| 11 |
+
| Category | Source Dataset | Sentences | Sent ID Prefix |
|
| 12 |
+
|----------|---------------|-----------|----------------|
|
| 13 |
+
| Wikipedia | `undertheseanlp/UVW-2026` | 8,000 | `uvw-` |
|
| 14 |
+
| News | `undertheseanlp/UVN-1` | 8,000 | `uvn-` |
|
| 15 |
+
| Legal | `undertheseanlp/UTS_VLC` | 8,000 | `vlc-` |
|
| 16 |
+
| Fiction | `undertheseanlp/UVB-v0.1` | 8,000 | `uvb-f-` |
|
| 17 |
+
| Non-fiction | `undertheseanlp/UVB-v0.1` | 8,000 | `uvb-n-` |
|
| 18 |
+
|
| 19 |
+
## Repository Structure
|
| 20 |
+
|
| 21 |
+
- Root `.conllu` files: The published dataset splits (`vi_udd-ud-{train,dev,test}.conllu`)
|
| 22 |
+
- `data/`: Parquet files for HuggingFace dataset hosting
|
| 23 |
+
- `src/`: Pipeline scripts for data fetching, conversion, validation, and upload
|
| 24 |
+
- `src/udtools/`: Vendored copy of the [Universal Dependencies tools](https://github.com/UniversalDependencies/tools) package (validator + scorer)
|
| 25 |
+
|
| 26 |
+
## Key Pipeline Scripts
|
| 27 |
+
|
| 28 |
+
| Script | Purpose |
|
| 29 |
+
|--------|---------|
|
| 30 |
+
| `src/fetch_data.py` | Fetch 8,000 sentences from `undertheseanlp/UTS_VLC` (legal domain) → `sentences_vlc.txt` |
|
| 31 |
+
| `src/fetch_uvn_data.py` | Fetch 8,000 sentences from `undertheseanlp/UVN-1` (news domain) → `sentences_uvn.txt` |
|
| 32 |
+
| `src/fetch_uvw_data.py` | Fetch 8,000 sentences from `undertheseanlp/UVW-2026` (Wikipedia, quality_score >= 5) → `sentences_uvw.txt` |
|
| 33 |
+
| `src/fetch_uvb_data.py` | Fetch 8,000 fiction + 8,000 non-fiction from `undertheseanlp/UVB-v0.1` → `sentences_uvb.txt` |
|
| 34 |
+
| `src/build_dataset.py` | Combine all sentence files, assign sent_id prefixes, create stratified train/dev/test splits → `sentences_{train,dev,test}.txt` |
|
| 35 |
+
| `src/convert_to_ud.py` | Convert raw sentences to UD format using `underthesea` NLP toolkit (dependency parsing + POS tagging). Outputs JSONL and CoNLL-U |
|
| 36 |
+
| `src/statistics.py` | Compute dataset statistics from CoNLL-U files |
|
| 37 |
+
| `src/upload_to_hf.py` | Upload dataset splits to HuggingFace Hub with domain field (requires `HF_TOKEN` env var) |
|
| 38 |
+
| `src/run_conversion.sh` | Wrapper that runs conversion with GPU monitoring and timestamped results |
|
| 39 |
+
| `src/run_on_runpod.py` | Manage RunPod GPU instances for conversion (requires `RUNPOD_API_KEY`) |
|
| 40 |
+
|
| 41 |
+
## Pipeline Commands
|
| 42 |
+
|
| 43 |
+
### 1. Fetch sentences from all sources
|
| 44 |
+
```bash
|
| 45 |
+
python src/fetch_data.py # Legal → sentences_vlc.txt
|
| 46 |
+
python src/fetch_uvn_data.py # News → sentences_uvn.txt
|
| 47 |
+
python src/fetch_uvw_data.py # Wikipedia → sentences_uvw.txt
|
| 48 |
+
python src/fetch_uvb_data.py # Books → sentences_uvb.txt
|
| 49 |
+
```
|
| 50 |
+
|
| 51 |
+
### 2. Build combined dataset with splits
|
| 52 |
+
```bash
|
| 53 |
+
python src/build_dataset.py # → sentences_{train,dev,test}.txt
|
| 54 |
+
```
|
| 55 |
+
|
| 56 |
+
### 3. Run UD conversion (GPU-optimized)
|
| 57 |
+
```bash
|
| 58 |
+
python src/convert_to_ud.py -i sentences_train.txt -o output/ -p train -b 64
|
| 59 |
+
python src/convert_to_ud.py -i sentences_dev.txt -o output/ -p dev -b 64
|
| 60 |
+
python src/convert_to_ud.py -i sentences_test.txt -o output/ -p test -b 64
|
| 61 |
+
# Or use the shell wrapper:
|
| 62 |
+
./src/run_conversion.sh <input_file> [batch_size]
|
| 63 |
+
```
|
| 64 |
+
|
| 65 |
+
### 4. Validate CoNLL-U files
|
| 66 |
+
```bash
|
| 67 |
+
cd src/udtools
|
| 68 |
+
pip install -e .
|
| 69 |
+
python validate.py --lang vi vi_udd-ud-train.conllu
|
| 70 |
+
```
|
| 71 |
+
|
| 72 |
+
### 5. Run udtools tests
|
| 73 |
+
```bash
|
| 74 |
+
cd src/udtools
|
| 75 |
+
python -m pytest tests/
|
| 76 |
+
```
|
| 77 |
+
|
| 78 |
+
### 6. Compute dataset statistics
|
| 79 |
+
```bash
|
| 80 |
+
python src/statistics.py
|
| 81 |
+
```
|
| 82 |
+
|
| 83 |
+
### 7. Upload to HuggingFace
|
| 84 |
+
```bash
|
| 85 |
+
export HF_TOKEN=<token>
|
| 86 |
+
python src/upload_to_hf.py
|
| 87 |
+
```
|
| 88 |
+
|
| 89 |
+
## Architecture Notes
|
| 90 |
+
|
| 91 |
+
### Conversion Pipeline (`convert_to_ud.py`)
|
| 92 |
+
The core conversion flow: raw Vietnamese text -> `underthesea.dependency_parse()` + `underthesea.pos_tag()` -> Vietnamese POS mapped to Universal POS via `UPOS_MAP` -> syntax error post-processing via `fix_syntax_errors()` -> CoNLL-U output.
|
| 93 |
+
|
| 94 |
+
`fix_syntax_errors()` is a critical multi-pass function that corrects UD validation issues:
|
| 95 |
+
- Redirects children of leaf-only relations (aux, case, punct, det, etc.)
|
| 96 |
+
- Maps invalid deprels via `DEPREL_MAP`
|
| 97 |
+
- Enforces UPOS/deprel consistency (e.g., `det` must be DET/PRON, `advmod` must be ADV)
|
| 98 |
+
- Handles Vietnamese-specific auxiliary verbs (`AUX_WORDS`) and copula (`la`)
|
| 99 |
+
- Fixes directional constraints (flat/conj/appos must be left-to-right)
|
| 100 |
+
- Resolves multiple subjects/objects per predicate
|
| 101 |
+
- Fixes non-projective punctuation attachment
|
| 102 |
+
|
| 103 |
+
### udtools (Vendored UD Validator)
|
| 104 |
+
The `src/udtools/` directory is a vendored copy of the official UD tools. The validator class hierarchy is: `Validator` -> `Level6` -> `Level5` -> ... -> `Level1`. Each level adds progressively stricter UD compliance checks. The `Validator` class in `validator.py` is the main entry point.
|
| 105 |
+
|
| 106 |
+
### Data Format
|
| 107 |
+
- **CoNLL-U**: Standard 10-column UD format (ID, FORM, LEMMA, UPOS, XPOS, FEATS, HEAD, DEPREL, DEPS, MISC)
|
| 108 |
+
- **JSONL**: HuggingFace-compatible format with fields: `sent_id`, `text`, `tokens`, `lemmas`, `upos`, `xpos`, `feats`, `head`, `deprel`, `deps`, `misc`, `domain`
|
| 109 |
+
- Sentence ID prefixes: `vlc-` = legal, `uvn-` = news, `uvw-` = wikipedia, `uvb-f-` = fiction, `uvb-n-` = non-fiction
|
| 110 |
+
- Split ratios: Train (91.4%) / Dev (4.3%) / Test (4.3%), stratified by domain
|
| 111 |
+
|
| 112 |
+
## Dependencies
|
| 113 |
+
|
| 114 |
+
- `underthesea`: Vietnamese NLP toolkit (tokenization, POS tagging, dependency parsing)
|
| 115 |
+
- `torch`: Required by underthesea models (GPU-accelerated)
|
| 116 |
+
- `datasets`, `huggingface_hub`: For HuggingFace dataset operations
|
| 117 |
+
- `udtools` dependencies: `udapi>=0.5.0`, `regex>=2020.09.27` (see `src/udtools/pyproject.toml`)
|
src/build_dataset.py
ADDED
|
@@ -0,0 +1,209 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Build the combined UDD-1 multi-domain dataset (40,000 sentences).
|
| 3 |
+
|
| 4 |
+
Reads sentence files from all domains, assigns domain-specific sent_id prefixes,
|
| 5 |
+
and creates stratified train/dev/test splits.
|
| 6 |
+
|
| 7 |
+
Domain mapping:
|
| 8 |
+
- sentences_vlc.txt -> prefix: vlc- (Legal)
|
| 9 |
+
- sentences_uvn.txt -> prefix: uvn- (News)
|
| 10 |
+
- sentences_uvw.txt -> prefix: uvw- (Wikipedia)
|
| 11 |
+
- sentences_uvb.txt -> prefix: uvb-f- (Fiction), uvb-n- (Non-fiction)
|
| 12 |
+
|
| 13 |
+
Output:
|
| 14 |
+
- sentences_train.txt (91.4%)
|
| 15 |
+
- sentences_dev.txt (4.3%)
|
| 16 |
+
- sentences_test.txt (4.3%)
|
| 17 |
+
|
| 18 |
+
Each line format: sent_id\tsentence
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
import random
|
| 22 |
+
from os.path import dirname, isfile, join
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
# Split ratios
|
| 26 |
+
TRAIN_RATIO = 0.914
|
| 27 |
+
DEV_RATIO = 0.043
|
| 28 |
+
TEST_RATIO = 0.043
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def load_sentences_with_prefix(filepath, prefix):
|
| 32 |
+
"""Load sentences from a file and assign sent_id prefix.
|
| 33 |
+
|
| 34 |
+
Returns list of (sent_id, sentence) tuples.
|
| 35 |
+
"""
|
| 36 |
+
sentences = []
|
| 37 |
+
with open(filepath, "r", encoding="utf-8") as f:
|
| 38 |
+
for line in f:
|
| 39 |
+
line = line.strip()
|
| 40 |
+
if not line:
|
| 41 |
+
continue
|
| 42 |
+
parts = line.split("\t")
|
| 43 |
+
# Format: idx\tsentence
|
| 44 |
+
if len(parts) == 2:
|
| 45 |
+
idx = parts[0]
|
| 46 |
+
sentence = parts[1]
|
| 47 |
+
sent_id = f"{prefix}{idx}"
|
| 48 |
+
sentences.append((sent_id, sentence))
|
| 49 |
+
# Format: idx\tsource\tsentence (sentences_uvb.txt)
|
| 50 |
+
elif len(parts) >= 3:
|
| 51 |
+
idx = parts[0]
|
| 52 |
+
source = parts[1]
|
| 53 |
+
sentence = parts[2]
|
| 54 |
+
sent_id = f"{prefix}{idx}"
|
| 55 |
+
sentences.append((sent_id, sentence, source))
|
| 56 |
+
return sentences
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def load_uvb_sentences(filepath):
|
| 60 |
+
"""Load UVB sentences and split by fiction/non-fiction with proper prefixes."""
|
| 61 |
+
fiction = []
|
| 62 |
+
non_fiction = []
|
| 63 |
+
fiction_idx = 0
|
| 64 |
+
non_fiction_idx = 0
|
| 65 |
+
|
| 66 |
+
with open(filepath, "r", encoding="utf-8") as f:
|
| 67 |
+
for line in f:
|
| 68 |
+
line = line.strip()
|
| 69 |
+
if not line:
|
| 70 |
+
continue
|
| 71 |
+
parts = line.split("\t")
|
| 72 |
+
if len(parts) >= 3:
|
| 73 |
+
source = parts[1]
|
| 74 |
+
sentence = parts[2]
|
| 75 |
+
if source == "fiction":
|
| 76 |
+
fiction_idx += 1
|
| 77 |
+
fiction.append((f"uvb-f-{fiction_idx}", sentence))
|
| 78 |
+
else:
|
| 79 |
+
non_fiction_idx += 1
|
| 80 |
+
non_fiction.append((f"uvb-n-{non_fiction_idx}", sentence))
|
| 81 |
+
|
| 82 |
+
return fiction, non_fiction
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def stratified_split(domain_sentences, seed=42):
|
| 86 |
+
"""Create stratified train/dev/test split preserving domain proportions.
|
| 87 |
+
|
| 88 |
+
Args:
|
| 89 |
+
domain_sentences: dict of domain_name -> list of (sent_id, sentence)
|
| 90 |
+
seed: random seed for reproducibility
|
| 91 |
+
|
| 92 |
+
Returns:
|
| 93 |
+
train, dev, test lists of (sent_id, sentence)
|
| 94 |
+
"""
|
| 95 |
+
random.seed(seed)
|
| 96 |
+
|
| 97 |
+
train = []
|
| 98 |
+
dev = []
|
| 99 |
+
test = []
|
| 100 |
+
|
| 101 |
+
for domain_name, sentences in domain_sentences.items():
|
| 102 |
+
# Shuffle within each domain
|
| 103 |
+
shuffled = list(sentences)
|
| 104 |
+
random.shuffle(shuffled)
|
| 105 |
+
|
| 106 |
+
n = len(shuffled)
|
| 107 |
+
n_dev = max(1, round(n * DEV_RATIO))
|
| 108 |
+
n_test = max(1, round(n * TEST_RATIO))
|
| 109 |
+
n_train = n - n_dev - n_test
|
| 110 |
+
|
| 111 |
+
train.extend(shuffled[:n_train])
|
| 112 |
+
dev.extend(shuffled[n_train:n_train + n_dev])
|
| 113 |
+
test.extend(shuffled[n_train + n_dev:])
|
| 114 |
+
|
| 115 |
+
print(f" {domain_name}: {n_train} train / {n_dev} dev / {n_test} test (total: {n})")
|
| 116 |
+
|
| 117 |
+
return train, dev, test
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def save_split(sentences, filepath):
|
| 121 |
+
"""Save a list of (sent_id, sentence) to file."""
|
| 122 |
+
with open(filepath, "w", encoding="utf-8") as f:
|
| 123 |
+
for sent_id, sentence in sentences:
|
| 124 |
+
f.write(f"{sent_id}\t{sentence}\n")
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def main():
|
| 128 |
+
base_dir = dirname(dirname(__file__))
|
| 129 |
+
|
| 130 |
+
# Define source files and their prefixes
|
| 131 |
+
sources = {
|
| 132 |
+
"vlc": ("sentences_vlc.txt", "vlc-"),
|
| 133 |
+
"uvn": ("sentences_uvn.txt", "uvn-"),
|
| 134 |
+
"uvw": ("sentences_uvw.txt", "uvw-"),
|
| 135 |
+
}
|
| 136 |
+
|
| 137 |
+
# Load sentences from each domain
|
| 138 |
+
domain_sentences = {}
|
| 139 |
+
|
| 140 |
+
for domain, (filename, prefix) in sources.items():
|
| 141 |
+
filepath = join(base_dir, filename)
|
| 142 |
+
if not isfile(filepath):
|
| 143 |
+
print(f"Warning: {filepath} not found, skipping {domain}")
|
| 144 |
+
continue
|
| 145 |
+
sents = load_sentences_with_prefix(filepath, prefix)
|
| 146 |
+
# Extract just (sent_id, sentence) tuples
|
| 147 |
+
domain_sentences[domain] = [(s[0], s[1]) for s in sents]
|
| 148 |
+
print(f"Loaded {len(domain_sentences[domain])} sentences from {filename}")
|
| 149 |
+
|
| 150 |
+
# Load UVB (books) with fiction/non-fiction split
|
| 151 |
+
uvb_filepath = join(base_dir, "sentences_uvb.txt")
|
| 152 |
+
if isfile(uvb_filepath):
|
| 153 |
+
fiction, non_fiction = load_uvb_sentences(uvb_filepath)
|
| 154 |
+
domain_sentences["uvb-fiction"] = fiction
|
| 155 |
+
domain_sentences["uvb-nonfiction"] = non_fiction
|
| 156 |
+
print(f"Loaded {len(fiction)} fiction + {len(non_fiction)} non-fiction sentences from sentences_uvb.txt")
|
| 157 |
+
else:
|
| 158 |
+
print(f"Warning: {uvb_filepath} not found, skipping books domain")
|
| 159 |
+
|
| 160 |
+
# Report totals
|
| 161 |
+
total = sum(len(v) for v in domain_sentences.values())
|
| 162 |
+
print(f"\nTotal sentences across all domains: {total}")
|
| 163 |
+
|
| 164 |
+
# Create stratified split
|
| 165 |
+
print("\nCreating stratified train/dev/test split...")
|
| 166 |
+
train, dev, test = stratified_split(domain_sentences)
|
| 167 |
+
|
| 168 |
+
print(f"\nSplit sizes:")
|
| 169 |
+
print(f" Train: {len(train)} ({100*len(train)/total:.1f}%)")
|
| 170 |
+
print(f" Dev: {len(dev)} ({100*len(dev)/total:.1f}%)")
|
| 171 |
+
print(f" Test: {len(test)} ({100*len(test)/total:.1f}%)")
|
| 172 |
+
print(f" Total: {len(train) + len(dev) + len(test)}")
|
| 173 |
+
|
| 174 |
+
# Save splits
|
| 175 |
+
save_split(train, join(base_dir, "sentences_train.txt"))
|
| 176 |
+
save_split(dev, join(base_dir, "sentences_dev.txt"))
|
| 177 |
+
save_split(test, join(base_dir, "sentences_test.txt"))
|
| 178 |
+
|
| 179 |
+
print(f"\nSaved to:")
|
| 180 |
+
print(f" {join(base_dir, 'sentences_train.txt')}")
|
| 181 |
+
print(f" {join(base_dir, 'sentences_dev.txt')}")
|
| 182 |
+
print(f" {join(base_dir, 'sentences_test.txt')}")
|
| 183 |
+
|
| 184 |
+
# Print domain distribution per split
|
| 185 |
+
print("\nDomain distribution per split:")
|
| 186 |
+
for split_name, split_data in [("Train", train), ("Dev", dev), ("Test", test)]:
|
| 187 |
+
domain_counts = {}
|
| 188 |
+
for sent_id, _ in split_data:
|
| 189 |
+
# Determine domain from sent_id prefix
|
| 190 |
+
if sent_id.startswith("vlc-"):
|
| 191 |
+
domain = "legal"
|
| 192 |
+
elif sent_id.startswith("uvn-"):
|
| 193 |
+
domain = "news"
|
| 194 |
+
elif sent_id.startswith("uvw-"):
|
| 195 |
+
domain = "wikipedia"
|
| 196 |
+
elif sent_id.startswith("uvb-f-"):
|
| 197 |
+
domain = "fiction"
|
| 198 |
+
elif sent_id.startswith("uvb-n-"):
|
| 199 |
+
domain = "non-fiction"
|
| 200 |
+
else:
|
| 201 |
+
domain = "unknown"
|
| 202 |
+
domain_counts[domain] = domain_counts.get(domain, 0) + 1
|
| 203 |
+
|
| 204 |
+
counts_str = ", ".join(f"{d}: {c}" for d, c in sorted(domain_counts.items()))
|
| 205 |
+
print(f" {split_name}: {counts_str}")
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
if __name__ == "__main__":
|
| 209 |
+
main()
|
src/convert_to_ud.py
ADDED
|
@@ -0,0 +1,692 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Convert sentences to Universal Dependencies format compatible with HuggingFace.
|
| 3 |
+
Structure follows: https://huggingface.co/datasets/commul/universal_dependencies/viewer/vi_vtb
|
| 4 |
+
Uses underthesea dependency_parse for proper annotations.
|
| 5 |
+
|
| 6 |
+
Optimized for GPU batch processing.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
import json
|
| 10 |
+
import os
|
| 11 |
+
from os.path import dirname, expanduser, join
|
| 12 |
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
| 13 |
+
import multiprocessing
|
| 14 |
+
|
| 15 |
+
# Fix GPU tensor compatibility issue with pack_padded_sequence
|
| 16 |
+
# The lengths tensor must be on CPU even when using CUDA
|
| 17 |
+
import torch
|
| 18 |
+
_original_pack = torch.nn.utils.rnn.pack_padded_sequence
|
| 19 |
+
|
| 20 |
+
def _patched_pack(input, lengths, batch_first=False, enforce_sorted=True):
|
| 21 |
+
if lengths.is_cuda:
|
| 22 |
+
lengths = lengths.cpu()
|
| 23 |
+
return _original_pack(input, lengths, batch_first=batch_first, enforce_sorted=enforce_sorted)
|
| 24 |
+
|
| 25 |
+
torch.nn.utils.rnn.pack_padded_sequence = _patched_pack
|
| 26 |
+
|
| 27 |
+
from underthesea import dependency_parse, pos_tag
|
| 28 |
+
|
| 29 |
+
# Global model cache for batch processing
|
| 30 |
+
_models_loaded = False
|
| 31 |
+
|
| 32 |
+
# Map Vietnamese POS tags to Universal POS tags
|
| 33 |
+
# Based on: https://universaldependencies.org/u/pos/
|
| 34 |
+
UPOS_MAP = {
|
| 35 |
+
'N': 'NOUN', # Noun
|
| 36 |
+
'Np': 'PROPN', # Proper noun
|
| 37 |
+
'Nc': 'NOUN', # Classifier noun
|
| 38 |
+
'Nu': 'NOUN', # Unit noun
|
| 39 |
+
'V': 'VERB', # Verb
|
| 40 |
+
'A': 'ADJ', # Adjective
|
| 41 |
+
'P': 'PRON', # Pronoun
|
| 42 |
+
'R': 'ADV', # Adverb
|
| 43 |
+
'L': 'DET', # Determiner/Quantifier
|
| 44 |
+
'M': 'NUM', # Numeral
|
| 45 |
+
'E': 'ADP', # Preposition
|
| 46 |
+
'C': 'CCONJ', # Coordinating conjunction
|
| 47 |
+
'CC': 'CCONJ', # Coordinating conjunction
|
| 48 |
+
'SC': 'SCONJ', # Subordinating conjunction
|
| 49 |
+
'I': 'INTJ', # Interjection
|
| 50 |
+
'T': 'PART', # Particle
|
| 51 |
+
'B': 'X', # Foreign word
|
| 52 |
+
'Y': 'X', # Abbreviation
|
| 53 |
+
'S': 'SYM', # Symbol
|
| 54 |
+
'X': 'X', # Other
|
| 55 |
+
'CH': 'PUNCT', # Punctuation
|
| 56 |
+
'Ny': 'NOUN', # Noun (variant)
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
# Vietnamese auxiliary verbs that should be tagged as AUX
|
| 60 |
+
# Based on UD Vietnamese validation data (data.json)
|
| 61 |
+
AUX_WORDS = {
|
| 62 |
+
'bị', 'chưa thể', 'chắc chắn', 'có thể', 'có vẻ', 'cần',
|
| 63 |
+
'giả', 'không thể', 'là', 'muốn', 'nghĩa là', 'nhằm',
|
| 64 |
+
'nên', 'phải', 'quyết', 'thôi', 'thể', 'xong', 'được', 'định'
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
# Vietnamese determiners - words that should be DET when used as 'det' relation
|
| 68 |
+
DET_WORDS = {
|
| 69 |
+
'các', 'những', 'mọi', 'mỗi', 'từng', 'bất kỳ', 'một', 'hai', 'ba',
|
| 70 |
+
'này', 'đó', 'kia', 'ấy', 'nọ', 'nào', 'đấy', 'cái', 'con', 'chiếc',
|
| 71 |
+
'người', 'cả', 'phá tán' # Words that appear as det in the data
|
| 72 |
+
}
|
| 73 |
+
|
| 74 |
+
# Words that can be ADV when used as 'advmod'
|
| 75 |
+
ADV_WORDS = {
|
| 76 |
+
'không', 'chưa', 'đã', 'đang', 'sẽ', 'còn', 'vẫn', 'cũng', 'rất',
|
| 77 |
+
'quá', 'lắm', 'hơn', 'nhất', 'luôn', 'thường', 'hay', 'ít', 'nhiều',
|
| 78 |
+
'tự', 'một cách', 'được', 'không thể', 'lại', 'cá biệt', 'dân sự'
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
# Invalid deprels that need to be mapped to valid ones
|
| 82 |
+
DEPREL_MAP = {
|
| 83 |
+
'acomp': 'xcomp', # Adjectival complement -> open clausal complement
|
| 84 |
+
'nmod:comp': 'nmod', # Invalid subtype
|
| 85 |
+
'nmod:agent': 'obl:agent', # Agent should be obl not nmod
|
| 86 |
+
'nmod:with': 'nmod', # Invalid subtype
|
| 87 |
+
'nmod:about': 'nmod', # Invalid subtype -> nmod
|
| 88 |
+
'compound:number': 'nummod', # Number compounds should be nummod
|
| 89 |
+
'compound:nmod': 'compound', # Invalid subtype
|
| 90 |
+
'obl:pcomp': 'obl', # Invalid subtype -> obl
|
| 91 |
+
}
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def to_upos(tag, token=None):
|
| 95 |
+
"""Convert Vietnamese POS tag to Universal POS tag."""
|
| 96 |
+
# Check if token is an auxiliary verb (case insensitive)
|
| 97 |
+
if token:
|
| 98 |
+
token_lower = token.lower()
|
| 99 |
+
if token_lower in AUX_WORDS:
|
| 100 |
+
return 'AUX'
|
| 101 |
+
# Also check if lowercased token matches
|
| 102 |
+
for aux in AUX_WORDS:
|
| 103 |
+
if token_lower == aux.lower():
|
| 104 |
+
return 'AUX'
|
| 105 |
+
return UPOS_MAP.get(tag, 'X')
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def fix_syntax_errors(tokens, upos, head, deprel):
|
| 109 |
+
"""
|
| 110 |
+
Post-process to fix common UD SYNTAX validation errors.
|
| 111 |
+
Returns fixed (upos, deprel) lists.
|
| 112 |
+
Run multiple passes to handle dependencies between fixes.
|
| 113 |
+
"""
|
| 114 |
+
n = len(tokens)
|
| 115 |
+
upos = list(upos)
|
| 116 |
+
deprel = list(deprel)
|
| 117 |
+
head = [int(h) for h in head]
|
| 118 |
+
|
| 119 |
+
# First pass: fix leaf nodes (aux/mark/case/punct should not have children)
|
| 120 |
+
# Need multiple passes to handle chains of leaf nodes
|
| 121 |
+
for _ in range(5): # Multiple passes to handle chains
|
| 122 |
+
changed = False
|
| 123 |
+
for i in range(n):
|
| 124 |
+
rel = deprel[i]
|
| 125 |
+
|
| 126 |
+
# Leaf nodes should not have children - redirect children to parent
|
| 127 |
+
# Include subtypes like aux:pass, mark:pcomp, etc.
|
| 128 |
+
# Also include det, nummod, clf which should be leaves
|
| 129 |
+
if rel.split(':')[0] in ('aux', 'cop', 'mark', 'case', 'punct', 'det', 'nummod', 'clf'):
|
| 130 |
+
has_children = any(head[j] == i + 1 for j in range(n))
|
| 131 |
+
if has_children:
|
| 132 |
+
my_head = head[i]
|
| 133 |
+
for j in range(n):
|
| 134 |
+
if head[j] == i + 1:
|
| 135 |
+
head[j] = my_head
|
| 136 |
+
changed = True
|
| 137 |
+
if not changed:
|
| 138 |
+
break
|
| 139 |
+
|
| 140 |
+
for i in range(n):
|
| 141 |
+
token_lower = tokens[i].lower()
|
| 142 |
+
rel = deprel[i]
|
| 143 |
+
pos = upos[i]
|
| 144 |
+
|
| 145 |
+
# Fix 0: Map invalid deprels to valid ones
|
| 146 |
+
if rel in DEPREL_MAP:
|
| 147 |
+
deprel[i] = DEPREL_MAP[rel]
|
| 148 |
+
rel = deprel[i]
|
| 149 |
+
|
| 150 |
+
# Fix 1: rel-upos-det - 'det' (including subtypes) should be DET or PRON
|
| 151 |
+
if rel.startswith('det') and pos not in ('DET', 'PRON'):
|
| 152 |
+
# Force all 'det' relations to have DET or PRON UPOS
|
| 153 |
+
upos[i] = 'DET'
|
| 154 |
+
|
| 155 |
+
# Fix 2: rel-upos-advmod - 'advmod' (including subtypes) should be ADV
|
| 156 |
+
if rel.startswith('advmod') and pos != 'ADV':
|
| 157 |
+
# For advmod, always prefer changing UPOS to ADV
|
| 158 |
+
upos[i] = 'ADV'
|
| 159 |
+
|
| 160 |
+
# Fix 2b: rel-upos-nummod - 'nummod' should be NUM
|
| 161 |
+
if rel.startswith('nummod') and upos[i] != 'NUM':
|
| 162 |
+
# If token is clearly not a number (e.g., VERB), change relation instead
|
| 163 |
+
if upos[i] == 'VERB':
|
| 164 |
+
deprel[i] = 'acl' # Adjectival clause for verbs
|
| 165 |
+
rel = 'acl' # Update local variable too
|
| 166 |
+
elif upos[i] == 'ADJ':
|
| 167 |
+
deprel[i] = 'amod' # Adjectival modifier
|
| 168 |
+
rel = 'amod'
|
| 169 |
+
else:
|
| 170 |
+
upos[i] = 'NUM'
|
| 171 |
+
|
| 172 |
+
# Fix 3: rel-upos-mark - 'mark' (including subtypes) should not be AUX
|
| 173 |
+
if rel.startswith('mark') and pos == 'AUX':
|
| 174 |
+
upos[i] = 'SCONJ'
|
| 175 |
+
|
| 176 |
+
# Fix 3b: rel-upos-punct - 'punct' must be PUNCT, and PUNCT must have 'punct' deprel
|
| 177 |
+
if rel == 'punct' and pos != 'PUNCT':
|
| 178 |
+
# Change relation to something appropriate based on POS
|
| 179 |
+
if pos in ('VERB', 'NOUN', 'ADJ'):
|
| 180 |
+
deprel[i] = 'dep' # Use generic dependency
|
| 181 |
+
else:
|
| 182 |
+
upos[i] = 'PUNCT'
|
| 183 |
+
|
| 184 |
+
# Fix 3b2: upos-rel-punct - PUNCT must have 'punct' deprel
|
| 185 |
+
if pos == 'PUNCT' and rel != 'punct':
|
| 186 |
+
deprel[i] = 'punct'
|
| 187 |
+
rel = 'punct'
|
| 188 |
+
|
| 189 |
+
# Fix 3c: rel-upos-case - 'case' should be ADP, not ADJ, AUX or PROPN
|
| 190 |
+
if rel == 'case' and pos in ('ADJ', 'AUX', 'PROPN', 'NOUN', 'VERB'):
|
| 191 |
+
upos[i] = 'ADP'
|
| 192 |
+
|
| 193 |
+
# Fix 3d: rel-upos-cc - 'cc' should be CCONJ or SCONJ
|
| 194 |
+
if rel == 'cc' and pos not in ('CCONJ', 'SCONJ'):
|
| 195 |
+
upos[i] = 'CCONJ'
|
| 196 |
+
|
| 197 |
+
# Fix 3e: rel-upos-aux - 'aux' should be AUX, but only for valid auxiliaries
|
| 198 |
+
is_valid_aux = token_lower in AUX_WORDS or any(token_lower == aux.lower() for aux in AUX_WORDS)
|
| 199 |
+
if rel.startswith('aux'):
|
| 200 |
+
if is_valid_aux:
|
| 201 |
+
upos[i] = 'AUX'
|
| 202 |
+
pos = 'AUX'
|
| 203 |
+
else:
|
| 204 |
+
# Not a valid auxiliary - change relation to advcl or xcomp
|
| 205 |
+
if pos == 'VERB' or upos[i] == 'VERB':
|
| 206 |
+
deprel[i] = 'advcl'
|
| 207 |
+
upos[i] = 'VERB'
|
| 208 |
+
elif pos == 'ADP' or upos[i] == 'ADP':
|
| 209 |
+
deprel[i] = 'mark'
|
| 210 |
+
upos[i] = 'ADP'
|
| 211 |
+
else:
|
| 212 |
+
deprel[i] = 'xcomp'
|
| 213 |
+
rel = deprel[i]
|
| 214 |
+
pos = upos[i]
|
| 215 |
+
# Also fix AUX UPOS that's not a valid auxiliary (MORPHO aux-lemma)
|
| 216 |
+
elif pos == 'AUX' and not is_valid_aux:
|
| 217 |
+
upos[i] = 'VERB' # Default to VERB for non-aux
|
| 218 |
+
pos = 'VERB'
|
| 219 |
+
|
| 220 |
+
# Fix 3f: rel-upos-cop - 'cop' should be AUX or PRON/DET, only 'là' is valid copula
|
| 221 |
+
if rel == 'cop':
|
| 222 |
+
if token_lower != 'là':
|
| 223 |
+
# Not a valid copula, change to xcomp
|
| 224 |
+
deprel[i] = 'xcomp'
|
| 225 |
+
rel = 'xcomp'
|
| 226 |
+
elif pos not in ('AUX', 'PRON', 'DET'):
|
| 227 |
+
upos[i] = 'AUX'
|
| 228 |
+
|
| 229 |
+
# Fix 4: obl-should-be-nmod - when parent is nominal, use nmod
|
| 230 |
+
if rel.startswith('obl') and head[i] > 0:
|
| 231 |
+
parent_idx = head[i] - 1
|
| 232 |
+
if parent_idx < n and upos[parent_idx] in ('NOUN', 'PROPN', 'PRON'):
|
| 233 |
+
# Preserve subtype if exists
|
| 234 |
+
if ':' in rel:
|
| 235 |
+
deprel[i] = 'nmod:' + rel.split(':')[1]
|
| 236 |
+
else:
|
| 237 |
+
deprel[i] = 'nmod'
|
| 238 |
+
|
| 239 |
+
# Fix 5: (handled in first pass above)
|
| 240 |
+
|
| 241 |
+
# Fix 5b: right-to-left relations - flat/conj/appos must be left-to-right
|
| 242 |
+
for i in range(n):
|
| 243 |
+
rel = deprel[i]
|
| 244 |
+
base_rel = rel.split(':')[0]
|
| 245 |
+
if base_rel in ('flat', 'conj', 'appos') and head[i] > 0:
|
| 246 |
+
parent_idx = head[i] - 1
|
| 247 |
+
if parent_idx > i: # Parent comes after child (wrong direction)
|
| 248 |
+
# Change to compound which allows both directions
|
| 249 |
+
if ':' in rel:
|
| 250 |
+
deprel[i] = 'compound:' + rel.split(':')[1]
|
| 251 |
+
else:
|
| 252 |
+
deprel[i] = 'compound'
|
| 253 |
+
|
| 254 |
+
# Fix 5c: Apply DEPREL_MAP again to catch any newly created invalid deprels
|
| 255 |
+
for i in range(n):
|
| 256 |
+
if deprel[i] in DEPREL_MAP:
|
| 257 |
+
deprel[i] = DEPREL_MAP[deprel[i]]
|
| 258 |
+
|
| 259 |
+
# Fix 5d: Final check for nummod with wrong UPOS
|
| 260 |
+
for i in range(n):
|
| 261 |
+
if deprel[i].startswith('nummod') and upos[i] != 'NUM':
|
| 262 |
+
if upos[i] == 'VERB':
|
| 263 |
+
deprel[i] = 'acl'
|
| 264 |
+
elif upos[i] == 'ADJ':
|
| 265 |
+
deprel[i] = 'amod'
|
| 266 |
+
elif upos[i] == 'NOUN':
|
| 267 |
+
deprel[i] = 'nmod'
|
| 268 |
+
else:
|
| 269 |
+
upos[i] = 'NUM'
|
| 270 |
+
|
| 271 |
+
# Fix 6: too-many-subjects - add :outer subtype for multiple subjects
|
| 272 |
+
# Group all subject types (nsubj, csubj) by predicate
|
| 273 |
+
predicates = {}
|
| 274 |
+
for i in range(n):
|
| 275 |
+
base_rel = deprel[i].split(':')[0]
|
| 276 |
+
if base_rel in ('nsubj', 'csubj') and head[i] > 0:
|
| 277 |
+
pred_idx = head[i]
|
| 278 |
+
if pred_idx not in predicates:
|
| 279 |
+
predicates[pred_idx] = []
|
| 280 |
+
predicates[pred_idx].append((i, base_rel))
|
| 281 |
+
|
| 282 |
+
for pred_idx, subj_list in predicates.items():
|
| 283 |
+
if len(subj_list) > 1:
|
| 284 |
+
# Sort by position to keep first subject as main
|
| 285 |
+
subj_list.sort(key=lambda x: x[0])
|
| 286 |
+
# Mark all but the first as :outer (only nsubj:outer is valid, not csubj:outer)
|
| 287 |
+
for idx, base_rel in subj_list[1:]:
|
| 288 |
+
if ':outer' not in deprel[idx]:
|
| 289 |
+
# csubj:outer is not a valid UD relation, use nsubj:outer instead
|
| 290 |
+
deprel[idx] = 'nsubj:outer'
|
| 291 |
+
|
| 292 |
+
# Fix 7: too-many-objects - add :pass or compound for multiple objects
|
| 293 |
+
predicates_obj = {}
|
| 294 |
+
for i in range(n):
|
| 295 |
+
if deprel[i] == 'obj' and head[i] > 0:
|
| 296 |
+
pred_idx = head[i]
|
| 297 |
+
if pred_idx not in predicates_obj:
|
| 298 |
+
predicates_obj[pred_idx] = []
|
| 299 |
+
predicates_obj[pred_idx].append(i)
|
| 300 |
+
|
| 301 |
+
for pred_idx, obj_indices in predicates_obj.items():
|
| 302 |
+
if len(obj_indices) > 1:
|
| 303 |
+
# Mark subsequent objects as compound
|
| 304 |
+
for idx in obj_indices[1:]:
|
| 305 |
+
# Check if it's adjacent to previous - likely compound
|
| 306 |
+
if idx > 0 and obj_indices[0] == idx - 1:
|
| 307 |
+
deprel[idx] = 'compound'
|
| 308 |
+
else:
|
| 309 |
+
deprel[idx] = 'iobj'
|
| 310 |
+
|
| 311 |
+
# Fix 8: punct-is-nonproj - attach punctuation to avoid non-projectivity
|
| 312 |
+
# Try to find the best attachment point that doesn't cross other edges
|
| 313 |
+
for i in range(n):
|
| 314 |
+
if upos[i] == 'PUNCT':
|
| 315 |
+
# Try candidates in order: previous token, next token, then expand outward
|
| 316 |
+
candidates = []
|
| 317 |
+
if i > 0:
|
| 318 |
+
candidates.append(i) # Previous token (1-based)
|
| 319 |
+
if i + 1 < n:
|
| 320 |
+
candidates.append(i + 2) # Next token (1-based)
|
| 321 |
+
|
| 322 |
+
# Expand to find more candidates
|
| 323 |
+
for dist in range(2, n):
|
| 324 |
+
if i - dist >= 0:
|
| 325 |
+
candidates.append(i - dist + 1) # 1-based
|
| 326 |
+
if i + dist < n:
|
| 327 |
+
candidates.append(i + dist + 1) # 1-based
|
| 328 |
+
|
| 329 |
+
# Find best attachment that doesn't cause crossing
|
| 330 |
+
best_head = candidates[0] if candidates else 1
|
| 331 |
+
for cand in candidates:
|
| 332 |
+
test_head = list(head)
|
| 333 |
+
test_head[i] = cand
|
| 334 |
+
if not punct_causes_crossing(i, cand - 1, test_head, n):
|
| 335 |
+
best_head = cand
|
| 336 |
+
break
|
| 337 |
+
|
| 338 |
+
head[i] = best_head
|
| 339 |
+
|
| 340 |
+
return upos, [str(h) for h in head], deprel
|
| 341 |
+
|
| 342 |
+
|
| 343 |
+
def punct_causes_crossing(punct_idx, new_head_idx, head, n):
|
| 344 |
+
"""Check if attaching punct to new_head causes any edge crossing."""
|
| 345 |
+
if new_head_idx < 0 or new_head_idx >= n:
|
| 346 |
+
return False
|
| 347 |
+
|
| 348 |
+
p_low, p_high = min(punct_idx, new_head_idx), max(punct_idx, new_head_idx)
|
| 349 |
+
|
| 350 |
+
# Check all other edges for crossing with this punct edge
|
| 351 |
+
for j in range(n):
|
| 352 |
+
if j == punct_idx:
|
| 353 |
+
continue
|
| 354 |
+
if head[j] > 0 and head[j] != punct_idx + 1: # j has a head and it's not punct
|
| 355 |
+
j_head = head[j] - 1
|
| 356 |
+
if j_head < 0 or j_head >= n:
|
| 357 |
+
continue
|
| 358 |
+
j_low, j_high = min(j, j_head), max(j, j_head)
|
| 359 |
+
|
| 360 |
+
# Check if edges cross (one endpoint inside, one outside)
|
| 361 |
+
# Edges cross if: (p_low < j_low < p_high < j_high) or (j_low < p_low < j_high < p_high)
|
| 362 |
+
if (p_low < j_low < p_high < j_high) or (j_low < p_low < j_high < p_high):
|
| 363 |
+
return True
|
| 364 |
+
|
| 365 |
+
return False
|
| 366 |
+
|
| 367 |
+
|
| 368 |
+
def compute_space_after(text, tokens):
|
| 369 |
+
"""Compute SpaceAfter=No for tokens based on original text."""
|
| 370 |
+
misc = []
|
| 371 |
+
pos = 0
|
| 372 |
+
for i, token in enumerate(tokens):
|
| 373 |
+
# Find token in text
|
| 374 |
+
token_start = text.find(token, pos)
|
| 375 |
+
if token_start == -1:
|
| 376 |
+
# Token not found, assume space after
|
| 377 |
+
misc.append("_")
|
| 378 |
+
continue
|
| 379 |
+
|
| 380 |
+
token_end = token_start + len(token)
|
| 381 |
+
pos = token_end
|
| 382 |
+
|
| 383 |
+
# Check if there's a space after this token
|
| 384 |
+
if token_end < len(text):
|
| 385 |
+
next_char = text[token_end]
|
| 386 |
+
if next_char in ' \t\n':
|
| 387 |
+
misc.append("_")
|
| 388 |
+
else:
|
| 389 |
+
misc.append("SpaceAfter=No")
|
| 390 |
+
else:
|
| 391 |
+
# End of text
|
| 392 |
+
misc.append("_")
|
| 393 |
+
|
| 394 |
+
return misc
|
| 395 |
+
|
| 396 |
+
|
| 397 |
+
def load_sentences(filepath):
|
| 398 |
+
"""Load sentences from input files.
|
| 399 |
+
|
| 400 |
+
Supported formats:
|
| 401 |
+
- sent_id\\tsentence (build_dataset.py output: sentences_train.txt, etc.)
|
| 402 |
+
- idx\\tsentence (fetch_data.py output: sentences_vlc.txt, etc.)
|
| 403 |
+
- idx\\tsource\\tsentence (fetch_uvb_data.py output: sentences_uvb.txt)
|
| 404 |
+
|
| 405 |
+
Returns list of (sent_id, sentence) tuples. For formats without a sent_id,
|
| 406 |
+
generates one as s{idx}.
|
| 407 |
+
"""
|
| 408 |
+
sentences = []
|
| 409 |
+
with open(filepath, "r", encoding="utf-8") as f:
|
| 410 |
+
for line in f:
|
| 411 |
+
line = line.strip()
|
| 412 |
+
if line:
|
| 413 |
+
parts = line.split("\t")
|
| 414 |
+
if len(parts) == 2:
|
| 415 |
+
first, second = parts
|
| 416 |
+
# If first part looks like a sent_id prefix (non-numeric), use it
|
| 417 |
+
if not first.isdigit():
|
| 418 |
+
sentences.append((first, second))
|
| 419 |
+
else:
|
| 420 |
+
sentences.append((f"s{first}", second))
|
| 421 |
+
elif len(parts) >= 3:
|
| 422 |
+
sentences.append((f"s{parts[0]}", parts[2]))
|
| 423 |
+
return sentences
|
| 424 |
+
|
| 425 |
+
|
| 426 |
+
def process_single_sentence(args):
|
| 427 |
+
"""Process a single sentence (used for parallel processing)."""
|
| 428 |
+
idx, text, sent_id = args
|
| 429 |
+
|
| 430 |
+
try:
|
| 431 |
+
# Use dependency_parse for tokens, heads, and deprels
|
| 432 |
+
parsed = dependency_parse(text)
|
| 433 |
+
tokens = [t[0] for t in parsed]
|
| 434 |
+
head = [str(t[1]) for t in parsed]
|
| 435 |
+
deprel = [t[2] for t in parsed]
|
| 436 |
+
|
| 437 |
+
# Get POS tags
|
| 438 |
+
tagged = pos_tag(text)
|
| 439 |
+
if len(tagged) == len(tokens):
|
| 440 |
+
xpos = [t[1] for t in tagged]
|
| 441 |
+
upos = [to_upos(t[1], t[0]) for t in tagged]
|
| 442 |
+
else:
|
| 443 |
+
xpos = ['X'] * len(tokens)
|
| 444 |
+
upos = ['X'] * len(tokens)
|
| 445 |
+
|
| 446 |
+
except Exception as e:
|
| 447 |
+
# Fallback to pos_tag only
|
| 448 |
+
tagged = pos_tag(text)
|
| 449 |
+
tokens = [t[0] for t in tagged]
|
| 450 |
+
xpos = [t[1] for t in tagged]
|
| 451 |
+
upos = [to_upos(t[1], t[0]) for t in tagged]
|
| 452 |
+
head = ["0"] * len(tokens)
|
| 453 |
+
deprel = ["dep"] * len(tokens)
|
| 454 |
+
if len(tokens) > 0:
|
| 455 |
+
deprel[0] = "root"
|
| 456 |
+
|
| 457 |
+
# Apply syntax fixes
|
| 458 |
+
upos, head, deprel = fix_syntax_errors(tokens, upos, head, deprel)
|
| 459 |
+
|
| 460 |
+
# Create other fields
|
| 461 |
+
n = len(tokens)
|
| 462 |
+
lemmas = [t.lower() for t in tokens]
|
| 463 |
+
feats = ["_"] * n
|
| 464 |
+
deps = ["_"] * n
|
| 465 |
+
misc = compute_space_after(text, tokens)
|
| 466 |
+
|
| 467 |
+
return idx, {
|
| 468 |
+
"sent_id": sent_id,
|
| 469 |
+
"text": text,
|
| 470 |
+
"comments": [f"# sent_id = {sent_id}", f"# text = {text}"],
|
| 471 |
+
"tokens": tokens,
|
| 472 |
+
"lemmas": lemmas,
|
| 473 |
+
"upos": upos,
|
| 474 |
+
"xpos": xpos,
|
| 475 |
+
"feats": feats,
|
| 476 |
+
"head": head,
|
| 477 |
+
"deprel": deprel,
|
| 478 |
+
"deps": deps,
|
| 479 |
+
"misc": misc,
|
| 480 |
+
"mwt": [],
|
| 481 |
+
"empty_nodes": []
|
| 482 |
+
}
|
| 483 |
+
|
| 484 |
+
|
| 485 |
+
def convert_to_ud_format(sentences, batch_size=32, num_workers=4):
|
| 486 |
+
"""Convert sentences to UD format using dependency_parse with batch processing.
|
| 487 |
+
|
| 488 |
+
Args:
|
| 489 |
+
sentences: list of (sent_id, text) tuples or list of text strings
|
| 490 |
+
batch_size: batch size for GPU processing
|
| 491 |
+
num_workers: number of workers (unused in batch mode)
|
| 492 |
+
"""
|
| 493 |
+
global _models_loaded
|
| 494 |
+
|
| 495 |
+
# Pre-warm models with a dummy sentence to load them into GPU memory
|
| 496 |
+
if not _models_loaded:
|
| 497 |
+
print(" Loading models into GPU memory...")
|
| 498 |
+
_ = dependency_parse("Xin chào")
|
| 499 |
+
_ = pos_tag("Xin chào")
|
| 500 |
+
_models_loaded = True
|
| 501 |
+
print(" Models loaded.")
|
| 502 |
+
|
| 503 |
+
data = [None] * len(sentences)
|
| 504 |
+
total = len(sentences)
|
| 505 |
+
|
| 506 |
+
# Process in batches for better GPU utilization
|
| 507 |
+
print(f" Processing {total} sentences with batch_size={batch_size}...")
|
| 508 |
+
|
| 509 |
+
for batch_start in range(0, total, batch_size):
|
| 510 |
+
batch_end = min(batch_start + batch_size, total)
|
| 511 |
+
batch = []
|
| 512 |
+
for i in range(batch_start, batch_end):
|
| 513 |
+
s = sentences[i]
|
| 514 |
+
if isinstance(s, tuple):
|
| 515 |
+
sent_id, text = s
|
| 516 |
+
batch.append((i + 1, text, sent_id))
|
| 517 |
+
else:
|
| 518 |
+
batch.append((i + 1, s, f"s{i + 1}"))
|
| 519 |
+
|
| 520 |
+
# Process batch - GPU models benefit from sequential calls within batch
|
| 521 |
+
# as they can better utilize GPU memory
|
| 522 |
+
for args in batch:
|
| 523 |
+
idx, row = process_single_sentence(args)
|
| 524 |
+
data[idx - 1] = row
|
| 525 |
+
|
| 526 |
+
# Progress update
|
| 527 |
+
processed = batch_end
|
| 528 |
+
if processed % 100 == 0 or processed == total:
|
| 529 |
+
print(f" Processed {processed}/{total} sentences ({100*processed/total:.1f}%)")
|
| 530 |
+
|
| 531 |
+
return data
|
| 532 |
+
|
| 533 |
+
|
| 534 |
+
def convert_to_ud_format_parallel(sentences, num_workers=None):
|
| 535 |
+
"""Convert sentences using multiple workers (CPU parallelism).
|
| 536 |
+
|
| 537 |
+
Note: This is useful when GPU is bottleneck or for CPU-only processing.
|
| 538 |
+
For GPU processing, use convert_to_ud_format with batch processing.
|
| 539 |
+
|
| 540 |
+
Args:
|
| 541 |
+
sentences: list of (sent_id, text) tuples or list of text strings
|
| 542 |
+
num_workers: number of parallel workers
|
| 543 |
+
"""
|
| 544 |
+
global _models_loaded
|
| 545 |
+
|
| 546 |
+
if num_workers is None:
|
| 547 |
+
num_workers = min(4, multiprocessing.cpu_count())
|
| 548 |
+
|
| 549 |
+
# Pre-warm models
|
| 550 |
+
if not _models_loaded:
|
| 551 |
+
print(" Loading models...")
|
| 552 |
+
_ = dependency_parse("Xin chào")
|
| 553 |
+
_ = pos_tag("Xin chào")
|
| 554 |
+
_models_loaded = True
|
| 555 |
+
print(" Models loaded.")
|
| 556 |
+
|
| 557 |
+
data = [None] * len(sentences)
|
| 558 |
+
total = len(sentences)
|
| 559 |
+
processed = 0
|
| 560 |
+
|
| 561 |
+
print(f" Processing {total} sentences with {num_workers} workers...")
|
| 562 |
+
|
| 563 |
+
# Build args list with sent_id
|
| 564 |
+
args_list = []
|
| 565 |
+
for i in range(total):
|
| 566 |
+
s = sentences[i]
|
| 567 |
+
if isinstance(s, tuple):
|
| 568 |
+
sent_id, text = s
|
| 569 |
+
args_list.append((i + 1, text, sent_id))
|
| 570 |
+
else:
|
| 571 |
+
args_list.append((i + 1, s, f"s{i + 1}"))
|
| 572 |
+
|
| 573 |
+
# Use ThreadPoolExecutor for I/O bound tasks with GPU
|
| 574 |
+
with ThreadPoolExecutor(max_workers=num_workers) as executor:
|
| 575 |
+
futures = {
|
| 576 |
+
executor.submit(process_single_sentence, args): i
|
| 577 |
+
for i, args in enumerate(args_list)
|
| 578 |
+
}
|
| 579 |
+
|
| 580 |
+
for future in as_completed(futures):
|
| 581 |
+
idx, row = future.result()
|
| 582 |
+
data[idx - 1] = row
|
| 583 |
+
processed += 1
|
| 584 |
+
|
| 585 |
+
if processed % 100 == 0 or processed == total:
|
| 586 |
+
print(f" Processed {processed}/{total} sentences ({100*processed/total:.1f}%)")
|
| 587 |
+
|
| 588 |
+
return data
|
| 589 |
+
|
| 590 |
+
|
| 591 |
+
def save_jsonl(data, filepath):
|
| 592 |
+
"""Save data as JSONL format."""
|
| 593 |
+
with open(filepath, "w", encoding="utf-8") as f:
|
| 594 |
+
for row in data:
|
| 595 |
+
f.write(json.dumps(row, ensure_ascii=False) + "\n")
|
| 596 |
+
|
| 597 |
+
|
| 598 |
+
def save_conllu(data, filepath):
|
| 599 |
+
"""Save data as CoNLL-U format."""
|
| 600 |
+
with open(filepath, "w", encoding="utf-8") as f:
|
| 601 |
+
for row in data:
|
| 602 |
+
f.write(f"# sent_id = {row['sent_id']}\n")
|
| 603 |
+
f.write(f"# text = {row['text']}\n")
|
| 604 |
+
for i in range(len(row['tokens'])):
|
| 605 |
+
# ID FORM LEMMA UPOS XPOS FEATS HEAD DEPREL DEPS MISC
|
| 606 |
+
line = "\t".join([
|
| 607 |
+
str(i + 1),
|
| 608 |
+
row['tokens'][i],
|
| 609 |
+
row['lemmas'][i],
|
| 610 |
+
row['upos'][i],
|
| 611 |
+
row['xpos'][i],
|
| 612 |
+
row['feats'][i],
|
| 613 |
+
row['head'][i],
|
| 614 |
+
row['deprel'][i],
|
| 615 |
+
row['deps'][i],
|
| 616 |
+
row['misc'][i]
|
| 617 |
+
])
|
| 618 |
+
f.write(line + "\n")
|
| 619 |
+
f.write("\n")
|
| 620 |
+
|
| 621 |
+
|
| 622 |
+
def main():
|
| 623 |
+
import argparse
|
| 624 |
+
import time
|
| 625 |
+
parser = argparse.ArgumentParser(description="Convert sentences to UD format")
|
| 626 |
+
parser.add_argument("--input", "-i", type=str, help="Input sentences file")
|
| 627 |
+
parser.add_argument("--output-dir", "-o", type=str, help="Output directory")
|
| 628 |
+
parser.add_argument("--prefix", "-p", type=str, default="train", help="Output file prefix")
|
| 629 |
+
parser.add_argument("--batch-size", "-b", type=int, default=64,
|
| 630 |
+
help="Batch size for GPU processing (default: 64, increase for more GPU usage)")
|
| 631 |
+
parser.add_argument("--parallel", action="store_true",
|
| 632 |
+
help="Use parallel processing with multiple workers")
|
| 633 |
+
parser.add_argument("--workers", "-w", type=int, default=4,
|
| 634 |
+
help="Number of workers for parallel processing (default: 4)")
|
| 635 |
+
args = parser.parse_args()
|
| 636 |
+
|
| 637 |
+
# Default paths
|
| 638 |
+
if args.input:
|
| 639 |
+
sentences_file = args.input
|
| 640 |
+
else:
|
| 641 |
+
source_folder = expanduser("~/Downloads/UD_Vietnamese-UUD-v0.1")
|
| 642 |
+
sentences_file = join(source_folder, "sentences.txt")
|
| 643 |
+
|
| 644 |
+
if args.output_dir:
|
| 645 |
+
output_dir = args.output_dir
|
| 646 |
+
else:
|
| 647 |
+
output_dir = dirname(sentences_file)
|
| 648 |
+
|
| 649 |
+
print("Loading sentences...")
|
| 650 |
+
sentences = load_sentences(sentences_file)
|
| 651 |
+
print(f"Loaded {len(sentences)} sentences")
|
| 652 |
+
|
| 653 |
+
# Check GPU availability
|
| 654 |
+
if torch.cuda.is_available():
|
| 655 |
+
print(f"GPU: {torch.cuda.get_device_name(0)}")
|
| 656 |
+
print(f"GPU Memory: {torch.cuda.get_device_properties(0).total_memory / 1024**3:.1f} GB")
|
| 657 |
+
else:
|
| 658 |
+
print("GPU: Not available (using CPU)")
|
| 659 |
+
|
| 660 |
+
print(f"\nConverting to UD format (batch_size={args.batch_size})...")
|
| 661 |
+
start_time = time.time()
|
| 662 |
+
|
| 663 |
+
if args.parallel:
|
| 664 |
+
data = convert_to_ud_format_parallel(sentences, num_workers=args.workers)
|
| 665 |
+
else:
|
| 666 |
+
data = convert_to_ud_format(sentences, batch_size=args.batch_size)
|
| 667 |
+
|
| 668 |
+
elapsed = time.time() - start_time
|
| 669 |
+
speed = len(sentences) / elapsed
|
| 670 |
+
print(f"\nCompleted in {elapsed:.1f}s ({speed:.1f} sentences/sec)")
|
| 671 |
+
|
| 672 |
+
# Save as JSONL (for HuggingFace)
|
| 673 |
+
jsonl_file = join(output_dir, f"{args.prefix}.jsonl")
|
| 674 |
+
save_jsonl(data, jsonl_file)
|
| 675 |
+
print(f"Saved JSONL to: {jsonl_file}")
|
| 676 |
+
|
| 677 |
+
# Save as CoNLL-U (standard UD format)
|
| 678 |
+
conllu_file = join(output_dir, f"{args.prefix}.conllu")
|
| 679 |
+
save_conllu(data, conllu_file)
|
| 680 |
+
print(f"Saved CoNLL-U to: {conllu_file}")
|
| 681 |
+
|
| 682 |
+
# Print sample
|
| 683 |
+
print("\nSample row:")
|
| 684 |
+
sample = data[0]
|
| 685 |
+
print(f" sent_id: {sample['sent_id']}")
|
| 686 |
+
print(f" text: {sample['text'][:60]}...")
|
| 687 |
+
print(f" tokens: {sample['tokens'][:5]}...")
|
| 688 |
+
print(f" upos: {sample['upos'][:5]}...")
|
| 689 |
+
|
| 690 |
+
|
| 691 |
+
if __name__ == "__main__":
|
| 692 |
+
main()
|
src/fetch_data.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Fetch data from HuggingFace dataset undertheseanlp/UTS_VLC
|
| 3 |
+
- Get documents from law dataset
|
| 4 |
+
- Segment sentences using underthesea
|
| 5 |
+
- Get first 8000 sentences
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import re
|
| 9 |
+
from os.path import dirname, join
|
| 10 |
+
|
| 11 |
+
from datasets import load_dataset
|
| 12 |
+
|
| 13 |
+
from underthesea import sent_tokenize, text_normalize
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def clean_text(text):
|
| 17 |
+
"""Remove markdown formatting and clean text."""
|
| 18 |
+
# Normalize Unicode using underthesea
|
| 19 |
+
text = text_normalize(text)
|
| 20 |
+
# Remove markdown headers
|
| 21 |
+
text = re.sub(r'^#+\s+', '', text, flags=re.MULTILINE)
|
| 22 |
+
# Remove bold/italic markers
|
| 23 |
+
text = re.sub(r'\*+', '', text)
|
| 24 |
+
# Remove horizontal rules
|
| 25 |
+
text = re.sub(r'^-+$', '', text, flags=re.MULTILINE)
|
| 26 |
+
# Remove links
|
| 27 |
+
text = re.sub(r'\[([^\]]+)\]\([^)]+\)', r'\1', text)
|
| 28 |
+
# Remove multiple newlines
|
| 29 |
+
text = re.sub(r'\n{2,}', '\n', text)
|
| 30 |
+
# Remove leading/trailing whitespace per line
|
| 31 |
+
lines = [line.strip() for line in text.split('\n')]
|
| 32 |
+
text = '\n'.join(lines)
|
| 33 |
+
return text
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def is_valid_sentence(sent):
|
| 37 |
+
"""Check if sentence is valid for UD annotation."""
|
| 38 |
+
sent = sent.strip()
|
| 39 |
+
# Remove trailing list markers like "1." or "a)"
|
| 40 |
+
sent = re.sub(r'\n\d+\.$', '', sent)
|
| 41 |
+
sent = re.sub(r'\n[a-z]\)$', '', sent)
|
| 42 |
+
sent = sent.strip()
|
| 43 |
+
|
| 44 |
+
if not sent:
|
| 45 |
+
return False, sent
|
| 46 |
+
# Too short
|
| 47 |
+
if len(sent) < 20:
|
| 48 |
+
return False, sent
|
| 49 |
+
# Too long
|
| 50 |
+
if len(sent) > 300:
|
| 51 |
+
return False, sent
|
| 52 |
+
# Skip headers (all caps, or starts with "Điều", "Chương", etc.)
|
| 53 |
+
if re.match(r'^(QUỐC HỘI|CỘNG HÒA|Độc lập|Phần thứ|Chương [IVX]+|MỤC \d+)', sent):
|
| 54 |
+
return False, sent
|
| 55 |
+
# Skip article titles
|
| 56 |
+
if re.match(r'^(Điều \d+|Khoản \d+|Mục \d+)', sent):
|
| 57 |
+
return False, sent
|
| 58 |
+
# Skip if mostly uppercase
|
| 59 |
+
if sum(1 for c in sent if c.isupper()) > len(sent) * 0.5:
|
| 60 |
+
return False, sent
|
| 61 |
+
# Skip if starts with special markers
|
| 62 |
+
if sent.startswith(('English:', 'Số hiệu:', 'Ngày hiệu lực:', '---', '|')):
|
| 63 |
+
return False, sent
|
| 64 |
+
# Must contain Vietnamese characters
|
| 65 |
+
if not re.search(r'[àáảãạăắằẳẵặâấầẩẫậèéẻẽẹêếềểễệìíỉĩịòóỏõọôốồổỗộơớờởỡợùúủũụưứừửữựỳýỷỹỵđ]', sent, re.IGNORECASE):
|
| 66 |
+
return False, sent
|
| 67 |
+
# Skip if ends with just a number (incomplete sentence)
|
| 68 |
+
if re.search(r'\n\d+$', sent):
|
| 69 |
+
return False, sent
|
| 70 |
+
return True, sent
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def fetch_and_process():
|
| 74 |
+
# Load dataset from HuggingFace
|
| 75 |
+
print("Loading dataset from HuggingFace...")
|
| 76 |
+
ds = load_dataset("undertheseanlp/UTS_VLC", split="2026")
|
| 77 |
+
|
| 78 |
+
# Segment sentences from all documents until we have 8000
|
| 79 |
+
print("Segmenting sentences...")
|
| 80 |
+
all_sentences = []
|
| 81 |
+
for idx, doc in enumerate(ds):
|
| 82 |
+
content = doc["content"]
|
| 83 |
+
content = clean_text(content)
|
| 84 |
+
sentences = sent_tokenize(content)
|
| 85 |
+
for sent in sentences:
|
| 86 |
+
sent = sent.strip()
|
| 87 |
+
is_valid, cleaned_sent = is_valid_sentence(sent)
|
| 88 |
+
if is_valid:
|
| 89 |
+
all_sentences.append(cleaned_sent)
|
| 90 |
+
if len(all_sentences) >= 8000:
|
| 91 |
+
print(f"Processed {idx + 1} documents")
|
| 92 |
+
break
|
| 93 |
+
|
| 94 |
+
# Get first 8000 sentences
|
| 95 |
+
sentences_out = all_sentences[:8000]
|
| 96 |
+
print(f"Total sentences collected: {len(sentences_out)}")
|
| 97 |
+
|
| 98 |
+
# Save to output file
|
| 99 |
+
output_dir = dirname(dirname(__file__))
|
| 100 |
+
output_file = join(output_dir, "sentences_vlc.txt")
|
| 101 |
+
|
| 102 |
+
with open(output_file, "w", encoding="utf-8") as f:
|
| 103 |
+
for i, sent in enumerate(sentences_out, 1):
|
| 104 |
+
f.write(f"{i}\t{sent}\n")
|
| 105 |
+
|
| 106 |
+
print(f"Saved to: {output_file}")
|
| 107 |
+
|
| 108 |
+
# Print sample
|
| 109 |
+
print("\nSample sentences:")
|
| 110 |
+
for i, sent in enumerate(sentences_out[:5], 1):
|
| 111 |
+
print(f" {i}. {sent[:80]}...")
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
if __name__ == "__main__":
|
| 115 |
+
fetch_and_process()
|
src/fetch_uvb_data.py
ADDED
|
@@ -0,0 +1,250 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Fetch data from HuggingFace dataset undertheseanlp/UVB-v0.1
|
| 3 |
+
- Get 8,000 high-quality sentences from fiction books
|
| 4 |
+
- Get 8,000 high-quality sentences from non-fiction books
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import re
|
| 8 |
+
from os.path import dirname, join
|
| 9 |
+
|
| 10 |
+
from datasets import load_dataset
|
| 11 |
+
from underthesea import sent_tokenize, text_normalize
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
# Fiction-related genres
|
| 15 |
+
FICTION_GENRES = {
|
| 16 |
+
"Fiction", "Novels", "Romance", "Fantasy", "Science Fiction",
|
| 17 |
+
"Mystery", "Thriller", "Horror", "Historical Fiction", "Literary Fiction",
|
| 18 |
+
"Adventure", "Crime", "Suspense", "Drama", "Short Stories"
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
# Non-fiction related genres
|
| 22 |
+
NON_FICTION_GENRES = {
|
| 23 |
+
"Non Fiction", "Nonfiction", "History", "Biography", "Autobiography",
|
| 24 |
+
"Self Help", "Psychology", "Philosophy", "Science", "Politics",
|
| 25 |
+
"Economics", "Business", "Education", "Travel", "Memoir",
|
| 26 |
+
"Essays", "Reference", "Health", "Religion", "Spirituality"
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def clean_text(text):
|
| 31 |
+
"""Remove formatting and clean text."""
|
| 32 |
+
# Normalize Unicode using underthesea
|
| 33 |
+
text = text_normalize(text)
|
| 34 |
+
# Remove markdown headers
|
| 35 |
+
text = re.sub(r'^#+\s+', '', text, flags=re.MULTILINE)
|
| 36 |
+
# Remove bold/italic markers
|
| 37 |
+
text = re.sub(r'\*+', '', text)
|
| 38 |
+
# Remove horizontal rules
|
| 39 |
+
text = re.sub(r'^-+$', '', text, flags=re.MULTILINE)
|
| 40 |
+
# Remove links
|
| 41 |
+
text = re.sub(r'\[([^\]]+)\]\([^)]+\)', r'\1', text)
|
| 42 |
+
# Remove multiple newlines
|
| 43 |
+
text = re.sub(r'\n{2,}', '\n', text)
|
| 44 |
+
# Remove leading/trailing whitespace per line
|
| 45 |
+
lines = [line.strip() for line in text.split('\n')]
|
| 46 |
+
text = '\n'.join(lines)
|
| 47 |
+
return text
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def is_high_quality_sentence(sent):
|
| 51 |
+
"""Check if sentence is high quality for UD annotation."""
|
| 52 |
+
sent = sent.strip()
|
| 53 |
+
|
| 54 |
+
if not sent:
|
| 55 |
+
return False, sent
|
| 56 |
+
|
| 57 |
+
# Length constraints
|
| 58 |
+
if len(sent) < 30: # Minimum length for meaningful sentence
|
| 59 |
+
return False, sent
|
| 60 |
+
if len(sent) > 250: # Maximum length
|
| 61 |
+
return False, sent
|
| 62 |
+
|
| 63 |
+
# Word count constraints
|
| 64 |
+
words = sent.split()
|
| 65 |
+
if len(words) < 5: # At least 5 words
|
| 66 |
+
return False, sent
|
| 67 |
+
if len(words) > 40: # Max 40 words
|
| 68 |
+
return False, sent
|
| 69 |
+
|
| 70 |
+
# Must start with uppercase letter (proper sentence)
|
| 71 |
+
if not sent[0].isupper():
|
| 72 |
+
return False, sent
|
| 73 |
+
|
| 74 |
+
# Must end with proper punctuation
|
| 75 |
+
if not sent.rstrip()[-1] in '.!?…"»':
|
| 76 |
+
return False, sent
|
| 77 |
+
|
| 78 |
+
# Skip if mostly uppercase (headers, titles)
|
| 79 |
+
if sum(1 for c in sent if c.isupper()) > len(sent) * 0.3:
|
| 80 |
+
return False, sent
|
| 81 |
+
|
| 82 |
+
# Must contain Vietnamese characters
|
| 83 |
+
if not re.search(r'[àáảãạăắằẳẵặâấầẩẫậèéẻẽẹêếềểễệìíỉĩịòóỏõọôốồổỗộơớờởỡợùúủũụưứừửữựỳýỷỹỵđ]', sent, re.IGNORECASE):
|
| 84 |
+
return False, sent
|
| 85 |
+
|
| 86 |
+
# Skip sentences with too many numbers (tables, lists)
|
| 87 |
+
num_digits = sum(1 for c in sent if c.isdigit())
|
| 88 |
+
if num_digits > len(sent) * 0.15:
|
| 89 |
+
return False, sent
|
| 90 |
+
|
| 91 |
+
# Skip sentences with special patterns
|
| 92 |
+
if re.match(r'^(Chương|Phần|Mục|Điều|\d+\.|\([a-z]\))', sent):
|
| 93 |
+
return False, sent
|
| 94 |
+
|
| 95 |
+
# Skip sentences with URLs or emails
|
| 96 |
+
if re.search(r'(http|www\.|@|\.com|\.vn)', sent, re.IGNORECASE):
|
| 97 |
+
return False, sent
|
| 98 |
+
|
| 99 |
+
# Skip sentences with excessive punctuation
|
| 100 |
+
punct_count = sum(1 for c in sent if c in '.,;:!?-–—()[]{}""\'\'«»')
|
| 101 |
+
if punct_count > len(words) * 1.5:
|
| 102 |
+
return False, sent
|
| 103 |
+
|
| 104 |
+
# Skip incomplete sentences (ending with ellipsis in middle)
|
| 105 |
+
if '...' in sent[:-5]:
|
| 106 |
+
return False, sent
|
| 107 |
+
|
| 108 |
+
# Skip dialogue-heavy sentences (too many quotes)
|
| 109 |
+
quote_count = sent.count('"') + sent.count('"') + sent.count('"')
|
| 110 |
+
if quote_count > 4:
|
| 111 |
+
return False, sent
|
| 112 |
+
|
| 113 |
+
return True, sent
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def classify_book(genres):
|
| 117 |
+
"""Classify book as fiction or non-fiction based on genres."""
|
| 118 |
+
if not genres:
|
| 119 |
+
return None
|
| 120 |
+
|
| 121 |
+
genres_set = set(genres)
|
| 122 |
+
|
| 123 |
+
is_fiction = bool(genres_set & FICTION_GENRES)
|
| 124 |
+
is_non_fiction = bool(genres_set & NON_FICTION_GENRES)
|
| 125 |
+
|
| 126 |
+
if is_fiction and not is_non_fiction:
|
| 127 |
+
return "fiction"
|
| 128 |
+
elif is_non_fiction and not is_fiction:
|
| 129 |
+
return "non-fiction"
|
| 130 |
+
elif is_fiction and is_non_fiction:
|
| 131 |
+
# Prefer the dominant one
|
| 132 |
+
fiction_count = len(genres_set & FICTION_GENRES)
|
| 133 |
+
non_fiction_count = len(genres_set & NON_FICTION_GENRES)
|
| 134 |
+
return "fiction" if fiction_count > non_fiction_count else "non-fiction"
|
| 135 |
+
|
| 136 |
+
return None
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def extract_sentences_from_book(content, max_sentences=500):
|
| 140 |
+
"""Extract high-quality sentences from book content."""
|
| 141 |
+
content = clean_text(content)
|
| 142 |
+
sentences = sent_tokenize(content)
|
| 143 |
+
|
| 144 |
+
valid_sentences = []
|
| 145 |
+
for sent in sentences:
|
| 146 |
+
is_valid, cleaned_sent = is_high_quality_sentence(sent)
|
| 147 |
+
if is_valid:
|
| 148 |
+
valid_sentences.append(cleaned_sent)
|
| 149 |
+
if len(valid_sentences) >= max_sentences:
|
| 150 |
+
break
|
| 151 |
+
|
| 152 |
+
return valid_sentences
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def fetch_and_process():
|
| 156 |
+
print("Loading UVB-v0.1 dataset from HuggingFace...")
|
| 157 |
+
ds = load_dataset("undertheseanlp/UVB-v0.1", split="train")
|
| 158 |
+
|
| 159 |
+
print(f"Total books in dataset: {len(ds)}")
|
| 160 |
+
|
| 161 |
+
# Classify books
|
| 162 |
+
fiction_books = []
|
| 163 |
+
non_fiction_books = []
|
| 164 |
+
|
| 165 |
+
for book in ds:
|
| 166 |
+
genres = book.get("genres", [])
|
| 167 |
+
rating = book.get("goodreads_rating", 0) or 0
|
| 168 |
+
num_ratings = book.get("goodreads_num_ratings", 0) or 0
|
| 169 |
+
|
| 170 |
+
# Quality filter: prefer books with good ratings
|
| 171 |
+
quality_score = rating * min(num_ratings / 100, 10) # Weight by rating count
|
| 172 |
+
|
| 173 |
+
book_type = classify_book(genres)
|
| 174 |
+
book_info = {
|
| 175 |
+
"title": book["title"],
|
| 176 |
+
"content": book["content"],
|
| 177 |
+
"rating": rating,
|
| 178 |
+
"num_ratings": num_ratings,
|
| 179 |
+
"quality_score": quality_score,
|
| 180 |
+
"genres": genres
|
| 181 |
+
}
|
| 182 |
+
|
| 183 |
+
if book_type == "fiction":
|
| 184 |
+
fiction_books.append(book_info)
|
| 185 |
+
elif book_type == "non-fiction":
|
| 186 |
+
non_fiction_books.append(book_info)
|
| 187 |
+
|
| 188 |
+
print(f"Fiction books: {len(fiction_books)}")
|
| 189 |
+
print(f"Non-fiction books: {len(non_fiction_books)}")
|
| 190 |
+
|
| 191 |
+
# Sort by quality score (higher is better)
|
| 192 |
+
fiction_books.sort(key=lambda x: x["quality_score"], reverse=True)
|
| 193 |
+
non_fiction_books.sort(key=lambda x: x["quality_score"], reverse=True)
|
| 194 |
+
|
| 195 |
+
# Extract sentences from fiction books
|
| 196 |
+
print("\nExtracting sentences from fiction books...")
|
| 197 |
+
fiction_sentences = []
|
| 198 |
+
for i, book in enumerate(fiction_books):
|
| 199 |
+
if len(fiction_sentences) >= 8000:
|
| 200 |
+
break
|
| 201 |
+
sentences = extract_sentences_from_book(book["content"])
|
| 202 |
+
for sent in sentences:
|
| 203 |
+
if len(fiction_sentences) >= 8000:
|
| 204 |
+
break
|
| 205 |
+
fiction_sentences.append(sent)
|
| 206 |
+
print(f" [{i+1}/{len(fiction_books)}] {book['title'][:50]} - {len(sentences)} sentences (total: {len(fiction_sentences)})")
|
| 207 |
+
|
| 208 |
+
# Extract sentences from non-fiction books
|
| 209 |
+
print("\nExtracting sentences from non-fiction books...")
|
| 210 |
+
non_fiction_sentences = []
|
| 211 |
+
for i, book in enumerate(non_fiction_books):
|
| 212 |
+
if len(non_fiction_sentences) >= 8000:
|
| 213 |
+
break
|
| 214 |
+
sentences = extract_sentences_from_book(book["content"])
|
| 215 |
+
for sent in sentences:
|
| 216 |
+
if len(non_fiction_sentences) >= 8000:
|
| 217 |
+
break
|
| 218 |
+
non_fiction_sentences.append(sent)
|
| 219 |
+
print(f" [{i+1}/{len(non_fiction_books)}] {book['title'][:50]} - {len(sentences)} sentences (total: {len(non_fiction_sentences)})")
|
| 220 |
+
|
| 221 |
+
print(f"\nFiction sentences collected: {len(fiction_sentences)}")
|
| 222 |
+
print(f"Non-fiction sentences collected: {len(non_fiction_sentences)}")
|
| 223 |
+
|
| 224 |
+
# Combine all sentences
|
| 225 |
+
all_sentences = fiction_sentences[:8000] + non_fiction_sentences[:8000]
|
| 226 |
+
print(f"Total sentences: {len(all_sentences)}")
|
| 227 |
+
|
| 228 |
+
# Save to output file
|
| 229 |
+
output_dir = dirname(dirname(__file__))
|
| 230 |
+
output_file = join(output_dir, "sentences_uvb.txt")
|
| 231 |
+
|
| 232 |
+
with open(output_file, "w", encoding="utf-8") as f:
|
| 233 |
+
for i, sent in enumerate(all_sentences, 1):
|
| 234 |
+
source = "fiction" if i <= len(fiction_sentences[:8000]) else "non-fiction"
|
| 235 |
+
f.write(f"{i}\t{source}\t{sent}\n")
|
| 236 |
+
|
| 237 |
+
print(f"\nSaved to: {output_file}")
|
| 238 |
+
|
| 239 |
+
# Print samples
|
| 240 |
+
print("\nSample fiction sentences:")
|
| 241 |
+
for i, sent in enumerate(fiction_sentences[:3], 1):
|
| 242 |
+
print(f" {i}. {sent[:100]}...")
|
| 243 |
+
|
| 244 |
+
print("\nSample non-fiction sentences:")
|
| 245 |
+
for i, sent in enumerate(non_fiction_sentences[:3], 1):
|
| 246 |
+
print(f" {i}. {sent[:100]}...")
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
if __name__ == "__main__":
|
| 250 |
+
fetch_and_process()
|
src/fetch_uvn_data.py
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Fetch data from HuggingFace dataset undertheseanlp/UVN-1
|
| 3 |
+
- Get documents from news dataset
|
| 4 |
+
- Segment sentences using underthesea
|
| 5 |
+
- Get first 8000 sentences
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import re
|
| 9 |
+
from os.path import dirname, join
|
| 10 |
+
|
| 11 |
+
from datasets import load_dataset
|
| 12 |
+
|
| 13 |
+
from underthesea import sent_tokenize, text_normalize
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def clean_text(text):
|
| 17 |
+
"""Remove formatting and clean text."""
|
| 18 |
+
# Normalize Unicode using underthesea
|
| 19 |
+
text = text_normalize(text)
|
| 20 |
+
# Remove markdown headers
|
| 21 |
+
text = re.sub(r'^#+\s+', '', text, flags=re.MULTILINE)
|
| 22 |
+
# Remove bold/italic markers
|
| 23 |
+
text = re.sub(r'\*+', '', text)
|
| 24 |
+
# Remove horizontal rules
|
| 25 |
+
text = re.sub(r'^-+$', '', text, flags=re.MULTILINE)
|
| 26 |
+
# Remove links
|
| 27 |
+
text = re.sub(r'\[([^\]]+)\]\([^)]+\)', r'\1', text)
|
| 28 |
+
# Remove multiple newlines
|
| 29 |
+
text = re.sub(r'\n{2,}', '\n', text)
|
| 30 |
+
# Remove leading/trailing whitespace per line
|
| 31 |
+
lines = [line.strip() for line in text.split('\n')]
|
| 32 |
+
text = '\n'.join(lines)
|
| 33 |
+
return text
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def is_valid_sentence(sent):
|
| 37 |
+
"""Check if sentence is valid for UD annotation."""
|
| 38 |
+
sent = sent.strip()
|
| 39 |
+
|
| 40 |
+
if not sent:
|
| 41 |
+
return False, sent
|
| 42 |
+
# Too short
|
| 43 |
+
if len(sent) < 20:
|
| 44 |
+
return False, sent
|
| 45 |
+
# Too long
|
| 46 |
+
if len(sent) > 300:
|
| 47 |
+
return False, sent
|
| 48 |
+
# Must contain Vietnamese characters
|
| 49 |
+
if not re.search(r'[àáảãạăắằẳẵặâấầẩẫậèéẻẽẹêếềểễệìíỉĩịòóỏõọôốồổỗộơớờởỡợùúủũụưứừửữựỳýỷỹỵđ]', sent, re.IGNORECASE):
|
| 50 |
+
return False, sent
|
| 51 |
+
# Skip if mostly uppercase (headers, titles)
|
| 52 |
+
if sum(1 for c in sent if c.isupper()) > len(sent) * 0.5:
|
| 53 |
+
return False, sent
|
| 54 |
+
# Skip bylines (e.g., "Theo VnExpress", "PV/Báo ...")
|
| 55 |
+
if re.match(r'^(Theo |PV |Nguồn:|Ảnh:|Video:|Bài:|Tin ảnh:)', sent):
|
| 56 |
+
return False, sent
|
| 57 |
+
# Skip photo captions (short sentences ending with source attribution)
|
| 58 |
+
if re.search(r'\(Ảnh:.*\)$', sent):
|
| 59 |
+
return False, sent
|
| 60 |
+
if re.search(r'\(Nguồn:.*\)$', sent):
|
| 61 |
+
return False, sent
|
| 62 |
+
# Skip date/time patterns at start
|
| 63 |
+
if re.match(r'^\d{1,2}/\d{1,2}/\d{4}', sent):
|
| 64 |
+
return False, sent
|
| 65 |
+
if re.match(r'^\d{1,2}:\d{2}', sent):
|
| 66 |
+
return False, sent
|
| 67 |
+
# Skip sentences with URLs
|
| 68 |
+
if re.search(r'(http|www\.|\.com|\.vn)', sent, re.IGNORECASE):
|
| 69 |
+
return False, sent
|
| 70 |
+
# Skip sentences that are just tags or categories
|
| 71 |
+
if re.match(r'^(Tags?:|Chuyên mục:|Từ khóa:)', sent, re.IGNORECASE):
|
| 72 |
+
return False, sent
|
| 73 |
+
# Skip sentences with excessive numbers (data tables)
|
| 74 |
+
num_digits = sum(1 for c in sent if c.isdigit())
|
| 75 |
+
if num_digits > len(sent) * 0.3:
|
| 76 |
+
return False, sent
|
| 77 |
+
return True, sent
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
TARGET_COUNT = 8000
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def fetch_and_process():
|
| 84 |
+
# Load dataset from HuggingFace
|
| 85 |
+
print("Loading UVN-1 dataset from HuggingFace...")
|
| 86 |
+
ds = load_dataset("undertheseanlp/UVN-1", split="train")
|
| 87 |
+
|
| 88 |
+
print(f"Total articles in dataset: {len(ds)}")
|
| 89 |
+
|
| 90 |
+
# Segment sentences from all documents until we have enough
|
| 91 |
+
print("Segmenting sentences...")
|
| 92 |
+
all_sentences = []
|
| 93 |
+
for idx, doc in enumerate(ds):
|
| 94 |
+
content = doc["content"]
|
| 95 |
+
content = clean_text(content)
|
| 96 |
+
sentences = sent_tokenize(content)
|
| 97 |
+
for sent in sentences:
|
| 98 |
+
sent = sent.strip()
|
| 99 |
+
is_valid, cleaned_sent = is_valid_sentence(sent)
|
| 100 |
+
if is_valid:
|
| 101 |
+
all_sentences.append(cleaned_sent)
|
| 102 |
+
if len(all_sentences) >= TARGET_COUNT:
|
| 103 |
+
print(f"Processed {idx + 1} documents")
|
| 104 |
+
break
|
| 105 |
+
|
| 106 |
+
# Get first TARGET_COUNT sentences
|
| 107 |
+
sentences_out = all_sentences[:TARGET_COUNT]
|
| 108 |
+
print(f"Total sentences collected: {len(sentences_out)}")
|
| 109 |
+
|
| 110 |
+
# Save to output file
|
| 111 |
+
output_dir = dirname(dirname(__file__))
|
| 112 |
+
output_file = join(output_dir, "sentences_uvn.txt")
|
| 113 |
+
|
| 114 |
+
with open(output_file, "w", encoding="utf-8") as f:
|
| 115 |
+
for i, sent in enumerate(sentences_out, 1):
|
| 116 |
+
f.write(f"{i}\t{sent}\n")
|
| 117 |
+
|
| 118 |
+
print(f"Saved to: {output_file}")
|
| 119 |
+
|
| 120 |
+
# Print sample
|
| 121 |
+
print("\nSample sentences:")
|
| 122 |
+
for i, sent in enumerate(sentences_out[:5], 1):
|
| 123 |
+
print(f" {i}. {sent[:80]}...")
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
if __name__ == "__main__":
|
| 127 |
+
fetch_and_process()
|
src/fetch_uvw_data.py
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Fetch data from HuggingFace dataset undertheseanlp/UVW-2026
|
| 3 |
+
- Get articles with quality_score >= 5
|
| 4 |
+
- Segment sentences using underthesea
|
| 5 |
+
- Get first 8000 sentences
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import re
|
| 9 |
+
from os.path import dirname, join
|
| 10 |
+
|
| 11 |
+
from datasets import load_dataset
|
| 12 |
+
|
| 13 |
+
from underthesea import sent_tokenize, text_normalize
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def clean_text(text):
|
| 17 |
+
"""Remove formatting and clean text."""
|
| 18 |
+
# Normalize Unicode using underthesea
|
| 19 |
+
text = text_normalize(text)
|
| 20 |
+
# Remove markdown headers
|
| 21 |
+
text = re.sub(r'^#+\s+', '', text, flags=re.MULTILINE)
|
| 22 |
+
# Remove bold/italic markers
|
| 23 |
+
text = re.sub(r'\*+', '', text)
|
| 24 |
+
# Remove horizontal rules
|
| 25 |
+
text = re.sub(r'^-+$', '', text, flags=re.MULTILINE)
|
| 26 |
+
# Remove links
|
| 27 |
+
text = re.sub(r'\[([^\]]+)\]\([^)]+\)', r'\1', text)
|
| 28 |
+
# Remove multiple newlines
|
| 29 |
+
text = re.sub(r'\n{2,}', '\n', text)
|
| 30 |
+
# Remove leading/trailing whitespace per line
|
| 31 |
+
lines = [line.strip() for line in text.split('\n')]
|
| 32 |
+
text = '\n'.join(lines)
|
| 33 |
+
return text
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def is_valid_sentence(sent):
|
| 37 |
+
"""Check if sentence is valid for UD annotation."""
|
| 38 |
+
sent = sent.strip()
|
| 39 |
+
|
| 40 |
+
if not sent:
|
| 41 |
+
return False, sent
|
| 42 |
+
# Too short
|
| 43 |
+
if len(sent) < 20:
|
| 44 |
+
return False, sent
|
| 45 |
+
# Too long
|
| 46 |
+
if len(sent) > 300:
|
| 47 |
+
return False, sent
|
| 48 |
+
# Must contain Vietnamese characters
|
| 49 |
+
if not re.search(r'[àáảãạăắằẳẵặâấầẩẫậèéẻẽẹêếềểễệìíỉĩịòóỏõọôốồổỗộơớờởỡợùúủũụưứừửữựỳýỷỹỵđ]', sent, re.IGNORECASE):
|
| 50 |
+
return False, sent
|
| 51 |
+
# Skip if mostly uppercase (headers, titles)
|
| 52 |
+
if sum(1 for c in sent if c.isupper()) > len(sent) * 0.5:
|
| 53 |
+
return False, sent
|
| 54 |
+
# Skip Wikipedia stub markers
|
| 55 |
+
if re.search(r'(bài sơ khai|sơ khai về|cần được mở rộng|Thể loại:)', sent):
|
| 56 |
+
return False, sent
|
| 57 |
+
# Skip category lists
|
| 58 |
+
if re.match(r'^(Thể loại|Danh sách|Xem thêm|Tham khảo|Liên kết ngoài|Chú thích)', sent):
|
| 59 |
+
return False, sent
|
| 60 |
+
# Skip infobox remnants (pipe-separated values, key=value patterns)
|
| 61 |
+
if sent.count('|') > 2:
|
| 62 |
+
return False, sent
|
| 63 |
+
if re.search(r'\w+=\w+', sent) and sent.count('=') > 1:
|
| 64 |
+
return False, sent
|
| 65 |
+
# Skip reference fragments ([1], [cần dẫn nguồn])
|
| 66 |
+
if re.search(r'\[\d+\]', sent):
|
| 67 |
+
return False, sent
|
| 68 |
+
if re.search(r'\[cần', sent):
|
| 69 |
+
return False, sent
|
| 70 |
+
# Skip sentences with URLs
|
| 71 |
+
if re.search(r'(http|www\.|\.com|\.org)', sent, re.IGNORECASE):
|
| 72 |
+
return False, sent
|
| 73 |
+
# Skip sentences with excessive numbers (data tables)
|
| 74 |
+
num_digits = sum(1 for c in sent if c.isdigit())
|
| 75 |
+
if num_digits > len(sent) * 0.3:
|
| 76 |
+
return False, sent
|
| 77 |
+
# Skip list items starting with bullets or numbers
|
| 78 |
+
if re.match(r'^[\*\-•]\s', sent):
|
| 79 |
+
return False, sent
|
| 80 |
+
return True, sent
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
TARGET_COUNT = 8000
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def fetch_and_process():
|
| 87 |
+
# Load dataset from HuggingFace
|
| 88 |
+
print("Loading UVW-2026 dataset from HuggingFace...")
|
| 89 |
+
ds = load_dataset("undertheseanlp/UVW-2026", split="train")
|
| 90 |
+
|
| 91 |
+
print(f"Total articles in dataset: {len(ds)}")
|
| 92 |
+
|
| 93 |
+
# Filter by quality score
|
| 94 |
+
print("Filtering articles by quality_score >= 5...")
|
| 95 |
+
high_quality = [doc for doc in ds if (doc.get("quality_score") or 0) >= 5]
|
| 96 |
+
print(f"High-quality articles: {len(high_quality)}")
|
| 97 |
+
|
| 98 |
+
# Segment sentences from all documents until we have enough
|
| 99 |
+
print("Segmenting sentences...")
|
| 100 |
+
all_sentences = []
|
| 101 |
+
for idx, doc in enumerate(high_quality):
|
| 102 |
+
content = doc["content"]
|
| 103 |
+
content = clean_text(content)
|
| 104 |
+
sentences = sent_tokenize(content)
|
| 105 |
+
for sent in sentences:
|
| 106 |
+
sent = sent.strip()
|
| 107 |
+
is_valid, cleaned_sent = is_valid_sentence(sent)
|
| 108 |
+
if is_valid:
|
| 109 |
+
all_sentences.append(cleaned_sent)
|
| 110 |
+
if len(all_sentences) >= TARGET_COUNT:
|
| 111 |
+
print(f"Processed {idx + 1} articles")
|
| 112 |
+
break
|
| 113 |
+
|
| 114 |
+
# Get first TARGET_COUNT sentences
|
| 115 |
+
sentences_out = all_sentences[:TARGET_COUNT]
|
| 116 |
+
print(f"Total sentences collected: {len(sentences_out)}")
|
| 117 |
+
|
| 118 |
+
# Save to output file
|
| 119 |
+
output_dir = dirname(dirname(__file__))
|
| 120 |
+
output_file = join(output_dir, "sentences_uvw.txt")
|
| 121 |
+
|
| 122 |
+
with open(output_file, "w", encoding="utf-8") as f:
|
| 123 |
+
for i, sent in enumerate(sentences_out, 1):
|
| 124 |
+
f.write(f"{i}\t{sent}\n")
|
| 125 |
+
|
| 126 |
+
print(f"Saved to: {output_file}")
|
| 127 |
+
|
| 128 |
+
# Print sample
|
| 129 |
+
print("\nSample sentences:")
|
| 130 |
+
for i, sent in enumerate(sentences_out[:5], 1):
|
| 131 |
+
print(f" {i}. {sent[:80]}...")
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
if __name__ == "__main__":
|
| 135 |
+
fetch_and_process()
|
src/upload_to_hf.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Upload UD dataset to HuggingFace Hub.
|
| 3 |
+
Dataset: undertheseanlp/UDD-v0.1
|
| 4 |
+
|
| 5 |
+
Loads train/dev/test JSONL splits and uploads as DatasetDict with domain field.
|
| 6 |
+
|
| 7 |
+
Usage:
|
| 8 |
+
export $(cat .env | xargs) && python upload_to_hf.py
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
import json
|
| 12 |
+
import os
|
| 13 |
+
from os.path import expanduser, join
|
| 14 |
+
|
| 15 |
+
from datasets import Dataset, DatasetDict
|
| 16 |
+
from huggingface_hub import HfApi, login
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
# Sent_id prefix -> domain mapping
|
| 20 |
+
DOMAIN_MAP = {
|
| 21 |
+
"vlc-": "legal",
|
| 22 |
+
"uvn-": "news",
|
| 23 |
+
"uvw-": "wikipedia",
|
| 24 |
+
"uvb-f-": "fiction",
|
| 25 |
+
"uvb-n-": "non-fiction",
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def get_domain(sent_id):
|
| 30 |
+
"""Extract domain from sent_id prefix."""
|
| 31 |
+
for prefix, domain in DOMAIN_MAP.items():
|
| 32 |
+
if sent_id.startswith(prefix):
|
| 33 |
+
return domain
|
| 34 |
+
return "unknown"
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def load_jsonl(filepath):
|
| 38 |
+
"""Load JSONL file and add domain field."""
|
| 39 |
+
data = []
|
| 40 |
+
with open(filepath, "r", encoding="utf-8") as f:
|
| 41 |
+
for line in f:
|
| 42 |
+
row = json.loads(line)
|
| 43 |
+
row["domain"] = get_domain(row.get("sent_id", ""))
|
| 44 |
+
data.append(row)
|
| 45 |
+
return data
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def main():
|
| 49 |
+
# Login with token from environment
|
| 50 |
+
token = os.environ.get("HF_TOKEN")
|
| 51 |
+
if token:
|
| 52 |
+
print("Logging in with HF_TOKEN...")
|
| 53 |
+
login(token=token)
|
| 54 |
+
else:
|
| 55 |
+
print("Warning: HF_TOKEN not set. Using cached credentials.")
|
| 56 |
+
|
| 57 |
+
source_folder = expanduser("~/Downloads/UD_Vietnamese-UUD-v0.1")
|
| 58 |
+
readme_file = join(source_folder, "README.md")
|
| 59 |
+
|
| 60 |
+
# Load all splits
|
| 61 |
+
splits = {}
|
| 62 |
+
for split_name, filename in [("train", "train.jsonl"), ("validation", "dev.jsonl"), ("test", "test.jsonl")]:
|
| 63 |
+
filepath = join(source_folder, filename)
|
| 64 |
+
if os.path.isfile(filepath):
|
| 65 |
+
print(f"Loading {split_name} from {filepath}...")
|
| 66 |
+
data = load_jsonl(filepath)
|
| 67 |
+
splits[split_name] = Dataset.from_list(data)
|
| 68 |
+
print(f" {split_name}: {len(data)} sentences")
|
| 69 |
+
else:
|
| 70 |
+
print(f"Warning: {filepath} not found, skipping {split_name} split")
|
| 71 |
+
|
| 72 |
+
if not splits:
|
| 73 |
+
print("Error: No data files found!")
|
| 74 |
+
return
|
| 75 |
+
|
| 76 |
+
# Create DatasetDict
|
| 77 |
+
print("\nCreating HuggingFace DatasetDict...")
|
| 78 |
+
dataset_dict = DatasetDict(splits)
|
| 79 |
+
|
| 80 |
+
print(f"Dataset: {dataset_dict}")
|
| 81 |
+
for split_name, ds in dataset_dict.items():
|
| 82 |
+
print(f" {split_name}: {len(ds)} rows, features: {list(ds.features.keys())}")
|
| 83 |
+
|
| 84 |
+
# Print domain distribution
|
| 85 |
+
for split_name, ds in dataset_dict.items():
|
| 86 |
+
domains = {}
|
| 87 |
+
for row in ds:
|
| 88 |
+
d = row["domain"]
|
| 89 |
+
domains[d] = domains.get(d, 0) + 1
|
| 90 |
+
domain_str = ", ".join(f"{d}: {c}" for d, c in sorted(domains.items()))
|
| 91 |
+
print(f" {split_name} domains: {domain_str}")
|
| 92 |
+
|
| 93 |
+
# Push to HuggingFace Hub
|
| 94 |
+
repo_id = "undertheseanlp/UDD-v0.1"
|
| 95 |
+
print(f"\nPushing to HuggingFace Hub: {repo_id}")
|
| 96 |
+
|
| 97 |
+
dataset_dict.push_to_hub(
|
| 98 |
+
repo_id,
|
| 99 |
+
private=False,
|
| 100 |
+
commit_message="Update: 40K sentences from 5 domains (legal, news, wikipedia, fiction, non-fiction)"
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
# Upload README.md
|
| 104 |
+
if os.path.isfile(readme_file):
|
| 105 |
+
print("Uploading README.md...")
|
| 106 |
+
api = HfApi()
|
| 107 |
+
api.upload_file(
|
| 108 |
+
path_or_fileobj=readme_file,
|
| 109 |
+
path_in_repo="README.md",
|
| 110 |
+
repo_id=repo_id,
|
| 111 |
+
repo_type="dataset",
|
| 112 |
+
commit_message="Update README with dataset card"
|
| 113 |
+
)
|
| 114 |
+
|
| 115 |
+
print(f"\nDone! Dataset available at: https://huggingface.co/datasets/{repo_id}")
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
if __name__ == "__main__":
|
| 119 |
+
main()
|