rain1024 commited on
Commit
9075d7a
·
1 Parent(s): ed3f857

Improve WS sentence quality filters, diversity sampling, and update technical report

Browse files

- Add 14-rule quality filter pipeline: lang_detect with Vietnamese fallback,
balanced brackets, markup/glued text rejection, safe_sent_tokenize() fix
- Replace sequential extraction with round-robin sampling (MAX_PER_DOC=500,
MAX_PER_BOOK=500) for source diversity across all domains
- Add sentence_score() continuous quality function and near-duplicate detection
- Update technical report v1.1 with quality pipeline, diversity metrics, and
sentence scoring documentation
- Update sentence selection guidelines with all filter specifications

TECHNICAL_REPORT_v1.1.md CHANGED
@@ -27,8 +27,10 @@ More broadly, the review highlighted three priorities: (1) gold-standard evaluat
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 |
@@ -58,7 +60,78 @@ Sentences are drawn from 4 HuggingFace datasets, the same sources as UDD-1 v1.0
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
 
@@ -115,7 +188,11 @@ Splits are stratified by domain (each domain contributes exactly 20% to every sp
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
 
@@ -461,8 +538,10 @@ syllable3 B-W
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
@@ -487,16 +566,18 @@ The word segmentation dataset feeds into tree-1's CRF training pipeline. The gol
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
 
 
27
 
28
  | Contribution | Status | Description |
29
  |---|---|---|
30
+ | udd-ws-v1.1 dataset | Complete | 100K sentences, 5 domains, BIO format, stratified splits |
31
+ | Sentence quality pipeline | Complete | 14-rule quality filter + continuous quality scoring |
32
+ | Diversity-aware sampling | Complete | Round-robin extraction with per-source caps |
33
+ | Active learning literature survey | Complete | 35 papers covering AL for parsing, treebank construction, guidelines |
34
  | Vietnamese WS annotation guidelines | Planned | NIIVTB 9-rule framework adapted for UDD-1 |
35
  | AL framework design | This report | Concrete plan for gold-standard UD annotation |
36
  | Gold-standard annotation | Planned | Target: 2-5K sentences via active learning |
 
60
 
61
  **Table 1**: Domain breakdown of udd-ws-v1.1.
62
 
63
+ #### 2.2.1 Preprocessing
64
+
65
+ All source texts undergo Unicode normalization (`underthesea.text_normalize()`), markdown removal, and whitespace normalization before sentence segmentation. Sentence splitting uses `safe_sent_tokenize()`, a wrapper around `underthesea.sent_tokenize()` that fixes incorrect splits inside Vietnamese thousands-separator numbers (e.g., "2.000" was split into "2." + "000..."). This affected ~1,700 sentences across the corpus.
66
+
67
+ #### 2.2.2 Quality Filters
68
+
69
+ Every sentence must pass a comprehensive quality filter pipeline (14 rules) before inclusion. The full specification is in `guidelines/00. Sentence Selection/Guideline.md`.
70
+
71
+ **Common filters** (`base_valid()`, all domains):
72
+
73
+ | Category | Rule | Condition |
74
+ |----------|------|-----------|
75
+ | Structure | Length bounds | 20--300 characters |
76
+ | Structure | Minimum words | >= 4 words |
77
+ | Structure | Proper start | First character uppercase or digit |
78
+ | Structure | Proper end | Terminal punctuation (`.!?…"»"'):`) |
79
+ | Language | Vietnamese content | At least one Vietnamese diacritical character |
80
+ | Language | Not mostly uppercase | Uppercase characters <= 50% |
81
+ | Language | Language detection | `underthesea.lang_detect()` == `"vi"` with fallback: accept if 3+ Vietnamese diacritical characters (prevents false rejection of sentences with foreign proper nouns) |
82
+ | Markup | No HTML/template | Reject `{`, `}`, `<`, `>`, `\|` |
83
+ | Markup | No template key=value | Reject `\w+=\w+` (but allow spaced `=` like `GDP = 3.500 USD`) |
84
+ | Markup | No file extensions | Reject `.jpg`, `.png`, `.gif`, `.svg`, `.webp` |
85
+ | Brackets | Balanced | `(` count == `)` count; `[` count == `]` count |
86
+ | Glued text | Multi-tone detection | Reject tokens with 2+ toned vowels (Vietnamese syllables carry at most one tone mark; multiple tones indicate OCR-like merge errors) |
87
+ | Glued text | Digit-letter glue | Reject tokens with a toned vowel AND `\d[letter]` pattern |
88
+
89
+ **Domain-specific filters** add further rules: legal header/article removal, news byline/caption filtering, Wikipedia stub/infobox/reference rejection, and books apply stricter thresholds (30--250 chars, 5--40 words, <= 30% uppercase, <= 15% digits, punctuation density, no mid-sentence ellipsis, limited dialogue).
90
+
91
+ #### 2.2.3 Deduplication
92
+
93
+ Two levels of deduplication are applied during extraction (not as post-processing):
94
+
95
+ - **Exact deduplication**: Raw sentence strings are tracked in a `seen` set. Identical sentences from different documents are rejected.
96
+ - **Near-duplicate detection**: All digit sequences are normalized to `#` (`normalize_for_dedup()`), then exact-matched. This catches formulaic sentences differing only in numbers (e.g., legal clauses referencing different article numbers, news reporting different statistics).
97
+
98
+ #### 2.2.4 Diversity-Aware Sampling
99
+
100
+ Initial sequential extraction produced low source diversity: fiction was dominated by 5 books (primarily Murakami's *1Q84*), and legal text came from only 106 documents. We replaced sequential extraction with **round-robin sampling** with per-source caps:
101
+
102
+ 1. **Phase 1 (Candidate collection)**: Scan all documents/books, collecting up to `MAX_PER_DOC=500` (or `MAX_PER_BOOK=500`) valid sentences per source. For non-book domains, scanning stops at 3x the target candidate count.
103
+ 2. **Phase 2 (Round-robin selection)**: Cycle through all sources, taking one sentence per source per round, with exact and near-duplicate deduplication. This ensures no single source dominates.
104
+
105
+ Books are ranked by quality score (`goodreads_rating * min(num_ratings / 100, 10)`) and processed in descending order, so higher-quality books are scanned first.
106
+
107
+ **Source diversity achieved**:
108
+
109
+ | Domain | Sequential (before) | Round-robin (after) |
110
+ |--------|:---:|:---:|
111
+ | Legal | 106 documents | 275 documents |
112
+ | News | 1,030 documents | 3,091 documents |
113
+ | Wikipedia | 180 articles | 785 articles |
114
+ | Fiction | 5 books | 72 books |
115
+ | Non-fiction | 20 books | 68 books |
116
+
117
+ **Table 1b**: Source diversity improvement from round-robin sampling.
118
+
119
+ #### 2.2.5 Sentence Quality Score
120
+
121
+ Beyond binary pass/fail filters, each sentence is assigned a continuous quality score via `sentence_score()` returning a value in (0, 1). The score combines 6 sub-scores:
122
+
123
+ | Sub-score | Weight | Description |
124
+ |-----------|--------|-------------|
125
+ | Length | 0.20 | Gaussian around ideal range [60, 200] chars |
126
+ | Word count | 0.15 | Gaussian around ideal range [8, 35] words |
127
+ | Structure | 0.20 | Proper start (+0.5) + proper end (+0.5) |
128
+ | Cleanliness | 0.30 | Penalties for markup, unbalanced brackets, glued text, file extensions, excessive uppercase |
129
+ | Completeness | 0.15 | Penalties for unbalanced quotes, excessive digit ratio |
130
+ | Vietnamese density | multiplier | Ratio of Vietnamese diacritical characters to total letters (20%+ maps to 1.0). Applied as a **multiplier** so non-Vietnamese text scores near 0. |
131
+
132
+ Formula: `final_score = clamp(base_score * vietnamese_density, 0.01, 0.99)`
133
+
134
+ This score is used for quality reporting and will be used for active learning sentence selection (prioritizing sentences in the 0.7--0.95 range where annotation effort has the highest marginal value).
135
 
136
  ### 2.3 BIO Annotation
137
 
 
188
 
189
  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).
190
 
191
+ ### 2.6 Input Quality Summary
192
+
193
+ The 14-rule quality filter pipeline ensures that all 100,000 input sentences are well-formed Vietnamese text. Post-filtering validation confirms 0 duplicates, 0 near-duplicates, 0 unbalanced brackets, 0 markup remnants, 0 lowercase starts, 0 missing end punctuation, and 0 glued text across the entire dataset.
194
+
195
+ ### 2.7 Silver-Standard Caveat
196
 
197
  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).
