calliope-ts 0.0.1

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 (50) hide show
  1. package/.claude/settings.local.json +8 -0
  2. package/.opencode/skills/calliope-ts/SKILL.md +74 -0
  3. package/LICENSE +201 -0
  4. package/README.md +485 -0
  5. package/dist/depfix.d.ts +13 -0
  6. package/dist/depfix.d.ts.map +1 -0
  7. package/dist/depfix.js +84 -0
  8. package/dist/display.d.ts +38 -0
  9. package/dist/display.d.ts.map +1 -0
  10. package/dist/display.js +890 -0
  11. package/dist/index.d.ts +50 -0
  12. package/dist/index.d.ts.map +1 -0
  13. package/dist/index.js +504 -0
  14. package/dist/parser.d.ts +10 -0
  15. package/dist/parser.d.ts.map +1 -0
  16. package/dist/parser.js +688 -0
  17. package/dist/phonological.d.ts +41 -0
  18. package/dist/phonological.d.ts.map +1 -0
  19. package/dist/phonological.js +788 -0
  20. package/dist/rhyme.d.ts +26 -0
  21. package/dist/rhyme.d.ts.map +1 -0
  22. package/dist/rhyme.js +340 -0
  23. package/dist/scandroid.d.ts +17 -0
  24. package/dist/scandroid.d.ts.map +1 -0
  25. package/dist/scandroid.js +435 -0
  26. package/dist/scansion.d.ts +37 -0
  27. package/dist/scansion.d.ts.map +1 -0
  28. package/dist/scansion.js +1007 -0
  29. package/dist/scansion_debug.js +586 -0
  30. package/dist/stress.d.ts +32 -0
  31. package/dist/stress.d.ts.map +1 -0
  32. package/dist/stress.js +1372 -0
  33. package/dist/tagfix.d.ts +6 -0
  34. package/dist/tagfix.d.ts.map +1 -0
  35. package/dist/tagfix.js +101 -0
  36. package/dist/types.d.ts +173 -0
  37. package/dist/types.d.ts.map +1 -0
  38. package/dist/types.js +4 -0
  39. package/package.json +62 -0
  40. package/src/depfix.ts +88 -0
  41. package/src/display.ts +954 -0
  42. package/src/index.ts +541 -0
  43. package/src/parser.ts +837 -0
  44. package/src/phonological.ts +849 -0
  45. package/src/rhyme.ts +328 -0
  46. package/src/scandroid.ts +434 -0
  47. package/src/scansion.ts +1053 -0
  48. package/src/stress.ts +1381 -0
  49. package/src/tagfix.ts +104 -0
  50. package/src/types.ts +230 -0
