File size: 12,049 Bytes
5f01b59
 
 
 
d312601
5f01b59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2269b3e
d312601
678d876
303d098
5f01b59
 
 
 
 
 
 
 
 
 
 
 
 
 
303d098
 
 
 
5f01b59
 
 
 
303d098
5f01b59
8ab6363
5f01b59
 
 
 
 
 
 
525adca
5f01b59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
678d876
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5f01b59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44c6b49
 
 
 
 
 
 
 
 
5f01b59
 
 
3f65edd
44c6b49
5f01b59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3b1639a
5f01b59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
678d876
 
 
5f01b59
 
 
 
 
678d876
5f01b59
 
678d876
 
 
 
 
 
 
5f01b59
 
 
 
 
 
 
635289f
 
 
 
 
 
 
5f01b59
 
 
 
678d876
5f01b59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
635289f
678d876
 
635289f
 
 
 
 
 
 
61de904
678d876
 
 
 
635289f
678d876
 
635289f
 
 
 
678d876
 
635289f
678d876
 
635289f
 
 
 
 
 
 
 
678d876
 
 
5f01b59
678d876
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5f01b59
678d876
5f01b59
 
678d876
5f01b59
678d876
5f01b59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
678d876
 
 
635289f
678d876
 
5f01b59
 
678d876
 
5f01b59
 
 
 
 
 
 
 
678d876
 
5f01b59
 
 
 
 
 
 
 
 
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
"""
BloomOne β€” HuggingFace Space Frontend.

A Gradio chatbot UI that connects to the Modal-hosted BloomOne backend
(Gemini 2.5 Flash + pipeline tools) via REST API.

The backend handles LLM inference and pipeline tool execution.
This frontend is a lightweight chat interface.
"""

import os
import json

import gradio as gr
import httpx

# ── Configuration ────────────────────────────────────────────────────────────

BACKEND_URL = os.environ.get(
    "BLOOMONE_BACKEND_URL",
    "https://thomas-15--bloomone-chatbot.modal.run",
)
API_CHAT_URL = f"{BACKEND_URL}/v1/chat"
API_HEALTH_URL = f"{BACKEND_URL}/v1/health"
API_UPLOAD_URL = f"{BACKEND_URL}/v1/upload"
BLOOMONE_API_KEY = os.environ.get("BLOOMONE_API_KEY", "")

# Timeout: pipeline stages can take minutes (especially binding prediction)
API_TIMEOUT = httpx.Timeout(300.0, connect=30.0)


# ── API Client ───────────────────────────────────────────────────────────────


def call_backend(messages: list[dict]) -> dict:
    """
    Call the Modal-hosted BloomOne chat API.

    Returns dict with: response, status_updates, updated_messages
    """
    headers = {}
    if BLOOMONE_API_KEY:
        headers["Authorization"] = f"Bearer {BLOOMONE_API_KEY}"

    try:
        resp = httpx.post(
            API_CHAT_URL,
            json={"messages": messages},
            headers=headers,
            timeout=API_TIMEOUT,
            follow_redirects=True,
        )
        resp.raise_for_status()
        return resp.json()
    except httpx.ConnectError:
        return {
            "response": (
                "πŸ”„ **Backend is warming up** (cold start ~30-60s).\n\n"
                "The GPU container is loading Gemma 4 27B. "
                "Please try again in about a minute."
            ),
            "status_updates": [],
            "updated_messages": messages,
        }
    except httpx.TimeoutException:
        return {
            "response": (
                "⏰ **Request timed out.**\n\n"
                "The pipeline stage may still be running. "
                "Try again or ask for a simpler query first."
            ),
            "status_updates": [],
            "updated_messages": messages,
        }
    except Exception as e:
        return {
            "response": f"❌ **Backend error:** {str(e)}",
            "status_updates": [],
            "updated_messages": messages,
        }


