File size: 14,181 Bytes
1cd02df
9a90731
 
4a71975
3d9fd27
 
7b2a5f2
 
 
9910527
4a71975
775a297
42e0794
 
f6db629
9bcc24d
9d4148e
 
f6db629
42e0794
 
775a297
279de0a
775a297
 
 
42e0794
9a90731
 
775a297
 
279de0a
775a297
9a90731
775a297
 
 
9a90731
279de0a
3d9fd27
607c738
dd02bbc
 
279de0a
3d9fd27
42e0794
3d9fd27
209a87c
607c738
203fe3e
ce1ad36
9a90731
 
 
 
6cfdc3b
607c738
619c0c2
b394a30
 
 
619c0c2
 
607c738
9a90731
607c738
9dd3863
e5ad2d7
9a90731
e5ad2d7
 
 
607c738
 
 
e5ad2d7
607c738
 
 
 
 
e5ad2d7
607c738
 
e5ad2d7
607c738
 
 
 
 
 
f05aad0
e5ad2d7
607c738
 
9dd3863
e5ad2d7
9dd3863
 
607c738
e5ad2d7
 
 
 
 
607c738
 
33cafda
607c738
 
33cafda
 
 
607c738
33cafda
 
 
 
 
607c738
33cafda
 
 
 
607c738
33cafda
607c738
e5ad2d7
33cafda
 
e5ad2d7
607c738
 
 
 
33cafda
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
607c738
 
 
 
33cafda
607c738
 
 
 
33cafda
e5ad2d7
 
 
33cafda
 
e5ad2d7
 
 
 
 
 
 
 
 
ade236f
e5ad2d7
 
 
 
 
 
 
 
 
9a90731
33cafda
0c9e6cc
619c0c2
 
 
 
5c33d13
619c0c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
af56ec6
619c0c2
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
import streamlit as st
st.set_page_config(page_title="AI Pathology Assistant", layout="wide", initial_sidebar_state="collapsed")

import os
import time
import re
import requests
from PIL import Image
from io import BytesIO
from openai import OpenAI

# ------------------ Authentication ------------------
VALID_USERS = {
    "[email protected]": "Pass.123",
    "[email protected]": "Pass.123",
    "[email protected]": "Pass.123",
    "[email protected]": "Pass.123",
    "[email protected]": "Pass.123",
    "[email protected]": "Pass.123",
}

def login():
    st.title("πŸ” Login Required")
    email = st.text_input("Email")
    password = st.text_input("Password", type="password")
    if st.button("Login"):
        if VALID_USERS.get(email) == password:
            st.session_state["authenticated"] = True
            st.experimental_set_query_params(logged_in="1")
            st.rerun()
        else:
            st.error("❌ Incorrect email or password.")

if not st.session_state.get("authenticated", False):
    login()
    st.stop()

# ------------------ App Title ------------------
st.title("🧬 AI Pathology Assistant")

# ------------------ Load OpenAI ------------------
OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY")
if not OPENAI_API_KEY:
    st.error("❌ Missing OPENAI_API_KEY environment variable.")
    st.stop()

client = OpenAI(api_key=OPENAI_API_KEY)

# ------------------ Assistant Setup ------------------
ASSISTANT_ID = "asst_jXDSjCG8LI4HEaFEcjFVq8KB"

# ------------------ Session State Initialization ------------------
for key in ["messages", "thread_id", "image_urls", "pending_prompt", "image_url", "image_updated"]:
    if key not in st.session_state:
        st.session_state[key] = [] if key.endswith("s") else None if "url" in key else False

# ------------------ Tabs ------------------
show_tab2 = True  # Set to True to activate visual tab
if show_tab2:
    tab1, tab2 = st.tabs(["πŸ’¬ Chat Assistant", "πŸ“· Visual Reference Search"])
else:
    tab1 = st.tabs(["πŸ’¬ Chat Assistant"])[0]
    tab2 = None

