calliope-ts 0.0.2 → 0.0.3

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.
Files changed (159) hide show
  1. package/README.md +3 -13
  2. package/dist/caesura.d.ts +33 -0
  3. package/dist/caesura.d.ts.map +1 -0
  4. package/dist/caesura.js +202 -0
  5. package/dist/calliope/boundaries.d.ts +19 -0
  6. package/dist/calliope/boundaries.d.ts.map +1 -0
  7. package/dist/calliope/boundaries.js +182 -0
  8. package/dist/calliope/bracketing.d.ts +11 -0
  9. package/dist/calliope/bracketing.d.ts.map +1 -0
  10. package/dist/calliope/bracketing.js +416 -0
  11. package/dist/calliope/deps.d.ts +4 -0
  12. package/dist/calliope/deps.d.ts.map +1 -0
  13. package/dist/calliope/deps.js +181 -0
  14. package/dist/calliope/engine.d.ts +3 -0
  15. package/dist/calliope/engine.d.ts.map +1 -0
  16. package/dist/calliope/engine.js +71 -0
  17. package/dist/calliope/feats.d.ts +9 -0
  18. package/dist/calliope/feats.d.ts.map +1 -0
  19. package/dist/calliope/feats.js +45 -0
  20. package/dist/calliope/names.d.ts +7 -0
  21. package/dist/calliope/names.d.ts.map +1 -0
  22. package/dist/calliope/names.js +42 -0
  23. package/dist/calliope/postag.d.ts +8 -0
  24. package/dist/calliope/postag.d.ts.map +1 -0
  25. package/dist/calliope/postag.js +250 -0
  26. package/dist/calliope/prosodic.d.ts +3 -0
  27. package/dist/calliope/prosodic.d.ts.map +1 -0
  28. package/dist/calliope/prosodic.js +275 -0
  29. package/dist/calliope/relstress.d.ts +4 -0
  30. package/dist/calliope/relstress.d.ts.map +1 -0
  31. package/dist/calliope/relstress.js +688 -0
  32. package/dist/calliope/stressrules.d.ts +28 -0
  33. package/dist/calliope/stressrules.d.ts.map +1 -0
  34. package/dist/calliope/stressrules.js +147 -0
  35. package/dist/calliope/syntax.d.ts +38 -0
  36. package/dist/calliope/syntax.d.ts.map +1 -0
  37. package/dist/calliope/syntax.js +234 -0
  38. package/dist/calliope/udpos.d.ts +13 -0
  39. package/dist/calliope/udpos.d.ts.map +1 -0
  40. package/dist/calliope/udpos.js +156 -0
  41. package/dist/clio/caesura.d.ts +27 -0
  42. package/dist/clio/caesura.d.ts.map +1 -0
  43. package/dist/clio/caesura.js +148 -0
  44. package/dist/clio/depfix.d.ts +13 -0
  45. package/dist/clio/depfix.d.ts.map +1 -0
  46. package/dist/clio/depfix.js +84 -0
  47. package/dist/clio/display.d.ts +32 -0
  48. package/dist/clio/display.d.ts.map +1 -0
  49. package/dist/clio/display.js +976 -0
  50. package/dist/clio/engine.d.ts +3 -0
  51. package/dist/clio/engine.d.ts.map +1 -0
  52. package/dist/clio/engine.js +28 -0
  53. package/dist/clio/parser.d.ts +10 -0
  54. package/dist/clio/parser.d.ts.map +1 -0
  55. package/dist/clio/parser.js +696 -0
  56. package/dist/clio/phonological.d.ts +41 -0
  57. package/dist/clio/phonological.d.ts.map +1 -0
  58. package/dist/clio/phonological.js +788 -0
  59. package/dist/clio/phrasestress.d.ts +6 -0
  60. package/dist/clio/phrasestress.d.ts.map +1 -0
  61. package/dist/clio/phrasestress.js +106 -0
  62. package/dist/clio/pipeline.d.ts +11 -0
  63. package/dist/clio/pipeline.d.ts.map +1 -0
  64. package/dist/clio/pipeline.js +147 -0
  65. package/dist/clio/rhyme.d.ts +65 -0
  66. package/dist/clio/rhyme.d.ts.map +1 -0
  67. package/dist/clio/rhyme.js +761 -0
  68. package/dist/clio/scandroid.d.ts +17 -0
  69. package/dist/clio/scandroid.d.ts.map +1 -0
  70. package/dist/clio/scandroid.js +435 -0
  71. package/dist/clio/scansion.d.ts +46 -0
  72. package/dist/clio/scansion.d.ts.map +1 -0
  73. package/dist/clio/scansion.js +1086 -0
  74. package/dist/clio/semantics.d.ts +44 -0
  75. package/dist/clio/semantics.d.ts.map +1 -0
  76. package/dist/clio/semantics.js +139 -0
  77. package/dist/clio/stress.d.ts +83 -0
  78. package/dist/clio/stress.d.ts.map +1 -0
  79. package/dist/clio/stress.js +1737 -0
  80. package/dist/clio/tagfix.d.ts +6 -0
  81. package/dist/clio/tagfix.d.ts.map +1 -0
  82. package/dist/clio/tagfix.js +101 -0
  83. package/dist/display.d.ts +0 -6
  84. package/dist/display.d.ts.map +1 -1
  85. package/dist/display.js +322 -141
  86. package/dist/engine.d.ts +9 -0
  87. package/dist/engine.d.ts.map +1 -0
  88. package/dist/engine.js +12 -0
  89. package/dist/index.d.ts +4 -3
  90. package/dist/index.d.ts.map +1 -1
  91. package/dist/index.js +169 -26
  92. package/dist/parser.d.ts +3 -3
  93. package/dist/parser.d.ts.map +1 -1
  94. package/dist/parser.js +320 -563
  95. package/dist/phonological.d.ts +1 -1
  96. package/dist/phonological.d.ts.map +1 -1
  97. package/dist/phonological.js +73 -4
  98. package/dist/phrasestress.d.ts +6 -0
  99. package/dist/phrasestress.d.ts.map +1 -0
  100. package/dist/phrasestress.js +106 -0
  101. package/dist/rhyme.d.ts +40 -1
  102. package/dist/rhyme.d.ts.map +1 -1
  103. package/dist/rhyme.js +435 -7
  104. package/dist/scansion.d.ts +9 -0
  105. package/dist/scansion.d.ts.map +1 -1
  106. package/dist/scansion.js +145 -18
  107. package/dist/semantics.d.ts +44 -0
  108. package/dist/semantics.d.ts.map +1 -0
  109. package/dist/semantics.js +139 -0
  110. package/dist/stress.d.ts +127 -4
  111. package/dist/stress.d.ts.map +1 -1
  112. package/dist/stress.js +834 -61
  113. package/dist/types.d.ts +15 -0
  114. package/dist/types.d.ts.map +1 -1
  115. package/package.json +5 -3
  116. package/src/caesura.ts +201 -0
  117. package/src/calliope/boundaries.ts +190 -0
  118. package/src/calliope/bracketing.ts +390 -0
  119. package/src/calliope/deps.ts +160 -0
  120. package/src/calliope/engine.ts +77 -0
  121. package/src/calliope/feats.ts +46 -0
  122. package/src/calliope/names.ts +44 -0
  123. package/src/calliope/postag.ts +253 -0
  124. package/src/calliope/prosodic.ts +262 -0
  125. package/src/calliope/relstress.ts +645 -0
  126. package/src/calliope/stressrules.ts +147 -0
  127. package/src/calliope/syntax.ts +218 -0
  128. package/src/calliope/udpos.ts +152 -0
  129. package/src/clio/caesura.ts +145 -0
  130. package/src/clio/depfix.ts +88 -0
  131. package/src/clio/display.ts +1042 -0
  132. package/src/clio/engine.ts +38 -0
  133. package/src/clio/parser.ts +845 -0
  134. package/src/clio/phonological.ts +849 -0
  135. package/src/clio/phrasestress.ts +108 -0
  136. package/src/clio/pipeline.ts +154 -0
  137. package/src/clio/rhyme.ts +740 -0
  138. package/src/clio/scandroid.ts +434 -0
  139. package/src/clio/scansion.ts +1130 -0
  140. package/src/clio/semantics.ts +134 -0
  141. package/src/clio/stress.ts +1731 -0
  142. package/src/clio/tagfix.ts +104 -0
  143. package/src/display.ts +321 -137
  144. package/src/engine.ts +22 -0
  145. package/src/index.ts +176 -32
  146. package/src/parser.ts +346 -682
  147. package/src/phonological.ts +72 -4
  148. package/src/phrasestress.ts +108 -0
  149. package/src/rhyme.ts +428 -8
  150. package/src/scansion.ts +136 -15
  151. package/src/semantics.ts +134 -0
  152. package/src/stress.ts +794 -64
  153. package/src/types.ts +39 -4
  154. package/tests/DataForHayesLinesOnly.txt +364 -0
  155. package/tests/DataForHayesStressSymbolsRevised.txt +728 -0
  156. package/tests/basic.test.ts +443 -37
  157. package/tests/bench-hayes.mjs +72 -0
  158. package/tests/wagner-stress.test.ts +188 -0
  159. package/vitest.config.ts +0 -15