198
 
 
538
 
539
  | Script | Purpose | Command |
540
  |--------|---------|---------|
541
+ | `src/fetch_ws_sentences.py` | Fetch 100K sentences with quality filters and round-robin sampling | `uv run src/fetch_ws_sentences.py` |
542
  | `src/build_ws_dataset.py` | Convert to BIO + stratified split | `uv run src/build_ws_dataset.py` |
543
+ | `src/fix_ws_errors.py` | Fix known WS errors (cross-boundary merges, always-split compounds) | `uv run src/fix_ws_errors.py` |
544
+ | `src/check_ws_errors.py` | Rule-based WS error checker (7 rules) | `uv run src/check_ws_errors.py` |
545
  | `src/ws_statistics.py` | Convert to CoNLL-U + compute statistics | `uv run src/ws_statistics.py` |
546
 
547
  ### 4.3 Intermediate Files
 
566
 
567
  UDD-1 v1.1 establishes the data and methodological foundation for building a gold-standard Vietnamese UD treebank:
568
 
569
+ 1. **udd-ws-v1.1**: A 100,000-sentence, 5-domain word segmentation dataset in BIO format, built with a rigorous 14-rule quality filter pipeline, diversity-aware round-robin sampling (72 fiction books, 68 non-fiction books, 275 legal documents, 3,091 news documents, 785 Wikipedia articles), and two-level deduplication (exact + digit-normalized near-duplicate detection). The dataset provides training data for robust tokenization models that underpin all downstream annotations.
570
+
571
+ 2. **Sentence quality infrastructure**: A continuous quality scoring function (`sentence_score()`) and comprehensive validation pipeline that ensures all input sentences are well-formed Vietnamese text, free of markup, OCR artifacts, and duplicates. The `safe_sent_tokenize()` wrapper fixes Vietnamese-specific sentence splitting errors in the upstream NLP toolkit.
572
 
573
+ 3. **Three-task active learning pipeline**: Task-specific AL strategies for each layer of the Vietnamese NLP pipeline:
574
  - **Word segmentation**: CRF token marginal uncertainty + dictionary-based error targeting → 2,000 gold sentences
575
  - **POS tagging**: Tag marginal uncertainty + confusion-pair targeting (AUX/VERB, NOUN/VERB) → 1,000 gold sentences
576
  - **Dependency parsing**: Head entropy + DPP batch diversity + partial arc annotation → 800--1,000 gold sentences
577
 
578
+ 4. **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.
579
 
580
+ 5. **Vietnamese UD guidelines**: Co-developed through the annotation process, addressing Vietnamese-specific challenges (copula, passive markers, serial verbs, classifiers, topic-comment structure).
581
 
582
  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.
583
 
guidelines/00. Sentence Selection/Guideline.md CHANGED
@@ -1,6 +1,8 @@
1
  # Sentence Selection Criteria
2
 
3
- This document describes the criteria used to select sentences for inclusion in the UDD-1 treebank. Sentences are drawn from 5 domains (Legal, News, Wikipedia, Fiction, Non-fiction), each contributing 8,000 sentences to a total of 40,000.
 
 
4
 
5
  ## 1. Preprocessing
6
 
@@ -9,20 +11,59 @@ All source texts undergo the same preprocessing before sentence selection:
9
  1. **Unicode normalization** via `underthesea.text_normalize()`
10
  2. **Markdown removal**: headers (`#`), bold/italic (`**`, `*`), links (`[text](url)`), horizontal rules (`---`)
11
  3. **Whitespace normalization**: collapse multiple newlines, strip leading/trailing whitespace per line
12
- 4. **Sentence segmentation** via `underthesea.sent_tokenize()`
13
 
14
  ## 2. Common Criteria (All Domains)
15
 
16
- Every sentence must pass the following checks:
 
 
17
 
18
  | Criteria | Condition |
19
  |----------|-----------|
20
  | Non-empty | Sentence must not be blank after stripping |
21
  | Minimum length | >= 20 characters |
22
  | Maximum length | <= 300 characters |
23
- | Contains Vietnamese | Must contain at least one Vietnamese diacritical character (e.g., à, á, ả, ã, ạ, ă, â, đ, ê, ô, ơ, ư) |
24
- | Not mostly uppercase | Uppercase characters must be <= 50% of total characters |
25
- | No URLs | Must not contain `http`, `www.`, `.com`, `.vn` |
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
 
