cli.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. "use strict";
  2. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  3. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  4. return new (P || (P = Promise))(function (resolve, reject) {
  5. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  6. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  7. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  8. step((generator = generator.apply(thisArg, _arguments || [])).next());
  9. });
  10. };
  11. Object.defineProperty(exports, "__esModule", { value: true });
  12. exports.Cli = void 0;
  13. const dynamic_cstr_js_1 = require("../rule_engine/dynamic_cstr.js");
  14. const MathCompoundStore = require("../rule_engine/math_compound_store.js");
  15. const speech_rule_engine_js_1 = require("../rule_engine/speech_rule_engine.js");
  16. const clearspeak_preferences_js_1 = require("../speech_rules/clearspeak_preferences.js");
  17. const debugger_js_1 = require("./debugger.js");
  18. const engine_js_1 = require("./engine.js");
  19. const EngineConst = require("./engine_const.js");
  20. const ProcessorFactory = require("./processor_factory.js");
  21. const System = require("./system.js");
  22. const system_external_js_1 = require("./system_external.js");
  23. const variables_js_1 = require("./variables.js");
  24. class Cli {
  25. constructor() {
  26. this.setup = {
  27. mode: EngineConst.Mode.SYNC
  28. };
  29. this.processors = [];
  30. this.output = Cli.process.stdout;
  31. this.dp = new system_external_js_1.SystemExternal.xmldom.DOMParser({
  32. onError: (_key, _msg) => {
  33. throw new engine_js_1.SREError('XML DOM error!');
  34. }
  35. });
  36. }
  37. set(arg, value, _def) {
  38. this.setup[arg] = typeof value === 'undefined' ? true : value;
  39. }
  40. processor(processor) {
  41. this.processors.push(processor);
  42. }
  43. loadLocales() {
  44. return __awaiter(this, void 0, void 0, function* () {
  45. for (const loc of variables_js_1.Variables.LOCALES.keys()) {
  46. yield System.setupEngine({ locale: loc });
  47. }
  48. });
  49. }
  50. enumerate() {
  51. return __awaiter(this, arguments, void 0, function* (all = false) {
  52. const promise = System.setupEngine(this.setup);
  53. const order = dynamic_cstr_js_1.DynamicCstr.DEFAULT_ORDER.slice(0, -1);
  54. return (all ? this.loadLocales() : promise).then(() => engine_js_1.EnginePromise.getall().then(() => {
  55. const length = order.map((x) => x.length);
  56. const maxLength = (obj, index) => {
  57. length[index] = Math.max.apply(null, Object.keys(obj)
  58. .map((x) => x.length)
  59. .concat(length[index]));
  60. };
  61. const compStr = (str, length) => str + new Array(length - str.length + 1).join(' ');
  62. let dynamic = speech_rule_engine_js_1.SpeechRuleEngine.getInstance().enumerate();
  63. dynamic = MathCompoundStore.enumerate(dynamic);
  64. const table = [];
  65. maxLength(dynamic, 0);
  66. for (const [ax1, dyna1] of Object.entries(dynamic)) {
  67. let clear1 = true;
  68. maxLength(dyna1, 1);
  69. for (const [ax2, dyna2] of Object.entries(dyna1)) {
  70. let clear2 = true;
  71. maxLength(dyna2, 2);
  72. for (const [ax3, dyna3] of Object.entries(dyna2)) {
  73. const styles = Object.keys(dyna3).sort();
  74. if (ax3 === 'clearspeak') {
  75. let clear3 = true;
  76. const prefs = clearspeak_preferences_js_1.ClearspeakPreferences.getLocalePreferences(dynamic)[ax1];
  77. if (!prefs) {
  78. continue;
  79. }
  80. for (const dyna4 of Object.values(prefs)) {
  81. table.push([
  82. compStr(clear1 ? ax1 : '', length[0]),
  83. compStr(clear2 ? ax2 : '', length[1]),
  84. compStr(clear3 ? ax3 : '', length[2]),
  85. dyna4.join(', ')
  86. ]);
  87. clear1 = false;
  88. clear2 = false;
  89. clear3 = false;
  90. }
  91. }
  92. else {
  93. table.push([
  94. compStr(clear1 ? ax1 : '', length[0]),
  95. compStr(clear2 ? ax2 : '', length[1]),
  96. compStr(ax3, length[2]),
  97. styles.join(', ')
  98. ]);
  99. }
  100. clear1 = false;
  101. clear2 = false;
  102. }
  103. }
  104. }
  105. let i = 0;
  106. const header = order.map((x) => compStr(x, length[i++]));
  107. const markdown = Cli.commander.opts().pprint;
  108. const separator = length.map((x) => new Array(x + 1).join(markdown ? '-' : '='));
  109. if (!markdown) {
  110. separator[i - 1] = separator[i - 1] + '========================';
  111. }
  112. table.unshift(separator);
  113. table.unshift(header);
  114. let output = table.map((x) => x.join(' | '));
  115. if (markdown) {
  116. output = output.map((x) => `| ${x} |`);
  117. output.unshift(`# Options SRE v${System.version}\n`);
  118. }
  119. console.info(output.join('\n'));
  120. }));
  121. });
  122. }
  123. execute(input) {
  124. engine_js_1.EnginePromise.getall().then(() => {
  125. this.runProcessors_((proc, file) => this.output.write(System.processFile(proc, file) + '\n'), input);
  126. });
  127. }
  128. readline() {
  129. Cli.process.stdin.setEncoding('utf8');
  130. const inter = system_external_js_1.SystemExternal.extRequire('readline').createInterface({
  131. input: Cli.process.stdin,
  132. output: this.output
  133. });
  134. let input = '';
  135. inter.on('line', ((expr) => {
  136. input += expr;
  137. if (this.readExpression_(input)) {
  138. inter.close();
  139. }
  140. }).bind(this));
  141. inter.on('close', (() => {
  142. this.runProcessors_((proc, expr) => {
  143. inter.output.write(ProcessorFactory.output(proc, expr) + '\n');
  144. }, input);
  145. System.engineReady().then(() => debugger_js_1.Debugger.getInstance().exit(() => System.exit(0)));
  146. }).bind(this));
  147. }
  148. commandLine() {
  149. return __awaiter(this, void 0, void 0, function* () {
  150. const commander = Cli.commander;
  151. const system = System;
  152. const set = ((key) => {
  153. return (val, def) => this.set(key, val, def);
  154. }).bind(this);
  155. const processor = this.processor.bind(this);
  156. commander
  157. .version(system.version)
  158. .usage('[options] <file ...>')
  159. .option('-i, --input [name]', 'Input file [name]. (Deprecated)')
  160. .option('-o, --output [name]', 'Output file [name]. Defaults to stdout.')
  161. .option('-d, --domain [name]', 'Speech rule set [name]. See --options' + ' for details.', set(dynamic_cstr_js_1.Axis.DOMAIN), dynamic_cstr_js_1.DynamicCstr.DEFAULT_VALUES[dynamic_cstr_js_1.Axis.DOMAIN])
  162. .option('-s, --style [name]', 'Speech style [name]. See --options' + ' for details.', set(dynamic_cstr_js_1.Axis.STYLE), dynamic_cstr_js_1.DynamicCstr.DEFAULT_VALUES[dynamic_cstr_js_1.Axis.STYLE])
  163. .option('-c, --locale [code]', 'Locale [code].', set(dynamic_cstr_js_1.Axis.LOCALE), dynamic_cstr_js_1.DynamicCstr.DEFAULT_VALUES[dynamic_cstr_js_1.Axis.LOCALE])
  164. .option('-b, --modality [name]', 'Modality [name].', set(dynamic_cstr_js_1.Axis.MODALITY), dynamic_cstr_js_1.DynamicCstr.DEFAULT_VALUES[dynamic_cstr_js_1.Axis.MODALITY])
  165. .option('-k, --markup [name]', 'Generate speech output with markup tags.', set('markup'), 'none')
  166. .option('-e, --automark', 'Automatically set marks for external reference.', set('automark'))
  167. .option('-L, --linebreaks', 'Linebreak marking in 2D output.', set('linebreaks'))
  168. .option('-r, --rate [value]', 'Base rate [value] for tagged speech' + ' output.', set('rate'), '100')
  169. .option('-p, --speech', 'Generate speech output (default).', () => processor('speech'))
  170. .option('-a, --audit', 'Generate auditory descriptions (JSON format).', () => processor('description'))
  171. .option('-j, --json', 'Generate JSON of semantic tree.', () => processor('json'))
  172. .option('-x, --xml', 'Generate XML of semantic tree.', () => processor('semantic'))
  173. .option('-m, --mathml', 'Generate enriched MathML.', () => processor('enriched'))
  174. .option('-u, --rebuild', 'Rebuild semantic tree from enriched MathML.', () => processor('rebuild'))
  175. .option('-t, --latex', 'Accepts LaTeX input for certain locale/modality combinations.', () => processor('latex'))
  176. .option('-g, --generate <depth>', 'Include generated speech in enriched' +
  177. ' MathML (with -m option only).', set('speech'), 'none')
  178. .option('-w, --structure', 'Include structure attribute in enriched' +
  179. ' MathML (with -m option only).', set('structure'))
  180. .option('-A, --aria', 'Include aria tree annotations' +
  181. ' MathML (with -m and -w option only).', set('aria'))
  182. .option('-P, --pprint', 'Pretty print output whenever possible.', set('pprint'))
  183. .option('-f, --rules [name]', 'Loads a local rule file [name].', set('rules'))
  184. .option('-C, --subiso [name]', 'Supplementary country code (or similar) for the given locale.', set('subiso'))
  185. .option('-N, --number', 'Translate number to word.', () => processor('number'))
  186. .option('-O, --ordinal', 'Translate number to ordinal.', () => processor('ordinal'), 'ordinal')
  187. .option('-S, --numeric', 'Translate number to numeric ordinal.', () => processor('numericOrdinal'))
  188. .option('-F, --vulgar', 'Translate vulgar fraction to word. Provide vulgar fraction as slash seperated numbers.', () => processor('vulgar'))
  189. .option('-v, --verbose', 'Verbose mode.')
  190. .option('-l, --log [name]', 'Log file [name].')
  191. .option('--opt', 'List engine setup options. Output as markdown with -P option.')
  192. .option('--opt-all', 'List engine setup options for all available locales. Output as markdown with -P option.')
  193. .on('option:opt', () => {
  194. this.enumerate().then(() => System.exit(0));
  195. })
  196. .on('option:opt-all', () => {
  197. this.enumerate(true).then(() => System.exit(0));
  198. })
  199. .parse(Cli.process.argv);
  200. yield System.engineReady().then(() => System.setupEngine(this.setup));
  201. const options = Cli.commander.opts();
  202. if (options.output) {
  203. this.output = system_external_js_1.SystemExternal.fs.createWriteStream(options.output);
  204. }
  205. if (options.verbose) {
  206. yield debugger_js_1.Debugger.getInstance().init(options.log);
  207. }
  208. if (options.input) {
  209. this.execute(options.input);
  210. }
  211. if (Cli.commander.args.length) {
  212. Cli.commander.args.forEach(this.execute.bind(this));
  213. System.engineReady().then(() => debugger_js_1.Debugger.getInstance().exit(() => System.exit(0)));
  214. }
  215. else {
  216. this.readline();
  217. }
  218. });
  219. }
  220. runProcessors_(processor, input) {
  221. try {
  222. if (!this.processors.length) {
  223. this.processors.push('speech');
  224. }
  225. if (input) {
  226. this.processors.forEach((proc) => processor(proc, input));
  227. }
  228. }
  229. catch (err) {
  230. console.error(err.name + ': ' + err.message);
  231. debugger_js_1.Debugger.getInstance().exit(() => Cli.process.exit(1));
  232. }
  233. }
  234. readExpression_(input) {
  235. try {
  236. const testInput = input.replace(/(&|#|;)/g, '');
  237. this.dp.parseFromString(testInput, 'text/xml');
  238. }
  239. catch (_err) {
  240. return false;
  241. }
  242. return true;
  243. }
  244. }
  245. exports.Cli = Cli;
  246. Cli.process = system_external_js_1.SystemExternal.extRequire('process');
  247. Cli.commander = system_external_js_1.SystemExternal.documentSupported
  248. ? null
  249. : system_external_js_1.SystemExternal.extRequire('commander').program;