File size: 13,485 Bytes
85c36de
942bf87
51a3749
ea9a1bf
e199881
51a3749
f0f9b27
 
f776418
f0f9b27
febb4a6
 
 
 
 
 
 
51a3749
68ded6f
febb4a6
 
 
 
 
 
 
942bf87
f776418
febb4a6
 
 
 
 
 
 
 
f0f9b27
febb4a6
adaeb14
 
febb4a6
adaeb14
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dc9275e
f776418
febb4a6
 
 
 
77584b9
febb4a6
f776418
 
 
77584b9
f776418
 
 
febb4a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0c1f1e9
febb4a6
 
 
 
0c1f1e9
febb4a6
0c1f1e9
febb4a6
 
 
 
 
 
0c1f1e9
febb4a6
 
 
 
 
 
 
 
 
 
68ded6f
febb4a6
 
 
0c1f1e9
febb4a6
0c1f1e9
 
febb4a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68ded6f
77584b9
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
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
99
100
101
102
103
104
105
106
107
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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
import gradio as gr
import joblib
import numpy as np
import pandas as pd
from propy import AAComposition, Autocorrelation, CTD, PseudoAAC
from sklearn.preprocessing import MinMaxScaler
import torch
from transformers import BertTokenizer, BertModel
from lime.lime_tabular import LimeTabularExplainer
from math import expm1
import matplotlib.pyplot as plt
import io
import base64
import os

# --- Configuration and Model Loading ---
MODEL_DIR = os.path.dirname(os.path.abspath(__file__))

# Load AMP Classifier
try:
    model = joblib.load(os.path.join(MODEL_DIR, "RF.joblib"))
    scaler = joblib.load(os.path.join(MODEL_DIR, "norm (4).joblib"))
except FileNotFoundError as e:
    raise gr.Error(f"Classifier model or scaler not found: {e}. Make sure RF.joblib and norm (4).joblib are in the {MODEL_DIR} directory.")
except Exception as e:
    raise gr.Error(f"Error loading classifier components: {e}")

# Load ProtBert
try:
    tokenizer = BertTokenizer.from_pretrained("Rostlab/prot_bert", do_lower_case=False)
    protbert_model = BertModel.from_pretrained("Rostlab/prot_bert")
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    protbert_model = protbert_model.to(device).eval()
except Exception as e:
    raise gr.Error(f"Error loading ProtBert model/tokenizer: {e}. Check internet connection or model availability.")


