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: add search bar #98

Merged
merged 9 commits into from
Dec 1, 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
14 changes: 10 additions & 4 deletions backend/src/protein.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,20 +43,22 @@ def decode_base64(b64_header_and_data: str):
return b64decode(b64_data_only).decode("utf-8")


def pdb_file_name(name: str):
return f"{os.path.join('src/data/pdbAlphaFold', name)}.pdb"
def pdb_file_name(protein_name: str):
return os.path.join("src/data/pdbAlphaFold", protein_name) + ".pdb"


def parse_protein_pdb(name: str, file_contents: str, encoding="str"):
def parse_protein_pdb(name: str, file_contents: str = "", encoding="str"):
if encoding == "str":
return PDB(file_contents, name)
elif encoding == "b64":
return PDB(decode_base64(file_contents), name)
elif encoding == "file":
return PDB(open(pdb_file_name(name), "r").read(), name)
else:
raise ValueError(f"Invalid encoding: {encoding}")


def protein_name_taken(name: str):
def protein_name_found(name: str):
"""Checks if a protein name already exists in the database
Returns: True if exists | False if not exists
"""
Expand Down Expand Up @@ -96,3 +98,7 @@ def save_protein(pdb: PDB):
)
except Exception as e:
raise e


def pdb_to_fasta(pdb: PDB):
return ">{}\n{}".format(pdb.name, "".join(pdb.amino_acids()))
37 changes: 26 additions & 11 deletions backend/src/server.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,35 @@
import logging as log
import os
from fastapi.staticfiles import StaticFiles
from io import BytesIO
from fastapi.responses import FileResponse, StreamingResponse
from .api_types import ProteinEntry, UploadBody, UploadError, EditBody
from .db import Database, bytea_to_str, str_to_bytea
from .protein import parse_protein_pdb, pdb_file_name, protein_name_taken
from .protein import parse_protein_pdb, pdb_file_name, protein_name_found, pdb_to_fasta
from .setup import disable_cors, init_fastapi_app


app = init_fastapi_app()
disable_cors(app, origins=["http://0.0.0.0:5173", "http://localhost:5173"])
# mount the data directory so we can easily access files through the url
app.mount("/data", StaticFiles(directory="src/data"), name="data")
disable_cors(app, origins=[os.environ["PUBLIC_FRONTEND_URL"]])


@app.get("/pdb/{protein_name:str}")
def get_pdb_file(protein_name: str):
if protein_name_found(protein_name):
return FileResponse(pdb_file_name(protein_name), filename=protein_name + ".pdb")


@app.get("/fasta/{protein_name:str}")
def get_fasta_file(protein_name: str):
if protein_name_found(protein_name):
pdb = parse_protein_pdb(protein_name, encoding="file")
fasta = pdb_to_fasta(pdb)
return StreamingResponse(
BytesIO(fasta.encode()),
media_type="text/plain",
headers={
"Content-Disposition": f"attachment; filename={protein_name}.fasta"
},
)


# important to note the return type (response_mode) so frontend can generate that type through `./run.sh api`
Expand Down Expand Up @@ -113,10 +133,8 @@ def delete_protein_entry(protein_name: str):
# None return means success
@app.post("/protein-upload", response_model=UploadError | None)
def upload_protein_entry(body: UploadBody):
body.name = body.name.replace(" ", "_")

# check that the name is not already taken in the DB
if protein_name_taken(body.name):
if protein_name_found(body.name):
return UploadError.NAME_NOT_UNIQUE

# if name is unique, save the pdb file and add the entry to the database
Expand Down Expand Up @@ -150,9 +168,6 @@ def upload_protein_entry(body: UploadBody):
# TODO: add more edits, now only does name and content edits
@app.put("/protein-edit", response_model=UploadError | None)
def edit_protein_entry(body: EditBody):
body.new_name = body.new_name.replace(" ", "_")
body.old_name = body.old_name.replace(" ", "_")

# check that the name is not already taken in the DB
# TODO: check if permission so we don't have people overriding other people's names

