Spaces:
Sleeping
Sleeping
Update prediction.py
Browse files- prediction.py +81 -126
prediction.py
CHANGED
@@ -1,133 +1,88 @@
|
|
1 |
import streamlit as st
|
2 |
import torch
|
|
|
|
|
3 |
import numpy as np
|
4 |
-
from transformers import AutoTokenizer, AutoModel
|
5 |
from rdkit import Chem
|
6 |
-
from rdkit.Chem import AllChem
|
7 |
-
from
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
encoder_layer = nn.TransformerEncoderLayer(d_model=768, nhead=8, dim_feedforward=1024, dropout=0.1, batch_first=True)
|
27 |
-
self.transformer_encoder = nn.TransformerEncoder(encoder_layer, num_layers=num_layers)
|
28 |
-
self.regression_head = nn.Sequential(
|
29 |
-
nn.Linear(emb_dim, 256), nn.ReLU(),
|
30 |
-
nn.Linear(256, 128), nn.ReLU(),
|
31 |
-
nn.Linear(128, output_dim)
|
32 |
-
)
|
33 |
-
|
34 |
-
def forward(self, x, feat):
|
35 |
-
feat_emb = self.feat_proj(feat)
|
36 |
-
stacked = torch.stack([x, feat_emb], dim=1)
|
37 |
-
encoded = self.transformer_encoder(stacked)
|
38 |
-
aggregated = encoded.mean(dim=1)
|
39 |
-
return self.regression_head(aggregated)
|
40 |
-
|
41 |
-
# Load your saved model
|
42 |
-
@st.cache_resource
|
43 |
-
def load_regression_model():
|
44 |
-
model = TransformerRegressor()
|
45 |
-
state_dict = torch.load("transformer_model.pt", map_location=torch.device("cpu"))
|
46 |
-
model.load_state_dict(state_dict)
|
47 |
-
model.eval()
|
48 |
-
return model
|
49 |
-
|
50 |
-
model = load_regression_model()
|
51 |
-
|
52 |
-
# Feature Functions
|
53 |
-
descriptor_fns = [Descriptors.MolWt, Descriptors.MolLogP, Descriptors.TPSA,
|
54 |
-
Descriptors.NumRotatableBonds, Descriptors.NumHAcceptors,
|
55 |
-
Descriptors.NumHDonors, Descriptors.RingCount,
|
56 |
-
Descriptors.FractionCSP3, Descriptors.HeavyAtomCount,
|
57 |
-
Descriptors.NHOHCount]
|
58 |
-
|
59 |
-
def fix_smiles(s):
|
60 |
-
try:
|
61 |
-
mol = Chem.MolFromSmiles(s.strip())
|
62 |
-
if mol:
|
63 |
-
return Chem.MolToSmiles(mol)
|
64 |
-
except:
|
65 |
-
return None
|
66 |
-
return None
|
67 |
|
68 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
69 |
mol = Chem.MolFromSmiles(smiles)
|
70 |
-
if
|
71 |
-
return
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
st.markdown("<h1 style='text-align: center; color: #4CAF50;'>🔬 Polymer Property Prediction</h1>", unsafe_allow_html=True)
|
99 |
-
st.markdown("<hr style='border: 1px solid #ccc;'>", unsafe_allow_html=True)
|
100 |
-
|
101 |
-
smiles_input = st.text_input("Enter SMILES Representation of Polymer")
|
102 |
-
|
103 |
-
if st.button("Predict"):
|
104 |
-
fixed = fix_smiles(smiles_input)
|
105 |
-
if not fixed:
|
106 |
-
st.error("Invalid SMILES string.")
|
107 |
else:
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
save_to_db(smiles_input, predictions)
|
133 |
-
st.success("Prediction saved successfully!")
|
|
|
1 |
import streamlit as st
|
2 |
import torch
|
3 |
+
import joblib
|
4 |
+
import pandas as pd
|
5 |
import numpy as np
|
|
|
6 |
from rdkit import Chem
|
7 |
+
from rdkit.Chem import AllChem
|
8 |
+
from transformers import AutoTokenizer, AutoModel
|
9 |
+
import os
|
10 |
+
|
11 |
+
# Load ChemBERTa model and tokenizer
|
12 |
+
tokenizer = AutoTokenizer.from_pretrained("seyonec/ChemBERTa-zinc-base-v1")
|
13 |
+
chemberta_model = AutoModel.from_pretrained("seyonec/ChemBERTa-zinc-base-v1")
|
14 |
+
|
15 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
16 |
+
chemberta_model.to(device)
|
17 |
+
chemberta_model.eval()
|
18 |
+
|
19 |
+
# Load models
|
20 |
+
model_dir = "saved_model"
|
21 |
+
model_paths = [os.path.join(model_dir, f) for f in os.listdir(model_dir) if f.endswith(".pkl") and "scaler" not in f]
|
22 |
+
models = [joblib.load(p) for p in model_paths]
|
23 |
+
|
24 |
+
# Load input and target scalers
|
25 |
+
input_scaler_path = os.path.join(model_dir, "scaler.pkl")
|
26 |
+
input_scaler = joblib.load(input_scaler_path) if os.path.exists(input_scaler_path) else None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
27 |
|
28 |
+
target_scaler_path = os.path.join(model_dir, "target_scaler.pkl")
|
29 |
+
target_scaler = joblib.load(target_scaler_path) if os.path.exists(target_scaler_path) else None
|
30 |
+
|
31 |
+
# Properties
|
32 |
+
PROPERTY_NAMES = ["Tensile Strength", "Ionization Energy", "Electron Affinity", "logP", "Refractive Index", "Molecular Weight"]
|
33 |
+
|
34 |
+
def smiles_to_fingerprint(smiles, radius=2, nBits=2048):
|
35 |
mol = Chem.MolFromSmiles(smiles)
|
36 |
+
if mol is None:
|
37 |
+
return None
|
38 |
+
return np.array(AllChem.GetMorganFingerprintAsBitVect(mol, radius, nBits))
|
39 |
+
|
40 |
+
def smiles_to_chemberta_embedding(smiles):
|
41 |
+
inputs = tokenizer(smiles, return_tensors="pt", padding=True, truncation=True).to(device)
|
42 |
+
with torch.no_grad():
|
43 |
+
outputs = chemberta_model(**inputs)
|
44 |
+
return outputs.last_hidden_state[:, 0, :].squeeze().cpu().numpy()
|
45 |
+
|
46 |
+
def create_features(smiles):
|
47 |
+
fp = smiles_to_fingerprint(smiles)
|
48 |
+
if fp is None:
|
49 |
+
return None
|
50 |
+
emb = smiles_to_chemberta_embedding(smiles)
|
51 |
+
return np.concatenate([fp, emb])
|
52 |
+
|
53 |
+
# Streamlit UI
|
54 |
+
st.title("TransPolymer Property Predictor")
|
55 |
+
user_input = st.text_input("Enter SMILES:")
|
56 |
+
|
57 |
+
if st.button("Predict"):
|
58 |
+
if not user_input.strip():
|
59 |
+
st.error("Please enter a valid SMILES string.")
|
60 |
+
else:
|
61 |
+
features = create_features(user_input)
|
62 |
+
if features is None:
|
63 |
+
st.error("Invalid SMILES format.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
64 |
else:
|
65 |
+
if input_scaler:
|
66 |
+
features = input_scaler.transform([features])
|
67 |
+
else:
|
68 |
+
features = [features]
|
69 |
+
|
70 |
+
raw_preds = np.mean([model.predict(features) for model in models], axis=0).flatten()
|
71 |
+
|
72 |
+
if target_scaler:
|
73 |
+
predictions = target_scaler.inverse_transform([raw_preds])[0]
|
74 |
+
else:
|
75 |
+
predictions = raw_preds
|
76 |
+
|
77 |
+
result_df = pd.DataFrame([predictions], columns=PROPERTY_NAMES)
|
78 |
+
result_df.insert(0, "SMILES", user_input)
|
79 |
+
|
80 |
+
st.success("Predicted Properties:")
|
81 |
+
st.dataframe(result_df.style.format(precision=4))
|
82 |
+
|
83 |
+
# Optional: save to CSV
|
84 |
+
history_path = "prediction_history.csv"
|
85 |
+
if os.path.exists(history_path):
|
86 |
+
existing = pd.read_csv(history_path)
|
87 |
+
result_df = pd.concat([existing, result_df], ignore_index=True)
|
88 |
+
result_df.to_csv(history_path, index=False)
|
|
|
|