# Full list of selected features (as provided in the original code)
selected_features = ["_SolventAccessibilityC3", "_SecondaryStrC1", "_SecondaryStrC3", "_ChargeC1", "_PolarityC1",
    "_NormalizedVDWVC1", "_HydrophobicityC3", "_SecondaryStrT23", "_PolarizabilityD1001", "_PolarizabilityD2001",
    "_PolarabilityD3001", "_SolventAccessibilityD1001", "_SolventAccessibilityD2001", "_SolventAccessibilityD3001",
    "_SecondaryStrD1001", "_SecondaryStrD1075", "_SecondaryStrD2001", "_SecondaryStrD3001", "_ChargeD1001",
    "_ChargeD1025", "_ChargeD2001", "_ChargeD3075", "_ChargeD3100", "_PolarityD1001", "_PolarityD1050",
    "_PolarityD2001", "_PolarityD3001", "_NormalizedVDWVD1001", "_NormalizedVDWVD2001", "_NormalizedVDWVD2025",
    "_NormalizedVDWVD2050", "_NormalizedVDWVD3001", "_HydrophobicityD1001", "_HydrophobicityD2001",
    "_HydrophobicityD3001", "_HydrophobicityD3025", "A", "R", "D", "C", "E", "Q", "H", "I", "M", "P", "Y", "V",
    "AR", "AV", "RC", "RL", "RV", "CR", "CC", "CL", "CK", "EE", "EI", "EL", "HC", "IA", "IL", "IV", "LA", "LC", "LE",
    "LI", "LT", "LV", "KC", "MA", "MS", "SC", "TC", "TV", "YC", "VC", "VE", "VL", "VK", "VV",
    "MoreauBrotoAuto_FreeEnergy30", "MoranAuto_Hydrophobicity2", "MoranAuto_Hydrophobicity4",
    "GearyAuto_Hydrophobicity20", "GearyAuto_Hydrophobicity24", "GearyAuto_Hydrophobicity26",
    "GearyAuto_Hydrophobicity27", "GearyAuto_Hydrophobicity28", "GearyAuto_Hydrophobicity29",
    "GearyAuto_Hydrophobicity30", "GearyAuto_AvFlexibility22", "GearyAuto_AvFlexibility26",
    "GearyAuto_AvFlexibility27", "GearyAuto_AvFlexibility28", "GearyAuto_AvFlexibility29", "GearyAuto_AvFlexibility30",
    "GearyAuto_Polarizability22", "GearyAuto_Polarizability24", "GearyAuto_Polarizability25",
    "GearyAuto_Polarizability27", "GearyAuto_Polarizability28", "GearyAuto_Polarizability29",
    "GearyAuto_Polarizability30", "GearyAuto_FreeEnergy24", "GearyAuto_FreeEnergy25", "GearyAuto_FreeEnergy30",
    "GearyAuto_ResidueASA21", "GearyAuto_ResidueASA22", "GearyAuto_ResidueASA23", "GearyAuto_ResidueASA24",
    "GearyAuto_ResidueASA30", "GearyAuto_ResidueVol21", "GearyAuto_ResidueVol24", "GearyAuto_ResidueVol25",
    "GearyAuto_ResidueVol26", "GearyAuto_ResidueVol28", "GearyAuto_ResidueVol29", "GearyAuto_ResidueVol30",
    "GearyAuto_Steric18", "GearyAuto_Steric21", "GearyAuto_Steric26", "GearyAuto_Steric27", "GearyAuto_Steric28",
    "GearyAuto_Steric29", "GearyAuto_Steric30", "GearyAuto_Mutability23", "GearyAuto_Mutability25",
    "GearyAuto_Mutability26", "GearyAuto_Mutability27", "GearyAuto_Mutability28", "GearyAuto_Mutability29",
    "GearyAuto_Mutability30", "APAAC1", "APAAC4", "APAAC5", "APAAC6", "APAAC8", "APAAC9", "APAAC12", "APAAC13",
    "APAAC15", "APAAC18", "APAAC19", "APAAC24"]

# LIME Explainer Setup
try:
    sample_data = np.random.rand(500, len(selected_features)) # Fallback: Generate random sample data
except Exception:
    print("Warning: Could not load pre-saved sample data for LIME. Generating random sample data.")
    sample_data = np.random.rand(500, len(selected_features))

explainer = LimeTabularExplainer(
    training_data=sample_data,
    feature_names=selected_features,
    class_names=["AMP", "Non-AMP"],
    mode="classification"
)

# --- Feature Extraction Function ---
def extract_features(sequence: str) -> np.ndarray:
    cleaned_sequence = ''.join([aa for aa in sequence.upper() if aa in "ACDEFGHIKLMNPQRSTVWY"])
    if not (10 <= len(cleaned_sequence) <= 100):
        raise gr.Error(f"Invalid sequence length ({len(cleaned_sequence)}). Must be between 10 and 100 characters and contain only standard amino acids.")

    try:
        dipeptide_features = AAComposition.CalculateAADipeptideComposition(cleaned_sequence)
        ctd_features = CTD.CalculateCTD(cleaned_sequence)
        auto_features = Autocorrelation.CalculateAutoTotal(cleaned_sequence)
        pseudo_features = PseudoAAC.GetAPseudoAAC(cleaned_sequence, lamda=9)

        all_features_dict = {}
        all_features_dict.update(ctd_features)
        all_features_dict.update(dipeptide_features)
        all_features_dict.update(auto_features)
        all_features_dict.update(pseudo_features)

        feature_df_all = pd.DataFrame([all_features_dict])

        computed_features_ordered = feature_df_all.reindex(columns=selected_features, fill_value=0)
        computed_features_ordered = computed_features_ordered.fillna(0)

        normalized_array = scaler.transform(computed_features_ordered.values)

        return normalized_array
    except Exception as e:
        raise gr.Error(f"Feature extraction failed: {e}. Ensure sequence is valid and Propy dependencies are met.")

