File size: 14,423 Bytes
7af26d8
b570d12
7af26d8
 
b570d12
 
 
 
 
 
 
 
 
 
 
 
 
7af26d8
 
 
b570d12
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7af26d8
 
 
b570d12
 
 
 
 
 
 
 
 
 
 
 
 
 
7af26d8
b570d12
7af26d8
 
 
 
 
 
 
b570d12
 
 
7af26d8
b570d12
 
 
 
7af26d8
b570d12
7af26d8
 
 
b570d12
7af26d8
b570d12
 
 
7af26d8
 
 
 
 
 
 
 
 
 
 
 
 
 
b570d12
7af26d8
 
 
 
 
 
 
 
 
 
 
 
 
 
b570d12
 
7af26d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b570d12
7af26d8
b570d12
 
7af26d8
 
 
b570d12
7af26d8
12a8aeb
 
45b84c7
 
12a8aeb
 
45b84c7
 
12a8aeb
45b84c7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12a8aeb
 
 
45b84c7
 
12a8aeb
45b84c7
 
 
 
 
12a8aeb
 
 
 
 
 
 
45b84c7
 
 
 
12a8aeb
8cc7c11
 
 
 
 
 
 
 
 
12a8aeb
8cc7c11
45b84c7
 
 
12a8aeb
 
45b84c7
8cc7c11
 
12a8aeb
 
 
8cc7c11
45b84c7
12a8aeb
 
45b84c7
 
12a8aeb
 
45b84c7
12a8aeb
 
45b84c7
 
12a8aeb
45b84c7
 
 
 
 
 
12a8aeb
8cc7c11
 
 
2ed0333
 
 
7af26d8
12a8aeb
 
45b84c7
 
7af26d8
 
 
 
 
 
2ed0333
b570d12
2ed0333
 
 
 
 
 
 
b570d12
 
 
 
4433bc8
7af26d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b570d12
 
 
 
 
 
 
7af26d8
b570d12
 
 
 
 
 
 
 
 
 
 
 
7af26d8
b570d12
 
 
 
 
 
 
 
 
7af26d8
b570d12
 
7af26d8
63e3118
 
 
 
 
 
 
 
 
 
 
 
 
b570d12
7af26d8
 
b570d12
7af26d8
b570d12
7af26d8
 
 
b570d12
 
 
 
7af26d8
b570d12
 
 
 
 
7af26d8
b570d12
 
7af26d8
b570d12
 
7af26d8
b570d12
7af26d8
b570d12
7af26d8
b570d12
 
 
7af26d8
b570d12
 
 
7af26d8
 
 
 
b570d12
 
 
7af26d8
 
b570d12
 
 
 
 
 
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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
"""SugarKi public UI — sugar-chemistry Ki predictor (frontend, MWBC/sugarki).

Pretty Gradio interface that calls the SugarKi backend Space (private,
ZeroGPU). No model weights here — just the UI.
"""
from __future__ import annotations

import os
from gradio_client import Client
import gradio as gr

BACKEND = os.environ.get("SUGARKI_BACKEND", "Umesh1608/sugarki-backend")
HF_TOKEN = os.environ.get("HF_TOKEN")

if not HF_TOKEN:
    print("WARNING: HF_TOKEN not set; backend calls will fail if backend is private.")

# ----------------------------------------------------------------------
# Curated example library
# ----------------------------------------------------------------------

SUGAR_INHIBITORS = {
    "D-mannitol":            "OCC(O)C(O)C(O)C(O)CO",
    "D-fructose":            "OCC(=O)C(O)C(O)C(O)CO",
    "D-sorbitol":            "OCC(O)C(O)C(O)C(O)CO",
    "D-glucose":             "OCC(O)C(O)C(O)C(O)C=O",
    "D-galactose":           "OCC(O)C(O)C(O)C(O)C=O",
    "D-mannose":             "OCC(O)C(O)C(O)C(O)C=O",
    "Xylitol":               "OCC(O)C(O)C(O)CO",
    "Glycerol":              "OCC(O)CO",
    "Glucose-6-phosphate":   "OC(=O)CC(O)C(O)C(O)COP(O)(O)=O",
    "Fructose-1,6-bisphos.": "O=P(O)(O)OCC(O)(C(O)C(O)COP(O)(O)=O)O",
    "Sucrose":               "OCC1OC(OC2(COC1O)OC(CO)C(O)C2O)C(O)C(O)C1O",
    "Trehalose":             "OCC1OC(OC2OC(CO)C(O)C(O)C2O)C(O)C(O)C1O",
    "Custom (paste SMILES)": "",
}

