-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.js
261 lines (231 loc) · 8.97 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
require("dotenv").config();
const Airbrake = require('@airbrake/node');
new Airbrake.Notifier({
projectId: 257349,
projectKey: '9331de259df466d79c1d0e786be78051',
environment: process.env.NODE_ENV || 'development'
});
(() => {
'use strict';
const Pack = require("./package.json");
const X2JS = require("x2js");
const ejs = require('ejs');
const Resolve = require("path").resolve;
const { XMLParser, XMLBuilder } = require("fast-xml-parser");
const MathML2Latex = require('mathml-to-latex');
const MathML2Ascii = require('mathml-to-asciimath');
const { PORT, HOST } = require("./configurations/appConfig");
const { GenerateMath } = require("./conversions/text");
// const { GenerateSvg } = require("./conversions/svg");
/**
* Transforms MathML to AsciiMath
* @param {{mathml: string;success: boolean;language: string;words: any[];ascii: string;display: string;imagepath: string;alix: number;}} mathObj Math Object
* @returns {String} AsciiMath
*/
const GenerateAsciiMath = (mathml, ascii) => {
try {
return MathML2Ascii(mathml);
}
catch(err) {
return ascii;
}
}
/**
* Transforms MathML to Accessible HTML with ALIX
* @param {{language: String;disp: String;txt: String;altimg: String;alttext: String;svg: String;alix: Number;alixThresholdNoImage: Number;}} opts options
* @returns {Promise<String>} Accessible HTML with ALIX
*/
const GenerateHtmlFromTemplate = async (opts) => {
var filename = Resolve('./templates/accessibleHtmlWithAlix.ejs');
// Validate opts
if (opts === undefined) {
opts = {};
}
if (opts.language === undefined) {
opts.language = "no";
}
if (opts.disp === undefined) {
opts.disp = "block";
}
if (opts.txt === undefined) {
opts.txt = "";
}
if (opts.altimg === undefined) {
opts.altimg = "";
}
if (opts.alttext === undefined) {
opts.alttext = "";
}
if (opts.svg === undefined) {
opts.svg = "";
}
if (opts.alix === undefined) {
opts.alix = 0;
}
if (opts.alixThresholdNoImage === undefined) {
opts.alixThresholdNoImage = 25;
}
// Render template
return ejs.renderFile(filename, opts).then(res => {
return res;
});
}
/**
* Translates the text array from English to a specified language
* @param {Array<String>} inputText The English text as array
* @param {String} lang The language to translate to
* @returns {String} The translated text
*/
const TranslateText = (inputText, lang) => {
var text = inputText.join(" ");
if (lang !== null) {
try {
var newText = text;
const postProcess = require(`./translations/${lang}.json`);
postProcess.forEach(p => {
var regexString = `\\b(${p.search})\\b`;
var re = new RegExp(regexString, "g");
newText = newText.replace(re, p.replace);
});
// Fixes punctuation errors
const punctuations = require(`./translations/all.json`);
punctuations.forEach(s => {
newText = newText.split(s.search).join(s.replace);
});
return newText;
}
catch (ex) {
// File not found, just return the text
}
}
return text;
};
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
// create application/json parser
const jsonParser = bodyParser.json()
app.set('view engine', 'ejs');
app.set("view options", { layout: true });
// On all requests, log the it
app.use((request, response, next) => {
console.info(`${new Date().toISOString()}\tA request from ${request.ip} (${request.method.toUpperCase()} ${request.url}) ended with ${response.statusCode}`);
next();
});
// Define routes
app.get('/health', jsonParser, (req, res) => {
res.send({
name: Pack.name,
version: Pack.version,
timestamp: new Date().toISOString()
});
});
app.get('/', jsonParser, (req, res) => {
res.status(400).send({
success: false,
name: Pack.name,
version: Pack.version,
message: "Use POST instead of GET with optional query variables: 'noImage' (ALIX threshold number) and 'noEquationText' (ALIX threshold number), and payload: { \"contentType\": \"math|chemistry|physics|other\", \"content\": \"...\" }"
});
});
// POST / payload: { "contentType": "math|chemistry|physics|other", "content": "..." }
app.post('/', jsonParser, async (req, res) => {
const { contentType, content } = req.body;
const { noImage, noEquationText } = req.query;
const noImageInt = parseInt(noImage) || 25;
const noEquationTextInt = parseInt(noEquationText) || 12;
const alixThresholds = {
"noImage": noImageInt,
"noEquationText": noEquationTextInt
};
if (!contentType || !content) {
res.status(400).send("Missing contentType or content");
return;
}
let result = null;
switch (contentType) {
case "math":
result = GenerateMath(content, alixThresholds);
break;
case "chemistry":
res.status(501).json({ success: false, error: "non-mathematical formula" });
break;
case "physics":
res.status(501).json({ success: false, error: "non-mathematical formula" });
break;
case "other":
res.status(501).json({ success: false, error: "non-mathematical formula" });
break;
default:
res.status(400).json({ success: false, error: "unknown content type" });
return;
}
if (result === null) {
res.status(400).send("Invalid content");
return;
}
if (result.success === false) {
res.status(500).send(result.message);
return;
}
// IF we got here, all is well
const parser = new XMLParser();
const builder = new XMLBuilder();
var x2js = new X2JS();
var xmlDom = x2js.xml2dom(content);
var XMLObject = parser.parse(content, {
ignoreAttributes: false,
ignoreNameSpace: false,
});
var XMLContent = builder.build(XMLObject);
// Extract language from m:math attribute
const languageStr = xmlDom.documentElement.getAttribute("xml:lang") || xmlDom.documentElement.getAttribute("lang") || "en";
// Extract display from m:math attribute
const displayStr = xmlDom.documentElement.getAttribute("display") || "block";
// Extract altimg from m:math attribute
const altimgStr = xmlDom.documentElement.getAttribute("altimg") || "";
// Extract alttext from m:math attribute
const alttextStr = xmlDom.documentElement.getAttribute("alttext") || "";
const latexStr = MathML2Latex.convert(XMLContent.replace(/<m:/g, "<").replace(/<\/m:/g, "</"));
const asciiStr = GenerateAsciiMath(XMLContent, alttextStr);
const translatedStr = TranslateText(result.words, languageStr);
var returnObj = {
"success": result.success,
"input": {
"mathml": content,
},
"output": {
"text": {
"words": result.words,
"translated": translatedStr,
"latex": latexStr,
"ascii": asciiStr,
"html": await GenerateHtmlFromTemplate({
language: languageStr,
disp: displayStr,
txt: translatedStr,
altimg: altimgStr,
alttext: asciiStr,
svg: null,
alix: result.alix,
alixThresholdNoImage: alixThresholds.noImage
}),
},
"image": {
"path": altimgStr
},
"attributes": {
"language": languageStr,
"alix": result.alix,
"alixThresholdNoImage": alixThresholds.noImage,
"alixThresholdNoEquationText": alixThresholds.noEquationText,
}
},
};
res.json(returnObj);
});
// Start the server
app.listen(PORT, () => {
console.info(`${new Date().toISOString()}\t${Pack.name} running on ${HOST}:${PORT}`);
});
})();