rain1024 commited on
Commit
1b2f095
·
1 Parent(s): f5d0a0d

Add word segmentation dataset pipeline and technical report v1.1

Browse files

- Add src/fetch_ws_sentences.py: fetches 100K sentences (20K × 5 domains)
from HuggingFace datasets with domain-specific quality filters
- Add src/build_ws_dataset.py: converts sentences to BIO format (VLSP 2013
compatible) with stratified 80/10/10 train/dev/test splits
- Add src/ws_statistics.py: computes dataset statistics and converts BIO
files to CoNLL-U format
- Update CLAUDE.md with WS dataset pipeline documentation
- Add TECHNICAL_REPORT_1.1.md: documents udd-ws-v1.1 dataset and proposes
active learning framework for gold-standard Vietnamese UD annotation
with solo annotator setting and task-specific AL strategies for WS,
POS tagging, and dependency parsing

CLAUDE.md CHANGED
@@ -37,6 +37,8 @@ UDD-1 (Universal Dependency Dataset for Vietnamese) is a Vietnamese Universal De
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
 
@@ -86,6 +88,23 @@ export HF_TOKEN=<token>
86
  python src/upload_to_hf.py
87
  ```
88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89
  ## Architecture Notes
90
 
91
  ### Conversion Pipeline (`convert_to_ud.py`)
 
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
+ | `src/fetch_ws_sentences.py` | Fetch 100K sentences (20K × 5 domains) for word segmentation dataset → `ws_sentences_*.txt` |
41
+ | `src/build_ws_dataset.py` | Convert sentences to BIO format via `word_tokenize` + `regex_tokenize` → `ws_{train,dev,test}.txt` |
42
 
43
  ## Pipeline Commands
44
 
 
88
  python src/upload_to_hf.py
89
  ```
90
 
91
+ ### Word Segmentation Dataset Pipeline
92
+
93
+ Separate pipeline producing a 100K-sentence BIO-tagged dataset (VLSP 2013 compatible) for CRF word segmentation training in tree-1.
94
+
95
+ ```bash
96
+ # Step 1: Fetch 20K sentences per domain (100K total)
97
+ uv run src/fetch_ws_sentences.py
98
+ # → ws_sentences_vlc.txt, ws_sentences_uvn.txt, ws_sentences_uvw.txt,
99
+ # ws_sentences_uvb_f.txt, ws_sentences_uvb_n.txt
100
+
101
+ # Step 2: Convert to BIO format with stratified 80/10/10 split
102
+ uv run src/build_ws_dataset.py
103
+ # → udd-ws-v1.1-train.txt (~80K), udd-ws-v1.1-dev.txt (~10K), udd-ws-v1.1-test.txt (~10K)
104
+ ```
105
+
106
+ Output BIO format (`syllable\tB-W` / `syllable\tI-W`, blank line between sentences) is compatible with tree-1's `load_data_vlsp2013()` which maps `B-W→B`, `I-W→I`.
107
+
108
  ## Architecture Notes
109
 
110
  ### Conversion Pipeline (`convert_to_ud.py`)