EXAMPLE_MDH_WT = (
    "MGSSHHHHHHSSGLVPRGSHMVKLTLSALPALSPAVAVPAYDPRAQIPGIVHFGVGAFHRSHQAMYLDRL"
    "LNSGRGAGWAICGVGVLPQDARMRDVLAEQDHLYTLVTRSPDGQAQARVIGAIVEFLFAPDDPERVLERL"
    "ADPTTRIVSLTVTEGGYSVSNATGEFDPTPPDIAHDLTPGAVPRTFFGFLTEGLRRRRERGLPPFTVVSC"
    "DNMPGNGEVTRRALTAFARLQDPELGDWIAHNVAFPNSMVDRITPATTEQDRQDIAAAYGIEDAWPVVAE"
    "SFAQWVLEDRFTQGRPALETVGVQVVSDVEPYELMKLRLLNASHQALAYLGLLAGYRFVHEVCQDPLFAR"
    "FLLDYMTQEATPTLRPVPGIDLGAYRRELIARFSNPAIRDPLTRLTVDSSERIPKFLLPVIRDQLARGGE"
    "LARCALVIASWRAYLATVLEEGSASFPDQHAQALAEAVRRDAQQPGAFLDLEAVFGELGRNARFRTAYLS"
    "AWESLRRQGPLGAMRALMGEESSPSNVTSLSGR"
)

EXAMPLES = [
    [EXAMPLE_MDH_WT, "D-mannitol", "substrate", "OCC(=O)C(O)C(O)C(O)CO"],
]

# ----------------------------------------------------------------------
# Backend client
# ----------------------------------------------------------------------

_client = None
def _backend():
    global _client
    if _client is None:
        kwargs = {}
        if HF_TOKEN:
            kwargs["hf_token"] = HF_TOKEN
        _client = Client(BACKEND, **kwargs)
    return _client


def predict(sequence, inhibitor_choice, inhibitor_custom, inh_type, substrate_smiles):
    if not sequence or not sequence.strip():
        return "### ⚠️ Please paste an enzyme sequence", None, "", None

    smiles = (
        inhibitor_custom.strip()
        if inhibitor_choice == "Custom (paste SMILES)"
        else SUGAR_INHIBITORS.get(inhibitor_choice, "")
    )
    if not smiles:
        return "### ⚠️ Inhibitor SMILES is empty", None, "", None

    try:
        result = _backend().predict(
            sequence.strip(), smiles, inh_type,
            substrate_smiles.strip() if substrate_smiles else "",
            api_name="/predict_ki",
        )
    except Exception as e:
        return f"### ❌ Backend error\n```\n{e}\n```", None, "", None

    if isinstance(result, dict) and result.get("error"):
        msg = result.get("error_message", str(result))
        return f"### ❌ Prediction error\n```\n{msg}\n```", None, "", result

    # Headline card
    ki_mm = result.get("Ki_mM")
    ki_um = result.get("Ki_uM")
    log_ki = result.get("log10_Ki_mM")
    inh_used = result.get("inh_type_used", "?")
    his_stripped = "✓ stripped" if result.get("his_tag_stripped") else "—"
    sigma = result.get("ensemble_std_log10", "?")

    # Format Ki nicely with appropriate units
    if ki_mm is not None:
        if ki_mm < 0.001:
            ki_display = f"**{ki_mm * 1e6:.2f} nM**"
        elif ki_mm < 1:
            ki_display = f"**{ki_um:.1f} µM**"
        else:
            ki_display = f"**{ki_mm:.3f} mM**"
    else:
        ki_display = "—"

    summary_md = f"""
### 🧪 Predicted Ki: {ki_display}

| | |
|---|---|
| **Ki (mM)** | {ki_mm:.4f} |
| **Ki (µM)** | {ki_um:,.1f} |
| **log₁₀(Ki / mM)** | {log_ki:+.3f} |
| **Inhibition mode** | `{inh_used}` |
| **His-tag prefix** | {his_stripped} |
| **Ensemble σ across 5 modes** | {sigma} |

> **Model:** {result.get('model_version', 'SugarKi')}
"""

    # Per-mode table
    mode_mm = result.get("mode_predictions_mM", {})
    mode_log = result.get("mode_predictions_log10", {})

    mode_rows = []
    for mode in ["external", "product", "substrate", "product_or_substrate", "unknown"]:
        if mode in mode_mm:
            mm = mode_mm[mode]
            um = mm * 1000
            log = mode_log.get(mode, 0)
            highlight = " ⭐" if mode == inh_used else ""
            mode_rows.append([
                f"{mode.replace('_', ' ').title()}{highlight}",
                f"{log:+.3f}",
                f"{mm:.3f}",
                f"{um:,.1f}",
            ])

    notes = result.get("notes", "")
    notes_md = f"\n\n**ℹ️ Notes:** _{notes}_\n" if notes else ""

    return summary_md, mode_rows, notes_md, result


