Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: NMRium snapshot cli #64

Merged
merged 3 commits into from
Dec 14, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
* 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
44 changes: 43 additions & 1 deletion app/scripts/nmr-cli/package-lock.json

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

3 changes: 2 additions & 1 deletion app/scripts/nmr-cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
"dependencies": {
"filelist-utils": "^1.10.2",
"nmr-load-save": "^0.23.11",
"playwright": "^1.40.1",
"yargs": "^17.7.2"
}
}
}