package/src/parser.ts CHANGED
@@ -1,319 +1,45 @@
1
- // parser.ts — Syntactic dependency parser powered by FinNLP, producing
2
- // ClsDocument with full dependency graph and phrase‑structure node tree
3
- // that matches the Universal Dependencies format as used in McAleeses Calliope.
4
-
5
- import * as Lexed from 'lexed';
6
- import * as EnPos from 'en-pos';
7
- import * as EnParse from 'en-parse';
8
- import * as EnNorm from 'en-norm';
9
- import { correctTags } from './tagfix.js';
10
- import { applyDepFixes } from './depfix.js';
1
+ // parser.ts — Syntactic dependency parser powered by UDPipe (English GUM model),
2
+ // producing a ClsDocument with a full dependency graph and a phrase‑structure node
3
+ // tree in the Universal Dependencies format used in McAleese's Calliope.
4
+ //
5
+ // HISTORY: this module previously ran a staged FinNLP pipeline
6
+ // (en-norm lexed en-pos → en-parse) with hand-written tag/dep correction
7
+ // layers (tagfix.ts / depfix.ts) to patch en-parse's systematic errors. It now
8
+ // delegates tokenisation, POS tagging, and dependency parsing to UDPipe via the
9
+ // `udpipe-node` package (a pure-WASM build — no native binary, no subprocess),
10
+ // which is a far more accurate parser. UDPipe's output maps cleanly onto the
11
+ // existing data model:
12
+ // • XPOS column is Penn Treebank → ClsWord.lexicalClass (unchanged downstream)
13
+ // • DEPREL column is Universal Dependencies → ClsDependency.dependentType
14
+ // The correction layers are therefore no longer applied on this path.
15
+
16
+ import { createUDPipe } from 'udpipe-node/wasm';
17
+ import type { UDSentence, UDWord } from 'udpipe-node';
18
+ import { correctUDPipePos } from './calliope/postag.js';
19
+ import { pennTagOf } from './calliope/udpos.js';
11
20
  import {
12
21
  ClsDocument,
13
22
  ClsSentence,
14
23
  ClsWord,
15
24
  ClsDependency,
16
- ClsNode
25
+ ClsNode,
17
26
  } from './types.js';
18
27
 