def upload_to_backend(file_path: str) -> dict:
    """
    Upload a file to the Modal backend's /v1/upload endpoint.

    Returns dict with: path (on Modal volume), filename, size_bytes
    """
    headers = {}
    if BLOOMONE_API_KEY:
        headers["Authorization"] = f"Bearer {BLOOMONE_API_KEY}"

    try:
        import pathlib
        filename = pathlib.Path(file_path).name
        with open(file_path, "rb") as f:
            resp = httpx.post(
                API_UPLOAD_URL,
                files={"file": (filename, f)},
                headers=headers,
                timeout=API_TIMEOUT,
                follow_redirects=True,
            )
        resp.raise_for_status()
        return resp.json()
    except Exception as e:
        return {"error": str(e)}


# ── Gradio Interface ─────────────────────────────────────────────────────────

CUSTOM_CSS = """
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');

* { font-family: 'Inter', sans-serif !important; }

.gradio-container {
    max-width: 900px !important;
    margin: 0 auto !important;
}

.header-section {
    text-align: center;
    padding: 24px 16px 8px;
    background: linear-gradient(135deg, #0f0c29 0%, #302b63 50%, #24243e 100%);
    border-radius: 16px;
    margin-bottom: 16px;
    color: white;
}
.header-section h1 { color: white !important; font-size: 2.2em !important; }
.header-section h3 { color: #b8b8d0 !important; font-weight: 400 !important; }
.header-section p { color: #9090b0 !important; }

.disclaimer-bar {
    font-size: 0.78em;
    color: #888;
    text-align: center;
    padding: 6px 0;
    border-top: 1px solid rgba(255,255,255,0.05);
}

.status-chip {
    display: inline-block;
    padding: 2px 10px;
    border-radius: 12px;
    font-size: 0.8em;
    margin: 2px 4px;
}

.upload-status p {
    font-size: 0.85em;
    padding: 6px 12px;
    background: rgba(34, 197, 94, 0.08);
    border: 1px solid rgba(34, 197, 94, 0.2);
    border-radius: 8px;
    margin: 4px 0;
}

footer { display: none !important; }
"""



