brent10070's picture
Upload app.py
cd0af83 verified
Raw History Blame Contribute Delete
3.31 kB
import gradio as gr
import torch
import torch.nn as nn
import numpy as np
SEQ_LEN = 70
AA_LIST = list('AGILMPVFWYCNSTQDEHKR')
AA_TO_IDX = {aa: i for i, aa in enumerate(AA_LIST)}
def seq_to_onehot(seq, max_len=SEQ_LEN):
onehot = np.zeros((20, max_len), dtype=np.float32)
for i, char in enumerate(seq[:max_len]):
if char in AA_TO_IDX:
onehot[AA_TO_IDX[char], i] = 1.0
return onehot
## Model
class CNNModel(nn.Module):
def __init__(self, num_classes=2, input_channels=20, seq_len=70):
super(CNNModel, self).__init__()
self.features = nn.Sequential(
nn.Conv1d(in_channels=input_channels, out_channels=64, kernel_size=9, padding=4),
nn.BatchNorm1d(64),
nn.ReLU(),
nn.MaxPool1d(kernel_size=2),
nn.Conv1d(in_channels=64, out_channels=128, kernel_size=5, padding=2),
nn.BatchNorm1d(128),
nn.ReLU(),
nn.MaxPool1d(kernel_size=2),
nn.Conv1d(in_channels=128, out_channels=256, kernel_size=3, padding=1),
nn.BatchNorm1d(256),
nn.ReLU(),
nn.MaxPool1d(kernel_size=2)
)
self._to_linear = self._calculate_flatten_size(input_channels, seq_len)
self.classifier = nn.Sequential(
nn.Linear(self._to_linear, 256),
nn.ReLU(),
nn.Dropout(0.5),
nn.Linear(256, 128),
nn.ReLU(),
nn.Dropout(0.5),
nn.Linear(128, num_classes)
)
def _calculate_flatten_size(self, input_channels, seq_len):
with torch.no_grad():
x = torch.zeros(1, input_channels, seq_len)
x = self.features(x)
return x.view(1, -1).size(1)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.classifier(x)
return x
# ==========================================
model = CNNModel(num_classes=2)
model.load_state_dict(torch.load("best_model_weights.pth", map_location=torch.device('cpu')))
model.eval()
def predict_peptide(sequence):
clean_seq = sequence.strip().upper()
if len(clean_seq) == 0:
return "Error: Please enter a valid sequence."
seq_oh = seq_to_onehot(clean_seq)
input_tensor = torch.tensor(seq_oh).unsqueeze(0)
# Model prediction
with torch.no_grad():
outputs = model(input_tensor)
probs = torch.nn.functional.softmax(outputs, dim=1)
positive_prob = probs[0, 1].item()
return f"{positive_prob:.2%}"
# ==========================================
# Gradio
demo = gr.Interface(
fn=predict_peptide,
inputs=gr.Textbox(
lines=2,
placeholder="e.g., MAASVATAGSV... (Enter up to 70 N-terminal amino acids)",
label="Amino Acid Sequence"
),
outputs=gr.Label(label="Probability of being a Plastid Transit Peptide"),
title="PlastidTP: Binary classification model for Plastid Transit Peptides (pTPs)",
description="This tool uses a Deep Convolutional Neural Network to predict plastid transit peptides based on the N-terminal sequence. Sequences longer than 70 residues will be automatically truncated."
)
if __name__ == "__main__":
demo.launch()