twfilter 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
data/README.md CHANGED
@@ -1,12 +1,22 @@
1
- # twfilter
1
+ # twfilter · 臺灣華語文本篩選
2
2
 
3
- Provenance analysis for Chinese text: is this span Taiwan Mandarin (臺灣華語), and if not,
4
- on what evidence. Pure Ruby, no runtime dependencies, no native extensions, no network,
5
- deterministic output.
3
+ [![Gem](https://img.shields.io/gem/v/twfilter)](https://rubygems.org/gems/twfilter)
4
+ [![DOI](https://zenodo.org/badge/1320326341.svg)](https://doi.org/10.5281/zenodo.21761465)
6
5
 
7
- Traditional Chinese is written in Taiwan, Hong Kong and Macau, and by mainland publishers
8
- converting from simplified. Script alone does not identify origin. Every string below is
9
- written in traditional characters, and only three of them are Taiwan Mandarin.
6
+ Decides whether a span of Chinese text may enter a corpus of Taiwanese Mandarin\* (臺灣華語,
7
+ `cmn-Hant-TW`) and reports the evidence for every rejection. Pure Ruby, no runtime
8
+ dependencies, no native extensions, no network, deterministic output.
9
+
10
+ 判斷一段中文能不能收進臺灣華語語料庫,每個不收的理由都會列出來。純 Ruby,沒有相依套件,不用原生擴充,
11
+ 不連網路,同樣的輸入永遠得到同樣的結果。
12
+
13
+ **English** · [中文](#中文)
14
+
15
+ ## English
16
+
17
+ Traditional characters are written in Taiwan, Hong Kong and Macau, and by publishers in China
18
+ who convert from simplified. Script alone does not identify origin. Of the strings below, only
19
+ the first and the last are Taiwanese Mandarin:
10
20
 
11
21
  ```ruby
12
22
  TWFilter.keep?("這個政策有沒有經過完整評估?") # => true
@@ -14,65 +24,90 @@ TWFilter.keep?("请把这个信息转发给同事") # => false (simplifi
14
24
  TWFilter.keep?("請把這個信息轉發給同事") # => false (lexicon: 信息, Taiwan writes 資訊)
15
25
  TWFilter.keep?("他站在門裏面等了很久") # => false (orthography: 裏, Taiwan writes 裡)
16
26
  TWFilter.keep?("佢哋唔知道發生咗咩事") # => false (Cantonese particles)
17
- TWFilter.keep?("這事兒辦得挺漂亮的") # => false (erhua suffix on 事)
18
- TWFilter.keep?("他的女兒今年考上大學") # => true (兒 here is a root morpheme)
27
+ TWFilter.keep?("這事兒辦得挺漂亮的") # => false (erhua: 事兒)
28
+ TWFilter.keep?("他的女兒今年考上大學") # => true (女兒 is not an erhua form)
19
29
  ```
20
30
 
21
- Depth matters as much as breadth. Conversion tables are not provenance signals, and
22
- subject matter is not provenance either:
31
+ Conversion tables are not provenance signals, and subject matter is not provenance either:
23
32
 
24
33
  ```ruby
25
34
  # 程序 is ordinary Taiwanese legal vocabulary, not a mainland form
26
35
  TWFilter.keep?("行政程序法所定之程序應由主管機關進行") # => true
27
36
 
28
- # 了嗎 is attested in every native Taiwanese source; it is not a marker
37
+ # 了嗎 is ordinary in Taiwanese prose; it is not a marker
29
38
  TWFilter.keep?("你吃飯了嗎?我們等一下再出發。") # => true
30
39
 
31
40
  # Ambiguous vocabulary is flagged for review, not discarded
32
41
  TWFilter.examine("這個視頻的畫質很不錯").marks.map(&:code) # => [:mainland_soft]
33
42
 
34
- # Taiwanese reporting about China is Taiwan Mandarin; the topic is tagged, not rejected
43
+ # Taiwanese reporting about China is Taiwanese Mandarin; the topic is tagged, not rejected
35
44
  TWFilter.examine("行政院昨天回應了北京的最新聲明").marks.map(&:code) # => [:foreign_topic]
36
45
 
37
46
  # 南京 is also a Taipei street; an address suffix suppresses the topic tag
38
47
  TWFilter.examine("臺北市南京東路五段的捷運站出口").findings # => []
39
48
  ```
40
49
 
41
- Provenance is decided on orthography, character inventory, lexical choice, morphology and
42
- a positive evidence signal, and every criterion that fired is reported.
50
+ The checks cover orthography, character inventory, lexical choice and morphology, and a
51
+ positive-evidence count; every criterion that fired is reported. Passing them is not proof of
52
+ Taiwanese origin; see [Limits](#limits).
53
+
54
+ ### Install
55
+
56
+ ```ruby
57
+ gem "twfilter", "~> 0.2"
58
+ ```
59
+
60
+ Ruby 3.4 or later.
61
+
62
+ ### What it does and does not do
43
63
 
44
- ## What it does and does not do
64
+ **Does:** decide whether a span shows signs of a variety other than Taiwanese Mandarin;
65
+ normalize punctuation to the Taiwan standard; split text into sentences; report a
66
+ character-difficulty tier; report every reason for every decision.
45
67
 
46
- **Does** — decide provenance of a span of text; normalize punctuation to the Taiwan
47
- standard; segment into sentences; report a character-difficulty tier; report every reason
48
- for every decision.
68
+ **Does not:** segment words, tag parts of speech, identify the language (it assumes Han-script
69
+ input), translate, convert between simplified and traditional, or judge grammaticality. A
70
+ rejected span is not ungrammatical; it is _not Taiwanese_.
49
71
 
50
- **Does not** — segment words, tag parts of speech, detect language (assume Han script
51
- input), translate, convert between simplified and traditional, or judge grammaticality.
52
- A span rejected here is not ungrammatical; it is *not Taiwanese*.
72
+ ### Limits
53
73
 
54
- ## Applications
74
+ Mainland text converted to traditional characters by OpenCC passes the `corpus` policy at
75
+ 98.5 % (`s2tw`) and 99.6 % (`s2twp`), against 99.7 % for native Taiwanese text (provenance
76
+ checks only, test part of the [evaluation set](#evaluation)). Conversion leaves almost no
77
+ trace at the sentence level: `s2tw` maps characters to Taiwan's standard forms, `s2twp` also
78
+ replaces mainland vocabulary with Taiwan vocabulary, and only 0.5–1.6 % of converted sentences
79
+ contain a reviewed conversion artefact that never occurs in native text. Passing the filter
80
+ therefore does not establish Taiwanese origin. Origin has to come from the provenance of the
81
+ source: who published the text, and where.
82
+
83
+ The erhua list (玩兒, 事兒, 點兒) was sized on encyclopedic and official text. Colloquial
84
+ mainland text, where 這兒, 那兒 and 哪兒 are frequent, is not in the evaluation set.
85
+
86
+ ### Applications
55
87
 
56
88
  1. **Learner-facing corpora.** Extracted from [TaiwanCards](https://taiwancards.com), where
57
- it gates every sentence, gloss and collocation before it can reach a card. The
58
- `publishable` policy encodes the boundary of the pedagogical inventory: MOE 常用 4 808
59
- only, no ambiguous vocabulary, MOE punctuation only.
60
- 2. **Web corpus construction.** Filtering crawl output where the language identifier
61
- reports `zho_Hant` but the provenance is unknown. Traditional-script crawls conflate
62
- four written standards; this separates them at 10⁴ sentences per second per core.
63
- 3. **Training-set curation.** Building or auditing a monolingual set for a model intended
64
- to produce Taiwan Mandarin rather than converted mainland text. `Report#findings` is
65
- machine-readable, so exclusions stay attributable.
66
- 4. **Editorial and localization QA.** Detecting mainland vocabulary, orthography and
67
- punctuation in copy that is supposed to be Taiwanese — the `mainland_soft` band is
68
- designed for review queues rather than automatic rejection.
69
-
70
- ## Decision procedure
89
+ it gates every sentence, gloss and collocation before it reaches a card. The
90
+ `publishable` policy encodes the pedagogical inventory: the 4 808 characters of the MOE
91
+ 常用 chart plus the 13 characters admitted at that tier, no ambiguous vocabulary, MOE
92
+ punctuation only.
93
+ 2. **Web corpus construction.** Filtering crawl output where the language identifier reports
94
+ `zho_Hant` but the provenance is unknown. Traditional-script crawls conflate four written
95
+ standards; this removes simplified and mainland-orthography text, written Cantonese and
96
+ listed mainland vocabulary. It does not remove mainland text converted by OpenCC
97
+ ([Limits](#limits)); host-level provenance has to do that part.
98
+ 3. **Training-set curation.** Building or auditing a monolingual set for a model meant to
99
+ produce Taiwanese Mandarin. `Report#findings` is machine-readable, so every exclusion
100
+ stays attributable.
101
+ 4. **Editorial and localization QA.** Finding mainland vocabulary, orthography and
102
+ punctuation in copy meant to be Taiwanese. The `mainland_soft` band is designed for review
103
+ queues rather than automatic rejection.
104
+
105
+ ### Decision procedure
71
106
 
72
107
  ```mermaid
73
108
  flowchart TD
74
- T["input span"] --> N["Punctuation.normalize<br/>教育部《重訂標點符號手冊》"]
75
- N --> SH
109
+ T["input span<br/>(punctuation already normalized by the caller)"] --> U["Unicode NFC<br/>compatibility ideographs → unified characters"]
110
+ U --> SH
76
111
 
77
112
  subgraph SH["Checks::Shape"]
78
113
  A1["han count ∈ policy.han_range"]
@@ -84,16 +119,16 @@ flowchart TD
84
119
  subgraph SC["Checks::Script — character inventory"]
85
120
  B1["simplified-only set<br/>OpenCC STCharacters ∖ TSCharacters ∖ Taiwan variants"]
86
121
  B2["converted orthography 裏着衞爲説麽綫墻眞啓衆産囯麪"]
87
- B3["MOE tier ≤ policy.max_tier"]
122
+ B3["MOE tier ≤ policy.max_tier; 〇 admitted at 常用"]
88
123
  end
89
124
 
90
125
  SC --> LX
91
126
  subgraph LX["Checks::Lexicon, Erhua, Wenyan"]
92
- C1["mainland hard ×149 → reject"]
93
- C2["mainland soft ×38 → mark"]
127
+ C1["mainland hard ×144 → reject"]
128
+ C2["mainland soft ×43 → mark"]
94
129
  C3["Cantonese characters ×17, HK/SEA lexis ×19 → reject"]
95
130
  C4["foreign topics ×80 → mark"]
96
- C5["erhua: 兒 outside a headed or tailed window → reject"]
131
+ C5["erhua: 玩兒 事兒 點兒, unless 兒 opens a root such as 兒童 → reject"]
97
132
  C6["literary density > 0.05 → reject"]
98
133
  end
99
134
 
@@ -101,53 +136,62 @@ flowchart TD
101
136
  EV --> R["Report{ok?, findings[], tier, han, evidence}"]
102
137
  ```
103
138
 
104
- Positive evidence never rejects. `了嗎` is not a defect: it is attested in every native
105
- source measured. `有` as a perfective marker counts in favour, never against — but only
106
- outside negation, since `沒有看` and `有沒有看` are pan-Mandarin and carry no Taiwan signal.
107
-
108
- ## Input and output
109
-
110
- **Input** — anything responding to `to_s`. Empty, whitespace-only, Latin-only and
111
- supplementary-plane input are reported, not raised on. Invalid byte sequences must be
112
- scrubbed by the caller. There is no length limit; segmentation and normalization are
113
- linear in input length.
114
-
115
- **Output** — `TWFilter::Report`:
116
-
117
- | member | meaning |
118
- | --- | --- |
119
- | `ok?` | true iff no finding has severity `:reject` |
120
- | `findings` | every criterion that fired, in check order |
121
- | `rejects`, `marks` | the two severity partitions; their union is `findings` |
122
- | `tier` | highest MOE chart index reached: 0 常用, 1 次常用, 2 罕用, `nil` if unlisted |
123
- | `han` | Han character count |
124
- | `evidence` | count of positive Taiwan signals |
125
- | `reasons` | `rejects` rendered as `"code: detail"` strings |
126
- | `to_h` | plain data, JSON-serializable |
127
-
128
- A `Finding` is `{check, code, severity, detail}`. Codes are stable across releases;
129
- severity depends on the policy. Nothing is ever discarded silently — `keep?` is a
130
- convenience over `examine`, not a separate path.
131
-
132
- ## Policies
139
+ `examine` does not normalize punctuation; call `normalize` first (see
140
+ [Placement in a pipeline](#placement-in-a-pipeline)). Every lexical marker is a substring
141
+ match. A marker inside a longer attested string is suppressed by a mask listed in
142
+ `mainland_exceptions.tsv` (博客來, 數字段票, 洪水平原); no mask is generated.
143
+
144
+ Positive evidence never rejects. `了嗎` occurs in 141 New Taipei City press-release sentences
145
+ and 24 Common Voice zh-TW sentences of the evaluation set, so it is not a marker. `有` as a
146
+ perfective marker counts in favor, never against, and only outside negation: `沒有看` and
147
+ `有沒有看` are pan-Mandarin and carry no Taiwan signal.
148
+
149
+ ### Input and output
150
+
151
+ **Input:** anything that responds to `to_s`, as a UTF-8 string; another encoding raises
152
+ `Encoding::CompatibilityError`, and invalid byte sequences must be scrubbed by the caller.
153
+ Empty, whitespace-only, Latin-only and supplementary-plane input is reported, not raised on.
154
+ There is no length limit; segmentation and normalization are linear in input length. The
155
+ checks run on the Unicode NFC form of the input, so a CJK compatibility ideograph such as
156
+ U+F934 is judged as the unified character U+8001. `Report#text` returns the caller's string
157
+ unchanged, and every finding detail quotes the caller's own spelling.
158
+
159
+ **Output:** `TWFilter::Report`:
160
+
161
+ | member | meaning |
162
+ | ------------------ | ---------------------------------------------------------------------------- |
163
+ | `ok?` | true iff no finding has severity `:reject` |
164
+ | `findings` | every criterion that fired, in check order |
165
+ | `rejects`, `marks` | the two severity partitions; their union is `findings` |
166
+ | `tier` | highest MOE chart index reached: 0 常用, 1 次常用, 2 罕用, `nil` if unlisted |
167
+ | `han` | Han character count |
168
+ | `evidence` | count of positive Taiwan signals |
169
+ | `reasons` | `rejects` rendered as `"code: detail"` strings |
170
+ | `to_h` | plain data, JSON-serializable |
171
+
172
+ A `Finding` is `{check, code, severity, detail}`. Codes are stable across releases; severity
173
+ depends on the policy. Nothing is discarded silently: `keep?` is a shorthand for
174
+ `examine(...).ok?`, not a separate path.
175
+
176
+ ### Policies
133
177
 
134
178
  Immutable value objects. Derive with `#with`.
135
179
 
136
- | | `corpus` | `publishable` | `permissive` |
137
- | --- | --- | --- | --- |
138
- | han count | 6–60 | 6–40 | 1–∞ |
139
- | han ratio | ≥ 0.65 | ≥ 0.70 | 0 |
140
- | character tier | ≤ 罕用 | ≤ 常用 4 808 | ≤ 罕用 |
141
- | soft lexical markers | mark | reject | mark |
142
- | foreign topics | mark | reject | mark |
143
- | punctuation inventory | wide | MOE strict | wide |
144
- | converted orthography | reject | reject | reject |
180
+ | | `corpus` | `publishable` | `permissive` |
181
+ | --------------------- | -------- | ------------- | ------------ |
182
+ | han count | 6–60 | 6–40 | 1–∞ |
183
+ | han ratio | ≥ 0.65 | ≥ 0.70 | 0 |
184
+ | character tier | ≤ 罕用 | ≤ 常用 4 808 | ≤ 罕用 |
185
+ | soft lexical markers | mark | reject | mark |
186
+ | foreign topics | mark | reject | mark |
187
+ | punctuation inventory | wide | MOE strict | wide |
188
+ | converted orthography | reject | reject | reject |
145
189
 
146
190
  ```ruby
147
191
  TWFilter::Policy.corpus.with(max_tier: :secondary, han_range: (4..80))
148
192
  ```
149
193
 
150
- ## Usage
194
+ ### Usage
151
195
 
152
196
  ```ruby
153
197
  require "twfilter"
@@ -179,19 +223,19 @@ TWFilter.sentences("他說:「好。」我走了。") # => ["他說:「好
179
223
  TWFilter.tier("散步") # => 0
180
224
  TWFilter.tier("饕餮") # => 1
181
225
 
182
- # Block judgement — a paragraph is accepted as a unit or not at all
226
+ # Block judgment: a paragraph is accepted as a unit or not at all
183
227
  TWFilter::Block.judge(paragraph_sentences)
184
228
 
185
229
  # Table fingerprint, to record beside derived measurements
186
230
  TWFilter.provenance
187
- # => {version: "1.0.0", dir: "…/lib/twfilter/data", tables: 19, digest: "14cd9fd7fc97dc9a"}
231
+ # => {version: "0.2.0", dir: "…/lib/twfilter/data", overlay: nil, tables: 21, digest: "c2d3ca4229d644fb"}
188
232
  ```
189
233
 
190
- ## Placement in a pipeline
234
+ ### Placement in a pipeline
191
235
 
192
- Normalize before segmenting: the ellipsis and dash rules change sentence boundaries.
193
- Segment before examining: the shape thresholds are defined on sentences. Examine before
194
- deduplicating and counting, so rejected material never reaches the statistics.
236
+ Normalize before segmenting: the ellipsis and dash rules change sentence boundaries. Segment
237
+ before examining: the shape thresholds are defined on sentences. Examine before deduplicating
238
+ and counting, so rejected material never reaches the statistics.
195
239
 
196
240
  ```text
197
241
  acquire → normalize → segment → examine → deduplicate → tokenize → count
@@ -201,80 +245,134 @@ acquire → normalize → segment → examine → deduplicate → tokenize → c
201
245
 
202
246
  `Block.judge` is an optional stage between segmentation and examination for sources whose
203
247
  documents are topically coherent: it rejects a whole window when any member fails, and
204
- requires a minimum density of positive evidence across the window. Use it on crawls, not
205
- on dictionaries.
206
-
207
- ## Performance
208
-
209
- Single core, Apple M5 Max, on 199 936 sentences of Taiwanese web text (6.2 M characters):
210
-
211
- | operation | throughput | per 10⁷ sentences |
212
- | --- | ---: | ---: |
213
- | `Sentences.split` | 741 000 /s · 68 MB/s | 13 s |
214
- | `Punctuation.normalize` | 67 000 /s · 6.1 MB/s | 149 s |
215
- | `tier` | 134 000 /s · 12 MB/s | 75 s |
216
- | `examine` (all five checks) | **10 700 /s · 1.0 MB/s** | 934 s |
217
-
218
- Suitable for corpora of arbitrary size. Cost is linear in input length and dominated by
219
- `Checks::Lexicon`, which scans 264 union-compiled patterns per span; the other four checks
220
- together account for under a third of the total. Memory is constant — tables load once
221
- (≈ 3 MB resident) and every entry point is a pure function over a string, so the work
222
- parallelizes by `fork` or by thread without coordination.
223
-
224
- A 37.7 M-sentence corpus takes ≈ 3.5 minutes of wall time across 18 cores. In practice
225
- I/O, JSON parsing and deduplication dominate; this library is not usually the bottleneck.
226
-
227
- ## Reference tables
228
-
229
- `lib/twfilter/data/` — plain text, one record per line, tab-separated where a record has
248
+ requires a minimum density of positive evidence across the window. Use it on crawls, not on
249
+ dictionaries.
250
+
251
+ ### Relation to existing corpora
252
+
253
+ Existing Taiwanese Mandarin resources control provenance at acquisition time:
254
+ [TaiwanWaC](https://www.sketchengine.eu/taiwanwac-chinese-corpus/) (260 M words) by
255
+ collecting traditional-script web text, the
256
+ [Sinica TMC](https://tmc.ling.sinica.edu.tw/corpus_list_en/) and
257
+ [NCCU](https://spokentaiwanmandarin.nccu.edu.tw/) spoken corpora by recording speakers in
258
+ Taiwan. None of them publishes "is this span Taiwanese Mandarin" as a reusable decision, and
259
+ acquisition-time control does not transfer to new text.
260
+
261
+ The gap is measurable. Over 37.8 M sentences that had **already** passed a `.tw`-host /
262
+ `html_lang: zh-TW` admission gate (the
263
+ [twngrams](https://huggingface.co/datasets/taiwan-corpora/twngrams) build), the 0.1.0 checks
264
+ removed 1.72 % on character inventory, a further 1.80 % on lexicon (mainland pairs, written
265
+ Cantonese, Hong Kong and Singapore forms) and the block-evidence policy another 20.20 %: 23 %
266
+ of what URL metadata alone would have admitted. Mainland text converted by a phrase-aware
267
+ converter is not part of that residue: it passes ([Limits](#limits)).
268
+
269
+ ### Evaluation
270
+
271
+ Measured on an evaluation set of 515 306 sentences with 6–60 Han characters, split into dev
272
+ and test parts by a hash of each sentence. The method, sources and scripts are in
273
+ [`tools/benchmark/`](tools/benchmark/). The sentences are not distributed: the set is rebuilt
274
+ from the official releases listed in `tools/benchmark/sources_manifest.json`.
275
+
276
+ | class | sources | sentences |
277
+ | --------- | --------------------------------------------------------------------------------------------------------------------------- | --------: |
278
+ | native | Common Voice zh-TW sentences (CC0), 全國法規資料庫 statutes, New Taipei City press releases (OGDL v1, Copyright Act art. 9) | 367 929 |
279
+ | converted | 44 468 Common Voice zh-CN sentences converted by OpenCC 1.4.2 as `s2t`, `s2tw`, `s2twp` | 133 399 |
280
+ | Hong Kong | Common Voice zh-HK sentences | 13 978 |
281
+
282
+ Acceptance on the test part under the `corpus` policy, provenance checks only (shape checks
283
+ excluded), 0.2.0, with 95 % Wilson intervals:
284
+
285
+ | class | sentences | accepted |
286
+ | ---------------------------------- | --------: | ---------------------: |
287
+ | native, Common Voice zh-TW | 7 454 | 99.85 % [99.74, 99.92] |
288
+ | native, statutes | 2 500 | 99.96 % [99.77, 99.99] |
289
+ | native, press releases | 2 500 | 98.84 % [98.34, 99.19] |
290
+ | converted, `s2t` | 10 000 | 77.06 % [76.23, 77.87] |
291
+ | converted, `s2tw` | 10 000 | 98.53 % [98.27, 98.75] |
292
+ | converted, `s2twp` | 10 000 | 99.58 % [99.43, 99.69] |
293
+ | Hong Kong, no Cantonese characters | 3 596 | 89.57 % [88.53, 90.53] |
294
+ | Hong Kong, Cantonese characters | 3 257 | 8.14 % [7.25, 9.13] |
295
+
296
+ The classes differ in topic and register as well as in variety: the converted sentences are
297
+ mostly Wikipedia text, the native ones mostly statutes and press releases. A figure that
298
+ separates the classes may separate topics. The converted class is simulated with OpenCC
299
+ rather than collected from the web.
300
+
301
+ ### Performance
302
+
303
+ Single core, Apple M5 Max, on 199 936 sentences of Taiwanese web text (6.2 M characters),
304
+ measured with 0.1.0:
305
+
306
+ | operation | throughput | per 10⁷ sentences |
307
+ | --------------------------- | -----------------------: | ----------------: |
308
+ | `Sentences.split` | 741 000 /s · 68 MB/s | 13 s |
309
+ | `Punctuation.normalize` | 67 000 /s · 6.1 MB/s | 149 s |
310
+ | `tier` | 134 000 /s · 12 MB/s | 75 s |
311
+ | `examine` (all five checks) | **10 700 /s · 1.0 MB/s** | 934 s |
312
+
313
+ 0.2.0 adds an NFC test per span; the table has not been re-measured. Cost is linear in input
314
+ length. `Checks::Lexicon`, which scans five union-compiled patterns over 303 terms per span,
315
+ takes about half of `examine`, and the positive-evidence count about a quarter. Memory is
316
+ constant: the tables load once, on first use (about 15 MB resident with Ruby 4.0), and every
317
+ entry point is a pure function over a string, so the work parallelizes by `fork` or by thread
318
+ without coordination.
319
+
320
+ In the twngrams build, the script and lexicon stages over 37.8 M sentences took 536 s of wall
321
+ time and 4 347 CPU seconds, including I/O and JSON parsing.
322
+
323
+ ### Reference tables
324
+
325
+ `lib/twfilter/data/`: plain text, one record per line, tab-separated where a record has
230
326
  fields. Diffable, reviewable and versioned with the gem.
231
327
 
232
- | table | rows | content |
233
- | --- | ---: | --- |
234
- | `moe_common/secondary/rare.txt` | 4 808 / 6 343 / 18 356 | 教育部標準字體表 |
235
- | `moe_exception.txt` | 12 | dictionary headword characters outside all three charts |
236
- | `simplified_only.txt` | 3 785 | derived from the OpenCC round-trip |
237
- | `variants_used_in_taiwan.txt` | 16 | simplified-looking forms standard in Taiwan |
238
- | `converted_orthography.txt` | 14 | mainland traditional variants |
239
- | `mainland_hard.tsv` | 149 | rejecting pairs, with attestation counts |
240
- | `mainland_soft.tsv` | 38 | marking pairs, ambiguous or dominated |
241
- | `mainland_exceptions.tsv` | 6 | superstrings in which a marker is legitimate |
242
- | `cantonese.txt` | 17 | written-Cantonese characters outside the 常用 chart |
243
- | `regional_hard.tsv` | 19 | Hong Kong, Cantonese-sequence and Singapore forms |
244
- | `foreign_topics.txt` | 80 | non-Taiwanese toponyms and institutions — subject matter, not provenance |
245
- | `taiwan_markers/lexicon/particles/grammar.txt` | 66 / 51 / 7 / 20 | positive evidence |
246
- | `erhua_headed/tailed.txt` | 14 / 36 | 兒 as a root morpheme |
247
- | `wenyan.txt` | 4 | literary particles for density estimation |
248
- | `MANIFEST.json` | — | row count and SHA-256 per table |
249
-
250
- **Grading.** Candidate pairs are graded by attestation ratio against a reference corpus of
251
- ten natively Taiwanese sources, 11 923 110 characters: *hard* when the mainland form is
252
- unattested and the Taiwan form occurs at least three times; *soft* when the Taiwan form
253
- dominates by 20 : 1 or the pair is hand-graded ambiguous; excluded otherwise. Most candidates
254
- are excluded — conversion tables built for orthographic mapping contain many pairs where both
255
- forms are ordinary Taiwanese.
256
-
257
- The reference corpus admits no source with an open authorship gate. Open web comments on
258
- Taiwanese channels are Taiwan-hosted but not Taiwan-authored: every mainland form attested
259
- anywhere in the corpus occurs there and only there, so counting them would license the
260
- mainland vocabulary of mainland commenters as Taiwanese.
261
-
262
- **Membership.** Each table states the rule that admits a row, and `spec/twfilter/membership_spec.rb`
263
- enforces it against the shipped data:
264
-
265
- | table | a row is admitted iff |
266
- | --- | --- |
267
- | `cantonese.txt` | the character is used in written Cantonese and is not in 常用國字標準字體表 |
268
- | `regional_hard.tsv` | the form is unattested in Taiwan and its Taiwan counterpart occurs ≥ 3 times |
269
- | `converted_orthography.txt` | the form is in no MOE chart and the Taiwan form outnumbers it ≥ 20 : 1 |
270
- | `variants_used_in_taiwan.txt` | the form looks simplified but is in an MOE chart |
271
- | `mainland_hard.tsv` | the mainland form is unattested and the Taiwan form occurs ≥ 3 times |
272
- | `mainland_soft.tsv` | the pair is a real opposition but the mainland form is attested here |
273
- | `mainland_exceptions.tsv` | the head term is a detector in one of the two bands |
274
- | `taiwan_lexicon.txt` | a mainland writer would not use this string for this referent |
275
- | `taiwan_markers.txt` | the name denotes an ROC institution or a Taiwanese place |
276
- | `taiwan_particles.txt` | the graph is the Taiwan-preferred spelling of the particle |
277
- | `taiwan_grammar.txt` | the construction is a Southern Min substrate feature |
328
+ | table | rows | content |
329
+ | ---------------------------------------------- | ---------------------: | ----------------------------------------------------------------------- |
330
+ | `moe_common/secondary/rare.txt` | 4 808 / 6 343 / 18 356 | 教育部標準字體表 |
331
+ | `moe_exception.txt` | 12 | dictionary headword characters outside all three charts |
332
+ | `admitted_uncharted.txt` | 1 | characters outside every chart admitted at the 常用 tier: 〇 |
333
+ | `simplified_only.txt` | 3 785 | derived from the OpenCC round-trip |
334
+ | `variants_used_in_taiwan.txt` | 16 | simplified-looking forms standard in Taiwan |
335
+ | `converted_orthography.txt` | 14 | mainland traditional variants |
336
+ | `mainland_hard.tsv` | 144 | rejecting pairs, with attestation counts |
337
+ | `mainland_soft.tsv` | 43 | marking pairs: ambiguous, dominated, or Taiwanese in some registers |
338
+ | `mainland_exceptions.tsv` | 20 | superstrings in which a marker is legitimate |
339
+ | `cantonese.txt` | 17 | written-Cantonese characters outside the 常用 chart |
340
+ | `regional_hard.tsv` | 19 | Hong Kong, Cantonese-sequence and Singapore forms |
341
+ | `foreign_topics.txt` | 80 | non-Taiwanese toponyms and institutions: subject matter, not provenance |
342
+ | `taiwan_markers/lexicon/particles/grammar.txt` | 66 / 51 / 7 / 20 | positive evidence |
343
+ | `erhua.txt` | 3 | erhua forms that reject: 玩兒 事兒 點兒 |
344
+ | `erhua_headed.txt` | 15 | 兒 opening a root (兒童, 兒藝), which suppresses an erhua match |
345
+ | `wenyan.txt` | 4 | literary particles for density estimation |
346
+ | `MANIFEST.json` | — | row count and SHA-256 per table |
347
+
348
+ **Grading.** Candidate pairs were graded by attestation against a reference corpus of
349
+ Taiwanese sources: _hard_ when the mainland form was unattested and the Taiwan form occurred
350
+ at least three times; _soft_ when the Taiwan form dominated or the pair was hand-graded
351
+ ambiguous; excluded otherwise. Columns 3 and 4 of the pair tables hold those counts. The
352
+ reference corpus is not distributed, and it had itself been filtered by earlier versions of
353
+ these markers, so the counts are not an independent measurement. The grading is frozen in
354
+ `tools/input/lexicon/`; `tools/build_tables.rb` derives every shipped table from
355
+ `tools/input/` alone, and every later change is an explicit, measured edit in that script.
356
+
357
+ **Membership.** Each table states the rule that admits a row. The rules marked ✓ are enforced
358
+ against the shipped data by `spec/twfilter/membership_spec.rb`; the others are editorial.
359
+
360
+ | table | a row is admitted iff | enforced |
361
+ | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------ | :-------------: |
362
+ | `cantonese.txt` | the character is used in written Cantonese and is not in 常用國字標準字體表 | ✓ chart part |
363
+ | `regional_hard.tsv` | the form is unattested in the reference corpus and its Taiwan counterpart occurs ≥ 3 times | ✓ |
364
+ | `converted_orthography.txt` | the form is in no MOE chart and Taiwan standardizes another form | ✓ chart part |
365
+ | `variants_used_in_taiwan.txt` | the form looks simplified but is in an MOE chart | ✓ |
366
+ | `admitted_uncharted.txt` | the character is in no MOE chart and Taiwanese writing uses it | ✓ chart part |
367
+ | `mainland_hard.tsv` | the mainland form is unattested in the reference corpus and the Taiwan form occurs ≥ 3 times | ✓ |
368
+ | `mainland_soft.tsv` | the pair is a real opposition and the Taiwan form occurs ≥ 3 times | ✓ |
369
+ | `mainland_exceptions.tsv` | the head term is a detector, and every mask contains it | ✓ |
370
+ | `erhua.txt` | the form is erhua and almost never occurs as erhua in native text (one native sentence of the evaluation set, with 事兒) | ✓ form shape |
371
+ | `erhua_headed.txt` | 兒 opens a word in which it is the root | ✓ form shape |
372
+ | `taiwan_lexicon.txt` | a mainland writer would not use this string for this referent | |
373
+ | `taiwan_markers.txt` | the name denotes an ROC institution or a Taiwanese place | |
374
+ | `taiwan_particles.txt` | the graph is the Taiwan-preferred spelling of the particle | ✓ one character |
375
+ | `taiwan_grammar.txt` | the construction is a Southern Min substrate feature | |
278
376
 
279
377
  The rules exclude more than they admit. Subject matter is not provenance, so Taiwanese food
280
378
  names are not evidence; A-not-A interrogatives are pan-Mandarin, so `好不好` is not evidence;
@@ -282,52 +380,51 @@ and a character in everyday Taiwanese use cannot mark another variety, however
282
380
  characteristic of it that character may be.
283
381
 
284
382
  **Topics are not provenance.** `foreign_topics.txt` is a subject-matter tag. Taiwanese media
285
- covers the mainland constantly, several entries are ordinary ROC administrative vocabulary,
286
- and Taipei streets are named after mainland cities. It marks under `corpus` and rejects only
287
- under `publishable`, where excluding foreign subject matter is an editorial decision.
383
+ covers China constantly, several entries are ordinary ROC administrative vocabulary, and
384
+ Taipei streets are named after cities in China. The table marks under `corpus` and rejects
385
+ only under `publishable`, where excluding foreign subject matter is an editorial decision.
288
386
 
289
- ## Influencing the criteria
387
+ ### Influencing the criteria
290
388
 
291
- Preferred: contribute to the published dataset. The tables are maintained at
292
- [huggingface.co/datasets/taiwan-corpora/twfilter-tables](https://huggingface.co/datasets/taiwan-corpora/twfilter-tables),
293
- where each release carries its grading evidence, and the gem vendors a copy of a specific
294
- version. A correction accepted there reaches every consumer at the next release, with a
295
- record of what changed and why — which a local edit does not.
389
+ Preferred: contribute to the published dataset,
390
+ [huggingface.co/datasets/taiwan-corpora/twfilter-tables](https://huggingface.co/datasets/taiwan-corpora/twfilter-tables).
391
+ Each gem release ships the tables it was tested with, so a correction accepted there reaches
392
+ every consumer at the next release, with a record of what changed and why.
296
393
 
297
- Three table sources are supported. All three are reported by `provenance`.
394
+ Three table sources are supported, and `provenance` reports all three.
298
395
 
299
- **Bundled** — the default, versioned with the gem, the only configuration whose results are
300
- comparable with anyone else's.
396
+ **Bundled:** the default, versioned with the gem, and the only configuration whose results
397
+ are comparable with anyone else's.
301
398
 
302
- **Replacement** — a directory holding the full set, e.g. a checkout of the dataset newer
303
- than the gem:
399
+ **Replacement:** a directory holding the full set, such as a checkout of the dataset newer
400
+ than the gem. Only `*.txt` and `*.tsv` files are read.
304
401
 
305
402
  ```ruby
306
403
  TWFilter::Tables.dir = "path/to/twfilter-tables" # or TWFILTER_DATA_DIR
307
404
  ```
308
405
 
309
- **Overlay** — the bundled set plus your additions. Filename suffixes select the operation:
406
+ **Overlay:** the bundled set plus your changes. Filename suffixes select the operation:
310
407
 
311
- | file in the overlay directory | effect on `mainland_hard.tsv` |
312
- | --- | --- |
313
- | `mainland_hard.add.tsv` | rows appended |
314
- | `mainland_hard.remove.tsv` | rows removed, matched on the full row or its first field |
315
- | `mainland_hard.tsv` | table replaced |
408
+ | file in the overlay directory | effect on `mainland_hard.tsv` |
409
+ | ----------------------------- | -------------------------------------------------------- |
410
+ | `mainland_hard.add.tsv` | rows appended |
411
+ | `mainland_hard.remove.tsv` | rows removed, matched on the full row or its first field |
412
+ | `mainland_hard.tsv` | table replaced |
316
413
 
317
414
  ```ruby
318
415
  TWFilter::Tables.overlay = "path/to/house-style" # or TWFILTER_OVERLAY_DIR
319
416
  ```
320
417
 
321
- Row format is validated on load and a violation raises `TWFilter::InvalidTableError`:
418
+ Row format is validated on load, and a violation raises `TWFilter::InvalidTableError`:
322
419
 
323
- | shape | tables | row |
324
- | --- | --- | --- |
325
- | `:chars` | the MOE charts, `simplified_only`, `variants_used_in_taiwan`, `converted_orthography`, `cantonese`, `wenyan` | one Han character |
326
- | `:pairs` | `mainland_hard`, `mainland_soft`, `mainland_exceptions` | two or more tab-separated fields, first non-empty |
327
- | `:terms` | everything else, including tables you invent | one term, no tabs |
420
+ | shape | tables | row |
421
+ | -------- | ---------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------- |
422
+ | `:chars` | the MOE charts, `admitted_uncharted`, `simplified_only`, `variants_used_in_taiwan`, `converted_orthography`, `cantonese`, `wenyan` | one Han character |
423
+ | `:pairs` | `mainland_hard`, `mainland_soft`, `mainland_exceptions`, `regional_hard` | two or more tab-separated fields, first non-empty |
424
+ | `:terms` | everything else, including tables you invent | one term, no tabs |
328
425
 
329
426
  Files named `*.remove.*` carry keys only and are not shape-checked. UTF-8, one record per
330
- line, no header, no comments; blank lines ignored.
427
+ line, no header, no comments; blank lines are ignored.
331
428
 
332
429
  Record `provenance` alongside any measurement derived this way. Two corpora filtered with
333
430
  different tables are not comparable, and the digest is what makes that detectable.
@@ -338,17 +435,41 @@ Policy thresholds are the supported knob and need no table changes:
338
435
  lenient = TWFilter::Policy.corpus.with(soft_lexicon_rejects: false, foreign_topics_reject: false)
339
436
  ```
340
437
 
341
- ## Development
438
+ ### Development
342
439
 
343
440
  ```bash
344
441
  bundle install
345
442
  bundle exec rake # specs and RBS validation
346
- bundle exec rake tables # regenerate the tables and their manifest
443
+ bundle exec rake tables # regenerate the tables and their manifest from tools/input/
347
444
  ```
348
445
 
349
- Specs require no data, no network and no credentials.
446
+ `tools/build_tables.rb` reads only `tools/input/`: the MOE chart lists, two OpenCC character
447
+ tables and the frozen lexical grading. A spec rebuilds the tables into a temporary directory
448
+ and compares them with `lib/twfilter/data/` byte for byte. Specs need no data beyond the
449
+ repository, no network and no credentials. `tools/` is not part of the packaged gem.
450
+
451
+ ### Citation
452
+
453
+ ```bibtex
454
+ @software{patin_twfilter,
455
+ title = {twfilter: Taiwanese Mandarin variety identification},
456
+ author = {Patin, Den},
457
+ year = {2026},
458
+ version = {0.2.0},
459
+ doi = {10.5281/zenodo.21761465},
460
+ publisher = {Zenodo},
461
+ url = {https://github.com/taiwan-corpora/twfilter}
462
+ }
463
+ ```
464
+
465
+ `10.5281/zenodo.21761465` is the concept DOI and always resolves to the latest release;
466
+ `10.5281/zenodo.21761466` identifies release 0.1.0. The reference tables are published
467
+ separately as
468
+ [taiwan-corpora/twfilter-tables](https://huggingface.co/datasets/taiwan-corpora/twfilter-tables).
469
+
470
+ Developed and maintained in Taipei, Taiwan by Den Patin 丁丹旭 (<hi@dpat.in>), independent researcher, linguist and software engineer.
350
471
 
351
- ## License
472
+ ### License
352
473
 
353
474
  Code: MIT. Tables: mixed, all permitting commercial use. See [NOTICES.md](NOTICES.md) for
354
475
  per-table provenance and terms.
@@ -362,3 +483,293 @@ OpenCC — https://github.com/BYVoid/OpenCC, Apache License 2.0
362
483
 
363
484
  No table carries a NonCommercial, ShareAlike or copyleft term. Verdicts and counts produced
364
485
  by the gem are the caller's, not derivatives of the tables.
486
+
487
+ ## 中文
488
+
489
+ 臺灣、香港、澳門都寫繁體字,中國也有不少文字是從簡體轉成繁體的。光看字體,看不出一段文字從哪裡來。
490
+ 下面這幾句,只有第一句跟最後一句是臺灣華語:
491
+
492
+ ```ruby
493
+ TWFilter.keep?("這個政策有沒有經過完整評估?") # => true
494
+ TWFilter.keep?("请把这个信息转发给同事") # => false(簡體字)
495
+ TWFilter.keep?("請把這個信息轉發給同事") # => false(詞彙:信息,臺灣說資訊)
496
+ TWFilter.keep?("他站在門裏面等了很久") # => false(字形:裏,臺灣寫裡)
497
+ TWFilter.keep?("佢哋唔知道發生咗咩事") # => false(粵語用字)
498
+ TWFilter.keep?("這事兒辦得挺漂亮的") # => false(兒化:事兒)
499
+ TWFilter.keep?("他的女兒今年考上大學") # => true(女兒不是兒化)
500
+ ```
501
+
502
+ 轉換表裡的對應詞不等於來源證據,談到什麼主題也不等於來源:
503
+
504
+ ```ruby
505
+ # 程序在臺灣的法律用語裡很常見,不是中國用語
506
+ TWFilter.keep?("行政程序法所定之程序應由主管機關進行") # => true
507
+
508
+ # 「了嗎」在臺灣的文章裡也很普通,不當作標記
509
+ TWFilter.keep?("你吃飯了嗎?我們等一下再出發。") # => true
510
+
511
+ # 有爭議的詞只標記、留給人看,不直接丟掉
512
+ TWFilter.examine("這個視頻的畫質很不錯").marks.map(&:code) # => [:mainland_soft]
513
+
514
+ # 臺灣報導中國的新聞還是臺灣華語:主題只會被標記,不會被排除
515
+ TWFilter.examine("行政院昨天回應了北京的最新聲明").marks.map(&:code) # => [:foreign_topic]
516
+
517
+ # 南京也是臺北的路名;後面接地址就不算主題
518
+ TWFilter.examine("臺北市南京東路五段的捷運站出口").findings # => []
519
+ ```
520
+
521
+ 檢查的範圍有字形、用字、詞彙、構詞,再加上臺灣特有說法的正面證據;每一條觸發的規則都會回報。通過檢查不代表
522
+ 一定是臺灣寫的,請看[限制](#限制)。
523
+
524
+ ### 安裝
525
+
526
+ ```ruby
527
+ gem "twfilter", "~> 0.2"
528
+ ```
529
+
530
+ 需要 Ruby 3.4 以上。
531
+
532
+ ### 做什麼、不做什麼
533
+
534
+ **會做:** 判斷一段文字有沒有臺灣華語以外的跡象;把標點符號統一成臺灣的標準;斷句;給出用字的難度等級;
535
+ 每個判斷都附上全部的理由。
536
+
537
+ **不做:** 斷詞、詞性標記、語言辨識(輸入預設就是漢字文本)、翻譯、簡繁轉換,也不判斷合不合文法。被排除的
538
+ 句子不是寫錯了,只是*不是臺灣華語*。
539
+
540
+ ### 限制
541
+
542
+ 用 OpenCC 從簡體轉成繁體的中國文字,在 `corpus` 政策下幾乎都會通過:`s2tw` 跟 `s2twp` 的通過率跟臺灣原生
543
+ 文字差不多,數字在 [Evaluation](#evaluation)。`s2tw` 會把字換成臺灣的標準字形,`s2twp` 還會把中國用語換成
544
+ 臺灣用語,轉完以後在單句裡幾乎看不出痕跡。所以通過篩選不能證明文字來自臺灣,來源要看是誰發表、在哪裡發表。
545
+
546
+ 兒化詞表(玩兒、事兒、點兒)是用百科跟公部門文字訂出來的。評估資料裡沒有中國的口語文字,而這種文字裡「這兒」、
547
+ 「那兒」、「哪兒」很常見。
548
+
549
+ ### 用途
550
+
551
+ 1. **給學習者用的語料。** 這個套件是從 [TaiwanCards](https://taiwancards.com) 拆出來的,每個例句、釋義跟
552
+ 搭配詞上字卡前都要先通過它。`publishable` 政策就是教學用的範圍:教育部常用字 4 808 字,加上在這一級收的
553
+ 13 個字,不收有爭議的詞,標點只用教育部的標準。
554
+ 2. **建網路語料庫。** 語言辨識只會告訴你是 `zho_Hant`,不會告訴你來源。這個套件可以把簡體、中國的繁體字形、
555
+ 粵語書面語跟列出的中國用語篩掉,但篩不掉用 OpenCC 轉換的中國文字(見[限制](#限制)),那部分要靠網站來源
556
+ 判斷。
557
+ 3. **整理訓練資料。** 要讓模型產出臺灣華語,可以用它建立或檢查訓練資料。`Report#findings` 是機器可讀的,
558
+ 每一筆被排除的資料都查得到原因。
559
+ 4. **編輯跟在地化校對。** 找出應該是臺灣用語的文案裡混進的中國用語、字形跟標點。`mainland_soft` 這一級就是
560
+ 設計給人工校對的,不直接排除。
561
+
562
+ ### 判斷流程
563
+
564
+ 完整流程圖在 [Decision procedure](#decision-procedure)。順序是:先轉成 Unicode NFC,再檢查句子形狀
565
+ (`Checks::Shape`)、用字(`Checks::Script`),然後是詞彙、兒化跟文言比例(`Checks::Lexicon`、`Erhua`、
566
+ `Wenyan`),最後計算臺灣特有說法的正面證據。
567
+
568
+ `examine` 不會整理標點,要先呼叫 `normalize`(見[放進處理流程](#放進處理流程))。詞彙標記都是子字串比對;
569
+ 標記出現在已知的較長詞語裡(博客來、數字段票、洪水平原)時,會被 `mainland_exceptions.tsv` 裡列出的例外
570
+ 蓋掉。這些例外都是人工列的,不是自動產生的。
571
+
572
+ 正面證據只加分,不會讓句子被排除。表示完成的「有 + 動詞」只有在沒有否定的時候才算,因為「沒有看」跟「有沒有看」
573
+ 是各地華語都有的說法,不是臺灣的特徵。
574
+
575
+ ### 輸入跟輸出
576
+
577
+ **輸入:** 任何有 `to_s` 的物件,字串要是 UTF-8;其他編碼會丟出 `Encoding::CompatibilityError`,無效的位元組
578
+ 要先自己清掉(`scrub`)。空字串、只有空白、只有拉丁字母、擴充平面的字,都會寫在檢查結果(finding)裡,不會丟出例外。
579
+ 長度沒有限制,斷句跟標點整理的時間跟長度成正比。檢查用的是 Unicode NFC 形式,所以相容表意字(像 U+F934)會
580
+ 當成對應的統一表意字(U+8001)來判斷。`Report#text` 回傳的是原本傳進來的字串,檢查結果引用的內容也照原本的
581
+ 寫法。
582
+
583
+ **輸出:** `TWFilter::Report`,各欄位的說明在 [Input and output](#input-and-output)。`ok?` 只要沒有
584
+ `:reject` 等級的檢查結果就是 true;`marks` 是只標記、不排除的部分;`reasons` 把排除理由寫成
585
+ `"code: detail"` 字串;`to_h` 可以直接轉成 JSON。`keep?` 只是 `examine(...).ok?` 的簡寫,不是另一條判斷路徑。
586
+
587
+ ### 政策
588
+
589
+ 政策是不能修改的值物件,用 `#with` 產生新的。
590
+
591
+ | | `corpus` | `publishable` | `permissive` |
592
+ | ------------------ | -------- | ------------- | ------------ |
593
+ | 漢字數 | 6–60 | 6–40 | 1–∞ |
594
+ | 漢字比例 | ≥ 0.65 | ≥ 0.70 | 0 |
595
+ | 用字等級 | ≤ 罕用 | ≤ 常用 4 808 | ≤ 罕用 |
596
+ | 有爭議的詞(soft) | 標記 | 排除 | 標記 |
597
+ | 外地主題 | 標記 | 排除 | 標記 |
598
+ | 標點範圍 | 寬 | 教育部標準 | 寬 |
599
+ | 中國繁體字形 | 排除 | 排除 | 排除 |
600
+
601
+ ```ruby
602
+ TWFilter::Policy.corpus.with(max_tier: :secondary, han_range: (4..80))
603
+ ```
604
+
605
+ ### 用法
606
+
607
+ ```ruby
608
+ require "twfilter"
609
+
610
+ # 判斷來源,附上理由
611
+ report = TWFilter.examine("请把这个信息转发给同事")
612
+ report.ok? # => false
613
+ report.reasons # => ["simplified: 请这个转", "unlisted: 请这个转", "mainland: 信息"]
614
+ report.findings.map(&:code) # => [:simplified, :unlisted, :mainland]
615
+
616
+ # 只標記,留給編輯看
617
+ report = TWFilter.examine("這個程式的運行狀況非常穩定")
618
+ report.ok? # => true
619
+ report.marks.map(&:detail) # => ["運行"]
620
+ TWFilter::Checks::Lexicon.taiwan_form("運行") # => "執行"
621
+
622
+ # 教學用的門檻
623
+ TWFilter.keep?("他每天都會去公園散步運動。", policy: TWFilter::Policy.publishable) # => true
624
+ TWFilter.keep?("饕餮紋飾在青銅器上十分常見。", policy: TWFilter::Policy.publishable) # => false
625
+
626
+ # 標點統一成臺灣的標準
627
+ TWFilter.normalize("他說“好”...") # => "他說「好」……"
628
+ TWFilter.normalize("馬丁·路德PDF") # => "馬丁‧路德PDF"
629
+
630
+ # 斷句:。!?…; 會斷句,後面的引號括號跟著前一句,、不斷
631
+ TWFilter.sentences("他說:「好。」我走了。") # => ["他說:「好。」", "我走了。"]
632
+
633
+ # 用字難度
634
+ TWFilter.tier("散步") # => 0
635
+ TWFilter.tier("饕餮") # => 1
636
+
637
+ # 整段判斷:一段話要嘛整段收,要嘛整段不收
638
+ TWFilter::Block.judge(paragraph_sentences)
639
+
640
+ # 表格指紋,跟從它算出來的數字一起記下來
641
+ TWFilter.provenance
642
+ # => {version: "0.2.0", dir: "…/lib/twfilter/data", overlay: nil, tables: 21, digest: "c2d3ca4229d644fb"}
643
+ ```
644
+
645
+ ### 放進處理流程
646
+
647
+ 先整理標點再斷句,因為刪節號跟破折號的規則會影響句子邊界。先斷句再檢查,因為形狀的門檻是以句子為單位訂的。
648
+ 先檢查,再去除重複、計數,被排除的資料才不會跑進統計裡。
649
+
650
+ ```text
651
+ acquire → normalize → segment → examine → deduplicate → tokenize → count
652
+ │ │ │
653
+ Punctuation Sentences Report
654
+ ```
655
+
656
+ `Block.judge` 是可以放在斷句跟檢查之間的一步,適合主題前後一致的來源:一個區塊裡只要有一句不通過就整塊不收,
657
+ 而且整塊要有足夠的臺灣正面證據。網路爬下來的資料適合用,字典不適合。
658
+
659
+ ### 跟現有語料庫的關係
660
+
661
+ 現有的臺灣華語資源都是在收集的時候控制來源,像 TaiwanWaC 收繁體網頁,中研院跟政大的口語語料庫錄臺灣的
662
+ 說話者。它們都沒有把「這段是不是臺灣華語」做成可以重複使用的判斷,收集時的控制也沒辦法套用到新的文字上。
663
+ 在已經用 `.tw` 網域跟 `html_lang: zh-TW` 篩過一次的 twngrams 資料上,0.1.0 版還是篩掉了大約 23 %,數字跟
664
+ 說明在 [Relation to existing corpora](#relation-to-existing-corpora)。
665
+
666
+ ### 評估
667
+
668
+ 評估資料是從官方公開資料重建的,有臺灣原生文字、用 OpenCC 轉換的中國文字,還有香港文字,句子本身不公開,
669
+ 重建的方法跟程式在 [`tools/benchmark/`](tools/benchmark/)。結論:臺灣原生文字幾乎都會通過;只做字元轉換的
670
+ `s2t` 大約有四分之一會被擋下;換成臺灣標準字形的 `s2tw`、連詞彙也一起換的 `s2twp` 幾乎都會通過;沒有粵語
671
+ 用字的香港文字大多會通過,有粵語用字的幾乎都會被擋下。
672
+ 各類的句數、通過率跟信賴區間只列在 [Evaluation](#evaluation),效能數字在 [Performance](#performance)。
673
+
674
+ ### 參考表格
675
+
676
+ 表格放在 `lib/twfilter/data/`,都是純文字,一行一筆,有欄位的用 tab 分隔,跟 gem 一起做版本管理。每個表格
677
+ 收什麼、不收什麼的規則,還有哪些規則有測試把關,都在 [Reference tables](#reference-tables)。詞彙對照表裡的
678
+ 出現次數來自一個不公開的臺灣參考語料庫,而那個語料庫本身也被早期版本的標記篩過,所以這些次數不是獨立的
679
+ 測量。
680
+
681
+ 主題不等於來源。`foreign_topics.txt` 只是主題標籤:臺灣的媒體天天報導中國,裡面有些詞是中華民國的行政用語,
682
+ 臺北也有很多以中國城市命名的路。所以它在 `corpus` 下只標記,只有在 `publishable` 下才排除,那是編輯上的
683
+ 決定。
684
+
685
+ ### 調整判斷標準
686
+
687
+ 最好的方式是到公開的資料集提出修正:
688
+ [huggingface.co/datasets/taiwan-corpora/twfilter-tables](https://huggingface.co/datasets/taiwan-corpora/twfilter-tables)。
689
+ 每個 gem 版本都會帶著測試過的那一版表格,修正被接受以後,下一版就會到每個使用者手上,也留得下改了什麼、
690
+ 為什麼改的紀錄。
691
+
692
+ 表格來源有三種,`provenance` 都會回報。
693
+
694
+ **內建:** 預設值,跟 gem 一起做版本管理,也是唯一能跟別人的結果直接比較的設定。
695
+
696
+ **整套替換:** 指定一個放著完整表格的資料夾,像是比 gem 新的資料集。只會讀 `*.txt` 跟 `*.tsv` 檔案。
697
+
698
+ ```ruby
699
+ TWFilter::Tables.dir = "path/to/twfilter-tables" # 或用環境變數 TWFILTER_DATA_DIR
700
+ ```
701
+
702
+ **疊加:** 在內建表格上加上自己的修改,用檔名後綴決定動作:`mainland_hard.add.tsv` 加列,
703
+ `mainland_hard.remove.tsv` 依整列或第一欄刪列,`mainland_hard.tsv` 整個取代。
704
+
705
+ ```ruby
706
+ TWFilter::Tables.overlay = "path/to/house-style" # 或用環境變數 TWFILTER_OVERLAY_DIR
707
+ ```
708
+
709
+ 載入的時候會檢查每一列的格式,不合格會丟出 `TWFilter::InvalidTableError`;各表格的格式在
710
+ [Influencing the criteria](#influencing-the-criteria)。用自訂表格算出來的數字,請把 `provenance` 一起記下來:
711
+ 用不同表格篩出來的語料庫不能直接比較,digest 就是用來發現這件事的。
712
+
713
+ 只想放寬或收緊,調政策的門檻就好,不用改表格:
714
+
715
+ ```ruby
716
+ lenient = TWFilter::Policy.corpus.with(soft_lexicon_rejects: false, foreign_topics_reject: false)
717
+ ```
718
+
719
+ ### 開發
720
+
721
+ ```bash
722
+ bundle install
723
+ bundle exec rake # 跑測試跟 RBS 驗證
724
+ bundle exec rake tables # 從 tools/input/ 重新產生表格跟 manifest
725
+ ```
726
+
727
+ `tools/build_tables.rb` 只讀 `tools/input/`:教育部字表、兩個 OpenCC 字元表,還有凍結的詞彙分級結果。有一個
728
+ 測試會把表格重建到暫存資料夾,再跟 `lib/twfilter/data/` 逐位元組比對。跑測試不需要 repository 以外的資料,
729
+ 不用連網路,也不用任何帳號。`tools/` 不會打包進 gem。
730
+
731
+ ### 引用
732
+
733
+ ```bibtex
734
+ @software{patin_twfilter,
735
+ title = {twfilter: Taiwanese Mandarin variety identification},
736
+ author = {Patin, Den},
737
+ year = {2026},
738
+ version = {0.2.0},
739
+ doi = {10.5281/zenodo.21761465},
740
+ publisher = {Zenodo},
741
+ url = {https://github.com/taiwan-corpora/twfilter}
742
+ }
743
+ ```
744
+
745
+ `10.5281/zenodo.21761465` 是概念 DOI,永遠指向最新版;`10.5281/zenodo.21761466` 是 0.1.0 版。參考表格另外以
746
+ [taiwan-corpora/twfilter-tables](https://huggingface.co/datasets/taiwan-corpora/twfilter-tables) 發布。
747
+
748
+ 由 Den Patin 丁丹旭(<hi@dpat.in>)在臺灣臺北開發與維護。獨立研究者,做語言學跟軟體工程。
749
+
750
+ ### 授權條款
751
+
752
+ 程式碼是 MIT。表格的授權條款依檔案不同,但都可以商業使用,每個表格的來源跟條款在 [NOTICES.md](NOTICES.md)。
753
+
754
+ 任何附帶這個 gem 的產品,都要附上這兩段出處:
755
+
756
+ ```text
757
+ 數位發展部,CNS11643中文標準交換碼全字庫網站
758
+ OpenCC — https://github.com/BYVoid/OpenCC, Apache License 2.0
759
+ ```
760
+
761
+ 沒有任何表格帶有非商業、相同方式分享或 copyleft 的條件。用這個 gem 得到的判斷跟計數屬於使用者,不是表格的
762
+ 衍生著作。
763
+
764
+ \* _Taiwanese Mandarin_ (臺灣華語; BCP 47 `cmn-Hant-TW`) denotes the variety of
765
+ Mandarin in general use in Taiwan, as produced by its native and near-native
766
+ speakers, together with the lexical, phonological and morphosyntactic properties
767
+ that distinguish it from the codified standard of the ROC Ministry of Education
768
+ (標準國語, Standard Guoyu) and from PRC Putonghua (普通話). The term follows Her
769
+ (2009) and the naming of the Corpus of Contemporary Taiwanese Mandarin
770
+ (臺灣華語文語料庫, National Academy for Educational Research); much of the phonetic
771
+ literature calls the same variety _Taiwan Mandarin_. It is not 臺灣國語, the
772
+ Hokkien-accented sociolect of that variety, nor Taiwanese Hokkien (臺語).
773
+ Her, One-Soon 何萬順 (2009). 語言與族群認同:從台灣外省族群的母語與台灣華語談起
774
+ [Language and group identity: On Taiwan Mainlanders' mother tongues and Taiwan
775
+ Mandarin]. _Language and Linguistics_ 10(2), 375–419.