27
  ## 3. Domain-Specific Criteria
28
 
@@ -32,7 +73,7 @@ Additional filters for legal text noise:
32
 
33
  - **Header removal**: skip lines matching `QUỐC HỘI`, `CỘNG HÒA`, `Độc lập`, `Phần thứ`, `Chương [IVX]+`, `MỤC \d+`
34
  - **Article/clause titles**: skip `Điều \d+`, `Khoản \d+`, `Mục \d+`
35
- - **Metadata lines**: skip lines starting with `English:`, `Số hiệu:`, `Ngày hiệu lực:`, `---`, `|`
36
  - **Trailing list markers**: remove trailing `1.` or `a)` patterns before validation
37
  - **Incomplete lines**: skip lines ending with a bare number
38
 
@@ -55,19 +96,18 @@ Two-stage filtering:
55
  **Stage 2 - Sentence-level**:
56
  - **Stub markers**: skip sentences containing `bài sơ khai`, `sơ khai về`, `cần được mở rộng`, `Thể loại:`
57
  - **Section headers**: skip `Thể loại`, `Danh sách`, `Xem thêm`, `Tham khảo`, `Liên kết ngoài`, `Chú thích`
58
- - **Infobox remnants**: skip sentences with more than 2 pipe characters (`|`) or multiple `key=value` patterns
59
  - **Reference fragments**: skip sentences containing `[1]`, `[2]`, `[cần dẫn nguồn]`
60
  - **Bullet lists**: skip lines starting with `*`, `-`, or `•`
61
  - **Excessive numbers**: digit characters must be <= 30% of total characters
62
 
63
  ### 3.4 Fiction & Non-fiction (source: `undertheseanlp/UVB-v0.1`)
64
 
65
- The most restrictive criteria, designed to select well-formed literary sentences:
66
 
67
  **Book-level filtering**:
68
  - Books are classified as fiction or non-fiction based on genre tags (e.g., `Novels`, `Romance`, `Fantasy` for fiction; `History`, `Biography`, `Psychology` for non-fiction)
69
  - Books are ranked by quality score: `goodreads_rating * min(num_ratings / 100, 10)`, higher-rated books are prioritized
70
- - Maximum 500 sentences per book to ensure source diversity
71
 
72
  **Sentence-level filtering** (stricter than other domains):
73
 
@@ -75,68 +115,70 @@ The most restrictive criteria, designed to select well-formed literary sentences
75
  |----------|-----------|
76
  | Minimum length | >= 30 characters (vs. 20 for others) |
77
  | Maximum length | <= 250 characters (vs. 300 for others) |
78
- | Minimum word count | >= 5 words |
79
  | Maximum word count | <= 40 words |
80
- | Starts with uppercase | First character must be uppercase |
81
- | Ends with punctuation | Last character must be one of `.!?…"»` |
82
  | Uppercase ratio | <= 30% (vs. 50% for others) |
83
  | Digit ratio | <= 15% (vs. 30% for news/wiki) |
84
  | Punctuation density | Punctuation count must be <= 1.5x word count |
85
  | No mid-sentence ellipsis | `...` must not appear before the last 5 characters |
86
- | Limited dialogue | At most 4 quotation marks (`"`, `"`, `"`) per sentence |
87
  | No chapter headers | Skip `Chương`, `Phần`, `Mục`, `Điều`, numbered items |
88
  | No URLs/emails | Skip sentences containing `http`, `www.`, `@`, `.com`, `.vn` |
89
 
90
- ## 4. Sampling Strategy
91
 
92
- - Each domain contributes exactly **8,000 sentences** (books domain: 8,000 fiction + 8,000 non-fiction)
93
- - Sentences are collected sequentially from documents until the target count is reached
94
- - For Wikipedia: only high-quality articles are used (quality_score >= 5)
95
- - For Books: books are processed in descending order of quality score
96
 
97
- ## 5. Train/Dev/Test Split
98
 
99
- After collecting all 40,000 sentences, the dataset is split using stratified sampling:
100
 
101
- | Split | Ratio | Sentences | ~Tokens |
102
- |-------|-------|-----------|---------|
103
- | Train | 91.4% | ~36,560 | ~548K |
104
- | Dev | 4.3% | ~1,720 | ~26K |
105
- | Test | 4.3% | ~1,720 | ~26K |
 
 
 
106
 
107
- ### Rationale for Split Ratio
108
 
109
- The 91.4/4.3/4.3 ratio follows established practices in Universal Dependencies:
 
 
 
110
 
111
- 1. **UD official guidelines** (universaldependencies.org) specify that for treebanks with >110K words, dev and test sets should each contain "between 10K words and 10% of the data" (de Marneffe et al., 2021). UDD-1's dev and test sets each contain ~26K tokens, comfortably exceeding the 10K-word minimum while staying under 10%.
112
 
113
- 2. **CoNLL shared task standard.** The CoNLL 2017 and 2018 shared tasks on UD parsing established 10K words as the minimum threshold for a meaningful test set (Zeman et al., 2017; 2018). UDD-1's test set is more than double this minimum.
 
 
 
 
 
 
114
 
115
- 3. **Comparable to major UD treebanks in absolute dev/test size.** Large UD treebanks allocate progressively smaller percentages to dev/test while maintaining sufficient absolute sizes:
116
 
117
- | Treebank | Total | Dev | Test | Dev% | Test% |
118
- |----------|-------|-----|------|------|-------|
119
- | Czech-PDT | 213,897 | 22,666 | 20,187 | 10.6% | 9.4% |
120
- | Korean-Kaist | 27,363 | 2,066 | 2,287 | 7.6% | 8.4% |
121
- | English-EWT | 16,622 | 2,001 | 2,077 | 12.0% | 12.5% |
122
- | Hindi-HDTB | 16,649 | 1,659 | 1,684 | 10.0% | 10.1% |
123
- | French-GSD | 16,342 | 1,476 | 416 | 9.0% | 2.5% |
124
- | Japanese-GSD | 8,100 | 507 | 543 | 6.3% | 6.7% |
125
- | Vietnamese-VTB | 3,323 | 1,123 | 800 | 33.8% | 24.1% |
126
 
127
- UDD-1's ~1,720-sentence dev/test sets are in the same range as English-EWT (~2,000) and Hindi-HDTB (~1,670).
128
 