# ------------------ Tab 1: Chat Assistant ------------------
with tab1:
    with st.sidebar:
        st.header("πŸ§ͺ Pathology Tools")

        if st.button("🧹 Clear Chat"):
            for k in ["messages", "thread_id", "image_urls", "pending_prompt"]:
                st.session_state[k] = [] if k.endswith("s") else None
            st.rerun()

        show_image = st.toggle("πŸ“Έ Show Images", value=True)

        keyword = st.text_input("Keyword Search", placeholder="e.g. mitosis, carcinoma")
        if st.button("πŸ”Ž Search") and keyword:
            st.session_state.pending_prompt = f"Find clauses or references related to: {keyword}"

        section = st.text_input("Section Lookup", placeholder="e.g. Connective Tissue")
        if section:
            st.session_state.pending_prompt = f"Summarize or list key points from section: {section}"

        action = st.selectbox("Common Pathology Queries", [
            "Select an action...",
            "List histological features of inflammation",
            "Summarize features of carcinoma",
            "List muscle types and features",
            "Extract diagnostic markers",
            "Summarize embryology stages"
        ])
        if action != "Select an action...":
            st.session_state.pending_prompt = action

    chat_col, image_col = st.columns([2, 1])

    with chat_col:
        st.markdown("### πŸ’¬ Ask a Pathology-Specific Question")
        user_input = st.chat_input("Example: What are features of squamous cell carcinoma?")

        if user_input:
            st.session_state.messages.append({"role": "user", "content": user_input})
        elif st.session_state.pending_prompt:
            st.session_state.messages.append({"role": "user", "content": st.session_state.pending_prompt})
            st.session_state.pending_prompt = None

        # Only trigger assistant if last message is from user
        if st.session_state.messages and st.session_state.messages[-1]["role"] == "user":
            try:
                with st.spinner("πŸ”¬ Analyzing..."):
                    if not st.session_state.thread_id:
                        st.session_state.thread_id = client.beta.threads.create().id

                    client.beta.threads.messages.create(
                        thread_id=st.session_state.thread_id,
                        role="user",
                        content=st.session_state.messages[-1]["content"]
                    )

                    run = client.beta.threads.runs.create(
                        thread_id=st.session_state.thread_id,
                        assistant_id=ASSISTANT_ID
                    )

                    # Wait for run to complete
                    while True:
                        status = client.beta.threads.runs.retrieve(
                            thread_id=st.session_state.thread_id,
                            run_id=run.id
                        )
                        if status.status in ("completed", "failed", "cancelled"):
                            break
                        time.sleep(1)

                    if status.status == "completed":
                        responses = client.beta.threads.messages.list(
                            thread_id=st.session_state.thread_id
                        ).data

                        # Only take the last assistant message
                        for m in responses:
                            if m.role == "assistant":
                                reply = m.content[0].text.value.strip()
                                if not any(
                                    reply in msg["content"] or msg["content"] in reply
                                    for msg in st.session_state.messages if msg["role"] == "assistant"
                                ):
                                    st.session_state.messages.append({"role": "assistant", "content": reply})

                                    # Extract image URLs
                                    images = re.findall(
                                        r'https://raw\.githubusercontent\.com/AndrewLORTech/witspathologai/main/[^\s\n"]+\.png',
                                        reply
                                    )
                                    st.session_state.image_urls = images
                                break
                    else:
                        st.error("❌ Assistant failed to complete.")
                st.rerun()
            except Exception as e:
                st.error(f"❌ Error: {e}")

        # Display all messages
        for msg in st.session_state.messages:
            with st.chat_message(msg["role"]):
                st.markdown(msg["content"], unsafe_allow_html=True)

        # Follow-up Questions
        if st.session_state.messages and st.session_state.messages[-1]["role"] == "assistant":
            last = st.session_state.messages[-1]["content"]
            if "Some Possible Questions:" in last:
                suggestions = re.findall(r"[-β€’]\s*(.*)", last)
                questions = [q.strip() for q in suggestions if q.strip().endswith("?")]

                if questions:
                    st.markdown("#### πŸ’‘ Follow-Up Suggestions")
                    for q in questions:
                        if st.button(f"πŸ“Œ {q}"):
                            st.session_state.pending_prompt = q
                            st.rerun()
                else:
                    st.markdown("#### πŸ’‘ No follow-up questions detected in the assistant's response.")

    with image_col:
        if show_image and st.session_state.image_urls:
            st.markdown("### πŸ–ΌοΈ Images")
            for url in st.session_state.image_urls:
                try:
                    img = Image.open(BytesIO(requests.get(url, timeout=5).content))
                    st.image(img, caption=url.split("/")[-1], use_container_width=True)
                except Exception:
                    st.warning(f"⚠️ Failed to load image: {url}")


# ------------------ Tab 2: Visual Reference Search ------------------
import urllib.parse
import requests
from PIL import Image
from io import BytesIO