19
- // ─── Local type declarations for the FinNLP API ────────────────────
20
- // These mirror the actual interfaces exported by finnlp / en-parse.
21
- // (The library ships with .d.ts files, but declaring them here ensures
22
- // type‑safety even if the consumer’s tsconfig resolution differs.)
23
-
24
- interface FinDepNode {
25
- label: string; // dependency label, e.g. "NSUBJ", "ROOT"
26
- type: string; // phrase type, e.g. "NP", "VP"
27
- parent: number; // 0‑based index of governor token; -1 for root
28
- }
29
-
30
- interface FinNodeInterface {
31
- left: FinNodeInterface[];
32
- right: FinNodeInterface[];
33
- tokens: string[];
34
- tags: string[];
35
- index: number[]; // [from, to] inclusive token indices (0‑based)
36
- type: string;
37
- label: string;
38
- }
39
-
40
- interface FinSentenceResult {
41
- sentence: string;
42
- tokens: string[];
43
- lemmas: string[];
44
- tags: string[];
45
- deps: FinDepNode[];
46
- depsTree: FinNodeInterface;
47
- confidence: number;
48
- }
49
-
50
- interface FinRunInstance {
51
- raw: string;
52
- intercepted: string;
53
- sentences: FinSentenceResult[];
54
- }
55
-
56
- // ─── Contraction re‑merging ───────────────────────────────────────
57
- // FinNLP's en‑norm module resolves contractions (e.g. "we'll" → "we" + "will"),
58
- // producing 2 tokens from 1. For scansion, the contracted form must be
59
- // 1 phonetic unit. This step re‑merges dehiscised contraction pairs
60
- // after parsing, using the raw text to distinguish genuine contractions
61
- // from accidental "host + clitic" word sequences.
62
-
63
- interface ContractionEntry {
64
- host: string;
65
- clitic: string;
66
- }
67
-
68
- const CONTRACTION_MAP: Record<string, ContractionEntry> = {
69
- "we'll": { host: 'we', clitic: 'will' },
70
- "we've": { host: 'we', clitic: 'have' },
71
- "we're": { host: 'we', clitic: 'are' },
72
- "we'd": { host: 'we', clitic: 'would' },
73
- "i'll": { host: 'i', clitic: 'will' },
74
- "i've": { host: 'i', clitic: 'have' },
75
- "i'm": { host: 'i', clitic: 'am' },
76
- "i'd": { host: 'i', clitic: 'would' },
77
- "you'll": { host: 'you', clitic: 'will' },
78
- "you've": { host: 'you', clitic: 'have' },
79
- "you're": { host: 'you', clitic: 'are' },
80
- "you'd": { host: 'you', clitic: 'would' },
81
- "he'll": { host: 'he', clitic: 'will' },
82
- "he's": { host: 'he', clitic: 'is' },
83
- "he'd": { host: 'he', clitic: 'would' },
84
- "she'll": { host: 'she', clitic: 'will' },
85
- "she's": { host: 'she', clitic: 'is' },
86
- "she'd": { host: 'she', clitic: 'would' },
87
- "it'll": { host: 'it', clitic: 'will' },
88
- "it'd": { host: 'it', clitic: 'would' },
89
- "they'll": { host: 'they', clitic: 'will' },
90
- "they've": { host: 'they', clitic: 'have' },
91
- "they're": { host: 'they', clitic: 'are' },
92
- "they'd": { host: 'they', clitic: 'would' },
93
- "that's": { host: 'that', clitic: 'is' },
94
- "that'll": { host: 'that', clitic: 'will' },
95
- "this'll": { host: 'this', clitic: 'will' },
96
- "it's": { host: 'it', clitic: 'is' },
97
- "who'll": { host: 'who', clitic: 'will' },
98
- "who's": { host: 'who', clitic: 'is' },
99
- "who'd": { host: 'who', clitic: 'would' },
100
- "who've": { host: 'who', clitic: 'have' },
101
- "what's": { host: 'what', clitic: 'is' },
102
- "there's": { host: 'there', clitic: 'is' },
103
- "here's": { host: 'here', clitic: 'is' },
104
- "where's": { host: 'where', clitic: 'is' },
105
- "when's": { host: 'when', clitic: 'is' },
106
- "how's": { host: 'how', clitic: 'is' },
107
- "why's": { host: 'why', clitic: 'is' },
108
- "one's": { host: 'one', clitic: 'is' },
109
- "let's": { host: 'let', clitic: 'us' },
110
- "y'all": { host: 'you', clitic: 'all' },
111
- "don't": { host: 'do', clitic: 'not' },
112
- "can't": { host: 'can', clitic: 'not' },
113
- "won't": { host: 'will', clitic: 'not' },
114
- "shouldn't": { host: 'should', clitic: 'not' },
115
- "couldn't": { host: 'could', clitic: 'not' },
116
- "wouldn't": { host: 'would', clitic: 'not' },
117
- "isn't": { host: 'is', clitic: 'not' },
118
- "aren't": { host: 'are', clitic: 'not' },
119
- "wasn't": { host: 'was', clitic: 'not' },
120
- "weren't": { host: 'were', clitic: 'not' },
121
- "haven't": { host: 'have', clitic: 'not' },
122
- "hasn't": { host: 'has', clitic: 'not' },
123
- "hadn't": { host: 'had', clitic: 'not' },
124
- "didn't": { host: 'did', clitic: 'not' },
125
- "doesn't": { host: 'does', clitic: 'not' },
126
- "ain't": { host: 'am', clitic: 'not' },
127
- "might've": { host: 'might', clitic: 'have' },
128
- "would've": { host: 'would', clitic: 'have' },
129
- "should've": { host: 'should', clitic: 'have' },
130
- "could've": { host: 'could', clitic: 'have' },
131
- "must've": { host: 'must', clitic: 'have' },
132
- };
133
-
134
- interface RawSegment {
135
- text: string;
136
- isContraction: boolean;
137
- isArchaicD: boolean; // poetic preterite "-'d" (fix'd, lov'd, charm'd) — NOT a real
138
- // contraction, but en-norm dehiscises it as host + "would",
139
- // misaligning the whole rest of the line. Re-merged
140
- // conditionally (only when the would/had token is present).
141
- }
142
-
143
- /** Archaic poetic "-'d" preterite: any -'d form that is not a genuine pronoun/wh
144
- * contraction (those live in CONTRACTION_MAP and are checked first). */
145
- const ARCHAIC_D_RE = /^[a-z]{2,}'d$/;
146
-
147
- /**
148
- * Tokenise the raw (un‑normalised) text into word‑like segments,
149
- * marking which are contracted forms.
150
- */
151
- function tokenizeRawText(text: string): RawSegment[] {
152
- const re = /\b[a-zA-Z]+(?:'[a-zA-Z]+)?\b/g;
153
- const segments: RawSegment[] = [];
154
- let match;
155
- while ((match = re.exec(text)) !== null) {
156
- const lower = match[0].toLowerCase();
157
- const isContraction = lower in CONTRACTION_MAP;
158
- segments.push({
159
- text: lower,
160
- isContraction,
161
- isArchaicD: !isContraction && ARCHAIC_D_RE.test(lower),
162
- });
163
- }
164
- return segments;
28
+ // ── UDPipe instance (lazy singleton) ────────────────────────────────
29
+ // The "./wasm" entry point pre-initialises the WASM runtime via top-level await,
30
+ // so by the time this module is imported the engine is ready and construction /
31
+ // parsing are fully synchronous `parseDocument` keeps its synchronous contract.
32
+ let _nlp: ReturnType<typeof createUDPipe> | null = null;
33
+ function nlp(): ReturnType<typeof createUDPipe> {
34
+ // CALLIOPE_UDPIPE_MODEL lets us swap the UDPipe model (EWT / GUM / LinES /
35
+ // ParTUT) for auditing — different treebanks tag XPOS quite differently, so the
36
+ // model choice materially affects the parse the phonological pipeline consumes.
37
+ // Unset → the bundled GUM model.
38
+ const modelPath = process.env.CALLIOPE_UDPIPE_MODEL || undefined;
39
+ return (_nlp ??= createUDPipe({ defaultInputMode: 'presegmented', modelPath }));
165
40
  }
166
41
 
167
- /**
168
- * Re‑merge contraction pairs in a sentence's ClsWord array.
169
- *
170
- * Segments from the raw text are walked in parallel with the sentence's
171
- * tokens. Non‑contraction segments consume 1 token; contraction segments
172
- * consume 2 tokens (host + clitic), which are merged into a single ClsWord
173
- * that preserves the host's properties and the original contracted form.
174
- *
175
- * Returns the updated word array.
176
- */
177
- function mergeContractionsInSentence(
178
- words: ClsWord[],
179
- segments: RawSegment[],
180
- startSegmentIdx: number
181
- ): { words: ClsWord[]; consumedSegments: number } {
182
- const merged: ClsWord[] = [];
183
- let tokenIdx = 0;
184
- let segIdx = startSegmentIdx;
185
-
186
- while (tokenIdx < words.length && segIdx < segments.length) {
187
- // Punctuation tokens have NO raw-text segment (tokenizeRawText matches only
188
- // letter sequences), so they must not consume a segment. Otherwise a
189
- // sentence ending in "!"/"." over-advances segIdx and misaligns every later
190
- // sentence — dropping a pronoun that precedes a contraction ("No more! He
191
- // won't…" lost "He" and mis-tagged the contraction PRP).
192
- if (isPunctuation(words[tokenIdx].lexicalClass)) {
193
- merged.push(words[tokenIdx]);
194
- tokenIdx++;
195
- continue;
196
- }
197
-
198
- const seg = segments[segIdx];
199
-
200
- // Archaic poetic preterite ("fix'd", "lov'd"): en-norm expands the -'d into a
201
- // separate "would"/"had" token, splitting one syllable into two words AND
202
- // shifting every later token off its raw segment. Re-merge host + modal back
203
- // into the apostrophized form — but ONLY when the spurious modal is actually
204
- // there (conditional, so a hand-typed "fix'd" that survived intact is safe).
205
- if (seg.isArchaicD) {
206
- const next = tokenIdx + 1 < words.length ? words[tokenIdx + 1].word.toLowerCase() : '';
207
- if (next === 'would' || next === 'had') {
208
- merged.push({ ...words[tokenIdx], word: seg.text });
209
- tokenIdx += 2;
210
- segIdx++;
211
- continue;
212
- }
213
- merged.push(words[tokenIdx]);
214
- tokenIdx++;
215
- segIdx++;
216
- continue;
217
- }
218
-
219
- if (seg.isContraction) {
220
- if (tokenIdx + 1 >= words.length) {
221
- merged.push(words[tokenIdx]);
222
- tokenIdx++;
223
- segIdx++;
224
- continue;
225
- }
226
-
227
- const hostWord = words[tokenIdx];
228
- const cliticWord = words[tokenIdx + 1];
229
-
230
- // Keep the host as the merged word, update its text to the contracted form.
231
- const mergedWord: ClsWord = {
232
- ...hostWord,
233
- word: seg.text,
234
- };
235
-
236
- merged.push(mergedWord);
237
- tokenIdx += 2;
238
- segIdx++;
239
- } else {
240
- merged.push(words[tokenIdx]);
241
- tokenIdx++;
242
- segIdx++;
243
- }
244
- }
245
-
246
- // Append any remaining words that exceeded segment count.
247
- while (tokenIdx < words.length) {
248
- merged.push(words[tokenIdx]);
249
- tokenIdx++;
250
- }
251
-
252
- return { words: merged, consumedSegments: segIdx - startSegmentIdx };
253
- }
254
-
255
- function mergeHyphenatedWords(words: ClsWord[]): ClsWord[] {
256
- const merged: ClsWord[] = [];
257
- let i = 0;
258
- while (i < words.length) {
259
- if (i + 2 < words.length &&
260
- words[i + 1].word === '-' &&
261
- !isPunctuation(words[i].lexicalClass) &&
262
- !isPunctuation(words[i + 2].lexicalClass)) {
263
- const combined = words[i].word + '-' + words[i + 2].word;
264
- const mergedWord: ClsWord = {
265
- ...words[i],
266
- word: combined,
267
- lexicalClass: words[i + 2].lexicalClass.startsWith('N') ? words[i + 2].lexicalClass : words[i].lexicalClass,
268
- isContent: words[i].isContent || words[i + 2].isContent,
269
- };
270
- merged.push(mergedWord);
271
- i += 3;
272
- } else {
273
- merged.push(words[i]);
274
- i++;
275
- }
276
- }
277
- return merged;
278
- }
279
-
280
- // ─── Mappings: FinNLP → Antelope‑compatible labels ──────────────────
281
- // FinNLP (aka Stanford Dependency Types) versus Antelope NLP dependency (aka Universal Dependencies) type equivalencies.
282
-
283
- const FIN_TO_ANTELOPE_LABEL: Record<string, string> = {
284
- AUX: 'aux',
285
- AUXPASS: 'auxpass',
286
- NSUBJ: 'nsubj',
287
- NSUBJPASS: 'nsubjpass',
288
- DOBJ: 'dobj',
289
- IOBJ: 'iobj',
290
- OBL: 'pobj', // OBL (oblique) ≈ pobj in Antelope
291
- DET: 'det',
292
- CASE: 'prep', // CASE marks the preposition; matched to UD prep
293
- CC: 'cc',
294
- COMPMARK: 'mark',
295
- ADVMARK: 'mark',
296
- NOMD: 'poss', // nominal modifier ≈ possessive relation
297
- AMOD: 'amod',
298
- ADVMOD: 'advmod',
299
- ADVCL: 'advcl',
300
- XCOMP: 'xcomp',
301
- CCOMP: 'ccomp',
302
- ACL: 'acl',
303
- VPRT: 'prt',
304
- NUMDMOD: 'nummod',
305
- EXPL: 'expl',
306
- DISCOURSE: 'discourse',
307
- PUNCT: 'punct',
308
- INTERJ: 'intj',
309
- EXT: 'dep', // extension – best mapped to generic 'dep'
310
- DEP: 'dep',
311
- ROOT: 'root',
312
- };
313
-
314
- function toAntelopeLabel(finLabel: string): string {
315
- return FIN_TO_ANTELOPE_LABEL[finLabel] ?? finLabel.toLowerCase();
316
- }
42
+ // ── POS / punctuation classification (unchanged) ─────────────────────
317
43
 
318
44
  const CONTENT_POS = new Set([
319
45
  'NN', 'NNS', 'NNP', 'NNPS',
@@ -328,7 +54,7 @@ const PUNCT_TAGS = new Set([
328
54
  ',', '.', ':', ';', '!', '?',
329
55
  '-LRB-', '-RRB-', '``', "''",
330
56
  '--', '...', '"', "'",
331
- '(', ')', '[', ']', '{', '}', // FinNLP emits literal bracket tags, not -LRB-/-RRB-
57
+ '(', ')', '[', ']', '{', '}',
332
58
  ]);
333
59
 
334
60
  export function isPunctuation(tag: string): boolean {
@@ -336,10 +62,9 @@ export function isPunctuation(tag: string): boolean {
336
62
  }
337
63
 
338
64
  /**
339
- * Quotation-mark tags. Quotes are tokens (never syllabified) but NOT prosodic
340
- * breaks: a quoted word inside a clause ('call them "wisdom" teeth') is read in
341
- * one breath — no intonational boundary, no caesura. Treating quotes as IU
342
- * boundaries fragmented such lines into 3-4 IUs and flipped their meter.
65
+ * Quotation-mark tags. Quotes are tokens (never syllabified) but NOT prosodic
66
+ * breaks: a quoted word inside a clause is read in one breath no intonational
67
+ * boundary, no caesura.
343
68
  */
344
69
  const QUOTE_TAGS = new Set(['``', "''", '"', "'"]);
345
70
 
@@ -347,275 +72,272 @@ export function isQuoteTag(tag: string): boolean {
347
72
  return QUOTE_TAGS.has(tag);
348
73
  }
349
74
 
75
+ function isContentWord(tag: string): boolean {
76
+ return CONTENT_POS.has(tag);
77
+ }
78
+
350
79
  /**
351
- * Typographic dashes that FinNLP mis-tags as content words. A standalone en-dash
352
- * "–", em-dash "—", horizontal bar "―", minus sign "−" or a run of 2+ hyphens is a
353
- * prosodic break (a dash caesura), NOT a stress-bearing token — but FinNLP's POS
354
- * model labels the bare glyph `NNP` (proper noun), so it flowed through the
355
- * pipeline, received a syllable, and even attracted a strong metrical beat
356
- * ("crunch – a guilt" scanned the dash as 's'). We re-tag any such glyph to the
357
- * Penn dash/colon class ':' (already an IU/caesura boundary) at parse time, so the
358
- * dash drops out of syllabification & scansion and instead marks a pause.
359
- * A *single* hyphen-minus is deliberately excluded — it joins hyphenated compounds
360
- * ("torch-flames") handled by mergeHyphenatedWords.
80
+ * Lowercase the first alphabetic character of every line. Kept available but
81
+ * NOT called by default empirically net-negative with UDPipe (see parseDocument).
82
+ */
83
+ export function lowerLineInitials(text: string): string {
84
+ return text
85
+ .split('\n')
86
+ .map((line) => line.replace(/[A-Za-z]/, (c) => c.toLowerCase()))
87
+ .join('\n');
88
+ }
89
+
90
+ // Archaic / Early-Modern English forms the UD model (trained on modern text)
91
+ // systematically mis-tags. This is a closed lexicon of forms that are virtually
92
+ // never modern words, so an unconditional retag is safe domain adaptation for a
93
+ // verse tool (it replaces the role the old en-pos correction layer played for
94
+ // these tokens). Surface forms are matched lowercased, sans apostrophes.
95
+ const ARCHAIC_POS: Record<string, string> = {
96
+ thy: 'PRP$', thine: 'PRP$',
97
+ thee: 'PRP', thou: 'PRP', ye: 'PRP',
98
+ hath: 'VBZ', doth: 'VBZ', saith: 'VBZ',
99
+ hast: 'VBP', dost: 'VBP', wilt: 'MD',
100
+ shalt: 'MD', canst: 'MD', wouldst: 'MD', shouldst: 'MD', couldst: 'MD',
101
+ hadst: 'VBD', didst: 'VBD', wast: 'VBD', wert: 'VBD',
102
+ };
103
+
104
+ // ── Dash handling (unchanged) ────────────────────────────────────────
105
+
106
+ /**
107
+ * Standalone en/em/figure/bar/minus dashes (or a run of 2+ hyphens) are prosodic
108
+ * breaks (a dash caesura), not stress-bearing tokens. Re-tagged to the Penn dash
109
+ * class ':' so they drop out of syllabification & scansion and mark a pause.
361
110
  */
362
111
  const DASH_GLYPH_RE = /^(?:[‒–—―−]+|-{2,})$/;
363
112
  function isDashGlyph(word: string): boolean {
364
113
  return DASH_GLYPH_RE.test(word);
365
114
  }
366
115
 
367
- const DASH_CLASS = '‒–—―−'; // figure / en / em / bar / minus
116
+ const DASH_CLASS = '‒–—―−';
368
117
  const DASH_GLYPHS_RE = new RegExp(`[${DASH_CLASS}]`, 'g');
369
118
  const DASH_PAREN_RE = new RegExp(`([${DASH_CLASS}])([^${DASH_CLASS}]*?[.!?][^${DASH_CLASS}]*?)([${DASH_CLASS}])`, 'g');
370
119
 
371
120
  /**
372
- * Normalize dash *usages* to comma clause-breaks BEFORE parsing. In verse a dash
373
- * is a comma-like prosodic break not a word, not a sentence end — but FinNLP
374
- * mis-handles it two ways: it glues a SPACE-flanked hyphen-minus into the
375
- * neighbouring word ("I still carry - Oh" token "carry-Oh", then OOV), and it
376
- * tags a bare en/em-dash as a proper noun (NNP) that pollutes the dependency tree.
377
- * Worse, a parenthetical aside set off by dashes often contains sentence-final
378
- * punctuation ("– Oh, Petersburg! –") that splits the line into separate
379
- * sentences and severs the main clause's dependencies (here, carry↔address).
380
- *
381
- * So we (1) fold every dash usage — em/en/figure/bar/minus, a 2+ hyphen run, or a
382
- * space-flanked single hyphen — into a canonical dash glyph (leaving unspaced
383
- * hyphen compounds like "torch-flames" intact for `mergeHyphenatedWords`);
384
- * (2) neutralize sentence-final punctuation INSIDE a dash-delimited parenthetical
385
- * so the line stays one sentence; (3) rewrite the dashes to commas, which FinNLP
386
- * parses cleanly and which are the same prosodic break (a comma is an IU boundary
387
- * → caesura). The verbatim original (dashes and all) is preserved by the caller
388
- * for the reading-view projection; only the parser's working copy is normalized.
121
+ * Normalize dash *usages* to colon-class clause-breaks BEFORE parsing. A dash is
122
+ * an ι (intonational-unit) boundary — a stronger pause than a comma. We fold
123
+ * every dash usage into a canonical glyph, neutralise sentence-final punctuation
124
+ * inside a dash-delimited parenthetical (so the line stays one sentence), then
125
+ * rewrite the dashes to a colon-class break (which prosodic.ts reads as an ι
126
+ * boundary). Unspaced hyphen compounds ("torch-flames") are left intact.
389
127
  */
390
128
  function normalizeDashesToClauseBreaks(text: string): string {
391
- // (1) space-flanked single/multi hyphen-minus, and any 2+ hyphen run → en-dash
392
129
  text = text.replace(/(^|\s)-+(?=\s|$)/g, '$1–');
393
130
  text = text.replace(/-{2,}/g, '–');
394
- // (2) neutralize sentence-final punctuation between paired dashes (keeps it one sentence)
395
131
  text = text.replace(DASH_PAREN_RE, (_m, a, inner, b) => a + inner.replace(/[.!?]+/g, ',') + b);
396
- // (3) dash glyphs → comma clause-break
397
- text = text.replace(DASH_GLYPHS_RE, ',');
398
- // tidy: collapse comma runs, no space before a comma, one space after, no leading comma
399
- text = text.replace(/(?:\s*,\s*){2,}/g, ', ')
400
- .replace(/\s+,/g, ',')
401
- .replace(/,(\S)/g, ', $1')
402
- .replace(/^\s*,\s*/, '');
132
+ text = text.replace(DASH_GLYPHS_RE, ' : ');
133
+ text = text.replace(/(?:\s*:\s*){2,}/g, ' : ')
134
+ .replace(/\s+:/g, ' :')
135
+ .replace(/:(\S)/g, ': $1')
136
+ .replace(/^\s*:\s*/, '')
137
+ .replace(/\s{2,}/g, ' ')
138
+ .trim();
403
139
  return text;
404
140
  }
405
141
 
406
- function isContentWord(tag: string): boolean {
407
- return CONTENT_POS.has(tag);
142
+ // ── Clitic / contraction re‑merge (UDPipe-specific) ──────────────────
143
+ // UDPipe tokenises contractions and elisions on the apostrophe boundary, e.g.
144
+ // it's → it + 's don't → do + n't we'll → we + 'll
145
+ // th'expense → th' + expense 'Tis → ' + Tis fix'd → fix + 'd
146
+ // For scansion a contraction must be ONE orthographic word (one syllable count,
147
+ // one stress domain). We re-merge using UDPipe's SpaceAfter flag (which marks
148
+ // tokens that were contiguous in the source) plus the apostrophe shape:
149
+ // • a LEFT clitic (apostrophe-initial, or n't) merges into the previous word,
150
+ // EXCEPT the possessive 's (XPOS=POS), which stays split (as it always has);
151
+ // • a RIGHT proclitic (a short apostrophe-final piece like "th'", or a bare
152
+ // leading apostrophe before an aphaeresis like 'tis/'twas) merges into the
153
+ // next word.
154
+
155
+ const APOS = /['’]/;
156
+ const LEFT_CLITIC_RE = /^['’]([a-z]+)?$|^n['’]?t$/i; // 's 've 'll 'd 're 'm n't
157
+ const RIGHT_PROCLITIC_RE = /^[a-z]{1,3}['’]$/i; // th' o' d' ne'
158
+ const APHAERESIS = new Set(['tis', 'twas', 'twere', 'twill', 'twould', 'gainst', 'neath', 'tween', 'twixt', 'til', 'cause', 'em', 'round', 'bout']);
159
+
160
+ interface Cluster {
161
+ tokens: UDWord[];
162
+ repr: UDWord; // the token that carries the syntactic role / POS
408
163
  }
409
164
 
410
- // ─── Public API ───────────────────────────────────────────────────
165
+ /** Group UDPipe words into orthographic clusters, re-merging clitics. */
166
+ function clusterWords(uds: UDWord[]): { clusters: Cluster[]; idToCluster: Map<number, number> } {
167
+ const idToCluster = new Map<number, number>();
168
+ const clusters: Cluster[] = [];
169
+
170
+ for (let i = 0; i < uds.length; i++) {
171
+ const w = uds[i];
172
+ const prev = uds[i - 1];
173
+ const contiguous = prev ? prev.spaceAfter === false : false;
174
+ const isLeftClitic =
175
+ contiguous && w.xpos !== 'POS' && LEFT_CLITIC_RE.test(w.form);
176
+
177
+ if (isLeftClitic && clusters.length > 0) {
178
+ clusters[clusters.length - 1].tokens.push(w);
179
+ idToCluster.set(w.id, clusters.length - 1);
180
+ continue;
181
+ }
182
+ clusters.push({ tokens: [w], repr: w });
183
+ idToCluster.set(w.id, clusters.length - 1);
184
+ }
185
+
186
+ // Right-merge pass: a cluster that is a lone proclitic (th') or a bare leading
187
+ // apostrophe before an aphaeresis ('tis) folds into the following cluster.
188
+ const merged: Cluster[] = [];
189
+ for (let c = 0; c < clusters.length; c++) {
190
+ const cl = clusters[c];
191
+ const next = clusters[c + 1];
192
+ const onlyTok = cl.tokens.length === 1 ? cl.tokens[0] : null;
193
+ const contiguous = onlyTok ? onlyTok.spaceAfter === false : false;
194
+ const nextWord = next?.repr;
195
+
196
+ const isProclitic =
197
+ !!onlyTok && contiguous && !!nextWord &&
198
+ (RIGHT_PROCLITIC_RE.test(onlyTok.form) ||
199
+ (/^['’]$/.test(onlyTok.form) && APHAERESIS.has(nextWord.form.toLowerCase())));
200
+
201
+ if (isProclitic && next) {
202
+ next.tokens.unshift(onlyTok!); // prepend proclitic
203
+ for (const t of cl.tokens) idToCluster.set(t.id, merged.length); // re-point to next cluster's eventual index
204
+ // The next cluster will be pushed next iteration; fix its index mapping then.
205
+ // Mark by leaving cl out (skip pushing it).
206
+ // Re-point all of next's tokens to current merged length too:
207
+ continue;
208
+ }
209
+ merged.push(cl);
210
+ }
211
+
212
+ // Rebuild idToCluster cleanly against the merged list (indices shifted by right-merges).
213
+ idToCluster.clear();
214
+ for (let c = 0; c < merged.length; c++) {
215
+ for (const t of merged[c].tokens) idToCluster.set(t.id, c);
216
+ // representative = first token that is neither a left-clitic nor a proclitic
217
+ merged[c].repr =
218
+ merged[c].tokens.find(
219
+ (t) => !(t.xpos !== 'POS' && LEFT_CLITIC_RE.test(t.form)) && !RIGHT_PROCLITIC_RE.test(t.form) && !/^['’]$/.test(t.form),
220
+ ) ?? merged[c].tokens[0];
221
+ }
222
+
223
+ return { clusters: merged, idToCluster };
224
+ }
225
+
226
+ // Dependency labels are passed through to `ClsDependency.dependentType` as RAW
227
+ // Universal Dependencies relations (obl, nsubj:pass, compound, nmod:poss, …) —
228
+ // they are deliberately NOT folded into the old Stanford names. The canonical
229
+ // normaliser `calliope/deps.ts` maps every UD relation onto the engine's Scenario
230
+ // label space (canonicalRel), so new UD tags are accommodated there, not hidden
231
+ // here.
232
+
233
+ // ── Public API ───────────────────────────────────────────────────────
411
234
 
412
- /**
413
- * Parse a multi‑sentence text string and return a ClsDocument whose
414
- * internal structure mirrors the Antelope NLP (aka Universal Dependency type)
415
- * output from McAleese’s original Calliope implementation.
416
- */
417
235
  export function parseDocument(text: string): ClsDocument {
418
- // Collapse runs of sentence-final punctuation (ellipsis "...", "!!", "??")
419
- // to a single mark BEFORE tokenisation. FinNLP otherwise glues the surplus
420
- // marks onto the preceding word ("springtime..." → token "springtime.." → OOV,
421
- // mis-tagged JJ, mis-syllabified, and re-phrased), which made two lines that
422
- // differ only in trailing punctuation scan differently. This is metrically
423
- // harmless (punctuation bears no syllable); the verbatim original is preserved
424
- // by the caller and used for the reading projection.
236
+ // Normalise curly/typographic apostrophes to straight ' so contractions and
237
+ // elisions tokenise identically regardless of glyph.
238
+ text = text.replace(/[‘’ʼ′]/g, "'");
239
+ // Collapse runs of sentence-final punctuation (ellipsis, "!!") to a single mark.
425
240
  text = text.replace(/([.!?])\1+/g, '$1');
426
-
427
- // Dashes → comma clause-breaks (fixes "carry-Oh" gluing AND the parenthetical
428
- // sentence-split that severs main-clause dependencies). See the helper above.
241
+ // Dashes → colon-class clause-breaks (see helper above).
429
242
  text = normalizeDashesToClauseBreaks(text);
430
243
 
431
- // Pre‑scan the raw text for contraction positions before FinNLP
432
- // normalises them away.
433
- const rawSegments = tokenizeRawText(text);
434
-
435
- // Run the FinNLP pipeline STAGED rather than via `Fin.Run`, so the tag-
436
- // correction layer (tagfix.ts) sits between en-pos and en-parse: corrected
437
- // tags repair the tagging AND the dependency tree built from it. The
438
- // stages below mirror finnlp's own Run() exactly (en-norm lexed →
439
- // en-pos → en-parse); lemmas are skipped (unused downstream).
440
- const intercepted = EnNorm.resolveContractions(EnNorm.replaceConfusables(text));
441
- const lexer = new Lexed.Lexed(intercepted).lexer();
442
- const runner: FinRunInstance = { raw: text, intercepted, sentences: [] };
443
- for (let li = 0; li < lexer.sentences.length; li++) {
444
- const tokens = EnNorm.normalizeCaps(lexer.tokens[li]);
445
- const tagging = new EnPos.Tag(tokens).initial().smooth();
446
- const tags = correctTags(tokens, tagging.tags);
447
- const depsTree = EnParse.tree(tags, tokens)[0];
448
- runner.sentences.push({
449
- sentence: lexer.sentences[li],
450
- tokens, tags, lemmas: [],
451
- depsTree,
452
- // Post-parse dependency repair (depfix.ts): systematic en-parse
453
- // attachment errors (noun-compound double-objects, dangling DT).
454
- deps: applyDepFixes(tokens, tags, EnParse.toArray(depsTree)),
455
- confidence: 0,
456
- });
457
- }
244
+ // NOTE on line-initial caps: lowering the first letter of each line before
245
+ // tagging (the role the old `normalizeCaps` played) was tested and is NET
246
+ // NEGATIVE with UDPipe — it recovers cases like "Nap"/"Gap" (UH→NN) but a
247
+ // line-initial capital often HELPS UDPipe's parse (e.g. "Through Eden took…"
248
+ // parses "Eden" as nsubj when capitalised, obl when lowercased), so it changes
249
+ // more scansions than it fixes. Left disabled; see lowerLineInitials() below.
250
+
251
+ const udSentences: UDSentence[] = nlp().parse(text, { inputMode: 'presegmented' });
458
252
 
459
253
  const sentences: ClsSentence[] = [];
460
254
  let absoluteOffset = 0;
461
- let segmentIdx = 0;
462
255
 
463
- for (let si = 0; si < runner.sentences.length; si++) {
464
- const s = runner.sentences[si];
465
- const rawTokens: string[] = s.tokens;
466
- const rawTags: string[] = s.tags;
467
- const rawDeps: FinDepNode[] = s.deps;
256
+ udSentences.forEach((ud, si) => {
257
+ const { clusters, idToCluster } = clusterWords(ud.words);
468
258
 
469
259
  // ---- 1. Build ClsWord array ----
470
- const wordsPre: ClsWord[] = rawTokens.map((word, i) => {
471
- // Re-tag a mis-tagged dash glyph (FinNLP labels "–"/"—" as NNP) to the Penn
472
- // dash class ':' so it acts as a caesura/IU boundary, not a stressable word.
473
- const tag = isDashGlyph(word) ? ':' : rawTags[i];
474
- return ({
475
- index: i + 1, // 1‑based, matching Antelope
476
- lexicalClass: tag,
477
- lexicalDetails: '',
478
- lexicalPlural: tag === 'NNS' || tag === 'NNPS',
479
- position: '',
480
- word,
481
- absoluteIndex: absoluteOffset + i,
482
- isContent: isContentWord(tag),
483
- syllables: [], // filled later by stress module
484
- phraseStress: 0,
485
- dependency: undefined, // patched below
486
- node: undefined, // patched below
487
- });
488
- });
489
-
490
- // ---- 1a. Re‑merge contraction pairs ----
491
- const { words: contractedWords, consumedSegments } = mergeContractionsInSentence(
492
- wordsPre, rawSegments, segmentIdx
493
- );
494
- segmentIdx += consumedSegments;
495
-
496
- // ---- 1b. Re‑merge hyphenated words ----
497
- const words = mergeHyphenatedWords(contractedWords);
498
-
499
- // Re‑index words after merging (1‑based).
500
- words.forEach((w, i) => {
501
- w.index = i + 1;
260
+ const words: ClsWord[] = clusters.map((cl, i) => {
261
+ // Preserve the ORIGINAL case of the surface form (UDPipe keeps it); only
262
+ // lowercase a private lookup key for the archaic-lexicon / dash checks.
263
+ // Lowercasing `word` itself lost every proper-noun capital ("pakistan",
264
+ // "marcel proust") in the display and projection; downstream stress/name
265
+ // lookups all lowercase internally, so case in `word` is display-only.
266
+ const surfaceRaw = cl.tokens.map((t) => t.form).join('');
267
+ const surface = surfaceRaw.toLowerCase();
268
+ // Penn tag: use the raw XPOS when it already is Penn (EWT/GUM), else derive
269
+ // it from UPOS+FEATS (LinES/ParTUT emit non-Penn XPOS the pipeline can't read).
270
+ const rawTag = pennTagOf(cl.repr);
271
+ const archaic = ARCHAIC_POS[surface.replace(/['’]/g, '')];
272
+ const tag = isDashGlyph(surfaceRaw) ? ':' : (archaic ?? rawTag);
273
+ return {
274
+ index: i + 1,
275
+ lexicalClass: tag,
276
+ lexicalDetails: cl.repr.feats,
277
+ lexicalPlural: tag === 'NNS' || tag === 'NNPS',
278
+ position: '',
279
+ word: surfaceRaw,
280
+ absoluteIndex: absoluteOffset + i,
281
+ isContent: isContentWord(tag),
282
+ syllables: [],
283
+ phraseStress: 0,
284
+ dependency: undefined,
285
+ node: undefined,
286
+ };
502
287
  });
503
288
 
504
- // ---- 2. Build ClsDependency array ----
505
- const dependencies: ClsDependency[] = [];
506
-
507
- // Build contraction merge map: wordsPre idx contractedWords idx.
508
- // MUST replay mergeContractionsInSentence exactly: punctuation tokens have no
509
- // raw segment (consume none), and an archaic -'d merges only when the
510
- // spurious would/had token follows.
511
- const contractionMap = new Map<number, number>();
512
- let pi = 0;
513
- let qi = 0;
514
- let segOff = segmentIdx - consumedSegments;
515
- while (pi < wordsPre.length && segOff < segmentIdx) {
516
- if (isPunctuation(wordsPre[pi].lexicalClass)) {
517
- contractionMap.set(pi, qi);
518
- pi++;
519
- qi++;
520
- continue;
521
- }
522
- const seg = rawSegments[segOff];
523
- const archaicMerge = seg.isArchaicD
524
- && pi + 1 < wordsPre.length
525
- && ['would', 'had'].includes(wordsPre[pi + 1].word.toLowerCase());
526
- if ((seg.isContraction && pi + 1 < wordsPre.length) || archaicMerge) {
527
- contractionMap.set(pi, qi);
528
- contractionMap.set(pi + 1, qi);
529
- pi += 2;
530
- qi += 1;
531
- segOff++;
532
- } else {
533
- contractionMap.set(pi, qi);
534
- pi++;
535
- qi++;
536
- segOff++;
289
+ // Sentence-initial de-capitalisation (mirrors en-norm.normalizeCaps in the
290
+ // pre-UD path): lower the first letter of the sentence's first word UNLESS it
291
+ // is a proper noun, so "The"→"the" and "I"→"i" (an orthographic capital forced
292
+ // by line position carries no lexical signal) while mid-line proper nouns
293
+ // ("Marcel Proust", "Pakistan") keep their caps for display/projection.
294
+ for (const w of words) {
295
+ if (isPunctuation(w.lexicalClass)) continue;
296
+ if (!/^(NNP|NNPS)$/.test(w.lexicalClass) && /^[A-Z]/.test(w.word)) {
297
+ w.displayWord = w.word; // keep the original surface for reports/phonopoetics
298
+ w.word = w.word[0].toLowerCase() + w.word.slice(1);
537
299
  }
538
- }
539
- while (pi < wordsPre.length) {
540
- contractionMap.set(pi, qi);
541
- pi++;
542
- qi++;
300
+ break;
543
301
  }
544
302
 
545
- // Build hyphen merge map: contractedWords idx → words idx
546
- const hyphenMap = new Map<number, number>();
547
- let ci = 0;
548
- let wi = 0;
549
- while (ci < contractedWords.length) {
550
- if (ci + 2 < contractedWords.length &&
551
- contractedWords[ci + 1].word === '-' &&
552
- !isPunctuation(contractedWords[ci].lexicalClass) &&
553
- !isPunctuation(contractedWords[ci + 2].lexicalClass)) {
554
- hyphenMap.set(ci, wi);
555
- hyphenMap.set(ci + 1, wi);
556
- hyphenMap.set(ci + 2, wi);
557
- ci += 3;
558
- wi++;
303
+ // ---- 2. Build ClsDependency array ----
304
+ const dependencies: ClsDependency[] = [];
305
+ clusters.forEach((cl, depIdx) => {
306
+ const r = cl.repr;
307
+ let govIdx: number | undefined;
308
+ if (r.head === 0) {
309
+ govIdx = undefined; // attaches to root
559
310
  } else {
560
- hyphenMap.set(ci, wi);
561
- ci++;
562
- wi++;
311
+ const g = idToCluster.get(r.head);
312
+ // If the representative's head fell inside its own cluster (e.g. a copula
313
+ // clitic), follow that clitic's head out of the cluster.
314
+ if (g === depIdx) {
315
+ const external = cl.tokens
316
+ .map((t) => idToCluster.get(t.head))
317
+ .find((gi) => gi !== undefined && gi !== depIdx);
318
+ govIdx = external;
319
+ } else {
320
+ govIdx = g;
321
+ }
563
322
  }
564
- }
565
-
566
- // Compose: wordsPre idx → words idx
567
- const mergeMap2 = new Map<number, number>();
568
- for (const [preIdx, cIdx] of contractionMap) {
569
- const wIdx = hyphenMap.get(cIdx);
570
- if (wIdx !== undefined) mergeMap2.set(preIdx, wIdx);
571
- }
572
-
573
- // Build dependencies from rawDeps, remapping governor and dependent indices.
574
- for (let i = 0; i < rawDeps.length; i++) {
575
- const dep = rawDeps[i];
576
- const govPreIdx = dep.parent; // 0‑based, -1 for root
577
- const depPreIdx = i;
578
-
579
- const govPostIdx = govPreIdx >= 0 ? mergeMap2.get(govPreIdx) : undefined;
580
- const depPostIdx = mergeMap2.get(depPreIdx);
581
-
582
- if (depPostIdx === undefined) continue;
583
- if (govPreIdx >= 0 && govPostIdx === depPostIdx) continue; // self-loop from merged pair
584
323
 
585
- // If this dependent is the clitic half of a contraction, skip
586
- // (its dependency info is already captured through the host mapping).
587
- // Check if this is the second token of a contraction:
588
- const isCliticHalf = i > 0 &&
589
- mergeMap2.get(i) === mergeMap2.get(i - 1);
590
-
591
- if (isCliticHalf) continue;
592
-
593
- const govWord: ClsWord | undefined =
594
- govPostIdx !== undefined && govPostIdx >= 0 ? words[govPostIdx] : undefined;
595
- const depWord: ClsWord = words[depPostIdx];
596
-
597
- // If governor was a clitic half that got merged into host, re-point to host
598
- const actualGovWord = govWord || (govPreIdx >= 0 && govPreIdx < wordsPre.length
599
- ? words[mergeMap2.get(govPreIdx)!]
600
- : undefined);
324
+ const depWord = words[depIdx];
325
+ const govWord = govIdx !== undefined ? words[govIdx] : null;
601
326
 
602
327
  dependencies.push({
603
- index: depPostIdx + 1,
604
- governorIndex: govPostIdx !== undefined ? govPostIdx + 1 : 0,
605
- dependentIndex: depPostIdx + 1,
606
- dependentType: toAntelopeLabel(dep.label),
607
- governorName: (govPostIdx !== undefined && govPostIdx >= 0 && words[govPostIdx])
608
- ? words[govPostIdx].word : 'ROOT',
328
+ index: depIdx + 1,
329
+ governorIndex: govIdx !== undefined ? govIdx + 1 : 0,
330
+ dependentIndex: depIdx + 1,
331
+ dependentType: govIdx === undefined ? 'root' : r.deprel,
332
+ governorName: govWord ? govWord.word : 'ROOT',
609
333
  dependentName: depWord.word,
610
- governor: (govPostIdx !== undefined && govPostIdx >= 0 && words[govPostIdx])
611
- ? words[govPostIdx] : null as unknown as ClsWord,
334
+ governor: govWord as unknown as ClsWord,
612
335
  dependent: depWord,
613
336
  });
614
- }
337
+ });
615
338
 
616
- // Ensure ROOT dependency exists.
617
- const hasRoot = dependencies.some(d => d.governorIndex === 0);
618
- if (!hasRoot && words.length > 0) {
339
+ // Ensure a ROOT dependency exists.
340
+ if (!dependencies.some((d) => d.governorIndex === 0) && words.length > 0) {
619
341
  dependencies.push({
620
342
  index: 0,
621
343
  governorIndex: 0,
@@ -628,18 +350,23 @@ export function parseDocument(text: string): ClsDocument {
628
350
  });
629
351
  }
630
352
 
631
- // Back‑reference: each word stores the dependency edge where it is the dependent.
632
- words.forEach(w => {
633
- w.dependency = dependencies.find(d => d.dependent === w);
353
+ // Back‑reference: each word stores the dependency edge where it is dependent.
354
+ words.forEach((w) => {
355
+ w.dependency = dependencies.find((d) => d.dependent === w);
634
356
  });
635
357
 
636
- // ---- 3. Build phrase‑structure node tree from FinNLP's depsTree ----
637
- const rootNode = buildNodeTree(s.depsTree, words);
358
+ // UDPipe XPOS correction (the role en-pos + tagfix.ts played pre-UD): fix the
359
+ // systematic mis-tags UDPipe makes on terse, decontextualised verse via
360
+ // en-lexicon cross-check. Runs HERE (in the parser, after deps are attached)
361
+ // so direct `parseDocument` consumers — and every engine — see corrected tags;
362
+ // rule (3) needs the dependency back-references just set above.
363
+ correctUDPipePos({ index: si + 1, nodes: null, dependencies, words, xml: '' });
638
364
 
639
- // Attach each word’s corresponding leaf node (if any).
365
+ // ---- 3. Build phrase‑structure node tree from the dependency graph ----
366
+ const rootNode = buildDepNodeTree(words, dependencies);
640
367
  const wordNodeMap = new Map<number, ClsNode>();
641
368
  collectWordNodes(rootNode, wordNodeMap);
642
- words.forEach(w => {
369
+ words.forEach((w) => {
643
370
  w.node = wordNodeMap.get(w.index);
644
371
  });
645
372
 
@@ -652,186 +379,123 @@ export function parseDocument(text: string): ClsDocument {
652
379
  });
653
380
 
654
381
  absoluteOffset += words.length;
655
- }
382
+ });
656
383
 
657
384
  return { sentences, xml: '' };
658
385
  }
659
386
 
660
- // ─── Node‑tree construction ──────────────────────────────────────
661
-
662
- /** Sentinel used for empty / unparsable trees. */
663
- const EMPTY_NODE: ClsNode = {
664
- index: '0',
665
- nodeName: 'EMPTY',
666
- parent: null,
667
- contains: [],
668
- };
669
-
670
- /**
671
- * Recursively convert a FinNLP NodeInterface tree into a ClsNode tree
672
- * that mirrors Antelope’s phrase‑structure output.
673
- *
674
- * The root of the FinNLP tree is always wrapped in an SQ node.
675
- */
676
- function buildNodeTree(
677
- finRoot: FinNodeInterface | null | undefined,
678
- words: ClsWord[]
679
- ): ClsNode {
680
- // Guard: missing or empty tree
681
- if (!finRoot || !finRoot.tokens || finRoot.tokens.length === 0) {
682
- // Create a minimal SQ node containing all words as direct leaves.
683
- const sq: ClsNode = {
684
- index: '1',
685
- nodeName: 'SQ',
686
- parent: null,
687
- contains: words.map(w => createWordLeaf(w)),
688
- };
689
- return sq;
690
- }
691
-
692
- // The top‑level SQ node (Antelope style)
693
- const sqNode: ClsNode = {
694
- index: '1',
695
- nodeName: 'SQ',
696
- parent: null,
697
- contains: [],
698
- };
387
+ // ── Dependency constituency projection ─────────────────────────────
388
+ // phonological.ts groups clitic groups into phonological phrases by finding the
389
+ // smallest phrase node containing them, so it needs a properly nested, position-
390
+ // ordered constituency tree. We synthesise one by projection: each head plus its
391
+ // dependent subtrees forms a phrase, labelled by the head's POS family.
392
+
393
+ function phraseType(tag: string): string {
394
+ if (/^(NN|NNS|NNP|NNPS|PRP|PRP\$|DT|CD|WP|WDT|EX)$/.test(tag)) return 'NP';
395
+ if (/^(VB|VBD|VBG|VBN|VBP|VBZ|MD)$/.test(tag)) return 'VP';
396
+ if (/^(IN|TO)$/.test(tag)) return 'PP';
397
+ if (/^(JJ|JJR|JJS)$/.test(tag)) return 'ADJP';
398
+ if (/^(RB|RBR|RBS|WRB)$/.test(tag)) return 'ADVP';
399
+ return 'XP';
400
+ }
699
401
 
700
- // Convert the root FinNLP node and attach it under SQ.
701
- const convertedRoot = convertFinNode(finRoot, words, sqNode);
702
- if (convertedRoot) {
703
- convertedRoot.parent = sqNode;
704
- sqNode.contains.push(convertedRoot);
402
+ function buildDepNodeTree(words: ClsWord[], deps: ClsDependency[]): ClsNode {
403
+ const sq: ClsNode = { index: '1', nodeName: 'SQ', parent: null, contains: [] };
404
+ if (words.length === 0) return sq;
405
+
406
+ // children[g] = list of dependent word-indices (1-based) governed by g (1-based);
407
+ // roots are governed by 0.
408
+ const children = new Map<number, number[]>();
409
+ for (const d of deps) {
410
+ if (d.dependentIndex < 1 || d.dependentIndex > words.length) continue;
411
+ const g = d.governorIndex;
412
+ if (!children.has(g)) children.set(g, []);
413
+ children.get(g)!.push(d.dependentIndex);
705
414
  }
706
415
 
707
- // Ensure every word is represented somewhere in the tree.
708
- // Words not yet attached (e.g., punctuation at the edges) are added
709
- // directly under SQ.
710
- const attachedIndices = new Set<number>();
711
- collectAttachedWordIndices(sqNode, attachedIndices);
712
- for (const w of words) {
713
- if (!attachedIndices.has(w.index)) {
714
- const leaf = createWordLeaf(w);
715
- leaf.parent = sqNode;
716
- sqNode.contains.push(leaf);
416
+ const build = (wordIdx: number, parent: ClsNode): ClsNode => {
417
+ const word = words[wordIdx - 1];
418
+ const kids = (children.get(wordIdx) ?? []).filter((k) => k !== wordIdx);
419
+ if (kids.length === 0) {
420
+ const leaf = createWordLeaf(word);
421
+ leaf.parent = parent;
422
+ return leaf;
717
423
  }
718
- }
719
-
720
- return sqNode;
721
- }
722
-
723
- /**
724
- * Convert a single FinNodeInterface (sub‑tree) into a ClsNode.
725
- */
726
- function convertFinNode(
727
- finNode: FinNodeInterface,
728
- words: ClsWord[],
729
- parentNode: ClsNode
730
- ): ClsNode {
731
- // Determine whether this is a leaf (single‑word) node.
732
- const isLeaf =
733
- (!finNode.left || finNode.left.length === 0) &&
734
- (!finNode.right || finNode.right.length === 0);
735
-
736
- if (isLeaf && finNode.tokens.length === 1) {
737
- // Single‑word leaf → reference the ClsWord
738
- const wordIdx = finNode.index[0]; // 0‑based
739
- const word = words[wordIdx];
740
- if (!word) {
741
- // Fallback: create a text leaf
742
- return {
743
- index: `leaf_${wordIdx}`,
744
- nodeName: finNode.tokens[0],
745
- parent: parentNode,
746
- contains: [],
747
- };
424
+ const node: ClsNode = {
425
+ index: `ph_${wordIdx}`,
426
+ nodeName: phraseType(word.lexicalClass),
427
+ parent,
428
+ contains: [],
429
+ };
430
+ // Order head + dependents by surface position for a projective tree.
431
+ const ordered = [...kids, wordIdx].sort((a, b) => a - b);
432
+ for (const idx of ordered) {
433
+ if (idx === wordIdx) {
434
+ const leaf = createWordLeaf(word);
435
+ leaf.parent = node;
436
+ node.contains.push(leaf);
437
+ } else {
438
+ node.contains.push(build(idx, node));
439
+ }
748
440
  }
749
- return createWordLeaf(word);
750
- }
751
-
752
- // Phrase node – use the FinNLP type as label (NP, VP, PP, etc.)
753
- const phraseType = finNode.type && finNode.type !== 'ROOT'
754
- ? finNode.type
755
- : 'XP';
756
- const phraseNode: ClsNode = {
757
- index: `ph_${finNode.index[0]}_${finNode.index[1]}`,
758
- nodeName: phraseType,
759
- parent: parentNode,
760
- contains: [],
441
+ return node;
761
442
  };
762
443
 
763
- // Process left children (pre‑head dependents)
764
- if (finNode.left && finNode.left.length > 0) {
765
- for (const leftChild of finNode.left) {
766
- const childNode = convertFinNode(leftChild, words, phraseNode);
767
- if (childNode) {
768
- childNode.parent = phraseNode;
769
- phraseNode.contains.push(childNode);
770
- }
444
+ const roots = (children.get(0) ?? []).sort((a, b) => a - b);
445
+ if (roots.length === 0) {
446
+ // No explicit root: attach all words as leaves under SQ.
447
+ for (const w of words) {
448
+ const leaf = createWordLeaf(w);
449
+ leaf.parent = sq;
450
+ sq.contains.push(leaf);
771
451
  }
452
+ return sq;
772
453
  }
773
-
774
- // The head token(s) of this node
775
- for (let i = finNode.index[0]; i <= finNode.index[1]; i++) {
776
- const word = words[i];
777
- if (word) {
778
- const leaf = createWordLeaf(word);
779
- leaf.parent = phraseNode;
780
- phraseNode.contains.push(leaf);
781
- }
454
+ for (const r of roots) {
455
+ const child = build(r, sq);
456
+ sq.contains.push(child);
782
457
  }
783
458
 
784
- // Process right children (post‑head dependents)
785
- if (finNode.right && finNode.right.length > 0) {
786
- for (const rightChild of finNode.right) {
787
- const childNode = convertFinNode(rightChild, words, phraseNode);
788
- if (childNode) {
789
- childNode.parent = phraseNode;
790
- phraseNode.contains.push(childNode);
791
- }
459
+ // Attach any orphan words (rare) directly under SQ.
460
+ const attached = new Set<number>();
461
+ collectAttachedWordIndices(sq, attached);
462
+ for (const w of words) {
463
+ if (!attached.has(w.index)) {
464
+ const leaf = createWordLeaf(w);
465
+ leaf.parent = sq;
466
+ sq.contains.push(leaf);
792
467
  }
793
468
  }
794
-
795
- return phraseNode;
469
+ return sq;
796
470
  }
797
471
 
798
- // ─── Leaf‑node helpers ────────────────────────────────────────────
472
+ // ── Leaf / traversal helpers (unchanged) ─────────────────────────────
799
473
 
800
474
  function createWordLeaf(word: ClsWord): ClsNode {
801
475
  return {
802
476
  index: `w${word.index}`,
803
- nodeName: word.index.toString(), // Antelope style: the word’s 1‑based index as string
477
+ nodeName: word.index.toString(),
804
478
  parent: null,
805
479
  contains: [word],
806
480
  };
807
481
  }
808
482
 
809
- // ─── Tree traversal helpers ───────────────────────────────────────
810
-
811
483
  function collectWordNodes(node: ClsNode, map: Map<number, ClsNode>): void {
812
484
  for (const child of node.contains) {
813
485
  if (child instanceof Object && 'word' in (child as any)) {
814
- // child is a ClsWord
815
- const w = child as ClsWord;
816
- // The leaf is the current node (since word leaves contain the word directly)
817
- map.set(w.index, node);
486
+ map.set((child as ClsWord).index, node);
818
487
  } else if (child instanceof Object && 'index' in (child as any)) {
819
- // child is a ClsNode
820
488
  collectWordNodes(child as ClsNode, map);
821
489
  }
822
490
  }
823
491
  }
824
492
 
825
- function collectAttachedWordIndices(
826
- node: ClsNode,
827
- set: Set<number>
828
- ): void {
493
+ function collectAttachedWordIndices(node: ClsNode, set: Set<number>): void {
829
494
  for (const child of node.contains) {
830
495
  if (child instanceof Object && 'word' in (child as any)) {
831
- const w = child as ClsWord;
832
- set.add(w.index);
496
+ set.add((child as ClsWord).index);
833
497
  } else if (child instanceof Object && 'index' in (child as any)) {
834
498
  collectAttachedWordIndices(child as ClsNode, set);
835
499
  }
836
500
  }
837
- }
501
+ }