129
- 4. **Maximizing training data.** Since UDD-1 is a silver-standard treebank intended for parser training, maximizing the training portion is beneficial. The dev/test sets at ~1,720 sentences each are large enough for reliable evaluation, while the remaining 91.4% provides maximum training signal (Nivre et al., 2020).
 
 
 
 
 
 
130
 
131
  ### Split Method
132
 
133
  - **Stratified by domain**: each domain is shuffled independently and split according to the ratios above, ensuring proportional representation across all splits
134
  - **Reproducible**: random seed = 42
135
  - Sentence IDs encode the domain: `vlc-` (legal), `uvn-` (news), `uvw-` (wikipedia), `uvb-f-` (fiction), `uvb-n-` (non-fiction)
136
-
137
- ## References
138
-
139
- - de Marneffe, M.-C., Manning, C.D., Nivre, J., & Zeman, D. (2021). Universal Dependencies. *Computational Linguistics*, 47(2), 255-308. https://aclanthology.org/2021.cl-2.11/
140
- - Nivre, J., et al. (2020). Universal Dependencies v2: An Evergrowing Multilingual Treebank Collection. In *Proceedings of LREC 2020*, pp. 4034-4043. https://aclanthology.org/2020.lrec-1.497/
141
- - Zeman, D., et al. (2017). CoNLL 2017 Shared Task: Multilingual Parsing from Raw Text to Universal Dependencies. In *Proceedings of the CoNLL 2017 Shared Task*, pp. 1-19. https://aclanthology.org/K17-3001/
142
- - Zeman, D., et al. (2018). CoNLL 2018 Shared Task: Multilingual Parsing from Raw Text to Universal Dependencies. In *Proceedings of the CoNLL 2018 Shared Task*, pp. 1-21. https://aclanthology.org/K18-2001/
 
1
  # Sentence Selection Criteria
2
 
3
+ This document describes the criteria used to select sentences for inclusion in the UDD-1 dataset. Sentences are drawn from 5 domains (Legal, News, Wikipedia, Fiction, Non-fiction), each contributing 20,000 sentences to a total of 100,000.
4
+
5
+ Implementation: `src/fetch_ws_sentences.py`
6
 
7
  ## 1. Preprocessing
8
 
 
11
  1. **Unicode normalization** via `underthesea.text_normalize()`
12
  2. **Markdown removal**: headers (`#`), bold/italic (`**`, `*`), links (`[text](url)`), horizontal rules (`---`)
13
  3. **Whitespace normalization**: collapse multiple newlines, strip leading/trailing whitespace per line
14
+ 4. **Sentence segmentation** via `safe_sent_tokenize()` — a wrapper around `underthesea.sent_tokenize()` that fixes incorrect splits inside Vietnamese thousands-separator numbers (e.g., "2.000" was split into "2." + "000...")
15
 
16
  ## 2. Common Criteria (All Domains)
17
 
18
+ Every sentence must pass all of the following checks (`base_valid()`):
19
+
20
+ ### 2.1 Structure
21
 
22
  | Criteria | Condition |
23
  |----------|-----------|
24
  | Non-empty | Sentence must not be blank after stripping |
25
  | Minimum length | >= 20 characters |
26
  | Maximum length | <= 300 characters |
27
+ | Minimum word count | >= 4 words (ensures enough syntactic structure for annotation) |
28
+ | Starts with uppercase or digit | First character must be `[A-Z]` or `[0-9]` |
29
+ | Ends with punctuation | Last character must be one of `.!?…"»"'):` |
30
+
31
+ ### 2.2 Language
32
+
33
+ | Criteria | Condition |
34
+ |----------|-----------|
35
+ | Contains Vietnamese diacritics | At least one Vietnamese-specific character (à, á, ả, ã, ạ, ă, â, đ, ê, ô, ơ, ư, and their variants) |
36
+ | Not mostly uppercase | Uppercase characters must be <= 50% of total |
37
+ | Language detection with fallback | `underthesea.lang_detect(sent)` must return `"vi"`. **Fallback**: if lang_detect rejects but the sentence contains 3+ Vietnamese diacritical characters, the sentence is accepted (prevents false rejection of Vietnamese sentences with foreign proper nouns) |
38
+
39
+ ### 2.3 Markup and Noise
40
+
41
+ | Criteria | Condition |
42
+ |----------|-----------|
43
+ | No HTML/template characters | Must not contain `{`, `}`, `<`, `>`, or `\|` |
44
+ | No template key=value | Reject `\w+=\w+` patterns (e.g., `label1=value`), but allow spaced `=` (e.g., `GDP = 3.500 USD`) |
45
+ | No file extensions | Must not contain `.jpg`, `.jpeg`, `.png`, `.gif`, `.svg`, `.webp` |
46
+ | Balanced brackets | `(` count must equal `)` count; `[` count must equal `]` count |
47
+
48
+ ### 2.4 Glued Text Detection
49
+
50
+ Vietnamese syllables each carry at most one tone mark. The following rules detect OCR-like merge errors:
51
+
52
+ | Criteria | Condition | Example |
53
+ |----------|-----------|---------|
54
+ | Multiple tones in one token | Any whitespace-delimited token with 2+ toned vowels is rejected | "lõmlà" (õ + à) → should be "lõm là" |
55
+ | Digit glued to Vietnamese text | Token has a toned vowel AND matches `\d[letter]` | "59Sẹo" → should be "59 Sẹo" |
56
+
57
+ Toned vowels: á à ả ã ạ, ắ ằ ẳ ẵ ặ, ấ ầ ẩ ẫ ậ, é è ẻ ẽ ẹ, ế ề ể ễ ệ, í ì ỉ ĩ ị, ó ò ỏ õ ọ, ố ồ ổ ỗ ộ, ớ ờ ở ỡ ợ, ú ù ủ ũ ụ, ứ ừ ử ữ ự, ý ỳ ỷ ỹ ỵ (and uppercase equivalents).
58
+
59
+ ### 2.5 Deduplication
60
+
61
+ Two levels of deduplication are applied during extraction (not as post-processing):
62
+
63
+ | Level | Method | Catches |
64
+ |-------|--------|---------|
65
+ | **Exact** | `seen` set of raw sentence strings | Identical sentences from different documents |
66
+ | **Near-duplicate** | Normalize all digit sequences to `#`, then exact match on the normalized form | Formulaic sentences differing only in numbers (e.g., legal clauses referencing different article numbers, news reporting different statistics) |
67
 