# --- MIC Prediction Function ---
def predictmic(sequence: str, selected_bacteria_keys: list) -> dict:
    cleaned_sequence = ''.join([aa for aa in sequence.upper() if aa in "ACDEFGHIKLMNPQRSTVWY"])
    if not (10 <= len(cleaned_sequence) <= 100):
        raise gr.Error(f"Invalid sequence length for MIC prediction ({len(cleaned_sequence)}). Must be between 10 and 100 characters.")

    seq_spaced = ' '.join(list(cleaned_sequence))
    try:
        tokens = tokenizer(seq_spaced, return_tensors="pt", padding='max_length', truncation=True, max_length=512)
        tokens = {k: v.to(device) for k, v in tokens.items()}
        with torch.no_grad():
            outputs = protbert_model(**tokens)
            embedding = outputs.last_hidden_state.mean(dim=1).squeeze().cpu().numpy().reshape(1, -1)
    except Exception as e:
        raise gr.Error(f"Error generating ProtBert embedding: {e}. Check sequence format or model availability.")

    bacteria_config = {
        "e_coli": {"display_name": "E.coli", "model": "coli_xgboost_model.pkl", "scaler": "coli_scaler.pkl", "pca": None},
        "p_aeruginosa": {"display_name": "P. aeruginosa", "model": "arg_xgboost_model.pkl", "scaler": "arg_scaler.pkl", "pca": None},
        "s_aureus": {"display_name": "S. aureus", "model": "aur_xgboost_model.pkl", "scaler": "aur_scaler.pkl", "pca": None},
        "k_pneumoniae": {"display_name": "K. pneumoniae", "model": "pne_mlp_model.pkl", "scaler": "pne_scaler.pkl", "pca": "pne_pca.pkl"}
    }

    mic_results = {}
    for bacterium_key in selected_bacteria_keys:
        cfg = bacteria_config.get(bacterium_key)
        if not cfg:
            mic_results[bacterium_key] = "Error: Invalid bacterium key provided."
            continue

        try:
            mic_scaler = joblib.load(os.path.join(MODEL_DIR, cfg["scaler"]))
            scaled_embedding = mic_scaler.transform(embedding)

            transformed_embedding = scaled_embedding
            if cfg["pca"]:
                mic_pca = joblib.load(os.path.join(MODEL_DIR, cfg["pca"]))
                transformed_embedding = mic_pca.transform(scaled_embedding)

            mic_model = joblib.load(os.path.join(MODEL_DIR, cfg["model"]))
            mic_log = mic_model.predict(transformed_embedding)[0]
            mic = round(expm1(mic_log), 3)
            mic_results[bacterium_key] = mic
        except FileNotFoundError as e:
            mic_results[bacterium_key] = f"Model file not found for {cfg['display_name']}: {e}"
        except Exception as e:
            mic_results[bacterium_key] = f"Prediction error for {cfg['display_name']}: {e}"
    return mic_results

# --- LIME Plot Generation Helper ---
def generate_lime_plot_base64(explanation_list: list) -> str:
    if not explanation_list:
        return ""

    fig, ax = plt.subplots(figsize=(10, 6))
    features = [item[0] for item in explanation_list]
    weights = [item[1] for item in explanation_list]

    sorted_indices = np.argsort(np.abs(weights))[::-1]
    features_sorted = [features[i] for i in sorted_indices]
    weights_sorted = [weights[i] for i in sorted_indices]

    y_pos = np.arange(len(features_sorted))
    colors = ['green' if w > 0 else 'red' for w in weights_sorted]
    ax.barh(y_pos, weights_sorted, align='center', color=colors)
    ax.set_yticks(y_pos)
    ax.set_yticklabels(features_sorted, fontsize=10)
    ax.invert_yaxis()
    ax.set_xlabel('Contribution to Prediction (LIME Weight)', fontsize=12)
    ax.set_title('Top Features Influencing Prediction (LIME)', fontsize=14)
    ax.axvline(0, color='grey', linestyle='--', linewidth=0.8)
    plt.grid(axis='x', linestyle=':', alpha=0.7)

    buf = io.BytesIO()
    plt.savefig(buf, format='png', bbox_inches='tight', dpi=150)
    buf.seek(0)
    image_base64 = base64.b64encode(buf.getvalue()).decode('utf-8')
    plt.close(fig)
    return image_base64

