calliope-ts 0.0.2 → 0.0.4

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 (160) hide show
  1. package/README.md +32 -20
  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/calliope_src_contents.md +19049 -0
  130. package/src/clio/caesura.ts +145 -0
  131. package/src/clio/depfix.ts +88 -0
  132. package/src/clio/display.ts +1042 -0
  133. package/src/clio/engine.ts +38 -0
  134. package/src/clio/parser.ts +845 -0
  135. package/src/clio/phonological.ts +849 -0
  136. package/src/clio/phrasestress.ts +108 -0
  137. package/src/clio/pipeline.ts +154 -0
  138. package/src/clio/rhyme.ts +740 -0
  139. package/src/clio/scandroid.ts +434 -0
  140. package/src/clio/scansion.ts +1130 -0
  141. package/src/clio/semantics.ts +134 -0
  142. package/src/clio/stress.ts +1731 -0
  143. package/src/clio/tagfix.ts +104 -0
  144. package/src/display.ts +321 -137
  145. package/src/engine.ts +22 -0
  146. package/src/index.ts +176 -32
  147. package/src/parser.ts +346 -682
  148. package/src/phonological.ts +72 -4
  149. package/src/phrasestress.ts +108 -0
  150. package/src/rhyme.ts +428 -8
  151. package/src/scansion.ts +136 -15
  152. package/src/semantics.ts +134 -0
  153. package/src/stress.ts +794 -64
  154. package/src/types.ts +39 -4
  155. package/tests/DataForHayesLinesOnly.txt +364 -0
  156. package/tests/DataForHayesStressSymbolsRevised.txt +728 -0
  157. package/tests/basic.test.ts +443 -37
  158. package/tests/bench-hayes.mjs +72 -0
  159. package/tests/wagner-stress.test.ts +188 -0
  160. package/vitest.config.ts +0 -15