68
  ## 3. Domain-Specific Criteria
69
 
 
73
 
74
  - **Header removal**: skip lines matching `QUỐC HỘI`, `CỘNG HÒA`, `Độc lập`, `Phần thứ`, `Chương [IVX]+`, `MỤC \d+`
75
  - **Article/clause titles**: skip `Điều \d+`, `Khoản \d+`, `Mục \d+`
76
+ - **Metadata lines**: skip lines starting with `English:`, `Số hiệu:`, `Ngày hiệu lực:`, `---`
77
  - **Trailing list markers**: remove trailing `1.` or `a)` patterns before validation
78
  - **Incomplete lines**: skip lines ending with a bare number
79
 
 
96
  **Stage 2 - Sentence-level**:
97
  - **Stub markers**: skip sentences containing `bài sơ khai`, `sơ khai về`, `cần được mở rộng`, `Thể loại:`
98
  - **Section headers**: skip `Thể loại`, `Danh sách`, `Xem thêm`, `Tham khảo`, `Liên kết ngoài`, `Chú thích`
99
+ - **Infobox remnants**: skip sentences with 2+ pipe characters (`|`)
100
  - **Reference fragments**: skip sentences containing `[1]`, `[2]`, `[cần dẫn nguồn]`
101
  - **Bullet lists**: skip lines starting with `*`, `-`, or `•`
102
  - **Excessive numbers**: digit characters must be <= 30% of total characters
103
 
104
  ### 3.4 Fiction & Non-fiction (source: `undertheseanlp/UVB-v0.1`)
105
 
106
+ The most restrictive criteria, designed to select well-formed literary sentences. `is_valid_book()` calls `base_valid()` first, then applies additional checks:
107
 
108
  **Book-level filtering**:
109
  - Books are classified as fiction or non-fiction based on genre tags (e.g., `Novels`, `Romance`, `Fantasy` for fiction; `History`, `Biography`, `Psychology` for non-fiction)
110
  - Books are ranked by quality score: `goodreads_rating * min(num_ratings / 100, 10)`, higher-rated books are prioritized
 
111
 
112
  **Sentence-level filtering** (stricter than other domains):
113
 
 
115
  |----------|-----------|
116
  | Minimum length | >= 30 characters (vs. 20 for others) |
117
  | Maximum length | <= 250 characters (vs. 300 for others) |
118
+ | Minimum word count | >= 5 words (vs. 4 for others) |
119
  | Maximum word count | <= 40 words |
 
 
120
  | Uppercase ratio | <= 30% (vs. 50% for others) |
121
  | Digit ratio | <= 15% (vs. 30% for news/wiki) |
122
  | Punctuation density | Punctuation count must be <= 1.5x word count |
123
  | No mid-sentence ellipsis | `...` must not appear before the last 5 characters |
124
+ | Limited dialogue | At most 4 quotation marks per sentence |
125
  | No chapter headers | Skip `Chương`, `Phần`, `Mục`, `Điều`, numbered items |
126
  | No URLs/emails | Skip sentences containing `http`, `www.`, `@`, `.com`, `.vn` |
127
 
128
+ ## 4. Sentence Quality Score
129
 
130
+ Beyond the binary pass/fail filters, each sentence is assigned a continuous quality score via `sentence_score(sent)` returning a value in **(0, 1)**. This score can be used for ranking, quality reporting, and active learning selection.
 
 
 
131
 
132
+ ### 4.1 Sub-scores
133
 
134
+ The score combines 6 dimensions:
135
 
136
+ | Sub-score | Weight | Description |
137
+ |-----------|--------|-------------|
138
+ | **Length** | 0.20 | Gaussian around ideal range [60, 200] chars. Sentences shorter or longer are penalized smoothly. |
139
+ | **Word count** | 0.15 | Gaussian around ideal range [8, 35] words. |
140
+ | **Structure** | 0.20 | Binary checks: starts with uppercase/digit (+0.5), ends with punctuation (+0.5). |
141
+ | **Cleanliness** | 0.30 | Starts at 1.0, deducted for: markup chars (-0.3), template `=` (-0.2), unbalanced brackets (-0.2), glued text (-0.3), file extensions (-0.2), excessive uppercase (-0.2). Minimum 0.0. |
142
+ | **Completeness** | 0.15 | Starts at 1.0, deducted for: unbalanced quotes (-0.2), excessive digit ratio >30% (-0.3) or >20% (-0.1). Minimum 0.0. |
143
+ | **Vietnamese density** | multiplier | Ratio of Vietnamese diacritical characters to total letters, scaled so that 20%+ diacritics maps to 1.0. Applied as a **multiplier** on the weighted sum of other sub-scores — non-Vietnamese text scores near 0 regardless of other qualities. |
144
 
145
+ ### 4.2 Formula
146
 
147
+ ```
148
+ base_score = 0.20 * length + 0.15 * word_count + 0.20 * structure + 0.30 * cleanliness + 0.15 * completeness
149
+ final_score = clamp(base_score * vietnamese_density, 0.01, 0.99)
150
+ ```
151
 
152
+ ### 4.3 Score Interpretation
153
 
154
+ | Range | Quality | Examples |
155
+ |-------|---------|---------|
156
+ | 0.95 - 0.99 | Excellent | Well-formed Vietnamese sentence, ideal length, no noise |
157
+ | 0.80 - 0.95 | Good | Minor issues: slightly short/long, or light noise |
158
+ | 0.50 - 0.80 | Marginal | Significant issues: markup remnants, unbalanced punctuation |
159
+ | 0.10 - 0.50 | Poor | Multiple issues: heavy markup + structural problems |
160
+ | 0.01 - 0.10 | Reject | Non-Vietnamese or nearly empty |
161
 
162
+ ## 5. Sampling Strategy
163
 
164
+ - Each domain contributes exactly **20,000 unique sentences** (total: 100,000)
165
+ - Sentences are collected sequentially from documents until the target count is reached
166
+ - Both exact and near-duplicate deduplication are applied during extraction
167
+ - For Wikipedia: only high-quality articles are used (quality_score >= 5)
168
+ - For Books: books are processed in descending order of quality score
 
 
 
 
169
 
170
+ ## 6. Train/Dev/Test Split
171
 
172
+ After collecting all 100,000 sentences, the dataset is split using stratified sampling:
173
+
174
+ | Split | Ratio | ~Sentences |
175
+ |-------|-------|------------|
176
+ | Train | 80% | ~80,000 |
177
+ | Dev | 10% | ~10,000 |
178
+ | Test | 10% | ~10,000 |
179
 