# --- Gradio API Endpoints ---

def classify_and_interpret_amp(sequence: str) -> dict:
    try:
        features = extract_features(sequence)

        prediction_class_idx = model.predict(features)[0]
        probabilities = model.predict_proba(features)[0]

        amp_label = "AMP (Positive)" if prediction_class_idx == 0 else "Non-AMP"
        confidence = probabilities[prediction_class_idx]

        explanation = explainer.explain_instance(
            data_row=features[0],
            predict_fn=model.predict_proba,
            num_features=10
        )

        top_features = []
        for feat_str, weight in explanation.as_list():
            parts = feat_str.split(" ", 1)
            feature_name = parts[0]
            condition = parts[1] if len(parts) > 1 else ""

            top_features.append({
                "feature": feature_name,
                "condition": condition.strip(),
                "value": round(weight, 4)
            })

        lime_plot_base64_str = generate_lime_plot_base64(explanation.as_list())

        return {
            "label": amp_label,
            "confidence": float(confidence),
            "shap_plot_base64": lime_plot_base64_str,
            "top_features": top_features
        }

    except gr.Error as e:
        raise e
    except Exception as e:
        raise gr.Error(f"An unexpected error occurred during AMP classification: {e}")

def get_mic_predictions_api(sequence: str, selected_bacteria_keys: list) -> dict:
    try:
        mic_results = predictmic(sequence, selected_bacteria_keys)
        return mic_results
    except gr.Error as e:
        raise e
    except Exception as e:
        raise gr.Error(f"An unexpected error occurred during MIC prediction API call: {e}")

# --- Gradio Interface Definition ---
with gr.Blocks() as demo:
    gr.Markdown("# EPIC-AMP Platform Backend API")
    gr.Markdown("This Gradio application provides the backend services for the EPIC-AMP frontend.")

    with gr.Tab("AMP Classification & Interpretability API"):
        gr.Markdown("### `/predict` Endpoint (AMP Classification, Confidence, LIME Plot, Top Features)")
        gr.Markdown("Input an amino acid sequence (10-100 AAs) to get classification details.")
        sequence_input_amp = gr.Textbox(label="Amino Acid Sequence", lines=5, placeholder="Enter sequence here...")
        amp_api_output = gr.Json(label="AMP Prediction Details JSON Output")
        gr.Button("Test Classification").click(
            fn=classify_and_interpret_amp,
            inputs=[sequence_input_amp],
            outputs=[amp_api_output],
            api_name="predict"
        )

    with gr.Tab("MIC Prediction API"):
        gr.Markdown("### `/predict_mic` Endpoint (MIC Values)")
        gr.Markdown("Input an amino acid sequence (only if classified as AMP) and select bacteria to get predicted MIC values.")
        sequence_input_mic = gr.Textbox(label="Amino Acid Sequence", lines=5, placeholder="Enter AMP sequence for MIC prediction...")
        mic_bacteria_checkboxes = gr.CheckboxGroup(
            choices=["e_coli", "p_aeruginosa", "s_aureus", "k_pneumoniae"],
            label="Select Bacteria for MIC Prediction (keys for backend)"
        )
        mic_api_output = gr.Json(label="MIC Prediction JSON Output")
        gr.Button("Test MIC Prediction").click(
            fn=get_mic_predictions_api,
            inputs=[sequence_input_mic, mic_bacteria_checkboxes],
            outputs=[mic_api_output],
            api_name="predict_mic"
        )

# Corrected launch command: removed 'enable_queue'
demo.launch(share=True, show_api=True)