@@ -0,0 +1,696 @@
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 McAleese’s Calliope.
4
+ import * as Lexed from 'lexed';
5
+ import * as EnPos from 'en-pos';
6
+ import * as EnParse from 'en-parse';
7
+ import * as EnNorm from 'en-norm';
8
+ import { correctTags } from './tagfix.js';
9
+ import { applyDepFixes } from './depfix.js';
10
+ const CONTRACTION_MAP = {
11
+ "we'll": { host: 'we', clitic: 'will' },
12
+ "we've": { host: 'we', clitic: 'have' },
13
+ "we're": { host: 'we', clitic: 'are' },
14
+ "we'd": { host: 'we', clitic: 'would' },
15
+ "i'll": { host: 'i', clitic: 'will' },
16
+ "i've": { host: 'i', clitic: 'have' },
17
+ "i'm": { host: 'i', clitic: 'am' },
18
+ "i'd": { host: 'i', clitic: 'would' },
19
+ "you'll": { host: 'you', clitic: 'will' },
20
+ "you've": { host: 'you', clitic: 'have' },
21
+ "you're": { host: 'you', clitic: 'are' },
22
+ "you'd": { host: 'you', clitic: 'would' },
23
+ "he'll": { host: 'he', clitic: 'will' },
24
+ "he's": { host: 'he', clitic: 'is' },
25
+ "he'd": { host: 'he', clitic: 'would' },
26
+ "she'll": { host: 'she', clitic: 'will' },
27
+ "she's": { host: 'she', clitic: 'is' },
28
+ "she'd": { host: 'she', clitic: 'would' },
29
+ "it'll": { host: 'it', clitic: 'will' },
30
+ "it'd": { host: 'it', clitic: 'would' },
31
+ "they'll": { host: 'they', clitic: 'will' },
32
+ "they've": { host: 'they', clitic: 'have' },
33
+ "they're": { host: 'they', clitic: 'are' },
34
+ "they'd": { host: 'they', clitic: 'would' },
35
+ "that's": { host: 'that', clitic: 'is' },
36
+ "that'll": { host: 'that', clitic: 'will' },
37
+ "this'll": { host: 'this', clitic: 'will' },
38
+ "it's": { host: 'it', clitic: 'is' },
39
+ "who'll": { host: 'who', clitic: 'will' },
40
+ "who's": { host: 'who', clitic: 'is' },
41
+ "who'd": { host: 'who', clitic: 'would' },
42
+ "who've": { host: 'who', clitic: 'have' },
43
+ "what's": { host: 'what', clitic: 'is' },
44
+ "there's": { host: 'there', clitic: 'is' },
45
+ "here's": { host: 'here', clitic: 'is' },
46
+ "where's": { host: 'where', clitic: 'is' },
47
+ "when's": { host: 'when', clitic: 'is' },
48
+ "how's": { host: 'how', clitic: 'is' },
49
+ "why's": { host: 'why', clitic: 'is' },
50
+ "one's": { host: 'one', clitic: 'is' },
51
+ "let's": { host: 'let', clitic: 'us' },
52
+ "y'all": { host: 'you', clitic: 'all' },
53
+ "don't": { host: 'do', clitic: 'not' },
54
+ "can't": { host: 'can', clitic: 'not' },
55
+ "won't": { host: 'will', clitic: 'not' },
56
+ "shouldn't": { host: 'should', clitic: 'not' },
57
+ "couldn't": { host: 'could', clitic: 'not' },
58
+ "wouldn't": { host: 'would', clitic: 'not' },
59
+ "isn't": { host: 'is', clitic: 'not' },
60
+ "aren't": { host: 'are', clitic: 'not' },
61
+ "wasn't": { host: 'was', clitic: 'not' },
62
+ "weren't": { host: 'were', clitic: 'not' },
63
+ "haven't": { host: 'have', clitic: 'not' },
64
+ "hasn't": { host: 'has', clitic: 'not' },
65
+ "hadn't": { host: 'had', clitic: 'not' },
66
+ "didn't": { host: 'did', clitic: 'not' },
67
+ "doesn't": { host: 'does', clitic: 'not' },
68
+ "ain't": { host: 'am', clitic: 'not' },
69
+ "might've": { host: 'might', clitic: 'have' },
70
+ "would've": { host: 'would', clitic: 'have' },
71
+ "should've": { host: 'should', clitic: 'have' },
72
+ "could've": { host: 'could', clitic: 'have' },
73
+ "must've": { host: 'must', clitic: 'have' },
74
+ };
75
+ /** Archaic poetic "-'d" preterite: any -'d form that is not a genuine pronoun/wh
76
+ * contraction (those live in CONTRACTION_MAP and are checked first). Hyphenated
77
+ * compounds count too (hen-peck'd, half-hid'd) — en-norm keeps the compound as one
78
+ * token but dehiscises the -'d into "would", which the merge re-attaches. */
79
+ const ARCHAIC_D_RE = /^[a-z]+(?:-[a-z]+)*'d$/;
80
+ /**
81
+ * Tokenise the raw (un‑normalised) text into word‑like segments,
82
+ * marking which are contracted forms.
83
+ */
84
+ function tokenizeRawText(text) {
85
+ // A hyphenated word that carries an apostrophe-suffix (hen-peck'd, ne'er-do-well's)
86
+ // is ONE segment — en-norm keeps the hyphen compound as a single token, so splitting
87
+ // it here (→ "hen" + "peck'd") desynced the segment↔token walk and broke the -'d
88
+ // re-merge. Plain hyphen compounds WITHOUT an apostrophe (torch-flames) still split,
89
+ // exactly as before (the first alternative requires a trailing 'x), so mergeHyphenated-
90
+ // Words keeps handling those.
91
+ const re = /\b[a-zA-Z]+(?:-[a-zA-Z]+)*'[a-zA-Z]+\b|\b[a-zA-Z]+(?:'[a-zA-Z]+)?\b/g;
92
+ const segments = [];
93
+ let match;
94
+ while ((match = re.exec(text)) !== null) {
95
+ const lower = match[0].toLowerCase();
96
+ const isContraction = lower in CONTRACTION_MAP;
97
+ segments.push({
98
+ text: lower,
99
+ isContraction,
100
+ isArchaicD: !isContraction && ARCHAIC_D_RE.test(lower),
101
+ });
102
+ }
103
+ return segments;
104
+ }
105
+ /**
106
+ * Re‑merge contraction pairs in a sentence's ClsWord array.
107
+ *
108
+ * Segments from the raw text are walked in parallel with the sentence's
109
+ * tokens. Non‑contraction segments consume 1 token; contraction segments
110
+ * consume 2 tokens (host + clitic), which are merged into a single ClsWord
111
+ * that preserves the host's properties and the original contracted form.
112
+ *
113
+ * Returns the updated word array.
114
+ */
115
+ function mergeContractionsInSentence(words, segments, startSegmentIdx) {
116
+ const merged = [];
117
+ let tokenIdx = 0;
118
+ let segIdx = startSegmentIdx;
119
+ while (tokenIdx < words.length && segIdx < segments.length) {
120
+ // Punctuation tokens have NO raw-text segment (tokenizeRawText matches only
121
+ // letter sequences), so they must not consume a segment. Otherwise a
122
+ // sentence ending in "!"/"." over-advances segIdx and misaligns every later
123
+ // sentence — dropping a pronoun that precedes a contraction ("No more! He
124
+ // won't…" lost "He" and mis-tagged the contraction PRP).
125
+ if (isPunctuation(words[tokenIdx].lexicalClass)) {
126
+ merged.push(words[tokenIdx]);
127
+ tokenIdx++;
128
+ continue;
129
+ }
130
+ const seg = segments[segIdx];
131
+ // Archaic poetic preterite ("fix'd", "lov'd"): en-norm expands the -'d into a
132
+ // separate "would"/"had" token, splitting one syllable into two words AND
133
+ // shifting every later token off its raw segment. Re-merge host + modal back
134
+ // into the apostrophized form — but ONLY when the spurious modal is actually
135
+ // there (conditional, so a hand-typed "fix'd" that survived intact is safe).
136
+ if (seg.isArchaicD) {
137
+ const next = tokenIdx + 1 < words.length ? words[tokenIdx + 1].word.toLowerCase() : '';
138
+ if (next === 'would' || next === 'had') {
139
+ merged.push({ ...words[tokenIdx], word: seg.text });
140
+ tokenIdx += 2;
141
+ segIdx++;
142
+ continue;
143
+ }
144
+ merged.push(words[tokenIdx]);
145
+ tokenIdx++;
146
+ segIdx++;
147
+ continue;
148
+ }
149
+ if (seg.isContraction) {
150
+ if (tokenIdx + 1 >= words.length) {
151
+ merged.push(words[tokenIdx]);
152
+ tokenIdx++;
153
+ segIdx++;
154
+ continue;
155
+ }
156
+ const hostWord = words[tokenIdx];
157
+ const cliticWord = words[tokenIdx + 1];
158
+ // Keep the host as the merged word, update its text to the contracted form.
159
+ const mergedWord = {
160
+ ...hostWord,
161
+ word: seg.text,
162
+ };
163
+ merged.push(mergedWord);
164
+ tokenIdx += 2;
165
+ segIdx++;
166
+ }
167
+ else {
168
+ merged.push(words[tokenIdx]);
169
+ tokenIdx++;
170
+ segIdx++;
171
+ }
172
+ }
173
+ // Append any remaining words that exceeded segment count.
174
+ while (tokenIdx < words.length) {
175
+ merged.push(words[tokenIdx]);
176
+ tokenIdx++;
177
+ }
178
+ return { words: merged, consumedSegments: segIdx - startSegmentIdx };
179
+ }
180
+ function mergeHyphenatedWords(words) {
181
+ const merged = [];
182
+ let i = 0;
183
+ while (i < words.length) {
184
+ if (i + 2 < words.length &&
185
+ words[i + 1].word === '-' &&
186
+ !isPunctuation(words[i].lexicalClass) &&
187
+ !isPunctuation(words[i + 2].lexicalClass)) {
188
+ const combined = words[i].word + '-' + words[i + 2].word;
189
+ const mergedWord = {
190
+ ...words[i],
191
+ word: combined,
192
+ lexicalClass: words[i + 2].lexicalClass.startsWith('N') ? words[i + 2].lexicalClass : words[i].lexicalClass,
193
+ isContent: words[i].isContent || words[i + 2].isContent,
194
+ };
195
+ merged.push(mergedWord);
196
+ i += 3;
197
+ }
198
+ else {
199
+ merged.push(words[i]);
200
+ i++;
201
+ }
202
+ }
203
+ return merged;
204
+ }
205
+ // ─── Mappings: FinNLP → Antelope‑compatible labels ──────────────────
206
+ // FinNLP (aka Stanford Dependency Types) versus Antelope NLP dependency (aka Universal Dependencies) type equivalencies.
207
+ const FIN_TO_ANTELOPE_LABEL = {
208
+ AUX: 'aux',
209
+ AUXPASS: 'auxpass',
210
+ NSUBJ: 'nsubj',
211
+ NSUBJPASS: 'nsubjpass',
212
+ DOBJ: 'dobj',
213
+ IOBJ: 'iobj',
214
+ OBL: 'pobj', // OBL (oblique) ≈ pobj in Antelope
215
+ DET: 'det',
216
+ CASE: 'prep', // CASE marks the preposition; matched to UD prep
217
+ CC: 'cc',
218
+ COMPMARK: 'mark',
219
+ ADVMARK: 'mark',
220
+ NOMD: 'poss', // nominal modifier ≈ possessive relation
221
+ AMOD: 'amod',
222
+ ADVMOD: 'advmod',
223
+ ADVCL: 'advcl',
224
+ XCOMP: 'xcomp',
225
+ CCOMP: 'ccomp',
226
+ ACL: 'acl',
227
+ VPRT: 'prt',
228
+ NUMDMOD: 'nummod',
229
+ EXPL: 'expl',
230
+ DISCOURSE: 'discourse',
231
+ PUNCT: 'punct',
232
+ INTERJ: 'intj',
233
+ EXT: 'dep', // extension – best mapped to generic 'dep'
234
+ DEP: 'dep',
235
+ ROOT: 'root',
236
+ };
237
+ function toAntelopeLabel(finLabel) {
238
+ return FIN_TO_ANTELOPE_LABEL[finLabel] ?? finLabel.toLowerCase();
239
+ }
240
+ const CONTENT_POS = new Set([
241
+ 'NN', 'NNS', 'NNP', 'NNPS',
242
+ 'JJ', 'JJR', 'JJS',
243
+ 'VB', 'VBD', 'VBG', 'VBN', 'VBP', 'VBZ',
244
+ 'RB', 'RBR', 'RBS',
245
+ 'CD', // cardinal numbers (content‑like)
246
+ ]);
247
+ /** Punctuation POS tags that should not be syllabified. */
248
+ const PUNCT_TAGS = new Set([
249
+ ',', '.', ':', ';', '!', '?',
250
+ '-LRB-', '-RRB-', '``', "''",
251
+ '--', '...', '"', "'",
252
+ '(', ')', '[', ']', '{', '}', // FinNLP emits literal bracket tags, not -LRB-/-RRB-
253
+ ]);
254
+ export function isPunctuation(tag) {
255
+ return PUNCT_TAGS.has(tag);
256
+ }
257
+ /**
258
+ * Quotation-mark tags. Quotes are tokens (never syllabified) but NOT prosodic
259
+ * breaks: a quoted word inside a clause ('call them "wisdom" teeth') is read in
260
+ * one breath — no intonational boundary, no caesura. Treating quotes as IU
261
+ * boundaries fragmented such lines into 3-4 IUs and flipped their meter.
262
+ */
263
+ const QUOTE_TAGS = new Set(['``', "''", '"', "'"]);
264
+ export function isQuoteTag(tag) {
265
+ return QUOTE_TAGS.has(tag);
266
+ }
267
+ /**
268
+ * Typographic dashes that FinNLP mis-tags as content words. A standalone en-dash
269
+ * "–", em-dash "—", horizontal bar "―", minus sign "−" or a run of 2+ hyphens is a
270
+ * prosodic break (a dash caesura), NOT a stress-bearing token — but FinNLP's POS
271
+ * model labels the bare glyph `NNP` (proper noun), so it flowed through the
272
+ * pipeline, received a syllable, and even attracted a strong metrical beat
273
+ * ("crunch – a guilt" scanned the dash as 's'). We re-tag any such glyph to the
274
+ * Penn dash/colon class ':' (already an IU/caesura boundary) at parse time, so the
275
+ * dash drops out of syllabification & scansion and instead marks a pause.
276
+ * A *single* hyphen-minus is deliberately excluded — it joins hyphenated compounds
277
+ * ("torch-flames") handled by mergeHyphenatedWords.
278
+ */
279
+ const DASH_GLYPH_RE = /^(?:[‒–—―−]+|-{2,})$/;
280
+ function isDashGlyph(word) {
281
+ return DASH_GLYPH_RE.test(word);
282
+ }
283
+ const DASH_CLASS = '‒–—―−'; // figure / en / em / bar / minus
284
+ const DASH_GLYPHS_RE = new RegExp(`[${DASH_CLASS}]`, 'g');
285
+ const DASH_PAREN_RE = new RegExp(`([${DASH_CLASS}])([^${DASH_CLASS}]*?[.!?][^${DASH_CLASS}]*?)([${DASH_CLASS}])`, 'g');
286
+ /**
287
+ * Normalize dash *usages* to comma clause-breaks BEFORE parsing. In verse a dash
288
+ * is a comma-like prosodic break — not a word, not a sentence end — but FinNLP
289
+ * mis-handles it two ways: it glues a SPACE-flanked hyphen-minus into the
290
+ * neighbouring word ("I still carry - Oh" → token "carry-Oh", then OOV), and it
291
+ * tags a bare en/em-dash as a proper noun (NNP) that pollutes the dependency tree.
292
+ * Worse, a parenthetical aside set off by dashes often contains sentence-final
293
+ * punctuation ("– Oh, Petersburg! –") that splits the line into separate
294
+ * sentences and severs the main clause's dependencies (here, carry↔address).
295
+ *
296
+ * So we (1) fold every dash usage — em/en/figure/bar/minus, a 2+ hyphen run, or a
297
+ * space-flanked single hyphen — into a canonical dash glyph (leaving unspaced
298
+ * hyphen compounds like "torch-flames" intact for `mergeHyphenatedWords`);
299
+ * (2) neutralize sentence-final punctuation INSIDE a dash-delimited parenthetical
300
+ * so the line stays one sentence; (3) rewrite the dashes to commas, which FinNLP
301
+ * parses cleanly and which are the same prosodic break (a comma is an IU boundary
302
+ * → caesura). The verbatim original (dashes and all) is preserved by the caller
303
+ * for the reading-view projection; only the parser's working copy is normalized.
304
+ */
305
+ function normalizeDashesToClauseBreaks(text) {
306
+ // (1) space-flanked single/multi hyphen-minus, and any 2+ hyphen run → en-dash
307
+ text = text.replace(/(^|\s)-+(?=\s|$)/g, '$1–');
308
+ text = text.replace(/-{2,}/g, '–');
309
+ // (2) neutralize sentence-final punctuation between paired dashes (keeps it one sentence)
310
+ text = text.replace(DASH_PAREN_RE, (_m, a, inner, b) => a + inner.replace(/[.!?]+/g, ',') + b);
311
+ // (3) dash glyphs → comma clause-break
312
+ text = text.replace(DASH_GLYPHS_RE, ',');
313
+ // tidy: collapse comma runs, no space before a comma, one space after, no leading comma
314
+ text = text.replace(/(?:\s*,\s*){2,}/g, ', ')
315
+ .replace(/\s+,/g, ',')
316
+ .replace(/,(\S)/g, ', $1')
317
+ .replace(/^\s*,\s*/, '');
318
+ return text;
319
+ }
320
+ function isContentWord(tag) {
321
+ return CONTENT_POS.has(tag);
322
+ }
323
+ // ─── Public API ───────────────────────────────────────────────────
324
+ /**
325
+ * Parse a multi‑sentence text string and return a ClsDocument whose
326
+ * internal structure mirrors the Antelope NLP (aka Universal Dependency type)
327
+ * output from McAleese’s original Calliope implementation.
328
+ */
329
+ export function parseDocument(text) {
330
+ // Collapse runs of sentence-final punctuation (ellipsis "...", "!!", "??")
331
+ // to a single mark BEFORE tokenisation. FinNLP otherwise glues the surplus
332
+ // marks onto the preceding word ("springtime..." → token "springtime.." → OOV,
333
+ // mis-tagged JJ, mis-syllabified, and re-phrased), which made two lines that
334
+ // differ only in trailing punctuation scan differently. This is metrically
335
+ // harmless (punctuation bears no syllable); the verbatim original is preserved
336
+ // by the caller and used for the reading projection.
337
+ text = text.replace(/([.!?])\1+/g, '$1');
338
+ // Dashes → comma clause-breaks (fixes "carry-Oh" gluing AND the parenthetical
339
+ // sentence-split that severs main-clause dependencies). See the helper above.
340
+ text = normalizeDashesToClauseBreaks(text);
341
+ // Pre‑scan the raw text for contraction positions before FinNLP
342
+ // normalises them away.
343
+ const rawSegments = tokenizeRawText(text);
344
+ // Run the FinNLP pipeline STAGED rather than via `Fin.Run`, so the tag-
345
+ // correction layer (tagfix.ts) sits between en-pos and en-parse: corrected
346
+ // tags repair the tagging AND the dependency tree built from it. The
347
+ // stages below mirror finnlp's own Run() exactly (en-norm → lexed →
348
+ // en-pos → en-parse); lemmas are skipped (unused downstream).
349
+ const intercepted = EnNorm.resolveContractions(EnNorm.replaceConfusables(text));
350
+ const lexer = new Lexed.Lexed(intercepted).lexer();
351
+ const runner = { raw: text, intercepted, sentences: [] };
352
+ for (let li = 0; li < lexer.sentences.length; li++) {
353
+ const tokens = EnNorm.normalizeCaps(lexer.tokens[li]);
354
+ const tagging = new EnPos.Tag(tokens).initial().smooth();
355
+ const tags = correctTags(tokens, tagging.tags);
356
+ const depsTree = EnParse.tree(tags, tokens)[0];
357
+ runner.sentences.push({
358
+ sentence: lexer.sentences[li],
359
+ tokens, tags, lemmas: [],
360
+ depsTree,
361
+ // Post-parse dependency repair (depfix.ts): systematic en-parse
362
+ // attachment errors (noun-compound double-objects, dangling DT).
363
+ deps: applyDepFixes(tokens, tags, EnParse.toArray(depsTree)),
364
+ confidence: 0,
365
+ });
366
+ }
367
+ const sentences = [];
368
+ let absoluteOffset = 0;
369
+ let segmentIdx = 0;
370
+ for (let si = 0; si < runner.sentences.length; si++) {
371
+ const s = runner.sentences[si];
372
+ const rawTokens = s.tokens;
373
+ const rawTags = s.tags;
374
+ const rawDeps = s.deps;
375
+ // ---- 1. Build ClsWord array ----
376
+ const wordsPre = rawTokens.map((word, i) => {
377
+ // Re-tag a mis-tagged dash glyph (FinNLP labels "–"/"—" as NNP) to the Penn
378
+ // dash class ':' so it acts as a caesura/IU boundary, not a stressable word.
379
+ const tag = isDashGlyph(word) ? ':' : rawTags[i];
380
+ return ({
381
+ index: i + 1, // 1‑based, matching Antelope
382
+ lexicalClass: tag,
383
+ lexicalDetails: '',
384
+ lexicalPlural: tag === 'NNS' || tag === 'NNPS',
385
+ position: '',
386
+ word,
387
+ absoluteIndex: absoluteOffset + i,
388
+ isContent: isContentWord(tag),
389
+ syllables: [], // filled later by stress module
390
+ phraseStress: 0,
391
+ dependency: undefined, // patched below
392
+ node: undefined, // patched below
393
+ });
394
+ });
395
+ // ---- 1a. Re‑merge contraction pairs ----
396
+ const { words: contractedWords, consumedSegments } = mergeContractionsInSentence(wordsPre, rawSegments, segmentIdx);
397
+ segmentIdx += consumedSegments;
398
+ // ---- 1b. Re‑merge hyphenated words ----
399
+ const words = mergeHyphenatedWords(contractedWords);
400
+ // Re‑index words after merging (1‑based).
401
+ words.forEach((w, i) => {
402
+ w.index = i + 1;
403
+ });
404
+ // ---- 2. Build ClsDependency array ----
405
+ const dependencies = [];
406
+ // Build contraction merge map: wordsPre idx → contractedWords idx.
407
+ // MUST replay mergeContractionsInSentence exactly: punctuation tokens have no
408
+ // raw segment (consume none), and an archaic -'d merges only when the
409
+ // spurious would/had token follows.
410
+ const contractionMap = new Map();
411
+ let pi = 0;
412
+ let qi = 0;
413
+ let segOff = segmentIdx - consumedSegments;
414
+ while (pi < wordsPre.length && segOff < segmentIdx) {
415
+ if (isPunctuation(wordsPre[pi].lexicalClass)) {
416
+ contractionMap.set(pi, qi);
417
+ pi++;
418
+ qi++;
419
+ continue;
420
+ }
421
+ const seg = rawSegments[segOff];
422
+ const archaicMerge = seg.isArchaicD
423
+ && pi + 1 < wordsPre.length
424
+ && ['would', 'had'].includes(wordsPre[pi + 1].word.toLowerCase());
425
+ if ((seg.isContraction && pi + 1 < wordsPre.length) || archaicMerge) {
426
+ contractionMap.set(pi, qi);
427
+ contractionMap.set(pi + 1, qi);
428
+ pi += 2;
429
+ qi += 1;
430
+ segOff++;
431
+ }
432
+ else {
433
+ contractionMap.set(pi, qi);
434
+ pi++;
435
+ qi++;
436
+ segOff++;
437
+ }
438
+ }
439
+ while (pi < wordsPre.length) {
440
+ contractionMap.set(pi, qi);
441
+ pi++;
442
+ qi++;
443
+ }
444
+ // Build hyphen merge map: contractedWords idx → words idx
445
+ const hyphenMap = new Map();
446
+ let ci = 0;
447
+ let wi = 0;
448
+ while (ci < contractedWords.length) {
449
+ if (ci + 2 < contractedWords.length &&
450
+ contractedWords[ci + 1].word === '-' &&
451
+ !isPunctuation(contractedWords[ci].lexicalClass) &&
452
+ !isPunctuation(contractedWords[ci + 2].lexicalClass)) {
453
+ hyphenMap.set(ci, wi);
454
+ hyphenMap.set(ci + 1, wi);
455
+ hyphenMap.set(ci + 2, wi);
456
+ ci += 3;
457
+ wi++;
458
+ }
459
+ else {
460
+ hyphenMap.set(ci, wi);
461
+ ci++;
462
+ wi++;
463
+ }
464
+ }
465
+ // Compose: wordsPre idx → words idx
466
+ const mergeMap2 = new Map();
467
+ for (const [preIdx, cIdx] of contractionMap) {
468
+ const wIdx = hyphenMap.get(cIdx);
469
+ if (wIdx !== undefined)
470
+ mergeMap2.set(preIdx, wIdx);
471
+ }
472
+ // Build dependencies from rawDeps, remapping governor and dependent indices.
473
+ for (let i = 0; i < rawDeps.length; i++) {
474
+ const dep = rawDeps[i];
475
+ const govPreIdx = dep.parent; // 0‑based, -1 for root
476
+ const depPreIdx = i;
477
+ const govPostIdx = govPreIdx >= 0 ? mergeMap2.get(govPreIdx) : undefined;
478
+ const depPostIdx = mergeMap2.get(depPreIdx);
479
+ if (depPostIdx === undefined)
480
+ continue;
481
+ if (govPreIdx >= 0 && govPostIdx === depPostIdx)
482
+ continue; // self-loop from merged pair
483
+ // If this dependent is the clitic half of a contraction, skip
484
+ // (its dependency info is already captured through the host mapping).
485
+ // Check if this is the second token of a contraction:
486
+ const isCliticHalf = i > 0 &&
487
+ mergeMap2.get(i) === mergeMap2.get(i - 1);
488
+ if (isCliticHalf)
489
+ continue;
490
+ const govWord = govPostIdx !== undefined && govPostIdx >= 0 ? words[govPostIdx] : undefined;
491
+ const depWord = words[depPostIdx];
492
+ // If governor was a clitic half that got merged into host, re-point to host
493
+ const actualGovWord = govWord || (govPreIdx >= 0 && govPreIdx < wordsPre.length
494
+ ? words[mergeMap2.get(govPreIdx)]
495
+ : undefined);
496
+ dependencies.push({
497
+ index: depPostIdx + 1,
498
+ governorIndex: govPostIdx !== undefined ? govPostIdx + 1 : 0,
499
+ dependentIndex: depPostIdx + 1,
500
+ dependentType: toAntelopeLabel(dep.label),
501
+ governorName: (govPostIdx !== undefined && govPostIdx >= 0 && words[govPostIdx])
502
+ ? words[govPostIdx].word : 'ROOT',
503
+ dependentName: depWord.word,
504
+ governor: (govPostIdx !== undefined && govPostIdx >= 0 && words[govPostIdx])
505
+ ? words[govPostIdx] : null,
506
+ dependent: depWord,
507
+ });
508
+ }
509
+ // Ensure ROOT dependency exists.
510
+ const hasRoot = dependencies.some(d => d.governorIndex === 0);
511
+ if (!hasRoot && words.length > 0) {
512
+ dependencies.push({
513
+ index: 0,
514
+ governorIndex: 0,
515
+ dependentIndex: 1,
516
+ dependentType: 'root',
517
+ governorName: 'ROOT',
518
+ dependentName: words[0].word,
519
+ governor: null,
520
+ dependent: words[0],
521
+ });
522
+ }
523
+ // Back‑reference: each word stores the dependency edge where it is the dependent.
524
+ words.forEach(w => {
525
+ w.dependency = dependencies.find(d => d.dependent === w);
526
+ });
527
+ // ---- 3. Build phrase‑structure node tree from FinNLP's depsTree ----
528
+ const rootNode = buildNodeTree(s.depsTree, words);
529
+ // Attach each word’s corresponding leaf node (if any).
530
+ const wordNodeMap = new Map();
531
+ collectWordNodes(rootNode, wordNodeMap);
532
+ words.forEach(w => {
533
+ w.node = wordNodeMap.get(w.index);
534
+ });
535
+ sentences.push({
536
+ index: si + 1,
537
+ nodes: rootNode,
538
+ dependencies,
539
+ words,
540
+ xml: '',
541
+ });
542
+ absoluteOffset += words.length;
543
+ }
544
+ return { sentences, xml: '' };
545
+ }
546
+ // ─── Node‑tree construction ──────────────────────────────────────
547
+ /** Sentinel used for empty / unparsable trees. */
548
+ const EMPTY_NODE = {
549
+ index: '0',
550
+ nodeName: 'EMPTY',
551
+ parent: null,
552
+ contains: [],
553
+ };
554
+ /**
555
+ * Recursively convert a FinNLP NodeInterface tree into a ClsNode tree
556
+ * that mirrors Antelope’s phrase‑structure output.
557
+ *
558
+ * The root of the FinNLP tree is always wrapped in an SQ node.
559
+ */
560
+ function buildNodeTree(finRoot, words) {
561
+ // Guard: missing or empty tree
562
+ if (!finRoot || !finRoot.tokens || finRoot.tokens.length === 0) {
563
+ // Create a minimal SQ node containing all words as direct leaves.
564
+ const sq = {
565
+ index: '1',
566
+ nodeName: 'SQ',
567
+ parent: null,
568
+ contains: words.map(w => createWordLeaf(w)),
569
+ };
570
+ return sq;
571
+ }
572
+ // The top‑level SQ node (Antelope style)
573
+ const sqNode = {
574
+ index: '1',
575
+ nodeName: 'SQ',
576
+ parent: null,
577
+ contains: [],
578
+ };
579
+ // Convert the root FinNLP node and attach it under SQ.
580
+ const convertedRoot = convertFinNode(finRoot, words, sqNode);
581
+ if (convertedRoot) {
582
+ convertedRoot.parent = sqNode;
583
+ sqNode.contains.push(convertedRoot);
584
+ }
585
+ // Ensure every word is represented somewhere in the tree.
586
+ // Words not yet attached (e.g., punctuation at the edges) are added
587
+ // directly under SQ.
588
+ const attachedIndices = new Set();
589
+ collectAttachedWordIndices(sqNode, attachedIndices);
590
+ for (const w of words) {
591
+ if (!attachedIndices.has(w.index)) {
592
+ const leaf = createWordLeaf(w);
593
+ leaf.parent = sqNode;
594
+ sqNode.contains.push(leaf);
595
+ }
596
+ }
597
+ return sqNode;
598
+ }
599
+ /**
600
+ * Convert a single FinNodeInterface (sub‑tree) into a ClsNode.
601
+ */
602
+ function convertFinNode(finNode, words, parentNode) {
603
+ // Determine whether this is a leaf (single‑word) node.
604
+ const isLeaf = (!finNode.left || finNode.left.length === 0) &&
605
+ (!finNode.right || finNode.right.length === 0);
606
+ if (isLeaf && finNode.tokens.length === 1) {
607
+ // Single‑word leaf → reference the ClsWord
608
+ const wordIdx = finNode.index[0]; // 0‑based
609
+ const word = words[wordIdx];
610
+ if (!word) {
611
+ // Fallback: create a text leaf
612
+ return {
613
+ index: `leaf_${wordIdx}`,
614
+ nodeName: finNode.tokens[0],
615
+ parent: parentNode,
616
+ contains: [],
617
+ };
618
+ }
619
+ return createWordLeaf(word);
620
+ }
621
+ // Phrase node – use the FinNLP type as label (NP, VP, PP, etc.)
622
+ const phraseType = finNode.type && finNode.type !== 'ROOT'
623
+ ? finNode.type
624
+ : 'XP';
625
+ const phraseNode = {
626
+ index: `ph_${finNode.index[0]}_${finNode.index[1]}`,
627
+ nodeName: phraseType,
628
+ parent: parentNode,
629
+ contains: [],
630
+ };
631
+ // Process left children (pre‑head dependents)
632
+ if (finNode.left && finNode.left.length > 0) {
633
+ for (const leftChild of finNode.left) {
634
+ const childNode = convertFinNode(leftChild, words, phraseNode);
635
+ if (childNode) {
636
+ childNode.parent = phraseNode;
637
+ phraseNode.contains.push(childNode);
638
+ }
639
+ }
640
+ }
641
+ // The head token(s) of this node
642
+ for (let i = finNode.index[0]; i <= finNode.index[1]; i++) {
643
+ const word = words[i];
644
+ if (word) {
645
+ const leaf = createWordLeaf(word);
646
+ leaf.parent = phraseNode;
647
+ phraseNode.contains.push(leaf);
648
+ }
649
+ }
650
+ // Process right children (post‑head dependents)
651
+ if (finNode.right && finNode.right.length > 0) {
652
+ for (const rightChild of finNode.right) {
653
+ const childNode = convertFinNode(rightChild, words, phraseNode);
654
+ if (childNode) {
655
+ childNode.parent = phraseNode;
656
+ phraseNode.contains.push(childNode);
657
+ }
658
+ }
659
+ }
660
+ return phraseNode;
661
+ }
662
+ // ─── Leaf‑node helpers ────────────────────────────────────────────
663
+ function createWordLeaf(word) {
664
+ return {
665
+ index: `w${word.index}`,
666
+ nodeName: word.index.toString(), // Antelope style: the word’s 1‑based index as string
667
+ parent: null,
668
+ contains: [word],
669
+ };
670
+ }
671
+ // ─── Tree traversal helpers ───────────────────────────────────────
672
+ function collectWordNodes(node, map) {
673
+ for (const child of node.contains) {
674
+ if (child instanceof Object && 'word' in child) {
675
+ // child is a ClsWord
676
+ const w = child;
677
+ // The leaf is the current node (since word leaves contain the word directly)
678
+ map.set(w.index, node);
679
+ }
680
+ else if (child instanceof Object && 'index' in child) {
681
+ // child is a ClsNode
682
+ collectWordNodes(child, map);
683
+ }
684
+ }
685
+ }
686
+ function collectAttachedWordIndices(node, set) {
687
+ for (const child of node.contains) {
688
+ if (child instanceof Object && 'word' in child) {
689
+ const w = child;
690
+ set.add(w.index);
691
+ }
692
+ else if (child instanceof Object && 'index' in child) {
693
+ collectAttachedWordIndices(child, set);
694
+ }
695
+ }
696
+ }