Skip to content

Commit

Permalink
fix: added spectra router
Browse files Browse the repository at this point in the history
  • Loading branch information
CS76 committed Aug 7, 2023
1 parent 41f50b7 commit 62f6981
Show file tree
Hide file tree
Showing 10 changed files with 154 additions and 45 deletions.
6 changes: 6 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -43,4 +43,10 @@ RUN python3 -m pip install uvicorn[standard]

COPY ./app /code/app

RUN curl -sL https://deb.nodesource.com/setup_current.x | bash -
RUN apt-get install -y nodejs
RUN npm install -g npm@latest

RUN npm install -g /code/app/scripts/nmr-cli

CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80", "--workers", "4", "--reload"]
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,5 +49,5 @@ NMRKit is developed and maintained by the [NFDI4Chem partners](https://www.nfdi4
The code for this web application is released under the [MIT license](https://opensource.org/licenses/MIT).


<p align="left"><a href="https://nfdi4chem.de/" target="_blank"><img src="https://www.nfdi4chem.de/wp-content/themes/wptheme/assets/img/logo.svg" width="50%" alt="NFDI4Chem Logo"></a></p>
<p align="left"><a href="https://nfdi4chem.de/" target="_blank"><img src="https://www.nfdi4chem.de/wp-content/themes/wptheme/assets/img/logo.svg" width="30%" alt="NFDI4Chem Logo"></a></p>
<p align="left"><a href="https://cheminf.uni-jena.de/" target="_blank"><img src="/public/img/fsu-jena.jpg" width="30%" alt="NFDI4Chem Logo"></a></p>
2 changes: 2 additions & 0 deletions app/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

from .routers import registration
from .routers import chem
from .routers import spectra
from fastapi.middleware.cors import CORSMiddleware

from app.core import config, tasks
Expand All @@ -29,6 +30,7 @@

app.include_router(registration.router)
app.include_router(chem.router)
app.include_router(spectra.router)

app.add_event_handler("startup", tasks.create_start_app_handler(app))
app.add_event_handler("shutdown", tasks.create_stop_app_handler(app))
Expand Down
2 changes: 1 addition & 1 deletion app/routers/chem.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ def get_health() -> HealthCheck:

@router.get(
"/hosecode",
tags=["registration"],
tags=["chem"],
summary="Generates HOSE codes of molecule",
response_model=list[str],
response_description="Returns an array of hose codes generated",
Expand Down
70 changes: 70 additions & 0 deletions app/routers/spectra.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
from typing import Annotated
from fastapi import APIRouter, HTTPException, status, FastAPI, File, UploadFile
from fastapi.responses import Response
from app.schemas import HealthCheck
import subprocess
import json

router = APIRouter(
prefix="/spectra",
tags=["spectra"],
dependencies=[],
responses={404: {"description": "Not found"}},
)

@router.get("/", include_in_schema=False)
@router.get(
"/health",
tags=["healthcheck"],
summary="Perform a Health Check on Chem Module",
response_description="Return HTTP Status Code 200 (OK)",
status_code=status.HTTP_200_OK,
include_in_schema=False,
response_model=HealthCheck,
)
def get_health() -> HealthCheck:
"""
## Perform a Health Check
Endpoint to perform a healthcheck on. This endpoint can primarily be used Docker
to ensure a robust container orchestration and management is in place. Other
services which rely on proper functioning of the API service will not deploy if this
endpoint returns any other HTTP status code except 200 (OK).
Returns:
HealthCheck: Returns a JSON response with the health status
"""
return HealthCheck(status="OK")


@router.post(
"/parse",
tags=["spectra"],
summary="Parse the input spectra format and extract metadata",
response_description="",
status_code=status.HTTP_200_OK,
)
async def parse_spectra(file: UploadFile):
"""
## Parse the spectra file and extract meta-data
Endpoint to uses nmr-load-save to read the input spectra file (.jdx,.nmredata,.dx) and extracts metadata
Returns:
data: spectra data in json format
"""
try:
contents = file.file.read()
file_path = "/tmp/" + file.filename
with open(file_path, 'wb') as f:
f.write(contents)
p = subprocess.Popen("npx nmr-cli -p " + file_path, stdout=subprocess.PIPE, shell=True)
(output, err) = p.communicate()
p_status = p.wait()
return output
except Exception as e:
raise HTTPException(
status_code=422,
detail="Error paring the structure " + e.message + ". Error: " + err + ". Status:" + p_status,
headers={"X-Error": "RDKit molecule input parse error"},
)
finally:
file.file.close()
69 changes: 69 additions & 0 deletions app/scripts/nmr-cli/bin/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
#!/usr/bin/env node
const {join,isAbsolute}= require("path");
const yargs = require("yargs");
const loader = require("nmr-load-save");
const fileUtils = require("filelist-utils");

const usageMessage ="Usage: nmr-cli -u <url> or -p <path>"

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;
}


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;
}


const parameters = options.argv;

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

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

}

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

}





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

File renamed without changes.
39 changes: 0 additions & 39 deletions app/scripts/nmr-load-save/bin/index.js

This file was deleted.

3 changes: 2 additions & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,5 @@ prometheus-fastapi-instrumentator
databases[postgresql]==0.4.2
SQLAlchemy==2.0.19
alembic==1.11.1
psycopg2-binary
psycopg2-binary
python-multipart

0 comments on commit 62f6981

Please sign in to comment.