IAMTFRMZA commited on
Commit
e5ad2d7
Β·
verified Β·
1 Parent(s): 619c0c2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +56 -34
app.py CHANGED
@@ -65,26 +65,24 @@ else:
65
  # ------------------ Tab 1: Chat Assistant ------------------
66
  with tab1:
67
  with st.sidebar:
68
- st.header("πŸ”§ Tools")
69
- if st.button("🧹 Clear Chat"):
70
- for key in ["messages", "thread_id", "image_url", "image_updated", "pending_prompt"]:
71
- st.session_state[key] = [] if key == "messages" else None if "url" in key else False
72
- st.rerun()
73
 
74
- if st.button("πŸšͺ Logout"):
75
- st.session_state.clear()
 
76
  st.rerun()
77
 
78
  show_image = st.toggle("πŸ“Έ Show Images", value=True)
 
79
  keyword = st.text_input("Keyword Search", placeholder="e.g. mitosis, carcinoma")
80
  if st.button("πŸ”Ž Search") and keyword:
81
  st.session_state.pending_prompt = f"Find clauses or references related to: {keyword}"
82
 
83
  section = st.text_input("Section Lookup", placeholder="e.g. Connective Tissue")
84
- if st.button("πŸ“‘ Lookup") and section:
85
  st.session_state.pending_prompt = f"Summarize or list key points from section: {section}"
86
 
87
- action = st.selectbox("πŸ“‚ Common Pathology Queries", [
88
  "Select an action...",
89
  "List histological features of inflammation",
90
  "Summarize features of carcinoma",
@@ -92,19 +90,19 @@ with tab1:
92
  "Extract diagnostic markers",
93
  "Summarize embryology stages"
94
  ])
95
- if action and action != "Select an action...":
96
  st.session_state.pending_prompt = action
97
- st.rerun()
98
 
99
  chat_col, image_col = st.columns([2, 1])
 
100
  with chat_col:
101
  st.markdown("### πŸ’¬ Ask a Pathology-Specific Question")
102
  user_input = st.chat_input("Example: What are features of squamous cell carcinoma?")
103
- if user_input or st.session_state.pending_prompt:
104
- st.session_state.messages.append({
105
- "role": "user",
106
- "content": user_input or st.session_state.pending_prompt
107
- })
108
  st.session_state.pending_prompt = None
109
 
110
  if st.session_state.messages and st.session_state.messages[-1]["role"] == "user":
@@ -125,44 +123,68 @@ with tab1:
125
 
126
  with st.spinner("πŸ”¬ Analyzing..."):
127
  while True:
128
- status = client.beta.threads.runs.retrieve(thread_id=st.session_state.thread_id, run_id=run.id)
 
 
129
  if status.status in ("completed", "failed", "cancelled"):
130
  break
131
  time.sleep(1)
132
 
133
  if status.status == "completed":
134
- messages = client.beta.threads.messages.list(thread_id=st.session_state.thread_id)
135
- for m in reversed(messages.data):
 
 
136
  if m.role == "assistant":
137
  reply = m.content[0].text.value.strip()
138
- if not any(reply in msg["content"] or msg["content"] in reply for msg in st.session_state.messages if msg["role"] == "assistant"):
 
139
  st.session_state.messages.append({"role": "assistant", "content": reply})
140
 
141
- image_matches = re.findall(r'https://raw\.githubusercontent\.com/AndrewLORTech/witspathologai/main/[^\s\n"]+\.png', reply)
142
- if image_matches:
143
- st.session_state.image_url = image_matches[0]
144
- st.session_state.image_updated = True
 
 
145
  break
146
  else:
147
- st.error("❌ Assistant failed to respond.")
148
  st.rerun()
149
  except Exception as e:
150
  st.error(f"❌ Error: {e}")
151
 
 
152
  for msg in st.session_state.messages:
153
  with st.chat_message(msg["role"]):
154
  st.markdown(msg["content"], unsafe_allow_html=True)
155
 
156
- with image_col:
157
- if show_image and st.session_state.image_url:
158
- try:
159
- r = requests.get(st.session_state.image_url)
160
- r.raise_for_status()
161
- img = Image.open(BytesIO(r.content))
162
- st.image(img, caption="πŸ“„ Referenced Image", use_container_width=True)
163
- except Exception as e:
164
- st.error(f"πŸ–ΌοΈ Failed to load image: {e}")
 
 
 
 
 
 
 
165
 
 
 
 
 
 
 
 
 
 
166
 
167
  # ------------------ Tab 2: Visual Reference Search ------------------
168
  import urllib.parse
 
65
  # ------------------ Tab 1: Chat Assistant ------------------
66
  with tab1:
67
  with st.sidebar:
68
+ st.header("πŸ§ͺ Pathology Tools")
 
 
 
 
69
 