180
  ### Split Method
181
 
182
  - **Stratified by domain**: each domain is shuffled independently and split according to the ratios above, ensuring proportional representation across all splits
183
  - **Reproducible**: random seed = 42
184
  - Sentence IDs encode the domain: `vlc-` (legal), `uvn-` (news), `uvw-` (wikipedia), `uvb-f-` (fiction), `uvb-n-` (non-fiction)
 
 
 
 
 
 
 
src/fetch_ws_sentences.py CHANGED
@@ -22,11 +22,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
@@ -45,17 +55,180 @@ def clean_text(text):
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
 
@@ -128,9 +301,7 @@ def is_valid_wiki(sent):
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):
@@ -150,9 +321,9 @@ def is_valid_wiki(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:
@@ -161,18 +332,9 @@ def is_valid_book(sent):
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
@@ -183,7 +345,7 @@ def is_valid_book(sent):
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)
@@ -236,38 +398,149 @@ def classify_book(genres):
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
 
 
22
  from os.path import dirname, join
23
 
24
  from datasets import load_dataset
25
+ from underthesea import lang_detect, sent_tokenize, text_normalize
26
 
27
 
28
  TARGET_PER_DOMAIN = 20000
29
 
30
+ # Vietnamese toned vowels — each syllable has at most one tone mark.
31
+ # A whitespace-delimited token with 2+ toned vowels is glued text.
32
+ TONED_VOWELS = set(
33
+ 'áàảãạắằẳẵặấầẩẫậéèẻẽẹếềểễệíìỉĩịóòỏõọốồổỗộớờởỡợúùủũụứừửữựýỳỷỹỵ'
34
+ 'ÁÀẢÃẠẮẰẲẴẶẤẦẨẪẬÉÈẺẼẸẾỀỂỄỆÍÌỈĨỊÓÒỎÕỌỐỒỔỖỘỚỜỞỠỢÚÙỦŨỤỨỪỬỮỰÝỲỶỸỴ'
35
+ )
36
+
37
+ # All Vietnamese diacritical characters (toned vowels + base vowels ă, â, ê, ô, ơ, ư, đ)
38
+ VIET_DIACRITICS = TONED_VOWELS | set('ăâêôơưđĂÂÊÔƠƯĐ')
39
+
40
 
41
  # ============================================================================
42
  # Shared text cleaning
 
55
  return text
56
 
57
 
58
+ def safe_sent_tokenize(text):
59
+ """Sentence tokenize with fix for numbers split across sentence boundaries.
60
+
61
+ underthesea's sent_tokenize splits "2.000" into ["...hơn 2.", "000 học sinh..."].
62
+ This merges consecutive sentences where the split occurred inside a number.
63
+ """
64
+ raw_sents = sent_tokenize(text)
65
+ if not raw_sents:
66
+ return raw_sents
67
+ merged = [raw_sents[0]]
68
+ for sent in raw_sents[1:]:
69
+ prev = merged[-1]
70
+ # Previous ends with digit(s) + period, current starts with digit(s)
71
+ if re.search(r'\d\s*\.\s*$', prev) and re.match(r'\d', sent):
72
+ merged[-1] = prev + sent
73
+ else:
74
+ merged.append(sent)
75
+ return merged
76
+
77
+
78
+ def sentence_score(sent):
79
+ """Score a sentence's quality on a (0, 1) scale.
80
+
81
+ Combines 6 sub-scores:
82
+ 1. Length score — Gaussian around ideal range [60, 200] chars
83
+ 2. Word count score — Gaussian around ideal range [8, 35] words
84
+ 3. Vietnamese density — ratio of Vietnamese diacritical chars to total letters
85
+ 4. Structure score — proper start (uppercase/digit) + proper end (punctuation)
86
+ 5. Cleanliness score — absence of markup, unbalanced brackets, glued text
87
+ 6. Completeness score — balanced quotes, no trailing fragments
88
+
89
+ Returns a float in (0, 1). Higher is better.
90
+ """
91
+ import math
92
+
93
+ sent = sent.strip()
94
+ if not sent:
95
+ return 0.0
96
+
97
+ # --- 1. Length score (0-1): Gaussian penalty outside [60, 200] ---
98
+ char_len = len(sent)
99
+ if 60 <= char_len <= 200:
100
+ len_score = 1.0
101
+ elif char_len < 60:
102
+ len_score = math.exp(-0.5 * ((char_len - 60) / 30) ** 2)
103
+ else:
104
+ len_score = math.exp(-0.5 * ((char_len - 200) / 60) ** 2)
105
+
106
+ # --- 2. Word count score (0-1): Gaussian penalty outside [8, 35] ---
107
+ words = sent.split()
108
+ wc = len(words)
109
+ if 8 <= wc <= 35:
110
+ wc_score = 1.0
111
+ elif wc < 8:
112
+ wc_score = math.exp(-0.5 * ((wc - 8) / 3) ** 2)
113
+ else:
114
+ wc_score = math.exp(-0.5 * ((wc - 35) / 10) ** 2)
115
+
116
+ # --- 3. Vietnamese density (0-1): diacritical chars / total letters ---
117
+ total_letters = sum(1 for c in sent if c.isalpha())
118
+ viet_chars = sum(1 for c in sent if c in VIET_DIACRITICS)
119
+ viet_score = min(viet_chars / max(total_letters, 1) * 5, 1.0) # 20%+ diacritics → 1.0
120
+
121
+ # --- 4. Structure score (0-1): start + end quality ---
122
+ start_ok = 0.5 if (sent[0].isupper() or sent[0].isdigit()) else 0.0
123
+ end_ok = 0.5 if sent[-1] in '.!?…"»"\'):' else 0.0
124
+ struct_score = start_ok + end_ok
125
+
126
+ # --- 5. Cleanliness score (0-1): penalty for noise signals ---
127
+ clean_score = 1.0
128
+ # Markup characters
129
+ if re.search(r'[{}<>|]', sent):
130
+ clean_score -= 0.3
131
+ if re.search(r'\w+=\w+', sent):
132
+ clean_score -= 0.2
133
+ # Unbalanced brackets
134
+ for o, c in [('(', ')'), ('[', ']')]:
135
+ if sent.count(o) != sent.count(c):
136
+ clean_score -= 0.2
137
+ break
138
+ # Glued text
139
+ for token in words:
140
+ tone_count = sum(1 for ch in token if ch in TONED_VOWELS)
141
+ if tone_count >= 2:
142
+ clean_score -= 0.3
143
+ break
144
+ if tone_count >= 1 and re.search(r'\d[a-zA-ZĐđÀ-ỹ]', token):
145
+ clean_score -= 0.3
146
+ break
147
+ # File extensions
148
+ if re.search(r'\.(jpg|jpeg|png|gif|svg|webp)\b', sent, re.IGNORECASE):
149
+ clean_score -= 0.2
150
+ # Excessive uppercase
151
+ if sum(1 for c in sent if c.isupper()) > len(sent) * 0.5:
152
+ clean_score -= 0.2
153
+ clean_score = max(clean_score, 0.0)
154
+
155
+ # --- 6. Completeness score (0-1): balanced quotes, no fragments ---
156
+ comp_score = 1.0
157
+ # Unbalanced quotes
158
+ double_quotes = sent.count('"') + sent.count('\u201c') + sent.count('\u201d')
159
+ if double_quotes % 2 != 0:
160
+ comp_score -= 0.2
161
+ # Excessive digit ratio
162
+ digit_ratio = sum(1 for c in sent if c.isdigit()) / max(len(sent), 1)
163
+ if digit_ratio > 0.3:
164
+ comp_score -= 0.3
165
+ elif digit_ratio > 0.2:
166
+ comp_score -= 0.1
167
+ comp_score = max(comp_score, 0.0)
168
+
169
+ # --- Weighted combination ---
170
+ # Vietnamese density is a multiplier (gate): non-Vietnamese → near 0
171
+ base_score = (
172
+ 0.20 * len_score
173
+ + 0.15 * wc_score
174
+ + 0.20 * struct_score
175
+ + 0.30 * clean_score
176
+ + 0.15 * comp_score
177
+ )
178
+ score = base_score * viet_score
179
+ return round(max(0.01, min(score, 0.99)), 4)
180
+
181
+
182
  def base_valid(sent):
