-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathconvert.js
More file actions
653 lines (551 loc) · 20 KB
/
convert.js
File metadata and controls
653 lines (551 loc) · 20 KB
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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
const pkg = require("../package.json");
const fs = require("fs-extra");
const fetch = require("node-fetch");
const FormData = require("form-data");
const Window = require("window");
const { JSDOM } = require("jsdom");
const config = require("./config");
const { MathpixMarkdownModel } = require("mathpix-markdown-it");
function mmdToHTMLString(mmd) {
let destinationContentString;
const window = new Window();
global.DOMParser = new JSDOM().window.DOMParser;
global.window = window;
global.document = window.document;
destinationContentString = MathpixMarkdownModel.markdownToHTML(mmd, {
htmlTags: true,
htmlSanitize: false,
htmlWrapper: {
title: "mpx",
includeStyles: true,
includeFonts: true,
},
});
return destinationContentString;
}
function MarkdownToHTML(source, destination, sourceText) {
let sourceContentString = source;
if (!sourceText) {
try {
if (!fs.existsSync(source)) {
console.log(`Could not find source file at path: ${source}`);
return process.exit(1);
}
sourceContentString = fs.readFileSync(source, "utf8");
} catch (err) {
console.log(`Could not read source path: ${source}`);
return process.exit(1);
}
}
let destinationContentString = mmdToHTMLString(sourceContentString);
if (destination) {
try {
fs.writeFileSync(destination, destinationContentString);
} catch (err) {
console.log(`Could not write to destination path: ${destination}`);
return process.exit(1);
}
return;
}
return destinationContentString;
}
async function ConvertWithExportAPI(expectedContentType, url, source, destination, sourceText) {
await config.checkEnvironmentVariables();
let sourceContentString = source;
if (!sourceText) {
try {
if (!fs.existsSync(source)) {
console.log(`Could not find source file at path: ${source}`);
return process.exit(1);
}
sourceContentString = fs.readFileSync(source, "utf8");
} catch (err) {
console.log(`Could not read source path: ${source}`);
return process.exit(1);
}
}
let headers = {};
if (process.env["MATHPIX_OCR_API_KEY"]) {
headers = {
app_key: process.env["MATHPIX_OCR_API_KEY"],
};
} else {
headers = {
authorization: "Bearer " + process.env["MATHPIX_SNIP_AUTH_TOKEN"],
};
}
let options = {
method: "POST",
headers: headers,
body: JSON.stringify({
mmd: sourceContentString,
fileName: destination.split(".")[0],
}),
};
const res = await fetch(url, options);
if (res.status !== 200 || res.headers.get("content-type") !== expectedContentType) {
if (res.headers.get("content-type") === "application/json") {
const jsonResponseBody = await res.json();
if (
jsonResponseBody["errors"] &&
jsonResponseBody["errors"].length &&
jsonResponseBody["errors"][0]["id"] === "invalid_app_key_header"
) {
console.log(`Invalid app key set in "MATHPIX_OCR_API_KEY" environment variable.`);
return process.exit(1);
} else {
console.log(`Unexpected error, please submit a bug report at: ${pkg.repository.issues}`);
return process.exit(1);
}
} else {
const textResponseBody = await res.text();
console.log(`Unexpected error, please submit a bug report at: ${pkg.repository.issues}`);
return process.exit(1);
}
}
const bufferResponseBody = await res.buffer();
try {
fs.writeFileSync(destination, bufferResponseBody);
} catch (err) {
console.log(`Could not write to destination path: ${destination}`);
return process.exit(1);
}
}
async function MarkdownToDocx(source, destination, sourceText) {
const cType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
const url = "https://api.mathpix.com/v1/export/docx";
await ConvertWithExportAPI(cType, url, source, destination, sourceText);
}
async function MarkdownToTex(source, destination, sourceText) {
const cType = "application/zip";
const url = "https://api.mathpix.com/v1/export/latex";
await ConvertWithExportAPI(cType, url, source, `${destination}.zip`, sourceText);
}
async function MarkdownToHTMLPDF(source, destination, sourceText) {
const cType = "application/pdf";
const url = "https://api.mathpix.com/v1/export/pdf/html";
await ConvertWithExportAPI(cType, url, source, destination, sourceText);
}
async function MarkdownToLatexPDF(source, destination, sourceText) {
const cType = "application/pdf";
const url = "https://api.mathpix.com/v1/export/pdf/latex";
await ConvertWithExportAPI(cType, url, source, destination, sourceText);
}
async function MarkdownToMarkdown(source, destination) {
try {
await fs.copy(source, destination);
} catch (err) {
console.log(`Could not write to destination path: ${destination}`);
return process.exit(1);
}
}
async function ConvertPDF(outputType, source, destination) {
await config.checkEnvironmentVariables();
if (process.env["MATHPIX_OCR_API_KEY"]) {
await ConvertPDFWithOCRAPI(process.env["MATHPIX_OCR_API_KEY"], outputType, source, destination);
} else {
await ConvertPDFWithSnipAPI(
process.env["MATHPIX_SNIP_AUTH_TOKEN"],
outputType,
source,
destination
);
}
}
async function ConvertPDFWithOCRAPI(apiKey, outputType, source, destination) {
process.stdout.write(`Converting pdf to ${outputType}\r`);
const formData = new FormData();
formData.append("file", fs.createReadStream(source));
let url = "https://api.mathpix.com/v3/pdf-file";
const formHeaders = formData.getHeaders();
formHeaders["app_key"] = apiKey;
let options = {
method: "POST",
headers: formHeaders,
};
options.body = formData;
let res = await fetch(url, options);
if (res.status !== 200) {
if (res.headers.get("content-type").startsWith("application/json")) {
const jsonResponseBody = await res.json();
if (
jsonResponseBody["errors"] &&
jsonResponseBody["errors"].length &&
jsonResponseBody["errors"][0]["id"] === "http_unauthorized"
) {
console.log(`Invalid app key set in "MATHPIX_OCR_API_KEY" environment variable.`);
return process.exit(1);
} else if (
jsonResponseBody["errors"] &&
jsonResponseBody["errors"].length &&
jsonResponseBody["errors"][0]["id"] === "pdf_page_limit_exceeded"
) {
console.log("This pdf would put you over your OCR API's PDF page limit.");
console.log("Please contact support@mathpix.com to request a higher limit.");
return process.exit(1);
} else {
const responseBody = JSON.stringify(jsonResponseBody);
throw new Error(`OCR API POST PDF Response ${res.status} with json body:\n${responseBody}`);
}
} else {
throw new Error(`OCR API POST PDF Response ${res.status} ${res.statusText}`);
}
}
if (!res.headers.get("content-type").startsWith("application/json")) {
throw new Error(
`OCR API response returned content-type header: ${res.headers.get("content-type")}.`
);
}
let responseJSON = await res.json();
if (!("pdf_id" in responseJSON)) {
throw new Error("Missing pdf_id in OCR API response.");
}
await new Promise((resolve) => {
const pollResultInterval = setInterval(async () => {
const url = `https://api.mathpix.com/v3/pdf/${responseJSON["pdf_id"]}`;
const options = { method: "GET", headers: { app_key: apiKey } };
const res = await fetch(url, options);
if (res.status !== 200) {
console.log(`Unexpected error, please submit a bug report at: ${pkg.repository.issues}`);
return process.exit(1);
}
const statusJSON = await res.json();
if (statusJSON["status"] === "completed") {
resolve();
clearInterval(pollResultInterval);
}
if (statusJSON["status"] === "error") {
console.log(`Error: ${statusJSON["error"]}`);
return process.exit(1);
}
process.stdout.clearLine();
process.stdout.cursorTo(0);
process.stdout.write(
`Converting pdf to ${outputType} ${Math.round(statusJSON["percent_done"])}% complete... \r`
);
}, 500);
});
let originalOutputType = outputType;
if (outputType === "html") {
outputType = "mmd";
}
const outputURL = `https://api.mathpix.com/v3/pdf/${responseJSON["pdf_id"]}.${outputType}`;
const outputRes = await fetch(outputURL, { method: "GET", headers: { app_key: apiKey } });
if (outputRes.status !== 200) {
console.log(`Unexpected error, please submit a bug report at: ${pkg.repository.issues}`);
return process.exit(1);
}
if (originalOutputType === "html") {
const mmd = await outputRes.text();
try {
fs.writeFileSync(destination, mmdToHTMLString(mmd));
} catch (err) {
console.log(`Could not write to destination path: ${destination}`);
return process.exit(1);
}
return;
}
const bufferResponseBody = await outputRes.buffer();
try {
fs.writeFileSync(destination, bufferResponseBody);
} catch (err) {
console.log(`Could not write to destination path: ${destination}`);
return process.exit(1);
}
}
async function ConvertPDFWithSnipAPI(authToken, outputType, source, destination) {
process.stdout.write(`Converting pdf to ${outputType}\r`);
const formData = new FormData();
formData.append("file", fs.createReadStream(source));
let url = "https://api.mathpix.com/v1/pdfs";
const formHeaders = formData.getHeaders();
formHeaders["authorization"] = "Bearer " + authToken;
let options = {
method: "POST",
headers: formHeaders,
};
options.body = formData;
let res = await fetch(url, options);
if (res.status !== 200) {
if (res.headers.get("content-type").startsWith("application/json")) {
const jsonResponseBody = await res.json();
if (
jsonResponseBody["errors"] &&
jsonResponseBody["errors"].length &&
jsonResponseBody["errors"][0]["id"] === "pdf_page_max_limit"
) {
console.log("This pdf would put you over your Snip plan's PDF page limit.");
console.log("Please upgrade your plan or enable extra usage to continue at");
console.log("https://accounts.mathpix.com");
return process.exit(1);
} else {
const responseBody = JSON.stringify(jsonResponseBody);
throw new Error(`Snip Server POST PDF Response ${res.status} with json body:\n${responseBody}`);
}
} else {
throw new Error(`Snip Server POST PDF Response ${res.status} ${res.statusText}`);
}
}
if (!res.headers.get("content-type").startsWith("application/json")) {
throw new Error(
`Snip Server response returned content-type header: ${res.headers.get("content-type")}.`
);
}
let responseJSON = await res.json();
if (!("pdf" in responseJSON) && !("id" in responseJSON["pdf"])) {
throw new Error("Missing pdf id in Snip API response.");
}
let pdfID = responseJSON["pdf"]["id"];
let headers = {
authorization: "Bearer " + authToken,
};
await new Promise((resolve) => {
const pollResultInterval = setInterval(async () => {
const url = `https://api.mathpix.com/v1/pdfs/${pdfID}`;
const options = { method: "GET", headers: headers };
const res = await fetch(url, options);
if (res.status !== 200) {
console.log(`Unexpected error, please submit a bug report at: ${pkg.repository.issues}`);
return process.exit(1);
}
const statusJSON = await res.json();
if (statusJSON["pdf"]["status"] === "completed") {
resolve();
clearInterval(pollResultInterval);
}
if (statusJSON["pdf"]["status"] === "error") {
console.log(`Error: ${statusJSON["error"]}`);
return process.exit(1);
}
let completedPages = statusJSON["pdf"]["completed_pages"];
let totalPages = statusJSON["pdf"]["total_pages"];
let percentComplete = completedPages / totalPages;
process.stdout.clearLine();
process.stdout.cursorTo(0);
process.stdout.write(
`Converting pdf to ${outputType} ${Math.round(percentComplete)}% complete... \r`
);
}, 500);
});
process.stdout.clearLine();
process.stdout.cursorTo(0);
let originalOutputType = outputType;
if (outputType === "html") {
outputType = "mmd";
}
const outputURL = `https://api.mathpix.com/v1/pdfs/${pdfID}/${outputType}`;
const outputRes = await fetch(outputURL, { method: "GET", headers: headers });
if (outputRes.status !== 200) {
console.log(`Unexpected error, please submit a bug report at: ${pkg.repository.issues}`);
return process.exit(1);
}
if (originalOutputType === "html") {
const mmd = await outputRes.text();
try {
fs.writeFileSync(destination, mmdToHTMLString(mmd));
} catch (err) {
console.log(`Could not write to destination path: ${destination}`);
return process.exit(1);
}
return;
}
const bufferResponseBody = await outputRes.buffer();
try {
fs.writeFileSync(destination, bufferResponseBody);
} catch (err) {
console.log(`Could not write to destination path: ${destination}`);
return process.exit(1);
}
}
async function PDFToMMD(source, destination) {
await ConvertPDF("mmd", source, destination);
}
async function PDFToVanillaMarkdown(source, destination) {
await ConvertPDF("md", source, destination);
}
async function PDFToDOCX(source, destination) {
await ConvertPDF("docx", source, destination);
}
async function PDFToTEX(source, destination) {
await ConvertPDF("tex", source, `${destination}.zip`);
}
async function PDFToHTML(source, destination) {
await ConvertPDF("html", source, destination);
}
async function ConvertImageWithSnipAPI(authToken, outputType, source, destination, htmlPDF) {
process.stdout.write(`Converting image to ${outputType}\r`);
const formData = new FormData();
formData.append("file", fs.createReadStream(source));
let url = "https://api.mathpix.com/v1/snips-multipart";
const formHeaders = formData.getHeaders();
formHeaders["authorization"] = "Bearer " + authToken;
let options = {
method: "POST",
headers: formHeaders,
};
options.body = formData;
let res = await fetch(url, options);
if (res.status !== 201) {
process.stdout.clearLine();
process.stdout.cursorTo(0);
if (res.headers.get("content-type").startsWith("application/json")) {
const jsonResponseBody = await res.json();
if (
jsonResponseBody["errors"] &&
jsonResponseBody["errors"].length &&
jsonResponseBody["errors"][0]["id"] === "snip_max_limit"
) {
console.log("This image would put you over your Snip plan's snip limit.");
console.log("Please upgrade your plan or enable extra usage to continue at");
console.log("https://accounts.mathpix.com");
return process.exit(1);
} else {
const responseBody = JSON.stringify(jsonResponseBody);
throw new Error(`Snip server response ${res.status} with json body:\n${responseBody}`);
}
} else {
throw new Error(`Snip server response ${res.status} ${res.statusText}`);
}
}
if (!res.headers.get("content-type").startsWith("application/json")) {
throw new Error(
`Snip server response returned content-type header: ${res.headers.get("content-type")}.`
);
}
process.stdout.clearLine();
process.stdout.cursorTo(0);
let responseJSON = await res.json();
if (destination.endsWith("docx")) {
await MarkdownToDocx(responseJSON["text_display"], destination, true);
} else if (destination.endsWith("tex")) {
await MarkdownToTex(responseJSON["text_display"], destination, true);
} else if (destination.endsWith("pdf") && htmlPDF) {
await MarkdownToHTMLPDF(responseJSON["text_display"], destination, true);
} else if (destination.endsWith("pdf")) {
await MarkdownToLatexPDF(responseJSON["text_display"], destination, true);
} else if (destination.endsWith("html")) {
await MarkdownToHTML(responseJSON["text_display"], destination, true);
} else {
try {
fs.writeFileSync(destination, responseJSON["text_display"]);
} catch (err) {
console.log(`Could not write to destination path: ${destination}`);
return process.exit(1);
}
}
}
async function ConvertImageWithOCRAPI(apiKey, outputType, source, destination, htmlPDF) {
process.stdout.write(`Converting image to ${outputType}\r`);
const formData = new FormData();
formData.append("file", fs.createReadStream(source));
let url = "https://api.mathpix.com/v3/text";
const formHeaders = formData.getHeaders();
formHeaders["app_key"] = apiKey;
let options = {
method: "POST",
headers: formHeaders,
};
options.body = formData;
let res = await fetch(url, options);
if (res.status !== 200) {
process.stdout.clearLine();
process.stdout.cursorTo(0);
if (res.headers.get("content-type").startsWith("application/json")) {
const jsonResponseBody = await res.json();
if (
jsonResponseBody["errors"] &&
jsonResponseBody["errors"].length &&
jsonResponseBody["errors"][0]["id"] === "http_max_requests"
) {
console.log("This image would put you over your request rate limit.");
console.log("Please contact support@mathpix.com to increase your limit.");
return process.exit(1);
} else {
const responseBody = JSON.stringify(jsonResponseBody);
throw new Error(`OCR API response ${res.status} with json body:\n${responseBody}`);
}
} else {
throw new Error(`OCR API response ${res.status} ${res.statusText}`);
}
}
if (!res.headers.get("content-type").startsWith("application/json")) {
throw new Error(
`OCR API response returned content-type header: ${res.headers.get("content-type")}.`
);
}
process.stdout.clearLine();
process.stdout.cursorTo(0);
let responseJSON = await res.json();
if (destination.endsWith("docx")) {
await MarkdownToDocx(responseJSON["latex_styled"], destination, true);
} else if (destination.endsWith("tex")) {
await MarkdownToTex(responseJSON["latex_styled"], destination, true);
} else if (destination.endsWith("pdf") && htmlPDF) {
await MarkdownToHTMLPDF(responseJSON["latex_styled"], destination, true);
} else if (destination.endsWith("pdf")) {
await MarkdownToLatexPDF(responseJSON["latex_styled"], destination, true);
} else if (destination.endsWith("html")) {
await MarkdownToHTML(responseJSON["latex_styled"], destination, true);
} else {
try {
fs.writeFileSync(destination, responseJSON["latex_styled"]);
} catch (err) {
console.log(`Could not write to destination path: ${destination}`);
return process.exit(1);
}
}
}
async function ConvertImage(outputType, source, destination, htmlPDF) {
await config.checkEnvironmentVariables();
if (process.env["MATHPIX_OCR_API_KEY"]) {
console.log("Convert with ocr api", source, destination, outputType);
await ConvertImageWithOCRAPI(process.env["MATHPIX_OCR_API_KEY"], outputType, source, destination);
} else {
console.log("Convert with snip api", source, destination, outputType);
await ConvertImageWithSnipAPI(
process.env["MATHPIX_SNIP_AUTH_TOKEN"],
outputType,
source,
destination,
htmlPDF
);
}
}
async function ImageToMMD(source, destination) {
await ConvertImage("mmd", source, destination);
}
async function ImageToDOCX(source, destination) {
await ConvertImage("docx", source, destination);
}
async function ImageToTEX(source, destination) {
await ConvertImage("tex", source, `${destination}.zip`);
}
async function ImageToHTML(source, destination) {
await ConvertImage("html", source, destination);
}
async function ImageToLatexPDF(source, destination) {
await ConvertImage("pdf", source, destination);
}
async function ImageToHTMLPDF(source, destination) {
await ConvertImage("pdf", source, destination, true);
}
module.exports = {
MarkdownToHTML,
MarkdownToDocx,
MarkdownToTex,
MarkdownToHTMLPDF,
MarkdownToLatexPDF,
MarkdownToMarkdown,
PDFToMMD,
PDFToVanillaMarkdown,
PDFToDOCX,
PDFToTEX,
PDFToHTML,
ImageToMMD,
ImageToDOCX,
ImageToTEX,
ImageToHTML,
ImageToLatexPDF,
ImageToHTMLPDF,
ConvertImage,
};