Spaces:
Sleeping
Sleeping
Download predictor.py from zapell/gloop-predictor: direct link, hf CLI and curl.
- Browser
- Download file 4.99 kB
-
https://huggingface.co/spaces/zapell/gloop-predictor/resolve/main/predictor.py
- Command line
-
hf download hf://spaces/zapell/gloop-predictor/predictor.py
-
curl -L -o predictor.py https://huggingface.co/spaces/zapell/gloop-predictor/resolve/main/predictor.py
4.99 kB
| """Load the fine-tuned DNABERT-2 once and score DNA sequences in 500 bp windows. | |
| Used by api/app.py for both the /predict endpoint and the web page. Tokenizer settings match | |
| scripts/07_evaluate.py, so a 500 bp test window gets the same score as in | |
| results/tables/dnabert2_test_predictions.csv. | |
| """ | |
| import re | |
| import torch | |
| from transformers import AutoModelForSequenceClassification, AutoTokenizer | |
| WINDOW_BP = 500 # the model was trained on 500 bp windows | |
| MIN_BP = 50 # shorter inputs are rejected; the model has nothing to go on | |
| MAX_BP = 10_000 # per sequence, i.e. at most 20 windows | |
| MAX_WINDOWS = 100 # per request, so one request can't tie up the CPU for minutes | |
| MAX_LENGTH = 128 # tokens; same as training (~0.25 x 500 bp) | |
| THRESHOLD = 0.5 | |
| POSITIVE_CALL = "candidate G-loop" | |
| NEGATIVE_CALL = "not predicted" | |
| def clean_sequence(text: str) -> str: | |
| """Strip a FASTA header, whitespace and digits; uppercase. Raise ValueError if the result | |
| isn't a single A/C/G/T sequence of MIN_BP to MAX_BP letters.""" | |
| lines = text.strip().splitlines() | |
| headers = [line for line in lines if line.startswith(">")] | |
| if len(headers) > 1: | |
| raise ValueError("Found more than one FASTA record. Send one sequence per entry.") | |
| seq = re.sub(r"[\s\d]", "", "".join(line for line in lines if not line.startswith(">"))).upper() | |
| bad = sorted(set(seq) - set("ACGT")) | |
| if bad: | |
| raise ValueError(f"Only A, C, G and T are allowed (the model never saw other letters); " | |
| f"found: {', '.join(bad)}.") | |
| if not MIN_BP <= len(seq) <= MAX_BP: | |
| raise ValueError(f"Sequence is {len(seq)} bp; it must be {MIN_BP}-{MAX_BP} bp.") | |
| return seq | |
| def window_spans(length: int) -> list[tuple[int, int]]: | |
| """Back-to-back 500 bp windows; the last one is shifted left to end at the sequence end. | |
| Sequences of 500 bp or less are one window.""" | |
| if length <= WINDOW_BP: | |
| return [(0, length)] | |
| starts = list(range(0, length - WINDOW_BP + 1, WINDOW_BP)) | |
| if starts[-1] + WINDOW_BP < length: | |
| starts.append(length - WINDOW_BP) | |
| return [(s, s + WINDOW_BP) for s in starts] | |
| class Predictor: | |
| def __init__(self, model_dir: str): | |
| self.device = "cuda" if torch.cuda.is_available() else "cpu" | |
| self.tokenizer = AutoTokenizer.from_pretrained(model_dir, model_max_length=MAX_LENGTH, | |
| padding_side="right", use_fast=True, | |
| trust_remote_code=True) | |
| self.model = AutoModelForSequenceClassification.from_pretrained(model_dir, | |
| trust_remote_code=True) | |
| self.model.to(self.device).eval() | |
| def probabilities(self, sequences: list[str], batch_size: int = 32) -> list[float]: | |
| """P(label 1 = candidate G-loop) for each sequence, as in 07_evaluate.py.""" | |
| probs = [] | |
| with torch.no_grad(): | |
| for i in range(0, len(sequences), batch_size): | |
| batch = self.tokenizer(sequences[i:i + batch_size], return_tensors="pt", | |
| padding="longest", truncation=True, | |
| max_length=MAX_LENGTH).to(self.device) | |
| logits = self.model(**batch).logits | |
| probs += torch.softmax(logits.float(), dim=-1)[:, 1].tolist() | |
| return probs | |
| def score(self, texts: list[str]) -> list[dict]: | |
| """Clean each input, cut it into windows, and score every window in one pass.""" | |
| seqs = [clean_sequence(t) for t in texts] | |
| spans = [window_spans(len(s)) for s in seqs] | |
| n_windows = sum(len(sp) for sp in spans) | |
| if n_windows > MAX_WINDOWS: | |
| raise ValueError(f"Request needs {n_windows} windows of {WINDOW_BP} bp; " | |
| f"the limit is {MAX_WINDOWS}. Send fewer or shorter sequences.") | |
| probs = iter(self.probabilities([s[a:b] for s, sp in zip(seqs, spans) for a, b in sp])) | |
| results = [] | |
| for seq, sp in zip(seqs, spans): | |
| windows = [] | |
| for start, end in sp: | |
| p = next(probs) | |
| windows.append({"start": start + 1, "end": end, "gloop_probability": p, | |
| "call": POSITIVE_CALL if p >= THRESHOLD else NEGATIVE_CALL}) | |
| best = max(w["gloop_probability"] for w in windows) | |
| warning = None | |
| if len(seq) < WINDOW_BP: | |
| warning = (f"Sequence is {len(seq)} bp, shorter than the {WINDOW_BP} bp windows " | |
| f"the model was trained on; treat the score with caution.") | |
| results.append({"length_bp": len(seq), "max_probability": best, | |
| "call": POSITIVE_CALL if best >= THRESHOLD else NEGATIVE_CALL, | |
| "windows": windows, "warning": warning}) | |
| return results | |