# ----------------------------------------------------------------------
# UI — uses theme-aware colors so text stays readable on any background
# ----------------------------------------------------------------------

CSS = """
/* Force a consistent DARK theme regardless of system preference.
   Dark backgrounds with light text — both set together so contrast is guaranteed. */

html, body, .gradio-container, .gradio-container .main {
    background: #0b1220 !important;
    color: #f3f4f6 !important;
}

/* All Gradio block-level containers — force dark backgrounds */
.gradio-container .block,
.gradio-container .form,
.gradio-container .panel,
.gradio-container .gr-box,
.gradio-container .gr-block,
.gradio-container .gr-form,
.gradio-container .gr-panel,
.gradio-container fieldset,
.gradio-container details,
.gradio-container summary,
.gradio-container .label-wrap,
.gradio-container .wrap,
.gradio-container .accordion,
.gradio-container .gr-accordion,
.gradio-container .prose,
.gradio-container .markdown,
.gradio-container .markdown-body {
    background-color: #111827 !important;
    color: #f3f4f6 !important;
    border-color: #374151 !important;
}

/* Inputs — slightly lighter slate so they stand out from the page */
.gradio-container input,
.gradio-container textarea,
.gradio-container select,
.gradio-container .gr-input,
.gradio-container .gr-textarea {
    background-color: #1f2937 !important;
    color: #f9fafb !important;
    border-color: #374151 !important;
}
.gradio-container input::placeholder,
.gradio-container textarea::placeholder {
    color: #9ca3af !important;
}

/* All text */
.gradio-container, .gradio-container * {
    color: #f3f4f6 !important;
}
.gradio-container h1,
.gradio-container h2,
.gradio-container h3,
.gradio-container h4,
.gradio-container h5,
.gradio-container h6,
.gradio-container strong,
.gradio-container b {
    color: #ffffff !important;
}

/* Tables */
.gradio-container table {
    background-color: #111827 !important;
    border-color: #374151 !important;
}
.gradio-container table th,
.gradio-container table td {
    color: #e5e7eb !important;
    background-color: #111827 !important;
    border-color: #374151 !important;
}
.gradio-container table th {
    background-color: #1f2937 !important;
    color: #ffffff !important;
}

/* Links and inline code — bright accent colors that pop on dark */
.gradio-container a { color: #93c5fd !important; }
.gradio-container code {
    background-color: #1f2937 !important;
    color: #fbcfe8 !important;
}

/* Primary buttons — keep vivid blue with white text */
.gradio-container button.primary,
.gradio-container button.lg.primary,
.gradio-container .primary,
.gradio-container .primary * {
    background: #2563eb !important;
    color: #ffffff !important;
    border-color: #1d4ed8 !important;
}

/* Title block layout */
.title-block { text-align: center; padding: 1em 0; margin-bottom: 0.5em; }

/* Ki result card */
.ki-card {
    background: #111827 !important;
    border: 1px solid #374151 !important;
    border-radius: 8px !important;
    padding: 1em 1.5em !important;
}
"""

