generateImages_browserless.mjs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  1. import Blob from "cross-blob";
  2. import FS from "fs";
  3. import jsdom from "jsdom";
  4. //import headless_gl from "gl"; // this is now imported dynamically in a try catch, in case gl install fails, see #1160
  5. import OSMD from "../../build/opensheetmusicdisplay.min.js"; // window needs to be available before we can require OSMD
  6. /*
  7. Render each OSMD sample, grab the generated images, and
  8. dump them into a local directory as PNG or SVG files.
  9. inspired by Vexflow's generate_png_images and vexflow-tests.js
  10. This can be used to generate PNGs or SVGs from OSMD without a browser.
  11. It's also used with the visual regression test system (using PNGs) in
  12. `tools/visual_regression.sh`
  13. (see package.json, used with npm run generate:blessed and generate:current, then test:visual).
  14. Note: this script needs to "fake" quite a few browser elements, like window, document,
  15. and a Canvas HTMLElement (for PNG) or the DOM (for SVG) ,
  16. which otherwise are missing in pure nodejs, causing errors in OSMD.
  17. For PNG it needs the canvas package installed.
  18. There are also some hacks needed to set the container size (offsetWidth) correctly.
  19. Otherwise you'd need to run a headless browser, which is way slower,
  20. see the semi-obsolete generateDiffImagesPuppeteerLocalhost.js
  21. */
  22. function sleep (ms) {
  23. return new Promise((resolve) => {
  24. setTimeout(resolve, ms);
  25. });
  26. }
  27. // global variables
  28. // (without these being global, we'd have to pass many of these values to the generateSampleImage function)
  29. // eslint-disable-next-line prefer-const
  30. let [osmdBuildDir, sampleDir, imageDir, imageFormat, pageWidth, pageHeight, filterRegex, mode, debugSleepTimeString, skyBottomLinePreference] = process.argv.slice(2, 12);
  31. imageFormat = imageFormat?.toLowerCase();
  32. if (!osmdBuildDir || !sampleDir || !imageDir || (imageFormat !== "png" && imageFormat !== "svg")) {
  33. console.log("usage: " +
  34. // eslint-disable-next-line max-len
  35. "node test/Util/generateImages_browserless.mjs osmdBuildDir sampleDirectory imageDirectory svg|png [width|0] [height|0] [filterRegex|all|allSmall] [--debug|--osmdtesting] [debugSleepTime]");
  36. console.log(" (use pageWidth and pageHeight 0 to not divide the rendering into pages (endless page))");
  37. console.log(' (use "all" to skip filterRegex parameter. "allSmall" with --osmdtesting skips two huge OSMD samples that take forever to render)');
  38. console.log("example: node test/Util/generateImages_browserless.mjs ../../build ./test/data/ ./export png");
  39. console.log("Error: need osmdBuildDir, sampleDir, imageDir and svg|png arguments. Exiting.");
  40. process.exit(1);
  41. }
  42. let pageFormat;
  43. if (!mode) {
  44. mode = "";
  45. }
  46. // let OSMD; // can only be required once window was simulated
  47. // eslint-disable-next-line @typescript-eslint/no-var-requires
  48. async function init () {
  49. debug("init");
  50. const osmdTestingMode = mode.includes("osmdtesting"); // can also be --debugosmdtesting
  51. const osmdTestingSingleMode = mode.includes("osmdtestingsingle");
  52. const DEBUG = mode.startsWith("--debug");
  53. // const debugSleepTime = Number.parseInt(process.env.GENERATE_DEBUG_SLEEP_TIME) || 0; // 5000 works for me [sschmidTU]
  54. if (DEBUG) {
  55. // debug(' (note that --debug slows down the script by about 0.3s per file, through logging)')
  56. const debugSleepTimeMs = Number.parseInt(debugSleepTimeString, 10);
  57. if (debugSleepTimeMs > 0) {
  58. debug("debug sleep time: " + debugSleepTimeString);
  59. await sleep(Number.parseInt(debugSleepTimeMs, 10));
  60. // [VSCode] apparently this is necessary for the debugger to attach itself in time before the program closes.
  61. // sometimes this is not enough, so you may have to try multiple times or increase the sleep timer. Unfortunately debugging nodejs isn't easy.
  62. }
  63. }
  64. debug("sampleDir: " + sampleDir, DEBUG);
  65. debug("imageDir: " + imageDir, DEBUG);
  66. debug("imageFormat: " + imageFormat, DEBUG);
  67. pageFormat = "Endless";
  68. pageWidth = Number.parseInt(pageWidth, 10);
  69. pageHeight = Number.parseInt(pageHeight, 10);
  70. const endlessPage = !(pageHeight > 0 && pageWidth > 0);
  71. if (!endlessPage) {
  72. pageFormat = `${pageWidth}x${pageHeight}`;
  73. }
  74. // ---- hacks to fake Browser elements OSMD and Vexflow need, like window, document, and a canvas HTMLElement ----
  75. // eslint-disable-next-line @typescript-eslint/no-var-requires
  76. const dom = new jsdom.JSDOM("<!DOCTYPE html></html>");
  77. // eslint-disable-next-line no-global-assign
  78. // window = dom.window;
  79. // eslint-disable-next-line no-global-assign
  80. // document = dom.window.document;
  81. // eslint-disable-next-line no-global-assign
  82. global.window = dom.window;
  83. // eslint-disable-next-line no-global-assign
  84. global.document = window.document;
  85. //window.console = console; // probably does nothing
  86. global.HTMLElement = window.HTMLElement;
  87. global.HTMLAnchorElement = window.HTMLAnchorElement;
  88. global.XMLHttpRequest = window.XMLHttpRequest;
  89. global.DOMParser = window.DOMParser;
  90. global.Node = window.Node;
  91. if (imageFormat === "png") {
  92. global.Canvas = window.Canvas;
  93. }
  94. // For WebGLSkyBottomLineCalculatorBackend: Try to import gl dynamically
  95. // this is so that the script doesn't fail if gl could not be installed,
  96. // which can happen in some linux setups where gcc-11 is installed, see #1160
  97. try {
  98. const { default: headless_gl } = await import("gl");
  99. const oldCreateElement = document.createElement.bind(document);
  100. document.createElement = function (tagName, options) {
  101. if (tagName.toLowerCase() === "canvas") {
  102. const canvas = oldCreateElement(tagName, options);
  103. const oldGetContext = canvas.getContext.bind(canvas);
  104. canvas.getContext = function (contextType, contextAttributes) {
  105. if (contextType.toLowerCase() === "webgl" || contextType.toLowerCase() === "experimental-webgl") {
  106. const gl = headless_gl(canvas.width, canvas.height, contextAttributes);
  107. gl.canvas = canvas;
  108. return gl;
  109. } else {
  110. return oldGetContext(contextType, contextAttributes);
  111. }
  112. };
  113. return canvas;
  114. } else {
  115. return oldCreateElement(tagName, options);
  116. }
  117. };
  118. } catch {
  119. if (skyBottomLinePreference === "--webgl") {
  120. debug("WebGL image generation was requested but gl is not installed; using non-WebGL generation.");
  121. }
  122. }
  123. // fix Blob not found (to support external modules like is-blob)
  124. global.Blob = Blob;
  125. const div = document.createElement("div");
  126. div.id = "browserlessDiv";
  127. document.body.appendChild(div);
  128. // const canvas = document.createElement('canvas')
  129. // div.canvas = document.createElement('canvas')
  130. const zoom = 1.0;
  131. // width of the div / PNG generated
  132. let width = pageWidth * zoom;
  133. // TODO sometimes the width is way too small for the score, may need to adjust zoom.
  134. if (endlessPage) {
  135. width = 1440;
  136. }
  137. let height = pageHeight;
  138. if (endlessPage) {
  139. height = 32767;
  140. }
  141. div.width = width;
  142. div.height = height;
  143. // div.offsetWidth = width; // doesn't work, offsetWidth is always 0 from this. see below
  144. // div.clientWidth = width;
  145. // div.clientHeight = height;
  146. // div.scrollHeight = height;
  147. // div.scrollWidth = width;
  148. div.setAttribute("width", width);
  149. div.setAttribute("height", height);
  150. div.setAttribute("offsetWidth", width);
  151. // debug('div.offsetWidth: ' + div.offsetWidth, DEBUG) // 0 here, set correctly later
  152. // debug('div.height: ' + div.height, DEBUG)
  153. // hack: set offsetWidth reliably
  154. Object.defineProperties(window.HTMLElement.prototype, {
  155. offsetLeft: {
  156. get: function () { return parseFloat(window.getComputedStyle(this).marginTop) || 0; }
  157. },
  158. offsetTop: {
  159. get: function () { return parseFloat(window.getComputedStyle(this).marginTop) || 0; }
  160. },
  161. offsetHeight: {
  162. get: function () { return height; }
  163. },
  164. offsetWidth: {
  165. get: function () { return width; }
  166. }
  167. });
  168. debug("div.offsetWidth: " + div.offsetWidth, DEBUG);
  169. debug("div.height: " + div.height, DEBUG);
  170. // ---- end browser hacks (hopefully) ----
  171. // load globally
  172. // Create the image directory if it doesn't exist.
  173. FS.mkdirSync(imageDir, { recursive: true });
  174. const sampleDirFilenames = FS.readdirSync(sampleDir);
  175. let samplesToProcess = []; // samples we want to process/generate pngs of, excluding the filtered out files/filenames
  176. for (const sampleFilename of sampleDirFilenames) {
  177. if (osmdTestingMode && filterRegex === "allSmall") {
  178. if (sampleFilename.match("^(Actor)|(Gounod)")) { // TODO maybe filter by file size instead
  179. debug("filtering big file: " + sampleFilename, DEBUG);
  180. continue;
  181. }
  182. }
  183. // eslint-disable-next-line no-useless-escape
  184. if (sampleFilename.match("^.*(\.xml)|(\.musicxml)|(\.mxl)$")) {
  185. // debug('found musicxml/mxl: ' + sampleFilename)
  186. samplesToProcess.push(sampleFilename);
  187. } else {
  188. debug("discarded file/directory: " + sampleFilename, DEBUG);
  189. }
  190. }
  191. // filter samples to process by regex if given
  192. if (filterRegex && filterRegex !== "" && filterRegex !== "all" && !(osmdTestingMode && filterRegex === "allSmall")) {
  193. debug("filtering samples for regex: " + filterRegex, DEBUG);
  194. samplesToProcess = samplesToProcess.filter((filename) => filename.match(filterRegex));
  195. debug(`found ${samplesToProcess.length} matches: `, DEBUG);
  196. for (let i = 0; i < samplesToProcess.length; i++) {
  197. debug(samplesToProcess[i], DEBUG);
  198. }
  199. }
  200. const backend = imageFormat === "png" ? "canvas" : "svg";
  201. const osmdInstance = new OSMD.OpenSheetMusicDisplay(div, {
  202. autoResize: false,
  203. backend: backend,
  204. pageBackgroundColor: "#FFFFFF",
  205. pageFormat: pageFormat
  206. // defaultFontFamily: 'Arial',
  207. // drawTitle: false
  208. });
  209. // for more options check OSMDOptions.ts
  210. // you can set finer-grained rendering/engraving settings in EngravingRules:
  211. // osmdInstance.EngravingRules.TitleTopDistance = 5.0 // 5.0 is default
  212. // (unless in osmdTestingMode, these will be reset with drawingParameters default)
  213. // osmdInstance.EngravingRules.PageTopMargin = 5.0 // 5 is default
  214. // osmdInstance.EngravingRules.PageBottomMargin = 5.0 // 5 is default. <5 can cut off scores that extend in the last staffline
  215. // note that for now the png and canvas will still have the height given in the script argument,
  216. // so even with a margin of 0 the image will be filled to the full height.
  217. // osmdInstance.EngravingRules.PageLeftMargin = 5.0 // 5 is default
  218. // osmdInstance.EngravingRules.PageRightMargin = 5.0 // 5 is default
  219. // osmdInstance.EngravingRules.MetronomeMarkXShift = -8; // -6 is default
  220. // osmdInstance.EngravingRules.DistanceBetweenVerticalSystemLines = 0.15; // 0.35 is default
  221. // for more options check EngravingRules.ts (though not all of these are meant and fully supported to be changed at will)
  222. if (DEBUG) {
  223. osmdInstance.setLogLevel("debug");
  224. // debug(`osmd PageFormat: ${osmdInstance.EngravingRules.PageFormat.width}x${osmdInstance.EngravingRules.PageFormat.height}`)
  225. debug(`osmd PageFormat idString: ${osmdInstance.EngravingRules.PageFormat.idString}`);
  226. debug("PageHeight: " + osmdInstance.EngravingRules.PageHeight);
  227. } else {
  228. osmdInstance.setLogLevel("info"); // doesn't seem to work, log.debug still logs
  229. }
  230. debug("[OSMD.generateImages] starting loop over samples, saving images to " + imageDir, DEBUG);
  231. for (let i = 0; i < samplesToProcess.length; i++) {
  232. const sampleFilename = samplesToProcess[i];
  233. debug("sampleFilename: " + sampleFilename, DEBUG);
  234. await generateSampleImage(sampleFilename, sampleDir, osmdInstance, osmdTestingMode, {}, DEBUG);
  235. if (osmdTestingMode && !osmdTestingSingleMode && sampleFilename.startsWith("Beethoven") && sampleFilename.includes("Geliebte")) {
  236. // generate one more testing image with skyline and bottomline. (startsWith 'Beethoven' don't catch the function test)
  237. await generateSampleImage(sampleFilename, sampleDir, osmdInstance, osmdTestingMode, {skyBottomLine: true}, DEBUG);
  238. // generate one more testing image with GraphicalNote positions
  239. await generateSampleImage(sampleFilename, sampleDir, osmdInstance, osmdTestingMode, {boundingBoxes: "VexFlowGraphicalNote"}, DEBUG);
  240. }
  241. }
  242. debug("done, exiting.");
  243. }
  244. // eslint-disable-next-line
  245. // let maxRss = 0, maxRssFilename = '' // to log memory usage (debug)
  246. async function generateSampleImage (sampleFilename, directory, osmdInstance, osmdTestingMode,
  247. options = {}, DEBUG = false) {
  248. function makeSkyBottomLineOptions() {
  249. const preference = skyBottomLinePreference ?? "";
  250. if (preference === "--batch") {
  251. return {
  252. preferredSkyBottomLineBatchCalculatorBackend: 0, // plain
  253. skyBottomLineBatchCriteria: 0, // use batch algorithm only
  254. };
  255. } else if (preference === "--webgl") {
  256. return {
  257. preferredSkyBottomLineBatchCalculatorBackend: 1, // webgl
  258. skyBottomLineBatchCriteria: 0, // use batch algorithm only
  259. };
  260. } else {
  261. return {
  262. preferredSkyBottomLineBatchCalculatorBackend: 0, // plain
  263. skyBottomLineBatchCriteria: Infinity, // use non-batch algorithm only
  264. };
  265. }
  266. }
  267. const samplePath = directory + "/" + sampleFilename;
  268. let loadParameter = FS.readFileSync(samplePath);
  269. if (sampleFilename.endsWith(".mxl")) {
  270. loadParameter = await OSMD.MXLHelper.MXLtoXMLstring(loadParameter);
  271. } else {
  272. loadParameter = loadParameter.toString();
  273. }
  274. // debug('loadParameter: ' + loadParameter)
  275. // debug('typeof loadParameter: ' + typeof loadParameter)
  276. // set sample-specific options for OSMD visual regression testing
  277. let includeSkyBottomLine = false;
  278. let drawBoundingBoxString;
  279. let isTestOctaveShiftInvisibleInstrument;
  280. let isTestInvisibleMeasureNotAffectingLayout;
  281. if (osmdTestingMode) {
  282. const isFunctionTestAutobeam = sampleFilename.startsWith("OSMD_function_test_autobeam");
  283. const isFunctionTestAutoColoring = sampleFilename.startsWith("OSMD_function_test_auto-custom-coloring");
  284. const isFunctionTestSystemAndPageBreaks = sampleFilename.startsWith("OSMD_Function_Test_System_and_Page_Breaks");
  285. const isFunctionTestDrawingRange = sampleFilename.startsWith("OSMD_function_test_measuresToDraw_");
  286. const defaultOrCompactTightMode = sampleFilename.startsWith("OSMD_Function_Test_Container_height") ? "compacttight" : "default";
  287. const isTestFlatBeams = sampleFilename.startsWith("test_drum_tuplet_beams");
  288. const isTestEndClefStaffEntryBboxes = sampleFilename.startsWith("test_end_measure_clefs_staffentry_bbox");
  289. const isTestPageBreakImpliesSystemBreak = sampleFilename.startsWith("test_pagebreak_implies_systembreak");
  290. const isTestPageBottomMargin0 = sampleFilename.includes("PageBottomMargin0");
  291. const isTestTupletBracketTupletNumber = sampleFilename.includes("test_tuplet_bracket_tuplet_number");
  292. const isTestCajon2NoteSystem = sampleFilename.includes("test_cajon_2-note-system");
  293. isTestOctaveShiftInvisibleInstrument = sampleFilename.includes("test_octaveshift_first_instrument_invisible");
  294. const isTextOctaveShiftExtraGraphicalMeasure = sampleFilename.includes("test_octaveshift_extragraphicalmeasure");
  295. isTestInvisibleMeasureNotAffectingLayout = sampleFilename.includes("test_invisible_measure_not_affecting_layout");
  296. osmdInstance.EngravingRules.loadDefaultValues(); // note this may also be executed in setOptions below via drawingParameters default
  297. if (isTestEndClefStaffEntryBboxes) {
  298. drawBoundingBoxString = "VexFlowStaffEntry";
  299. } else {
  300. drawBoundingBoxString = options.boundingBoxes; // undefined is also a valid value: no bboxes
  301. }
  302. osmdInstance.setOptions({
  303. autoBeam: isFunctionTestAutobeam, // only set to true for function test autobeam
  304. coloringMode: isFunctionTestAutoColoring ? 2 : 0,
  305. // eslint-disable-next-line max-len
  306. coloringSetCustom: isFunctionTestAutoColoring ? ["#d82c6b", "#F89D15", "#FFE21A", "#4dbd5c", "#009D96", "#43469d", "#76429c", "#ff0000"] : undefined,
  307. colorStemsLikeNoteheads: isFunctionTestAutoColoring,
  308. drawingParameters: defaultOrCompactTightMode, // note: default resets all EngravingRules. could be solved differently
  309. drawFromMeasureNumber: isFunctionTestDrawingRange ? 9 : 1,
  310. drawUpToMeasureNumber: isFunctionTestDrawingRange ? 12 : Number.MAX_SAFE_INTEGER,
  311. newSystemFromXML: isFunctionTestSystemAndPageBreaks,
  312. newSystemFromNewPageInXML: isTestPageBreakImpliesSystemBreak,
  313. newPageFromXML: isFunctionTestSystemAndPageBreaks,
  314. pageBackgroundColor: "#FFFFFF", // reset by drawingparameters default
  315. pageFormat: pageFormat, // reset by drawingparameters default,
  316. ...makeSkyBottomLineOptions()
  317. });
  318. // note that loadDefaultValues() may be executed in setOptions with drawingParameters default
  319. //osmdInstance.EngravingRules.RenderSingleHorizontalStaffline = true; // to use this option here, place it after setOptions(), see above
  320. osmdInstance.EngravingRules.AlwaysSetPreferredSkyBottomLineBackendAutomatically = false; // this would override the command line options (--plain etc)
  321. includeSkyBottomLine = options.skyBottomLine ? options.skyBottomLine : false; // apparently es6 doesn't have ?? operator
  322. osmdInstance.drawSkyLine = includeSkyBottomLine; // if includeSkyBottomLine, draw skyline and bottomline, else not
  323. osmdInstance.drawBottomLine = includeSkyBottomLine;
  324. osmdInstance.setDrawBoundingBox(drawBoundingBoxString, false); // false: don't render (now). also (re-)set if undefined!
  325. if (isTestFlatBeams) {
  326. osmdInstance.EngravingRules.FlatBeams = true;
  327. // osmdInstance.EngravingRules.FlatBeamOffset = 30;
  328. osmdInstance.EngravingRules.FlatBeamOffset = 10;
  329. osmdInstance.EngravingRules.FlatBeamOffsetPerBeam = 10;
  330. } else {
  331. osmdInstance.EngravingRules.FlatBeams = false;
  332. }
  333. if (isTestPageBottomMargin0) {
  334. osmdInstance.EngravingRules.PageBottomMargin = 0;
  335. }
  336. if (isTestTupletBracketTupletNumber) {
  337. osmdInstance.EngravingRules.TupletNumberLimitConsecutiveRepetitions = true;
  338. osmdInstance.EngravingRules.TupletNumberMaxConsecutiveRepetitions = 2;
  339. osmdInstance.EngravingRules.TupletNumberAlwaysDisableAfterFirstMax = true; // necessary to trigger bug
  340. }
  341. if (isTestCajon2NoteSystem) {
  342. osmdInstance.EngravingRules.PercussionUseCajon2NoteSystem = true;
  343. }
  344. if (isTextOctaveShiftExtraGraphicalMeasure || isTestOctaveShiftInvisibleInstrument) {
  345. osmdInstance.EngravingRules.NewSystemAtXMLNewSystemAttribute = true;
  346. }
  347. }
  348. try {
  349. debug("loading sample " + sampleFilename, DEBUG);
  350. await osmdInstance.load(loadParameter, sampleFilename); // if using load.then() without await, memory will not be freed up between renders
  351. if (isTestOctaveShiftInvisibleInstrument) {
  352. osmdInstance.Sheet.Instruments[0].Visible = false;
  353. }
  354. if (isTestInvisibleMeasureNotAffectingLayout) {
  355. if (osmdInstance.Sheet.Instruments[1]) { // some systems can't handle ?. in this script (just a safety check anyways)
  356. osmdInstance.Sheet.Instruments[1].Visible = false;
  357. }
  358. }
  359. } catch (ex) {
  360. debug("couldn't load sample " + sampleFilename + ", skipping. Error: \n" + ex);
  361. return;
  362. }
  363. debug("xml loaded", DEBUG);
  364. try {
  365. osmdInstance.render();
  366. // there were reports that await could help here, but render isn't a synchronous function, and it seems to work. see #932
  367. } catch (ex) {
  368. debug("renderError: " + ex);
  369. }
  370. debug("rendered", DEBUG);
  371. const markupStrings = []; // svg
  372. const dataUrls = []; // png
  373. let canvasImage;
  374. for (let pageNumber = 1; pageNumber < Number.POSITIVE_INFINITY; pageNumber++) {
  375. if (imageFormat === "png") {
  376. canvasImage = document.getElementById("osmdCanvasVexFlowBackendCanvas" + pageNumber);
  377. if (!canvasImage) {
  378. break;
  379. }
  380. if (!canvasImage.toDataURL) {
  381. debug(`error: could not get canvas image for page ${pageNumber} for file: ${sampleFilename}`);
  382. break;
  383. }
  384. dataUrls.push(canvasImage.toDataURL());
  385. } else if (imageFormat === "svg") {
  386. const svgElement = document.getElementById("osmdSvgPage" + pageNumber);
  387. if (!svgElement) {
  388. break;
  389. }
  390. // The important xmlns attribute is not serialized unless we set it here
  391. svgElement.setAttribute("xmlns", "http://www.w3.org/2000/svg");
  392. markupStrings.push(svgElement.outerHTML);
  393. }
  394. }
  395. for (let pageIndex = 0; pageIndex < Math.max(dataUrls.length, markupStrings.length); pageIndex++) {
  396. const pageNumberingString = `${pageIndex + 1}`;
  397. const skybottomlineString = includeSkyBottomLine ? "skybottomline_" : "";
  398. const graphicalNoteBboxesString = drawBoundingBoxString ? "bbox" + drawBoundingBoxString + "_" : "";
  399. // pageNumberingString = dataUrls.length > 0 ? pageNumberingString : '' // don't put '_1' at the end if only one page. though that may cause more work
  400. const pageFilename = `${imageDir}/${sampleFilename}_${skybottomlineString}${graphicalNoteBboxesString}${pageNumberingString}.${imageFormat}`;
  401. if (imageFormat === "png") {
  402. const dataUrl = dataUrls[pageIndex];
  403. if (!dataUrl || !dataUrl.split) {
  404. debug(`error: could not get dataUrl (imageData) for page ${pageIndex + 1} of sample: ${sampleFilename}`);
  405. continue;
  406. }
  407. const imageData = dataUrl.split(";base64,").pop();
  408. const imageBuffer = Buffer.from(imageData, "base64");
  409. debug("got image data, saving to: " + pageFilename, DEBUG);
  410. FS.writeFileSync(pageFilename, imageBuffer, { encoding: "base64" });
  411. } else if (imageFormat === "svg") {
  412. const markup = markupStrings[pageIndex];
  413. if (!markup) {
  414. debug(`error: could not get markup (SVG data) for page ${pageIndex + 1} of sample: ${sampleFilename}`);
  415. continue;
  416. }
  417. debug("got svg markup data, saving to: " + pageFilename, DEBUG);
  418. FS.writeFileSync(pageFilename, markup, { encoding: "utf-8" });
  419. }
  420. // debug: log memory usage
  421. // const usage = process.memoryUsage()
  422. // for (const entry of Object.entries(usage)) {
  423. // if (entry[0] === 'rss') {
  424. // if (entry[1] > maxRss) {
  425. // maxRss = entry[1]
  426. // maxRssFilename = pageFilename
  427. // }
  428. // }
  429. // debug(entry[0] + ': ' + entry[1] / (1024 * 1024) + 'mb')
  430. // }
  431. // debug('maxRss: ' + (maxRss / 1024 / 1024) + 'mb' + ' for ' + maxRssFilename)
  432. }
  433. // debug('maxRss total: ' + (maxRss / 1024 / 1024) + 'mb' + ' for ' + maxRssFilename)
  434. // await sleep(5000)
  435. // }) // end read file
  436. }
  437. function debug (msg, debugEnabled = true) {
  438. if (debugEnabled) {
  439. console.log("[generateImages] " + msg);
  440. }
  441. }
  442. init();