Skip to content

Commit

Permalink
refactor: combine the functionality of nmr-snapshot-cli with nmr-cli …
Browse files Browse the repository at this point in the history
…and remove nmr-snapshot-cli3
  • Loading branch information
hamed-musallam committed Nov 23, 2023
1 parent 0bf04a0 commit 1034b3f
Show file tree
Hide file tree
Showing 8 changed files with 209 additions and 258 deletions.
10 changes: 7 additions & 3 deletions app/scripts/nmr-cli/Dockerfile
Original file line number Diff line number Diff line change
@@ -1,15 +1,19 @@
# build the image ` docker build --tag nmr-cli . `
# run the container ` docker run -it nmr-cli bash `

FROM node:20.9.0-alpine
# a temporary command to add bash to the Docker image to be able to run the container with an interactive Shell for testing purpose
RUN apk update && apk add bash
FROM mcr.microsoft.com/playwright:v1.40.0-jammy

SHELL ["/bin/bash", "-o", "pipefail", "-c"]

WORKDIR /app

#ENV BASE_NMRIUM_URL=https://nmrium.nmrxiv.org/
ENV BASE_NMRIUM_URL=https://nmriumdev.nmrxiv.org/


COPY package.json ./
COPY package-lock.json ./

RUN npm install

COPY . ./
Expand Down
180 changes: 139 additions & 41 deletions app/scripts/nmr-cli/bin/index.js
Original file line number Diff line number Diff line change
@@ -1,64 +1,162 @@
#!/usr/bin/env node
const {join,isAbsolute}= require("path");
const { join, isAbsolute } = require("path");
const yargs = require("yargs");
const loader = require("nmr-load-save");
const fileUtils = require("filelist-utils");
const playwright = require('playwright');

const usageMessage ="Usage: nmr-cli -u <url> or -p <path>"
const usageMessage = "Usage: nmr-cli -u <url> or -p <path> -s<Optional parameter to capture spectra snapshots>"


/**
* How to Use the Command Line Tool:
* Example 1: Process spectra files from a URL
* Usage: nmr-cli -u https://example.com/file.zip
* -------------------------------------------------------------------------
* Example 2: process a spectra files from a directory < nmr-cli -p /path/to/directory >
* Usage: nmr-cli -p /path/to/directory
* -------------------------------------------------------------------------
* you could also combine the above examples with an optional parameter to capturing a snapshot using the -s option
*
*/

const options = yargs
.usage(usageMessage)
.option("u", { alias: "url", describe: "File URL", type: "string",nargs:1})
.option("p", { alias: "path", describe: "Directory path", type: "string",nargs:1}).showHelpOnFail();

async function loadSpectrumFromURL(url) {
const {pathname:relativePath,origin:baseURL} = new URL(url);
const source = {
entries: [
{
relativePath,
}
],
baseURL
};
const fileCollection = await fileUtils.fileCollectionFromWebSource(source,{});

const {
nmriumState: { data },
} = await loader.read(fileCollection);
return data;
.usage(usageMessage)
.option("u", { alias: "url", describe: "File URL", type: "string", nargs: 1 })
.option("p", { alias: "path", describe: "Directory path", type: "string", nargs: 1 })
.option("s", { alias: "capture-snapshot", describe: "Capture snapshot", type: "boolean" }).showHelpOnFail();




function generateNMRiumURL() {
const baseURL = process.env['BASE_NMRIUM_URL'];
const url = new URL(baseURL)
url.searchParams.append('workspace', "embedded")
return url.toString()
}

async function captureSpectraViewAsBase64(nmriumState) {
const { data: { spectra }, version } = nmriumState;
const browser = await playwright.chromium.launch()
const context = await browser.newContext(playwright.devices['Desktop Chrome HiDPI'])
const page = await context.newPage()

const url = generateNMRiumURL()

await page.goto(url)

await page.locator('text=Loading').waitFor({ state: 'hidden' });

let snapshots = []

for (const spectrum of spectra || []) {
const spectrumObject = {
version,
data: {
spectra: [{ ...spectrum }],
}

}

// convert typed array to array
const stringObject = JSON.stringify(spectrumObject, (key, value) => {
return ArrayBuffer.isView(value) ? Array.from(value) : value
})

// load the spectrum into NMRium using the custom event
await page.evaluate(
`
window.postMessage({ type: "nmr-wrapper:load", data:{data: ${stringObject},type:"nmrium"}}, '*');
`
)

//wait for NMRium process and load spectra
await page.locator('text=Loading').waitFor({ state: 'hidden' });

// take a snapshot for the spectrum
try {
const snapshot = await page.locator('#nmrSVG .container').screenshot()

snapshots.push({
image: snapshot.toString('base64'),
id: spectrum.id,
})
} catch (e) {
console.log(e)
}
}

await context.close()
await browser.close()

return snapshots;
}

async function loadSpectrumFromFilePath(path) {
const dirPath = isAbsolute(path)?path:join(process.cwd(),path)

const fileCollection = await fileUtils.fileCollectionFromPath(dirPath,{});

const {
nmriumState: { data },
} = await loader.read(fileCollection);
return data;
async function loadSpectrumFromURL(url, enableSnapshot = false) {
const { pathname: relativePath, origin: baseURL } = new URL(url);
const source = {
entries: [
{
relativePath,
}
],
baseURL
};
const fileCollection = await fileUtils.fileCollectionFromWebSource(source, {});

const {
nmriumState: { data, version },
} = await loader.read(fileCollection);

let images = []

if (enableSnapshot) {
images = await captureSpectraViewAsBase64({ data, version });
}


const parameters = options.argv;
return { data, version, images };
}


async function loadSpectrumFromFilePath(path, enableSnapshot = false) {
const dirPath = isAbsolute(path) ? path : join(process.cwd(), path)

const fileCollection = await fileUtils.fileCollectionFromPath(dirPath, {});

const {
nmriumState: { data, version }
} = await loader.read(fileCollection);

let images = []

if(parameters.u && parameters.p){
if (enableSnapshot) {
images = await captureSpectraViewAsBase64({ data, version });
}


return { data, version, images };
}


const parameters = options.argv;

if (parameters.u && parameters.p) {
options.showHelp();
}else{
} else {

if(parameters.u){
loadSpectrumFromURL(parameters.u).then((result)=>{
console.log(JSON.stringify(result))
})
if (parameters.u) {
loadSpectrumFromURL(parameters.u, parameters.s).then((result) => {
console.log(JSON.stringify(result))
})

}

if(parameters.p){
loadSpectrumFromFilePath(parameters.p).then((result)=>{
if (parameters.p) {
loadSpectrumFromFilePath(parameters.p, parameters.s).then((result) => {
console.log(JSON.stringify(result))
})
})
}

}
Expand Down
76 changes: 59 additions & 17 deletions app/scripts/nmr-cli/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 4 additions & 3 deletions app/scripts/nmr-cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@
},
"dependencies": {
"filelist-utils": "^1.10.2",
"nmr-load-save": "^0.22.4",
"yargs": "^17.7.2"
"nmr-load-save": "^0.23.3",
"yargs": "^17.7.2",
"playwright": "^1.40.0"
}
}
}
Loading

0 comments on commit 1034b3f

Please sign in to comment.