package/src/parser.ts ADDED
@@ -0,0 +1,837 @@
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
+
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';
11
+ import {
12
+ ClsDocument,
13
+ ClsSentence,
14
+ ClsWord,
15
+ ClsDependency,
16
+ ClsNode
17
+ } from './types.js';
18
+
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;
165
+ }
166
+
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
+ }
317
+
318
+ const CONTENT_POS = new Set([
319
+ 'NN', 'NNS', 'NNP', 'NNPS',
320
+ 'JJ', 'JJR', 'JJS',
321
+ 'VB', 'VBD', 'VBG', 'VBN', 'VBP', 'VBZ',
322
+ 'RB', 'RBR', 'RBS',
323
+ 'CD', // cardinal numbers (content‑like)
324
+ ]);
325
+
326
+ /** Punctuation POS tags that should not be syllabified. */
327
+ const PUNCT_TAGS = new Set([
328
+ ',', '.', ':', ';', '!', '?',
329
+ '-LRB-', '-RRB-', '``', "''",
330
+ '--', '...', '"', "'",
331
+ '(', ')', '[', ']', '{', '}', // FinNLP emits literal bracket tags, not -LRB-/-RRB-
332
+ ]);
333
+
334
+ export function isPunctuation(tag: string): boolean {
335
+ return PUNCT_TAGS.has(tag);
336
+ }
337
+
338
+ /**
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.
343
+ */
344
+ const QUOTE_TAGS = new Set(['``', "''", '"', "'"]);
345
+
346
+ export function isQuoteTag(tag: string): boolean {
347
+ return QUOTE_TAGS.has(tag);
348
+ }
349
+
350
+ /**
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.
361
+ */
362
+ const DASH_GLYPH_RE = /^(?:[‒–—―−]+|-{2,})$/;
363
+ function isDashGlyph(word: string): boolean {
364
+ return DASH_GLYPH_RE.test(word);
365
+ }
366
+
367
+ const DASH_CLASS = '‒–—―−'; // figure / en / em / bar / minus
368
+ const DASH_GLYPHS_RE = new RegExp(`[${DASH_CLASS}]`, 'g');
369
+ const DASH_PAREN_RE = new RegExp(`([${DASH_CLASS}])([^${DASH_CLASS}]*?[.!?][^${DASH_CLASS}]*?)([${DASH_CLASS}])`, 'g');
370
+
371
+ /**
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.
389
+ */
390
+ function normalizeDashesToClauseBreaks(text: string): string {
391
+ // (1) space-flanked single/multi hyphen-minus, and any 2+ hyphen run → en-dash
392
+ text = text.replace(/(^|\s)-+(?=\s|$)/g, '$1–');
393
+ text = text.replace(/-{2,}/g, '–');
394
+ // (2) neutralize sentence-final punctuation between paired dashes (keeps it one sentence)
395
+ 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*/, '');
403
+ return text;
404
+ }
405
+
406
+ function isContentWord(tag: string): boolean {
407
+ return CONTENT_POS.has(tag);
408
+ }
409
+
410
+ // ─── Public API ───────────────────────────────────────────────────
411
+
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
+ 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.
425
+ 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.
429
+ text = normalizeDashesToClauseBreaks(text);
430
+
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
+ }
458
+
459
+ const sentences: ClsSentence[] = [];
460
+ let absoluteOffset = 0;
461
+ let segmentIdx = 0;
462
+
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;
468
+
469
+ // ---- 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;
502
+ });
503
+
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++;
537
+ }
538
+ }
539
+ while (pi < wordsPre.length) {
540
+ contractionMap.set(pi, qi);
541
+ pi++;
542
+ qi++;
543
+ }
544
+
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++;
559
+ } else {
560
+ hyphenMap.set(ci, wi);
561
+ ci++;
562
+ wi++;
563
+ }
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
+
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);
601
+
602
+ 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',
609
+ dependentName: depWord.word,
610
+ governor: (govPostIdx !== undefined && govPostIdx >= 0 && words[govPostIdx])
611
+ ? words[govPostIdx] : null as unknown as ClsWord,
612
+ dependent: depWord,
613
+ });
614
+ }
615
+
616
+ // Ensure ROOT dependency exists.
617
+ const hasRoot = dependencies.some(d => d.governorIndex === 0);
618
+ if (!hasRoot && words.length > 0) {
619
+ dependencies.push({
620
+ index: 0,
621
+ governorIndex: 0,
622
+ dependentIndex: 1,
623
+ dependentType: 'root',
624
+ governorName: 'ROOT',
625
+ dependentName: words[0].word,
626
+ governor: null as unknown as ClsWord,
627
+ dependent: words[0],
628
+ });
629
+ }
630
+
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);
634
+ });
635
+
636
+ // ---- 3. Build phrase‑structure node tree from FinNLP's depsTree ----
637
+ const rootNode = buildNodeTree(s.depsTree, words);
638
+
639
+ // Attach each word’s corresponding leaf node (if any).
640
+ const wordNodeMap = new Map<number, ClsNode>();
641
+ collectWordNodes(rootNode, wordNodeMap);
642
+ words.forEach(w => {
643
+ w.node = wordNodeMap.get(w.index);
644
+ });
645
+
646
+ sentences.push({
647
+ index: si + 1,
648
+ nodes: rootNode,
649
+ dependencies,
650
+ words,
651
+ xml: '',
652
+ });
653
+
654
+ absoluteOffset += words.length;
655
+ }
656
+
657
+ return { sentences, xml: '' };
658
+ }
659
+
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
+ };
699
+
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);
705
+ }
706
+
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);
717
+ }
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
+ };
748
+ }
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: [],
761
+ };
762
+
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
+ }
771
+ }
772
+ }
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
+ }
782
+ }
783
+
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
+ }
792
+ }
793
+ }
794
+
795
+ return phraseNode;
796
+ }
797
+
798
+ // ─── Leaf‑node helpers ────────────────────────────────────────────
799
+
800
+ function createWordLeaf(word: ClsWord): ClsNode {
801
+ return {
802
+ index: `w${word.index}`,
803
+ nodeName: word.index.toString(), // Antelope style: the word’s 1‑based index as string
804
+ parent: null,
805
+ contains: [word],
806
+ };
807
+ }
808
+
809
+ // ─── Tree traversal helpers ───────────────────────────────────────
810
+
811
+ function collectWordNodes(node: ClsNode, map: Map<number, ClsNode>): void {
812
+ for (const child of node.contains) {
813
+ 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);
818
+ } else if (child instanceof Object && 'index' in (child as any)) {
819
+ // child is a ClsNode
820
+ collectWordNodes(child as ClsNode, map);
821
+ }
822
+ }
823
+ }
824
+
825
+ function collectAttachedWordIndices(
826
+ node: ClsNode,
827
+ set: Set<number>
828
+ ): void {
829
+ for (const child of node.contains) {
830
+ if (child instanceof Object && 'word' in (child as any)) {
831
+ const w = child as ClsWord;
832
+ set.add(w.index);
833
+ } else if (child instanceof Object && 'index' in (child as any)) {
834
+ collectAttachedWordIndices(child as ClsNode, set);
835
+ }
836
+ }
837
+ }