with gr.Blocks(title="SugarKi — Ki prediction", theme=gr.themes.Default(), css=CSS) as demo:

    # ----- header -----
    gr.Markdown(
        """
        <div align='center'>

        # 🧪 SugarKi

        ##### Family-specialized Ki prediction for sugar-chemistry enzymes
        ##### polyol DHs · sugar kinases · glycosidases · phosphatases · aldolases · isomerases · phosphomutases

        </div>
        """
    )

    # ----- about + inputs explainer -----
    with gr.Accordion("📐 How does SugarKi work?", open=True):
        gr.Markdown(
            """
            SugarKi takes an **enzyme sequence** and an **inhibitor SMILES** and predicts the
            inhibition constant **Ki** specifically for sugar-chemistry enzymes — where current
            SOTA models like CatPred fail catastrophically (R² = −0.95 on monosaccharide
            inhibitors).

            **Inputs**

            - `Enzyme sequence` — paste any sugar-family enzyme (His-tag auto-stripped). Best for EC 1.1.1.x, 2.7.1.x, 3.1.3.x, 3.2.1.x, 4.1.2.x, 5.3.1.x, 5.4.2.x.
            - `Inhibitor SMILES` — SMILES of the small molecule whose Ki you want.
            - `Inhibition type` — choose `product` for product inhibition (e.g., mannitol on mannitol DH), `substrate` for substrate-mode at high [S], or `auto` for an ensemble across all 5 modes.
            - `Substrate SMILES` (optional) — native substrate, helps disambiguate product-inhibition cases.

            ### Validation

            - WT MDH-006 (mannitol DH) + D-mannitol → predicted **11.78 mM** in substrate mode vs literature **12 mM** (1.8% error).
            - Sugar-Ki test set R² = **0.702** vs CatPred 0.243 / SELFprot 0.623.
            - Typical MAE ≈ 0.6 log units; relative ranking is more reliable than absolute Ki values.
            """
        )

    # ----- input + output -----
    with gr.Row():
        with gr.Column(scale=3):
            seq_in = gr.Textbox(
                label="Enzyme amino acid sequence",
                placeholder="MGSSHHHHHH... or just the catalytic domain (30–1000 aa)",
                lines=10,
                value=EXAMPLE_MDH_WT,
                show_copy_button=True,
            )
            with gr.Row():
                inh_choice = gr.Dropdown(
                    choices=list(SUGAR_INHIBITORS.keys()),
                    value="D-mannitol",
                    label="Inhibitor",
                )
                inh_type = gr.Dropdown(
                    ["auto", "external", "product", "substrate",
                     "product_or_substrate", "unknown"],
                    value="auto",
                    label="Inhibition type",
                    info="`product` for product inhibition; `substrate` for substrate inhibition at high [S]",
                )
            inh_custom = gr.Textbox(
                label="Custom inhibitor SMILES (only used if inhibitor = 'Custom (paste SMILES)')",
                value="",
            )
            sub_smiles = gr.Textbox(
                label="Native substrate SMILES (optional, helps product-inhibition prediction)",
                value="",
            )
            btn = gr.Button("🧬 Predict Ki", variant="primary", size="lg")

        with gr.Column(scale=2):
            summary_out = gr.Markdown(elem_classes=["ki-card"])
            gr.Markdown(
                """
                **What each inhibition mode means**

                - **External** — small-molecule inhibitor unrelated to substrate or product (classical competitive/non-competitive ligand).
                - **Product** — the inhibitor IS the reaction product (product inhibition; e.g., mannitol on mannitol dehydrogenase).
                - **Substrate** — the inhibitor IS the native substrate; binding becomes inhibitory at high [S] (substrate inhibition).
                - **Product or Substrate** — chemically ambiguous: the molecule could play either role for this enzyme.
                - **Unknown** — mode not annotated; treat as a generic ensemble estimate.

                The ⭐ row is the mode you selected (or the auto-resolved default).
                """
            )
            mode_table = gr.Dataframe(
                headers=["Inhibition mode", "log₁₀(Ki/mM)", "Ki (mM)", "Ki (µM)"],
                label="Per-mode predictions (across 5 inhibition assumptions)",
                wrap=True,
                interactive=False,
            )
            notes_out = gr.Markdown()
            with gr.Accordion("Raw JSON response", open=False):
                raw_out = gr.JSON()

    btn.click(
        predict,
        inputs=[seq_in, inh_choice, inh_custom, inh_type, sub_smiles],
        outputs=[summary_out, mode_table, notes_out, raw_out],
    )

    gr.Examples(
        examples=EXAMPLES,
        inputs=[seq_in, inh_choice, inh_type, sub_smiles],
        label="Example: MDH-006 WT + D-mannitol (substrate-mode)",
    )

    # ----- footer -----
    gr.Markdown(
        """
        ---

        ### How SugarKi compares to existing Ki predictors

        | Model | Sugar-chemistry Ki | General Ki |
        |---|---|---|
        | CatPred zero-shot | R² = 0.243 (catastrophic on monosaccharides/polyols) | R² = 0.578 |
        | SELFprot zero-shot | R² = 0.623 | R² = 0.314 |
        | **SugarKi specialist** | **R² = 0.702** | (router falls back to CatPred) |

        ### Limitations

        - Test MAE ~0.6 log units; **rankings** more reliable than **absolute** values.
        - Best on EC families 1.1.1.x / 2.7.1.x / 3.2.1.x / 3.1.3.x / 4.1.2.x / 5.3.1.x / 5.4.2.x.
        - Allosteric inhibition not separately modeled.
        - First call cold-starts ~30 s while ESMFold loads; subsequent calls re-use cached structures.

        ### Citation

        Paper in preparation. Hosted by [MWBC](https://huggingface.co/MWBC), backed by
        a private SugarKi inference Space ([Umesh1608](https://huggingface.co/Umesh1608)).
        """
    )


if __name__ == "__main__":
    demo.launch()