70
+ if st.button("🧹 Clear Chat"):
71
+ for k in ["messages", "thread_id", "image_urls", "pending_prompt"]:
72
+ st.session_state[k] = [] if k.endswith("s") else None
73
  st.rerun()
74
 
75
  show_image = st.toggle("πŸ“Έ Show Images", value=True)
76
+
77
  keyword = st.text_input("Keyword Search", placeholder="e.g. mitosis, carcinoma")
78
  if st.button("πŸ”Ž Search") and keyword:
79
  st.session_state.pending_prompt = f"Find clauses or references related to: {keyword}"
80
 
81
  section = st.text_input("Section Lookup", placeholder="e.g. Connective Tissue")
82
+ if section:
83
  st.session_state.pending_prompt = f"Summarize or list key points from section: {section}"
84
 
85
+ action = st.selectbox("Common Pathology Queries", [
86
  "Select an action...",
87
  "List histological features of inflammation",
88
  "Summarize features of carcinoma",
 
90
  "Extract diagnostic markers",
91
  "Summarize embryology stages"
92
  ])
93
+ if action != "Select an action...":
94
  st.session_state.pending_prompt = action
 
95
 
96
  chat_col, image_col = st.columns([2, 1])
97
+
98
  with chat_col:
99
  st.markdown("### πŸ’¬ Ask a Pathology-Specific Question")
100
  user_input = st.chat_input("Example: What are features of squamous cell carcinoma?")
101
+
102
+ if user_input:
103
+ st.session_state.messages.append({"role": "user", "content": user_input})
104
+ elif st.session_state.pending_prompt:
105
+ st.session_state.messages.append({"role": "user", "content": st.session_state.pending_prompt})
106
  st.session_state.pending_prompt = None
107
 
108
  if st.session_state.messages and st.session_state.messages[-1]["role"] == "user":
 
123
 
124
  with st.spinner("πŸ”¬ Analyzing..."):
125
  while True:
126
+ status = client.beta.threads.runs.retrieve(
127
+ thread_id=st.session_state.thread_id, run_id=run.id
128
+ )
129
  if status.status in ("completed", "failed", "cancelled"):
130
  break
131
  time.sleep(1)
132
 
133
  if status.status == "completed":
134
+ responses = client.beta.threads.messages.list(
135
+ thread_id=st.session_state.thread_id
136
+ ).data
137
+ for m in reversed(responses):
138
  if m.role == "assistant":
139
  reply = m.content[0].text.value.strip()
140
+ if not any(reply in msg["content"] or msg["content"] in reply
141
+ for msg in st.session_state.messages if msg["role"] == "assistant"):
142
  st.session_state.messages.append({"role": "assistant", "content": reply})
143
 
144
+ # Extract image URLs from response
145
+ images = re.findall(
146
+ r'https://raw\.githubusercontent\.com/AndrewLORTech/witspathologai/main/[^\s\n"]+\.png',
147
+ reply
148
+ )
149
+ st.session_state.image_urls = images
150
  break
151
  else:
152
+ st.error("❌ Assistant failed to complete.")
153
  st.rerun()
154
  except Exception as e:
155
  st.error(f"❌ Error: {e}")
156
 
157
+ # Display messages
158
  for msg in st.session_state.messages:
159
  with st.chat_message(msg["role"]):
160
  st.markdown(msg["content"], unsafe_allow_html=True)
161
 
162
+ # Display follow-up questions
163
+ if st.session_state.messages and st.session_state.messages[-1]["role"] == "assistant":
164
+ last = st.session_state.messages[-1]["content"]
165
+ if "Some Possible Questions:" in last:
166
+ # Filter only lines that are actual questions
167
+ all_lines = re.findall(r"[-β€’]\s*(.*)", last)
168
+ questions = [line for line in all_lines if line.strip().endswith("?")]
169
+
170
+ if questions:
171
+ st.markdown("#### πŸ’‘ Follow-Up Suggestions")
172
+ for q in questions:
173
+ if st.button(f"πŸ“Œ {q}"):
174
+ st.session_state.pending_prompt = q
175
+ st.rerun()
176
+ else:
177
+ st.markdown("#### πŸ’‘ No follow-up questions detected in the assistant's response.")
178
 
179
+ with image_col:
180
+ if show_image and st.session_state.image_urls:
181
+ st.markdown("### πŸ–ΌοΈ Images")
182
+ for url in st.session_state.image_urls:
183
+ try:
184
+ img = Image.open(BytesIO(requests.get(url, timeout=5).content))
185
+ st.image(img, caption=url.split("/")[-1], use_container_width=True)
186
+ except Exception:
187
+ st.warning(f"⚠️ Failed to load image: {url}")
188
 
189
  # ------------------ Tab 2: Visual Reference Search ------------------
190
  import urllib.parse