TECHNICAL_REPORT_1.1.md ADDED
@@ -0,0 +1,519 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # UDD-1 v1.1: Toward a Gold-Standard Vietnamese Universal Dependencies Treebank via Active Learning
2
+
3
+ **Underthesea NLP**
4
+
5
+ ## Abstract
6
+
7
+ UDD-1 v1.0 established a 10,000-sentence silver-standard Vietnamese UD treebank from the legal domain. Version 1.1 takes two steps toward gold-standard annotation. First, we scale the data foundation: a multi-domain word segmentation dataset of 100,000 sentences in BIO format (VLSP-compatible) across 5 domains (legal, news, Wikipedia, fiction, non-fiction), enabling training of robust word segmentation models that form the prerequisite for accurate dependency parsing. Second, we lay out a concrete active learning framework for constructing a gold-standard Vietnamese UD treebank under a **solo annotator** setting, with task-specific AL strategies for word segmentation (CRF marginal uncertainty), POS tagging (tag confusion targeting), and dependency parsing (head entropy with partial arc annotation). The pipeline is estimated at ~100 annotator-days to produce 2,000 gold WS, 1,000 gold POS, and 800--1,000 gold DP sentences.
8
+
9
+ Beyond gold annotation, a central goal of this work is the co-development of **standardized Vietnamese annotation guidelines** for the three core NLP tasks: word segmentation, POS tagging, and dependency parsing. Vietnamese currently lacks a unified, publicly available annotation standard that covers all three tasks consistently. Existing guidelines are fragmented --- the VLSP 2013 shared task defined word segmentation conventions, the NIIVTB project (Nguyen et al., 2018) established 9 rules for word boundary decisions, and UD_Vietnamese-VTB provides limited language-specific UD guidelines --- but no single resource integrates them into a coherent annotation framework. Through the active learning loop, where the most ambiguous and informative examples are systematically surfaced, we develop comprehensive Vietnamese annotation guidelines that address language-specific phenomena (copula *là*, passive markers *được/bị*, serial verb constructions, classifier phrases, topic-comment structure) with explicit decision procedures, worked examples, and cross-task consistency. These guidelines are intended as a reusable community resource for future Vietnamese treebank and dataset construction.
10
+
11
+ This report documents the word segmentation dataset (udd-ws-v1.1), the active learning roadmap, and the guideline development methodology.
12
+
13
+ ## 1. Introduction
14
+
15
+ ### 1.1 Motivation
16
+
17
+ The TECHNICAL_REPORT_REVIEW of UDD-1 v1.0 identified a clear path forward:
18
+
19
+ > *"Could you run the Underthesea parser on 50-100 sentences from the legal corpus that have been manually annotated by a Vietnamese linguist, to report in-domain LAS/UAS? This single addition would move the paper from borderline to solid accept."*
20
+
21
+ More broadly, the review highlighted three priorities: (1) gold-standard evaluation of annotation quality, (2) reduction of the 8.6% UPOS-forcing artifact rate, and (3) multi-domain coverage beyond the legal domain. Version 1.1 addresses all three through a two-pronged strategy:
22
+
23
+ - **Word segmentation dataset (udd-ws-v1.1)**: A 100K-sentence, 5-domain BIO-tagged dataset that provides the training data for robust word segmentation --- the first step in the Vietnamese NLP pipeline (WS → POS → DP).
24
+ - **Active learning framework**: A systematic plan to construct gold-standard UD annotations efficiently, using the silver-standard data as a starting point and selectively correcting the most informative errors.
25
+
26
+ ### 1.2 Overview of Contributions
27
+
28
+ | Contribution | Status | Description |
29
+ |---|---|---|
30
+ | udd-ws-v1.1 dataset | Planned | 100K sentences, 5 domains, BIO format, stratified splits |
31
+ | Active learning literature survey | Planned | 35 papers covering AL for parsing, treebank construction, guidelines |
32
+ | Vietnamese WS annotation guidelines | Planned | NIIVTB 9-rule framework adapted for UDD-1 |
33
+ | AL framework design | This report | Concrete plan for gold-standard UD annotation |
34
+ | Gold-standard annotation | Planned | Target: 2-5K sentences via active learning |
35
+
36
+ ## 2. Word Segmentation Dataset: udd-ws-v1.1
37
+
38
+ ### 2.1 Rationale
39
+
40
+ Word segmentation is the foundation of Vietnamese NLP. The dependency parser in UDD-1 v1.0 uses an implicit tokenizer that produces segmentation errors propagating to all downstream annotations (Section 5.6 of TECHNICAL_REPORT.md). Building a dedicated word segmentation dataset enables:
41
+
42
+ 1. Training domain-robust CRF word segmentation models (tree-1 pipeline)
43
+ 2. Evaluating segmentation quality across domains independently of the parser
44
+ 3. Providing a clean input pipeline for future gold-standard UD annotation
45
+
46
+ ### 2.2 Data Collection
47
+
48
+ Sentences are drawn from 4 HuggingFace datasets, the same sources as UDD-1 v1.0 but scaled to 20,000 sentences per domain:
49
+
50
+ | Domain | Source Dataset | Sentences | Sent ID Prefix |
51
+ |--------|---------------|-----------|----------------|
52
+ | Legal | `undertheseanlp/UTS_VLC` | 20,000 | `vlc-` |
53
+ | News | `undertheseanlp/UVN-1` | 20,000 | `uvn-` |
54
+ | Wikipedia | `undertheseanlp/UVW-2026` | 20,000 | `uvw-` |
55
+ | Fiction | `undertheseanlp/UVB-v0.1` | 20,000 | `uvb-f-` |
56
+ | Non-fiction | `undertheseanlp/UVB-v0.1` | 20,000 | `uvb-n-` |
57
+ | **Total** | | **100,000** | |
58
+
59
+ **Table 1**: Domain breakdown of udd-ws-v1.1.
60
+
61
+ Each domain applies the same quality filters as UDD-1 v1.0 (see `guidelines/00. Sentence Selection.md`), with books applying stricter criteria (30-250 chars, 5-40 words, must start uppercase and end with punctuation).
62
+
63
+ ### 2.3 BIO Annotation
64
+
65
+ Sentences are converted to syllable-level BIO format using:
66
+
67
+ 1. `underthesea.word_tokenize(sentence, format="text")` → compound tokens with underscores (e.g., `"Việt_Nam là một quốc_gia"`)
68
+ 2. `underthesea.pipeline.word_tokenize.regex_tokenize.tokenize()` → syllable splitting
69
+ 3. First syllable of each token → `B-W`, continuation syllables → `I-W`
70
+
71
+ Output format (VLSP 2013 compatible, tab-separated with comment headers):
72
+
73
+ ```
74
+ # sent_id = vlc-1
75
+ # text = Một doanh nghiệp lớn hoạt động hiệu quả .
76
+ Một B-W
77
+ doanh B-W
78
+ nghiệp I-W
79
+ lớn B-W
80
+ hoạt B-W
81
+ động I-W
82
+ hiệu B-W
83
+ quả I-W
84
+ . B-W
85
+ ```
86
+
87
+ This format is directly loadable by tree-1's `load_data_vlsp2013()` function, which maps `B-W → B`, `I-W → I`.
88
+
89
+ ### 2.4 Dataset Statistics
90
+
91
+ | | Train | Dev | Test | Total |
92
+ |---|---:|---:|---:|---:|
93
+ | Sentences | 80,000 | 10,000 | 10,000 | 100,000 |
94
+ | Words | 1,592,531 | 201,565 | 197,832 | 1,991,928 |
95
+ | Syllables | 2,087,103 | 263,953 | 259,338 | 2,610,394 |
96
+ | Avg word/sent | 19.91 | 20.16 | 19.78 | 19.92 |
97
+ | Avg syl/sent | 26.09 | 26.40 | 25.93 | 26.10 |
98
+ | Avg syl/word | 1.31 | 1.31 | 1.31 | 1.31 |
99
+
100
+ **Table 2**: udd-ws-v1.1 split statistics.
101
+
102
+ Splits are stratified by domain (each domain contributes exactly 20% to every split) with random seed 42 for reproducibility.
103
+
104
+ ### 2.5 Word Length Distribution
105
+
106
+ | Syllables per word | Count | Percentage |
107
+ |:---:|---:|---:|
108
+ | 1 | 1,403,963 | 70.48% |
109
+ | 2 | 564,634 | 28.35% |
110
+ | 3 | 17,820 | 0.89% |
111
+ | 4 | 4,384 | 0.22% |
112
+ | 5+ | 1,127 | 0.06% |
113
+
114
+ **Table 3**: Word length distribution across the full dataset.
115
+
116
+ The distribution is consistent with Vietnamese linguistics: ~70% single-syllable words, ~28% two-syllable compounds, and ~2% longer compounds. The 1.31 average syllables per word aligns with the 1.38 figure reported for legal text in SEGMENTATION_EVAL.md (the difference reflecting the inclusion of less formal fiction/non-fiction domains).
117
+
118
+ ### 2.6 Silver-Standard Caveat
119
+
120
+ The BIO annotations are generated automatically by `underthesea.word_tokenize()` and inherit its segmentation biases. SEGMENTATION_EVAL.md documents known issues including 462 over-segmented dictionary words (7,373 occurrences) and 382 potentially under-segmented tokens. The dataset is a silver-standard resource suitable for CRF training but not for evaluation of segmentation quality. A gold-standard evaluation subset is planned as part of the active learning framework (Section 3).
121
+
122
+ ## 3. Active Learning Framework for Gold-Standard UD Annotation
123
+
124
+ ### 3.1 Goal
125
+
126
+ Construct a **gold-standard** Vietnamese UD treebank of 2,000--5,000 sentences with verified word segmentation, POS tags, and dependency relations, sufficient to:
127
+
128
+ 1. Report in-domain LAS/UAS on legal and multi-domain text
129
+ 2. Serve as evaluation data for parser development
130
+ 3. Serve as seed training data for active-learning-boosted parsers
131
+ 4. Establish Vietnamese-specific UD annotation guidelines through the annotation process
132
+
133
+ ### 3.2 Solo Annotator Setting
134
+
135
+ This project operates under a **solo annotator** constraint: a single Vietnamese linguist performs all annotation. This is a realistic setting for under-resourced languages where trained annotators are scarce. The solo setting has specific implications:
136
+
137
+ - **No inter-annotator agreement (IAA)**: Quality is ensured through consistency checks, model-based error detection, and guideline self-auditing rather than dual annotation.
138
+ - **Consistency advantage**: A single annotator produces internally consistent annotations, avoiding the reconciliation overhead of multi-annotator setups.
139
+ - **Anchoring risk**: The annotator corrects silver-standard pre-annotations, creating anchoring bias toward the parser's output. Mitigation: guidelines explicitly instruct the annotator to evaluate each decision independently; periodic blind re-annotation of 5% of sentences to measure self-consistency.
140
+ - **Throughput**: One annotator correcting pre-annotated data can process 50--100 sentences/day for word segmentation, 30--50 for POS, and 15--30 for dependency parsing (estimates from Brants & Skut 1998, adjusted for Vietnamese complexity).
141
+
142
+ **Quality assurance without IAA**:
143
+
144
+ | Method | Purpose | Frequency |
145
+ |--------|---------|-----------|
146
+ | Self-consistency check | Re-annotate 5% of completed sentences blind | Every 200 sentences |
147
+ | Model-based error detection | Flag arcs where retrained model disagrees with gold | After each AL cycle |
148
+ | Dictionary validation | Cross-check WS against Viet74K dictionary | Continuous |
149
+ | UD validator | Automated structural constraint checking | After each batch |
150
+ | Guideline self-audit | Review decisions against written guidelines | Weekly |
151
+
152
+ **Table 4**: Quality assurance methods for solo annotator setting.
153
+
154
+ ### 3.3 Why Active Learning
155
+
156
+ Manual annotation of dependency treebanks is expensive. Brants & Skut (1998) showed that correcting pre-annotated data is 3--5x faster than annotation from scratch. Active learning further reduces cost by selecting the most informative examples for annotation.
157
+
158
+ The literature (surveyed in `active_learning/references/research_active_learning_ud/`) demonstrates:
159
+
160
+ | Method | Cost Reduction | Reference |
161
+ |--------|---------------|-----------|
162
+ | Uncertainty sampling | ~50% fewer sentences | Hwa (2004) |
163
+ | Head entropy + partial annotation | 40--60% less arc annotation | Li et al. (2016) |
164
+ | DPP batch diversity + uncertainty | ~20--30% fewer sentences | Shi et al. (2021) |
165
+ | Partial annotation + self-training | Best cost reduction across 4 tasks | Zhang et al. (2023) |
166
+
167
+ **Table 5**: Active learning cost reduction benchmarks from the literature.
168
+
169
+ UDD-1's situation is particularly favorable for AL: we already have 100K silver-standard sentences that can serve as the initial model's training data and as candidates for selective correction.
170
+
171
+ ### 3.4 Three-Task Active Learning Pipeline
172
+
173
+ The Vietnamese NLP pipeline is sequential: **Word Segmentation → POS Tagging → Dependency Parsing**. Each task depends on the output of the previous one, so errors cascade. We apply active learning independently to each task with task-specific strategies, proceeding in pipeline order.
174
+
175
+ ```
176
+ ┌─────────────────────────────────────────────────────────────────┐
177
+ │ Task 1: Word Segmentation │
178
+ │ │
179
+ │ Silver data ──► Train CRF ──► Score uncertainty ──► Annotate │
180
+ │ (100K BIO) (tree-1) (token marginals) (correct │
181
+ │ BIO tags) │
182
+ │ ◄──── Retrain ◄──── Gold WS data │
183
+ └───────────────────────────────┬─────────────────────────────────┘
184
+ │ Gold-segmented sentences
185
+ ┌───────────────────────────────▼─────────────────────────────────┐
186
+ │ Task 2: POS Tagging │
187
+ │ │
188
+ │ Silver POS ──► Train CRF ──► Score uncertainty ──► Annotate │
189
+ │ (auto-tagged) (tree-1) (tag marginals) (correct │
190
+ │ UPOS tags) │
191
+ │ ◄──── Retrain ◄──── Gold POS data │
192
+ └───────────────────────────────┬─────────────────────────────────┘
193
+ │ Gold-segmented + Gold-POS sentences
194
+ ┌───────────────────────────────▼─────────────────────────────────┐
195
+ │ Task 3: Dependency Parsing │
196
+ │ │
197
+ │ Silver DP ──► Train parser ──► Score uncertainty ──► Annotate │
198
+ │ (auto-parsed) (biaffine) (head entropy) (correct │
199
+ │ arcs + │
200
+ │ deprels) │
201
+ │ ◄──── Retrain ◄──── Gold DP data │
202
+ └─────────────────────────────────────────────────────────────────┘
203
+ ```
204
+
205
+ ### 3.5 Task 1: Active Learning for Word Segmentation
206
+
207
+ **Objective**: Build a gold-standard word segmentation evaluation set and improve the CRF segmenter through targeted correction of silver BIO data.
208
+
209
+ **Starting point**: 100K silver BIO sentences (udd-ws-v1.1), CRF model trained on this data (tree-1, 98.90% syllable F1 on silver test set).
210
+
211
+ #### 3.5.1 Query Strategy: Token-Level Marginal Uncertainty
212
+
213
+ CRF models produce marginal probabilities for each token's label. For word segmentation, the uncertainty of a token at position $i$ is:
214
+
215
+ $$u_i = 1 - \max(P(\text{B-W}|x, i),\ P(\text{I-W}|x, i))$$
216
+
217
+ **Sentence-level score**: average uncertainty across all tokens in the sentence, weighted by the number of multi-syllable word boundaries (positions where a B-W/I-W decision is non-trivial).
218
+
219
+ **Selection protocol**:
220
+ 1. Train CRF on udd-ws-v1.1-train (80K silver sentences)
221
+ 2. Predict on udd-ws-v1.1-dev + udd-ws-v1.1-test (20K sentences) with marginal probabilities
222
+ 3. Rank sentences by aggregated token uncertainty
223
+ 4. Select top-N sentences stratified by domain (equal representation)
224
+ 5. Additionally select sentences containing known error patterns from SEGMENTATION_EVAL.md:
225
+ - Sentences with tokens matching the 462 over-segmented dictionary words
226
+ - Sentences with tokens matching the 382 under-segmented candidates
227
+ - Sentences with 4+ syllable tokens (potential under-segmentation)
228
+
229
+ #### 3.5.2 Annotation Procedure
230
+
231
+ The annotator corrects BIO tags in a text editor (or annotation tool), focusing on word boundaries:
232
+
233
+ 1. **Review pre-annotated BIO output** with uncertain tokens highlighted
234
+ 2. **Correct boundaries** using the NIIVTB 9-rule framework (see `ANNOTATION_GUIDELINE_WORD_SEGMENTATION.md`):
235
+ - Rule 1 (Insertability test): Can another word be inserted between syllables?
236
+ - Rule 2 (Semantic opacity): Is the meaning compositional?
237
+ - Rules 3--9: Additional criteria for specific constructions
238
+ 3. **Flag ambiguous cases** for guideline development
239
+
240
+ **Batch size**: 500 sentences per AL cycle (solo annotator, ~1--2 days of work).
241
+
242
+ #### 3.5.3 AL Cycle for Word Segmentation
243
+
244
+ | Cycle | Sentences | Cumulative Gold | Focus |
245
+ |-------|-----------|----------------|-------|
246
+ | 0 (Baseline) | 0 | 0 | Train CRF on 80K silver |
247
+ | 1 | 500 | 500 | Highest uncertainty + known error patterns |
248
+ | 2 | 500 | 1,000 | Retrained CRF's new uncertain tokens |
249
+ | 3 | 500 | 1,500 | Domain-specific compounds, remaining errors |
250
+ | 4 | 500 | 2,000 | Diminishing returns check; stop if F1 plateaus |
251
+
252
+ **Stopping criterion**: Stop when the CRF retrained on silver+gold data achieves <0.1% F1 improvement on a held-out gold test set (200 sentences set aside from Cycle 1).
253
+
254
+ **Expected outcome**: 2,000 gold WS sentences, CRF word F1 improvement from ~98.0% to >99%.
255
+
256
+ ### 3.6 Task 2: Active Learning for POS Tagging
257
+
258
+ **Objective**: Build gold POS annotations on the gold-segmented sentences from Task 1, and improve the CRF POS tagger.
259
+
260
+ **Starting point**: Gold-segmented sentences from Task 1. Silver POS tags from `underthesea.pos_tag()`, mapped to UPOS via `UPOS_MAP`. CRF POS tagger (tree-1, 95.89% accuracy on silver UDD-1).
261
+
262
+ **Dependency on Task 1**: POS tagging operates on correctly segmented words. Only sentences with verified word segmentation from Task 1 enter the POS annotation pool.
263
+
264
+ #### 3.6.1 Query Strategy: Tag Marginal Uncertainty + Confusion-Targeted Selection
265
+
266
+ CRF POS taggers produce marginal probabilities over the 15 UPOS tags for each token. Two complementary selection criteria:
267
+
268
+ **Criterion A — Token uncertainty**:
269
+ $$u_i = 1 - \max_t P(t|x, i), \quad t \in \{\text{ADJ, ADP, ADV, ..., X}\}$$
270
+
271
+ Sentence score = average of top-K most uncertain tokens (not all tokens, to avoid penalizing long easy sentences).
272
+
273
+ **Criterion B — Confusion-targeted selection**: Prioritize sentences containing tokens from known confusion pairs identified in v1.0:
274
+ - **AUX vs. VERB**: *được*, *bị*, *phải*, *có thể* (20 auxiliary words with dual function)
275
+ - **NOUN vs. VERB**: Vietnamese words frequently function as both (e.g., *quy định* "regulation"/"to regulate")
276
+ - **ADJ vs. VERB**: Stative verbs vs. adjectives (e.g., *đẹp* "beautiful/to be beautiful")
277
+ - **DET vs. PRON**: *này*, *đó*, *nào* (deictic function)
278
+ - **ADP vs. SCONJ**: *khi*, *vì*, *do* (preposition vs. subordinator)
279
+
280
+ **Selection formula**: Score = $\alpha \cdot \text{uncertainty} + (1-\alpha) \cdot \text{confusion\_density}$, where confusion density is the proportion of tokens matching known confusion pairs. $\alpha = 0.6$ to favor uncertainty while ensuring coverage of systematic errors.
281
+
282
+ #### 3.6.2 Annotation Procedure
283
+
284
+ The annotator corrects UPOS tags on gold-segmented sentences:
285
+
286
+ 1. **Review silver UPOS tags** with uncertain and confusion-pair tokens highlighted
287
+ 2. **Correct tags** by examining each highlighted token in sentential context:
288
+ - For AUX/VERB: Apply the AUX word list + syntactic function test (does it modify another verb?)
289
+ - For NOUN/VERB: Apply the *có thể* test (can *có thể* "can" be inserted before it? → VERB)
290
+ - For ADJ/VERB: Apply the *rất* test (can *rất* "very" modify it? → ADJ)
291
+ 3. **Record XPOS** if the XPOS-UPOS mismatch is justified (functional reclassification) vs. an error
292
+ 4. **Do not consider dependency relations**: POS is annotated independently of deprel to break the UPOS-forcing cycle from v1.0
293
+
294
+ #### 3.6.3 AL Cycle for POS Tagging
295
+
296
+ | Cycle | Sentences | Cumulative Gold | Focus |
297
+ |-------|-----------|----------------|-------|
298
+ | 0 (Baseline) | 0 | 0 | Evaluate CRF POS on gold-segmented sentences |
299
+ | 1 | 300 | 300 | Highest uncertainty + AUX/VERB confusion |
300
+ | 2 | 300 | 600 | Retrained model's new errors + NOUN/VERB confusion |
301
+ | 3 | 200 | 800 | Remaining confusion pairs, domain-specific terms |
302
+ | 4 | 200 | 1,000 | Diminishing returns check |
303
+
304
+ **Stopping criterion**: Stop when POS accuracy on held-out gold test set (100 sentences) improves <0.2% per cycle.
305
+
306
+ **Expected outcome**: 1,000 gold POS sentences, UPOS accuracy improvement from ~95.9% to >97%, elimination of the UPOS-forcing artifact.
307
+
308
+ ### 3.7 Task 3: Active Learning for Dependency Parsing
309
+
310
+ **Objective**: Build gold dependency annotations on sentences with verified WS and POS, producing the first in-domain LAS/UAS measurements for Vietnamese legal and multi-domain text.
311
+
312
+ **Starting point**: Sentences with gold WS + gold POS from Tasks 1--2. Silver dependency arcs from `underthesea.dependency_parse()`. Biaffine parser (~76% LAS on VLSP 2020 news benchmark).
313
+
314
+ **Dependency on Tasks 1--2**: Only sentences with verified WS and POS enter the DP annotation pool. This ensures that measured LAS/UAS reflects parsing quality, not cascading tokenization or POS errors.
315
+
316
+ #### 3.7.1 Query Strategy: Head Entropy + Partial Arc Annotation
317
+
318
+ Dependency parsing has the highest annotation cost per sentence (each token requires a head and a deprel). Following Li et al. (2016), we use **partial annotation** to minimize effort: within each selected sentence, the annotator only corrects arcs that the parser is uncertain about.
319
+
320
+ **Head entropy** for token $i$ with possible heads $h \in \{0, 1, ..., n\}$:
321
+
322
+ $$H_i = -\sum_{h} P(h|x, i) \log P(h|x, i)$$
323
+
324
+ This requires a probabilistic parser that outputs head distributions. We use a biaffine parser (Dozat and Manning, 2017) trained on UDD-1 silver data + VLSP 2020, which naturally produces attention scores convertible to probabilities via softmax.
325
+
326
+ **Sentence selection**: DPP (Determinantal Point Process) batch selection (Shi et al., 2021) combining:
327
+ - **Informativeness**: Sum of head entropy across tokens → selects uncertain sentences
328
+ - **Diversity**: PhoBERT sentence embeddings as the DPP kernel → selects structurally diverse sentences
329
+ - **Domain balance**: Equal quota per domain (legal, news, Wikipedia, fiction, non-fiction)
330
+
331
+ **Arc selection within sentences**: For each selected sentence, mark arcs where $H_i > \tau$ (threshold determined from validation set, typically keeping the top 30--40% most uncertain arcs). The annotator focuses on these arcs while accepting the parser's output for confident arcs.
332
+
333
+ #### 3.7.2 Annotation Procedure
334
+
335
+ The annotator corrects dependency arcs using a tree visualization tool (e.g., Arborator-Grew or ConlluEditor):
336
+
337
+ 1. **View the full parse tree** with uncertain arcs highlighted (red = high entropy, green = confident)
338
+ 2. **For each uncertain arc**, decide:
339
+ - **Head**: Which word does this token depend on? (click to reassign)
340
+ - **Deprel**: What is the relation? (select from dropdown of 37 UD base types)
341
+ 3. **Verify confident arcs only if they look wrong** — the annotator can skip green arcs but is encouraged to scan for obvious errors
342
+ 4. **Apply Vietnamese-specific decisions** using the evolving guideline document:
343
+ - Copula *là*: `cop` when linking subject to predicate nominal, `mark` in cleft constructions
344
+ - Passive *được/bị*: `aux:pass` when modifying another verb, `root`/`xcomp` when main verb
345
+ - Serial verbs: second verb as `xcomp` or `conj` depending on shared arguments
346
+ - Classifiers: `clf` (UD v2 subtype) for numeral-classifier-noun constructions
347
+ - Topic fronting: `dislocated` when the fronted NP is resumed by a pronoun, `nsubj` otherwise
348
+
349
+ #### 3.7.3 AL Cycle for Dependency Parsing
350
+
351
+ | Cycle | Sentences | Arcs Annotated (est.) | Cumulative Gold | Focus |
352
+ |-------|-----------|----------------------|----------------|-------|
353
+ | 0 (Baseline) | 0 | 0 | 0 | Evaluate parser on VLSP 2020 test |
354
+ | 1 (Pilot) | 50 | ~500 (all arcs) | 50 | Full annotation; establish LAS/UAS baseline on legal text; bootstrap guidelines |
355
+ | 2 | 200 | ~800 (partial) | 250 | High-entropy arcs only; focus on nsubj/obj/obl attachment errors |
356
+ | 3 | 200 | ~800 (partial) | 450 | Coordination, subordination, relative clause errors |
357
+ | 4 | 200 | ~800 (partial) | 650 | Multi-domain expansion (news, wiki, books) |
358
+ | 5 | 150 | ~600 (partial) | 800 | Domain-specific constructions, long sentences |
359
+ | 6+ | 100/cycle | ~400/cycle | 1,000+ | Continue until LAS improvement plateaus |
360
+
361
+ **Cycle 1 is special**: The first 50 sentences are fully annotated (all arcs, not just uncertain ones) to establish a reliable gold test set and measure the initial parser's in-domain LAS/UAS. This addresses the primary reviewer request.
362
+
363
+ **Stopping criterion**: Stop when retrained parser's LAS on the gold test set (50 sentences from Cycle 1) improves <0.5% per cycle, or when the annotator reports that most uncertain arcs are genuinely ambiguous (guideline-level issues rather than parser errors).
364
+
365
+ **Expected outcome**: 800--1,000 gold DP sentences with ~3,000--4,000 verified arcs. First reported in-domain LAS/UAS for Vietnamese legal text and multi-domain text.
366
+
367
+ ### 3.8 Cross-Task Annotation Flow
368
+
369
+ The three tasks are executed sequentially with overlap. As Task 1 produces gold-segmented sentences, they flow into Task 2; as Task 2 produces gold-POS sentences, they flow into Task 3.
370
+
371
+ ```
372
+ Week: 1 2 3 4 5 6 7 8 9 10 11 12
373
+ ├────┼────┼────┼────┼────┼────┼────┼────┼────┼────┼────┤
374
+ Task 1: ████████████████████
375
+ WS Cycle 1-4 (2K sentences)
376
+ Task 2: ██████████████████
377
+ POS Cycle 1-4 (1K sentences)
378
+ Task 3: ████████████████████████████
379
+ DP Cycle 1-6+ (800-1K sentences)
380
+ Guidelines: ◆───────◆───────◆───────◆───────◆───────◆
381
+ v0.1 v0.2 v0.3 v0.4 v0.5 v1.0
382
+ ```
383
+
384
+ **Overlap**: Task 2 can begin once Task 1 has produced its first 500 gold sentences (Cycle 1). Task 3 can begin once Task 2 has produced its first 300 gold sentences. This overlap reduces total calendar time from ~18 weeks (sequential) to ~12 weeks.
385
+
386
+ ### 3.9 Guideline Development (Solo Annotator)
387
+
388
+ Without a second annotator for IAA, guidelines evolve through a **self-audit** process:
389
+
390
+ | Cycle | Guideline Action | Quality Check |
391
+ |-------|-----------------|---------------|
392
+ | WS Cycle 1 | Draft WS guidelines from NIIVTB 9 rules | Dictionary validation of all corrections |
393
+ | WS Cycle 2 | Revise WS guidelines based on encountered edge cases | Re-annotate 25 sentences from Cycle 1 blind; measure self-consistency |
394
+ | POS Cycle 1 | Draft POS guidelines (confusion pairs, AUX list) | Model-based error detection on corrected data |
395
+ | POS Cycle 2 | Revise POS guidelines | Re-annotate 15 sentences from Cycle 1 |
396
+ | DP Cycle 1 | Draft DP guidelines (pilot, 50 full sentences) | UD validator on all sentences |
397
+ | DP Cycle 3 | Major guideline revision after 450 sentences | Re-annotate 25 sentences from Cycles 1--2 |
398
+ | Final | Consolidate all guidelines into single document | Full self-consistency audit on 100 random sentences |
399
+
400
+ **Self-consistency target**: >95% agreement between original and re-annotation on the same sentences. Disagreements indicate guideline ambiguities that need resolution.
401
+
402
+ Vietnamese-specific challenges requiring guideline development:
403
+ 1. **Copula `là`**: Multiple syntactic functions (copula, focus marker, relative clause marker)
404
+ 2. **Passive markers `được/bị`**: AUX vs. main VERB distinction is context-dependent
405
+ 3. **Serial verb constructions**: Common in Vietnamese; requires explicit deprel convention
406
+ 4. **Classifier constructions**: Numeral-classifier-noun patterns need specific annotation rules
407
+ 5. **Topic-comment structure**: Vietnamese allows topic fronting; affects nsubj vs. dislocated
408
+ 6. **Legal domain vocabulary**: Terms like *điều*, *khoản*, *mục* have specific syntactic roles
409
+
410
+ ### 3.10 Quality Targets
411
+
412
+ | Metric | v1.0 (Silver) | v1.1 Target (Gold Subset) |
413
+ |--------|--------------|---------------------------|
414
+ | Word segmentation F1 | Unknown (same as underthesea) | >98% (gold test) |
415
+ | UPOS accuracy | ~91.4% (8.6% forced) | >97% (gold test) |
416
+ | LAS | ~76% (news benchmark) | Measured on legal + multi-domain |
417
+ | UAS | Unknown | Measured on legal + multi-domain |
418
+ | Self-consistency | N/A | >95% on re-annotation |
419
+ | Gold WS sentences | 0 | 2,000 |
420
+ | Gold POS sentences | 0 | 1,000 |
421
+ | Gold DP sentences | 0 | 800--1,000 |
422
+
423
+ **Table 6**: Quality targets for v1.1 gold annotation.
424
+
425
+ ### 3.11 Cost Estimation (Solo Annotator)
426
+
427
+ | Task | Sentences | Est. Speed | Est. Days | Calendar Weeks |
428
+ |------|-----------|-----------|-----------|----------------|
429
+ | WS (4 cycles × 500) | 2,000 | 80 sent/day | 25 days | 5 weeks |
430
+ | POS (4 cycles × 250) | 1,000 | 40 sent/day | 25 days | 5 weeks |
431
+ | DP Pilot (full) | 50 | 15 sent/day | 3 days | 1 week |
432
+ | DP Partial (5 cycles × 150--200) | 750--1,000 | 25 sent/day | 30--40 days | 6--8 weeks |
433
+ | Guideline development | — | — | 10 days | distributed |
434
+ | Self-consistency audits | ~200 re-annotated | — | 5 days | distributed |
435
+ | **Total** | | | **~100 days** | **~12 weeks (with overlap)** |
436
+
437
+ **Table 7**: Cost estimation for solo annotator.
438
+
439
+ The partial annotation strategy for dependency parsing (annotating only ~40% of arcs per sentence) reduces DP annotation effort by approximately 60% compared to full annotation, consistent with Li et al. (2016). Total effort of ~100 annotator-days is feasible for a single linguist working full-time over 3 months, or part-time over 6 months.
440
+
441
+ ## 4. Data Format and Access
442
+
443
+ ### 4.1 Word Segmentation Dataset (udd-ws-v1.1)
444
+
445
+ **Files** (local, UDD-1 repository):
446
+ - `udd-ws-v1.1-train.txt` — 80,000 sentences (19 MB)
447
+ - `udd-ws-v1.1-dev.txt` — 10,000 sentences (2.5 MB)
448
+ - `udd-ws-v1.1-test.txt` — 10,000 sentences (2.4 MB)
449
+ - `udd-ws-v1.1-{train,dev,test}.conllu` — CoNLL-U format (words as tokens)
450
+
451
+ **Format**: BIO text with comment headers (VLSP 2013 compatible):
452
+ ```
453
+ # sent_id = uvn-1234
454
+ # text = Original sentence text here
455
+ syllable1 B-W
456
+ syllable2 I-W
457
+ syllable3 B-W
458
+ ```
459
+
460
+ ### 4.2 Pipeline Scripts
461
+
462
+ | Script | Purpose | Command |
463
+ |--------|---------|---------|
464
+ | `src/fetch_ws_sentences.py` | Fetch 100K sentences from HuggingFace | `uv run src/fetch_ws_sentences.py` |
465
+ | `src/build_ws_dataset.py` | Convert to BIO + stratified split | `uv run src/build_ws_dataset.py` |
466
+ | `src/ws_statistics.py` | Convert to CoNLL-U + compute statistics | `uv run src/ws_statistics.py` |
467
+
468
+ ### 4.3 Intermediate Files
469
+
470
+ - `ws_sentences_{vlc,uvn,uvw,uvb_f,uvb_n}.txt` — Raw sentences per domain (format: `idx\tsentence`)
471
+
472
+ ## 5. Relation to UDD-1 v1.0
473
+
474
+ UDD-1 v1.1 does not replace v1.0. The relationship is:
475
+
476
+ | | v1.0 | v1.1 |
477
+ |---|---|---|
478
+ | **UD Treebank** | 10K sentences, legal domain, silver-standard CoNLL-U | Unchanged (v1.0 treebank remains) |
479
+ | **WS Dataset** | N/A | 100K sentences, 5 domains, BIO format |
480
+ | **Gold Annotation** | None | Planned: 2-5K sentences via active learning |
481
+ | **Annotation Guidelines** | Implicit (parser behavior) | Explicit (co-developed through AL) |
482
+ | **Domains** | Legal only | Legal, News, Wikipedia, Fiction, Non-fiction |
483
+
484
+ The word segmentation dataset feeds into tree-1's CRF training pipeline. The gold annotations planned through active learning will eventually enable a v2.0 release with verified quality.
485
+
486
+ ## 6. Conclusion
487
+
488
+ UDD-1 v1.1 establishes the data and methodological foundation for building a gold-standard Vietnamese UD treebank:
489
+
490
+ 1. **udd-ws-v1.1**: A 100,000-sentence, 5-domain word segmentation dataset in BIO format, providing the training data for robust tokenization models that underpin all downstream annotations.
491
+
492
+ 2. **Three-task active learning pipeline**: Task-specific AL strategies for each layer of the Vietnamese NLP pipeline:
493
+ - **Word segmentation**: CRF token marginal uncertainty + dictionary-based error targeting → 2,000 gold sentences
494
+ - **POS tagging**: Tag marginal uncertainty + confusion-pair targeting (AUX/VERB, NOUN/VERB) → 1,000 gold sentences
495
+ - **Dependency parsing**: Head entropy + DPP batch diversity + partial arc annotation → 800--1,000 gold sentences
496
+
497
+ 3. **Solo annotator methodology**: Quality assurance through self-consistency checks (>95% target), model-based error detection, dictionary validation, and UD structural validation --- demonstrating that gold treebank construction is feasible without multiple annotators.
498
+
499
+ 4. **Vietnamese UD guidelines**: Co-developed through the annotation process, addressing Vietnamese-specific challenges (copula, passive markers, serial verbs, classifiers, topic-comment structure).
500
+
501
+ The immediate next step is Task 1, Cycle 1: selecting 500 sentences with highest CRF uncertainty from udd-ws-v1.1 for gold word segmentation annotation. In parallel, the DP pilot (50 fully annotated sentences) will produce the first in-domain LAS/UAS measurements for Vietnamese legal text. Total estimated effort: ~100 annotator-days over 12 weeks.
502
+
503
+ ## References
504
+
505
+ - Baldridge, J. and Osborne, M. (2004). Active Learning and the Total Cost of Annotation. In *Proceedings of EMNLP 2004*.
506
+
507
+ - Brants, T. and Skut, W. (1998). Automation of Treebank Annotation. In *Proceedings of CoNLL 1998*.
508
+
509
+ - de Marneffe, M.-C., Manning, C.D., Nivre, J., and Zeman, D. (2021). Universal Dependencies. *Computational Linguistics*, 47(2):255--308.
510
+
511
+ - Hwa, R. (2004). Sample Selection for Statistical Parsing. *Computational Linguistics*, 30(3):253--276.
512
+
513
+ - Li, Z., Zhang, M., Zhang, Y., Liu, Z., Chen, W., Wu, H., and Wang, H. (2016). Active Learning for Dependency Parsing with Partial Annotation. In *Proceedings of ACL 2016*, pp. 344--354.
514
+
515
+ - Nguyen, Q., Vu, T., Nguyen, D., Nguyen, M., and Phan, T. (2018). Ensuring Annotation Consistency and Accuracy for Vietnamese Treebank. *Language Resources and Evaluation*, Springer.
516
+
517
+ - Shi, T., Benton, A., Malioutov, I., and Irsoy, O. (2021). Diversity-Aware Batch Active Learning for Dependency Parsing. In *Proceedings of NAACL 2021*.
518
+
519
+ - Zhang, Z., Strubell, E., and Hovy, E. (2023). Data-efficient Active Learning for Structured Prediction with Partial Annotation and Self-Training. In *Findings of EMNLP 2023*.
src/build_ws_dataset.py ADDED
@@ -0,0 +1,278 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # requires-python = ">=3.9"
3
+ # dependencies = [
4
+ # "underthesea>=6.8.0",
5
+ # ]
6
+ # ///
7
+ """
8
+ Build word segmentation dataset in BIO format (VLSP 2013 compatible).
9
+
10
+ Reads 5 intermediate sentence files (ws_sentences_*.txt), applies
11
+ underthesea.word_tokenize to get compound tokens, then splits into
12
+ syllables with B-W/I-W tags. Creates stratified 80/10/10 train/dev/test
13
+ splits with equal domain proportions.
14
+
15
+ Output files:
16
+ - udd-ws-v1.1-train.txt (~80K sentences)
17
+ - udd-ws-v1.1-dev.txt (~10K sentences)
18
+ - udd-ws-v1.1-test.txt (~10K sentences)
19
+
20
+ BIO format (tab-separated, blank line between sentences):
21
+ # sent_id = vlc-1
22
+ # text = Một doanh nghiệp lớn.
23
+ syllable1\tB-W
24
+ syllable2\tI-W
25
+ syllable3\tB-W
26
+ <blank line>
27
+ """
28
+
29
+ import random
30
+ from os.path import dirname, isfile, join
31
+
32
+ from underthesea import word_tokenize
33
+ from underthesea.pipeline.word_tokenize.regex_tokenize import tokenize as regex_tokenize
34
+
35
+
36
+ # Split ratios
37
+ TRAIN_RATIO = 0.80
38
+ DEV_RATIO = 0.10
39
+ TEST_RATIO = 0.10
40
+
41
+ # Domain source files, sent_id prefixes
42
+ DOMAIN_CONFIG = {
43
+ "legal": ("ws_sentences_vlc.txt", "vlc-"),
44
+ "news": ("ws_sentences_uvn.txt", "uvn-"),
45
+ "wikipedia": ("ws_sentences_uvw.txt", "uvw-"),
46
+ "fiction": ("ws_sentences_uvb_f.txt", "uvb-f-"),
47
+ "non-fiction": ("ws_sentences_uvb_n.txt", "uvb-n-"),
48
+ }
49
+
50
+
51
+ def load_sentences(filepath, prefix):
52
+ """Load sentences from idx\\tsentence file, returning (sent_id, text) tuples."""
53
+ sentences = []
54
+ with open(filepath, "r", encoding="utf-8") as f:
55
+ for line in f:
56
+ line = line.strip()
57
+ if not line:
58
+ continue
59
+ parts = line.split("\t", 1)
60
+ if len(parts) == 2:
61
+ idx = parts[0]
62
+ sent_id = f"{prefix}{idx}"
63
+ sentences.append((sent_id, parts[1]))
64
+ return sentences
65
+
66
+
67
+ def sentence_to_bio(sent_id, text):
68
+ """Convert a sentence to BIO-tagged syllable sequence.
69
+
70
+ Uses underthesea.word_tokenize to get compound tokens (with underscores),
71
+ then splits each token into syllables and assigns B-W/I-W tags.
72
+
73
+ Returns (sent_id, text, bio_pairs) or None on failure.
74
+ """
75
+ tokenized = word_tokenize(text, format="text")
76
+ if not tokenized or not tokenized.strip():
77
+ return None
78
+
79
+ tokens = tokenized.strip().split()
80
+ if not tokens:
81
+ return None
82
+
83
+ bio_pairs = []
84
+ for token in tokens:
85
+ token_text = token.replace("_", " ")
86
+ syllables = regex_tokenize(token_text)
87
+ for i, syl in enumerate(syllables):
88
+ tag = "B-W" if i == 0 else "I-W"
89
+ bio_pairs.append((syl, tag))
90
+
91
+ if not bio_pairs:
92
+ return None
93
+
94
+ return (sent_id, text, bio_pairs)
95
+
96
+
97
+ def stratified_split(domain_data, seed=42):
98
+ """Create stratified train/dev/test split preserving domain proportions.
99
+
100
+ Args:
101
+ domain_data: dict of domain_name -> list of BIO sequences
102
+
103
+ Returns:
104
+ train, dev, test lists of BIO sequences
105
+ """
106
+ random.seed(seed)
107
+
108
+ train = []
109
+ dev = []
110
+ test = []
111
+
112
+ for domain_name, sequences in domain_data.items():
113
+ shuffled = list(sequences)
114
+ random.shuffle(shuffled)
115
+
116
+ n = len(shuffled)
117
+ n_dev = max(1, round(n * DEV_RATIO))
118
+ n_test = max(1, round(n * TEST_RATIO))
119
+ n_train = n - n_dev - n_test
120
+
121
+ train.extend(shuffled[:n_train])
122
+ dev.extend(shuffled[n_train:n_train + n_dev])
123
+ test.extend(shuffled[n_train + n_dev:])
124
+
125
+ print(f" {domain_name}: {n_train} train / {n_dev} dev / {n_test} test (total: {n})")
126
+
127
+ # Shuffle each split so domains are interleaved
128
+ random.shuffle(train)
129
+ random.shuffle(dev)
130
+ random.shuffle(test)
131
+
132
+ return train, dev, test
133
+
134
+
135
+ def write_bio_file(sequences, filepath):
136
+ """Write BIO sequences to file in VLSP format with comment headers."""
137
+ with open(filepath, "w", encoding="utf-8") as f:
138
+ for sent_id, text, bio_pairs in sequences:
139
+ f.write(f"# sent_id = {sent_id}\n")
140
+ f.write(f"# text = {text}\n")
141
+ for syl, tag in bio_pairs:
142
+ f.write(f"{syl}\t{tag}\n")
143
+ f.write("\n")
144
+ print(f" Saved {len(sequences)} sentences to {filepath}")
145
+
146
+
147
+ def validate_bio_file(filepath):
148
+ """Validate BIO format constraints."""
149
+ errors = 0
150
+ sentence_count = 0
151
+ in_sentence = False
152
+
153
+ with open(filepath, "r", encoding="utf-8") as f:
154
+ for line_num, line in enumerate(f, 1):
155
+ line = line.rstrip("\n")
156
+ if not line:
157
+ if in_sentence:
158
+ sentence_count += 1
159
+ in_sentence = False
160
+ continue
161
+
162
+ # Skip comment lines
163
+ if line.startswith("#"):
164
+ continue
165
+
166
+ parts = line.split("\t")
167
+ if len(parts) != 2:
168
+ print(f" ERROR line {line_num}: expected 2 tab-separated fields, got {len(parts)}")
169
+ errors += 1
170
+ continue
171
+
172
+ syl, tag = parts
173
+ if tag not in ("B-W", "I-W"):
174
+ print(f" ERROR line {line_num}: invalid tag '{tag}'")
175
+ errors += 1
176
+
177
+ # I-W cannot start a sentence
178
+ if not in_sentence and tag == "I-W":
179
+ print(f" ERROR line {line_num}: sentence starts with I-W")
180
+ errors += 1
181
+
182
+ in_sentence = True
183
+
184
+ # Handle last sentence without trailing newline
185
+ if in_sentence:
186
+ sentence_count += 1
187
+
188
+ if errors == 0:
189
+ print(f" PASS: {sentence_count} sentences, no errors")
190
+ else:
191
+ print(f" FAIL: {sentence_count} sentences, {errors} errors")
192
+
193
+ return errors, sentence_count
194
+
195
+
196
+ def main():
197
+ base_dir = dirname(dirname(__file__))
198
+
199
+ # Load sentences from all domains
200
+ print("Loading sentences from domain files...")
201
+ domain_data = {}
202
+ total_loaded = 0
203
+
204
+ for domain, (filename, prefix) in DOMAIN_CONFIG.items():
205
+ filepath = join(base_dir, filename)
206
+ if not isfile(filepath):
207
+ print(f" WARNING: {filename} not found, skipping {domain}")
208
+ continue
209
+ sentences = load_sentences(filepath, prefix)
210
+ print(f" {domain}: loaded {len(sentences)} sentences from {filename}")
211
+ total_loaded += len(sentences)
212
+ domain_data[domain] = sentences
213
+
214
+ print(f" Total loaded: {total_loaded}")
215
+
216
+ # Convert sentences to BIO format
217
+ print("\nConverting sentences to BIO format...")
218
+ domain_bio = {}
219
+ total_converted = 0
220
+ total_failed = 0
221
+
222
+ for domain, sentences in domain_data.items():
223
+ bio_sequences = []
224
+ failed = 0
225
+ for i, (sent_id, text) in enumerate(sentences):
226
+ result = sentence_to_bio(sent_id, text)
227
+ if result:
228
+ bio_sequences.append(result)
229
+ else:
230
+ failed += 1
231
+ if (i + 1) % 5000 == 0:
232
+ print(f" {domain}: {i+1}/{len(sentences)} processed ({len(bio_sequences)} ok, {failed} failed)")
233
+ domain_bio[domain] = bio_sequences
234
+ total_converted += len(bio_sequences)
235
+ total_failed += failed
236
+ print(f" {domain}: {len(bio_sequences)} converted, {failed} failed")
237
+
238
+ print(f" Total converted: {total_converted}, failed: {total_failed}")
239
+
240
+ # Create stratified split
241
+ print("\nCreating stratified 80/10/10 split...")
242
+ train, dev, test = stratified_split(domain_bio)
243
+
244
+ total = len(train) + len(dev) + len(test)
245
+ print(f"\nSplit sizes:")
246
+ print(f" Train: {len(train)} ({100*len(train)/total:.1f}%)")
247
+ print(f" Dev: {len(dev)} ({100*len(dev)/total:.1f}%)")
248
+ print(f" Test: {len(test)} ({100*len(test)/total:.1f}%)")
249
+ print(f" Total: {total}")
250
+
251
+ # Write output files
252
+ print("\nWriting BIO files...")
253
+ train_path = join(base_dir, "udd-ws-v1.1-train.txt")
254
+ dev_path = join(base_dir, "udd-ws-v1.1-dev.txt")
255
+ test_path = join(base_dir, "udd-ws-v1.1-test.txt")
256
+
257
+ write_bio_file(train, train_path)
258
+ write_bio_file(dev, dev_path)
259
+ write_bio_file(test, test_path)
260
+
261
+ # Validate output
262
+ print("\nValidating output files...")
263
+ for name, path in [("Train", train_path), ("Dev", dev_path), ("Test", test_path)]:
264
+ print(f" {name} ({path}):")
265
+ validate_bio_file(path)
266
+
267
+ # Print sample
268
+ print("\nSample output (first sentence from train):")
269
+ if train:
270
+ sent_id, text, bio_pairs = train[0]
271
+ print(f" # sent_id = {sent_id}")
272
+ print(f" # text = {text}")
273
+ for syl, tag in bio_pairs:
274
+ print(f" {syl}\t{tag}")
275
+
276
+
277
+ if __name__ == "__main__":
278
+ main()
src/fetch_ws_sentences.py ADDED
@@ -0,0 +1,355 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # requires-python = ">=3.9"
3
+ # dependencies = [
4
+ # "datasets>=2.0.0",
5
+ # "underthesea>=6.8.0",
6
+ # ]
7
+ # ///
8
+ """
9
+ Fetch sentences for word segmentation dataset (100K total).
10
+
11
+ Fetches 20,000 sentences per domain from 4 HuggingFace datasets:
12
+ - Legal: undertheseanlp/UTS_VLC → ws_sentences_vlc.txt
13
+ - News: undertheseanlp/UVN-1 → ws_sentences_uvn.txt
14
+ - Wikipedia: undertheseanlp/UVW-2026 → ws_sentences_uvw.txt
15
+ - Fiction: undertheseanlp/UVB-v0.1 → ws_sentences_uvb_f.txt
16
+ - Non-fiction: undertheseanlp/UVB-v0.1 → ws_sentences_uvb_n.txt
17
+
18
+ Output format: idx\tsentence (one sentence per line)
19
+ """
20
+
21
+ import re
22
+ from os.path import dirname, join
23
+
24
+ from datasets import load_dataset
25
+ from underthesea import sent_tokenize, text_normalize
26
+
27
+
28
+ TARGET_PER_DOMAIN = 20000
29
+
30
+
31
+ # ============================================================================
32
+ # Shared text cleaning
33
+ # ============================================================================
34
+
35
+ def clean_text(text):
36
+ """Remove markdown formatting and clean text."""
37
+ text = text_normalize(text)
38
+ text = re.sub(r'^#+\s+', '', text, flags=re.MULTILINE)
39
+ text = re.sub(r'\*+', '', text)
40
+ text = re.sub(r'^-+$', '', text, flags=re.MULTILINE)
41
+ text = re.sub(r'\[([^\]]+)\]\([^)]+\)', r'\1', text)
42
+ text = re.sub(r'\n{2,}', '\n', text)
43
+ lines = [line.strip() for line in text.split('\n')]
44
+ text = '\n'.join(lines)
45
+ return text
46
+
47
+
48
+ def base_valid(sent):
49
+ """Shared base validation: length, Vietnamese diacritics, uppercase ratio."""
50
+ sent = sent.strip()
51
+ if not sent:
52
+ return False, sent
53
+ if len(sent) < 20 or len(sent) > 300:
54
+ return False, sent
55
+ if not re.search(r'[àáảãạăắằẳẵặâấầẩẫậèéẻẽẹêếềểễệìíỉĩịòóỏõọôốồổỗộơớờởỡợùúủũụưứừửữựỳýỷỹỵđ]', sent, re.IGNORECASE):
56
+ return False, sent
57
+ if sum(1 for c in sent if c.isupper()) > len(sent) * 0.5:
58
+ return False, sent
59
+ return True, sent
60
+
61
+
62
+ # ============================================================================
63
+ # Domain-specific validators
64
+ # ============================================================================
65
+
66
+ def is_valid_legal(sent):
67
+ """Validate sentence from legal domain (UTS_VLC)."""
68
+ ok, sent = base_valid(sent)
69
+ if not ok:
70
+ return False, sent
71
+ # Remove trailing list markers
72
+ sent = re.sub(r'\n\d+\.$', '', sent)
73
+ sent = re.sub(r'\n[a-z]\)$', '', sent)
74
+ sent = sent.strip()
75
+ if not sent:
76
+ return False, sent
77
+ # Skip legal structure headers
78
+ 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):
79
+ return False, sent
80
+ if re.match(r'^(Điều \d+|Khoản \d+|Mục \d+)', sent):
81
+ return False, sent
82
+ if sent.startswith(('English:', 'Số hiệu:', 'Ngày hiệu lực:', '---', '|')):
83
+ return False, sent
84
+ if re.search(r'\n\d+$', sent):
85
+ return False, sent
86
+ return True, sent
87
+
88
+
89
+ def is_valid_news(sent):
90
+ """Validate sentence from news domain (UVN-1)."""
91
+ ok, sent = base_valid(sent)
92
+ if not ok:
93
+ return False, sent
94
+ # Skip bylines
95
+ if re.match(r'^(Theo |PV |Nguồn:|Ảnh:|Video:|Bài:|Tin ảnh:)', sent):
96
+ return False, sent
97
+ # Skip photo captions
98
+ if re.search(r'\(Ảnh:.*\)$', sent):
99
+ return False, sent
100
+ if re.search(r'\(Nguồn:.*\)$', sent):
101
+ return False, sent
102
+ # Skip date/time at start
103
+ if re.match(r'^\d{1,2}/\d{1,2}/\d{4}', sent):
104
+ return False, sent
105
+ if re.match(r'^\d{1,2}:\d{2}', sent):
106
+ return False, sent
107
+ # Skip URLs
108
+ if re.search(r'(http|www\.|\.com|\.vn)', sent, re.IGNORECASE):
109
+ return False, sent
110
+ # Skip tags/categories
111
+ if re.match(r'^(Tags?:|Chuyên mục:|Từ khóa:)', sent, re.IGNORECASE):
112
+ return False, sent
113
+ # Skip data tables (>30% digits)
114
+ if sum(1 for c in sent if c.isdigit()) > len(sent) * 0.3:
115
+ return False, sent
116
+ return True, sent
117
+
118
+
119
+ def is_valid_wiki(sent):
120
+ """Validate sentence from Wikipedia domain (UVW-2026)."""
121
+ ok, sent = base_valid(sent)
122
+ if not ok:
123
+ return False, sent
124
+ # Skip stub markers
125
+ if re.search(r'(bài sơ khai|sơ khai về|cần được mở rộng|Thể loại:)', sent):
126
+ return False, sent
127
+ # Skip category/list pages
128
+ 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):
129
+ return False, sent
130
+ # Skip infobox remnants
131
+ if sent.count('|') > 2:
132
+ return False, sent
133
+ if re.search(r'\w+=\w+', sent) and sent.count('=') > 1:
134
+ return False, sent
135
+ # Skip reference fragments
136
+ if re.search(r'\[\d+\]', sent):
137
+ return False, sent
138
+ if re.search(r'\[cần', sent):
139
+ return False, sent
140
+ # Skip URLs
141
+ if re.search(r'(http|www\.|\.com|\.org)', sent, re.IGNORECASE):
142
+ return False, sent
143
+ # Skip data tables
144
+ if sum(1 for c in sent if c.isdigit()) > len(sent) * 0.3:
145
+ return False, sent
146
+ # Skip list items
147
+ if re.match(r'^[\*\-•]\s', sent):
148
+ return False, sent
149
+ return True, sent
150
+
151
+
152
+ def is_valid_book(sent):
153
+ """Validate sentence from book domain (UVB-v0.1) — stricter quality."""
154
+ sent = sent.strip()
155
+ if not sent:
156
+ return False, sent
157
+ # Stricter length
158
+ if len(sent) < 30 or len(sent) > 250:
159
+ return False, sent
160
+ # Word count
161
+ words = sent.split()
162
+ if len(words) < 5 or len(words) > 40:
163
+ return False, sent
164
+ # Must start with uppercase
165
+ if not sent[0].isupper():
166
+ return False, sent
167
+ # Must end with proper punctuation
168
+ if sent.rstrip()[-1] not in '.!?…"»':
169
+ return False, sent
170
+ # Stricter uppercase threshold
171
+ if sum(1 for c in sent if c.isupper()) > len(sent) * 0.3:
172
+ return False, sent
173
+ # Must contain Vietnamese diacritics
174
+ if not re.search(r'[àáảãạăắằẳẵặâấầẩẫậèéẻẽẹêếềểễệìíỉĩịòóỏõọôốồổỗộơớờởỡợùúủũụưứừửữựỳýỷỹỵđ]', sent, re.IGNORECASE):
175
+ return False, sent
176
+ # Skip too many numbers
177
+ if sum(1 for c in sent if c.isdigit()) > len(sent) * 0.15:
178
+ return False, sent
179
+ # Skip structure markers
180
+ if re.match(r'^(Chương|Phần|Mục|Điều|\d+\.|\([a-z]\))', sent):
181
+ return False, sent
182
+ # Skip URLs/emails
183
+ if re.search(r'(http|www\.|@|\.com|\.vn)', sent, re.IGNORECASE):
184
+ return False, sent
185
+ # Skip excessive punctuation
186
+ punct_count = sum(1 for c in sent if c in '.,;:!?-–—()[]{}""\'\'«»')
187
+ if punct_count > len(words) * 1.5:
188
+ return False, sent
189
+ # Skip incomplete sentences (ellipsis in middle)
190
+ if '...' in sent[:-5]:
191
+ return False, sent
192
+ # Skip dialogue-heavy
193
+ quote_count = sent.count('"') + sent.count('\u201c') + sent.count('\u201d')
194
+ if quote_count > 4:
195
+ return False, sent
196
+ return True, sent
197
+
198
+
199
+ # ============================================================================
200
+ # Book genre classification (from fetch_uvb_data.py)
201
+ # ============================================================================
202
+
203
+ FICTION_GENRES = {
204
+ "Fiction", "Novels", "Romance", "Fantasy", "Science Fiction",
205
+ "Mystery", "Thriller", "Horror", "Historical Fiction", "Literary Fiction",
206
+ "Adventure", "Crime", "Suspense", "Drama", "Short Stories"
207
+ }
208
+
209
+ NON_FICTION_GENRES = {
210
+ "Non Fiction", "Nonfiction", "History", "Biography", "Autobiography",
211
+ "Self Help", "Psychology", "Philosophy", "Science", "Politics",
212
+ "Economics", "Business", "Education", "Travel", "Memoir",
213
+ "Essays", "Reference", "Health", "Religion", "Spirituality"
214
+ }
215
+
216
+
217
+ def classify_book(genres):
218
+ """Classify book as fiction or non-fiction based on genres."""
219
+ if not genres:
220
+ return None
221
+ genres_set = set(genres)
222
+ is_fiction = bool(genres_set & FICTION_GENRES)
223
+ is_non_fiction = bool(genres_set & NON_FICTION_GENRES)
224
+ if is_fiction and not is_non_fiction:
225
+ return "fiction"
226
+ elif is_non_fiction and not is_fiction:
227
+ return "non-fiction"
228
+ elif is_fiction and is_non_fiction:
229
+ fiction_count = len(genres_set & FICTION_GENRES)
230
+ non_fiction_count = len(genres_set & NON_FICTION_GENRES)
231
+ return "fiction" if fiction_count > non_fiction_count else "non-fiction"
232
+ return None
233
+
234
+
235
+ # ============================================================================
236
+ # Sentence extraction helpers
237
+ # ============================================================================
238
+
239
+ def extract_sentences(docs, validator, target, label=""):
240
+ """Extract validated sentences from documents until target count reached."""
241
+ sentences = []
242
+ for idx, doc in enumerate(docs):
243
+ content = doc["content"]
244
+ content = clean_text(content)
245
+ for sent in sent_tokenize(content):
246
+ sent = sent.strip()
247
+ ok, cleaned = validator(sent)
248
+ if ok:
249
+ sentences.append(cleaned)
250
+ if len(sentences) >= target:
251
+ print(f" {label}: processed {idx + 1} documents, collected {len(sentences)} sentences")
252
+ break
253
+ return sentences[:target]
254
+
255
+
256
+ def extract_book_sentences(books, target, label=""):
257
+ """Extract validated sentences from books until target count reached."""
258
+ sentences = []
259
+ for i, book in enumerate(books):
260
+ if len(sentences) >= target:
261
+ break
262
+ content = clean_text(book["content"])
263
+ for sent in sent_tokenize(content):
264
+ ok, cleaned = is_valid_book(sent)
265
+ if ok:
266
+ sentences.append(cleaned)
267
+ if len(sentences) >= target:
268
+ break
269
+ if (i + 1) % 50 == 0 or len(sentences) >= target:
270
+ print(f" {label}: [{i+1}/{len(books)}] books processed, {len(sentences)} sentences")
271
+ return sentences[:target]
272
+
273
+
274
+ def save_sentences(sentences, filepath):
275
+ """Save sentences to file in idx\\tsentence format."""
276
+ with open(filepath, "w", encoding="utf-8") as f:
277
+ for i, sent in enumerate(sentences, 1):
278
+ f.write(f"{i}\t{sent}\n")
279
+ print(f" Saved {len(sentences)} sentences to {filepath}")
280
+
281
+
282
+ # ============================================================================
283
+ # Main
284
+ # ============================================================================
285
+
286
+ def main():
287
+ base_dir = dirname(dirname(__file__))
288
+
289
+ # --- Legal (UTS_VLC) ---
290
+ print(f"\n[1/5] Fetching legal sentences (target: {TARGET_PER_DOMAIN})...")
291
+ ds_vlc = load_dataset("undertheseanlp/UTS_VLC", split="2026")
292
+ vlc_sentences = extract_sentences(ds_vlc, is_valid_legal, TARGET_PER_DOMAIN, "Legal")
293
+ save_sentences(vlc_sentences, join(base_dir, "ws_sentences_vlc.txt"))
294
+
295
+ # --- News (UVN-1) ---
296
+ print(f"\n[2/5] Fetching news sentences (target: {TARGET_PER_DOMAIN})...")
297
+ ds_uvn = load_dataset("undertheseanlp/UVN-1", split="train")
298
+ uvn_sentences = extract_sentences(ds_uvn, is_valid_news, TARGET_PER_DOMAIN, "News")
299
+ save_sentences(uvn_sentences, join(base_dir, "ws_sentences_uvn.txt"))
300
+
301
+ # --- Wikipedia (UVW-2026) ---
302
+ print(f"\n[3/5] Fetching Wikipedia sentences (target: {TARGET_PER_DOMAIN})...")
303
+ ds_uvw = load_dataset("undertheseanlp/UVW-2026", split="train")
304
+ high_quality = [doc for doc in ds_uvw if (doc.get("quality_score") or 0) >= 5]
305
+ print(f" High-quality articles: {len(high_quality)}")
306
+ uvw_sentences = extract_sentences(high_quality, is_valid_wiki, TARGET_PER_DOMAIN, "Wikipedia")
307
+ save_sentences(uvw_sentences, join(base_dir, "ws_sentences_uvw.txt"))
308
+
309
+ # --- Books (UVB-v0.1) ---
310
+ print(f"\n[4/5] Fetching fiction sentences (target: {TARGET_PER_DOMAIN})...")
311
+ print(f"[5/5] Fetching non-fiction sentences (target: {TARGET_PER_DOMAIN})...")
312
+ ds_uvb = load_dataset("undertheseanlp/UVB-v0.1", split="train")
313
+
314
+ fiction_books = []
315
+ non_fiction_books = []
316
+ for book in ds_uvb:
317
+ genres = book.get("genres", [])
318
+ rating = book.get("goodreads_rating", 0) or 0
319
+ num_ratings = book.get("goodreads_num_ratings", 0) or 0
320
+ quality_score = rating * min(num_ratings / 100, 10)
321
+ book_type = classify_book(genres)
322
+ book_info = {
323
+ "title": book["title"],
324
+ "content": book["content"],
325
+ "quality_score": quality_score,
326
+ }
327
+ if book_type == "fiction":
328
+ fiction_books.append(book_info)
329
+ elif book_type == "non-fiction":
330
+ non_fiction_books.append(book_info)
331
+
332
+ fiction_books.sort(key=lambda x: x["quality_score"], reverse=True)
333
+ non_fiction_books.sort(key=lambda x: x["quality_score"], reverse=True)
334
+ print(f" Fiction books: {len(fiction_books)}, Non-fiction books: {len(non_fiction_books)}")
335
+
336
+ fiction_sentences = extract_book_sentences(fiction_books, TARGET_PER_DOMAIN, "Fiction")
337
+ save_sentences(fiction_sentences, join(base_dir, "ws_sentences_uvb_f.txt"))
338
+
339
+ nonfiction_sentences = extract_book_sentences(non_fiction_books, TARGET_PER_DOMAIN, "Non-fiction")
340
+ save_sentences(nonfiction_sentences, join(base_dir, "ws_sentences_uvb_n.txt"))
341
+
342
+ # --- Summary ---
343
+ print("\n" + "=" * 60)
344
+ print("Summary:")
345
+ print(f" Legal: {len(vlc_sentences):,}")
346
+ print(f" News: {len(uvn_sentences):,}")
347
+ print(f" Wikipedia: {len(uvw_sentences):,}")
348
+ print(f" Fiction: {len(fiction_sentences):,}")
349
+ print(f" Non-fiction: {len(nonfiction_sentences):,}")
350
+ total = len(vlc_sentences) + len(uvn_sentences) + len(uvw_sentences) + len(fiction_sentences) + len(nonfiction_sentences)
351
+ print(f" Total: {total:,}")
352
+
353
+
354
+ if __name__ == "__main__":
355
+ main()
src/ws_statistics.py ADDED
@@ -0,0 +1,250 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # requires-python = ">=3.9"
3
+ # dependencies = []
4
+ # ///
5
+ """
6
+ Convert WS BIO dataset to CoNLL-U format and compute statistics.
7
+
8
+ Reads udd-ws-v1.1-{train,dev,test}.txt (BIO format) and:
9
+ 1. Converts to CoNLL-U: udd-ws-v1.1-{train,dev,test}.conllu
10
+ 2. Prints statistics matching the style of statistics.py
11
+
12
+ CoNLL-U format: each word is a token, multi-syllable words have
13
+ syllables joined by space in FORM field (Vietnamese UD convention).
14
+ """
15
+
16
+ from collections import Counter
17
+ from os.path import dirname, isfile, join
18
+
19
+
20
+ def parse_bio_file(filepath):
21
+ """Parse BIO file into sentences with metadata and word-level tokens.
22
+
23
+ Returns list of dicts with keys: sent_id, text, words, domain.
24
+ Each word is a string (syllables joined by space for multi-syllable words).
25
+ """
26
+ sentences = []
27
+ current = {"sent_id": "", "text": "", "syllables": [], "tags": []}
28
+
29
+ with open(filepath, "r", encoding="utf-8") as f:
30
+ for line in f:
31
+ line = line.rstrip("\n")
32
+ if line.startswith("# sent_id = "):
33
+ current["sent_id"] = line.split("= ", 1)[1]
34
+ continue
35
+ if line.startswith("# text = "):
36
+ current["text"] = line.split("= ", 1)[1]
37
+ continue
38
+ if line.startswith("#"):
39
+ continue
40
+ if not line:
41
+ if current["syllables"]:
42
+ words = bio_to_words(current["syllables"], current["tags"])
43
+ domain = sent_id_to_domain(current["sent_id"])
44
+ sentences.append({
45
+ "sent_id": current["sent_id"],
46
+ "text": current["text"],
47
+ "words": words,
48
+ "domain": domain,
49
+ })
50
+ current = {"sent_id": "", "text": "", "syllables": [], "tags": []}
51
+ continue
52
+ parts = line.split("\t")
53
+ if len(parts) == 2:
54
+ current["syllables"].append(parts[0])
55
+ current["tags"].append(parts[1])
56
+
57
+ if current["syllables"]:
58
+ words = bio_to_words(current["syllables"], current["tags"])
59
+ domain = sent_id_to_domain(current["sent_id"])
60
+ sentences.append({
61
+ "sent_id": current["sent_id"],
62
+ "text": current["text"],
63
+ "words": words,
64
+ "domain": domain,
65
+ })
66
+
67
+ return sentences
68
+
69
+
70
+ def bio_to_words(syllables, tags):
71
+ """Convert syllable-level BIO tags to word list."""
72
+ words = []
73
+ current = []
74
+ for syl, tag in zip(syllables, tags):
75
+ if tag == "B-W":
76
+ if current:
77
+ words.append(" ".join(current))
78
+ current = [syl]
79
+ else:
80
+ current.append(syl)
81
+ if current:
82
+ words.append(" ".join(current))
83
+ return words
84
+
85
+
86
+ def sent_id_to_domain(sent_id):
87
+ if sent_id.startswith("vlc-"):
88
+ return "legal"
89
+ elif sent_id.startswith("uvn-"):
90
+ return "news"
91
+ elif sent_id.startswith("uvw-"):
92
+ return "wikipedia"
93
+ elif sent_id.startswith("uvb-f-"):
94
+ return "fiction"
95
+ elif sent_id.startswith("uvb-n-"):
96
+ return "non-fiction"
97
+ return "unknown"
98
+
99
+
100
+ def write_conllu(sentences, filepath):
101
+ """Write sentences to CoNLL-U format."""
102
+ with open(filepath, "w", encoding="utf-8") as f:
103
+ for sent in sentences:
104
+ f.write(f"# sent_id = {sent['sent_id']}\n")
105
+ f.write(f"# text = {sent['text']}\n")
106
+ for i, word in enumerate(sent["words"], 1):
107
+ # ID FORM LEMMA UPOS XPOS FEATS HEAD DEPREL DEPS MISC
108
+ f.write(f"{i}\t{word}\t_\t_\t_\t_\t_\t_\t_\t_\n")
109
+ f.write("\n")
110
+
111
+
112
+ def compute_statistics(sentences):
113
+ """Compute statistics from parsed sentences."""
114
+ stats = {}
115
+
116
+ stats["num_sentences"] = len(sentences)
117
+ stats["num_words"] = sum(len(s["words"]) for s in sentences)
118
+ stats["num_syllables"] = sum(
119
+ sum(len(w.split()) for w in s["words"]) for s in sentences
120
+ )
121
+
122
+ # Sentence length (in words)
123
+ sent_lengths = [len(s["words"]) for s in sentences]
124
+ stats["avg_sent_length"] = sum(sent_lengths) / len(sent_lengths) if sent_lengths else 0
125
+ stats["min_sent_length"] = min(sent_lengths) if sent_lengths else 0
126
+ stats["max_sent_length"] = max(sent_lengths) if sent_lengths else 0
127
+
128
+ # Sentence length in syllables
129
+ sent_syl_lengths = [sum(len(w.split()) for w in s["words"]) for s in sentences]
130
+ stats["avg_sent_syl_length"] = sum(sent_syl_lengths) / len(sent_syl_lengths) if sent_syl_lengths else 0
131
+
132
+ # Word length distribution (by syllable count)
133
+ word_syl_counts = Counter()
134
+ for s in sentences:
135
+ for w in s["words"]:
136
+ n_syls = len(w.split())
137
+ word_syl_counts[n_syls] += 1
138
+ stats["word_syl_counts"] = word_syl_counts
139
+
140
+ # Domain distribution
141
+ domain_counts = Counter(s["domain"] for s in sentences)
142
+ stats["domain_counts"] = domain_counts
143
+
144
+ return stats
145
+
146
+
147
+ def print_statistics(name, stats):
148
+ """Print statistics in the same format as statistics.py."""
149
+ print("=" * 60)
150
+ print(f" {name}")
151
+ print("=" * 60)
152
+
153
+ print("\n## Basic Statistics")
154
+ print(f" Sentences: {stats['num_sentences']:>10,}")
155
+ print(f" Words: {stats['num_words']:>10,}")
156
+ print(f" Syllables: {stats['num_syllables']:>10,}")
157
+ print(f" Avg word/sent: {stats['avg_sent_length']:>10.2f}")
158
+ print(f" Avg syl/sent: {stats['avg_sent_syl_length']:>10.2f}")
159
+ print(f" Avg syl/word: {stats['num_syllables']/stats['num_words']:>10.2f}")
160
+ print(f" Min word/sent: {stats['min_sent_length']:>10}")
161
+ print(f" Max word/sent: {stats['max_sent_length']:>10}")
162
+
163
+ print("\n## Word Length Distribution (by syllable count)")
164
+ print(f" {'Syllables':<12} {'Count':>10} {'Percent':>8}")
165
+ print(" " + "-" * 32)
166
+ total_words = stats["num_words"]
167
+ for n_syls in sorted(stats["word_syl_counts"]):
168
+ count = stats["word_syl_counts"][n_syls]
169
+ pct = count / total_words * 100
170
+ print(f" {n_syls:<12} {count:>10,} {pct:>7.2f}%")
171
+
172
+ print("\n## Domain Distribution")
173
+ print(f" {'Domain':<15} {'Count':>10} {'Percent':>8}")
174
+ print(" " + "-" * 35)
175
+ total_sents = stats["num_sentences"]
176
+ for domain in ["legal", "news", "wikipedia", "fiction", "non-fiction"]:
177
+ count = stats["domain_counts"].get(domain, 0)
178
+ pct = count / total_sents * 100
179
+ print(f" {domain:<15} {count:>10,} {pct:>7.2f}%")
180
+
181
+ print()
182
+
183
+
184
+ def main():
185
+ base_dir = dirname(dirname(__file__))
186
+
187
+ splits = {
188
+ "train": "udd-ws-v1.1-train.txt",
189
+ "dev": "udd-ws-v1.1-dev.txt",
190
+ "test": "udd-ws-v1.1-test.txt",
191
+ }
192
+
193
+ all_stats = {}
194
+
195
+ for split_name, filename in splits.items():
196
+ bio_path = join(base_dir, filename)
197
+ if not isfile(bio_path):
198
+ print(f"WARNING: {bio_path} not found, skipping")
199
+ continue
200
+
201
+ # Parse BIO
202
+ print(f"Reading {filename}...")
203
+ sentences = parse_bio_file(bio_path)
204
+
205
+ # Write CoNLL-U
206
+ conllu_path = bio_path.replace(".txt", ".conllu")
207
+ write_conllu(sentences, conllu_path)
208
+ print(f" → {conllu_path}")
209
+
210
+ # Compute statistics
211
+ stats = compute_statistics(sentences)
212
+ all_stats[split_name] = stats
213
+
214
+ # Print per-split statistics
215
+ for split_name, stats in all_stats.items():
216
+ print_statistics(f"udd-ws-v1.1 — {split_name}", stats)
217
+
218
+ # Print combined statistics
219
+ if all_stats:
220
+ combined = {
221
+ "num_sentences": sum(s["num_sentences"] for s in all_stats.values()),
222
+ "num_words": sum(s["num_words"] for s in all_stats.values()),
223
+ "num_syllables": sum(s["num_syllables"] for s in all_stats.values()),
224
+ "min_sent_length": min(s["min_sent_length"] for s in all_stats.values()),
225
+ "max_sent_length": max(s["max_sent_length"] for s in all_stats.values()),
226
+ "word_syl_counts": Counter(),
227
+ "domain_counts": Counter(),
228
+ }
229
+ for s in all_stats.values():
230
+ combined["word_syl_counts"] += s["word_syl_counts"]
231
+ combined["domain_counts"] += s["domain_counts"]
232
+ combined["avg_sent_length"] = combined["num_words"] / combined["num_sentences"]
233
+ combined["avg_sent_syl_length"] = combined["num_syllables"] / combined["num_sentences"]
234
+
235
+ print_statistics("udd-ws-v1.1 — TOTAL", combined)
236
+
237
+ # Summary table
238
+ print("=" * 60)
239
+ print(" Summary")
240
+ print("=" * 60)
241
+ print(f"\n {'Split':<8} {'Sentences':>10} {'Words':>10} {'Syllables':>12}")
242
+ print(" " + "-" * 42)
243
+ for split_name, stats in all_stats.items():
244
+ print(f" {split_name:<8} {stats['num_sentences']:>10,} {stats['num_words']:>10,} {stats['num_syllables']:>12,}")
245
+ print(f" {'TOTAL':<8} {combined['num_sentences']:>10,} {combined['num_words']:>10,} {combined['num_syllables']:>12,}")
246
+ print()
247
+
248
+
249
+ if __name__ == "__main__":
250
+ main()