File size: 7,500 Bytes
1cd02df
4a71975
3d9fd27
 
d09f114
 
 
 
9910527
4a71975
775a297
42e0794
 
 
 
 
 
 
775a297
73cb72b
775a297
 
 
42e0794
775a297
 
 
73cb72b
775a297
 
 
 
 
 
 
bff8693
89fd98c
73cb72b
89fd98c
3d9fd27
dd02bbc
 
73cb72b
3d9fd27
42e0794
3d9fd27
bff8693
209a87c
bff8693
6cfdc3b
 
 
 
10e5f47
 
6cfdc3b
 
 
 
 
73cb72b
 
df99638
 
10e5f47
6cfdc3b
 
 
73cb72b
89fd98c
73cb72b
6cfdc3b
 
89fd98c
6cfdc3b
 
 
 
 
 
 
 
 
 
 
89fd98c
6cfdc3b
 
 
bff8693
6cfdc3b
 
 
73cb72b
6cfdc3b
 
 
 
 
df99638
dd02bbc
6cfdc3b
dd02bbc
6cfdc3b
ba9c72e
6cfdc3b
dd02bbc
 
6cfdc3b
dd02bbc
6cfdc3b
dd02bbc
 
 
6cfdc3b
dd02bbc
 
 
73cb72b
dd02bbc
6cfdc3b
 
dd02bbc
 
 
6cfdc3b
 
 
 
73cb72b
10e5f47
73cb72b
 
 
10e5f47
73cb72b
 
 
 
 
 
 
 
dd02bbc
6cfdc3b
73cb72b
6cfdc3b
dd02bbc
73cb72b
29d68fa
6cfdc3b
bff8693
6cfdc3b
29d68fa
73cb72b
6cfdc3b
10e5f47
73cb72b
2c8e0e1
 
bff8693
2c8e0e1
 
bff8693
 
2c8e0e1
 
bff8693
73cb72b
bff8693
 
73cb72b
 
bff8693
 
 
73cb72b
bff8693
2c8e0e1
 
 
 
bff8693
2c8e0e1
10e5f47
5451697
 
 
e15129e
bff8693
10e5f47
73cb72b
bff8693
73cb72b
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
import streamlit as st
import os
import time
import re
import requests
from PIL import Image
from io import BytesIO
from urllib.parse import quote
from openai import OpenAI

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

def login():
    st.title("\U0001F512 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.rerun()
        else:
            st.error("\u274C Incorrect email or password.")

if "authenticated" not in st.session_state:
    st.session_state.authenticated = False
if not st.session_state.authenticated:
    login()
    st.stop()

# ------------------ Configuration ------------------
st.set_page_config(page_title="AI Pathology Assistant", layout="wide", initial_sidebar_state="collapsed")
st.title("\U0001F9EC AI Pathology Assistant")
st.caption("AI-powered exploration of pathology, anatomy, and histology documents via OCR + GPT")

OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY")
if not OPENAI_API_KEY:
    st.error("\u274C Missing OPENAI_API_KEY environment variable.")
    st.stop()

client = OpenAI(api_key=OPENAI_API_KEY)
ASSISTANT_ID = "asst_jXDSjCG8LI4HEaFEcjFVq8KB"

# ------------------ State Setup ------------------
if "messages" not in st.session_state:
    st.session_state.messages = []
if "thread_id" not in st.session_state:
    st.session_state.thread_id = None
if "image_urls" not in st.session_state:
    st.session_state.image_urls = []
if "pending_prompt" not in st.session_state:
    st.session_state.pending_prompt = None

# ------------------ Sidebar ------------------
with st.sidebar:
    st.header("\U0001F9EA Pathology Tools")
    if st.button("\U0001F9F9 Clear Chat"):
        st.session_state.messages = []
        st.session_state.thread_id = None
        st.session_state.image_urls = []
        st.session_state.pending_prompt = None
        st.rerun()

    show_image = st.toggle("\U0001F4F8 Show Slide Images", value=True)
    keyword = st.text_input("Keyword Search", placeholder="e.g. mitosis, carcinoma")
    if st.button("\U0001F50E 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}"

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

# ------------------ Chat UI ------------------
chat_col, image_col = st.columns([2, 1])

with chat_col:
    st.markdown("### \U0001F4AC 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

    if st.session_state.messages and st.session_state.messages[-1]["role"] == "user":
        try:
            if st.session_state.thread_id is None:
                thread = client.beta.threads.create()
                st.session_state.thread_id = thread.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
            )

            with st.spinner("\U0001F52C Analyzing..."):
                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":
                messages = client.beta.threads.messages.list(thread_id=st.session_state.thread_id)
                for m in reversed(messages.data):
                    if m.role == "assistant":
                        raw_reply = m.content[0].text.value

                        image_matches = re.findall(
                            r'https://raw\.githubusercontent\.com/AndrewLORTech/witspathologai/main/[^"]+?\.png',
                            raw_reply
                        )
                        st.session_state.image_urls = image_matches

                        reply_cleaned = re.sub(
                            r'https://raw\.githubusercontent\.com/AndrewLORTech/witspathologai/main/[^"]+?\.png',
                            '[Image reference available in Slide Previews →]',
                            raw_reply
                        )
                        st.session_state.messages.append({"role": "assistant", "content": reply_cleaned})
                        break
            else:
                st.error("\u274C Assistant failed to respond.")
            st.rerun()
        except Exception as e:
            st.error(f"\u274C Error: {e}")

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

# ------------------ Scrollable Image Preview ------------------
with image_col:
    if show_image and st.session_state.image_urls:
        st.markdown("### \U0001F5BC Image(s)")
        st.markdown("""
        <style>
        .carousel-wrapper {
            display: flex;
            overflow-x: auto;
            scroll-snap-type: x mandatory;
            gap: 1rem;
            padding: 0.5rem 0;
        }
        .carousel-wrapper::-webkit-scrollbar {
            height: 8px;
        }
        .carousel-wrapper::-webkit-scrollbar-thumb {
            background: #999;
            border-radius: 6px;
        }
        .carousel-wrapper img {
            scroll-snap-align: start;
            height: 420px;
            border-radius: 8px;
        }
        </style>
        """, unsafe_allow_html=True)

        html = '<div class="carousel-wrapper">'
        for raw_url in st.session_state.image_urls:
            try:
                _, raw_path = raw_url.split("githubusercontent.com/", 1)
                segments = raw_path.strip().split("/")
                encoded_segments = [quote(seg) for seg in segments]
                encoded_url = "https://raw.githubusercontent.com/" + "/".join(encoded_segments)
                html += f'<img src="{encoded_url}" alt="slide preview">'
            except Exception as e:
                st.error(f"\u274C Failed to load image: {e}")
        html += "</div>"
        st.markdown(html, unsafe_allow_html=True)