@rueter/jscg3
v1.0.0
Published
Pure JavaScript CG-3 (Constraint Grammar 3) engine (built in comparison to Visl original) that runs the grammars you provide
Maintainers
Readme
jscg3
A pure JavaScript implementation of VISL CG-3 (Constraint Grammar 3), ported from pycg3.
jscg3 runs the Constraint Grammar files you provide on analyses you provide. It has no dependencies, no native
code and no WebAssembly. The core (@rueter/jscg3) uses nothing that is specific to Node, so it runs in a browser too; reading
files lives in a separate entry point (@rueter/jscg3/node).
It produces the same output as pycg3, byte for byte, on every grammar and text it has been compared on (below), and it is about nine times faster.
Features
- Pure JavaScript: ES modules, Node >= 18 or any current browser.
- Streaming: windows (sentences) are parsed, processed and written one at a time (
runStreamis a generator). - CLI and library: a
jscg3command withvislcg3's options, and a module interface. - VISL CG-3 syntax and semantics:
DELIMITERS,MAPPING-PREFIX,LIST,SETand the set operators,SECTIONs (iterated to a fixed point as in vislcg3),SELECT,REMOVE,IFF,ADD,MAP,UNMAP,REPLACE,SUBSTITUTE,APPEND,COPY(withEXCEPT),ADDCOHORT,REMCOHORT,SETVARIABLE,REMVARIABLE,SETPARENT,SETCHILD,REMPARENT,SWITCHPARENT, the relation rules (ADDRELATION,SETRELATION,REMRELATIONand the plural ones); contextual tests with positions, scans,C,NOT,NEGATE,BARRIER,CBARRIER,LINK,OR,ALL,NONE, sub-readings (SUB:n,0/n,0/*),$$and&&unification, dependency positions (p c s pp cc, theAflag,@0), and positions that look into the neighbouring windows (W,<,>).
Installation
npm install @rueter/jscg3Command line
# Disambiguate input file with grammar
jscg3 -g grammar.cg3 -i input.txt -o output.txt
# Pipes
cat input.txt | jscg3 -g grammar.cg3 > output.txt
# Trace rule applications (-t), include deleted readings (-p), mark changed readings (-e), run N sections (-s N)
jscg3 -g grammar.cg3 -i input.txt -t -p
# Windows kept behind and read ahead for tests with W < > (default 2); make every scan cross window edges
jscg3 -g grammar.cg3 -i input.txt --num-windows 3 --always-spanLibrary
import { GrammarParser, Disambiguator } from '@rueter/jscg3';
const grammar = new GrammarParser().parse(`
DELIMITERS = "<$.>" ;
LIST Noun = N ;
LIST Verb = V ;
SECTION
SELECT Verb (0 Noun) (-1 ("<to>")) ;
`);
const engine = new Disambiguator(grammar);
console.log(engine.runText('"<to>"\n\t"to" PREP\n"<run>"\n\t"run" N\n\t"run" V\n"<.>"\n\t"." CLB\n'));In a pipeline, as UralicNLP uses pycg3
import { Cg } from '@rueter/jscg3';
import '@rueter/jscg3/node'; // adds Cg.fromFiles (Node only)
const cg = Cg.fromFiles(['disambiguator.cg3', 'functions.cg3']); // grammars, run in the order given
// or, anywhere: new Cg([disambiguatorText, functionsText])
// analyses in the shape pyhfst's lookup gives: one list of [analysis, weight] pairs per word
const morphologies = [[['time+N+Sg', 0.0], ['time+V+Inf', 0.0]],
[['fly+V+Prs+Sg3', 0.0], ['fly+N+Pl', 0.0]]];
const result = cg.disambiguate(['Time', 'flies'], morphologies);
// [['Time', [CgWord, ...]], ['flies', [CgWord, ...]]]
const word = result[0][1][0];
word.lemma; word.tags; word.weight; word.morphology; word.subReadings;
cg.toMorphologies(result); // back to pyhfst's shape: the input of whatever comes next- Several grammars run one after the other, each taking the previous one's output (
vislcg3 -g a | vislcg3 -g b).new Cg([textOrGrammar, ...], { names, trace })takes grammar texts or parsed grammars. new Cg(..., { trace: true })puts the rule labels inCgWord.trace.cg.runText(cgStream)is the plain CG stream in, stream out.- Compounds (
part#part) become a reading for the last part with the earlier parts assubReadings. A+vNvariant tag is dropped from the analyses unless you pass{ dropVariants: false }as the third argument ofdisambiguate. - An empty word in the list is skipped together with its analyses.
- Getting the analyses (an analyser, a tokeniser) and shipping grammars and FSTs for a language is up to the caller.
Looking into the neighbouring windows
A position with W, < or > (*1W, -1<, 0*W, @1>, C*1W ...) may go on past the edge of the window into the one before
or after it, as in vislcg3: the begin cohort (>>>) of the next window is the cohort after the last one, the last cohort of the
previous window the one before the begin cohort. The engine runs windows the way vislcg3 does: a window is run when two more
have been read (and the begin cohort of a fourth is there), and two windows already run stay behind it
(new Disambiguator(grammar, { numWindows: 2 }), --num-windows); a window is handed on once it falls out of those. A test
only sees what is there: windows ahead are as they were read, windows behind as the rules left them. alwaysSpan: true
(--always-span) lets every scan cross window edges. A dependency may attach across windows; from then on vislcg3 numbers the
output globally (#1001->2003: window, then place in the window) and a parent in a window that has already been written is
printed as no parent, as vislcg3 does. Relations (ID: / R:) reach across windows by cohort id.
Regular expressions in tags ("..."r, /.../r, <...>r) are JavaScript regular expressions in unicode mode, with
\p{Lu} and the like (also in the doubled-backslash form GiellaLT grammars use) understood.
Fidelity to vislcg3
The engine is a line-for-line port of pycg3, which in turn ports vislcg3's runContextualTest, runSingleTest and
doesSetMatchCohort* with their quirks. jscg3 was compared with the real vislcg3 1.7.0 and with pycg3 on GiellaLT
grammars, cohort by cohort, with -t rule traces:
| Grammar and text | Cohorts | Identical to vislcg3 (traces included) | Identical to vislcg3 (traces and tag order ignored) | Identical to pycg3 |
|---|---|---|---|---|
| Erzya disambiguator.cg3 | 127,432 | 127,426 | 127,427 | all (byte-identical) |
| Finnish disambiguator.cg3 | 5,216 | 4,540 | 5,188 | all (byte-identical) |
| North Sámi disambiguator.cg3 | 2,797 | 2,788 | 2,794 | all (byte-identical) |
| Southern Sámi disambiguator.cg3 | 27,252 | 27,240 | 27,249 | all (byte-identical) |
| Southern Sámi dependency | 27,252 | 27,252 | 27,252 | all (byte-identical) |
| North Sámi dependency | 2,797 | 2,797 | 2,797 | all (byte-identical) |
| Southern Sámi, three grammars chained | 613 | 613 | 613 | |
tests/fidelity_cases.json holds 147 small cases that were run through the real vislcg3; npm test replays them.
Speed on the Southern Sámi disambiguator (27,252 cohorts, with -t -p): vislcg3 1.1 s, jscg3 8 s, pycg3 70 s.
# any grammar (or chain of grammars), any CG input: jscg3 against vislcg3, cohort by cohort
node tools/diff_vislcg3.js --grammar G.cg3 --input corpus.cg
node tools/diff_vislcg3.js --grammar A.cg3 --grammar B.cg3 --input raw.cg --other pycg3.outOn the CG-3 project's own regression tests (node tools/run_upstream.js /path/to/cg3/test) 20 of the 69 pass, the same ones as in pycg3.
Not implemented (as in pycg3): templates, WITH, MOVE/SWITCH/SPLITCOHORT/MERGECOHORTS/COPYCOHORT, enclosures/parentheses,
MARK/ATTACH/jumps, regex captures ($1) and varstrings, bag of tags, the
leftmost/rightmost dependency positions (llc, rrp, ...), --unique-tags, -e, --sections ranges, --split-mappings, JSON/binary I/O.
A compiled disambiguator.bin cannot be read; use the .cg3 source.
Tests
npm testLicense
MIT License (see LICENSE).
Cite
Jack Rueter & Olga Erina, pycg3 / jscg3