with gr.Blocks(
    title="BloomOne β€” AI Neoantigen Vaccine Design",
    theme=gr.themes.Soft(),
    css=CUSTOM_CSS,
) as demo:

    # ── Header ───────────────────────────────────────────────────────
    gr.Markdown(
        """
        <div class="header-section">

        # 🧬 BloomOne

        ### Personalized Neoantigen mRNA Vaccine Pipeline

        Powered by **Gemma 4 31B** on Modal β€” ask me to design a
        personalized mRNA vaccine from tumor mutations.

        </div>
        """,
    )

    # ── Chat ─────────────────────────────────────────────────────────

    chatbot = gr.Chatbot(
        type="messages",
        height=500,
        show_label=False,
        show_copy_button=True,
        avatar_images=(None, "🧬"),
        placeholder=(
            "πŸ’‘ **Try asking:**\n\n"
            "β€’ *Run the neoantigen pipeline for TCGA-BF-A3DL-01*\n"
            "β€’ *What data do you need to design a neoantigen vaccine?*\n"
            "β€’ *Explain the pipeline stages*"
        ),
    )

    # Full OpenAI message history (persists tool calls across turns)
    full_history = gr.State([])

    # Track uploaded file path on Modal volume
    uploaded_file_path = gr.State(None)

    with gr.Row():
        msg = gr.Textbox(
            placeholder="Describe your neoantigen analysis...",
            show_label=False,
            container=False,
            scale=7,
            autofocus=True,
        )
        file_upload = gr.File(
            label="Upload MAF/VCF",
            file_types=[".maf", ".vcf", ".tsv", ".csv", ".txt"],
            file_count="single",
            scale=2,
            min_width=120,
        )
        send_btn = gr.Button(
            "Send",
            variant="primary",
            scale=1,
            min_width=80,
        )

    # Upload status indicator
    upload_status = gr.Markdown(
        "",
        elem_classes=["upload-status"],
        visible=False,
    )

    gr.Markdown(
        '<p class="disclaimer-bar">'
        "⚠️ All outputs are for <strong>RESEARCH USE ONLY</strong>. "
        "Not validated for clinical use. "
        "Backend: Gemma 4 31B on Modal."
        "</p>"
    )

    # ── Examples ─────────────────────────────────────────────────────

    gr.Examples(
        examples=[
            "Run the neoantigen vaccine pipeline for melanoma case "
            "TCGA-BF-A3DL-01 with HLA-A*02:01,HLA-B*07:02,HLA-C*07:01",
            "What data do you need to design a neoantigen vaccine?",
            "Explain the 7 pipeline stages",
        ],
        inputs=msg,
    )

    # ── Event Handlers ───────────────────────────────────────────────

    def handle_file_upload(file, current_path, progress=gr.Progress()):
        """Upload file to Modal backend and return the volume path."""
        if file is None:
            return current_path, gr.update(), gr.update(visible=False)

        import pathlib
        file_size = pathlib.Path(file).stat().st_size
        size_mb = file_size / (1024 * 1024)
        filename = pathlib.Path(file).name

        progress(0, desc=f"πŸ“€ Forwarding {filename} ({size_mb:.1f} MB) to backend...")

        result = upload_to_backend(file)

        if "error" in result:
            progress(1.0, desc="❌ Upload failed")
            return current_path, gr.update(
                value=None,
                label="Upload MAF/VCF",
            ), gr.update(
                value=f"❌ Upload failed: {result['error']}",
                visible=True,
            )

        progress(1.0, desc="βœ… Done!")
        return result["path"], gr.update(
            value=None,
            label="Upload MAF/VCF",
        ), gr.update(
            value=(
                f"βœ… **Uploaded:** `{result['filename']}` "
                f"({result.get('size_bytes', 0) / (1024*1024):.1f} MB) β€” "
                f"ready to use in chat"
            ),
            visible=True,
        )

    def user_submit(message, display_history, openai_messages, file_path):
        """Show user message immediately and clear input."""
        if not message.strip() and not file_path:
            return "", display_history, openai_messages, file_path

        content = message.strip()
        if file_path:
            file_notice = f"[User uploaded a MAF file to: {file_path}]"
            if content:
                content = f"{file_notice}\n\n{content}"
            else:
                content = (
                    f"{file_notice}\n\n"
                    "I've uploaded my MAF file. "
                    "Please run the pipeline with it."
                )

        display_history = list(display_history) + [
            {"role": "user", "content": content}
        ]
        openai_messages = list(openai_messages) + [
            {"role": "user", "content": content}
        ]
        return "", display_history, openai_messages, None

    def bot_respond(display_history, openai_messages):
        """Call the Modal backend and display the response."""
        # Show "thinking" state
        yield (
            display_history
            + [{"role": "assistant", "content": "πŸ”„ *Thinking...*"}],
            openai_messages,
        )

        # Call backend API
        result = call_backend(openai_messages)

        # Build response with status updates
        response_text = ""
        if result.get("status_updates"):
            response_text = "\n".join(result["status_updates"])
            response_text += "\n\n---\n\n"
        response_text += result.get("response", "")

        # Update state
        updated_messages = result.get("updated_messages", openai_messages)

        yield (
            display_history
            + [{"role": "assistant", "content": response_text}],
            updated_messages,
        )

    # ── Wire Events ──────────────────────────────────────────────────

    file_upload.change(
        handle_file_upload,
        inputs=[file_upload, uploaded_file_path],
        outputs=[uploaded_file_path, file_upload, upload_status],
    )

    msg.submit(
        user_submit,
        inputs=[msg, chatbot, full_history, uploaded_file_path],
        outputs=[msg, chatbot, full_history, uploaded_file_path],
    ).then(
        bot_respond,
        inputs=[chatbot, full_history],
        outputs=[chatbot, full_history],
    )

    send_btn.click(
        user_submit,
        inputs=[msg, chatbot, full_history, uploaded_file_path],
        outputs=[msg, chatbot, full_history, uploaded_file_path],
    ).then(
        bot_respond,
        inputs=[chatbot, full_history],
        outputs=[chatbot, full_history],
    )


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