with tab2:
    ASSISTANT_ID = "asst_9v09zgizdcuuhNdcFQpRo9RO"

    if "image_thread_id" not in st.session_state:
        st.session_state.image_thread_id = None
    if "image_response" not in st.session_state:
        st.session_state.image_response = None
    if "image_results" not in st.session_state:
        st.session_state.image_results = []
    if "image_lightbox" not in st.session_state:
        st.session_state.image_lightbox = None

    image_input = st.chat_input("Ask for histology visual references (e.g. ovary histology, mitosis)")
    if image_input:
        st.session_state.image_response = None
        st.session_state.image_results = []
        st.session_state.image_lightbox = None

        try:
            if st.session_state.image_thread_id is None:
                thread = client.beta.threads.create()
                st.session_state.image_thread_id = thread.id

            client.beta.threads.messages.create(
                thread_id=st.session_state.image_thread_id,
                role="user",
                content=image_input
            )

            run = client.beta.threads.runs.create(
                thread_id=st.session_state.image_thread_id,
                assistant_id=ASSISTANT_ID
            )

            with st.spinner("πŸ”¬ Searching for histology references..."):
                while True:
                    run_status = client.beta.threads.runs.retrieve(
                        thread_id=st.session_state.image_thread_id,
                        run_id=run.id
                    )
                    if run_status.status in ("completed", "failed", "cancelled"):
                        break
                    time.sleep(1)

            if run_status.status == "completed":
                messages = client.beta.threads.messages.list(thread_id=st.session_state.image_thread_id)
                for msg in reversed(messages.data):
                    if msg.role == "assistant":
                        response_text = msg.content[0].text.value
                        st.session_state.image_response = response_text

                        # Extract and decode image URLs
                        lines = response_text.splitlines()
                        image_urls = []
                        expecting_url = False

                        for line in lines:
                            line_clean = line.strip().replace("**", "")
                            if "Image URL:" in line_clean:
                                parts = line_clean.split("Image URL:")
                                if len(parts) > 1 and parts[1].strip().startswith("http"):
                                    image_urls.append(urllib.parse.unquote(parts[1].strip()))
                                else:
                                    expecting_url = True
                            elif expecting_url:
                                if line_clean.startswith("http"):
                                    image_urls.append(urllib.parse.unquote(line_clean))
                                expecting_url = False

                        st.session_state.image_results = [{"image": url} for url in image_urls]

                        if image_urls and not st.session_state.image_lightbox:
                            st.session_state.image_lightbox = image_urls[0]
                        break
        except Exception as e:
            st.error(f"❌ Visual Assistant Error: {e}")

    if st.session_state.image_results and st.session_state.image_response:
        st.subheader("πŸ–ΌοΈ Image Preview(s)")

        # Split the assistant response into metadata cards
        cards = []
        blocks = st.session_state.image_response.split("### πŸ–ΌοΈ ")
        for block in blocks:
            if not block.strip():
                continue
            lines = block.strip().splitlines()
            title = lines[0].strip()
            meta = "\n".join(lines[1:])
            cards.append((title, meta))

        cols = st.columns(4)
        for i, ((title, meta), item) in enumerate(zip(cards, st.session_state.image_results)):
            image_url = item.get("image")
            with cols[i % 4]:
                with st.container():
                    # Remove Image Filename and Image URL lines from display
                    meta_clean = "\n".join(
                        line for line in meta.splitlines()
                        if all(x not in line.lower() for x in ["image filename", "image url"])
                    )

                    st.markdown(f"**πŸ”¬ {title}**")
                    st.caption(meta_clean)
                    try:
                        r = requests.get(image_url, timeout=10)
                        r.raise_for_status()
                        img = Image.open(BytesIO(r.content))
                        st.image(img, caption=image_url.split("/")[-1], use_container_width=True)
                        if st.button("πŸ” Zoom", key=f"zoom_{i}"):
                            st.session_state.image_lightbox = image_url
                    except Exception as e:
                        st.warning("⚠️ Could not load image.")
                        st.error(str(e))
    else:
        st.info("ℹ️ No image references found yet.")

    if st.session_state.image_lightbox:
        st.markdown("### πŸ”¬ Full Image View")
        try:
            img_url = urllib.parse.unquote(st.session_state.image_lightbox)
            r = requests.get(img_url, timeout=10)
            r.raise_for_status()
            full_img = Image.open(BytesIO(r.content))
            st.image(full_img, caption=img_url.split("/")[-1], use_container_width=True)
        except Exception as e:
            st.warning("⚠️ Could not load full image.")
            st.error(str(e))
        if st.button("❌ Close Preview"):
            st.session_state.image_lightbox = None
            st.rerun()