183
+ """Shared base validation: length, word count, structure, language, punctuation, markup."""
184
  sent = sent.strip()
185
  if not sent:
186
  return False, sent
187
  if len(sent) < 20 or len(sent) > 300:
188
  return False, sent
189
+ # Minimum word count — ensures enough syntactic structure
190
+ if len(sent.split()) < 4:
191
+ return False, sent
192
+ # Must start with uppercase letter or digit
193
+ if not sent[0].isupper() and not sent[0].isdigit():
194
+ return False, sent
195
+ # Must end with proper punctuation (including : and ) for legal/academic)
196
+ if sent[-1] not in '.!?…"»"\'):':
197
+ return False, sent
198
  if not re.search(r'[àáảãạăắằẳẵặâấầẩẫậèéẻẽẹêếềểễệìíỉĩịòóỏõọôốồổỗộơớờởỡợùúủũụưứừửữựỳýỷỹỵđ]', sent, re.IGNORECASE):
199
  return False, sent
200
  if sum(1 for c in sent if c.isupper()) > len(sent) * 0.5:
201
  return False, sent
202
+ # Markup characters — reject template/HTML remnants
203
+ if re.search(r'[{}<>]', sent):
204
+ return False, sent
205
+ if '|' in sent:
206
+ return False, sent
207
+ # Template-like = (no spaces): reject "key=value" but allow "x = y"
208
+ if re.search(r'\w+=\w+', sent):
209
+ return False, sent
210
+ # Unbalanced brackets — opening and closing counts must match
211
+ for open_ch, close_ch in [('(', ')'), ('[', ']')]:
212
+ if sent.count(open_ch) != sent.count(close_ch):
213
+ return False, sent
214
+ # File extension remnants (wiki image markup)
215
+ if re.search(r'\.(jpg|jpeg|png|gif|svg|webp)\b', sent, re.IGNORECASE):
216
+ return False, sent
217
+ # Glued text — two syllables merged without space
218
+ for token in sent.split():
219
+ tone_count = sum(1 for c in token if c in TONED_VOWELS)
220
+ # Vietnamese syllable has at most 1 tone mark; 2+ means glued (e.g., "lõmlà")
221
+ if tone_count >= 2:
222
+ return False, sent
223
+ # Digit glued to Vietnamese text (e.g., "59Sẹo")
224
+ if tone_count >= 1 and re.search(r'\d[a-zA-ZĐđÀ-ỹ]', token):
225
+ return False, sent
226
+ # Language detection with Vietnamese diacritics fallback
227
+ if lang_detect(sent) != "vi":
228
+ # Fallback: accept if sentence has 3+ Vietnamese diacritical characters
229
+ viet_char_count = sum(1 for c in sent if c in VIET_DIACRITICS)
230
+ if viet_char_count < 3:
231
+ return False, sent
232
  return True, sent
233
 
234
 
 
301
  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):
302
  return False, sent
303
  # Skip infobox remnants
304
+ if sent.count('|') >= 2:
 
 
305
  return False, sent
306
  # Skip reference fragments
307
  if re.search(r'\[\d+\]', sent):
 
321
 
322
 
323
  def is_valid_book(sent):
324
+ """Validate sentence from book domain (UVB-v0.1) — stricter quality on top of base_valid."""
325
+ ok, sent = base_valid(sent)
326
+ if not ok:
327
  return False, sent
328
  # Stricter length
329
  if len(sent) < 30 or len(sent) > 250:
 
332
  words = sent.split()
333
  if len(words) < 5 or len(words) > 40:
334
  return False, sent
 
 
 
 
 
 
335
  # Stricter uppercase threshold
336
  if sum(1 for c in sent if c.isupper()) > len(sent) * 0.3:
337
  return False, sent
 
 
 
338
  # Skip too many numbers
339
  if sum(1 for c in sent if c.isdigit()) > len(sent) * 0.15:
340
  return False, sent
 
345
  if re.search(r'(http|www\.|@|\.com|\.vn)', sent, re.IGNORECASE):
346
  return False, sent
347
  # Skip excessive punctuation
348
+ punct_count = sum(1 for c in sent if c in '.,;:!?-\u2013\u2014()[]""\'\'\xab\xbb')
349
  if punct_count > len(words) * 1.5:
350
  return False, sent
351
  # Skip incomplete sentences (ellipsis in middle)
 
398
  # Sentence extraction helpers
399
  # ============================================================================
400
 