Expand Down
3 changes: 3 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ services:
- docker_node_modules:/app/node_modules/
ports:
- "5173:5173"
environment:
PUBLIC_BACKEND_URL: http://localhost:8000
command: ["yarn", "dev", "--", "--host", "0.0.0.0"]
backend:
container_name: venome-backend
Expand All @@ -25,6 +27,7 @@ services:
depends_on:
- postgres
environment:
PUBLIC_FRONTEND_URL: http://localhost:5173
BACKEND_HOST: 0.0.0.0
BACKEND_PORT: 8000
DB_HOST: postgres
Expand Down
79 changes: 79 additions & 0 deletions frontend/src/lib/ListProteins.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
<script lang="ts">
import { goto } from "$app/navigation";
import type { ProteinEntry } from "$lib/backend";
import { numberWithCommas } from "$lib/format";
import {
Table,
TableBody,
TableBodyCell,
TableBodyRow,
TableHead,
TableHeadCell,
} from "flowbite-svelte";
import { Tabs, TabItem } from "flowbite-svelte";
import { Card } from "flowbite-svelte";

export let allEntries: ProteinEntry[] | null = null;
</script>

<Tabs style="underline" contentClass="bg-none p-5">
<TabItem open title="Table">
<Table>
<TableHead>
<TableHeadCell>Protein name</TableHeadCell>
<TableHeadCell>Length</TableHeadCell>
<TableHeadCell>Mass (Da)</TableHeadCell>
</TableHead>
<TableBody tableBodyClass="divide-y">
{#if allEntries}
{#each allEntries as entry}
<TableBodyRow
class="cursor-pointer hover:bg-gray-100"
on:click={() => {
goto(`/protein/${entry.name}`);
}}
>
<TableBodyCell
><span class="text-primary-700">{entry.name}</span
></TableBodyCell
>
<TableBodyCell>{entry.length}</TableBodyCell>
<TableBodyCell>{numberWithCommas(entry.mass)}</TableBodyCell>
</TableBodyRow>
{/each}
{/if}
</TableBody>
</Table>
</TabItem>
<TabItem title="Gallery">
<div class="entries">
{#if allEntries}
{#each allEntries as entry}
<Card
class="hover:shadow-lg cursor-pointer"
title="Click to see {entry.name}"
on:click={() => goto(`/protein/${entry.name}`)}
>
<div class="name text-primary-700">
{entry.name}
</div>
<div class="description">
Length: {entry.length}, Mass (Da): {numberWithCommas(entry.mass)}
</div>
</Card>
{/each}
{/if}
</div>
</TabItem>
</Tabs>

<style>
.entries {
display: flex;
flex-wrap: wrap;
gap: 20px;
}
.name {
font-size: 1.5em;
}
</style>
7 changes: 4 additions & 3 deletions frontend/src/lib/backend.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
export * from "../openapi";
export { DefaultService as Backend } from "../openapi";
import { OpenAPI } from "../openapi";
import { env } from "$env/dynamic/public";

const BACKEND_PORT = 8000;
const BACKEND_HOST = "localhost";
OpenAPI.BASE = `http://${BACKEND_HOST}:${BACKEND_PORT}`; // backend server
export const BACKEND_URL = env["PUBLIC_BACKEND_URL"];
if (!BACKEND_URL) throw new Error("PUBLIC_BACKEND_URL is not set in .env");
OpenAPI.BASE = BACKEND_URL;
42 changes: 34 additions & 8 deletions frontend/src/lib/format.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,11 @@
import { goto } from "$app/navigation";
import { writable, type Writable } from "svelte/store";

export function numberWithCommas(x: number, round = 0) {
const formatter = new Intl.NumberFormat("en-US");
return formatter.format(+x.toFixed(round));
}

export function formatProteinName(name: string) {
return name.replaceAll(" ", "_");
}

export function humanReadableProteinName(name: string) {
return name.replaceAll("_", " ");
}

export function fileToString(f: File): Promise<string> {
return new Promise((resolve, reject) => {
const reader = new FileReader();
Expand All @@ -21,3 +16,34 @@ export function fileToString(f: File): Promise<string> {
reader.onerror = reject;
});
}

/**
* When I have a url parameter, I want to first set it to that
* Then, if the url parameter changes in svelte, I want to change the url in the browser parameter too
*/
export function writableUrlParams(
searchParams: URLSearchParams,
name: string
): Writable<any> {
const param = writable(searchParams.get(name) ?? "");
return {
subscribe: param.subscribe,
set(searchBy) {
searchParams.set(name, searchBy); // update url
goto(`?${searchParams.toString()}`, {
keepFocus: true,
replaceState: true,
noScroll: true,
}); // update browser top
},
update() {
const searchBy = searchParams.get(name) ?? "";
searchParams.set(name, searchBy); // update url
goto(`?${searchParams.toString()}`, {
keepFocus: true,
replaceState: true,
noScroll: true,
}); // update browser top
},
};
}
91 changes: 6 additions & 85 deletions frontend/src/routes/+page.svelte
Original file line number Diff line number Diff line change
@@ -1,98 +1,19 @@
<script lang="ts">
import { onMount } from "svelte";
import { goto } from "$app/navigation";
import { Backend } from "$lib/backend";
import type { ProteinEntry } from "$lib/backend";
import { humanReadableProteinName, numberWithCommas } from "$lib/format";
import {
Table,
TableBody,
TableBodyCell,
TableBodyRow,
TableHead,
TableHeadCell,
} from "flowbite-svelte";
import { Tabs, TabItem } from "flowbite-svelte";
import { Card, Button, Toggle } from "flowbite-svelte";
import { onMount } from "svelte";

// at some point, this should be change to request from the backend
let allEntries: ProteinEntry[] | null = null;
onMount(async () => {
// calls get_all_entries() from backend
// to generate this Backend object run `./run.sh gen_api` for newly created server functions
allEntries = await Backend.getAllEntries();
console.log(allEntries);
// remove once we have a landing page
onMount(() => {
goto("/search");
});
</script>

<!-- akin to <head /> in html -->
<svelte:head>
<title>Home</title>
</svelte:head>

<section>
<Tabs style="underline" contentClass="bg-none p-5">
<TabItem open title="Table">
<Table>
<TableHead>
<TableHeadCell>Protein name</TableHeadCell>
<TableHeadCell>Length</TableHeadCell>
<TableHeadCell>Mass (Da)</TableHeadCell>
</TableHead>
<TableBody tableBodyClass="divide-y">
{#if allEntries}
{#each allEntries as entry}
<TableBodyRow
class="cursor-pointer hover:bg-gray-100"
on:click={() => {
goto(`/protein/${entry.name}`);
}}
>
<TableBodyCell
><span class="text-primary-700"
>{humanReadableProteinName(entry.name)}</span
></TableBodyCell
>
<TableBodyCell>{entry.length}</TableBodyCell>
<TableBodyCell>{numberWithCommas(entry.mass)}</TableBodyCell>
</TableBodyRow>
{/each}
{/if}
</TableBody>
</Table>
</TabItem>
<TabItem title="Gallery">
<div class="entries">
{#if allEntries}
{#each allEntries as entry}
<Card
class="hover:shadow-lg cursor-pointer"
title="Click to see {entry.name}"
on:click={() => goto(`/protein/${entry.name}`)}
>
<div class="name text-primary-700">
{humanReadableProteinName(entry.name)}
</div>
<div class="description">
Length: {entry.length}, Mass (Da): {numberWithCommas(
entry.mass
)}
</div>
</Card>
{/each}
{/if}
</div>
</TabItem>
</Tabs>
</section>
<div>Landing Page</div>

<style>
.entries {
display: flex;
flex-wrap: wrap;
gap: 20px;
}
.name {
font-size: 1.5em;
}
/* put stuff here */
</style>
2 changes: 1 addition & 1 deletion frontend/src/routes/Header.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
</a>
</div>
<div class="nav">
<a href="/">Search</a>
<a href="/search">Search</a>
<a href="/upload">Upload</a>
</div>
</div>
Expand Down
Loading