Skip to content

Commit

Permalink
Added get bedset pep and genome browser to ui and api
Browse files Browse the repository at this point in the history
  • Loading branch information
khoroshevskyi committed Oct 23, 2024
1 parent 402edee commit 0d75d2e
Show file tree
Hide file tree
Showing 3 changed files with 118 additions and 6 deletions.
15 changes: 15 additions & 0 deletions bedhost/routers/bedset_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@

from ..main import bbagent
from ..const import PKG_NAME, EXAMPLE_BEDSET
from ..utils import zip_pep


router = APIRouter(prefix="/v1/bedset", tags=["bedset"])
Expand Down Expand Up @@ -63,6 +64,20 @@ async def get_bedset_metadata(
raise HTTPException(status_code=404, detail="No records found")


@router.get(
"/{bedset_id}/pep",
summary="Download PEP project for a single BEDset record",
description=f"Example\n bed_id: {EXAMPLE_BEDSET}",
)
async def get_bedset_pep(
bedset_id: str,
):
try:
return zip_pep(bbagent.bedset.get_bedset_pep(bedset_id))
except BedSetNotFoundError as _:
raise HTTPException(status_code=404, detail="No records found")


@router.get(
"/{bedset_id}/metadata/plots",
response_model=BedSetPlots,
Expand Down
80 changes: 80 additions & 0 deletions bedhost/utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import io
import zipfile
from datetime import date
from typing import Any, Dict

import pandas as pd
import yaml
from fastapi import Response
from peppy.const import (
CFG_SAMPLE_TABLE_KEY,
CFG_SUBSAMPLE_TABLE_KEY,
CONFIG_KEY,
NAME_KEY,
SAMPLE_RAW_DICT_KEY,
SUBSAMPLE_RAW_LIST_KEY,
)


def zip_conv_result(conv_result: dict, filename: str = "project.zip") -> Response:
"""
Given a dictionary of converted results, zip them up and return a response
## Copied from pephub/helpers.py
:param conv_result: dictionary of converted results
:param filename: name of the zip
return Response: response object
"""
mf = io.BytesIO()

with zipfile.ZipFile(mf, mode="w", compression=zipfile.ZIP_DEFLATED) as zf:
for name, res in conv_result.items():
# Add file, at correct path
zf.writestr(name, str.encode(res))

# Grab ZIP file from in-memory, make response with correct MIME-type
resp = Response(
mf.getvalue(),
media_type="application/x-zip-compressed",
headers={"Content-Disposition": f"attachment;filename={filename}"},
)

return resp


def zip_pep(project: Dict[str, Any]) -> Response:
"""
Zip a project up to download
## Copied from pephub/helpers.py
:param project: peppy project to zip
"""

content_to_zip = {}
config = project[CONFIG_KEY]
project_name = config[NAME_KEY]

if project[SAMPLE_RAW_DICT_KEY] is not None:
config[CFG_SAMPLE_TABLE_KEY] = ["sample_table.csv"]
content_to_zip["sample_table.csv"] = pd.DataFrame(
project[SAMPLE_RAW_DICT_KEY]
).to_csv(index=False)

if project[SUBSAMPLE_RAW_LIST_KEY] is not None:
if not isinstance(project[SUBSAMPLE_RAW_LIST_KEY], list):
config[CFG_SUBSAMPLE_TABLE_KEY] = ["subsample_table1.csv"]
content_to_zip["subsample_table1.csv"] = pd.DataFrame(
project[SUBSAMPLE_RAW_LIST_KEY]
).to_csv(index=False)
else:
config[CFG_SUBSAMPLE_TABLE_KEY] = []
for number, file in enumerate(project[SUBSAMPLE_RAW_LIST_KEY]):
file_name = f"subsample_table{number + 1}.csv"
config[CFG_SUBSAMPLE_TABLE_KEY].append(file_name)
content_to_zip[file_name] = pd.DataFrame(file).to_csv(index=False)

content_to_zip[f"{project_name}_config.yaml"] = yaml.dump(config, indent=4)

zip_filename = project_name or f"downloaded_pep_{date.today()}"
return zip_conv_result(content_to_zip, filename=zip_filename)
29 changes: 23 additions & 6 deletions ui/src/components/bedset-splash-components/header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,23 @@ export const BedsetSplashHeader = (props: Props) => {
<p className="mb-0">{metadata?.description || 'No description available'}</p>
</div>
<div className="d-flex flex-row align-items-center gap-1">

{/* TODO: change hg38 on correct genome */}
{/*<a href={`https://genome.ucsc.edu/cgi-bin/hgTracks?db=hg38&hubUrl=https://api-dev.bedbase.org/v1/bedset/${metadata.id}/track_hub`}>*/}
<a href={`https://genome.ucsc.edu/cgi-bin/hgTracks?db=hg38&hubUrl=${API_BASE}/bedset/${metadata.id}/track_hub`}>
<button className="btn btn-outline-primary btn-sm">
<i className="bi bi-distribute-vertical me-1" />
Genome Browser
</button>
</a>

<a href={`${API_BASE}/bedset/${metadata.id}/pep`}>
<button className="btn btn-outline-primary btn-sm">
<i className="bi bi-download me-1" />
Download PEP
</button>
</a>

<a href={`${API_BASE}/bedset/${metadata.id}/metadata?full=true`}>
<button className="btn btn-outline-primary btn-sm">
<i className="bi bi-info-circle me-1" />
Expand All @@ -65,12 +82,12 @@ export const BedsetSplashHeader = (props: Props) => {
metadata.bed_ids?.length === 0
? undefined
: () => {
addMultipleBedsToCart(metadata.bed_ids || []);
setAddedToCart(true);
setTimeout(() => {
setAddedToCart(false);
}, 500);
}
addMultipleBedsToCart(metadata.bed_ids || []);
setAddedToCart(true);
setTimeout(() => {
setAddedToCart(false);
}, 500);
}
}
disabled={metadata.bed_ids?.length === 0 || addedToCart}
className="btn btn-primary btn-sm"
Expand Down

0 comments on commit 0d75d2e

Please sign in to comment.