Spaces:
Sleeping

gloop-predictor / app.py
zapell's picture
Deploy app from 552c095
4fa5de2 verified
Raw History Blame Contribute Delete
4.93 kB
"""Web app that scores DNA sequences for candidate G-loop formation.
One process serves three things:
/ web page: paste a sequence, see a score for each 500 bp window
/predict JSON API (same scores as the web page)
/docs interactive API documentation
Run from the repo root (on a laptop, or a Great Lakes compute node, never a login node):
uvicorn app:app --app-dir api --port 8000
The model is the local results/models/dnabert2_binary if it exists (Great Lakes), otherwise
zapell/gloop-dnabert2, downloaded once from Hugging Face. Set MODEL_DIR to use another.
"""
import os
import gradio as gr
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, Field
import examples
from predictor import MAX_BP, MAX_WINDOWS, THRESHOLD, WINDOW_BP, Predictor
LOCAL_MODEL = "results/models/dnabert2_binary"
HUB_MODEL = "zapell/gloop-dnabert2"
MODEL_DIR = os.environ.get("MODEL_DIR") or (LOCAL_MODEL if os.path.isdir(LOCAL_MODEL) else HUB_MODEL)
NOTE = ("Scores are computational predictions of candidate G-loop regions "
"(G4 and R-loop co-occurrence), not experimentally confirmed G-loops.")
predictor = Predictor(MODEL_DIR) # loaded once at startup
app = FastAPI(
title="G-loop predictor",
description="Scores DNA sequences for candidate G-loop formation with a fine-tuned DNABERT-2. " + NOTE,
version="0.2.0",
)
class PredictRequest(BaseModel):
sequences: list[str] = Field(..., min_length=1,
description=f"DNA sequences of A/C/G/T (FASTA header allowed), "
f"up to {MAX_BP} bp each and {MAX_WINDOWS} windows "
f"of {WINDOW_BP} bp per request.")
class Window(BaseModel):
start: int = Field(..., description="1-based start position in the input sequence.")
end: int = Field(..., description="1-based end position (inclusive).")
gloop_probability: float = Field(..., description="Model probability of a candidate G-loop.")
call: str = Field(..., description=f"'candidate G-loop' if probability >= {THRESHOLD}, "
f"else 'not predicted'.")
class Prediction(BaseModel):
length_bp: int
max_probability: float = Field(..., description="Highest window probability.")
call: str = Field(..., description="'candidate G-loop' if any window is called positive.")
windows: list[Window]
warning: str | None = None
class PredictResponse(BaseModel):
model: str
predictions: list[Prediction]
note: str = NOTE
@app.get("/health")
def health() -> dict:
return {"status": "ok", "model": MODEL_DIR}
@app.post("/predict", response_model=PredictResponse)
def predict(request: PredictRequest) -> PredictResponse:
try:
results = predictor.score(request.sequences)
except ValueError as e:
raise HTTPException(status_code=422, detail=str(e))
return PredictResponse(model=MODEL_DIR, predictions=results)
# ---- Web page ---------------------------------------------------------------------------------
def score_text(text: str):
try:
result = predictor.score([text])[0]
except ValueError as e:
raise gr.Error(str(e))
summary = (f"**{result['call']}**: highest window probability "
f"**{result['max_probability']:.3f}** ({result['length_bp']} bp, "
f"{len(result['windows'])} window{'s' if len(result['windows']) > 1 else ''}).")
if result["warning"]:
summary += f"\n\n⚠️ {result['warning']}"
rows = [[w["start"], w["end"], round(w["gloop_probability"], 3), w["call"]]
for w in result["windows"]]
return summary, rows
demo = gr.Interface(
fn=score_text,
inputs=gr.Textbox(lines=8, label="DNA sequence or FASTA record",
placeholder="Paste human DNA (A/C/G/T), ideally 500 bp. "
f"Longer sequences up to {MAX_BP:,} bp are scored "
f"in {WINDOW_BP} bp windows."),
outputs=[gr.Markdown(label="Result"),
gr.Dataframe(headers=["start", "end", "G-loop probability", "call"],
label="Windows")],
examples=[[examples.GLOOP], [examples.BACKGROUND]],
title="G-loop predictor",
description=("Estimates how likely a stretch of human DNA is a **candidate G-loop**, a place "
"where a G-quadruplex (G4) and an R-loop occur together. The model is DNABERT-2 "
"fine-tuned on K562 G4 (BG4 ChIP) and R-loop (R-ChIP) peaks. " + NOTE +
" The examples are held-out test windows: a G-loop and a GC-rich background "
"region. JSON API docs are at [/docs](/docs)."),
flagging_mode="never",
)
# Mounted last so /predict, /health and /docs above take precedence over the page at /.
app = gr.mount_gradio_app(app, demo, path="/")