401
+ def normalize_for_dedup(sent):
402
+ """Normalize sentence for near-duplicate detection.
403
+
404
+ Replaces all digit sequences with '#' so that sentences differing only
405
+ in numbers (e.g., article numbers, amounts) are treated as duplicates.
406
+ Also lowercases for case-insensitive matching.
407
+ """
408
+ return re.sub(r'\d+', '#', sent.lower())
409
+
410
+
411
+ MAX_PER_DOC = 500 # Cap sentences per document to ensure source diversity
412
+
413
+
414
  def extract_sentences(docs, validator, target, label=""):
415
+ """Extract validated, deduplicated sentences from documents via round-robin.
416
+
417
+ Phase 1: Scan all documents, collect up to MAX_PER_DOC valid sentences each.
418
+ Phase 2: Round-robin across documents to ensure even source representation.
419
+ """
420
+ # Phase 1: collect candidate sentences per document
421
+ doc_pools = [] # list of [sentences]
422
  for idx, doc in enumerate(docs):
423
  content = doc["content"]
424
  content = clean_text(content)
425
+ sents = []
426
+ for sent in safe_sent_tokenize(content):
427
  sent = sent.strip()
428
  ok, cleaned = validator(sent)
429
  if ok:
430
+ sents.append(cleaned)
431
+ if len(sents) >= MAX_PER_DOC:
432
+ break
433
+ if sents:
434
+ doc_pools.append(sents)
435
+ if (idx + 1) % 200 == 0:
436
+ print(f" {label}: [{idx+1}] docs scanned, {len(doc_pools)} with valid sentences")
437
+ # Stop scanning if we have enough candidates (3x target for safety)
438
+ total_candidates = sum(len(s) for s in doc_pools)
439
+ if total_candidates >= target * 3:
440
+ print(f" {label}: [{idx+1}] docs scanned, {len(doc_pools)} with candidates, {total_candidates:,} total")
441
+ break
442
+
443
+ if not doc_pools:
444
+ return []
445
+
446
+ total_candidates = sum(len(s) for s in doc_pools)
447
+ print(f" {label}: {len(doc_pools)} docs with candidates, {total_candidates:,} total candidate sentences")
448
+
449
+ # Phase 2: round-robin selection with dedup
450
+ sentences = []
451
+ seen = set()
452
+ seen_normalized = set()
453
+ round_idx = 0
454
+
455
+ while len(sentences) < target and doc_pools:
456
+ made_progress = False
457
+ for i in range(len(doc_pools)):
458
+ sents = doc_pools[i]
459
+ if round_idx >= len(sents):
460
+ continue
461
+ cleaned = sents[round_idx]
462
+ if cleaned in seen:
463
+ continue
464
+ norm = normalize_for_dedup(cleaned)
465
+ if norm in seen_normalized:
466
+ continue
467
+ seen.add(cleaned)
468
+ seen_normalized.add(norm)
469
+ sentences.append(cleaned)
470
+ made_progress = True
471
+ if len(sentences) >= target:
472
+ break
473
+ if not made_progress:
474
  break
475
+ # Remove exhausted documents
476
+ doc_pools = [s for s in doc_pools if round_idx + 1 < len(s)]
477
+ round_idx += 1
478
+
479
+ print(f" {label}: {len(sentences):,} sentences from {round_idx} rounds")
480
  return sentences[:target]
481
 
482
 
483
+ MAX_PER_BOOK = 500 # Cap sentences per book to ensure source diversity
484
+
485
+
486
  def extract_book_sentences(books, target, label=""):
487
+ """Extract validated, deduplicated sentences from books via round-robin.
488
+
489
+ Phase 1: Extract up to MAX_PER_BOOK valid sentences from each book.
490
+ Phase 2: Round-robin across all books to ensure even representation.
491
+ """
492
+ # Phase 1: collect candidate sentences per book
493
+ book_pools = [] # list of (title, [sentences])
494
  for i, book in enumerate(books):
 
 
495
  content = clean_text(book["content"])
496
+ sents = []
497
+ for sent in safe_sent_tokenize(content):
498
  ok, cleaned = is_valid_book(sent)
499
  if ok:
500
+ sents.append(cleaned)
501
+ if len(sents) >= MAX_PER_BOOK:
502
+ break
503
+ if sents:
504
+ book_pools.append((book["title"], sents))
505
+ if (i + 1) % 50 == 0:
506
+ print(f" {label}: [{i+1}/{len(books)}] books scanned, {len(book_pools)} with valid sentences")
507
+
508
+ total_candidates = sum(len(s) for _, s in book_pools)
509
+ print(f" {label}: {len(book_pools)} books with candidates, {total_candidates:,} total candidate sentences")
510
+
511
+ # Phase 2: round-robin selection with dedup
512
+ sentences = []
513
+ seen = set()
514
+ seen_normalized = set()
515
+ round_idx = 0
516
+ books_contributed = set()
517
+
518
+ while len(sentences) < target and book_pools:
519
+ made_progress = False
520
+ for i in range(len(book_pools)):
521
+ title, sents = book_pools[i]
522
+ if round_idx >= len(sents):
523
+ continue
524
+ cleaned = sents[round_idx]
525
+ if cleaned in seen:
526
+ continue
527
+ norm = normalize_for_dedup(cleaned)
528
+ if norm in seen_normalized:
529
+ continue
530
+ seen.add(cleaned)
531
+ seen_normalized.add(norm)
532
+ sentences.append(cleaned)
533
+ books_contributed.add(title)
534
+ made_progress = True
535
+ if len(sentences) >= target:
536
+ break
537
+ if not made_progress:
538
+ break
539
+ # Remove exhausted books
540
+ book_pools = [(t, s) for t, s in book_pools if round_idx + 1 < len(s)]
541
+ round_idx += 1
542
+
543
+ print(f" {label}: {len(sentences):,} sentences from {len(books_contributed)} books ({round_idx} rounds)")
544
  return sentences[:target]
545
 
546
 
ws_sentences_uvb_f.txt CHANGED
The diff for this file is too large to render. See raw diff
 
ws_sentences_uvb_n.txt CHANGED
The diff for this file is too large to render. See raw diff
 
ws_sentences_uvn.txt CHANGED
The diff for this file is too large to render. See raw diff
 
ws_sentences_uvw.txt CHANGED
The diff for this file is too large to render. See raw diff
 
ws_sentences_vlc.txt CHANGED
The diff for this file is too large to render. See raw diff